diff --git a/AUTHORS.txt b/AUTHORS.txt index 0016bb9aa8..6312a866c4 100644 --- a/AUTHORS.txt +++ b/AUTHORS.txt @@ -25,7 +25,7 @@ Chris @hannon235 added node.js api for box2d Jason Aeschliman @jaeschliman fixed cc.Node setposition -Sun Zhuoshi(Intel) @sunzhuoshi engine loader fixed +Zhuoshi Sun(Intel) @sunzhuoshi engine loader fixed Alejandro Reyero @KaTXi fixed error message @@ -50,7 +50,6 @@ Ivo Wetzel(Zynga Germany) @BonsaiDen Fixes for Audio Support Detection, Texture Support in Particle System, and Performance improvements - Mario Adrian @many20 Code review, multi touch improvements, ccbi bugs fixed @@ -58,7 +57,7 @@ keisuke hata(Square) @Seasons7 Code review, bug fix Marat Yakupov @moadib Various bug fixes -Wu Liang @akira-cn Touch location fix for designResolution +Liang Wu @akira-cn Touch location fix for designResolution Jimmy Sambuo @jsambuo AudioEngine improvements @@ -74,14 +73,29 @@ Szymon PiƂkowski @ardcore CCTexture Bug fix Tomasz Tunik @tomasztunik CCNode Memory leak fix -Lin Xuankang(Intel) @AndriyLin cc.WebAudioEngine implements +Xuankang Lin(Intel) @AndriyLin cc.WebAudioEngine implements Kang-Hao Lu(Opera/Oupeng) @kennyluck Optimize John Resig's inheritance pattern cc.clone improvements Mark Henderson @MarkEHenderson Code review, LabelTTF and Scale9Sprite bug fix -06wj @06wj CCScheduler improvements +Jing Wang @06wj CCScheduler improvements + Js file loading image add + cc.RectApplyAffineTransform improvements + +Ze Wang @WanderWang Fix crash when BrowserTypes match nothing from navigator.userAgent + LabelTTF improvements + cc.TextureCache.dumpCachedTextureInfo 's bug fix + +Christian Schwartz @cschwartz SpriteFrame.initWithTextureFilename converted fix + +XiaoJun Zheng @SmallAiTT _getResType error fix + cc.ScrollView bug fix + +Guozhu Cheng @bengol cc.SimpleAudioEngine bug fix + +Jing Xiao @xbruce cc.SAXParser bug fix Cocos2d-x and cocos2d-html5 can not grow so fast without the active community. diff --git a/CHANGELOG.txt b/CHANGELOG.txt index a71dc76729..ebc12bd87c 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,3 +1,35 @@ +Cocos2d-html5-v2.1.6 @ Sep.19, 2013 +* Improved Sprite, Node, LabelTTF class define from separated code to combined code for maintainability, now it is clean and clear +* added a new sample game "Fruit attack" which works great on PC browsers, mobile browsers, and can even be run natively as an android and iOS app with JSB +* cc.Sprite and its subClasses's texture has been replaced from DOM element to cc.Texture2D on Canvas mode +* Improved cc.Texture2d for direct using without pre-loading image resources, you don't need to wait resources loading when create a new scene or layers +* Migrated CCBReader and GUI to Cocos2d-x 2.1.4 +* Improved update function of Action, and avoid using temporary object, it is good for GC and performance +* Modified LabelTTF's rendering from direct drawing to pre-rendering for performance, 100% faster than before on mobile browser +* Fixed APIs of HTML5 according to JSB for compatibility, e.g. cc.ParticleSystemQuad has merged into cc.ParticleSystem, please check it on upgrade guide v2.1.5 to v2.1.6(http://www.cocos2d-x.org/wiki/Upgrade_Guide_from_Cocos2d-html5_v215_to_v216) +* Added Hiding url address bar for mobile browser, please check the template and hello world +* Re-writed Canvas Mode of RenderTexture to adapt WebGL interface +* Added frame event, collider and blend type supporting for Armature. Now Armature supports two tools:1.CocoStudio(windows,http://www.cocostudio.org),2.DragonBones(flash, https://github.com/2youyouo2/SkeletonAnimationDesignPanel) +* Set auto render mode default value to canvas in mobile browsers and WebGL in desktop browsers + +* Bug fix: +1. Fixed cc.Sprite's displayFrame returns wrong value on Canvas mode. +2. Fixed cc.LabelBMFont is very slow when calling setString +3. Fixed a bug of CCBReader that cc.ControlButton doesn't work when its controller is _jsControlled +4. Fixed a bug of cc.TextureCache that the status of texture is wrong in callback +5. Fixed a bug of cc.Scale9Sprite that its contentSize is wrong when call setCapInsets +6. Fixed a bug of cc.TableView's that contentSize is wrong when change datasource +7. Fixed a bug of cc.Sprite that its children also follow fliped when it was fliped +8. Fixed cc.Node's nodeToWorldTransform returns wrong value on Canvas Mode +9. Fixed a bug of cc.LayerColor that represent incorrect opacity passed into init method +10. Stop listening and remove the event for HtmlImageElement object onload +11. Fixed cc.ProgressTimer display wrong when its sprite was flipped +12. Fixed some bugs for actions that set their object property through reference when initiating actions. + +* Known Issues: + 1. Effect Advanced Lens3D doesn't work + 2. ClipNodeTest effects varies in different browsers + Cocos2d-html5-v2.1.5 @ July.24, 2013 * Ported engine API to keep the same as Cocos2d-x v2.1.4 API * Optimized John Resig's inheritance pattern (cc.Class.extend) with advanced property initialization. @@ -8,7 +40,7 @@ Cocos2d-html5-v2.1.5 @ July.24, 2013 * Optimized performance for MoonWarriors and CocosDragonJS * Bug fix: - 1. Fixed cc.EditBox Dom Element position issue when EGLView is setted + 1. Fixed cc.EditBox Dom Element position issue when EGLView is set 2. Fixed cc.EGLView adjustSize bug 3. Fixed the bug of cc.ParticleBatchNode that it doesn't hide particles after particle life has expired when calling stopSystem() 4. Fixed a bug that LabelTTF dimension behavior doesn't support height=0 @@ -17,6 +49,7 @@ Cocos2d-html5-v2.1.5 @ July.24, 2013 * Known Issues: 1. Effect Advanced Lens3D doesn't work 2. ClipNodeTest effects varies in different browsers + 3. nodeToParentTransform in cc.Node returns wrong value on Canvas mode Cocos2d-html5-v2.1.4 @ Jun.12, 2013 * Added support for multiple resources loading. This mechanic is the same as cocos2d-x now diff --git a/CocosDenshion/SimpleAudioEngine.js b/CocosDenshion/SimpleAudioEngine.js index 6a1b0c664f..d31fe46b51 100644 --- a/CocosDenshion/SimpleAudioEngine.js +++ b/CocosDenshion/SimpleAudioEngine.js @@ -69,16 +69,16 @@ cc.AudioEngine = cc.Class.extend(/** @lends cc.AudioEngine# */{ /** * Helper function for cutting out the extension from the path * @param {String} fullpath + * @return {String|null} path without ext name * @protected */ _getPathWithoutExt: function (fullpath) { if (typeof(fullpath) != "string") { - return; + return null; } var endPos = fullpath.lastIndexOf("."); - if (endPos != -1) { + if (endPos !== -1) return fullpath.substring(0, endPos); - } return fullpath; }, @@ -89,7 +89,7 @@ cc.AudioEngine = cc.Class.extend(/** @lends cc.AudioEngine# */{ */ _getExtFromFullPath: function (fullpath) { var startPos = fullpath.lastIndexOf("."); - if (startPos != -1) { + if (startPos !== -1) { return fullpath.substring(startPos + 1, fullpath.length); } return -1; @@ -113,21 +113,15 @@ cc.SimpleSFX = function (audio, ext) { * @extends cc.AudioEngine */ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */{ - _supportedFormat:[], - _soundEnable:false, + _supportedFormat:null, _effectList:{}, _soundList:{}, _playingMusic:null, _effectsVolume:1, _maxAudioInstance:10, + _capabilities:null, + _soundSupported:false, _canPlay:true, - _capabilities:{ - mp3:false, - ogg:false, - wav:false, - mp4:false, - m4a:false - }, /** * Constructor @@ -136,12 +130,17 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */ cc.AudioEngine.prototype.ctor.call(this); this._supportedFormat = []; - this._checkCanPlay(this._capabilities); + this._effectList = {}; + this._soundList = {}; + + this._capabilities = { mp3: false, ogg: false, wav: false, mp4: false, m4a: false}; + var locCapabilities = this._capabilities; + this._checkCanPlay(locCapabilities); // enable sound if any of the audio format is supported - this._soundEnable = this._capabilities.mp3 || this._capabilities.mp4 - || this._capabilities.m4a || this._capabilities.ogg - || this._capabilities.wav; + this._soundSupported = locCapabilities.mp3 || locCapabilities.mp4 + || locCapabilities.m4a || locCapabilities.ogg + || locCapabilities.wav; var ua = navigator.userAgent; if(/Mobile/.test(ua) && (/iPhone OS/.test(ua)||/iPad/.test(ua)||/Firefox/.test(ua)) || /MSIE/.test(ua)){ @@ -156,7 +155,23 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */ init:function () { // detect the prefered audio format this._getSupportedAudioFormat(); - return this._soundEnable; + return this._soundSupported; + }, + + /** + * Preload music resource. + * @param {String} path + */ + preloadMusic:function(path){ + this.preloadSound(path); + }, + + /** + * Preload effect resource. + * @param {String} path + */ + preloadEffect:function(path){ + this.preloadSound(path); }, /** @@ -165,7 +180,7 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */ * @param {String} path The path of the music file with filename extension. */ preloadSound:function (path) { - if (this._soundEnable) { + if (this._soundSupported) { var extName = this._getExtFromFullPath(path); var keyname = this._getPathWithoutExt(path); if (this.isFormatSupported(extName) && !this._soundList.hasOwnProperty(keyname)) { @@ -174,29 +189,26 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */ sfxCache.ext = extName; sfxCache.audio = new Audio(path); sfxCache.audio.preload = 'auto'; - sfxCache.audio.addEventListener('canplaythrough', function (e) { + var soundPreloadCanplayHandler = function (e) { cc.Loader.getInstance().onResLoaded(); - this.removeEventListener('canplaythrough', arguments.callee, false); - }, false); - - sfxCache.audio.addEventListener("error", function (e) { + this.removeEventListener('canplaythrough', soundPreloadCanplayHandler, false); + this.removeEventListener('error', soundPreloadErrorHandler, false); + }; + var soundPreloadErrorHandler = function (e) { cc.Loader.getInstance().onResLoadingErr(e.srcElement.src); - this.removeEventListener('error', arguments.callee, false); - }, false); + this.removeEventListener('canplaythrough', soundPreloadCanplayHandler, false); + this.removeEventListener('error', soundPreloadErrorHandler, false); + }; + sfxCache.audio.addEventListener('canplaythrough', soundPreloadCanplayHandler, false); + sfxCache.audio.addEventListener("error", soundPreloadErrorHandler, false); this._soundList[keyname] = sfxCache; sfxCache.audio.load(); + return; } - else{ - cc.Loader.getInstance().onResLoaded(); - } - } - else { - cc.Loader.getInstance().onResLoaded(); } } - - //cc.Loader.getInstance().onResLoaded(); + cc.Loader.getInstance().onResLoaded(); }, /** @@ -208,24 +220,27 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */ * cc.AudioEngine.getInstance().playMusic(path, false); */ playMusic:function (path, loop) { + if (!this._soundSupported) + return; + var keyname = this._getPathWithoutExt(path); var extName = this._getExtFromFullPath(path); var au; - if (this._soundList.hasOwnProperty(this._playingMusic)) { - this._soundList[this._playingMusic].audio.pause(); + var locSoundList = this._soundList; + if (locSoundList.hasOwnProperty(this._playingMusic)) { + locSoundList[this._playingMusic].audio.pause(); } this._playingMusic = keyname; - if (this._soundList.hasOwnProperty(this._playingMusic)) { - au = this._soundList[this._playingMusic].audio; - } - else { + if (locSoundList.hasOwnProperty(this._playingMusic)) { + au = locSoundList[this._playingMusic].audio; + } else { var sfxCache = new cc.SimpleSFX(); sfxCache.ext = extName; au = sfxCache.audio = new Audio(path); sfxCache.audio.preload = 'auto'; - this._soundList[keyname] = sfxCache; + locSoundList[keyname] = sfxCache; sfxCache.audio.load(); } @@ -249,12 +264,13 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */ * cc.AudioEngine.getInstance().stopMusic(); */ stopMusic:function (releaseData) { - if (this._soundList.hasOwnProperty(this._playingMusic)) { - var au = this._soundList[this._playingMusic].audio; + var locSoundList = this._soundList, locPlayingMusic = this._playingMusic; + if (locSoundList.hasOwnProperty(locPlayingMusic)) { + var au = locSoundList[locPlayingMusic].audio; au.pause(); au.currentTime = au.duration; if (releaseData) { - delete this._soundList[this._playingMusic]; + delete locSoundList[locPlayingMusic]; } cc.AudioEngine.isMusicPlaying = false; } @@ -335,11 +351,9 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */ var music = this._soundList[this._playingMusic].audio; if (volume > 1) { music.volume = 1; - } - else if (volume < 0) { + } else if (volume < 0) { music.volume = 0; - } - else { + } else { music.volume = volume; } } @@ -365,16 +379,19 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */ * Play sound effect. * @param {String} path The path of the sound effect with filename extension. * @param {Boolean} loop Whether to loop the effect playing, default value is false + * @return {Number|null} the audio id * @example * //example * var soundId = cc.AudioEngine.getInstance().playEffect(path); */ - playEffect:function (path, loop) { + playEffect: function (path, loop) { + if (!this._soundSupported) + return null; + var keyname = this._getPathWithoutExt(path), actExt; if (this._soundList.hasOwnProperty(keyname)) { actExt = this._soundList[keyname].ext; - } - else { + } else { actExt = this._getExtFromFullPath(path); } @@ -385,9 +402,8 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */ if (reclaim[i].ended) { au = reclaim[i]; au.currentTime = 0; - if (window.chrome){ + if (window.chrome) au.load(); - } break; } } @@ -403,13 +419,11 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */ reclaim.push(au); } - if (loop) { + if (loop) au.loop = loop; - } au.play(); var audioID = this._audioID++; this._audioIDList[audioID] = au; - return audioID; }, @@ -432,19 +446,16 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */ * cc.AudioEngine.getInstance().setEffectsVolume(0.5); */ setEffectsVolume:function (volume) { - if (volume > 1) { + if (volume > 1) this._effectsVolume = 1; - } - else if (volume < 0) { + else if (volume < 0) this._effectsVolume = 0; - } - else { + else this._effectsVolume = volume; - } - var tmpArr, au; - for (var i in this._effectList) { - tmpArr = this._effectList[i]; + var tmpArr, au, locEffectList = this._effectList; + for (var i in locEffectList) { + tmpArr = locEffectList[i]; if (tmpArr.length > 0) { for (var j = 0; j < tmpArr.length; j++) { au = tmpArr[j]; @@ -480,13 +491,13 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */ */ pauseAllEffects:function () { var tmpArr, au; - for (var i in this._effectList) { - tmpArr = this._effectList[i]; + var locEffectList = this._effectList; + for (var i in locEffectList) { + tmpArr = locEffectList[i]; for (var j = 0; j < tmpArr.length; j++) { au = tmpArr[j]; - if (!au.ended) { + if (!au.ended) au.pause(); - } } } }, @@ -503,9 +514,8 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */ if (this._audioIDList.hasOwnProperty(audioID)) { var au = this._audioIDList[audioID]; - if (!au.ended) { + if (!au.ended) au.play(); - } } }, @@ -517,14 +527,14 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */ */ resumeAllEffects:function () { var tmpArr, au; - for (var i in this._effectList) { - tmpArr = this._effectList[i]; + var locEffectList = this._effectList; + for (var i in locEffectList) { + tmpArr = locEffectList[i]; if (tmpArr.length > 0) { for (var j = 0; j < tmpArr.length; j++) { au = tmpArr[j]; - if (!au.ended) { + if (!au.ended) au.play(); - } } } } @@ -556,9 +566,9 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */ * cc.AudioEngine.getInstance().stopAllEffects(); */ stopAllEffects:function () { - var tmpArr, au; - for (var i in this._effectList) { - tmpArr = this._effectList[i]; + var tmpArr, au, locEffectList = this._effectList; + for (var i in locEffectList) { + tmpArr = locEffectList[i]; for (var j = 0; j < tmpArr.length; j++) { au = tmpArr[j]; if (!au.ended) { @@ -583,24 +593,24 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */ delete this._effectList[keyname]; } - var au,pathName; - for (var k in this._audioIDList) { - au = this._audioIDList[k]; + var au, pathName, locAudioIDList = this._audioIDList; + for (var k in locAudioIDList) { + au = locAudioIDList[k]; pathName = this._getPathWithoutExt(au.src); if(pathName.indexOf(keyname) > -1){ this.stopEffect(k); - delete this._audioIDList[k]; + delete locAudioIDList[k]; } } }, _getEffectList:function (elt) { - if (this._effectList.hasOwnProperty(elt)) { - return this._effectList[elt]; - } - else { - this._effectList[elt] = []; - return this._effectList[elt]; + var locEffectList = this._effectList; + if (locEffectList.hasOwnProperty(elt)) { + return locEffectList[elt]; + } else { + locEffectList[elt] = []; + return locEffectList[elt]; } }, @@ -609,20 +619,19 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */ * @param {String} ext * @returns {Boolean} */ - isFormatSupported:function (ext) { - var tmpExt; - for (var i = 0; i < this._supportedFormat.length; i++) { - tmpExt = this._supportedFormat[i]; - if (tmpExt == ext) { + isFormatSupported: function (ext) { + var tmpExt, locSupportedFormat = this._supportedFormat; + for (var i = 0; i < locSupportedFormat.length; i++) { + tmpExt = locSupportedFormat[i]; + if (tmpExt == ext) return true; - } } return false; }, _getSupportedAudioFormat:function () { // check for sound support by the browser - if (!this._soundEnable) { + if (!this._soundSupported) { return; } @@ -667,11 +676,11 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{ // the Web Audio Context _ctx: null, // may be: mp3, ogg, wav, mp4, m4a - _supportedFormat: [], + _supportedFormat: null, // if sound is not enabled, this engine's init() will return false - _soundEnable: false, + _soundSupported: false, // containing all binary buffers of loaded audio resources - _audioData: {}, + _audioData: null, /* * Issue: When loading two resources with different suffixes asynchronously, the second one might start loading * when the first one is already loading! @@ -679,13 +688,13 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{ * exception "DOM exception 12", it should be a bug of the browser. * So just add something to mark some audios as LOADING so as to avoid duplication. */ - _audiosLoading: {}, + _audiosLoading: null, // the music being played, cc.WebAudioSFX, when null, no music is being played; when not null, it may be playing or paused _music: null, // the volume applied to the music _musicVolume: 1, // the effects being played: { key => [cc.WebAudioSFX] }, many effects of the same resource may be played simultaneously - _effects: {}, + _effects: null, // the volume applied to all effects _effectsVolume: 1, @@ -705,6 +714,10 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{ */ ctor: function() { cc.AudioEngine.prototype.ctor.call(this); + this._supportedFormat = []; + this._audioData = {}; + this._audiosLoading = {}; + this._effects = {}; }, /** @@ -722,16 +735,14 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{ var capabilities = {}; this._checkCanPlay(capabilities); - var formats = ['ogg', 'mp3', 'wav', 'mp4', 'm4a']; + var formats = ['ogg', 'mp3', 'wav', 'mp4', 'm4a'], locSupportedFormat = this._supportedFormat; for (var idx in formats) { var name = formats[idx]; - if (capabilities[name]) { - this._supportedFormat.push(name); - } + if (capabilities[name]) + locSupportedFormat.push(name); } - this._soundEnable = this._supportedFormat.length > 0; - - return this._soundEnable; + this._soundSupported = locSupportedFormat.length > 0; + return this._soundSupported; }, /** @@ -740,10 +751,10 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{ * @returns {Boolean} */ isFormatSupported: function(ext) { - for (var idx in this._supportedFormat) { - if (ext === this._supportedFormat[idx]) { + var locSupportedFormat = this._supportedFormat; + for (var idx in locSupportedFormat) { + if (ext === locSupportedFormat[idx]) return true; - } } return false; }, @@ -771,13 +782,29 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{ req.send(); }, + /** + * Preload music resource. + * @param {String} path + */ + preloadMusic:function(path){ + this.preloadSound(path); + }, + + /** + * Preload effect resource. + * @param {String} path + */ + preloadEffect:function(path){ + this.preloadSound(path); + }, + /** * Preload music resource.
* This method is called when cc.Loader preload resources. * @param {String} path The path of the music file with filename extension. */ preloadSound: function(path) { - if (!this._soundEnable) { + if (!this._soundSupported) { return; } @@ -1138,11 +1165,12 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{ if (keyName in this._audioData) { // the resource has been loaded, just play it - if (!(keyName in this._effects)) { - this._effects[keyName] = []; + var locEffects = this._effects; + if (!(keyName in locEffects)) { + locEffects[keyName] = []; } // a list of sound objects from the same resource - var effectList = this._effects[keyName]; + var effectList = locEffects[keyName]; for (var idx in effectList) { var sfxCache = effectList[idx]; if (!this._isSoundPlaying(sfxCache) && !this._isSoundPaused(sfxCache)) { @@ -1209,8 +1237,9 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{ } this._effectsVolume = volume; - for (var key in this._effects) { - var effectList = this._effects[key]; + var locEffects = this._effects; + for (var key in locEffects) { + var effectList = locEffects[key]; for (var idx in effectList) { this._setSoundVolume(effectList[idx], volume); } @@ -1328,8 +1357,9 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{ * cc.AudioEngine.getInstance().stopAllEffects(); */ stopAllEffects: function() { - for (var key in this._effects) { - var effectList = this._effects[key]; + var locEffects = this._effects; + for (var key in locEffects) { + var effectList = locEffects[key]; for (var idx in effectList) { this._endSound(effectList[idx]); } @@ -1339,7 +1369,7 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{ * If I reassign a new {} to it, that will be appear in the instance. * In other words, the dict in prototype won't release its children. */ - delete this._effects[key]; + delete locEffects[key]; } }, diff --git a/HelloHTML5World/build.xml b/HelloHTML5World/build.xml index e79a277aaf..951921bde0 100644 --- a/HelloHTML5World/build.xml +++ b/HelloHTML5World/build.xml @@ -95,7 +95,6 @@ - @@ -158,27 +157,25 @@ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + diff --git a/HelloHTML5World/cocos2d.js b/HelloHTML5World/cocos2d.js index 30638e6410..c4c6cd9cbb 100644 --- a/HelloHTML5World/cocos2d.js +++ b/HelloHTML5World/cocos2d.js @@ -58,6 +58,7 @@ } window.addEventListener('DOMContentLoaded', function () { + this.removeEventListener('DOMContentLoaded', arguments.callee, false); //first load engine file if specified var s = d.createElement('script'); /*********Delete this section if you have packed all files into one*******/ diff --git a/HelloHTML5World/index.html b/HelloHTML5World/index.html index 728316cf86..e644972d08 100644 --- a/HelloHTML5World/index.html +++ b/HelloHTML5World/index.html @@ -4,11 +4,12 @@ Cocos2d-html5 Hello World test - - + + + -
- -
+ + - - \ No newline at end of file + \ No newline at end of file diff --git a/HelloHTML5World/main.js b/HelloHTML5World/main.js index 975f74dfd8..3caec9bd2f 100644 --- a/HelloHTML5World/main.js +++ b/HelloHTML5World/main.js @@ -43,8 +43,7 @@ var cocos2dApp = cc.Application.extend({ // initialize director var director = cc.Director.getInstance(); - // enable High Resource Mode(2x, such as iphone4) and maintains low resource on other devices. - //director.enableRetinaDisplay(true); + cc.EGLView.getInstance().setDesignResolutionSize(800, 450, cc.RESOLUTION_POLICY.SHOW_ALL); // turn on display FPS director.setDisplayStats(this.config['showFPS']); diff --git a/cocos2d/CCCamera.js b/cocos2d/CCCamera.js index eef780d2e2..a3e3469c08 100644 --- a/cocos2d/CCCamera.js +++ b/cocos2d/CCCamera.js @@ -59,9 +59,10 @@ cc.Camera = cc.Class.extend(/** @lends cc.Action# */{ _upZ:null, _dirty:null, - _lookupMatrix:new cc.kmMat4(), + _lookupMatrix:null, ctor:function () { + this._lookupMatrix = new cc.kmMat4(); this.restore(); }, diff --git a/cocos2d/CCDirector.js b/cocos2d/CCDirector.js index 9b7a3dcc44..399213422e 100644 --- a/cocos2d/CCDirector.js +++ b/cocos2d/CCDirector.js @@ -282,7 +282,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ * converts a UIKit coordinate to an OpenGL coordinate
* Useful to convert (multi) touches coordinates to the current layout (portrait or landscape) *

- * @param {cc.Point} point + * @param {cc.Point} uiPoint * @return {cc.Point} */ convertToGL:function (uiPoint) { @@ -326,7 +326,9 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ /** * Draw the scene. This method is called every frame. Don't call it manually. */ - drawScene:function () { + drawScene: null, + + _drawSceneForCanvas: function () { // calculate "global" dt this.calculateDeltaTime(); @@ -334,23 +336,6 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ if (!this._paused) this._scheduler.update(this._deltaTime); - if (cc.renderContextType === cc.CANVAS) - this._drawSceneForCanvas(); - else - this._drawSceneForWebGL(); - - this._totalFrames++; - - // swap buffers - /* if (this._openGLView) { - this._openGLView.swapBuffers(); - }*/ - - if (this._displayStats) - this._calculateMPF(); - }, - - _drawSceneForCanvas:function () { cc.renderContext.clearRect(0, 0, cc.canvas.width, -cc.canvas.height); /* to avoid flickr, nextScene MUST be here: after tick and before draw. @@ -368,9 +353,21 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ if (this._displayStats) this._showStats(); + + this._totalFrames++; + + if (this._displayStats) + this._calculateMPF(); }, - _drawSceneForWebGL:function () { + _drawSceneForWebGL: function () { + // calculate "global" dt + this.calculateDeltaTime(); + + //tick before glClear: issue #533 + if (!this._paused) + this._scheduler.update(this._deltaTime); + var gl = cc.renderContext; gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); @@ -393,6 +390,11 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ this._showStats(); cc.kmGLPopMatrix(); + + this._totalFrames++; + + if (this._displayStats) + this._calculateMPF(); }, /** @@ -770,6 +772,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ setOpenGLView:function (openGLView) { // set size this._winSizeInPoints = cc.size(cc.canvas.width, cc.canvas.height); //this._openGLView.getDesignResolutionSize(); + this._openGLView = openGLView || cc.EGLView.getInstance(); if (cc.renderContextType === cc.CANVAS) return; @@ -785,7 +788,6 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ //if (this._openGLView != openGLView) { // because EAGLView is not kind of CCObject - this._openGLView = openGLView || cc.EGLView.getInstance(); this._createStatsLabel(); @@ -1089,12 +1091,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ this._mouseDispatcher = mouseDispatcher; }, - _createStatsLabel:function () { - if(cc.renderContextType === cc.CANVAS) - this._createStatsLabelForCanvas(); - else - this._createStatsLabelForWebGL(); - }, + _createStatsLabel: null, _createStatsLabelForWebGL:function(){ if((cc.Director._fpsImageLoaded == null) || (cc.Director._fpsImageLoaded == false)) @@ -1171,6 +1168,14 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ } }); +if (cc.Browser.supportWebGL) { + cc.Director.prototype.drawScene = cc.Director.prototype._drawSceneForWebGL; + cc.Director.prototype._createStatsLabel = cc.Director.prototype._createStatsLabelForWebGL; +} else { + cc.Director.prototype.drawScene = cc.Director.prototype._drawSceneForCanvas; + cc.Director.prototype._createStatsLabel = cc.Director.prototype._createStatsLabelForCanvas; +} + /*************************************************** * implementation of DisplayLinkDirector **************************************************/ @@ -1273,6 +1278,7 @@ cc.defaultFPS = 60; cc.Director._fpsImage = new Image(); cc.Director._fpsImage.addEventListener("load", function () { cc.Director._fpsImageLoaded = true; + this.removeEventListener('load', arguments.callee, false); }); cc.Director._fpsImage.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAAgCAYAAAD9qabkAAAKQ2lDQ1BJQ0MgcHJvZmlsZQAAeNqdU3dYk/cWPt/3ZQ9WQtjwsZdsgQAiI6wIyBBZohCSAGGEEBJAxYWIClYUFRGcSFXEgtUKSJ2I4qAouGdBiohai1VcOO4f3Ke1fXrv7e371/u855zn/M55zw+AERImkeaiagA5UoU8Otgfj09IxMm9gAIVSOAEIBDmy8JnBcUAAPADeXh+dLA//AGvbwACAHDVLiQSx+H/g7pQJlcAIJEA4CIS5wsBkFIAyC5UyBQAyBgAsFOzZAoAlAAAbHl8QiIAqg0A7PRJPgUA2KmT3BcA2KIcqQgAjQEAmShHJAJAuwBgVYFSLALAwgCgrEAiLgTArgGAWbYyRwKAvQUAdo5YkA9AYACAmUIszAAgOAIAQx4TzQMgTAOgMNK/4KlfcIW4SAEAwMuVzZdL0jMUuJXQGnfy8ODiIeLCbLFCYRcpEGYJ5CKcl5sjE0jnA0zODAAAGvnRwf44P5Dn5uTh5mbnbO/0xaL+a/BvIj4h8d/+vIwCBAAQTs/v2l/l5dYDcMcBsHW/a6lbANpWAGjf+V0z2wmgWgrQevmLeTj8QB6eoVDIPB0cCgsL7SViob0w44s+/zPhb+CLfvb8QB7+23rwAHGaQJmtwKOD/XFhbnauUo7nywRCMW735yP+x4V//Y4p0eI0sVwsFYrxWIm4UCJNx3m5UpFEIcmV4hLpfzLxH5b9CZN3DQCshk/ATrYHtctswH7uAQKLDljSdgBAfvMtjBoLkQAQZzQyefcAAJO/+Y9AKwEAzZek4wAAvOgYXKiUF0zGCAAARKCBKrBBBwzBFKzADpzBHbzAFwJhBkRADCTAPBBCBuSAHAqhGJZBGVTAOtgEtbADGqARmuEQtMExOA3n4BJcgetwFwZgGJ7CGLyGCQRByAgTYSE6iBFijtgizggXmY4EImFINJKApCDpiBRRIsXIcqQCqUJqkV1II/ItchQ5jVxA+pDbyCAyivyKvEcxlIGyUQPUAnVAuagfGorGoHPRdDQPXYCWomvRGrQePYC2oqfRS+h1dAB9io5jgNExDmaM2WFcjIdFYIlYGibHFmPlWDVWjzVjHVg3dhUbwJ5h7wgkAouAE+wIXoQQwmyCkJBHWExYQ6gl7CO0EroIVwmDhDHCJyKTqE+0JXoS+cR4YjqxkFhGrCbuIR4hniVeJw4TX5NIJA7JkuROCiElkDJJC0lrSNtILaRTpD7SEGmcTCbrkG3J3uQIsoCsIJeRt5APkE+S+8nD5LcUOsWI4kwJoiRSpJQSSjVlP+UEpZ8yQpmgqlHNqZ7UCKqIOp9aSW2gdlAvU4epEzR1miXNmxZDy6Qto9XQmmlnafdoL+l0ugndgx5Fl9CX0mvoB+nn6YP0dwwNhg2Dx0hiKBlrGXsZpxi3GS+ZTKYF05eZyFQw1zIbmWeYD5hvVVgq9ip8FZHKEpU6lVaVfpXnqlRVc1U/1XmqC1SrVQ+rXlZ9pkZVs1DjqQnUFqvVqR1Vu6k2rs5Sd1KPUM9RX6O+X/2C+mMNsoaFRqCGSKNUY7fGGY0hFsYyZfFYQtZyVgPrLGuYTWJbsvnsTHYF+xt2L3tMU0NzqmasZpFmneZxzQEOxrHg8DnZnErOIc4NznstAy0/LbHWaq1mrX6tN9p62r7aYu1y7Rbt69rvdXCdQJ0snfU6bTr3dQm6NrpRuoW623XP6j7TY+t56Qn1yvUO6d3RR/Vt9KP1F+rv1u/RHzcwNAg2kBlsMThj8MyQY+hrmGm40fCE4agRy2i6kcRoo9FJoye4Ju6HZ+M1eBc+ZqxvHGKsNN5l3Gs8YWJpMtukxKTF5L4pzZRrmma60bTTdMzMyCzcrNisyeyOOdWca55hvtm82/yNhaVFnMVKizaLx5balnzLBZZNlvesmFY+VnlW9VbXrEnWXOss623WV2xQG1ebDJs6m8u2qK2brcR2m23fFOIUjynSKfVTbtox7PzsCuya7AbtOfZh9iX2bfbPHcwcEh3WO3Q7fHJ0dcx2bHC866ThNMOpxKnD6VdnG2ehc53zNRemS5DLEpd2lxdTbaeKp26fesuV5RruutK10/Wjm7ub3K3ZbdTdzD3Ffav7TS6bG8ldwz3vQfTw91jicczjnaebp8LzkOcvXnZeWV77vR5Ps5wmntYwbcjbxFvgvct7YDo+PWX6zukDPsY+Ap96n4e+pr4i3z2+I37Wfpl+B/ye+zv6y/2P+L/hefIW8U4FYAHBAeUBvYEagbMDawMfBJkEpQc1BY0FuwYvDD4VQgwJDVkfcpNvwBfyG/ljM9xnLJrRFcoInRVaG/owzCZMHtYRjobPCN8Qfm+m+UzpzLYIiOBHbIi4H2kZmRf5fRQpKjKqLupRtFN0cXT3LNas5Fn7Z72O8Y+pjLk722q2cnZnrGpsUmxj7Ju4gLiquIF4h/hF8ZcSdBMkCe2J5MTYxD2J43MC52yaM5zkmlSWdGOu5dyiuRfm6c7Lnnc8WTVZkHw4hZgSl7I/5YMgQlAvGE/lp25NHRPyhJuFT0W+oo2iUbG3uEo8kuadVpX2ON07fUP6aIZPRnXGMwlPUit5kRmSuSPzTVZE1t6sz9lx2S05lJyUnKNSDWmWtCvXMLcot09mKyuTDeR55m3KG5OHyvfkI/lz89sVbIVM0aO0Uq5QDhZML6greFsYW3i4SL1IWtQz32b+6vkjC4IWfL2QsFC4sLPYuHhZ8eAiv0W7FiOLUxd3LjFdUrpkeGnw0n3LaMuylv1Q4lhSVfJqedzyjlKD0qWlQyuCVzSVqZTJy26u9Fq5YxVhlWRV72qX1VtWfyoXlV+scKyorviwRrjm4ldOX9V89Xlt2treSrfK7etI66Trbqz3Wb+vSr1qQdXQhvANrRvxjeUbX21K3nShemr1js20zcrNAzVhNe1bzLas2/KhNqP2ep1/XctW/a2rt77ZJtrWv913e/MOgx0VO97vlOy8tSt4V2u9RX31btLugt2PGmIbur/mft24R3dPxZ6Pe6V7B/ZF7+tqdG9s3K+/v7IJbVI2jR5IOnDlm4Bv2pvtmne1cFoqDsJB5cEn36Z8e+NQ6KHOw9zDzd+Zf7f1COtIeSvSOr91rC2jbaA9ob3v6IyjnR1eHUe+t/9+7zHjY3XHNY9XnqCdKD3x+eSCk+OnZKeenU4/PdSZ3Hn3TPyZa11RXb1nQ8+ePxd07ky3X/fJ897nj13wvHD0Ivdi2yW3S609rj1HfnD94UivW2/rZffL7Vc8rnT0Tes70e/Tf/pqwNVz1/jXLl2feb3vxuwbt24m3Ry4Jbr1+Hb27Rd3Cu5M3F16j3iv/L7a/eoH+g/qf7T+sWXAbeD4YMBgz8NZD+8OCYee/pT/04fh0kfMR9UjRiONj50fHxsNGr3yZM6T4aeypxPPyn5W/3nrc6vn3/3i+0vPWPzY8Av5i8+/rnmp83Lvq6mvOscjxx+8znk98ab8rc7bfe+477rfx70fmSj8QP5Q89H6Y8en0E/3Pud8/vwv94Tz+4A5JREAAAAGYktHRAD/AP8A/6C9p5MAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfcAgcQLxxUBNp/AAAQZ0lEQVR42u2be3QVVZbGv1N17829eRLyIKAEOiISEtPhJTJAYuyBDmhWjAEx4iAGBhxA4wABbVAMWUAeykMCM+HRTcBRWkNH2l5moS0LCCrQTkYeQWBQSCAIgYRXEpKbW/XNH5zS4noR7faPEeu31l0h4dSpvc+t/Z199jkFWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhY/H9D/MR9qfKnLj/00U71aqfJn9+HCkCR/Wk36ddsgyJ/1wF4fkDfqqm9/gPsUeTnVr6a2xlQfnxdI7zs0W7irzD17Ytb2WT7EeNv/r4ox1O3Quf2QP2pgt9utwfout4FQE8AVBSlnaRmfvAURQkg2RlAbwB9AThlW5L0GaiKojhJhgOIBqDa7XaPrusdPtr5kQwF0BVAAoBIABRCKDd5aFUhRDAAw57eAOwAhKIoupft3zoqhB1AqLwuHIBut9uFt02qqvqRDJR2dAEQJj/BAOjn56dqmma+xiaECAEQAWAggLsB6A6HQ2iaZggBhBAqgEAAnQB0kzaEmT4hAITT6VQ8Ho/HJAKKECJQtr8LwD1y/A1/vcdfEUIEyfZ9AcQbYvZ942Px88L2UwlJR0dH0EMPPbRj5syZPUeNGrXR7Xb/641xIwJ1XY9NSUlZm52dfW+XLl1w8uRJzJ8//+OGhoYJqqqe1TSt1Wsm9NN1PSIqKmr12rVrR5WUlHy1bdu2AQCumWc3IYRD1/UwVVXnFRQUTIuNjUVzczN2797dWFJSkq8oymZd15sAGAEnFEUJ1nX9nzIzM1dnZmZGh4SE4OTJk5g5c+Zf29vbp9pstrMej6fVOyhIhgAYU1hY+B+hoaGoqKg4XVlZea+XTULTNFdCQsLGiRMnPuR2u3UhBOV9eeDAAWXTpk095DUe6WsoyRE5OTlr0tLSAux2O/bs2cO5c+e+pijKUpIXSHaQVAGkvPLKK++6XK4OksJLCFlXV2cvKSlJBFAjhU+x2WwhHo9nUHp6+urMzMy7wsLCUF9fjxdffPHjxsbGiTab7WuPx9NiEutOuq4PyMjI+M+srKyYqKgoHD58GDNmzNjq8XhyVFU9b/q+LH7hBAEYu3PnTlZVVRFAGgCX6f/tAHoOHDjwa0p27txp/JO9e/f+QM7cipw9nfL3kQBKt2zZQpJ87rnn6mQmoHilw2EACs+cOUOSrK+vZ1NTE0nyo48+IoBpxswoBcMJ4Ndjx471kOTFixe5d+9ekqTH42H//v13A4jyzpAURfEH0H/OnDnthu1z5sw558MmFUCPWbNmnaMP3nrrLZoyDmP8Hl68eDFJ8siRI9/Yc+zYMQKYKdtAztrTrl27xptRXV1NAKMAOAyBBBA/Y8aMdpLs6Ojgxx9//E37+++//29yvFXppwvAwMcee8xjtDHsuXLlCqOjo//ia3wsfpkoALqFhoZuIckJEyackimm3dQmEMDUmpoakmRISMhhAHOHDx/eQJIbN24kgKEyMAHAFRMTs2XXrl1saWkhSZ0kp0+ffhrAr3wEW/S8efOukORLL72kA1gKYMPWrVtJkk899dRJAHeYrgsEsIQkjx8/TgDvAPjd448/3kaSb7zxBmUa7vC6z53BwcFbSHL9+vU6Sc6aNes8gF5ewWAH0PfVV18lSQL4DMBGIcQ6AKtcLleBFC2jXtFt8ODBe0iyoqKCAJYByC8qKmJDQwOzsrK+MAmqo1OnTveHhoa+GRkZ+XZkZOSWiIiIvzgcjk9mzpypkWRmZuZpmbYbGV4AgPnNzc1sa2sjgN0A5iQmJtaSZHl5OQHcb/K3s81mW0uSTU1NBFAFYFbfvn1Pk+Tbb79NAA8IIVzW42/hByA+Pz/fLR/2ZXIda05NI/z9/TeR5J49ewhgqlxTrtI0jY2NjQQw3zTLuWJiYjaUlJToS5Ys6fjkk080kwDEeAmADcA9GzZsIElGRUW9CyAWwLApU6Y0kOSKFSsog9QICGdERMTGsrIyZmVlEcC9AB4IDw/fTpLbtm0jgN94CUAnAJmVlZVcs2aNZ/LkyRdJcvbs2b4EwAkgZfPmzTxw4AABFAN4BkC6vFeUSewcAO5duXIlSTIhIaEawGMAxgKYAmAGgCS73e5vrKVk/yGythANYEhCQsIhkly+fDkBpKqqGmL6DgIALDKN/3yZpVWQZGVlJQE8aPI3KiMjo5okV61aRQAjAPQBMPfIkSN0u90EUCBtsPiFEwpgbn19PdetW2fM5N4zQ9ekpKQqkty0aRMBpMjiWM6JEydIkoqirJUFJ6iq6pAPVy8A6cZMehMBUACEuVyuFwG8HBwcPEIWx367ZMkSjSQXLVrUJouTRorrkAHdA8BdQogsAOsKCwtJkmPGjDkvMw2bDDo/ADEjRoz4XylyFbm5uY0mAbjLyyZ/AOOrq6tZVlbWsWDBgo69e/eyoqKCgwcPPg4gSQaoIRbp27dvN7KF+tLSUr28vJwFBQXtMpvpYRIM7+wrAkDeqVOnePbsWQIoNKfzpiXPg8uXLydJJicnNwF4f+nSpW6STEtLq5fjYwhk1wkTJtSQ5Ouvv04AqTKj+N2xY8dIkgEBAW/Ie1v8wncRegwZMmQvSfbr12+3Ua33WqPfOWbMmP0kWVpaSgCDZAqcfejQIWNZsEGKgvnh9gfQb9myZd8nAEJVVZtMkUNk8CcNHTq0liR1XWdYWNhmH1mJIme80OnTp18x1rp5eXkEsNJms92Fb7e/IgEsvHz5Mp999tkmAI/l5uZeMC0B7vEqqAYAyL106RJJsra2lpWVld+sucePH38ZQG+5NncBeOrgwYMkqbe3t/Po0aOsra011wAWyl0H7x0JJ4DE+fPnu0kyPT29DsDdUrBuyNKEEAkAdpw/f/6GeoEM8GUmfwEgPCIiopwkGxsbabPZPgOw6L777vvm4p49e26VGYjFLxUhhD+ApLKyMp44ccIoVnXybgbgzkcfffRzklyzZg0BDJYCMMmoCwQFBXkLgLGWvvcWAgBToSsKwNPTp09vMR7UuLi4rwH0lgU8c/Db5ezbeeTIkRWzZ8++aMxu+fn5BPCADBwHgP4LFy701NXVEUAJgAnPP/98kyxMNgHo53A4zH77BQQETMvPz7+Um5vbBuAlAFMSExPPmdbVL0qh8Acw8fDhw5SCchVAEYAVb775JknyhRdeaJYztHfxMwLAaqNwCGC2FArv8x0hAHKNLGPKlCme5OTk/Zs3bzb7O0wKiiG8KXl5ed8IxenTp0mSR48e1UmyW7duWywBuD2xyQcgFECgoih+8H1gyJgZV5Lkyy+/3CbTRIePtl2HDBmyw1QBHyGDdXZdXR1JUghRKkXBjOMHCoBdpr0L3nvvPZLkF198wejo6O0A4lVVDTb74HQ6AwD8Wq7Jh8rgGgDgQ13XjVR8qaxJuADMbmlpYXl5uV5UVNRWUFDgfv/993Vj/ZydnU1c37eHXML4S3viAcQqitJD2l104cIFY8lTKsXSBWBMVVWVcd9yed2A1NTUQ6Zl00CvLMMOoHdubm6zFIlWOf5+PsY/Kj09vdrU11QAwwGsv3jxIk21m2DZr10I0RXAuAcffPBgaWkpV69eTYfDcdiwUxY0w6xw+flX8L1xApjevXv3lREREaW6rofB93aPDUDQpEmTMgHgtddeqwBwEd/utZvpqK6uPgEAcXFxkA94NwB9unfvjrNnz4LklwDcf08iIqv66Zs2bXrl4YcfxooVKxAbG7uqrq5uAYA2TdOEqqpGYIi2tjbl6aeffu/YsWPv5uTk7JaC1wHg4Pnz542MwoVvTx+21dbWYvjw4WLixIl+2dnZ9lGjRgmSTE1NRUpKCkwFTGiaxtTU1OXTpk3707Bhw/6g67pDipnT4biuj7qut+Lbk3Vf1tTUXI9qu91Pjq1QFEUBgJaWFgBo8yGOQ8eNGxcAAOvXr/8QwBUfYygAKL169eoCABcuXACAWtn2hOGv0+kMNO1KiPDw8F4A4rZv3/7R1KlTR0+bNu1ht9u9r1+/fqitrQXJgwDarRC6/QjPzs4+QJIffPCB9/aQmSAA43ft2mW0e1QGoi8CAPyLsZccExNTC2BlRkbGRdOyYJCP2csBIN6UAZzCd7cBbQCijYp/dXU1ExMTz6SmptaMHj36f9LS0vYlJCRsl6mxIWSdu3fv/g5J7t+/nwC2AShMTk6+SJKff/45AWRLYbD7+fndAeDf5BJnLoCCyZMnt5JkdnZ2C4B/F0KEm1Pu+Pj4rST55ZdfEsBWAK+mpaVdMo3raDn7KwDuSEpK+m+S3LBhAwG8DuCtHTt2UBbpjgC408vvcFVV15HkuXPnjMp+p5uMf0RcXNyHJNnQ0EBVVfcCWBQXF3fG+Jv0yxABPwB5LS0tRmFxN4BlTzzxxGWSXLx4sS5F3GGFy+1Hp5SUlJq6ujoWFxdTpsZ2H+0iIyMj/0iSWVlZX5mr5jfJFroPGzasxlhTnjp1iiTZ3NxMl8tlrCd9pfa9SkpKSJI5OTmnZOageLUZZqxvfVFWVkZcPwdgNwnSCKPqb17jkmR8fPzfZMDZ5CRsFBmNI7h95s2b1yhT7/MAYmStwCx4vy0uLqa3v5qmEcCfvSr1QQAeXb16NY3Cm3HQ55133iGAp+SxZTNhKSkpfzUddkrFjYevzAQCeGjp0qXfsYckY2NjTwD4leGDLCL2HTdunNtoY+zWSHFcIHdsFCtcfuZ1vO9Eqs3m7/F47sb1k2qX/f3997W2tl7BjWfpBYDOzzzzzIVJkyZh0KBBCwEsB3AJvl9AETabLcDj8dwRFRW1ctasWb8JCgpSzp07d62wsPC/Wltb8xRFadR1/ZqPXYbgAQMGbI2Pjw/+6quv9ldVVT0r01ezuPRJSUn5Y9euXXVd11WzDaqq6kePHm3+7LPPRgO4KlNuxWazhXo8nuTk5OSXMjIyEl0uFxoaGtqKior+dPXq1VdUVT0jj7r68ieoT58+vx8yZMjdx48fP1JVVTVF9m20VW02WyfZf97YsWPjXS4X6urqWvPy8jYCWCyEuEDS8FdVFKWzruv//OSTTy5OTk7uqWkaPv3007qysrJ8RVH+LI8ym8/rB3Tu3HnRI488knLo0KG2ffv2ZQI4C98vP6mqqoZqmpaclpa2cOTIkX39/f3R0NDQUVxc/G5TU9PLqqrWa5rWLH1QVFUN0TStX1JSUvH48eP7BwYG4uDBg1cKCgpeBbBe2u+2Qug2EwD5N5sMPuNtMe8XP4TT6Qxoa2sbIGeXvUKIK7d4IISiKC5d1wPljOfA9bPwzYqiXNV13dd6Uqiq6qdpml2mpe02m63d4/G4vcTF5fF47LJf71nJA6BZVVW3pmntuPHlmAD5wk6Q9NnbHp9vHaqq6tA0zU/64PZhk1FfCZB9G/23ALiqKEqzD39tpvbGUqoFwFUhRLP3yzpCCDtJpxyXDulfG27+pqRR3DXsUWVd4Yq0x/taVQjhIhksC8L+ABpM9ljBf5sKwI8pIBr75L5E4vvu+UNeG/a+hv+AL7yFH8qPtOfHjtOP6V/Bja8D6z/B2Nys/1u9Xv33tLf4GfF/LC4GCJwByWIAAAAASUVORK5CYII="; diff --git a/cocos2d/CCDrawingPrimitives.js b/cocos2d/CCDrawingPrimitives.js index d21fd0d6a1..d6f86e2f3e 100644 --- a/cocos2d/CCDrawingPrimitives.js +++ b/cocos2d/CCDrawingPrimitives.js @@ -55,7 +55,7 @@ cc.DrawingPrimitive = cc.Class.extend(/** @lends cc.DrawingPrimitive# */{ /** * returns render context of drawing primitive - * @return {CanvasContext} + * @return {CanvasRenderingContext2D} */ getRenderContext:function () { return this._renderContext; @@ -63,7 +63,7 @@ cc.DrawingPrimitive = cc.Class.extend(/** @lends cc.DrawingPrimitive# */{ /** * Constructor - * @param {CanvasContext} renderContext + * @param {CanvasRenderingContext2D} renderContext */ ctor:function (renderContext) { this._renderContext = renderContext; @@ -172,7 +172,7 @@ cc.DrawingPrimitive = cc.Class.extend(/** @lends cc.DrawingPrimitive# */{ /** * draw a catmull rom line - * @param {cc.PointArray} points + * @param {Array} points * @param {Number} segments */ drawCatmullRom:function (points, segments) { @@ -181,7 +181,7 @@ cc.DrawingPrimitive = cc.Class.extend(/** @lends cc.DrawingPrimitive# */{ /** * draw a cardinal spline path - * @param {cc.PointArray} config + * @param {Array} config * @param {Number} tension * @param {Number} segments */ @@ -200,6 +200,7 @@ cc.DrawingPrimitiveCanvas = cc.DrawingPrimitive.extend(/** @lends cc.DrawingPrim * 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) { @@ -217,6 +218,7 @@ cc.DrawingPrimitiveCanvas = cc.DrawingPrimitive.extend(/** @lends cc.DrawingPrim * @override * @param {Array} points point of array * @param {Number} numberOfPoints + * @param {Number} size */ drawPoints:function (points, numberOfPoints, size) { if (points == null) { @@ -397,7 +399,7 @@ cc.DrawingPrimitiveCanvas = cc.DrawingPrimitive.extend(/** @lends cc.DrawingPrim /** * draw a CatmullRom curve * @override - * @param {cc.PointArray} points + * @param {Array} points * @param {Number} segments */ drawCatmullRom:function (points, segments) { @@ -407,7 +409,7 @@ cc.DrawingPrimitiveCanvas = cc.DrawingPrimitive.extend(/** @lends cc.DrawingPrim /** * draw a cardinal spline path * @override - * @param {cc.PointArray} config + * @param {Array} config * @param {Number} tension * @param {Number} segments */ @@ -473,7 +475,7 @@ cc.DrawingPrimitiveCanvas = cc.DrawingPrimitive.extend(/** @lends cc.DrawingPrim /** * draw a star - * @param {CanvasContext} ctx canvas context + * @param {CanvasRenderingContext2D} ctx canvas context * @param {Number} radius * @param {cc.Color3B|cc.Color4B|cc.Color4F} color */ @@ -513,7 +515,7 @@ cc.DrawingPrimitiveCanvas = cc.DrawingPrimitive.extend(/** @lends cc.DrawingPrim /** * draw a color ball - * @param {CanvasContext} ctx canvas context + * @param {CanvasRenderingContext2D} ctx canvas context * @param {Number} radius * @param {cc.Color3B|cc.Color4B|cc.Color4F} color */ @@ -551,8 +553,8 @@ cc.DrawingPrimitiveCanvas = cc.DrawingPrimitive.extend(/** @lends cc.DrawingPrim /** * set the drawing color with 4 unsigned bytes * @param {Number} r red value (0 to 255) - * @param {Number} r green value (0 to 255) - * @param {Number} r blue 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) */ setDrawColor4B:function (r, g, b, a) { @@ -563,8 +565,8 @@ cc.DrawingPrimitiveCanvas = cc.DrawingPrimitive.extend(/** @lends cc.DrawingPrim /** * set the drawing color with 4 floats * @param {Number} r red value (0 to 1) - * @param {Number} r green value (0 to 1) - * @param {Number} r blue value (0 to 1) + * @param {Number} g green value (0 to 1) + * @param {Number} b blue value (0 to 1) * @param {Number} a Alpha value (0 to 1) */ setDrawColor4F:function (r, g, b, a) { @@ -608,7 +610,7 @@ cc.DrawingPrimitiveWebGL = cc.DrawingPrimitive.extend({ if (!ctx instanceof WebGLRenderingContext) throw "Can't initialise DrawingPrimitiveWebGL. context need is WebGLRenderingContext"; - this._super(ctx); + cc.DrawingPrimitive.prototype.ctor.call(this, ctx); this._color = new cc.Color4F(1.0, 1.0, 1.0, 1.0); }, @@ -751,7 +753,7 @@ cc.DrawingPrimitiveWebGL = cc.DrawingPrimitive.extend({ }, /** - * draws a poligon given a pointer to cc.Point coordiantes and the number of vertices measured in points. + * draws a polygon given a pointer to cc.Point coordiantes and the number of vertices measured in points. * @param {Array} vertices a pointer to cc.Point coordiantes * @param {Number} numOfVertices the number of vertices measured in points * @param {Boolean} closePolygon The polygon can be closed or open @@ -994,8 +996,8 @@ cc.DrawingPrimitiveWebGL = cc.DrawingPrimitive.extend({ /** * set the drawing color with 4 unsigned bytes * @param {Number} r red value (0 to 255) - * @param {Number} r green value (0 to 255) - * @param {Number} r blue 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) */ setDrawColor4B:function (r, g, b, a) { @@ -1008,8 +1010,8 @@ cc.DrawingPrimitiveWebGL = cc.DrawingPrimitive.extend({ /** * set the drawing color with 4 floats * @param {Number} r red value (0 to 1) - * @param {Number} r green value (0 to 1) - * @param {Number} r blue value (0 to 1) + * @param {Number} g green value (0 to 1) + * @param {Number} b blue value (0 to 1) * @param {Number} a Alpha value (0 to 1) */ setDrawColor4F:function (r, g, b, a) { diff --git a/cocos2d/CCLoader.js b/cocos2d/CCLoader.js index f2ea27542d..bf09c4165c 100644 --- a/cocos2d/CCLoader.js +++ b/cocos2d/CCLoader.js @@ -223,7 +223,6 @@ cc.Loader = cc.Class.extend(/** @lends cc.Loader# */{ } }, - _schedulePreload: function () { var _self = this; this._interval = setInterval(function () { @@ -235,7 +234,6 @@ cc.Loader = cc.Class.extend(/** @lends cc.Loader# */{ clearInterval(this._interval); }, - _getResType: function (resInfo) { var isFont = resInfo.fontName; if (isFont != null) { @@ -243,6 +241,10 @@ cc.Loader = cc.Class.extend(/** @lends cc.Loader# */{ } else { var src = resInfo.src; var ext = src.substring(src.lastIndexOf(".") + 1, src.length); + + var index = ext.indexOf("?"); + if(index > 0) ext = ext.substring(0, index); + for (var resType in cc.RESOURCE_TYPE) { if (cc.RESOURCE_TYPE[resType].indexOf(ext) != -1) { return resType; @@ -270,9 +272,9 @@ cc.Loader = cc.Class.extend(/** @lends cc.Loader# */{ this._selector(this); } - this._curNumber = 0; this._loadedNumber = 0; + this._totalNumber = 0; }, _registerFaceFont: function (fontRes) { @@ -404,7 +406,7 @@ cc.LoaderScene = cc.Scene.extend(/** @lends cc.LoaderScene# */{ * Constructor */ ctor: function () { - this._super(); + cc.Scene.prototype.ctor.call(this); this._winSize = cc.Director.getInstance().getWinSize(); }, init:function(){ @@ -418,6 +420,7 @@ cc.LoaderScene = cc.Scene.extend(/** @lends cc.LoaderScene# */{ var _this = this; this._logoTexture.addEventListener("load", function () { _this._initStage(centerPos); + this.removeEventListener('load', arguments.callee, false); }); this._logoTexture.src = "data:image/jpeg;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAAlAAD/4QMpaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjAtYzA2MCA2MS4xMzQ3NzcsIDIwMTAvMDIvMTItMTc6MzI6MDAgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdFJlZj0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlUmVmIyIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjM4MDBEMDY2QTU1MjExRTFBQTAzQjEzMUNFNzMxRkQwIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjM4MDBEMDY1QTU1MjExRTFBQTAzQjEzMUNFNzMxRkQwIiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIFBob3Rvc2hvcCBDUzUgV2luZG93cyI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkU2RTk0OEM4OERCNDExRTE5NEUyRkE3M0M3QkE1NTlEIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkU2RTk0OEM5OERCNDExRTE5NEUyRkE3M0M3QkE1NTlEIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+/+4ADkFkb2JlAGTAAAAAAf/bAIQADQkJCQoJDQoKDRMMCwwTFhENDREWGhUVFhUVGhkUFhUVFhQZGR0fIB8dGScnKionJzk4ODg5QEBAQEBAQEBAQAEODAwOEA4RDw8RFA4RDhQVERISERUfFRUXFRUfKB0ZGRkZHSgjJiAgICYjLCwoKCwsNzc1NzdAQEBAQEBAQEBA/8AAEQgAyACgAwEiAAIRAQMRAf/EALAAAAEFAQEAAAAAAAAAAAAAAAQAAgMFBgcBAQEAAwEBAAAAAAAAAAAAAAAAAQMEAgUQAAIBAgIEBwoLBgQGAwAAAAECAwAEEQUhMRIGQVFxsTITFGGBwdEiQlKSMzWRoeFicqKyI1NzFYJjJDQWB9KjVCbxwkNkJWXik3QRAAIBAgMFBQcDBQEAAAAAAAABAhEDIRIEMUFRcTJhwVIUBZGhsSJyEzOB0ULhYpIjUxX/2gAMAwEAAhEDEQA/AMJSpUqAVKlXuFAeUq9wpUB5XuFe4V6ooDzZHDox0CnGMinzwl7Z8NajaHeoO3vmTBZBtp9YUIqTEV5ROxHKnWRnaU8VRMhFBUjpV7hSoSeUq9pUB5Sr2lhQHlKvcK8oBV7hSFSRrtaKAZs07YNPM1pG2xJIAw1jSeandry/8X4m8VCKkWwaWwam7Xl/4v1W8VLtmX/i/VbxUoKkWwakSM407tmX/i/VbxUmzGwjQsjdY41IARie/U0IbZO0kNtCXnOCkEBeFu4KI3Bs7DNb27ya+jDx3kJeEnpJJEcQVbWDsk17u5urd591ucZkWhym2Vnd9RkCDEpFxDRpbw0bunu5mlp2De2FMLYXOD2wB2xbOeraUcYGJ72mlSUiqzzdzMd3Z3mixltA2yzcK/NlHM1DQyRXce1HocdNOEfJXZ88y9ZojOqhiBszIRiHQ8Y4cK5TvHuzLljHNMqxNoDjLFraHHnjPxcNCGVbxEUzYNTx5jZSxhpW6qTzlwJ+DCvO2Zf+L9VvFSgqyHYNLYNTdssPxfibxUu15f8Ai/VPiqCakOwa82DU/a8v/F+JvFTDdWPBL8R8VKCvYRYV5UzoMAy6QdIIqI0B4KJtxiRQwou16QoGUkntH5Tz0RbZbmF2hktraSVBo2lUkY8tDye0flPPXTslVUyiyVRsjqUOA4yMT8dW2ram2m6UVTNq9S7EIyUVJydMTn/6DnP+im9Wl+g5z/opvVrpteEhQWY4AaSTwAVf5WPiZh/9S5/zj7zltzlmYWkfWXNvJDGTgGcYDHirR7i7mSbwXParsFMrgb7w6jKw/wCmnc9I14kF3vpvCljbMyWMOJL4aEiB8qU/ObUK7HYWVrl1pFZWiCOCBQqKOLjPGTrNZZqKbUXVHq2nNwTuJRk1VpbgXN8s7Rk5ym0UQQzhIG2NAjhxHWbI+gCBVjBBFbwxwQqEiiUJGg1BVGAFe7dV28WYLYZFmF2Th1UD7JGjymGyn1iK5OyzIBGB1HgrLZhamzumQAGJwSqnSCh1q3GOCodxt4cxurdcpzuN4cyhiWaF5Bg09udUmnWw1H/jV9nFuJ7Quo+8h8peThFA+047vduyMtk7fYqTl07YFdfUufMPzT5p71UdtlmYXaGS2t3mQHAsgxANdadYJopLe4QS2867EsZ4QfCNYrCFbjdDPmgkYyWFxgVf04ifJf6ScNdRUW1XBb6FU5TjF5EpSSrGu/s5lN+g5z/opvVpfoOc/wCim9WtdHnatvObJXDW7xLGhB8nrPaY9/HCr+tEdPCVaSeDoYLnqF63lzW4/PFSW3ecxbI84VSzWUwUaSdg0DXXK5nvAipnd6qgKvWnQO7pri9ZUEmm3Vl2j1kr8pRlFRyquBNZjGxQ/S56Y1S2fu9OVueon11Szahoou06QoQUXadIVCD2FJJ7R+U89dMydv8Axdn+TH9muZye0flPPXQstlK5Tbka1gUjlC1q0vVLkeb6r+O3Tx9xcY1nt8c0NrZCyiOE1108NYjGv1joo7Js1jzKyScYLIvkzL6LDwHXVJksH9Sb49dKNq0tj1jA6uriOCL+02FWX7iVtZX1/AzaHTyeoauKn2MX9W79zebiZCuR5MjSrhfXuEtwTrUeZH+yNfdrRNcxI6IzhXlJEak6WIGJ2Rw4ChWnChndtlVBLMdQA0k1gbXNMzzDfDLs6mjaPKppJbWwJ1bOwwxw43OnHh71YT3DpfWUJmFlb5jHHDdeXBHIsrRea5TSqvxqG04cNN62vetoCS4tre5mgnkGE9q+3DKOkuI2WX6LDQRRHWDh1UCtwj7QRg2wdl8Djgw1qe7XvW0BQ3kfZ7mSLgU+T9E6RVbnuVrnWVSWqj+Lt8ZbRuHEdKPkYVcZ2MJY5fSGyeVar45+rkWQHAqccalPE5km1htWK5nK4Wnt5FuUBUwOMG4nGkA/BXUrW4S6torlOjMgcd/xVn7rLo7zKs0uEjCNeSvdwoBhgsZxX1l2j36k3Lu+uyprdj5Vs5A+i/lD48a0aaVJOPi7jB6lbzWozpjB48pf1NDXNN4vfl7+Z4BXS65pvF78vfzPAK71XTHmZ/S/yT+jvJ7L3fHytz1E+upbL+Qj5W56jfXWRnsIYKLtekKEFGWvSFQgyjk9o/Keet3YthlMP/5x9msJJ7R+U89biyb/AMXEv7gD6tadL1T+kwepRrC39ZkLDMbiwMvUHRPG0bjlGg8ore/23sxBldxfMPLupNhT8yL/AORNZbdzJ484scytxgLqJY5LZj6Q2sV5G1Vud1mjjyG0ij0NEGSZToKyhjtqw4waztuiXA3qKTbSxltfGhbZlE95ZtZqxVbgiOZhrER9ph3Svk9+pJILZ4Y4DGBFCUMKjRsGPobPFhUfW0NJmljE2xJcIrcI2vFUEln1lRXd6lrazXT9GCNpD+yNqoI7mOVduNw6nzlOIoPOUa6yye1XXcbMR5GdQ3xY0BSbj31/FcTQZirJ+q431q7anbHCTZ72Bw7lbPrKBMcBWNNgbMBBh+bsjBdni0VJ1lARZs6yWiupxCuMDy6KpS2IwOo6DTr3Mre3e5tZZVUM4ZBjqOOJoWO4jkXajcOOMHGgDISvWIrdAkKR80+TzVl908bPPL3LzxOuHdifxVfiTAg92qI/w+/8gGgSyN/mR7XPVlp0lF/3L3mbVKtu5Hjbk/8AHE2Fc03i9+Xv5ngFdKNc13i9+Xv5ngFaNV0x5nn+l/kn9HeEWXu+PlbnqJ9dS2Xu9OVueon11kZ7CGCjLXpCgxRlr0hUIPYUcntH5Tz1s8vb+Bt1/dqPirGSe0flPPWusG/g4Py15q06XqlyMWvVYQ+ruI9xJOqzO9hOto/sP8tbGOFIrmWeM7IuMDMnAXXQJOUjQeOsJk0nY96ip0CYunrjaHx1t+srPJUbXBm2LrFPikwTOb+T+VhbZxGMrDXp83x1QSy2tucJpUjPETp+Cn5/ftaRvKvtp3Kx48HG3erHMzOxZiWZtLMdJNQSbbL71Vk6yynViOkqnEEfOWtPbXi3EQkGg6mXiNckjeSJxJGxR10qw0GtxuxmvbImD4CZMFlA4fRfv0BqesqqzTMZNMEDbIHtHH2QeCiZJSqMQdOGiue53mz3czQwsRbIcNHnkec3c4qAMuriz68gTIToxwOOnlp0MjxMJYW741Gs3RVldtbygE/dMcHX/moDaxTiWNZB53B3arb8/wC+4SOF4sf/AKxU9kcBsfOGHfoUHtG/RbzY5Die5HHhXdvavqiZ9Q8Jdlq4/gbKua7xe/L38zwCuhpf2Uk/Zo50kmwJKIdogDjw1VzzeL35e/meAVp1LTgqY4nn+mRauzqmqwrjzCLL3fHytz1E+upLL+Qj5W56jfXWRnroYKLtekKEFF2vSFQg9hSSe0flPPWosm/hIfoLzVl5PaPynnrRWb/w0X0F5q06XqlyM2sVYx5gmbFre/t71NY2T+0h8VbSO5SWNJUOKSAMp7jDGspmMPaLRlXS6eWve1/FRO7WYdbZm1Y/eW/R7qHxHRXGojlm3ulid6aVbaW+OALvgCLq2Hm9WxHKWqjhj6xsK1e8dm15l4niG1LZkswGsxtrPeOmsvayBJA1VItlWjptLuTdPMo7LtjRDq9naK4+WF9IrUW7BaHOljGqVHB7w2hzVoZt87d8vaNYSLl02CcRsDEbJbj71Uu7UBkvJ7/D7q2QoDxySaAO8MTXdxRVMpRp5XZOWdF/ms7R5XdyKfKWJsO/5PhrG5XlNxmEywW6bTnTxAAcJNbGSMXkM1pjgbiNo1PziPJ+Os7u7m/6ReM00ZOgxSpqYYHT3wRXMKN4ll9zUG4bQfNshu8sZVuEA2hirA4qe/VOwwrVbzbww5mI44UKRRYkbWG0S3JWctbd7u5WFfOOLHiUdJqmaipfLsIsObhWe001lMkMVvJNjhghIALMcBxCs7fxXQmkupx1bXDswGPlaTidVaEyKNXkoo4eBV+Sq7L7Vs9zcBgeyQ4GQ/MB1crmoim2orezqcowTuSeEY48jQ7oZX2PLzdyLhNd6RjrEY6I7+uspvH78vfzPAK6UAAAFGAGgAcArmu8Xvy9/M8ArTfio24RW5nnaG67uou3H/KPuqT2X8hHytz1G+upLL3enK3PUb66ys9RDBRdr0hQgou06QqEGUkntH5Tz1e238vF9BeaqKT2j8p56vbb+Xi+gvNWjTdUuRn1XTHmTh8KrJTJlt8t1CPIY44cGnpJVjTJYkmjaN9Ib4u7V923njTethRauZJV3PaW1rfLIiXEDYg6R4VYc9CXW7thfOZbKdbGZtLW8uPVY/u3GrkNUkM9zlcxUjbhfWOA90cRq4gv4LhdqN+VToNYWmnRm9NNVWNTyHc6VWBv8wt4YeHqm6xyPmroq1Z7WGFLSxTq7WLSuPSdjrkfumq5yHXDUeA92oO2SKpVumNAaoJLMXH3myp0rpJ4uKhc3tbDM5BMri1zAj79j7KTiY8TcdBpcsith0286o+sPCagEX9Pzg4zXUCp6QYse8oouCG3tk6m1BYv05W6T+IdyolxbHDAAa2OgDlNCz3ryN2WxBd5PJMg1t81eId2ukqnLlTBbfcuY+9uJLiRcvtPvHdsHK+cfRHcHDWsyawjyy0WBcDI3lTP6TeIcFV+S5OmXx9bJg1048o8Cj0V8Jq2DVu09nL80up7OxHi+oal3P8AXB/IsZS8T/YOV65zvCcc7vfzPAK3ivWCz445zeH954BXOr6I8yfSfyz+jvCLP3fHytz1G+upLP3fHytz1E+usbPaQ0UXadIUIKLtekKhB7Ckk9o/Keer22/l4/oLzVRSe0flPPV7b/y8X0F5q0abqlyM+q6Y8yQsBTDMor1o8aiaE1pbluMqS3sbLLHIhSRQyngqukhaJ9uBjo+H5aOa3ao2t34qouRlLajTalGP8v0IY8ylXQ+PKPFU/bYXOLPge6CKia0LaxTOxHu1Q7cuBd9yPEJ7TbjXKO8CajbMIF6CNIeNvJHjqIWJ7tSpYkalqVblwIdyG+RGXur0hXYJFxal+Dhq5y3slkv3Y2pD0pTr+QUClpJRUdo9XW4OLrTHtM16cZLLWkeC7y4jvlNEpcRtw1Ux27Ci448NZrTFy3nn3IQWxlgGrDZ3pza7/M8ArZo+ArF5171uvp+CqdV0R5l/psUrs2vB3hdl7vTlbnqJ9dS2Xu+PlbnqJ9dY2eshooq16QoQUXa9IVCD2FLJ7RuU89WNtmUSQqkgYMgw0accKrpPaPynnrZWG4Vi+VWmY5tnMWXG+XrIYnA0rhj0mdcTgdNdwnKDqjmduM1SRR/qlr8/4KX6pa8T/BVzDuLZXudRZblmbxXcPUNPc3KqCIwrbOzgrHEnHjoyD+3eSXkht7DeKG4umDGOJVUklfouThXfmbnZ7Cvy1vt9pmv1W1+d8FL9VteJvgq5yrcOGfLmzHN80iyyETPbptAEFo2ZG8pmUa1OFNn3Ky6W/sbDKM5hv5bx2WTZA+7RF2y52WOPJTzE+z2Dy1vt9pT/AKpacTerS/U7Tib1a04/t7kDXPY03jhN0W6sQ7K7W3q2dnrMccaDy/8At80kuZfqWYxWNtlcvUPPhiGYhWDeUy7IwYU8xPs9g8tb7faUn6pacTerTxm9oOBvVq3v9z927aynuId44LiWKNnjhAXF2UYhRg516qpsryjLr21665zFLSTaK9U2GOA87SwqY37knRU+BzOzags0s1Oyr+BKM6sxwP6tSDPLMen6vy0rvdm3Sxlu7K/S7WDDrFUDUTxgnTU826eXW7KlxmqQuwDBXUKcD+1Xee/wXuKX5XDGWLapSVcOyhEM/seJ/V+WnjeGx4pPV+Wkm6kKZlFay3Jlt7iFpYZY8ASVK6DjtDDA0f8A0Tl340/1f8Ndx8xJVWXB0KbktFFpNzdVXAC/qOwA0CQni2flrO3Vwbm5lnI2TKxbDirX/wBE5d+NcfV/wVR7xZPa5U9utvI8nWhmbbw0YEAYYAVxfhfy5rlKR4Fulu6X7mW1mzT8S4Yis/5CPlbnqJ9dSWfu9OVueon11mZvQ2i7XpChKKtekKhBlNJ7R+U89bDfGTb3a3ZX0Lcj6kdY+T2j8p560288m1kWQr6MJ+ylSAr+2cnV5renjs3H1loX+3j9XvbbtxLN9lqW4UnV5jdnjtXHxihtyZNjeSBu5J9k1BJe7xy7W5CJ/wCzuD/mTVTf2+fq97LJuLrPsNRueS7W6aJ/38x+vLVXuY+xvHaNxbf2GoCezf8A36j/APsSf8w1sLnqczTefJluYoLm5uo5F61sBshItP1cNFYe1f8A3ir/APfE/wCZUe9bB94r5jwuPsrQFhmG4l/Z2M17HdW90tuu3IkTHaCjWdIw0VVZdks9/C06yJFEp2dp+E1bbqybGTZ8vpQD7L1XRv8A7blT96Oda7tpNuuNE37Cq9KSisjyuUoxrStKllHbLlWTXsMs8chuSuwEPDqwoLe5y+YRE/gLzmqRekvKKtd4327yM/ulHxmrHJStySWVRyrjxKI2XC/CTlnlPPKTpTdFbP0L1bgrf5Lp0G3dPhQHwV0S1lzBsns3sESR8Crh9WAJGjSOKuU3E+zdZQ3oJh8IArdZXFDmOTpHa3i2+YrI2KtKy4ricBsBuHHgFXSo440+Wa2qqxjvM9uMoy+WvzWpLCWWWE28HxL6e43ojgkeSCBY1Ri5BGIUDT51cl3vm276BBqSEH4WbxV0tlkyXJcxTMb+OW6uY9mGHrCzDQwwAbTp2uKuTZ9N1uYsfRRR8WPhrm419mSSjRyiqxVK7y23B/ftuTm2oSdJyzNVw3BFn7vTlbnqF9dS2fu9OVueon11lZuQ2iLdsGFD05H2dNQGV0ntG5Tz1dWm9N1b2kVq8EVwsI2UaQaQOKhmitZGLOmk68DhSFvY+gfWNSAg7z3Qvo7yKCKIohiaNR5LKxx8qpxvjcqS0VpbxvwOAcRQPZ7D0G9Y0uz2HoH1jUCpLY7zXlpbm3eKO5QuzjrBqZji3x17PvNcyT288VvDBJbMWUovS2hslW7mFQ9nsPQPrGl2ew9A+saCod/WNxtbYsrfb17WBxx5ddD2281xC88klvDcSXEnWuzrqOGGC9zRUPZ7D0G9Y0uzWHoH1jQVCLreq6ntZbaO3it1mGy7RjTs1X2mYy20ZiCq8ZOODcdEdmsPQb1jS7PYegfWNdJuLqnQiSUlRqpFLmryxtH1Ma7Qw2gNNPOdSt0oI27p007s9h6B9Y0uz2HoH1jXX3Z+I4+1b8IJdX89xLHKQFMXQUahpxoiPN5P+onfU+A0/s9h6DesaXZ7D0D6xpG7OLbUtu0StW5JJx2bBsmbtiSiEk+cxoCWWSaVpZOk2vDVo0VYdnsPQb1jSNvZcCH1jSd2c+p1XAmFqEOmOPEfaH+BQd1ueo211IzrgFUYKNAAqI1WztCpUqVCRUqVKgFSpUqAVKlSoBUqVKgFSpUqAVKlSoBUqVKgFSpUqAVKlSoD/9k="; this._logoTexture.width = 160; @@ -425,7 +428,7 @@ cc.LoaderScene = cc.Scene.extend(/** @lends cc.LoaderScene# */{ // bg this._bgLayer = cc.LayerColor.create(cc.c4(32, 32, 32, 255)); - this._bgLayer.setPosition(cc.p(0, 0)); + this._bgLayer.setPosition(0, 0); this.addChild(this._bgLayer, 0); //loading percent @@ -437,14 +440,11 @@ cc.LoaderScene = cc.Scene.extend(/** @lends cc.LoaderScene# */{ }, _initStage: function (centerPos) { - if (cc.renderContextType === cc.CANVAS) { - this._logo = cc.Sprite.createWithTexture(this._logoTexture); - } else { - this._texture2d = new cc.Texture2D(); - this._texture2d.initWithElement(this._logoTexture); - this._texture2d.handleLoadedTexture(); - this._logo = cc.Sprite.createWithTexture(this._texture2d); - } + this._texture2d = new cc.Texture2D(); + this._texture2d.initWithElement(this._logoTexture); + this._texture2d.handleLoadedTexture(); + this._logo = cc.Sprite.createWithTexture(this._texture2d); + this._logo.setPosition(centerPos); this._bgLayer.addChild(this._logo, 10); diff --git a/cocos2d/CCScheduler.js b/cocos2d/CCScheduler.js index 442db0169c..1936d460cd 100644 --- a/cocos2d/CCScheduler.js +++ b/cocos2d/CCScheduler.js @@ -170,8 +170,8 @@ cc.ArrayContainsObject = function (arr, findObj) { /** * find object from array by target * @param {Array} arr source array - * @param {cc.ListEntry|cc.HashUpdateEntry|cc.HashSelectorEntry} findInt find target - * @return {cc.ListEntry|cc.HashUpdateEntry|cc.HashSelectorEntry} + * @param {cc.ListEntry|cc.HashUpdateEntry} findInt find target + * @return {cc.ListEntry|cc.HashUpdateEntry} */ cc.HASH_FIND_INT = function (arr, findInt) { if (arr == null) { @@ -331,12 +331,13 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ this._elapsed = 0; this._timesExecuted = 0; } else { + var locTarget = this._target, locSelector = this._selector; if (this._runForever && !this._useDelay) { //standard timer usage this._elapsed += dt; if (this._elapsed >= this._interval) { - if (this._target && this._selector) + if (locTarget && locSelector) this._callSelector(); this._elapsed = 0; } @@ -345,7 +346,7 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ this._elapsed += dt; if (this._useDelay) { if (this._elapsed >= this._delay) { - if (this._target && this._selector) + if (locTarget && locSelector) this._callSelector(); this._elapsed = this._elapsed - this._delay; @@ -354,7 +355,7 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ } } else { if (this._elapsed >= this._interval) { - if (this._target && this._selector) + if (locTarget && locSelector) this._callSelector(); this._elapsed = 0; @@ -363,7 +364,7 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ } if (this._timesExecuted > this._repeat) - cc.Director.getInstance().getScheduler().unscheduleCallbackForTarget(this._target, this._selector); + cc.Director.getInstance().getScheduler().unscheduleCallbackForTarget(locTarget, locSelector); } } } @@ -640,7 +641,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ * @param {Boolean} paused * @example * //register a schedule to scheduler - * cc.Director.getInstance().getScheduler().scheduleCallbackForTarget(function, this, interval, repeat, delay, !this._isRunning ); + * cc.Director.getInstance().getScheduler().scheduleCallbackForTarget(this, function, interval, repeat, delay, !this._isRunning ); */ scheduleCallbackForTarget:function (target, callback_fn, interval, repeat, delay, paused) { cc.Assert(callback_fn, "scheduler.scheduleCallbackForTarget() Argument callback_fn must be non-NULL"); @@ -999,4 +1000,3 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ } }); - diff --git a/cocos2d/actions/CCAction.js b/cocos2d/actions/CCAction.js index 0f5a7e7cf4..34fbec375c 100644 --- a/cocos2d/actions/CCAction.js +++ b/cocos2d/actions/CCAction.js @@ -48,8 +48,8 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ _tag:cc.ACTION_TAG_INVALID, //**************Public Functions*********** - ctor:function(){ - this._originalTarget = null; + ctor:function () { + this._originalTarget = null; this._target = null; this._tag = cc.ACTION_TAG_INVALID; }, @@ -73,7 +73,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ * returns a clone of action * @return {cc.Action} */ - clone:function(){ + clone:function () { var action = new cc.Action(); action._originalTarget = null; action._target = null; @@ -211,7 +211,7 @@ cc.FiniteTimeAction = cc.Action.extend(/** @lends cc.FiniteTimeAction# */{ //! duration in seconds _duration:0, - ctor: function () { + ctor:function () { cc.Action.prototype.ctor.call(this); this._duration = 0; }, @@ -244,7 +244,7 @@ cc.FiniteTimeAction = cc.Action.extend(/** @lends cc.FiniteTimeAction# */{ /** * */ - clone:function(){ + clone:function () { return new cc.FiniteTimeAction(); } }); @@ -261,8 +261,8 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{ _speed:0.0, _innerAction:null, - ctor:function(){ - cc.Action.prototype.ctor.call(this); + ctor:function () { + cc.Action.prototype.ctor.call(this); this._speed = 0; this._innerAction = null; }, @@ -297,7 +297,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{ * returns a clone of action * @returns {cc.Speed} */ - clone:function(){ + clone:function () { var action = new cc.Speed(); action.initWithAction(this._innerAction.clone(), this._speed); return action; @@ -411,7 +411,7 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{ bottomBoundary:0.0, _worldRect:null, - ctor: function () { + ctor:function () { cc.Action.prototype.ctor.call(this); this._followedNode = null; this._boundarySet = false; @@ -427,7 +427,7 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{ this._worldRect = cc.RectZero(); }, - clone:function(){ + clone:function () { var action = new cc.Follow(); var locRect = this._worldRect; var rect = new cc.Rect(locRect.x, locRect.y, locRect.width, locRect.height); @@ -462,7 +462,7 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{ this._followedNode = followedNode; this._worldRect = rect; - this._boundarySet = !cc.rectEqualToRect(rect, cc.RectZero()); + this._boundarySet = !cc._rectEqualToZero(rect); this._boundaryFullyCovered = false; @@ -497,17 +497,20 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{ * @param {Number} dt */ step:function (dt) { + var tempPosX = this._followedNode.getPositionX(); + var tempPosY = this._followedNode.getPositionY(); + tempPosX = this._halfScreenSize.x - tempPosX; + tempPosY = this._halfScreenSize.y - tempPosY; + if (this._boundarySet) { // whole map fits inside a single screen, no need to modify the position - unless map boundaries are increased if (this._boundaryFullyCovered) return; - var tempPos = cc.pSub(this._halfScreenSize, this._followedNode.getPosition()); - - this._target.setPosition(cc.p(cc.clampf(tempPos.x, this.leftBoundary, this.rightBoundary), - cc.clampf(tempPos.y, this.bottomBoundary, this.topBoundary))); + this._target.setPosition(cc.clampf(tempPosX, this.leftBoundary, this.rightBoundary), + cc.clampf(tempPosY, this.bottomBoundary, this.topBoundary)); } else { - this._target.setPosition(cc.pSub(this._halfScreenSize, this._followedNode.getPosition())); + this._target.setPosition(tempPosX, tempPosY); } }, diff --git a/cocos2d/actions/CCActionCatmullRom.js b/cocos2d/actions/CCActionCatmullRom.js index bba06639c0..1ee9973741 100644 --- a/cocos2d/actions/CCActionCatmullRom.js +++ b/cocos2d/actions/CCActionCatmullRom.js @@ -45,7 +45,7 @@ * @param {Number} t * @return {cc.Point} */ - cc.CardinalSplineAt = function (p0, p1, p2, p3, tension, t) { +cc.CardinalSplineAt = function (p0, p1, p2, p3, tension, t) { var t2 = t * t; var t3 = t2 * t; @@ -69,7 +69,7 @@ * returns a new copy of the array reversed. * @return {Array} */ -cc.reverseControlPoints = function( controlPoints ) { +cc.reverseControlPoints = function (controlPoints) { var newArray = []; for (var i = controlPoints.length - 1; i >= 0; i--) { newArray.push(cc.p(controlPoints[i].x, controlPoints[i].y)); @@ -77,9 +77,9 @@ cc.reverseControlPoints = function( controlPoints ) { return newArray; }; -cc.copyControlPoints = function( controlPoints){ +cc.copyControlPoints = function (controlPoints) { var newArray = []; - for (var i = 0; i< controlPoints.length; i++) + for (var i = 0; i < controlPoints.length; i++) newArray.push(cc.p(controlPoints[i].x, controlPoints[i].y)); return newArray; }; @@ -90,8 +90,8 @@ cc.copyControlPoints = function( controlPoints){ * @param {Number} pos * @return {Array} */ -cc.getControlPointAt = function( controlPoints, pos ) { - var p = Math.min( controlPoints.length-1, Math.max(pos,0)); +cc.getControlPointAt = function (controlPoints, pos) { + var p = Math.min(controlPoints.length - 1, Math.max(pos, 0)); return controlPoints[p]; }; @@ -160,8 +160,8 @@ cc.CardinalSplineTo = cc.ActionInterval.extend(/** @lends cc.CardinalSplineTo# * * returns a new clone of the action * @returns {cc.CardinalSplineTo} */ - clone:function(){ - var action = new cc.CardinalSplineTo(); + clone:function () { + var action = new cc.CardinalSplineTo(); action.initWithDuration(this._duration, cc.copyControlPoints(this._points), this._tension); return action; }, @@ -172,7 +172,7 @@ cc.CardinalSplineTo = cc.ActionInterval.extend(/** @lends cc.CardinalSplineTo# * startWithTarget:function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); // Issue #1441 from cocos2d-iphone - this._deltaT = 1 / (this._points.length-1); + this._deltaT = 1 / (this._points.length - 1); this._previousPosition = this._target.getPosition(); this._accumulatedDiff = cc.p(0, 0); @@ -183,32 +183,39 @@ cc.CardinalSplineTo = cc.ActionInterval.extend(/** @lends cc.CardinalSplineTo# * */ update:function (time) { var p, lt; - + var ps = this._points; // eg. // p..p..p..p..p..p..p // 1..2..3..4..5..6..7 // want p to be 1, 2, 3, 4, 5, 6 if (time == 1) { - p = this._points.length - 1; + p = ps.length - 1; lt = 1; } else { - p = 0 | (time / this._deltaT); - lt = (time - this._deltaT * p) / this._deltaT; + var locDT = this._deltaT; + p = 0 | (time / locDT); + lt = (time - locDT * p) / locDT; } var newPos = cc.CardinalSplineAt( - cc.getControlPointAt( this._points, p - 1), - cc.getControlPointAt( this._points, p - 0), - cc.getControlPointAt( this._points, p + 1), - cc.getControlPointAt( this._points, p + 2), + cc.getControlPointAt(ps, p - 1), + cc.getControlPointAt(ps, p - 0), + cc.getControlPointAt(ps, p + 1), + cc.getControlPointAt(ps, p + 2), this._tension, lt); - if(cc.ENABLE_STACKABLE_ACTIONS){ - var node = this._target; - var diff = cc.pSub(node.getPosition(), this._previousPosition); - if (diff.x != 0 || diff.y != 0) { - this._accumulatedDiff = cc.pAdd(this._accumulatedDiff, diff); - newPos = cc.pAdd(newPos, this._accumulatedDiff); + if (cc.ENABLE_STACKABLE_ACTIONS) { + var tempX, tempY; + tempX = this._target.getPositionX() - this._previousPosition.x; + tempY = this._target.getPositionY() - this._previousPosition.y; + if (tempX != 0 || tempY != 0) { + var locAccDiff = this._accumulatedDiff; + tempX = locAccDiff.x + tempX; + tempY = locAccDiff.y + tempY; + locAccDiff.x = tempX; + locAccDiff.y = tempY; + newPos.x += tempX; + newPos.y += tempY; } } this.updatePosition(newPos); @@ -315,20 +322,24 @@ cc.CardinalSplineBy = cc.CardinalSplineTo.extend(/** @lends cc.CardinalSplineBy# } // convert to "diffs" to "reverse absolute" - var reverseArray = cc.reverseControlPoints( copyConfig ); + var reverseArray = cc.reverseControlPoints(copyConfig); // 1st element (which should be 0,0) should be here too p = reverseArray[ reverseArray.length - 1 ]; reverseArray.pop(); - p = cc.pNeg(p); + p.x = -p.x; + p.y = -p.y; + reverseArray.unshift(p); - for (i = 1; i < reverseArray.length; ++i) { + for (var i = 1; i < reverseArray.length; ++i) { current = reverseArray[i]; - current = cc.pNeg(current); - var abs = cc.pAdd(current, p); - reverseArray[i] = abs; - p = abs; + current.x = -current.x; + current.y = -current.y; + current.x += p.x; + current.y += p.y; + reverseArray[i] = current; + p = current; } return cc.CardinalSplineBy.create(this._duration, reverseArray, this._tension); }, @@ -338,16 +349,19 @@ cc.CardinalSplineBy = cc.CardinalSplineTo.extend(/** @lends cc.CardinalSplineBy# * @param {cc.Point} newPos */ updatePosition:function (newPos) { - var p = cc.pAdd(newPos, this._startPosition); - this._target.setPosition(p); - this._previousPosition = p; + var pos = this._startPosition; + var posX = newPos.x + pos.x; + var posY = newPos.y + pos.y; + this._target.setPosition(posX, posY); + this._previousPosition.x = posX; + this._previousPosition.y = posY; }, /** * returns a new clone of the action * @returns {cc.CardinalSplineBy} */ - clone:function(){ + clone:function () { var a = new cc.CardinalSplineBy(); a.initWithDuration(this._duration, cc.copyControlPoints(this._points), this._tension); return a; @@ -393,7 +407,7 @@ cc.CatmullRomTo = cc.CardinalSplineTo.extend(/** @lends cc.CatmullRomTo# */{ * returns a new clone of the action * @returns {cc.CatmullRomTo} */ - clone:function(){ + clone:function () { var action = new cc.CatmullRomTo(); action.initWithDuration(this._duration, cc.copyControlPoints(this._points)); return action; @@ -438,7 +452,7 @@ cc.CatmullRomBy = cc.CardinalSplineBy.extend({ * returns a new clone of the action * @returns {cc.CatmullRomBy} */ - clone:function(){ + clone:function () { var action = new cc.CatmullRomBy(); action.initWithDuration(this._duration, cc.copyControlPoints(this._points)); return action; diff --git a/cocos2d/actions/CCActionEase.js b/cocos2d/actions/CCActionEase.js index 79e5a39b11..6c3dda7314 100644 --- a/cocos2d/actions/CCActionEase.js +++ b/cocos2d/actions/CCActionEase.js @@ -746,19 +746,20 @@ cc.EaseElasticInOut = cc.EaseElastic.extend(/** @lends cc.EaseElasticInOut# */{ */ update:function (time1) { var newT = 0; + var locPeriod = this._period if (time1 === 0 || time1 == 1) { newT = time1; } else { time1 = time1 * 2; - if (!this._period) - this._period = 0.3 * 1.5; + if (!locPeriod) + locPeriod = this._period = 0.3 * 1.5; - var s = this._period / 4; + var s = locPeriod / 4; time1 = time1 - 1; if (time1 < 0) - newT = -0.5 * Math.pow(2, 10 * time1) * Math.sin((time1 - s) * Math.PI * 2 / this._period); + newT = -0.5 * Math.pow(2, 10 * time1) * Math.sin((time1 - s) * Math.PI * 2 / locPeriod); else - newT = Math.pow(2, -10 * time1) * Math.sin((time1 - s) * Math.PI * 2 / this._period) * 0.5 + 1; + newT = Math.pow(2, -10 * time1) * Math.sin((time1 - s) * Math.PI * 2 / locPeriod) * 0.5 + 1; } this._inner.update(newT); }, diff --git a/cocos2d/actions/CCActionGrid.js b/cocos2d/actions/CCActionGrid.js index b00edbd113..1db91db1e3 100644 --- a/cocos2d/actions/CCActionGrid.js +++ b/cocos2d/actions/CCActionGrid.js @@ -75,7 +75,8 @@ cc.GridAction = cc.ActionInterval.extend(/** @lends cc.GridAction# */{ */ initWithDuration:function (duration, gridSize) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { - this._gridSize = gridSize; + this._gridSize.width = gridSize.width; + this._gridSize.height = gridSize.height; return true; } return false; diff --git a/cocos2d/actions/CCActionGrid3D.js b/cocos2d/actions/CCActionGrid3D.js index 36eb310623..da4fe9d03a 100644 --- a/cocos2d/actions/CCActionGrid3D.js +++ b/cocos2d/actions/CCActionGrid3D.js @@ -25,8 +25,8 @@ ****************************************************************************/ cc.RAND_MAX = 0xffffff; -cc.rand = function(){ - return Math.random() * cc.RAND_MAX; +cc.rand = function () { + return Math.random() * cc.RAND_MAX; }; /** * cc.Waves3D action @@ -38,7 +38,7 @@ cc.Waves3D = cc.Grid3DAction.extend(/** @lends cc.Waves3D# */{ _amplitude:null, _amplitudeRate:null, - ctor:function(){ + ctor:function () { cc.GridAction.prototype.ctor.call(this); this._waves = 0; @@ -98,7 +98,7 @@ cc.Waves3D = cc.Grid3DAction.extend(/** @lends cc.Waves3D# */{ update:function (time) { var locGridSize = this._gridSize; - var locAmplitude = this._amplitude, locPos = cc.p(0,0); + var locAmplitude = this._amplitude, locPos = cc.p(0, 0); var locAmplitudeRate = this._amplitudeRate, locWaves = this._waves; for (var i = 0; i < locGridSize.width + 1; ++i) { for (var j = 0; j < locGridSize.height + 1; ++j) { @@ -164,9 +164,11 @@ cc.FlipX3D = cc.Grid3DAction.extend(/** @lends cc.Waves3D# */{ var mx = Math.cos(angle); var diff = new cc.Vertex3F(); - - var v0 = this.originalVertex(cc.p(1, 1)); - var v1 = this.originalVertex(cc.p(0, 0)); + var tempVer = cc.p(0, 0); + tempVer.x = tempVer.y = 1; + var v0 = this.originalVertex(tempVer); + tempVer.x = tempVer.y = 0; + var v1 = this.originalVertex(tempVer); var x0 = v0.x; var x1 = v1.x; @@ -243,8 +245,11 @@ cc.FlipY3D = cc.FlipX3D.extend(/** @lends cc.FlipY3D# */{ var diff = new cc.Vertex3F(); - var v0 = this.originalVertex(cc.p(1, 1)); - var v1 = this.originalVertex(cc.p(0, 0)); + var tempP = cc.p(0, 0); + tempP.x = tempP.y = 1; + var v0 = this.originalVertex(tempP); + tempP.x = tempP.y = 0; + var v1 = this.originalVertex(tempP); var y0 = v0.y; var y1 = v1.y; @@ -322,10 +327,10 @@ cc.Lens3D = cc.Grid3DAction.extend(/** @lends cc.Lens3D# */{ _concave:false, _dirty:false, - ctor:function(){ + ctor:function () { cc.GridAction.prototype.ctor.call(this); - this._position = null; + this._position = cc.p(0, 0); this._radius = 0; this._lensEffect = 0; this._concave = false; @@ -352,7 +357,7 @@ cc.Lens3D = cc.Grid3DAction.extend(/** @lends cc.Lens3D# */{ * Set whether lens is concave * @param {Boolean} concave */ - setConcave:function(concave){ + setConcave:function (concave) { this._concave = concave; }, @@ -370,7 +375,8 @@ cc.Lens3D = cc.Grid3DAction.extend(/** @lends cc.Lens3D# */{ */ setPosition:function (position) { if (!cc.pointEqualToPoint(position, this._position)) { - this._position = position; + this._position.x = position.x; + this._position.y = position.y; this._dirty = true; } }, @@ -385,7 +391,8 @@ cc.Lens3D = cc.Grid3DAction.extend(/** @lends cc.Lens3D# */{ */ initWithDuration:function (duration, gridSize, position, radius) { if (cc.Grid3DAction.prototype.initWithDuration.call(this, duration, gridSize)) { - this._position = cc.p(-1, -1); + this._position.x = -1; + this._position.y = -1; this.setPosition(position); this._radius = radius; this._lensEffect = 0.7; @@ -399,27 +406,35 @@ cc.Lens3D = cc.Grid3DAction.extend(/** @lends cc.Lens3D# */{ if (this._dirty) { var locGridSizeWidth = this._gridSize.width, locGridSizeHeight = this._gridSize.height; var locRadius = this._radius, locLensEffect = this._lensEffect; - var locPos = cc.p(0,0); + var locPos = cc.p(0, 0); + var vect = cc.p(0, 0); + var v, r, l, new_r, pre_log; for (var i = 0; i < locGridSizeWidth + 1; ++i) { for (var j = 0; j < locGridSizeHeight + 1; ++j) { locPos.x = i; locPos.y = j; - var v = this.originalVertex(locPos); - var vect = cc.pSub(this._position, v); - var r = cc.pLength(vect); + v = this.originalVertex(locPos); + vect.x = this._position.x - v.x; + vect.y = this._position.y - v.y; + r = cc.pLength(vect); if (r < locRadius) { r = locRadius - r; - var pre_log = r / locRadius; + pre_log = r / locRadius; if (pre_log == 0) pre_log = 0.001; - var l = Math.log(pre_log) * locLensEffect; - var new_r = Math.exp(l) * locRadius; + l = Math.log(pre_log) * locLensEffect; + new_r = Math.exp(l) * locRadius; + + r = cc.pLength(vect); + if (r > 0) { + vect.x = vect.x / r; + vect.y = vect.y / r; - if (cc.pLength(vect) > 0) { - vect = cc.pNormalize(vect); - v.z += cc.pLength(cc.pMult(vect, new_r)) * locLensEffect; + vect.x = vect.x * new_r; + vect.y = vect.y * new_r; + v.z += cc.pLength(vect) * locLensEffect; } } this.setVertex(locPos, v); @@ -457,10 +472,10 @@ cc.Ripple3D = cc.Grid3DAction.extend(/** @lends cc.Ripple3D# */{ _amplitude:null, _amplitudeRate:null, - ctor:function(){ + ctor:function () { cc.GridAction.prototype.ctor.call(this); - this._position = null; + this._position = cc.p(0,0); this._radius = 0; this._waves = 0; this._amplitude = 0; @@ -480,7 +495,8 @@ cc.Ripple3D = cc.Grid3DAction.extend(/** @lends cc.Ripple3D# */{ * @param {cc.Point} position */ setPosition:function (position) { - this._position = position; + this._position.x = position.x; + this._position.y = position.y; }, /** @@ -539,14 +555,18 @@ cc.Ripple3D = cc.Grid3DAction.extend(/** @lends cc.Ripple3D# */{ update:function (time) { var locGridSizeWidth = this._gridSize.width, locGridSizeHeight = this._gridSize.height; - var locPos = cc.p(0,0), locRadius = this._radius; + var locPos = cc.p(0, 0), locRadius = this._radius; var locWaves = this._waves, locAmplitude = this._amplitude, locAmplitudeRate = this._amplitudeRate; + var v, r, tempPos = cc.p(0, 0); for (var i = 0; i < (locGridSizeWidth + 1); ++i) { for (var j = 0; j < (locGridSizeHeight + 1); ++j) { locPos.x = i; locPos.y = j; - var v = this.originalVertex(locPos); - var r = cc.pLength(cc.pSub(this._position, v)); + v = this.originalVertex(locPos); + + tempPos.x = this._position.x - v.x; + tempPos.y = this._position.y - v.y; + r = cc.pLength(tempPos); if (r < locRadius) { r = locRadius - r; @@ -584,7 +604,7 @@ cc.Shaky3D = cc.Grid3DAction.extend(/** @lends cc.Shaky3D# */{ _randRange:null, _shakeZ:null, - ctor:function(){ + ctor:function () { cc.GridAction.prototype.ctor.call(this); this._randRange = 0; @@ -610,12 +630,13 @@ cc.Shaky3D = cc.Grid3DAction.extend(/** @lends cc.Shaky3D# */{ update:function (time) { var locGridSizeWidth = this._gridSize.width, locGridSizeHeight = this._gridSize.height; - var locRandRange = this._randRange, locShakeZ = this._shakeZ, locP = cc.p(0,0); + var locRandRange = this._randRange, locShakeZ = this._shakeZ, locP = cc.p(0, 0); + var v; for (var i = 0; i < (locGridSizeWidth + 1); ++i) { for (var j = 0; j < (locGridSizeHeight + 1); ++j) { locP.x = i; locP.y = j; - var v = this.originalVertex(locP); + v = this.originalVertex(locP); v.x += (cc.rand() % (locRandRange * 2)) - locRandRange; v.y += (cc.rand() % (locRandRange * 2)) - locRandRange; if (locShakeZ) @@ -650,7 +671,7 @@ cc.Liquid = cc.Grid3DAction.extend(/** @lends cc.Liquid# */{ _amplitude:null, _amplitudeRate:null, - ctor:function(){ + ctor:function () { cc.GridAction.prototype.ctor.call(this); this._waves = 0; @@ -709,13 +730,14 @@ cc.Liquid = cc.Grid3DAction.extend(/** @lends cc.Liquid# */{ }, update:function (time) { - var locSizeWidth = this._gridSize.width, locSizeHeight = this._gridSize.height, locPos = cc.p(0,0); + var locSizeWidth = this._gridSize.width, locSizeHeight = this._gridSize.height, locPos = cc.p(0, 0); var locWaves = this._waves, locAmplitude = this._amplitude, locAmplitudeRate = this._amplitudeRate; + var v; for (var i = 1; i < locSizeWidth; ++i) { for (var j = 1; j < locSizeHeight; ++j) { locPos.x = i; locPos.y = j; - var v = this.originalVertex(locPos); + v = this.originalVertex(locPos); v.x = (v.x + (Math.sin(time * Math.PI * locWaves * 2 + v.x * .01) * locAmplitude * locAmplitudeRate)); v.y = (v.y + (Math.sin(time * Math.PI * locWaves * 2 + v.y * .01) * locAmplitude * locAmplitudeRate)); this.setVertex(locPos, v); @@ -750,7 +772,7 @@ cc.Waves = cc.Grid3DAction.extend(/** @lends cc.Waves# */{ _vertical:null, _horizontal:null, - ctor:function(){ + ctor:function () { cc.GridAction.prototype.ctor.call(this); this._waves = 0; @@ -815,14 +837,15 @@ cc.Waves = cc.Grid3DAction.extend(/** @lends cc.Waves# */{ }, update:function (time) { - var locSizeWidth = this._gridSize.width, locSizeHeight = this._gridSize.height, locPos = cc.p(0,0); + var locSizeWidth = this._gridSize.width, locSizeHeight = this._gridSize.height, locPos = cc.p(0, 0); var locVertical = this._vertical, locHorizontal = this._horizontal; var locWaves = this._waves, locAmplitude = this._amplitude, locAmplitudeRate = this._amplitudeRate; + var v; for (var i = 0; i < locSizeWidth + 1; ++i) { for (var j = 0; j < locSizeHeight + 1; ++j) { locPos.x = i; locPos.y = j; - var v = this.originalVertex(locPos); + v = this.originalVertex(locPos); if (locVertical) v.x = (v.x + (Math.sin(time * Math.PI * locWaves * 2 + v.y * .01) * locAmplitude * locAmplitudeRate)); if (locHorizontal) @@ -862,10 +885,10 @@ cc.Twirl = cc.Grid3DAction.extend({ _amplitude:null, _amplitudeRate:null, - ctor:function(){ + ctor:function () { cc.GridAction.prototype.ctor.call(this); - this._position = null; + this._position = cc.p(0,0); this._twirls = 0; this._amplitude = 0; this._amplitudeRate = 0; @@ -881,10 +904,11 @@ cc.Twirl = cc.Grid3DAction.extend({ /** * set twirl center - * @param {Number} position + * @param {cc.Point} position */ setPosition:function (position) { - this._position = position; + this._position.x = position.x; + this._position.y = position.y; }, /** @@ -933,22 +957,26 @@ cc.Twirl = cc.Grid3DAction.extend({ update:function (time) { var c = this._position; - var locSizeWidth = this._gridSize.width, locSizeHeight = this._gridSize.height, locPos = cc.p(0,0); + var locSizeWidth = this._gridSize.width, locSizeHeight = this._gridSize.height, locPos = cc.p(0, 0); var amp = 0.1 * this._amplitude * this._amplitudeRate; var locTwirls = this._twirls; + var v, a, dX, dY, avg = cc.p(0, 0); for (var i = 0; i < (locSizeWidth + 1); ++i) { for (var j = 0; j < (locSizeHeight + 1); ++j) { locPos.x = i; locPos.y = j; - var v = this.originalVertex(locPos); + v = this.originalVertex(locPos); + + avg.x = i - (locSizeWidth / 2.0); + avg.y = j - (locSizeHeight / 2.0); - var avg = cc.p(i - (locSizeWidth / 2.0), j - (locSizeHeight / 2.0)); + a = cc.pLength(avg) * Math.cos(Math.PI / 2.0 + time * Math.PI * locTwirls * 2) * amp; - var a = cc.pLength(avg) * Math.cos(Math.PI / 2.0 + time * Math.PI * locTwirls * 2) * amp; - var d = cc.p(Math.sin(a) * (v.y - c.y) + Math.cos(a) * (v.x - c.x), Math.cos(a) * (v.y - c.y) - Math.sin(a) * (v.x - c.x)); + dX = Math.sin(a) * (v.y - c.y) + Math.cos(a) * (v.x - c.x); + dY = Math.cos(a) * (v.y - c.y) - Math.sin(a) * (v.x - c.x); - v.x = c.x + d.x; - v.y = c.y + d.y; + v.x = c.x + dX; + v.y = c.y + dY; this.setVertex(locPos, v); } diff --git a/cocos2d/actions/CCActionInstant.js b/cocos2d/actions/CCActionInstant.js index 36197bb80b..3ee2c9e312 100644 --- a/cocos2d/actions/CCActionInstant.js +++ b/cocos2d/actions/CCActionInstant.js @@ -203,17 +203,17 @@ cc.RemoveSelf.create = function(isNeedCleanUp){ * @extends cc.ActionInstant */ cc.FlipX = cc.ActionInstant.extend(/** @lends cc.FlipX# */{ - _flipX:false, + _flippedX:false, ctor:function(){ cc.FiniteTimeAction.prototype.ctor.call(this); - this._flipX = false; + this._flippedX = false; }, /** * @param {Boolean} x * @return {Boolean} */ initWithFlipX:function (x) { - this._flipX = x; + this._flippedX = x; return true; }, @@ -221,19 +221,19 @@ cc.FlipX = cc.ActionInstant.extend(/** @lends cc.FlipX# */{ * @param {Number} time */ update:function (time) { - this._target.setFlipX(this._flipX); + this._target.setFlippedX(this._flippedX); }, /** * @return {cc.FiniteTimeAction} */ reverse:function () { - return cc.FlipX.create(!this._flipX); + return cc.FlipX.create(!this._flippedX); }, clone:function(){ var action = new cc.FlipX(); - action.initWithFlipX(this._flipX); + action.initWithFlipX(this._flippedX); return action; } }); @@ -256,17 +256,17 @@ cc.FlipX.create = function (x) { * @extends cc.ActionInstant */ cc.FlipY = cc.ActionInstant.extend(/** @lends cc.FlipY# */{ - _flipY:false, + _flippedY:false, ctor:function(){ cc.FiniteTimeAction.prototype.ctor.call(this); - this._flipY = false; + this._flippedY = false; }, /** * @param {Boolean} Y * @return {Boolean} */ initWithFlipY:function (Y) { - this._flipY = Y; + this._flippedY = Y; return true; }, @@ -275,19 +275,19 @@ cc.FlipY = cc.ActionInstant.extend(/** @lends cc.FlipY# */{ */ update:function (time) { //this._super(); - this._target.setFlipY(this._flipY); + this._target.setFlippedY(this._flippedY); }, /** * @return {cc.FiniteTimeAction} */ reverse:function () { - return cc.FlipY.create(!this._flipY); + return cc.FlipY.create(!this._flippedY); }, clone:function(){ var action = new cc.FlipY(); - action.initWithFlipY(this._flipY); + action.initWithFlipY(this._flippedY); return action; } }); diff --git a/cocos2d/actions/CCActionInterval.js b/cocos2d/actions/CCActionInterval.js index 8029c44972..6ee4107efa 100644 --- a/cocos2d/actions/CCActionInterval.js +++ b/cocos2d/actions/CCActionInterval.js @@ -47,7 +47,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ _elapsed:0, _firstTick:false, - ctor:function(){ + ctor:function () { cc.FiniteTimeAction.prototype.ctor.call(this); this._elapsed = 0; this._firstTick = false; @@ -85,7 +85,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ * returns a new clone of the action * @returns {cc.ActionInterval} */ - clone:function(){ + clone:function () { var action = new cc.ActionInterval(); action.initWithDuration(this._duration); return action; @@ -181,9 +181,9 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{ * @param {cc.FiniteTimeAction} actionTwo * @return {Boolean} */ - initOneTwo:function (actionOne, actionTwo) { - cc.Assert(actionOne != null, "Sequence.initOneTwo"); - cc.Assert(actionTwo != null, "Sequence.initOneTwo"); + initWithTwoActions:function (actionOne, actionTwo) { + cc.Assert(actionOne != null, "Sequence.initWithTwoActions"); + cc.Assert(actionTwo != null, "Sequence.initWithTwoActions"); var d = actionOne.getDuration() + actionTwo.getDuration(); this.initWithDuration(d); @@ -197,9 +197,9 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{ * returns a new clone of the action * @returns {cc.Sequence} */ - clone:function(){ + clone:function () { var action = new cc.Sequence(); - action.initOneTwo(this._actions[0].clone(), this._actions[1].clone()); + action.initWithTwoActions(this._actions[0].clone(), this._actions[1].clone()); return action; }, @@ -232,13 +232,13 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{ // action[0] new_t = (locSplit) ? time / locSplit : 1; - if(found === 0 && locLast === 1){ + if (found === 0 && locLast === 1) { // Reverse mode ? // XXX: Bug. this case doesn't contemplate when _last==-1, found=0 and in "reverse mode" // since it will require a hack to know if an action is on reverse mode or not. // "step" should be overriden, and the "reverseMode" value propagated to inner Sequences. - this._actions[1].update(0); - this._actions[1].stop(); + locActions[1].update(0); + locActions[1].stop(); } } else { // action[1] @@ -259,7 +259,7 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{ } // Last action found and it is done. - if(locLast === found && locActions[found].isDone()) + if (locLast === found && locActions[found].isDone()) return; // Last action found and it is done @@ -298,7 +298,7 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{ */ cc.Sequence.create = function (/*Multiple Arguments*/tempArray) { var paraArray = (tempArray instanceof Array) ? tempArray : arguments; - if((paraArray.length > 0) && (paraArray[paraArray.length-1] == null)) + if ((paraArray.length > 0) && (paraArray[paraArray.length - 1] == null)) cc.log("parameters should not be ending with null in Javascript"); var prev = paraArray[0]; @@ -317,7 +317,7 @@ cc.Sequence.create = function (/*Multiple Arguments*/tempArray) { */ cc.Sequence._actionOneTwo = function (actionOne, actionTwo) { var sequence = new cc.Sequence(); - sequence.initOneTwo(actionOne, actionTwo); + sequence.initWithTwoActions(actionOne, actionTwo); return sequence; }; @@ -334,7 +334,7 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{ _actionInstant:false, _innerAction:null, //CCFiniteTimeAction - ctor: function () { + ctor:function () { cc.ActionInterval.prototype.ctor.call(this); this._times = 0; this._total = 0; @@ -366,7 +366,7 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{ * returns a new clone of the action * @returns {cc.Repeat} */ - clone:function(){ + clone:function () { var action = new cc.Repeat(); action.initWithAction(this._innerAction.clone(), this._times); return action; @@ -397,14 +397,16 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{ var locInnerAction = this._innerAction; var locDuration = this._duration; var locTimes = this._times; + var locNextDt = this._nextDt; - if (time >= this._nextDt) { - while (time > this._nextDt && this._total < locTimes) { + if (time >= locNextDt) { + while (time > locNextDt && this._total < locTimes) { locInnerAction.update(1); this._total++; locInnerAction.stop(); locInnerAction.startWithTarget(this._target); - this._nextDt += locInnerAction.getDuration() / locDuration; + locNextDt += locInnerAction.getDuration() / locDuration; + this._nextDt = locNextDt; } // fix for issue #1288, incorrect end value of repeat @@ -418,7 +420,7 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{ locInnerAction.stop(); } else { // issue #390 prevent jerk, use right update - locInnerAction.update(time - (this._nextDt - locInnerAction.getDuration() / locDuration)); + locInnerAction.update(time - (locNextDt - locInnerAction.getDuration() / locDuration)); } } } else { @@ -481,7 +483,7 @@ cc.Repeat.create = function (action, times) { cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{ _innerAction:null, //CCActionInterval - ctor:function(){ + ctor:function () { cc.ActionInterval.prototype.ctor.call(this); this._innerAction = null; }, @@ -501,7 +503,7 @@ cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{ * returns a new clone of the action * @returns {cc.RepeatForever} */ - clone:function(){ + clone:function () { var action = new cc.RepeatForever(); action.initWithAction(this._innerAction.clone()); return action; @@ -586,7 +588,7 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{ _one:null, _two:null, - ctor: function(){ + ctor:function () { cc.ActionInterval.prototype.ctor.call(this); this._one = null; this._two = null; @@ -597,7 +599,7 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{ * @param {cc.FiniteTimeAction} action2 * @return {Boolean} */ - initOneTwo:function (action1, action2) { + initWithTwoActions:function (action1, action2) { cc.Assert(action1 != null, "no action1"); cc.Assert(action2 != null, "no action2"); @@ -625,9 +627,9 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{ * returns a new clone of the action * @returns {cc.Spawn} */ - clone:function(){ + clone:function () { var action = new cc.Spawn(); - action.initOneTwo(this._one.clone(), this._two.clone()); + action.initWithTwoActions(this._one.clone(), this._two.clone()); return action; }, @@ -676,7 +678,7 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{ */ cc.Spawn.create = function (/*Multiple Arguments*/tempArray) { var paramArray = (tempArray instanceof Array) ? tempArray : arguments; - if((paramArray.length > 0) && (paramArray[paramArray.length-1] == null)) + if ((paramArray.length > 0) && (paramArray[paramArray.length - 1] == null)) cc.log("parameters should not be ending with null in Javascript"); var prev = paramArray[0]; @@ -695,7 +697,7 @@ cc.Spawn.create = function (/*Multiple Arguments*/tempArray) { */ cc.Spawn._actionOneTwo = function (action1, action2) { var pSpawn = new cc.Spawn(); - pSpawn.initOneTwo(action1, action2); + pSpawn.initWithTwoActions(action1, action2); return pSpawn; }; @@ -715,7 +717,7 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{ _startAngleY:0, _diffAngleY:0, - ctor: function () { + ctor:function () { cc.ActionInterval.prototype.ctor.call(this); this._dstAngleX = 0; this._startAngleX = 0; @@ -745,7 +747,7 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{ * returns a new clone of the action * @returns {cc.RotateTo} */ - clone:function(){ + clone:function () { var action = new cc.RotateTo(); action.initWithDuration(this._duration, this._dstAngleX, this._dstAngleY); return action; @@ -760,9 +762,9 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{ // Calculate X var locStartAngleX = target.getRotationX() % 360.0; var locDiffAngleX = this._dstAngleX - locStartAngleX; - if(locDiffAngleX > 180) + if (locDiffAngleX > 180) locDiffAngleX -= 360; - if(locDiffAngleX < -180) + if (locDiffAngleX < -180) locDiffAngleX += 360; this._startAngleX = locStartAngleX; this._diffAngleX = locDiffAngleX; @@ -770,11 +772,11 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{ // Calculate Y It's duplicated from calculating X since the rotation wrap should be the same this._startAngleY = target.getRotationY() % 360.0; var locDiffAngleY = this._dstAngleY - this._startAngleY; - if(locDiffAngleY > 180) + if (locDiffAngleY > 180) locDiffAngleY -= 360; - if(locDiffAngleY < -180) + if (locDiffAngleY < -180) locDiffAngleY += 360; - this._diffAngleY = locDiffAngleY + this._diffAngleY = locDiffAngleY }, /** @@ -788,7 +790,7 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{ * @param {Number} time time in seconds */ update:function (time) { - if (this._target){ + if (this._target) { this._target.setRotationX(this._startAngleX + this._diffAngleX * time); this._target.setRotationY(this._startAngleY + this._diffAngleY * time); } @@ -807,7 +809,7 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{ */ cc.RotateTo.create = function (duration, deltaAngleX, deltaAngleY) { var rotateTo = new cc.RotateTo(); - rotateTo.initWithDuration(duration, deltaAngleX,deltaAngleY); + rotateTo.initWithDuration(duration, deltaAngleX, deltaAngleY); return rotateTo; }; @@ -822,7 +824,7 @@ cc.RotateBy = cc.ActionInterval.extend(/** @lends cc.RotateBy# */{ _angleY:0, _startAngleY:0, - ctor: function () { + ctor:function () { cc.ActionInterval.prototype.ctor.call(this); this._angleX = 0; this._startAngleX = 0; @@ -849,7 +851,7 @@ cc.RotateBy = cc.ActionInterval.extend(/** @lends cc.RotateBy# */{ * returns a new clone of the action * @returns {cc.RotateBy} */ - clone:function(){ + clone:function () { var action = new cc.RotateBy(); action.initWithDuration(this._duration, this._angleX, this._angleY); return action; @@ -913,7 +915,7 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{ _startPosition:null, _previousPosition:null, - ctor: function () { + ctor:function () { cc.ActionInterval.prototype.ctor.call(this); this._positionDelta = cc.p(0, 0); @@ -928,7 +930,8 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{ */ initWithDuration:function (duration, position) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { - this._positionDelta = position; + this._positionDelta.x = position.x; + this._positionDelta.y = position.y; return true; } return false; @@ -938,7 +941,7 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{ * returns a new clone of the action * @returns {cc.MoveBy} */ - clone: function () { + clone:function () { var action = new cc.MoveBy(); action.initWithDuration(this._duration, this._positionDelta) return action; @@ -949,9 +952,12 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{ */ startWithTarget:function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); - var locPos = target.getPosition(); - this._previousPosition = cc.p(locPos.x, locPos.y); - this._startPosition = cc.p(locPos.x, locPos.y); + var locPosX = target.getPositionX(); + var locPosY = target.getPositionY(); + this._previousPosition.x = locPosX; + this._previousPosition.y = locPosY; + this._startPosition.x = locPosX; + this._startPosition.y = locPosY; }, /** @@ -959,16 +965,24 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{ */ update:function (time) { if (this._target) { - if(cc.ENABLE_STACKABLE_ACTIONS){ - var currentPos = this._target.getPosition(); - var diff = cc.pSub(currentPos, this._previousPosition); - this._startPosition = cc.pAdd(this._startPosition, diff); - var newPos = cc.p(this._startPosition.x + this._positionDelta.x * time, - this._startPosition.y + this._positionDelta.y * time); - this._target.setPosition(newPos); - this._previousPosition = newPos; - } else{ - this._target.setPosition(cc.pAdd(this._startPosition, cc.pMult(this._positionDelta, t))); + var x = this._positionDelta.x * time; + var y = this._positionDelta.y * time; + var locStartPosition = this._startPosition; + if (cc.ENABLE_STACKABLE_ACTIONS) { + var targetX = this._target.getPositionX(); + var targetY = this._target.getPositionY(); + var locPreviousPosition = this._previousPosition; + + locStartPosition.x = locStartPosition.x + targetX - locPreviousPosition.x; + locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y; + x = x + locStartPosition.x; + y = y + locStartPosition.y; + + this._target.setPosition(x, y); + locPreviousPosition.x = x; + locPreviousPosition.y = y; + } else { + this._target.setPosition(locStartPosition.x + x, locStartPosition.y + y); } } }, @@ -977,7 +991,7 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{ * MoveTo reverse is not implemented */ reverse:function () { - return cc.MoveBy.create(this._duration, cc.p( -this._positionDelta.x, -this._positionDelta.y)); + return cc.MoveBy.create(this._duration, cc.p(-this._positionDelta.x, -this._positionDelta.y)); } }); @@ -1005,7 +1019,7 @@ cc.MoveBy.create = function (duration, deltaPosition) { */ cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{ _endPosition:null, - ctor: function () { + ctor:function () { cc.MoveBy.prototype.ctor.call(this); this._endPosition = cc.p(0, 0); }, @@ -1017,7 +1031,8 @@ cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{ */ initWithDuration:function (duration, position) { if (cc.MoveBy.prototype.initWithDuration.call(this, duration, position)) { - this._endPosition = position; + this._endPosition.x = position.x; + this._endPosition.y = position.y; return true; } return false; @@ -1027,7 +1042,7 @@ cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{ * returns a new clone of the action * @returns {cc.MoveTo} */ - clone: function () { + clone:function () { var action = new cc.MoveTo(); action.initWithDuration(this._duration, this._endPosition); return action; @@ -1038,7 +1053,8 @@ cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{ */ startWithTarget:function (target) { cc.MoveBy.prototype.startWithTarget.call(this, target); - this._positionDelta = cc.pSub(this._endPosition, target.getPosition()); + this._positionDelta.x = this._endPosition.x - target.getPositionX(); + this._positionDelta.y = this._endPosition.y - target.getPositionY(); } }); /** @@ -1070,7 +1086,7 @@ cc.SkewTo = cc.ActionInterval.extend(/** @lends cc.SkewTo# */{ _deltaX:0, _deltaY:0, - ctor: function () { + ctor:function () { cc.ActionInterval.prototype.ctor.call(this); this._skewX = 0; this._skewY = 0; @@ -1102,7 +1118,7 @@ cc.SkewTo = cc.ActionInterval.extend(/** @lends cc.SkewTo# */{ * returns a new clone of the action * @returns {cc.SkewTo} */ - clone: function () { + clone:function () { var action = new cc.SkewTo(); action.initWithDuration(this._duration, this._endSkewX, this._endSkewY); return action; @@ -1178,7 +1194,7 @@ cc.SkewBy = cc.SkewTo.extend(/** @lends cc.SkewBy# */{ * returns a new clone of the action * @returns {cc.SkewBy} */ - clone: function () { + clone:function () { var action = new cc.SkewBy(); action.initWithDuration(this._duration, this._skewX, this._skewY); return action; @@ -1230,7 +1246,7 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{ _jumps:0, _previousPosition:null, - ctor: function () { + ctor:function () { cc.ActionInterval.prototype.ctor.call(this); this._startPosition = cc.p(0, 0); this._previousPosition = cc.p(0, 0); @@ -1247,7 +1263,8 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{ */ initWithDuration:function (duration, position, height, jumps) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { - this._delta = position; + this._delta.x = position.x; + this._delta.y = position.y; this._height = height; this._jumps = jumps; return true; @@ -1259,7 +1276,7 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{ * returns a new clone of the action * @returns {cc.JumpBy} */ - clone: function () { + clone:function () { var action = new cc.JumpBy(); action.initWithDuration(this._duration, this._delta, this._height, this._jumps); return action; @@ -1270,9 +1287,12 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{ */ startWithTarget:function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); - var locPos = target.getPosition(); - this._previousPosition = cc.p(locPos.x, locPos.y); - this._startPosition = cc.p(locPos.x, locPos.y); + var locPosX = target.getPositionX(); + var locPosY = target.getPositionY(); + this._previousPosition.x = locPosX; + this._previousPosition.y = locPosY; + this._startPosition.x = locPosX; + this._startPosition.y = locPosY; }, /** @@ -1285,16 +1305,22 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{ y += this._delta.y * time; var x = this._delta.x * time; - if(cc.ENABLE_STACKABLE_ACTIONS){ - var currentPos = this._target.getPosition(); - - var diff = cc.pSub(currentPos, this._previousPosition); - this._startPosition = cc.pAdd(diff, this._startPosition); - var newPos = cc.pAdd(this._startPosition, cc.p(x, y)); - this._target.setPosition(newPos); - this._previousPosition = newPos; + var locStartPosition = this._startPosition; + if (cc.ENABLE_STACKABLE_ACTIONS) { + var targetX = this._target.getPositionX(); + var targetY = this._target.getPositionY(); + var locPreviousPosition = this._previousPosition; + + locStartPosition.x = locStartPosition.x + targetX - locPreviousPosition.x; + locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y; + x = x + locStartPosition.x; + y = y + locStartPosition.y; + + this._target.setPosition(x, y); + locPreviousPosition.x = x; + locPreviousPosition.y = y; } else { - this._target.setPosition(cc.pAdd(this._startPosition, cc.p(x,y))); + this._target.setPosition(locStartPosition.x + x, locStartPosition.y + y); } } }, @@ -1333,14 +1359,15 @@ cc.JumpTo = cc.JumpBy.extend(/** @lends cc.JumpTo# */{ */ startWithTarget:function (target) { cc.JumpBy.prototype.startWithTarget.call(this, target); - this._delta = cc.p(this._delta.x - this._startPosition.x, this._delta.y - this._startPosition.y); + this._delta.x = this._delta.x - this._startPosition.x; + this._delta.y = this._delta.y - this._startPosition.y; }, /** * returns a new clone of the action * @returns {cc.JumpTo} */ - clone: function(){ + clone:function () { var action = new cc.JumpTo(); action.initWithDuration(this._duration, this._delta, this._height, this._jumps); return action; @@ -1384,14 +1411,14 @@ cc.bezierAt = function (a, b, c, d, t) { * @extends cc.ActionInterval */ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{ - _config: null, - _startPosition: null, - _previousPosition: null, + _config:null, + _startPosition:null, + _previousPosition:null, /** * Constructor */ - ctor: function () { + ctor:function () { cc.ActionInterval.prototype.ctor.call(this); this._config = []; this._startPosition = cc.p(0, 0); @@ -1414,10 +1441,10 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{ * returns a new clone of the action * @returns {cc.BezierBy} */ - clone:function(){ + clone:function () { var action = new cc.BezierBy(); var newConfigs = []; - for(var i = 0; i < this._config.length; i++){ + for (var i = 0; i < this._config.length; i++) { var selConf = this._config[i]; newConfigs.push(cc.p(selConf.x, selConf.y)); } @@ -1430,9 +1457,12 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{ */ startWithTarget:function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); - var locPos = target.getPosition(); - this._previousPosition = cc.p(locPos.x, locPos.y); - this._startPosition = cc.p(locPos.x, locPos.y); + var locPosX = target.getPositionX(); + var locPosY = target.getPositionY(); + this._previousPosition.x = locPosX; + this._previousPosition.y = locPosY; + this._startPosition.x = locPosX; + this._startPosition.y = locPosY; }, /** @@ -1454,16 +1484,21 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{ var x = cc.bezierAt(xa, xb, xc, xd, time); var y = cc.bezierAt(ya, yb, yc, yd, time); - if(cc.ENABLE_STACKABLE_ACTIONS){ - var currentPos = this._target.getPosition(); - var diff = cc.pSub(currentPos, this._previousPosition); - this._startPosition = cc.pAdd(this._startPosition, diff); - var newPos = cc.pAdd(this._startPosition, cc.p(x, y)); - - this._target.setPosition(newPos); - this._previousPosition = newPos; + var locStartPosition = this._startPosition; + if (cc.ENABLE_STACKABLE_ACTIONS) { + var targetX = this._target.getPositionX(); + var targetY = this._target.getPositionY(); + var locPreviousPosition = this._previousPosition; + + locStartPosition.x = locStartPosition.x + targetX - locPreviousPosition.x; + locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y; + x = x + locStartPosition.x; + y = y + locStartPosition.y; + this._target.setPosition(x, y); + locPreviousPosition.x = x; + locPreviousPosition.y = y; } else { - this._target.setPosition(cc.pAdd(this._startPosition, cc.p(x,y))); + this._target.setPosition(locStartPosition.x + x, locStartPosition.y + y); } } }, @@ -1474,8 +1509,8 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{ reverse:function () { var locConfig = this._config; var r = [ - cc.pAdd(locConfig[1], cc.pNeg(locConfig[2]) ), - cc.pAdd(locConfig[0], cc.pNeg(locConfig[2]) ), + cc.pAdd(locConfig[1], cc.pNeg(locConfig[2])), + cc.pAdd(locConfig[0], cc.pNeg(locConfig[2])), cc.pNeg(locConfig[2]) ]; return cc.BezierBy.create(this._duration, r); } @@ -1505,7 +1540,7 @@ cc.BezierBy.create = function (t, c) { cc.BezierTo = cc.BezierBy.extend(/** @lends cc.BezierTo# */{ _toConfig:null, - ctor: function () { + ctor:function () { cc.BezierBy.prototype.ctor.call(this); this._toConfig = []; }, @@ -1516,7 +1551,7 @@ cc.BezierTo = cc.BezierBy.extend(/** @lends cc.BezierTo# */{ * @return {Boolean} */ initWithDuration:function (t, c) { - if(cc.ActionInterval.prototype.initWithDuration.call(this, t)){ + if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) { this._toConfig = c; return true; } @@ -1527,7 +1562,7 @@ cc.BezierTo = cc.BezierBy.extend(/** @lends cc.BezierTo# */{ * returns a new clone of the action * @returns {cc.BezierTo} */ - clone: function () { + clone:function () { var action = new cc.BezierTo(); action.initWithDuration(this._duration, this._toConfig); return action; @@ -1541,6 +1576,7 @@ cc.BezierTo = cc.BezierBy.extend(/** @lends cc.BezierTo# */{ var locStartPos = this._startPosition; var locToConfig = this._toConfig; var locConfig = this._config; + locConfig[0] = cc.pSub(locToConfig[0], locStartPos); locConfig[1] = cc.pSub(locToConfig[1], locStartPos); locConfig[2] = cc.pSub(locToConfig[2], locStartPos); @@ -1577,7 +1613,7 @@ cc.ScaleTo = cc.ActionInterval.extend(/** @lends cc.ScaleTo# */{ _deltaX:0, _deltaY:0, - ctor: function () { + ctor:function () { cc.ActionInterval.prototype.ctor.call(this); this._scaleX = 1; this._scaleY = 1; @@ -1608,7 +1644,7 @@ cc.ScaleTo = cc.ActionInterval.extend(/** @lends cc.ScaleTo# */{ * returns a new clone of the action * @returns {cc.ScaleTo} */ - clone: function(){ + clone:function () { var action = new cc.ScaleTo(); action.initWithDuration(this._duration, this._endScaleX, this._endScaleY); return action; @@ -1646,7 +1682,7 @@ cc.ScaleTo = cc.ActionInterval.extend(/** @lends cc.ScaleTo# */{ * // It scales to 0.5 in x and 2 in Y * var actionTo = cc.ScaleTo.create(2, 0.5, 2); */ -cc.ScaleTo.create = function (duration, sx, sy){ //function overload +cc.ScaleTo.create = function (duration, sx, sy) { //function overload var scaleTo = new cc.ScaleTo(); scaleTo.initWithDuration(duration, sx, sy); return scaleTo; @@ -1678,7 +1714,7 @@ cc.ScaleBy = cc.ScaleTo.extend(/** @lends cc.ScaleBy# */{ * returns a new clone of the action * @returns {cc.ScaleBy} */ - clone: function(){ + clone:function () { var action = new cc.ScaleBy(); action.initWithDuration(this._duration, this._endScaleX, this._endScaleY); return action; @@ -1710,7 +1746,7 @@ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{ _times:0, _originalState:false, - ctor: function(){ + ctor:function () { cc.ActionInterval.prototype.ctor.call(this); this._times = 0; this._originalState = false; @@ -1733,7 +1769,7 @@ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{ * returns a new clone of the action * @returns {cc.Blink} */ - clone: function(){ + clone:function () { var action = new cc.Blink(); action.initWithDuration(this._duration, this._times); return action; @@ -1750,12 +1786,12 @@ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{ } }, - startWithTarget:function(target){ + startWithTarget:function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._originalState = target.isVisible(); }, - stop:function(){ + stop:function () { this._target.setVisible(this._originalState); cc.ActionInterval.prototype.stop.call(this); }, @@ -1805,7 +1841,7 @@ cc.FadeIn = cc.ActionInterval.extend(/** @lends cc.FadeIn# */{ * returns a new clone of the action * @returns {cc.FadeIn} */ - clone: function () { + clone:function () { var action = new cc.FadeIn(); action.initWithDuration(this._duration); return action; @@ -1850,7 +1886,7 @@ cc.FadeOut = cc.ActionInterval.extend(/** @lends cc.FadeOut# */{ * returns a new clone of the action * @returns {cc.FadeOut} */ - clone: function(){ + clone:function () { var action = new cc.FadeOut(); action.initWithDuration(this._duration); return action; @@ -1876,10 +1912,10 @@ cc.FadeOut.create = function (d) { * @extends cc.ActionInterval */ cc.FadeTo = cc.ActionInterval.extend(/** @lends cc.FadeTo# */{ - _toOpacity: null, - _fromOpacity: null, + _toOpacity:null, + _fromOpacity:null, - ctor: function () { + ctor:function () { cc.ActionInterval.prototype.ctor.call(this); this._toOpacity = 0; this._fromOpacity = 0; @@ -1902,7 +1938,7 @@ cc.FadeTo = cc.ActionInterval.extend(/** @lends cc.FadeTo# */{ * returns a new clone of the action * @returns {cc.FadeTo} */ - clone: function(){ + clone:function () { var action = new cc.FadeTo(); action.initWithDuration(this._duration, this._toOpacity); return action; @@ -1947,7 +1983,7 @@ cc.TintTo = cc.ActionInterval.extend(/** @lends cc.TintTo# */{ _to:null, _from:null, - ctor: function(){ + ctor:function () { cc.ActionInterval.prototype.ctor.call(this); this._to = cc.c3b(0, 0, 0); this._from = cc.c3b(0, 0, 0); @@ -1972,7 +2008,7 @@ cc.TintTo = cc.ActionInterval.extend(/** @lends cc.TintTo# */{ * returns a new clone of the action * @returns {cc.TintTo} */ - clone:function(){ + clone:function () { var action = new cc.TintTo(); var locTo = this._to; action.initWithDuration(this._duration, locTo.r, locTo.g, locTo.b); @@ -1993,7 +2029,7 @@ cc.TintTo = cc.ActionInterval.extend(/** @lends cc.TintTo# */{ update:function (time) { var locFrom = this._from, locTo = this._to; this._target.setColor(cc.c3b(locFrom.r + (locTo.r - locFrom.r) * time, - (locFrom.g + (locTo.g - locFrom.g) * time),(locFrom.b + (locTo.b - locFrom.b) * time))); + (locFrom.g + (locTo.g - locFrom.g) * time), (locFrom.b + (locTo.b - locFrom.b) * time))); } }); @@ -2027,14 +2063,14 @@ cc.TintBy = cc.ActionInterval.extend(/** @lends cc.TintBy# */{ _fromG:0, _fromB:0, - ctor:function(){ + ctor:function () { cc.ActionInterval.prototype.ctor.call(this); - this._deltaR=0; - this._deltaG=0; - this._deltaB=0; - this._fromR=0; - this._fromG=0; - this._fromB=0; + this._deltaR = 0; + this._deltaG = 0; + this._deltaB = 0; + this._fromR = 0; + this._fromG = 0; + this._fromB = 0; }, /** @@ -2058,7 +2094,7 @@ cc.TintBy = cc.ActionInterval.extend(/** @lends cc.TintBy# */{ * returns a new clone of the action * @returns {cc.TintBy} */ - clone: function(){ + clone:function () { var action = new cc.TintBy(); action.initWithDuration(this._duration, this._deltaR, this._deltaG, this._deltaB); return action; @@ -2134,8 +2170,8 @@ cc.DelayTime = cc.ActionInterval.extend(/** @lends cc.DelayTime# */{ * returns a new clone of the action * @returns {cc.DelayTime} */ - clone: function(){ - var action = new cc.DelayTime(); + clone:function () { + var action = new cc.DelayTime(); action.initWithDuration(this._duration); return action; } @@ -2166,7 +2202,7 @@ cc.DelayTime.create = function (d) { cc.ReverseTime = cc.ActionInterval.extend(/** @lends cc.ReverseTime# */{ _other:null, - ctor:function(){ + ctor:function () { cc.ActionInterval.prototype.ctor.call(this); this._other = null; }, @@ -2191,7 +2227,7 @@ cc.ReverseTime = cc.ActionInterval.extend(/** @lends cc.ReverseTime# */{ * returns a new clone of the action * @returns {cc.ReverseTime} */ - clone: function(){ + clone:function () { var action = new cc.ReverseTime(); action.initWithAction(this._other.clone()); return action; @@ -2254,13 +2290,13 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{ _executedLoops:0, _splitTimes:null, - ctor:function(){ + ctor:function () { cc.ActionInterval.prototype.ctor.call(this); - this._animation=null; - this._nextFrame=0; - this._origFrame=null; - this._executedLoops=0; - this._splitTimes=null; + this._animation = null; + this._nextFrame = 0; + this._origFrame = null; + this._executedLoops = 0; + this._splitTimes = null; }, /** @@ -2314,7 +2350,7 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{ * returns a new clone of the action * @returns {cc.Animate} */ - clone: function(){ + clone:function () { var action = new cc.Animate(); action.initWithAnimation(this._animation.clone()); return action; @@ -2356,7 +2392,7 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{ if (locSplitTimes[i] <= time) { this._target.setDisplayFrame(frames[i].getSpriteFrame()); this._nextFrame = i + 1; - }else{ + } else { // Issue 1438. Could be more than one frame per tick, due to low frame rate or frame delta < 1/FPS break; } @@ -2421,7 +2457,7 @@ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{ _action:null, _forcedTarget:null, - ctor: function(){ + ctor:function () { cc.ActionInterval.prototype.ctor.call(this); this._action = null; this._forcedTarget = null; @@ -2446,7 +2482,7 @@ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{ * returns a new clone of the action * @returns {cc.TargetedAction} */ - clone:function(){ + clone:function () { var action = new cc.TargetedAction(); action.initWithTarget(this._forcedTarget, this._action.clone()); return action; diff --git a/cocos2d/actions/CCActionManager.js b/cocos2d/actions/CCActionManager.js index fdc80f8f15..ed5c01df78 100644 --- a/cocos2d/actions/CCActionManager.js +++ b/cocos2d/actions/CCActionManager.js @@ -329,7 +329,7 @@ cc.ActionManager = cc.Class.extend({ for (var elt = 0; elt < locTargets.length; elt++) { this._currentTarget = locTargets[elt]; locCurrTarget = this._currentTarget; - this._currentTargetSalvaged = false; + //this._currentTargetSalvaged = false; if (!locCurrTarget.paused) { // The 'actions' CCMutableArray may change while inside this loop. for (locCurrTarget.actionIndex = 0; locCurrTarget.actionIndex < locCurrTarget.actions.length; diff --git a/cocos2d/actions/CCActionPageTurn3D.js b/cocos2d/actions/CCActionPageTurn3D.js index 0f7980e8a6..7341694a25 100644 --- a/cocos2d/actions/CCActionPageTurn3D.js +++ b/cocos2d/actions/CCActionPageTurn3D.js @@ -52,10 +52,13 @@ cc.PageTurn3D = cc.Grid3DAction.extend(/** @lends cc.PageTurn3D# */{ var cosTheta = Math.cos(theta); var locGridSize = this._gridSize; + var locVer = cc.p(0, 0); for (var i = 0; i <= locGridSize.width; ++i) { for (var j = 0; j <= locGridSize.height; ++j) { + locVer.x = i; + locVer.y = j; // Get original vertex - var p = this.originalVertex(cc.p(i, j)); + var p = this.originalVertex(locVer); var R = Math.sqrt((p.x * p.x) + ((p.y - ay) * (p.y - ay))); var r = R * sinTheta; @@ -82,7 +85,7 @@ cc.PageTurn3D = cc.Grid3DAction.extend(/** @lends cc.PageTurn3D# */{ p.z = 0.5; // Set new coords - this.setVertex(cc.p(i, j), p); + this.setVertex(locVer, p); } } } diff --git a/cocos2d/actions/CCActionTiledGrid.js b/cocos2d/actions/CCActionTiledGrid.js index da347808a9..2a05c4d451 100644 --- a/cocos2d/actions/CCActionTiledGrid.js +++ b/cocos2d/actions/CCActionTiledGrid.js @@ -33,7 +33,7 @@ cc.ShakyTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.ShakyTiles3D# */{ _randRange:0, _shakeZ:false, - ctor:function(){ + ctor:function () { cc.GridAction.prototype.ctor.call(this); this._randRange = 0; this._shakeZ = false; @@ -58,9 +58,12 @@ cc.ShakyTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.ShakyTiles3D# */{ update:function (time) { var locGridSize = this._gridSize, locRandRange = this._randRange; + var locPos = cc.p(0, 0); for (var i = 0; i < locGridSize.width; ++i) { for (var j = 0; j < locGridSize.height; ++j) { - var coords = this.originalTile(cc.p(i, j)); + locPos.x = i; + locPos.y = j; + var coords = this.originalTile(locPos); // X coords.bl.x += ( cc.rand() % (locRandRange * 2) ) - locRandRange; @@ -81,7 +84,7 @@ cc.ShakyTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.ShakyTiles3D# */{ coords.tr.z += ( cc.rand() % (locRandRange * 2) ) - locRandRange; } - this.setTile(cc.p(i, j), coords); + this.setTile(locPos, coords); } } } @@ -111,7 +114,7 @@ cc.ShatteredTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.ShatteredTiles3D _once:false, _shatterZ:false, - ctor:function(){ + ctor:function () { cc.GridAction.prototype.ctor.call(this); this._randRange = 0; this._shakeZ = false; @@ -139,9 +142,12 @@ cc.ShatteredTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.ShatteredTiles3D update:function (time) { if (this._once === false) { var locGridSize = this._gridSize, locRandRange = this._randRange; + var coords, locPos = cc.p(0, 0); for (var i = 0; i < locGridSize.width; ++i) { for (var j = 0; j < locGridSize.height; ++j) { - var coords = this.originalTile(cc.p(i, j)); + locPos.x = i; + locPos.y = j; + coords = this.originalTile(locPos); // X coords.bl.x += ( cc.rand() % (locRandRange * 2) ) - locRandRange; @@ -161,7 +167,7 @@ cc.ShatteredTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.ShatteredTiles3D coords.tl.z += ( cc.rand() % (locRandRange * 2) ) - locRandRange; coords.tr.z += ( cc.rand() % (locRandRange * 2) ) - locRandRange; } - this.setTile(cc.p(i, j), coords); + this.setTile(locPos, coords); } } this._once = true; @@ -254,7 +260,7 @@ cc.ShuffleTiles = cc.TiledGrid3DAction.extend(/** @lends cc.ShuffleTiles# */{ getDelta:function (pos) { var locGridSize = this._gridSize; var idx = pos.width * locGridSize.height + pos.height; - return cc.SizeMake(((this._tilesOrder[idx] / locGridSize.height) - pos.width), + return cc.size(((this._tilesOrder[idx] / locGridSize.height) - pos.width), ((this._tilesOrder[idx] % locGridSize.height) - pos.height)); }, @@ -310,7 +316,7 @@ cc.ShuffleTiles = cc.TiledGrid3DAction.extend(/** @lends cc.ShuffleTiles# */{ locTiles[tileIndex] = new cc.Tile(); locTiles[tileIndex].position = cc.p(i, j); locTiles[tileIndex].startPosition = cc.p(i, j); - locTiles[tileIndex].delta = this.getDelta(cc.SizeMake(i, j)); + locTiles[tileIndex].delta = this.getDelta(cc.size(i, j)); ++tileIndex; } } @@ -319,11 +325,15 @@ cc.ShuffleTiles = cc.TiledGrid3DAction.extend(/** @lends cc.ShuffleTiles# */{ update:function (time) { var tileIndex = 0, locGridSize = this._gridSize, locTiles = this._tiles; + var selTile, locPos = cc.p(0, 0); for (var i = 0; i < locGridSize.width; ++i) { for (var j = 0; j < locGridSize.height; ++j) { - var selTile = locTiles[tileIndex]; - selTile.position = cc.pMult(cc.p(selTile.delta.width, selTile.delta.height), time); - this.placeTile(cc.p(i, j), selTile); + locPos.x = i; + locPos.y = j; + selTile = locTiles[tileIndex]; + selTile.position.x = selTile.delta.width * time; + selTile.position.y = selTile.delta.height * time; + this.placeTile(locPos, selTile); ++tileIndex; } } @@ -354,10 +364,11 @@ cc.FadeOutTRTiles = cc.TiledGrid3DAction.extend(/** @lends cc.FadeOutTRTiles# */ * @param {Number} time */ testFunc:function (pos, time) { - var n = cc.pMult(cc.p(this._gridSize.width, this._gridSize.height), time); - if ((n.x + n.y) == 0.0) + var locX = this._gridSize.width * time; + var locY = this._gridSize.height * time; + if ((locX + locY) == 0.0) return 1.0; - return Math.pow((pos.width + pos.height) / (n.x + n.y), 6); + return Math.pow((pos.width + pos.height) / (locX + locY), 6); }, /** @@ -402,15 +413,20 @@ cc.FadeOutTRTiles = cc.TiledGrid3DAction.extend(/** @lends cc.FadeOutTRTiles# */ update:function (time) { var locGridSize = this._gridSize; + var locPos = cc.p(0, 0), locSize = cc.size(0, 0), distance; for (var i = 0; i < locGridSize.width; ++i) { for (var j = 0; j < locGridSize.height; ++j) { - var distance = this.testFunc(cc.SizeMake(i, j), time); + locPos.x = i; + locPos.y = j; + locSize.width = i; + locSize.height = j; + distance = this.testFunc(locSize, time); if (distance == 0) - this.turnOffTile(cc.p(i, j)); + this.turnOffTile(locPos); else if (distance < 1) - this.transformTile(cc.p(i, j), distance); + this.transformTile(locPos, distance); else - this.turnOnTile(cc.p(i, j)); + this.turnOnTile(locPos); } } } @@ -439,11 +455,12 @@ cc.FadeOutBLTiles = cc.FadeOutTRTiles.extend(/** @lends cc.FadeOutBLTiles# */{ * @param {Number} time */ testFunc:function (pos, time) { - var n = cc.pMult(cc.p(this._gridSize.width, this._gridSize.height), (1.0 - time)); + var locX = this._gridSize.width * (1.0 - time); + var locY = this._gridSize.height * (1.0 - time); if ((pos.width + pos.height) == 0) return 1.0; - return Math.pow((n.x + n.y) / (pos.width + pos.height), 6); + return Math.pow((locX + locY) / (pos.width + pos.height), 6); } }); @@ -466,10 +483,10 @@ cc.FadeOutBLTiles.create = function (duration, gridSize) { */ cc.FadeOutUpTiles = cc.FadeOutTRTiles.extend(/** @lends cc.FadeOutUpTiles# */{ testFunc:function (pos, time) { - var n = cc.pMult(cc.p(this._gridSize.width, this._gridSize.height), time); - if (n.y == 0.0) + var locY = this._gridSize.height * time; + if (locY == 0.0) return 1.0; - return Math.pow(pos.height / n.y, 6); + return Math.pow(pos.height / locY, 6); }, transformTile:function (pos, distance) { @@ -504,10 +521,10 @@ cc.FadeOutUpTiles.create = function (duration, gridSize) { */ cc.FadeOutDownTiles = cc.FadeOutUpTiles.extend(/** @lends cc.FadeOutDownTiles# */{ testFunc:function (pos, time) { - var n = cc.pMult(cc.p(this._gridSize.width, this._gridSize.height), (1.0 - time)); + var locY = this._gridSize.height * (1.0 - time); if (pos.height == 0) return 1.0; - return Math.pow(n.y / pos.height, 6); + return Math.pow(locY / pos.height, 6); } }); @@ -603,9 +620,11 @@ cc.TurnOffTiles = cc.TiledGrid3DAction.extend(/** @lends cc.TurnOffTiles# */{ */ update:function (time) { var l = 0 | (time * this._tilesCount), locGridSize = this._gridSize; + var t,tilePos = cc.p(0,0); for (var i = 0; i < this._tilesCount; i++) { - var t = this._tilesOrder[i]; - var tilePos = cc.p(0 | (t / locGridSize.height), t % (0 | locGridSize.height)); + t = this._tilesOrder[i]; + tilePos.x = 0 | (t / locGridSize.height); + tilePos.y = t % (0 | locGridSize.height); if (i < l) this.turnOffTile(tilePos); else @@ -645,7 +664,7 @@ cc.WavesTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.WavesTiles3D# */{ _amplitude:0, _amplitudeRate:0, - ctor:function(){ + ctor:function () { cc.GridAction.prototype.ctor.call(this); this._waves = 0; this._amplitude = 0; @@ -704,15 +723,18 @@ cc.WavesTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.WavesTiles3D# */{ update:function (time) { var locGridSize = this._gridSize, locWaves = this._waves, locAmplitude = this._amplitude, locAmplitudeRate = this._amplitudeRate; + var locPos = cc.p(0, 0), coords; for (var i = 0; i < locGridSize.width; i++) { for (var j = 0; j < locGridSize.height; j++) { - var coords = this.originalTile(cc.p(i, j)); + locPos.x = i; + locPos.y = j; + coords = this.originalTile(locPos); coords.bl.z = (Math.sin(time * Math.PI * locWaves * 2 + (coords.bl.y + coords.bl.x) * 0.01) * locAmplitude * locAmplitudeRate); coords.br.z = coords.bl.z; coords.tl.z = coords.bl.z; coords.tr.z = coords.bl.z; - this.setTile(cc.p(i, j), coords); + this.setTile(locPos, coords); } } } @@ -742,7 +764,7 @@ cc.JumpTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.JumpTiles3D# */{ _amplitude:0, _amplitudeRate:0, - ctor:function(){ + ctor:function () { cc.GridAction.prototype.ctor.call(this); this._jumps = 0; this._amplitude = 0; @@ -804,11 +826,14 @@ cc.JumpTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.JumpTiles3D# */{ var locGridSize = this._gridSize; var locGrid = this._target.getGrid(); + var coords, locPos = cc.p(0, 0); for (var i = 0; i < locGridSize.width; i++) { for (var j = 0; j < locGridSize.height; j++) { + locPos.x = i; + locPos.y = j; //hack for html5 //var coords = this.originalTile(cc.p(i, j)); - var coords = locGrid.originalTile(cc.p(i, j)); + coords = locGrid.originalTile(locPos); if (((i + j) % 2) == 0) { coords.bl.z += sinz; @@ -823,7 +848,7 @@ cc.JumpTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.JumpTiles3D# */{ } //hack for html5 //this.setTile(cc.p(i, j), coords); - locGrid.setTile(cc.p(i, j), coords); + locGrid.setTile(locPos, coords); } } } @@ -852,7 +877,7 @@ cc.SplitRows = cc.TiledGrid3DAction.extend(/** @lends cc.SplitRows# */{ _rows:0, _winSize:null, - ctor:function(){ + ctor:function () { cc.GridAction.prototype.ctor.call(this); this._rows = 0; this._winSize = null; @@ -866,14 +891,16 @@ cc.SplitRows = cc.TiledGrid3DAction.extend(/** @lends cc.SplitRows# */{ */ initWithDuration:function (duration, rows) { this._rows = rows; - return cc.TiledGrid3DAction.prototype.initWithDuration.call(this, duration, cc.SizeMake(1, rows)); + return cc.TiledGrid3DAction.prototype.initWithDuration.call(this, duration, cc.size(1, rows)); }, update:function (time) { var locGridSize = this._gridSize, locWinSizeWidth = this._winSize.width; + var coords, direction, locPos = cc.p(0, 0); for (var j = 0; j < locGridSize.height; ++j) { - var coords = this.originalTile(cc.p(0, j)); - var direction = 1; + locPos.y = j; + coords = this.originalTile(locPos); + direction = 1; if ((j % 2 ) == 0) direction = -1; @@ -883,7 +910,7 @@ cc.SplitRows = cc.TiledGrid3DAction.extend(/** @lends cc.SplitRows# */{ coords.tl.x += direction * locWinSizeWidth * time; coords.tr.x += direction * locWinSizeWidth * time; - this.setTile(cc.p(0, j), coords); + this.setTile(locPos, coords); } }, @@ -914,7 +941,7 @@ cc.SplitCols = cc.TiledGrid3DAction.extend(/** @lends cc.SplitCols# */{ _cols:0, _winSize:null, - ctor:function(){ + ctor:function () { cc.GridAction.prototype.ctor.call(this); this._cols = 0; this._winSize = null; @@ -927,14 +954,16 @@ cc.SplitCols = cc.TiledGrid3DAction.extend(/** @lends cc.SplitCols# */{ */ initWithDuration:function (duration, cols) { this._cols = cols; - return cc.TiledGrid3DAction.prototype.initWithDuration.call(this, duration, cc.SizeMake(cols, 1)); + return cc.TiledGrid3DAction.prototype.initWithDuration.call(this, duration, cc.size(cols, 1)); }, update:function (time) { var locGridSizeWidth = this._gridSize.width, locWinSizeHeight = this._winSize.height; + var coords, direction, locPos = cc.p(0, 0); for (var i = 0; i < locGridSizeWidth; ++i) { - var coords = this.originalTile(cc.p(i, 0)); - var direction = 1; + locPos.x = i; + coords = this.originalTile(locPos); + direction = 1; if ((i % 2 ) == 0) direction = -1; @@ -944,7 +973,7 @@ cc.SplitCols = cc.TiledGrid3DAction.extend(/** @lends cc.SplitCols# */{ coords.tl.y += direction * locWinSizeHeight * time; coords.tr.y += direction * locWinSizeHeight * time; - this.setTile(cc.p(i, 0), coords); + this.setTile(locPos, coords); } }, diff --git a/cocos2d/base_nodes/CCAtlasNode.js b/cocos2d/base_nodes/CCAtlasNode.js index fa64826a00..d122b3218a 100644 --- a/cocos2d/base_nodes/CCAtlasNode.js +++ b/cocos2d/base_nodes/CCAtlasNode.js @@ -25,7 +25,7 @@ ****************************************************************************/ /**

cc.AtlasNode is a subclass of cc.Node that implements the cc.RGBAProtocol and
- * cc.TextureProtocol protocol (Canvas implement)

+ * cc.TextureProtocol protocol

* *

It knows how to render a TextureAtlas object.
* If you are going to render a TextureAtlas consider subclassing cc.AtlasNode (or a subclass of cc.AtlasNode)

@@ -35,8 +35,7 @@ * @class * @extends cc.NodeRGBA */ -cc.AtlasNodeCanvas = cc.NodeRGBA.extend(/** @lends cc.AtlasNode# */{ - /// ---- common properties start ---- +cc.AtlasNode = cc.NodeRGBA.extend(/** @lends cc.AtlasNode# */{ RGBAProtocol:true, //! chars per row _itemsPerRow:0, @@ -59,7 +58,7 @@ cc.AtlasNodeCanvas = cc.NodeRGBA.extend(/** @lends cc.AtlasNode# */{ _ignoreContentScaleFactor:false, // This variable is only used for CCLabelAtlas FPS display. So plz don't modify its value. ctor:function () { - this._super(); + cc.NodeRGBA.prototype.ctor.call(this); this._colorUnmodified = cc.white(); this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST}; this._ignoreContentScaleFactor = false; @@ -144,10 +143,12 @@ cc.AtlasNodeCanvas = cc.NodeRGBA.extend(/** @lends cc.AtlasNode# */{ this._quadsToDraw = quadsToDraw; }, - /// ---- common properties end ---- _textureForCanvas:null, _originalTexture:null, + _uniformColor:null, + _colorF32Array:null, + /** initializes an cc.AtlasNode with an Atlas file the width and height of each item and the quantity of items to render * @param {String} tile * @param {Number} tileWidth @@ -163,13 +164,15 @@ cc.AtlasNodeCanvas = cc.NodeRGBA.extend(/** @lends cc.AtlasNode# */{ /** * initializes an CCAtlasNode with a texture the width and height of each item measured in points and the quantity of items to render - * @param {HTMLImageElement|HTMLCanvasElement} texture + * @param {cc.Texture2D} texture * @param {Number} tileWidth * @param {Number} tileHeight * @param {Number} itemsToRender - * @returen {Boolean} + * @return {Boolean} */ - initWithTexture:function(texture, tileWidth, tileHeight, itemsToRender){ + initWithTexture:null, + + _initWithTextureForCanvas:function(texture, tileWidth, tileHeight, itemsToRender){ this._itemWidth = tileWidth; this._itemHeight = tileHeight; @@ -186,218 +189,7 @@ cc.AtlasNodeCanvas = cc.NodeRGBA.extend(/** @lends cc.AtlasNode# */{ return true; }, - /** - * @param {cc.Color3B} color3 - */ - setColor:function (color3) { - if ((this._realColor.r == color3.r) && (this._realColor.g == color3.g) && (this._realColor.b == color3.b)) - return; - var temp = new cc.Color3B(color3.r,color3.g,color3.b); - this._colorUnmodified = color3; - - if (this._opacityModifyRGB) { - temp.r = temp.r * this._displayedOpacity / 255; - temp.g = temp.g * this._displayedOpacity / 255; - temp.b = temp.b * this._displayedOpacity / 255; - } - cc.NodeRGBA.prototype.setColor.call(this, color3); - if (this.getTexture()) { - var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(this._originalTexture); - if (cacheTextureForColor) { - var tx = this._originalTexture; - var textureRect = cc.rect(0, 0, tx.width, tx.height); - var colorTexture = cc.generateTintImage(tx, cacheTextureForColor, this._realColor, textureRect); - this.setTexture(colorTexture); - } - } - }, - - /** - * @param {Number} opacity - */ - setOpacity:function (opacity) { - cc.NodeRGBA.prototype.setOpacity.call(this, opacity); - - // special opacity for premultiplied textures - if (this._opacityModifyRGB) { - this.setColor(this._colorUnmodified); - } - }, - - // cc.Texture protocol - /** - * returns the used texture - * @return {cc.Texture2D} - */ - getTexture:function () { - return this._textureForCanvas; - }, - - /** sets a new texture. it will be retained - * @param {HTMLCanvasElement|HTMLImageElement} texture - */ - setTexture:function (texture) { - this._textureForCanvas = texture; - }, - - _calculateMaxItems:function () { - var selTexture = this.getTexture(); - var size = cc.size(selTexture.width, selTexture.height); - - this._itemsPerColumn = 0 | (size.height / this._itemHeight); - this._itemsPerRow = 0 | (size.width / this._itemWidth); - }, - - _setIgnoreContentScaleFactor:function(ignoreContentScaleFactor){ - this._ignoreContentScaleFactor = ignoreContentScaleFactor; - } -}); - -/**

cc.AtlasNode is a subclass of cc.Node that implements the cc.RGBAProtocol and
- * cc.TextureProtocol protocol (WebGL implement)

- * - *

It knows how to render a TextureAtlas object.
- * If you are going to render a TextureAtlas consider subclassing cc.AtlasNode (or a subclass of cc.AtlasNode)

- * - *

All features from cc.Node are valid, plus the following features:
- * - opacity and RGB colors

- * @class - * @extends cc.Node - */ -cc.AtlasNodeWebGL = cc.NodeRGBA.extend({ - /// ---- common properties start ---- - RGBAProtocol:true, - //! chars per row - _itemsPerRow:0, - //! chars per column - _itemsPerColumn:0, - //! width of each char - _itemWidth:0, - //! height of each char - _itemHeight:0, - - _colorUnmodified:null, - _textureAtlas:null, - - // protocol variables - _opacityModifyRGB:false, - _blendFunc:null, - - // quads to draw - _quadsToDraw:0, - _ignoreContentScaleFactor:false, // This variable is only used for CCLabelAtlas FPS display. So plz don't modify its value. - - ctor:function () { - this._super(); - this._colorUnmodified = cc.white(); - this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST}; - this._ignoreContentScaleFactor = false; - }, - - /** updates the Atlas (indexed vertex array). - * Shall be overridden in subclasses - */ - updateAtlasValues:function () { - cc.Assert(false, "cc.AtlasNode:Abstract updateAtlasValue not overridden"); - }, - - /** cc.AtlasNode - RGBA protocol - * @return {cc.Color3B} - */ - getColor:function () { - if (this._opacityModifyRGB) - return this._colorUnmodified; - return cc.NodeRGBA.prototype.getColor.call(this); - }, - - /** - * @param {Boolean} value - */ - setOpacityModifyRGB:function (value) { - var oldColor = this.getColor(); - this._opacityModifyRGB = value; - this.setColor(oldColor); - }, - - /** - * @return {Boolean} - */ - isOpacityModifyRGB:function () { - return this._opacityModifyRGB; - }, - - /** cc.AtlasNode - CocosNodeTexture protocol - * @return {cc.BlendFunc} - */ - getBlendFunc:function () { - return this._blendFunc; - }, - - /** - * BlendFunc setter - * @param {Number | cc.BlendFunc} src - * @param {Number} dst - */ - setBlendFunc:function (src, dst) { - if (arguments.length == 1) - this._blendFunc = src; - else - this._blendFunc = {src:src, dst:dst}; - }, - - /** - * @param {cc.TextureAtlas} value - */ - setTextureAtlas:function (value) { - this._textureAtlas = value; - }, - - /** - * @return {cc.TextureAtlas} - */ - getTextureAtlas:function () { - return this._textureAtlas; - }, - - /** - * @return {Number} - */ - getQuadsToDraw:function () { - return this._quadsToDraw; - }, - - /** - * @param {Number} quadsToDraw - */ - setQuadsToDraw:function (quadsToDraw) { - this._quadsToDraw = quadsToDraw; - }, - /// ---- common properties end ---- - - _uniformColor:null, - - /** initializes an cc.AtlasNode with an Atlas file the width and height of each item and the quantity of items to render - * @param {String} tile - * @param {Number} tileWidth - * @param {Number} tileHeight - * @param {Number} itemsToRender - * @return {Boolean} - */ - initWithTileFile:function (tile, tileWidth, tileHeight, itemsToRender) { - cc.Assert(tile != null, "title should not be null"); - var texture = cc.TextureCache.getInstance().addImage(tile); - return this.initWithTexture(texture, tileWidth, tileHeight, itemsToRender); - }, - - /** - * initializes an CCAtlasNode with a texture the width and height of each item measured in points and the quantity of items to render - * @param {cc.Texture2D} texture - * @param {Number} tileWidth - * @param {Number} tileHeight - * @param {Number} itemsToRender - * @returen {Boolean} - */ - initWithTexture:function(texture, tileWidth, tileHeight, itemsToRender){ + _initWithTextureForWebGL:function(texture, tileWidth, tileHeight, itemsToRender){ this._itemWidth = tileWidth; this._itemHeight = tileHeight; this._colorUnmodified = cc.WHITE; @@ -427,10 +219,12 @@ cc.AtlasNodeWebGL = cc.NodeRGBA.extend({ return true; }, + draw:null, + /** * @param {WebGLRenderingContext} ctx renderContext */ - draw:function (ctx) { + _drawForWebGL:function (ctx) { var context = ctx || cc.renderContext; cc.NODE_DRAW_SETUP(this); cc.glBlendFunc(this._blendFunc.src, this._blendFunc.dst); @@ -441,31 +235,76 @@ cc.AtlasNodeWebGL = cc.NodeRGBA.extend({ /** * @param {cc.Color3B} color3 */ - setColor:function (color3) { - var temp = cc.Color3B(color3.r,color3.g,color3.b); + setColor:null, + + _setColorForCanvas:function (color3) { + var locRealColor = this._realColor; + if ((locRealColor.r == color3.r) && (locRealColor.g == color3.g) && (locRealColor.b == color3.b)) + return; + var temp = new cc.Color3B(color3.r,color3.g,color3.b); this._colorUnmodified = color3; if (this._opacityModifyRGB) { - temp.r = temp.r * this._displayedOpacity / 255; - temp.g = temp.g * this._displayedOpacity / 255; - temp.b = temp.b * this._displayedOpacity / 255; + var locDisplayedOpacity = this._displayedOpacity; + temp.r = temp.r * locDisplayedOpacity / 255; + temp.g = temp.g * locDisplayedOpacity / 255; + temp.b = temp.b * locDisplayedOpacity / 255; } cc.NodeRGBA.prototype.setColor.call(this, color3); - this._colorF32Array = new Float32Array([this._displayedColor.r / 255.0, this._displayedColor.g / 255.0, - this._displayedColor.b / 255.0, this._displayedOpacity / 255.0]); + + if (this.getTexture()) { + var element = this._originalTexture.getHtmlElementObj(); + if(!element) + return; + var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(element); + if (cacheTextureForColor) { + var textureRect = cc.rect(0, 0, element.width, element.height); + element = cc.generateTintImage(element, cacheTextureForColor, this._realColor, textureRect); + var locTexture = new cc.Texture2D(); + locTexture.initWithElement(element); + locTexture.handleLoadedTexture(); + this.setTexture(locTexture); + } + } + }, + + _setColorForWebGL:function (color3) { + var temp = cc.Color3B(color3.r,color3.g,color3.b); + this._colorUnmodified = color3; + var locDisplayedOpacity = this._displayedOpacity; + if (this._opacityModifyRGB) { + temp.r = temp.r * locDisplayedOpacity / 255; + temp.g = temp.g * locDisplayedOpacity / 255; + temp.b = temp.b * locDisplayedOpacity / 255; + } + cc.NodeRGBA.prototype.setColor.call(this, color3); + var locDisplayedColor = this._displayedColor; + this._colorF32Array = new Float32Array([locDisplayedColor.r / 255.0, locDisplayedColor.g / 255.0, + locDisplayedColor.b / 255.0, locDisplayedOpacity / 255.0]); }, /** * @param {Number} opacity */ - setOpacity:function (opacity) { + setOpacity: null, + + _setOpacityForCanvas: function (opacity) { + cc.NodeRGBA.prototype.setOpacity.call(this, opacity); + // special opacity for premultiplied textures + if (this._opacityModifyRGB) { + this.setColor(this._colorUnmodified); + } + }, + + _setOpacityForWebGL: function (opacity) { cc.NodeRGBA.prototype.setOpacity.call(this, opacity); // special opacity for premultiplied textures if (this._opacityModifyRGB) { this.setColor(this._colorUnmodified); } else { var locDisplayedColor = this._displayedColor; - this._colorF32Array = new Float32Array([locDisplayedColor.r / 255.0, locDisplayedColor.g / 255.0, locDisplayedColor.b / 255.0, this._displayedOpacity / 255.0]); + this._colorF32Array = new Float32Array([locDisplayedColor.r / 255.0, locDisplayedColor.g / 255.0, + locDisplayedColor.b / 255.0, this._displayedOpacity / 255.0]); } }, @@ -474,25 +313,46 @@ cc.AtlasNodeWebGL = cc.NodeRGBA.extend({ * returns the used texture * @return {cc.Texture2D} */ - getTexture:function () { + getTexture: null, + + _getTextureForCanvas: function () { + return this._textureForCanvas; + }, + + _getTextureForWebGL: function () { return this._textureAtlas.getTexture(); }, /** sets a new texture. it will be retained * @param {cc.Texture2D} texture */ - setTexture:function (texture) { + setTexture: null, + + _setTextureForCanvas: function (texture) { + this._textureForCanvas = texture; + }, + + _setTextureForWebGL: function (texture) { this._textureAtlas.setTexture(texture); this._updateBlendFunc(); this._updateOpacityModifyRGB(); }, - _calculateMaxItems:function () { + _calculateMaxItems:null, + + _calculateMaxItemsForCanvas:function () { + var selTexture = this.getTexture(); + var size = selTexture.getContentSize(); + + this._itemsPerColumn = 0 | (size.height / this._itemHeight); + this._itemsPerRow = 0 | (size.width / this._itemWidth); + }, + + _calculateMaxItemsForWebGL:function () { var selTexture = this.getTexture(); var size = selTexture.getContentSize(); - if(this._ignoreContentScaleFactor){ + if(this._ignoreContentScaleFactor) size = selTexture.getContentSizeInPixels(); - } this._itemsPerColumn = 0 | (size.height / this._itemHeight); this._itemsPerRow = 0 | (size.width / this._itemWidth); @@ -514,7 +374,23 @@ cc.AtlasNodeWebGL = cc.NodeRGBA.extend({ } }); -cc.AtlasNode = cc.Browser.supportWebGL ? cc.AtlasNodeWebGL : cc.AtlasNodeCanvas; +if(cc.Browser.supportWebGL){ + cc.AtlasNode.prototype.initWithTexture = cc.AtlasNode.prototype._initWithTextureForWebGL; + cc.AtlasNode.prototype.draw = cc.AtlasNode.prototype._drawForWebGL; + cc.AtlasNode.prototype.setColor = cc.AtlasNode.prototype._setColorForWebGL; + cc.AtlasNode.prototype.setOpacity = cc.AtlasNode.prototype._setOpacityForWebGL; + cc.AtlasNode.prototype.getTexture = cc.AtlasNode.prototype._getTextureForWebGL; + cc.AtlasNode.prototype.setTexture = cc.AtlasNode.prototype._setTextureForWebGL; + cc.AtlasNode.prototype._calculateMaxItems = cc.AtlasNode.prototype._calculateMaxItemsForWebGL; +} else { + cc.AtlasNode.prototype.initWithTexture = cc.AtlasNode.prototype._initWithTextureForCanvas; + cc.AtlasNode.prototype.draw = cc.Node.prototype.draw; + cc.AtlasNode.prototype.setColor = cc.AtlasNode.prototype._setColorForCanvas; + cc.AtlasNode.prototype.setOpacity = cc.AtlasNode.prototype._setOpacityForCanvas; + cc.AtlasNode.prototype.getTexture = cc.AtlasNode.prototype._getTextureForCanvas; + cc.AtlasNode.prototype.setTexture = cc.AtlasNode.prototype._setTextureForCanvas; + cc.AtlasNode.prototype._calculateMaxItems = cc.AtlasNode.prototype._calculateMaxItemsForCanvas; +} /** creates a cc.AtlasNode with an Atlas file the width and height of each item and the quantity of items to render * @param {String} tile diff --git a/cocos2d/base_nodes/CCNode.js b/cocos2d/base_nodes/CCNode.js index 553ec00c9b..b535ca8829 100644 --- a/cocos2d/base_nodes/CCNode.js +++ b/cocos2d/base_nodes/CCNode.js @@ -47,12 +47,8 @@ cc.NODE_ON_EXIT = null; */ cc.s_globalOrderOfArrival = 1; - - -//cc.NodeBase = cc.Class.extend(/** @lends cc.Node# */{ - /**

cc.Node is the main element. Anything thats gets drawn or contains things that get drawn is a cc.Node.
- The most popular cc.Nodes are: cc.Scene, cc.Layer, cc.Sprite, cc.Menu. (WebGL implement)

+ The most popular cc.Nodes are: cc.Scene, cc.Layer, cc.Sprite, cc.Menu.

The main features of a cc.Node are:
- They can contain other cc.Node nodes (addChild, getChildByTag, removeChild, etc)
@@ -70,8 +66,6 @@ cc.s_globalOrderOfArrival = 1; - position
- scale (x, y)
- rotation (in degrees, clockwise)
- - cc.Camera (an interface to gluLookAt )
- - cc.GridBase (to do mesh transformations)
- anchor point
- size
- visible
@@ -92,7 +86,6 @@ cc.s_globalOrderOfArrival = 1; -# The node will be translated (position)
-# The node will be rotated (rotation)
-# The node will be scaled (scale)
- -# The node will be moved according to the camera values (camera)

Order in transformations with grid enabled
-# The node will be translated (position)
@@ -101,9 +94,6 @@ cc.s_globalOrderOfArrival = 1; -# The grid will capture the screen
-# The node will be moved according to the camera values (camera)
-# The grid will render the captured screen

- -

Camera:
- - Each node has a camera. By default it points to the center of the cc.Node.

* @class * @extends cc.Class * @example @@ -112,8 +102,7 @@ cc.s_globalOrderOfArrival = 1; * cc.Sprite.initWithImage = function(){ * }; */ -cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ - /// ---- common properties start ---- +cc.Node = cc.Class.extend(/** @lends cc.Node# */{ _zOrder:0, _vertexZ:0.0, @@ -160,20 +149,22 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ _componentContainer:null, _isTransitionFinished:false, + _rotationRadiansX:0, + _rotationRadiansY:0, + _initNode:function () { this._anchorPoint = cc.p(0, 0); this._anchorPointInPoints = cc.p(0, 0); this._contentSize = cc.size(0, 0); this._position = cc.p(0, 0); + this._children = []; var director = cc.Director.getInstance(); this._actionManager = director.getActionManager(); this._scheduler = director.getScheduler(); this._initializedNode = true; this._additionalTransform = cc.AffineTransformMakeIdentity(); - this._additionalTransformDirty = false; this._componentContainer = new cc.ComponentContainer(this); - this._isTransitionFinished = false; }, /** @@ -195,49 +186,56 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ if (!array || array.length === 0) return; - var i, len = array.length; + var i, len = array.length,node; var nodeCallbackType = cc.Node.StateCallbackType; switch (callbackType) { case nodeCallbackType.onEnter: for (i = 0; i < len; i++) { - if (array[i]) - array[i].onEnter(); + node = array[i]; + if (node) + node.onEnter(); } break; case nodeCallbackType.onExit: for (i = 0; i < len; i++) { - if (array[i]) - array[i].onExit(); + node = array[i]; + if (node) + node.onExit(); } break; case nodeCallbackType.onEnterTransitionDidFinish: for (i = 0; i < len; i++) { - if (array[i]) - array[i].onEnterTransitionDidFinish(); + node = array[i]; + if (node) + node.onEnterTransitionDidFinish(); } break; case nodeCallbackType.cleanup: for (i = 0; i < len; i++) { - if (array[i]) - array[i].cleanup(); + node = array[i]; + if (node) + node.cleanup(); } break; case nodeCallbackType.updateTransform: for (i = 0; i < len; i++) { - if (array[i]) - array[i].updateTransform(); + node = array[i]; + if (node) + node.updateTransform(); } break; case nodeCallbackType.onExitTransitionDidStart: for (i = 0; i < len; i++) { - if (array[i]) - array[i].onExitTransitionDidStart(); + node = array[i]; + if (node) + node.onExitTransitionDidStart(); } break; case nodeCallbackType.sortAllChildren: for (i = 0; i < len; i++) { - if (array[i]) - array[i].sortAllChildren(); + node = array[i]; + if (node) + node.sortAllChildren(); } break; default : @@ -249,8 +247,17 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ /** * set the dirty node */ - setNodeDirty:function () { - this._transformDirty = this._inverseDirty = true; + setNodeDirty:null, + + _setNodeDirtyForCanvas:function () { + this._setNodeDirtyForCache(); + if(this._transformDirty === false) + this._transformDirty = this._inverseDirty = true; + }, + + _setNodeDirtyForWebGL:function () { + if(this._transformDirty === false) + this._transformDirty = this._inverseDirty = true; }, /** @@ -384,8 +391,6 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ return this._rotationX; }, - _rotationRadiansX: 0, - _rotationRadiansY: 0, /** *

* Sets the rotation (angle) of the node in degrees.
@@ -395,11 +400,10 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ *

* @param {Number} newRotation The rotation of the node in degrees. */ - setRotation: function (newRotation) { + setRotation:function (newRotation) { this._rotationX = this._rotationY = newRotation; - this._rotationRadiansX = this._rotationX * (Math.PI / 180); - this._rotationRadiansY = this._rotationY * (Math.PI / 180); - + this._rotationRadiansX = this._rotationX * 0.017453292519943295; //(Math.PI / 180); + this._rotationRadiansY = this._rotationY * 0.017453292519943295; //(Math.PI / 180); this.setNodeDirty(); }, @@ -424,7 +428,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ */ setRotationX:function (rotationX) { this._rotationX = rotationX; - this._rotationRadiansX = this._rotationX * (Math.PI / 180); + this._rotationRadiansX = this._rotationX * 0.017453292519943295; //(Math.PI / 180); this.setNodeDirty(); }, @@ -448,7 +452,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ */ setRotationY:function (rotationY) { this._rotationY = rotationY; - this._rotationRadiansY = this._rotationY * (Math.PI / 180); + this._rotationRadiansY = this._rotationY * 0.017453292519943295; //(Math.PI / 180); this.setNodeDirty(); }, @@ -464,7 +468,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ /** * The scale factor of the node. 1.0 is the default scale factor. It modifies the X and Y scale at the same time. * @param {Number} scale or scaleX value - * @param {Number} scaleY + * @param {Number} [scaleY=] */ setScale:function (scale, scaleY) { this._scaleX = scale; @@ -473,8 +477,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ }, /** - * Gets the scale factor of the node, when X and Y have the same scale factor. - * @warning Assert when m_fScaleX != m_fScaleY. + * Returns the scale factor on X axis of this node * @return {Number} The scale factor on X axis. */ getScaleX:function () { @@ -494,8 +497,8 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ }, /** - * scaleY getter - * @return {Number} + * Returns the scale factor on Y axis of this node + * @return {Number} The scale factor on Y axis. */ getScaleY:function () { return this._scaleY; @@ -527,28 +530,21 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ * node.setPosition( cc.p(size.width/2, size.height/2) ) */ setPosition:function (newPosOrxValue, yValue) { + var locPosition = this._position; if (arguments.length == 2) { - this._position = new cc.Point(newPosOrxValue, yValue); - } else if (arguments.length == 1) { - this._position = new cc.Point(newPosOrxValue.x, newPosOrxValue.y); - } - this.setNodeDirty(); - }, - - _setPositionByValue:function (newPosOrxValue, yValue) { - if (arguments.length == 2) { - this._position.x = newPosOrxValue; - this._position.y = yValue; + locPosition.x = newPosOrxValue; + locPosition.y = yValue; } else if (arguments.length == 1) { - this._position.x = newPosOrxValue.x; - this._position.y = newPosOrxValue.y; + locPosition.x = newPosOrxValue.x; + locPosition.y = newPosOrxValue.y; } this.setNodeDirty(); }, /** *

Position (x,y) of the node in OpenGL coordinates. (0,0) is the left-bottom corner.

- * @return {cc.Point} + * @const + * @return {cc.Point} The position (x,y) of the node in OpenGL coordinates */ getPosition:function () { return cc.p(this._position.x, this._position.y); @@ -589,7 +585,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ * @return {Number} The amount of children. */ getChildrenCount:function () { - return this._children ? this._children.length : 0; + return this._children.length; }, /** @@ -604,8 +600,6 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ * } */ getChildren:function () { - if (!this._children) - this._children = []; return this._children; }, @@ -634,7 +628,8 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ * The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner.
* But you can use values higher than (1,1) and lower than (0,0) too.
* The default anchorPoint is (0.5,0.5), so it starts in the center of the node.

- * @return {cc.Point} The anchor point of node. + * @const + * @return {cc.Point} The anchor point of node. */ getAnchorPoint:function () { return cc.p(this._anchorPoint.x, this._anchorPoint.y); @@ -653,9 +648,13 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ * @param {cc.Point} point The anchor point of node. */ setAnchorPoint:function (point) { - if (!cc.pointEqualToPoint(point, this._anchorPoint)) { - this._anchorPoint = new cc.Point(point.x, point.y); - this._anchorPointInPoints = new cc.Point(this._contentSize.width * point.x, this._contentSize.height * point.y); + var locAnchorPoint = this._anchorPoint; + if (!cc.pointEqualToPoint(point, locAnchorPoint)) { + locAnchorPoint.x = point.x; + locAnchorPoint.y = point.y; + var locAPP = this._anchorPointInPoints, locSize = this._contentSize; + locAPP.x = locSize.width * point.x; + locAPP.y = locSize.height * point.y; this.setNodeDirty(); } }, @@ -664,6 +663,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ * The anchorPoint in absolute pixels.
* you can only read it. If you wish to modify it, use anchorPoint instead * @see getAnchorPoint() + * @const * @return {cc.Point} The anchor point in absolute pixels. */ getAnchorPointInPoints:function () { @@ -674,6 +674,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ *

The untransformed size of the node.
* The contentSize remains the same no matter the node is scaled or rotated.
* All nodes has a size. Layer and Scene has the same size of the screen.

+ * @const * @return {cc.Size} The untransformed size of the node. */ getContentSize:function () { @@ -690,9 +691,13 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ * @param {cc.Size} size The untransformed size of the node. */ setContentSize:function (size) { - if (!cc.sizeEqualToSize(size, this._contentSize)) { - this._contentSize = new cc.Size(size.width, size.height); - this._anchorPointInPoints = new cc.Point(this._contentSize.width * this._anchorPoint.x, this._contentSize.height * this._anchorPoint.y); + var locContentSize = this._contentSize; + if (!cc.sizeEqualToSize(size, locContentSize)) { + locContentSize.width = size.width; + locContentSize.height = size.height; + var locAPP = this._anchorPointInPoints, locAnchorPoint = this._anchorPoint; + locAPP.x = locContentSize.width * locAnchorPoint.x; + locAPP.y = locContentSize.height * locAnchorPoint.y; this.setNodeDirty(); } }, @@ -915,11 +920,12 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ * Returns a "local" axis aligned bounding box of the node.
* The returned box is relative only to its parent. * @note This method returns a temporaty variable, so it can't returns const CCRect& + * @const * @return {cc.Rect} */ getBoundingBox:function () { var rect = cc.rect(0, 0, this._contentSize.width, this._contentSize.height); - return cc.RectApplyAffineTransform(rect, this.nodeToParentTransform()); + return cc._RectApplyAffineTransformIn(rect, this.nodeToParentTransform()); }, /** @@ -934,17 +940,14 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.cleanup); }, - /** Node description + /** + * Gets the description string. It makes debugging easier. * @return {String} */ description:function () { return ""; }, - _childrenAlloc:function () { - this._children = []; - }, - // composition: GET /** * Gets a child from the container given its tag @@ -971,8 +974,8 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ *

If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately.

* * @param {cc.Node} child A child node - * @param {Number} zOrder Z order for drawing priority. Please refer to setZOrder(int) - * @param {Number} tag A interger to identify the node easily. Please refer to setTag(int) + * @param {Number} [zOrder=] Z order for drawing priority. Please refer to setZOrder(int) + * @param {Number} [tag=] A interger to identify the node easily. Please refer to setTag(int) */ addChild:function (child, zOrder, tag) { if (child === this) { @@ -985,16 +988,12 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ cc.Assert(child._parent === null, "child already added. It can't be added again"); return; } - var tempzOrder = (zOrder != null) ? zOrder : child.getZOrder(); - var tmptag = (tag != null) ? tag : child.getTag(); - child.setTag(tmptag); - - if (!this._children) - this._childrenAlloc(); - this._insertChild(child, tempzOrder); + var tmpzOrder = (zOrder != null) ? zOrder : child._zOrder; + child._tag = (tag != null) ? tag : child._tag; + this._insertChild(child, tmpzOrder); + child._parent = this; - child.setParent(this); if (this._running) { child.onEnter(); // prevent onEnterTransitionDidFinish to be called twice when a node is added in onEnter @@ -1023,7 +1022,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ * Removes this node itself from its parent node.
* If the node orphan, then nothing happens. * @deprecated - * @param {Boolean} cleanup true if all actions and callbacks on this node should be removed, false otherwise. + * @param {Boolean} cleanup true if all actions and callbacks on this node should be removed, false otherwise. */ removeFromParentAndCleanup:function (cleanup) { cc.log("removeFromParentAndCleanup is deprecated. Use removeFromParent instead"); @@ -1037,18 +1036,17 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ * to override this method

* * @param {cc.Node} child The child node which will be removed. - * @param {Boolean} cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise. + * @param {Boolean|null} [cleanup=null] true if all running actions and callbacks on the child node will be cleanup, false otherwise. */ removeChild:function (child, cleanup) { // explicit nil handling - if (this._children == null) + if (this._children.length === 0) return; if (cleanup == null) cleanup = true; - if (this._children.indexOf(child) > -1) { + if (this._children.indexOf(child) > -1) this._detachChild(child, cleanup); - } this.setNodeDirty(); }, @@ -1073,7 +1071,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ /** * Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter. * @deprecated - * @param {Boolean | null} cleanup + * @param {Boolean | null } cleanup */ removeAllChildrenWithCleanup:function (cleanup) { cc.log("removeAllChildrenWithCleanup is deprecated. Use removeAllChildren instead"); @@ -1143,26 +1141,14 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ */ _insertChild:function (child, z) { this._reorderChildDirty = true; - var __children = this._children; - var a = __children[__children.length - 1]; - if (!a || a.getZOrder() <= z) - __children.push(child); - else { - for (var i = 0; i < __children.length; i++) { - var node = __children[i]; - if (node && (node.getZOrder() > z )) { - this._children = cc.ArrayAppendObjectToIndex(__children, child, i); - break; - } - } - } + this._children.push(child); child._setZOrder(z); }, /** Reorders a child according to a new z value.
* The child MUST be already added. - * @param {cc.Node} child - * @param {Number} zOrder + * @param {cc.Node} child An already added child node. It MUST be already added. + * @param {Number} zOrder Z order for drawing priority. Please refer to setZOrder(int) */ reorderChild:function (child, zOrder) { cc.Assert(child != null, "Child must be non-nil"); @@ -1181,20 +1167,23 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ */ sortAllChildren:function () { if (this._reorderChildDirty) { - var i, j, length = this._children.length; - var localChildren = this._children; + var _children = this._children; + var i, j, length = _children.length,tempChild; + // insertion sort for (i = 0; i < length; i++) { - var tempItem = localChildren[i]; + var tempItem = _children[i]; j = i - 1; + tempChild = _children[j]; //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller - while (j >= 0 && ( tempItem._zOrder < localChildren[j]._zOrder || - ( tempItem._zOrder == localChildren[j]._zOrder && tempItem._orderOfArrival < localChildren[j]._orderOfArrival ))) { - localChildren[j + 1] = localChildren[j]; + while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder || + ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) { + _children[j + 1] = tempChild; j = j - 1; + tempChild = _children[j]; } - localChildren[j + 1] = tempItem; + _children[j + 1] = tempItem; } //don't need to check children recursively, that's done in visit of each child @@ -1380,7 +1369,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ * Schedules a custom selector.
* If the selector is already scheduled, then the interval parameter will be updated without scheduling it again. * - * @param {function} callback_fn + * @param {function} callback_fn A function wrapped as a selector * @param {Number} interval Tick interval in seconds. 0 means tick every frame. If interval = 0, it's recommended to use scheduleUpdate() instead. * @param {Number} repeat The selector will be excuted (repeat + 1) times, you can use kCCRepeatForever for tick infinitely. * @param {Number} delay The amount of time that the first tick will wait before execution. @@ -1513,7 +1502,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ }, /** - * Retrusn the world affine transform matrix. The matrix is in Pixels. + * Returns the world affine transform matrix. The matrix is in Pixels. * @return {cc.AffineTransform} */ nodeToWorldTransform:function () { @@ -1662,7 +1651,6 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ removeAllComponents:function(){ this._componentContainer.removeAll(); }, - /// ---- common properties end ---- _transform4x4:null, _stackMatrix:null, @@ -1670,8 +1658,19 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ _camera:null, _grid:null, - ctor:function () { + /** + * Constructor + */ + ctor: null, + + _ctorForCanvas: function () { + this._initNode(); + }, + + _ctorForWebGL: function () { this._initNode(); + + //WebGL var mat4 = new cc.kmMat4(); mat4.mat[2] = mat4.mat[3] = mat4.mat[6] = mat4.mat[7] = mat4.mat[8] = mat4.mat[9] = mat4.mat[11] = mat4.mat[14] = 0.0; mat4.mat[10] = mat4.mat[15] = 1.0; @@ -1682,13 +1681,48 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ /** * recursive method that visit its children and draw them + * @param {CanvasRenderingContext2D|WebGLRenderingContext} ctx */ - visit: function () { + visit:null, + + _visitForCanvas:function (ctx) { + // quick return if not visible + if (!this._visible) + return; + + //visit for canvas + var context = ctx || cc.renderContext, i; + var children = this._children,child; + context.save(); + this.transform(context); + var len = children.length; + if (len > 0) { + this.sortAllChildren(); + // draw children zOrder < 0 + for (i = 0; i < len; i++) { + child = children[i]; + if (child._zOrder < 0) + child.visit(context); + else + break; + } + this.draw(context); + for (; i < len; i++) { + children[i].visit(context); + } + } else + this.draw(context); + + this._orderOfArrival = 0; + context.restore(); + }, + + _visitForWebGL: function(){ // quick return if not visible if (!this._visible) return; var context = cc.renderContext, i, currentStack = cc.current_stack; - this._stackMatrix = this._stackMatrix || new cc.kmMat4(); + //cc.kmGLPushMatrixWitMat4(this._stackMatrix); //optimize performance for javascript currentStack.stack.push(currentStack.top); @@ -1734,15 +1768,18 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ /** * Performs OpenGL view-matrix transformation based on position, scale, rotation and other attributes. */ - transform:function () { + transform:null, + + _transformForCanvas: function (ctx) { + // transform for canvas + var context = ctx || cc.renderContext; + var t = this.nodeToParentTransform(); + context.transform(t.a, t.c, t.b, t.d, t.tx, -t.ty); + }, + + _transformForWebGL: function () { //optimize performance for javascript var t4x4 = this._transform4x4, topMat4 = cc.current_stack.top; - if(!t4x4){ - t4x4 = new cc.kmMat4(); - t4x4.mat[2] = t4x4.mat[3] = t4x4.mat[6] = t4x4.mat[7] = t4x4.mat[8] = t4x4.mat[9] = t4x4.mat[11] = t4x4.mat[14] = 0.0; - t4x4.mat[10] = t4x4.mat[15] = 1.0; - this._transform4x4 = t4x4; - } // Convert 3x3 into 4x4 matrix //cc.CGAffineToGL(this.nodeToParentTransform(), this._transform4x4.mat); @@ -1780,7 +1817,81 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ * The matrix is in Pixels. * @return {cc.AffineTransform} */ - nodeToParentTransform:function () { + nodeToParentTransform: null, + + _nodeToParentTransformForCanvas:function () { + if (!this._transform) + this._transform = {a:1, b:0, c:0, d:1, tx:0, ty:0}; + if (this._transformDirty) { + var t = this._transform;// quick reference + // base position + t.tx = this._position.x; + t.ty = this._position.y; + + // rotation Cos and Sin + var Cos = 1, Sin = 0; + if (this._rotationX) { + Cos = Math.cos(this._rotationRadiansX); + Sin = Math.sin(this._rotationRadiansX); + } + + // base abcd + t.a = t.d = Cos; + t.b = -Sin; + t.c = Sin; + + var lScaleX = this._scaleX, lScaleY = this._scaleY; + var appX = this._anchorPointInPoints.x, appY = this._anchorPointInPoints.y; + + // Firefox on Vista and XP crashes + // GPU thread in case of scale(0.0, 0.0) + var sx = (lScaleX < 0.000001 && lScaleX > -0.000001)? 0.000001 : lScaleX, + sy = (lScaleY < 0.000001 && lScaleY > -0.000001)? 0.000001 : lScaleY; + + // skew + if (this._skewX || this._skewY) { + // offset the anchorpoint + var skx = Math.tan(-this._skewX * Math.PI / 180); + var sky = Math.tan(-this._skewY * Math.PI / 180); + var xx = appY * skx * sx; + var yy = appX * sky * sy; + t.a = Cos + -Sin * sky; + t.b = Cos * skx + -Sin; + t.c = Sin + Cos * sky; + t.d = Sin * skx + Cos; + t.tx += Cos * xx + -Sin * yy; + t.ty += Sin * xx + Cos * yy; + } + + // scale + if (lScaleX !== 1 || lScaleY !== 1) { + t.a *= sx; + t.c *= sx; + t.b *= sy; + t.d *= sy; + } + + // adjust anchorPoint + t.tx += Cos * -appX * sx + -Sin * appY * sy; + t.ty -= Sin * -appX * sx + Cos * appY * sy; + + // if ignore anchorPoint + if (this._ignoreAnchorPointForPosition) { + t.tx += appX; + t.ty += appY; + } + + if (this._additionalTransformDirty) { + this._transform = cc.AffineTransformConcat(this._transform, this._additionalTransform); + this._additionalTransformDirty = false; + } + + this._transformDirty = false; + } + return this._transform; + }, + + _nodeToParentTransformForWebGL:function () { if (this._transformDirty) { // Translate values var x = this._position.x; @@ -1839,11 +1950,11 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ return this._transform; }, - /** - * set the dirty node - */ - setNodeDirty:function () { - this._transformDirty = this._inverseDirty = true; + _setNodeDirtyForCache:function () { + this._cacheDirty = true; + if (this._parent) { + this._parent._setNodeDirtyForCache(); + } }, /** @@ -1914,1852 +2025,89 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{ */ setGLServerState:function (state) { this._glServerState = state; + }, + + /** returns a "world" axis aligned bounding box of the node.
+ * @return {cc.Rect} + */ + getBoundingBoxToWorld:function () { + var rect = cc.rect(0, 0, this._contentSize.width, this._contentSize.height); + rect = cc.RectApplyAffineTransform(rect, this.nodeToWorldTransform()); + rect = cc.rect(0 | rect.x - 4, 0 | rect.y - 4, 0 | rect.width + 8, 0 | rect.height + 8); + //query child's BoundingBox + if (!this._children) + return rect; + + var locChildren = this._children; + for (var i = 0; i < locChildren.length; i++) { + var child = locChildren[i]; + if (child && child._visible) { + var childRect = child.getBoundingBoxToWorld(); + if (childRect) + rect = cc.rectUnion(rect, childRect); + } + } + return rect; } }); -/** - * cc.Node's state callback type - * @constant - * @type Number - */ -cc.NodeWebGL.StateCallbackType = {onEnter:1, onExit:2, cleanup:3, onEnterTransitionDidFinish:4, updateTransform:5, onExitTransitionDidStart:6, sortAllChildren:7}; +if(cc.Browser.supportWebGL){ + //WebGL + cc.Node.prototype.ctor = cc.Node.prototype._ctorForWebGL; + cc.Node.prototype.setNodeDirty = cc.Node.prototype._setNodeDirtyForWebGL; + cc.Node.prototype.visit = cc.Node.prototype._visitForWebGL; + cc.Node.prototype.transform = cc.Node.prototype._transformForWebGL; + cc.Node.prototype.nodeToParentTransform = cc.Node.prototype._nodeToParentTransformForWebGL; +}else{ + //Canvas + cc.Node.prototype.ctor = cc.Node.prototype._ctorForCanvas; + cc.Node.prototype.setNodeDirty = cc.Node.prototype._setNodeDirtyForCanvas; + cc.Node.prototype.visit = cc.Node.prototype._visitForCanvas; + cc.Node.prototype.transform = cc.Node.prototype._transformForCanvas; + cc.Node.prototype.nodeToParentTransform = cc.Node.prototype._nodeToParentTransformForCanvas; +} /** * allocates and initializes a node. * @constructs - * @return {cc.NodeWebGL} + * @return {cc.Node} * @example * // example - * var node = cc.NodeWebGL.create(); + * var node = cc.Node.create(); */ -cc.NodeWebGL.create = function () { - return new cc.NodeWebGL(); +cc.Node.create = function () { + return new cc.Node(); }; -/**

cc.Node is the main element. Anything thats gets drawn or contains things that get drawn is a cc.Node.
- The most popular cc.Nodes are: cc.Scene, cc.Layer, cc.Sprite, cc.Menu. (Canvas implement)

- -

The main features of a cc.Node are:
- - They can contain other cc.Node nodes (addChild, getChildByTag, removeChild, etc)
- - They can schedule periodic callback (schedule, unschedule, etc)
- - They can execute actions (runAction, stopAction, etc)

- -

Some cc.Node nodes provide extra functionality for them or their children.

- -

Subclassing a cc.Node usually means (one/all) of:
- - overriding init to initialize resources and schedule callbacks
- - create callbacks to handle the advancement of time
- - overriding draw to render the node

- -

Features of cc.Node:
- - position
- - scale (x, y)
- - rotation (in degrees, clockwise)
- - anchor point
- - size
- - visible
- - z-order
- - openGL z position

+/** + * cc.Node's state callback type + * @constant + * @type Number + */ +cc.Node.StateCallbackType = {onEnter:1, onExit:2, cleanup:3, onEnterTransitionDidFinish:4, updateTransform:5, onExitTransitionDidStart:6, sortAllChildren:7}; -

Default values:
- - rotation: 0
- - position: (x=0,y=0)
- - scale: (x=1,y=1)
- - contentSize: (x=0,y=0)
- - anchorPoint: (x=0,y=0)

- -

Limitations:
- - A cc.Node is a "void" object. It doesn't have a texture

- -

Order in transformations with grid disabled
- -# The node will be translated (position)
- -# The node will be rotated (rotation)
- -# The node will be scaled (scale)
- -

Order in transformations with grid enabled
- -# The node will be translated (position)
- -# The node will be rotated (rotation)
- -# The node will be scaled (scale)
- -# The grid will capture the screen
- -# The node will be moved according to the camera values (camera)
- -# The grid will render the captured screen

- * @class - * @extends cc.Class - * @example - * // example - * cc.Sprite = cc.Node.extend({}); - * cc.Sprite.initWithImage = function(){ - * }; - */ -cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{ - /// ---- common properties start ---- - _zOrder:0, - _vertexZ:0.0, - - _rotationX:0, - _rotationY:0.0, - _scaleX:1.0, - _scaleY:1.0, - _position:null, - _skewX:0.0, - _skewY:0.0, - // children (lazy allocs), - _children:null, - // lazy alloc, - _visible:true, - _anchorPoint:null, - _anchorPointInPoints:null, - _contentSize:null, - _running:false, - _parent:null, - // "whole screen" objects. like Scenes and Layers, should set _ignoreAnchorPointForPosition to true - _ignoreAnchorPointForPosition:false, - _tag:cc.NODE_TAG_INVALID, - // userData is always inited as nil - _userData:null, - _userObject:null, - _transformDirty:true, - _inverseDirty:true, - _cacheDirty:true, - _transformGLDirty:null, - _transform:null, - _inverse:null, - - //since 2.0 api - _reorderChildDirty:false, - _shaderProgram:null, - _orderOfArrival:0, - - _actionManager:null, - _scheduler:null, - - _initializedNode:false, - _additionalTransformDirty:false, - _additionalTransform:null, - _componentContainer:null, - _isTransitionFinished:false, - - _initNode:function () { - this._anchorPoint = cc.p(0, 0); - this._anchorPointInPoints = cc.p(0, 0); - this._contentSize = cc.size(0, 0); - this._position = cc.p(0, 0); - - var director = cc.Director.getInstance(); - this._actionManager = director.getActionManager(); - this._scheduler = director.getScheduler(); - this._initializedNode = true; - this._additionalTransform = cc.AffineTransformMakeIdentity(); - this._additionalTransformDirty = false; - this._componentContainer = new cc.ComponentContainer(this); - this._isTransitionFinished = false; - }, - - /** - * Initializes the instance of cc.Node - * @returns {boolean} Whether the initialization was successful. - */ - init:function () { - if (this._initializedNode === false) - this._initNode(); - return true; - }, - - /** - * @param {Array} array - * @param {cc.Node.StateCallbackType} callbackType - * @private - */ - _arrayMakeObjectsPerformSelector:function (array, callbackType) { - if (!array || array.length === 0) - return; - - var i, len = array.length; - var nodeCallbackType = cc.Node.StateCallbackType; - switch (callbackType) { - case nodeCallbackType.onEnter: - for (i = 0; i < len; i++) { - if (array[i]) - array[i].onEnter(); - } - break; - case nodeCallbackType.onExit: - for (i = 0; i < len; i++) { - if (array[i]) - array[i].onExit(); - } - break; - case nodeCallbackType.onEnterTransitionDidFinish: - for (i = 0; i < len; i++) { - if (array[i]) - array[i].onEnterTransitionDidFinish(); - } - break; - case nodeCallbackType.cleanup: - for (i = 0; i < len; i++) { - if (array[i]) - array[i].cleanup(); - } - break; - case nodeCallbackType.updateTransform: - for (i = 0; i < len; i++) { - if (array[i]) - array[i].updateTransform(); - } - break; - case nodeCallbackType.onExitTransitionDidStart: - for (i = 0; i < len; i++) { - if (array[i]) - array[i].onExitTransitionDidStart(); - } - break; - case nodeCallbackType.sortAllChildren: - for (i = 0; i < len; i++) { - if (array[i]) - array[i].sortAllChildren(); - } - break; - default : - throw "Unknown callback function"; - break; - } - }, - - /** - * set the dirty node - */ - setNodeDirty:function () { - this._transformDirty = this._inverseDirty = true; - }, - - /** - *

get the skew degrees in X
- * The X skew angle of the node in degrees.
- * This angle describes the shear distortion in the X direction.
- * Thus, it is the angle between the Y axis and the left edge of the shape
- * The default skewX angle is 0. Positive values distort the node in a CW direction.
- *

- * @return {Number} The X skew angle of the node in degrees. - */ - getSkewX:function () { - return this._skewX; - }, - - /** - *

- * Changes the X skew angle of the node in degrees.
- *
- * This angle describes the shear distortion in the X direction.
- * Thus, it is the angle between the Y axis and the left edge of the shape
- * The default skewX angle is 0. Positive values distort the node in a CW direction. - *

- * @param {Number} newSkewX The X skew angle of the node in degrees. - */ - setSkewX:function (newSkewX) { - this._skewX = newSkewX; - this.setNodeDirty(); - }, - - /** - *

get the skew degrees in Y
- * The Y skew angle of the node in degrees.
- * This angle describes the shear distortion in the Y direction.
- * Thus, it is the angle between the X axis and the bottom edge of the shape
- * The default skewY angle is 0. Positive values distort the node in a CCW direction.
- *

- * @return {Number} The Y skew angle of the node in degrees. - */ - getSkewY:function () { - return this._skewY; - }, - - /** - *

- * Changes the Y skew angle of the node in degrees. - * - * This angle describes the shear distortion in the Y direction. - * Thus, it is the angle between the X axis and the bottom edge of the shape - * The default skewY angle is 0. Positive values distort the node in a CCW direction. - *

- * @param {Number} newSkewY The Y skew angle of the node in degrees. - */ - setSkewY:function (newSkewY) { - this._skewY = newSkewY; - this.setNodeDirty(); - }, - - /** - * zOrder getter - * @return {Number} - */ - getZOrder:function () { - return this._zOrder; - }, - - /** - *

- * Sets the z order which stands for the drawing order
- *
- * This is an internal method. Don't call it outside the framework.
- * The difference between setZOrder(int) and _setOrder(int) is:
- * - _setZOrder(int) is a pure setter for m_nZOrder memeber variable
- * - setZOrder(int) firstly changes m_nZOrder, then recorder this node in its parent's chilren array. - *

- * @param {Number} z - * @private - */ - _setZOrder:function (z) { - this._zOrder = z; - }, - - /** - *

- * Sets the Z order which stands for the drawing order, and reorder this node in its parent's children array.
- *
- * The Z order of node is relative to its "brothers": children of the same parent.
- * It's nothing to do with OpenGL's z vertex. This one only affects the draw order of nodes in cocos2d.
- * The larger number it is, the later this node will be drawn in each message loop.
- * Please refer to setVertexZ(float) for the difference. - *

- * @param {Number} z Z order of this node. - */ - setZOrder:function (z) { - this._setZOrder(z); - if (this._parent) - this._parent.reorderChild(this, z); - }, - - /** - * Gets WebGL Z vertex of this node. - * @return {Number} WebGL Z vertex of this node - */ - getVertexZ:function () { - return this._vertexZ; - }, - - /** - *

- * Sets the real WebGL Z vertex.
- *
- * Differences between openGL Z vertex and cocos2d Z order:
- * - OpenGL Z modifies the Z vertex, and not the Z order in the relation between parent-children
- * - OpenGL Z might require to set 2D projection
- * - cocos2d Z order works OK if all the nodes uses the same openGL Z vertex. eg: vertexZ = 0
- *
- * @warning Use it at your own risk since it might break the cocos2d parent-children z order - *

- * @param {Number} Var - */ - setVertexZ:function (Var) { - this._vertexZ = Var; - }, - - /** - * The rotation (angle) of the node in degrees. 0 is the default rotation angle. Positive values rotate node CW. - * @return {Number} The rotation of the node in degrees. - */ - getRotation:function () { - cc.Assert(this._rotationX == this._rotationY, "CCNode#rotation. RotationX != RotationY. Don't know which one to return"); - return this._rotationX; - }, - - _rotationRadiansX:0, - _rotationRadiansY:0, - /** - *

- * Sets the rotation (angle) of the node in degrees.
- *
- * 0 is the default rotation angle.
- * Positive values rotate node clockwise, and negative values for anti-clockwise. - *

- * @param {Number} newRotation The rotation of the node in degrees. - */ - setRotation:function (newRotation) { - this._rotationX = this._rotationY = newRotation; - this._rotationRadiansX = this._rotationX * 0.017453292519943295; //(Math.PI / 180); - this._rotationRadiansY = this._rotationY * 0.017453292519943295; //(Math.PI / 180); - - this.setNodeDirty(); - }, - - /** - * The rotation (angle) of the node in degrees. 0 is the default rotation angle.
- * Positive values rotate node CW. It only modifies the X rotation performing a horizontal rotational skew . - * (support only in WebGl rendering mode) - * @return {Number} The X rotation in degrees. - */ - getRotationX:function () { - return this._rotationX; - }, - - /** - *

- * Sets the X rotation (angle) of the node in degrees which performs a horizontal rotational skew.
- *
- * 0 is the default rotation angle.
- * Positive values rotate node clockwise, and negative values for anti-clockwise. - *

- * @param {Number} rotationX The X rotation in degrees which performs a horizontal rotational skew. - */ - setRotationX:function (rotationX) { - this._rotationX = rotationX; - this._rotationRadiansX = this._rotationX * 0.017453292519943295; //(Math.PI / 180); - this.setNodeDirty(); - }, - - /** - * The rotation (angle) of the node in degrees. 0 is the default rotation angle.
- * Positive values rotate node CW. It only modifies the Y rotation performing a vertical rotational skew . - * @return {Number} The Y rotation in degrees. - */ - getRotationY:function () { - return this._rotationY; - }, - - /** - *

- * Sets the Y rotation (angle) of the node in degrees which performs a vertical rotational skew.
- *
- * 0 is the default rotation angle.
- * Positive values rotate node clockwise, and negative values for anti-clockwise. - *

- * @param rotationY The Y rotation in degrees. - */ - setRotationY:function (rotationY) { - this._rotationY = rotationY; - this._rotationRadiansY = this._rotationY * 0.017453292519943295; //(Math.PI / 180); - this.setNodeDirty(); - }, - - /** Get the scale factor of the node. - * @warning: Assert when _scaleX != _scaleY. - * @return {Number} - */ - getScale:function () { - cc.Assert(this._scaleX == this._scaleY, "cc.Node#scale. ScaleX != ScaleY. Don't know which one to return"); - return this._scaleX; - }, - - /** - * The scale factor of the node. 1.0 is the default scale factor. It modifies the X and Y scale at the same time. - * @param {Number} scale or scaleX value - * @param {Number} scaleY - */ - setScale:function (scale, scaleY) { - this._scaleX = scale; - this._scaleY = scaleY || scale; - this.setNodeDirty(); - }, - - /** - * Returns the scale factor on X axis of this node - * @return {Number} The scale factor on X axis. - */ - getScaleX:function () { - return this._scaleX; - }, - - /** - *

- * Changes the scale factor on X axis of this node
- * The deafult value is 1.0 if you haven't changed it before - *

- * @param {Number} newScaleX The scale factor on X axis. - */ - setScaleX:function (newScaleX) { - this._scaleX = newScaleX; - this.setNodeDirty(); - }, - - /** - * Returns the scale factor on Y axis of this node - * @return {Number} The scale factor on Y axis. - */ - getScaleY:function () { - return this._scaleY; - }, - - /** - *

- * Changes the scale factor on Y axis of this node
- * The Default value is 1.0 if you haven't changed it before. - *

- * @param {Number} newScaleY The scale factor on Y axis. - */ - setScaleY:function (newScaleY) { - this._scaleY = newScaleY; - this.setNodeDirty(); - }, - - /** - *

- * Changes the position (x,y) of the node in OpenGL coordinates - * Usually we use ccp(x,y) to compose CCPoint object. - * The original point (0,0) is at the left-bottom corner of screen. - * and Passing two numbers (x,y) is much efficient than passing CCPoint object. - *

- * @param {cc.Point|Number} newPosOrxValue The position (x,y) of the node in coordinates or X coordinate for position - * @param {Number} yValue Y coordinate for position - * @example - * var size = cc.Director.getInstance().getWinSize(); - * node.setPosition( cc.p(size.width/2, size.height/2) ) - */ - setPosition:function (newPosOrxValue, yValue) { - if (arguments.length === 2) { - this._position = new cc.Point(newPosOrxValue, yValue); - } else if (arguments.length === 1) { - this._position = new cc.Point(newPosOrxValue.x, newPosOrxValue.y); - } - this.setNodeDirty(); - }, - - _setPositionByValue:function (newPosOrxValue, yValue) { - if (arguments.length === 2) { - this._position.x = newPosOrxValue; - this._position.y = yValue; - } else if (arguments.length === 1) { - this._position.x = newPosOrxValue.x; - this._position.y = newPosOrxValue.y; - } - this.setNodeDirty(); - }, - - /** - *

Position (x,y) of the node in OpenGL coordinates. (0,0) is the left-bottom corner.

- * @return {cc.Point} The position (x,y) of the node in OpenGL coordinates - */ - getPosition:function () { - return cc.p(this._position.x, this._position.y); - }, - - /** - * @return {Number} - */ - getPositionX:function () { - return this._position.x; - }, - - /** - * @param {Number} x - */ - setPositionX:function (x) { - this._position.x = x; - this.setNodeDirty(); - }, - - /** - * @return {Number} - */ - getPositionY:function () { - return this._position.y; - }, - - /** - * @param {Number} y - */ - setPositionY:function (y) { - this._position.y = y; - this.setNodeDirty(); - }, - - /** - * Get the amount of children. - * @return {Number} The amount of children. - */ - getChildrenCount:function () { - return this._children ? this._children.length : 0; - }, - - /** - * Return an array of children
- * Composing a "tree" structure is a very important feature of CCNode - * @return {Array} An array of children - * @example - * //This sample code traverses all children nodes, and set theie position to (0,0) - * var allChildren = parent.getChildren(); - * for(var i = 0; i< allChildren.length; i++) { - * allChildren[i].setPosition(0,0); - * } - */ - getChildren:function () { - if (!this._children) - this._children = []; - return this._children; - }, - - /** - * Determines if the node is visible - * @see setVisible(bool) - * @return {Boolean} true if the node is visible, false if the node is hidden. - */ - isVisible:function () { - return this._visible; - }, - - /** - * Sets whether the node is visible
- * The default value is true, a node is default to visible - * @param {Boolean} Var true if the node is visible, false if the node is hidden. - */ - setVisible:function (Var) { - this._visible = Var; - this.setNodeDirty(); - }, - - /** - *

anchorPoint is the point around which all transformations and positioning manipulations take place.
- * It's like a pin in the node where it is "attached" to its parent.
- * The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner.
- * But you can use values higher than (1,1) and lower than (0,0) too.
- * The default anchorPoint is (0.5,0.5), so it starts in the center of the node.

- * @return {cc.Point} The anchor point of node. - */ - getAnchorPoint:function () { - return cc.p(this._anchorPoint.x, this._anchorPoint.y); - }, - - /** - *

- * Sets the anchor point in percent.
- *
- * anchorPoint is the point around which all transformations and positioning manipulations take place.
- * It's like a pin in the node where it is "attached" to its parent.
- * The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner.
- * But you can use values higher than (1,1) and lower than (0,0) too.
- * The default anchorPoint is (0.5,0.5), so it starts in the center of the node. - *

- * @param {cc.Point} point The anchor point of node. - */ - setAnchorPoint:function (point) { - if (!cc.pointEqualToPoint(point, this._anchorPoint)) { - this._anchorPoint = new cc.Point(point.x, point.y); - this._anchorPointInPoints = new cc.Point(this._contentSize.width * point.x, this._contentSize.height * point.y); - this.setNodeDirty(); - } - }, - - /** - * The anchorPoint in absolute pixels.
- * you can only read it. If you wish to modify it, use anchorPoint instead - * @see getAnchorPoint() - * @return {cc.Point} The anchor point in absolute pixels. - */ - getAnchorPointInPoints:function () { - return cc.p(this._anchorPointInPoints.x, this._anchorPointInPoints.y); - }, - - /** - *

The untransformed size of the node.
- * The contentSize remains the same no matter the node is scaled or rotated.
- * All nodes has a size. Layer and Scene has the same size of the screen.

- * @return {cc.Size} The untransformed size of the node. - */ - getContentSize:function () { - return cc.size(this._contentSize.width, this._contentSize.height); - }, - - /** - *

- * Sets the untransformed size of the node.
- *
- * The contentSize remains the same no matter the node is scaled or rotated.
- * All nodes has a size. Layer and Scene has the same size of the screen. - *

- * @param {cc.Size} size The untransformed size of the node. - */ - setContentSize:function (size) { - if (!cc.sizeEqualToSize(size, this._contentSize)) { - this._contentSize = new cc.Size(size.width, size.height); - this._anchorPointInPoints = new cc.Point(this._contentSize.width * this._anchorPoint.x, this._contentSize.height * this._anchorPoint.y); - this.setNodeDirty(); - } - }, - - /** - *

- * Returns whether or not the node accepts event callbacks.
- * Running means the node accept event callbacks like onEnter(), onExit(), update() - *

- * @return {Boolean} Whether or not the node is running. - */ - isRunning:function () { - return this._running; - }, - - /** - * Returns a pointer to the parent node - * @return {cc.Node} A pointer to the parnet node - */ - getParent:function () { - return this._parent; - }, - - /** - * Sets the parent node - * @param {cc.Node} Var A pointer to the parnet node - */ - setParent:function (Var) { - this._parent = Var; - }, - - /** - * Gets whether the anchor point will be (0,0) when you position this node. - * @see ignoreAnchorPointForPosition(bool) - * @return {Boolean} true if the anchor point will be (0,0) when you position this node. - */ - isIgnoreAnchorPointForPosition:function () { - return this._ignoreAnchorPointForPosition; - }, - - /** - *

- * Sets whether the anchor point will be (0,0) when you position this node.
- *
- * This is an internal method, only used by CCLayer and CCScene. Don't call it outside framework.
- * The default value is false, while in CCLayer and CCScene are true - *

- * @param {Boolean} newValue true if anchor point will be (0,0) when you position this node - */ - ignoreAnchorPointForPosition:function (newValue) { - if (newValue != this._ignoreAnchorPointForPosition) { - this._ignoreAnchorPointForPosition = newValue; - this.setNodeDirty(); - } - }, - - /** - * Returns a tag that is used to identify the node easily. - * - * @return {Number} A interger that identifies the node. - * @example - * //You can set tags to node then identify them easily. - * // set tags - * node1.setTag(TAG_PLAYER); - * node2.setTag(TAG_MONSTER); - * node3.setTag(TAG_BOSS); - * parent.addChild(node1); - * parent.addChild(node2); - * parent.addChild(node3); - * // identify by tags - * var allChildren = parent.getChildren(); - * for(var i = 0; i < allChildren.length; i++){ - * switch(node.getTag()) { - * case TAG_PLAYER: - * break; - * case TAG_MONSTER: - * break; - * case TAG_BOSS: - * break; - * } - * } - */ - getTag:function () { - return this._tag; - }, - - /** - * Changes the tag that is used to identify the node easily.
- * Please refer to getTag for the sample code. - * @param {Number} Var A interger that indentifies the node. - */ - setTag:function (Var) { - this._tag = Var; - }, - - /** - *

- * Returns a custom user data pointer
- * You can set everything in UserData pointer, a data block, a structure or an object. - *

- * @return {object} A custom user data pointer - */ - getUserData:function () { - return this._userData; - }, - - /** - *

- * Sets a custom user data pointer
- * You can set everything in UserData pointer, a data block, a structure or an object, etc. - *

- * @warning Don't forget to relfease the memroy manually,especially before you change this data pointer, and before this node is autoreleased. - * @param {object} Var A custom user data - */ - setUserData:function (Var) { - this._userData = Var; - }, - - /** - * Returns a user assigned CCObject.
- * Similar to userData, but instead of holding a void* it holds an id - * @return {object} A user assigned CCObject - */ - getUserObject:function () { - return this._userObject; - }, - - /** - *

- * Returns a user assigned CCObject
- * Similar to UserData, but instead of holding a void* it holds an object.
- * The UserObject will be retained once in this method, and the previous UserObject (if existed) will be relese.
- * The UserObject will be released in CCNode's destructure. - *

- * @param {object} newValue A user assigned CCObject - */ - setUserObject:function (newValue) { - if (this._userObject != newValue) { - this._userObject = newValue; - } - }, - - - /** - * Returns the arrival order, indecates which children is added previously. - * @return {Number} The arrival order. - */ - getOrderOfArrival:function () { - return this._orderOfArrival; - }, - - /** - *

- * Sets the arrival order when this node has a same ZOrder with other children.
- *
- * A node which called addChild subsequently will take a larger arrival order,
- * If two children have the same Z order, the child with larger arrival order will be drawn later. - *

- * @warning This method is used internally for zOrder sorting, don't change this manually - * @param {Number} Var The arrival order. - */ - setOrderOfArrival:function (Var) { - this._orderOfArrival = Var; - }, - - /** - *

Gets the CCActionManager object that is used by all actions.
- * (IMPORTANT: If you set a new cc.ActionManager, then previously created actions are going to be removed.)

- * @see setActionManager() - * @return {cc.ActionManager} A CCActionManager object. - */ - getActionManager:function () { - if (!this._actionManager) { - this._actionManager = cc.Director.getInstance().getActionManager(); - } - return this._actionManager; - }, - - /** - *

Sets the cc.ActionManager object that is used by all actions.

- * @warning If you set a new CCActionManager, then previously created actions will be removed. - * @param {cc.ActionManager} actionManager A CCActionManager object that is used by all actions. - */ - setActionManager:function (actionManager) { - if (this._actionManager != actionManager) { - this.stopAllActions(); - this._actionManager = actionManager; - } - }, - - /** - *

- * cc.Scheduler used to schedule all "updates" and timers.
- * IMPORTANT: If you set a new cc.Scheduler, then previously created timers/update are going to be removed. - *

- * @return {cc.Scheduler} A CCScheduler object. - */ - getScheduler:function () { - if (!this._scheduler) { - this._scheduler = cc.Director.getInstance().getScheduler(); - } - return this._scheduler; - }, - - /** - *

- * Sets a CCScheduler object that is used to schedule all "updates" and timers.
- *

- * @warning If you set a new CCScheduler, then previously created timers/update are going to be removed. - * @param scheduler A cc.Shdeduler object that is used to schedule all "update" and timers. - */ - setScheduler:function (scheduler) { - if (this._scheduler != scheduler) { - this.unscheduleAllCallbacks(); - this._scheduler = scheduler; - } - }, - - /** - * Returns a "local" axis aligned bounding box of the node.
- * The returned box is relative only to its parent. - * @note This method returns a temporaty variable, so it can't returns const CCRect& - * @return {cc.Rect} - */ - getBoundingBox:function () { - var rect = cc.rect(0, 0, this._contentSize.width, this._contentSize.height); - return cc.RectApplyAffineTransform(rect, this.nodeToParentTransform()); - }, - - /** - * Stops all running actions and schedulers - */ - cleanup:function () { - // actions - this.stopAllActions(); - this.unscheduleAllCallbacks(); - - // timers - this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.cleanup); - }, - - /** - * Gets the description string. It makes debugging easier. - * @return {String} - */ - description:function () { - return ""; - }, - - _childrenAlloc:function () { - this._children = []; - }, - - // composition: GET - /** - * Gets a child from the container given its tag - * @param {Number} aTag An identifier to find the child node. - * @return {cc.Node} a CCNode object whose tag equals to the input parameter - */ - getChildByTag:function (aTag) { - //cc.Assert(aTag != cc.NODE_TAG_INVALID, "Invalid tag"); - var __children = this._children; - if (__children != null) { - for (var i = 0; i < __children.length; i++) { - var node = __children[i]; - if (node && node._tag == aTag) - return node; - } - } - //throw "not found"; - return null; - }, - // composition: ADD - - /**

"add" logic MUST only be on this method

- * - *

If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately.

- * - * @param {cc.Node} child A child node - * @param {Number} zOrder Z order for drawing priority. Please refer to setZOrder(int) - * @param {Number} tag A interger to identify the node easily. Please refer to setTag(int) - */ - addChild:function (child, zOrder, tag) { - if (child === this) { - console.warn('cc.Node.addChild: An Node can\'t be added as a child of itself.'); - return; - } - - cc.Assert(child != null, "Argument must be non-nil"); - if (child._parent !== null) { - cc.Assert(child._parent === null, "child already added. It can't be added again"); - return; - } - var tempzOrder = (zOrder != null) ? zOrder : child.getZOrder(); - var tmptag = (tag != null) ? tag : child.getTag(); - child.setTag(tmptag); - - if (!this._children) - this._childrenAlloc(); - - this._insertChild(child, tempzOrder); - - child.setParent(this); - if (this._running) { - child.onEnter(); - // prevent onEnterTransitionDidFinish to be called twice when a node is added in onEnter - if(this._isTransitionFinished) - child.onEnterTransitionDidFinish(); - } - }, - - // composition: REMOVE - /** - * Remove itself from its parent node. If cleanup is true, then also remove all actions and callbacks.
- * If the cleanup parameter is not passed, it will force a cleanup.
- * If the node orphan, then nothing happens. - * @param {Boolean} cleanup - * @see removeFromParentAndCleanup(bool) - */ - removeFromParent:function (cleanup) { - if (this._parent) { - if (cleanup == null) - cleanup = true; - this._parent.removeChild(this, cleanup); - } - }, - - /** - * Remove itself from its parent node. - * @deprecated - * @param {Boolean} cleanup - */ - removeFromParentAndCleanup:function (cleanup) { - cc.log("removeFromParentAndCleanup is deprecated. Use removeFromParent instead"); - this.removeFromParent(cleanup); - }, - - /**

Removes a child from the container. It will also cleanup all running actions depending on the cleanup parameter.

- * If the cleanup parameter is not passed, it will force a cleanup.
- *

"remove" logic MUST only be on this method
- * If a class wants to extend the 'removeChild' behavior it only needs
- * to override this method

- * - * @param {cc.Node} child The child node which will be removed. - * @param {Boolean} cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise. - */ - removeChild:function (child, cleanup) { - // explicit nil handling - if (this._children == null) - return; - - if (cleanup == null) - cleanup = true; - if (this._children.indexOf(child) > -1) { - this._detachChild(child, cleanup); - } - - this.setNodeDirty(); - }, - - /** - * Removes a child from the container by tag value. It will also cleanup all running actions depending on the cleanup parameter. - * If the cleanup parameter is not passed, it will force a cleanup.
- * @param {Number} tag An integer number that identifies a child node - * @param {Boolean} cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise. - * @see removeChildByTag(int, bool) - */ - removeChildByTag:function (tag, cleanup) { - cc.Assert(tag != cc.NODE_TAG_INVALID, "Invalid tag"); - - var child = this.getChildByTag(tag); - if (child == null) - cc.log("cocos2d: removeChildByTag: child not found!"); - else - this.removeChild(child, cleanup); - }, - - /** - * Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter. - * @deprecated - * @param {Boolean | null } cleanup - */ - removeAllChildrenWithCleanup:function (cleanup) { - cc.log("removeAllChildrenWithCleanup is deprecated. Use removeAllChildren instead"); - this.removeAllChildren(cleanup); - }, - - /** - * Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter.
- * If the cleanup parameter is not passed, it will force a cleanup.
- * @param {Boolean | null } cleanup true if all running actions on all children nodes should be cleanup, false oterwise. - */ - removeAllChildren:function (cleanup) { - // not using detachChild improves speed here - var __children = this._children; - if (__children != null) { - if (cleanup == null) - cleanup = true; - for (var i = 0; i < __children.length; i++) { - var node = __children[i]; - if (node) { - // IMPORTANT: - // -1st do onExit - // -2nd cleanup - if (this._running) { - node.onExitTransitionDidStart(); - node.onExit(); - } - if (cleanup) - node.cleanup(); - // set parent nil at the end - node.setParent(null); - } - } - this._children.length = 0; - } - }, - - /** - * @param {cc.Node} child - * @param {Boolean} doCleanup - * @private - */ - _detachChild:function (child, doCleanup) { - // IMPORTANT: - // -1st do onExit - // -2nd cleanup - if (this._running) { - child.onExitTransitionDidStart(); - child.onExit(); - } - - // If you don't do cleanup, the child's actions will not get removed and the - // its scheduledSelectors_ dict will not get released! - if (doCleanup) - child.cleanup(); - - // set parent nil at the end - child.setParent(null); - - cc.ArrayRemoveObject(this._children, child); - }, - - /** helper used by reorderChild & add - * @param {cc.Node} child - * @param {Number} z - * @private - */ - _insertChild:function (child, z) { - this._reorderChildDirty = true; - var __children = this._children; - var a = __children[__children.length - 1]; - if (!a || a.getZOrder() <= z) - __children.push(child); - else { - for (var i = 0; i < __children.length; i++) { - var node = __children[i]; - if (node && (node.getZOrder() > z )) { - this._children = cc.ArrayAppendObjectToIndex(__children, child, i); - break; - } - } - } - child._setZOrder(z); - }, - - /** Reorders a child according to a new z value.
- * The child MUST be already added. - * @param {cc.Node} child An already added child node. It MUST be already added. - * @param {Number} zOrder Z order for drawing priority. Please refer to setZOrder(int) - */ - reorderChild:function (child, zOrder) { - cc.Assert(child != null, "Child must be non-nil"); - this._reorderChildDirty = true; - child.setOrderOfArrival(cc.s_globalOrderOfArrival++); - child._setZOrder(zOrder); - this.setNodeDirty(); - }, - - /** - *

- * Sorts the children array once before drawing, instead of every time when a child is added or reordered.
- * This appraoch can improves the performance massively. - *

- * @note Don't call this manually unless a child added needs to be removed in the same frame - */ - sortAllChildren:function () { - if (this._reorderChildDirty) { - var i, j, length = this._children.length; - - // insertion sort - for (i = 0; i < length; i++) { - var tempItem = this._children[i]; - j = i - 1; - - //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller - while (j >= 0 && ( tempItem._zOrder < this._children[j]._zOrder || - ( tempItem._zOrder == this._children[j]._zOrder && tempItem._orderOfArrival < this._children[j]._orderOfArrival ))) { - this._children[j + 1] = this._children[j]; - j = j - 1; - } - this._children[j + 1] = tempItem; - } - - //don't need to check children recursively, that's done in visit of each child - this._reorderChildDirty = false; - } - }, - - // draw - /**

Override this method to draw your own node.
- * The following GL states will be enabled by default:
- - glEnableClientState(GL_VERTEX_ARRAY);
- - glEnableClientState(GL_COLOR_ARRAY);
- - glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- - glEnable(GL_TEXTURE_2D);

- -

AND YOU SHOULD NOT DISABLE THEM AFTER DRAWING YOUR NODE

- -

But if you enable any other GL state, you should disable it after drawing your node.

- * @param {CanvasContext} ctx - */ - draw:function (ctx) { - //cc.Assert(0); - // override me - // Only use- this function to draw your staff. - // DON'T draw your stuff outside this method - }, - - /** performs OpenGL view-matrix transformation of it's ancestors.
- * Generally the ancestors are already transformed, but in certain cases (eg: attaching a FBO)
- * it's necessary to transform the ancestors again. - */ - transformAncestors:function () { - if (this._parent != null) { - this._parent.transformAncestors(); - this._parent.transform(); - } - }, - - //scene managment - /** - *

- * Event callback that is invoked every time when CCNode enters the 'stage'.
- * If the CCNode enters the 'stage' with a transition, this event is called when the transition starts.
- * During onEnter you can't access a "sister/brother" node.
- * If you override onEnter, you shall call its parent's one, e.g., CCNode::onEnter(). - *

- */ - onEnter:function () { - this._isTransitionFinished = false; - this._running = true;//should be running before resumeSchedule - this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.onEnter); - this.resumeSchedulerAndActions(); - }, - - /** - *

- * Event callback that is invoked when the CCNode enters in the 'stage'.
- * If the CCNode enters the 'stage' with a transition, this event is called when the transition finishes.
- * If you override onEnterTransitionDidFinish, you shall call its parent's one, e.g. CCNode::onEnterTransitionDidFinish() - *

- */ - onEnterTransitionDidFinish:function () { - this._isTransitionFinished = true; - this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.onEnterTransitionDidFinish); - }, - - /** - *

callback that is called every time the cc.Node leaves the 'stage'.
- * If the cc.Node leaves the 'stage' with a transition, this callback is called when the transition starts.

- */ - onExitTransitionDidStart:function () { - this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.onExitTransitionDidStart); - }, - - /** - *

- * callback that is called every time the cc.Node leaves the 'stage'.
- * If the cc.Node leaves the 'stage' with a transition, this callback is called when the transition finishes.
- * During onExit you can't access a sibling node.
- * If you override onExit, you shall call its parent's one, e.g., CCNode::onExit(). - *

- */ - onExit:function () { - this._running = false; - this.pauseSchedulerAndActions(); - this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.onExit); - this._componentContainer.removeAll(); - }, - - // actions - /** - * Executes an action, and returns the action that is executed.
- * The node becomes the action's target. Refer to CCAction::getTarget() - * @warning Starting from v0.8 actions don't retain their target anymore. - * @param {cc.Action} action - * @return {cc.Action} An Action pointer - */ - runAction:function (action) { - cc.Assert(action != null, "Argument must be non-nil"); - this.getActionManager().addAction(action, this, !this._running); - return action; - }, - - /** - * Stops and removes all actions from the running action list . - */ - stopAllActions:function () { - this.getActionManager().removeAllActionsFromTarget(this); - }, - - /** - * Stops and removes an action from the running action list. - * @param {cc.Action} action An action object to be removed. - */ - stopAction:function (action) { - this.getActionManager().removeAction(action); - }, - - /** - * Removes an action from the running action list by its tag. - * @param {Number} tag A tag that indicates the action to be removed. - */ - stopActionByTag:function (tag) { - cc.Assert(tag != cc.ACTION_TAG_INVALID, "Invalid tag"); - this.getActionManager().removeActionByTag(tag, this); - }, - - /** - * Gets an action from the running action list by its tag. - * @see setTag(int), getTag(). - * @param {Number} tag - * @return {cc.Action} The action object with the given tag. - */ - getActionByTag:function (tag) { - cc.Assert(tag != cc.ACTION_TAG_INVALID, "Invalid tag"); - return this.getActionManager().getActionByTag(tag, this); - }, - - /** Returns the numbers of actions that are running plus the ones that are schedule to run (actions in actionsToAdd and actions arrays).
- * Composable actions are counted as 1 action. Example:
- * If you are running 1 Sequence of 7 actions, it will return 1.
- * If you are running 7 Sequences of 2 actions, it will return 7. - * @return {Number} The number of actions that are running plus the ones that are schedule to run - */ - numberOfRunningActions:function () { - return this.getActionManager().numberOfRunningActionsInTarget(this); - }, - - // cc.Node - Callbacks - // timers - /** - * schedules the "update" method.
- * It will use the order number 0. This method will be called every frame.
- * Scheduled methods with a lower order value will be called before the ones that have a higher order value.
- * Only one "update" method could be scheduled per node. - */ - scheduleUpdate:function () { - this.scheduleUpdateWithPriority(0); - }, - - /** - *

- * schedules the "update" callback function with a custom priority. - * This callback function will be called every frame.
- * Scheduled callback functions with a lower priority will be called before the ones that have a higher value.
- * Only one "update" callback function could be scheduled per node (You can't have 2 'update' callback functions).
- *

- * @param {Number} priority - */ - scheduleUpdateWithPriority:function (priority) { - this.getScheduler().scheduleUpdateForTarget(this, priority, !this._running); - }, - - /** - * unschedules the "update" method. - * @see scheduleUpdate(); - */ - unscheduleUpdate:function () { - this.getScheduler().unscheduleUpdateForTarget(this); - }, - - /** - * Schedules a custom selector.
- * If the selector is already scheduled, then the interval parameter will be updated without scheduling it again. - * - * @param {function} callback_fn A function wrapped as a selector - * @param {Number} interval Tick interval in seconds. 0 means tick every frame. If interval = 0, it's recommended to use scheduleUpdate() instead. - * @param {Number} repeat The selector will be excuted (repeat + 1) times, you can use kCCRepeatForever for tick infinitely. - * @param {Number} delay The amount of time that the first tick will wait before execution. - */ - schedule:function (callback_fn, interval, repeat, delay) { - interval = interval || 0; - - cc.Assert(callback_fn, "Argument must be non-nil"); - cc.Assert(interval >= 0, "Argument must be positive"); - - repeat = (repeat == null) ? cc.REPEAT_FOREVER : repeat; - delay = delay || 0; - - this.getScheduler().scheduleCallbackForTarget(this, callback_fn, interval, repeat, delay, !this._running); - }, - - /** - * Schedules a callback function that runs only once, with a delay of 0 or larger - * @see schedule(SEL_SCHEDULE, float, unsigned int, float) - * @param {function} callback_fn A function wrapped as a selector - * @param {Number} delay The amount of time that the first tick will wait before execution. - */ - scheduleOnce:function (callback_fn, delay) { - this.schedule(callback_fn, 0.0, 0, delay); - }, - - /** - * unschedules a custom callback function. - * @see schedule(SEL_SCHEDULE, float, unsigned int, float) - * @param {function} callback_fn A function wrapped as a selector - */ - unschedule:function (callback_fn) { - // explicit nil handling - if (!callback_fn) - return; - - this.getScheduler().unscheduleCallbackForTarget(this, callback_fn); - }, - - /** - * unschedule all scheduled callback functions: custom callback functions, and the 'update' callback function.
- * Actions are not affected by this method. - */ - unscheduleAllCallbacks:function () { - this.getScheduler().unscheduleAllCallbacksForTarget(this); - }, - - /** - * Resumes all scheduled selectors and actions.
- * This method is called internally by onEnter - */ - resumeSchedulerAndActions:function () { - this.getScheduler().resumeTarget(this); - this.getActionManager().resumeTarget(this); - }, - - /** - * Pauses all scheduled selectors and actions.
- * This method is called internally by onExit - */ - pauseSchedulerAndActions:function () { - this.getScheduler().pauseTarget(this); - this.getActionManager().pauseTarget(this); - }, - - /** - *

Sets the additional transform.
- * The additional transform will be concatenated at the end of nodeToParentTransform.
- * It could be used to simulate `parent-child` relationship between two nodes (e.g. one is in BatchNode, another isn't).
- *

- * @example - * // create a batchNode - * var batch= cc.SpriteBatchNode.create("Icon-114.png"); - * this.addChild(batch); - * - * // create two sprites, spriteA will be added to batchNode, they are using different textures. - * var spriteA = cc.Sprite.createWithTexture(batch->getTexture()); - * var spriteB = cc.Sprite.create("Icon-72.png"); - * - * batch.addChild(spriteA); - * - * // We can't make spriteB as spriteA's child since they use different textures. So just add it to layer. - * // But we want to simulate `parent-child` relationship for these two node. - * this.addChild(spriteB); - * - * //position - * spriteA.setPosition(ccp(200, 200)); - * - * // Gets the spriteA's transform. - * var t = spriteA.nodeToParentTransform(); - * - * // Sets the additional transform to spriteB, spriteB's postion will based on its pseudo parent i.e. spriteA. - * spriteB.setAdditionalTransform(t); - * - * //scale - * spriteA.setScale(2); - * - * // Gets the spriteA's transform. - * t = spriteA.nodeToParentTransform(); - * - * // Sets the additional transform to spriteB, spriteB's scale will based on its pseudo parent i.e. spriteA. - * spriteB.setAdditionalTransform(t); - * - * //rotation - * spriteA.setRotation(20); - * - * // Gets the spriteA's transform. - * t = spriteA.nodeToParentTransform(); - * - * // Sets the additional transform to spriteB, spriteB's rotation will based on its pseudo parent i.e. spriteA. - * spriteB.setAdditionalTransform(t); - */ - setAdditionalTransform:function (additionalTransform) { - this._additionalTransform = additionalTransform; - this._transformDirty = true; - this._additionalTransformDirty = true; - }, - - /** - * Returns the matrix that transform parent's space coordinates to the node's (local) space coordinates.
- * The matrix is in Pixels. - * @return {cc.AffineTransform} - */ - parentToNodeTransform:function () { - if (this._inverseDirty) { - this._inverse = cc.AffineTransformInvert(this.nodeToParentTransform()); - this._inverseDirty = false; - } - return this._inverse; - }, - - /** - * Retrusn the world affine transform matrix. The matrix is in Pixels. - * @return {cc.AffineTransform} - */ - nodeToWorldTransform:function () { - var t = this.nodeToParentTransform(); - for (var p = this._parent; p != null; p = p.getParent()) - t = cc.AffineTransformConcat(t, p.nodeToParentTransform()); - return t; - }, - - /** - * Returns the inverse world affine transform matrix. The matrix is in Pixels. - * @return {cc.AffineTransform} - */ - worldToNodeTransform:function () { - return cc.AffineTransformInvert(this.nodeToWorldTransform()); - }, - - /** - * Converts a Point to node (local) space coordinates. The result is in Points. - * @param {cc.Point} worldPoint - * @return {cc.Point} - */ - convertToNodeSpace:function (worldPoint) { - return cc.PointApplyAffineTransform(worldPoint, this.worldToNodeTransform()); - }, - - /** - * Converts a Point to world space coordinates. The result is in Points. - * @param {cc.Point} nodePoint - * @return {cc.Point} - */ - convertToWorldSpace:function (nodePoint) { - return cc.PointApplyAffineTransform(nodePoint, this.nodeToWorldTransform()); - }, - - /** - * Converts a Point to node (local) space coordinates. The result is in Points.
- * treating the returned/received node point as anchor relative. - * @param {cc.Point} worldPoint - * @return {cc.Point} - */ - convertToNodeSpaceAR:function (worldPoint) { - return cc.pSub(this.convertToNodeSpace(worldPoint), this._anchorPointInPoints); - }, - - /** - * Converts a local Point to world space coordinates.The result is in Points.
- * treating the returned/received node point as anchor relative. - * @param {cc.Point} nodePoint - * @return {cc.Point} - */ - convertToWorldSpaceAR:function (nodePoint) { - var pt = cc.pAdd(nodePoint, this._anchorPointInPoints); - return this.convertToWorldSpace(pt); - }, - - _convertToWindowSpace:function (nodePoint) { - var worldPoint = this.convertToWorldSpace(nodePoint); - return cc.Director.getInstance().convertToUI(worldPoint); - }, - - /** convenience methods which take a cc.Touch instead of cc.Point - * @param {cc.Touch} touch - * @return {cc.Point} - */ - convertTouchToNodeSpace:function (touch) { - var point = touch.getLocation(); - //TODO This point needn't convert to GL in HTML5 - //point = cc.Director.getInstance().convertToGL(point); - return this.convertToNodeSpace(point); - }, - - /** - * converts a cc.Touch (world coordinates) into a local coordiante. This method is AR (Anchor Relative). - * @param {cc.Touch}touch - * @return {cc.Point} - */ - convertTouchToNodeSpaceAR:function (touch) { - var point = touch.getLocation(); - point = cc.Director.getInstance().convertToGL(point); - return this.convertToNodeSpaceAR(point); - }, - - /** - * Update will be called automatically every frame if "scheduleUpdate" is called, and the node is "live"
- * (override me) - * @param {Number} dt - */ - update:function (dt) { - if(this._componentContainer && !this._componentContainer.isEmpty()) - this._componentContainer.visit(dt); - }, - - /** - *

- * Calls children's updateTransform() method recursively.
- *
- * This method is moved from CCSprite, so it's no longer specific to CCSprite.
- * As the result, you apply CCSpriteBatchNode's optimization on your customed CCNode.
- * e.g., batchNode->addChild(myCustomNode), while you can only addChild(sprite) before. - *

- */ - updateTransform:function () { - // Recursively iterate over children - this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.updateTransform); - }, - - /** - * Currently JavaScript Bindigns (JSB), in some cases, needs to use retain and release. This is a bug in JSB, - * and the ugly workaround is to use retain/release. So, these 2 methods were added to be compatible with JSB. - * This is a hack, and should be removed once JSB fixes the retain/release bug - */ - retain:function () { - }, - release:function () { - }, - - /** - * gets a component by its name - * @param {String} name - * @return {cc.Component} gets a component by its name - */ - getComponent:function(name){ - return this._componentContainer.getComponent(name); - }, - - /** - * adds a component - * @param {cc.Component} component - */ - addComponent:function(component){ - this._componentContainer.add(component); - }, - - /** - * removes a component by its name - * @param {String} name - */ - removeComponent:function(name){ - return this._componentContainer.remove(name); - }, - - /** - * removes all components - */ - removeAllComponents:function(){ - this._componentContainer.removeAll(); - }, - /// ---- common properties end ---- - - /** - * Constructor - */ - ctor:function () { - this._initNode(); - }, - - /** - * recursive method that visit its children and draw them - * @param {CanvasContext} ctx - */ - visit:function (ctx) { - // quick return if not visible - if (!this._visible) - return; - - //visit for canvas - var context = ctx || cc.renderContext, i; - var children = this._children; - context.save(); - this.transform(context); - if (children && children.length > 0) { - var len = children.length; - this.sortAllChildren(); - // draw children zOrder < 0 - for (i = 0; i < len; i++) { - if (children[i] && children[i]._zOrder < 0) - children[i].visit(context); - else - break; - } - this.draw(context); - for (; i < len; i++) { - if (children[i] && children[i]._zOrder >= 0) - children[i].visit(context); - } - - } else - this.draw(context); - - this._orderOfArrival = 0; - context.restore(); - }, - - /** - * Performs OpenGL view-matrix transformation based on position, scale, rotation and other attributes. - */ - transform:function (ctx) { - // transform for canvas - var context = ctx || cc.renderContext; - var t = this.nodeToParentTransform(); - context.transform(t.a, t.b, t.c, t.d, t.tx, -t.ty); - }, - - /** Returns the matrix that transform the node's (local) space coordinates into the parent's space coordinates.
- * The matrix is in Pixels. - * @return {cc.AffineTransform} - */ - nodeToParentTransform:function () { - if (!this._transform) - this._transform = {a:1, b:0, c:0, d:1, tx:0, ty:0}; - if (this._transformDirty) { - var t = this._transform;// quick reference - // base position - t.tx = this._position.x; - t.ty = this._position.y; - - // rotation Cos and Sin - var Cos = 1, Sin = 0; - if (this._rotationX) { - Cos = Math.cos(this._rotationRadiansX); - Sin = Math.sin(this._rotationRadiansX); - } - - // base abcd - t.a = t.d = Cos; - t.c = -Sin; - t.b = Sin; - - var lScaleX = this._scaleX, lScaleY = this._scaleY; - var appX = this._anchorPointInPoints.x, appY = this._anchorPointInPoints.y; - - // Firefox on Vista and XP crashes - // GPU thread in case of scale(0.0, 0.0) - var sx = (lScaleX < 0.000001 && lScaleX > -0.000001)? 0.000001 : lScaleX, - sy = (lScaleY < 0.000001 && lScaleY > -0.000001)? 0.000001 : lScaleY; - - // skew - if (this._skewX || this._skewY) { - // offset the anchorpoint - var skx = Math.tan(-this._skewX * Math.PI / 180); - var sky = Math.tan(-this._skewY * Math.PI / 180); - var xx = appY * skx * sx; - var yy = appX * sky * sy; - t.a = Cos + -Sin * sky; - t.c = Cos * skx + -Sin; - t.b = Sin + Cos * sky; - t.d = Sin * skx + Cos; - t.tx += Cos * xx + -Sin * yy; - t.ty += Sin * xx + Cos * yy; - } - - // scale - if (lScaleX !== 1 || lScaleY !== 1) { - t.a *= sx; - t.b *= sx; - t.c *= sy; - t.d *= sy; - } - - // adjust anchorPoint - t.tx += Cos * -appX * sx + -Sin * appY * sy; - t.ty -= Sin * -appX * sx + Cos * appY * sy; - - // if ignore anchorPoint - if (this._ignoreAnchorPointForPosition) { - t.tx += appX - t.ty += appY; - } - - if (this._additionalTransformDirty) { - this._transform = cc.AffineTransformConcat(this._transform, this._additionalTransform); - //Because the cartesian coordination is inverted in html5 canvas, these needs to be inverted as well - this._transform.b *= -1; - this._transform.c *= -1; - - this._additionalTransformDirty = false; - } - - t.tx = t.tx | 0; - t.ty = t.ty | 0; - this._transformDirty = false; - } - return this._transform; - }, - - /** - * set the dirty node - */ - setNodeDirty:function () { - this._setNodeDirtyForCache(); - this._transformDirty = this._inverseDirty = true; - }, - - _setNodeDirtyForCache:function () { - this._cacheDirty = true; - if (this._parent) { - this._parent._setNodeDirtyForCache(); - } - }, - - /** returns a "world" axis aligned bounding box of the node.
- * @return {cc.Rect} - */ - getBoundingBoxToWorld:function () { - var rect = cc.rect(0, 0, this._contentSize.width, this._contentSize.height); - rect = cc.RectApplyAffineTransform(rect, this.nodeToWorldTransform()); - rect = cc.rect(0 | rect.x - 4, 0 | rect.y - 4, 0 | rect.width + 8, 0 | rect.height + 8); - //query child's BoundingBox - if (!this._children) - return rect; - - var locChildren = this._children; - for (var i = 0; i < locChildren.length; i++) { - var child = locChildren[i]; - if (child && child._visible) { - var childRect = child.getBoundingBoxToWorld(); - if (childRect) - rect = cc.rectUnion(rect, childRect); - } - } - return rect; - } -}); - -/** - * cc.Node's state callback type - * @constant - * @type Number - */ -cc.NodeCanvas.StateCallbackType = {onEnter:1, onExit:2, cleanup:3, onEnterTransitionDidFinish:4, updateTransform:5, onExitTransitionDidStart:6, sortAllChildren:7}; - -/** - * allocates and initializes a node. - * @constructs - * @return {cc.NodeCanvas} - * @example - * // example - * var node = cc.NodeWebGL.create(); - */ -cc.NodeCanvas.create = function () { - return new cc.NodeCanvas(); -}; - -cc.Node = cc.Browser.supportWebGL ? cc.NodeWebGL : cc.NodeCanvas; - -/** - *

- * cc.NodeRGBA is a subclass of cc.Node that implements the CCRGBAProtocol protocol.
- *
- * All features from CCNode are valid, plus the following new features:
- * - opacity
- * - RGB colors
- *
- * Opacity/Color propagates into children that conform to the CCRGBAProtocol if cascadeOpacity/cascadeColor is enabled.
- *

- * - * @class - * @extends cc.Node - */ -cc.NodeRGBA = cc.Node.extend(/** @lends cc.NodeRGBA# */{ - RGBAProtocol:true, - _displayedOpacity:0, - _realOpacity:0, - _displayedColor:null, - _realColor:null, - _cascadeColorEnabled:false, - _cascadeOpacityEnabled:false, +/** + *

+ * cc.NodeRGBA is a subclass of cc.Node that implements the CCRGBAProtocol protocol.
+ *
+ * All features from CCNode are valid, plus the following new features:
+ * - opacity
+ * - RGB colors
+ *
+ * Opacity/Color propagates into children that conform to the CCRGBAProtocol if cascadeOpacity/cascadeColor is enabled.
+ *

+ * + * @class + * @extends cc.Node + */ +cc.NodeRGBA = cc.Node.extend(/** @lends cc.NodeRGBA# */{ + RGBAProtocol:true, + _displayedOpacity:255, + _realOpacity:255, + _displayedColor:null, + _realColor:null, + _cascadeColorEnabled:false, + _cascadeOpacityEnabled:false, ctor:function(){ cc.Node.prototype.ctor.call(this); @@ -3771,18 +2119,6 @@ cc.NodeRGBA = cc.Node.extend(/** @lends cc.NodeRGBA# */{ this._cascadeOpacityEnabled = false; }, - - init:function(){ - if(cc.Node.prototype.init.call(this)){ - this._displayedOpacity = this._realOpacity = 255; - this._displayedColor = cc.WHITE; - this._realColor = cc.WHITE; - this._cascadeOpacityEnabled = this._cascadeColorEnabled = false; - return true; - } - return false; - }, - getOpacity:function(){ return this._realOpacity; }, @@ -3795,9 +2131,9 @@ cc.NodeRGBA = cc.Node.extend(/** @lends cc.NodeRGBA# */{ this._displayedOpacity = this._realOpacity = opacity; if (this._cascadeOpacityEnabled) { - var parentOpacity = 255; - if (this._parent && this._parent.RGBAProtocol && this._parent.isCascadeOpacityEnabled()) - parentOpacity = this._parent.getDisplayedOpacity(); + var parentOpacity = 255, locParent = this._parent; + if (locParent && locParent.RGBAProtocol && locParent.isCascadeOpacityEnabled()) + parentOpacity = locParent.getDisplayedOpacity(); this.updateDisplayedOpacity(parentOpacity); } }, @@ -3823,7 +2159,8 @@ cc.NodeRGBA = cc.Node.extend(/** @lends cc.NodeRGBA# */{ }, getColor:function(){ - return this._realColor; + var locRealColor = this._realColor; + return new cc.Color3B(locRealColor.r, locRealColor.g, locRealColor.b); }, getDisplayedColor:function(){ @@ -3831,13 +2168,19 @@ cc.NodeRGBA = cc.Node.extend(/** @lends cc.NodeRGBA# */{ }, setColor:function(color){ - this._displayedColor = cc.c3b(color.r, color.g, color.b); - this._realColor = cc.c3b(color.r, color.g, color.b); + var locDisplayedColor = this._displayedColor, locRealColor = this._realColor; + locDisplayedColor.r = color.r; + locDisplayedColor.g = color.g; + locDisplayedColor.b = color.b; + locRealColor.r = color.r; + locRealColor.g = color.g; + locRealColor.b = color.b; if (this._cascadeColorEnabled) { var parentColor = cc.white(); - if (this._parent && this._parent.RGBAProtocol && this._parent.isCascadeColorEnabled()) - parentColor = this._parent.getDisplayedColor(); + var locParent = this._parent; + if (locParent && locParent.RGBAProtocol && locParent.isCascadeColorEnabled()) + parentColor = locParent.getDisplayedColor(); this.updateDisplayedColor(parentColor); } }, diff --git a/cocos2d/base_nodes/CCdomNode.js b/cocos2d/base_nodes/CCdomNode.js index 106b194d6e..7bd78d3300 100644 --- a/cocos2d/base_nodes/CCdomNode.js +++ b/cocos2d/base_nodes/CCdomNode.js @@ -285,7 +285,7 @@ cc.DOM.methods = /** @lends cc.DOM# */{ redraw:function () { if (this.isSprite) { var tmp = this._children; - this._children = null; + this._children = []; cc.Sprite.prototype.visit.call(this, this.ctx); this._children = tmp; } @@ -294,6 +294,49 @@ cc.DOM.methods = /** @lends cc.DOM# */{ } } }; + +cc.DOM._resetEGLViewDiv = function(){ + var eglViewDiv = cc.$("#EGLViewDiv"); + if(eglViewDiv){ + var eglViewer = cc.EGLView.getInstance(); + var designSize = eglViewer.getDesignResolutionSize(); + var viewPortRect = eglViewer.getViewPortRect(); + var screenSize = eglViewer.getFrameSize(); + var designSizeWidth = designSize.width, designSizeHeight = designSize.height; + if((designSize.width === 0) && (designSize.height === 0)){ + designSizeWidth = screenSize.width; + designSizeHeight = screenSize.height; + } + + var viewPortWidth = viewPortRect.size.width, viewPortHeight = viewPortRect.size.height; + if((viewPortRect.size.width === 0) && (viewPortRect.size.height === 0)){ + viewPortWidth = screenSize.width; + viewPortHeight = screenSize.height; + } + + eglViewDiv.style.position = 'absolute'; + //x.dom.style.display='block'; + eglViewDiv.style.width = designSizeWidth + "px"; + eglViewDiv.style.maxHeight = designSizeHeight + "px"; + eglViewDiv.style.margin = 0; + + eglViewDiv.resize(eglViewer.getScaleX(), eglViewer.getScaleY()); + + if (viewPortWidth < screenSize.width) { + eglViewDiv.style.left = ((viewPortWidth - designSizeWidth) / 2 + + (screenSize.width - viewPortWidth ) / 2) + "px"; + } else { + eglViewDiv.style.left = (viewPortWidth - designSizeWidth) / 2 + "px"; + } + + if (viewPortHeight < screenSize.height) { + eglViewDiv.style.bottom = ((screenSize.height - viewPortHeight ) / 2) + "px"; + } else { + eglViewDiv.style.bottom = "0px"; + } + } +}; + /** * @function * @private @@ -317,47 +360,56 @@ cc.DOM.parentDOM = function (x) { cc.DOM.parentDOM(p); } else { //parent has no more parent, if its running, then add it to the container - //if (p.isRunning()) { - //find EGLView div - var eglViewDiv = cc.$("#EGLViewDiv"); - if(eglViewDiv){ - p.dom.appendTo(eglViewDiv); - } else { - eglViewDiv = cc.$new("div"); - eglViewDiv.id = "EGLViewDiv"; - - var eglViewer = cc.EGLView.getInstance(); - var designSize = eglViewer.getDesignResolutionSize(); - var viewPortRect = eglViewer.getViewPortRect(); - var screenSize = eglViewer.getFrameSize(); - var designSizeWidth = designSize.width, designSizeHeight = designSize.height; - if((designSize.width === 0) && (designSize.height === 0)){ - designSizeWidth = screenSize.width; - designSizeHeight = screenSize.height; - } - - var viewPortWidth = viewPortRect.size.width, viewPortHeight = viewPortRect.size.height; - if((viewPortRect.size.width === 0) && (viewPortRect.size.height === 0)){ - viewPortWidth = screenSize.width; - viewPortHeight = screenSize.height; + if (p.isRunning()) { + //find EGLView div + var eglViewDiv = cc.$("#EGLViewDiv"); + if (eglViewDiv) { + p.dom.appendTo(eglViewDiv); + } else { + eglViewDiv = cc.$new("div"); + eglViewDiv.id = "EGLViewDiv"; + + var eglViewer = cc.EGLView.getInstance(); + var designSize = eglViewer.getDesignResolutionSize(); + var viewPortRect = eglViewer.getViewPortRect(); + var screenSize = eglViewer.getFrameSize(); + var designSizeWidth = designSize.width, designSizeHeight = designSize.height; + if ((designSize.width === 0) && (designSize.height === 0)) { + designSizeWidth = screenSize.width; + designSizeHeight = screenSize.height; + } + + var viewPortWidth = viewPortRect.size.width, viewPortHeight = viewPortRect.size.height; + if ((viewPortRect.size.width === 0) && (viewPortRect.size.height === 0)) { + viewPortWidth = screenSize.width; + viewPortHeight = screenSize.height; + } + + eglViewDiv.style.position = 'absolute'; + //x.dom.style.display='block'; + eglViewDiv.style.width = designSizeWidth + "px"; + eglViewDiv.style.maxHeight = designSizeHeight + "px"; + eglViewDiv.style.margin = 0; + + eglViewDiv.resize(eglViewer.getScaleX(), eglViewer.getScaleY()); + + if (viewPortWidth < screenSize.width) { + eglViewDiv.style.left = ((viewPortWidth - designSizeWidth) / 2 + + (screenSize.width - viewPortWidth ) / 2) + "px"; + } else { + eglViewDiv.style.left = (viewPortWidth - designSizeWidth) / 2 + "px"; + } + + if (viewPortHeight < screenSize.height) { + eglViewDiv.style.bottom = ((screenSize.height - viewPortHeight ) / 2) + "px"; + } else { + eglViewDiv.style.bottom = "0px"; + } + + p.dom.appendTo(eglViewDiv); + eglViewDiv.appendTo(cc.container); } - - eglViewDiv.style.position = 'absolute'; - eglViewDiv.style.bottom = 0; - //x.dom.style.display='block'; - eglViewDiv.style.width = designSizeWidth + "px"; - eglViewDiv.style.maxHeight = designSizeHeight + "px"; - eglViewDiv.style.margin = 0; - - eglViewDiv.resize(eglViewer.getScaleX(), eglViewer.getScaleX()); - eglViewDiv.style.left = ((viewPortWidth - designSizeWidth) / 2 - + (screenSize.width - viewPortWidth ) / 2) + "px"; - eglViewDiv.style.bottom = ((screenSize.height - viewPortHeight ) / 2) + "px"; - - p.dom.appendTo(eglViewDiv); - eglViewDiv.appendTo(cc.container); } - //} } return true; }; @@ -376,7 +428,7 @@ cc.DOM.setTransform = function (x) { x.ctx.translate(x.getAnchorPointInPoints().x, x.getAnchorPointInPoints().y); if (x.isSprite) { var tmp = x._children; - x._children = null; + x._children = []; cc.Sprite.prototype.visit.call(x, x.ctx); x._children = tmp; } diff --git a/cocos2d/build.xml b/cocos2d/build.xml index c3d1ade5c3..59c01d81e2 100644 --- a/cocos2d/build.xml +++ b/cocos2d/build.xml @@ -6,7 +6,7 @@ + debug="false" output="../lib/Cocos2d-html5-v2.1.6.min.js"> @@ -95,7 +95,6 @@ - @@ -159,27 +158,25 @@ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + +
diff --git a/cocos2d/cocoa/CCAffineTransform.js b/cocos2d/cocoa/CCAffineTransform.js index e5642b93c7..2437f5ca18 100644 --- a/cocos2d/cocoa/CCAffineTransform.js +++ b/cocos2d/cocoa/CCAffineTransform.js @@ -76,6 +76,11 @@ cc.PointApplyAffineTransform = function (point, t) { return {x: t.a * point.x + t.c * point.y + t.tx, y: t.b * point.x + t.d * point.y + t.ty}; }; +cc._PointApplyAffineTransform = function (x, y, t) { + return {x: t.a * x + t.c * y + t.tx, + y: t.b * x + t.d * y + t.ty}; +}; + cc.__SizeApplyAffineTransform = function (size, t) { return {width: t.a * size.width + t.c * size.height, height: t.b * size.width + t.d * size.height}; }; @@ -122,19 +127,42 @@ cc.RectApplyAffineTransform = function (rect, anAffineTransform) { var right = cc.rectGetMaxX(rect); var bottom = cc.rectGetMaxY(rect); - var topLeft = cc.PointApplyAffineTransform(cc.p(left, top), anAffineTransform); - var topRight = cc.PointApplyAffineTransform(cc.p(right, top), anAffineTransform); - var bottomLeft = cc.PointApplyAffineTransform(cc.p(left, bottom), anAffineTransform); - var bottomRight = cc.PointApplyAffineTransform(cc.p(right, bottom), anAffineTransform); + var topLeft = cc._PointApplyAffineTransform(left, top, anAffineTransform); + var topRight = cc._PointApplyAffineTransform(right, top, anAffineTransform); + var bottomLeft = cc._PointApplyAffineTransform(left, bottom, anAffineTransform); + var bottomRight = cc._PointApplyAffineTransform(right, bottom, anAffineTransform); - var minX = Math.min(Math.min(topLeft.x, topRight.x), Math.min(bottomLeft.x, bottomRight.x)); - var maxX = Math.max(Math.max(topLeft.x, topRight.x), Math.max(bottomLeft.x, bottomRight.x)); - var minY = Math.min(Math.min(topLeft.y, topRight.y), Math.min(bottomLeft.y, bottomRight.y)); - var maxY = Math.max(Math.max(topLeft.y, topRight.y), Math.max(bottomLeft.y, bottomRight.y)); + var minX = Math.min(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x); + var maxX = Math.max(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x); + var minY = Math.min(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y); + var maxY = Math.max(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y); return cc.rect(minX, minY, (maxX - minX), (maxY - minY)); }; +cc._RectApplyAffineTransformIn = function(rect, anAffineTransform){ + var top = cc.rectGetMinY(rect); + var left = cc.rectGetMinX(rect); + var right = cc.rectGetMaxX(rect); + var bottom = cc.rectGetMaxY(rect); + + var topLeft = cc._PointApplyAffineTransform(left, top, anAffineTransform); + var topRight = cc._PointApplyAffineTransform(right, top, anAffineTransform); + var bottomLeft = cc._PointApplyAffineTransform(left, bottom, anAffineTransform); + var bottomRight = cc._PointApplyAffineTransform(right, bottom, anAffineTransform); + + var minX = Math.min(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x); + var maxX = Math.max(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x); + var minY = Math.min(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y); + var maxY = Math.max(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y); + + rect.x = minX; + rect.y = minY; + rect.width = maxX - minX; + rect.height = maxY - minY; + return rect; +}; + /** * @function * @param {cc.AffineTransform} t @@ -144,7 +172,14 @@ cc.RectApplyAffineTransform = function (rect, anAffineTransform) { * Constructor */ cc.AffineTransformTranslate = function (t, tx, ty) { - return {a: t.a, b: t.b, c: t.c, d: t.d, tx: t.tx + t.a * tx + t.c * ty, ty: t.ty + t.b * tx + t.d * ty}; + return { + a: t.a, + b: t.b, + c: t.c, + d: t.d, + tx: t.tx + t.a * tx + t.c * ty, + ty: t.ty + t.b * tx + t.d * ty + }; }; /** diff --git a/cocos2d/cocoa/CCGeometry.js b/cocos2d/cocoa/CCGeometry.js index 4944efb269..503fe76d42 100644 --- a/cocos2d/cocoa/CCGeometry.js +++ b/cocos2d/cocoa/CCGeometry.js @@ -47,6 +47,7 @@ cc.Point = function (_x, _y) { * @return {cc.Point} */ cc.PointMake = function (x, y) { + cc.log("cc.PointMake will be deprecated sooner or later. Use cc.p instead."); return new cc.Point(x, y); }; @@ -134,6 +135,7 @@ cc.Size = function (_width, _height) { * @return {cc.Size} */ cc.SizeMake = function (width, height) { + cc.log("cc.SizeMake will be deprecated sooner or later. Use cc.size instead."); return cc.size(width, height); }; @@ -237,6 +239,7 @@ cc.Rect = function (x1, y1, width1, height1) { * @return {cc.Rect} */ cc.RectMake = function (x, y, width, height) { + cc.log("cc.RectMake will be deprecated sooner or later. Use cc.rect instead."); return cc.rect(x, y, width, height); }; @@ -270,6 +273,12 @@ cc.rectEqualToRect = function (rect1, rect2) { (cc.sizeEqualToSize(rect1.size, rect2.size))); }; +cc._rectEqualToZero = function(rect){ + if(!rect) + return false; + return (rect.x === 0) && (rect.y === 0) && (rect.width === 0) && (rect.height === 0); +}; + /** * @function * @param {cc.Rect} rect1 diff --git a/cocos2d/draw_nodes/CCDrawNode.js b/cocos2d/draw_nodes/CCDrawNode.js index 9085aed136..3626cdfcc1 100644 --- a/cocos2d/draw_nodes/CCDrawNode.js +++ b/cocos2d/draw_nodes/CCDrawNode.js @@ -102,7 +102,7 @@ cc.DrawNodeCanvas = cc.Node.extend(/** @lends cc.DrawNodeCanvas# */{ // ----common function end ---- ctor:function () { - this._super(); + cc.Node.prototype.ctor.call(this); this._buffer = []; this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST); }, @@ -115,19 +115,19 @@ cc.DrawNodeCanvas = cc.Node.extend(/** @lends cc.DrawNodeCanvas# */{ for (var i = 0; i < this._buffer.length; i++) { var element = this._buffer[i]; - if (element.type === cc.DRAWNODE_TYPE_DOT) { + if (element.type === cc.DrawNode.TYPE_DOT) { context.fillStyle = "rgba(" + (0 | (element.color.r * 255)) + "," + (0 | (element.color.g * 255)) + "," + (0 | (element.color.b * 255)) + "," + element.color.a + ")"; cc.drawingUtil.drawPoint(element.position, element.radius); } - if (element.type === cc.DRAWNODE_TYPE_SEGMENT) { + if (element.type === cc.DrawNode.TYPE_SEGMENT) { context.strokeStyle = "rgba(" + (0 | (element.color.r * 255)) + "," + (0 | (element.color.g * 255)) + "," + (0 | (element.color.b * 255)) + "," + element.color.a + ")"; context.lineWidth = element.radius * 2; context.lineCap = "round"; cc.drawingUtil.drawLine(element.from, element.to); } - if (element.type === cc.DRAWNODE_TYPE_POLY) { + if (element.type === cc.DrawNode.TYPE_POLY ) { context.fillStyle = "rgba(" + (0 | (element.fillColor.r * 255)) + "," + (0 | (element.fillColor.g * 255)) + "," + (0 | (element.fillColor.b * 255)) + "," + element.fillColor.a + ")"; cc.drawingUtil.drawPoly(element.verts, element.count, false, true); @@ -147,7 +147,7 @@ cc.DrawNodeCanvas = cc.Node.extend(/** @lends cc.DrawNodeCanvas# */{ * @param {cc.Color4F} color */ drawDot:function (pos, radius, color) { - var element = new cc._DrawNodeElement(cc.DRAWNODE_TYPE_DOT); + var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_DOT); element.position = pos; element.radius = radius; element.color = color; @@ -162,7 +162,7 @@ cc.DrawNodeCanvas = cc.Node.extend(/** @lends cc.DrawNodeCanvas# */{ * @param {cc.Color4F} color */ drawSegment:function (from, to, radius, color) { - var element = new cc._DrawNodeElement(cc.DRAWNODE_TYPE_SEGMENT); + var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_SEGMENT); element.from = from; element.to = to; element.radius = radius; @@ -178,7 +178,7 @@ cc.DrawNodeCanvas = cc.Node.extend(/** @lends cc.DrawNodeCanvas# */{ * @param {cc.Color4F} borderColor */ drawPoly:function (verts, fillColor, borderWidth, borderColor) { - var element = new cc._DrawNodeElement(cc.DRAWNODE_TYPE_POLY); + var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY ); element.verts = verts; element.count = verts.length; element.fillColor = fillColor; @@ -195,17 +195,6 @@ cc.DrawNodeCanvas = cc.Node.extend(/** @lends cc.DrawNodeCanvas# */{ } }); -/** - * Creates a DrawNodeCanvas - * @return {cc.DrawNodeCanvas} - */ -cc.DrawNodeCanvas.create = function () { - var ret = new cc.DrawNodeCanvas(); - if (ret && ret.init()) - return ret; - return null; -}; - /** *

CCDrawNode for WebGL
* Node that draws dots, segments and polygons.
@@ -235,13 +224,13 @@ cc.DrawNodeWebGL = cc.Node.extend(/** @lends cc.DrawNodeWebGL# */{ // ----common function end ---- ctor:function () { - this._super(); + cc.Node.prototype.ctor.call(this); this._buffer = []; this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST); }, init:function () { - if (this._super()) { + if (cc.Node.prototype.init.call(this)) { this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_LENGTHTEXTURECOLOR)); this._ensureCapacity(512); this._trianglesWebBuffer = cc.renderContext.createBuffer(); @@ -276,20 +265,21 @@ cc.DrawNodeWebGL = cc.Node.extend(/** @lends cc.DrawNodeWebGL# */{ _ensureCapacity:function(count){ if(this._buffer.length + count > this._bufferCapacity){ + var TriangleLength = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT; this._bufferCapacity += Math.max(this._bufferCapacity, count); //re alloc if((this._buffer == null) || (this._buffer.length === 0)){ //init this._buffer = []; - this._trianglesArrayBuffer = new ArrayBuffer(cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT * this._bufferCapacity); + this._trianglesArrayBuffer = new ArrayBuffer(TriangleLength * this._bufferCapacity); this._trianglesReader = new Uint8Array(this._trianglesArrayBuffer); } else { var newTriangles = []; - var newArrayBuffer = new ArrayBuffer(cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT * this._bufferCapacity); + var newArrayBuffer = new ArrayBuffer(TriangleLength * this._bufferCapacity); for(var i = 0; i < this._buffer.length;i++){ newTriangles[i] = new cc.V2F_C4B_T2F_Triangle(this._buffer[i].a,this._buffer[i].b,this._buffer[i].c, - newArrayBuffer,i * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT); + newArrayBuffer,i * TriangleLength); } this._trianglesReader = new Uint8Array(newArrayBuffer); this._buffer = newTriangles; @@ -351,29 +341,30 @@ cc.DrawNodeWebGL = cc.Node.extend(/** @lends cc.DrawNodeWebGL# */{ var v6 = cc.v2fsub(a, cc.v2fsub(nw, tw)); var v7 = cc.v2fadd(a, cc.v2fadd(nw, tw)); + var TriangleLength = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, triangleBuffer = this._trianglesArrayBuffer; this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v0, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(cc.v2fadd(n, t)))}, {vertices: v1, colors: c4bColor, texCoords: cc.__t(cc.v2fsub(n, t))}, {vertices: v2, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))}, - this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT)); + triangleBuffer, this._buffer.length * TriangleLength)); this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v3, colors: c4bColor, texCoords: cc.__t(n)}, {vertices: v1, colors: c4bColor, texCoords: cc.__t(cc.v2fsub(n, t))}, {vertices: v2, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))}, - this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT)); + triangleBuffer, this._buffer.length * TriangleLength)); this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v3, colors: c4bColor, texCoords: cc.__t(n)}, {vertices: v4, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))}, {vertices: v2, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))}, - this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT)); + triangleBuffer, this._buffer.length * TriangleLength)); this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v3, colors: c4bColor, texCoords: cc.__t(n)}, {vertices: v4, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))}, {vertices: v5, colors: c4bColor, texCoords: cc.__t(n)}, - this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT)); + triangleBuffer, this._buffer.length * TriangleLength)); this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v6, colors: c4bColor, texCoords: cc.__t(cc.v2fsub(t, n))}, {vertices: v4, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))}, {vertices: v5, colors: c4bColor, texCoords: cc.__t(n)}, - this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT)); + triangleBuffer, this._buffer.length * TriangleLength)); this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v6, colors: c4bColor, texCoords: cc.__t(cc.v2fsub(t, n))}, {vertices: v7, colors: c4bColor, texCoords: cc.__t(cc.v2fadd(n, t))}, {vertices: v5, colors: c4bColor, texCoords: cc.__t(n)}, - this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT)); + triangleBuffer, this._buffer.length * TriangleLength)); this._dirty = true; }, @@ -405,14 +396,16 @@ cc.DrawNodeWebGL = cc.Node.extend(/** @lends cc.DrawNodeWebGL# */{ var vertexCount = 3 * triangleCount; this._ensureCapacity(vertexCount); + var triangleBytesLen = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, trianglesBuffer = this._trianglesArrayBuffer; + var locBuffer = this._buffer; var inset = (outline == false ? 0.5 : 0.0); for (i = 0; i < count - 2; i++) { v0 = cc.v2fsub(cc.__v2f(verts[0]), cc.v2fmult(extrude[0].offset, inset)); v1 = cc.v2fsub(cc.__v2f(verts[i + 1]), cc.v2fmult(extrude[i + 1].offset, inset)); v2 = cc.v2fsub(cc.__v2f(verts[i + 2]), cc.v2fmult(extrude[i + 2].offset, inset)); - this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, + locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, {vertices: v1, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, {vertices: v2, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, - this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT)); + trianglesBuffer, locBuffer.length * triangleBytesLen)); } for (i = 0; i < count; i++) { @@ -429,19 +422,19 @@ cc.DrawNodeWebGL = cc.Node.extend(/** @lends cc.DrawNodeWebGL# */{ var outer1 = outline ? cc.v2fadd(v1, cc.v2fmult(offset1, borderWidth)) : cc.v2fadd(v1, cc.v2fmult(offset1, 0.5)); if (outline) { - this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, + locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, {vertices: inner1, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, {vertices: outer1, colors: c4bBorderColor, texCoords: cc.__t(n0)}, - this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT)); - this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, + trianglesBuffer, locBuffer.length * triangleBytesLen)); + locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, {vertices: outer0, colors: c4bBorderColor, texCoords: cc.__t(n0)}, {vertices: outer1, colors: c4bBorderColor, texCoords: cc.__t(n0)}, - this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT)); + trianglesBuffer, locBuffer.length * triangleBytesLen)); } else { - this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, + locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, {vertices: inner1, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, {vertices: outer1, colors: c4bFillColor, texCoords: cc.__t(n0)}, - this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT)); - this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, + trianglesBuffer, locBuffer.length * triangleBytesLen)); + locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, {vertices: outer0, colors: c4bFillColor, texCoords: cc.__t(n0)}, {vertices: outer1, colors: c4bFillColor, texCoords: cc.__t(n0)}, - this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT)); + trianglesBuffer, locBuffer.length * triangleBytesLen)); } } extrude = null; @@ -457,23 +450,23 @@ cc.DrawNodeWebGL = cc.Node.extend(/** @lends cc.DrawNodeWebGL# */{ } }); +cc.DrawNode = cc.Browser.supportWebGL ? cc.DrawNodeWebGL : cc.DrawNodeCanvas; + /** - * Creates a DrawNodeCanvas - * @return {cc.DrawNodeWebGL} + * Creates a DrawNode + * @return {cc.DrawNode} */ -cc.DrawNodeWebGL.create = function () { - var ret = new cc.DrawNodeWebGL(); +cc.DrawNode.create = function () { + var ret = new cc.DrawNode(); if (ret && ret.init()) return ret; return null; }; -cc.DrawNode = cc.Browser.supportWebGL ? cc.DrawNodeWebGL : cc.DrawNodeCanvas; - cc._DrawNodeElement = function (type) { this.type = type; }; -cc.DRAWNODE_TYPE_DOT = 0; -cc.DRAWNODE_TYPE_SEGMENT = 1; -cc.DRAWNODE_TYPE_POLY = 2; +cc.DrawNode.TYPE_DOT = 0; +cc.DrawNode.TYPE_SEGMENT = 1; +cc.DrawNode.TYPE_POLY = 2; diff --git a/cocos2d/kazmath/mat4.js b/cocos2d/kazmath/mat4.js index eed25b2efe..74e88b88e9 100644 --- a/cocos2d/kazmath/mat4.js +++ b/cocos2d/kazmath/mat4.js @@ -27,8 +27,9 @@ /* A 4x4 matrix + mat = | 0 4 8 12 | - mat = | 1 5 9 13 | + | 1 5 9 13 | | 2 6 10 14 | | 3 7 11 15 | */ diff --git a/cocos2d/label_nodes/CCLabelAtlas.js b/cocos2d/label_nodes/CCLabelAtlas.js index aa417c5e58..66479026ca 100644 --- a/cocos2d/label_nodes/CCLabelAtlas.js +++ b/cocos2d/label_nodes/CCLabelAtlas.js @@ -25,27 +25,29 @@ ****************************************************************************/ /** - * using image file to print text label on the screen, might be a bit slower than cc.Label, similar to cc.LabelBMFont (Canvas version) + * using image file to print text label on the screen, might be a bit slower than cc.Label, similar to cc.LabelBMFont * @class * @extends cc.AtlasNode */ -cc.LabelAtlasCanvas = cc.AtlasNode.extend(/** @lends cc.LabelAtlasCanvas# */{ - // ---- common properties start ---- +cc.LabelAtlas = cc.AtlasNode.extend(/** @lends cc.LabelAtlas# */{ // string to render _string:null, // the first char in the charmap _mapStartChar:null, /** - * initializes the cc.LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas - * It accepts two groups of parameters: - * a) string, fntFile - * b) label, textureFilename, width, height, startChar + *

+ * initializes the cc.LabelAtlas with a string, a char map file(the atlas),
+ * the width and height of each element and the starting char of the atlas
+ * It accepts two groups of parameters:
+ * a) string, fntFile
+ * b) label, textureFilename, width, height, startChar
+ *

* @param {String} strText * @param {String|cc.Texture2D} charMapFile charMapFile or fntFile or texture file - * @param {Number} itemWidth - * @param {Number} itemHeight - * @param {Number} startCharMap + * @param {Number} [itemWidth=0] + * @param {Number} [itemHeight=0] + * @param {Number} [startCharMap=""] * @return {Boolean} returns true on success */ initWithString:function (strText, charMapFile, itemWidth, itemHeight, startCharMap) { @@ -60,8 +62,9 @@ cc.LabelAtlasCanvas = cc.AtlasNode.extend(/** @lends cc.LabelAtlasCanvas# */{ cc.Assert(parseInt(dict["version"], 10) == 1, "Unsupported version. Upgrade cocos2d version"); textureFilename = relPathStr + dict["textureFilename"]; - width = parseInt(dict["itemWidth"], 10) / cc.CONTENT_SCALE_FACTOR(); - height = parseInt(dict["itemHeight"], 10) / cc.CONTENT_SCALE_FACTOR(); + var locScaleFactor = cc.CONTENT_SCALE_FACTOR(); + width = parseInt(dict["itemWidth"], 10) / locScaleFactor; + height = parseInt(dict["itemHeight"], 10) / locScaleFactor; startChar = String.fromCharCode(parseInt(dict["firstChar"], 10)); } else { textureFilename = charMapFile; @@ -88,7 +91,7 @@ cc.LabelAtlasCanvas = cc.AtlasNode.extend(/** @lends cc.LabelAtlasCanvas# */{ * @param {cc.Color3B} color3 */ setColor:function (color3) { - this._super(color3); + cc.AtlasNode.prototype.setColor.call(this, color3); this.updateAtlasValues(); }, /** @@ -102,8 +105,8 @@ cc.LabelAtlasCanvas = cc.AtlasNode.extend(/** @lends cc.LabelAtlasCanvas# */{ /** * draw the label */ - draw:function () { - this._super(); + draw:function (ctx) { + cc.AtlasNode.prototype.draw.call(this,ctx); if (cc.LABELATLAS_DEBUG_DRAW) { var s = this.getContentSize(); var vertices = [cc.p(0, 0), cc.p(s.width, 0), @@ -111,21 +114,25 @@ cc.LabelAtlasCanvas = cc.AtlasNode.extend(/** @lends cc.LabelAtlasCanvas# */{ cc.drawingUtil.drawPoly(vertices, 4, true); } }, - // ---- common properties end ---- /** * Atlas generation */ - updateAtlasValues:function () { + updateAtlasValues: null, + + _updateAtlasValuesForCanvas: function () { + var locString = this._string; + var n = locString.length; var texture = this.getTexture(); var locItemWidth = this._itemWidth, locItemHeight = this._itemHeight; - for (var i = 0; i < this._string.length; i++) { - var a = this._string.charCodeAt(i) - this._mapStartChar.charCodeAt(0); - var row = parseInt(a % this._itemsPerRow, 10) * cc.CONTENT_SCALE_FACTOR(); - var col = parseInt(a / this._itemsPerRow, 10) * cc.CONTENT_SCALE_FACTOR(); + var locScaleFactor = cc.CONTENT_SCALE_FACTOR(); + for (var i = 0; i < n; i++) { + var a = locString.charCodeAt(i) - this._mapStartChar.charCodeAt(0); + var row = parseInt(a % this._itemsPerRow, 10) * locScaleFactor; + var col = parseInt(a / this._itemsPerRow, 10) * locScaleFactor; var rect = cc.rect(row * locItemWidth, col * locItemHeight, locItemWidth, locItemHeight); - var c = this._string.charCodeAt(i); + var c = locString.charCodeAt(i); var fontChar = this.getChildByTag(i); if (!fontChar) { fontChar = new cc.Sprite(); @@ -145,176 +152,34 @@ cc.LabelAtlasCanvas = cc.AtlasNode.extend(/** @lends cc.LabelAtlasCanvas# */{ fontChar.initWithTexture(texture, rect); // restore to default in case they were modified fontChar.setVisible(true); - fontChar.setOpacity(this._opacity); + fontChar.setOpacity(this._displayedOpacity); } } - fontChar.setPosition(cc.p(i * locItemWidth + locItemWidth / 2, locItemHeight / 2)); - } - }, - - /** - * set the display string - * @param {String} label - */ - setString:function (label) { - label = String(label); - var len = label.length; - this._string = label; - this.setContentSize(cc.size(len * this._itemWidth, this._itemHeight)); - if (this._children) { - for (var i = 0; i < this._children.length; i++) { - var node = this._children[i]; - if (node) - node.setVisible(false); - } - } - - this.updateAtlasValues(); - this._quadsToDraw = len; - }, - - setOpacity:function (opacity) { - if (this._opacity != opacity) { - this._super(opacity); - for (var i = 0; i < this._children.length; i++) { - if (this._children[i]) - this._children[i].setOpacity(opacity); - } - } - } -}); - -/** - * It accepts two groups of parameters: - * a) string, fntFile - * b) label, textureFilename, width, height, startChar - * @return {cc.LabelAtlas|Null} returns the LabelAtlas object on success - * @example - * //Example - * //creates the cc.LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas - * var myLabel = cc.LabelAtlas.create('Text to display', 'CharMapfile.png', 12, 20, ' ') - * - * //creates the cc.LabelAtlas with a string, a fnt file - * var myLabel = cc.LabelAtlas.create('Text to display', 'CharMapFile.plist‘); - */ -cc.LabelAtlasCanvas.create = function (strText, charMapFile, itemWidth, itemHeight, startCharMap) { - var ret = new cc.LabelAtlasCanvas(); - if (ret && cc.LabelAtlasCanvas.prototype.initWithString.apply(ret,arguments)) { - return ret; - } - return null; -}; - -/** - * using image file to print text label on the screen, might be a bit slower than cc.Label, similar to cc.LabelBMFont (WebGL version) - * @class - * @extends cc.AtlasNode - */ -cc.LabelAtlasWebGL = cc.AtlasNode.extend(/** @lends cc.LabelAtlasWebGL# */{ - // ---- common properties start ---- - // string to render - _string:null, - // the first char in the charmap - _mapStartChar:null, - - /** - * initializes the cc.LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas - * It accepts two groups of parameters: - * a) string, fntFile - * b) label, textureFilename, width, height, startChar - * @param {String} strText - * @param {String | cc.Texture2D} charMapFile charMapFile or fntFile - * @param {Number} itemWidth - * @param {Number} itemHeight - * @param {Number} startCharMap - * @return {Boolean} returns true on success - */ - initWithString:function (strText, charMapFile, itemWidth, itemHeight, startCharMap) { - var label = strText + "", textureFilename, width, height, startChar; - cc.Assert(label !== null, "Label must be non-nil"); - if (arguments.length === 2) { - var fileUtils = cc.FileUtils.getInstance(); - var pathStr = fileUtils.fullPathForFilename(charMapFile); - var relPathStr = pathStr.substr(0, pathStr.lastIndexOf('/')) + '/'; - - var dict = fileUtils.dictionaryWithContentsOfFileThreadSafe(pathStr); - cc.Assert(parseInt(dict["version"], 10) == 1, "Unsupported version. Upgrade cocos2d version"); - - textureFilename = relPathStr + dict["textureFilename"]; - width = parseInt(dict["itemWidth"], 10) / cc.CONTENT_SCALE_FACTOR(); - height = parseInt(dict["itemHeight"], 10) / cc.CONTENT_SCALE_FACTOR(); - startChar = String.fromCharCode(parseInt(dict["firstChar"], 10)); - } else { - textureFilename = charMapFile; - width = itemWidth || 0; - height = itemHeight || 0; - startChar = startCharMap || " "; - } - - var texture = null; - if(textureFilename instanceof cc.Texture2D) - texture = textureFilename; - else - texture = cc.TextureCache.getInstance().addImage(textureFilename); - - if (this.initWithTexture(texture, width, height, label.length)) { - this._mapStartChar = startChar; - this.setString(label); - return true; - } - return false; - }, - - /** - * @param {cc.Color3B} color3 - */ - setColor:function (color3) { - this._super(color3); - this.updateAtlasValues(); - }, - /** - * return the text of this label - * @return {String} - */ - getString:function () { - return this._string; - }, - - /** - * draw the label - */ - draw:function () { - this._super(); - if (cc.LABELATLAS_DEBUG_DRAW) { - var s = this.getContentSize(); - var vertices = [cc.p(0, 0), cc.p(s.width, 0), - cc.p(s.width, s.height), cc.p(0, s.height)]; - cc.drawingUtil.drawPoly(vertices, 4, true); + fontChar.setPosition(i * locItemWidth + locItemWidth / 2, locItemHeight / 2); } }, - // ---- common properties end ---- - /** - * Atlas generation - */ - updateAtlasValues:function () { - var n = this._string.length; + _updateAtlasValuesForWebGL: function () { + var locString = this._string; + var n = locString.length; var locTextureAtlas = this._textureAtlas; var texture = locTextureAtlas.getTexture(); var textureWide = texture.getPixelsWide(); var textureHigh = texture.getPixelsHigh(); - var itemWidthInPixels = this._itemWidth ; + var itemWidthInPixels = this._itemWidth; var itemHeightInPixels = this._itemHeight; - if(!this._ignoreContentScaleFactor){ + if (!this._ignoreContentScaleFactor) { itemWidthInPixels = this._itemWidth * cc.CONTENT_SCALE_FACTOR(); itemHeightInPixels = this._itemHeight * cc.CONTENT_SCALE_FACTOR(); } - cc.Assert( n <= locTextureAtlas.getCapacity(), "updateAtlasValues: Invalid String length"); + cc.Assert(n <= locTextureAtlas.getCapacity(), "updateAtlasValues: Invalid String length"); var quads = locTextureAtlas.getQuads(); - var curColor = {r: this._displayedColor.r, g:this._displayedColor.g, b:this._displayedColor.b, a:this._displayedOpacity}; + var locDisplayedColor = this._displayedColor; + var curColor = {r: locDisplayedColor.r, g: locDisplayedColor.g, b: locDisplayedColor.b, a: this._displayedOpacity}; + var locItemWidth = this._itemWidth; for (var i = 0; i < n; i++) { - var a = this._string.charCodeAt(i) - this._mapStartChar.charCodeAt(0); + var a = locString.charCodeAt(i) - this._mapStartChar.charCodeAt(0); var row = a % this._itemsPerRow; var col = 0 | (a / this._itemsPerRow); @@ -332,33 +197,34 @@ cc.LabelAtlasWebGL = cc.AtlasNode.extend(/** @lends cc.LabelAtlasWebGL# */{ bottom = top + itemHeightInPixels / textureHigh; } var quad = quads[i]; - quad.tl.texCoords.u = left; - quad.tl.texCoords.v = top; - quad.tr.texCoords.u = right; - quad.tr.texCoords.v = top; - quad.bl.texCoords.u = left; - quad.bl.texCoords.v = bottom; - quad.br.texCoords.u = right; - quad.br.texCoords.v = bottom; - - quad.bl.vertices.x = (i * this._itemWidth); - quad.bl.vertices.y = 0; - quad.bl.vertices.z = 0.0; - quad.br.vertices.x = (i * this._itemWidth + this._itemWidth); - quad.br.vertices.y = 0; - quad.br.vertices.z = 0.0; - quad.tl.vertices.x = i * this._itemWidth; - quad.tl.vertices.y = this._itemHeight; - quad.tl.vertices.z = 0.0; - quad.tr.vertices.x = i * this._itemWidth + this._itemWidth; - quad.tr.vertices.y = this._itemHeight; - quad.tr.vertices.z = 0.0; - quad.tl.colors = curColor; - quad.tr.colors = curColor; - quad.bl.colors = curColor; - quad.br.colors = curColor; + var locQuadTL = quad.tl, locQuadTR = quad.tr, locQuadBL = quad.bl, locQuadBR = quad.br; + locQuadTL.texCoords.u = left; + locQuadTL.texCoords.v = top; + locQuadTR.texCoords.u = right; + locQuadTR.texCoords.v = top; + locQuadBL.texCoords.u = left; + locQuadBL.texCoords.v = bottom; + locQuadBR.texCoords.u = right; + locQuadBR.texCoords.v = bottom; + + locQuadBL.vertices.x = (i * locItemWidth); + locQuadBL.vertices.y = 0; + locQuadBL.vertices.z = 0.0; + locQuadBR.vertices.x = (i * locItemWidth + locItemWidth); + locQuadBR.vertices.y = 0; + locQuadBR.vertices.z = 0.0; + locQuadTL.vertices.x = i * locItemWidth; + locQuadTL.vertices.y = this._itemHeight; + locQuadTL.vertices.z = 0.0; + locQuadTR.vertices.x = i * locItemWidth + locItemWidth; + locQuadTR.vertices.y = this._itemHeight; + locQuadTR.vertices.z = 0.0; + locQuadTL.colors = curColor; + locQuadTR.colors = curColor; + locQuadBL.colors = curColor; + locQuadBR.colors = curColor; } - if (n > 0 ){ + if (n > 0) { locTextureAtlas.setDirty(true); var totalQuads = locTextureAtlas.getTotalQuads(); if (n > totalQuads) @@ -370,7 +236,28 @@ cc.LabelAtlasWebGL = cc.AtlasNode.extend(/** @lends cc.LabelAtlasWebGL# */{ * set the display string * @param {String} label */ - setString:function (label) { + setString: null, + + _setStringForCanvas: function (label) { + label = String(label); + var len = label.length; + this._string = label; + this.setContentSize(cc.size(len * this._itemWidth, this._itemHeight)); + if (this._children) { + var locChildren = this._children; + len = locChildren.length; + for (var i = 0; i < len; i++) { + var node = locChildren[i]; + if (node) + node.setVisible(false); + } + } + + this.updateAtlasValues(); + this._quadsToDraw = len; + }, + + _setStringForWebGL: function (label) { label = String(label); var len = label.length; if (len > this._textureAtlas.getTotalQuads()) @@ -383,22 +270,46 @@ cc.LabelAtlasWebGL = cc.AtlasNode.extend(/** @lends cc.LabelAtlasWebGL# */{ this._quadsToDraw = len; }, - setOpacity:function (opacity) { - if (this._opacity !== opacity) { - this._super(opacity); + setOpacity: null, + + _setOpacityForCanvas: function (opacity) { + if (this._displayedOpacity !== opacity) { + cc.AtlasNode.prototype.setOpacity.call(this, opacity); + var locChildren = this._children; + for (var i = 0, len = locChildren.length; i < len; i++) { + if (locChildren[i]) + locChildren[i].setOpacity(opacity); + } } + }, + + _setOpacityForWebGL: function (opacity) { + if (this._opacity !== opacity) + cc.AtlasNode.prototype.setOpacity.call(this, opacity); } }); +if(cc.Browser.supportWebGL){ + cc.LabelAtlas.prototype.updateAtlasValues = cc.LabelAtlas.prototype._updateAtlasValuesForWebGL; + cc.LabelAtlas.prototype.setString = cc.LabelAtlas.prototype._setStringForWebGL; + cc.LabelAtlas.prototype.setOpacity = cc.LabelAtlas.prototype._setOpacityForWebGL; +} else { + cc.LabelAtlas.prototype.updateAtlasValues = cc.LabelAtlas.prototype._updateAtlasValuesForCanvas; + cc.LabelAtlas.prototype.setString = cc.LabelAtlas.prototype._setStringForCanvas; + cc.LabelAtlas.prototype.setOpacity = cc.LabelAtlas.prototype._setOpacityForCanvas; +} + /** - * It accepts two groups of parameters: - * a) string, fntFile - * b) label, textureFilename, width, height, startChar + *

+ * It accepts two groups of parameters:
+ * a) string, fntFile
+ * b) label, textureFilename, width, height, startChar
+ *

* @param {String} strText * @param {String} charMapFile charMapFile or fntFile - * @param {Number} itemWidth - * @param {Number} itemHeight - * @param {Number} startCharMap + * @param {Number} [itemWidth=0] + * @param {Number} [itemHeight=0] + * @param {Number} [startCharMap=""] * @return {cc.LabelAtlas|Null} returns the LabelAtlas object on success * @example * //Example @@ -408,13 +319,11 @@ cc.LabelAtlasWebGL = cc.AtlasNode.extend(/** @lends cc.LabelAtlasWebGL# */{ * //creates the cc.LabelAtlas with a string, a fnt file * var myLabel = cc.LabelAtlas.create('Text to display', 'CharMapFile.plist‘); */ -cc.LabelAtlasWebGL.create = function (strText, charMapFile, itemWidth, itemHeight, startCharMap) { - var ret = new cc.LabelAtlasWebGL(); - if (ret && cc.LabelAtlasWebGL.prototype.initWithString.apply(ret,arguments)) { +cc.LabelAtlas.create = function (strText, charMapFile, itemWidth, itemHeight, startCharMap) { + var ret = new cc.LabelAtlas(); + if (ret && cc.LabelAtlas.prototype.initWithString.apply(ret,arguments)) { return ret; } return null; }; -cc.LabelAtlas = cc.Browser.supportWebGL ? cc.LabelAtlasWebGL : cc.LabelAtlasCanvas; - diff --git a/cocos2d/label_nodes/CCLabelBMFont.js b/cocos2d/label_nodes/CCLabelBMFont.js index 421d707939..7b9f3c0319 100644 --- a/cocos2d/label_nodes/CCLabelBMFont.js +++ b/cocos2d/label_nodes/CCLabelBMFont.js @@ -445,6 +445,8 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ _cascadeColorEnabled:false, _cascadeOpacityEnabled:false, + _textureLoaded: false, + _setString:function(newString, needUpdateLabel){ if(!needUpdateLabel){ this._string = newString; @@ -459,10 +461,12 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ selNode.setVisible(false); } } - this.createFontChars(); + if(this._textureLoaded){ + this.createFontChars(); - if(needUpdateLabel) - this.updateLabel(); + if(needUpdateLabel) + this.updateLabel(); + } }, /** * Constructor @@ -489,10 +493,10 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ this._reusedChar = []; }, /** - * @param {CanvasContext} ctx + * @param {CanvasRenderingContext2D} ctx */ draw:function (ctx) { - this._super(); + cc.SpriteBatchNode.prototype.draw.call(this, ctx); //LabelBMFont - Debug draw if (cc.LABELBMFONT_DEBUG_DRAW) { @@ -510,17 +514,19 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ * @param {cc.Color3B} color3 */ setColor:function (color3) { - if ((this._realColor.r == color3.r) && (this._realColor.g == color3.g) && (this._realColor.b == color3.b)) + if (((this._realColor.r == color3.r) && (this._realColor.g == color3.g) && (this._realColor.b == color3.b))) return; this._displayedColor = {r:color3.r, g:color3.g, b:color3.b}; this._realColor = {r:color3.r, g:color3.g, b:color3.b}; - if(this._cascadeColorEnabled){ - var parentColor = cc.white(); - var locParent = this._parent; - if(locParent && locParent.RGBAProtocol && locParent.isCascadeColorEnabled()) - parentColor = locParent.getDisplayedColor(); - this.updateDisplayedColor(parentColor); + if(this._textureLoaded){ + if(this._cascadeColorEnabled){ + var parentColor = cc.white(); + var locParent = this._parent; + if(locParent && locParent.RGBAProtocol && locParent.isCascadeColorEnabled()) + parentColor = locParent.getDisplayedColor(); + this.updateDisplayedColor(parentColor); + } } }, @@ -574,8 +580,15 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ this._displayedOpacity = this._realOpacity * parentOpacity/255.0; var locChildren = this._children; for(var i = 0; i< locChildren; i++){ - locChildren[i].updateDisplayedOpacity(this._displayedOpacity); + var locChild = locChildren[i]; + if(cc.Browser.supportWebGL){ + locChild.updateDisplayedOpacity(this._displayedOpacity); + }else{ + cc.NodeRGBA.prototype.updateDisplayedOpacity.call(locChild, this._displayedOpacity); + locChild.setNodeDirty(); + } } + this._changeTextureColor(); }, isCascadeOpacityEnabled:function(){ @@ -603,7 +616,38 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ var locChildren = this._children; for(var i = 0;i < locChildren.length;i++){ - locChildren[i].updateDisplayedColor(this._displayedColor); + var locChild = locChildren[i]; + if(cc.Browser.supportWebGL){ + locChild.updateDisplayedColor(this._displayedColor); + }else{ + cc.NodeRGBA.prototype.updateDisplayedColor.call(locChild, this._displayedColor); + locChild.setNodeDirty(); + } + } + this._changeTextureColor(); + }, + + _changeTextureColor:function(){ + if(cc.Browser.supportWebGL){ + return; + } + var locElement, locTexture = this.getTexture(); + if (locTexture) { + locElement = locTexture.getHtmlElementObj(); + if (!locElement) + return; + var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(this._originalTexture.getHtmlElementObj()); + if (cacheTextureForColor) { + if (locElement instanceof HTMLCanvasElement && !this._rectRotated) + cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, null, locElement); + else{ + locElement = cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor); + locTexture = new cc.Texture2D(); + locTexture.initWithElement(locElement); + locTexture.handleLoadedTexture(); + this.setTexture(locTexture); + } + } } }, @@ -643,8 +687,23 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ this._configuration = newConf; this._fntFile = fntFile; texture = cc.TextureCache.getInstance().addImage(this._configuration.getAtlasName()); - } else - texture = (cc.renderContextType === cc.CANVAS) ? new Image() : new cc.Texture2D(); + var locIsLoaded = texture.isLoaded(); + this._textureLoaded = locIsLoaded; + if(!locIsLoaded){ + this._textureLoaded = false; + texture.addLoadedEventListener(function(sender){ + this._textureLoaded = true; + //reset the LabelBMFont + this.initWithTexture(sender, theString.length) + this.setString(theString,true); + }, this); + } + } else{ + texture = new cc.Texture2D(); + var image = new Image(); + texture.initWithElement(image); + this._textureLoaded = false; + } if (this.initWithTexture(texture, theString.length)) { this._alignment = alignment || cc.TEXT_ALIGNMENT_LEFT; @@ -666,7 +725,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ this._opacityModifyRGB = locTexture.hasPremultipliedAlpha(); this._reusedChar = new cc.Sprite(); - this._reusedChar.initWithTexture(locTexture, cc.RectMake(0, 0, 0, 0), false); + this._reusedChar.initWithTexture(locTexture, cc.rect(0, 0, 0, 0), false); this._reusedChar.setBatchNode(this); } this.setString(theString,true); @@ -737,26 +796,21 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ rect.y += this._imageOffset.y; var fontChar = this.getChildByTag(i); - var hasSprite = true; + //var hasSprite = true; if (!fontChar) { fontChar = new cc.Sprite(); if ((key === 32) && (locContextType === cc.CANVAS)) { - fontChar.init(); - fontChar.setTextureRect(cc.RectZero(), false, cc.SizeZero()); + fontChar.initWithTexture(locTexture, cc.RectZero(), false); } else fontChar.initWithTexture(locTexture, rect, false); - + fontChar._newTextureWhenChangeColor = true; this.addChild(fontChar, 0, i); } else { if ((key === 32) && (locContextType === cc.CANVAS)) { - fontChar.init(); - fontChar.setTextureRect(cc.RectZero(), false, cc.SizeZero()); + fontChar.setTextureRect(rect, false, cc.SizeZero()); } else { // updating previous sprite - if (locContextType === cc.CANVAS) - fontChar.initWithTexture(locTexture, rect, false); - else - fontChar.setTextureRect(rect, false, rect.size); + fontChar.setTextureRect(rect, false, rect.size); // restore to default in case they were modified fontChar.setVisible(true); } @@ -764,8 +818,14 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ // Apply label properties fontChar.setOpacityModifyRGB(this._opacityModifyRGB); // Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on - fontChar.updateDisplayedColor(this._displayedColor); - fontChar.updateDisplayedOpacity(this._displayedOpacity); + if (cc.Browser.supportWebGL) { + fontChar.updateDisplayedColor(this._displayedColor); + fontChar.updateDisplayedOpacity(this._displayedOpacity); + } else { + cc.NodeRGBA.prototype.updateDisplayedColor.call(fontChar, this._displayedColor); + cc.NodeRGBA.prototype.updateDisplayedOpacity.call(fontChar, this._displayedOpacity); + fontChar.setNodeDirty(); + } var yOffset = this._configuration.commonHeight - fontDef.yOffset; var fontPos = cc.p(nextFontPositionX + fontDef.xOffset + fontDef.rect.width * 0.5 + kerningAmount, @@ -1053,9 +1113,10 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ /** * @param {Number} scale + * @param {Number} [scaleY=null] */ setScale:function (scale, scaleY) { - this._super(scale, scaleY); + cc.Node.prototype.setScale.call(this, scale, scaleY); this.updateLabel(); }, @@ -1063,7 +1124,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ * @param {Number} scaleX */ setScaleX:function (scaleX) { - this._super(scaleX); + cc.Node.prototype.setScaleX.call(this,scaleX); this.updateLabel(); }, @@ -1071,7 +1132,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ * @param {Number} scaleY */ setScaleY:function (scaleY) { - this._super(scaleY); + cc.Node.prototype.setScaleY.call(this,scaleY); this.updateLabel(); }, @@ -1089,11 +1150,23 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ this._fntFile = fntFile; this._configuration = newConf; - this.setTexture(cc.TextureCache.getInstance().addImage(this._configuration.getAtlasName())); - if (cc.renderContextType === cc.CANVAS) { + var texture = cc.TextureCache.getInstance().addImage(this._configuration.getAtlasName()); + var locIsLoaded = texture.isLoaded(); + this._textureLoaded = locIsLoaded; + this.setTexture(texture); + if (cc.renderContextType === cc.CANVAS) this._originalTexture = this.getTexture(); + if(!locIsLoaded){ + texture.addLoadedEventListener(function(sender){ + this._textureLoaded = true; + this.setTexture(sender); + this.createFontChars(); + this._changeTextureColor(); + this.updateLabel(); + }, this); + } else { + this.createFontChars(); } - this.createFontChars(); } }, @@ -1105,12 +1178,12 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ }, /** - * set the anchorpoint of the label + * set the AnchorPoint of the label * @param {cc.Point} point */ setAnchorPoint:function (point) { if (!cc.pointEqualToPoint(point, this._anchorPoint)) { - this._super(point); + cc.Node.prototype.setAnchorPoint.call(this, point); this.updateLabel(); } }, diff --git a/cocos2d/label_nodes/CCLabelTTF.js b/cocos2d/label_nodes/CCLabelTTF.js index d6ec0fd7ba..39731b39bd 100644 --- a/cocos2d/label_nodes/CCLabelTTF.js +++ b/cocos2d/label_nodes/CCLabelTTF.js @@ -24,655 +24,23 @@ THE SOFTWARE. ****************************************************************************/ - -/** - * cc.LabelTTF is a subclass of cc.TextureNode that knows how to render text labels (Canvas implement)
- * All features from cc.TextureNode are valid in cc.LabelTTF
- * cc.LabelTTF objects are slow for js-binding on mobile devices.Consider using CCLabelAtlas or CCLabelBMFont instead.
- * Consider using cc.LabelAtlas or cc.LabelBMFont instead.
- * @class - * @extends cc.Sprite - */ -cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{ - /// ---- common properties start ---- - _dimensions:null, - _hAlignment:cc.TEXT_ALIGNMENT_CENTER, - _vAlignment:cc.VERTICAL_TEXT_ALIGNMENT_TOP, - _fontName:"Arial", - _fontSize:0.0, - _string:"", - _isMultiLine:false, - _fontStyleStr:null, - _colorStyleStr:null, - - // font shadow - _shadowEnabled:false, - _shadowOffset:null, - _shadowOpacity:0, - _shadowBlur:0, - - // font stroke - _strokeEnabled:false, - _strokeColor:null, - _strokeSize:0, - _strokeColorStr:null, - - // font tint - _textFillColor:null, - - /** - * Constructor - */ - ctor:function () { - cc.Sprite.prototype.ctor.call(this); - this._dimensions = cc.SizeZero(); - this._hAlignment = cc.TEXT_ALIGNMENT_CENTER; - this._vAlignment = cc.VERTICAL_TEXT_ALIGNMENT_TOP; - this._opacityModifyRGB = false; - this._fontStyleStr = ""; - this._colorStyleStr = ""; - this._fontName = "Arial"; - this._isMultiLine = false; - - this._shadowEnabled = false; - this._shadowOffset = cc.SizeZero(); - this._shadowOpacity = 0; - this._shadowBlur = 0; - - this._strokeEnabled = false; - this._strokeColor = cc.white(); - this._strokeSize = 0; - this._strokeColorStr = ""; - - this._textFillColor = cc.white(); - this._setColorStyleStr(); - }, - - init:function () { - return this.initWithString([" ", this._fontName, this._fontSize]); - }, - /** - * Prints out a description of this class - * @return {String} - */ - description:function () { - return ""; - }, - - setColor:function (color3) { - this.setFontFillColor(color3, true); - }, - - setOpacity:function (opacity) { - if (this._opacity === opacity) - return; - cc.Sprite.prototype.setOpacity.call(this, opacity); - this._setColorStyleStr(); - }, - - _setColorStyleStr:function () { - this._colorStyleStr = "rgba(" + this._textFillColor.r + "," + this._textFillColor.g + "," + this._textFillColor.b + ", " + this._realOpacity / 255 + ")"; - }, - - /** - * returns the text of the label - * @return {String} - */ - getString:function () { - return this._string; - }, - - /** - * return Horizontal Alignment of cc.LabelTTF - * @return {cc.TEXT_ALIGNMENT_LEFT|cc.TEXT_ALIGNMENT_CENTER|cc.TEXT_ALIGNMENT_RIGHT} - */ - getHorizontalAlignment:function () { - return this._hAlignment; - }, - - /** - * return Vertical Alignment of cc.LabelTTF - * @return {cc.VERTICAL_TEXT_ALIGNMENT_TOP|cc.VERTICAL_TEXT_ALIGNMENT_CENTER|cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM} - */ - getVerticalAlignment:function () { - return this._vAlignment; - }, - - /** - * return Dimensions of cc.LabelTTF - * @return {cc.Size} - */ - getDimensions:function () { - return this._dimensions; - }, - - /** - * return font size of cc.LabelTTF - * @return {Number} - */ - getFontSize:function () { - return this._fontSize; - }, - - /** - * return font name of cc.LabelTTF - * @return {String} - */ - getFontName:function () { - return this._fontName; - }, - - /** - * initializes the cc.LabelTTF with a font name, alignment, dimension and font size - * @param {String} initialize string - * @param {String} fontName - * @param {Number} fontSize - * @param {cc.Size} dimensions - * @param {cc.TEXT_ALIGNMENT_LEFT|cc.TEXT_ALIGNMENT_CENTER|cc.TEXT_ALIGNMENT_RIGHT} alignment - * @return {Boolean} return false on error - */ - initWithString:function (arg) { - var strInfo = arg[0] + "", fontName, fontSize, dimensions, hAlignment, vAlignment; - cc.Assert(strInfo != null, "cc.LabelTTF.initWithString() label is null"); - if (arg.length == 6) { - fontName = arg[1]; - fontSize = arg[2]; - dimensions = arg[3]; - hAlignment = arg[4]; - vAlignment = arg[5]; - } else if (arg.length == 5) { - fontName = arg[1]; - fontSize = arg[2]; - dimensions = arg[3]; - hAlignment = arg[4]; - vAlignment = cc.VERTICAL_TEXT_ALIGNMENT_TOP; - } else { - fontName = arg[1] || "Arial"; - fontSize = arg[2] || 16; - dimensions = cc.size(0, arg[2]); - hAlignment = cc.TEXT_ALIGNMENT_LEFT; - vAlignment = cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM; - } - - if (cc.Sprite.prototype.init.call(this)) { - this._opacityModifyRGB = false; - this._dimensions = cc.size(dimensions.width, dimensions.height); - this._fontName = fontName; - this._hAlignment = hAlignment; - this._vAlignment = vAlignment; - this._fontSize = fontSize; - this._fontStyleStr = this._fontSize + "px '" + this._fontName + "'"; - this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(this._fontName,this._fontSize); - this.setString(strInfo); - return true; - } - - return false; - }, - /// ---- common properties end ---- - - /** - * initializes the CCLabelTTF with a font name, alignment, dimension and font size - * @param {String} text - * @param {cc.FontDefinition} textDefinition - * @return {Boolean} - */ - initWithStringAndTextDefinition:function(text, textDefinition){ - if(!cc.Sprite.prototype.init.call(this)) - return false; - - // prepare everything needed to render the label - this._updateWithTextDefinition(textDefinition, false); - - // set the string - this.setString(text); - - return true; - }, - - /** - * set the text definition used by this label - * @param {cc.FontDefinition} theDefinition - */ - setTextDefinition:function(theDefinition){ - if (theDefinition) - this._updateWithTextDefinition(theDefinition, true); - }, - - /** - * get the text definition used by this label - * @return {cc.FontDefinition} - */ - getTextDefinition:function(){ - return this._prepareTextDefinition(false); - }, - - /** - * enable or disable shadow for the label - * @param {cc.Size} shadowOffset - * @param {Number} shadowOpacity - * @param {Number} shadowBlur - * @param {Boolean} [mustUpdateTexture=false] - */ - enableShadow:function(shadowOffset, shadowOpacity, shadowBlur, mustUpdateTexture){ - if (false === this._shadowEnabled) - this._shadowEnabled = true; - - if ((this._shadowOffset.width != shadowOffset.width) || (this._shadowOffset.height != shadowOffset.height)) { - this._shadowOffset.width = shadowOffset.width; - this._shadowOffset.height = shadowOffset.height; - } - - if (this._shadowOpacity != shadowOpacity ) - this._shadowOpacity = shadowOpacity; - - if (this._shadowBlur != shadowBlur) - this._shadowBlur = shadowBlur; - }, - - /** - * disable shadow rendering - * @param {Boolean} [mustUpdateTexture=false] - */ - disableShadow:function(mustUpdateTexture){ - if (this._shadowEnabled) { - this._shadowEnabled = false; - } - }, - - /** - * enable or disable stroke - * @param {cc.Color3B} strokeColor - * @param {Number} strokeSize - * @param {Boolean} [mustUpdateTexture=] - */ - enableStroke:function(strokeColor, strokeSize, mustUpdateTexture){ - if(this._strokeEnabled === false) - this._strokeEnabled = true; - - var locStrokeColor = this._strokeColor; - if ( (locStrokeColor.r !== strokeColor.r) || (locStrokeColor.g !== strokeColor.g) || (locStrokeColor.b !== strokeColor.b) ) { - this._strokeColor = strokeColor; - this._strokeColorStr = "rgba("+ (0 | strokeColor.r) + "," + (0 | strokeColor.g) + "," + (0 | strokeColor.b) + ", 1)"; - } - - if (this._strokeSize!== strokeSize) - this._strokeSize = strokeSize; - }, - - /** - * disable stroke - * @param {Boolean} mustUpdateTexture - */ - disableStroke:function(mustUpdateTexture){ - if (this._strokeEnabled){ - this._strokeEnabled = false; - } - }, - - /** - * set text tinting - * @param {cc.Color3B} tintColor - * @param {Boolean} mustUpdateTexture - */ - setFontFillColor:function(tintColor, mustUpdateTexture){ - var locTextFillColor = this._textFillColor; - if (locTextFillColor.r != tintColor.r || locTextFillColor.g != tintColor.g || locTextFillColor.b != tintColor.b){ - this._textFillColor = tintColor; - this._setColorStyleStr(); - } - }, - - //set the text definition for this label - _updateWithTextDefinition:function(textDefinition, mustUpdateTexture){ - this._dimensions = cc.SizeMake(textDefinition.fontDimensions.width, textDefinition.fontDimensions.height); - this._hAlignment = textDefinition.fontAlignmentH; - this._vAlignment = textDefinition.fontAlignmentV; - - this._fontName = textDefinition.fontName; - this._fontSize = textDefinition.fontSize; - this._fontStyleStr = this._fontSize + "px '" + this._fontName + "'"; - - - // shadow - if ( textDefinition.shadowEnabled) - this.enableShadow(textDefinition.shadowOffset, textDefinition.shadowOpacity, textDefinition.shadowBlur, false); - - // stroke - if ( textDefinition.strokeEnabled ) - this.enableStroke(textDefinition.strokeColor, textDefinition.strokeSize, false); - - // fill color - this.setFontFillColor(textDefinition.fontFillColor, false); - }, - - _prepareTextDefinition:function(adjustForResolution){ - var texDef = new cc.FontDefinition(); - - if (adjustForResolution){ - texDef.fontSize = this._fontSize * cc.CONTENT_SCALE_FACTOR(); - texDef.fontDimensions = cc.SIZE_POINTS_TO_PIXELS(this._dimensions); - } else { - texDef.fontSize = this._fontSize; - texDef.fontDimensions = cc.SizeMake(this._dimensions.width, this._dimensions.height); - } - - texDef.fontName = this._fontName; - texDef.fontAlignmentH = this._hAlignment; - texDef.fontAlignmentV = this._vAlignment; - - // stroke - if ( this._strokeEnabled ){ - texDef.strokeEnabled = true; - var locStrokeColor = this._strokeColor; - texDef.strokeColor = new cc.Color3B(locStrokeColor.r, locStrokeColor.g, locStrokeColor.b); - texDef.strokeSize = adjustForResolution ? this._strokeSize * cc.CONTENT_SCALE_FACTOR() : this._strokeSize; - }else - texDef.strokeEnabled = false; - - // shadow - if ( this._shadowEnabled ){ - texDef.shadowEnabled = true; - texDef.shadowBlur = this._shadowBlur; - texDef.shadowOpacity = this._shadowOpacity; - - texDef.shadowOffset = adjustForResolution ? cc.SIZE_POINTS_TO_PIXELS(this._shadowOffset) - : cc.size(this._shadowOffset.width,this._shadowOffset.height); - }else - texDef._shadowEnabled = false; - - // text tint - var locTextFillColor = this._textFillColor; - texDef.fontFillColor = new cc.Color3B(locTextFillColor.r, locTextFillColor.g, locTextFillColor.b); - return texDef; - }, - - /** - * changes the string to render - * @warning Changing the string is as expensive as creating a new cc.LabelTTF. To obtain better performance use cc.LabelAtlas - * @param {String} text text for the label - */ - setString:function (text) { - text = String(text); - if (this._string != text) { - this._string = text + ""; - - // Force update - if (this._string.length > 0) - this._updateTTF(); - } - }, - - /** - * set Horizontal Alignment of cc.LabelTTF - * @param {cc.TEXT_ALIGNMENT_LEFT|cc.TEXT_ALIGNMENT_CENTER|cc.TEXT_ALIGNMENT_RIGHT} alignment Horizontal Alignment - */ - setHorizontalAlignment:function (alignment) { - if (alignment !== this._hAlignment) { - this._hAlignment = alignment; - - // Force update - if (this._string.length > 0) - this._updateTTF(); - } - }, - - /** - * set Vertical Alignment of cc.LabelTTF - * @param {cc.VERTICAL_TEXT_ALIGNMENT_TOP|cc.VERTICAL_TEXT_ALIGNMENT_CENTER|cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM} verticalAlignment - */ - setVerticalAlignment:function (verticalAlignment) { - if (verticalAlignment != this._vAlignment) { - this._vAlignment = verticalAlignment; - - // Force update - if (this._string.length > 0) - this._updateTTF(); - } - }, - - /** - * set Dimensions of cc.LabelTTF - * @param {cc.Size} dim - */ - setDimensions:function (dim) { - if (dim.width != this._dimensions.width || dim.height != this._dimensions.height) { - this._dimensions = dim; - - // Force udpate - if (this._string.length > 0) - this._updateTTF(); - } - }, - - /** - * set font size of cc.LabelTTF - * @param {Number} fontSize - */ - setFontSize:function (fontSize) { - if (this._fontSize != fontSize) { - this._fontSize = fontSize; - this._fontStyleStr = this._fontSize + "px '" + this._fontName + "'"; - this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(this._fontName,this._fontSize); - // Force update - if (this._string.length > 0) - this._updateTTF(); - } - }, - - /** - * set font name of cc.LabelTTF - * @param {String} fontName - */ - setFontName:function (fontName) { - if (this._fontName != fontName) { - this._fontName = new String(fontName); - this._fontStyleStr = this._fontSize + "px '" + this._fontName + "'"; - this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(this._fontName,this._fontSize); - // Force update - if (this._string.length > 0) - this._updateTTF(); - } - }, - - _updateTTF:function () { - var context = cc.renderContext; - if (context.font != this._fontStyleStr) - context.font = this._fontStyleStr; - // we need to find out if the label needs multiline, if its automatic new line or specified newline - var stringWidth = context.measureText(this._string).width; - var locDimensionsWidth = this._dimensions.width; - if (this._string.indexOf('\n') !== -1 || (locDimensionsWidth !== 0 && stringWidth > locDimensionsWidth && this._string.indexOf(" ") !== -1)) { - var strings = this._strings = this._string.split('\n'); - var lineWidths = this._lineWidths = []; - for (var i = 0; i < strings.length; i++) { - if (strings[i].indexOf(" ") !== -1 && locDimensionsWidth > 0) { - var percent = locDimensionsWidth / context.measureText(this._strings[i]).width; - var startSearch = 0 | (percent * strings[i].length + 1); - var cutoff = startSearch; - var tempLineWidth = 0; - if (percent < 1) { - do { - cutoff = strings[i].lastIndexOf(" ", cutoff - 1); - var str = strings[i].substring(0, cutoff); - tempLineWidth = context.measureText(str).width; - if (cutoff === -1) { - cutoff = strings[i].indexOf(" ", startSearch); - break; - } - } while (tempLineWidth > locDimensionsWidth); - var newline = strings[i].substr(cutoff + 1); - strings.splice(i + 1, 0, newline); - strings[i] = str; - } - } - lineWidths[i] = tempLineWidth || context.measureText(strings[i]).width; - } - this._isMultiLine = true; - } else - this._isMultiLine = false; - - // we will need to change contentSize to cater this - //if dimension is not set, set contentSize according to actual size - if (locDimensionsWidth === 0) { - if (this._isMultiLine) - this.setContentSize(cc.size(Math.max.apply(Math, this._lineWidths), this._fontClientHeight * this._strings.length)); - else - this.setContentSize(cc.size(stringWidth, this._fontClientHeight)); - } else { - if(this._dimensions.height === 0) { - if (this._isMultiLine) - this.setContentSize(cc.size(locDimensionsWidth, this._fontClientHeight * this._strings.length)); - else - this.setContentSize(cc.size(locDimensionsWidth, this._fontClientHeight)); - } else { - //dimension is already set, contentSize must be same as dimension - this.setContentSize(cc.size(locDimensionsWidth, this._dimensions.height)); - } - } - this._anchorPointInPoints.x = this._contentSize.width * this._anchorPoint.x; - this._anchorPointInPoints.y = this._contentSize.height * this._anchorPoint.y; - }, - /** - * renders the label - * @param {CanvasRenderingContext2D|Null} ctx - * @param {Number} renderType - */ - draw:function (ctx, renderType) { - var context = ctx || cc.renderContext; - if (this._flipX) - context.scale(-1, 1); - if (this._flipY) - context.scale(1, -1); - - //this is fillText for canvas - context.fillStyle = this._colorStyleStr; - - if (context.font != this._fontStyleStr) - context.font = this._fontStyleStr; - - //stroke style setup - if(this._strokeEnabled){ - context.lineWidth = this._strokeSize; - context.strokeStyle = this._strokeColorStr; - } - - //shadow style setup - if(this._shadowEnabled){ - var locShadowOffset = this._shadowOffset; - context.shadowColor = "rgba(128,128,128,1)"; - context.shadowOffsetX = locShadowOffset.width; - context.shadowOffsetY = -locShadowOffset.height; - context.shadowBlur = this._shadowBlur; - } - - var locVAlignment = this._vAlignment, locHAlignment = this._hAlignment, - locContentSizeWidth = this._contentSize.width* cc.CONTENT_SCALE_FACTOR(), - locContentSizeHeight = this._contentSize.height* cc.CONTENT_SCALE_FACTOR(); - var locFontHeight = this._fontClientHeight* cc.CONTENT_SCALE_FACTOR(); - - context.textBaseline = cc.LabelTTF._textBaseline[locVAlignment]; - context.textAlign = cc.LabelTTF._textAlign[locHAlignment]; - var xoffset = 0; - if (locHAlignment === cc.TEXT_ALIGNMENT_RIGHT) - xoffset = locContentSizeWidth; - else if (locHAlignment === cc.TEXT_ALIGNMENT_CENTER) - xoffset = locContentSizeWidth / 2; - if (this._isMultiLine) { - var yOffset = 0, strLen = this._strings.length; - if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM) - yOffset = locFontHeight + locContentSizeHeight - locFontHeight * strLen; - else if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_CENTER) - yOffset = locFontHeight / 2 + (locContentSizeHeight - locFontHeight * strLen) / 2; - - for (var i = 0; i < strLen; i++) { - var line = this._strings[i]; - context.fillText(line, xoffset, -locContentSizeHeight + (locFontHeight * i) + yOffset); - } - } else { - if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM){ - context.fillText(this._string, xoffset, 0); - if(this._strokeEnabled) - context.strokeText(this._string, xoffset, 0); - }else if(locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_TOP){ - context.fillText(this._string, xoffset, -locContentSizeHeight); - if(this._strokeEnabled) - context.strokeText(this._string, xoffset, -locContentSizeHeight); - }else{ - context.fillText(this._string, xoffset, -locContentSizeHeight/2); - if(this._strokeEnabled) - context.strokeText(this._string, xoffset, -locContentSizeHeight/2); - } - } - - if (cc.SPRITE_DEBUG_DRAW === 1) { - context.fillStyle = "rgba(255,0,0,0.2)"; - context.lineWidth = 1; - context.shadowColor = ""; - context.shadowOffsetX = 0; - context.shadowOffsetY = 0; - context.shadowBlur = 0; - context.fillRect(this._offsetPosition.x, this._offsetPosition.y, locContentSizeWidth, -locContentSizeHeight); - } - cc.INCREMENT_GL_DRAWS(1); - } -}); - -cc.LabelTTFCanvas._textAlign = ["left", "center", "right"]; - -cc.LabelTTFCanvas._textBaseline = ["top", "middle", "bottom"]; - -/** - * creates a cc.LabelTTF from a fontname, alignment, dimension and font size - * @param {String} label - * @param {String} fontName - * @param {Number} fontSize - * @param {cc.Size} dimensions - * @param {cc.TEXT_ALIGNMENT_LEFT|cc.TEXT_ALIGNMENT_CENTER|cc.TEXT_ALIGNMENT_RIGHT} alignment - * @return {cc.LabelTTF|Null} - * @example - * // Example - * var myLabel = cc.LabelTTF.create('label text', 'Times New Roman', 32, cc.size(32,16), cc.TEXT_ALIGNMENT_LEFT); - */ -cc.LabelTTFCanvas.create = function (/* Multi arguments */) { - var ret = new cc.LabelTTFCanvas(); - if (ret.initWithString(arguments)) - return ret; - return null; -}; - /** - * Create a label with string and a font definition - * @param {String} text - * @param {cc.FontDefinition} textDefinition - * @return {cc.LabelTTF|Null} - */ -cc.LabelTTFCanvas.createWithFontDefinition = function(text, textDefinition){ - var ret = new cc.LabelTTF(); - if(ret && ret.initWithStringAndTextDefinition(text, textDefinition)) - return ret; - return null; -}; - -/** - * cc.LabelTTF is a subclass of cc.TextureNode that knows how to render text labels (WebGL implement)
+ * cc.LabelTTF is a subclass of cc.TextureNode that knows how to render text labels
* All features from cc.TextureNode are valid in cc.LabelTTF
- * cc.LabelTTF objects are slow for js-binding on mobile devices.
+ * cc.LabelTTF objects are slow for js-binding on mobile devices.Consider using cc.LabelAtlas or cc.LabelBMFont instead.
* Consider using cc.LabelAtlas or cc.LabelBMFont instead.
* @class * @extends cc.Sprite */ -cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ - /// ---- common properties start ---- +cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ _dimensions:null, _hAlignment:cc.TEXT_ALIGNMENT_CENTER, _vAlignment:cc.VERTICAL_TEXT_ALIGNMENT_TOP, - _fontName : null, + _fontName: null, _fontSize:0.0, _string:"", _isMultiLine:false, _fontStyleStr:null, - _scaledFontStyleStr:null, _colorStyleStr:null, // font shadow @@ -694,6 +62,10 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ _strokeShadowOffsetX:0, _strokeShadowOffsetY:0, _originalPosition:null, + _needUpdateTexture:false, + + _labelCanvas:null, + _labelContext:null, /** * Constructor @@ -701,15 +73,12 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ ctor:function () { cc.Sprite.prototype.ctor.call(this); this._dimensions = cc.SizeZero(); - this._hAlignment = cc.TEXT_ALIGNMENT_CENTER; + this._hAlignment = cc.TEXT_ALIGNMENT_LEFT; this._vAlignment = cc.VERTICAL_TEXT_ALIGNMENT_TOP; this._opacityModifyRGB = false; this._fontStyleStr = ""; - this._scaledFontStyleStr = ""; this._colorStyleStr = ""; this._fontName = "Arial"; - this._opacity = 255; - this._color = cc.white(); this._isMultiLine = false; this._shadowEnabled = false; @@ -724,16 +93,16 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ this._textFillColor = cc.white(); this._fillColorStr = "rgba(255,255,255,1)"; - this._strokeShadowOffsetX = 0; this._strokeShadowOffsetY = 0; this._originalPosition = cc.PointZero(); + this._needUpdateTexture = false; this._setColorStyleStr(); }, init:function () { - return this.initWithString([" ", this._fontName, this._fontSize]); + return this.initWithString(" ", this._fontName, this._fontSize); }, /** * Prints out a description of this class @@ -743,15 +112,35 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ return ""; }, - setOpacity:function (opacity) { + setColor: null, + + _setColorForCanvas: function (color3) { + this.setFontFillColor(color3, true); + }, + + getColor: null, + + _getColorForCanvas: function () { + return this._textFillColor; + }, + + setOpacity: null, + + _setOpacityForCanvas: function (opacity) { if (this._opacity === opacity) return; cc.Sprite.prototype.setOpacity.call(this, opacity); this._setColorStyleStr(); + this._needUpdateTexture = true; }, _setColorStyleStr:function () { - this._colorStyleStr = "rgba(" + this._color.r + "," + this._color.g + "," + this._color.b + ", " + this._opacity / 255 + ")"; + var locFillColor = this._textFillColor; + this._colorStyleStr = "rgba(" + locFillColor.r + "," + locFillColor.g + "," + locFillColor.b + ", " + this._displayedOpacity / 255 + ")"; + if(this._strokeEnabled){ + var locStrokeColor = this._strokeColor; + this._strokeColorStr = "rgba(" + locStrokeColor.r + "," + locStrokeColor.g + "," + locStrokeColor.b + ", " + this._displayedOpacity / 255 + ")"; + } }, /** @@ -804,54 +193,40 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ /** * initializes the cc.LabelTTF with a font name, alignment, dimension and font size - * @param {String} initialize string + * @param {String} label string * @param {String} fontName * @param {Number} fontSize - * @param {cc.Size} dimensions - * @param {cc.TEXT_ALIGNMENT_LEFT|cc.TEXT_ALIGNMENT_CENTER|cc.TEXT_ALIGNMENT_RIGHT} alignment + * @param {cc.Size} [dimensions=] + * @param {Number} [hAlignment=] + * @param {Number} [vAlignment=] * @return {Boolean} return false on error */ - initWithString:function (arg) { - var strInfo = (arg[0] == undefined ) ? " " : arg[0] + "", fontName, fontSize, dimensions, hAlignment, vAlignment; + initWithString:function (label, fontName, fontSize, dimensions, hAlignment, vAlignment) { + var strInfo = label + ""; cc.Assert(strInfo != null, "cc.LabelTTF.initWithString() label is null"); - if (arg.length == 6) { - fontName = arg[1]; - fontSize = arg[2]; - dimensions = arg[3]; - hAlignment = arg[4]; - vAlignment = arg[5]; - } else if (arg.length == 5) { - fontName = arg[1]; - fontSize = arg[2]; - dimensions = arg[3]; - hAlignment = arg[4]; - vAlignment = cc.VERTICAL_TEXT_ALIGNMENT_TOP; - } else { - fontName = arg[1] || "Arial"; - fontSize = arg[2] || 16; - dimensions = cc.size(0, arg[2]); - hAlignment = cc.TEXT_ALIGNMENT_LEFT; - vAlignment = cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM; - } + + fontSize = fontSize || 16; + dimensions = dimensions || cc.size(0, fontSize); + hAlignment = hAlignment || cc.TEXT_ALIGNMENT_LEFT; + vAlignment = vAlignment || cc.VERTICAL_TEXT_ALIGNMENT_TOP; if (cc.Sprite.prototype.init.call(this)) { this._opacityModifyRGB = false; this._dimensions = cc.size(dimensions.width, dimensions.height); - this._fontName = fontName; + this._fontName = fontName || "Arial"; this._hAlignment = hAlignment; this._vAlignment = vAlignment; - this._fontSize = fontSize; - this._fontStyleStr = this._fontSize + "px '" + this._fontName + "'"; - this._scaledFontStyleStr = this._fontSize * cc.CONTENT_SCALE_FACTOR() + "px '" + this._fontName + "'"; - this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(this._fontName,this._fontSize); + this._fontSize = fontSize * cc.CONTENT_SCALE_FACTOR(); + this._fontStyleStr = this._fontSize + "px '" + fontName + "'"; + this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(fontName,this._fontSize); this.setString(strInfo); + this._setColorStyleStr(); this._updateTexture(); this._needUpdateTexture = false; return true; } return false; }, - /// ---- common properties end ---- /** * initializes the CCLabelTTF with a font name, alignment, dimension and font size @@ -859,7 +234,22 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ * @param {cc.FontDefinition} textDefinition * @return {Boolean} */ - initWithStringAndTextDefinition:function(text, textDefinition){ + initWithStringAndTextDefinition:null, + + _initWithStringAndTextDefinitionForCanvas:function(text, textDefinition){ + if(!cc.Sprite.prototype.init.call(this)) + return false; + + // prepare everything needed to render the label + this._updateWithTextDefinition(textDefinition, false); + + // set the string + this.setString(text); + + return true; + }, + + _initWithStringAndTextDefinitionForWebGL:function(text, textDefinition){ if(!cc.Sprite.prototype.init.call(this)) return false; @@ -903,12 +293,10 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ if (false === this._shadowEnabled) this._shadowEnabled = true; - - if(this._shadowOffset){ - if ((this._shadowOffset.width != shadowOffset.width) || (this._shadowOffset.height != shadowOffset.height)) { - this._shadowOffset.width = shadowOffset.width; - this._shadowOffset.height = shadowOffset.height; - } + var locShadowOffset = this._shadowOffset; + if (locShadowOffset && (locShadowOffset.width != shadowOffset.width) || (locShadowOffset.height != shadowOffset.height)) { + locShadowOffset.width = shadowOffset.width; + locShadowOffset.height = shadowOffset.height; } if (this._shadowOpacity != shadowOpacity ) @@ -950,7 +338,7 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ if (this._strokeSize!== strokeSize) this._strokeSize = strokeSize || 0; - this._needUpdateTexture = true; + this._needUpdateTexture = true; }, /** @@ -969,29 +357,42 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ * @param {cc.Color3B} tintColor * @param {Boolean} [mustUpdateTexture=false] */ - setFontFillColor:function(tintColor, mustUpdateTexture){ + setFontFillColor:null, + + _setFontFillColorForCanvas: function (tintColor, mustUpdateTexture) { + var locTextFillColor = this._textFillColor; + if (locTextFillColor.r != tintColor.r || locTextFillColor.g != tintColor.g || locTextFillColor.b != tintColor.b) { + this._textFillColor = tintColor; + this._setColorStyleStr(); + this._needUpdateTexture = true; + } + }, + + _setFontFillColorForWebGL: function (tintColor, mustUpdateTexture) { var locTextFillColor = this._textFillColor; - if (locTextFillColor.r != tintColor.r || locTextFillColor.g != tintColor.g || locTextFillColor.b != tintColor.b){ + if (locTextFillColor.r != tintColor.r || locTextFillColor.g != tintColor.g || locTextFillColor.b != tintColor.b) { this._textFillColor = tintColor; - this._fillColorStr = "rgba("+ (0 | tintColor.r) + "," + (0 | tintColor.g) + "," + (0 | tintColor.b) + ", 1)"; + this._fillColorStr = "rgba(" + (0 | tintColor.r) + "," + (0 | tintColor.g) + "," + (0 | tintColor.b) + ", 1)"; this._needUpdateTexture = true; } }, //set the text definition for this label _updateWithTextDefinition:function(textDefinition, mustUpdateTexture){ - if(textDefinition.fontDimensions) - this._dimensions = cc.SizeMake(textDefinition.fontDimensions.width, textDefinition.fontDimensions.height); - else - this._dimensions = cc.SizeMake(0,0); + if(textDefinition.fontDimensions){ + this._dimensions.width = textDefinition.fontDimensions.width; + this._dimensions.height = textDefinition.fontDimensions.height; + } else { + this._dimensions.width = 0; + this._dimensions.height = 0; + } this._hAlignment = textDefinition.fontAlignmentH; this._vAlignment = textDefinition.fontAlignmentV; this._fontName = textDefinition.fontName; - this._fontSize = textDefinition.fontSize || 12; + this._fontSize = textDefinition.fontSize||12; this._fontStyleStr = this._fontSize + "px '" + this._fontName + "'"; - this._scaledFontStyleStr = this._fontSize * cc.CONTENT_SCALE_FACTOR() + "px '" + this._fontName + "'"; this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(this._fontName,this._fontSize); // shadow @@ -1012,13 +413,12 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ _prepareTextDefinition:function(adjustForResolution){ var texDef = new cc.FontDefinition(); - //Do these reference to CONTENT_SCALE_FACTOR need to be removed ? if (adjustForResolution){ texDef.fontSize = this._fontSize * cc.CONTENT_SCALE_FACTOR(); texDef.fontDimensions = cc.SIZE_POINTS_TO_PIXELS(this._dimensions); } else { texDef.fontSize = this._fontSize; - texDef.fontDimensions = cc.SizeMake(this._dimensions.width, this._dimensions.height); + texDef.fontDimensions = cc.size(this._dimensions.width, this._dimensions.height); } texDef.fontName = this._fontName; @@ -1072,7 +472,7 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ * @param {cc.TEXT_ALIGNMENT_LEFT|cc.TEXT_ALIGNMENT_CENTER|cc.TEXT_ALIGNMENT_RIGHT} alignment Horizontal Alignment */ setHorizontalAlignment:function (alignment) { - if (alignment != this._hAlignment) { + if (alignment !== this._hAlignment) { this._hAlignment = alignment; // Force update @@ -1111,10 +511,9 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ * @param {Number} fontSize */ setFontSize:function (fontSize) { - if (this._fontSize != fontSize) { + if (this._fontSize !== fontSize) { this._fontSize = fontSize; this._fontStyleStr = fontSize + "px '" + this._fontName + "'"; - this._scaledFontStyleStr = this._fontSize * cc.CONTENT_SCALE_FACTOR() + "px '" + this._fontName + "'"; this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(this._fontName,fontSize); // Force update this._needUpdateTexture = true; @@ -1126,17 +525,16 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ * @param {String} fontName */ setFontName:function (fontName) { - if (this._fontName && this._fontName != fontName) { + if (this._fontName && this._fontName != fontName ) { this._fontName = fontName; this._fontStyleStr = this._fontSize + "px '" + fontName + "'"; - this._scaledFontStyleStr = this._fontSize * cc.CONTENT_SCALE_FACTOR() + "px '" + this._fontName + "'"; this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(fontName,this._fontSize); // Force update this._needUpdateTexture = true; } }, - _drawTTFInCanvasForWebGL: function (context) { + _drawTTFInCanvas: function (context) { if (!context) return; @@ -1145,12 +543,16 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ context.setTransform(1, 0, 0, 1, 0, locContentSizeHeight); //this is fillText for canvas - if (context.font != this._scaledFontStyleStr) - context.font = this._scaledFontStyleStr; - context.fillStyle = this._fillColorStr; + if (context.font != this._fontStyleStr) + context.font = this._fontStyleStr; + if(cc.renderContextType === cc.CANVAS) + context.fillStyle = this._colorStyleStr; + else + context.fillStyle = "rgba(255,255,255,1)"; //stroke style setup - if (this._strokeEnabled) { + var locStrokeEnabled = this._strokeEnabled; + if (locStrokeEnabled) { context.lineWidth = this._strokeSize; context.strokeStyle = this._strokeColorStr; } @@ -1199,26 +601,26 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ for (var i = 0; i < locStrLen; i++) { var line = this._strings[i]; var tmpOffsetY = -locContentSizeHeight + (locFontHeight * i) + yOffset; - context.fillText(line, xOffset, tmpOffsetY); - if (this._strokeEnabled) + if (locStrokeEnabled) context.strokeText(line, xOffset, tmpOffsetY); + context.fillText(line, xOffset, tmpOffsetY); } } else { if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM) { yOffset = isNegForOffsetY ? -locStrokeShadowOffsetY : 0; - context.fillText(this._string, xOffset, yOffset); - if (this._strokeEnabled) + if (locStrokeEnabled) context.strokeText(this._string, xOffset, yOffset); + context.fillText(this._string, xOffset, yOffset); } else if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_TOP) { yOffset = isNegForOffsetY ? -locStrokeShadowOffsetY/2 -locContentSizeHeight : - locContentSizeHeight + locStrokeShadowOffsetY/2; - context.fillText(this._string, xOffset, yOffset); - if (this._strokeEnabled) + if (locStrokeEnabled) context.strokeText(this._string, xOffset, yOffset); + context.fillText(this._string, xOffset, yOffset); } else { yOffset = isNegForOffsetY ? -locStrokeShadowOffsetY -locContentSizeHeight / 2 : - locContentSizeHeight / 2; - context.fillText(this._string, xOffset, yOffset); - if (this._strokeEnabled) + if (locStrokeEnabled) context.strokeText(this._string, xOffset, yOffset); + context.fillText(this._string, xOffset, yOffset); } } }, @@ -1228,10 +630,11 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ return this._labelContext; if (!this._labelCanvas) { - this._labelCanvas = document.createElement("canvas"); + var locCanvas = document.createElement("canvas"); var labelTexture = new cc.Texture2D(); - labelTexture.initWithElement(this._labelCanvas); + labelTexture.initWithElement(locCanvas); this.setTexture(labelTexture); + this._labelCanvas = locCanvas; } this._labelContext = this._labelCanvas.getContext("2d"); return this._labelContext; @@ -1283,18 +686,19 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ //get offset for stroke and shadow if (locDimensionsWidth === 0) { if (this._isMultiLine) - locSize = cc.size(Math.max.apply(Math, this._lineWidths) + locStrokeShadowOffsetX, (this._fontClientHeight * this._strings.length) + locStrokeShadowOffsetY); + locSize = cc.size(0 | (Math.max.apply(Math, this._lineWidths) + locStrokeShadowOffsetX), + 0 | ((this._fontClientHeight * this._strings.length) + locStrokeShadowOffsetY)); else - locSize = cc.size(stringWidth + locStrokeShadowOffsetX, this._fontClientHeight + locStrokeShadowOffsetY); + locSize = cc.size(0 | (stringWidth + locStrokeShadowOffsetX), 0 | (this._fontClientHeight + locStrokeShadowOffsetY)); } else { if(this._dimensions.height === 0){ if (this._isMultiLine) - locSize = cc.size(locDimensionsWidth + locStrokeShadowOffsetX, (this._fontClientHeight * this._strings.length) + locStrokeShadowOffsetY); + locSize = cc.size(0 | (locDimensionsWidth + locStrokeShadowOffsetX), 0 | ((this._fontClientHeight * this._strings.length) + locStrokeShadowOffsetY)); else - locSize = cc.size(locDimensionsWidth + locStrokeShadowOffsetX, this._fontClientHeight + locStrokeShadowOffsetY); + locSize = cc.size(0 | (locDimensionsWidth + locStrokeShadowOffsetX), 0 | (this._fontClientHeight + locStrokeShadowOffsetY)); } else { //dimension is already set, contentSize must be same as dimension - locSize = cc.size(locDimensionsWidth + locStrokeShadowOffsetX, this._dimensions.height + locStrokeShadowOffsetY); + locSize = cc.size(0 | (locDimensionsWidth + locStrokeShadowOffsetX), 0 | (this._dimensions.height + locStrokeShadowOffsetY)); } } this.setContentSize(locSize); @@ -1308,68 +712,89 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ }, setPosition:function(posX, posY){ - if(posY) - this._originalPosition = cc.p(posX, posY); - else - this._originalPosition = cc.p(posX.x, posX.y); + var locOriginalPosition = this._originalPosition; + if (arguments.length == 2){ + locOriginalPosition.x = posX; + locOriginalPosition.y = posY; + }else { + locOriginalPosition.x = posX.x; + locOriginalPosition.y = posX.y; + } //get real position var locStrokeShadowOffsetX = 0, locStrokeShadowOffsetY = 0; if(this._strokeEnabled) locStrokeShadowOffsetX = locStrokeShadowOffsetY = this._strokeSize * 2; - if(this._shadowEnabled){ + if (this._shadowEnabled) { var locOffsetSize = this._shadowOffset; - locStrokeShadowOffsetX += locOffsetSize.width> 0?0:locOffsetSize.width; - locStrokeShadowOffsetY += locOffsetSize.height>0?0:locOffsetSize.height; + locStrokeShadowOffsetX += locOffsetSize.width > 0 ? 0 : locOffsetSize.width; + locStrokeShadowOffsetY += locOffsetSize.height > 0 ? 0 : locOffsetSize.height; } - var realPosition = cc.p(this._originalPosition.x + locStrokeShadowOffsetX, this._originalPosition.y + locStrokeShadowOffsetY); + var realPosition = cc.p(locOriginalPosition.x + locStrokeShadowOffsetX, locOriginalPosition.y + locStrokeShadowOffsetY); cc.Sprite.prototype.setPosition.call(this, realPosition); }, + setPositionX:function(x){ + this._originalPosition.x = x; + cc.Sprite.prototype.setPositionX.call(this, x); + }, + + setPositionY:function(y){ + this._originalPosition.y = y; + cc.Sprite.prototype.setPositionY.call(this, y); + }, + getPosition:function(){ return cc.p(this._originalPosition.x, this._originalPosition.y); }, _updateTexture:function () { - this._labelContext = this._getLabelContext(); + var locContext = this._getLabelContext(), locLabelCanvas = this._labelCanvas; + var locContentSize = this._contentSize; if(this._string.length === 0){ - this._labelCanvas.width = 1; - this._labelCanvas.height = this._contentSize.height; - this.setTextureRect(cc.rect(0, 0, 1, this._contentSize.height)); + locLabelCanvas.width = 1; + locLabelCanvas.height = locContentSize.height; + this.setTextureRect(cc.rect(0, 0, 1, locContentSize.height)); return true; } //set size for labelCanvas - this._labelContext.font = this._fontStyleStr; + locContext.font = this._fontStyleStr; this._updateTTF(); - var width = this._contentSize.width, height = this._contentSize.height; - this._labelCanvas.width = width * cc.CONTENT_SCALE_FACTOR(); - this._labelCanvas.height = height * cc.CONTENT_SCALE_FACTOR();; + var width = locContentSize.width, height = locContentSize.height; + locLabelCanvas.width = width; + locLabelCanvas.height = height; //draw text to labelCanvas - this._drawTTFInCanvasForWebGL(this._labelContext); - + this._drawTTFInCanvas(locContext); this._texture.handleLoadedTexture(); this.setTextureRect(cc.rect(0, 0, width, height)); return true; }, - _needUpdateTexture:false, - visit:function(){ + visit:function(ctx){ + if(!this._string || this._string == "") + return; if(this._needUpdateTexture ){ this._needUpdateTexture = false; this._updateTexture(); } - cc.Sprite.prototype.visit.call(this); + var context = ctx || cc.renderContext; + cc.Sprite.prototype.visit.call(this,context); }, + draw: null, + /** * draw sprite to canvas * @param {WebGLRenderingContext} ctx 3d context of canvas */ - draw:function (ctx) { + _drawForWebGL: function (ctx) { + if (!this._string || this._string == "") + return; + var gl = ctx || cc.renderContext, locTexture = this._texture; //cc.Assert(!this._batchNode, "If cc.Sprite is being rendered by cc.SpriteBatchNode, cc.Sprite#draw SHOULD NOT be called"); @@ -1398,11 +823,12 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ if (cc.SPRITE_DEBUG_DRAW === 1) { // draw bounding box + var locQuad = this._quad; var verticesG1 = [ - cc.p(this._quad.tl.vertices.x, this._quad.tl.vertices.y), - cc.p(this._quad.bl.vertices.x, this._quad.bl.vertices.y), - cc.p(this._quad.br.vertices.x, this._quad.br.vertices.y), - cc.p(this._quad.tr.vertices.x, this._quad.tr.vertices.y) + cc.p(locQuad.tl.vertices.x, locQuad.tl.vertices.y), + cc.p(locQuad.bl.vertices.x, locQuad.bl.vertices.y), + cc.p(locQuad.br.vertices.x, locQuad.br.vertices.y), + cc.p(locQuad.tr.vertices.x, locQuad.tr.vertices.y) ]; cc.drawingUtil.drawPoly(verticesG1, 4, true); } else if (cc.SPRITE_DEBUG_DRAW === 2) { @@ -1414,33 +840,45 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{ cc.drawingUtil.drawPoly(verticesG2, 4, true); } // CC_SPRITE_DEBUG_DRAW cc.g_NumberOfDraws++; - }, - - releaseTexture:function(){ - if(this._texture) - this._texture.releaseTexture(); } }); -cc.LabelTTFWebGL._textAlign = ["left", "center", "right"]; - -cc.LabelTTFWebGL._textBaseline = ["top", "middle", "bottom"]; +if(cc.Browser.supportWebGL){ + cc.LabelTTF.prototype.setColor = cc.Sprite.prototype.setColor; + cc.LabelTTF.prototype.getColor = cc.Sprite.prototype.getColor; + cc.LabelTTF.prototype.setOpacity = cc.Sprite.prototype.setOpacity; + cc.LabelTTF.prototype.initWithStringAndTextDefinition = cc.LabelTTF.prototype._initWithStringAndTextDefinitionForWebGL; + cc.LabelTTF.prototype.setFontFillColor = cc.LabelTTF.prototype._setFontFillColorForWebGL; + cc.LabelTTF.prototype.draw = cc.LabelTTF.prototype._drawForWebGL; +} else { + cc.LabelTTF.prototype.setColor = cc.LabelTTF.prototype._setColorForCanvas; + cc.LabelTTF.prototype.getColor = cc.LabelTTF.prototype._getColorForCanvas; + cc.LabelTTF.prototype.setOpacity = cc.LabelTTF.prototype._setOpacityForCanvas; + cc.LabelTTF.prototype.initWithStringAndTextDefinition = cc.LabelTTF.prototype._initWithStringAndTextDefinitionForCanvas; + cc.LabelTTF.prototype.setFontFillColor = cc.LabelTTF.prototype._setFontFillColorForCanvas; + cc.LabelTTF.prototype.draw = cc.Sprite.prototype.draw; +} + +cc.LabelTTF._textAlign = ["left", "center", "right"]; + +cc.LabelTTF._textBaseline = ["top", "middle", "bottom"]; /** * creates a cc.LabelTTF from a fontname, alignment, dimension and font size * @param {String} label * @param {String} fontName * @param {Number} fontSize - * @param {cc.Size} dimensions - * @param {cc.TEXT_ALIGNMENT_LEFT|cc.TEXT_ALIGNMENT_CENTER|cc.TEXT_ALIGNMENT_RIGHT} alignment + * @param {cc.Size} [dimensions=cc.SIZE_ZERO] + * @param {Number} [hAlignment] + * @param {Number} [vAlignment=cc.VERTICAL_TEXT_ALIGNMENT_TOP] * @return {cc.LabelTTF|Null} * @example * // Example * var myLabel = cc.LabelTTF.create('label text', 'Times New Roman', 32, cc.size(32,16), cc.TEXT_ALIGNMENT_LEFT); */ -cc.LabelTTFWebGL.create = function (/* Multi arguments */) { - var ret = new cc.LabelTTFWebGL(); - if (ret.initWithString(arguments)) +cc.LabelTTF.create = function (label, fontName, fontSize, dimensions, hAlignment, vAlignment) { + var ret = new cc.LabelTTF(); + if (ret.initWithString(label, fontName, fontSize, dimensions, hAlignment, vAlignment)) return ret; return null; }; @@ -1451,15 +889,13 @@ cc.LabelTTFWebGL.create = function (/* Multi arguments */) { * @param {cc.FontDefinition} textDefinition * @return {cc.LabelTTF|Null} */ -cc.LabelTTFWebGL.createWithFontDefinition = function(text, textDefinition){ +cc.LabelTTF.createWithFontDefinition = function(text, textDefinition){ var ret = new cc.LabelTTF(); if(ret && ret.initWithStringAndTextDefinition(text, textDefinition)) return ret; return null; }; -cc.LabelTTF = (cc.Browser.supportWebGL) ? cc.LabelTTFWebGL : cc.LabelTTFCanvas; - if(cc.USE_LA88_LABELS) cc.LabelTTF._SHADER_PROGRAM = cc.SHADER_POSITION_TEXTURECOLOR; else @@ -1467,7 +903,6 @@ else cc.LabelTTF.__labelHeightDiv = document.createElement("div"); cc.LabelTTF.__labelHeightDiv.style.fontFamily = "Arial"; -cc.LabelTTF.__labelHeightDiv.innerHTML = "ajghl~!"; cc.LabelTTF.__labelHeightDiv.style.position = "absolute"; cc.LabelTTF.__labelHeightDiv.style.left = "-100px"; cc.LabelTTF.__labelHeightDiv.style.top = "-100px"; @@ -1475,11 +910,19 @@ cc.LabelTTF.__labelHeightDiv.style.lineHeight = "normal"; document.body.appendChild(cc.LabelTTF.__labelHeightDiv); cc.LabelTTF.__getFontHeightByDiv = function(fontName, fontSize){ + var clientHeight = cc.LabelTTF.__fontHeightCache[fontName + "." + fontSize]; + if (clientHeight > 0) return clientHeight; var labelDiv = cc.LabelTTF.__labelHeightDiv; + labelDiv.innerHTML = "ajghl~!"; labelDiv.style.fontFamily = fontName; labelDiv.style.fontSize = fontSize + "px"; - return labelDiv.clientHeight ; + clientHeight = labelDiv.clientHeight ; + cc.LabelTTF.__fontHeightCache[fontName + "." + fontSize] = clientHeight; + labelDiv.innerHTML = ""; + return clientHeight; }; +cc.LabelTTF.__fontHeightCache = {}; + diff --git a/cocos2d/layers_scenes_transitions_nodes/CCLayer.js b/cocos2d/layers_scenes_transitions_nodes/CCLayer.js index 2cf2d02271..9b17d55273 100644 --- a/cocos2d/layers_scenes_transitions_nodes/CCLayer.js +++ b/cocos2d/layers_scenes_transitions_nodes/CCLayer.js @@ -81,9 +81,9 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{ */ registerWithTouchDispatcher:function () { if (this._touchMode === cc.TOUCH_ALL_AT_ONCE) - cc.Director.getInstance().getTouchDispatcher().addStandardDelegate(this, 0); + cc.registerStandardDelegate(this,this._touchPriority); else - cc.Director.getInstance().getTouchDispatcher().addTargetedDelegate(this, this._touchPriority, true); + cc.registerTargetedDelegate(this._touchPriority, true, this); }, isMouseEnabled:function () { @@ -140,7 +140,7 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{ this.registerWithTouchDispatcher(); } else { // have problems? - cc.Director.getInstance().getTouchDispatcher().removeDelegate(this); + cc.unregisterTouchDelegate(this); } } } @@ -222,15 +222,12 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{ */ setAccelerometerInterval:function (interval) { if (this._isAccelerometerEnabled) { - if (this._running) { - var director = cc.Director.getInstance(); - director.getAccelerometer().setAccelerometerInterval(interval); - } + cc.Director.getInstance().getAccelerometer().setAccelerometerInterval(interval); } }, onAccelerometer:function (accelerationValue) { - //Layer#onAccelerometer override me + cc.Assert(false, "Layer#onAccelerometer override me"); }, /** @@ -292,7 +289,7 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{ onExit:function () { var director = cc.Director.getInstance(); if (this._isTouchEnabled) - director.getTouchDispatcher().removeDelegate(this); + cc.unregisterTouchDelegate(this); // remove this layer from the delegates who concern Accelerometer Sensor if (this._isAccelerometerEnabled) @@ -526,7 +523,7 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{ /** * Call back when a key is pressed down - * @param {Integer} keyCode + * @param {Number} keyCode * @example * // example * if(keyCode == cc.KEY.w){} @@ -536,7 +533,7 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{ /** * Call back when a key is released - * @param {Integer} keyCode + * @param {Number} keyCode * @example * // example * if(keyCode == cc.KEY.w){} @@ -680,17 +677,16 @@ cc.LayerRGBA = cc.Layer.extend(/** @lends cc.LayerRGBA# */{ }, updateDisplayedColor: function (parentColor) { - var locDispColor = this._displayedColor, locRealColor = this._realColor; - locDispColor.r = locRealColor.r * parentColor.r/255.0; - locDispColor.g = locRealColor.g * parentColor.g/255.0; - locDispColor.b = locRealColor.b * parentColor.b/255.0; + this._displayedColor.r = this._realColor.r * parentColor.r/255.0; + this._displayedColor.g = this._realColor.g * parentColor.g/255.0; + this._displayedColor.b = this._realColor.b * parentColor.b/255.0; if (this._cascadeColorEnabled){ - var selChildren = this._children; - for(var i = 0; i< selChildren.length;i++){ - var item = selChildren[i]; - if(item && item.RGBAProtocol) - item.updateDisplayedColor(locDispColor); + var locChildren = this._children; + for(var i = 0; i < locChildren.length; i++){ + var selItem = locChildren[i]; + if(selItem && selItem.RGBAProtocol) + selItem.updateDisplayedColor(this._displayedColor); } } }, @@ -712,15 +708,16 @@ cc.LayerRGBA = cc.Layer.extend(/** @lends cc.LayerRGBA# */{ }); /** - * CCLayerColor is a subclass of CCLayer that implements the CCRGBAProtocol protocol. (Canvas implement)
- * All features from CCLayer are valid, plus the following new features:
- *
  • opacity
  • - *
  • RGB colors
+ *

+ * CCLayerColor is a subclass of CCLayer that implements the CCRGBAProtocol protocol.
+ * All features from CCLayer are valid, plus the following new features:
+ *

  • opacity

  • + *
  • RGB colors

+ *

* @class * @extends cc.Layer */ -cc.LayerColorCanvas = cc.LayerRGBA.extend(/** @lends cc.LayerColorCanvas# */{ - // ---- common properties start ---- +cc.LayerColor = cc.LayerRGBA.extend(/** @lends cc.LayerColor# */{ _blendFunc:null, /** @@ -780,188 +777,8 @@ cc.LayerColorCanvas = cc.LayerRGBA.extend(/** @lends cc.LayerColorCanvas# */{ cc.LayerRGBA.prototype.setOpacity.call(this, opacity); this._updateColor(); }, - // ---- common properties end ---- - - _updateColor:function () { - }, _isLighterMode:false, - /** - * Constructor - */ - ctor:function () { - cc.LayerRGBA.prototype.ctor.call(this); - this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST); - this._color = new cc.Color4B(0, 0, 0, 0); - this._opacity = 255; - }, - - /** - * blendFunc setter - * @param {Number} src - * @param {Number} dst - */ - setBlendFunc:function (src, dst) { - if (arguments.length == 1) - this._blendFunc = src; - else - this._blendFunc = {src:src, dst:dst}; - this._isLighterMode = (this._blendFunc && (this._blendFunc.src == 1) && (this._blendFunc.dst == 771)); - }, - - /** - * @param {cc.Color4B} color - * @param {Number} width - * @param {Number} height - * @return {Boolean} - */ - init:function (color, width, height) { - if(!cc.Layer.prototype.init.call(this)) - return false; - - var winSize = cc.Director.getInstance().getWinSize(); - color = color || new cc.Color4B(0, 0, 0, 255); - width = width || winSize.width; - height = height || winSize.height; - - this._displayedColor.r = color.r; - this._displayedColor.g = color.g; - this._displayedColor.b = color.b; - - this._realColor.r = color.r; - this._realColor.g = color.g; - this._realColor.b = color.b; - - this._opacity = color.a; - this.setContentSize(cc.size(width, height)); - this._updateColor(); - return true; - }, - - /** - * renders the layer - * @param {CanvasContext|Null} ctx - */ - draw:function (ctx) { - var context = ctx || cc.renderContext; - - var tWidth = this.getContentSize().width; - var tHeight = this.getContentSize().height; - var locDisplayedColor = this._displayedColor; - - context.fillStyle = "rgba(" + (0 | locDisplayedColor.r) + "," + (0 | locDisplayedColor.g) + "," + (0 | locDisplayedColor.b) + "," + this._displayedOpacity / 255 + ")"; - context.fillRect(0, 0, tWidth, -tHeight); - - cc.g_NumberOfDraws++; - } -}); - -/** - * creates a cc.LayerColorCanvas with color, width and height in Points - * @param {cc.Color4B} color - * @param {Number|Null} width - * @param {Number|Null} height - * @return {cc.LayerColor} - * @example - * // Example - * //Create a yellow color layer as background - * var yellowBackground = cc.LayerColor.create(cc.c4b(255,255,0,255)); - * //If you didnt pass in width and height, it defaults to the same size as the canvas - * - * //create a yellow box, 200 by 200 in size - * var yellowBox = cc.LayerColorCanvas.create(cc.c3b(255,255,0,255), 200, 200); - */ -cc.LayerColorCanvas.create = function (color, width, height) { - var ret = new cc.LayerColorCanvas(); - switch (arguments.length) { - case 0: - ret.init(); - break; - case 1: - ret.init(color); - break; - case 3: - ret.init(color, width, height); - break; - default : - ret.init(); - break; - } - return ret; -}; - - -/** - * CCLayerColor is a subclass of CCLayer that implements the CCRGBAProtocol protocol. (WebGL implement)
- * All features from CCLayer are valid, plus the following new features:
- *
  • opacity
  • - *
  • RGB colors
- * @class - * @extends cc.Layer - */ -cc.LayerColorWebGL = cc.LayerRGBA.extend(/** @lends cc.LayerColorCanvas# */{ - // ---- common properties start ---- - _blendFunc:null, - - /** - * blendFunc getter - * @return {cc.BlendFunc} - */ - getBlendFunc:function () { - return this._blendFunc; - }, - - /** - * change width and height in Points - * @param {Number} w width - * @param {Number} h height - */ - changeWidthAndHeight:function (w, h) { - this.setContentSize(cc.size(w, h)); - }, - - /** - * change width in Points - * @param {Number} w width - */ - changeWidth:function (w) { - this.setContentSize(cc.size(w, this._contentSize.height)); - }, - - /** - * change height in Points - * @param {Number} h height - */ - changeHeight:function (h) { - this.setContentSize(cc.size(this._contentSize.width, h)); - }, - - /** - * set OpacityModifyRGB of cc.LayerColor - * @param {Boolean} value - */ - setOpacityModifyRGB:function (value) { - }, - - /** - * is OpacityModifyRGB - * @return {Boolean} - */ - isOpacityModifyRGB:function () { - return false; - }, - - setColor:function(color){ - cc.LayerRGBA.prototype.setColor.call(this, color); - this._updateColor(); - }, - - setOpacity:function(opacity){ - cc.LayerRGBA.prototype.setOpacity.call(this, opacity); - this._updateColor(); - }, - - // ---- common properties end ---- _squareVertices:null, _squareColors:null, _verticesFloat32Buffer:null, @@ -972,26 +789,35 @@ cc.LayerColorWebGL = cc.LayerRGBA.extend(/** @lends cc.LayerColorCanvas# */{ /** * Constructor */ - ctor:function () { + ctor: null, + + _ctorForCanvas: function () { + cc.LayerRGBA.prototype.ctor.call(this); + this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST); + this._color = new cc.Color4B(0, 0, 0, 0); + }, + + _ctorForWebGL: function () { cc.LayerRGBA.prototype.ctor.call(this); this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST); this._squareVerticesAB = new ArrayBuffer(32); this._squareColorsAB = new ArrayBuffer(64); - this._squareVertices = [new cc.Vertex2F(0, 0, this._squareVerticesAB, 0), - new cc.Vertex2F(0, 0, this._squareVerticesAB, cc.Vertex2F.BYTES_PER_ELEMENT), - new cc.Vertex2F(0, 0, this._squareVerticesAB, cc.Vertex2F.BYTES_PER_ELEMENT * 2), - new cc.Vertex2F(0, 0, this._squareVerticesAB, cc.Vertex2F.BYTES_PER_ELEMENT * 3)]; - this._squareColors = [new cc.Color4F(0, 0, 0, 1, this._squareColorsAB, 0), - new cc.Color4F(0, 0, 0, 1, this._squareColorsAB, cc.Color4F.BYTES_PER_ELEMENT), - new cc.Color4F(0, 0, 0, 1, this._squareColorsAB, cc.Color4F.BYTES_PER_ELEMENT * 2), - new cc.Color4F(0, 0, 0, 1, this._squareColorsAB, cc.Color4F.BYTES_PER_ELEMENT * 3)]; + var locSquareVerticesAB = this._squareVerticesAB, locSquareColorsAB = this._squareColorsAB; + var locVertex2FLen = cc.Vertex2F.BYTES_PER_ELEMENT, locColor4FLen = cc.Color4F.BYTES_PER_ELEMENT; + this._squareVertices = [new cc.Vertex2F(0, 0, locSquareVerticesAB, 0), + new cc.Vertex2F(0, 0, locSquareVerticesAB, locVertex2FLen), + new cc.Vertex2F(0, 0, locSquareVerticesAB, locVertex2FLen * 2), + new cc.Vertex2F(0, 0, locSquareVerticesAB, locVertex2FLen * 3)]; + this._squareColors = [new cc.Color4F(0, 0, 0, 1, locSquareColorsAB, 0), + new cc.Color4F(0, 0, 0, 1, locSquareColorsAB, locColor4FLen), + new cc.Color4F(0, 0, 0, 1, locSquareColorsAB, locColor4FLen * 2), + new cc.Color4F(0, 0, 0, 1, locSquareColorsAB, locColor4FLen * 3)]; this._verticesFloat32Buffer = cc.renderContext.createBuffer(); this._colorsUint8Buffer = cc.renderContext.createBuffer(); }, - /** * blendFunc setter * @param {Number} src @@ -1002,32 +828,37 @@ cc.LayerColorWebGL = cc.LayerRGBA.extend(/** @lends cc.LayerColorCanvas# */{ this._blendFunc = src; else this._blendFunc = {src:src, dst:dst}; + if(cc.renderContextType === cc.CANVAS) + this._isLighterMode = (this._blendFunc && (this._blendFunc.src == 1) && (this._blendFunc.dst == 771)); }, /** - * @param {cc.Color4B} color - * @param {Number} width - * @param {Number} height + * @param {cc.Color4B} [color=] + * @param {Number} [width=] + * @param {Number} [height=] * @return {Boolean} */ init:function (color, width, height) { if(!cc.Layer.prototype.init.call(this)) return false; - this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_COLOR)); + if(cc.renderContextType !== cc.CANVAS) + this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_COLOR)); var winSize = cc.Director.getInstance().getWinSize(); color = color || new cc.Color4B(0, 0, 0, 255); width = width || winSize.width; height = height || winSize.height; - this._displayedColor.r = color.r; - this._displayedColor.g = color.g; - this._displayedColor.b = color.b; + var locDisplayedColor = this._displayedColor; + locDisplayedColor.r = color.r; + locDisplayedColor.g = color.g; + locDisplayedColor.b = color.b; - this._realColor.r = color.r; - this._realColor.g = color.g; - this._realColor.b = color.b; + var locRealColor = this._realColor; + locRealColor.r = color.r; + locRealColor.g = color.g; + locRealColor.b = color.b; this._displayedOpacity = color.a; this._realOpacity = color.a; @@ -1041,32 +872,67 @@ cc.LayerColorWebGL = cc.LayerRGBA.extend(/** @lends cc.LayerColorCanvas# */{ * override contentSize * @param {cc.Size} size */ - setContentSize:function (size) { - this._squareVertices[1].x = size.width; - this._squareVertices[2].y = size.height; - this._squareVertices[3].x = size.width; - this._squareVertices[3].y = size.height; + setContentSize:null, + + _setContentSizeForWebGL:function (size) { + var locSquareVertices = this._squareVertices; + locSquareVertices[1].x = size.width; + locSquareVertices[2].y = size.height; + locSquareVertices[3].x = size.width; + locSquareVertices[3].y = size.height; this._bindLayerVerticesBufferData(); cc.Layer.prototype.setContentSize.call(this,size); }, - _updateColor:function () { + _updateColor:null, + + _updateColorForCanvas:function () { + }, + + _updateColorForWebGL:function () { var locDisplayedColor = this._displayedColor; - var locDisplayedOpacity = this._displayedOpacity; + var locDisplayedOpacity = this._displayedOpacity, locSquareColors = this._squareColors; for (var i = 0; i < 4; i++) { - this._squareColors[i].r = locDisplayedColor.r / 255; - this._squareColors[i].g = locDisplayedColor.g / 255; - this._squareColors[i].b = locDisplayedColor.b / 255; - this._squareColors[i].a = locDisplayedOpacity / 255; + locSquareColors[i].r = locDisplayedColor.r / 255; + locSquareColors[i].g = locDisplayedColor.g / 255; + locSquareColors[i].b = locDisplayedColor.b / 255; + locSquareColors[i].a = locDisplayedOpacity / 255; } this._bindLayerColorsBufferData(); }, + _bindLayerVerticesBufferData:function () { + var glContext = cc.renderContext; + glContext.bindBuffer(glContext.ARRAY_BUFFER, this._verticesFloat32Buffer); + glContext.bufferData(glContext.ARRAY_BUFFER, this._squareVerticesAB , glContext.STATIC_DRAW); + }, + + _bindLayerColorsBufferData:function () { + var glContext = cc.renderContext; + glContext.bindBuffer(glContext.ARRAY_BUFFER, this._colorsUint8Buffer); + glContext.bufferData(glContext.ARRAY_BUFFER, this._squareColorsAB, glContext.STATIC_DRAW); + }, + /** * renders the layer - * @param {CanvasContext|Null} ctx + * @param {CanvasRenderingContext2D|Null} ctx */ - draw:function (ctx) { + draw:null, + + _drawForCanvas:function (ctx) { + var context = ctx || cc.renderContext; + + var locContentSize = this.getContentSize(); + var locDisplayedColor = this._displayedColor; + + context.fillStyle = "rgba(" + (0 | locDisplayedColor.r) + "," + (0 | locDisplayedColor.g) + "," + + (0 | locDisplayedColor.b) + "," + this._displayedOpacity / 255 + ")"; + context.fillRect(0, 0, locContentSize.width, -locContentSize.height); + + cc.g_NumberOfDraws++; + }, + + _drawForWebGL:function (ctx) { var context = ctx || cc.renderContext; cc.NODE_DRAW_SETUP(this); @@ -1083,26 +949,27 @@ cc.LayerColorWebGL = cc.LayerRGBA.extend(/** @lends cc.LayerColorCanvas# */{ cc.glBlendFunc(this._blendFunc.src, this._blendFunc.dst); context.drawArrays(context.TRIANGLE_STRIP, 0, 4); - }, - - _bindLayerVerticesBufferData:function () { - var glContext = cc.renderContext; - glContext.bindBuffer(glContext.ARRAY_BUFFER, this._verticesFloat32Buffer); - glContext.bufferData(glContext.ARRAY_BUFFER, this._squareVerticesAB , glContext.STATIC_DRAW); - }, - - _bindLayerColorsBufferData:function () { - var glContext = cc.renderContext; - glContext.bindBuffer(glContext.ARRAY_BUFFER, this._colorsUint8Buffer); - glContext.bufferData(glContext.ARRAY_BUFFER, this._squareColorsAB, glContext.STATIC_DRAW); } }); +if(cc.Browser.supportWebGL){ + cc.LayerColor.prototype.ctor = cc.LayerColor.prototype._ctorForWebGL; + cc.LayerColor.prototype.setContentSize = cc.LayerColor.prototype._setContentSizeForWebGL; + cc.LayerColor.prototype._updateColor = cc.LayerColor.prototype._updateColorForWebGL; + cc.LayerColor.prototype.draw = cc.LayerColor.prototype._drawForWebGL; +} else { + cc.LayerColor.prototype.ctor = cc.LayerColor.prototype._ctorForCanvas; + cc.LayerColor.prototype.setContentSize = cc.LayerRGBA.prototype.setContentSize; + cc.LayerColor.prototype._updateColor = cc.LayerColor.prototype._updateColorForCanvas; + cc.LayerColor.prototype.draw = cc.LayerColor.prototype._drawForCanvas; +} + + /** * creates a cc.Layer with color, width and height in Points * @param {cc.Color4B} color - * @param {Number|Null} width - * @param {Number|Null} height + * @param {Number|Null} [width=] + * @param {Number|Null} [height=] * @return {cc.LayerColor} * @example * // Example @@ -1113,8 +980,8 @@ cc.LayerColorWebGL = cc.LayerRGBA.extend(/** @lends cc.LayerColorCanvas# */{ * //create a yellow box, 200 by 200 in size * var yellowBox = cc.LayerColor.create(cc.c4b(255,255,0,255), 200, 200); */ -cc.LayerColorWebGL.create = function (color, width, height) { - var ret = new cc.LayerColorWebGL(); +cc.LayerColor.create = function (color, width, height) { + var ret = new cc.LayerColor(); switch (arguments.length) { case 0: ret.init(); @@ -1132,8 +999,6 @@ cc.LayerColorWebGL.create = function (color, width, height) { return ret; }; -cc.LayerColor = cc.Browser.supportWebGL ? cc.LayerColorWebGL : cc.LayerColorCanvas; - /** *

* CCLayerGradient is a subclass of cc.LayerColor that draws gradients across the background.
@@ -1301,14 +1166,15 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ v = v || cc.p(0, -1); // Initializes the CCLayer with a gradient between start and end in the direction of v. - this._startColor.r = start.r; - this._startColor.g = start.g; - this._startColor.b = start.b; + var locStartColor = this._startColor, locEndColor = this._endColor; + locStartColor.r = start.r; + locStartColor.g = start.g; + locStartColor.b = start.b; this._startOpacity = start.a; - this._endColor.r = end.r; - this._endColor.g = end.g; - this._endColor.b = end.b; + locEndColor.r = end.r; + locEndColor.g = end.g; + locEndColor.b = end.b; this._endOpacity = end.a; this._alongVector = v; @@ -1375,25 +1241,27 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ var E = {r: locEndColor.r / 255, g: locEndColor.g / 255, b: locEndColor.b / 255, a: (this._endOpacity * opacityf) / 255}; // (-1, -1) - this._squareColors[0].r = ((E.r + (S.r - E.r) * ((c + u.x + u.y) / (2.0 * c)))); - this._squareColors[0].g = ((E.g + (S.g - E.g) * ((c + u.x + u.y) / (2.0 * c)))); - this._squareColors[0].b = ((E.b + (S.b - E.b) * ((c + u.x + u.y) / (2.0 * c)))); - this._squareColors[0].a = ((E.a + (S.a - E.a) * ((c + u.x + u.y) / (2.0 * c)))); + var locSquareColors = this._squareColors; + var locSquareColor0 = locSquareColors[0], locSquareColor1 = locSquareColors[1], locSquareColor2 = locSquareColors[2],locSquareColor3 = locSquareColors[3]; + locSquareColor0.r = ((E.r + (S.r - E.r) * ((c + u.x + u.y) / (2.0 * c)))); + locSquareColor0.g = ((E.g + (S.g - E.g) * ((c + u.x + u.y) / (2.0 * c)))); + locSquareColor0.b = ((E.b + (S.b - E.b) * ((c + u.x + u.y) / (2.0 * c)))); + locSquareColor0.a = ((E.a + (S.a - E.a) * ((c + u.x + u.y) / (2.0 * c)))); // (1, -1) - this._squareColors[1].r = ((E.r + (S.r - E.r) * ((c - u.x + u.y) / (2.0 * c)))); - this._squareColors[1].g = ((E.g + (S.g - E.g) * ((c - u.x + u.y) / (2.0 * c)))); - this._squareColors[1].b = ((E.b + (S.b - E.b) * ((c - u.x + u.y) / (2.0 * c)))); - this._squareColors[1].a = ((E.a + (S.a - E.a) * ((c - u.x + u.y) / (2.0 * c)))); + locSquareColor1.r = ((E.r + (S.r - E.r) * ((c - u.x + u.y) / (2.0 * c)))); + locSquareColor1.g = ((E.g + (S.g - E.g) * ((c - u.x + u.y) / (2.0 * c)))); + locSquareColor1.b = ((E.b + (S.b - E.b) * ((c - u.x + u.y) / (2.0 * c)))); + locSquareColor1.a = ((E.a + (S.a - E.a) * ((c - u.x + u.y) / (2.0 * c)))); // (-1, 1) - this._squareColors[2].r = ((E.r + (S.r - E.r) * ((c + u.x - u.y) / (2.0 * c)))); - this._squareColors[2].g = ((E.g + (S.g - E.g) * ((c + u.x - u.y) / (2.0 * c)))); - this._squareColors[2].b = ((E.b + (S.b - E.b) * ((c + u.x - u.y) / (2.0 * c)))); - this._squareColors[2].a = ((E.a + (S.a - E.a) * ((c + u.x - u.y) / (2.0 * c)))); + locSquareColor2.r = ((E.r + (S.r - E.r) * ((c + u.x - u.y) / (2.0 * c)))); + locSquareColor2.g = ((E.g + (S.g - E.g) * ((c + u.x - u.y) / (2.0 * c)))); + locSquareColor2.b = ((E.b + (S.b - E.b) * ((c + u.x - u.y) / (2.0 * c)))); + locSquareColor2.a = ((E.a + (S.a - E.a) * ((c + u.x - u.y) / (2.0 * c)))); // (1, 1) - this._squareColors[3].r = ((E.r + (S.r - E.r) * ((c - u.x - u.y) / (2.0 * c)))); - this._squareColors[3].g = ((E.g + (S.g - E.g) * ((c - u.x - u.y) / (2.0 * c)))); - this._squareColors[3].b = ((E.b + (S.b - E.b) * ((c - u.x - u.y) / (2.0 * c)))); - this._squareColors[3].a = ((E.a + (S.a - E.a) * ((c - u.x - u.y) / (2.0 * c)))); + locSquareColor3.r = ((E.r + (S.r - E.r) * ((c - u.x - u.y) / (2.0 * c)))); + locSquareColor3.g = ((E.g + (S.g - E.g) * ((c - u.x - u.y) / (2.0 * c)))); + locSquareColor3.b = ((E.b + (S.b - E.b) * ((c - u.x - u.y) / (2.0 * c)))); + locSquareColor3.a = ((E.a + (S.a - E.a) * ((c - u.x - u.y) / (2.0 * c)))); this._bindLayerColorsBufferData(); } diff --git a/cocos2d/layers_scenes_transitions_nodes/CCTransition.js b/cocos2d/layers_scenes_transitions_nodes/CCTransition.js index 1ac114cc56..dec51e86ce 100644 --- a/cocos2d/layers_scenes_transitions_nodes/CCTransition.js +++ b/cocos2d/layers_scenes_transitions_nodes/CCTransition.js @@ -102,8 +102,6 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ * stuff gets drawn here */ draw:function () { - this._super(); - if (this._isInSceneOnTop) { this._outScene.visit(); this._inScene.visit(); @@ -117,7 +115,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ * custom onEnter */ onEnter:function () { - cc.Scene.prototype.onEnter.call(this); + cc.Node.prototype.onEnter.call(this); // disable events while transitions cc.Director.getInstance().getTouchDispatcher().setDispatchEvents(false); @@ -133,7 +131,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ * custom onExit */ onExit:function () { - cc.Scene.prototype.onExit.call(this); + cc.Node.prototype.onExit.call(this); // enable events while transitions cc.Director.getInstance().getTouchDispatcher().setDispatchEvents(true); @@ -149,7 +147,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ * custom cleanup */ cleanup:function () { - this._super(); + cc.Node.prototype.cleanup.call(this); if (this._isSendCleanupToScene) this._outScene.cleanup(); @@ -167,7 +165,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ if (this.init()) { this._duration = t; this.setAnchorPoint(cc.p(0, 0)); - this.setPosition(cc.p(0, 0)); + this.setPosition(0, 0); // retain this._inScene = scene; this._outScene = cc.Director.getInstance().getRunningScene(); @@ -192,14 +190,14 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ finish:function () { // clean up this._inScene.setVisible(true); - this._inScene.setPosition(cc.p(0, 0)); + this._inScene.setPosition(0, 0); this._inScene.setScale(1.0); this._inScene.setRotation(0.0); if(cc.renderContextType === cc.WEBGL) this._inScene.getCamera().restore(); this._outScene.setVisible(false); - this._outScene.setPosition(cc.p(0, 0)); + this._outScene.setPosition(0, 0); this._outScene.setScale(1.0); this._outScene.setRotation(0.0); if(cc.renderContextType === cc.WEBGL) @@ -249,7 +247,7 @@ cc.TransitionSceneOriented = cc.TransitionScene.extend(/** @lends cc.TransitionS * @return {Boolean} */ initWithDuration:function (t, scene, orientation) { - if (this._super(t, scene)) { + if (cc.TransitionScene.prototype.initWithDuration.call(this, t, scene)) { this._orientation = orientation; } return true; @@ -279,18 +277,12 @@ cc.TransitionSceneOriented.create = function (t, scene, orientation) { * @extends cc.TransitionScene */ cc.TransitionRotoZoom = cc.TransitionScene.extend(/** @lends cc.TransitionRotoZoom# */{ - /** - * Constructor - */ - ctor:function () { - }, - /** * Custom On Enter callback * @override */ onEnter:function () { - this._super(); + cc.TransitionScene.prototype.onEnter.call(this); this._inScene.setScale(0.001); this._outScene.setScale(1.0); @@ -337,11 +329,11 @@ cc.TransitionJumpZoom = cc.TransitionScene.extend(/** @lends cc.TransitionJumpZo * Custom on enter */ onEnter:function () { - this._super(); + cc.TransitionScene.prototype.onEnter.call(this); var winSize = cc.Director.getInstance().getWinSize(); this._inScene.setScale(0.5); - this._inScene.setPosition(cc.p(winSize.width, 0)); + this._inScene.setPosition(winSize.width, 0); this._inScene.setAnchorPoint(cc.p(0.5, 0.5)); this._outScene.setAnchorPoint(cc.p(0.5, 0.5)); @@ -383,7 +375,7 @@ cc.TransitionMoveInL = cc.TransitionScene.extend(/** @lends cc.TransitionMoveInL * Custom on enter */ onEnter:function () { - this._super(); + cc.TransitionScene.prototype.onEnter.call(this); this.initScenes(); var action = this.action(); @@ -396,7 +388,7 @@ cc.TransitionMoveInL = cc.TransitionScene.extend(/** @lends cc.TransitionMoveInL * initializes the scenes */ initScenes:function () { - this._inScene.setPosition(cc.p(-cc.Director.getInstance().getWinSize().width, 0)); + this._inScene.setPosition(-cc.Director.getInstance().getWinSize().width, 0); }, /** @@ -439,12 +431,11 @@ cc.TransitionMoveInL.create = function (t, scene) { * @extends cc.TransitionMoveInL */ cc.TransitionMoveInR = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveInR# */{ - /** * Init */ initScenes:function () { - this._inScene.setPosition(cc.p(cc.Director.getInstance().getWinSize().width, 0)); + this._inScene.setPosition(cc.Director.getInstance().getWinSize().width, 0); } }); @@ -476,7 +467,7 @@ cc.TransitionMoveInT = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveI * init */ initScenes:function () { - this._inScene.setPosition(cc.p(0, cc.Director.getInstance().getWinSize().height)); + this._inScene.setPosition(0, cc.Director.getInstance().getWinSize().height); } }); @@ -508,7 +499,7 @@ cc.TransitionMoveInB = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveI * init */ initScenes:function () { - this._inScene.setPosition(cc.p(0, -cc.Director.getInstance().getWinSize().height)); + this._inScene.setPosition(0, -cc.Director.getInstance().getWinSize().height); } }); @@ -549,17 +540,11 @@ cc.TransitionSlideInL = cc.TransitionScene.extend(/** @lends cc.TransitionSlideI this._isInSceneOnTop = false; }, - /** - * Constructor - */ - ctor:function () { - }, - /** * custom on enter */ onEnter:function () { - this._super(); + cc.TransitionScene.prototype.onEnter.call(this); this.initScenes(); var inA = this.action(); @@ -575,7 +560,7 @@ cc.TransitionSlideInL = cc.TransitionScene.extend(/** @lends cc.TransitionSlideI * initializes the scenes */ initScenes:function () { - this._inScene.setPosition(cc.p(-(cc.Director.getInstance().getWinSize().width - cc.ADJUST_FACTOR), 0)); + this._inScene.setPosition(-(cc.Director.getInstance().getWinSize().width - cc.ADJUST_FACTOR), 0); }, /** * returns the action that will be performed by the incomming and outgoing scene @@ -624,7 +609,7 @@ cc.TransitionSlideInR = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli * initializes the scenes */ initScenes:function () { - this._inScene.setPosition(cc.p(cc.Director.getInstance().getWinSize().width - cc.ADJUST_FACTOR, 0)); + this._inScene.setPosition(cc.Director.getInstance().getWinSize().width - cc.ADJUST_FACTOR, 0); }, /** * returns the action that will be performed by the incomming and outgoing scene @@ -666,7 +651,7 @@ cc.TransitionSlideInB = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli * initializes the scenes */ initScenes:function () { - this._inScene.setPosition(cc.p(0, cc.Director.getInstance().getWinSize().height - cc.ADJUST_FACTOR)); + this._inScene.setPosition(0, cc.Director.getInstance().getWinSize().height - cc.ADJUST_FACTOR); }, /** @@ -709,7 +694,7 @@ cc.TransitionSlideInT = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli * initializes the scenes */ initScenes:function () { - this._inScene.setPosition(cc.p(0, -(cc.Director.getInstance().getWinSize().height - cc.ADJUST_FACTOR))); + this._inScene.setPosition(0, -(cc.Director.getInstance().getWinSize().height - cc.ADJUST_FACTOR)); }, /** @@ -749,7 +734,7 @@ cc.TransitionShrinkGrow = cc.TransitionScene.extend(/** @lends cc.TransitionShri * Custom on enter */ onEnter:function () { - this._super(); + cc.TransitionScene.prototype.onEnter.call(this); this._inScene.setScale(0.001); this._outScene.setScale(1.0); @@ -804,7 +789,7 @@ cc.TransitionFlipX = cc.TransitionSceneOriented.extend(/** @lends cc.TransitionF * custom on enter */ onEnter:function () { - this._super(); + cc.TransitionScene.prototype.onEnter.call(this); var inA, outA; this._inScene.setVisible(false); @@ -874,7 +859,7 @@ cc.TransitionFlipY = cc.TransitionSceneOriented.extend(/** @lends cc.TransitionF * custom on enter */ onEnter:function () { - this._super(); + cc.TransitionScene.prototype.onEnter.call(this); var inA, outA; this._inScene.setVisible(false); @@ -943,7 +928,7 @@ cc.TransitionFlipAngular = cc.TransitionSceneOriented.extend(/** @lends cc.Trans * custom on enter */ onEnter:function () { - this._super(); + cc.TransitionScene.prototype.onEnter.call(this); var inA, outA; this._inScene.setVisible(false); @@ -1013,7 +998,7 @@ cc.TransitionZoomFlipX = cc.TransitionSceneOriented.extend(/** @lends cc.Transit * custom on enter */ onEnter:function () { - this._super(); + cc.TransitionScene.prototype.onEnter.call(this); var inA, outA; this._inScene.setVisible(false); @@ -1089,7 +1074,7 @@ cc.TransitionZoomFlipY = cc.TransitionSceneOriented.extend(/** @lends cc.Transit * custom on enter */ onEnter:function () { - this._super(); + cc.TransitionScene.prototype.onEnter.call(this); var inA, outA; this._inScene.setVisible(false); @@ -1163,7 +1148,7 @@ cc.TransitionZoomFlipAngular = cc.TransitionSceneOriented.extend(/** @lends cc.T * custom on enter */ onEnter:function () { - this._super(); + cc.TransitionScene.prototype.onEnter.call(this); var inA, outA; this._inScene.setVisible(false); @@ -1236,15 +1221,15 @@ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{ * Constructor */ ctor:function () { - this._super(); - this._color = new cc.Color3B() + cc.TransitionScene.prototype.ctor.call(this); + this._color = new cc.Color4B() }, /** * custom on enter */ onEnter:function () { - this._super(); + cc.TransitionScene.prototype.onEnter.call(this); var l = cc.LayerColor.create(this._color); this._inScene.setVisible(false); @@ -1265,7 +1250,7 @@ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{ * custom on exit */ onExit:function () { - this._super(); + cc.TransitionScene.prototype.onExit.call(this); this.removeChildByTag(cc.SCENE_FADE, false); }, @@ -1278,7 +1263,7 @@ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{ */ initWithDuration:function (t, scene, color) { color = color || cc.black(); - if (this._super(t, scene)) { + if (cc.TransitionScene.prototype.initWithDuration.call(this, t, scene)) { this._color.r = color.r; this._color.g = color.g; this._color.b = color.b; @@ -1315,7 +1300,7 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross * custom on enter */ onEnter:function () { - this._super(); + cc.TransitionScene.prototype.onEnter.call(this); // create a transparent color layer // in which we are going to add our rendertextures @@ -1330,7 +1315,7 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross return; inTexture.getSprite().setAnchorPoint(cc.p(0.5, 0.5)); - inTexture.setPosition(cc.p(winSize.width / 2, winSize.height / 2)); + inTexture.setPosition(winSize.width / 2, winSize.height / 2); inTexture.setAnchorPoint(cc.p(0.5, 0.5)); // render inScene to its texturebuffer @@ -1341,7 +1326,7 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross // create the second render texture for outScene var outTexture = cc.RenderTexture.create(winSize.width, winSize.height); outTexture.getSprite().setAnchorPoint(cc.p(0.5, 0.5)); - outTexture.setPosition(cc.p(winSize.width / 2, winSize.height / 2)); + outTexture.setPosition(winSize.width / 2, winSize.height / 2); outTexture.setAnchorPoint(cc.p(0.5, 0.5)); // render outScene to its texturebuffer @@ -1378,7 +1363,7 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross */ onExit:function () { this.removeChildByTag(cc.SCENE_FADE, false); - this._super(); + cc.TransitionScene.prototype.onExit.call(this); }, /** @@ -1418,12 +1403,12 @@ cc.TransitionTurnOffTiles = cc.TransitionScene.extend(/** @lends cc.TransitionTu * custom on enter */ onEnter:function () { - this._super(); + cc.TransitionScene.prototype.onEnter.call(this); var winSize = cc.Director.getInstance().getWinSize(); var aspect = winSize.width / winSize.height; var x = 0 | (12 * aspect); var y = 12; - var toff = cc.TurnOffTiles.create(this._duration, cc.SizeMake(x, y)); + var toff = cc.TurnOffTiles.create(this._duration, cc.size(x, y)); var action = this.easeActionWithAction(toff); this._outScene.runAction(cc.Sequence.create(action, cc.CallFunc.create(this.finish, this), cc.StopGrid.create())); }, @@ -1465,7 +1450,7 @@ cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplit * custom on enter */ onEnter:function () { - this._super(); + cc.TransitionScene.prototype.onEnter.call(this); this._inScene.setVisible(false); var split = this.action(); @@ -1555,14 +1540,14 @@ cc.TransitionFadeTR = cc.TransitionScene.extend(/** @lends cc.TransitionFadeTR# * Custom on enter */ onEnter:function () { - this._super(); + cc.TransitionScene.prototype.onEnter.call(this); var winSize = cc.Director.getInstance().getWinSize(); var aspect = winSize.width / winSize.height; var x = 0 | (12 * aspect); var y = 12; - var action = this.actionWithSize(cc.SizeMake(x, y)); + var action = this.actionWithSize(cc.size(x, y)); this._outScene.runAction( cc.Sequence.create(this.easeActionWithAction(action), cc.CallFunc.create(this.finish, this), cc.StopGrid.create()) diff --git a/cocos2d/layers_scenes_transitions_nodes/CCTransitionPageTurn.js b/cocos2d/layers_scenes_transitions_nodes/CCTransitionPageTurn.js index 93e0d6c750..168b7e93e0 100644 --- a/cocos2d/layers_scenes_transitions_nodes/CCTransitionPageTurn.js +++ b/cocos2d/layers_scenes_transitions_nodes/CCTransitionPageTurn.js @@ -54,7 +54,7 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu // XXX: needed before [super init] this._back = backwards; - if (this._super(t, scene)) { + if (cc.TransitionScene.prototype.initWithDuration.call(this, t, scene)) { // do something } return true; @@ -75,7 +75,7 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu * custom on enter */ onEnter:function () { - this._super(); + cc.TransitionScene.prototype.onEnter.call(this); var winSize = cc.Director.getInstance().getWinSize(); var x, y; if (winSize.width > winSize.height) { @@ -86,7 +86,7 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu y = 16; } - var action = this.actionWithSize(cc.SizeMake(x, y)); + var action = this.actionWithSize(cc.size(x, y)); if (!this._back) { this._outScene.runAction( cc.Sequence.create(action,cc.CallFunc.create(this.finish, this),cc.StopGrid.create())); diff --git a/cocos2d/layers_scenes_transitions_nodes/CCTransitionProgress.js b/cocos2d/layers_scenes_transitions_nodes/CCTransitionProgress.js index e4d5b3e276..2b9f6e9032 100644 --- a/cocos2d/layers_scenes_transitions_nodes/CCTransitionProgress.js +++ b/cocos2d/layers_scenes_transitions_nodes/CCTransitionProgress.js @@ -45,8 +45,7 @@ cc.TransitionProgress = cc.TransitionScene.extend(/** @lends cc.TransitionProgre * @override */ onEnter:function () { - this._super(); - + cc.TransitionScene.prototype.onEnter.call(this); this._setupTransition(); // create a transparent color layer @@ -56,24 +55,19 @@ cc.TransitionProgress = cc.TransitionScene.extend(/** @lends cc.TransitionProgre // create the second render texture for outScene var texture = cc.RenderTexture.create(winSize.width, winSize.height); texture.getSprite().setAnchorPoint(cc.p(0.5, 0.5)); - texture.setPosition(cc.p(winSize.width / 2, winSize.height / 2)); + texture.setPosition(winSize.width / 2, winSize.height / 2); texture.setAnchorPoint(cc.p(0.5, 0.5)); - if (cc.renderContextType === cc.CANVAS) { - // render outScene to its texturebuffer - texture.clear(); - this._sceneToBeModified.visit(texture.context); - } else { - // render outScene to its texturebuffer - texture.clear(0, 0, 0, 1); - texture.begin(); - this._sceneToBeModified.visit(); - texture.end(); - } + // render outScene to its texturebuffer + texture.clear(0, 0, 0, 1); + texture.begin(); + this._sceneToBeModified.visit(); + texture.end(); + // Since we've passed the outScene to the texture we don't need it. - if (this._sceneToBeModified == this._outScene) { + if (this._sceneToBeModified == this._outScene) this.hideOutShowIn(); - } + // We need the texture in RenderTexture. var pNode = this._progressTimerNodeWithRenderTexture(texture); @@ -86,7 +80,6 @@ cc.TransitionProgress = cc.TransitionScene.extend(/** @lends cc.TransitionProgre // add the layer (which contains our two rendertextures) to the scene this.addChild(pNode, 2, cc.SCENE_RADIAL); - }, /** @@ -95,7 +88,7 @@ cc.TransitionProgress = cc.TransitionScene.extend(/** @lends cc.TransitionProgre onExit:function () { // remove our layer and release all containing objects this.removeChildByTag(cc.SCENE_RADIAL, true); - this._super(); + cc.TransitionScene.prototype.onExit.call(this); }, _setupTransition:function () { @@ -143,13 +136,13 @@ cc.TransitionProgressRadialCCW = cc.TransitionProgress.extend(/** @lends cc.Tran // but it is flipped upside down so we flip the sprite if (cc.renderContextType === cc.WEBGL) - pNode.getSprite().setFlipY(true); + pNode.getSprite().setFlippedY(true); pNode.setType(cc.PROGRESS_TIMER_TYPE_RADIAL); // Return the radial type that we want to use pNode.setReverseDirection(false); pNode.setPercentage(100); - pNode.setPosition(cc.p(size.width / 2, size.height / 2)); + pNode.setPosition(size.width / 2, size.height / 2); pNode.setAnchorPoint(cc.p(0.5, 0.5)); return pNode; @@ -185,13 +178,13 @@ cc.TransitionProgressRadialCW = cc.TransitionProgress.extend(/** @lends cc.Trans // but it is flipped upside down so we flip the sprite if (cc.renderContextType === cc.WEBGL) - pNode.getSprite().setFlipY(true); + pNode.getSprite().setFlippedY(true); pNode.setType(cc.PROGRESS_TIMER_TYPE_RADIAL); // Return the radial type that we want to use pNode.setReverseDirection(true); pNode.setPercentage(100); - pNode.setPosition(cc.p(size.width / 2, size.height / 2)); + pNode.setPosition(size.width / 2, size.height / 2); pNode.setAnchorPoint(cc.p(0.5, 0.5)); return pNode; @@ -226,15 +219,15 @@ cc.TransitionProgressHorizontal = cc.TransitionProgress.extend(/** @lends cc.Tra var pNode = cc.ProgressTimer.create(texture.getSprite()); // but it is flipped upside down so we flip the sprite - if (cc.renderContextType == cc.WEBGL) - pNode.getSprite().setFlipY(true); + if (cc.renderContextType === cc.WEBGL) + pNode.getSprite().setFlippedY(true); pNode.setType(cc.PROGRESS_TIMER_TYPE_BAR); pNode.setMidpoint(cc.p(1, 0)); pNode.setBarChangeRate(cc.p(1, 0)); pNode.setPercentage(100); - pNode.setPosition(cc.p(size.width / 2, size.height / 2)); + pNode.setPosition(size.width / 2, size.height / 2); pNode.setAnchorPoint(cc.p(0.5, 0.5)); return pNode; @@ -268,15 +261,15 @@ cc.TransitionProgressVertical = cc.TransitionProgress.extend(/** @lends cc.Trans var pNode = cc.ProgressTimer.create(texture.getSprite()); // but it is flipped upside down so we flip the sprite - if (cc.renderContextType == cc.WEBGL) - pNode.getSprite().setFlipY(true); + if (cc.renderContextType === cc.WEBGL) + pNode.getSprite().setFlippedY(true); pNode.setType(cc.PROGRESS_TIMER_TYPE_BAR); pNode.setMidpoint(cc.p(0, 0)); pNode.setBarChangeRate(cc.p(0, 1)); pNode.setPercentage(100); - pNode.setPosition(cc.p(size.width / 2, size.height / 2)); + pNode.setPosition(size.width / 2, size.height / 2); pNode.setAnchorPoint(cc.p(0.5, 0.5)); return pNode; @@ -309,15 +302,15 @@ cc.TransitionProgressInOut = cc.TransitionProgress.extend(/** @lends cc.Transiti var pNode = cc.ProgressTimer.create(texture.getSprite()); // but it is flipped upside down so we flip the sprite - if (cc.renderContextType == cc.WEBGL) - pNode.getSprite().setFlipY(true); + if (cc.renderContextType === cc.WEBGL) + pNode.getSprite().setFlippedY(true); pNode.setType(cc.PROGRESS_TIMER_TYPE_BAR); pNode.setMidpoint(cc.p(0.5, 0.5)); pNode.setBarChangeRate(cc.p(1, 1)); pNode.setPercentage(0); - pNode.setPosition(cc.p(size.width / 2, size.height / 2)); + pNode.setPosition(size.width / 2, size.height / 2); pNode.setAnchorPoint(cc.p(0.5, 0.5)); return pNode; @@ -358,15 +351,15 @@ cc.TransitionProgressOutIn = cc.TransitionProgress.extend(/** @lends cc.Transiti var pNode = cc.ProgressTimer.create(texture.getSprite()); // but it is flipped upside down so we flip the sprite - if (cc.renderContextType == cc.WEBGL) - pNode.getSprite().setFlipY(true); + if (cc.renderContextType === cc.WEBGL) + pNode.getSprite().setFlippedY(true); pNode.setType(cc.PROGRESS_TIMER_TYPE_BAR); pNode.setMidpoint(cc.p(0.5, 0.5)); pNode.setBarChangeRate(cc.p(1, 1)); pNode.setPercentage(100); - pNode.setPosition(cc.p(size.width / 2, size.height / 2)); + pNode.setPosition(size.width / 2, size.height / 2); pNode.setAnchorPoint(cc.p(0.5, 0.5)); return pNode; diff --git a/cocos2d/menu_nodes/CCMenu.js b/cocos2d/menu_nodes/CCMenu.js index 8f90bd77a9..f2c5f4bcf4 100644 --- a/cocos2d/menu_nodes/CCMenu.js +++ b/cocos2d/menu_nodes/CCMenu.js @@ -154,7 +154,7 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{ this.ignoreAnchorPointForPosition(true); this.setAnchorPoint(cc.p(0.5, 0.5)); this.setContentSize(winSize); - this.setPosition(cc.p(winSize.width / 2, winSize.height / 2)); + this.setPosition(winSize.width / 2, winSize.height / 2); if (arrayOfItems) { for (var i = 0; i < arrayOfItems.length; i++) @@ -174,8 +174,8 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{ /** * @param {cc.Node} child - * @param {Number|Null} zOrder - * @param {Number|Null} tag + * @param {Number|Null} [zOrder=] + * @param {Number|Null} [tag=] */ addChild:function (child, zOrder, tag) { cc.Assert((child instanceof cc.MenuItem), "Menu only supports MenuItem objects as children"); @@ -194,18 +194,19 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{ * @param {Number} padding */ alignItemsVerticallyWithPadding:function (padding) { - var height = -padding; - if (this._children && this._children.length > 0) { - for (var i = 0; i < this._children.length; i++) { - height += this._children[i].getContentSize().height * this._children[i].getScaleY() + padding; - } - } + var height = -padding, locChildren = this._children, len, i, locScaleY, locHeight, locChild; + if (locChildren && locChildren.length > 0) { + for (i = 0, len = locChildren.length; i < len; i++) + height += locChildren[i].getContentSize().height * locChildren[i].getScaleY() + padding; - var y = height / 2.0; - if (this._children && this._children.length > 0) { - for (i = 0; i < this._children.length; i++) { - this._children[i].setPosition(cc.p(0, y - this._children[i].getContentSize().height * this._children[i].getScaleY() / 2)); - y -= this._children[i].getContentSize().height * this._children[i].getScaleY() + padding; + var y = height / 2.0; + + for (i = 0, len = locChildren.length; i < len; i++) { + locChild = locChildren[i]; + locHeight = locChild.getContentSize().height; + locScaleY = locChild.getScaleY(); + locChild.setPosition(0, y - locHeight * locScaleY / 2); + y -= locHeight * locScaleY + padding; } } }, @@ -222,18 +223,19 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{ * @param {Number} padding */ alignItemsHorizontallyWithPadding:function (padding) { - var width = -padding; - if (this._children && this._children.length > 0) { - for (var i = 0; i < this._children.length; i++) { - width += this._children[i].getContentSize().width * this._children[i].getScaleX() + padding; - } - } + var width = -padding, locChildren = this._children, i, len, locScaleX, locWidth, locChild; + if (locChildren && locChildren.length > 0) { + for (i = 0, len = locChildren.length; i < len; i++) + width += locChildren[i].getContentSize().width * locChildren[i].getScaleX() + padding; - var x = -width / 2.0; - if (this._children && this._children.length > 0) { - for (i = 0; i < this._children.length; i++) { - this._children[i].setPosition(cc.p(x + this._children[i].getContentSize().width * this._children[i].getScaleX() / 2, 0)); - x += this._children[i].getContentSize().width * this._children[i].getScaleX() + padding; + var x = -width / 2.0; + + for (i = 0, len = locChildren.length; i < len; i++) { + locChild = locChildren[i]; + locScaleX = locChild.getScaleX(); + locWidth = locChildren[i].getContentSize().width; + locChild.setPosition(x + locWidth * locScaleX / 2, 0); + x += locWidth * locScaleX + padding; } } }, @@ -258,16 +260,17 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{ var row = 0; var rowHeight = 0; var columnsOccupied = 0; - var rowColumns; - if (this._children && this._children.length > 0) { - for (i = 0; i < this._children.length; i++) { + var rowColumns, tmp, len; + var locChildren = this._children; + if (locChildren && locChildren.length > 0) { + for (i = 0, len = locChildren.length; i < len; i++) { cc.Assert(row < rows.length, ""); rowColumns = rows[row]; // can not have zero columns on a row cc.Assert(rowColumns, ""); - var tmp = this._children[i].getContentSize().height; + tmp = locChildren[i].getContentSize().height; rowHeight = ((rowHeight >= tmp || isNaN(tmp)) ? rowHeight : tmp); ++columnsOccupied; @@ -291,27 +294,24 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{ var x = 0.0; var y = (height / 2); - if (this._children && this._children.length > 0) { - for (i = 0; i < this._children.length; i++) { - var child = this._children[i]; + if (locChildren && locChildren.length > 0) { + for (i = 0, len = locChildren.length; i < len; i++) { + var child = locChildren[i]; if (rowColumns == 0) { rowColumns = rows[row]; w = winSize.width / (1 + rowColumns); x = w; } - var tmp = child.getContentSize().height; + tmp = child.getContentSize().height; rowHeight = ((rowHeight >= tmp || isNaN(tmp)) ? rowHeight : tmp); - - child.setPosition(cc.p(x - winSize.width / 2, - y - child.getContentSize().height / 2)); + child.setPosition(x - winSize.width / 2, y - tmp / 2); x += w; ++columnsOccupied; if (columnsOccupied >= rowColumns) { y -= rowHeight + 5; - columnsOccupied = 0; rowColumns = 0; rowHeight = 0; @@ -331,8 +331,8 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{ alignItemsInRows:function (/*Multiple arguments*/) { if((arguments.length > 0) && (arguments[arguments.length-1] == null)) cc.log("parameters should not be ending with null in Javascript"); - var columns = []; - for (var i = 0; i < arguments.length; i++) { + var columns = [], i; + for (i = 0; i < arguments.length; i++) { columns.push(arguments[i]); } var columnWidths = []; @@ -343,11 +343,12 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{ var column = 0; var columnWidth = 0; var rowsOccupied = 0; - var columnRows; + var columnRows, child, len, tmp, locContentSize; - if (this._children && this._children.length > 0) { - for (var i = 0; i < this._children.length; i++) { - var child = this._children[i]; + var locChildren = this._children; + if (locChildren && locChildren.length > 0) { + for (i = 0, len = locChildren.length; i < len; i++) { + child = locChildren[i]; // check if too many menu items for the amount of rows/columns cc.Assert(column < columns.length, ""); @@ -356,10 +357,11 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{ cc.Assert(columnRows, ""); // columnWidth = fmaxf(columnWidth, [item contentSize].width); - var tmp = child.getContentSize().width; + locContentSize = child.getContentSize(); + tmp = locContentSize.width; columnWidth = ((columnWidth >= tmp || isNaN(tmp)) ? columnWidth : tmp); - columnHeight += (child.getContentSize().height + 5); + columnHeight += (locContentSize.height + 5); ++rowsOccupied; if (rowsOccupied >= columnRows) { @@ -385,22 +387,22 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{ var x = -width / 2; var y = 0.0; - if (this._children && this._children.length > 0) { - for (var i = 0; i < this._children.length; i++) { - var child = this._children[i]; + if (locChildren && locChildren.length > 0) { + for (i = 0, len = locChildren.length; i < len; i++) { + child = locChildren[i]; if (columnRows == 0) { columnRows = columns[column]; y = columnHeights[column]; } // columnWidth = fmaxf(columnWidth, [item contentSize].width); - var tmp = child.getContentSize().width; + locContentSize = child.getContentSize(); + tmp = locContentSize.width; columnWidth = ((columnWidth >= tmp || isNaN(tmp)) ? columnWidth : tmp); - child.setPosition(cc.p(x + columnWidths[column] / 2, - y - winSize.height / 2)); + child.setPosition(x + columnWidths[column] / 2, y - winSize.height / 2); - y -= child.getContentSize().height + 10; + y -= locContentSize.height + 10; ++rowsOccupied; if (rowsOccupied >= columnRows) { @@ -418,7 +420,7 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{ * make the menu clickable */ registerWithTouchDispatcher:function () { - cc.Director.getInstance().getTouchDispatcher().addTargetedDelegate(this, this.getTouchPriority(), true); + cc.registerTargetedDelegate(this.getTouchPriority(), true, this); }, /** @@ -524,16 +526,17 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{ _itemForTouch:function (touch) { var touchLocation = touch.getLocation(); - var itemChildren = this._children; + var itemChildren = this._children, locItemChild; if (itemChildren && itemChildren.length > 0) { for (var i = 0; i < itemChildren.length; i++) { - if (itemChildren[i].isVisible() && itemChildren[i].isEnabled()) { - var local = itemChildren[i].convertToNodeSpace(touchLocation); - var r = itemChildren[i].rect(); + locItemChild = itemChildren[i]; + if (locItemChild.isVisible() && locItemChild.isEnabled()) { + var local = locItemChild.convertToNodeSpace(touchLocation); + var r = locItemChild.rect(); r.x = 0; r.y = 0; if (cc.rectContainsPoint(r, local)) - return itemChildren[i]; + return locItemChild; } } } diff --git a/cocos2d/menu_nodes/CCMenuItem.js b/cocos2d/menu_nodes/CCMenuItem.js index 65b8f313af..94204b1a34 100644 --- a/cocos2d/menu_nodes/CCMenuItem.js +++ b/cocos2d/menu_nodes/CCMenuItem.js @@ -184,12 +184,15 @@ cc.MenuItem = cc.NodeRGBA.extend(/** @lends cc.MenuItem# */{ */ activate:function () { if (this._isEnabled) { - if (this._target && (typeof(this._callback) == "string")) { - this._target[this._callback](this); - } else if (this._target && (typeof(this._callback) == "function")) { - this._callback.call(this._target, this); + var locTarget = this._target, locCallback = this._callback; + if(!locCallback) + return ; + if (locTarget && (typeof(locCallback) == "string")) { + locTarget[locCallback](this); + } else if (locTarget && (typeof(locCallback) == "function")) { + locCallback.call(locTarget, this); } else - this._callback(this); + locCallback(this); } } }); @@ -274,11 +277,12 @@ cc.MenuItemLabel = cc.MenuItem.extend(/** @lends cc.MenuItemLabel# */{ */ setEnabled:function (enabled) { if (this._isEnabled != enabled) { + var locLabel = this._label; if (!enabled) { - this._colorBackup = this._label.getColor(); - this._label.setColor(this._disabledColor); + this._colorBackup = locLabel.getColor(); + locLabel.setColor(this._disabledColor); } else { - this._label.setColor(this._colorBackup); + locLabel.setColor(this._colorBackup); } } cc.MenuItem.prototype.setEnabled.call(this, enabled); @@ -601,14 +605,14 @@ cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{ }, /** - * @return {cc.Node} + * @return {cc.Sprite} */ getNormalImage:function () { return this._normalImage; }, /** - * @param {cc.Node} normalImage + * @param {cc.Sprite} normalImage */ setNormalImage:function (normalImage) { if (this._normalImage == normalImage) { @@ -623,19 +627,26 @@ cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{ } this._normalImage = normalImage; - this.setContentSize(this._normalImage.getContentSize()); - this._updateImagesVisibility(); + if(normalImage.textureLoaded()){ + this.setContentSize(this._normalImage.getContentSize()); + this._updateImagesVisibility(); + } else { + normalImage.addLoadedEventListener(function(sender){ + this.setContentSize(sender.getContentSize()); + this._updateImagesVisibility(); + }, this); + } }, /** - * @return {cc.Node} + * @return {cc.Sprite} */ getSelectedImage:function () { return this._selectedImage; }, /** - * @param {cc.Node} selectedImage + * @param {cc.Sprite} selectedImage */ setSelectedImage:function (selectedImage) { if (this._selectedImage == selectedImage) @@ -651,7 +662,13 @@ cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{ } this._selectedImage = selectedImage; - this._updateImagesVisibility(); + if(selectedImage.textureLoaded()){ + this._updateImagesVisibility(); + } else { + selectedImage.addLoadedEventListener(function(sender){ + this._updateImagesVisibility(); + }, this); + } }, /** @@ -662,7 +679,7 @@ cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{ }, /** - * @param {cc.Node} disabledImage + * @param {cc.Sprite} disabledImage */ setDisabledImage:function (disabledImage) { if (this._disabledImage == disabledImage) @@ -677,7 +694,13 @@ cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{ this.removeChild(this._disabledImage, true); this._disabledImage = disabledImage; - this._updateImagesVisibility(); + if(disabledImage.textureLoaded()){ + this._updateImagesVisibility(); + } else { + disabledImage.addLoadedEventListener(function(sender){ + this._updateImagesVisibility(); + }, this); + } }, /** @@ -693,11 +716,22 @@ cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{ this.setNormalImage(normalSprite); this.setSelectedImage(selectedSprite); this.setDisabledImage(disabledSprite); - if (this._normalImage) - this.setContentSize(this._normalImage.getContentSize()); + var locNormalImage = this._normalImage; + if (locNormalImage){ + if(locNormalImage.textureLoaded()){ + this.setContentSize(locNormalImage.getContentSize()); + this.setCascadeColorEnabled(true); + this.setCascadeOpacityEnabled(true); + } else{ + locNormalImage.addLoadedEventListener(function(sender){ + this.setContentSize(sender.getContentSize()); + this.setCascadeColorEnabled(true); + this.setCascadeOpacityEnabled(true); + }, this); + } + } + - this.setCascadeColorEnabled(true); - this.setCascadeOpacityEnabled(true); return true; }, @@ -1030,7 +1064,7 @@ cc.MenuItemToggle = cc.MenuItem.extend(/** @lends cc.MenuItemToggle# */{ this.addChild(item, 0, cc.CURRENT_ITEM); var s = item.getContentSize(); this.setContentSize(s); - item.setPosition(cc.p(s.width / 2, s.height / 2)); + item.setPosition(s.width / 2, s.height / 2); } }, diff --git a/cocos2d/misc_nodes/CCProgressTimer.js b/cocos2d/misc_nodes/CCProgressTimer.js index a27babe44f..3136104a77 100644 --- a/cocos2d/misc_nodes/CCProgressTimer.js +++ b/cocos2d/misc_nodes/CCProgressTimer.js @@ -50,14 +50,13 @@ cc.PROGRESS_TEXTURE_COORDS_COUNT = 4; cc.PROGRESS_TEXTURE_COORDS = 0x4b; /** - * cc.Progresstimer is a subclass of cc.Node. (Canvas implement)
+ * cc.Progresstimer is a subclass of cc.Node.
* It renders the inner sprite according to the percentage.
* The progress can be Radial, Horizontal or vertical. * @class * @extends cc.NodeRGBA */ -cc.ProgressTimerCanvas = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerCanvas# */{ - /// ---- common properties start ---- +cc.ProgressTimer = cc.NodeRGBA.extend(/** @lends cc.ProgressTimer# */{ _type:null, _percentage:0.0, _sprite:null, @@ -164,16 +163,22 @@ cc.ProgressTimerCanvas = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerCanvas# * return cc.PointZero(); }, - /// ---- common properties end ---- - _origin:cc.PointZero(), - _originSize:cc.SizeZero(), - _drawSize:cc.SizeZero(), - _drawPosition:cc.PointZero(), + _origin:null, _startAngle:270, _endAngle:270, _radius:0, + _counterClockWise:false, + _barRect:null, - ctor:function () { + _vertexDataCount:0, + _vertexData:null, + _vertexArrayBuffer:null, + _vertexWebGLBuffer:null, + _vertexDataDirty:false, + + ctor: null, + + _ctorForCanvas: function () { cc.NodeRGBA.prototype.ctor.call(this); this._type = cc.PROGRESS_TIMER_TYPE_RADIAL; @@ -185,371 +190,14 @@ cc.ProgressTimerCanvas = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerCanvas# * this._sprite = null; this._origin = cc.PointZero(); - this._originSize = cc.SizeZero(); - this._drawSize = cc.SizeZero(); - this._drawPosition = cc.PointZero(); this._startAngle = 270; this._endAngle = 270; this._radius = 0; + this._counterClockWise = false; + this._barRect = cc.RectZero(); }, - /** - * @param {Boolean} reverse - */ - setReverseProgress:function (reverse) { - if (this._reverseDirection !== reverse) { - this._reverseDirection = reverse; - } - }, - - /** - * @param {cc.Sprite} sprite - */ - setSprite:function (sprite) { - if (this._sprite != sprite) { - this._sprite = sprite; - this.setContentSize(this._sprite.getContentSize()); - } - }, - - /** - * set Progress type of cc.ProgressTimer - * @param {cc.PROGRESS_TIMER_TYPE_RADIAL|cc.PROGRESS_TIMER_TYPE_BAR} type - */ - setType:function (type) { - if (type !== this._type) { - this._type = type; - } - }, - - /** - * set color of sprite - * @param {cc.Color3B} color - */ - setColor:function (color) { - this._sprite.setColor(color); - }, - - /** - * Opacity - * @param {Number} opacity - */ - setOpacity:function (opacity) { - this._sprite.setOpacity(opacity); - }, - - /** - * return color of sprite - * @return {cc.Color3B} - */ - getColor:function () { - return this._sprite.getColor(); - }, - - /** - * return Opacity of sprite - * @return {Number} - */ - getOpacity:function () { - return this._sprite.getOpacity(); - }, - - /** - * Reverse Progress setter - * @param {Boolean} reverse - */ - setReverseDirection:function (reverse) { - if (this._reverseDirection !== reverse) { - this._reverseDirection = reverse; - } - }, - - /** - * Initializes a progress timer with the sprite as the shape the timer goes through - * @param {cc.Sprite} sprite - * @return {Boolean} - */ - initWithSprite:function (sprite) { - this.setPercentage(0); - this.setAnchorPoint(cc.p(0.5, 0.5)); - - this._type = cc.PROGRESS_TIMER_TYPE_RADIAL; - this._reverseDirection = false; - this.setMidpoint(cc.p(0.5, 0.5)); - this.setBarChangeRate(cc.p(1, 1)); - this.setSprite(sprite); - - return true; - }, - - /** - * stuff gets drawn here - * @param {CanvasRenderingContext2D} ctx - */ - draw:function (ctx) { - var context = ctx || cc.renderContext; - var locSprite = this._sprite; - context.globalAlpha = locSprite._opacity / 255; - var centerPoint, mpX = 0, mpY = 0; - var spriteContentSize = locSprite._contentSize; - var spriteAnchorPoint = locSprite._anchorPointInPoints; - if (locSprite._flipX) { - centerPoint = cc.p(spriteContentSize.width * 0.5, spriteContentSize.height * 0.5); - mpX = 0 | (centerPoint.x - spriteAnchorPoint.x); - context.translate(mpX, 0); - context.scale(-1, 1); - } - - if (locSprite._flipY) { - centerPoint = cc.p(spriteContentSize.width * 0.5, spriteContentSize.height * 0.5); - mpY = -(0 | (centerPoint.y - spriteAnchorPoint.y)); - context.translate(0, mpY); - context.scale(1, -1); - } - context.translate(spriteAnchorPoint.x, -spriteAnchorPoint.y); - - var pos; - var offsetPixels = locSprite._offsetPosition, locSpriteTexture = locSprite._texture, locSpriteRect = locSprite._rect; - var locOrigin = this._origin; - if (this._type == cc.PROGRESS_TIMER_TYPE_BAR) { - pos = cc.p(( -spriteAnchorPoint.x + offsetPixels.x + this._drawPosition.x), - ( -spriteAnchorPoint.y + offsetPixels.y + this._drawPosition.y)); - var locOriginSize = this._originSize; - if (locSpriteTexture instanceof HTMLImageElement) { - if ((locOriginSize.width != 0) && (locOriginSize.height != 0)) { - context.drawImage(locSpriteTexture, - locSpriteRect.x + locOrigin.x, locSpriteRect.y + locOrigin.y, - locOriginSize.width, locOriginSize.height, - pos.x, -(pos.y + this._drawSize.height), - locOriginSize.width, locOriginSize.height); - } - } else if (locSpriteTexture instanceof HTMLCanvasElement) { - if ((locOriginSize.width != 0) && (locOriginSize.height != 0)) { - context.drawImage(locSpriteTexture, - locOrigin.x, locOrigin.y, - locOriginSize.width, locOriginSize.height, - pos.x, -(pos.y + this._drawSize.height), - locOriginSize.width, locOriginSize.height); - } - } - } else { - context.beginPath(); - context.arc(locOrigin.x, locOrigin.y, this._radius, (Math.PI / 180) * this._startAngle, (Math.PI / 180) * this._endAngle, false); - context.lineTo(locOrigin.x, locOrigin.y); - context.clip(); - context.closePath(); - - pos = cc.p(0 | ( -spriteAnchorPoint.x + offsetPixels.x), - 0 | ( -spriteAnchorPoint.y + offsetPixels.y)); - - if (locSpriteTexture instanceof HTMLImageElement) { - context.drawImage(locSpriteTexture, - locSpriteRect.x, locSpriteRect.y, - locSpriteRect.width, locSpriteRect.height, - pos.x, -(pos.y + locSpriteRect.height), - locSpriteRect.width, locSpriteRect.height); - } else if (locSpriteTexture instanceof HTMLCanvasElement) { - context.drawImage(locSpriteTexture, - 0, 0, - locSpriteRect.width, locSpriteRect.height, - pos.x, -(pos.y + locSpriteRect.height), - locSpriteRect.width, locSpriteRect.height); - } - } - cc.INCREMENT_GL_DRAWS(1); - }, - - _updateProgress:function () { - var size = this._sprite.getContentSize(); - var textureSize = this._sprite.getTextureRect().size; - var locMidPoint = this._midPoint; - if (this._type == cc.PROGRESS_TIMER_TYPE_RADIAL) { - - this._origin = cc.p(-(size.width * (0.5 - locMidPoint.x)), -(size.height * (0.5 - locMidPoint.y))); - this._radius = Math.round(Math.sqrt(size.width * size.width + size.height * size.height)); - if (this._reverseDirection) { - this._startAngle = 270 - 3.6 * this._percentage; - } else { - this._endAngle = 270 + 3.6 * this._percentage; - } - } else { - this._origin = cc.p(0, 0); - this._drawPosition = cc.p(0, 0); - var locBarChangeRate = this._barChangeRate; - - var percentageF = this._percentage / 100; - var startPoint = cc.p(size.width * locMidPoint.x, size.height * locMidPoint.y); - var startPointTx = cc.p(textureSize.width * locMidPoint.x, textureSize.height * locMidPoint.y); - - var drawedSize = cc.size((size.width * (1 - locBarChangeRate.x)), (size.height * (1 - locBarChangeRate.y))); - var drawingSize = cc.size((size.width - drawedSize.width) * percentageF, (size.height - drawedSize.height) * percentageF); - this._drawSize = cc.size(drawedSize.width + drawingSize.width, drawedSize.height + drawingSize.height); - - var txDrawedSize = cc.size((textureSize.width * (1 - locBarChangeRate.x)), (textureSize.height * (1 - locBarChangeRate.y))); - var txDrawingSize = cc.size((textureSize.width - txDrawedSize.width) * percentageF, (textureSize.height - txDrawedSize.height) * percentageF); - this._originSize = cc.size(txDrawedSize.width + txDrawingSize.width, txDrawedSize.height + txDrawingSize.height); - - var needToLeft = startPoint.x * percentageF; - var needToLeftTx = startPointTx.x * percentageF; - - if (size.width == this._drawSize.width) { - this._origin.x = 0; - this._drawPosition.x = 0; - } else { - this._origin.x = (startPointTx.x - needToLeftTx); - this._drawPosition.x = (startPoint.x - needToLeft); - } - - var needToTop = (textureSize.height - startPointTx.y) * percentageF; - - if (size.height == this._drawSize.height) { - this._origin.y = 0; - this._drawPosition.y = 0; - } else { - this._origin.y = (textureSize.height - startPointTx.y - needToTop); - this._drawPosition.y = (startPoint.y - (startPoint.y * percentageF)); - } - } - } -}); - -/** - * create a progress timer object with image file name that renders the inner sprite according to the percentage - * @param {cc.Sprite} sprite - * @return {cc.ProgressTimer} - * @example - * // Example - * var progress = cc.ProgressTimer.create('progress.png') - */ -cc.ProgressTimerCanvas.create = function (sprite) { - var progressTimer = new cc.ProgressTimerCanvas(); - if (progressTimer.initWithSprite(sprite)) - return progressTimer; - return null; -}; - -/** - * cc.Progresstimer is a subclass of cc.Node. (Canvas implement)
- * It renders the inner sprite according to the percentage.
- * The progress can be Radial, Horizontal or vertical. - * @class - * @extends cc.NodeRGBA - */ -cc.ProgressTimerWebGL = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerWebGL# */{ - /// ---- common properties start ---- - _type:null, - _percentage:0.0, - _sprite:null, - - _midPoint:null, - _barChangeRate:null, - _reverseDirection:false, - - /** - * Midpoint is used to modify the progress start position. - * If you're using radials type then the midpoint changes the center point - * If you're using bar type the the midpoint changes the bar growth - * it expands from the center but clamps to the sprites edge so: - * you want a left to right then set the midpoint all the way to cc.p(0,y) - * you want a right to left then set the midpoint all the way to cc.p(1,y) - * you want a bottom to top then set the midpoint all the way to cc.p(x,0) - * you want a top to bottom then set the midpoint all the way to cc.p(x,1) - * @return {cc.Point} - */ - getMidpoint:function () { - return this._midPoint; - }, - - /** - * Midpoint setter - * @param {cc.Point} mpoint - */ - setMidpoint:function (mpoint) { - this._midPoint = cc.pClamp(mpoint, cc.p(0, 0), cc.p(1, 1)); - }, - - /** - * This allows the bar type to move the component at a specific rate - * Set the component to 0 to make sure it stays at 100%. - * For example you want a left to right bar but not have the height stay 100% - * Set the rate to be cc.p(0,1); and set the midpoint to = cc.p(0,.5f); - * @return {cc.Point} - */ - getBarChangeRate:function () { - return this._barChangeRate; - }, - - /** - * @param {cc.Point} barChangeRate - */ - setBarChangeRate:function (barChangeRate) { - this._barChangeRate = cc.pClamp(barChangeRate, cc.p(0, 0), cc.p(1, 1)); - }, - - /** - * Change the percentage to change progress - * @return {cc.PROGRESS_TIMER_TYPE_RADIAL|cc.PROGRESS_TIMER_TYPE_BAR} - */ - getType:function () { - return this._type; - }, - - /** - * Percentages are from 0 to 100 - * @return {Number} - */ - getPercentage:function () { - return this._percentage; - }, - - /** - * The image to show the progress percentage, retain - * @return {cc.Sprite} - */ - getSprite:function () { - return this._sprite; - }, - - /** - * from 0-100 - * @param {Number} percentage - */ - setPercentage:function (percentage) { - if (this._percentage != percentage) { - this._percentage = cc.clampf(percentage, 0, 100); - this._updateProgress(); - } - }, - - setOpacityModifyRGB:function (bValue) { - }, - - isOpacityModifyRGB:function () { - return false; - }, - - isReverseDirection:function () { - return this._reverseDirection; - }, - - _boundaryTexCoord:function (index) { - if (index < cc.PROGRESS_TEXTURE_COORDS_COUNT) { - if (this._reverseDirection) - return cc.p((cc.PROGRESS_TEXTURE_COORDS >> (7 - (index << 1))) & 1, (cc.PROGRESS_TEXTURE_COORDS >> (7 - ((index << 1) + 1))) & 1); - else - return cc.p((cc.PROGRESS_TEXTURE_COORDS >> ((index << 1) + 1)) & 1, (cc.PROGRESS_TEXTURE_COORDS >> (index << 1)) & 1); - } - return cc.PointZero(); - }, - /// ---- common properties end ---- - - _vertexDataCount:0, - _vertexData:null, - _vertexArrayBuffer:null, - _vertexWebGLBuffer:null, - _vertexDataDirty:false, - - ctor:function () { + _ctorForWebGL: function () { cc.NodeRGBA.prototype.ctor.call(this); this._type = cc.PROGRESS_TIMER_TYPE_RADIAL; this._percentage = 0.0; @@ -601,7 +249,14 @@ cc.ProgressTimerWebGL = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerWebGL# */{ /** * @param {Boolean} reverse */ - setReverseProgress:function (reverse) { + setReverseProgress:null, + + _setReverseProgressForCanvas:function (reverse) { + if (this._reverseDirection !== reverse) + this._reverseDirection = reverse; + }, + + _setReverseProgressForWebGL:function (reverse) { if (this._reverseDirection !== reverse) { this._reverseDirection = reverse; @@ -615,10 +270,19 @@ cc.ProgressTimerWebGL = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerWebGL# */{ /** * @param {cc.Sprite} sprite */ - setSprite:function (sprite) { + setSprite:null, + + _setSpriteForCanvas:function (sprite) { if (this._sprite != sprite) { this._sprite = sprite; this.setContentSize(this._sprite.getContentSize()); + } + }, + + _setSpriteForWebGL:function (sprite) { + if (sprite && this._sprite != sprite) { + this._sprite = sprite; + this.setContentSize(sprite.getContentSize()); // Everytime we set a new sprite, we free the current vertex data if (this._vertexData) { @@ -633,7 +297,14 @@ cc.ProgressTimerWebGL = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerWebGL# */{ * set Progress type of cc.ProgressTimer * @param {cc.PROGRESS_TIMER_TYPE_RADIAL|cc.PROGRESS_TIMER_TYPE_BAR} type */ - setType:function (type) { + setType:null, + + _setTypeForCanvas:function (type) { + if (type !== this._type) + this._type = type; + }, + + _setTypeForWebGL:function (type) { if (type !== this._type) { // release all previous information if (this._vertexData) { @@ -641,7 +312,6 @@ cc.ProgressTimerWebGL = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerWebGL# */{ this._vertexArrayBuffer = null; this._vertexDataCount = 0; } - this._type = type; } }, @@ -650,7 +320,14 @@ cc.ProgressTimerWebGL = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerWebGL# */{ * Reverse Progress setter * @param {Boolean} reverse */ - setReverseDirection:function (reverse) { + setReverseDirection: null, + + _setReverseDirectionForCanvas: function (reverse) { + if (this._reverseDirection !== reverse) + this._reverseDirection = reverse; + }, + + _setReverseDirectionForWebGL: function (reverse) { if (this._reverseDirection !== reverse) { this._reverseDirection = reverse; //release all previous information @@ -692,12 +369,28 @@ cc.ProgressTimerWebGL = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerWebGL# */{ var max = cc.p(quad.tr.vertices.x, quad.tr.vertices.y); return {x: min.x * (1 - alpha.x) + max.x * alpha.x, y: min.y * (1 - alpha.y) + max.y * alpha.y}; }, + /** * Initializes a progress timer with the sprite as the shape the timer goes through * @param {cc.Sprite} sprite * @return {Boolean} */ - initWithSprite:function (sprite) { + initWithSprite:null, + + _initWithSpriteForCanvas:function (sprite) { + this.setPercentage(0); + this.setAnchorPoint(cc.p(0.5, 0.5)); + + this._type = cc.PROGRESS_TIMER_TYPE_RADIAL; + this._reverseDirection = false; + this.setMidpoint(cc.p(0.5, 0.5)); + this.setBarChangeRate(cc.p(1, 1)); + this.setSprite(sprite); + + return true; + }, + + _initWithSpriteForWebGL:function (sprite) { this.setPercentage(0); this._vertexData = null; this._vertexArrayBuffer = null; @@ -717,9 +410,63 @@ cc.ProgressTimerWebGL = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerWebGL# */{ /** * stuff gets drawn here - * @param {WebGLRenderingContext } ctx + * @param {CanvasRenderingContext2D} ctx */ - draw:function (ctx) { + draw:null, + + _drawForCanvas:function (ctx) { + var context = ctx || cc.renderContext; + + var locSprite = this._sprite; + context.globalAlpha = locSprite._displayedOpacity / 255; + var locRect = locSprite._rect, locOffsetPosition = locSprite._offsetPosition; + var flipXOffset = 0 | (locOffsetPosition.x), flipYOffset = -locOffsetPosition.y - locRect.height; + + context.save(); + if (locSprite._flippedX) { + flipXOffset = -locOffsetPosition.x - locRect.width; + context.scale(-1, 1); + } + if (locSprite._flippedY) { + flipYOffset = locOffsetPosition.y; + context.scale(1, -1); + } + + //clip + if (this._type == cc.PROGRESS_TIMER_TYPE_BAR) { + var locBarRect = this._barRect; + context.beginPath(); + context.rect(locBarRect.x,locBarRect.y,locBarRect.width,locBarRect.height); + context.clip(); + context.closePath(); + }else if(this._type == cc.PROGRESS_TIMER_TYPE_RADIAL){ + var locOrigin = this._origin; + context.beginPath(); + context.arc(locOrigin.x, locOrigin.y, this._radius, (Math.PI / 180) * this._startAngle, (Math.PI / 180) * this._endAngle, this._counterClockWise); + context.lineTo(locOrigin.x, locOrigin.y); + context.clip(); + context.closePath(); + } + + //draw sprite + if (locSprite._texture && locRect.width > 0) { + var image = locSprite._texture.getHtmlElementObj(); + if (locSprite._colorized) { + context.drawImage(image, + 0, 0, locRect.width, locRect.height, + flipXOffset, flipYOffset, locRect.width, locRect.height); + } else { + context.drawImage(image, + locRect.x, locRect.y, locRect.width, locRect.height, + flipXOffset, flipYOffset, locRect.width, locRect.height); + } + } + + context.restore(); + cc.INCREMENT_GL_DRAWS(1); + }, + + _drawForWebGL:function (ctx) { var context = ctx || cc.renderContext; if (!this._vertexData || !this._sprite) return; @@ -1020,7 +767,101 @@ cc.ProgressTimerWebGL = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerWebGL# */{ this._vertexDataDirty = true; }, - _updateProgress:function () { + _updateProgress:null, + + _updateProgressForCanvas:function () { + var locSprite = this._sprite; + var spriteSize = locSprite.getContentSize(); + var locMidPoint = this._midPoint; + + if (this._type == cc.PROGRESS_TIMER_TYPE_RADIAL) { + this._radius = Math.round(Math.sqrt(spriteSize.width * spriteSize.width + spriteSize.height * spriteSize.height)); + var locStartAngle = 270; + var locEndAngle = 270; + var locCounterClockWise = false; + var locOrigin = this._origin; + + locOrigin.x = spriteSize.width * locMidPoint.x; + locOrigin.y = -spriteSize.height * locMidPoint.y; + + if (this._reverseDirection) { + locStartAngle = 270 - 3.6 * this._percentage; + } else { + locEndAngle = 270 + 3.6 * this._percentage; + } + + if (locSprite._flippedX) { + locOrigin.x -= spriteSize.width * (this._midPoint.x * 2); + locStartAngle= -locStartAngle; + locEndAngle= -locEndAngle; + locStartAngle -= 180; + locEndAngle -= 180; + locCounterClockWise = !locCounterClockWise; + } + if (locSprite._flippedY) { + locOrigin.y+=spriteSize.height*(this._midPoint.y*2); + locCounterClockWise = !locCounterClockWise; + locStartAngle= -locStartAngle; + locEndAngle= -locEndAngle; + } + + this._startAngle = locStartAngle; + this._endAngle = locEndAngle; + this._counterClockWise = locCounterClockWise; + } else { + var locBarChangeRate = this._barChangeRate; + var percentageF = this._percentage / 100; + var locBarRect = this._barRect; + + var drawedSize = cc.size((spriteSize.width * (1 - locBarChangeRate.x)), (spriteSize.height * (1 - locBarChangeRate.y))); + var drawingSize = cc.size((spriteSize.width - drawedSize.width) * percentageF, (spriteSize.height - drawedSize.height) * percentageF); + var currentDrawSize = cc.size(drawedSize.width + drawingSize.width, drawedSize.height + drawingSize.height); + + var startPoint = cc.p(spriteSize.width * locMidPoint.x, spriteSize.height * locMidPoint.y); + + var needToLeft = startPoint.x - currentDrawSize.width / 2; + if (locMidPoint.x > 0.5) { + if (currentDrawSize.width / 2 >= spriteSize.width - startPoint.x) { + needToLeft = spriteSize.width - currentDrawSize.width; + } + } + + var needToTop = startPoint.y - currentDrawSize.height / 2; + if (locMidPoint.y > 0.5) { + if (currentDrawSize.height / 2 >= spriteSize.height - startPoint.y) { + needToTop = spriteSize.height - 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; + } + }, + + _updateProgressForWebGL:function () { var locType = this._type; if(locType === cc.PROGRESS_TIMER_TYPE_RADIAL) this._updateRadial(); @@ -1031,6 +872,26 @@ cc.ProgressTimerWebGL = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerWebGL# */{ } }); +if(cc.Browser.supportWebGL) { + cc.ProgressTimer.prototype.ctor = cc.ProgressTimer.prototype._ctorForWebGL; + cc.ProgressTimer.prototype.setReverseProgress = cc.ProgressTimer.prototype._setReverseProgressForWebGL; + cc.ProgressTimer.prototype.setSprite = cc.ProgressTimer.prototype._setSpriteForWebGL; + cc.ProgressTimer.prototype.setType = cc.ProgressTimer.prototype._setTypeForWebGL; + cc.ProgressTimer.prototype.setReverseDirection = cc.ProgressTimer.prototype._setReverseDirectionForWebGL; + cc.ProgressTimer.prototype.initWithSprite = cc.ProgressTimer.prototype._initWithSpriteForWebGL; + cc.ProgressTimer.prototype.draw = cc.ProgressTimer.prototype._drawForWebGL; + cc.ProgressTimer.prototype._updateProgress = cc.ProgressTimer.prototype._updateProgressForWebGL; +} else { + cc.ProgressTimer.prototype.ctor = cc.ProgressTimer.prototype._ctorForCanvas; + cc.ProgressTimer.prototype.setReverseProgress = cc.ProgressTimer.prototype._setReverseProgressForCanvas; + cc.ProgressTimer.prototype.setSprite = cc.ProgressTimer.prototype._setSpriteForCanvas; + cc.ProgressTimer.prototype.setType = cc.ProgressTimer.prototype._setTypeForCanvas; + cc.ProgressTimer.prototype.setReverseDirection = cc.ProgressTimer.prototype._setReverseDirectionForCanvas; + cc.ProgressTimer.prototype.initWithSprite = cc.ProgressTimer.prototype._initWithSpriteForCanvas; + cc.ProgressTimer.prototype.draw = cc.ProgressTimer.prototype._drawForCanvas; + cc.ProgressTimer.prototype._updateProgress = cc.ProgressTimer.prototype._updateProgressForCanvas; +} + /** * create a progress timer object with image file name that renders the inner sprite according to the percentage * @param {cc.Sprite} sprite @@ -1039,13 +900,11 @@ cc.ProgressTimerWebGL = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerWebGL# */{ * // Example * var progress = cc.ProgressTimer.create('progress.png') */ -cc.ProgressTimerWebGL.create = function (sprite) { - var progressTimer = new cc.ProgressTimerWebGL(); +cc.ProgressTimer.create = function (sprite) { + var progressTimer = new cc.ProgressTimer(); if (progressTimer.initWithSprite(sprite)) return progressTimer; return null; }; -cc.ProgressTimer = (cc.Browser.supportWebGL) ? cc.ProgressTimerWebGL : cc.ProgressTimerCanvas; - diff --git a/cocos2d/misc_nodes/CCRenderTexture.js b/cocos2d/misc_nodes/CCRenderTexture.js index 4d3fb87708..40d8e0a4a8 100644 --- a/cocos2d/misc_nodes/CCRenderTexture.js +++ b/cocos2d/misc_nodes/CCRenderTexture.js @@ -74,18 +74,20 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * the offscreen canvas for rendering and storing the texture * @type HTMLCanvasElement */ - canvas:null, + _cacheCanvas:null, /** * stores a reference to the canvas context object - * @type CanvasContext + * @type CanvasRenderingContext2D */ - context:null, + _cacheContext:null, + _fBO:0, _depthRenderBuffer:0, _oldFBO:0, _texture:null, _textureCopy:null, _uITextureImage:null, + _pixelFormat:cc.TEXTURE_2D_PIXEL_FORMAT_RGBA8888, _sprite:null, @@ -96,35 +98,49 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ _clearStencil:0, _autoDraw:false, + _clearColorStr:null, + /** * Constructor */ - ctor:function () { + ctor: null, + + _ctorForCanvas: function () { cc.Node.prototype.ctor.call(this); + this._clearColor = cc.c4f(1, 1, 1, 1); + this._clearColorStr = "rgba(255,255,255,1)"; - if (cc.renderContextType === cc.CANVAS) { - this.canvas = document.createElement('canvas'); - this.context = this.canvas.getContext('2d'); - this.setAnchorPoint(cc.p(0, 0)); - } else { - this._clearColor = cc.c4f(0, 0, 0, 0); - } + this._cacheCanvas = document.createElement('canvas'); + this._cacheContext = this._cacheCanvas.getContext('2d'); + this.setAnchorPoint(cc.p(0, 0)); }, - onExit:function () { + _ctorForWebGL: function () { + cc.Node.prototype.ctor.call(this); + this._clearColor = cc.c4f(0, 0, 0, 0); + }, + + onExit:null, + + _onExitForCanvas:function () { cc.Node.prototype.onExit.call(this); - if (cc.renderContextType === cc.WEBGL) { - this._sprite = null; - this._textureCopy = null; - - var gl = cc.renderContext; - gl.deleteFramebuffer(this._fBO); - if (this._depthRenderBuffer) - gl.deleteRenderbuffer(this._depthRenderBuffer); - this._uITextureImage = null; - if(this._texture) - this._texture.releaseTexture(); - } + this._cacheContext = null; + this._cacheCanvas = null; + }, + + _onExitForWebGL: function () { + cc.Node.prototype.onExit.call(this); + + this._sprite = null; + this._textureCopy = null; + + var gl = cc.renderContext; + gl.deleteFramebuffer(this._fBO); + if (this._depthRenderBuffer) + gl.deleteRenderbuffer(this._depthRenderBuffer); + this._uITextureImage = null; + if (this._texture) + this._texture.releaseTexture(); }, /** @@ -142,30 +158,6 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ this._sprite = sprite; }, - /** - * @return {HTMLCanvasElement} - */ - getCanvas:function () { - return this.canvas; - }, - - /** - * @param {cc.Size} size - */ - setContentSize:function (size) { - if (!size) - return; - - //if (!cc.Size.CCSizeEqualToSize(size, this._contentSize)) { - this._super(size); - if(cc.renderContextType === cc.CANVAS){ - this.canvas.width = size.width * 1.5; - this.canvas.height = size.height * 1.5; - this.context.translate(0, this.canvas.height); - } - //} - }, - /** * @param {Number} width * @param {Number} height @@ -173,109 +165,124 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * @param {Number} depthStencilFormat * @return {Boolean} */ - initWithWidthAndHeight:function (width, height, format, depthStencilFormat) { - if (cc.renderContextType === cc.CANVAS) { - this.canvas.width = width || 10; - this.canvas.height = height || 10; - - this.context.translate(0, this.canvas.height); - this._sprite = cc.Sprite.createWithTexture(this.canvas); + initWithWidthAndHeight: null, + + _initWithWidthAndHeightForCanvas: function (width, height, format, depthStencilFormat) { + var locCacheCanvas = this._cacheCanvas; + locCacheCanvas.width = width || 10; + locCacheCanvas.height = height || 10; + this._cacheContext.translate(0, locCacheCanvas.height); + var texture = new cc.Texture2D(); + texture.initWithElement(locCacheCanvas); + texture.handleLoadedTexture(); + this._sprite = cc.Sprite.createWithTexture(texture); + return true; + }, - return true; - } else { - cc.Assert(format != cc.TEXTURE_2D_PIXEL_FORMAT_A8, "only RGB and RGBA formats are valid for a render texture"); + _initWithWidthAndHeightForWebGL: function (width, height, format, depthStencilFormat) { + cc.Assert(format != cc.TEXTURE_2D_PIXEL_FORMAT_A8, "only RGB and RGBA formats are valid for a render texture"); - var gl = cc.renderContext; + var gl = cc.renderContext; - width = 0 | (width * cc.CONTENT_SCALE_FACTOR()); - height = 0 | (height * cc.CONTENT_SCALE_FACTOR()); + width = 0 | (width * cc.CONTENT_SCALE_FACTOR()); + height = 0 | (height * cc.CONTENT_SCALE_FACTOR()); - this._oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING); + this._oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING); - // textures must be power of two squared - var powW , powH; + // textures must be power of two squared + var powW , powH; - if (cc.Configuration.getInstance().supportsNPOT()) { - powW = width; - powH = height; - } else { - powW = cc.NextPOT(width); - powH = cc.NextPOT(height); - } + if (cc.Configuration.getInstance().supportsNPOT()) { + powW = width; + powH = height; + } else { + powW = cc.NextPOT(width); + powH = cc.NextPOT(height); + } - //void *data = malloc(powW * powH * 4); - var dataLen = powW * powH * 4; - var data = new Uint8Array(dataLen); - //memset(data, 0, (int)(powW * powH * 4)); - for (var i = 0; i < powW * powH * 4; i++) - data[i] = 0; + //void *data = malloc(powW * powH * 4); + var dataLen = powW * powH * 4; + var data = new Uint8Array(dataLen); + //memset(data, 0, (int)(powW * powH * 4)); + for (var i = 0; i < powW * powH * 4; i++) + data[i] = 0; - this._pixelFormat = format; + this._pixelFormat = format; - this._texture = new cc.Texture2D(); - if (!this._texture) - return false; + this._texture = new cc.Texture2D(); + if (!this._texture) + return false; - this._texture.initWithData(data, this._pixelFormat, powW, powH, cc.size(width, height)); - //free( data ); + var locTexture = this._texture; + locTexture.initWithData(data, this._pixelFormat, powW, powH, cc.size(width, height)); + //free( data ); - var oldRBO = gl.getParameter(gl.RENDERBUFFER_BINDING); + var oldRBO = gl.getParameter(gl.RENDERBUFFER_BINDING); - if (cc.Configuration.getInstance().checkForGLExtension("GL_QCOM")) { - this._textureCopy = new cc.Texture2D(); - if (!this._textureCopy) { - return false; - } - this._textureCopy.initWithData(data, this._pixelFormat, powW, powH, cc.size(width, height)); + if (cc.Configuration.getInstance().checkForGLExtension("GL_QCOM")) { + this._textureCopy = new cc.Texture2D(); + if (!this._textureCopy) { + return false; } + this._textureCopy.initWithData(data, this._pixelFormat, powW, powH, cc.size(width, height)); + } - // generate FBO - this._fBO = gl.createFramebuffer(); - gl.bindFramebuffer(gl.FRAMEBUFFER, this._fBO); + // generate FBO + this._fBO = gl.createFramebuffer(); + gl.bindFramebuffer(gl.FRAMEBUFFER, this._fBO); - // associate texture with FBO - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this._texture._webTextureObj, 0); + // associate texture with FBO + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, locTexture._webTextureObj, 0); - if (depthStencilFormat != 0) { - //create and attach depth buffer - this._depthRenderBuffer = gl.createRenderbuffer(); - gl.bindRenderbuffer(gl.RENDERBUFFER, this._depthRenderBuffer); - gl.renderbufferStorage(gl.RENDERBUFFER, depthStencilFormat, powW, powH); - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer); + if (depthStencilFormat != 0) { + //create and attach depth buffer + this._depthRenderBuffer = gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, this._depthRenderBuffer); + gl.renderbufferStorage(gl.RENDERBUFFER, depthStencilFormat, powW, powH); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer); - // if depth format is the one with stencil part, bind same render buffer as stencil attachment - //if (depthStencilFormat == gl.DEPTH24_STENCIL8) - // gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer); - } + // if depth format is the one with stencil part, bind same render buffer as stencil attachment + //if (depthStencilFormat == gl.DEPTH24_STENCIL8) + // gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer); + } - // check if it worked (probably worth doing :) ) - cc.Assert(gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE, "Could not attach texture to framebuffer"); + // check if it worked (probably worth doing :) ) + cc.Assert(gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE, "Could not attach texture to framebuffer"); - this._texture.setAliasTexParameters(); + locTexture.setAliasTexParameters(); - this._sprite = cc.Sprite.createWithTexture(this._texture); - this._sprite.setScaleY(-1); - this._sprite.setBlendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + this._sprite = cc.Sprite.createWithTexture(locTexture); + var locSprite = this._sprite; + locSprite.setScaleY(-1); + locSprite.setBlendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); - gl.bindRenderbuffer(gl.RENDERBUFFER, oldRBO); - gl.bindFramebuffer(gl.FRAMEBUFFER, this._oldFBO); + gl.bindRenderbuffer(gl.RENDERBUFFER, oldRBO); + gl.bindFramebuffer(gl.FRAMEBUFFER, this._oldFBO); - // Diabled by default. - this._autoDraw = false; + // Disabled by default. + this._autoDraw = false; - // add sprite for backward compatibility - this.addChild(this._sprite); - return true; - } + // add sprite for backward compatibility + this.addChild(locSprite); + return true; }, /** * starts grabbing */ - begin:function () { - if (cc.renderContextType === cc.CANVAS) - return; + begin: null, + + _beginForCanvas: function () { + cc.renderContext = this._cacheContext; + + /*// Save the current matrix + cc.kmGLMatrixMode(cc.KM_GL_PROJECTION); + cc.kmGLPushMatrix(); + cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW); + cc.kmGLPushMatrix();*/ + }, + _beginForWebGL: function () { // Save the current matrix cc.kmGLMatrixMode(cc.KM_GL_PROJECTION); cc.kmGLPushMatrix(); @@ -326,8 +333,8 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * @param {Number} g green 0-1 * @param {Number} b blue 0-1 * @param {Number} a alpha 0-1 0 is transparent - * @param {Number} depthValue - * @param {Number} stencilValue + * @param {Number} [depthValue=] + * @param {Number} [stencilValue=] */ beginWithClear:function (r, g, b, a, depthValue, stencilValue) { var gl = cc.renderContext; @@ -337,10 +344,27 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ this._beginWithClear(r, g, b, a, depthValue, stencilValue, (gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT)); }, - _beginWithClear:function (r, g, b, a, depthValue, stencilValue, flags) { - if (cc.renderContextType === cc.CANVAS) - return; + _beginWithClear: null, + + _beginWithClearForCanvas: function (r, g, b, a, depthValue, stencilValue, flags) { + this.begin(); + + r = r || 0; + g = g || 0; + b = b || 0; + a = a || 1; + + //var context = cc.renderContext; + var context = this._cacheContext; + var locCanvas = this._cacheCanvas; + context.save(); + context.fillStyle = "rgba(" + (0 | (r * 255)) + "," + (0 | (g * 255)) + "," + (0 | (b * 255)) + "," + a + ")"; + context.clearRect(0, 0, locCanvas.width, -locCanvas.height); + context.fillRect(0, 0, locCanvas.width, -locCanvas.height); + context.restore(); + }, + _beginWithClearForWebGL: function (r, g, b, a, depthValue, stencilValue, flags) { this.begin(); var gl = cc.renderContext; @@ -381,10 +405,21 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ /** * ends grabbing */ - end:function () { - if (cc.renderContextType === cc.CANVAS) - return; + end: null, + + _endForCanvas: function () { + cc.renderContext = cc.mainRenderContextBackup; + + //TODO + /*//restore viewport + director.setViewport(); + cc.kmGLMatrixMode(cc.KM_GL_PROJECTION); + cc.kmGLPopMatrix(); + cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW); + cc.kmGLPopMatrix();*/ + }, + _endForWebGL: function () { var gl = cc.renderContext; var director = cc.Director.getInstance(); gl.bindFramebuffer(gl.FRAMEBUFFER, this._oldFBO); @@ -398,15 +433,15 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ /* var size = director.getWinSizeInPixels(); - // restore viewport - gl.viewport(0, 0, size.width * cc.CONTENT_SCALE_FACTOR(), size.height * cc.CONTENT_SCALE_FACTOR()); + // restore viewport + gl.viewport(0, 0, size.width * cc.CONTENT_SCALE_FACTOR(), size.height * cc.CONTENT_SCALE_FACTOR()); - // special viewport for 3d projection + retina display - if (director.getProjection() == cc.DIRECTOR_PROJECTION_3D && cc.CONTENT_SCALE_FACTOR() != 1) { - gl.viewport((-size.width / 2), (-size.height / 2), (size.width * cc.CONTENT_SCALE_FACTOR()), (size.height * cc.CONTENT_SCALE_FACTOR())); - } + // special viewport for 3d projection + retina display + if (director.getProjection() == cc.DIRECTOR_PROJECTION_3D && cc.CONTENT_SCALE_FACTOR() != 1) { + gl.viewport((-size.width / 2), (-size.height / 2), (size.width * cc.CONTENT_SCALE_FACTOR()), (size.height * cc.CONTENT_SCALE_FACTOR())); + } - director.setProjection(director.getProjection());*/ + director.setProjection(director.getProjection());*/ }, /** @@ -417,26 +452,31 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * @param {Number} a alpha 0-1 */ clear:function (r, g, b, a) { - if (cc.renderContextType === cc.CANVAS) { - var rect = r; - if (rect) - this.context.clearRect(rect.x, rect.y, rect.width, rect.height); - else - this.context.clearRect(0, 0, this.canvas.width, -this.canvas.height); - } else { - this.beginWithClear(r, g, b, a); - this.end(); - } + this.beginWithClear(r, g, b, a); + this.end(); + }, + + clearRect:null, + + _clearRectForCanvas:function(x, y, width, height){ + this._cacheContext.clearRect(x, y, width, -height); + }, + + _clearRectForWebGL:function(x, y, width, height){ + //TODO need to implement }, /** * clears the texture with a specified depth value * @param {Number} depthValue */ - clearDepth:function (depthValue) { - if (cc.renderContextType === cc.CANVAS) - return; + clearDepth:null, + _clearDepthForCanvas:function (depthValue) { + cc.log("clearDepth isn't supported on Cocos2d-Html5"); + }, + + _clearDepthForWebGL:function (depthValue) { this.begin(); var gl = cc.renderContext; @@ -455,10 +495,13 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * clears the texture with a specified stencil value * @param {Number} stencilValue */ - clearStencil:function (stencilValue) { - if (cc.renderContextType === cc.CANVAS) - return; + clearStencil:null, + + _clearStencilForCanvas:function (stencilValue) { + cc.log("clearDepth isn't supported on Cocos2d-Html5"); + }, + _clearStencilForWebGL:function (stencilValue) { var gl = cc.renderContext; // save old stencil value var stencilClearValue = gl.getParameter(gl.STENCIL_CLEAR_VALUE); @@ -470,11 +513,27 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ gl.clearStencil(stencilClearValue); }, - visit:function (ctx) { - if (cc.renderContextType === cc.CANVAS) { - this._super(ctx); + visit:null, + + _visitForCanvas:function (ctx) { + // override visit. + // Don't call visit on its children + if (!this._visible) return; - } + + ctx = ctx || cc.renderContext; + ctx.save(); + + this.draw(ctx); // update children of RenderTexture before + this.transform(ctx); + this._sprite.visit(); // draw the RenderTexture + + ctx.restore(); + + this._orderOfArrival = 0; + }, + + _visitForWebGL:function (ctx) { // override visit. // Don't call visit on its children if (!this._visible) @@ -482,8 +541,9 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ cc.kmGLPushMatrix(); - if (this._grid && this._grid.isActive()) { - this._grid.beforeDraw(); + var locGrid = this._grid; + if (locGrid && locGrid.isActive()) { + locGrid.beforeDraw(); this.transformAncestors(); } @@ -491,64 +551,91 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ this._sprite.visit(); this.draw(ctx); - if (this._grid && this._grid.isActive()) - this._grid.afterDraw(this); + if (locGrid && locGrid.isActive()) + locGrid.afterDraw(this); cc.kmGLPopMatrix(); this._orderOfArrival = 0; }, - draw:function (ctx) { - if (cc.renderContextType === cc.CANVAS) { - this._super(ctx); - return; + draw:null, + + _drawForCanvas: function (ctx) { + ctx = ctx || cc.renderContext; + if (this._autoDraw) { + this.begin(); + + if (this._clearFlags) { + var locCanvas = this._cacheCanvas; + ctx.save(); + ctx.fillStyle = this._clearColorStr; + ctx.clearRect(0, 0, locCanvas.width, -locCanvas.height); + ctx.fillRect(0, 0, locCanvas.width, -locCanvas.height); + ctx.restore(); + } + + //! make sure all children are drawn + this.sortAllChildren(); + var locChildren = this._children; + var childrenLen = locChildren.length; + var selfSprite = this._sprite; + for (var i = 0; i < childrenLen; i++) { + var getChild = locChildren[i]; + if (getChild != selfSprite) + getChild.visit(); + } + + this.end(); } + }, + _drawForWebGL: function (ctx) { var gl = cc.renderContext; if (this._autoDraw) { this.begin(); - if (this._clearFlags) { + var locClearFlags = this._clearFlags; + if (locClearFlags) { var oldClearColor = [0.0, 0.0, 0.0, 0.0]; var oldDepthClearValue = 0.0; var oldStencilClearValue = 0; // backup and set - if (this._clearFlags & gl.COLOR_BUFFER_BIT) { + if (locClearFlags & gl.COLOR_BUFFER_BIT) { oldClearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE); gl.clearColor(this._clearColor.r, this._clearColor.g, this._clearColor.b, this._clearColor.a); } - if (this._clearFlags & gl.DEPTH_BUFFER_BIT) { + if (locClearFlags & gl.DEPTH_BUFFER_BIT) { oldDepthClearValue = gl.getParameter(gl.DEPTH_CLEAR_VALUE); gl.clearDepth(this._clearDepth); } - if (this._clearFlags & gl.STENCIL_BUFFER_BIT) { + if (locClearFlags & gl.STENCIL_BUFFER_BIT) { oldStencilClearValue = gl.getParameter(gl.STENCIL_CLEAR_VALUE); gl.clearStencil(this._clearStencil); } // clear - gl.clear(this._clearFlags); + gl.clear(locClearFlags); // restore - if (this._clearFlags & gl.COLOR_BUFFER_BIT) + if (locClearFlags & gl.COLOR_BUFFER_BIT) gl.clearColor(oldClearColor[0], oldClearColor[1], oldClearColor[2], oldClearColor[3]); - if (this._clearFlags & gl.DEPTH_BUFFER_BIT) + if (locClearFlags & gl.DEPTH_BUFFER_BIT) gl.clearDepth(oldDepthClearValue); - if (this._clearFlags & gl.STENCIL_BUFFER_BIT) + if (locClearFlags & gl.STENCIL_BUFFER_BIT) gl.clearStencil(oldStencilClearValue); } //! make sure all children are drawn this.sortAllChildren(); - - for (var i = 0; i < this._children.length; i++) { - var getChild = this._children[i]; + var locChildren = this._children; + for (var i = 0; i < locChildren.length; i++) { + var getChild = locChildren[i]; if (getChild != this._sprite) getChild.visit(); } @@ -561,7 +648,14 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * creates a new CCImage from with the texture's data. Caller is responsible for releasing it by calling delete. * @return {cc.Image} */ - newCCImage:function (flipImage) { + newCCImage:null, + + _newCCImageForCanvas:function (flipImage) { + cc.log("saveToFile isn't supported on Cocos2d-Html5"); + return null; + }, + + _newCCImageForWebGL:function (flipImage) { if(flipImage === null) flipImage = true; cc.Assert(this._pixelFormat == cc.TEXTURE_2D_PIXEL_FORMAT_RGBA8888, "only RGBA8888 can be saved as image"); @@ -621,7 +715,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * @param {Number} format */ saveToFile:function (filePath, format) { - cc.log("saveToFile is NoSupported on Cocos2d-Html5"); + cc.log("saveToFile isn't supported on Cocos2d-Html5"); }, /** @@ -629,7 +723,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * @param {cc.Class} obj */ listenToBackground:function (obj) { - cc.log("listenToBackground is NoSupported on Cocos2d-Html5"); + cc.log("listenToBackground isn't supported on Cocos2d-Html5"); }, /** @@ -637,7 +731,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * @param {cc.Class} obj */ listenToForeground:function (obj) { - cc.log("listenToForeground is NoSupported on Cocos2d-Html5"); + cc.log("listenToForeground isn't supported on Cocos2d-Html5"); }, /** @@ -660,8 +754,24 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ return this._clearColor; }, - setClearColor:function (clearColor) { - this._clearColor = cc.c4f(clearColor.r, clearColor.g, clearColor.b, clearColor.a); + setClearColor:null, + + _setClearColorForCanvas:function (clearColor) { + var locClearColor = this._clearColor; + locClearColor.r = clearColor.r; + locClearColor.g = clearColor.g; + locClearColor.b = clearColor.b; + locClearColor.a = clearColor.a; + + this._clearColorStr = "rgba(" + (0 | (clearColor.r * 255)) + "," + (0 | (clearColor.g * 255)) + "," + (0 | (clearColor.b * 255)) + "," + clearColor.a + ")"; + }, + + _setClearColorForWebGL:function (clearColor) { + var locClearColor = this._clearColor; + locClearColor.r = clearColor.r; + locClearColor.g = clearColor.g; + locClearColor.b = clearColor.b; + locClearColor.a = clearColor.a; }, /** @@ -702,6 +812,36 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ } }); +if(cc.Browser.supportWebGL){ + cc.RenderTexture.prototype.ctor = cc.RenderTexture.prototype._ctorForWebGL; + cc.RenderTexture.prototype.onExit = cc.RenderTexture.prototype._onExitForWebGL; + cc.RenderTexture.prototype.initWithWidthAndHeight = cc.RenderTexture.prototype._initWithWidthAndHeightForWebGL; + cc.RenderTexture.prototype.begin = cc.RenderTexture.prototype._beginForWebGL; + cc.RenderTexture.prototype._beginWithClear = cc.RenderTexture.prototype._beginWithClearForWebGL; + cc.RenderTexture.prototype.end = cc.RenderTexture.prototype._endForWebGL; + cc.RenderTexture.prototype.clearRect = cc.RenderTexture.prototype._clearRectForWebGL; + cc.RenderTexture.prototype.clearDepth = cc.RenderTexture.prototype._clearDepthForWebGL; + cc.RenderTexture.prototype.clearStencil = cc.RenderTexture.prototype._clearStencilForWebGL; + cc.RenderTexture.prototype.visit = cc.RenderTexture.prototype._visitForWebGL; + cc.RenderTexture.prototype.draw = cc.RenderTexture.prototype._drawForWebGL; + cc.RenderTexture.prototype.newCCImage = cc.RenderTexture.prototype._newCCImageForWebGL; + cc.RenderTexture.prototype.setClearColor = cc.RenderTexture.prototype._setClearColorForWebGL; +} else { + cc.RenderTexture.prototype.ctor = cc.RenderTexture.prototype._ctorForCanvas; + cc.RenderTexture.prototype.onExit = cc.RenderTexture.prototype._onExitForCanvas; + cc.RenderTexture.prototype.initWithWidthAndHeight = cc.RenderTexture.prototype._initWithWidthAndHeightForCanvas; + cc.RenderTexture.prototype.begin = cc.RenderTexture.prototype._beginForCanvas; + cc.RenderTexture.prototype._beginWithClear = cc.RenderTexture.prototype._beginWithClearForCanvas; + cc.RenderTexture.prototype.end = cc.RenderTexture.prototype._endForCanvas; + cc.RenderTexture.prototype.clearRect = cc.RenderTexture.prototype._clearRectForCanvas; + cc.RenderTexture.prototype.clearDepth = cc.RenderTexture.prototype._clearDepthForCanvas; + cc.RenderTexture.prototype.clearStencil = cc.RenderTexture.prototype._clearStencilForCanvas; + cc.RenderTexture.prototype.visit = cc.RenderTexture.prototype._visitForCanvas; + cc.RenderTexture.prototype.draw = cc.RenderTexture.prototype._drawForCanvas; + cc.RenderTexture.prototype.newCCImage = cc.RenderTexture.prototype._newCCImageForCanvas; + cc.RenderTexture.prototype.setClearColor = cc.RenderTexture.prototype._setClearColorForCanvas; +} + /** * creates a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid * @param {Number} width diff --git a/cocos2d/particle_nodes/CCParticleBatchNode.js b/cocos2d/particle_nodes/CCParticleBatchNode.js index 431796d110..947e7ca78c 100644 --- a/cocos2d/particle_nodes/CCParticleBatchNode.js +++ b/cocos2d/particle_nodes/CCParticleBatchNode.js @@ -45,7 +45,7 @@ cc.PARTICLE_DEFAULT_CAPACITY = 500; * If the cc.ParticleSystems are not added to a cc.ParticleBatchNode then an OpenGL ES draw call will be needed for each one, which is less efficient.
* * Limitations:
- * - At the moment only cc.ParticleSystemQuad is supported
+ * - At the moment only cc.ParticleSystem is supported
* - All systems need to be drawn with the same parameters, blend function, aliasing, texture
* * Most efficient usage
@@ -62,7 +62,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ _textureAtlas:null, ctor:function () { - this._super(); + cc.Node.prototype.ctor.call(this); this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST}; }, @@ -108,13 +108,13 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ /** * Add a child into the cc.ParticleBatchNode - * @param {cc.ParticleSystemQuad} child + * @param {cc.ParticleSystem} child * @param {Number} zOrder * @param {Number} tag */ addChild:function (child, zOrder, tag) { cc.Assert(child != null, "Argument must be non-NULL"); - cc.Assert(child instanceof cc.ParticleSystem, "cc.ParticleBatchNode only supports cc.ParticleSystemQuads as children"); + cc.Assert(child instanceof cc.ParticleSystem, "cc.ParticleBatchNode only supports cc.ParticleSystem as children"); zOrder = (zOrder == null) ? child.getZOrder() : zOrder; tag = (tag == null) ? child.getTag() : tag; @@ -151,20 +151,21 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ */ insertChild:function (pSystem, index) { var totalParticles = pSystem.getTotalParticles(); - var totalQuads = this._textureAtlas.getTotalQuads(); + var locTextureAtlas = this._textureAtlas; + var totalQuads = locTextureAtlas.getTotalQuads(); pSystem.setAtlasIndex(index); - if (totalQuads + totalParticles > this._textureAtlas.getCapacity()) { + if (totalQuads + totalParticles > locTextureAtlas.getCapacity()) { this._increaseAtlasCapacityTo(totalQuads + totalParticles); // after a realloc empty quads of textureAtlas can be filled with gibberish (realloc doesn't perform calloc), insert empty quads to prevent it - this._textureAtlas.fillWithEmptyQuadsFromIndex(this._textureAtlas.getCapacity() - totalParticles, totalParticles); + locTextureAtlas.fillWithEmptyQuadsFromIndex(locTextureAtlas.getCapacity() - totalParticles, totalParticles); } // make room for quads, not necessary for last child if (pSystem.getAtlasIndex() + totalParticles != totalQuads) - this._textureAtlas.moveQuadsFromIndex(index, index + totalParticles); + locTextureAtlas.moveQuadsFromIndex(index, index + totalParticles); // increase totalParticles here for new particles, update method of particlesystem will fill the quads - this._textureAtlas.increaseTotalQuadsWith(totalParticles); + locTextureAtlas.increaseTotalQuadsWith(totalParticles); this._updateAllAtlasIndexes(); }, @@ -177,16 +178,17 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ if (child == null) return; - cc.Assert(child instanceof cc.ParticleSystem, "cc.ParticleBatchNode only supports cc.ParticleSystemQuads as children"); + cc.Assert(child instanceof cc.ParticleSystem, "cc.ParticleBatchNode only supports cc.ParticleSystem as children"); cc.Assert(this._children.indexOf(child) > -1, "cc.ParticleBatchNode doesn't contain the sprite. Can't remove it"); - this._super(child, cleanup); + cc.Node.prototype.removeChild.call(this, child, cleanup); + var locTextureAtlas = this._textureAtlas; // remove child helper - this._textureAtlas.removeQuadsAtIndex(child.getAtlasIndex(), child.getTotalParticles()); + locTextureAtlas.removeQuadsAtIndex(child.getAtlasIndex(), child.getTotalParticles()); // after memmove of data, empty the quads at the end of array - this._textureAtlas.fillWithEmptyQuadsFromIndex(this._textureAtlas.getTotalQuads(), child.getTotalParticles()); + locTextureAtlas.fillWithEmptyQuadsFromIndex(locTextureAtlas.getTotalQuads(), child.getTotalParticles()); // paticle could be reused for self rendering child.setBatchNode(null); @@ -224,8 +226,9 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ // Find new AtlasIndex var newAtlasIndex = 0; - for (var i = 0; i < this._children.length; i++) { - var pNode = this._children[i]; + var locChildren = this._children; + for (var i = 0; i < locChildren.length; i++) { + var pNode = locChildren[i]; if (pNode == child) { newAtlasIndex = child.getAtlasIndex(); break; @@ -253,10 +256,11 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ * @param {Boolean} doCleanup */ removeAllChildren:function (doCleanup) { - for (var i = 0; i < this._children.length; i++) { - this._children[i].setBatchNode(null); + var locChildren = this._children; + for (var i = 0; i < locChildren.length; i++) { + locChildren[i].setBatchNode(null); } - this._super(doCleanup); + cc.Node.prototype.removeAllChildren.call(this, doCleanup); this._textureAtlas.removeAllQuads(); }, @@ -306,9 +310,10 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ this._textureAtlas.setTexture(texture); // If the new texture has No premultiplied alpha, AND the blendFunc hasn't been changed, then update it - if (texture && !texture.hasPremultipliedAlpha() && ( this._blendFunc.src == gl.BLEND_SRC && this._blendFunc.dst == gl.BLEND_DST )) { - this._blendFunc.src = gl.SRC_ALPHA; - this._blendFunc.dst = gl.ONE_MINUS_SRC_ALPHA; + var locBlendFunc = this._blendFunc; + if (texture && !texture.hasPremultipliedAlpha() && ( locBlendFunc.src == gl.BLEND_SRC && locBlendFunc.dst == gl.BLEND_DST )) { + locBlendFunc.src = gl.SRC_ALPHA; + locBlendFunc.dst = gl.ONE_MINUS_SRC_ALPHA; } }, @@ -335,10 +340,8 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ // override visit. // Don't call visit on it's children visit:function (ctx) { - if (cc.renderContextType === cc.CANVAS) { - this._super(ctx); + if (cc.renderContextType === cc.CANVAS) return; - } // CAREFUL: // This visit is almost identical to cc.Node#visit @@ -367,8 +370,9 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ _updateAllAtlasIndexes:function () { var index = 0; - for (var i = 0; i < this._children[0].length; i++) { - var child = this._children[i]; + var locChildren = this._children; + for (var i = 0; i < locChildren.length; i++) { + var child = locChildren[i]; child.setAtlasIndex(index); index += child.getTotalParticles(); } @@ -386,9 +390,10 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ }, _searchNewPositionInChildrenForZ:function (z) { - var count = this._children.length; + var locChildren = this._children; + var count = locChildren.length; for (var i = 0; i < count; i++) { - if (this._children[i].getZOrder() > z) + if (locChildren[i].getZOrder() > z) return i; } return count; @@ -401,10 +406,10 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ var newIndex = 0; var oldIndex = 0; - var minusOne = 0; - var count = this._children.length; + var minusOne = 0, locChildren = this._children; + var count = locChildren.length; for (var i = 0; i < count; i++) { - var pNode = this._children[i]; + var pNode = locChildren[i]; // new index if (pNode.getZOrder() > z && !foundNewIdx) { newIndex = i; diff --git a/cocos2d/particle_nodes/CCParticleExamples.js b/cocos2d/particle_nodes/CCParticleExamples.js index 4d33780e8e..8d7f977141 100644 --- a/cocos2d/particle_nodes/CCParticleExamples.js +++ b/cocos2d/particle_nodes/CCParticleExamples.js @@ -27,12 +27,12 @@ /** * A fire particle system * @class - * @extends cc.ParticleSystemQuad + * @extends cc.ParticleSystem * * @example * var emitter = cc.ParticleFire.create(); */ -cc.ParticleFire = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleFire# */{ +cc.ParticleFire = cc.ParticleSystem.extend(/** @lends cc.ParticleFire# */{ /** * initialize a fire particle system * @return {Boolean} @@ -47,7 +47,7 @@ cc.ParticleFire = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleFire# */{ * @return {Boolean} */ initWithTotalParticles:function (numberOfParticles) { - if (cc.ParticleSystemQuad.prototype.initWithTotalParticles.call(this, numberOfParticles)) { + if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) { // duration this._duration = cc.PARTICLE_DURATION_INFINITY; @@ -71,7 +71,7 @@ cc.ParticleFire = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleFire# */{ // emitter position var winSize = cc.Director.getInstance().getWinSize(); - this.setPosition(cc.p(winSize.width / 2, 60)); + this.setPosition(winSize.width / 2, 60); this._posVar = cc.p(40, 20); // life of particles @@ -131,12 +131,12 @@ cc.ParticleFire.create = function () { /** * A fireworks particle system * @class - * @extends cc.ParticleSystemQuad + * @extends cc.ParticleSystem * * @example * var emitter = cc.ParticleFireworks.create(); */ -cc.ParticleFireworks = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleFireworks# */{ +cc.ParticleFireworks = cc.ParticleSystem.extend(/** @lends cc.ParticleFireworks# */{ /** * initialize a fireworks particle system * @return {Boolean} @@ -151,7 +151,7 @@ cc.ParticleFireworks = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleFirewo * @return {Boolean} */ initWithTotalParticles:function (numberOfParticles) { - if (cc.ParticleSystemQuad.prototype.initWithTotalParticles.call(this, numberOfParticles)) { + if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) { // duration this._duration = cc.PARTICLE_DURATION_INFINITY; @@ -171,7 +171,7 @@ cc.ParticleFireworks = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleFirewo // emitter position var winSize = cc.Director.getInstance().getWinSize(); - this.setPosition(cc.p(winSize.width / 2, winSize.height / 2)); + this.setPosition(winSize.width / 2, winSize.height / 2); // angle this._angle = 90; @@ -233,12 +233,12 @@ cc.ParticleFireworks.create = function () { /** * A sun particle system * @class - * @extends cc.ParticleSystemQuad + * @extends cc.ParticleSystem * * @example * var emitter = cc.ParticleSun.create(); */ -cc.ParticleSun = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleSun# */{ +cc.ParticleSun = cc.ParticleSystem.extend(/** @lends cc.ParticleSun# */{ /** * initialize a sun particle system * @return {Boolean} @@ -253,7 +253,7 @@ cc.ParticleSun = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleSun# */{ * @return {Boolean} */ initWithTotalParticles:function (numberOfParticles) { - if (cc.ParticleSystemQuad.prototype.initWithTotalParticles.call(this, numberOfParticles)) { + if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) { // additive this.setBlendAdditive(true); @@ -280,7 +280,7 @@ cc.ParticleSun = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleSun# */{ // emitter position var winSize = cc.Director.getInstance().getWinSize(); - this.setPosition(cc.p(winSize.width / 2, winSize.height / 2)); + this.setPosition(winSize.width / 2, winSize.height / 2); this.setPosVar(cc.PointZero()); // life of particles @@ -338,12 +338,12 @@ cc.ParticleSun.create = function () { /** * A galaxy particle system * @class - * @extends cc.ParticleSystemQuad + * @extends cc.ParticleSystem * * @example * var emitter = cc.ParticleGalaxy.create(); */ -cc.ParticleGalaxy = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleGalaxy# */{ +cc.ParticleGalaxy = cc.ParticleSystem.extend(/** @lends cc.ParticleGalaxy# */{ /** * initialize a galaxy particle system * @return {Boolean} @@ -359,7 +359,7 @@ cc.ParticleGalaxy = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleGalaxy# * * @return {Boolean} */ initWithTotalParticles:function (numberOfParticles) { - if (cc.ParticleSystemQuad.prototype.initWithTotalParticles.call(this, numberOfParticles)) { + if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) { // duration this._duration = cc.PARTICLE_DURATION_INFINITY; @@ -387,7 +387,7 @@ cc.ParticleGalaxy = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleGalaxy# * // emitter position var winSize = cc.Director.getInstance().getWinSize(); - this.setPosition(cc.p(winSize.width / 2, winSize.height / 2)); + this.setPosition(winSize.width / 2, winSize.height / 2); this._posVar = cc.PointZero(); // life of particles @@ -445,12 +445,12 @@ cc.ParticleGalaxy.create = function () { /** * A flower particle system * @class - * @extends cc.ParticleSystemQuad + * @extends cc.ParticleSystem * * @example * var emitter = cc.ParticleFlower.create(); */ -cc.ParticleFlower = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleFlower# */{ +cc.ParticleFlower = cc.ParticleSystem.extend(/** @lends cc.ParticleFlower# */{ /** * initialize a flower particle system * @return {Boolean} @@ -465,7 +465,7 @@ cc.ParticleFlower = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleFlower# * * @return {Boolean} */ initWithTotalParticles:function (numberOfParticles) { - if (cc.ParticleSystemQuad.prototype.initWithTotalParticles.call(this, numberOfParticles)) { + if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) { // duration this._duration = cc.PARTICLE_DURATION_INFINITY; @@ -493,7 +493,7 @@ cc.ParticleFlower = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleFlower# * // emitter position var winSize = cc.Director.getInstance().getWinSize(); - this.setPosition(cc.p(winSize.width / 2, winSize.height / 2)); + this.setPosition(winSize.width / 2, winSize.height / 2); this._posVar = cc.PointZero(); // life of particles @@ -553,12 +553,12 @@ cc.ParticleFlower.create = function () { /** * A meteor particle system * @class - * @extends cc.ParticleSystemQuad + * @extends cc.ParticleSystem * * @example * var emitter = cc.ParticleMeteor.create(); */ -cc.ParticleMeteor = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleMeteor# */{ +cc.ParticleMeteor = cc.ParticleSystem.extend(/** @lends cc.ParticleMeteor# */{ /** * initialize a meteor particle system * @return {Boolean} @@ -573,7 +573,7 @@ cc.ParticleMeteor = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleMeteor# * * @return {Boolean} */ initWithTotalParticles:function (numberOfParticles) { - if (cc.ParticleSystemQuad.prototype.initWithTotalParticles.call(this, numberOfParticles)) { + if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) { // duration this._duration = cc.PARTICLE_DURATION_INFINITY; @@ -601,7 +601,7 @@ cc.ParticleMeteor = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleMeteor# * // emitter position var winSize = cc.Director.getInstance().getWinSize(); - this.setPosition(cc.p(winSize.width / 2, winSize.height / 2)); + this.setPosition(winSize.width / 2, winSize.height / 2); this._posVar = cc.PointZero(); // life of particles @@ -660,12 +660,12 @@ cc.ParticleMeteor.create = function () { /** * A spiral particle system * @class - * @extends cc.ParticleSystemQuad + * @extends cc.ParticleSystem * * @example * var emitter = cc.ParticleSpiral.create(); */ -cc.ParticleSpiral = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleSpiral# */{ +cc.ParticleSpiral = cc.ParticleSystem.extend(/** @lends cc.ParticleSpiral# */{ /** * initialize a spiral particle system * @return {Boolean} @@ -680,7 +680,7 @@ cc.ParticleSpiral = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleSpiral# * * @return {Boolean} */ initWithTotalParticles:function (numberOfParticles) { - if (cc.ParticleSystemQuad.prototype.initWithTotalParticles.call(this, numberOfParticles)) { + if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) { // duration this._duration = cc.PARTICLE_DURATION_INFINITY; @@ -708,7 +708,7 @@ cc.ParticleSpiral = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleSpiral# * // emitter position var winSize = cc.Director.getInstance().getWinSize(); - this.setPosition(cc.p(winSize.width / 2, winSize.height / 2)); + this.setPosition(winSize.width / 2, winSize.height / 2); this._posVar = cc.PointZero(); // life of particles @@ -767,12 +767,12 @@ cc.ParticleSpiral.create = function () { /** * An explosion particle system * @class - * @extends cc.ParticleSystemQuad + * @extends cc.ParticleSystem * * @example * var emitter = cc.ParticleExplosion.create(); */ -cc.ParticleExplosion = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleExplosion# */{ +cc.ParticleExplosion = cc.ParticleSystem.extend(/** @lends cc.ParticleExplosion# */{ /** * initialize an explosion particle system * @return {Boolean} @@ -788,7 +788,7 @@ cc.ParticleExplosion = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleExplos * @return {Boolean} */ initWithTotalParticles:function (numberOfParticles) { - if (cc.ParticleSystemQuad.prototype.initWithTotalParticles.call(this, numberOfParticles)) { + if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) { // duration this._duration = 0.1; @@ -815,7 +815,7 @@ cc.ParticleExplosion = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleExplos // emitter position var winSize = cc.Director.getInstance().getWinSize(); - this.setPosition(cc.p(winSize.width / 2, winSize.height / 2)); + this.setPosition(winSize.width / 2, winSize.height / 2); this._posVar = cc.PointZero(); // life of particles @@ -874,12 +874,12 @@ cc.ParticleExplosion.create = function () { /** * A smoke particle system * @class - * @extends cc.ParticleSystemQuad + * @extends cc.ParticleSystem * * @example * var emitter = cc.ParticleSmoke.create(); */ -cc.ParticleSmoke = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleSmoke# */{ +cc.ParticleSmoke = cc.ParticleSystem.extend(/** @lends cc.ParticleSmoke# */{ /** * initialize a smoke particle system * @return {Boolean} @@ -895,7 +895,7 @@ cc.ParticleSmoke = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleSmoke# */{ * @return {Boolean} */ initWithTotalParticles:function (numberOfParticles) { - if (cc.ParticleSystemQuad.prototype.initWithTotalParticles.call(this, numberOfParticles)) { + if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) { // duration this._duration = cc.PARTICLE_DURATION_INFINITY; @@ -919,7 +919,7 @@ cc.ParticleSmoke = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleSmoke# */{ // emitter position var winSize = cc.Director.getInstance().getWinSize(); - this.setPosition(cc.p(winSize.width / 2, 0)); + this.setPosition(winSize.width / 2, 0); this._posVar = cc.p(20, 0); // life of particles @@ -978,12 +978,12 @@ cc.ParticleSmoke.create = function () { /** * A snow particle system * @class - * @extends cc.ParticleSystemQuad + * @extends cc.ParticleSystem * * @example * var emitter = cc.ParticleSnow.create(); */ -cc.ParticleSnow = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleSnow# */{ +cc.ParticleSnow = cc.ParticleSystem.extend(/** @lends cc.ParticleSnow# */{ /** * initialize a snow particle system * @return {Boolean} @@ -998,7 +998,7 @@ cc.ParticleSnow = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleSnow# */{ * @return {Boolean} */ initWithTotalParticles:function (numberOfParticles) { - if (cc.ParticleSystemQuad.prototype.initWithTotalParticles.call(this, numberOfParticles)) { + if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) { // duration this._duration = cc.PARTICLE_DURATION_INFINITY; @@ -1022,7 +1022,7 @@ cc.ParticleSnow = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleSnow# */{ // emitter position var winSize = cc.Director.getInstance().getWinSize(); - this.setPosition(cc.p(winSize.width / 2, winSize.height + 10)); + this.setPosition(winSize.width / 2, winSize.height + 10); this._posVar = cc.p(winSize.width / 2, 0); // angle @@ -1086,12 +1086,12 @@ cc.ParticleSnow.create = function () { /** * A rain particle system * @class - * @extends cc.ParticleSystemQuad + * @extends cc.ParticleSystem * * @example * var emitter = cc.ParticleRain.create(); */ -cc.ParticleRain = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleRain# */{ +cc.ParticleRain = cc.ParticleSystem.extend(/** @lends cc.ParticleRain# */{ /** * initialize a rain particle system * @return {Boolean} @@ -1106,7 +1106,7 @@ cc.ParticleRain = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleRain# */{ * @return {Boolean} */ initWithTotalParticles:function (numberOfParticles) { - if (cc.ParticleSystemQuad.prototype.initWithTotalParticles.call(this, numberOfParticles)) { + if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) { // duration this._duration = cc.PARTICLE_DURATION_INFINITY; @@ -1134,7 +1134,7 @@ cc.ParticleRain = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleRain# */{ // emitter position var winSize = cc.Director.getInstance().getWinSize(); - this.setPosition(cc.p(winSize.width / 2, winSize.height)); + this.setPosition(winSize.width / 2, winSize.height); this._posVar = cc.p(winSize.width / 2, 0); // life of particles diff --git a/cocos2d/particle_nodes/CCParticleSystem.js b/cocos2d/particle_nodes/CCParticleSystem.js index 1d33a1740e..a68c370bd5 100644 --- a/cocos2d/particle_nodes/CCParticleSystem.js +++ b/cocos2d/particle_nodes/CCParticleSystem.js @@ -232,7 +232,7 @@ cc.Particle.TemporaryPoints = [ * 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d,
* cocos2d uses a another approach, but the results are almost identical.
* cocos2d supports all the variables used by Particle Designer plus a bit more:
- * - spinning particles (supported when using CCParticleSystemQuad)
+ * - spinning particles (supported when using ParticleSystem)
* - tangential acceleration (Gravity mode)
* - radial acceleration (Gravity mode)
* - radius direction (Radius mode) (Particle Designer supports outwards to inwards direction only)
@@ -288,8 +288,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ _isActive: false, _particleCount: 0, _duration: 0, - _sourcePosition: cc.PointZero(), - _posVar: cc.PointZero(), + _sourcePosition: null, + _posVar: null, _life: 0, _lifeVar: 0, _angle: 0, @@ -298,10 +298,10 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ _startSizeVar: 0, _endSize: 0, _endSizeVar: 0, - _startColor: new cc.Color4F(0, 0, 0, 1), - _startColorVar: new cc.Color4F(0, 0, 0, 1), - _endColor: new cc.Color4F(0, 0, 0, 1), - _endColorVar: new cc.Color4F(0, 0, 0, 1), + _startColor: null, + _startColorVar: null, + _endColor: null, + _endColorVar: null, _startSpin: 0, _startSpinVar: 0, _endSpin: 0, @@ -315,6 +315,19 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ _isAutoRemoveOnFinish: false, _emitterMode: 0, + // quads to be rendered + _quads:null, + // indices + _indices:null, + + //_VAOname:0, + //0: vertex 1: indices + _buffersVBO:null, + _pointRect:null, + + _textureLoaded: null, + _quadsArrayBuffer:null, + /** * Constructor * @override @@ -370,6 +383,110 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ this._opacityModifyRGB = false; this._positionType = cc.PARTICLE_TYPE_FREE; this._isAutoRemoveOnFinish = false; + + this._buffersVBO = [0, 0]; + this._quads = []; + this._indices = []; + this._pointRect = cc.RectZero(); + this._textureLoaded = true; + + if (cc.renderContextType === cc.WEBGL) { + this._quadsArrayBuffer = null; + } + }, + + /** + * initializes the indices for the vertices + */ + initIndices:function () { + var locIndices = this._indices; + for (var i = 0, len = this._totalParticles; i < len; ++i) { + var i6 = i * 6; + var i4 = i * 4; + locIndices[i6 + 0] = i4 + 0; + locIndices[i6 + 1] = i4 + 1; + locIndices[i6 + 2] = i4 + 2; + + locIndices[i6 + 5] = i4 + 1; + locIndices[i6 + 4] = i4 + 2; + locIndices[i6 + 3] = i4 + 3; + } + }, + + /** + *

initializes the texture with a rectangle measured Points
+ * pointRect should be in Texture coordinates, not pixel coordinates + *

+ * @param {cc.Rect} pointRect + */ + initTexCoordsWithRect:function (pointRect) { + var scaleFactor = cc.CONTENT_SCALE_FACTOR(); + // convert to pixels coords + var rect = cc.rect( + pointRect.x * scaleFactor, + pointRect.y * scaleFactor, + pointRect.width * scaleFactor, + pointRect.height * scaleFactor); + + var wide = pointRect.width; + var high = pointRect.height; + + if (this._texture) { + wide = this._texture.getPixelsWide(); + high = this._texture.getPixelsHigh(); + } + + if(cc.renderContextType === cc.CANVAS) + return; + + var left, bottom, right, top; + if (cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL) { + left = (rect.x * 2 + 1) / (wide * 2); + bottom = (rect.y * 2 + 1) / (high * 2); + right = left + (rect.width * 2 - 2) / (wide * 2); + top = bottom + (rect.height * 2 - 2) / (high * 2); + } else { + left = rect.x / wide; + bottom = rect.y / high; + right = left + rect.width / wide; + top = bottom + rect.height / high; + } + + // Important. Texture in cocos2d are inverted, so the Y component should be inverted + var temp = top; + top = bottom; + bottom = temp; + + var quads; + var start = 0, end = 0; + if (this._batchNode) { + quads = this._batchNode.getTextureAtlas().getQuads(); + start = this._atlasIndex; + end = this._atlasIndex + this._totalParticles; + } else { + quads = this._quads; + start = 0; + end = this._totalParticles; + } + + for (var i = start; i < end; i++) { + if (!quads[i]) + quads[i] = cc.V3F_C4B_T2F_QuadZero(); + + // bottom-left vertex: + var selQuad = quads[i]; + selQuad.bl.texCoords.u = left; + selQuad.bl.texCoords.v = bottom; + // bottom-right vertex: + selQuad.br.texCoords.u = right; + selQuad.br.texCoords.v = bottom; + // top-left vertex: + selQuad.tl.texCoords.u = left; + selQuad.tl.texCoords.v = top; + // top-right vertex: + selQuad.tr.texCoords.u = right; + selQuad.tr.texCoords.v = top; + } }, /** @@ -386,11 +503,35 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ */ setBatchNode:function (batchNode) { if (this._batchNode != batchNode) { + var oldBatch = this._batchNode; + this._batchNode = batchNode; //weak reference if (batchNode) { + var locParticles = this._particles; for (var i = 0; i < this._totalParticles; i++) - this._particles[i].atlasIndex = i; + locParticles[i].atlasIndex = i; + } + + // NEW: is self render ? + if (!batchNode) { + this._allocMemory(); + this.initIndices(); + this.setTexture(oldBatch.getTexture()); + //if (cc.TEXTURE_ATLAS_USE_VAO) + // this._setupVBOandVAO(); + //else + this._setupVBO(); + } else if (!oldBatch) { + // OLD: was it self render cleanup ? + // copy current state to batch + this._batchNode.getTextureAtlas()._copyQuadsToTextureAtlas(this._quads, this._atlasIndex); + + //delete buffer + cc.renderContext.deleteBuffer(this._buffersVBO[1]); //where is re-bindBuffer code? + + //if (cc.TEXTURE_ATLAS_USE_VAO) + // glDeleteVertexArrays(1, this._VAOname); } } }, @@ -1081,11 +1222,57 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ /** * set maximum particles of the system - * @param {Number} totalParticles + * @param {Number} tp totalParticles */ - setTotalParticles:function (totalParticles) { - cc.Assert(totalParticles <= this._allocatedParticles, "Particle: resizing particle array only supported for quads"); - this._totalParticles = totalParticles; + setTotalParticles:function (tp) { + //cc.Assert(tp <= this._allocatedParticles, "Particle: resizing particle array only supported for quads"); + if (cc.renderContextType === cc.CANVAS){ + this._totalParticles = (tp < 200) ? tp : 200; + return; + } + + // If we are setting the total numer of particles to a number higher + // than what is allocated, we need to allocate new arrays + if (tp > this._allocatedParticles) { + var quadSize = cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT; + // Allocate new memory + this._indices = new Uint16Array(tp * 6); + var locQuadsArrayBuffer = new ArrayBuffer(tp * quadSize); + //TODO need fix + // Assign pointers + var locParticles = []; + var locQuads = []; + for (var j = 0; j < tp; j++) { + locParticles[j] = new cc.Particle(); + locQuads[j] = new cc.V3F_C4B_T2F_Quad(null, null, null, null, locQuadsArrayBuffer, j * quadSize); + } + this._allocatedParticles = tp; + this._totalParticles = tp; + + // Init particles + if (this._batchNode) { + for (var i = 0; i < tp; i++) + locParticles[i].atlasIndex = i; + } + + this._particles = locParticles; + this._quadsArrayBuffer = locQuadsArrayBuffer; + this._quads = locQuads; + + this.initIndices(); + //if (cc.TEXTURE_ATLAS_USE_VAO) + // this._setupVBOandVAO(); + //else + this._setupVBO(); + + //set the texture coord + if(this._texture){ + var size = this._texture.getContentSize(); + this.initTexCoordsWithRect(cc.rect(0, 0, size.width, size.height)); + } + } else + this._totalParticles = tp; + this.resetSystem(); }, /** @@ -1098,12 +1285,19 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ /** * set Texture of Particle System - * @param {cc.Texture2D | HTMLImageElement | HTMLCanvasElement} texture + * @param {cc.Texture2D } texture */ setTexture:function (texture) { - if (this._texture != texture) { - this._texture = texture; - this._updateBlendFunc(); + if(texture.isLoaded()){ + var size = texture.getContentSize(); + this.setTextureWithRect(texture, cc.rect(0, 0, size.width, size.height)); + } else { + this._textureLoaded = false; + texture.addLoadedEventListener(function(sender){ + this._textureLoaded = true; + var size = sender.getContentSize(); + this.setTextureWithRect(sender, cc.rect(0, 0, size.width, size.height)); + }, this); } }, @@ -1340,7 +1534,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ // position var x = parseFloat(locValueForKey("sourcePositionx", dictionary)); var y = parseFloat(locValueForKey("sourcePositiony", dictionary)); - this.setPosition(cc.p(x, y)); + this.setPosition(x, y); this._posVar.x = parseFloat(locValueForKey("sourcePositionVariancex", dictionary)); this._posVar.y = parseFloat(locValueForKey("sourcePositionVariancey", dictionary)); @@ -1454,10 +1648,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ cc.Assert(addTexture != null, "cc.ParticleSystem: error loading the texture"); - if (cc.renderContextType === cc.CANVAS) - this.setTexture(canvasObj); - else - this.setTexture(addTexture); + this.setTexture(addTexture); } } @@ -1519,6 +1710,20 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ // udpate after action in run! this.scheduleUpdateWithPriority(1); + if(cc.renderContextType === cc.WEBGL){ + // allocating data space + if (!this._allocMemory()) + return false; + + this.initIndices(); + //if (cc.TEXTURE_ATLAS_USE_VAO) + // this._setupVBOandVAO(); + //else + this._setupVBO(); + + this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_TEXTURECOLOR)); + } + return true; }, @@ -1681,8 +1886,9 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ resetSystem:function () { this._isActive = true; this._elapsed = 0; + var locParticles = this._particles; for (this._particleIdx = 0; this._particleIdx < this._particleCount; ++this._particleIdx) - this._particles[this._particleIdx].timeToLive = 0 ; + locParticles[this._particleIdx].timeToLive = 0 ; }, /** @@ -1699,14 +1905,129 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * @param {cc.Point} newPosition */ updateQuadWithParticle:function (particle, newPosition) { - // should be overriden + var quad = null; + if (this._batchNode) { + var batchQuads = this._batchNode.getTextureAtlas().getQuads(); + quad = batchQuads[this._atlasIndex + particle.atlasIndex]; + this._batchNode.getTextureAtlas()._dirty = true; + } else + quad = this._quads[this._particleIdx]; + + var r, g, b, a; + if(this._opacityModifyRGB){ + r = 0 | (particle.color.r * particle.color.a * 255); + g = 0 | (particle.color.g * particle.color.a * 255); + b = 0 | (particle.color.b * particle.color.a * 255); + a = 0 | (particle.color.a * 255); + }else{ + r = 0 | (particle.color.r * 255); + g = 0 | (particle.color.g * 255); + b = 0 | (particle.color.b * 255); + a = 0 | (particle.color.a * 255); + } + + var locColors = quad.bl.colors; + locColors.r = r; + locColors.g = g; + locColors.b = b; + locColors.a = a; + + locColors = quad.br.colors; + locColors.r = r; + locColors.g = g; + locColors.b = b; + locColors.a = a; + + locColors = quad.tl.colors; + locColors.r = r; + locColors.g = g; + locColors.b = b; + locColors.a = a; + + locColors = quad.tr.colors; + locColors.r = r; + locColors.g = g; + locColors.b = b; + locColors.a = a; + + // vertices + var size_2 = particle.size / 2; + if (particle.rotation) { + var x1 = -size_2; + var y1 = -size_2; + + var x2 = size_2; + var y2 = size_2; + var x = newPosition.x; + var y = newPosition.y; + + var rad = -cc.DEGREES_TO_RADIANS(particle.rotation); + var cr = Math.cos(rad); + var sr = Math.sin(rad); + var ax = x1 * cr - y1 * sr + x; + var ay = x1 * sr + y1 * cr + y; + var bx = x2 * cr - y1 * sr + x; + var by = x2 * sr + y1 * cr + y; + var cx = x2 * cr - y2 * sr + x; + var cy = x2 * sr + y2 * cr + y; + var dx = x1 * cr - y2 * sr + x; + var dy = x1 * sr + y2 * cr + y; + + // bottom-left + quad.bl.vertices.x = ax; + quad.bl.vertices.y = ay; + + // bottom-right vertex: + quad.br.vertices.x = bx; + quad.br.vertices.y = by; + + // top-left vertex: + quad.tl.vertices.x = dx; + quad.tl.vertices.y = dy; + + // top-right vertex: + quad.tr.vertices.x = cx; + quad.tr.vertices.y = cy; + } else { + // bottom-left vertex: + quad.bl.vertices.x = newPosition.x - size_2; + quad.bl.vertices.y = newPosition.y - size_2; + + // bottom-right vertex: + quad.br.vertices.x = newPosition.x + size_2; + quad.br.vertices.y = newPosition.y - size_2; + + // top-left vertex: + quad.tl.vertices.x = newPosition.x - size_2; + quad.tl.vertices.y = newPosition.y + size_2; + + // top-right vertex: + quad.tr.vertices.x = newPosition.x + size_2; + quad.tr.vertices.y = newPosition.y + size_2; + } }, /** * should be overridden by subclasses */ postStep:function () { - // should be overriden + if (cc.renderContextType === cc.WEBGL) { + var gl = cc.renderContext; + + gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); + gl.bufferData(gl.ARRAY_BUFFER, this._quadsArrayBuffer, gl.DYNAMIC_DRAW); + + // Option 2: Data + // glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * particleCount, quads_, GL_DYNAMIC_DRAW); + + // Option 3: Orphaning + glMapBuffer + // glBufferData(GL_ARRAY_BUFFER, sizeof(m_pQuads[0])*m_uTotalParticles, NULL, GL_STREAM_DRAW); + // void *buf = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); + // memcpy(buf, m_pQuads, sizeof(m_pQuads[0])*m_uTotalParticles); + // glUnmapBuffer(GL_ARRAY_BUFFER); + + //cc.CHECK_GL_ERROR_DEBUG(); + } }, /** @@ -1748,6 +2069,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ tpb = cc.Particle.TemporaryPoints[2], tpc = cc.Particle.TemporaryPoints[3]; + var locParticles = this._particles; while (this._particleIdx < this._particleCount) { // Reset the working particles @@ -1755,7 +2077,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ cc.pZeroIn(tpb); cc.pZeroIn(tpc); - var selParticle = this._particles[this._particleIdx]; + var selParticle = locParticles[this._particleIdx]; // life selParticle.timeToLive -= dt; @@ -1770,7 +2092,6 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ if (selParticle.pos.x || selParticle.pos.y) { cc.pIn(radial, selParticle.pos); cc.pNormalizeIn(radial); - } else { cc.pZeroIn(radial); } @@ -1863,20 +2184,19 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ // life < 0 var currentIndex = selParticle.atlasIndex; if(this._particleIdx !== this._particleCount -1){ - var deadParticle = this._particles[this._particleIdx]; - this._particles[this._particleIdx] = this._particles[this._particleCount -1]; - this._particles[this._particleCount -1] = deadParticle; + var deadParticle = locParticles[this._particleIdx]; + locParticles[this._particleIdx] = locParticles[this._particleCount -1]; + locParticles[this._particleCount -1] = deadParticle; } if (this._batchNode) { //disable the switched particle this._batchNode.disableParticle(this._atlasIndex + currentIndex); //switch indexes - this._particles[this._particleCount - 1].atlasIndex = currentIndex; + locParticles[this._particleCount - 1].atlasIndex = currentIndex; } --this._particleCount; - if (this._particleCount == 0 && this._isAutoRemoveOnFinish) { this.unscheduleUpdate(); this._parent.removeChild(this, true); @@ -1889,8 +2209,6 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ if (!this._batchNode) this.postStep(); - - //cc.PROFILER_STOP_CATEGORY(kCCProfilerCategoryParticles , "cc.ParticleSystem - update"); }, updateWithNoTime:function () { @@ -1915,38 +2233,403 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ _updateBlendFunc:function () { cc.Assert(!this._batchNode, "Can't change blending functions when the particle is being batched"); - if (this._texture) { - if (this._texture instanceof cc.Texture2D) { - var premultiplied = this._texture.hasPremultipliedAlpha(); - this._opacityModifyRGB = false; + var locTexture = this._texture; + if (locTexture && locTexture instanceof cc.Texture2D) { + this._opacityModifyRGB = false; + var locBlendFunc = this._blendFunc; + if (locBlendFunc.src == cc.BLEND_SRC && locBlendFunc.dst == cc.BLEND_DST) { + if (locTexture.hasPremultipliedAlpha()) { + this._opacityModifyRGB = true; + } else { + locBlendFunc.src = gl.SRC_ALPHA; + locBlendFunc.dst = gl.ONE_MINUS_SRC_ALPHA; + } + } + } + }, - if (this._texture && ( this._blendFunc.src == cc.BLEND_SRC && this._blendFunc.dst == cc.BLEND_DST )) { - if (premultiplied) { - this._opacityModifyRGB = true; - } else { - this._blendFunc.src = gl.SRC_ALPHA; - this._blendFunc.dst = gl.ONE_MINUS_SRC_ALPHA; + clone:function () { + var retParticle = new cc.ParticleSystem(); + + // self, not super + if (retParticle.initWithTotalParticles(this._totalParticles)) { + // angle + retParticle._angle = this._angle; + retParticle._angleVar = this._angleVar; + + // duration + retParticle._duration = this._duration; + + // blend function + retParticle._blendFunc.src = this._blendFunc.src; + retParticle._blendFunc.dst = this._blendFunc.dst; + + // color + var particleStartColor = retParticle._startColor, locStartColor = this._startColor; + particleStartColor.r = locStartColor.r; + particleStartColor.g = locStartColor.g; + particleStartColor.b = locStartColor.b; + particleStartColor.a = locStartColor.a; + + var particleStartColorVar = retParticle._startColorVar, locStartColorVar = this._startColorVar; + particleStartColorVar.r = locStartColorVar.r; + particleStartColorVar.g = locStartColorVar.g; + particleStartColorVar.b = locStartColorVar.b; + particleStartColorVar.a = locStartColorVar.a; + + var particleEndColor = retParticle._endColor, locEndColor = this._endColor; + particleEndColor.r = locEndColor.r; + particleEndColor.g = locEndColor.g; + particleEndColor.b = locEndColor.b; + particleEndColor.a = locEndColor.a; + + var particleEndColorVar = retParticle._endColorVar, locEndColorVar = this._endColorVar; + particleEndColorVar.r = locEndColorVar.r; + particleEndColorVar.g = locEndColorVar.g; + particleEndColorVar.b = locEndColorVar.b; + particleEndColorVar.a = locEndColorVar.a; + + // particle size + retParticle._startSize = this._startSize; + retParticle._startSizeVar = this._startSizeVar; + retParticle._endSize = this._endSize; + retParticle._endSizeVar = this._endSizeVar; + + // position + retParticle.setPosition(new cc.Point(this._position.x, this._position.y)); + retParticle._posVar.x = this._posVar.x; + retParticle._posVar.y = this._posVar.y; + + // Spinning + retParticle._startSpin = this._startSpin; + retParticle._startSpinVar = this._startSpinVar; + retParticle._endSpin = this._endSpin; + retParticle._endSpinVar = this._endSpinVar; + + retParticle._emitterMode = this._emitterMode; + + // Mode A: Gravity + tangential accel + radial accel + if (this._emitterMode == cc.PARTICLE_MODE_GRAVITY) { + var particleModeA = retParticle.modeA, locModeA = this.modeA; + // gravity + particleModeA.gravity.x = locModeA.gravity.x; + particleModeA.gravity.y = locModeA.gravity.y; + + // speed + particleModeA.speed = locModeA.speed; + particleModeA.speedVar = locModeA.speedVar; + + // radial acceleration + particleModeA.radialAccel = locModeA.radialAccel; + + particleModeA.radialAccelVar = locModeA.radialAccelVar; + + // tangential acceleration + particleModeA.tangentialAccel = locModeA.tangentialAccel; + + particleModeA.tangentialAccelVar = locModeA.tangentialAccelVar; + } else if (this._emitterMode == cc.PARTICLE_MODE_RADIUS) { + var particleModeB = retParticle.modeB, locModeB = this.modeB; + // or Mode B: radius movement + particleModeB.startRadius = locModeB.startRadius; + particleModeB.startRadiusVar = locModeB.startRadiusVar; + particleModeB.endRadius = locModeB.endRadius; + particleModeB.endRadiusVar = locModeB.endRadiusVar; + particleModeB.rotatePerSecond = locModeB.rotatePerSecond; + particleModeB.rotatePerSecondVar = locModeB.rotatePerSecondVar; + } + + // life span + retParticle._life = this._life; + retParticle._lifeVar = this._lifeVar; + + // emission Rate + retParticle._emissionRate = this._emissionRate; + + //don't get the internal texture if a batchNode is used + if (!this._batchNode) { + // Set a compatible default for the alpha transfer + retParticle._opacityModifyRGB = this._opacityModifyRGB; + + // texture + retParticle._texture = this._texture; + } + } + return retParticle; + }, + + /** + *

Sets a new CCSpriteFrame as particle.
+ * WARNING: this method is experimental. Use setTextureWithRect instead. + *

+ * @param {cc.SpriteFrame} spriteFrame + */ + setDisplayFrame:function (spriteFrame) { + cc.Assert(cc._rectEqualToZero(spriteFrame.getOffsetInPixels()), "QuadParticle only supports SpriteFrames with no offsets"); + + // update texture before updating texture rect + if (cc.renderContextType === cc.WEBGL) + if (!this._texture || spriteFrame.getTexture()._webTextureObj != this._texture._webTextureObj) + this.setTexture(spriteFrame.getTexture()); + }, + + /** + * Sets a new texture with a rect. The rect is in Points. + * @param {cc.Texture2D} texture + * @param {cc.Rect} rect + */ + setTextureWithRect:function (texture, rect) { + var locTexture = this._texture; + if (cc.renderContextType === cc.WEBGL) { + // Only update the texture if is different from the current one + if ((!locTexture || texture._webTextureObj != locTexture._webTextureObj) && (locTexture != texture)) { + this._texture = texture; + this._updateBlendFunc(); + } + } else { + if ((!locTexture || texture != locTexture) && (locTexture != texture)) { + this._texture = texture; + this._updateBlendFunc(); + } + } + + this._pointRect = rect; + this.initTexCoordsWithRect(rect); + }, + + /** + * draw particle + * @param {CanvasRenderingContext2D} ctx CanvasContext + * @override + */ + draw:function (ctx) { + cc.Assert(!this._batchNode, "draw should not be called when added to a particleBatchNode"); + if(!this._textureLoaded) + return; + + if (cc.renderContextType === cc.CANVAS) + this._drawForCanvas(ctx); + else + this._drawForWebGL(ctx); + + cc.g_NumberOfDraws++; + }, + + _drawForCanvas:function (ctx) { + var context = ctx || cc.renderContext; + context.save(); + if (this.isBlendAdditive()) + context.globalCompositeOperation = 'lighter'; + else + context.globalCompositeOperation = 'source-over'; + + for (var i = 0; i < this._particleCount; i++) { + var particle = this._particles[i]; + var lpx = (0 | (particle.size * 0.5)); + + if (this._drawMode == cc.PARTICLE_TEXTURE_MODE) { + + var element = this._texture.getHtmlElementObj(); + + // Delay drawing until the texture is fully loaded by the browser + if (!element.width || !element.height) + continue; + + context.save(); + context.globalAlpha = particle.color.a; + context.translate((0 | particle.drawPos.x), -(0 | particle.drawPos.y)); + + var size = Math.floor(particle.size / 4) * 4; + var w = this._pointRect.width; + var h = this._pointRect.height; + + context.scale( + Math.max((1 / w) * size, 0.000001), + Math.max((1 / h) * size, 0.000001) + ); + + + if (particle.rotation) + context.rotate(cc.DEGREES_TO_RADIANS(particle.rotation)); + + context.translate(-(0 | (w / 2)), -(0 | (h / 2))); + if (particle.isChangeColor) { + + var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(element); + if (cacheTextureForColor) { + // Create another cache for the tinted version + // This speeds up things by a fair bit + if (!cacheTextureForColor.tintCache) { + cacheTextureForColor.tintCache = document.createElement('canvas'); + cacheTextureForColor.tintCache.width = element.width; + cacheTextureForColor.tintCache.height = element.height; + } + cc.generateTintImage(element, cacheTextureForColor, particle.color, this._pointRect, cacheTextureForColor.tintCache); + element = cacheTextureForColor.tintCache; } } + + context.drawImage(element, 0, 0); + context.restore(); + + } else { + context.save(); + context.globalAlpha = particle.color.a; + + context.translate(0 | particle.drawPos.x, -(0 | particle.drawPos.y)); + + if (this._shapeType == cc.PARTICLE_STAR_SHAPE) { + if (particle.rotation) + context.rotate(cc.DEGREES_TO_RADIANS(particle.rotation)); + cc.drawingUtil.drawStar(context, lpx, particle.color); + } else + cc.drawingUtil.drawColorBall(context, lpx, particle.color); + context.restore(); } } + context.restore(); + }, + + _drawForWebGL:function (ctx) { + if(!this._texture) + return; + + var gl = ctx || cc.renderContext; + + this._shaderProgram.use(); + this._shaderProgram.setUniformForModelViewAndProjectionMatrixWithMat4(); + + cc.glBindTexture2D(this._texture); + cc.glBlendFuncForParticle(this._blendFunc.src, this._blendFunc.dst); + + //cc.Assert(this._particleIdx == this._particleCount, "Abnormal error in particle quad"); + + // + // Using VBO without VAO + // + cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSCOLORTEX); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0); // vertices + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12); // colors + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16); // tex coords + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]); + gl.drawElements(gl.TRIANGLES, this._particleIdx * 6, gl.UNSIGNED_SHORT, 0); + }, + + /** + * listen the event that coming to foreground on Android + * @param {cc.Class} obj + */ + listenBackToForeground:function (obj) { + if (cc.TEXTURE_ATLAS_USE_VAO) + this._setupVBOandVAO(); + else + this._setupVBO(); + }, + + _setupVBOandVAO:function () { + //Not support on WebGL + /*if (cc.renderContextType == cc.CANVAS) { + return; + }*/ + + //NOT SUPPORTED + /*glGenVertexArrays(1, this._VAOname); + glBindVertexArray(this._VAOname); + + var kQuadSize = sizeof(m_pQuads[0].bl); + + glGenBuffers(2, this._buffersVBO[0]); + + glBindBuffer(GL_ARRAY_BUFFER, this._buffersVBO[0]); + glBufferData(GL_ARRAY_BUFFER, sizeof(this._quads[0]) * this._totalParticles, this._quads, GL_DYNAMIC_DRAW); + + // vertices + glEnableVertexAttribArray(kCCVertexAttrib_Position); + glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, kQuadSize, offsetof(ccV3F_C4B_T2F, vertices)); + + // colors + glEnableVertexAttribArray(kCCVertexAttrib_Color); + glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, offsetof(ccV3F_C4B_T2F, colors)); + + // tex coords + glEnableVertexAttribArray(kCCVertexAttrib_TexCoords); + glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, offsetof(ccV3F_C4B_T2F, texCoords)); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(m_pIndices[0]) * m_uTotalParticles * 6, m_pIndices, GL_STATIC_DRAW); + + glBindVertexArray(0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + glBindBuffer(GL_ARRAY_BUFFER, 0); + + CHECK_GL_ERROR_DEBUG();*/ + }, + + _setupVBO:function () { + if (cc.renderContextType == cc.CANVAS) + return; + + var gl = cc.renderContext; + + //gl.deleteBuffer(this._buffersVBO[0]); + this._buffersVBO[0] = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); + gl.bufferData(gl.ARRAY_BUFFER, this._quadsArrayBuffer, gl.DYNAMIC_DRAW); + + this._buffersVBO[1] = gl.createBuffer(); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW); + + //cc.CHECK_GL_ERROR_DEBUG(); + }, + + _allocMemory:function () { + if (cc.renderContextType === cc.CANVAS) + return true; + + //cc.Assert((!this._quads && !this._indices), "Memory already allocated"); + cc.Assert(!this._batchNode, "Memory should not be allocated when not using batchNode"); + var quadSize = cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT; + var totalParticles = this._totalParticles; + var locQuads = []; + this._indices = new Uint16Array(totalParticles * 6); + var locQuadsArrayBuffer = new ArrayBuffer(quadSize * totalParticles); + + for (var i = 0; i < totalParticles; i++) + locQuads[i] = new cc.V3F_C4B_T2F_Quad(null, null, null, null, locQuadsArrayBuffer, i * quadSize); + if (!locQuads || !this._indices) { + cc.log("cocos2d: Particle system: not enough memory"); + return false; + } + this._quads = locQuads; + this._quadsArrayBuffer = locQuadsArrayBuffer; + return true; } }); /** *

return the string found by key in dict.
- * This plist files can be creted manually or with Particle Designer:
+ * This plist files can be create manually or with Particle Designer:
* http://particledesigner.71squared.com/
*

* @param {String} plistFile * @return {cc.ParticleSystem} */ cc.ParticleSystem.create = function (plistFile) { - return cc.ParticleSystemQuad.create(plistFile); - /*var particle = new cc.ParticleSystem(); - if (particle && particle.initWithFile(plistFile)) - return particle; - return null;*/ + var ret = new cc.ParticleSystem(); + if (!plistFile || typeof(plistFile) === "number") { + var ton = plistFile || 100; + ret.setDrawMode(cc.PARTICLE_TEXTURE_MODE); + ret.initWithTotalParticles(ton); + return ret; + } + + if (ret && ret.initWithFile(plistFile)) + return ret; + return null; }; /** @@ -1955,12 +2638,11 @@ cc.ParticleSystem.create = function (plistFile) { * @return {cc.ParticleSystem} */ cc.ParticleSystem.createWithTotalParticles = function (number_of_particles) { - return cc.ParticleSystemQuad.create(number_of_particles); - /*//emitter.initWithTotalParticles(number_of_particles); + //emitter.initWithTotalParticles(number_of_particles); var particle = new cc.ParticleSystem(); if (particle && particle.initWithTotalParticles(number_of_particles)) return particle; - return null;*/ + return null; }; // Different modes diff --git a/cocos2d/particle_nodes/CCParticleSystemQuad.js b/cocos2d/particle_nodes/CCParticleSystemQuad.js deleted file mode 100644 index d8b9a4f132..0000000000 --- a/cocos2d/particle_nodes/CCParticleSystemQuad.js +++ /dev/null @@ -1,823 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2012 cocos2d-x.org - Copyright (c) 2008-2010 Ricardo Quesada - Copyright (c) 2011 Zynga 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. - ****************************************************************************/ - -/** - *

- * CCParticleSystemQuad is a subclass of CCParticleSystem
- *
- * It includes all the features of ParticleSystem.
- *
- * Special features and Limitations:
- * - Particle size can be any float number.
- * - The system can be scaled
- * - The particles can be rotated
- * - It supports subrects
- * - It supports batched rendering since 1.1
- *

- * @class - * @extends cc.ParticleSystem - * @example - * //create a particle system - * this._emitter = new cc.ParticleSystemQuad(); - * this._emitter.initWithTotalParticles(150); - */ -cc.ParticleSystemQuad = cc.ParticleSystem.extend(/** @lends cc.ParticleSystemQuad# */{ - // quads to be rendered - _quads:null, - // indices - _indices:null, - - //_VAOname:0, - //0: vertex 1: indices - _buffersVBO:null, - _pointRect:null, - - /** - * Constructor - * @override - */ - ctor:function () { - cc.ParticleSystem.prototype.ctor.call(this); - this._buffersVBO = [0, 0]; - this._quads = []; - this._indices = []; - this._pointRect = cc.RectZero(); - - if (cc.renderContextType === cc.WEBGL) { - this._quadsArrayBuffer = null; - } - }, - - /** - * initialices the indices for the vertices - */ - initIndices:function () { - var locIndices = this._indices; - for (var i = 0, len = this._totalParticles; i < len; ++i) { - var i6 = i * 6; - var i4 = i * 4; - locIndices[i6 + 0] = i4 + 0; - locIndices[i6 + 1] = i4 + 1; - locIndices[i6 + 2] = i4 + 2; - - locIndices[i6 + 5] = i4 + 1; - locIndices[i6 + 4] = i4 + 2; - locIndices[i6 + 3] = i4 + 3; - } - }, - - /** - *

initilizes the texture with a rectangle measured Points
- * pointRect should be in Texture coordinates, not pixel coordinates - *

- * @param {cc.Rect} pointRect - */ - initTexCoordsWithRect:function (pointRect) { - var scaleFactor = cc.CONTENT_SCALE_FACTOR(); - // convert to pixels coords - var rect = cc.rect( - pointRect.x * scaleFactor, - pointRect.y * scaleFactor, - pointRect.width * scaleFactor, - pointRect.height * scaleFactor); - - var wide = pointRect.width; - var high = pointRect.height; - - if (this._texture) { - if ((this._texture instanceof HTMLImageElement) || (this._texture instanceof HTMLCanvasElement)) { - wide = this._texture.width; - high = this._texture.height; - } else { - wide = this._texture.getPixelsWide(); - high = this._texture.getPixelsHigh(); - } - } - - if(cc.renderContextType === cc.CANVAS) - return; - - var left, bottom, right, top; - if (cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL) { - left = (rect.x * 2 + 1) / (wide * 2); - bottom = (rect.y * 2 + 1) / (high * 2); - right = left + (rect.width * 2 - 2) / (wide * 2); - top = bottom + (rect.height * 2 - 2) / (high * 2); - } else { - left = rect.x / wide; - bottom = rect.y / high; - right = left + rect.width / wide; - top = bottom + rect.height / high; - } - - // Important. Texture in cocos2d are inverted, so the Y component should be inverted - var temp = top; - top = bottom; - bottom = temp; - - var quads; - var start = 0, end = 0; - if (this._batchNode) { - quads = this._batchNode.getTextureAtlas().getQuads(); - start = this._atlasIndex; - end = this._atlasIndex + this._totalParticles; - } else { - quads = this._quads; - start = 0; - end = this._totalParticles; - } - - for (var i = start; i < end; i++) { - if (!quads[i]) - quads[i] = cc.V3F_C4B_T2F_QuadZero(); - - // bottom-left vertex: - quads[i].bl.texCoords.u = left; - quads[i].bl.texCoords.v = bottom; - // bottom-right vertex: - quads[i].br.texCoords.u = right; - quads[i].br.texCoords.v = bottom; - // top-left vertex: - quads[i].tl.texCoords.u = left; - quads[i].tl.texCoords.v = top; - // top-right vertex: - quads[i].tr.texCoords.u = right; - quads[i].tr.texCoords.v = top; - } - }, - - clone:function () { - var retParticle = new cc.ParticleSystemQuad(); - - // self, not super - if (retParticle.initWithTotalParticles(this._totalParticles)) { - // angle - retParticle._angle = this._angle; - retParticle._angleVar = this._angleVar; - - // duration - retParticle._duration = this._duration; - - // blend function - retParticle._blendFunc.src = this._blendFunc.src; - retParticle._blendFunc.dst = this._blendFunc.dst; - - // color - var particleStartColor = retParticle._startColor, locStartColor = this._startColor; - particleStartColor.r = locStartColor.r; - particleStartColor.g = locStartColor.g; - particleStartColor.b = locStartColor.b; - particleStartColor.a = locStartColor.a; - - var particleStartColorVar = retParticle._startColorVar, locStartColorVar = this._startColorVar; - particleStartColorVar.r = locStartColorVar.r; - particleStartColorVar.g = locStartColorVar.g; - particleStartColorVar.b = locStartColorVar.b; - particleStartColorVar.a = locStartColorVar.a; - - var particleEndColor = retParticle._endColor, locEndColor = this._endColor; - particleEndColor.r = locEndColor.r; - particleEndColor.g = locEndColor.g; - particleEndColor.b = locEndColor.b; - particleEndColor.a = locEndColor.a; - - var particleEndColorVar = retParticle._endColorVar, locEndColorVar = this._endColorVar; - particleEndColorVar.r = locEndColorVar.r; - particleEndColorVar.g = locEndColorVar.g; - particleEndColorVar.b = locEndColorVar.b; - particleEndColorVar.a = locEndColorVar.a; - - // particle size - retParticle._startSize = this._startSize; - retParticle._startSizeVar = this._startSizeVar; - retParticle._endSize = this._endSize; - retParticle._endSizeVar = this._endSizeVar; - - // position - retParticle.setPosition(new cc.Point(this._position.x, this._position.y)); - retParticle._posVar.x = this._posVar.x; - retParticle._posVar.y = this._posVar.y; - - // Spinning - retParticle._startSpin = this._startSpin; - retParticle._startSpinVar = this._startSpinVar; - retParticle._endSpin = this._endSpin; - retParticle._endSpinVar = this._endSpinVar; - - retParticle._emitterMode = this._emitterMode; - - // Mode A: Gravity + tangential accel + radial accel - if (this._emitterMode == cc.PARTICLE_MODE_GRAVITY) { - var particleModeA = retParticle.modeA, locModeA = this.modeA; - // gravity - particleModeA.gravity.x = locModeA.gravity.x; - particleModeA.gravity.y = locModeA.gravity.y; - - // speed - particleModeA.speed = locModeA.speed; - particleModeA.speedVar = locModeA.speedVar; - - // radial acceleration - particleModeA.radialAccel = locModeA.radialAccel; - - particleModeA.radialAccelVar = locModeA.radialAccelVar; - - // tangential acceleration - particleModeA.tangentialAccel = locModeA.tangentialAccel; - - particleModeA.tangentialAccelVar = locModeA.tangentialAccelVar; - } else if (this._emitterMode == cc.PARTICLE_MODE_RADIUS) { - var particleModeB = retParticle.modeB, locModeB = this.modeB; - // or Mode B: radius movement - particleModeB.startRadius = locModeB.startRadius; - particleModeB.startRadiusVar = locModeB.startRadiusVar; - particleModeB.endRadius = locModeB.endRadius; - particleModeB.endRadiusVar = locModeB.endRadiusVar; - particleModeB.rotatePerSecond = locModeB.rotatePerSecond; - particleModeB.rotatePerSecondVar = locModeB.rotatePerSecondVar; - } - - // life span - retParticle._life = this._life; - retParticle._lifeVar = this._lifeVar; - - // emission Rate - retParticle._emissionRate = this._emissionRate; - - //don't get the internal texture if a batchNode is used - if (!this._batchNode) { - // Set a compatible default for the alpha transfer - retParticle._opacityModifyRGB = this._opacityModifyRGB; - - // texture - if (this._texture instanceof cc.Texture2D) - retParticle._texture = this._texture; - else - retParticle._texture = this._texture; - } - } - return retParticle; - }, - - /** - *

Sets a new CCSpriteFrame as particle.
- * WARNING: this method is experimental. Use setTexture:withRect instead. - *

- * @param {cc.SpriteFrame} spriteFrame - */ - setDisplayFrame:function (spriteFrame) { - cc.Assert(cc.pointEqualToPoint(spriteFrame.getOffsetInPixels(), cc.PointZero()), "QuadParticle only supports SpriteFrames with no offsets"); - - // update texture before updating texture rect - if (cc.renderContextType === cc.WEBGL) - if (!this._texture || spriteFrame.getTexture()._webTextureObj != this._texture._webTextureObj) - this.setTexture(spriteFrame.getTexture()); - }, - - /** - * Sets a new texture with a rect. The rect is in Points. - * @param {cc.Texture2D} texture - * @param {cc.Rect} rect - */ - setTextureWithRect:function (texture, rect) { - if (cc.renderContextType === cc.WEBGL) { - // Only update the texture if is different from the current one - if (!this._texture || texture._webTextureObj != this._texture._webTextureObj) - cc.ParticleSystem.prototype.setTexture.call(this, texture); - this._pointRect = rect; - this.initTexCoordsWithRect(rect); - } else { - if (!this._texture || texture != this._texture) - cc.ParticleSystem.prototype.setTexture.call(this, texture); - this._pointRect = rect; - this.initTexCoordsWithRect(rect); - } - }, - - // super methods - // overriding the init method - /** - * Initializes a system with a fixed number of particles - * @override - * @param {Number} numberOfParticles - * @return {Boolean} - */ - initWithTotalParticles:function (numberOfParticles) { - // base initialization - if (cc.ParticleSystem.prototype.initWithTotalParticles.call(this, numberOfParticles)) { - if (cc.renderContextType === cc.CANVAS) - return true; - - // allocating data space - if (!this._allocMemory()) - return false; - - this.initIndices(); - //if (cc.TEXTURE_ATLAS_USE_VAO) - // this._setupVBOandVAO(); - //else - this._setupVBO(); - - this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_TEXTURECOLOR)); - return true; - } - return false; - }, - - /** - * set Texture of Particle System - * @override - * @param {HTMLImageElement|HTMLCanvasElement|cc.Texture2D} texture - * @param {Boolean} isCallSuper is direct call super method - */ - setTexture:function (texture, isCallSuper) { - if (isCallSuper != null && isCallSuper === true) { - cc.ParticleSystem.prototype.setTexture.call(this, texture); - return; - } - var size = null; - if ((texture instanceof HTMLImageElement) || (texture instanceof HTMLCanvasElement)) - size = cc.size(texture.width, texture.height); - else - size = texture.getContentSize(); - - this.setTextureWithRect(texture, cc.rect(0, 0, size.width, size.height)); - }, - - /** - * update particle's quad - * @override - * @param {cc.Particle} particle - * @param {cc.Point} newPosition - */ - updateQuadWithParticle:function (particle, newPosition) { - var quad = null; - if (this._batchNode) { - var batchQuads = this._batchNode.getTextureAtlas().getQuads(); - quad = batchQuads[this._atlasIndex + particle.atlasIndex]; - this._batchNode.getTextureAtlas()._dirty = true; - - } else - quad = this._quads[this._particleIdx]; - - var r, g, b, a; - if(this._opacityModifyRGB){ - r = 0 | (particle.color.r * particle.color.a * 255); - g = 0 | (particle.color.g * particle.color.a * 255); - b = 0 | (particle.color.b * particle.color.a * 255); - a = 0 | (particle.color.a * 255); - }else{ - r = 0 | (particle.color.r * 255); - g = 0 | (particle.color.g * 255); - b = 0 | (particle.color.b * 255); - a = 0 | (particle.color.a * 255); - } - - var locColors = quad.bl.colors; - locColors.r = r; - locColors.g = g; - locColors.b = b; - locColors.a = a; - - locColors = quad.br.colors; - locColors.r = r; - locColors.g = g; - locColors.b = b; - locColors.a = a; - - locColors = quad.tl.colors; - locColors.r = r; - locColors.g = g; - locColors.b = b; - locColors.a = a; - - locColors = quad.tr.colors; - locColors.r = r; - locColors.g = g; - locColors.b = b; - locColors.a = a; - - // vertices - var size_2 = particle.size / 2; - if (particle.rotation) { - var x1 = -size_2; - var y1 = -size_2; - - var x2 = size_2; - var y2 = size_2; - var x = newPosition.x; - var y = newPosition.y; - - var rad = -cc.DEGREES_TO_RADIANS(particle.rotation); - var cr = Math.cos(rad); - var sr = Math.sin(rad); - var ax = x1 * cr - y1 * sr + x; - var ay = x1 * sr + y1 * cr + y; - var bx = x2 * cr - y1 * sr + x; - var by = x2 * sr + y1 * cr + y; - var cx = x2 * cr - y2 * sr + x; - var cy = x2 * sr + y2 * cr + y; - var dx = x1 * cr - y2 * sr + x; - var dy = x1 * sr + y2 * cr + y; - - // bottom-left - quad.bl.vertices.x = ax; - quad.bl.vertices.y = ay; - - // bottom-right vertex: - quad.br.vertices.x = bx; - quad.br.vertices.y = by; - - // top-left vertex: - quad.tl.vertices.x = dx; - quad.tl.vertices.y = dy; - - // top-right vertex: - quad.tr.vertices.x = cx; - quad.tr.vertices.y = cy; - } else { - // bottom-left vertex: - quad.bl.vertices.x = newPosition.x - size_2; - quad.bl.vertices.y = newPosition.y - size_2; - - // bottom-right vertex: - quad.br.vertices.x = newPosition.x + size_2; - quad.br.vertices.y = newPosition.y - size_2; - - // top-left vertex: - quad.tl.vertices.x = newPosition.x - size_2; - quad.tl.vertices.y = newPosition.y + size_2; - - // top-right vertex: - quad.tr.vertices.x = newPosition.x + size_2; - quad.tr.vertices.y = newPosition.y + size_2; - } - }, - - /** - * override cc.ParticleSystem - * @override - */ - postStep:function () { - if (cc.renderContextType === cc.WEBGL) { - var gl = cc.renderContext; - - gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); - gl.bufferData(gl.ARRAY_BUFFER, this._quadsArrayBuffer, gl.DYNAMIC_DRAW); - - // Option 2: Data - // glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * particleCount, quads_, GL_DYNAMIC_DRAW); - - // Option 3: Orphaning + glMapBuffer - // glBufferData(GL_ARRAY_BUFFER, sizeof(m_pQuads[0])*m_uTotalParticles, NULL, GL_STREAM_DRAW); - // void *buf = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); - // memcpy(buf, m_pQuads, sizeof(m_pQuads[0])*m_uTotalParticles); - // glUnmapBuffer(GL_ARRAY_BUFFER); - - //cc.CHECK_GL_ERROR_DEBUG(); - } - }, - - /** - * draw particle - * @param {CanvasContext} ctx CanvasContext - * @override - */ - draw:function (ctx) { - cc.Assert(!this._batchNode, "draw should not be called when added to a particleBatchNode"); - - if (cc.renderContextType === cc.CANVAS) - this._drawForCanvas(ctx); - else - this._drawForWebGL(ctx); - - cc.g_NumberOfDraws++; - }, - - _drawForCanvas:function (ctx) { - var context = ctx || cc.renderContext; - context.save(); - if (this.isBlendAdditive()) - context.globalCompositeOperation = 'lighter'; - else - context.globalCompositeOperation = 'source-over'; - - for (var i = 0; i < this._particleCount; i++) { - var particle = this._particles[i]; - var lpx = (0 | (particle.size * 0.5)); - - if (this._drawMode == cc.PARTICLE_TEXTURE_MODE) { - - var drawTexture = this.getTexture(); - - // Delay drawing until the texture is fully loaded by the browser - if (!drawTexture.width || !drawTexture.height) - continue; - - context.save(); - context.globalAlpha = particle.color.a; - context.translate((0 | particle.drawPos.x), -(0 | particle.drawPos.y)); - - var size = Math.floor(particle.size / 4) * 4; - var w = this._pointRect.width; - var h = this._pointRect.height; - - context.scale( - Math.max((1 / w) * size, 0.000001), - Math.max((1 / h) * size, 0.000001) - ); - - - if (particle.rotation) - context.rotate(cc.DEGREES_TO_RADIANS(particle.rotation)); - - context.translate(-(0 | (w / 2)), -(0 | (h / 2))); - if (particle.isChangeColor) { - - var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(drawTexture); - if (cacheTextureForColor) { - // Create another cache for the tinted version - // This speeds up things by a fair bit - if (!cacheTextureForColor.tintCache) { - cacheTextureForColor.tintCache = document.createElement('canvas'); - cacheTextureForColor.tintCache.width = drawTexture.width; - cacheTextureForColor.tintCache.height = drawTexture.height; - } - cc.generateTintImage(drawTexture, cacheTextureForColor, particle.color, this._pointRect, cacheTextureForColor.tintCache); - drawTexture = cacheTextureForColor.tintCache; - } - } - - context.drawImage(drawTexture, 0, 0); - context.restore(); - - } else { - context.save(); - context.globalAlpha = particle.color.a; - - context.translate(0 | particle.drawPos.x, -(0 | particle.drawPos.y)); - - if (this._shapeType == cc.PARTICLE_STAR_SHAPE) { - if (particle.rotation) - context.rotate(cc.DEGREES_TO_RADIANS(particle.rotation)); - cc.drawingUtil.drawStar(context, lpx, particle.color); - } else - cc.drawingUtil.drawColorBall(context, lpx, particle.color); - context.restore(); - } - } - context.restore(); - }, - - _drawForWebGL:function (ctx) { - if(!this._texture) - return; - - var gl = ctx || cc.renderContext; - - this._shaderProgram.use(); - this._shaderProgram.setUniformForModelViewAndProjectionMatrixWithMat4(); - - cc.glBindTexture2D(this._texture); - cc.glBlendFuncForParticle(this._blendFunc.src, this._blendFunc.dst); - - //cc.Assert(this._particleIdx == this._particleCount, "Abnormal error in particle quad"); - - // - // Using VBO without VAO - // - cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSCOLORTEX); - - gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); - gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0); // vertices - gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12); // colors - gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16); // tex coords - - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]); - gl.drawElements(gl.TRIANGLES, this._particleIdx * 6, gl.UNSIGNED_SHORT, 0); - }, - - setBatchNode:function (batchNode) { - if (this._batchNode != batchNode) { - var oldBatch = this._batchNode; - cc.ParticleSystem.prototype.setBatchNode.call(this, batchNode); - - // NEW: is self render ? - if (!batchNode) { - this._allocMemory(); - this.initIndices(); - this.setTexture(oldBatch.getTexture()); - //if (cc.TEXTURE_ATLAS_USE_VAO) - // this._setupVBOandVAO(); - //else - this._setupVBO(); - } else if (!oldBatch) { - // OLD: was it self render cleanup ? - // copy current state to batch - this._batchNode.getTextureAtlas()._copyQuadsToTextureAtlas(this._quads, this._atlasIndex); - - //delete buffer - cc.renderContext.deleteBuffer(this._buffersVBO[1]); //where is re-bindBuffer code? - - //if (cc.TEXTURE_ATLAS_USE_VAO) - // glDeleteVertexArrays(1, this._VAOname); - } - } - }, - - setTotalParticles:function (tp) { - if (cc.renderContextType === cc.CANVAS){ - this._totalParticles = (tp < 200) ? tp : 200; - return; - } - - // If we are setting the total numer of particles to a number higher - // than what is allocated, we need to allocate new arrays - if (tp > this._allocatedParticles) { - var quadSize = cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT; - // Allocate new memory - this._indices = new Uint16Array(tp * 6); - var locQuadsArrayBuffer = new ArrayBuffer(tp * quadSize); - //TODO need fix - // Assign pointers - var locParticles = []; - var locQuads = []; - for (var j = 0; j < tp; j++) { - locParticles[j] = new cc.Particle(); - locQuads[j] = new cc.V3F_C4B_T2F_Quad(null, null, null, null, locQuadsArrayBuffer, j * quadSize); - } - this._allocatedParticles = tp; - this._totalParticles = tp; - - // Init particles - if (this._batchNode) { - for (var i = 0; i < tp; i++) - locParticles[i].atlasIndex = i; - } - - this._particles = locParticles; - this._quadsArrayBuffer = locQuadsArrayBuffer; - this._quads = locQuads; - - this.initIndices(); - //if (cc.TEXTURE_ATLAS_USE_VAO) - // this._setupVBOandVAO(); - //else - this._setupVBO(); - - //set the texture coord - if(this._texture){ - var size = this._texture.getContentSize(); - this.initTexCoordsWithRect(cc.rect(0, 0, size.width, size.height)); - } - } else - this._totalParticles = tp; - this.resetSystem(); - }, - - /** - * listen the event that coming to foreground on Android - * @param {cc.Class} obj - */ - listenBackToForeground:function (obj) { - if (cc.TEXTURE_ATLAS_USE_VAO) - this._setupVBOandVAO(); - else - this._setupVBO(); - }, - - _setupVBOandVAO:function () { - //Not support on WebGL - /*if (cc.renderContextType == cc.CANVAS) { - return; - }*/ - - //NOT SUPPORTED - /*glGenVertexArrays(1, this._VAOname); - glBindVertexArray(this._VAOname); - - var kQuadSize = sizeof(m_pQuads[0].bl); - - glGenBuffers(2, this._buffersVBO[0]); - - glBindBuffer(GL_ARRAY_BUFFER, this._buffersVBO[0]); - glBufferData(GL_ARRAY_BUFFER, sizeof(this._quads[0]) * this._totalParticles, this._quads, GL_DYNAMIC_DRAW); - - // vertices - glEnableVertexAttribArray(kCCVertexAttrib_Position); - glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, kQuadSize, offsetof(ccV3F_C4B_T2F, vertices)); - - // colors - glEnableVertexAttribArray(kCCVertexAttrib_Color); - glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, offsetof(ccV3F_C4B_T2F, colors)); - - // tex coords - glEnableVertexAttribArray(kCCVertexAttrib_TexCoords); - glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, offsetof(ccV3F_C4B_T2F, texCoords)); - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(m_pIndices[0]) * m_uTotalParticles * 6, m_pIndices, GL_STATIC_DRAW); - - glBindVertexArray(0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - glBindBuffer(GL_ARRAY_BUFFER, 0); - - CHECK_GL_ERROR_DEBUG();*/ - }, - - _setupVBO:function () { - if (cc.renderContextType == cc.CANVAS) - return; - - var gl = cc.renderContext; - - //gl.deleteBuffer(this._buffersVBO[0]); - this._buffersVBO[0] = gl.createBuffer(); - gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); - gl.bufferData(gl.ARRAY_BUFFER, this._quadsArrayBuffer, gl.DYNAMIC_DRAW); - - this._buffersVBO[1] = gl.createBuffer(); - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]); - gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW); - - //cc.CHECK_GL_ERROR_DEBUG(); - }, - - _allocMemory:function () { - if (cc.renderContextType === cc.CANVAS) - return; - - //cc.Assert((!this._quads && !this._indices), "Memory already allocated"); - cc.Assert(!this._batchNode, "Memory should not be allocated when not using batchNode"); - var quadSize = cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT; - var totalParticles = this._totalParticles; - var locQuads = []; - this._indices = new Uint16Array(totalParticles * 6); - var locQuadsArrayBuffer = new ArrayBuffer(quadSize * totalParticles); - - for (var i = 0; i < totalParticles; i++) - locQuads[i] = new cc.V3F_C4B_T2F_Quad(null, null, null, null, locQuadsArrayBuffer, i * quadSize); - if (!locQuads || !this._indices) { - cc.log("cocos2d: Particle system: not enough memory"); - return false; - } - this._quads = locQuads; - this._quadsArrayBuffer = locQuadsArrayBuffer; - return true; - } -}); - -/** - *

- * creates an initializes a CCParticleSystemQuad from a plist file.
- * This plist files can be creted manually or with Particle Designer:
- * http://particledesigner.71squared.com/
- *

- * @param {String|Number} pListFile - * @return {cc.ParticleSystem} - * @example - * //creates an initializes a CCParticleSystemQuad from a plist file. - * var system = cc.ParticleSystemQuad.create("Images/SpinningPeas.plist"); - */ -cc.ParticleSystemQuad.create = function (pListFile) { - var ret = new cc.ParticleSystemQuad(); - if (!pListFile || typeof(pListFile) === "number") { - var ton = pListFile || 100; - ret.setDrawMode(cc.PARTICLE_TEXTURE_MODE); - ret.initWithTotalParticles(ton); - return ret; - } - - if (ret && ret.initWithFile(pListFile)) - return ret; - return null; -}; - -cc.ParticleSystemQuad.createWithTotalParticles = function (numberOfParticles) { - return cc.ParticleSystemQuad.create(numberOfParticles); -}; - -cc.ARCH_OPTIMAL_PARTICLE_SYSTEM = cc.ParticleSystemQuad; diff --git a/cocos2d/physics_nodes/CCPhysicsDebugNode.js b/cocos2d/physics_nodes/CCPhysicsDebugNode.js index f5c3e2de3a..d598ba7732 100644 --- a/cocos2d/physics_nodes/CCPhysicsDebugNode.js +++ b/cocos2d/physics_nodes/CCPhysicsDebugNode.js @@ -136,7 +136,7 @@ cc.PhysicsDebugNode = cc.DrawNode.extend({ this._spacePtr.eachShape(cc.DrawShape.bind(this)); this._spacePtr.eachConstraint(cc.DrawConstraint.bind(this)); - this._super(); + cc.DrawNode.prototype.draw.call(this); this.clear(); } }); diff --git a/cocos2d/physics_nodes/CCPhysicsSprite.js b/cocos2d/physics_nodes/CCPhysicsSprite.js index cfee963008..c50c9ada60 100644 --- a/cocos2d/physics_nodes/CCPhysicsSprite.js +++ b/cocos2d/physics_nodes/CCPhysicsSprite.js @@ -51,11 +51,13 @@ }, getPosition:function () { var pos = this._body.GetPosition(); - return cc.p(pos.x * this._PTMRatio, pos.y * this._PTMRatio); + var locPTMRatio =this._PTMRatio; + return cc.p(pos.x * locPTMRatio, pos.y * locPTMRatio); }, setPosition:function (p) { var angle = this._body.GetAngle(); - this._body.setTransform(Box2D.b2Vec2(p.x / this._PTMRatio, p.y / this._PTMRatio), angle); + var locPTMRatio =this._PTMRatio; + this._body.setTransform(Box2D.b2Vec2(p.x / locPTMRatio, p.y / locPTMRatio), angle); this.setNodeDirty(); }, getRotation:function () { @@ -64,10 +66,10 @@ setRotation:function (r) { if (this._ignoreBodyRotation) { this._rotation = r; - } - else { - var p = this._body.GetPosition(); - this._body.SetTransform(p, cc.DEGREES_TO_RADIANS(r)); + } else { + var locBody = this._body; + var p = locBody.GetPosition(); + locBody.SetTransform(p, cc.DEGREES_TO_RADIANS(r)); } this.setNodeDirty(); }, @@ -102,16 +104,32 @@ return this._body; }, getPosition:function () { - return {x:this._body.p.x, y:this._body.p.y}; + var locBody = this._body; + return {x:locBody.p.x, y:locBody.p.y}; + }, + + getPositionX:function () { + return this._body.p.x; + }, + + getPositionY:function () { + return this._body.p.y; }, - setPosition:function (pos) { - this._body.p.x = pos.x; - this._body.p.y = pos.y; + + setPosition:function (newPosOrxValue, yValue) { + if(arguments.length==2){ + this._body.p.x = newPosOrxValue; + this._body.p.y = yValue; + }else{ + this._body.p.x = newPosOrxValue.x; + this._body.p.y = newPosOrxValue.y; + } //this._syncPosition(); }, _syncPosition:function () { - if (this._position.x != this._body.p.x || this._position.y != this._body.p.y) { - cc.Sprite.prototype.setPosition.call(this, {x:this._body.p.x, y:this._body.p.y}); + var locPosition = this._position, locBody = this._body; + if (locPosition.x != locBody.p.x || locPosition.y != locBody.p.y) { + cc.Sprite.prototype.setPosition.call(this, locBody.p.x, locBody.p.y); } }, getRotation:function () { @@ -119,9 +137,8 @@ }, setRotation:function (r) { if (this._ignoreBodyRotation) { - this._super(r); - } - else { + cc.Sprite.prototype.setRotation.call(this, r); + } else { this._body.a = -cc.DEGREES_TO_RADIANS(r); //this._syncRotation(); } @@ -135,73 +152,75 @@ if(cc.renderContextType === cc.CANVAS) return this._nodeToParentTransformForCanvas(); - var x = this._body.p.x; - var y = this._body.p.y; + var locBody = this._body, locAnchorPIP = this._anchorPointInPoints, locScaleX = this._scaleX, locScaleY = this._scaleY; + var x = locBody.p.x; + var y = locBody.p.y; if (this._ignoreAnchorPointForPosition) { - x += this._anchorPointInPoints.x; - y += this._anchorPointInPoints.y; + x += locAnchorPIP.x; + y += locAnchorPIP.y; } // Make matrix - var radians = this._body.a; + var radians = locBody.a; var c = Math.cos(radians); var s = Math.sin(radians); // Although scale is not used by physics engines, it is calculated just in case // the sprite is animated (scaled up/down) using actions. // For more info see: http://www.cocos2d-iphone.org/forum/topic/68990 - if (!cc.pointEqualToPoint(this._anchorPointInPoints, cc.PointZero())) { - x += c * -this._anchorPointInPoints.x * this._scaleX + -s * -this._anchorPointInPoints.y * this._scaleY; - y += s * -this._anchorPointInPoints.x * this._scaleX + c * -this._anchorPointInPoints.y * this._scaleY; + if (!cc._rectEqualToZero(locAnchorPIP)) { + x += c * -locAnchorPIP.x * locScaleX + -s * -locAnchorPIP.y * locScaleY; + y += s * -locAnchorPIP.x * locScaleX + c * -locAnchorPIP.y * locScaleY; } // Rot, Translate Matrix - this._transform = cc.AffineTransformMake(c * this._scaleX, s * this._scaleX, - -s * this._scaleY, c * this._scaleY, + this._transform = cc.AffineTransformMake(c * locScaleX, s * locScaleX, + -s * locScaleY, c * locScaleY, x, y); return this._transform; }, - _nodeToParentTransformForCanvas:function(){ - if(!this._transform) - this._transform = {a:1,b:0,c:0,d:1,tx:0,ty:0}; - if(this.isDirty()){ + _nodeToParentTransformForCanvas: function () { + if (!this._transform) + this._transform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; + if (this.isDirty()) { var t = this._transform;// quick reference // base position - t.tx = this._body.p.x; - t.ty = this._body.p.y; + var locBody = this._body, locScaleX = this._scaleX, locScaleY = this._scaleY, locAnchorPIP = this._anchorPointInPoints; + t.tx = locBody.p.x; + t.ty = locBody.p.y; // rotation Cos and Sin - var radians = -this._body.a; + var radians = -locBody.a; var Cos = 1, Sin = 0; - if(radians){ + if (radians) { Cos = Math.cos(radians); Sin = Math.sin(radians); } // base abcd t.a = t.d = Cos; - t.c = -Sin; - t.b = Sin; + t.b = -Sin; + t.c = Sin; // scale - if(this._scaleX !== 1 || this._scaleY !== 1){ - t.a *= this._scaleX; - t.b *= this._scaleX; - t.c *= this._scaleY; - t.d *= this._scaleY; + if (locScaleX !== 1 || locScaleY !== 1) { + t.a *= locScaleX; + t.c *= locScaleX; + t.b *= locScaleY; + t.d *= locScaleY; } // adjust anchorPoint - t.tx += Cos*-this._anchorPointInPoints.x*this._scaleX + -Sin*this._anchorPointInPoints.y*this._scaleY; - t.ty -= Sin*-this._anchorPointInPoints.x*this._scaleX + Cos*this._anchorPointInPoints.y*this._scaleY; + 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 += this._anchorPointInPoints.x; - t.ty += this._anchorPointInPoints.y; + if (this._ignoreAnchorPointForPosition) { + t.tx += locAnchorPIP.x; + t.ty += locAnchorPIP.y; } this._transformDirty = false; } @@ -255,7 +274,7 @@ /** * Creates a PhysicsSprite with a sprite frame name - * @param {String} spriteFrame name + * @param {String} spriteFrameName * @return {cc.Sprite} * @example * @@ -299,6 +318,4 @@ } return null; }; - - })(); diff --git a/cocos2d/platform/CCAccelerometer.js b/cocos2d/platform/CCAccelerometer.js index 19ac9788a2..322a97cf29 100644 --- a/cocos2d/platform/CCAccelerometer.js +++ b/cocos2d/platform/CCAccelerometer.js @@ -47,10 +47,10 @@ cc.Acceleration = function (x, y, z, timestamp) { * @extends cc.Class */ cc.Accelerometer = cc.Class.extend(/** @lends cc.Accelerometer# */{ - setDelegate:function (delegate) { + setDelegate: function (delegate) { cc.AccelerometerDispatcher.getInstance().addDelegate(delegate); }, - setAccelerometerInterval:function (interval) { + setAccelerometerInterval: function (interval) { cc.AccelerometerDispatcher.getInstance().setAccelerometerInterval(interval); } }); @@ -63,31 +63,31 @@ cc.Accelerometer = cc.Class.extend(/** @lends cc.Accelerometer# */{ * @extends cc.Class */ cc.AccelerometerDispatcher = cc.Class.extend(/** @lends cc.AccelerometerDispatcher# */{ - _delegate:null, - _acceleration:null, - _deviceEvent:null, - //_orientation:0, - _interval:0.1, - _minus:1, - init:function () { + _delegate: null, + _acceleration: null, + _deviceEvent: null, + _interval: 0, + _minus: 1, + init: function () { this._acceleration = new cc.Acceleration(); this._deviceEvent = window.DeviceMotionEvent || window.DeviceOrientationEvent; var ua = navigator.userAgent; - if(/Android/.test(ua)){ + if (/Android/.test(ua) || (/Adr/.test(ua) && cc.Browser.type == "ucbrowser")) { this._minus = -1; } + //TODO fix DeviceMotionEvent bug on QQ Browser version 4.1 and below. - /*if(ua.indexOf("qqbrowser")){ + if (cc.Browser.type == "mqqbrowser") { this._deviceEvent = window.DeviceOrientationEvent; - }*/ + } return true; }, - getDelegate:function () { + getDelegate: function () { return this._delegate; }, - addDelegate:function (delegate) { + addDelegate: function (delegate) { this._delegate = delegate; var acc = this.didAccelerate.bind(this); @@ -109,18 +109,20 @@ cc.AccelerometerDispatcher = cc.Class.extend(/** @lends cc.AccelerometerDispatch } }, - setAccelerometerInterval:function (interval) { - //not available on browser + setAccelerometerInterval: function (interval) { if (this._interval !== interval) { this._interval = interval; } }, - didAccelerate:function (eventData) { + didAccelerate: function (eventData) { if (!this._delegate) { return; } + var now = Date.now(); + if ((now - this._acceleration.timestamp) / 1000 < this._interval) return; + if (this._deviceEvent == window.DeviceMotionEvent) { var acceleration = eventData.accelerationIncludingGravity; this._acceleration.x = this._minus * acceleration.x * 0.1; @@ -132,7 +134,6 @@ cc.AccelerometerDispatcher = cc.Class.extend(/** @lends cc.AccelerometerDispatch this._acceleration.y = -(eventData.beta / 90) * 0.981; this._acceleration.z = (eventData.alpha / 90) * 0.981; } - this._acceleration.timestamp = Date.now(); var tmp = this._acceleration.x; diff --git a/cocos2d/platform/CCApplication.js b/cocos2d/platform/CCApplication.js index d3422b498e..57d130e2b4 100644 --- a/cocos2d/platform/CCApplication.js +++ b/cocos2d/platform/CCApplication.js @@ -94,8 +94,8 @@ cc.WEBGL = 1; cc.drawingUtil = null; /** - * main Canvas 2D Context of game engine - * @type CanvasContext + * main Canvas 2D/3D Context of game engine + * @type CanvasRenderingContext2D|WebGLRenderingContext */ cc.renderContext = null; @@ -208,11 +208,12 @@ cc.setup = function (el, width, height) { cc.renderContext = cc.webglContext = cc.create3DContext(cc.canvas,{'stencil': true, 'preserveDrawingBuffer': true, 'alpha': false }); if(cc.renderContext){ cc.renderContextType = cc.WEBGL; - gl = cc.renderContext; // global variable declared in CCMacro.js + window.gl = cc.renderContext; // global variable declared in CCMacro.js cc.drawingUtil = new cc.DrawingPrimitiveWebGL(cc.renderContext); cc.TextureCache.getInstance()._initializingRenderer(); } else { cc.renderContext = cc.canvas.getContext("2d"); + cc.mainRenderContextBackup = cc.renderContext; cc.renderContextType = cc.CANVAS; cc.renderContext.translate(0, cc.canvas.height); cc.drawingUtil = new cc.DrawingPrimitiveCanvas(cc.renderContext); @@ -226,16 +227,10 @@ cc.setup = function (el, width, height) { cc.setContextMenuEnable(false); - //binding window size - /* - cc.canvas.addEventListener("resize", function () { - if (!cc.firstRun) { - cc.Director.getInstance().addRegionToDirtyRegion(cc.rect(0, 0, cc.canvas.width, cc.canvas.height)); - } - }, true); - */ - if(cc.Browser.isMobile) + if(cc.Browser.isMobile){ cc._addUserSelectStatus(); + cc._addBottomTag(); + } var hidden, visibilityChange; if (typeof document.hidden !== "undefined") { @@ -275,6 +270,14 @@ cc._addUserSelectStatus = function(){ +"-webkit-tap-highlight-color:rgba(0,0,0,0);}"; }; +cc._addBottomTag = function () { + var bottom = document.createElement("div"); + bottom.id = "bottom"; + bottom.style.border = bottom.style.margin = bottom.style.padding = bottom.style.height = bottom.style.lineHeight = bottom.style.fontSize = "0px"; + document.body.appendChild(bottom); + window.location.href="#bottom"; +}; + cc._isContextMenuEnable = false; /** * enable/disable contextMenu for Canvas @@ -341,17 +344,17 @@ cc.Application = cc.Class.extend(/** @lends cc.Application# */{ if (!this.applicationDidFinishLaunching()) return 0; - var callback; - if (window.requestAnimFrame && this._animationInterval == 1 / 60) { + var callback, director = cc.Director.getInstance(), w = window; + if (w.requestAnimFrame && this._animationInterval == 1 / 60) { callback = function () { - cc.Director.getInstance().mainLoop(); - window.requestAnimFrame(callback); + director.mainLoop(); + w.requestAnimFrame(callback); }; - cc.log(window.requestAnimFrame); - window.requestAnimFrame(callback); + //cc.log(window.requestAnimFrame); + w.requestAnimFrame(callback); } else { callback = function () { - cc.Director.getInstance().mainLoop(); + director.mainLoop(); }; setInterval(callback, this._animationInterval * 1000); } diff --git a/cocos2d/platform/CCClass.js b/cocos2d/platform/CCClass.js index 6f96df7edb..5f88fe391b 100644 --- a/cocos2d/platform/CCClass.js +++ b/cocos2d/platform/CCClass.js @@ -84,8 +84,7 @@ ClassManager.getNewID=function(){ (function () { var initializing = false, fnTest = /\b_super\b/; var releaseMode = (document['ccConfig'] && document['ccConfig']['CLASS_RELEASE_MODE']) ? document['ccConfig']['CLASS_RELEASE_MODE'] : null; - if(releaseMode) - { + if(releaseMode) { console.log("release Mode"); } @@ -117,12 +116,10 @@ ClassManager.getNewID=function(){ // these function properties cacheable in Carakan. var desc = { writable: true, enumerable: false, configurable: true }; for (var name in prop) { - if(releaseMode && typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name])) - { + if(releaseMode && typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name])) { desc.value = ClassManager.compileSuper(prop[name], name, classId); Object.defineProperty(prototype, name, desc); - } - else if(typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name])){ + } else if(typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name])){ desc.value = (function (name, fn) { return function () { var tmp = this._super; @@ -140,12 +137,10 @@ ClassManager.getNewID=function(){ }; })(name, prop[name]); Object.defineProperty(prototype, name, desc); - } - else if(typeof prop[name] == "function") { + } else if(typeof prop[name] == "function") { desc.value = prop[name]; Object.defineProperty(prototype, name, desc); - } - else{ + } else{ prototype[name] = prop[name]; } } @@ -167,13 +162,20 @@ ClassManager.getNewID=function(){ // See https://github.com/oupengsoftware/v8/wiki/Dictionary-mode-%28English%29#wiki-append-property // // for principles under the hood. - var functionBody = releaseMode? "": "this._super=null;"; + /*var functionBody = releaseMode? "": "this._super=null;"; for (var p in prototype) { functionBody += "this." + p + "=this." + p + ";"; } if (prototype.ctor) functionBody += "this.ctor.apply(this,arguments)"; - var Class = new Function(functionBody); + var Class = new Function(functionBody);*/ + + // The dummy Class constructor + function Class() { + // All construction is actually done in the init method + if (this.ctor) + this.ctor.apply(this, arguments); + } Class.id = classId; // desc = { writable: true, enumerable: false, configurable: true, @@ -199,6 +201,15 @@ ClassManager.getNewID=function(){ }; return Class; }; + + Function.prototype.bind = Function.prototype.bind || function (bind) { + var self = this; + return function () { + var args = Array.prototype.slice.call(arguments); + return self.apply(bind || null, args); + }; + }; + })(); // @@ -259,3 +270,4 @@ cc.concatObjectProperties = function(dstObject, srcObject){ } return dstObject; }; + diff --git a/cocos2d/platform/CCCommon.js b/cocos2d/platform/CCCommon.js index ac38bc2a46..9fd76a5523 100644 --- a/cocos2d/platform/CCCommon.js +++ b/cocos2d/platform/CCCommon.js @@ -48,9 +48,9 @@ cc.clone = function (obj) { // derived class forgets to set "constructor" on the prototype. We ignore // these possibities for and the ultimate solution is a standardized // Object.clone(). - var newObj = new obj.constructor; + var newObj = (obj.constructor) ? new obj.constructor : {}; - // Assuming that the constuctor above initialized all properies on obj, the + // Assuming that the constuctor above initialized all properies on obj, the // following keyed assignments won't turn newObj into dictionary mode // becasue they're not *appending new properties* but *assigning existing // ones* (note that appending indexed properties is another story). See @@ -71,10 +71,10 @@ cc.clone = function (obj) { /** * Function added for JS bindings compatibility. Not needed in cocos2d-html5. * @function - * @param {object} jsobj subclass - * @param {object} klass superclass + * @param {object} jsObj subclass + * @param {object} superclass */ -cc.associateWithNative = function (jsobj, superclass) { +cc.associateWithNative = function (jsObj, superclass) { }; /** diff --git a/cocos2d/platform/CCConfig.js b/cocos2d/platform/CCConfig.js index 9e6fdd8bcd..9abd0bfee6 100644 --- a/cocos2d/platform/CCConfig.js +++ b/cocos2d/platform/CCConfig.js @@ -33,7 +33,7 @@ * @constant * @type String */ -cc.ENGINE_VERSION = "Cocos2d-html5-v2.1.5"; +cc.ENGINE_VERSION = "Cocos2d-html5-v2.1.6"; /** *

diff --git a/cocos2d/platform/CCEGLView.js b/cocos2d/platform/CCEGLView.js index 196e16df8a..ed8979c11f 100644 --- a/cocos2d/platform/CCEGLView.js +++ b/cocos2d/platform/CCEGLView.js @@ -88,29 +88,50 @@ cc.EGLView = cc.Class.extend(/** @lends cc.EGLView# */{ ctor:function () { this._ele = (cc.container.parentNode === document.body) ? document.documentElement : cc.container.parentNode; this._viewName = "Cocos2dHTML5"; - this._screenSize = cc.size(this._ele.clientWidth, this._ele.clientHeight); + this._designResolutionSize = cc.SizeZero(); this._viewPortRect = cc.RectZero(); this._delegate = cc.Director.getInstance().getTouchDispatcher(); this._contentTranslateLeftTop = {left:0, top:0}; + this._screenSize = cc.SizeZero(); this._hDC = cc.canvas; this._hRC = cc.renderContext; + this._initScreenSize(); }, /** * init */ initialize:function () { + this._scrollToBottom(); this._initialize = true; - this._adjustSize(); - var adjustSize = this._adjustSize.bind(this); window.addEventListener('resize', adjustSize, false); + if(cc.Browser.isMobile){ + setTimeout(adjustSize,300); + }else{ + this._adjustSize(); + } + }, + + _scrollToBottom:function(){ + if(cc.Browser.isMobile){ + cc.canvas.height = this._ele.clientHeight+500; + window.location.href="#bottom"; + } }, + _initScreenSize:function(){ + this._screenSize.width = this._ele.clientWidth; + this._screenSize.height = this._ele.clientHeight; + if(navigator.userAgent.match(/iPhone/i)){ + this._screenSize.height +=(this._screenSize.width/320)*60; + } + }, _adjustSize:function () { - this._screenSize = cc.size(this._ele.clientWidth, this._ele.clientHeight); + this._scrollToBottom(); + this._initScreenSize(); cc.canvas.width = this._screenSize.width; cc.canvas.height = this._screenSize.height; @@ -269,19 +290,23 @@ cc.EGLView = cc.Class.extend(/** @lends cc.EGLView# */{ setDesignResolutionSize:function (width, height, resolutionPolicy) { cc.Assert(resolutionPolicy !== cc.RESOLUTION_POLICY.UNKNOWN, "should set resolutionPolicy"); - if (!this._initialize) { - this.initialize(); - } - if (width == 0 || height == 0) return; - if ((width != null) && (height != null)) + if ((width != null) && (height != null)){ this._designResolutionSize = cc.size(width, height); + } if (resolutionPolicy != null) this._resolutionPolicy = resolutionPolicy; + if (!this._initialize) { + this.initialize(); + return; + } + + + this._scaleX = this._screenSize.width / this._designResolutionSize.width; this._scaleY = this._screenSize.height / this._designResolutionSize.height; @@ -329,6 +354,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.EGLView# */{ director._createStatsLabel(); director.setGLDefaultValues(); } + cc.DOM._resetEGLViewDiv(); }, /** @@ -390,7 +416,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.EGLView# */{ getScissorRect:function () { var gl = cc.renderContext, scaleX = this._scaleX, scaleY = this._scaleY; var boxArr = gl.getParameter(gl.SCISSOR_BOX); - return cc.RectMake((boxArr[0] - this._viewPortRect.x) / scaleX, (boxArr[1] - this._viewPortRect.y) / this._scaleY, + return cc.rect((boxArr[0] - this._viewPortRect.x) / scaleX, (boxArr[1] - this._viewPortRect.y) / this._scaleY, boxArr[2] / scaleX, boxArr[3] / scaleY); }, diff --git a/cocos2d/platform/CCFileUtils.js b/cocos2d/platform/CCFileUtils.js index 4fdf1b9f3a..4d1ba82d65 100644 --- a/cocos2d/platform/CCFileUtils.js +++ b/cocos2d/platform/CCFileUtils.js @@ -158,6 +158,7 @@ cc.FileUtils = cc.Class.extend({ * @warning If you get the file data succeed,you must delete it after used. */ getByteArrayFromFile:function (fileName, mode, size) { + fileName = this.fullPathForFilename(fileName); if (this._fileDataCache.hasOwnProperty(fileName)) return this._fileDataCache[fileName]; return this._loadBinaryFileData(fileName); @@ -177,7 +178,7 @@ cc.FileUtils = cc.Class.extend({ }, preloadBinaryFileData:function (fileUrl) { - fileUrl = this.fullPathFromRelativePath(fileUrl); + fileUrl = this.fullPathForFilename(fileUrl); var selfPointer = this; var xhr = this._getXMLHttpRequest(); @@ -191,6 +192,8 @@ cc.FileUtils = cc.Class.extend({ var fileContents = cc._convertResponseBodyToText(xhr["responseBody"]); if (fileContents) selfPointer._fileDataCache[fileUrl] = selfPointer._stringConvertToArray(fileContents); + } else { + cc.Loader.getInstance().onResLoadingErr(fileUrl); } cc.Loader.getInstance().onResLoaded(); } @@ -198,11 +201,17 @@ cc.FileUtils = cc.Class.extend({ } else { if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=x-user-defined"); - xhr.onload = function (e) { - var arrayStr = xhr.responseText; - if (arrayStr) { + + xhr.onreadystatechange = function (event) { + if (xhr.readyState == 4) { + if (xhr.status == 200) { + var fileContents = xhr.responseText; + if (fileContents) + selfPointer._fileDataCache[fileUrl] = selfPointer._stringConvertToArray(fileContents); + } else { + cc.Loader.getInstance().onResLoadingErr(fileUrl); + } cc.Loader.getInstance().onResLoaded(); - selfPointer._fileDataCache[fileUrl] = selfPointer._stringConvertToArray(arrayStr); } }; } @@ -254,7 +263,7 @@ cc.FileUtils = cc.Class.extend({ }, preloadTextFileData:function (fileUrl) { - fileUrl = this.fullPathFromRelativePath(fileUrl); + fileUrl = this.fullPathForFilename(fileUrl); var selfPointer = this; var xhr = this._getXMLHttpRequest(); @@ -262,55 +271,44 @@ cc.FileUtils = cc.Class.extend({ if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) { // IE-specific logic here xhr.setRequestHeader("Accept-Charset", "utf-8"); - xhr.onreadystatechange = function (event) { - if (xhr.readyState == 4) { - if (xhr.status == 200) { - var fileContents = xhr.responseText; - if (fileContents) - selfPointer._textFileCache[fileUrl] = fileContents; - } - cc.Loader.getInstance().onResLoaded(); - } - }; } else { if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8"); - xhr.onload = function (e) { - if (xhr.responseText) { - cc.Loader.getInstance().onResLoaded(); - selfPointer._fileDataCache[fileUrl] = xhr.responseText; - } - }; } + xhr.onreadystatechange = function (event) { + if (xhr.readyState == 4) { + if (xhr.status == 200) { + var fileContents = xhr.responseText; + if (fileContents) + selfPointer._textFileCache[fileUrl] = fileContents; + } else { + cc.Loader.getInstance().onResLoadingErr(fileUrl); + } + cc.Loader.getInstance().onResLoaded(); + } + }; xhr.send(null); }, _loadTextFileData:function (fileUrl) { var req = this._getXMLHttpRequest(); req.open('GET', fileUrl, false); - var arrayInfo = null; + var fileContents = null; if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) { req.setRequestHeader("Accept-Charset", "utf-8"); - req.send(null); - if (req.status != 200) - return null; - - var fileContents = req.responseText; - if (fileContents) { - arrayInfo = fileContents; - this._textFileCache[fileUrl] = fileContents; - } } else { if (req.overrideMimeType) req.overrideMimeType('text\/plain; charset=utf-8'); - req.send(null); - if (req.status != 200) - return null; + } + req.send(null); + if (req.status != 200) + return null; - arrayInfo = req.responseText; - this._textFileCache[fileUrl] = arrayInfo; + fileContents = req.responseText; + if (fileContents) { + this._textFileCache[fileUrl] = fileContents; } - return arrayInfo; + return fileContents; }, /** diff --git a/cocos2d/platform/CCSAXParser.js b/cocos2d/platform/CCSAXParser.js index b2067405bc..19392b9158 100644 --- a/cocos2d/platform/CCSAXParser.js +++ b/cocos2d/platform/CCSAXParser.js @@ -30,14 +30,20 @@ * @extends cc.Class */ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{ - xmlDoc:null, - parser:null, - _xmlDict:null, - plist:null, + xmlDoc: null, + _parser: null, + _xmlDict: null, + _isSupportDOMParser: null, - ctor:function () { + ctor: function () { this._xmlDict = {}; - this.plist = {}; + + if (window.DOMParser) { + this._isSupportDOMParser = true; + this._parser = new DOMParser(); + } else { + this._isSupportDOMParser = false; + } }, /** @@ -45,23 +51,15 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{ * @param {String} textxml plist xml contents * @return {Array} plist object array */ - parse:function (textxml) { + parse: function (textxml) { + var path = textxml; textxml = this.getList(textxml); - // get a reference to the requested corresponding xml file - if (window.DOMParser) { - this.parser = new DOMParser(); - this.xmlDoc = this.parser.parseFromString(textxml, "text/xml"); - } else {// Internet Explorer (untested!) - this.xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); - this.xmlDoc.async = "false"; - this.xmlDoc.loadXML(textxml); - } - if (this.xmlDoc == null) - cc.log("cocos2d:xml " + this.xmlDoc + " not found!"); - var plist = this.xmlDoc.documentElement; + var xmlDoc = this._parserXML(textxml, path); + + var plist = xmlDoc.documentElement; if (plist.tagName != 'plist') - throw "cocos2d:Not a plist file"; + throw "cocos2d: " + path + " is not a plist file"; // Get first real node var node = null; @@ -70,8 +68,9 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{ if (node.nodeType == 1) break } - this.plist = this._parseNode(node); - return this.plist; + xmlDoc = null; + + return this._parseNode(node); }, /** @@ -79,26 +78,32 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{ * @param {String} textxml tilemap xml content * @return {Document} xml document */ - tmxParse:function (textxml, isXMLString) { - if((isXMLString == null) || (isXMLString === false)) + tmxParse: function (textxml, isXMLString) { + if ((isXMLString == null) || (isXMLString === false)) textxml = this.getList(textxml); + return this._parserXML(textxml); + }, + + _parserXML: function (textxml, path) { // get a reference to the requested corresponding xml file - if (window.DOMParser) { - this.parser = new DOMParser(); - this.xmlDoc = this.parser.parseFromString(textxml, "text/xml"); - } else { // Internet Explorer (untested!) - this.xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); - this.xmlDoc.async = "false"; - this.xmlDoc.loadXML(textxml); + var xmlDoc; + if (this._isSupportDOMParser) { + xmlDoc = this._parser.parseFromString(textxml, "text/xml"); + } else { + // Internet Explorer (untested!) + xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); + xmlDoc.async = "false"; + xmlDoc.loadXML(textxml); } - if (this.xmlDoc == null) - cc.log("cocos2d:xml " + this.xmlDoc + " not found!"); - return this.xmlDoc; + if (xmlDoc == null) + cc.log("cocos2d:xml " + path + " not found!"); + + return xmlDoc; }, - _parseNode:function (node) { + _parseNode: function (node) { var data = null; switch (node.tagName) { case 'dict': @@ -134,7 +139,7 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{ return data; }, - _parseArray:function (node) { + _parseArray: function (node) { var data = []; for (var i = 0, len = node.childNodes.length; i < len; i++) { var child = node.childNodes[i]; @@ -145,7 +150,7 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{ return data; }, - _parseDict:function (node) { + _parseDict: function (node) { var data = {}; var key = null; @@ -167,19 +172,15 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{ * Preload plist file * @param {String} filePath */ - preloadPlist:function (filePath) { + preloadPlist: function (filePath) { filePath = cc.FileUtils.getInstance().fullPathForFilename(filePath); if (window.XMLHttpRequest) { - // for IE7+, Firefox, Chrome, Opera, Safari brower var xmlhttp = new XMLHttpRequest(); - // is xml file? if (xmlhttp.overrideMimeType) xmlhttp.overrideMimeType('text/xml'); - } else { - // for IE6, IE5 brower - xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } + if (xmlhttp != null) { var that = this; xmlhttp.onreadystatechange = function () { @@ -199,12 +200,21 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{ cc.Assert("cocos2d:Your browser does not support XMLHTTP."); }, + /** + * Unload the preloaded plist from xmlList + * @param {String} filePath + */ + unloadPlist: function (filePath) { + if (this._xmlDict.hasOwnProperty(filePath)) + delete this._xmlDict[filePath]; + }, + /** * get filename from filepath * @param {String} filePath * @return {String} */ - getName:function (filePath) { + getName: function (filePath) { var startPos = filePath.lastIndexOf("/", filePath.length) + 1; var endPos = filePath.lastIndexOf(".", filePath.length); return filePath.substring(startPos, endPos); @@ -215,7 +225,7 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{ * @param {String} filePath * @return {String} */ - getExt:function (filePath) { + getExt: function (filePath) { var startPos = filePath.lastIndexOf(".", filePath.length) + 1; return filePath.substring(startPos, filePath.length); }, @@ -225,7 +235,7 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{ * @param {String} key * @return {String} xml content */ - getList:function (key) { + getList: function (key) { if (this._xmlDict != null) { return this._xmlDict[key]; } diff --git a/cocos2d/platform/CCTypes.js b/cocos2d/platform/CCTypes.js index 05b2e22836..8ab9dff686 100644 --- a/cocos2d/platform/CCTypes.js +++ b/cocos2d/platform/CCTypes.js @@ -458,7 +458,6 @@ cc.Quad2 = function (tl1, tr1, bl1, br1) { * @param {cc.Vertex3F} tr1 */ cc.Quad3 = function (bl1, br1, tl1, tr1) { - //TODO need redefine by ArrayBuffer this.bl = bl1 || new cc.Vertex3F(0, 0, 0); this.br = br1 || new cc.Vertex3F(0, 0, 0); this.tl = tl1 || new cc.Vertex3F(0, 0, 0); @@ -608,7 +607,7 @@ cc.V3F_C4B_T2F_QuadZero = function () { cc.V3F_C4B_T2F_QuadCopy = function (sourceQuad) { if (!sourceQuad) return cc.V3F_C4B_T2F_QuadZero(); - + var tl = sourceQuad.tl, bl = sourceQuad.bl, tr = sourceQuad.tr, br = sourceQuad.br; return new cc.V3F_C4B_T2F_Quad( new cc.V3F_C4B_T2F(new cc.Vertex3F(sourceQuad.tl.vertices.x, sourceQuad.tl.vertices.y, sourceQuad.tl.vertices.z), new cc.Color4B(sourceQuad.tl.colors.r, sourceQuad.tl.colors.g, sourceQuad.tl.colors.b, sourceQuad.tl.colors.a), @@ -684,7 +683,7 @@ cc.T2F_Quad = function(bl, br, tl, tr){ }; /** - * struct that holds the size in pixels, texture coordinates and delays for animated cc.ParticleSystemQuad + * struct that holds the size in pixels, texture coordinates and delays for animated cc.ParticleSystem * @param {cc.T2F_Quad} texCoords * @param delay * @param size @@ -718,10 +717,11 @@ if(cc.Browser.supportWebGL){ this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Color4B.BYTES_PER_ELEMENT); this._offset = offset || 0; - this._rU8 = new Uint8Array(this._arrayBuffer, this._offset, 1); - this._gU8 = new Uint8Array(this._arrayBuffer, this._offset + Uint8Array.BYTES_PER_ELEMENT, 1); - this._bU8 = new Uint8Array(this._arrayBuffer, this._offset + Uint8Array.BYTES_PER_ELEMENT * 2, 1); - this._aU8 = new Uint8Array(this._arrayBuffer, this._offset + Uint8Array.BYTES_PER_ELEMENT * 3, 1); + var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = Uint8Array.BYTES_PER_ELEMENT; + this._rU8 = new Uint8Array(locArrayBuffer, locOffset, 1); + this._gU8 = new Uint8Array(locArrayBuffer, locOffset + locElementLen, 1); + this._bU8 = new Uint8Array(locArrayBuffer, locOffset + locElementLen * 2, 1); + this._aU8 = new Uint8Array(locArrayBuffer, locOffset + locElementLen * 3, 1); this._rU8[0] = r || 0; this._gU8[0] = g || 0; @@ -769,17 +769,18 @@ if(cc.Browser.supportWebGL){ }); //redefine cc.Color4F - cc.Color4F = function(r,g,b,a, arrayBuffer, offset){ + cc.Color4F = function (r, g, b, a, arrayBuffer, offset) { this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Color4F.BYTES_PER_ELEMENT); this._offset = offset || 0; - this._rF32 = new Float32Array(this._arrayBuffer,this._offset, 1); + var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = Float32Array.BYTES_PER_ELEMENT; + this._rF32 = new Float32Array(locArrayBuffer, locOffset, 1); this._rF32[0] = r || 0; - this._gF32 = new Float32Array(this._arrayBuffer,this._offset + Float32Array.BYTES_PER_ELEMENT, 1); + this._gF32 = new Float32Array(locArrayBuffer, locOffset + locElementLen, 1); this._gF32[0] = g || 0; - this._bF32 = new Float32Array(this._arrayBuffer,this._offset + Float32Array.BYTES_PER_ELEMENT * 2, 1); + this._bF32 = new Float32Array(locArrayBuffer, locOffset + locElementLen * 2, 1); this._bF32[0] = b || 0; - this._aF32 = new Float32Array(this._arrayBuffer,this._offset + Float32Array.BYTES_PER_ELEMENT * 3, 1); + this._aF32 = new Float32Array(locArrayBuffer, locOffset + locElementLen * 3, 1); this._aF32[0] = a || 0; }; cc.Color4F.BYTES_PER_ELEMENT = 16; @@ -859,11 +860,12 @@ if(cc.Browser.supportWebGL){ this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Vertex3F.BYTES_PER_ELEMENT); this._offset = offset || 0; - this._xF32 = new Float32Array(this._arrayBuffer, this._offset, 1); + var locArrayBuffer = this._arrayBuffer, locOffset = this._offset; + this._xF32 = new Float32Array(locArrayBuffer, locOffset, 1); this._xF32[0] = x || 0; - this._yF32 = new Float32Array(this._arrayBuffer, this._offset + Float32Array.BYTES_PER_ELEMENT, 1); + this._yF32 = new Float32Array(locArrayBuffer, locOffset + Float32Array.BYTES_PER_ELEMENT, 1); this._yF32[0] = y || 0; - this._zF32 = new Float32Array(this._arrayBuffer, this._offset + Float32Array.BYTES_PER_ELEMENT * 2, 1); + this._zF32 = new Float32Array(locArrayBuffer, locOffset + Float32Array.BYTES_PER_ELEMENT * 2, 1); this._zF32[0] = z || 0; }; cc.Vertex3F.BYTES_PER_ELEMENT = 12; @@ -934,13 +936,11 @@ if(cc.Browser.supportWebGL){ this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Quad2.BYTES_PER_ELEMENT); this._offset = offset || 0; - this._tl = tl ? new cc.Vertex2F(tl.x, tl.y, this._arrayBuffer, 0) : new cc.Vertex2F(0, 0, this._arrayBuffer, 0); - this._tr = tr ? new cc.Vertex2F(tr.x, tr.y, this._arrayBuffer, cc.Vertex2F.BYTES_PER_ELEMENT) : - new cc.Vertex2F(0, 0, this._arrayBuffer, cc.Vertex2F.BYTES_PER_ELEMENT); - this._bl = bl ? new cc.Vertex2F(bl.x, bl.y, this._arrayBuffer, cc.Vertex2F.BYTES_PER_ELEMENT * 2) : - new cc.Vertex2F(0, 0, this._arrayBuffer, cc.Vertex2F.BYTES_PER_ELEMENT * 2); - this._br = br ? new cc.Vertex2F(br.x, br.y, this._arrayBuffer, cc.Vertex2F.BYTES_PER_ELEMENT * 3) : - new cc.Vertex2F(0, 0, this._arrayBuffer, cc.Vertex2F.BYTES_PER_ELEMENT * 3); + var locArrayBuffer = this._arrayBuffer, locElementLen = cc.Vertex2F.BYTES_PER_ELEMENT; + this._tl = tl ? new cc.Vertex2F(tl.x, tl.y, locArrayBuffer, 0) : new cc.Vertex2F(0, 0, locArrayBuffer, 0); + this._tr = tr ? new cc.Vertex2F(tr.x, tr.y, locArrayBuffer, locElementLen) : new cc.Vertex2F(0, 0, locArrayBuffer, locElementLen); + this._bl = bl ? new cc.Vertex2F(bl.x, bl.y, locArrayBuffer, locElementLen * 2) : new cc.Vertex2F(0, 0, locArrayBuffer, locElementLen * 2); + this._br = br ? new cc.Vertex2F(br.x, br.y, locArrayBuffer, locElementLen * 3) : new cc.Vertex2F(0, 0, locArrayBuffer, locElementLen * 3); }; cc.Quad2.BYTES_PER_ELEMENT = 32; Object.defineProperties(cc.Quad2.prototype, { @@ -991,12 +991,13 @@ if(cc.Browser.supportWebGL){ this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V3F_C4B_T2F.BYTES_PER_ELEMENT); this._offset = offset || 0; - this._vertices = vertices ? new cc.Vertex3F(vertices.x, vertices.y, vertices.z, this._arrayBuffer, this._offset) : - new cc.Vertex3F(0, 0, 0, this._arrayBuffer, this._offset); - this._colors = colors ? new cc.Color4B(colors.r, colors.g, colors.b, colors.a, this._arrayBuffer, this._offset + cc.Vertex3F.BYTES_PER_ELEMENT) : - new cc.Color4B(0, 0, 0, 0, this._arrayBuffer, this._offset + cc.Vertex3F.BYTES_PER_ELEMENT); - this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, this._arrayBuffer, this._offset + cc.Vertex3F.BYTES_PER_ELEMENT + cc.Color4B.BYTES_PER_ELEMENT) : - new cc.Tex2F(0, 0, this._arrayBuffer, this._offset + cc.Vertex3F.BYTES_PER_ELEMENT + cc.Color4B.BYTES_PER_ELEMENT); + var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.Vertex3F.BYTES_PER_ELEMENT; + this._vertices = vertices ? new cc.Vertex3F(vertices.x, vertices.y, vertices.z, locArrayBuffer, locOffset) : + new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset); + this._colors = colors ? new cc.Color4B(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset + locElementLen) : + new cc.Color4B(0, 0, 0, 0, locArrayBuffer, locOffset + locElementLen); + this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, locArrayBuffer, locOffset + locElementLen + cc.Color4B.BYTES_PER_ELEMENT) : + new cc.Tex2F(0, 0, locArrayBuffer, locOffset + locElementLen + cc.Color4B.BYTES_PER_ELEMENT); }; cc.V3F_C4B_T2F.BYTES_PER_ELEMENT = 24; Object.defineProperties(cc.V3F_C4B_T2F.prototype, { @@ -1005,9 +1006,10 @@ if(cc.Browser.supportWebGL){ return this._vertices; }, set: function (verticesValue) { - this._vertices.x = verticesValue.x; - this._vertices.y = verticesValue.y; - this._vertices.z = verticesValue.z; + var locVertices = this._vertices; + locVertices.x = verticesValue.x; + locVertices.y = verticesValue.y; + locVertices.z = verticesValue.z; }, enumerable: true }, @@ -1016,10 +1018,11 @@ if(cc.Browser.supportWebGL){ return this._colors; }, set: function (colorValue) { - this._colors.r = colorValue.r; - this._colors.g = colorValue.g; - this._colors.b = colorValue.b; - this._colors.a = colorValue.a; + var locColors = this._colors; + locColors.r = colorValue.r; + locColors.g = colorValue.g; + locColors.b = colorValue.b; + locColors.a = colorValue.a; }, enumerable: true }, @@ -1040,14 +1043,15 @@ if(cc.Browser.supportWebGL){ this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT); this._offset = offset || 0; - this._tl = tl ? new cc.V3F_C4B_T2F(tl.vertices, tl.colors, tl.texCoords, this._arrayBuffer, this._offset) : - new cc.V3F_C4B_T2F(null, null, null, this._arrayBuffer, this._offset); - this._bl = bl ? new cc.V3F_C4B_T2F(bl.vertices, bl.colors, bl.texCoords, this._arrayBuffer, this._offset + cc.V3F_C4B_T2F.BYTES_PER_ELEMENT) : - new cc.V3F_C4B_T2F(null, null, null, this._arrayBuffer, this._offset + cc.V3F_C4B_T2F.BYTES_PER_ELEMENT); - this._tr = tr ? new cc.V3F_C4B_T2F(tr.vertices, tr.colors, tr.texCoords, this._arrayBuffer, this._offset + cc.V3F_C4B_T2F.BYTES_PER_ELEMENT * 2) : - new cc.V3F_C4B_T2F(null, null, null, this._arrayBuffer, this._offset + cc.V3F_C4B_T2F.BYTES_PER_ELEMENT * 2); - this._br = br ? new cc.V3F_C4B_T2F(br.vertices, br.colors, br.texCoords, this._arrayBuffer, this._offset + cc.V3F_C4B_T2F.BYTES_PER_ELEMENT * 3) : - new cc.V3F_C4B_T2F(null, null, null, this._arrayBuffer, this._offset + cc.V3F_C4B_T2F.BYTES_PER_ELEMENT * 3); + var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.V3F_C4B_T2F.BYTES_PER_ELEMENT; + this._tl = tl ? new cc.V3F_C4B_T2F(tl.vertices, tl.colors, tl.texCoords, locArrayBuffer, locOffset) : + new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset); + this._bl = bl ? new cc.V3F_C4B_T2F(bl.vertices, bl.colors, bl.texCoords, locArrayBuffer, locOffset + locElementLen) : + new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen); + this._tr = tr ? new cc.V3F_C4B_T2F(tr.vertices, tr.colors, tr.texCoords, locArrayBuffer, locOffset + locElementLen * 2) : + new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen * 2); + this._br = br ? new cc.V3F_C4B_T2F(br.vertices, br.colors, br.texCoords, locArrayBuffer, locOffset + locElementLen * 3) : + new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen * 3); }; cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT = 96; Object.defineProperties(cc.V3F_C4B_T2F_Quad.prototype, { @@ -1056,9 +1060,10 @@ if(cc.Browser.supportWebGL){ return this._tl; }, set: function (tlValue) { - this._tl.vertices = tlValue.vertices; - this._tl.colors = tlValue.colors; - this._tl.texCoords = tlValue.texCoords; + var locTl = this._tl; + locTl.vertices = tlValue.vertices; + locTl.colors = tlValue.colors; + locTl.texCoords = tlValue.texCoords; }, enumerable: true }, @@ -1067,9 +1072,10 @@ if(cc.Browser.supportWebGL){ return this._bl; }, set: function (blValue) { - this._bl.vertices = blValue.vertices; - this._bl.colors = blValue.colors; - this._bl.texCoords = blValue.texCoords; + var locBl = this._bl; + locBl.vertices = blValue.vertices; + locBl.colors = blValue.colors; + locBl.texCoords = blValue.texCoords; }, enumerable: true }, @@ -1078,9 +1084,10 @@ if(cc.Browser.supportWebGL){ return this._tr; }, set: function (trValue) { - this._tr.vertices = trValue.vertices; - this._tr.colors = trValue.colors; - this._tr.texCoords = trValue.texCoords; + var locTr = this._tr; + locTr.vertices = trValue.vertices; + locTr.colors = trValue.colors; + locTr.texCoords = trValue.texCoords; }, enumerable: true }, @@ -1089,9 +1096,10 @@ if(cc.Browser.supportWebGL){ return this._br; }, set: function (brValue) { - this._br.vertices = brValue.vertices; - this._br.colors = brValue.colors; - this._br.texCoords = brValue.texCoords; + var locBr = this._br; + locBr.vertices = brValue.vertices; + locBr.colors = brValue.colors; + locBr.texCoords = brValue.texCoords; }, enumerable: true }, @@ -1111,19 +1119,20 @@ if(cc.Browser.supportWebGL){ return cc.V3F_C4B_T2F_QuadZero(); //return new cc.V3F_C4B_T2F_Quad(sourceQuad,tl,sourceQuad,bl,sourceQuad.tr,sourceQuad.br,null,0); + var srcTL = sourceQuad.tl, srcBL = sourceQuad.bl, srcTR = sourceQuad.tr, srcBR = sourceQuad.br; return { - tl: {vertices: {x: sourceQuad.tl.vertices.x, y: sourceQuad.tl.vertices.y, z: sourceQuad.tl.vertices.z}, - colors: {r: sourceQuad.tl.colors.r, g: sourceQuad.tl.colors.g, b: sourceQuad.tl.colors.b, a: sourceQuad.tl.colors.a}, - texCoords: {u: sourceQuad.tl.texCoords.u, v: sourceQuad.tl.texCoords.v}}, - bl: {vertices: {x: sourceQuad.bl.vertices.x, y: sourceQuad.bl.vertices.y, z: sourceQuad.bl.vertices.z}, - colors: {r: sourceQuad.bl.colors.r, g: sourceQuad.bl.colors.g, b: sourceQuad.bl.colors.b, a: sourceQuad.bl.colors.a}, - texCoords: {u: sourceQuad.bl.texCoords.u, v: sourceQuad.bl.texCoords.v}}, - tr: {vertices: {x: sourceQuad.tr.vertices.x, y: sourceQuad.tr.vertices.y, z: sourceQuad.tr.vertices.z}, - colors: {r: sourceQuad.tr.colors.r, g: sourceQuad.tr.colors.g, b: sourceQuad.tr.colors.b, a: sourceQuad.tr.colors.a}, - texCoords: {u: sourceQuad.tr.texCoords.u, v: sourceQuad.tr.texCoords.v}}, - br: {vertices: {x: sourceQuad.br.vertices.x, y: sourceQuad.br.vertices.y, z: sourceQuad.br.vertices.z}, - colors: {r: sourceQuad.br.colors.r, g: sourceQuad.br.colors.g, b: sourceQuad.br.colors.b, a: sourceQuad.br.colors.a}, - texCoords: {u: sourceQuad.br.texCoords.u, v: sourceQuad.br.texCoords.v}} + tl: {vertices: {x: srcTL.vertices.x, y: srcTL.vertices.y, z: srcTL.vertices.z}, + colors: {r: srcTL.colors.r, g: srcTL.colors.g, b: srcTL.colors.b, a: srcTL.colors.a}, + texCoords: {u: srcTL.texCoords.u, v: srcTL.texCoords.v}}, + bl: {vertices: {x: srcBL.vertices.x, y: srcBL.vertices.y, z: srcBL.vertices.z}, + colors: {r: srcBL.colors.r, g: srcBL.colors.g, b: srcBL.colors.b, a: srcBL.colors.a}, + texCoords: {u: srcBL.texCoords.u, v: srcBL.texCoords.v}}, + tr: {vertices: {x: srcTR.vertices.x, y: srcTR.vertices.y, z: srcTR.vertices.z}, + colors: {r: srcTR.colors.r, g: srcTR.colors.g, b: srcTR.colors.b, a: srcTR.colors.a}, + texCoords: {u: srcTR.texCoords.u, v: srcTR.texCoords.v}}, + br: {vertices: {x: srcBR.vertices.x, y: srcBR.vertices.y, z: srcBR.vertices.z}, + colors: {r: srcBR.colors.r, g: srcBR.colors.g, b: srcBR.colors.b, a: srcBR.colors.a}, + texCoords: {u: srcBR.texCoords.u, v: srcBR.texCoords.v}} }; }; @@ -1132,12 +1141,13 @@ if(cc.Browser.supportWebGL){ this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V2F_C4B_T2F.BYTES_PER_ELEMENT); this._offset = offset || 0; - this._vertices = vertices ? new cc.Vertex2F(vertices.x, vertices.y, this._arrayBuffer, this._offset) : - new cc.Vertex2F(0, 0, this._arrayBuffer, this._offset); - this._colors = colors ? new cc.Color4B(colors.r, colors.g, colors.b, colors.a, this._arrayBuffer, this._offset + cc.Vertex2F.BYTES_PER_ELEMENT) : - new cc.Color4B(0, 0, 0, 0, this._arrayBuffer, this._offset + cc.Vertex2F.BYTES_PER_ELEMENT); - this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, this._arrayBuffer, this._offset + cc.Vertex2F.BYTES_PER_ELEMENT + cc.Color4B.BYTES_PER_ELEMENT) : - new cc.Tex2F(0, 0, this._arrayBuffer, this._offset + cc.Vertex2F.BYTES_PER_ELEMENT + cc.Color4B.BYTES_PER_ELEMENT); + var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.Vertex2F.BYTES_PER_ELEMENT; + this._vertices = vertices ? new cc.Vertex2F(vertices.x, vertices.y, locArrayBuffer, locOffset) : + new cc.Vertex2F(0, 0, locArrayBuffer, locOffset); + this._colors = colors ? new cc.Color4B(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset + locElementLen) : + new cc.Color4B(0, 0, 0, 0, locArrayBuffer, locOffset + locElementLen); + this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, locArrayBuffer, locOffset + locElementLen + cc.Color4B.BYTES_PER_ELEMENT) : + new cc.Tex2F(0, 0, locArrayBuffer, locOffset + locElementLen + cc.Color4B.BYTES_PER_ELEMENT); }; cc.V2F_C4B_T2F.BYTES_PER_ELEMENT = 20; Object.defineProperties(cc.V2F_C4B_T2F.prototype, { @@ -1156,10 +1166,11 @@ if(cc.Browser.supportWebGL){ return this._colors; }, set: function (colorValue) { - this._colors.r = colorValue.r; - this._colors.g = colorValue.g; - this._colors.b = colorValue.b; - this._colors.a = colorValue.a; + var locColors = this._colors; + locColors.r = colorValue.r; + locColors.g = colorValue.g; + locColors.b = colorValue.b; + locColors.a = colorValue.a; }, enumerable: true }, @@ -1180,12 +1191,13 @@ if(cc.Browser.supportWebGL){ this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT); this._offset = offset || 0; - this._a = a ? new cc.V2F_C4B_T2F(a.vertices, a.colors, a.texCoords, this._arrayBuffer, this._offset) : - new cc.V2F_C4B_T2F(null, null, null, this._arrayBuffer, this._offset); - this._b = b ? new cc.V2F_C4B_T2F(b.vertices, b.colors, b.texCoords, this._arrayBuffer, this._offset + cc.V2F_C4B_T2F.BYTES_PER_ELEMENT) : - new cc.V2F_C4B_T2F(null, null, null, this._arrayBuffer, this._offset + cc.V2F_C4B_T2F.BYTES_PER_ELEMENT); - this._c = c ? new cc.V2F_C4B_T2F(c.vertices, c.colors, c.texCoords, this._arrayBuffer, this._offset + cc.V2F_C4B_T2F.BYTES_PER_ELEMENT * 2) : - new cc.V2F_C4B_T2F(null, null, null, this._arrayBuffer, this._offset + cc.V2F_C4B_T2F.BYTES_PER_ELEMENT * 2); + var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT; + this._a = a ? new cc.V2F_C4B_T2F(a.vertices, a.colors, a.texCoords, locArrayBuffer, locOffset) : + new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset); + this._b = b ? new cc.V2F_C4B_T2F(b.vertices, b.colors, b.texCoords, locArrayBuffer, locOffset + locElementLen) : + new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen); + this._c = c ? new cc.V2F_C4B_T2F(c.vertices, c.colors, c.texCoords, locArrayBuffer, locOffset + locElementLen * 2) : + new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen * 2); }; cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT = 60; Object.defineProperties(cc.V2F_C4B_T2F_Triangle.prototype, { @@ -1194,9 +1206,10 @@ if(cc.Browser.supportWebGL){ return this._a; }, set: function (aValue) { - this._a.vertices = aValue.vertices; - this._a.colors = aValue.colors; - this._a.texCoords = aValue.texCoords; + var locA = this._a; + locA.vertices = aValue.vertices; + locA.colors = aValue.colors; + locA.texCoords = aValue.texCoords; }, enumerable: true }, @@ -1205,9 +1218,10 @@ if(cc.Browser.supportWebGL){ return this._b; }, set: function (bValue) { - this._b.vertices = bValue.vertices; - this._b.colors = bValue.colors; - this._b.texCoords = bValue.texCoords; + var locB = this._b; + locB.vertices = bValue.vertices; + locB.colors = bValue.colors; + locB.texCoords = bValue.texCoords; }, enumerable: true }, @@ -1216,9 +1230,10 @@ if(cc.Browser.supportWebGL){ return this._c; }, set: function (cValue) { - this._c.vertices = cValue.vertices; - this._c.colors = cValue.colors; - this._c.texCoords = cValue.texCoords; + var locC = this._c; + locC.vertices = cValue.vertices; + locC.colors = cValue.colors; + locC.texCoords = cValue.texCoords; }, enumerable: true } @@ -1311,8 +1326,9 @@ cc._Dictionary = cc.Class.extend({ if (key == null) return null; - for (var keyId in this._keyMapTb) { - if (this._keyMapTb[keyId] === key) + var locKeyMapTb = this._keyMapTb; + for (var keyId in locKeyMapTb) { + if (locKeyMapTb[keyId] === key) return this._valueMapTb[keyId]; } return null; @@ -1326,10 +1342,11 @@ cc._Dictionary = cc.Class.extend({ if (key == null) return; - for (var keyId in this._keyMapTb) { - if (this._keyMapTb[keyId] === key) { + var locKeyMapTb = this._keyMapTb; + for (var keyId in locKeyMapTb) { + if (locKeyMapTb[keyId] === key) { delete this._valueMapTb[keyId]; - delete this._keyMapTb[keyId]; + delete locKeyMapTb[keyId]; return; } } @@ -1344,9 +1361,9 @@ cc._Dictionary = cc.Class.extend({ }, allKeys: function () { - var keyArr = []; - for (var key in this._keyMapTb) - keyArr.push(this._keyMapTb[key]); + var keyArr = [], locKeyMapTb = this._keyMapTb; + for (var key in locKeyMapTb) + keyArr.push(locKeyMapTb[key]); return keyArr; }, diff --git a/cocos2d/platform/Sys.js b/cocos2d/platform/Sys.js index 285a7dfc63..e3bc7431de 100644 --- a/cocos2d/platform/Sys.js +++ b/cocos2d/platform/Sys.js @@ -51,7 +51,7 @@ Object.defineProperties(sys, if(cc.Browser.supportWebGL) capabilities["opengl"] = true; - if( 'ontouchstart' in document.documentElement ) + if( 'ontouchstart' in document.documentElement || window.navigator.msPointerEnabled) capabilities["touches"] = true; else if( 'onmouseup' in document.documentElement ) diff --git a/cocos2d/platform/jsloader.js b/cocos2d/platform/jsloader.js index 33ca17c25b..19bfa526ab 100644 --- a/cocos2d/platform/jsloader.js +++ b/cocos2d/platform/jsloader.js @@ -38,7 +38,7 @@ 'platform/CCMacro.js', 'platform/CCFileUtils.js', 'platform/CCTypes.js', - 'platform/CCAccelerometer.js', + 'platform/CCAccelerometer.js', 'platform/zlib.min.js', 'platform/CCEGLView.js', 'platform/CCImage.js', @@ -110,7 +110,6 @@ 'label_nodes/CCLabelTTF.js', 'label_nodes/CCLabelBMFont.js', 'particle_nodes/CCParticleSystem.js', - 'particle_nodes/CCParticleSystemQuad.js', 'particle_nodes/CCParticleExamples.js', 'particle_nodes/CCParticleBatchNode.js', 'touch_dispatcher/CCTouchDelegateProtocol.js', @@ -174,27 +173,25 @@ '../extensions/CCBReader/CCBRelativePositioning.js', '../extensions/CCBReader/CCBAnimationManager.js', '../extensions/CCEditBox.js', - '../extensions/CCArmature/utils/CCArmatureDefine.js', - '../extensions/CCArmature/utils/CCDataReaderHelper.js', - '../extensions/CCArmature/utils/CCSpriteFrameCacheHelper.js', - '../extensions/CCArmature/utils/CCTransformHelp.js', - '../extensions/CCArmature/utils/CCTweenFunction.js', - '../extensions/CCArmature/utils/CCUtilMath.js', - '../extensions/CCArmature/utils/CSArmatureDataManager.js', - '../extensions/CCArmature/datas/CCDatas.js', - '../extensions/CCArmature/display/CCBatchNode.js', - '../extensions/CCArmature/display/CCDecorativeDisplay.js', - '../extensions/CCArmature/display/CCDisplayFactory.js', - '../extensions/CCArmature/display/CCDisplayManager.js', - '../extensions/CCArmature/display/CCShaderNode.js', - '../extensions/CCArmature/display/CCSkin.js', - '../extensions/CCArmature/animation/CCProcessBase.js', - '../extensions/CCArmature/animation/CCArmatureAnimation.js', - '../extensions/CCArmature/animation/CCTween.js', - '../extensions/CCArmature/physics/CCColliderDetector.js', - '../extensions/CCArmature/physics/CCPhysicsWorld.js', - '../extensions/CCArmature/CCArmature.js', - '../extensions/CCArmature/CCBone.js' + '../extensions/CocoStudio/Armature/utils/CCArmatureDefine.js', + '../extensions/CocoStudio/Armature/utils/CCDataReaderHelper.js', + '../extensions/CocoStudio/Armature/utils/CCSpriteFrameCacheHelper.js', + '../extensions/CocoStudio/Armature/utils/CCTransformHelp.js', + '../extensions/CocoStudio/Armature/utils/CCTweenFunction.js', + '../extensions/CocoStudio/Armature/utils/CCUtilMath.js', + '../extensions/CocoStudio/Armature/utils/CSArmatureDataManager.js', + '../extensions/CocoStudio/Armature/datas/CCDatas.js', + '../extensions/CocoStudio/Armature/display/CCBatchNode.js', + '../extensions/CocoStudio/Armature/display/CCDecorativeDisplay.js', + '../extensions/CocoStudio/Armature/display/CCDisplayFactory.js', + '../extensions/CocoStudio/Armature/display/CCDisplayManager.js', + '../extensions/CocoStudio/Armature/display/CCSkin.js', + '../extensions/CocoStudio/Armature/animation/CCProcessBase.js', + '../extensions/CocoStudio/Armature/animation/CCArmatureAnimation.js', + '../extensions/CocoStudio/Armature/animation/CCTween.js', + '../extensions/CocoStudio/Armature/physics/CCColliderDetector.js', + '../extensions/CocoStudio/Armature/CCArmature.js', + '../extensions/CocoStudio/Armature/CCBone.js' ]); } @@ -248,23 +245,47 @@ } + var loadJsImg = document.getElementById("cocos2d_loadJsImg"); + if(!loadJsImg){ + loadJsImg = new Image(); + loadJsImg.src = "data:image/gif;base64,R0lGODlhEAAQALMNAD8/P7+/vyoqKlVVVX9/fxUVFUBAQGBgYMDAwC8vL5CQkP///wAAAP///wAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFAAANACwAAAAAEAAQAAAEO5DJSau9OOvNex0IMnDIsiCkiW6g6BmKYlBFkhSUEgQKlQCARG6nEBwOgl+QApMdCIRD7YZ5RjlGpCUCACH5BAUAAA0ALAAAAgAOAA4AAAQ6kLGB0JA4M7QW0hrngRllkYyhKAYqKUGguAws0ypLS8JxCLQDgXAIDg+FRKIA6v0SAECCBpXSkstMBAAh+QQFAAANACwAAAAACgAQAAAEOJDJORAac6K1kDSKYmydpASBUl0mqmRfaGTCcQgwcxDEke+9XO2WkxQSiUIuAQAkls0n7JgsWq8RACH5BAUAAA0ALAAAAAAOAA4AAAQ6kMlplDIzTxWC0oxwHALnDQgySAdBHNWFLAvCukc215JIZihVIZEogDIJACBxnCSXTcmwGK1ar1hrBAAh+QQFAAANACwAAAAAEAAKAAAEN5DJKc4RM+tDyNFTkSQF5xmKYmQJACTVpQSBwrpJNteZSGYoFWjIGCAQA2IGsVgglBOmEyoxIiMAIfkEBQAADQAsAgAAAA4ADgAABDmQSVZSKjPPBEDSGucJxyGA1XUQxAFma/tOpDlnhqIYN6MEAUXvF+zldrMBAjHoIRYLhBMqvSmZkggAIfkEBQAADQAsBgAAAAoAEAAABDeQyUmrnSWlYhMASfeFVbZdjHAcgnUQxOHCcqWylKEohqUEAYVkgEAMfkEJYrFA6HhKJsJCNFoiACH5BAUAAA0ALAIAAgAOAA4AAAQ3kMlJq704611SKloCAEk4lln3DQgyUMJxCBKyLAh1EMRR3wiDQmHY9SQslyIQUMRmlmVTIyRaIgA7"; + + var canvasNode = document.getElementById(c.tag); + canvasNode.style.backgroundColor = "black"; + canvasNode.parentNode.appendChild(loadJsImg); + + var canvasStyle = getComputedStyle?getComputedStyle(canvasNode):canvasNode.currentStyle; + loadJsImg.style.left = canvasNode.offsetLeft + (parseFloat(canvasStyle.width) - loadJsImg.width)/2 + "px"; + loadJsImg.style.top = canvasNode.offsetTop + (parseFloat(canvasStyle.height) - loadJsImg.height)/2 + "px"; + loadJsImg.style.position = "absolute"; + } + + var updateLoading = function(p){ + if(p>=1) { + loadJsImg.parentNode.removeChild(loadJsImg); + } + }; + var loaded = 0; var que = engine.concat(c.appFiles); que.push('main.js'); + if (navigator.userAgent.indexOf("Trident/5") > -1) { //ie9 - this.serial = -1; + var i = -1; var loadNext = function () { - var s = this.serial + 1; - if (s < que.length) { + i++; + if (i < que.length) { var f = d.createElement('script'); - f.src = que[s]; - f.serial = s; - f.onload = loadNext; + f.src = que[i]; + f.addEventListener('load',function(){ + loadNext(); + updateLoading(loaded / que.length); + this.removeEventListener('load', arguments.callee, false); + },false); d.body.appendChild(f); - //TODO: code for updating progress bar - //p = s / (que.length - 1); } + updateLoading(i / (que.length - 1)); }; loadNext(); } @@ -273,14 +294,12 @@ var s = d.createElement('script'); s.async = false; s.src = f; - s.onload = function () { + s.addEventListener('load',function(){ loaded++; - //TODO: code for updating progress bar - //p = loaded / que.length; - }; + updateLoading(loaded / que.length); + this.removeEventListener('load', arguments.callee, false); + },false); d.body.appendChild(s); - que[i] = s; - }); } })(); diff --git a/cocos2d/platform/miniFramework.js b/cocos2d/platform/miniFramework.js index ba8eb80354..d10f19fc6c 100644 --- a/cocos2d/platform/miniFramework.js +++ b/cocos2d/platform/miniFramework.js @@ -59,7 +59,7 @@ cc.Browser = {}; cc.Browser.isMobile = (cc.Browser.ua.indexOf('mobile') != -1 || cc.Browser.ua.indexOf('android') != -1); cc.Browser.type = (function () { var browserTypes = cc.Browser.ua.match(/micromessenger|qqbrowser|mqqbrowser|ucbrowser|360browser|baidubrowser|maxthon|ie|opera|firefox/) || cc.Browser.ua.match(/chrome|safari/); - if (browserTypes.length > 0) { + if (browserTypes && browserTypes.length > 0) { var el = browserTypes[0]; if (el == 'micromessenger') { return 'wechat'; @@ -77,7 +77,7 @@ cc.Browser = {}; // check supportWebGL item cc._userRenderMode = parseInt(c["renderMode"]) || 0; - if (cc._userRenderMode === 1) { + if (cc._userRenderMode === 1 || (cc._userRenderMode === 0 && cc.Browser.isMobile)) { //canvas only cc.Browser.supportWebGL = false; } else { diff --git a/cocos2d/sprite_nodes/CCAnimation.js b/cocos2d/sprite_nodes/CCAnimation.js index 1e2b817d96..912b042855 100644 --- a/cocos2d/sprite_nodes/CCAnimation.js +++ b/cocos2d/sprite_nodes/CCAnimation.js @@ -67,9 +67,9 @@ cc.AnimationFrame = cc.Class.extend(/** @lends cc.AnimationFrame# */{ * @param {object} userInfo */ initWithSpriteFrame:function (spriteFrame, delayUnits, userInfo) { - this.setSpriteFrame(spriteFrame); - this.setDelayUnits(delayUnits); - this.setUserInfo(userInfo); + this._spriteFrame = spriteFrame; + this._delayPerUnit = delayUnits; + this._userInfo = userInfo; return true; }, @@ -199,11 +199,7 @@ cc.Animation = cc.Class.extend(/** @lends cc.Animation# */{ addSpriteFrameWithFile:function (fileName) { var texture = cc.TextureCache.getInstance().addImage(fileName); var rect = cc.RectZero(); - if ((texture instanceof HTMLImageElement) || (texture instanceof HTMLCanvasElement)) { - rect.size = cc.size(texture.width, texture.height); - } else { - rect.size = texture.getContentSize(); - } + rect.size = texture.getContentSize(); var frame = cc.SpriteFrame.createWithTexture(texture, rect); this.addSpriteFrame(frame); }, diff --git a/cocos2d/sprite_nodes/CCAnimationCache.js b/cocos2d/sprite_nodes/CCAnimationCache.js index 5bae6e3379..f6bcf49d30 100644 --- a/cocos2d/sprite_nodes/CCAnimationCache.js +++ b/cocos2d/sprite_nodes/CCAnimationCache.js @@ -36,7 +36,6 @@ * cc.AnimationCache.getInstance().addAnimation(animation,"animation1"); */ cc.AnimationCache = cc.Class.extend(/** @lends cc.AnimationCache# */{ - /** * Adds a cc.Animation with a name. * @param {cc.Animation} animation diff --git a/cocos2d/sprite_nodes/CCSprite.js b/cocos2d/sprite_nodes/CCSprite.js index a514f31fe3..2644d0b4d6 100644 --- a/cocos2d/sprite_nodes/CCSprite.js +++ b/cocos2d/sprite_nodes/CCSprite.js @@ -25,7 +25,7 @@ ****************************************************************************/ /** - * cc.Sprite invalid index on the cc.SpriteBatchode + * cc.Sprite invalid index on the cc.SpriteBatchNode * @constant * @type Number */ @@ -166,7 +166,7 @@ cc.generateTintImage = function (texture, tintedImgCache, color, rect, renderCan rect = cc.rect(0, 0, texture.width, texture.height); var selColor; - if (color instanceof cc.Color3B) { + if (color.a == null) { // Optimization for the particle system which mainly uses c4f colors selColor = cc.c4f(color.r / 255.0, color.g / 255.0, color.b / 255, 1); } else { @@ -207,7 +207,7 @@ cc.generateTintImage = function (texture, tintedImgCache, color, rect, renderCan ctx.drawImage(tintedImgCache[2], rect.x, rect.y, w, h, 0, 0, w, h); } - if((selColor.r === 0) && (selColor.g === 0) &&(selColor.b === 0)){ + if ((selColor.r === 0) && (selColor.g === 0) && (selColor.b === 0)) { ctx.globalAlpha = a; ctx.drawImage(tintedImgCache[3], rect.x, rect.y, w, h, 0, 0, w, h); } @@ -257,14 +257,14 @@ cc.TransformValues = function (pos, scale, rotation, skew, ap, visible) { cc.RENDER_IN_SUBPIXEL = function (A) { return (0 | A); }; -if(cc.SPRITEBATCHNODE_RENDER_SUBPIXEL){ +if (cc.SPRITEBATCHNODE_RENDER_SUBPIXEL) { cc.RENDER_IN_SUBPIXEL = function (A) { return A; }; } /** - *

cc.Sprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_graphics) ) (Canvas implement)
+ *

cc.Sprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_graphics) )
* * cc.Sprite can be created with an image, or with a sub-rectangle of an image.
* @@ -292,34 +292,33 @@ if(cc.SPRITEBATCHNODE_RENDER_SUBPIXEL){ * var aSprite = new cc.Sprite(); * aSprite.initWithFile("HelloHTML5World.png",cc.rect(0,0,480,320)); */ -cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ - /// ---- common properties start ---- +cc.Sprite = cc.NodeRGBA.extend(/** @lends cc.Sprite# */{ RGBAProtocol:true, // // Data used when the sprite is rendered using a CCSpriteSheet // - _textureAtlas:null, //cc.SpriteBatchNode texture atlas + _textureAtlas:null, //cc.SpriteBatchNode texture atlas _atlasIndex:0, _batchNode:null, - _dirty:false, //Whether the sprite needs to be updated - _recursiveDirty:null, //Whether all of the sprite's children needs to be updated - _hasChildren:null, //Whether the sprite contains children - _shouldBeHidden:false, //should not be drawn because one of the ancestors is not visible + _dirty:false, //Whether the sprite needs to be updated + _recursiveDirty:null, //Whether all of the sprite's children needs to be updated + _hasChildren:null, //Whether the sprite contains children + _shouldBeHidden:false, //should not be drawn because one of the ancestors is not visible _transformToBatch:null, // // Data used when the sprite is self-rendered // - _blendFunc:null, //It's required for CCTextureProtocol inheritance - _texture:null, //cc.Texture2D object that is used to render the sprite + _blendFunc:null, //It's required for CCTextureProtocol inheritance + _texture:null, //cc.Texture2D object that is used to render the sprite // // Shared data // // texture - _rect:cc.rect(0, 0, 0, 0), //Retangle of cc.Texture2D - _rectRotated:false, //Whether the texture is rotated + _rect:cc.rect(0, 0, 0, 0), //Retangle of cc.Texture2D + _rectRotated:false, //Whether the texture is rotated // Offset Position (used by Zwoptex) _offsetPosition:null, // absolute @@ -328,8 +327,29 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ _opacityModifyRGB:false, // image is flipped - _flipX:false, //Whether the sprite is flipped horizontally or not. - _flipY:false, //Whether the sprite is flipped vertically or not. + _flippedX:false, //Whether the sprite is flipped horizontally or not. + _flippedY:false, //Whether the sprite is flipped vertically or not. + + _textureLoaded:false, + _loadedEventListeners: null, + _newTextureWhenChangeColor: null, //hack property for LabelBMFont + + textureLoaded:function(){ + return this._textureLoaded; + }, + + addLoadedEventListener:function(callback, target){ + this._loadedEventListeners.push({eventCallback:callback, eventTarget:target}); + }, + + _callLoadedEventCallbacks:function(){ + var locListeners = this._loadedEventListeners; + for(var i = 0, len = locListeners.length; i < len; i++){ + var selCallback = locListeners[i]; + selCallback.eventCallback.call(selCallback.eventTarget, this); + } + locListeners.length = 0; + }, /** * Whether or not the Sprite needs to be updated in the Atlas @@ -348,15 +368,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ }, /** - * Returns the quad (tex coords, vertex coords and color) information. (Use in WebGL model only) - * @return {null} - */ - getQuad:function () { - return null; - }, - - /** - * returns whether or not the texture rectangle is rotated + * Returns whether or not the texture rectangle is rotated. * @return {Boolean} */ isTextureRectRotated:function () { @@ -404,6 +416,22 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ this._textureAtlas = textureAtlas; }, + /** + * return the SpriteBatchNode of the cc.Sprite + * @return {cc.SpriteBatchNode} + */ + getSpriteBatchNode:function () { + return this._batchNode; + }, + + /** + * set the SpriteBatchNode of the cc.Sprite + * @param {cc.SpriteBatchNode} spriteBatchNode + */ + setSpriteBatchNode:function (spriteBatchNode) { + this._batchNode = spriteBatchNode; + }, + /** * Gets the offset position of the sprite. Calculated automatically by editors like Zwoptex. * @return {cc.Point} @@ -431,12 +459,35 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ */ initWithSpriteFrame:function (spriteFrame) { cc.Assert(spriteFrame != null, ""); + if(!spriteFrame.textureLoaded()){ + //add event listener + this._textureLoaded = false; + spriteFrame.addLoadedEventListener(this._spriteFrameLoadedCallback, this); + } var ret = this.initWithTexture(spriteFrame.getTexture(), spriteFrame.getRect()); this.setDisplayFrame(spriteFrame); return ret; }, + _spriteFrameLoadedCallback:null, + + _spriteFrameLoadedCallbackForWebGL:function(spriteFrame){ + this.setNodeDirty(); + this.setTextureRect(spriteFrame.getRect(), spriteFrame.isRotated(), spriteFrame.getOriginalSize()); + this._callLoadedEventCallbacks(); + }, + + _spriteFrameLoadedCallbackForCanvas:function(spriteFrame){ + this.setNodeDirty(); + this.setTextureRect(spriteFrame.getRect(), spriteFrame.isRotated(), spriteFrame.getOriginalSize()); + var curColor = this.getColor(); + if (curColor.r !== 255 || curColor.g !== 255 || curColor.b !== 255) + this._changeTextureColor(); + + this._callLoadedEventCallbacks(); + }, + /** * Initializes a sprite with a sprite frame name.
* A cc.SpriteFrame will be fetched from the cc.SpriteFrameCache by name.
@@ -478,18 +529,19 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ sortAllChildren:function () { if (this._reorderChildDirty) { - var j, tempItem, locChildren = this._children; + var j, tempItem, locChildren = this._children, tempChild; for (var i = 1; i < locChildren.length; i++) { tempItem = locChildren[i]; j = i - 1; + tempChild = locChildren[j]; - //continue moving element downwards while zOrder is smaller or when zOrder is the same but orderOfArrival is smaller - while (j >= 0 && ( tempItem.getZOrder() < locChildren[j].getZOrder() || ( tempItem.getZOrder() === locChildren[j].getZOrder() - && tempItem.getOrderOfArrival() < locChildren[j].getOrderOfArrival() ) )) { - locChildren[j + 1] = locChildren[j]; + //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller + while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder || + ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) { + locChildren[j + 1] = tempChild; j = j - 1; + tempChild = locChildren[j]; } - locChildren[j + 1] = tempItem; } @@ -538,10 +590,10 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ * @override */ removeAllChildren:function (cleanup) { - var locChildren = this._children; - if (this._batchNode && locChildren != null) { - for (var i = 0; i < locChildren.length; i++) - this._batchNode.removeSpriteFromAtlas(locChildren[i]); + var locChildren = this._children, locBatchNode = this._batchNode; + if (locBatchNode && locChildren != null) { + for (var i = 0, len = locChildren.length; i < len; i++) + locBatchNode.removeSpriteFromAtlas(locChildren[i]); } cc.Node.prototype.removeAllChildren.call(this, cleanup); @@ -563,8 +615,10 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ // recursively set dirty var locChildren = this._children; if (locChildren != null) { - for (var i = 0; i < locChildren.length; i++) - locChildren[i].setDirtyRecursively(true); + for (var i = 0; i < locChildren.length; i++) { + if (locChildren[i] instanceof cc.Sprite) + locChildren[i].setDirtyRecursively(true); + } } }, @@ -657,6 +711,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ *

The scale factor of the node. 1.0 is the default scale factor.
* It modifies the X and Y scale at the same time. (override cc.Node )

* @param {Number} scale + * @param {Number|null} [scaleY=] * @override */ setScale:function (scale, scaleY) { @@ -701,16 +756,16 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ */ ignoreAnchorPointForPosition:function (relative) { cc.Assert(!this._batchNode, "ignoreAnchorPointForPosition is invalid in cc.Sprite"); - cc.Node.prototype.ignoreAnchorPointForPosition.call(this,relative); + cc.Node.prototype.ignoreAnchorPointForPosition.call(this, relative); }, /** * Sets whether the sprite should be flipped horizontally or not. - * @param {Boolean} flipX true if the sprite should be flipped horizaontally, false otherwise. + * @param {Boolean} flippedX true if the sprite should be flipped horizontally, false otherwise. */ - setFlipX:function (flipX) { - if (this._flipX != flipX) { - this._flipX = flipX; + setFlippedX:function (flippedX) { + if (this._flippedX != flippedX) { + this._flippedX = flippedX; this.setTextureRect(this._rect, this._rectRotated, this._contentSize); this.setNodeDirty(); } @@ -718,11 +773,11 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ /** * Sets whether the sprite should be flipped vertically or not. - * @param {Boolean} flipY true if the sprite should be flipped vertically, flase otherwise. + * @param {Boolean} flippedY true if the sprite should be flipped vertically, false otherwise. */ - setFlipY:function (flipY) { - if (this._flipY != flipY) { - this._flipY = flipY; + setFlippedY:function (flippedY) { + if (this._flippedY != flippedY) { + this._flippedY = flippedY; this.setTextureRect(this._rect, this._rectRotated, this._contentSize); this.setNodeDirty(); } @@ -739,7 +794,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ * @return {Boolean} true if the sprite is flipped horizaontally, false otherwise. */ isFlippedX:function () { - return this._flipX; + return this._flippedX; }, /** @@ -753,20 +808,27 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ * @return {Boolean} true if the sprite is flipped vertically, flase otherwise. */ isFlippedY:function () { - return this._flipY; + return this._flippedY; }, // // RGBA protocol // - - // RGBAProtocol /** - * opacity: conforms to cc.RGBAProtocol protocol + * opacity: conforms to CCRGBAProtocol protocol * @param {Boolean} modify */ - setOpacityModifyRGB:function (modify) { - if(this._opacityModifyRGB !== modify){ + setOpacityModifyRGB:null, + + _setOpacityModifyRGBForWebGL: function (modify) { + if (this._opacityModifyRGB !== modify) { + this._opacityModifyRGB = modify; + this.updateColor(); + } + }, + + _setOpacityModifyRGBForCanvas: function (modify) { + if (this._opacityModifyRGB !== modify) { this._opacityModifyRGB = modify; this.setNodeDirty(); } @@ -780,7 +842,13 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ return this._opacityModifyRGB; }, - updateDisplayedOpacity:function(parentOpacity){ + updateDisplayedOpacity: null, + _updateDisplayedOpacityForWebGL:function (parentOpacity) { + cc.NodeRGBA.prototype.updateDisplayedOpacity.call(this, parentOpacity); + this.updateColor(); + }, + + _updateDisplayedOpacityForCanvas:function (parentOpacity) { cc.NodeRGBA.prototype.updateDisplayedOpacity.call(this, parentOpacity); this._changeTextureColor(); this.setNodeDirty(); @@ -827,62 +895,159 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ getTexture:function () { return this._texture; }, - /// ---- common properties end ---- + _quad:null, // vertex coords, texture coords and color info + _quadWebBuffer:null, + _quadDirty:false, _colorized:false, _isLighterMode:false, _originalTexture:null, /** * Constructor - * @param {String|cc.SpriteFrame|cc.SpriteBatchNode|HTMLImageElement} fileName sprite construct parameter + * @param {String|cc.SpriteFrame|cc.SpriteBatchNode|HTMLImageElement|cc.Texture2D} fileName sprite construct parameter */ - ctor:function (fileName) { + ctor: null, + + _ctorForWebGL: function (fileName) { + cc.NodeRGBA.prototype.ctor.call(this); + this._shouldBeHidden = false; + this._offsetPosition = cc.p(0, 0); + this._unflippedOffsetPositionFromCenter = cc.p(0, 0); + this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST}; + + this._quad = new cc.V3F_C4B_T2F_Quad(); + this._quadWebBuffer = cc.renderContext.createBuffer(); + this._quadDirty = true; + + this._textureLoaded = true; + this._loadedEventListeners = []; + + if (fileName) { + if (typeof(fileName) === "string") { + var frame = cc.SpriteFrameCache.getInstance().getSpriteFrame(fileName); + this.initWithSpriteFrame(frame); + } else if (typeof(fileName) === "object") { + if (fileName instanceof cc.SpriteFrame) { + this.initWithSpriteFrame(fileName); + } else if ((fileName instanceof HTMLImageElement) || (fileName instanceof HTMLCanvasElement)) { + var texture2d = new cc.Texture2D(); + texture2d.initWithElement(fileName); + texture2d.handleLoadedTexture(); + this.initWithTexture(texture2d); + } else if (fileName instanceof cc.Texture2D) { + this.initWithTexture(fileName); + } + } + } + }, + + _ctorForCanvas: function (fileName) { cc.NodeRGBA.prototype.ctor.call(this); this._shouldBeHidden = false; this._offsetPosition = cc.p(0, 0); this._unflippedOffsetPositionFromCenter = cc.p(0, 0); - this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST}; + this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST}; + + this._newTextureWhenChangeColor = false; + this._textureLoaded = true; + this._loadedEventListeners = []; if (fileName) { - if (typeof(fileName) == "string") { + if (typeof(fileName) === "string") { var frame = cc.SpriteFrameCache.getInstance().getSpriteFrame(fileName); this.initWithSpriteFrame(frame); } else if (typeof(fileName) === "object") { if (fileName instanceof cc.SpriteFrame) { this.initWithSpriteFrame(fileName); - } else if (fileName instanceof cc.SpriteBatchNode) { - if (arguments.length > 1) { - var rect = arguments[1]; - if (rect instanceof cc.Rect) - this.initWithBatchNode(fileName, rect); - } } else if ((fileName instanceof HTMLImageElement) || (fileName instanceof HTMLCanvasElement)) { - this.initWithTexture(fileName) + var texture2d = new cc.Texture2D(); + texture2d.initWithElement(fileName); + texture2d.handleLoadedTexture(); + this.initWithTexture(texture2d); + } else if (fileName instanceof cc.Texture2D) { + this.initWithTexture(fileName); } } } }, + /** + * Returns the quad (tex coords, vertex coords and color) information. + * @return {cc.V3F_C4B_T2F_Quad} + */ + getQuad:function () { + return this._quad; + }, + /** * conforms to cc.TextureProtocol protocol * @param {Number|cc.BlendFunc} src * @param {Number} dst */ - setBlendFunc:function (src, dst) { + setBlendFunc: null, + + _setBlendFuncForWebGL: function (src, dst) { + if (arguments.length == 1) + this._blendFunc = src; + else + this._blendFunc = {src: src, dst: dst}; + }, + + _setBlendFuncForCanvas: function (src, dst) { if (arguments.length == 1) this._blendFunc = src; else - this._blendFunc = {src:src, dst:dst}; - this._isLighterMode = (this._blendFunc && (this._blendFunc.src === gl.SRC_ALPHA) && (this._blendFunc.dst === gl.ONE)); + this._blendFunc = {src: src, dst: dst}; + this._isLighterMode = (this._blendFunc && + (( this._blendFunc.src == gl.SRC_ALPHA && this._blendFunc.dst == gl.ONE) || (this._blendFunc.src == gl.ONE && this._blendFunc.dst == gl.ONE))); }, /** * Initializes an empty sprite with nothing init. * @return {Boolean} */ - init:function () { - if(arguments.length > 0) + init:null, + + _initForWebGL: function () { + if (arguments.length > 0) + return this.initWithFile(arguments[0], arguments[1]); + + cc.NodeRGBA.prototype.init.call(this); + this._dirty = this._recursiveDirty = false; + this._opacityModifyRGB = true; + + this._blendFunc.src = cc.BLEND_SRC; + this._blendFunc.dst = cc.BLEND_DST; + + // update texture (calls _updateBlendFunc) + this.setTexture(null); + this._textureLoaded = true; + this._flippedX = this._flippedY = false; + + // default transform anchor: center + this.setAnchorPoint(cc.p(0.5, 0.5)); + + // zwoptex default values + this._offsetPosition = cc.PointZero(); + this._hasChildren = false; + + // Atlas: Color + var tempColor = {r: 255, g: 255, b: 255, a: 255}; + this._quad.bl.colors = tempColor; + this._quad.br.colors = tempColor; + this._quad.tl.colors = tempColor; + this._quad.tr.colors = tempColor; + this._quadDirty = true; + + // updated in "useSelfRender" + // Atlas: TexCoords + this.setTextureRect(cc.RectZero(), false, cc.SizeZero()); + return true; + }, + + _initForCanvas: function () { + if (arguments.length > 0) return this.initWithFile(arguments[0], arguments[1]); cc.NodeRGBA.prototype.init.call(this); @@ -894,7 +1059,8 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ // update texture (calls _updateBlendFunc) this.setTexture(null); - this._flipX = this._flipY = false; + this._textureLoaded = true; + this._flippedX = this._flippedY = false; // default transform anchor: center this.setAnchorPoint(cc.p(0.5, 0.5)); @@ -926,57 +1092,100 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ */ initWithFile:function (filename, rect) { cc.Assert(filename != null, "Sprite#initWithFile():Invalid filename for sprite"); - var selfPointer = this; var texture = cc.TextureCache.getInstance().textureForKey(filename); if (!texture) { - this._visible = false; - var loadImg = new Image(); - loadImg.addEventListener("load", function () { - if (!rect) { - rect = cc.rect(0, 0, loadImg.width, loadImg.height); - rect = cc.RECT_PIXELS_TO_POINTS(rect); - } - selfPointer.initWithTexture(loadImg, rect); - cc.TextureCache.getInstance().cacheImage(filename, loadImg); - selfPointer._visible = true; - }); - loadImg.addEventListener("error", function () { - cc.log("load failure:" + filename); - }); - loadImg.src = filename; - return true; + texture = cc.TextureCache.getInstance().addImage(filename); + return this.initWithTexture(texture, rect); } else { - if (texture) { - if (!rect) { - rect = cc.rect(0, 0, texture.width, texture.height); - rect = cc.RECT_PIXELS_TO_POINTS(rect); - } - return this.initWithTexture(texture, rect); + if (!rect) { + var size = texture.getContentSize(); + rect = cc.rect(0, 0, size.width, size.height); } + return this.initWithTexture(texture, rect); } - return false; }, /** - * Initializes a sprite with a texture and a rect in points, optionally rotated.
+ * Initializes a sprite with a texture and a rect in points, optionally rotated.
* After initialization, the rect used will be the size of the texture, and the offset will be (0,0). * @param {cc.Texture2D|HTMLImageElement|HTMLCanvasElement} texture A pointer to an existing CCTexture2D object. You can use a CCTexture2D object for many sprites. * @param {cc.Rect} rect Only the contents inside rect of this texture will be applied for this sprite. - * @param {Boolean} rotated Whether or not the texture rectangle is rotated. + * @param {Boolean} [rotated] Whether or not the texture rectangle is rotated. * @return {Boolean} true if the sprite is initialized properly, false otherwise. * @example * var img =cc.TextureCache.getInstance().addImage("HelloHTML5World.png"); * var mySprite = new cc.Sprite(); * mySprite.initWithTexture(img,cc.rect(0,0,480,320)); */ - initWithTexture:function (texture, rect, rotated) { + initWithTexture: null, + + _initWithTextureForWebGL: function (texture, rect, rotated) { + var argnum = arguments.length; + if (argnum == 0) + throw "Sprite.initWithTexture(): Argument must be non-nil "; + + rotated = rotated || false; + + if (!cc.NodeRGBA.prototype.init.call(this)) + return false; + + this._batchNode = null; + this._recursiveDirty = false; + this._dirty = false; + this._opacityModifyRGB = true; + + this._blendFunc.src = cc.BLEND_SRC; + this._blendFunc.dst = cc.BLEND_DST; + + this._flippedX = this._flippedY = false; + + // default transform anchor: center + this.setAnchorPoint(cc.p(0.5, 0.5)); + + // zwoptex default values + this._offsetPosition = cc.p(0, 0); + this._hasChildren = false; + + // Atlas: Color + var tmpColor = new cc.Color4B(255, 255, 255, 255); + var locQuad = this._quad; + locQuad.bl.colors = tmpColor; + locQuad.br.colors = tmpColor; + locQuad.tl.colors = tmpColor; + locQuad.tr.colors = tmpColor; + + var locTextureLoaded = texture.isLoaded(); + this._textureLoaded = locTextureLoaded; + + if (!locTextureLoaded) { + this._rectRotated = rotated || false; + this._rect = rect; + texture.addLoadedEventListener(this._textureLoadedCallback, this); + return true; + } + + if (!rect) { + rect = cc.rect(0, 0, 0, 0); + rect.size = texture.getContentSize(); + } + this.setTexture(texture); + this.setTextureRect(rect, rotated, rect.size); + + // by default use "Self Render". + // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render" + this.setBatchNode(null); + this._quadDirty = true; + return true; + }, + + _initWithTextureForCanvas: function (texture, rect, rotated) { var argnum = arguments.length; if (argnum == 0) throw "Sprite.initWithTexture(): Argument must be non-nil "; rotated = rotated || false; - if(!cc.NodeRGBA.prototype.init.call(this)) + if (!cc.NodeRGBA.prototype.init.call(this)) return false; this._batchNode = null; @@ -988,7 +1197,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ this._blendFunc.src = cc.BLEND_SRC; this._blendFunc.dst = cc.BLEND_DST; - this._flipX = this._flipY = false; + this._flippedX = this._flippedY = false; // default transform anchor: center this.setAnchorPoint(cc.p(0.5, 0.5)); @@ -997,12 +1206,19 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ this._offsetPosition = cc.p(0, 0); this._hasChildren = false; + var locTextureLoaded = texture.isLoaded(); + this._textureLoaded = locTextureLoaded; + + if (!locTextureLoaded) { + this._rectRotated = rotated || false; + this._rect = rect; + texture.addLoadedEventListener(this._textureLoadedCallback, this); + return true; + } + if (!rect) { rect = cc.rect(0, 0, 0, 0); - if ((texture instanceof HTMLImageElement) || (texture instanceof HTMLCanvasElement)) { - rect.size = cc.size(texture.width, texture.height); - rect = cc.RECT_PIXELS_TO_POINTS(rect); - } + rect.size = texture.getContentSize(); } this._originalTexture = texture; @@ -1015,13 +1231,99 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ return true; }, + _textureLoadedCallback: null, + + _textureLoadedCallbackForWebGL: function (sender) { + this._textureLoaded = true; + var locRect = this._rect; + if (!locRect) { + locRect = cc.rect(0, 0, 0, 0); + locRect.size = sender.getContentSize(); + } else if (cc._rectEqualToZero(locRect)) { + locRect.size = sender.getContentSize(); + } + + this.setTexture(sender); + this.setTextureRect(locRect, this._rectRotated, locRect.size); + + // by default use "Self Render". + // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render" + this.setBatchNode(null); + this._quadDirty = true; + this._callLoadedEventCallbacks(); + }, + + _textureLoadedCallbackForCanvas: function (sender) { + this._textureLoaded = true; + var locRect = this._rect; + if (!locRect) { + locRect = cc.rect(0, 0, 0, 0); + locRect.size = sender.getContentSize(); + } else if (cc._rectEqualToZero(locRect)) { + locRect.size = sender.getContentSize(); + } + this._originalTexture = sender; + + this.setTexture(sender); + this.setTextureRect(locRect, this._rectRotated, locRect.size); + + // by default use "Self Render". + // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render" + this.setBatchNode(null); + this._callLoadedEventCallbacks(); + }, + /** * updates the texture rect of the CCSprite in points. * @param {cc.Rect} rect a rect of texture * @param {Boolean} rotated * @param {cc.Size} untrimmedSize */ - setTextureRect:function (rect, rotated, untrimmedSize) { + setTextureRect:null, + + _setTextureRectForWebGL:function (rect, rotated, untrimmedSize) { + this._rectRotated = rotated || false; + untrimmedSize = untrimmedSize || rect.size; + + this.setContentSize(untrimmedSize); + this.setVertexRect(rect); + this._setTextureCoords(rect); + + var relativeOffset = this._unflippedOffsetPositionFromCenter; + if (this._flippedX) + relativeOffset.x = -relativeOffset.x; + if (this._flippedY) + relativeOffset.y = -relativeOffset.y; + + var locRect = this._rect; + this._offsetPosition.x = relativeOffset.x + (this._contentSize.width - locRect.width) / 2; + this._offsetPosition.y = relativeOffset.y + (this._contentSize.height - locRect.height) / 2; + + // rendering using batch node + if (this._batchNode) { + // update dirty_, don't update recursiveDirty_ + //this.setDirty(true); + this._dirty = true; + } else { + // self rendering + // Atlas: Vertex + var x1 = 0 + this._offsetPosition.x; + var y1 = 0 + this._offsetPosition.y; + var x2 = x1 + locRect.width; + var y2 = y1 + locRect.height; + + // Don't update Z. + var locQuad = this._quad; + locQuad.bl.vertices = {x:x1, y:y1, z:0}; + locQuad.br.vertices = {x:x2, y:y1, z:0}; + locQuad.tl.vertices = {x:x1, y:y2, z:0}; + locQuad.tr.vertices = {x:x2, y:y2, z:0}; + + this._quadDirty = true; + } + }, + + _setTextureRectForCanvas: function (rect, rotated, untrimmedSize) { this._rectRotated = rotated || false; untrimmedSize = untrimmedSize || rect.size; @@ -1029,9 +1331,9 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ this.setVertexRect(rect); var relativeOffset = this._unflippedOffsetPositionFromCenter; - if (this._flipX) + if (this._flippedX) relativeOffset.x = -relativeOffset.x; - if (this._flipY) + if (this._flippedY) relativeOffset.y = -relativeOffset.y; this._offsetPosition.x = relativeOffset.x + (this._contentSize.width - this._rect.width) / 2; this._offsetPosition.y = relativeOffset.y + (this._contentSize.height - this._rect.height) / 2; @@ -1048,1262 +1350,48 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{ /** * updates the quad according the the rotation, position, scale values. */ - updateTransform:function () { + updateTransform: null, + + _updateTransformForWebGL: function () { //cc.Assert(this._batchNode, "updateTransform is only valid when cc.Sprite is being rendered using an cc.SpriteBatchNode"); // recaculate matrix only if it is dirty if (this.isDirty()) { + var locQuad = this._quad, locParent = this._parent; // If it is not visible, or one of its ancestors is not visible, then do nothing: - if (!this._visible || ( this._parent && this._parent != this._batchNode && this._parent._shouldBeHidden)) { + if (!this._visible || ( locParent && locParent != this._batchNode && locParent._shouldBeHidden)) { + locQuad.br.vertices = {x: 0, y: 0, z: 0}; + locQuad.tl.vertices = {x: 0, y: 0, z: 0}; + locQuad.tr.vertices = {x: 0, y: 0, z: 0}; + locQuad.bl.vertices = {x: 0, y: 0, z: 0}; this._shouldBeHidden = true; } else { this._shouldBeHidden = false; - if (!this._parent || this._parent == this._batchNode) { + if (!locParent || locParent == this._batchNode) { this._transformToBatch = this.nodeToParentTransform(); } else { //cc.Assert(this._parent instanceof cc.Sprite, "Logic error in CCSprite. Parent must be a CCSprite"); - this._transformToBatch = cc.AffineTransformConcat(this.nodeToParentTransform(), this._parent._transformToBatch); - } - } - this._recursiveDirty = false; - this.setDirty(false); - } - - // recursively iterate over children - if (this._hasChildren) - this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.updateTransform); - }, - - /** - * Add child to sprite (override cc.Node ) - * @param {cc.Sprite} child - * @param {Number} zOrder child's zOrder - * @param {String} tag child's tag - * @override - */ - addChild:function (child, zOrder, tag) { - cc.Assert(child != null, "Argument must be non-NULL"); - if (zOrder == null) - zOrder = child._zOrder; - if (tag == null) - tag = child._tag; - - //cc.Node already sets isReorderChildDirty_ so this needs to be after batchNode check - cc.Node.prototype.addChild.call(this, child, zOrder, tag); - this._hasChildren = true; - }, - - /** - * opacity setter - * @param {Number} opacity - */ - setOpacity:function (opacity) { - cc.NodeRGBA.prototype.setOpacity.call(this, opacity); - this.setNodeDirty(); - }, - - /** - * color setter - * @param {cc.Color3B} color3 - */ - setColor:function (color3) { - var curColor = this.getColor(); - if ((curColor.r === color3.r) && (curColor.g === color3.g) && (curColor.b === color3.b)) - return; - - cc.NodeRGBA.prototype.setColor.call(this, color3); - this._changeTextureColor(); - this.setNodeDirty(); - }, - - updateDisplayedColor:function(parentColor){ - cc.NodeRGBA.prototype.updateDisplayedColor.call(this, parentColor); - this._changeTextureColor(); - this.setNodeDirty(); - }, - - // Frames - /** - * Sets a new display frame to the cc.Sprite. - * @param {cc.SpriteFrame} newFrame - */ - setDisplayFrame:function (newFrame) { - this.setNodeDirty(); - this._unflippedOffsetPositionFromCenter = newFrame.getOffset(); - var pNewTexture = newFrame.getTexture(); - // update texture before updating texture rect - if (pNewTexture != this._texture) - this.setTexture(pNewTexture); - - // update rect - this._rectRotated = newFrame.isRotated(); - - if (this._rectRotated) - this._originalTexture = pNewTexture; - - this.setTextureRect(newFrame.getRect(), this._rectRotated, newFrame.getOriginalSize()); - this._colorized = false; - var curColor = this.getColor(); - if (curColor.r !== 255 || curColor.g !== 255 || curColor.b !== 255) - this._changeTextureColor(); - }, - - /** - * Returns whether or not a cc.SpriteFrame is being displayed - * @param {cc.SpriteFrame} frame - * @return {Boolean} - */ - isFrameDisplayed:function (frame) { - if (frame.getTexture() != this._texture) - return false; - return cc.rectEqualToRect(frame.getRect(), this._rect); - }, - - /** - * Returns the current displayed frame. - * @return {cc.SpriteFrame} - */ - displayFrame:function () { - return cc.SpriteFrame._frameWithTextureForCanvas(this._texture, - cc.RECT_POINTS_TO_PIXELS(this._rect), - this._rectRotated, - cc.POINT_POINTS_TO_PIXELS(this._unflippedOffsetPositionFromCenter), - cc.SIZE_POINTS_TO_PIXELS(this._contentSize)); - }, - - /** - * Sets the batch node to sprite - * @param {cc.SpriteBatchNode|null} spriteBatchNode - * @example - * var batch = cc.SpriteBatchNode.create("Images/grossini_dance_atlas.png", 15); - * var sprite = cc.Sprite.createWithTexture(batch.getTexture(), cc.RectMake(0, 0, 57, 57)); - * batch.addChild(sprite); - * layer.addChild(batch); - */ - setBatchNode:function (spriteBatchNode) { - this._batchNode = spriteBatchNode; // weak reference - - // self render - if (!this._batchNode) { - this._atlasIndex = cc.SPRITE_INDEX_NOT_INITIALIZED; - this.setTextureAtlas(null); - this._recursiveDirty = false; - this.setDirty(false); - } else { - // using batch - this._transformToBatch = cc.AffineTransformIdentity(); - this.setTextureAtlas(this._batchNode.getTextureAtlas()); // weak ref - } - }, - - // CCTextureProtocol - /** - * Texture of sprite setter - * @param {HTMLImageElement|HTMLCanvasElement|cc.Texture2D} texture - */ - setTexture:function (texture) { - // CCSprite: setTexture doesn't work when the sprite is rendered using a CCSpriteSheet - cc.Assert(!texture || texture instanceof HTMLImageElement || texture instanceof HTMLCanvasElement, "setTexture expects a CCTexture2D. Invalid argument"); - - if (this._texture != texture) { - if (texture instanceof HTMLImageElement) { - if (!this._rect || cc.rectEqualToRect(this._rect, cc.RectZero())) { - this._rect = cc.rect(0, 0, texture.width, texture.height); - this._rect = cc.RECT_PIXELS_TO_POINTS(this._rect); - } - this._originalTexture = texture; - } - this._texture = texture; - } - }, - - _changeTextureColor:function () { - if (this.getTexture()) { - var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(this._originalTexture); - if (cacheTextureForColor) { - this._colorized = true; - //generate color texture cache - var rect = cc.RECT_POINTS_TO_PIXELS(this._rect); - if (this._texture instanceof HTMLCanvasElement && !this._rectRotated) - cc.generateTintImage(this.getTexture(), cacheTextureForColor, this._displayedColor, rect, this._texture); - else { - var colorTexture = cc.generateTintImage(this.getTexture(), cacheTextureForColor, this._displayedColor, rect); - this.setTexture(colorTexture); - } - } - } - }, - - /** - * draw sprite to canvas - * @param {CanvasContext} ctx 2d context of canvas - */ - draw:function (ctx) { - var context = ctx || cc.renderContext; - if (this._isLighterMode) - context.globalCompositeOperation = 'lighter'; - - context.globalAlpha = this._realOpacity / 255; - var locRect = this._rect; - var flipXOffset = 0 | (this._offsetPosition.x), flipYOffset = -this._offsetPosition.y - locRect.height; - if (this._flipX) { - flipXOffset = -this._offsetPosition.x - locRect.width; - context.scale(-1, 1); - } - if (this._flipY) { - flipYOffset = this._offsetPosition.y; - context.scale(1, -1); - } - if (this._texture) { - var scaleFactor = cc.CONTENT_SCALE_FACTOR(); - if (this._colorized) { - context.drawImage(this._texture, - 0, 0, locRect.width * scaleFactor, locRect.height * scaleFactor, - flipXOffset, flipYOffset, locRect.width, locRect.height); - } else { - context.drawImage(this._texture, - locRect.x * scaleFactor, locRect.y * scaleFactor, locRect.width * scaleFactor, locRect.height * scaleFactor, - flipXOffset, flipYOffset, locRect.width, locRect.height); - } - } else if (this._contentSize.width !== 0) { - var curColor = this.getColor(); - context.fillStyle = "rgba(" + curColor.r + "," + curColor.g + "," + curColor.b + ",1)"; - context.fillRect(flipXOffset, flipYOffset, this._contentSize.width, this._contentSize.height); - } - - if (cc.SPRITE_DEBUG_DRAW === 1) { - // draw bounding box - context.strokeStyle = "rgba(0,255,0,1)"; - flipYOffset = -flipYOffset; - var vertices1 = [cc.p(flipXOffset, flipYOffset), cc.p(flipXOffset + locRect.width, flipYOffset), cc.p(flipXOffset + locRect.width, flipYOffset - locRect.height), - cc.p(flipXOffset, flipYOffset - locRect.height)]; - cc.drawingUtil.drawPoly(vertices1, 4, true); - } else if (cc.SPRITE_DEBUG_DRAW === 2) { - // draw texture box - context.strokeStyle = "rgba(0,255,0,1)"; - var drawSize = this._rect.size; - flipYOffset = -flipYOffset; - var vertices2 = [cc.p(flipXOffset, flipYOffset), cc.p(flipXOffset + drawSize.width, flipYOffset), - cc.p(flipXOffset + drawSize.width, flipYOffset - drawSize.height), cc.p(flipXOffset, flipYOffset - drawSize.height)]; - cc.drawingUtil.drawPoly(vertices2, 4, true); - } - cc.g_NumberOfDraws++; - } -}); - -/** - *

- * Creates a sprite with an exsiting texture contained
- * After creation, the rect will be the size of the texture, and the offset will be (0,0). - *

- * @constructs - * @param {HTMLImageElement|HTMLCanvasElement|cc.Texture2D} texture A pointer to an existing CCTexture2D object. You can use a CCTexture2D object for many sprites. - * @param {cc.Rect} rect Only the contents inside the rect of this texture will be applied for this sprite. - * @param {cc.Point} offset offset of the texture - * @return {cc.Sprite} A valid sprite object - * @example - * //get an image - * var img = cc.TextureCache.getInstance().addImage("HelloHTML5World.png"); - * - * //create a sprite with texture - * var sprite1 = cc.Sprite.createWithTexture(img); - * - * //create a sprite with texture and rect - * var sprite2 = cc.Sprite.createWithTexture(img, cc.rect(0,0,480,320)); - * - * //create a sprite with texture and rect and offset - * var sprite3 = cc.Sprite.createWithTexture(img, cc.rect(0,0,480,320),cc.p(0,0)); - */ -cc.SpriteCanvas.createWithTexture = function (texture, rect, offset) { - var argnum = arguments.length; - var sprite = new cc.SpriteCanvas(); - switch (argnum) { - case 1: - /** Creates an sprite with a texture. - The rect used will be the size of the texture. - The offset will be (0,0). - */ - if (sprite && sprite.initWithTexture(texture)) { - return sprite; - } - return null; - break; - - case 2: - /** Creates an sprite with a texture and a rect. - The offset will be (0,0). - */ - if (sprite && sprite.initWithTexture(texture, rect)) { - return sprite; - } - return null; - break; - - case 3: - /** Creates an sprite with a texture, a rect and offset. */ - // not implement - cc.Assert(0, ""); - return null; - break; - - default: - throw "Sprite.createWithTexture(): Argument must be non-nil "; - break; - } -}; - -/** - * Create a sprite with filename and rect - * @constructs - * @param {String} fileName The string which indicates a path to image file, e.g., "scene1/monster.png". - * @param {cc.Rect} rect Only the contents inside rect of pszFileName's texture will be applied for this sprite. - * @return {cc.Sprite} A valid sprite object - * @example - * //create a sprite with filename - * var sprite1 = cc.Sprite.create("HelloHTML5World.png"); - * - * //create a sprite with filename and rect - * var sprite2 = cc.Sprite.create("HelloHTML5World.png",cc.rect(0,0,480,320)); - */ -cc.SpriteCanvas.create = function (fileName, rect) { - var argnum = arguments.length; - var sprite = new cc.SpriteCanvas(); - if (argnum === 0) { - if (sprite.init()) - return sprite; - } else { - if (sprite && sprite.init(fileName, rect)) - return sprite; - } - return null; -}; - -/** - * Creates a sprite with a sprite frame name - * @param {String} spriteFrameName name - * @return {cc.Sprite} A valid sprite object - * @example - * - * //create a sprite with a sprite frame - * var sprite = cc.Sprite.createWithSpriteFrameName('grossini_dance_01.png'); - */ -cc.SpriteCanvas.createWithSpriteFrameName = function (spriteFrameName) { - var spriteFrame = null; - if (typeof(spriteFrameName) == 'string') { - spriteFrame = cc.SpriteFrameCache.getInstance().getSpriteFrame(spriteFrameName); - if (!spriteFrame) { - cc.log("Invalid spriteFrameName: " + spriteFrameName); - return null; - } - } else { - cc.log("Invalid argument. Expecting string."); - return null; - } - var sprite = new cc.SpriteCanvas(); - if (sprite && sprite.initWithSpriteFrame(spriteFrame)) { - return sprite; - } - return null; -}; - -/** - * Creates a sprite with a sprite frame. - * @param {cc.SpriteFrame} spriteFrame A sprite frame which involves a texture and a rect - * @return {cc.Sprite} A valid sprite object - * @example - * //get a sprite frame - * var spriteFrame = cc.SpriteFrameCache.getInstance().getSpriteFrame("grossini_dance_01.png"); - * - * //create a sprite with a sprite frame - * var sprite = cc.Sprite.createWithSpriteFrame(spriteFrame); - */ -cc.SpriteCanvas.createWithSpriteFrame = function (spriteFrame) { - var sprite = new cc.SpriteCanvas(); - if (sprite && sprite.initWithSpriteFrame(spriteFrame)) { - return sprite; - } - return null; -}; - -/** - *

cc.Sprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_graphics) ) (WebGL implement)
- * - * cc.Sprite can be created with an image, or with a sub-rectangle of an image.
- * - * If the parent or any of its ancestors is a cc.SpriteBatchNode then the following features/limitations are valid
- * - Features when the parent is a cc.BatchNode:
- * - MUCH faster rendering, specially if the cc.SpriteBatchNode has many children. All the children will be drawn in a single batch.
- * - * - Limitations
- * - Camera is not supported yet (eg: CCOrbitCamera action doesn't work)
- * - GridBase actions are not supported (eg: CCLens, CCRipple, CCTwirl)
- * - The Alias/Antialias property belongs to CCSpriteBatchNode, so you can't individually set the aliased property.
- * - The Blending function property belongs to CCSpriteBatchNode, so you can't individually set the blending function property.
- * - Parallax scroller is not supported, but can be simulated with a "proxy" sprite.
- * - * If the parent is an standard cc.Node, then cc.Sprite behaves like any other cc.Node:
- * - It supports blending functions
- * - It supports aliasing / antialiasing
- * - But the rendering will be slower: 1 draw per children.
- * - * The default anchorPoint in cc.Sprite is (0.5, 0.5).

- * @class - * @extends cc.NodeRGBA - * - * @example - * var aSprite = new cc.Sprite(); - * aSprite.initWithFile("HelloHTML5World.png",cc.rect(0,0,480,320)); - */ -cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ - /// ---- common properties start ---- - RGBAProtocol:true, - // - // Data used when the sprite is rendered using a CCSpriteSheet - // - _textureAtlas:null, //cc.SpriteBatchNode texture atlas - - _atlasIndex:0, - _batchNode:null, - _dirty:false, //Whether the sprite needs to be updated - _recursiveDirty:null, //Whether all of the sprite's children needs to be updated - _hasChildren:null, //Whether the sprite contains children - _shouldBeHidden:false, //should not be drawn because one of the ancestors is not visible - _transformToBatch:null, - - // - // Data used when the sprite is self-rendered - // - _blendFunc:null, //It's required for CCTextureProtocol inheritance - _texture:null, //cc.Texture2D object that is used to render the sprite - - // - // Shared data - // - // texture - _rect:cc.rect(0, 0, 0, 0), //Retangle of cc.Texture2D - _rectRotated:false, //Whether the texture is rotated - - // Offset Position (used by Zwoptex) - _offsetPosition:null, // absolute - _unflippedOffsetPositionFromCenter:null, - - // opacity and RGB protocol - _opacityModifyRGB:false, - - // image is flipped - _flipX:false, //Whether the sprite is flipped horizontally or not. - _flipY:false, //Whether the sprite is flipped vertically or not. - - /** - * Whether or not the Sprite needs to be updated in the Atlas - * @return {Boolean} true if the sprite needs to be updated in the Atlas, false otherwise. - */ - isDirty:function () { - return this._dirty; - }, - - /** - * Makes the Sprite to be updated in the Atlas. - * @param {Boolean} bDirty - */ - setDirty:function (bDirty) { - this._dirty = bDirty; - }, - - /** - * Returns whether or not the texture rectangle is rotated. - * @return {Boolean} - */ - isTextureRectRotated:function () { - return this._rectRotated; - }, - - /** - * Returns the index used on the TextureAtlas. - * @return {Number} - */ - getAtlasIndex:function () { - return this._atlasIndex; - }, - - /** - * Set the index used on the TextureAtlas. - * @warning Don't modify this value unless you know what you are doing - * @param {Number} atlasIndex - */ - setAtlasIndex:function (atlasIndex) { - this._atlasIndex = atlasIndex; - }, - - /** - * returns the rect of the cc.Sprite in points - * @return {cc.Rect} - */ - getTextureRect:function () { - return cc.rect(this._rect.x, this._rect.y, this._rect.width, this._rect.height); - }, - - /** - * Gets the weak reference of the cc.TextureAtlas when the sprite is rendered using via cc.SpriteBatchNode - * @return {cc.TextureAtlas} - */ - getTextureAtlas:function () { - return this._textureAtlas; - }, - - /** - * Sets the weak reference of the cc.TextureAtlas when the sprite is rendered using via cc.SpriteBatchNode - * @param {cc.TextureAtlas} textureAtlas - */ - setTextureAtlas:function (textureAtlas) { - this._textureAtlas = textureAtlas; - }, - - /** - * return the SpriteBatchNode of the cc.Sprite - * @return {cc.SpriteBatchNode} - */ - getSpriteBatchNode:function () { - return this._batchNode; - }, - - /** - * set the SpriteBatchNode of the cc.Sprite - * @param {cc.SpriteBatchNode} spriteBatchNode - */ - setSpriteBatchNode:function (spriteBatchNode) { - this._batchNode = spriteBatchNode; - }, - - /** - * Gets the offset position of the sprite. Calculated automatically by editors like Zwoptex. - * @return {cc.Point} - */ - getOffsetPosition:function () { - return cc.p(this._offsetPosition.x, this._offsetPosition.y); - }, - - /** - * conforms to cc.TextureProtocol protocol - * @return {cc.BlendFunc} - */ - getBlendFunc:function () { - return this._blendFunc; - }, - - /** - * Initializes a sprite with an SpriteFrame. The texture and rect in SpriteFrame will be applied on this sprite - * @param {cc.SpriteFrame} spriteFrame A CCSpriteFrame object. It should includes a valid texture and a rect - * @return {Boolean} true if the sprite is initialized properly, false otherwise. - * @example - * var spriteFrame = cc.SpriteFrameCache.getInstance().getSpriteFrame("grossini_dance_01.png"); - * var sprite = new cc.Sprite(); - * sprite.initWithSpriteFrame(spriteFrame); - */ - initWithSpriteFrame:function (spriteFrame) { - cc.Assert(spriteFrame != null, ""); - var ret = this.initWithTexture(spriteFrame.getTexture(), spriteFrame.getRect()); - this.setDisplayFrame(spriteFrame); - - return ret; - }, - - /** - * Initializes a sprite with a sprite frame name.
- * A cc.SpriteFrame will be fetched from the cc.SpriteFrameCache by name.
- * If the cc.SpriteFrame doesn't exist it will raise an exception.
- * @param {String} spriteFrameName A key string that can fected a volid CCSpriteFrame from CCSpriteFrameCache - * @return {Boolean} true if the sprite is initialized properly, false otherwise. - * @example - * var sprite = new cc.Sprite(); - * sprite.initWithSpriteFrameName("grossini_dance_01.png"); - */ - initWithSpriteFrameName:function (spriteFrameName) { - cc.Assert(spriteFrameName != null, ""); - var frame = cc.SpriteFrameCache.getInstance().getSpriteFrame(spriteFrameName); - return this.initWithSpriteFrame(frame); - }, - - /** - * tell the sprite to use batch node render. - * @param {cc.SpriteBatchNode} batchNode - */ - useBatchNode:function (batchNode) { - this._textureAtlas = batchNode.getTextureAtlas(); // weak ref - this._batchNode = batchNode; - }, - - /** - *

- * set the vertex rect.
- * It will be called internally by setTextureRect.
- * Useful if you want to create 2x images from SD images in Retina Display.
- * Do not call it manually. Use setTextureRect instead.
- * (override this method to generate "double scale" sprites) - *

- * @param rect - */ - setVertexRect:function (rect) { - this._rect = rect; - }, - - sortAllChildren:function () { - if (this._reorderChildDirty) { - var j, tempItem, locChildren = this._children; - for (var i = 1; i < locChildren.length; i++) { - tempItem = locChildren[i]; - j = i - 1; - - //continue moving element downwards while zOrder is smaller or when zOrder is the same but orderOfArrival is smaller - while (j >= 0 && ( tempItem.getZOrder() < locChildren[j].getZOrder() || ( tempItem.getZOrder() === locChildren[j].getZOrder() - && tempItem.getOrderOfArrival() < locChildren[j].getOrderOfArrival() ) )) { - locChildren[j + 1] = locChildren[j]; - j = j - 1; - } - locChildren[j + 1] = tempItem; - } - - if (this._batchNode) { - this._arrayMakeObjectsPerformSelector(locChildren, cc.Node.StateCallbackType.sortAllChildren); - } - this._reorderChildDirty = false; - } - }, - - /** - * Reorders a child according to a new z value. (override cc.Node ) - * @param {cc.Node} child - * @param {Number} zOrder - * @override - */ - reorderChild:function (child, zOrder) { - cc.Assert(child != null, "child is null"); - cc.Assert(this._children.indexOf(child) > -1, "this child is not in children list"); - - if (zOrder === child.getZOrder()) - return; - - if (this._batchNode && !this._reorderChildDirty) { - this._setReorderChildDirtyRecursively(); - this._batchNode.reorderBatch(true); - } - cc.Node.prototype.reorderChild.call(this, child, zOrder); - }, - - /** - * Removes a child from the sprite. (override cc.Node ) - * @param child - * @param cleanup whether or not cleanup all running actions - * @override - */ - removeChild:function (child, cleanup) { - if (this._batchNode) - this._batchNode.removeSpriteFromAtlas(child); - cc.Node.prototype.removeChild.call(this, child, cleanup); - }, - - /** - * Removes all children from the container (override cc.Node ) - * @param cleanup whether or not cleanup all running actions - * @override - */ - removeAllChildren:function (cleanup) { - var locChildren = this._children; - if (this._batchNode && locChildren != null) { - for (var i = 0; i < locChildren.length; i++) - this._batchNode.removeSpriteFromAtlas(locChildren[i]); - } - - cc.Node.prototype.removeAllChildren.call(this, cleanup); - this._hasChildren = false; - }, - - // - // cc.Node property overloads - // - - /** - * set Recursively is or isn't Dirty - * used only when parent is CCSpriteBatchNode - * @param {Boolean} value - */ - setDirtyRecursively:function (value) { - this._recursiveDirty = value; - this.setDirty(value); - // recursively set dirty - var locChildren = this._children; - if (locChildren != null) { - for (var i = 0; i < locChildren.length; i++) { - if (locChildren[i] instanceof cc.Sprite) - locChildren[i].setDirtyRecursively(true); - } - } - }, - - /** - * HACK: optimization - */ - SET_DIRTY_RECURSIVELY:function () { - if (this._batchNode && !this._recursiveDirty) { - this._recursiveDirty = true; - this._dirty = true; - if (this._hasChildren) - this.setDirtyRecursively(true); - } - }, - - /** - * position setter (override cc.Node ) - * @param {cc.Point} pos - * @override - */ - setPosition:function (pos) { - if (arguments.length >= 2) - cc.Node.prototype.setPosition.call(this, pos, arguments[1]); - else - cc.Node.prototype.setPosition.call(this, pos); - this.SET_DIRTY_RECURSIVELY(); - }, - - /** - * Rotation setter (override cc.Node ) - * @param {Number} rotation - * @override - */ - setRotation:function (rotation) { - cc.Node.prototype.setRotation.call(this, rotation); - this.SET_DIRTY_RECURSIVELY(); - }, - - setRotationX:function (rotationX) { - cc.Node.prototype.setRotationX.call(this, rotationX); - this.SET_DIRTY_RECURSIVELY(); - }, - - setRotationY:function (rotationY) { - cc.Node.prototype.setRotationY.call(this, rotationY); - this.SET_DIRTY_RECURSIVELY(); - }, - - /** - * SkewX setter (override cc.Node ) - * @param {Number} sx SkewX value - * @override - */ - setSkewX:function (sx) { - cc.Node.prototype.setSkewX.call(this, sx); - this.SET_DIRTY_RECURSIVELY(); - }, - - /** - * SkewY setter (override cc.Node ) - * @param {Number} sy SkewY value - * @override - */ - setSkewY:function (sy) { - cc.Node.prototype.setSkewY.call(this, sy); - this.SET_DIRTY_RECURSIVELY(); - }, - - /** - * ScaleX setter (override cc.Node ) - * @param {Number} scaleX - * @override - */ - setScaleX:function (scaleX) { - cc.Node.prototype.setScaleX.call(this, scaleX); - this.SET_DIRTY_RECURSIVELY(); - }, - - /** - * ScaleY setter (override cc.Node ) - * @param {Number} scaleY - * @override - */ - setScaleY:function (scaleY) { - cc.Node.prototype.setScaleY.call(this, scaleY); - this.SET_DIRTY_RECURSIVELY(); - }, - - /** - *

The scale factor of the node. 1.0 is the default scale factor.
- * It modifies the X and Y scale at the same time. (override cc.Node )

- * @param {Number} scale - * @param {Number|null} scaleY - * @override - */ - setScale:function (scale, scaleY) { - cc.Node.prototype.setScale.call(this, scale, scaleY); - this.SET_DIRTY_RECURSIVELY(); - }, - - /** - * VertexZ setter (override cc.Node ) - * @param {Number} vertexZ - * @override - */ - setVertexZ:function (vertexZ) { - cc.Node.prototype.setVertexZ.call(this, vertexZ); - this.SET_DIRTY_RECURSIVELY(); - }, - - /** - * AnchorPoint setter (override cc.Node ) - * @param {cc.Point} anchor - * @override - */ - setAnchorPoint:function (anchor) { - cc.Node.prototype.setAnchorPoint.call(this, anchor); - this.SET_DIRTY_RECURSIVELY(); - }, - - /** - * visible setter (override cc.Node ) - * @param {Boolean} visible - * @override - */ - setVisible:function (visible) { - cc.Node.prototype.setVisible.call(this, visible); - this.SET_DIRTY_RECURSIVELY(); - }, - - /** - * IsRelativeAnchorPoint setter (override cc.Node ) - * @param {Boolean} relative - * @override - */ - ignoreAnchorPointForPosition:function (relative) { - cc.Assert(!this._batchNode, "ignoreAnchorPointForPosition is invalid in cc.Sprite"); - cc.Node.prototype.ignoreAnchorPointForPosition.call(this,relative); - }, - - /** - * Sets whether the sprite should be flipped horizontally or not. - * @param {Boolean} flipX true if the sprite should be flipped horizaontally, false otherwise. - */ - setFlipX:function (flipX) { - if (this._flipX != flipX) { - this._flipX = flipX; - this.setTextureRect(this._rect, this._rectRotated, this._contentSize); - this.setNodeDirty(); - } - }, - - /** - * FlipY value setter (override cc.Node ) - * @param {Boolean} flipY - */ - setFlipY:function (flipY) { - if (this._flipY != flipY) { - this._flipY = flipY; - this.setTextureRect(this._rect, this._rectRotated, this._contentSize); - this.setNodeDirty(); - } - }, - - /** - *

- * Returns the flag which indicates whether the sprite is flipped horizontally or not.
- *
- * It only flips the texture of the sprite, and not the texture of the sprite's children.
- * Also, flipping the texture doesn't alter the anchorPoint.
- * If you want to flip the anchorPoint too, and/or to flip the children too use:
- * sprite->setScaleX(sprite->getScaleX() * -1);

- * @return {Boolean} true if the sprite is flipped horizaontally, false otherwise. - */ - isFlippedX:function () { - return this._flipX; - }, - - /** - *

- * Return the flag which indicates whether the sprite is flipped vertically or not.
- *
- * It only flips the texture of the sprite, and not the texture of the sprite's children.
- * Also, flipping the texture doesn't alter the anchorPoint.
- * If you want to flip the anchorPoint too, and/or to flip the children too use:
- * sprite->setScaleY(sprite->getScaleY() * -1);

- * @return {Boolean} true if the sprite is flipped vertically, flase otherwise. - */ - isFlippedY:function () { - return this._flipY; - }, - - // - // RGBA protocol - // - - // RGBAProtocol - /** - * opacity: conforms to CCRGBAProtocol protocol - * @param {Boolean} modify - */ - setOpacityModifyRGB:function (modify) { - if (this._opacityModifyRGB !== modify) { - this._opacityModifyRGB = modify; - this.updateColor(); - } - }, - - /** - * return IsOpacityModifyRGB value - * @return {Boolean} - */ - isOpacityModifyRGB:function () { - return this._opacityModifyRGB; - }, - - updateDisplayedOpacity:function(parentOpacity){ - cc.NodeRGBA.prototype.updateDisplayedOpacity.call(this, parentOpacity); - this.updateColor(); - }, - - // Animation - - /** - * changes the display frame with animation name and index.
- * The animation name will be get from the CCAnimationCache - * @param animationName - * @param frameIndex - */ - setDisplayFrameWithAnimationName:function (animationName, frameIndex) { - cc.Assert(animationName, "cc.Sprite#setDisplayFrameWithAnimationName. animationName must not be null"); - var cache = cc.AnimationCache.getInstance().getAnimation(animationName); - cc.Assert(cache, "cc.Sprite#setDisplayFrameWithAnimationName: Frame not found"); - var animFrame = cache.getFrames()[frameIndex]; - cc.Assert(animFrame, "cc.Sprite#setDisplayFrame. Invalid frame"); - this.setDisplayFrame(animFrame.getSpriteFrame()); - }, - - /** - * Returns the batch node object if this sprite is rendered by cc.SpriteBatchNode - * @returns {cc.SpriteBatchNode|null} The cc.SpriteBatchNode object if this sprite is rendered by cc.SpriteBatchNode, null if the sprite isn't used batch node. - */ - getBatchNode:function () { - return this._batchNode; - }, - - _setReorderChildDirtyRecursively:function () { - //only set parents flag the first time - if (!this._reorderChildDirty) { - this._reorderChildDirty = true; - var pNode = this._parent; - while (pNode && pNode != this._batchNode) { - pNode._setReorderChildDirtyRecursively(); - pNode = pNode.getParent(); - } - } - }, - - // CCTextureProtocol - getTexture:function () { - return this._texture; - }, - /// ---- common properties end ---- - - _quad:null, // vertex coords, texture coords and color info - _quadWebBuffer:null, - _quadDirty:false, - - /** - * Constructor - * @param {String|cc.SpriteFrame|cc.SpriteBatchNode|HTMLImageElement|cc.Texture2D} fileName sprite construct parameter - */ - ctor:function (fileName) { - cc.NodeRGBA.prototype.ctor.call(this); - this._shouldBeHidden = false; - this._offsetPosition = cc.p(0, 0); - this._unflippedOffsetPositionFromCenter = cc.p(0, 0); - this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST}; - - this._quad = new cc.V3F_C4B_T2F_Quad(); - this._quadWebBuffer = cc.renderContext.createBuffer(); - this._quadDirty = true; - - if (fileName) { - if (typeof(fileName) == "string") { - var frame = cc.SpriteFrameCache.getInstance().getSpriteFrame(fileName); - this.initWithSpriteFrame(frame); - } else if (typeof(fileName) == "object") { - if (fileName instanceof cc.SpriteFrame) { - this.initWithSpriteFrame(fileName); - } else if (fileName instanceof cc.SpriteBatchNode) { - if (arguments.length > 1) { - var rect = arguments[1]; - if (rect instanceof cc.Rect) - this.initWithBatchNode(fileName, rect); - } - } else if ((fileName instanceof HTMLImageElement) || (fileName instanceof HTMLCanvasElement)) { - var texture2d = new cc.Texture2D(); - texture2d.initWithElement(fileName); - texture2d.handleLoadedTexture(); - this.initWithTexture(texture2d) - } else if (fileName instanceof cc.Texture2D) { - this.initWithTexture(fileName) - } - } - } - }, - - /** - * Returns the quad (tex coords, vertex coords and color) information. - * @return {cc.V3F_C4B_T2F_Quad} - */ - getQuad:function () { - return this._quad; - }, - - /** - * conforms to cc.TextureProtocol protocol - * @param {Number|cc.BlendFunc} src - * @param {Number} dst - */ - setBlendFunc:function (src, dst) { - if (arguments.length == 1) - this._blendFunc = src; - else - this._blendFunc = {src:src, dst:dst}; - }, - - /** - * Initializes an empty sprite with nothing init. - * @return {Boolean} - */ - init:function () { - if(arguments.length > 0) - return this.initWithFile(arguments[0], arguments[1]); - - cc.NodeRGBA.prototype.init.call(this); - this._dirty = this._recursiveDirty = false; - this._opacityModifyRGB = true; - - this._blendFunc.src = cc.BLEND_SRC; - this._blendFunc.dst = cc.BLEND_DST; - - // update texture (calls _updateBlendFunc) - this.setTexture(null); - - this._flipX = this._flipY = false; - - // default transform anchor: center - this.setAnchorPoint(cc.p(0.5, 0.5)); - - // zwoptex default values - this._offsetPosition = cc.PointZero(); - this._hasChildren = false; - - // Atlas: Color - var tempColor = {r:255, g:255, b:255, a:255}; - this._quad.bl.colors = tempColor; - this._quad.br.colors = tempColor; - this._quad.tl.colors = tempColor; - this._quad.tr.colors = tempColor; - this._quadDirty = true; - - // updated in "useSelfRender" - // Atlas: TexCoords - this.setTextureRect(cc.RectZero(), false, cc.SizeZero()); - return true; - }, - /** - *

- * Initializes a sprite with an image filename. - * - * This method will find pszFilename from local file system, load its content to CCTexture2D, - * then use CCTexture2D to create a sprite. - * After initialization, the rect used will be the size of the image. The offset will be (0,0). - *

- * @param {String} filename The path to an image file in local file system - * @param {cc.Rect} rect The rectangle assigned the content area from texture. - * @return {Boolean} true if the sprite is initialized properly, false otherwise. - * @example - * var mySprite = new cc.Sprite(); - * mySprite.initWithFile("HelloHTML5World.png",cc.rect(0,0,480,320)); - */ - initWithFile:function (filename, rect) { - cc.Assert(filename != null, "Sprite#initWithFile():Invalid filename for sprite"); - var selfPointer = this; - - var texture = cc.TextureCache.getInstance().textureForKey(filename); - if (!texture) { - this._visible = false; - var loadImg = new Image(); - loadImg.addEventListener("load", function () { - if (!rect) { - rect = cc.rect(0, 0, loadImg.width, loadImg.height); - } - var texture2d = new cc.Texture2D(); - texture2d.initWithElement(loadImg); - texture2d.handleLoadedTexture(); - selfPointer.initWithTexture(texture2d, rect); - cc.TextureCache.getInstance().cacheImage(filename, loadImg); - selfPointer._visible = true; - }); - loadImg.addEventListener("error", function () { - cc.log("load failure:" + filename); - }); - loadImg.src = filename; - return true; - } else { - if (texture) { - if (!rect) { - var size = texture.getContentSize(); - rect = cc.rect(0, 0, size.width, size.height); - } - return this.initWithTexture(texture, rect); - } - } - return false; - }, - - /** - * Initializes a sprite with a texture.
- * After initialization, the rect used will be the size of the texture, and the offset will be (0,0). - * @param {cc.Texture2D|HTMLImageElement|HTMLCanvasElement} texture A pointer to an existing CCTexture2D object. You can use a CCTexture2D object for many sprites. - * @param {cc.Rect} rect Only the contents inside rect of this texture will be applied for this sprite. - * @param {Boolean} rotated Whether or not the texture rectangle is rotated. - * @return {Boolean} true if the sprite is initialized properly, false otherwise. - * @example - * var img =cc.TextureCache.getInstance().addImage("HelloHTML5World.png"); - * var mySprite = new cc.Sprite(); - * mySprite.initWithTexture(img,cc.rect(0,0,480,320)); - */ - initWithTexture:function (texture, rect, rotated) { - var argnum = arguments.length; - if (argnum == 0) - throw "Sprite.initWithTexture(): Argument must be non-nil "; - - rotated = rotated || false; - - if(!cc.NodeRGBA.prototype.init.call(this)) - return false; - - this._batchNode = null; - this._recursiveDirty = false; - this._dirty = false; - this._opacityModifyRGB = true; - - this._blendFunc.src = cc.BLEND_SRC; - this._blendFunc.dst = cc.BLEND_DST; - - this._flipX = this._flipY = false; - - // default transform anchor: center - this.setAnchorPoint(cc.p(0.5, 0.5)); - - // zwoptex default values - this._offsetPosition = cc.p(0, 0); - this._hasChildren = false; - - // Atlas: Color - var tmpColor = new cc.Color4B(255, 255, 255, 255); - this._quad.bl.colors = tmpColor; - this._quad.br.colors = tmpColor; - this._quad.tl.colors = tmpColor; - this._quad.tr.colors = tmpColor; - - if (!rect) { - rect = cc.rect(0, 0, 0, 0); - rect.size = texture.getContentSize(); - } - this.setTexture(texture); - this.setTextureRect(rect, rotated, rect.size); - - // by default use "Self Render". - // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render" - this.setBatchNode(null); - this._quadDirty = true; - return true; - }, - /** - * updates the texture rect of the CCSprite in points. - * @param {cc.Rect} rect a rect of texture - * @param {Boolean} rotated - * @param {cc.Size} untrimmedSize - */ - setTextureRect:function (rect, rotated, untrimmedSize) { - this._rectRotated = rotated || false; - untrimmedSize = untrimmedSize || rect.size; - - this.setContentSize(untrimmedSize); - this.setVertexRect(rect); - this._setTextureCoords(rect); - - var relativeOffset = this._unflippedOffsetPositionFromCenter; - if (this._flipX) - relativeOffset.x = -relativeOffset.x; - if (this._flipY) - relativeOffset.y = -relativeOffset.y; - - this._offsetPosition.x = relativeOffset.x + (this._contentSize.width - this._rect.width) / 2; - this._offsetPosition.y = relativeOffset.y + (this._contentSize.height - this._rect.height) / 2; - - // rendering using batch node - if (this._batchNode) { - // update dirty_, don't update recursiveDirty_ - //this.setDirty(true); - this._dirty = true; - } else { - // self rendering - // Atlas: Vertex - var x1 = 0 + this._offsetPosition.x; - var y1 = 0 + this._offsetPosition.y; - var x2 = x1 + this._rect.width; - var y2 = y1 + this._rect.height; - - // Don't update Z. - this._quad.bl.vertices = {x:x1, y:y1, z:0}; - this._quad.br.vertices = {x:x2, y:y1, z:0}; - this._quad.tl.vertices = {x:x1, y:y2, z:0}; - this._quad.tr.vertices = {x:x2, y:y2, z:0}; - - this._quadDirty = true; - } - }, - - // BatchNode methods - /** - * updates the quad according the the rotation, position, scale values. - */ - updateTransform:function () { - //cc.Assert(this._batchNode, "updateTransform is only valid when cc.Sprite is being rendered using an cc.SpriteBatchNode"); - - // recaculate matrix only if it is dirty - if (this.isDirty()) { - // If it is not visible, or one of its ancestors is not visible, then do nothing: - if (!this._visible || ( this._parent && this._parent != this._batchNode && this._parent._shouldBeHidden)) { - this._quad.br.vertices = {x:0, y:0, z:0}; - this._quad.tl.vertices = {x:0, y:0, z:0}; - this._quad.tr.vertices = {x:0, y:0, z:0}; - this._quad.bl.vertices = {x:0, y:0, z:0}; - this._shouldBeHidden = true; - } else { - this._shouldBeHidden = false; - - if (!this._parent || this._parent == this._batchNode) { - this._transformToBatch = this.nodeToParentTransform(); - } else { - //cc.Assert(this._parent instanceof cc.Sprite, "Logic error in CCSprite. Parent must be a CCSprite"); - this._transformToBatch = cc.AffineTransformConcat(this.nodeToParentTransform(), this._parent._transformToBatch); + this._transformToBatch = cc.AffineTransformConcat(this.nodeToParentTransform(), locParent._transformToBatch); } // // calculate the Quad based on the Affine Matrix // + var locTransformToBatch = this._transformToBatch; var size = this._rect.size; var x1 = this._offsetPosition.x; var y1 = this._offsetPosition.y; var x2 = x1 + size.width; var y2 = y1 + size.height; - var x = this._transformToBatch.tx; - var y = this._transformToBatch.ty; + var x = locTransformToBatch.tx; + var y = locTransformToBatch.ty; - var cr = this._transformToBatch.a; - var sr = this._transformToBatch.b; - var cr2 = this._transformToBatch.d; - var sr2 = -this._transformToBatch.c; + var cr = locTransformToBatch.a; + var sr = locTransformToBatch.b; + var cr2 = locTransformToBatch.d; + var sr2 = -locTransformToBatch.c; var ax = x1 * cr - y1 * sr2 + x; var ay = x1 * sr + y1 * cr2 + y; @@ -2316,13 +1404,13 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ var dx = x1 * cr - y2 * sr2 + x; var dy = x1 * sr + y2 * cr2 + y; - this._quad.bl.vertices = {x:cc.RENDER_IN_SUBPIXEL(ax), y:cc.RENDER_IN_SUBPIXEL(ay), z:this._vertexZ}; - this._quad.br.vertices = {x:cc.RENDER_IN_SUBPIXEL(bx), y:cc.RENDER_IN_SUBPIXEL(by), z:this._vertexZ}; - this._quad.tl.vertices = {x:cc.RENDER_IN_SUBPIXEL(dx), y:cc.RENDER_IN_SUBPIXEL(dy), z:this._vertexZ}; - this._quad.tr.vertices = {x:cc.RENDER_IN_SUBPIXEL(cx), y:cc.RENDER_IN_SUBPIXEL(cy), z:this._vertexZ}; + var locVertexZ = this._vertexZ; + locQuad.bl.vertices = {x: cc.RENDER_IN_SUBPIXEL(ax), y: cc.RENDER_IN_SUBPIXEL(ay), z: locVertexZ}; + locQuad.br.vertices = {x: cc.RENDER_IN_SUBPIXEL(bx), y: cc.RENDER_IN_SUBPIXEL(by), z: locVertexZ}; + locQuad.tl.vertices = {x: cc.RENDER_IN_SUBPIXEL(dx), y: cc.RENDER_IN_SUBPIXEL(dy), z: locVertexZ}; + locQuad.tr.vertices = {x: cc.RENDER_IN_SUBPIXEL(cx), y: cc.RENDER_IN_SUBPIXEL(cy), z: locVertexZ}; } - if (cc.renderContextType === cc.WEBGL) - this._textureAtlas.updateQuad(this._quad, this._atlasIndex); + this._textureAtlas.updateQuad(locQuad, this._atlasIndex); this._recursiveDirty = false; this.setDirty(false); } @@ -2343,6 +1431,34 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ } }, + _updateTransformForCanvas: function () { + //cc.Assert(this._batchNode, "updateTransform is only valid when cc.Sprite is being rendered using an cc.SpriteBatchNode"); + + // recaculate matrix only if it is dirty + if (this._dirty) { + // If it is not visible, or one of its ancestors is not visible, then do nothing: + var locParent = this._parent; + if (!this._visible || ( locParent && locParent != this._batchNode && locParent._shouldBeHidden)) { + this._shouldBeHidden = true; + } else { + this._shouldBeHidden = false; + + if (!locParent || locParent == this._batchNode) { + this._transformToBatch = this.nodeToParentTransform(); + } else { + //cc.Assert(this._parent instanceof cc.Sprite, "Logic error in CCSprite. Parent must be a CCSprite"); + this._transformToBatch = cc.AffineTransformConcat(this.nodeToParentTransform(), locParent._transformToBatch); + } + } + this._recursiveDirty = false; + this._dirty = false; + } + + // recursively iterate over children + if (this._hasChildren) + this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.updateTransform); + }, + /** * Add child to sprite (override cc.Node ) * @param {cc.Sprite} child @@ -2350,7 +1466,9 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ * @param {String} tag child's tag * @override */ - addChild:function (child, zOrder, tag) { + addChild: null, + + _addChildForWebGL:function (child, zOrder, tag) { cc.Assert(child != null, "Argument must be non-NULL"); if (zOrder == null) zOrder = child._zOrder; @@ -2371,27 +1489,41 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ cc.Node.prototype.addChild.call(this, child, zOrder, tag); this._hasChildren = true; }, + + _addChildForCanvas: function (child, zOrder, tag) { + cc.Assert(child != null, "Argument must be non-NULL"); + if (zOrder == null) + zOrder = child._zOrder; + if (tag == null) + tag = child._tag; + + //cc.Node already sets isReorderChildDirty_ so this needs to be after batchNode check + cc.Node.prototype.addChild.call(this, child, zOrder, tag); + this._hasChildren = true; + }, + /** * Update sprite's color */ updateColor:function () { - var color4 = {r:this._displayedColor.r, g:this._displayedColor.g, b:this._displayedColor.b, a:this._displayedOpacity}; + var locDisplayedColor = this._displayedColor, locDisplayedOpacity = this._displayedOpacity; + var color4 = {r: locDisplayedColor.r, g: locDisplayedColor.g, b: locDisplayedColor.b, a: locDisplayedOpacity}; // special opacity for premultiplied textures - if (this._opacityModifyRGB) - { - color4.r *= this._displayedOpacity/255.0; - color4.g *= this._displayedOpacity/255.0; - color4.b *= this._displayedOpacity/255.0; + if (this._opacityModifyRGB) { + color4.r *= locDisplayedOpacity / 255.0; + color4.g *= locDisplayedOpacity / 255.0; + color4.b *= locDisplayedOpacity / 255.0; } - this._quad.bl.colors = color4; - this._quad.br.colors = color4; - this._quad.tl.colors = color4; - this._quad.tr.colors = color4; + var locQuad = this._quad; + locQuad.bl.colors = color4; + locQuad.br.colors = color4; + locQuad.tl.colors = color4; + locQuad.tr.colors = color4; // renders using Sprite Manager if (this._batchNode) { if (this._atlasIndex != cc.SPRITE_INDEX_NOT_INITIALIZED) { - this._textureAtlas.updateQuad(this._quad, this._atlasIndex) + this._textureAtlas.updateQuad(locQuad, this._atlasIndex) } else { // no need to set it recursively // update dirty_, don't update recursiveDirty_ @@ -2408,34 +1540,78 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ * opacity setter * @param {Number} opacity */ - setOpacity:function (opacity) { + setOpacity:null, + + _setOpacityForWebGL: function (opacity) { cc.NodeRGBA.prototype.setOpacity.call(this, opacity); this.updateColor(); }, + _setOpacityForCanvas: function (opacity) { + cc.NodeRGBA.prototype.setOpacity.call(this, opacity); + this.setNodeDirty(); + }, + /** * color setter * @param {cc.Color3B} color3 */ - setColor:function (color3) { + setColor: null, + + _setColorForWebGL: function (color3) { cc.NodeRGBA.prototype.setColor.call(this, color3); this.updateColor(); }, - updateDisplayedColor:function(parentColor){ + _setColorForCanvas: function (color3) { + var curColor = this.getColor(); + if ((curColor.r === color3.r) && (curColor.g === color3.g) && (curColor.b === color3.b)) + return; + + cc.NodeRGBA.prototype.setColor.call(this, color3); + this._changeTextureColor(); + this.setNodeDirty(); + }, + + updateDisplayedColor: null, + + _updateDisplayedColorForWebGL: function (parentColor) { cc.NodeRGBA.prototype.updateDisplayedColor.call(this, parentColor); this.updateColor(); }, + _updateDisplayedColorForCanvas: function (parentColor) { + cc.NodeRGBA.prototype.updateDisplayedColor.call(this, parentColor); + this._changeTextureColor(); + this.setNodeDirty(); + }, + // Frames /** * Sets a new display frame to the cc.Sprite. * @param {cc.SpriteFrame} newFrame */ - setDisplayFrame:function (newFrame) { + setDisplayFrame: null, + + _setDisplayFrameForWebGL: function (newFrame) { this.setNodeDirty(); - this._unflippedOffsetPositionFromCenter = newFrame.getOffset(); + var frameOffset = newFrame.getOffset(); + this._unflippedOffsetPositionFromCenter.x = frameOffset.x; + this._unflippedOffsetPositionFromCenter.y = frameOffset.y; + var pNewTexture = newFrame.getTexture(); + var locTextureLoaded = newFrame.textureLoaded(); + if (!locTextureLoaded) { + this._textureLoaded = false; + newFrame.addLoadedEventListener(function (sender) { + this._textureLoaded = true; + var locNewTexture = sender.getTexture(); + if (locNewTexture != this._texture) + this.setTexture(locNewTexture); + this.setTextureRect(sender.getRect(), sender._rectRotated, sender.getOriginalSize()); + this._callLoadedEventCallbacks(); + }, this); + } // update texture before updating texture rect if (pNewTexture != this._texture) this.setTexture(pNewTexture); @@ -2445,21 +1621,68 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ this.setTextureRect(newFrame.getRect(), this._rectRotated, newFrame.getOriginalSize()); }, + _setDisplayFrameForCanvas: function (newFrame) { + this.setNodeDirty(); + + var frameOffset = newFrame.getOffset(); + this._unflippedOffsetPositionFromCenter.x = frameOffset.x; + this._unflippedOffsetPositionFromCenter.y = frameOffset.y; + + // update rect + this._rectRotated = newFrame.isRotated(); + + var pNewTexture = newFrame.getTexture(); + var locTextureLoaded = newFrame.textureLoaded(); + if (!locTextureLoaded) { + this._textureLoaded = false; + newFrame.addLoadedEventListener(function (sender) { + this._textureLoaded = true; + var locNewTexture = sender.getTexture(); + if (locNewTexture != this._texture) + this.setTexture(locNewTexture); + this.setTextureRect(sender.getRect(), this._rectRotated, sender.getOriginalSize()); + this._callLoadedEventCallbacks(); + }, this); + } + // update texture before updating texture rect + if (pNewTexture != this._texture) + this.setTexture(pNewTexture); + + if (this._rectRotated) + this._originalTexture = pNewTexture; + + this.setTextureRect(newFrame.getRect(), this._rectRotated, newFrame.getOriginalSize()); + this._colorized = false; + if (locTextureLoaded) { + var curColor = this.getColor(); + if (curColor.r !== 255 || curColor.g !== 255 || curColor.b !== 255) + this._changeTextureColor(); + } + }, + /** * Returns whether or not a cc.SpriteFrame is being displayed * @param {cc.SpriteFrame} frame * @return {Boolean} */ - isFrameDisplayed:function (frame) { + isFrameDisplayed: null, + + _isFrameDisplayedForWebGL: function (frame) { return (cc.rectEqualToRect(frame.getRect(), this._rect) && frame.getTexture().getName() == this._texture.getName() && cc.pointEqualToPoint(frame.getOffset(), this._unflippedOffsetPositionFromCenter)); }, + _isFrameDisplayedForCanvas: function (frame) { + if (frame.getTexture() != this._texture) + return false; + return cc.rectEqualToRect(frame.getRect(), this._rect); + }, + /** * Returns the current displayed frame. * @return {cc.SpriteFrame} */ - displayFrame:function () { + displayFrame: function () { return cc.SpriteFrame.createWithTexture(this._texture, cc.RECT_POINTS_TO_PIXELS(this._rect), this._rectRotated, @@ -2472,11 +1695,13 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ * @param {cc.SpriteBatchNode|null} spriteBatchNode * @example * var batch = cc.SpriteBatchNode.create("Images/grossini_dance_atlas.png", 15); - * var sprite = cc.Sprite.createWithTexture(batch.getTexture(), cc.RectMake(0, 0, 57, 57)); + * var sprite = cc.Sprite.createWithTexture(batch.getTexture(), cc.rect(0, 0, 57, 57)); * batch.addChild(sprite); * layer.addChild(batch); */ - setBatchNode:function (spriteBatchNode) { + setBatchNode:null, + + _setBatchNodeForWebGL:function (spriteBatchNode) { this._batchNode = spriteBatchNode; // weak reference // self render @@ -2490,10 +1715,11 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ var y1 = this._offsetPosition.y; var x2 = x1 + this._rect.width; var y2 = y1 + this._rect.height; - this._quad.bl.vertices = {x:x1, y:y1, z:0}; - this._quad.br.vertices = {x:x2, y:y1, z:0}; - this._quad.tl.vertices = {x:x1, y:y2, z:0}; - this._quad.tr.vertices = {x:x2, y:y2, z:0}; + var locQuad = this._quad; + locQuad.bl.vertices = {x:x1, y:y1, z:0}; + locQuad.br.vertices = {x:x2, y:y1, z:0}; + locQuad.tl.vertices = {x:x1, y:y2, z:0}; + locQuad.tr.vertices = {x:x2, y:y2, z:0}; this._quadDirty = true; } else { @@ -2503,19 +1729,37 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ } }, + _setBatchNodeForCanvas:function (spriteBatchNode) { + this._batchNode = spriteBatchNode; // weak reference + + // self render + if (!this._batchNode) { + this._atlasIndex = cc.SPRITE_INDEX_NOT_INITIALIZED; + this.setTextureAtlas(null); + this._recursiveDirty = false; + this.setDirty(false); + } else { + // using batch + this._transformToBatch = cc.AffineTransformIdentity(); + this.setTextureAtlas(this._batchNode.getTextureAtlas()); // weak ref + } + }, + // CCTextureProtocol /** * Texture of sprite setter * @param {HTMLImageElement|HTMLCanvasElement|cc.Texture2D} texture */ - setTexture:function (texture) { + setTexture: null, + + _setTextureForWebGL: function (texture) { // CCSprite: setTexture doesn't work when the sprite is rendered using a CCSpriteSheet cc.Assert(!texture || texture instanceof cc.Texture2D, "setTexture expects a CCTexture2D. Invalid argument"); // If batchnode, then texture id should be the same cc.Assert(!this._batchNode, "cc.Sprite: Batched sprites should use the same texture as the batchnode"); - if(texture) + if (texture) this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_TEXTURECOLOR)); else this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_COLOR)); @@ -2526,6 +1770,17 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ } }, + _setTextureForCanvas: function (texture) { + // CCSprite: setTexture doesn't work when the sprite is rendered using a CCSpriteSheet + cc.Assert(!texture || texture instanceof cc.Texture2D, "setTexture expects a CCTexture2D. Invalid argument"); + if (this._texture != texture) { + if (texture && texture.getHtmlElementObj() instanceof HTMLImageElement) { + this._originalTexture = texture; + } + this._texture = texture; + } + }, + // Texture protocol _updateBlendFunc:function () { cc.Assert(!this._batchNode, "cc.Sprite: _updateBlendFunc doesn't work when the sprite is rendered using a cc.CCSpriteBatchNode"); @@ -2541,6 +1796,30 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ } }, + _changeTextureColor: function () { + var locElement, locTexture = this._texture, locRect = this.getTextureRect(); + if (locTexture && locRect.width > 0) { + locElement = locTexture.getHtmlElementObj(); + if (!locElement) + return; + + var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(this._originalTexture.getHtmlElementObj()); + if (cacheTextureForColor) { + this._colorized = true; + //generate color texture cache + if (locElement instanceof HTMLCanvasElement && !this._rectRotated && !this._newTextureWhenChangeColor) + cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, locRect, locElement); + else { + locElement = cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, locRect); + locTexture = new cc.Texture2D(); + locTexture.initWithElement(locElement); + locTexture.handleLoadedTexture(); + this.setTexture(locTexture); + } + } + } + }, + _setTextureCoords:function (rect) { rect = cc.RECT_POINTS_TO_PIXELS(rect); @@ -2551,7 +1830,7 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ var atlasWidth = tex.getPixelsWide(); var atlasHeight = tex.getPixelsHigh(); - var left, right, top, bottom, tempSwap; + var left, right, top, bottom, tempSwap, locQuad = this._quad; if (this._rectRotated) { if (cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL) { left = (2 * rect.x + 1) / (2 * atlasWidth); @@ -2565,26 +1844,26 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ bottom = (rect.y + rect.width) / atlasHeight; }// CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - if (this._flipX) { + if (this._flippedX) { tempSwap = top; top = bottom; bottom = tempSwap; } - if (this._flipY) { + if (this._flippedY) { tempSwap = left; left = right; right = tempSwap; } - this._quad.bl.texCoords.u = left; - this._quad.bl.texCoords.v = top; - this._quad.br.texCoords.u = left; - this._quad.br.texCoords.v = bottom; - this._quad.tl.texCoords.u = right; - this._quad.tl.texCoords.v = top; - this._quad.tr.texCoords.u = right; - this._quad.tr.texCoords.v = bottom; + locQuad.bl.texCoords.u = left; + locQuad.bl.texCoords.v = top; + locQuad.br.texCoords.u = left; + locQuad.br.texCoords.v = bottom; + locQuad.tl.texCoords.u = right; + locQuad.tl.texCoords.v = top; + locQuad.tr.texCoords.u = right; + locQuad.tr.texCoords.v = bottom; } else { if (cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL) { left = (2 * rect.x + 1) / (2 * atlasWidth); @@ -2598,38 +1877,43 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ bottom = (rect.y + rect.height) / atlasHeight; } // ! CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - if (this._flipX) { + if (this._flippedX) { tempSwap = left; left = right; right = tempSwap; } - if (this._flipY) { + if (this._flippedY) { tempSwap = top; top = bottom; bottom = tempSwap; } - this._quad.bl.texCoords.u = left; - this._quad.bl.texCoords.v = bottom; - this._quad.br.texCoords.u = right; - this._quad.br.texCoords.v = bottom; - this._quad.tl.texCoords.u = left; - this._quad.tl.texCoords.v = top; - this._quad.tr.texCoords.u = right; - this._quad.tr.texCoords.v = top; + locQuad.bl.texCoords.u = left; + locQuad.bl.texCoords.v = bottom; + locQuad.br.texCoords.u = right; + locQuad.br.texCoords.v = bottom; + locQuad.tl.texCoords.u = left; + locQuad.tl.texCoords.v = top; + locQuad.tr.texCoords.u = right; + locQuad.tr.texCoords.v = top; } this._quadDirty = true; }, /** * draw sprite to canvas */ - draw:function () { + draw: null, + + _drawForWebGL: function () { + if (!this._textureLoaded) + return; + var gl = cc.renderContext, locTexture = this._texture; //cc.Assert(!this._batchNode, "If cc.Sprite is being rendered by cc.SpriteBatchNode, cc.Sprite#draw SHOULD NOT be called"); if (locTexture) { - if(locTexture._isLoaded){ + if (locTexture._isLoaded) { this._shaderProgram.use(); this._shaderProgram.setUniformForModelViewAndProjectionMatrixWithMat4(); @@ -2639,7 +1923,7 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSCOLORTEX); gl.bindBuffer(gl.ARRAY_BUFFER, this._quadWebBuffer); - if(this._quadDirty){ + if (this._quadDirty) { gl.bufferData(gl.ARRAY_BUFFER, this._quad.arrayBuffer, gl.DYNAMIC_DRAW); this._quadDirty = false; } @@ -2659,7 +1943,7 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_COLOR); gl.bindBuffer(gl.ARRAY_BUFFER, this._quadWebBuffer); - if(this._quadDirty){ + if (this._quadDirty) { cc.renderContext.bufferData(cc.renderContext.ARRAY_BUFFER, this._quad.arrayBuffer, cc.renderContext.STATIC_DRAW); this._quadDirty = false; } @@ -2668,16 +1952,17 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); } cc.g_NumberOfDraws++; - if(cc.SPRITE_DEBUG_DRAW === 0) + if (cc.SPRITE_DEBUG_DRAW === 0) return; if (cc.SPRITE_DEBUG_DRAW === 1) { // draw bounding box + var locQuad = this._quad; var verticesG1 = [ - cc.p(this._quad.tl.vertices.x, this._quad.tl.vertices.y), - cc.p(this._quad.bl.vertices.x, this._quad.bl.vertices.y), - cc.p(this._quad.br.vertices.x, this._quad.br.vertices.y), - cc.p(this._quad.tr.vertices.x, this._quad.tr.vertices.y) + cc.p(locQuad.tl.vertices.x, locQuad.tl.vertices.y), + cc.p(locQuad.bl.vertices.x, locQuad.bl.vertices.y), + cc.p(locQuad.br.vertices.x, locQuad.br.vertices.y), + cc.p(locQuad.tr.vertices.x, locQuad.tr.vertices.y) ]; cc.drawingUtil.drawPoly(verticesG1, 4, true); } else if (cc.SPRITE_DEBUG_DRAW === 2) { @@ -2688,9 +1973,112 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ cc.p(offsetPixG2.x + drawSizeG2.width, offsetPixG2.y + drawSizeG2.height), cc.p(offsetPixG2.x, offsetPixG2.y + drawSizeG2.height)]; cc.drawingUtil.drawPoly(verticesG2, 4, true); } // CC_SPRITE_DEBUG_DRAW + }, + + _drawForCanvas: function (ctx) { + if (!this._textureLoaded) + return; + + var context = ctx || cc.renderContext; + if (this._isLighterMode) + context.globalCompositeOperation = 'lighter'; + + context.globalAlpha = this._displayedOpacity / 255; + var locRect = this._rect, locContentSize = this._contentSize, locOffsetPosition = this._offsetPosition; + var flipXOffset = 0 | (locOffsetPosition.x), flipYOffset = -locOffsetPosition.y - locRect.height; + if (this._flippedX || this._flippedY) { + context.save(); + if (this._flippedX) { + flipXOffset = -locOffsetPosition.x - locRect.width; + context.scale(-1, 1); + } + if (this._flippedY) { + flipYOffset = locOffsetPosition.y; + context.scale(1, -1); + } + } + + if (this._texture && locRect.width > 0) { + var image = this._texture.getHtmlElementObj(); + if (this._colorized) { + context.drawImage(image, + 0, 0, 0 | locRect.width, 0 | locRect.height, + flipXOffset, flipYOffset, 0 | locRect.width, 0 | locRect.height); + } else { + context.drawImage(image, + 0 | locRect.x, 0 | locRect.y, 0 | locRect.width, 0 | locRect.height, + flipXOffset, flipYOffset, 0 | locRect.width, 0 | locRect.height); + } + } else if (locContentSize.width !== 0) { + var curColor = this.getColor(); + context.fillStyle = "rgba(" + curColor.r + "," + curColor.g + "," + curColor.b + ",1)"; + context.fillRect(flipXOffset, flipYOffset, locContentSize.width, locContentSize.height); + } + + if (cc.SPRITE_DEBUG_DRAW === 1) { + // draw bounding box + context.strokeStyle = "rgba(0,255,0,1)"; + flipYOffset = -flipYOffset; + var vertices1 = [cc.p(flipXOffset, flipYOffset), cc.p(flipXOffset + locRect.width, flipYOffset), cc.p(flipXOffset + locRect.width, flipYOffset - locRect.height), + cc.p(flipXOffset, flipYOffset - locRect.height)]; + cc.drawingUtil.drawPoly(vertices1, 4, true); + } else if (cc.SPRITE_DEBUG_DRAW === 2) { + // draw texture box + context.strokeStyle = "rgba(0,255,0,1)"; + var drawSize = this._rect.size; + flipYOffset = -flipYOffset; + var vertices2 = [cc.p(flipXOffset, flipYOffset), cc.p(flipXOffset + drawSize.width, flipYOffset), + cc.p(flipXOffset + drawSize.width, flipYOffset - drawSize.height), cc.p(flipXOffset, flipYOffset - drawSize.height)]; + cc.drawingUtil.drawPoly(vertices2, 4, true); + } + if (this._flippedX || this._flippedY) + context.restore(); + cc.g_NumberOfDraws++; } }); +if(cc.Browser.supportWebGL){ + cc.Sprite.prototype._spriteFrameLoadedCallback = cc.Sprite.prototype._spriteFrameLoadedCallbackForWebGL; + cc.Sprite.prototype.setOpacityModifyRGB = cc.Sprite.prototype._setOpacityModifyRGBForWebGL; + cc.Sprite.prototype.updateDisplayedOpacity = cc.Sprite.prototype._updateDisplayedOpacityForWebGL; + cc.Sprite.prototype.ctor = cc.Sprite.prototype._ctorForWebGL; + cc.Sprite.prototype.setBlendFunc = cc.Sprite.prototype._setBlendFuncForWebGL; + cc.Sprite.prototype.init = cc.Sprite.prototype._initForWebGL; + cc.Sprite.prototype.initWithTexture = cc.Sprite.prototype._initWithTextureForWebGL; + cc.Sprite.prototype._textureLoadedCallback = cc.Sprite.prototype._textureLoadedCallbackForWebGL; + cc.Sprite.prototype.setTextureRect = cc.Sprite.prototype._setTextureRectForWebGL; + cc.Sprite.prototype.updateTransform = cc.Sprite.prototype._updateTransformForWebGL; + cc.Sprite.prototype.addChild = cc.Sprite.prototype._addChildForWebGL; + cc.Sprite.prototype.setOpacity = cc.Sprite.prototype._setOpacityForWebGL; + cc.Sprite.prototype.setColor = cc.Sprite.prototype._setColorForWebGL; + cc.Sprite.prototype.updateDisplayedColor = cc.Sprite.prototype._updateDisplayedColorForWebGL; + cc.Sprite.prototype.setDisplayFrame = cc.Sprite.prototype._setDisplayFrameForWebGL; + cc.Sprite.prototype.isFrameDisplayed = cc.Sprite.prototype._isFrameDisplayedForWebGL; + cc.Sprite.prototype.setBatchNode = cc.Sprite.prototype._setBatchNodeForWebGL; + cc.Sprite.prototype.setTexture = cc.Sprite.prototype._setTextureForWebGL; + cc.Sprite.prototype.draw = cc.Sprite.prototype._drawForWebGL; +}else{ + cc.Sprite.prototype._spriteFrameLoadedCallback = cc.Sprite.prototype._spriteFrameLoadedCallbackForCanvas; + cc.Sprite.prototype.setOpacityModifyRGB = cc.Sprite.prototype._setOpacityModifyRGBForCanvas; + cc.Sprite.prototype.updateDisplayedOpacity = cc.Sprite.prototype._updateDisplayedOpacityForCanvas; + cc.Sprite.prototype.ctor = cc.Sprite.prototype._ctorForCanvas; + cc.Sprite.prototype.setBlendFunc = cc.Sprite.prototype._setBlendFuncForCanvas; + cc.Sprite.prototype.init = cc.Sprite.prototype._initForCanvas; + cc.Sprite.prototype.initWithTexture = cc.Sprite.prototype._initWithTextureForCanvas; + cc.Sprite.prototype._textureLoadedCallback = cc.Sprite.prototype._textureLoadedCallbackForCanvas; + cc.Sprite.prototype.setTextureRect = cc.Sprite.prototype._setTextureRectForCanvas; + cc.Sprite.prototype.updateTransform = cc.Sprite.prototype._updateTransformForCanvas; + cc.Sprite.prototype.addChild = cc.Sprite.prototype._addChildForCanvas; + cc.Sprite.prototype.setOpacity = cc.Sprite.prototype._setOpacityForCanvas; + cc.Sprite.prototype.setColor = cc.Sprite.prototype._setColorForCanvas; + cc.Sprite.prototype.updateDisplayedColor = cc.Sprite.prototype._updateDisplayedColorForCanvas; + cc.Sprite.prototype.setDisplayFrame = cc.Sprite.prototype._setDisplayFrameForCanvas; + cc.Sprite.prototype.isFrameDisplayed = cc.Sprite.prototype._isFrameDisplayedForCanvas; + cc.Sprite.prototype.setBatchNode = cc.Sprite.prototype._setBatchNodeForCanvas; + cc.Sprite.prototype.setTexture = cc.Sprite.prototype._setTextureForCanvas; + cc.Sprite.prototype.draw = cc.Sprite.prototype._drawForCanvas; +} + /** *

* Creates a sprite with an exsiting texture contained in a CCTexture2D object
@@ -2699,7 +2087,6 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ * @constructs * @param {cc.Texture2D} texture A pointer to an existing CCTexture2D object. You can use a CCTexture2D object for many sprites. * @param {cc.Rect} rect Only the contents inside the rect of this texture will be applied for this sprite. - * @param {cc.Point} offset offset of the texture * @return {cc.Sprite} A valid sprite object * @example * //get an image @@ -2711,21 +2098,18 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{ * //create a sprite with texture and rect * var sprite2 = cc.Sprite.createWithTexture(img, cc.rect(0,0,480,320)); * - * //create a sprite with texture and rect and offset - * var sprite3 = cc.Sprite.createWithTexture(img, cc.rect(0,0,480,320),cc.p(0,0)); */ -cc.SpriteWebGL.createWithTexture = function (texture, rect, offset) { +cc.Sprite.createWithTexture = function (texture, rect) { var argnum = arguments.length; - var sprite = new cc.SpriteWebGL(); + var sprite = new cc.Sprite(); switch (argnum) { case 1: /** Creates an sprite with a texture. The rect used will be the size of the texture. The offset will be (0,0). */ - if (sprite && sprite.initWithTexture(texture)) { + if (sprite && sprite.initWithTexture(texture)) return sprite; - } return null; break; @@ -2733,16 +2117,8 @@ cc.SpriteWebGL.createWithTexture = function (texture, rect, offset) { /** Creates an sprite with a texture and a rect. The offset will be (0,0). */ - if (sprite && sprite.initWithTexture(texture, rect)) { + if (sprite && sprite.initWithTexture(texture, rect)) return sprite; - } - return null; - break; - - case 3: - /** Creates an sprite with a texture, a rect and offset. */ - // not implement - cc.Assert(0, ""); return null; break; @@ -2765,9 +2141,9 @@ cc.SpriteWebGL.createWithTexture = function (texture, rect, offset) { * //create a sprite with filename and rect * var sprite2 = cc.Sprite.create("HelloHTML5World.png",cc.rect(0,0,480,320)); */ -cc.SpriteWebGL.create = function (fileName, rect) { +cc.Sprite.create = function (fileName, rect) { var argnum = arguments.length; - var sprite = new cc.SpriteWebGL(); + var sprite = new cc.Sprite(); if (argnum === 0) { if (sprite.init()) return sprite; @@ -2796,7 +2172,7 @@ cc.SpriteWebGL.create = function (fileName, rect) { * //create a sprite with a sprite frame * var sprite = cc.Sprite.createWithSpriteFrameName('grossini_dance_01.png'); */ -cc.SpriteWebGL.createWithSpriteFrameName = function (spriteFrameName) { +cc.Sprite.createWithSpriteFrameName = function (spriteFrameName) { var spriteFrame = null; if (typeof(spriteFrameName) == 'string') { spriteFrame = cc.SpriteFrameCache.getInstance().getSpriteFrame(spriteFrameName); @@ -2808,7 +2184,7 @@ cc.SpriteWebGL.createWithSpriteFrameName = function (spriteFrameName) { cc.log("Invalid argument. Expecting string."); return null; } - var sprite = new cc.SpriteWebGL(); + var sprite = new cc.Sprite(); if (sprite && sprite.initWithSpriteFrame(spriteFrame)) { return sprite; } @@ -2831,12 +2207,10 @@ cc.SpriteWebGL.createWithSpriteFrameName = function (spriteFrameName) { * //create a sprite with a sprite frame * var sprite = cc.Sprite.createWithSpriteFrame(spriteFrame); */ -cc.SpriteWebGL.createWithSpriteFrame = function (spriteFrame) { - var sprite = new cc.SpriteWebGL(); +cc.Sprite.createWithSpriteFrame = function (spriteFrame) { + var sprite = new cc.Sprite(); if (sprite && sprite.initWithSpriteFrame(spriteFrame)) { return sprite; } return null; }; - -cc.Sprite = cc.Browser.supportWebGL ? cc.SpriteWebGL : cc.SpriteCanvas; diff --git a/cocos2d/sprite_nodes/CCSpriteBatchNode.js b/cocos2d/sprite_nodes/CCSpriteBatchNode.js index 04e42a2131..535d3e7ae3 100644 --- a/cocos2d/sprite_nodes/CCSpriteBatchNode.js +++ b/cocos2d/sprite_nodes/CCSpriteBatchNode.js @@ -33,7 +33,7 @@ cc.DEFAULT_SPRITE_BATCH_CAPACITY = 29; /** *

* In Canvas render mode ,cc.SpriteBatchNodeCanvas is like a normal node: if it contains children.
- * If its _useCache is set to true, it can cache the result that all children of SpriteBatchNodeCanvas to a canvas
+ * If its _useCache is set to true, it can cache the result that all children of SpriteBatchNode to a canvas
* (often known as "batch draw").
*
* A cc.SpriteBatchNode can reference one and only one texture (one image file, one texture atlas).
@@ -51,668 +51,9 @@ cc.DEFAULT_SPRITE_BATCH_CAPACITY = 29; * @extends cc.Node * @example * //create a SpriteBatchNode - * var parent2 = cc.SpriteBatchNodeCanvas.create("res/animations/grossini.png", 50); - */ -cc.SpriteBatchNodeCanvas = cc.Node.extend(/** @lends cc.SpriteBatchNodeCanvas# */{ - /// ---- common properties start ---- - _textureAtlas:null, - _blendFunc:null, - // all descendants: chlidren, gran children, etc... - _descendants:null, - - /** - *

- * This is the opposite of "addQuadFromSprite.
- * It add the sprite to the children and descendants array, but it doesn't update add it to the texture atlas
- *

- * @param {cc.Sprite} child - * @param {Number} z zOrder - * @param {Number} aTag - * @return {cc.SpriteBatchNode} - */ - addSpriteWithoutQuad:function (child, z, aTag) { - cc.Assert(child != null, "SpriteBatchNode.addQuadFromSprite():Argument must be non-nil"); - cc.Assert((child instanceof cc.Sprite), "cc.SpriteBatchNode only supports cc.Sprites as children"); - - // quad index is Z - child.setAtlasIndex(z); - - // XXX: optimize with a binary search - var i = 0; - if (this._descendants && this._descendants.length > 0) { - for (var index = 0; index < this._descendants.length; index++) { - var obj = this._descendants[index]; - if (obj && (obj.getAtlasIndex() >= z)) - ++i; - } - } - this._descendants = cc.ArrayAppendObjectToIndex(this._descendants, child, i); - - // IMPORTANT: Call super, and not self. Avoid adding it to the texture atlas array - cc.Node.prototype.addChild.call(this, child, z, aTag); - - //#issue 1262 don't use lazy sorting, tiles are added as quads not as sprites, so sprites need to be added in order - this.reorderBatch(false); - return this; - }, - - // property - /** - * Return TextureAtlas of cc.SpriteBatchNode - * @return {cc.TextureAtlas} - */ - getTextureAtlas:function () { - return this._textureAtlas; - }, - - /** - * TextureAtlas of cc.SpriteBatchNode setter - * @param {cc.TextureAtlas} textureAtlas - */ - setTextureAtlas:function (textureAtlas) { - if (textureAtlas != this._textureAtlas) { - this._textureAtlas = textureAtlas; - } - }, - - /** - * Return Descendants of cc.SpriteBatchNode - * @return {Array} - */ - getDescendants:function () { - return this._descendants; - }, - - /** - *

- * initializes a cc.SpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and a capacity of children.
- * The capacity will be increased in 33% in runtime if it run out of space.
- * The file will be loaded using the TextureMgr. - *

- * @param {String} fileImage - * @param {Number} capacity - * @return {Boolean} - */ - initWithFile:function (fileImage, capacity) { - var texture2D = cc.TextureCache.getInstance().textureForKey(fileImage); - if (!texture2D) - texture2D = cc.TextureCache.getInstance().addImage(fileImage); - return this.initWithTexture(texture2D, capacity); - }, - - _setNodeDirtyForCache:function () { - this._cacheDirty = true; - }, - - /** - *

- * initializes a cc.SpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and a capacity of children.
- * The capacity will be increased in 33% in runtime if it run out of space.
- * The file will be loaded using the TextureMgr. - *

- * @param {String} fileImage - * @param {Number} capacity - * @return {Boolean} - */ - init:function (fileImage, capacity) { - var texture2D = cc.TextureCache.getInstance().textureForKey(fileImage); - if (!texture2D) - texture2D = cc.TextureCache.getInstance().addImage(fileImage); - return this.initWithTexture(texture2D, capacity); - }, - - /** - * increase Atlas Capacity - */ - increaseAtlasCapacity:function () { - // if we're going beyond the current TextureAtlas's capacity, - // all the previously initialized sprites will need to redo their texture coords - // this is likely computationally expensive - var quantity = Math.floor((this._textureAtlas.getCapacity() + 1) * 4 / 3); - - cc.log("cocos2d: CCSpriteBatchNode: resizing TextureAtlas capacity from " + this._textureAtlas.getCapacity() + " to " + quantity + "."); - - if (!this._textureAtlas.resizeCapacity(quantity)) { - // serious problems - cc.log("cocos2d: WARNING: Not enough memory to resize the atlas"); - cc.Assert(false, "Not enough memory to resize the atla"); - } - }, - - /** - * removes a child given a certain index. It will also cleanup the running actions depending on the cleanup parameter. - * @warning Removing a child from a cc.SpriteBatchNode is very slow - * @param {Number} index - * @param {Boolean} doCleanup - */ - removeChildAtIndex:function (index, doCleanup) { - this.removeChild(this._children[index], doCleanup); - }, - - /** - * rebuild index in order for child - * @param {cc.Sprite} pobParent - * @param {Number} index - * @return {Number} - */ - rebuildIndexInOrder:function (pobParent, index) { - var children = pobParent.getChildren(); - if (children && children.length > 0) { - for (var i = 0; i < children.length; i++) { - var obj = children[i]; - if (obj && (obj.getZOrder() < 0)) { - index = this.rebuildIndexInOrder(obj, index); - } - } - } - // ignore self (batch node) - if (!pobParent == this) { - pobParent.setAtlasIndex(index); - index++; - } - if (children && children.length > 0) { - for (i = 0; i < children.length; i++) { - obj = children[i]; - if (obj && (obj.getZOrder() >= 0)) { - index = this.rebuildIndexInOrder(obj, index); - } - } - } - return index; - }, - - /** - * get highest atlas index in child - * @param {cc.Sprite} sprite - * @return {Number} - */ - highestAtlasIndexInChild:function (sprite) { - var children = sprite.getChildren(); - - if (!children || children.length == 0) - return sprite.getAtlasIndex(); - else - return this.highestAtlasIndexInChild(children[children.length - 1]); - }, - - /** - * get lowest atlas index in child - * @param {cc.Sprite} sprite - * @return {Number} - */ - lowestAtlasIndexInChild:function (sprite) { - var children = sprite.getChildren(); - - if (!children || children.length == 0) - return sprite.getAtlasIndex(); - else - return this.lowestAtlasIndexInChild(children[children.length - 1]); - }, - - /** - * get atlas index for child - * @param {cc.Sprite} sprite - * @param {Number} nZ - * @return {Number} - */ - atlasIndexForChild:function (sprite, nZ) { - var brothers = sprite.getParent().getChildren(); - var childIndex = cc.ArrayGetIndexOfObject(brothers, sprite); - - // ignore parent Z if parent is spriteSheet - var ignoreParent = sprite.getParent() == this; - var previous = null; - if (childIndex > 0 && childIndex < cc.UINT_MAX) - previous = brothers[childIndex - 1]; - - // first child of the sprite sheet - if (ignoreParent) { - if (childIndex == 0) - return 0; - return this.highestAtlasIndexInChild(previous) + 1; - } - - // parent is a cc.Sprite, so, it must be taken into account - // first child of an cc.Sprite ? - var selParent; - if (childIndex == 0) { - selParent = sprite.getParent(); - - // less than parent and brothers - if (nZ < 0) - return selParent.getAtlasIndex(); - else - return selParent.getAtlasIndex() + 1; - } else { - // previous & sprite belong to the same branch - if ((previous.getZOrder() < 0 && nZ < 0) || (previous.getZOrder() >= 0 && nZ >= 0)) - return this.highestAtlasIndexInChild(previous) + 1; - - // else (previous < 0 and sprite >= 0 ) - selParent = sprite.getParent(); - return selParent.getAtlasIndex() + 1; - } - }, - - /** - * Sprites use this to start sortChildren, don't call this manually - * @param {Boolean} reorder - */ - reorderBatch:function (reorder) { - this._reorderChildDirty = reorder; - }, - - /** - * set the source blending function for the texture - * @param {Number | cc.BlendFunc} src - * @param {Number} dst - */ - setBlendFunc:function (src, dst) { - if (arguments.length == 1) - this._blendFunc = src; - else - this._blendFunc = {src:src, dst:dst}; - }, - - /** - * returns the blending function used for the texture - * @return {cc.BlendFunc} - */ - getBlendFunc:function () { - return this._blendFunc; - }, - - /** - * (override reorderChild of cc.Node) - * @override - * @param {cc.Sprite} child - * @param {Number} zOrder - */ - reorderChild:function (child, zOrder) { - cc.Assert(child != null, "SpriteBatchNode.addChild():the child should not be null"); - cc.Assert(this._children.indexOf(child) > -1, "SpriteBatchNode.addChild():Child doesn't belong to Sprite"); - - if (zOrder === child.getZOrder()) - return; - - //set the z-order and sort later - cc.Node.prototype.reorderChild.call(this, child, zOrder); - this.setNodeDirty(); - }, - - /** - * remove child from cc.SpriteBatchNode (override removeChild of cc.Node) - * @param {cc.Sprite} child - * @param cleanup - */ - removeChild:function (child, cleanup) { - // explicit null handling - if (child == null) - return; - - cc.Assert(this._children.indexOf(child) > -1, "SpriteBatchNode.addChild():sprite batch node should contain the child"); - - // cleanup before removing - this.removeSpriteFromAtlas(child); - cc.Node.prototype.removeChild.call(this, child, cleanup); - }, - /// ---- common properties end ---- - - _textureForCanvas:null, - _renderTexture:null, - _useCache:false, - _originalTexture:null, - - /** - * Constructor - * @param {String} fileImage - */ - ctor:function (fileImage) { - cc.Node.prototype.ctor.call(this); - if (fileImage) - this.init(fileImage, cc.DEFAULT_SPRITE_BATCH_CAPACITY); - - this._renderTexture = cc.RenderTexture.create(cc.canvas.width, cc.canvas.height); - this.setContentSize(cc.size(cc.canvas.width, cc.canvas.height)); - }, - - /** - *

- * Updates a quad at a certain index into the texture atlas. The CCSprite won't be added into the children array.
- * This method should be called only when you are dealing with very big AtlasSrite and when most of the cc.Sprite won't be updated.
- * For example: a tile map (cc.TMXMap) or a label with lots of characters (BitmapFontAtlas)
- *

- * @param {cc.Sprite} sprite - * @param {Number} index - */ - updateQuadFromSprite:function (sprite, index) { - cc.Assert(sprite != null, "SpriteBatchNode.addQuadFromSprite():Argument must be non-nil"); - cc.Assert((sprite instanceof cc.Sprite), "cc.SpriteBatchNode only supports cc.Sprites as children"); - - // - // update the quad directly. Don't add the sprite to the scene graph - // - sprite.setBatchNode(this); - sprite.setAtlasIndex(index); - - sprite.setDirty(true); - // UpdateTransform updates the textureAtlas quad - sprite.updateTransform(); - }, - - /** - *

- * Inserts a quad at a certain index into the texture atlas. The cc.Sprite won't be added into the children array.
- * This method should be called only when you are dealing with very big AtlasSprite and when most of the cc.Sprite won't be updated.
- * For example: a tile map (cc.TMXMap) or a label with lots of characters (cc.LabelBMFont) - *

- * @param {cc.Sprite} sprite - * @param {Number} index - */ - insertQuadFromSprite:function (sprite, index) { - cc.Assert(sprite != null, "Argument must be non-NULL"); - cc.Assert(sprite instanceof cc.Sprite, "cc.SpriteBatchNode only supports cc.Sprites as children"); - - // - // update the quad directly. Don't add the sprite to the scene graph - // - sprite.setBatchNode(this); - sprite.setAtlasIndex(index); - - // XXX: updateTransform will update the textureAtlas too, using updateQuad. - // XXX: so, it should be AFTER the insertQuad - sprite.setDirty(true); - sprite.updateTransform(); - this._children = cc.ArrayAppendObjectToIndex(this._children, sprite, index); - }, - - setContentSize:function (size) { - if (!size) - return; - cc.Node.prototype.setContentSize.call(this, size); - this._renderTexture.setContentSize(size); - }, - - /** - *

- * initializes a CCSpriteBatchNode with a texture2d and capacity of children.
- * The capacity will be increased in 33% in runtime if it run out of space. - *

- * @param {cc.Texture2D} tex - * @param {Number} capacity - * @return {Boolean} - */ - initWithTexture:function (tex, capacity) { - this._children = []; - this._descendants = []; - - this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST); - - this._originalTexture = tex; - this._textureForCanvas = tex; - return true; - }, - - /** - * addChild helper, faster than insertChild - * @param {cc.Sprite} sprite - */ - appendChild:function (sprite) { - this._reorderChildDirty = true; - sprite.setBatchNode(this); - sprite.setDirty(true); - - cc.ArrayAppendObject(this._descendants, sprite); - var index = this._descendants.length - 1; - sprite.setAtlasIndex(index); - - // add children recursively - var children = sprite.getChildren(); - for (var i = 0; i < children.length; i++) - this.appendChild(children[i]); - }, - - /** - * remove sprite from TextureAtlas - * @param {cc.Sprite} sprite - */ - removeSpriteFromAtlas:function (sprite) { - // Cleanup sprite. It might be reused (issue #569) - sprite.setBatchNode(null); - - var index = cc.ArrayGetIndexOfObject(this._descendants, sprite); - if (index != -1) { - cc.ArrayRemoveObjectAtIndex(this._descendants, index); - - // update all sprites beyond this one - var len = this._descendants.length; - for (; index < len; ++index) { - var s = this._descendants[index]; - s.setAtlasIndex(s.getAtlasIndex() - 1); - } - } - - // remove children recursively - var children = sprite.getChildren(); - if (children && children.length > 0) { - for (var i = 0; i < children.length; i++) - if (children[i]) - this.removeSpriteFromAtlas(children[i]); - } - }, - // CCTextureProtocol - /** - * Return texture of cc.SpriteBatchNode - * @return {cc.Texture2D|HTMLImageElement|HTMLCanvasElement} - */ - getTexture:function () { - if (this._useCache) - return this._renderTexture.getCanvas(); - return this._textureForCanvas; - }, - - /** - * texture of cc.SpriteBatchNode setter - * @param {cc.Texture2D} texture - */ - setTexture:function (texture) { - this._textureForCanvas = texture; - for (var i = 0; i < this._children.length; i++) - this._children[i].setTexture(texture); - }, - - /** - * don't call visit on it's children ( override visit of cc.Node ) - * @override - * @param {CanvasContext} ctx - */ - visit:function (ctx) { - var context = ctx || cc.renderContext; - // quick return if not visible - if (!this._visible) - return; - - context.save(); - this.transform(ctx); - var i; - if (this._useCache) { - if (this._cacheDirty) { - //add dirty region - this._renderTexture.clear(); - this._renderTexture.context.save(); - this._renderTexture.context.translate(this._anchorPointInPoints.x, -(this._anchorPointInPoints.y )); - if (this._children) { - this.sortAllChildren(); - for (i = 0; i < this._children.length; i++) { - if (this._children[i]) - this._children[i].visit(this._renderTexture.context); - } - } - this._renderTexture.context.restore(); - this._cacheDirty = false; - } - // draw RenderTexture - this.draw(ctx); - } else { - if (this._children) { - this.sortAllChildren(); - for (i = 0; i < this._children.length; i++) { - if (this._children[i]) - this._children[i].visit(context); - } - } - } - context.restore(); - }, - - /** - * add child to cc.SpriteBatchNode (override addChild of cc.Node) - * @override - * @param {cc.Sprite} child - * @param {Number} zOrder - * @param {Number} tag - */ - addChild:function (child, zOrder, tag) { - if (child == null) - return; - - if (arguments.length === 4) - if (arguments[3] == true) { - cc.Node.prototype.addChild.call(this, child, zOrder, tag); - this.setNodeDirty(); - return; - } - - zOrder = (zOrder == null) ? child.getZOrder() : zOrder; - tag = (tag == null) ? child.getTag() : tag; - - cc.Assert(child != null, "SpriteBatchNode.addChild():child should not be null"); - cc.Assert((child instanceof cc.Sprite), "cc.SpriteBatchNode only supports cc.Sprites as children"); - - cc.Node.prototype.addChild.call(this, child, zOrder, tag); - this.appendChild(child); - this.setNodeDirty(); - }, - - /** - *

Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter.
- * (override removeAllChildren of cc.Node)

- * @param {Boolean} cleanup - */ - removeAllChildren:function (cleanup) { - // Invalidate atlas index. issue #569 - // useSelfRender should be performed on all descendants. issue #1216 - if (this._descendants && this._descendants.length > 0) { - for (var i = 0; i < this._descendants.length; i++) { - if (this._descendants[i]) - this._descendants[i].setBatchNode(null); - } - } - - cc.Node.prototype.removeAllChildren.call(this, cleanup); - this._descendants = []; - }, - - sortAllChildren:function () { - if (this._reorderChildDirty) { - var i = 0, j = 0, length = this._children.length; - //insertion sort - for (i = 1; i < length; i++) { - var tempItem = this._children[i]; - j = i - 1; - - //continue moving element downwards while zOrder is smaller or when zOrder is the same but orderOfArrival is smaller - while (j >= 0 && (tempItem.getZOrder() < this._children[j].getZOrder() || - (tempItem.getZOrder() == this._children[j].getZOrder() && tempItem.getOrderOfArrival() < this._children[j].getOrderOfArrival()))) { - this._children[j + 1] = this._children[j]; - j--; - } - this._children[j + 1] = tempItem; - } - - //sorted now check all children - if (this._children.length > 0) { - //first sort all children recursively based on zOrder - this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.sortAllChildren); - } - this._reorderChildDirty = false; - } - }, - - /** - * draw cc.SpriteBatchNode (override draw of cc.Node) - * @param {CanvasContext} ctx - */ - draw:function (ctx) { - var context = ctx || cc.renderContext; - //context.globalAlpha = this._opacity / 255; - var pos = cc.p(0 | ( -this._anchorPointInPoints.x), 0 | ( -this._anchorPointInPoints.y)); - //direct draw image by canvas drawImage - if (this._renderTexture) - context.drawImage(this._renderTexture.getCanvas(), pos.x, -(pos.y + this._renderTexture.getCanvas().height)); - } -}); - -/** - *

- * creates a cc.SpriteBatchNodeCanvas with a file image (.png, .jpg etc) with a default capacity of 29 children.
- * The capacity will be increased in 33% in runtime if it run out of space.
- * The file will be loaded using the TextureMgr.
- *

- * @param {String} fileImage - * @param {Number} capacity - * @return {cc.SpriteBatchNodeCanvas} - * @example - * //create a SpriteBatchNode * var parent2 = cc.SpriteBatchNode.create("res/animations/grossini.png", 50); */ -cc.SpriteBatchNodeCanvas.create = function (fileImage, capacity) { - capacity = capacity || cc.DEFAULT_SPRITE_BATCH_CAPACITY; - var batchNode = new cc.SpriteBatchNodeCanvas(); - batchNode.init(fileImage, capacity); - return batchNode; -}; - -/** - *

- * creates a cc.SpriteBatchNodeCanvas with a texture2d and a default capacity of 29 children.
- * The capacity will be increased in 33% in runtime if it run out of space.
- *

- * @param {cc.Texture2D} texture - * @param {Number} capacity - * @return {cc.SpriteBatchNodeCanvas} - */ -cc.SpriteBatchNodeCanvas.createWithTexture = function (texture, capacity) { - capacity = capacity || cc.DEFAULT_SPRITE_BATCH_CAPACITY; - var batchNode = new cc.SpriteBatchNodeCanvas(); - batchNode.initWithTexture(texture, capacity); - return batchNode; -}; - -/** - *

- * In WebGL render mode ,cc.SpriteBatchNode is like a batch node: if it contains children, it will draw them in 1 single OpenGL call
- * (often known as "batch draw").
- *
- * A cc.SpriteBatchNode can reference one and only one texture (one image file, one texture atlas).
- * Only the cc.Sprites that are contained in that texture can be added to the cc.SpriteBatchNode.
- * All cc.Sprites added to a cc.SpriteBatchNode are drawn in one WebGL draw call.
- * If the cc.Sprites are not added to a cc.SpriteBatchNode then an WebGL draw call will be needed for each one, which is less efficient.
- *
- * Limitations:
- * - The only object that is accepted as child (or grandchild, grand-grandchild, etc...) is cc.Sprite or any subclass of cc.Sprite.
- * eg: particles, labels and layer can't be added to a cc.SpriteBatchNode.
- * - Either all its children are Aliased or Antialiased. It can't be a mix.
- * This is because "alias" is a property of the texture, and all the sprites share the same texture.
- *

- * @class - * @extends cc.Node - * @example - * //create a SpriteBatchNodeWebGL - * var parent2 = cc.SpriteBatchNodeWebGL.create("res/animations/grossini.png", 50); - */ -cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ - /// ---- common properties start ---- +cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{ _textureAtlas:null, _blendFunc:null, // all descendants: chlidren, gran children, etc... @@ -736,15 +77,15 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ child.setAtlasIndex(z); // XXX: optimize with a binary search - var i = 0; - if (this._descendants && this._descendants.length > 0) { - for (var index = 0; index < this._descendants.length; index++) { - var obj = this._descendants[index]; + var i = 0, locDescendants = this._descendants; + if (locDescendants && locDescendants.length > 0) { + for (var index = 0; index < locDescendants.length; index++) { + var obj = locDescendants[index]; if (obj && (obj.getAtlasIndex() >= z)) ++i; } } - this._descendants = cc.ArrayAppendObjectToIndex(this._descendants, child, i); + this._descendants = cc.ArrayAppendObjectToIndex(locDescendants, child, i); // IMPORTANT: Call super, and not self. Avoid adding it to the texture atlas array cc.Node.prototype.addChild.call(this, child, z, aTag); @@ -826,9 +167,10 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ // if we're going beyond the current TextureAtlas's capacity, // all the previously initialized sprites will need to redo their texture coords // this is likely computationally expensive - var quantity = 0 | ((this._textureAtlas.getCapacity() + 1) * 4 / 3); + var locCapacity = this._textureAtlas.getCapacity(); + var quantity = Math.floor((locCapacity + 1) * 4 / 3); - cc.log("cocos2d: CCSpriteBatchNode: resizing TextureAtlas capacity from " + this._textureAtlas.getCapacity() + " to [" + quantity + "]."); + cc.log("cocos2d: CCSpriteBatchNode: resizing TextureAtlas capacity from " + locCapacity + " to " + quantity + "."); if (!this._textureAtlas.resizeCapacity(quantity)) { // serious problems @@ -1012,22 +354,34 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ // cleanup before removing this.removeSpriteFromAtlas(child); - cc.Node.prototype.removeChild.call(this, child, cleanup); }, - /// ---- common properties end ---- + _mvpMatrix:null, + _textureForCanvas:null, + _useCache:false, + _originalTexture:null, + /** * Constructor * @param {String} fileImage */ - ctor:function (fileImage) { + ctor: null, + + _ctorForCanvas: function (fileImage) { + cc.Node.prototype.ctor.call(this); + if (fileImage) + this.init(fileImage, cc.DEFAULT_SPRITE_BATCH_CAPACITY); + }, + + _ctorForWebGL: function (fileImage) { cc.Node.prototype.ctor.call(this); this._mvpMatrix = new cc.kmMat4(); if (fileImage) this.init(fileImage, cc.DEFAULT_SPRITE_BATCH_CAPACITY); }, + /** *

* Updates a quad at a certain index into the texture atlas. The CCSprite won't be added into the children array.
@@ -1037,12 +391,30 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ * @param {cc.Sprite} sprite * @param {Number} index */ - updateQuadFromSprite:function (sprite, index) { + updateQuadFromSprite:null, + + _updateQuadFromSpriteForCanvas:function (sprite, index) { + cc.Assert(sprite != null, "SpriteBatchNode.addQuadFromSprite():Argument must be non-nil"); + cc.Assert((sprite instanceof cc.Sprite), "cc.SpriteBatchNode only supports cc.Sprites as children"); + + // + // update the quad directly. Don't add the sprite to the scene graph + // + sprite.setBatchNode(this); + sprite.setAtlasIndex(index); + + sprite.setDirty(true); + // UpdateTransform updates the textureAtlas quad + sprite.updateTransform(); + }, + + _updateQuadFromSpriteForWebGL:function (sprite, index) { cc.Assert(sprite != null, "SpriteBatchNode.addQuadFromSprite():Argument must be non-nil"); cc.Assert((sprite instanceof cc.Sprite), "cc.SpriteBatchNode only supports cc.Sprites as children"); // make needed room - while (index >= this._textureAtlas.getCapacity() || this._textureAtlas.getCapacity() == this._textureAtlas.getTotalQuads()) { + var locCapacity = this._textureAtlas.getCapacity(); + while (index >= locCapacity || locCapacity == this._textureAtlas.getTotalQuads()) { this.increaseAtlasCapacity(); } @@ -1058,17 +430,19 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ }, _swap:function (oldIndex, newIndex) { - var quads = this._textureAtlas.getQuads(); - var tempItem = this._descendants[oldIndex]; + var locDescendants = this._descendants; + var locTextureAtlas = this._textureAtlas; + var quads = locTextureAtlas.getQuads(); + var tempItem = locDescendants[oldIndex]; var tempIteQuad = cc.V3F_C4B_T2F_QuadCopy(quads[oldIndex]); //update the index of other swapped item - this._descendants[newIndex].setAtlasIndex(oldIndex); - this._descendants[oldIndex] = this._descendants[newIndex]; + locDescendants[newIndex].setAtlasIndex(oldIndex); + locDescendants[oldIndex] = locDescendants[newIndex]; - this._textureAtlas.updateQuad(quads[newIndex], oldIndex); - this._descendants[newIndex] = tempItem; - this._textureAtlas.updateQuad(tempIteQuad, newIndex); + locTextureAtlas.updateQuad(quads[newIndex], oldIndex); + locDescendants[newIndex] = tempItem; + locTextureAtlas.updateQuad(tempIteQuad, newIndex); }, /** @@ -1080,12 +454,32 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ * @param {cc.Sprite} sprite * @param {Number} index */ - insertQuadFromSprite:function (sprite, index) { + insertQuadFromSprite:null, + + _insertQuadFromSpriteForCanvas:function (sprite, index) { + cc.Assert(sprite != null, "Argument must be non-NULL"); + cc.Assert(sprite instanceof cc.Sprite, "cc.SpriteBatchNode only supports cc.Sprites as children"); + + // + // update the quad directly. Don't add the sprite to the scene graph + // + sprite.setBatchNode(this); + sprite.setAtlasIndex(index); + + // XXX: updateTransform will update the textureAtlas too, using updateQuad. + // XXX: so, it should be AFTER the insertQuad + sprite.setDirty(true); + sprite.updateTransform(); + this._children = cc.ArrayAppendObjectToIndex(this._children, sprite, index); + }, + + _insertQuadFromSpriteForWebGL:function (sprite, index) { cc.Assert(sprite != null, "Argument must be non-NULL"); cc.Assert(sprite instanceof cc.Sprite, "cc.SpriteBatchNode only supports cc.Sprites as children"); // make needed room - while (index >= this._textureAtlas.getCapacity() || this._textureAtlas.getCapacity() === this._textureAtlas.getTotalQuads()) + var locTextureAtlas = this._textureAtlas; + while (index >= locTextureAtlas.getCapacity() || locTextureAtlas.getCapacity() === locTextureAtlas.getTotalQuads()) this.increaseAtlasCapacity(); // @@ -1093,7 +487,7 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ // sprite.setBatchNode(this); sprite.setAtlasIndex(index); - this._textureAtlas.insertQuad(sprite.getQuad(), index); + locTextureAtlas.insertQuad(sprite.getQuad(), index); // XXX: updateTransform will update the textureAtlas too, using updateQuad. // XXX: so, it should be AFTER the insertQuad @@ -1170,10 +564,23 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ * The capacity will be increased in 33% in runtime if it run out of space. *

* @param {cc.Texture2D} tex - * @param {Number} capacity + * @param {Number} [capacity] * @return {Boolean} */ - initWithTexture:function (tex, capacity) { + initWithTexture:null, + + _initWithTextureForCanvas:function (tex, capacity) { + this._children = []; + this._descendants = []; + + this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST); + + this._originalTexture = tex; + this._textureForCanvas = tex; + return true; + }, + + _initWithTextureForWebGL:function (tex, capacity) { this._children = []; this._descendants = []; @@ -1185,6 +592,7 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_TEXTURECOLOR)); return true; }, + /** * add child helper * @param {cc.Sprite} sprite @@ -1195,26 +603,27 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ sprite.setAtlasIndex(index); sprite.setDirty(true); - if (this._textureAtlas.getTotalQuads() == this._textureAtlas.getCapacity()) + var locTextureAtlas = this._textureAtlas; + if (locTextureAtlas.getTotalQuads() >= locTextureAtlas.getCapacity()) this.increaseAtlasCapacity(); - this._textureAtlas.insertQuad(sprite.getQuad(), index); + locTextureAtlas.insertQuad(sprite.getQuad(), index); this._descendants = cc.ArrayAppendObjectToIndex(this._descendants, sprite, index); // update indices - var i = index + 1; - if (this._descendants && this._descendants.length > 0) { - for (; i < this._descendants.length; i++) - this._descendants[i].setAtlasIndex(this._descendants[i].getAtlasIndex() + 1); + var i = index + 1, locDescendant = this._descendants; + if (locDescendant && locDescendant.length > 0) { + for (; i < locDescendant.length; i++) + locDescendant[i].setAtlasIndex(locDescendant[i].getAtlasIndex() + 1); } // add children recursively - var children = sprite.getChildren(); - if (children && children.length > 0) { - for (i = 0; i < children.length; i++) { - if (children[i]) { - var getIndex = this.atlasIndexForChild(children[i], children[i].getZOrder()); - this.insertChild(children[i], getIndex); + var locChildren = sprite.getChildren(); + if (locChildren && locChildren.length > 0) { + for (i = 0; i < locChildren.length; i++) { + if (locChildren[i]) { + var getIndex = this.atlasIndexForChild(locChildren[i], locChildren[i].getZOrder()); + this.insertChild(locChildren[i], getIndex); } } } @@ -1224,18 +633,36 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ * addChild helper, faster than insertChild * @param {cc.Sprite} sprite */ - appendChild:function (sprite) { + appendChild:null, + + _appendChildForCanvas:function (sprite) { + this._reorderChildDirty = true; + sprite.setBatchNode(this); + sprite.setDirty(true); + + this._descendants.push(sprite); + var index = this._descendants.length - 1; + sprite.setAtlasIndex(index); + + // add children recursively + var children = sprite.getChildren(); + for (var i = 0; i < children.length; i++) + this.appendChild(children[i]); + }, + + _appendChildForWebGL:function (sprite) { this._reorderChildDirty = true; sprite.setBatchNode(this); sprite.setDirty(true); - cc.ArrayAppendObject(this._descendants, sprite); + this._descendants.push(sprite); var index = this._descendants.length - 1; sprite.setAtlasIndex(index); - if (this._textureAtlas.getTotalQuads() == this._textureAtlas.getCapacity()) + var locTextureAtlas = this._textureAtlas; + if (locTextureAtlas.getTotalQuads() == locTextureAtlas.getCapacity()) this.increaseAtlasCapacity(); - this._textureAtlas.insertQuad(sprite.getQuad(), index); + locTextureAtlas.insertQuad(sprite.getQuad(), index); // add children recursively var children = sprite.getChildren(); @@ -1247,20 +674,49 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ * remove sprite from TextureAtlas * @param {cc.Sprite} sprite */ - removeSpriteFromAtlas:function (sprite) { + removeSpriteFromAtlas:null, + + _removeSpriteFromAtlasForCanvas:function (sprite) { + // Cleanup sprite. It might be reused (issue #569) + sprite.setBatchNode(null); + var locDescendants = this._descendants; + var index = cc.ArrayGetIndexOfObject(locDescendants, sprite); + if (index != -1) { + cc.ArrayRemoveObjectAtIndex(locDescendants, index); + + // update all sprites beyond this one + var len = locDescendants.length; + for (; index < len; ++index) { + var s = locDescendants[index]; + s.setAtlasIndex(s.getAtlasIndex() - 1); + } + } + + // remove children recursively + var children = sprite.getChildren(); + if (children && children.length > 0) { + for (var i = 0; i < children.length; i++) + if (children[i]) + this.removeSpriteFromAtlas(children[i]); + } + }, + + _removeSpriteFromAtlasForWebGL:function (sprite) { this._textureAtlas.removeQuadAtIndex(sprite.getAtlasIndex()); // remove from TextureAtlas // Cleanup sprite. It might be reused (issue #569) sprite.setBatchNode(null); - var index = cc.ArrayGetIndexOfObject(this._descendants, sprite); + var locDescendants = this._descendants; + var index = cc.ArrayGetIndexOfObject(locDescendants, sprite); if (index != -1) { - cc.ArrayRemoveObjectAtIndex(this._descendants, index); + cc.ArrayRemoveObjectAtIndex(locDescendants, index); // update all sprites beyond this one - var len = this._descendants.length; + + var len = locDescendants.length; for (; index < len; ++index) { - var s = this._descendants[index]; + var s = locDescendants[index]; s.setAtlasIndex(s.getAtlasIndex() - 1); } } @@ -1273,13 +729,18 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ this.removeSpriteFromAtlas(children[i]); } }, - // CCTextureProtocol /** * Return texture of cc.SpriteBatchNode * @return {cc.Texture2D|HTMLImageElement|HTMLCanvasElement} */ - getTexture:function () { + getTexture:null, + + _getTextureForCanvas:function () { + return this._textureForCanvas; + }, + + _getTextureForWebGL:function () { return this._textureAtlas.getTexture(); }, @@ -1287,7 +748,16 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ * texture of cc.SpriteBatchNode setter * @param {cc.Texture2D} texture */ - setTexture:function (texture) { + setTexture:null, + + _setTextureForCanvas:function (texture) { + this._textureForCanvas = texture; + var locChildren = this._children; + for (var i = 0; i < locChildren.length; i++) + locChildren[i].setTexture(texture); + }, + + _setTextureForWebGL:function (texture) { this._textureAtlas.setTexture(texture); this._updateBlendFunc(); }, @@ -1295,11 +765,33 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ /** * don't call visit on it's children ( override visit of cc.Node ) * @override - * @param {CanvasContext} ctx + * @param {CanvasRenderingContext2D} ctx */ - visit:function (ctx) { + visit:null, + + _visitForCanvas:function (ctx) { + var context = ctx || cc.renderContext; + // quick return if not visible + if (!this._visible) + return; + + context.save(); + this.transform(ctx); + var i, locChildren = this._children; + + if (locChildren) { + this.sortAllChildren(); + for (i = 0; i < locChildren.length; i++) { + if (locChildren[i]) + locChildren[i].visit(context); + } + } + + context.restore(); + }, + + _visitForWebGL:function (ctx) { var gl = ctx || cc.renderContext; - //cc.PROFILER_START_CATEGORY(kCCProfilerCategoryBatchSprite, "CCSpriteBatchNode - visit"); // CAREFUL: // This visit is almost identical to CocosNode#visit @@ -1311,37 +803,47 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ if (!this._visible) return; cc.kmGLPushMatrix(); - if (this._grid && this._grid.isActive()) { - this._grid.beforeDraw(); + var locGrid = this._grid; + if (locGrid && locGrid.isActive()) { + locGrid.beforeDraw(); this.transformAncestors(); } this.sortAllChildren(); this.transform(gl); this.draw(gl); - if (this._grid && this._grid.isActive()) - this._grid.afterDraw(this); + if (locGrid && locGrid.isActive()) + locGrid.afterDraw(this); cc.kmGLPopMatrix(); this.setOrderOfArrival(0); - //cc.PROFILER_STOP_CATEGORY(kCCProfilerCategoryBatchSprite, "CCSpriteBatchNode - visit"); }, /** * add child to cc.SpriteBatchNode (override addChild of cc.Node) * @override * @param {cc.Sprite} child - * @param {Number} zOrder - * @param {Number} tag + * @param {Number} [zOrder] + * @param {Number} [tag] */ - addChild:function (child, zOrder, tag) { + addChild: null, + + _addChildForCanvas: function (child, zOrder, tag) { if (child == null) return; - if (arguments.length === 4) - if (arguments[3] == true) { - cc.Node.prototype.addChild.call(this, child, zOrder, tag); - this.setNodeDirty(); - return; - } + zOrder = (zOrder == null) ? child.getZOrder() : zOrder; + tag = (tag == null) ? child.getTag() : tag; + + cc.Assert(child != null, "SpriteBatchNode.addChild():child should not be null"); + cc.Assert((child instanceof cc.Sprite), "cc.SpriteBatchNode only supports cc.Sprites as children"); + + cc.Node.prototype.addChild.call(this, child, zOrder, tag); + this.appendChild(child); + this.setNodeDirty(); + }, + + _addChildForWebGL: function (child, zOrder, tag) { + if (child == null) + return; zOrder = (zOrder == null) ? child.getZOrder() : zOrder; tag = (tag == null) ? child.getTag() : tag; @@ -1350,7 +852,7 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ cc.Assert((child instanceof cc.Sprite), "cc.SpriteBatchNode only supports cc.Sprites as children"); // check cc.Sprite is using the same texture id - cc.Assert(child.getTexture()._webTextureObj == this._textureAtlas.getTexture()._webTextureObj, + cc.Assert(child.getTexture() == this._textureAtlas.getTexture(), "SpriteBatchNode.addChild():cc.Sprite is not using the same texture id"); cc.Node.prototype.addChild.call(this, child, zOrder, tag); this.appendChild(child); @@ -1362,13 +864,31 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ * (override removeAllChildren of cc.Node)

* @param {Boolean} cleanup */ - removeAllChildren:function (cleanup) { + removeAllChildren:null, + + _removeAllChildrenForCanvas:function (cleanup) { + // Invalidate atlas index. issue #569 + // useSelfRender should be performed on all descendants. issue #1216 + var locDescendants = this._descendants; + if (locDescendants && locDescendants.length > 0) { + for (var i = 0, len = locDescendants.length; i < len; i++) { + if (locDescendants[i]) + locDescendants[i].setBatchNode(null); + } + } + + cc.Node.prototype.removeAllChildren.call(this, cleanup); + this._descendants = []; + }, + + _removeAllChildrenForWebGL:function (cleanup) { // Invalidate atlas index. issue #569 // useSelfRender should be performed on all descendants. issue #1216 - if (this._descendants && this._descendants.length > 0) { - for (var i = 0; i < this._descendants.length; i++) { - if (this._descendants[i]) - this._descendants[i].setBatchNode(null); + var locDescendants = this._descendants; + if (locDescendants && locDescendants.length > 0) { + for (var i = 0, len = locDescendants.length; i < len; i++) { + if (locDescendants[i]) + locDescendants[i].setBatchNode(null); } } cc.Node.prototype.removeAllChildren.call(this, cleanup); @@ -1376,20 +896,53 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ this._textureAtlas.removeAllQuads(); }, - sortAllChildren:function () { + sortAllChildren:null, + + _sortAllChildrenForCanvas:function () { + if (this._reorderChildDirty) { + var i, j = 0, locChildren = this._children; + var length = locChildren.length, tempChild; + //insertion sort + for (i = 1; i < length; i++) { + var tempItem = locChildren[i]; + j = i - 1; + tempChild = locChildren[j]; + + //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller + while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder || + ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) { + locChildren[j + 1] = tempChild; + j = j - 1; + tempChild = locChildren[j]; + } + locChildren[j + 1] = tempItem; + } + + //sorted now check all children + if (locChildren.length > 0) { + //first sort all children recursively based on zOrder + this._arrayMakeObjectsPerformSelector(locChildren, cc.Node.StateCallbackType.sortAllChildren); + } + this._reorderChildDirty = false; + } + }, + + _sortAllChildrenForWebGL:function () { if (this._reorderChildDirty) { var childrenArr = this._children; - var i, j = 0, length = childrenArr.length; + var i, j = 0, length = childrenArr.length, tempChild; //insertion sort for (i = 1; i < length; i++) { var tempItem = childrenArr[i]; j = i - 1; - - //continue moving element downwards while zOrder is smaller or when zOrder is the same but orderOfArrival is smaller - while (j >= 0 && (tempItem.getZOrder() < childrenArr[j].getZOrder() || - (tempItem.getZOrder() == childrenArr[j].getZOrder() && tempItem.getOrderOfArrival() < childrenArr[j].getOrderOfArrival()))) { - childrenArr[j + 1] = childrenArr[j]; - j--; + tempChild = childrenArr[j]; + + //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller + while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder || + ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) { + childrenArr[j + 1] = tempChild; + j = j - 1; + tempChild = childrenArr[j]; } childrenArr[j + 1] = tempItem; } @@ -1411,7 +964,9 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ /** * draw cc.SpriteBatchNode (override draw of cc.Node) */ - draw:function () { + draw:null, + + _drawForWebGL:function () { // Optimization: Fast Dispatch if (this._textureAtlas.getTotalQuads() === 0) return; @@ -1426,6 +981,36 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ } }); +if(cc.Browser.supportWebGL){ + cc.SpriteBatchNode.prototype.ctor = cc.SpriteBatchNode.prototype._ctorForWebGL; + cc.SpriteBatchNode.prototype.updateQuadFromSprite = cc.SpriteBatchNode.prototype._updateQuadFromSpriteForWebGL; + cc.SpriteBatchNode.prototype.insertQuadFromSprite = cc.SpriteBatchNode.prototype._insertQuadFromSpriteForWebGL; + cc.SpriteBatchNode.prototype.initWithTexture = cc.SpriteBatchNode.prototype._initWithTextureForWebGL; + cc.SpriteBatchNode.prototype.appendChild = cc.SpriteBatchNode.prototype._appendChildForWebGL; + cc.SpriteBatchNode.prototype.removeSpriteFromAtlas = cc.SpriteBatchNode.prototype._removeSpriteFromAtlasForWebGL; + cc.SpriteBatchNode.prototype.getTexture = cc.SpriteBatchNode.prototype._getTextureForWebGL; + cc.SpriteBatchNode.prototype.setTexture = cc.SpriteBatchNode.prototype._setTextureForWebGL; + cc.SpriteBatchNode.prototype.visit = cc.SpriteBatchNode.prototype._visitForWebGL; + cc.SpriteBatchNode.prototype.addChild = cc.SpriteBatchNode.prototype._addChildForWebGL; + cc.SpriteBatchNode.prototype.removeAllChildren = cc.SpriteBatchNode.prototype._removeAllChildrenForWebGL; + cc.SpriteBatchNode.prototype.sortAllChildren = cc.SpriteBatchNode.prototype._sortAllChildrenForWebGL; + cc.SpriteBatchNode.prototype.draw = cc.SpriteBatchNode.prototype._drawForWebGL; +} else { + cc.SpriteBatchNode.prototype.ctor = cc.SpriteBatchNode.prototype._ctorForCanvas; + cc.SpriteBatchNode.prototype.updateQuadFromSprite = cc.SpriteBatchNode.prototype._updateQuadFromSpriteForCanvas; + cc.SpriteBatchNode.prototype.insertQuadFromSprite = cc.SpriteBatchNode.prototype._insertQuadFromSpriteForCanvas; + cc.SpriteBatchNode.prototype.initWithTexture = cc.SpriteBatchNode.prototype._initWithTextureForCanvas; + cc.SpriteBatchNode.prototype.appendChild = cc.SpriteBatchNode.prototype._appendChildForCanvas; + cc.SpriteBatchNode.prototype.removeSpriteFromAtlas = cc.SpriteBatchNode.prototype._removeSpriteFromAtlasForCanvas; + cc.SpriteBatchNode.prototype.getTexture = cc.SpriteBatchNode.prototype._getTextureForCanvas; + cc.SpriteBatchNode.prototype.setTexture = cc.SpriteBatchNode.prototype._setTextureForCanvas; + cc.SpriteBatchNode.prototype.visit = cc.SpriteBatchNode.prototype._visitForCanvas; + cc.SpriteBatchNode.prototype.removeAllChildren = cc.SpriteBatchNode.prototype._removeAllChildrenForCanvas; + cc.SpriteBatchNode.prototype.addChild = cc.SpriteBatchNode.prototype._addChildForCanvas; + cc.SpriteBatchNode.prototype.sortAllChildren = cc.SpriteBatchNode.prototype._sortAllChildrenForCanvas; + cc.SpriteBatchNode.prototype.draw = cc.Node.prototype.draw; +} + /** *

* creates a cc.SpriteBatchNodeCanvas with a file image (.png, .jpg etc) with a default capacity of 29 children.
@@ -1434,14 +1019,14 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{ *

* @param {String} fileImage * @param {Number} capacity - * @return {cc.SpriteBatchNodeWebGL} + * @return {cc.SpriteBatchNode} * @example * //create a SpriteBatchNode * var parent2 = cc.SpriteBatchNode.create("res/animations/grossini.png", 50); */ -cc.SpriteBatchNodeWebGL.create = function (fileImage, capacity) { +cc.SpriteBatchNode.create = function (fileImage, capacity) { capacity = capacity || cc.DEFAULT_SPRITE_BATCH_CAPACITY; - var batchNode = new cc.SpriteBatchNodeWebGL(); + var batchNode = new cc.SpriteBatchNode(); batchNode.init(fileImage, capacity); return batchNode; }; @@ -1453,15 +1038,11 @@ cc.SpriteBatchNodeWebGL.create = function (fileImage, capacity) { *

* @param {cc.Texture2D} texture * @param {Number} capacity - * @return {cc.SpriteBatchNodeWebGL} + * @return {cc.SpriteBatchNode} */ -cc.SpriteBatchNodeWebGL.createWithTexture = function (texture, capacity) { +cc.SpriteBatchNode.createWithTexture = function (texture, capacity) { capacity = capacity || cc.DEFAULT_SPRITE_BATCH_CAPACITY; - var batchNode = new cc.SpriteBatchNodeWebGL(); + var batchNode = new cc.SpriteBatchNode(); batchNode.initWithTexture(texture, capacity); return batchNode; -}; - -cc.SpriteBatchNode = (cc.Browser.supportWebGL)?cc.SpriteBatchNodeWebGL:cc.SpriteBatchNodeCanvas; - - +}; \ No newline at end of file diff --git a/cocos2d/sprite_nodes/CCSpriteFrame.js b/cocos2d/sprite_nodes/CCSpriteFrame.js index 9df2204ccf..b113920052 100644 --- a/cocos2d/sprite_nodes/CCSpriteFrame.js +++ b/cocos2d/sprite_nodes/CCSpriteFrame.js @@ -49,6 +49,8 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ _originalSizeInPixels:null, _texture:null, _textureFilename:"", + _textureLoaded:false, + _eventListeners:null, ctor:function () { this._offset = cc.p(0, 0); @@ -60,9 +62,28 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ this._originalSizeInPixels = cc.size(0, 0); this._textureFilename = ""; this._texture = null; + this._textureLoaded = false; + this._eventListeners = []; }, // attributes + textureLoaded:function(){ + return this._textureLoaded; + }, + + addLoadedEventListener:function(callback, target){ + this._eventListeners.push({eventCallback:callback, eventTarget:target}); + }, + + _callLoadedEventCallbacks:function(){ + var locListeners = this._eventListeners; + for(var i = 0, len = locListeners.length; i < len; i++){ + var selCallback = locListeners[i]; + selCallback.eventCallback.call(selCallback.eventTarget, this); + } + locListeners.length = 0; + }, + /** * @return {cc.Rect} */ @@ -132,6 +153,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ /** * get original size of the trimmed image + * @const * @return {cc.Size} */ getOriginalSizeInPixels:function () { @@ -148,6 +170,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ /** * get original size of the trimmed image + * @const * @return {cc.Size} */ getOriginalSize:function () { @@ -164,28 +187,63 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ /** * get texture of the frame - * @return {cc.Texture2D|HTMLImageElement} + * @return {cc.Texture2D} */ getTexture:function () { if (this._texture) return this._texture; - if (this._textureFilename !== "") - return cc.TextureCache.getInstance().addImage(this._textureFilename); + if (this._textureFilename !== "") { + var locTexture = cc.TextureCache.getInstance().addImage(this._textureFilename); + if (locTexture) + this._textureLoaded = locTexture.isLoaded(); + return locTexture; + } return null; }, /** * set texture of the frame, the texture is retained - * @param {cc.Texture2D|HTMLImageElement} texture + * @param {cc.Texture2D} texture */ setTexture:function (texture) { if (this._texture != texture) { + var locLoaded = texture.isLoaded(); + this._textureLoaded = locLoaded; this._texture = texture; + if(!locLoaded){ + texture.addLoadedEventListener(function(sender){ + this._textureLoaded = true; + if(this._rotated){ + var tempElement = sender.getHtmlElementObj(); + tempElement = cc.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 locContentSize = sender.getContentSize(); + this._rect.width = locContentSize.width; + this._rect.height = locContentSize.height; + this._rectInPixels = cc.RECT_POINTS_TO_PIXELS(this._rect); + this._originalSizeInPixels.width = this._rectInPixels.width; + this._originalSizeInPixels.height = this._rectInPixels.height; + this._originalSize.width = locContentSize.width; + this._originalSize.height = locContentSize.height; + } + this._callLoadedEventCallbacks(); + }, this); + } } }, /** * Offset getter + * @const * @return {cc.Point} */ getOffset:function () { @@ -197,8 +255,8 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * @param {cc.Point} offsets */ setOffset:function (offsets) { - this._offset = offsets; - this._offsetInPixels = cc.POINT_POINTS_TO_PIXELS(offsetInPixels); + this._offset.x = offsets.x; + this._offset.y = offsets.y; }, clone: function(){ @@ -227,40 +285,25 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Initializes SpriteFrame with Texture, rect, rotated, offset and originalSize in pixels. * @param {cc.Texture2D|HTMLImageElement} texture * @param {cc.Rect} rect - * @param {Boolean} [rotated=] - * @param {cc.Point} [offset=] - * @param {cc.Size} [originalSize=] + * @param {Boolean} [rotated=false] + * @param {cc.Point} [offset=cc.size(0,0)] + * @param {cc.Size} [originalSize=rect.size] * @return {Boolean} */ initWithTexture:function (texture, rect, rotated, offset, originalSize) { - var argnum = arguments.length; - switch (argnum) { - /** Initializes a cc.SpriteFrame with a texture, rect in points. - It is assumed that the frame was not trimmed. - */ - case 2: - var rectInPixels = cc.RECT_POINTS_TO_PIXELS(rect); - return this.initWithTexture(texture, rectInPixels, false, cc.PointZero(), rectInPixels.size); - break; - - /** Initializes a cc.SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels. - The originalSize is the size in points of the frame before being trimmed. - */ - case 5: - this._texture = texture; - this._rectInPixels = rect; - this._rect = cc.RECT_PIXELS_TO_POINTS(rect); - this._offsetInPixels = offset; - this._offset = cc.POINT_PIXELS_TO_POINTS(this._offsetInPixels); - this._originalSizeInPixels = originalSize; - this._originalSize = cc.SIZE_PIXELS_TO_POINTS(this._originalSizeInPixels); - this._rotated = rotated; - return true; - break; - default: - throw "Argument must be non-nil "; - break; - } + rotated = rotated || false; + offset = offset || cc.size(0, 0); + originalSize = originalSize || rect.size; + + this.setTexture(texture); + this._rectInPixels = rect; + this._rect = cc.RECT_PIXELS_TO_POINTS(rect); + this._offsetInPixels = offset; + this._offset = cc.POINT_PIXELS_TO_POINTS(offset); + this._originalSizeInPixels = originalSize; + this._originalSize = cc.SIZE_PIXELS_TO_POINTS(originalSize); + this._rotated = rotated; + return true; }, /** @@ -271,18 +314,17 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * @param {string} filename * @param {cc.Rect} rect * @param {Boolean} rotated - * @param {cc.Point} offset - * @param {cc.Size} originalSize + * @param {cc.Point} [offset=cc.size(0,0)] + * @param {cc.Size} [originalSize=rect.size] */ initWithTextureFilename:function (filename, rect, rotated, offset, originalSize) { - var rectInPixels = cc.RECT_POINTS_TO_PIXELS(rect); offset = offset || cc.size(0, 0); - originalSize = originalSize || rectInPixels.size; + originalSize = originalSize || rect.size; this._texture = null; this._textureFilename = filename; - this._rectInPixels = rectInPixels; - this._rect = cc.RECT_PIXELS_TO_POINTS(rectInPixels); + this._rectInPixels = rect; + this._rect = cc.RECT_PIXELS_TO_POINTS(rect); this._rotated = rotated || false; this._offsetInPixels = offset; this._offset = cc.POINT_PIXELS_TO_POINTS(offset); @@ -323,11 +365,11 @@ cc.SpriteFrame.create = function (filename, rect, rotated, offset, originalSize) /** * Create a cc.SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels. - * @param {cc.Texture2D|HTMLImageElement} texture + * @param {cc.Texture2D} texture * @param {cc.Rect} rect - * @param {Boolean} rotated - * @param {cc.Point} offset - * @param {cc.Size} originalSize + * @param {Boolean} [rotated=] + * @param {cc.Point} [offset=] + * @param {cc.Size} [originalSize=] * @return {cc.SpriteFrame} * @example * //Create a cc.SpriteFrame with a texture, rect in texture. @@ -337,25 +379,8 @@ cc.SpriteFrame.create = function (filename, rect, rotated, offset, originalSize) * var frame2 = cc.SpriteFrame.createWithTexture(texture, frameRect, rotated, offset, sourceSize); */ cc.SpriteFrame.createWithTexture = function (texture, rect, rotated, offset, originalSize) { - var argnum = arguments.length; var spriteFrame = new cc.SpriteFrame(); - switch (argnum) { - /** Create a cc.SpriteFrame with a texture, rect in points. - It is assumed that the frame was not trimmed. - */ - case 2: - spriteFrame.initWithTexture(texture, rect); - break; - /** Create a cc.SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels. - The originalSize is the size in points of the frame before being trimmed. - */ - case 5: - spriteFrame.initWithTexture(texture, rect, rotated, offset, originalSize); - break; - default: - throw "Argument must be non-nil "; - break; - } + spriteFrame.initWithTexture(texture, rect, rotated, offset, originalSize); return spriteFrame; }; diff --git a/cocos2d/sprite_nodes/CCSpriteFrameCache.js b/cocos2d/sprite_nodes/CCSpriteFrameCache.js index c6d7b9da23..20b0d0d32f 100644 --- a/cocos2d/sprite_nodes/CCSpriteFrameCache.js +++ b/cocos2d/sprite_nodes/CCSpriteFrameCache.js @@ -138,10 +138,18 @@ cc.SpriteFrameCache = cc.Class.extend(/** @lends cc.SpriteFrameCache# */{ if(cc.renderContextType === cc.CANVAS && spriteFrame.isRotated()){ //clip to canvas - var tempTexture = cc.cutRotateImageToCanvas(spriteFrame.getTexture(), spriteFrame.getRect()); - var rect = spriteFrame.getRect(); - spriteFrame.setRect(cc.rect(0, 0, rect.width, rect.height)); - spriteFrame.setTexture(tempTexture); + var locTexture = spriteFrame.getTexture(); + if(locTexture.isLoaded()){ + var tempElement = spriteFrame.getTexture().getHtmlElementObj(); + tempElement = cc.cutRotateImageToCanvas(tempElement, spriteFrame.getRect()); + var tempTexture = new cc.Texture2D(); + tempTexture.initWithElement(tempElement); + tempTexture.handleLoadedTexture(); + spriteFrame.setTexture(tempTexture); + + var rect = spriteFrame.getRect(); + spriteFrame.setRect(cc.rect(0, 0, rect.width, rect.height)); + } } // add sprite frame @@ -153,8 +161,10 @@ cc.SpriteFrameCache = cc.Class.extend(/** @lends cc.SpriteFrameCache# */{ /** * Adds multiple Sprite Frames from a json file. A texture will be loaded automatically. * @param {object} jsonData + * @deprecated */ addSpriteFramesWithJson:function (jsonData) { + cc.log("addSpriteFramesWithJson is deprecated, because Json format doesn't support on JSB. Use XML format instead"); var dict = jsonData; var texturePath = ""; @@ -225,7 +235,8 @@ cc.SpriteFrameCache = cc.Class.extend(/** @lends cc.SpriteFrameCache# */{ } break; case 2: - if ((texture instanceof cc.Texture2D) || (texture instanceof HTMLImageElement) || (texture instanceof HTMLCanvasElement)) { + //if ((texture instanceof cc.Texture2D) || (texture instanceof HTMLImageElement) || (texture instanceof HTMLCanvasElement)) { + if (texture instanceof cc.Texture2D) { /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. */ this._addSpriteFramesWithDictionary(dict, texture); } else { diff --git a/cocos2d/support/CCNotificationCenter.js b/cocos2d/support/CCNotificationCenter.js index 84a283aa41..60188057bf 100644 --- a/cocos2d/support/CCNotificationCenter.js +++ b/cocos2d/support/CCNotificationCenter.js @@ -126,7 +126,6 @@ cc.NotificationCenter.getInstance = function() { }; cc.NotificationObserver = cc.Class.extend({ - /** * @param {cc.Class} target * @param {String} selector diff --git a/cocos2d/support/CCUserDefault.js b/cocos2d/support/CCUserDefault.js index 109888daa5..fd53f8c3d0 100644 --- a/cocos2d/support/CCUserDefault.js +++ b/cocos2d/support/CCUserDefault.js @@ -69,6 +69,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{ * @return {Boolean} */ getBoolForKey:function (key, defaultValue) { + cc.log("getBoolForKey is deprecated. Use sys.localStorage.getItem instead."); var value = this._getValueForKey(key); var ret = defaultValue || false; if (value == "true") { @@ -93,6 +94,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{ * @return {Number} */ getIntegerForKey:function (key, defaultValue) { + cc.log("getIntegerForKey is deprecated. Use sys.localStorage.getItem instead."); var value = this._getValueForKey(key); var ret = defaultValue || 0; @@ -112,6 +114,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{ * @return {Number} */ getFloatForKey:function (key, defaultValue) { + cc.log("getFloatForKey is deprecated. Use sys.localStorage.getItem instead."); var value = this._getValueForKey(key); var ret = defaultValue || 0; @@ -131,6 +134,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{ * @return {Number} */ getDoubleForKey:function (key, defaultValue) { + cc.log("getDoubleForKey is deprecated. Use sys.localStorage.getItem instead."); return this.getFloatForKey(key, defaultValue); }, @@ -143,6 +147,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{ * @return {String} */ getStringForKey:function (key, defaultValue) { + cc.log("getStringForKey is deprecated. Use sys.localStorage.getItem instead."); var value = this._getValueForKey(key); var ret = defaultValue || ""; @@ -169,6 +174,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{ * @param {Boolean} value */ setBoolForKey:function (key, value) { + cc.log("setBoolForKey is deprecated. Use sys.localStorage.setItem instead."); // save bool value as sring this.setStringForKey(key, String(value)); }, @@ -180,6 +186,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{ * @param {Number} value */ setIntegerForKey:function (key, value) { + cc.log("setIntegerForKey is deprecated. Use sys.localStorage.setItem instead."); // check key if (!key) { return; @@ -195,6 +202,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{ * @param {Number} value */ setFloatForKey:function (key, value) { + cc.log("setFloatForKey is deprecated. Use sys.localStorage.setItem instead."); // check key if (!key) { return; @@ -210,6 +218,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{ * @param {Number} value */ setDoubleForKey:function (key, value) { + cc.log("setDoubleForKey is deprecated. Use sys.localStorage.setItem instead."); return this.setFloatForKey(key, value); }, @@ -220,6 +229,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{ * @param {String} value */ setStringForKey:function (key, value) { + cc.log("setStringForKey is deprecated. Use sys.localStorage.setItem instead."); // check key if (!key) { return; @@ -241,6 +251,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{ * @return {cc.UserDefault|} */ cc.UserDefault.getInstance = function () { + cc.log("cc.UserDefault is deprecated. Use sys.localStorage instead."); if (!this._sUserDefault) { this._sUserDefault = new cc.UserDefault(); this._sUserDefault.init(); diff --git a/cocos2d/text_input_node/CCTextFieldTTF.js b/cocos2d/text_input_node/CCTextFieldTTF.js index 61f02c6209..67f69be2db 100644 --- a/cocos2d/text_input_node/CCTextFieldTTF.js +++ b/cocos2d/text_input_node/CCTextFieldTTF.js @@ -98,7 +98,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ ctor:function () { this._ColorSpaceHolder = new cc.Color3B(127, 127, 127); cc.IMEDispatcher.getInstance().addDelegate(this); - this._super(); + cc.LabelTTF.prototype.ctor.call(this); }, /** @@ -157,7 +157,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ if (placeholder) { this._placeHolder = placeholder; } - return this.initWithString(this._placeHolder, dimensions, alignment, fontName, fontSize); + return this.initWithString(this._placeHolder,fontName, fontSize, dimensions, alignment); break; case 3: if (placeholder) { @@ -176,22 +176,16 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ /** * Input text property * @param {String} text - * @param {Boolean} isCallParent */ - setString:function (text, isCallParent) { + setString:function (text) { text = String(text); - if (isCallParent && isCallParent == true) { - this._super(text); - return; - } - this._inputText = text || ""; // if there is no input text, display placeholder instead if (!this._inputText.length) - this._super(this._placeHolder); + cc.LabelTTF.prototype.setString.call(this, this._placeHolder); else - this._super(this._inputText); + cc.LabelTTF.prototype.setString.call(this,this._inputText); this._charCount = this._inputText.length; }, @@ -229,14 +223,16 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ return; if (this._inputText && this._inputText.length > 0) { - this._super(context); + cc.LabelTTF.prototype.draw.call(this, context); return; } // draw placeholder var color = this.getColor(); this.setColor(this._ColorSpaceHolder); - this._super(context); + if(cc.renderContextType === cc.CANVAS) + this._updateTexture(); + cc.LabelTTF.prototype.draw.call(this, context); this.setColor(color); }, @@ -311,7 +307,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ // set new input text var sText = this._inputText.substring(0, strLen - deleteLen); - this.setString(sText, false); + this.setString(sText); }, /** @@ -406,7 +402,7 @@ cc.TextFieldTTF.create = function (placeholder, dimensions, alignment, fontName, ret = new cc.TextFieldTTF(); fontName = arguments[1]; fontSize = arguments[2]; - if (ret && ret.initWithString(["", fontName, fontSize])) { + if (ret && ret.initWithString("", fontName, fontSize)) { if (placeholder) ret.setPlaceHolder(placeholder); return ret; diff --git a/cocos2d/textures/CCTexture2D.js b/cocos2d/textures/CCTexture2D.js index 03fc2d2867..b9f12d0089 100644 --- a/cocos2d/textures/CCTexture2D.js +++ b/cocos2d/textures/CCTexture2D.js @@ -131,7 +131,7 @@ cc._texParams = function (minFilter, magFilter, wrapS, wrapT) { * @class * @extends cc.Class */ -cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ +cc.Texture2DWebGL = cc.Class.extend(/** @lends cc.Texture2D# */{ // By default PVR images are treated as if they don't have the alpha channel premultiplied _pVRHaveAlphaPremultiplied:null, _pixelFormat:null, @@ -150,6 +150,8 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ _htmlElementObj:null, _webTextureObj:null, + _loadedEventListeners:null, + /*public:*/ ctor:function () { this._pixelsWide = 0; @@ -158,7 +160,7 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ this._maxS = 0; this._maxT = 0; this._hasPremultipliedAlpha = false; - this._contentSize = null; + this._contentSize = cc.size(0, 0); this._hasMipmaps = false; this._pVRHaveAlphaPremultiplied = true; @@ -168,11 +170,12 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ this._isLoaded = false; this._htmlElementObj = null; this._webTextureObj = null; + this._loadedEventListeners = []; }, - releaseTexture:function(){ - if(this._webTextureObj) - cc.renderContext.deleteTexture(this._webTextureObj); + releaseTexture:function () { + if (this._webTextureObj) + cc.renderContext.deleteTexture(this._webTextureObj); }, /** @@ -185,7 +188,7 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ /** * width in pixels - * @return {Number} + * @return {Number} */ getPixelsWide:function () { return this._pixelsWide; @@ -211,7 +214,7 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ * content size * @return {cc.Size} */ - getContentSize:function(){ + getContentSize:function () { return cc.size(this._contentSize.width / cc.CONTENT_SCALE_FACTOR(), this._contentSize.height / cc.CONTENT_SCALE_FACTOR()); }, @@ -241,7 +244,7 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ * return shader program used by drawAtPoint and drawInRect * @return {cc.GLProgram} */ - getShaderProgram:function(){ + getShaderProgram:function () { return this._shaderProgram; }, @@ -249,7 +252,7 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ * set shader program used by drawAtPoint and drawInRect * @param {cc.GLProgram} shaderProgram */ - setShaderProgram:function(shaderProgram){ + setShaderProgram:function (shaderProgram) { this._shaderProgram = shaderProgram; }, @@ -261,7 +264,7 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ return this._hasPremultipliedAlpha; }, - hasMipmaps:function(){ + hasMipmaps:function () { return this._hasMipmaps; }, @@ -297,30 +300,30 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ var bitsPerPixel = 0; //Hack: bitsPerPixelForFormat returns wrong number for RGB_888 textures. See function. - if(pixelFormat === cc.TEXTURE_2D_PIXEL_FORMAT_RGBA8888){ + if (pixelFormat === cc.TEXTURE_2D_PIXEL_FORMAT_RGBA8888) { bitsPerPixel = 24; - }else{ + } else { bitsPerPixel = this.bitsPerPixelForFormat(pixelFormat); } - var bytesPerRow = pixelsWide * bitsPerPixel/8; - if(bytesPerRow % 8 === 0){ - gl.pixelStorei(gl.UNPACK_ALIGNMENT,8); - } else if(bytesPerRow % 4 === 0){ - gl.pixelStorei(gl.UNPACK_ALIGNMENT,4); - } else if(bytesPerRow % 2 === 0){ - gl.pixelStorei(gl.UNPACK_ALIGNMENT,2); + var bytesPerRow = pixelsWide * bitsPerPixel / 8; + if (bytesPerRow % 8 === 0) { + gl.pixelStorei(gl.UNPACK_ALIGNMENT, 8); + } else if (bytesPerRow % 4 === 0) { + gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4); + } else if (bytesPerRow % 2 === 0) { + gl.pixelStorei(gl.UNPACK_ALIGNMENT, 2); } else { - gl.pixelStorei(gl.UNPACK_ALIGNMENT,1); + gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); } this._webTextureObj = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, this._webTextureObj); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE ); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); // Specify OpenGL texture image switch (pixelFormat) { @@ -353,6 +356,7 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ break; } + this._contentSize = contentSize; this._pixelsWide = pixelsWide; this._pixelsHigh = pixelsHigh; @@ -394,11 +398,11 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ point.x, height + point.y, 0.0, width + point.x, height + point.y, 0.0 ]; - cc.glEnableVertexAttribs( cc.VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_TEXCOORDS ); + cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_TEXCOORDS); this._shaderProgram.use(); this._shaderProgram.setUniformsForBuiltins(); - cc.glBindTexture2D( this ); + cc.glBindTexture2D(this); var gl = cc.renderContext; gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, vertices); @@ -423,11 +427,11 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ rect.x, rect.y + rect.height, /*0.0,*/ rect.x + rect.width, rect.y + rect.height /*0.0*/ ]; - cc.glEnableVertexAttribs( cc.VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_TEXCOORDS ); + cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_TEXCOORDS); this._shaderProgram.use(); this._shaderProgram.setUniformsForBuiltins(); - cc.glBindTexture2D( this ); + cc.glBindTexture2D(this); var gl = cc.renderContext; gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, vertices); @@ -459,7 +463,7 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ var maxTextureSize = conf.getMaxTextureSize(); if (imageWidth > maxTextureSize || imageHeight > maxTextureSize) { - cc.log("cocos2d: WARNING: Image (" + imageWidth + " x " + imageHeight+ ") is bigger than the supported " + maxTextureSize + " x " + maxTextureSize); + cc.log("cocos2d: WARNING: Image (" + imageWidth + " x " + imageHeight + ") is bigger than the supported " + maxTextureSize + " x " + maxTextureSize); return false; } this._isLoaded = true; @@ -468,26 +472,30 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ return this._initPremultipliedATextureWithImage(uiImage, imageWidth, imageHeight); }, - initWithElement:function(element){ - if(!element) + initWithElement:function (element) { + if (!element) return; - this._webTextureObj = cc.renderContext.createTexture(); this._htmlElementObj = element; }, - isLoaded:function(){ - return this._isLoaded; + /** + * HTMLElement Object getter + * @return {HTMLElement} + */ + getHtmlElementObj:function(){ + return this._htmlElementObj; + }, + + isLoaded:function () { + return this._isLoaded; }, - handleLoadedTexture:function(){ + handleLoadedTexture:function () { this._isLoaded = true; //upload image to buffer var gl = cc.renderContext; - var pixelsWide = this._htmlElementObj.width; - var pixelsHigh = this._htmlElementObj.height; - cc.glBindTexture2D(this); gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4); @@ -500,7 +508,13 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - this._contentSize = new cc.Size(pixelsWide,pixelsHigh); + this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_TEXTURE)); + gl.bindTexture(gl.TEXTURE_2D, null); + + var pixelsWide = this._htmlElementObj.width; + var pixelsHigh = this._htmlElementObj.height; + + this._contentSize = new cc.Size(pixelsWide, pixelsHigh); this._pixelsWide = pixelsWide; this._pixelsHigh = pixelsHigh; this._pixelFormat = cc.TEXTURE_2D_PIXEL_FORMAT_RGBA8888; @@ -510,9 +524,7 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ this._hasPremultipliedAlpha = false; this._hasMipmaps = false; - this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_TEXTURE)); - - gl.bindTexture(gl.TEXTURE_2D, null); + this._callLoadedEventCallbacks(); }, /** @@ -539,20 +551,20 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ } /*if (cc.ENABLE_CACHE_TEXTURE_DATA) { - // cache the texture data - cc.VolatileTexture.addStringTexture(this, text, dimensions, alignment, fontName, fontSize); - }*/ + // cache the texture data + cc.VolatileTexture.addStringTexture(this, text, dimensions, alignment, fontName, fontSize); + }*/ var image = new cc.Image(); - var eAlign ; + var eAlign; - if(cc.VERTICAL_TEXT_ALIGNMENT_TOP === vAlignment){ + if (cc.VERTICAL_TEXT_ALIGNMENT_TOP === vAlignment) { eAlign = (cc.TEXT_ALIGNMENT_CENTER === hAlignment) ? cc.ALIGN_TOP : (cc.TEXT_ALIGNMENT_LEFT === hAlignment) ? cc.ALIGN_TOP_LEFT : cc.ALIGN_TOP_RIGHT; - }else if(cc.VERTICAL_TEXT_ALIGNMENT_CENTER === vAlignment){ + } else if (cc.VERTICAL_TEXT_ALIGNMENT_CENTER === vAlignment) { eAlign = (cc.TEXT_ALIGNMENT_CENTER === hAlignment) ? cc.ALIGN_CENTER : (cc.TEXT_ALIGNMENT_LEFT === hAlignment) ? cc.ALIGN_LEFT : cc.ALIGN_RIGHT; - }else if(cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM === vAlignment){ + } else if (cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM === vAlignment) { eAlign = (cc.TEXT_ALIGNMENT_CENTER === hAlignment) ? cc.ALIGN_BOTTOM : (cc.TEXT_ALIGNMENT_LEFT === hAlignment) ? cc.ALIGN_BOTTOM_LEFT : cc.ALIGN_BOTTOM_RIGHT; } else { @@ -571,7 +583,7 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ * @param {String} file * @return {Boolean} */ - initWithETCFile:function(file){ + initWithETCFile:function (file) { return false; }, @@ -660,16 +672,16 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ var gl = cc.renderContext; cc.glBindTexture2D(this); - if(!this._hasMipmaps) - gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER, gl.LINEAR); + if (!this._hasMipmaps) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); else gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); //TODO /*#if CC_ENABLE_CACHE_TEXTURE_DATA - ccTexParams texParams = {m_bHasMipmaps?GL_LINEAR_MIPMAP_NEAREST:GL_LINEAR,GL_LINEAR,GL_NONE,GL_NONE}; - VolatileTexture::setTexParameters(this, &texParams); - #endif*/ + ccTexParams texParams = {m_bHasMipmaps?GL_LINEAR_MIPMAP_NEAREST:GL_LINEAR,GL_LINEAR,GL_NONE,GL_NONE}; + VolatileTexture::setTexParameters(this, &texParams); + #endif*/ }, /** @@ -677,21 +689,21 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ * GL_TEXTURE_MIN_FILTER = GL_NEAREST * GL_TEXTURE_MAG_FILTER = GL_NEAREST */ - setAliasTexParameters:function(){ + setAliasTexParameters:function () { var gl = cc.renderContext; cc.glBindTexture2D(this); - if(!this._hasMipmaps) - gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER, gl.NEAREST); - else + if (!this._hasMipmaps) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + else gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_NEAREST); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); //TODO /*#if CC_ENABLE_CACHE_TEXTURE_DATA - ccTexParams texParams = {m_bHasMipmaps?GL_NEAREST_MIPMAP_NEAREST:GL_NEAREST,GL_NEAREST,GL_NONE,GL_NONE}; - VolatileTexture::setTexParameters(this, &texParams); - #endif*/ + ccTexParams texParams = {m_bHasMipmaps?GL_NEAREST_MIPMAP_NEAREST:GL_NEAREST,GL_NEAREST,GL_NONE,GL_NONE}; + VolatileTexture::setTexParameters(this, &texParams); + #endif*/ }, /** @@ -710,7 +722,7 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ * returns the pixel format. * @return {String} */ - stringForFormat:function(){ + stringForFormat:function () { switch (this._pixelFormat) { case cc.TEXTURE_2D_PIXEL_FORMAT_RGBA8888: return "RGBA8888"; @@ -743,11 +755,11 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ return "PVRTC2"; default: - cc.Assert(false , "unrecognized pixel format"); + cc.Assert(false, "unrecognized pixel format"); cc.log("stringForFormat: " + this._pixelFormat + ", cannot give useful result"); break; } - return ""; + return ""; }, /** @@ -895,9 +907,379 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{ this._hasPremultipliedAlpha = uiImage.isPremultipliedAlpha(); return true; + }, + + addLoadedEventListener: function (callback, target) { + this._loadedEventListeners.push({eventCallback: callback, eventTarget: target}); + }, + + removeLoadedEventListener:function(target){ + var locListeners = this._loadedEventListeners; + for(var i = 0; i < locListeners.length; i++){ + var selCallback = locListeners[i]; + if(selCallback.eventTarget == target){ + locListeners.splice(i, 1); + } + } + }, + + _callLoadedEventCallbacks: function () { + var locListeners = this._loadedEventListeners; + for (var i = 0, len = locListeners.length; i < len; i++) { + var selCallback = locListeners[i]; + selCallback.eventCallback.call(selCallback.eventTarget, this); + } + locListeners.length = 0; + } +}); + +/** + *

+ * This class allows to easily create 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!

+ * @class + * @extends cc.Class + */ +cc.Texture2DCanvas = cc.Class.extend(/** @lends cc.Texture2D# */{ + _contentSize:null, + _isLoaded:false, + _htmlElementObj:null, + + _loadedEventListeners:null, + /*public:*/ + ctor:function () { + this._contentSize = cc.size(0,0); + this._isLoaded = false; + this._htmlElementObj = null; + this._loadedEventListeners = []; + }, + + /** + * width in pixels + * @return {Number} + */ + getPixelsWide:function () { + return this._contentSize.width; + }, + + /** + * hight in pixels + * @return {Number} + */ + getPixelsHigh:function () { + return this._contentSize.height; + }, + + /** + * content size + * @return {cc.Size} + */ + getContentSize:function () { + return cc.size(this._contentSize.width / cc.CONTENT_SCALE_FACTOR(), this._contentSize.height / cc.CONTENT_SCALE_FACTOR()); + }, + + getContentSizeInPixels:function () { + return this._contentSize; + }, + + initWithElement:function (element) { + if (!element) + return; + this._htmlElementObj = element; + }, + + /** + * HTMLElement Object getter + * @return {HTMLElement} + */ + getHtmlElementObj:function(){ + return this._htmlElementObj; + }, + + isLoaded:function () { + return this._isLoaded; + }, + + handleLoadedTexture:function () { + this._isLoaded = true; + var locElement = this._htmlElementObj; + this._contentSize = new cc.Size(locElement.width, locElement.height); + + this._callLoadedEventCallbacks(); + }, + + description:function () { + return ""; + }, + + /** + * Intializes with a texture2d with data + * @param {Array} data + * @param {Number} pixelFormat + * @param {Number} pixelsWide + * @param {Number} pixelsHigh + * @param {cc.Size} contentSize + * @return {Boolean} + */ + initWithData:function (data, pixelFormat, pixelsWide, pixelsHigh, contentSize) { + //support only in WebGl rendering mode + return false; + }, + + /** + Extensions to make it easy to create a CCTexture2D object from an image file. + Note that RGBA type textures will have their alpha premultiplied - use the blending mode (gl.ONE, gl.ONE_MINUS_SRC_ALPHA). + */ + /** + * Initializes a texture from a UIImage object + * @param uiImage + * @return {Boolean} + */ + initWithImage:function (uiImage) { + //support only in WebGl rendering mode + return false; + }, + + /** + Extensions to make it easy to create a cc.Texture2D object from a string of text. + Note that the generated textures are of type A8 - use the blending mode (gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA). + */ + /** + * Initializes a texture from a string with dimensions, alignment, font name and font size (note: initWithString does not support on HTML5) + * @param {String} text + * @param {String | cc.FontDefinition} fontName or fontDefinition + * @param {Number} fontSize + * @param {cc.Size} dimensions + * @param {Number} hAlignment + * @param {Number} vAlignment + * @return {Boolean} + */ + initWithString:function (text, fontName, fontSize, dimensions, hAlignment, vAlignment) { + //support only in WebGl rendering mode + return false; + }, + + releaseTexture:function () { + //support only in WebGl rendering mode + }, + + /** + * get WebGLTexture Object + * @return {WebGLTexture} + */ + getName:function () { + //support only in WebGl rendering mode + return null; + }, + + /** texture max S */ + getMaxS:function () { + //support only in WebGl rendering mode + return 1; + }, + + setMaxS:function (maxS) { + //support only in WebGl rendering mode + }, + + /** texture max T */ + getMaxT:function () { + return 1; + }, + + setMaxT:function (maxT) { + //support only in WebGl rendering mode + }, + + /** + * return shader program used by drawAtPoint and drawInRect + * @return {cc.GLProgram} + */ + getShaderProgram:function () { + //support only in WebGl rendering mode + return null; + }, + + /** + * set shader program used by drawAtPoint and drawInRect + * @param {cc.GLProgram} shaderProgram + */ + setShaderProgram:function (shaderProgram) { + //support only in WebGl rendering mode + }, + + /** + * whether or not the texture has their Alpha premultiplied + * @return {Boolean} + */ + hasPremultipliedAlpha:function () { + //support only in WebGl rendering mode + return false; + }, + + hasMipmaps:function () { + //support only in WebGl rendering mode + return false; + }, + + /** + * These functions are needed to create mutable textures + * @param {Array} data + */ + releaseData:function (data) { + //support only in WebGl rendering mode + data = null; + }, + + keepData:function (data, length) { + //support only in WebGl rendering mode + return data; + }, + + /** + Drawing extensions to make it easy to draw basic quads using a CCTexture2D object. + These functions require gl.TEXTURE_2D and both gl.VERTEX_ARRAY and gl.TEXTURE_COORD_ARRAY client states to be enabled. + */ + + /** + * draws a texture at a given point + * @param {cc.Point} point + */ + drawAtPoint:function (point) { + //support only in WebGl rendering mode + }, + + /** + * draws a texture inside a rect + * @param {cc.Rect} rect + */ + drawInRect:function (rect) { + //support only in WebGl rendering mode + }, + + /** + * Initializes a texture from a ETC file (note: initWithETCFile does not support on HTML5) + * @note Compatible to Cocos2d-x + * @param {String} file + * @return {Boolean} + */ + initWithETCFile:function (file) { + //support only in WebGl rendering mode + return false; + }, + + /** + * Initializes a texture from a PVR file + * @param {String} file + * @return {Boolean} + */ + initWithPVRFile:function (file) { + //support only in WebGl rendering mode + return false; + }, + + /** + Extensions to make it easy to create a cc.Texture2D object from a PVRTC file + Note that the generated textures don't have their alpha premultiplied - use the blending mode (gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA). + */ + /** + * Initializes a texture from a PVRTC buffer + * @note compatible to cocos2d-iphone interface. + * @param {Array} data + * @param {Number} level + * @param {Number} bpp + * @param {Boolean} hasAlpha + * @param {Number} length + * @param {Number} pixelFormat + * @return {Boolean} + */ + initWithPVRTCData:function (data, level, bpp, hasAlpha, length, pixelFormat) { + //support only in WebGl rendering mode + return true; + }, + + /** + * sets the min filter, mag filter, wrap s and wrap t texture parameters.
+ * If the texture size is NPOT (non power of 2), then in can only use gl.CLAMP_TO_EDGE in gl.TEXTURE_WRAP_{S,T}. + * @param texParams + */ + setTexParameters:function (texParams) { + //support only in WebGl rendering mode + }, + + /** + * sets antialias texture parameters:
+ * - GL_TEXTURE_MIN_FILTER = GL_NEAREST
+ * - GL_TEXTURE_MAG_FILTER = GL_NEAREST + */ + setAntiAliasTexParameters:function () { + //support only in WebGl rendering mode + }, + + /** + * sets alias texture parameters: + * GL_TEXTURE_MIN_FILTER = GL_NEAREST + * GL_TEXTURE_MAG_FILTER = GL_NEAREST + */ + setAliasTexParameters:function () { + //support only in WebGl rendering mode + }, + + /** + * Generates mipmap images for the texture.
+ * It only works if the texture size is POT (power of 2). + */ + generateMipmap:function () { + //support only in WebGl rendering mode + }, + + /** + * returns the pixel format. + * @return {String} + */ + stringForFormat:function () { + //support only in WebGl rendering mode + return ""; + }, + + /** + * returns the bits-per-pixel of the in-memory OpenGL texture + * @return {Number} + */ + bitsPerPixelForFormat:function (format) { + //support only in WebGl rendering mode + return -1; + }, + + addLoadedEventListener:function(callback, target){ + this._loadedEventListeners.push({eventCallback:callback, eventTarget:target}); + }, + + removeLoadedEventListener:function(target){ + var locListeners = this._loadedEventListeners; + for(var i = 0; i < locListeners.length; i++){ + var selCallback = locListeners[i]; + if(selCallback.eventTarget == target){ + locListeners.splice(i, 1); + } + } + }, + + _callLoadedEventCallbacks:function(){ + var locListeners = this._loadedEventListeners; + for(var i = 0, len = locListeners.length; i < len; i++){ + var selCallback = locListeners[i]; + selCallback.eventCallback.call(selCallback.eventTarget, this); + } + locListeners.length = 0; } }); +cc.Texture2D = cc.Browser.supportWebGL ? cc.Texture2DWebGL : cc.Texture2DCanvas; + /** *

* sets the default pixel format for UIImagescontains alpha channel.
diff --git a/cocos2d/textures/CCTextureAtlas.js b/cocos2d/textures/CCTextureAtlas.js index 9a34e5c569..80179f824b 100644 --- a/cocos2d/textures/CCTextureAtlas.js +++ b/cocos2d/textures/CCTextureAtlas.js @@ -122,20 +122,20 @@ cc.TextureAtlas = cc.Class.extend(/** @lends cc.TextureAtlas# */{ if(!quads) return; - for(var i = 0; i < quads.length ; i++){ + for(var i = 0; i < quads.length ; i++) this._setQuadToArray(quads[i], index + i); - } }, _setQuadToArray: function (quad, index) { - if (!this._quads[index]) { - this._quads[index] = new cc.V3F_C4B_T2F_Quad(quad.tl, quad.bl, quad.tr, quad.br, this._quadsArrayBuffer, index * cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT); + var locQuads = this._quads; + if (!locQuads[index]) { + locQuads[index] = new cc.V3F_C4B_T2F_Quad(quad.tl, quad.bl, quad.tr, quad.br, this._quadsArrayBuffer, index * cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT); return; } - this._quads[index].bl = quad.bl; - this._quads[index].br = quad.br; - this._quads[index].tl = quad.tl; - this._quads[index].tr = quad.tr; + locQuads[index].bl = quad.bl; + locQuads[index].br = quad.br; + locQuads[index].tl = quad.tl; + locQuads[index].tr = quad.tr; }, /** @@ -149,24 +149,24 @@ cc.TextureAtlas = cc.Class.extend(/** @lends cc.TextureAtlas# */{ _setupIndices:function () { if (this._capacity === 0) return; - - for (var i = 0; i < this._capacity; i++) { + var locIndices = this._indices, locCapacity = this._capacity; + for (var i = 0; i < locCapacity; i++) { if (cc.TEXTURE_ATLAS_USE_TRIANGLE_STRIP) { - this._indices[i * 6 + 0] = i * 4 + 0; - this._indices[i * 6 + 1] = i * 4 + 0; - this._indices[i * 6 + 2] = i * 4 + 2; - this._indices[i * 6 + 3] = i * 4 + 1; - this._indices[i * 6 + 4] = i * 4 + 3; - this._indices[i * 6 + 5] = i * 4 + 3; + locIndices[i * 6 + 0] = i * 4 + 0; + locIndices[i * 6 + 1] = i * 4 + 0; + locIndices[i * 6 + 2] = i * 4 + 2; + locIndices[i * 6 + 3] = i * 4 + 1; + locIndices[i * 6 + 4] = i * 4 + 3; + locIndices[i * 6 + 5] = i * 4 + 3; } else { - this._indices[i * 6 + 0] = i * 4 + 0; - this._indices[i * 6 + 1] = i * 4 + 1; - this._indices[i * 6 + 2] = i * 4 + 2; + locIndices[i * 6 + 0] = i * 4 + 0; + locIndices[i * 6 + 1] = i * 4 + 1; + locIndices[i * 6 + 2] = i * 4 + 2; // inverted index. issue #179 - this._indices[i * 6 + 3] = i * 4 + 3; - this._indices[i * 6 + 4] = i * 4 + 2; - this._indices[i * 6 + 5] = i * 4 + 1; + locIndices[i * 6 + 3] = i * 4 + 3; + locIndices[i * 6 + 4] = i * 4 + 2; + locIndices[i * 6 + 5] = i * 4 + 1; } } }, @@ -345,18 +345,19 @@ cc.TextureAtlas = cc.Class.extend(/** @lends cc.TextureAtlas# */{ return; var quadSize = cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT; - var sourceArr = this._quadsReader.subarray(fromIndex * quadSize,quadSize); + var locQuadsReader = this._quadsReader; + var sourceArr = locQuadsReader.subarray(fromIndex * quadSize,quadSize); var startOffset, moveLength; if(fromIndex > newIndex){ startOffset = newIndex * quadSize; moveLength = (fromIndex - newIndex) * quadSize; - this._quadsReader.set(this._quadsReader.subarray(startOffset, startOffset + moveLength),startOffset + quadSize); - this._quadsReader.set(sourceArr,startOffset); + locQuadsReader.set(locQuadsReader.subarray(startOffset, startOffset + moveLength),startOffset + quadSize); + locQuadsReader.set(sourceArr,startOffset); }else{ startOffset = (fromIndex + 1) * quadSize; moveLength = (newIndex - fromIndex) * quadSize; - this._quadsReader.set(this._quadsReader.subarray(startOffset, startOffset + moveLength),startOffset - quadSize); - this._quadsReader.set(sourceArr, newIndex * quadSize); + locQuadsReader.set(locQuadsReader.subarray(startOffset, startOffset + moveLength),startOffset - quadSize); + locQuadsReader.set(sourceArr, newIndex * quadSize); } this._dirty = true; }, @@ -515,19 +516,20 @@ cc.TextureAtlas = cc.Class.extend(/** @lends cc.TextureAtlas# */{ var quadSize = cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT; var srcOffset = oldIndex * quadSize; var srcLength = amount * quadSize; - var sourceArr = this._quadsReader.subarray(srcOffset, srcOffset + srcLength); + var locQuadsReader = this._quadsReader; + var sourceArr = locQuadsReader.subarray(srcOffset, srcOffset + srcLength); var dstOffset = newIndex * quadSize; var moveLength, moveStart; if (newIndex < oldIndex) { moveLength = (oldIndex - newIndex) * quadSize; moveStart = newIndex * quadSize; - this._quadsReader.set(this._quadsReader.subarray(moveStart, moveStart + moveLength), moveStart + srcLength) + locQuadsReader.set(locQuadsReader.subarray(moveStart, moveStart + moveLength), moveStart + srcLength) } else { moveLength = (newIndex - oldIndex) * quadSize; moveStart = (oldIndex + amount) * quadSize; - this._quadsReader.set(this._quadsReader.subarray(moveStart, moveStart + moveLength), srcOffset); + locQuadsReader.set(locQuadsReader.subarray(moveStart, moveStart + moveLength), srcOffset); } - this._quadsReader.set(sourceArr, dstOffset); + locQuadsReader.set(sourceArr, dstOffset); this._dirty = true; }, diff --git a/cocos2d/textures/CCTextureCache.js b/cocos2d/textures/CCTextureCache.js index 8b3363e41b..9bd22e8d34 100644 --- a/cocos2d/textures/CCTextureCache.js +++ b/cocos2d/textures/CCTextureCache.js @@ -43,9 +43,10 @@ cc.loadImage = function (imageUrl) { } var image = new Image(); image.src = imageUrl; - image.onLoad = function (e) { + image.addEventListener('load',function(){ cc.TextureCache.getInstance().cacheImage(imageUrl, image); - }; + this.removeEventListener('load', arguments.callee, false); + },false); }; /** @@ -66,367 +67,14 @@ cc.computeImageFormatType = function (filename) { }; /** - * Implementation TextureCache (Canvas implement) + * Implementation TextureCache * @class * @extends cc.Class */ -cc.TextureCacheCanvas = cc.Class.extend(/** @lends cc.TextureCacheCanvas# */{ - /// ---- common properties start ---- +cc.TextureCache = cc.Class.extend(/** @lends cc.TextureCache# */{ _textures:null, _textureColorsCache:null, - _textureKeySeq:1000, - - /** - * Constructor - */ - ctor:function () { - cc.Assert(cc.g_sharedTextureCache == null, "Attempted to allocate a second instance of a singleton."); - this._textureKeySeq += (0 | Math.random() * 1000); - this._textures = {}; - this._textureColorsCache = {}; - }, - - _addImageAsyncCallBack:function (target, selector) { - if (target && (typeof(selector) == "string")) { - target[selector](); - } else if (target && (typeof(selector) == "function")) { - selector.call(target); - } - }, - - /** - *

- * Returns a Texture2D object given an PVR filename
- * If the file image was not previously loaded, it will create a new CCTexture2D
- * object and it will return it. Otherwise it will return a reference of a previously loaded image
- * note: AddPVRTCImage does not support on HTML5 - *

- * @param {String} filename - * @return {cc.Texture2D} - */ - addPVRTCImage:function (filename) { - cc.Assert(0, "TextureCache:addPVRTCImage does not support on HTML5"); - }, - - - /** - *

- * Returns a Texture2D object given an ETC filename
- * If the file image was not previously loaded, it will create a new CCTexture2D
- * object and it will return it. Otherwise it will return a reference of a previously loaded image
- * note:addETCImage does not support on HTML5 - *

- * @param {String} filename - * @return {cc.Texture2D} - */ - addETCImage:function (filename) { - cc.Assert(0, "TextureCache:addPVRTCImage does not support on HTML5"); - }, - - /** - * Description - * @return {String} - */ - description:function () { - return ""; - }, - - /** - * Returns an already created texture. Returns null if the texture doesn't exist. - * @param {String} textureKeyName - * @return {HTMLImageElement|cc.Texture2D|Null} - * @example - * //example - * var key = cc.TextureCache.getInstance().textureForKey("hello.png"); - */ - textureForKey:function (textureKeyName) { - var fullPath = cc.FileUtils.getInstance().fullPathForFilename(textureKeyName); - if (this._textures.hasOwnProperty(fullPath)) - return this._textures[fullPath]; - return null; - }, - - /** - * @param {Image} texture - * @return {String|Null} - * @example - * //example - * var key = cc.TextureCache.getInstance().getKeyByTexture(texture); - */ - getKeyByTexture:function (texture) { - for (var key in this._textures) { - if (this._textures[key] == texture) { - return key; - } - } - return null; - }, - - _generalTextureKey:function () { - this._textureKeySeq++; - return "_textureKey_" + this._textureKeySeq; - }, - - /** - * @param {Image} texture - * @return {Array} - * @example - * //example - * var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(texture); - */ - getTextureColors:function (texture) { - var key = this.getKeyByTexture(texture); - if (!key) { - if (texture instanceof HTMLImageElement) - key = texture.src; - else - key = this._generalTextureKey(); - } - - if (!this._textureColorsCache.hasOwnProperty(key)) - this._textureColorsCache[key] = cc.generateTextureCacheForColor(texture); - return this._textureColorsCache[key]; - }, - - /** - *

Returns a Texture2D object given an PVR filename
- * If the file image was not previously loaded, it will create a new Texture2D
- * object and it will return it. Otherwise it will return a reference of a previously loaded image

- * @param {String} path - * @return {cc.Texture2D} - */ - addPVRImage:function (path) { - cc.Assert(path != null, "TextureCache: file image MUST not be null"); - - path = cc.FileUtils.getInstance().fullPathForFilename(path); - - var key = path; - - if (this._textures[key] != null) { - return this._textures[key]; - } - - // Split up directory and filename - var tex = new cc.Texture2D(); - if (tex.initWithPVRFile(key)) { - this._textures[key] = tex; - } else { - cc.log("cocos2d: Couldn't add PVRImage:" + key + " in TextureCache"); - } - return tex; - }, - /// ---- common properties end ---- - /** - *

Purges the dictionary of loaded textures.
- * Call this method if you receive the "Memory Warning"
- * In the short term: it will free some resources preventing your app from being killed
- * In the medium term: it will allocate more resources
- * In the long term: it will be the same

- * @example - * //example - * cc.TextureCache.getInstance().removeAllTextures(); - */ - removeAllTextures:function () { - this._textures = {}; - }, - - /** - * Deletes a texture from the cache given a texture - * @param {Image} texture - * @example - * //example - * cc.TextureCache.getInstance().removeTexture(texture); - */ - removeTexture:function (texture) { - if (!texture) - return; - - for (var selKey in this._textures) { - if (this._textures[selKey] == texture) { - delete(this._textures[selKey]); - } - } - }, - - /** - * Deletes a texture from the cache given a its key name - * @param {String} textureKeyName - * @example - * //example - * cc.TextureCache.getInstance().removeTexture("hello.png"); - */ - removeTextureForKey:function (textureKeyName) { - if (textureKeyName == null) - return; - var fullPath = cc.FileUtils.getInstance().fullPathForFilename(textureKeyName); - if (this._textures[fullPath]) - delete(this._textures[fullPath]); - }, - - /** - * Loading the images asynchronously - * @param {String} path - * @param {cc.Node} target - * @param {Function} selector - * @return {HTMLImageElement|cc.Texture2D} - * @example - * //example - * cc.TextureCache.getInstance().addImageAsync("hello.png", this, this.loadingCallBack); - */ - addImageAsync:function (path, target, selector) { - cc.Assert(path != null, "TextureCache: path MUST not be null"); - path = cc.FileUtils.getInstance().fullPathForFilename(path); - var texture = this._textures[path]; - - if (texture) { - this._addImageAsyncCallBack(target, selector); - } else { - texture = new Image(); - texture.crossOrigin = "Anonymous"; - - var that = this; - texture.addEventListener("load", function () { - that._addImageAsyncCallBack(target, selector); - }); - texture.addEventListener("error", function () { - cc.Loader.getInstance().onResLoadingErr(path); - //remove from cache - if (that._textures.hasOwnProperty(path)) - delete that._textures[path]; - }); - texture.src = path; - this._textures[path] = texture; - } - return this._textures[path]; - }, - - /** - *

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} path - * @return {HTMLImageElement|cc.Texture2D} - * @example - * //example - * cc.TextureCache.getInstance().addImage("hello.png"); - */ - addImage:function (path) { - cc.Assert(path != null, "TextureCache: path MUST not be null"); - - path = cc.FileUtils.getInstance().fullPathForFilename(path); - - var texture = this._textures[path]; - if (texture) { - cc.Loader.getInstance().onResLoaded(); - } else { - texture = new Image(); - texture.crossOrigin = "Anonymous"; - - var that = this; - texture.addEventListener("load", function () { - cc.Loader.getInstance().onResLoaded(); - }); - texture.addEventListener("error", function () { - cc.Loader.getInstance().onResLoadingErr(path); - //remove from cache - if (that._textures.hasOwnProperty(path)) - delete that._textures[path]; - }); - texture.src = path; - this._textures[path] = texture; - } - - return this._textures[path]; - }, - - /** - * Cache the image data - * @param {String} path - * @param {Image|HTMLImageElement|HTMLCanvasElement} texture - */ - cacheImage:function (path, texture) { - this._textures[path] = texture; - }, - - /** - *

Returns a Texture2D object given an UIImage image
- * If the image was not previously loaded, it will create a new Texture2D object and it will return it.
- * Otherwise it will return a reference of a previously loaded image
- * The "key" parameter will be used as the "key" for the cache.
- * If "key" is null, then a new texture will be created each time.

- * @param {HTMLImageElement|HTMLCanvasElement} image - * @param {String} key - * @return {HTMLImageElement|HTMLCanvasElement} - */ - addUIImage:function (image, key) { - cc.Assert(image != null, "TextureCache: image MUST not be nulll"); - - if (key && this._textures.hasOwnProperty(key) && this._textures[key]) - return this._textures[key]; - - // prevents overloading the autorelease pool - if ((key != null) && (image != null)) - this._textures[key] = image; - else - cc.log("cocos2d: Couldn't add UIImage in TextureCache"); - - return image; - }, - - /** - *

Output to cc.log the current contents of this TextureCache
- * This will attempt to calculate the size of each texture, and the total texture memory in use.

- */ - dumpCachedTextureInfo:function () { - var count = 0; - var totalBytes = 0; - for (var key in this._textures) { - var selTexture = this._textures[key]; - count++; - if (selTexture instanceof HTMLImageElement) - cc.log("cocos2d: '" + key + "' id=" + selTexture.src + " " + selTexture.width + " x " + selTexture.height); - else { - cc.log("cocos2d: '" + key + "' id= HTMLCanvasElement " + selTexture.width + " x " + selTexture.height); - totalBytes += selTexture.width * selTexture.height * 4; - } - } - - for (key in this._textureColorsCache) { - var selCanvas = this._textureColorsCache[key]; - count++; - cc.log("cocos2d: '" + key + "' id= HTMLCanvasElement " + selCanvas.width + " x " + selCanvas.height); - totalBytes += selCanvas.width * selCanvas.height * 4; - } - - cc.log("cocos2d: TextureCache dumpDebugInfo: " + count + " textures, HTMLCanvasElement for " - + (totalBytes / 1024) + " KB (" + (totalBytes / (1024.0 * 1024.0)).toFixed(2) + " MB)"); - } -}); - -/** - * Return ths shared instance of the cache - * @return {cc.TextureCache} - */ -cc.TextureCacheCanvas.getInstance = function () { - if (!cc.g_sharedTextureCache) - cc.g_sharedTextureCache = new cc.TextureCacheCanvas(); - return cc.g_sharedTextureCache; -}; - -/** - * Purges the cache. It releases the retained instance. - */ -cc.TextureCacheCanvas.purgeSharedTextureCache = function () { - cc.g_sharedTextureCache = null; -}; - -cc.TextureCacheWebGL = cc.Class.extend({ - /// ---- common properties start ---- - _textures:null, - _textureColorsCache:null, - _textureKeySeq:1000, + _textureKeySeq:null, _rendererInitialized:false, _loadedTexturesBefore:null, @@ -435,19 +83,21 @@ cc.TextureCacheWebGL = cc.Class.extend({ /** * Constructor */ - ctor:function () { + ctor: function () { cc.Assert(cc.g_sharedTextureCache == null, "Attempted to allocate a second instance of a singleton."); this._textureKeySeq += (0 | Math.random() * 1000); this._textures = {}; this._textureColorsCache = {}; - this._loadedTexturesBefore = {}; - this._loadingTexturesBefore = {}; + if(cc.renderContextType === cc.WEBGL){ + this._loadedTexturesBefore = {}; + this._loadingTexturesBefore = {}; + } }, _addImageAsyncCallBack:function (target, selector) { - if (target && (typeof(selector) == "string")) { + if (target && (typeof(selector) === "string")) { target[selector](); - } else if (target && (typeof(selector) == "function")) { + } else if (target && (typeof(selector) === "function")) { selector.call(target); } }, @@ -457,19 +107,14 @@ cc.TextureCacheWebGL = cc.Class.extend({ var selPath; //init texture from _loadedTexturesBefore - for(selPath in this._loadedTexturesBefore){ - var htmlImage = this._loadedTexturesBefore[selPath]; + var locLoadedTexturesBefore = this._loadedTexturesBefore, locTextures = this._textures; + for(selPath in locLoadedTexturesBefore){ + var htmlImage = locLoadedTexturesBefore[selPath]; var texture2d = new cc.Texture2D(); texture2d.initWithElement(htmlImage); texture2d.handleLoadedTexture(); - this._textures[selPath] = texture2d; - } - this._loadedTexturesBefore = {}; - - //init texture from _loadingTexturesBefore - for(selPath in this._loadedTexturesBefore){ - this.addImage(selPath); + locTextures[selPath] = texture2d; } this._loadedTexturesBefore = {}; }, @@ -488,6 +133,7 @@ cc.TextureCacheWebGL = cc.Class.extend({ cc.Assert(0, "TextureCache:addPVRTCImage does not support on HTML5"); }, + /** *

* Returns a Texture2D object given an ETC filename
@@ -513,7 +159,7 @@ cc.TextureCacheWebGL = cc.Class.extend({ /** * Returns an already created texture. Returns null if the texture doesn't exist. * @param {String} textureKeyName - * @return {HTMLImageElement|cc.Texture2D|Null} + * @return {cc.Texture2D|Null} * @example * //example * var key = cc.TextureCache.getInstance().textureForKey("hello.png"); @@ -594,7 +240,6 @@ cc.TextureCacheWebGL = cc.Class.extend({ } return tex; }, - /// ---- common properties end ---- /** *

Purges the dictionary of loaded textures.
@@ -607,9 +252,10 @@ cc.TextureCacheWebGL = cc.Class.extend({ * cc.TextureCache.getInstance().removeAllTextures(); */ removeAllTextures:function () { - for (var selKey in this._textures) { - if(this._textures[selKey]) - this._textures[selKey].releaseTexture(); + var locTextures = this._textures; + for (var selKey in locTextures) { + if(locTextures[selKey]) + locTextures[selKey].releaseTexture(); } this._textures = {}; }, @@ -625,10 +271,11 @@ cc.TextureCacheWebGL = cc.Class.extend({ if (!texture) return; - for (var selKey in this._textures) { - if (this._textures[selKey] == texture) { - this._textures[selKey].releaseTexture(); - delete(this._textures[selKey]); + var locTextures = this._textures; + for (var selKey in locTextures) { + if (locTextures[selKey] == texture) { + locTextures[selKey].releaseTexture(); + delete(locTextures[selKey]); } } }, @@ -644,10 +291,8 @@ cc.TextureCacheWebGL = cc.Class.extend({ if (textureKeyName == null) return; var fullPath = cc.FileUtils.getInstance().fullPathForFilename(textureKeyName); - if (this._textures[fullPath]){ - this._textures[fullPath].releaseTexture(); + if (this._textures[fullPath]) delete(this._textures[fullPath]); - } }, /** @@ -655,7 +300,7 @@ cc.TextureCacheWebGL = cc.Class.extend({ * @param {String} path * @param {cc.Node} target * @param {Function} selector - * @return {HTMLImageElement|cc.Texture2D} + * @return {cc.Texture2D} * @example * //example * cc.TextureCache.getInstance().addImageAsync("hello.png", this, this.loadingCallBack); @@ -664,28 +309,42 @@ cc.TextureCacheWebGL = cc.Class.extend({ cc.Assert(path != null, "TextureCache: path MUST not be null"); path = cc.FileUtils.getInstance().fullPathForFilename(path); var texture = this._textures[path]; - + var image,that; if (texture) { - this._addImageAsyncCallBack(target, selector); + if(texture.isLoaded()){ + this._addImageAsyncCallBack(target, selector); + }else{ + that = this; + image = texture.getHtmlElementObj(); + image.addEventListener("load", function () { + texture.handleLoadedTexture(); + that._addImageAsyncCallBack(target, selector); + this.removeEventListener('load', arguments.callee, false); + }); + } } else { - texture = new Image(); - texture.crossOrigin = "Anonymous"; + image = new Image(); + image.crossOrigin = "Anonymous"; - var that = this; - texture.addEventListener("load", function () { + that = this; + image.addEventListener("load", function () { if (that._textures.hasOwnProperty(path)) that._textures[path].handleLoadedTexture(); that._addImageAsyncCallBack(target, selector); + this.removeEventListener('load', arguments.callee, false); + this.removeEventListener('error', arguments.callee, false); }); - texture.addEventListener("error", function () { + image.addEventListener("error", function () { cc.Loader.getInstance().onResLoadingErr(path); //remove from cache if (that._textures.hasOwnProperty(path)) delete that._textures[path]; + + this.removeEventListener('error', arguments.callee, false); }); - texture.src = path; + image.src = path; var texture2d = new cc.Texture2D(); - texture2d.initWithElement(texture); + texture2d.initWithElement(image); this._textures[path] = texture2d; } return this._textures[path]; @@ -699,10 +358,15 @@ cc.TextureCacheWebGL = cc.Class.extend({ cc.Loader.getInstance().onResLoaded(); that._loadedTexturesBefore[path] = texture; delete that._loadingTexturesBefore[path]; + + this.removeEventListener('load', arguments.callee, false); + this.removeEventListener('error', arguments.callee, false); }); texture.addEventListener("error", function () { cc.Loader.getInstance().onResLoadingErr(path); delete that._loadingTexturesBefore[path]; + + this.removeEventListener('error', arguments.callee, false); }); texture.src = path; this._loadingTexturesBefore[path] = texture; @@ -715,41 +379,56 @@ cc.TextureCacheWebGL = cc.Class.extend({ * Otherwise it will return a reference of a previously loaded image.
* Supported image extensions: .png, .jpg, .gif

* @param {String} path - * @return {HTMLImageElement|cc.Texture2D} + * @return {cc.Texture2D} * @example * //example * cc.TextureCache.getInstance().addImage("hello.png"); */ addImage:function (path) { cc.Assert(path != null, "TextureCache: path MUST not be null"); - if(!this._rendererInitialized) - return this._addImageBeforeRenderer(path); + if(cc.renderContextType === cc.WEBGL){ + if (!this._rendererInitialized) + return this._addImageBeforeRenderer(path); + } path = cc.FileUtils.getInstance().fullPathForFilename(path); var texture = this._textures[path]; + var image; if (texture) { - cc.Loader.getInstance().onResLoaded(); + if (texture.isLoaded()) { + cc.Loader.getInstance().onResLoaded(); + } else { + image = texture.getHtmlElementObj(); + image.addEventListener("load", function () { + texture.handleLoadedTexture(); + cc.Loader.getInstance().onResLoaded(); + this.removeEventListener('load', arguments.callee, false); + }); + } } else { - texture = new Image(); - texture.crossOrigin = "Anonymous"; + image = new Image(); + image.crossOrigin = "Anonymous"; var that = this; - texture.addEventListener("load", function () { + image.addEventListener("load", function () { cc.Loader.getInstance().onResLoaded(); if (that._textures.hasOwnProperty(path)) that._textures[path].handleLoadedTexture(); + this.removeEventListener('load', arguments.callee, false); + this.removeEventListener('error', arguments.callee, false); }); - texture.addEventListener("error", function () { + image.addEventListener("error", function () { cc.Loader.getInstance().onResLoadingErr(path); //remove from cache if (that._textures.hasOwnProperty(path)) delete that._textures[path]; - }); - texture.src = path; + this.removeEventListener('error', arguments.callee, false); + }); + image.src = path; var texture2d = new cc.Texture2D(); - texture2d.initWithElement(texture); + texture2d.initWithElement(image); this._textures[path] = texture2d; } @@ -778,7 +457,7 @@ cc.TextureCacheWebGL = cc.Class.extend({ * Otherwise it will return a reference of a previously loaded image
* The "key" parameter will be used as the "key" for the cache.
* If "key" is null, then a new texture will be created each time.

- * @param {cc.Image} image + * @param {HTMLImageElement|HTMLCanvasElement} image * @param {String} key * @return {cc.Texture2D} */ @@ -806,18 +485,32 @@ cc.TextureCacheWebGL = cc.Class.extend({ */ dumpCachedTextureInfo:function () { var count = 0; - var totalBytes = 0; - for (var key in this._textures) { - var tex = this._textures[key]; - var bpp = tex.bitsPerPixelForFormat(); - // Each texture takes up width * height * bytesPerPixel bytes. - var bytes = tex.getPixelsWide() * tex.getPixelsHigh() * bpp / 8; - totalBytes += bytes; + var totalBytes = 0, locTextures = this._textures; + + for (var key in locTextures) { + var selTexture = locTextures[key]; count++; - cc.log("cocos2d: Texture URL=" + tex._htmlElementObj.src + " " + tex.getPixelsWide() + " x " + tex.getPixelsHigh() + " @ " + bpp + " bpp => " + bytes / 1024 + " KB"); + if (selTexture.getHtmlElementObj() instanceof HTMLImageElement) + cc.log("cocos2d: '" + key + "' id=" + selTexture.getHtmlElementObj().src + " " + selTexture.getPixelsWide() + " x " + selTexture.getPixelsHigh()); + else { + cc.log("cocos2d: '" + key + "' id= HTMLCanvasElement " + selTexture.getPixelsWide() + " x " + selTexture.getPixelsHigh()); + } + totalBytes += selTexture.getPixelsWide() * selTexture.getPixelsHigh() * 4; } - cc.log("cocos2d: TextureCache dumpDebugInfo: " + count + " textures, for " + (totalBytes / 1024) + " KB (" + (totalBytes / (1024.0 * 1024.0)).toFixed(2) + " MB)"); + var locTextureColorsCache = this._textureColorsCache; + for (key in locTextureColorsCache) { + var selCanvasColorsArr = locTextureColorsCache[key]; + for (var selCanvasKey in selCanvasColorsArr){ + var selCanvas = selCanvasColorsArr[selCanvasKey]; + count++; + cc.log("cocos2d: '" + key + "' id= HTMLCanvasElement " + selCanvas.width + " x " + selCanvas.height); + totalBytes += selCanvas.width * selCanvas.height * 4; + } + + } + cc.log("cocos2d: TextureCache dumpDebugInfo: " + count + " textures, HTMLCanvasElement for " + + (totalBytes / 1024) + " KB (" + (totalBytes / (1024.0 * 1024.0)).toFixed(2) + " MB)"); } }); @@ -825,19 +518,15 @@ cc.TextureCacheWebGL = cc.Class.extend({ * Return ths shared instance of the cache * @return {cc.TextureCache} */ -cc.TextureCacheWebGL.getInstance = function () { +cc.TextureCache.getInstance = function () { if (!cc.g_sharedTextureCache) - cc.g_sharedTextureCache = new cc.TextureCacheWebGL(); + cc.g_sharedTextureCache = new cc.TextureCache(); return cc.g_sharedTextureCache; }; /** * Purges the cache. It releases the retained instance. */ -cc.TextureCacheWebGL.purgeSharedTextureCache = function () { +cc.TextureCache.purgeSharedTextureCache = function () { cc.g_sharedTextureCache = null; }; - -cc.TextureCache = cc.Browser.supportWebGL ? cc.TextureCacheWebGL : cc.TextureCacheCanvas; - - diff --git a/cocos2d/tileMap_parallax_nodes/CCParallaxNode.js b/cocos2d/tileMap_parallax_nodes/CCParallaxNode.js index c5c29f91fa..9d512e30b5 100644 --- a/cocos2d/tileMap_parallax_nodes/CCParallaxNode.js +++ b/cocos2d/tileMap_parallax_nodes/CCParallaxNode.js @@ -202,7 +202,7 @@ cc.ParallaxNode = cc.Node.extend(/** @lends cc.ParallaxNode# */{ var point = locParallaxArray[i]; var x = -pos.x + pos.x * point.getRatio().x + point.getOffset().x; var y = -pos.y + pos.y * point.getRatio().y + point.getOffset().y; - point.getChild().setPosition(cc.p(x, y)); + point.getChild().setPosition(x, y); } this._lastPosition = pos; } diff --git a/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js b/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js index 4a4539ffc8..139ca28a62 100644 --- a/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js +++ b/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js @@ -69,6 +69,10 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ //used for retina display _contentScaleFactor: null, + _cacheCanvas:null, + _cacheContext:null, + _cacheTexture:null, + /** * Constructor */ @@ -76,9 +80,106 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ cc.SpriteBatchNode.prototype.ctor.call(this); this._children = []; this._descendants = []; - this._useCache = true; + this._layerSize = cc.SizeZero(); this._mapTileSize = cc.SizeZero(); + + if(cc.renderContextType === cc.CANVAS){ + var locCanvas = cc.canvas; + var tmpCanvas = document.createElement('canvas'); + tmpCanvas.width = locCanvas.width; + tmpCanvas.height = locCanvas.height; + this._cacheCanvas = tmpCanvas; + this._cacheContext = this._cacheCanvas.getContext('2d'); + var tempTexture = new cc.Texture2D(); + tempTexture.initWithElement(tmpCanvas); + tempTexture.handleLoadedTexture(); + this._cacheTexture = tempTexture; + this.setContentSize(cc.size(locCanvas.width, locCanvas.height)); + } + }, + + setContentSize:function (size) { + if (!size) + return; + cc.Node.prototype.setContentSize.call(this, size); + + if(cc.renderContextType === cc.CANVAS){ + var locCanvas = this._cacheCanvas; + locCanvas.width = 0|(size.width * 1.5); + locCanvas.height = 0|(size.height * 1.5); + this._cacheContext.translate(0, locCanvas.height); + var locContentSize = this._cacheTexture._contentSize; + locContentSize.width = locCanvas.width; + locContentSize.height = locCanvas.height; + } + }, + + /** + * Return texture of cc.SpriteBatchNode + * @return {cc.Texture2D} + */ + getTexture:function () { + if(cc.renderContextType === cc.CANVAS) + return this._cacheTexture; + else + return cc.SpriteBatchNode.prototype.getTexture.call(this); + }, + + /** + * don't call visit on it's children ( override visit of cc.Node ) + * @override + * @param {CanvasRenderingContext2D} ctx + */ + visit:function (ctx) { + if (cc.renderContextType === cc.WEBGL) { + cc.SpriteBatchNode.prototype.visit.call(this, ctx); + return; + } + var context = ctx || cc.renderContext; + // quick return if not visible + if (!this._visible) + return; + + context.save(); + this.transform(ctx); + var i, locChildren = this._children; + + if (this._cacheDirty) { + //add dirty region + var locCacheContext = this._cacheContext, locCacheCanvas = this._cacheCanvas; + locCacheContext.clearRect(0, 0, locCacheCanvas.width, -locCacheCanvas.height); + locCacheContext.save(); + locCacheContext.translate(this._anchorPointInPoints.x, -(this._anchorPointInPoints.y )); + if (locChildren) { + this.sortAllChildren(); + for (i = 0; i < locChildren.length; i++) { + if (locChildren[i]) + locChildren[i].visit(locCacheContext); + } + } + locCacheContext.restore(); + this._cacheDirty = false; + } + // draw RenderTexture + this.draw(ctx); + context.restore(); + }, + + /** + * draw cc.SpriteBatchNode (override draw of cc.Node) + * @param {CanvasRenderingContext2D} ctx + */ + draw:null, + + _drawForCanvas:function (ctx) { + var context = ctx || cc.renderContext; + //context.globalAlpha = this._opacity / 255; + var posX = 0 | ( -this._anchorPointInPoints.x), posY = 0 | ( -this._anchorPointInPoints.y); + var locCacheCanvas = this._cacheCanvas; + //direct draw image by canvas drawImage + if (locCacheCanvas) + context.drawImage(locCacheCanvas, posX, -(posY + locCacheCanvas.height)); }, /** @@ -379,7 +480,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ var sprite = this.getChildByTag(z); if (sprite) - cc.SpriteBatchNode.prototype.removeChild.call(this,sprite,true); //this.removeChild(sprite, true); + cc.SpriteBatchNode.prototype.removeChild.call(this, sprite, true); //this.removeChild(sprite, true); else { if(cc.renderContextType === cc.WEBGL) this._textureAtlas.removeQuadAtIndex(atlasIndex); @@ -438,8 +539,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ setupTiles:function () { // Optimization: quick hack that sets the image size on the tileset if (cc.renderContextType === cc.CANVAS) { - var textureCache = this._originalTexture; - this._tileSet.imageSize = cc.size(textureCache.width, textureCache.height); + this._tileSet.imageSize = this._originalTexture.getContentSizeInPixels(); } else { this._tileSet.imageSize = this._textureAtlas.getTexture().getContentSizeInPixels(); @@ -506,7 +606,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ var zz = this._atlasIndexArray[atlasIndex]; this._tiles[zz] = 0; cc.ArrayRemoveObjectAtIndex(this._atlasIndexArray, atlasIndex); - this._super(sprite, cleanup); + cc.SpriteBatchNode.prototype.removeChild.call(this, sprite, cleanup); }, /** @@ -550,7 +650,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ (this._mapTileSize.height / 2 ) * (-pos.x - pos.y)); break; case cc.TMX_ORIENTATION_HEX: - cc.Assert(cc.pointEqualToPoint(pos, cc.PointZero()), "offset for hexagonal map not implemented yet"); + cc.Assert((pos.x == 0 && pos.y == 0), "offset for hexagonal map not implemented yet"); break; } return ret; @@ -667,15 +767,15 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ sprite.setRotation(0.0); } - sprite.setFlipX(false); - sprite.setFlipY(false); + sprite.setFlippedX(false); + sprite.setFlippedY(false); // Rotation in tiled is achieved using 3 flipped states, flipping across the horizontal, vertical, and diagonal axes of the tiles. if ((gid & cc.TMX_TILE_DIAGONAL_FLAG) >>> 0) { // put the anchor in the middle for ease of rotation. sprite.setAnchorPoint(cc.p(0.5, 0.5)); - sprite.setPosition(cc.p(this.getPositionAt(pos).x + sprite.getContentSize().height / 2, - this.getPositionAt(pos).y + sprite.getContentSize().width / 2)); + sprite.setPosition(this.getPositionAt(pos).x + sprite.getContentSize().height / 2, + this.getPositionAt(pos).y + sprite.getContentSize().width / 2); var flag = (gid & (cc.TMX_TILE_HORIZONTAL_FLAG | cc.TMX_TILE_VERTICAL_FLAG) >>> 0) >>> 0; // handle the 4 diagonally flipped states. @@ -685,17 +785,17 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ sprite.setRotation(270); else if (flag == (cc.TMX_TILE_VERTICAL_FLAG | cc.TMX_TILE_HORIZONTAL_FLAG) >>> 0) { sprite.setRotation(90); - sprite.setFlipX(true); + sprite.setFlippedX(true); } else { sprite.setRotation(270); - sprite.setFlipX(true); + sprite.setFlippedX(true); } } else { if ((gid & cc.TMX_TILE_HORIZONTAL_FLAG) >>> 0) - sprite.setFlipX(true); + sprite.setFlippedX(true); if ((gid & cc.TMX_TILE_VERTICAL_FLAG) >>> 0) - sprite.setFlipY(true); + sprite.setFlippedY(true); } }, @@ -721,8 +821,6 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ this._reusedTile.initWithTexture(this._textureForCanvas, rect, false); this._reusedTile.setBatchNode(this); this._reusedTile.setParent(this); - - return this._reusedTile; } return this._reusedTile; }, @@ -776,6 +874,12 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ } }); +if(cc.Browser.supportWebGL){ + cc.TMXLayer.prototype.draw = cc.SpriteBatchNode.prototype.draw; +}else{ + cc.TMXLayer.prototype.draw = cc.TMXLayer.prototype._drawForCanvas; +} + /** * Creates a cc.TMXLayer with an tile set info, a layer info and a map info * @param {cc.TMXTilesetInfo} tilesetInfo diff --git a/cocos2d/tileMap_parallax_nodes/CCTMXTiledMap.js b/cocos2d/tileMap_parallax_nodes/CCTMXTiledMap.js index cd23fae034..09147115d5 100644 --- a/cocos2d/tileMap_parallax_nodes/CCTMXTiledMap.js +++ b/cocos2d/tileMap_parallax_nodes/CCTMXTiledMap.js @@ -55,7 +55,7 @@ cc.TMX_ORIENTATION_ISO = 2; * *

Features:
* - Each tile will be treated as an cc.Sprite
- * - The sprites are created on demand. They will be created only when you call "layer.tileAt(position)"
+ * - The sprites are created on demand. They will be created only when you call "layer.getTileAt(position)"
* - Each tile can be rotated / moved / scaled / tinted / "opacitied", since each tile is a cc.Sprite
* - Tiles can be added/removed in runtime
* - The z-order of the tiles can be modified in runtime
diff --git a/cocos2d/tileMap_parallax_nodes/CCTileMapAtlas.js b/cocos2d/tileMap_parallax_nodes/CCTileMapAtlas.js index d2efa47a2f..969c85a693 100644 --- a/cocos2d/tileMap_parallax_nodes/CCTileMapAtlas.js +++ b/cocos2d/tileMap_parallax_nodes/CCTileMapAtlas.js @@ -97,7 +97,7 @@ cc.TileMapAtlas = cc.AtlasNode.extend(/** @lends cc.TileMapAtlas# */{ * @param {cc.Point} position * @return {cc.Color3B} */ - tileAt:function (position) { + getTileAt:function (position) { cc.Assert(this._TGAInfo != null, "tgaInfo must not be nil"); cc.Assert(position.x < this._TGAInfo.width, "Invalid position.x"); cc.Assert(position.y < this._TGAInfo.height, "Invalid position.y"); diff --git a/cocos2d/touch_dispatcher/CCTouchDelegateProtocol.js b/cocos2d/touch_dispatcher/CCTouchDelegateProtocol.js index 3e0d73d2f4..fc2a42af7a 100644 --- a/cocos2d/touch_dispatcher/CCTouchDelegateProtocol.js +++ b/cocos2d/touch_dispatcher/CCTouchDelegateProtocol.js @@ -137,7 +137,7 @@ cc.TouchDelegate = cc.Class.extend(/** @lends cc.TouchDelegate# */{ /** * Virtual function - * @param {cc.Touch} touch + * @param {Array} touches * @param {event} event */ onTouchesBegan:function (touches, event) { @@ -145,7 +145,7 @@ cc.TouchDelegate = cc.Class.extend(/** @lends cc.TouchDelegate# */{ /** * Virtual function - * @param {cc.Touch} touch + * @param {Array} touches * @param {event} event */ onTouchesMoved:function (touches, event) { @@ -153,7 +153,7 @@ cc.TouchDelegate = cc.Class.extend(/** @lends cc.TouchDelegate# */{ /** * Virtual function - * @param {cc.Touch} touch + * @param {Array} touches * @param {event} event */ onTouchesEnded:function (touches, event) { @@ -161,7 +161,7 @@ cc.TouchDelegate = cc.Class.extend(/** @lends cc.TouchDelegate# */{ /** * Virtual function - * @param {cc.Touch} touch + * @param {Array} touches * @param {event} event */ onTouchesCancelled:function (touches, event) { @@ -169,7 +169,7 @@ cc.TouchDelegate = cc.Class.extend(/** @lends cc.TouchDelegate# */{ /* * In TouchesTest, class Padle inherits from cc.Sprite and cc.TargetedTouchDelegate. - * When it invoke cc.Director.getInstance().getTouchDispatcher().addTargetedDelegate(this, 0, true), + * When it invoke cc.registerTargetedDelegate(0, true, this), * it will crash in cc.TouchHandler.initWithDelegate() because of dynamic_cast() on android. * I don't know why, so add these functions for the subclass to invoke it's own retain() and release *Virtual function diff --git a/cocos2d/touch_dispatcher/CCTouchDispatcher.js b/cocos2d/touch_dispatcher/CCTouchDispatcher.js index 933adb9408..d935ecb1d0 100644 --- a/cocos2d/touch_dispatcher/CCTouchDispatcher.js +++ b/cocos2d/touch_dispatcher/CCTouchDispatcher.js @@ -178,11 +178,12 @@ cc.TouchDispatcher = cc.Class.extend(/** @lends cc.TouchDispatcher# */ { * Adds a standard touch delegate to the dispatcher's list. * See StandardTouchDelegate description. * IMPORTANT: The delegate will be retained. - * @param {cc.TouchDelegate} delegate - * @param {Number} priority + * @param {Object} delegate + * @param {Number} [priority=0] */ - addStandardDelegate:function (delegate, priority) { - var handler = cc.StandardTouchHandler.handlerWithDelegate(delegate, priority); + _addStandardDelegate:function (delegate, priority) { + priority = priority || 0; + var handler = cc.StandardTouchHandler.create(delegate, priority); if (!this._locked) { this._standardHandlers = this.forceAddHandler(handler, this._standardHandlers); @@ -201,12 +202,12 @@ cc.TouchDispatcher = cc.Class.extend(/** @lends cc.TouchDispatcher# */ { }, /** - * @param {cc.TouchDelegate} delegate + * @param {Object} delegate * @param {Number} priority * @param {Boolean} swallowsTouches */ - addTargetedDelegate:function (delegate, priority, swallowsTouches) { - var handler = cc.TargetedTouchHandler.handlerWithDelegate(delegate, priority, swallowsTouches); + _addTargetedDelegate:function (delegate, priority, swallowsTouches) { + var handler = cc.TargetedTouchHandler.create(delegate, priority, swallowsTouches); if (!this._locked) { this._targetedHandlers = this.forceAddHandler(handler, this._targetedHandlers); } else { @@ -259,7 +260,7 @@ cc.TouchDispatcher = cc.Class.extend(/** @lends cc.TouchDispatcher# */ { * The delegate will be released * @param {cc.TouchDelegate} delegate */ - removeDelegate:function (delegate) { + _removeDelegate:function (delegate) { if (delegate == null) { return; } @@ -1031,3 +1032,31 @@ cc.TouchDispatcher._preTouchPool = []; * @type {Number} */ cc.TouchDispatcher._preTouchPoolPointer = 0; + +/** + * register a targeted touch delegate to the dispatcher's list. + * @param {Number} priority + * @param {Boolean} swallowsTouches + * @param {Object} delegate + */ +cc.registerTargetedDelegate = function(priority, swallowsTouches, delegate){ + cc.Director.getInstance().getTouchDispatcher()._addTargetedDelegate(delegate, priority, swallowsTouches); +}; + +/** + * Adds a standard touch delegate to the dispatcher's list. + * See StandardTouchDelegate description. + * @param {Object} delegate + * @param {Number} [priority=] + */ +cc.registerStandardDelegate = function(delegate, priority){ + cc.Director.getInstance().getTouchDispatcher()._addStandardDelegate(delegate, priority); +}; + +/** + * Removes a touch delegate. from TouchDispatcher + * @param delegate + */ +cc.unregisterTouchDelegate = function(delegate){ + cc.Director.getInstance().getTouchDispatcher()._removeDelegate(delegate); +}; \ No newline at end of file diff --git a/cocos2d/touch_dispatcher/CCTouchHandler.js b/cocos2d/touch_dispatcher/CCTouchHandler.js index a67f2130e3..cd3bb2c647 100644 --- a/cocos2d/touch_dispatcher/CCTouchHandler.js +++ b/cocos2d/touch_dispatcher/CCTouchHandler.js @@ -94,12 +94,12 @@ cc.TouchHandler = cc.Class.extend(/** @lends cc.TouchHandler# */{ }); /** - * Allocates a TouchHandler with a delegate and a priority + * Create a TouchHandler with a delegate and a priority * @param {cc.TouchDelegate} delegate * @param {Number} priority * @return {cc.TouchHandler} */ -cc.TouchHandler.handlerWithDelegate = function (delegate, priority) { +cc.TouchHandler.create = function (delegate, priority) { var handler = new cc.TouchHandler(); if (handler) { handler.initWithDelegate(delegate, priority); @@ -121,20 +121,17 @@ cc.StandardTouchHandler = cc.TouchHandler.extend(/** @lends cc.StandardTouchHand * @return {Boolean} */ initWithDelegate:function (delegate, priority) { - if (this._super(delegate, priority)) { - return true; - } - return false; + return cc.TouchHandler.prototype.initWithDelegate.call(this, delegate, priority); } }); /** - * Allocates a TouchHandler with a delegate and a priority - * @param {cc.TouchDelegate} delegate + * Create a TouchHandler with a delegate and a priority + * @param {Object} delegate * @param {Number} priority * @return {cc.StandardTouchHandler} */ -cc.StandardTouchHandler.handlerWithDelegate = function (delegate, priority) { +cc.StandardTouchHandler.create = function (delegate, priority) { var handler = new cc.StandardTouchHandler(); if (handler) { handler.initWithDelegate(delegate, priority); @@ -181,7 +178,7 @@ cc.TargetedTouchHandler = cc.TouchHandler.extend(/** @lends cc.TargetedTouchHand * @return {Boolean} */ initWithDelegate:function (delegate, priority, swallow) { - if (this._super(delegate, priority)) { + if (cc.TouchHandler.prototype.initWithDelegate.call(this, delegate, priority)) { this._claimedTouches = []; this._swallowsTouches = swallow; return true; @@ -191,13 +188,13 @@ cc.TargetedTouchHandler = cc.TouchHandler.extend(/** @lends cc.TargetedTouchHand }); /** - * Allocates a TargetedTouchHandler with a delegate, a priority and whether or not it swallows touches or not - * @param {cc.TouchDelegate} delegate + * Create a TargetedTouchHandler with a delegate, a priority and whether or not it swallows touches or not + * @param {Object} delegate * @param {Number} priority * @param {Boolean} swallow * @return {cc.TargetedTouchHandler} */ -cc.TargetedTouchHandler.handlerWithDelegate = function (delegate, priority, swallow) { +cc.TargetedTouchHandler.create = function (delegate, priority, swallow) { var handler = new cc.TargetedTouchHandler(); if (handler) { handler.initWithDelegate(delegate, priority, swallow); diff --git a/extensions/CCArmature/display/CCShaderNode.js b/extensions/CCArmature/display/CCShaderNode.js deleted file mode 100644 index 8c8a6bda88..0000000000 --- a/extensions/CCArmature/display/CCShaderNode.js +++ /dev/null @@ -1,111 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2012 cocos2d-x.org - - 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.SIZE_X = 128; -cc.SIZE_Y = 128; - -cc.ShaderNode = cc.Node.extend({ - _center:cc.Vertex2(0.0, 0.0), - _resolution:cc.Vertex2(0.0, 0.0), - _time:0, - _uniformCenter:0, - _uniformResolution:0, - _uniformTime:0, - ctor:function () { - this._center = cc.Vertex2(0.0, 0.0); - this._resolution = cc.Vertex2(0.0, 0.0); - this._time = 0; - this._uniformCenter = 0; - this._uniformResolution = 0; - this._uniformTime = 0; - }, - - initWithVertex:function (vert, frag) { - this.loadShaderVertex(vert, frag); - this._time = 0; - this._resolution = cc.Vertex2(cc.SIZE_X, cc.SIZE_Y); - this.scheduleUpdate(); - this.setContentSize(cc.size(cc.SIZE_X, cc.SIZE_Y)); - this.setAnchorPoint(cc.p(0.5, 0.5)); - return true; - }, - - loadShaderVertex:function (vert, frag) { - var shader = new cc.GLProgram(); - shader.initWithVertexShaderFilename(vert, frag); - - shader.addAttribute("aVertex", cc.VERTEX_ATTRIB_POSITION); - shader.link(); - - shader.updateUniforms(); - - this._uniformCenter = cc.renderContext.getUniformLocation(shader.getProgram(), "center"); - this._uniformResolution = cc.renderContext.getUniformLocation(shader.getProgram(), "resolution"); - this._uniformTime = cc.renderContext.getUniformLocation(shader.getProgram(), "time"); - - this.setShaderProgram(shader); - - shader.release(); - }, - - update:function (dt) { - this._time += dt; - }, - - translateFormOtherNode:function (transform) { - this.setAdditionalTransform(transform); - - this._center = cc.Vertex2(this._additionalTransform.tx * cc.CONTENT_SCALE_FACTOR(), this._additionalTransform.ty * cc.CONTENT_SCALE_FACTOR()); - this._resolution = cc.Vertex2(cc.SIZE_X * this._additionalTransform.a, cc.SIZE_Y * this._additionalTransform.d); - }, - - setPosition:function (newPosition) { - cc.Node.prototype.setPosition.call(this, newPosition); - var position = this.getPosition(); - this._center = cc.Vertex2(position.x * cc.CONTENT_SCALE_FACTOR(), position.y * cc.CONTENT_SCALE_FACTOR()); - }, - - draw:function () { - cc.NODE_DRAW_SETUP(this); - var w = cc.SIZE_X, h = cc.SIZE_Y; - var vertices = [0, 0, w, 0, w, h, 0, 0, 0, h, w, h]; - - // Uniforms - this.getShaderProgram().setUniformLocationWith2f(this._uniformCenter, this._center.x, this._center.y); - this.getShaderProgram().setUniformLocationWith2f(this._uniformResolution, this._resolution.x, this._resolution.y); - - // time changes all the time, so it is Ok to call OpenGL directly, and not the "cached" version - cc.renderContext.uniform1f(this._uniformTime, this._time); - cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION); - cc.renderContext.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, cc.renderContext.FLOAT, false, 0, vertices); - cc.renderContext.drawArrays(cc.renderContext.TRIANGLES, 0, 6); - - cc.INCREMENT_GL_DRAWS(1); - } -}); -cc.ShaderNode.shaderNodeWithVertex = function (vert, frag) { - var node = new cc.ShaderNode(); - node.initWithVertex(vert, frag); - return node; -}; \ No newline at end of file diff --git a/extensions/CCArmature/physics/CCColliderDetector.js b/extensions/CCArmature/physics/CCColliderDetector.js deleted file mode 100644 index 25a4995d44..0000000000 --- a/extensions/CCArmature/physics/CCColliderDetector.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Created with JetBrains WebStorm. - * User: Administrator - * Date: 13-6-20 - * Time: 例捈3:57 - * To change this template use File | Settings | File Templates. - */ -cc.ColliderBody = cc.Class.extend({ - _b2b:null, - _contourData:null, - ctor:function () { - - }, - getB2Body:function () { - - }, - getContourData:function () { - - } -}); -cc.ColliderDetector = cc.Class.extend({ - _colliderBodyList:null, - _bone:null, - ctor:function () { - - }, - init:function (bone) { - }, - addContourData:function (contourData) { - }, - addContourDataList:function (contourDataList) { - }, - removeContourData:function (contourData) { - }, - removeAll:function () { - }, - updateTransform:function (t) { - }, - setColliderFilter:function (filter) { - }, - setActive:function (active) { - } -}); -cc.ColliderDetector.create = function () { - -}; \ No newline at end of file diff --git a/extensions/CCArmature/physics/CCPhysicsWorld.js b/extensions/CCArmature/physics/CCPhysicsWorld.js deleted file mode 100644 index ecccaf8cb7..0000000000 --- a/extensions/CCArmature/physics/CCPhysicsWorld.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Created with JetBrains WebStorm. - * User: Administrator - * Date: 13-6-20 - * Time: 例捈3:54 - * To change this template use File | Settings | File Templates. - */ - -cc.PhysicsWorld = cc.Class.extend({ - BoneColliderSignal:[], - _noGravityWorld:null, - _contactListener:null, - _debugDraw:null, - ctor:function () { - - }, - initNoGravityWorld:function () { - - }, - update:function () { - - }, - drawDebug:function () { - - }, - getNoGravityWorld:function () { - - } -}); -cc.PhysicsWorld.getInstance = function () { - -}; -cc.PhysicsWorld.purge = function () { - -}; \ No newline at end of file diff --git a/extensions/CCBReader/CCBAnimationManager.js b/extensions/CCBReader/CCBAnimationManager.js index 9174416846..41dc631303 100644 --- a/extensions/CCBReader/CCBAnimationManager.js +++ b/extensions/CCBReader/CCBAnimationManager.js @@ -45,6 +45,7 @@ cc.BuilderAnimationManager = cc.Class.extend({ _documentOutletNodes:null, _documentCallbackNames:null, _documentCallbackNodes:null, + _documentCallbackControlEvents:null, _documentControllerName:"", _lastCompletedSequenceName:"", _keyframeCallbacks:null, @@ -68,6 +69,7 @@ cc.BuilderAnimationManager = cc.Class.extend({ this._documentOutletNodes = []; this._documentCallbackNames = []; this._documentCallbackNodes = []; + this._documentCallbackControlEvents = []; this._keyframeCallbacks = []; this._keyframeCallFuncs = {}; @@ -112,6 +114,10 @@ cc.BuilderAnimationManager = cc.Class.extend({ this._documentCallbackNames.push(name); }, + addDocumentCallbackControlEvents:function(controlEvents){ + this._documentCallbackControlEvents.push(controlEvents); + }, + addDocumentOutletNode:function(node){ this._documentOutletNodes.push(node); }, @@ -136,6 +142,10 @@ cc.BuilderAnimationManager = cc.Class.extend({ return this._documentCallbackNodes; }, + getDocumentCallbackControlEvents:function(){ + return this._documentCallbackControlEvents; + }, + getDocumentOutletNames:function(){ return this._documentOutletNames; }, @@ -167,7 +177,9 @@ cc.BuilderAnimationManager = cc.Class.extend({ }, getRunningSequenceName:function () { - return this._runningSequence.getName(); + if(this._runningSequence) + return this._runningSequence.getName(); + return null; }, getContainerSize:function (node) { @@ -191,17 +203,19 @@ cc.BuilderAnimationManager = cc.Class.extend({ moveAnimationsFromNode:function(fromNode,toNode){ // Move base values - var baseValue = this._baseValues.objectForKey(fromNode); + var locBaseValues = this._baseValues; + var baseValue = locBaseValues.objectForKey(fromNode); if(baseValue != null) { - this._baseValues.setObject(baseValue, toNode); - this._baseValues.removeObjectForKey(fromNode); + locBaseValues.setObject(baseValue, toNode); + locBaseValues.removeObjectForKey(fromNode); } // Move seqs - var seqs = this._nodeSequences.objectForKey(fromNode); + var locNodeSequences = this._nodeSequences; + var seqs = locNodeSequences.objectForKey(fromNode); if(seqs != null) { - this._nodeSequences.setObject(seqs, toNode); - this._nodeSequences.removeObjectForKey(fromNode); + locNodeSequences.setObject(seqs, toNode); + locNodeSequences.removeObjectForKey(fromNode); } }, @@ -286,24 +300,24 @@ cc.BuilderAnimationManager = cc.Class.extend({ return cc.Sequence.create(actions); }, + runAnimationsForSequenceNamed:function(name){ - this.runAnimations(name); + this.runAnimationsForSequenceIdTweenDuration(this._getSequenceId(name), 0); }, - runAnimations:function (name, tweenDuration) { + runAnimationsForSequenceNamedTweenDuration:function(name, tweenDuration){ + this.runAnimationsForSequenceIdTweenDuration(this._getSequenceId(name), tweenDuration); + }, + + runAnimationsForSequenceIdTweenDuration:function(nSeqId, tweenDuration){ tweenDuration = tweenDuration || 0; - var nSeqId; - if(typeof(name) === "string") - nSeqId = this._getSequenceId(name); - else - nSeqId = name; cc.Assert(nSeqId != -1, "Sequence id couldn't be found"); this._rootNode.stopAllActions(); var allKeys = this._nodeSequences.allKeys(); - for(var i = 0 ; i< allKeys.length;i++){ + for(var i = 0,len = allKeys.length ; i< len;i++){ var node = allKeys[i]; node.stopAllActions(); @@ -343,10 +357,11 @@ cc.BuilderAnimationManager = cc.Class.extend({ cc.CallFunc.create(this._sequenceCompleted,this)); this._rootNode.runAction(completeAction); - // Playback callbacks and sounds + // Playback callbacks and sounds + var action; if (seq.getCallbackChannel()) { // Build sound actions for channel - var action = this.getActionForCallbackChannel(seq.getCallbackChannel()); + action = this.getActionForCallbackChannel(seq.getCallbackChannel()); if (action) { this._rootNode.runAction(action); } @@ -354,15 +369,26 @@ cc.BuilderAnimationManager = cc.Class.extend({ if (seq.getSoundChannel()) { // Build sound actions for channel - var action = this.getActionForSoundChannel(seq.getSoundChannel()); + action = this.getActionForSoundChannel(seq.getSoundChannel()); if (action) { this._rootNode.runAction(action); } } - // Set the running scene + // Set the running scene this._runningSequence = this._getSequence(nSeqId); }, + runAnimations:function (name, tweenDuration) { + tweenDuration = tweenDuration || 0; + var nSeqId; + if(typeof(name) === "string") + nSeqId = this._getSequenceId(name); + else + nSeqId = name; + + this.runAnimationsForSequenceIdTweenDuration(nSeqId, tweenDuration); + }, + setAnimationCompletedCallback:function(target,callbackFunc){ this._target = target; this._animationCompleteCallbackFunc = callbackFunc; @@ -374,6 +400,7 @@ cc.BuilderAnimationManager = cc.Class.extend({ setCallFunc:function(callFunc, callbackNamed) { this._keyframeCallFuncs[callbackNamed] = callFunc; }, + debug:function () { }, @@ -386,9 +413,10 @@ cc.BuilderAnimationManager = cc.Class.extend({ _getSequenceId:function (sequenceName) { var element = null; - for (var i = 0; i < this._sequences.length; i++) { - element = this._sequences[i]; - if (element && element.getName() == sequenceName) + var locSequences = this._sequences; + for (var i = 0, len = locSequences.length; i < len; i++) { + element = locSequences[i]; + if (element && element.getName() === sequenceName) return element.getSequenceId(); } return -1; @@ -396,8 +424,9 @@ cc.BuilderAnimationManager = cc.Class.extend({ _getSequence:function (sequenceId) { var element = null; - for (var i = 0; i < this._sequences.length; i++) { - element = this._sequences[i]; + var locSequences = this._sequences; + for (var i = 0, len = locSequences.length; i < len; i++) { + element = locSequences[i]; if (element && element.getSequenceId() === sequenceId) return element; } @@ -439,7 +468,7 @@ cc.BuilderAnimationManager = cc.Class.extend({ var containerSize = this.getContainerSize(node.getParent()); - var absPos = cc.getAbsolutePosition(cc.p(x,y), type,containerSize,propName); + var absPos = cc._getAbsolutePosition(x,y, type,containerSize,propName); return cc.MoveTo.create(duration,absPos); } else if( propName === "scale"){ @@ -451,8 +480,13 @@ cc.BuilderAnimationManager = cc.Class.extend({ x = getValueArr[0]; y = getValueArr[1]; - if(type == CCB_SCALETYPE_MULTIPLY_RESOLUTION) - var resolutionScale = cc.BuilderReader.getResolutionScale(); + if(type === CCB_SCALETYPE_MULTIPLY_RESOLUTION){ + //TODO need to test + var resolutionScale = cc.BuilderReader.getResolutionScale(); + x *= resolutionScale; + y *= resolutionScale; + } + return cc.ScaleTo.create(duration,x,y); } else if( propName === "skew") { //get relative position @@ -486,7 +520,7 @@ cc.BuilderAnimationManager = cc.Class.extend({ x = value[0]; y = value[1]; - node.setPosition(cc.getAbsolutePosition(cc.p(x,y),nType, this.getContainerSize(node.getParent()),propName)); + node.setPosition(cc._getAbsolutePosition(x,y,nType, this.getContainerSize(node.getParent()),propName)); }else if(propName === "scale"){ getArr = this._getBaseValue(node,propName); nType = getArr[2]; @@ -496,8 +530,6 @@ cc.BuilderAnimationManager = cc.Class.extend({ cc.setRelativeScale(node,x,y,nType,propName); } else if( propName === "skew") { - getArr = this._getBaseValue(node,propName); - nType = getArr[2]; x = value[0]; y = value[1]; node.setSkewX(x); @@ -512,7 +544,10 @@ cc.BuilderAnimationManager = cc.Class.extend({ } else if(propName === "displayFrame"){ node.setDisplayFrame(value); } else if(propName === "color"){ - node.setColor(value.getColor()); + var ccColor3B = value.getColor(); + if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){ + node.setColor(ccColor3B); + } } else if( propName === "visible"){ value = value || false; node.setVisible(value); @@ -527,7 +562,7 @@ cc.BuilderAnimationManager = cc.Class.extend({ _setFirstFrame:function (node, seqProp, tweenDuration) { var keyframes = seqProp.getKeyframes(); - if (keyframes.length == 0) { + if (keyframes.length === 0) { // Use base value (no animation) var baseValue = this._getBaseValue(node, seqProp.getName()); cc.Assert(baseValue, "No baseValue found for property"); @@ -605,18 +640,19 @@ cc.BuilderAnimationManager = cc.Class.extend({ }, _sequenceCompleted:function () { - if(this._lastCompletedSequenceName != this._runningSequence.getName()){ - this._lastCompletedSequenceName = this._runningSequence.getName(); + var locRunningSequence = this._runningSequence; + if(this._lastCompletedSequenceName != locRunningSequence.getName()){ + this._lastCompletedSequenceName = locRunningSequence.getName(); } if (this._delegate) - this._delegate.completedAnimationSequenceNamed(this._runningSequence.getName()); + this._delegate.completedAnimationSequenceNamed(locRunningSequence.getName()); if(this._target && this._animationCompleteCallbackFunc){ this._animationCompleteCallbackFunc.call(this._target); } - var nextSeqId = this._runningSequence.getChainedSequenceId(); + var nextSeqId = locRunningSequence.getChainedSequenceId(); this._runningSequence = null; if (nextSeqId != -1) @@ -655,7 +691,7 @@ cc.BuilderRotateTo = cc.ActionInterval.extend({ _diffAngle:0, initWithDuration:function (duration, angle) { - if (this._super(duration)) { + if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._dstAngle = angle; return true; } else { @@ -667,7 +703,7 @@ cc.BuilderRotateTo = cc.ActionInterval.extend({ }, startWithTarget:function (node) { - this._super(node); + cc.ActionInterval.prototype.startWithTarget.call(this, node); this._startAngle = this._target.getRotation(); this._diffAngle = this._dstAngle - this._startAngle; } diff --git a/extensions/CCBReader/CCBReader.js b/extensions/CCBReader/CCBReader.js index 219a091310..c8c02c74b2 100644 --- a/extensions/CCBReader/CCBReader.js +++ b/extensions/CCBReader/CCBReader.js @@ -135,7 +135,7 @@ cc.BuilderReader = cc.Class.extend({ _loadedSpriteSheets:null, _owner:null, - _actionManager:null, + _animationManager:null, _animationManagers:null, _animatedProps:null, @@ -152,7 +152,7 @@ cc.BuilderReader = cc.Class.extend({ _ownerCallbackNames:null, _ownerCallbackNodes:null, - _hasScriptingOwner:false, + _readNodeGraphFromData:false, ctor:function (ccNodeLoaderLibrary, ccbMemberVariableAssigner, ccbSelectorResolver, ccNodeLoaderListener) { this._stringCache = []; @@ -196,7 +196,7 @@ cc.BuilderReader = cc.Class.extend({ initWithData:function (data, owner) { //setup action manager - this._actionManager = new cc.BuilderAnimationManager(); + this._animationManager = new cc.BuilderAnimationManager(); //setup byte array //Array replace to CCData in Javascript @@ -208,7 +208,7 @@ cc.BuilderReader = cc.Class.extend({ this._owner = owner; //setup resolution scale and container size - this._actionManager.setRootContainerSize(cc.Director.getInstance().getWinSize()); + this._animationManager.setRootContainerSize(cc.Director.getInstance().getWinSize()); return true; }, @@ -220,17 +220,18 @@ cc.BuilderReader = cc.Class.extend({ animationManager = parentSize; parentSize = cc.Director.getInstance().getWinSize(); } - - var path = cc.FileUtils.getInstance().fullPathFromRelativePath(ccbFileName); - var data = cc.FileUtils.getInstance().getByteArrayFromFile(path); + var fileUtils = cc.FileUtils.getInstance(); + var path = fileUtils.fullPathFromRelativePath(ccbFileName); + var data = fileUtils.getByteArrayFromFile(path); return this.readNodeGraphFromData(data, owner, parentSize, animationManager); }, - readNodeGraphFromData:function (data, owner, parentSize, animationManager) { + readNodeGraphFromData:function (data, owner, parentSize) { this.initWithData(data, owner); - this._actionManager.setRootContainerSize(parentSize); - this._actionManager.setOwner(owner); + var locAnimationManager = this._animationManager; + locAnimationManager.setRootContainerSize(parentSize); + locAnimationManager.setOwner(owner); this._ownerOutletNames = []; this._ownerOutletNodes = []; @@ -240,27 +241,25 @@ cc.BuilderReader = cc.Class.extend({ var nodeGraph = this.readFileWithCleanUp(true); - if (nodeGraph && this._actionManager.getAutoPlaySequenceId() != -1) { + if (nodeGraph && locAnimationManager.getAutoPlaySequenceId() != -1) { //auto play animations - this._actionManager.runAnimations(this._actionManager.getAutoPlaySequenceId(), 0); + locAnimationManager.runAnimations(locAnimationManager.getAutoPlaySequenceId(), 0); } if (this._jsControlled) { - this._nodesWithAnimationManagers = []; - this._animationManagerForNodes = []; + var locNodes = []; + var locAnimations = []; - var getAllKeys = this._animationManagers.allKeys(); + var locAnimationManagers = this._animationManagers; + var getAllKeys = locAnimationManagers.allKeys(); for (var i = 0; i < getAllKeys.length; i++) { - this._nodesWithAnimationManagers.push(getAllKeys[i]); - this._animationManagerForNodes.push(this._animationManagers.objectForKey(getAllKeys[i])); + locNodes.push(getAllKeys[i]); + locAnimations.push(locAnimationManagers.objectForKey(getAllKeys[i])); } - } - // Return action manager by reference - //if (ppAnimationManager) - //{ - // *ppAnimationManager = mActionManager; - //} + this._nodesWithAnimationManagers = locNodes; + this._animationManagerForNodes = locAnimations; + } return nodeGraph; }, @@ -281,11 +280,11 @@ cc.BuilderReader = cc.Class.extend({ }, getAnimationManager:function () { - return this._actionManager; + return this._animationManager; }, setAnimationManager:function (animationManager) { - this._actionManager = animationManager; + this._animationManager = animationManager; }, getAnimatedProperties:function () { @@ -479,11 +478,15 @@ cc.BuilderReader = cc.Class.extend({ }, addDocumentCallbackName:function (name) { - this._actionManager.addDocumentCallbackName(name); + this._animationManager.addDocumentCallbackName(name); }, addDocumentCallbackNode:function (node) { - this._actionManager.addDocumentCallbackNode(node); + this._animationManager.addDocumentCallbackNode(node); + }, + + addDocumentCallbackControlEvents:function(controlEvents){ + this._animationManager.addDocumentCallbackControlEvents(controlEvents); }, readFileWithCleanUp:function (cleanUp) { @@ -495,17 +498,28 @@ cc.BuilderReader = cc.Class.extend({ return null; var node = this._readNodeGraph(); - this._animationManagers.setObject(this._actionManager, node); + this._animationManagers.setObject(this._animationManager, node); if (cleanUp) this._cleanUpNodeGraph(node); return node; }, + addOwnerOutletName: function(name){ + this._ownerOutletNames.push(name); + }, + + addOwnerOutletNode: function(node){ + if(node == null) + return; + + this._ownerOutletNodes.push(node); + }, + _cleanUpNodeGraph:function (node) { node.setUserObject(null); var getChildren = node.getChildren(); - for (var i = 0; i < getChildren.length; i++) { + for (var i = 0, len = getChildren.length; i < len; i++) { this._cleanUpNodeGraph(getChildren[i]); } }, @@ -517,9 +531,8 @@ cc.BuilderReader = cc.Class.extend({ return true; var channel = new cc.BuilderSequenceProperty(); - - for (var i = 0; i < numKeyframes; i++) - { + var locJsControlled = this._jsControlled, locAnimationManager = this._animationManager, locKeyframes = channel.getKeyframes(); + for (var i = 0; i < numKeyframes; i++) { var time = this.readFloat(); var callbackName = this.readCachedString(); var callbackType = this.readInt(false); @@ -530,10 +543,10 @@ cc.BuilderReader = cc.Class.extend({ keyframe.setTime(time); keyframe.setValue(value); - if(this._jsControlled) { - this._actionManager.getKeyframeCallbacks().push(callbackType+":"+callbackName); - } - channel.getKeyframes().push(keyframe); + if(locJsControlled) + locAnimationManager.getKeyframeCallbacks().push(callbackType+":"+callbackName); + + locKeyframes.push(keyframe); } // Assign to sequence @@ -545,12 +558,12 @@ cc.BuilderReader = cc.Class.extend({ _readSoundKeyframesForSeq:function(seq) { var numKeyframes = this.readInt(false); - if (!numKeyframes) return true; + if (!numKeyframes) + return true; var channel = new cc.BuilderSequenceProperty(); - - for (var i = 0; i < numKeyframes; i++) - { + var locKeyframes = channel.getKeyframes(); + for (var i = 0; i < numKeyframes; i++) { var time = this.readFloat(); var soundFile = this.readCachedString(); var pitch = this.readFloat(); @@ -562,16 +575,15 @@ cc.BuilderReader = cc.Class.extend({ keyframe.setTime(time); keyframe.setValue(value); - channel.getKeyframes().push(keyframe); + locKeyframes.push(keyframe); } // Assign to sequence seq.setSoundChannel(channel); - return true; }, _readSequences:function () { - var sequences = this._actionManager.getSequences(); + var sequences = this._animationManager.getSequences(); var numSeqs = this.readInt(false); for (var i = 0; i < numSeqs; i++) { var seq = new cc.BuilderSequence(); @@ -587,7 +599,7 @@ cc.BuilderReader = cc.Class.extend({ sequences.push(seq); } - this._actionManager.setAutoPlaySequenceId(this.readInt(true)); + this._animationManager.setAutoPlaySequenceId(this.readInt(true)); return true; }, @@ -630,11 +642,8 @@ cc.BuilderReader = cc.Class.extend({ if (spriteSheet == "") { spriteFile = this._ccbRootPath + spriteFile; var texture = cc.TextureCache.getInstance().addImage(spriteFile); - var bounds; - if (cc.renderContextType == cc.CANVAS) - bounds = cc.RectMake(0, 0, texture.width, texture.height); - else - bounds = cc.RectMake(0, 0, texture.getContentSize().width, texture.getContentSize().height); + var locContentSize = texture.getContentSize(); + var bounds = cc.rect(0, 0, locContentSize.width, locContentSize.height); value = cc.SpriteFrame.createWithTexture(texture, bounds); } else { spriteSheet = this._ccbRootPath + spriteSheet; @@ -673,7 +682,7 @@ cc.BuilderReader = cc.Class.extend({ } this._jsControlled = this.readBool(); - this._actionManager._jsControlled = this._jsControlled; + this._animationManager._jsControlled = this._jsControlled; // no need to set if it is "jscontrolled". It is obvious. return true; }, @@ -681,24 +690,21 @@ cc.BuilderReader = cc.Class.extend({ _readStringFromBytes:function (startIndex, strLen, reverse) { reverse = reverse || false; var strValue = ""; - var i; + var i, locData = this._data, locCurrentByte = this._currentByte; if (reverse) { - for (i = strLen - 1; i >= 0; i--) { - strValue += String.fromCharCode(this._data[this._currentByte + i]); - } + for (i = strLen - 1; i >= 0; i--) + strValue += String.fromCharCode(locData[locCurrentByte + i]); } else { - for (i = 0; i < strLen; i++) { - strValue += String.fromCharCode(this._data[this._currentByte + i]); - } + for (i = 0; i < strLen; i++) + strValue += String.fromCharCode(locData[locCurrentByte + i]); } return strValue; }, _readStringCache:function () { var numStrings = this.readInt(false); - for (var i = 0; i < numStrings; i++) { + for (var i = 0; i < numStrings; i++) this._readStringCacheEntry(); - } return true; }, @@ -708,9 +714,9 @@ cc.BuilderReader = cc.Class.extend({ var numBytes = b0 << 8 | b1; - var str = ""; + var str = "", locData = this._data, locCurrentByte = this._currentByte; for (var i = 0; i < numBytes; i++) { - var hexChar = this._data[this._currentByte + i].toString("16").toUpperCase(); + var hexChar = locData[locCurrentByte + i].toString("16").toUpperCase(); hexChar = hexChar.length > 1 ? hexChar : "0" + hexChar; str += "%" + hexChar; } @@ -724,8 +730,8 @@ cc.BuilderReader = cc.Class.extend({ /* Read class name. */ var className = this.readCachedString(); - var jsControlledName; - if (this._jsControlled) + var jsControlledName, locJsControlled = this._jsControlled, locActionManager = this._animationManager; + if (locJsControlled) jsControlledName = this.readCachedString(); var memberVarAssignmentType = this.readInt(false); @@ -743,19 +749,18 @@ cc.BuilderReader = cc.Class.extend({ var node = ccNodeLoader.loadCCNode(parent, this); //set root node - if (!this._actionManager.getRootNode()) - this._actionManager.setRootNode(node); + if (!locActionManager.getRootNode()) + locActionManager.setRootNode(node); - if (this._jsControlled && node == this._actionManager.getRootNode()) { - this._actionManager.setDocumentControllerName(jsControlledName); + if (locJsControlled && node == locActionManager.getRootNode()) { + locActionManager.setDocumentControllerName(jsControlledName); } - //read animated properties var seqs = new cc._Dictionary(); this._animatedProps = []; - var i; + var i, locAnimatedProps = this._animatedProps; var numSequence = this.readInt(false); for (i = 0; i < numSequence; ++i) { var seqId = this.readInt(false); @@ -768,12 +773,12 @@ cc.BuilderReader = cc.Class.extend({ seqProp.setName(this.readCachedString()); seqProp.setType(this.readInt(false)); - this._animatedProps.push(seqProp.getName()); + locAnimatedProps.push(seqProp.getName()); var numKeyframes = this.readInt(false); - + var locKeyframes = seqProp.getKeyframes(); for (var k = 0; k < numKeyframes; ++k) { var keyFrame = this.readKeyframe(seqProp.getType()); - seqProp.getKeyframes().push(keyFrame); + locKeyframes.push(keyFrame); } seqNodeProps.setObject(seqProp, seqProp.getName()); } @@ -781,31 +786,33 @@ cc.BuilderReader = cc.Class.extend({ } if (seqs.count() > 0) - this._actionManager.addNode(node, seqs); + locActionManager.addNode(node, seqs); //read properties ccNodeLoader.parseProperties(node, parent, this); //handle sub ccb files(remove middle node) - if (node instanceof cc.BuilderFile) { + var isCCBFileNode = node instanceof cc.BuilderFile; + if (isCCBFileNode) { var embeddedNode = node.getCCBFileNode(); embeddedNode.setPosition(node.getPosition()); embeddedNode.setRotation(node.getRotation()); - embeddedNode.setScale(node.getScale()); + embeddedNode.setScaleX(node.getScaleX()); + embeddedNode.setScaleY(node.getScaleY()); embeddedNode.setTag(node.getTag()); embeddedNode.setVisible(true); - embeddedNode.ignoreAnchorPointForPosition(node.isIgnoreAnchorPointForPosition()); + //embeddedNode.ignoreAnchorPointForPosition(node.isIgnoreAnchorPointForPosition()); + locActionManager.moveAnimationsFromNode(node, embeddedNode); node.setCCBFileNode(null); node = embeddedNode; } - + var target = null, locMemberAssigner = null; if (memberVarAssignmentType != CCB_TARGETTYPE_NONE) { - if (!this._jsControlled) { - var target = null; - if (memberVarAssignmentType == CCB_TARGETTYPE_DOCUMENTROOT) { - target = this._actionManager.getRootNode(); - } else if (memberVarAssignmentType == CCB_TARGETTYPE_OWNER) { + if (!locJsControlled) { + if (memberVarAssignmentType === CCB_TARGETTYPE_DOCUMENTROOT) { + target = locActionManager.getRootNode(); + } else if (memberVarAssignmentType === CCB_TARGETTYPE_OWNER) { target = this._owner; } @@ -815,15 +822,15 @@ cc.BuilderReader = cc.Class.extend({ if (target != null && (target.onAssignCCBMemberVariable)) { assigned = target.onAssignCCBMemberVariable(target, memberVarAssignmentName, node); } - - if (!assigned && this._ccbMemberVariableAssigner != null && this._ccbMemberVariableAssigner.onAssignCCBMemberVariable) { - this._ccbMemberVariableAssigner.onAssignCCBMemberVariable(target, memberVarAssignmentName, node); + locMemberAssigner = this._ccbMemberVariableAssigner; + if (!assigned && locMemberAssigner != null && locMemberAssigner.onAssignCCBMemberVariable) { + locMemberAssigner.onAssignCCBMemberVariable(target, memberVarAssignmentName, node); } } } else { if (memberVarAssignmentType == CCB_TARGETTYPE_DOCUMENTROOT) { - this._actionManager.addDocumentOutletName(memberVarAssignmentName); - this._actionManager.addDocumentOutletNode(node); + locActionManager.addDocumentOutletName(memberVarAssignmentName); + locActionManager.addDocumentOutletNode(node); } else { this._ownerOutletNames.push(memberVarAssignmentName); this._ownerOutletNodes.push(node); @@ -834,18 +841,17 @@ cc.BuilderReader = cc.Class.extend({ // Assign custom properties. if (ccNodeLoader.getCustomProperties().length > 0) { var customAssigned = false; - - if(!this._jsControlled) { - var target = node; + if(!locJsControlled) { + target = node; if(target != null && target.onAssignCCBCustomProperty != null) { var customProperties = ccNodeLoader.getCustomProperties(); var customPropKeys = customProperties.allKeys(); for(i = 0;i < customPropKeys.length;i++){ var customPropValue = customProperties.objectForKey(customPropKeys[i]); customAssigned = target.onAssignCCBCustomProperty(target, customPropKeys[i], customPropValue); - - if(!customAssigned && (this._ccbMemberVariableAssigner != null) && (this._ccbMemberVariableAssigner.onAssignCCBCustomProperty != null)) - customAssigned = this._ccbMemberVariableAssigner.onAssignCCBCustomProperty(target, customPropKeys[i], customPropValue); + locMemberAssigner = this._ccbMemberVariableAssigner; + if(!customAssigned && (locMemberAssigner != null) && (locMemberAssigner.onAssignCCBCustomProperty != null)) + customAssigned = locMemberAssigner.onAssignCCBCustomProperty(target, customPropKeys[i], customPropValue); } } } @@ -860,11 +866,15 @@ cc.BuilderReader = cc.Class.extend({ node.addChild(child); } - // Call onNodeLoaded - if (node != null && node.onNodeLoaded) { - node.onNodeLoaded(node, ccNodeLoader); - } else if (this._ccNodeLoaderListener != null) { - this._ccNodeLoaderListener.onNodeLoaded(node, ccNodeLoader); + // FIX ISSUE #1860: "onNodeLoaded will be called twice if ccb was added as a CCBFile". + // If it's a sub-ccb node, skip notification to CCNodeLoaderListener since it will be + // notified at LINE #734: CCNode * child = this->readNodeGraph(node); + if (!isCCBFileNode) { + // Call onNodeLoaded + if (node != null && node.onNodeLoaded) + node.onNodeLoaded(node, ccNodeLoader); + else if (this._ccNodeLoaderListener != null) + this._ccNodeLoaderListener.onNodeLoaded(node, ccNodeLoader); } return node; @@ -922,7 +932,7 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) { var node = reader.readNodeGraphFromFile(ccbFilePath, owner, parentSize); var i; - var callbackName, callbackNode, outletName, outletNode; + var callbackName, callbackNode, callbackControlEvents, outletName, outletNode; // Assign owner callbacks & member variables if (owner) { // Callbacks @@ -931,7 +941,10 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) { for (i = 0; i < ownerCallbackNames.length; i++) { callbackName = ownerCallbackNames[i]; callbackNode = ownerCallbackNodes[i]; - callbackNode.setCallback(owner[callbackName], owner); + if(callbackNode instanceof cc.ControlButton) + callbackNode.addTargetWithActionForControlEvents(owner, owner[callbackName], 255); //register all type of events + else + callbackNode.setCallback(owner[callbackName], owner); } // Variables @@ -954,14 +967,21 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) { var animationManager = animationManagersForNodes[i]; var j; - innerNode.animationManager = animationManager; var documentControllerName = animationManager.getDocumentControllerName(); if (!documentControllerName) continue; // Create a document controller - var controller = new _ccbGlobalContext[documentControllerName](); + var controller; + if(documentControllerName.indexOf(".") > -1){ + var controllerNameArr = documentControllerName.split("."); + controller = _ccbGlobalContext[controllerNameArr[0]]; + for(var ni = 1, niLen = controllerNameArr.length - 1; ni < niLen; ni++) + controller = controller[controllerNameArr[ni]]; + controller = new controller[controllerNameArr[controllerNameArr.length - 1]](); + }else + controller = new _ccbGlobalContext[documentControllerName](); controller.controllerName = documentControllerName; innerNode.controller = controller; @@ -970,11 +990,15 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) { // Callbacks var documentCallbackNames = animationManager.getDocumentCallbackNames(); var documentCallbackNodes = animationManager.getDocumentCallbackNodes(); + var documentCallbackControlEvents = animationManager.getDocumentCallbackControlEvents(); for (j = 0; j < documentCallbackNames.length; j++) { callbackName = documentCallbackNames[j]; callbackNode = documentCallbackNodes[j]; - - callbackNode.setCallback(controller[callbackName], controller); + callbackControlEvents = documentCallbackControlEvents[j]; + if(callbackNode instanceof cc.ControlButton) + callbackNode.addTargetWithActionForControlEvents(controller, controller[callbackName], callbackControlEvents); //register all type of events + else + callbackNode.setCallback(controller[callbackName], controller); } // Variables @@ -987,9 +1011,8 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) { controller[outletName] = outletNode; } - if (controller.onDidLoadFromCCB && typeof(controller.onDidLoadFromCCB) == "function") { + if (controller.onDidLoadFromCCB && typeof(controller.onDidLoadFromCCB) == "function") controller.onDidLoadFromCCB(); - } // Setup timeline callbacks var keyframeCallbacks = animationManager.getKeyframeCallbacks(); diff --git a/extensions/CCBReader/CCBReaderUtil.js b/extensions/CCBReader/CCBReaderUtil.js index b8c63196d6..ec327c8533 100644 --- a/extensions/CCBReader/CCBReaderUtil.js +++ b/extensions/CCBReader/CCBReaderUtil.js @@ -45,9 +45,9 @@ cc.BuilderMemberVariableAssigner = cc.Class.extend({ * @param {Object} target The custom class * @param {string} memberVariableName The name of the member variable. * @param {cc.Node} node The member variable. - * @return Whether the assignment was successful. + * @return {Boolean} Whether the assignment was successful. */ - onAssignCCBMemberVariable:function(target,memberVariableName, node){}, + onAssignCCBMemberVariable:function(target,memberVariableName, node){ return false;}, /** * The callback function of assigning custom properties. @@ -55,7 +55,7 @@ cc.BuilderMemberVariableAssigner = cc.Class.extend({ * @param {Object} target The custom class. * @param {string} memberVariableName The name of the member variable. * @param {*} value The value of the property. - * @return Whether the assignment was successful. + * @return {Boolean} Whether the assignment was successful. */ - onAssignCCBCustomProperty:function(target, memberVariableName, value){} + onAssignCCBCustomProperty:function(target, memberVariableName, value){ return false; } }); diff --git a/extensions/CCBReader/CCBRelativePositioning.js b/extensions/CCBReader/CCBRelativePositioning.js index 67948ff407..c23351eadd 100644 --- a/extensions/CCBReader/CCBRelativePositioning.js +++ b/extensions/CCBReader/CCBRelativePositioning.js @@ -26,21 +26,21 @@ cc.getAbsolutePosition = function(pt, type, containerSize, propName){ var absPt = cc.p(0,0); - if(type == CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT) + if(type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT) absPt = pt; - else if(type == CCB_POSITIONTYPE_RELATIVE_TOP_LEFT){ + else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_LEFT){ absPt.x = pt.x; absPt.y = containerSize.height - pt.y; - } else if(type == CCB_POSITIONTYPE_RELATIVE_TOP_RIGHT){ + } else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_RIGHT){ absPt.x = containerSize.width - pt.x; absPt.y = containerSize.height - pt.y; - } else if (type == CCB_POSITIONTYPE_RELATIVE_BOTTOM_RIGHT) { + } else if (type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_RIGHT) { absPt.x = containerSize.width - pt.x; absPt.y = pt.y; - } else if (type == CCB_POSITIONTYPE_PERCENT) { + } else if (type === CCB_POSITIONTYPE_PERCENT) { absPt.x = (containerSize.width * pt.x / 100.0); absPt.y = (containerSize.height * pt.y / 100.0); - } else if (type == CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) { + } else if (type === CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) { var resolutionScale = cc.BuilderReader.getResolutionScale(); absPt.x = pt.x * resolutionScale; absPt.y = pt.y * resolutionScale; @@ -49,10 +49,35 @@ cc.getAbsolutePosition = function(pt, type, containerSize, propName){ return absPt; }; +cc._getAbsolutePosition = function(x, y, type, containerSize, propName){ + var absPt = cc.p(0,0); + if(type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT){ + absPt.x = x; + absPt.y = y; + } else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_LEFT){ + absPt.x = x; + absPt.y = containerSize.height - y; + } else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_RIGHT){ + absPt.x = containerSize.width - x; + absPt.y = containerSize.height - y; + } else if (type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_RIGHT) { + absPt.x = containerSize.width - x; + absPt.y = y; + } else if (type === CCB_POSITIONTYPE_PERCENT) { + absPt.x = (containerSize.width * x / 100.0); + absPt.y = (containerSize.height * y / 100.0); + } else if (type === CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) { + var resolutionScale = cc.BuilderReader.getResolutionScale(); + absPt.x = x * resolutionScale; + absPt.y = y * resolutionScale; + } + return absPt; +}; + cc.setRelativeScale = function(node,scaleX, scaleY, type, propName){ cc.Assert(node, "pNode should not be null"); - if (type == CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) { + if (type === CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) { var resolutionScale = cc.BuilderReader.getResolutionScale(); scaleX *= resolutionScale; diff --git a/extensions/CCBReader/CCBSequence.js b/extensions/CCBReader/CCBSequence.js index 4980801bf1..b991c48e4b 100644 --- a/extensions/CCBReader/CCBSequence.js +++ b/extensions/CCBReader/CCBSequence.js @@ -77,7 +77,6 @@ cc.BuilderSequence = cc.Class.extend({ setSoundChannel:function(channel) { this._soundChannel = channel; } - }); cc.BuilderSequenceProperty = cc.Class.extend({ diff --git a/extensions/CCBReader/CCControlLoader.js b/extensions/CCBReader/CCControlLoader.js index 4924cc5379..3b3cd8283d 100644 --- a/extensions/CCBReader/CCControlLoader.js +++ b/extensions/CCBReader/CCControlLoader.js @@ -34,7 +34,7 @@ cc.BuilderFileLoader = cc.NodeLoader.extend({ if (propertyName == PROPERTY_CCBFILE) { node.setCCBFileNode(ccbFileNode); } else { - this._super(node, parent, propertyName, ccbFileNode, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeCCBFile.call(this, node, parent, propertyName, ccbFileNode, ccbReader); } } }); @@ -54,7 +54,7 @@ cc.ControlLoader = cc.NodeLoader.extend({ if (propertyName == PROPERTY_CCCONTROL) { node.addTargetWithActionForControlEvents(blockCCControlData.target, blockCCControlData.selCCControlHandler, blockCCControlData.controlEvents); } else { - this._super(node, parent, propertyName, blockCCControlData, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeBlockCCControl.call(this, node, parent, propertyName, blockCCControlData, ccbReader); } }, onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) { @@ -63,7 +63,7 @@ cc.ControlLoader = cc.NodeLoader.extend({ } else if (propertyName == PROPERTY_SELECTED) { node.setSelected(check); } else { - this._super(node, parent, propertyName, check, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader); } } }); @@ -96,7 +96,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({ if (propertyName == PROPERTY_ZOOMONTOUCHDOWN) { node.setZoomOnTouchDown(check); } else { - this._super(node, parent, propertyName, check, ccbReader); + cc.ControlLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader); } }, onHandlePropTypeString:function (node, parent, propertyName, stringValue, ccbReader) { @@ -107,7 +107,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({ } else if (propertyName == PROPERTY_TITLE_DISABLED) { node.setTitleForState(stringValue, cc.CONTROL_STATE_DISABLED); } else { - this._super(node, parent, propertyName, stringValue, ccbReader); + cc.ControlLoader.prototype.onHandlePropTypeString.call(this, node, parent, propertyName, stringValue, ccbReader); } }, onHandlePropTypeFontTTF:function (node, parent, propertyName, fontTTF, ccbReader) { @@ -118,7 +118,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({ } else if (propertyName == PROPERTY_TITLETTF_DISABLED) { node.setTitleTTFForState(fontTTF, cc.CONTROL_STATE_DISABLED); } else { - this._super(node, parent, propertyName, fontTTF, ccbReader); + cc.ControlLoader.prototype.onHandlePropTypeFontTTF.call(this, node, parent, propertyName, fontTTF, ccbReader); } }, onHandlePropTypeFloatScale:function (node, parent, propertyName, floatScale, ccbReader) { @@ -129,21 +129,21 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({ } else if (propertyName == PROPERTY_TITLETTFSIZE_DISABLED) { node.setTitleTTFSizeForState(floatScale, cc.CONTROL_STATE_DISABLED); } else { - this._super(node, parent, propertyName, floatScale, ccbReader); + cc.ControlLoader.prototype.onHandlePropTypeFloatScale.call(this, node, parent, propertyName, floatScale, ccbReader); } }, onHandlePropTypePoint:function (node, parent, propertyName, point, ccbReader) { if (propertyName == PROPERTY_LABELANCHORPOINT) { node.setLabelAnchorPoint(point); } else { - this._super(node, parent, propertyName, point, ccbReader); + cc.ControlLoader.prototype.onHandlePropTypePoint.call(this, node, parent, propertyName, point, ccbReader); } }, onHandlePropTypeSize:function (node, parent, propertyName, size, ccbReader) { if (propertyName == PROPERTY_PREFEREDSIZE) { node.setPreferredSize(size); } else { - this._super(node, parent, propertyName, size, ccbReader); + cc.ControlLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size, ccbReader); } }, onHandlePropTypeSpriteFrame:function (node, parent, propertyName, spriteFrame, ccbReader) { @@ -160,7 +160,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({ node.setBackgroundSpriteFrameForState(spriteFrame, cc.CONTROL_STATE_DISABLED); } } else { - this._super(node, parent, propertyName, spriteFrame, ccbReader); + cc.ControlLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, spriteFrame, ccbReader); } }, onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) { @@ -171,7 +171,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({ } else if (propertyName == PROPERTY_TITLECOLOR_DISABLED) { node.setTitleColorForState(ccColor3B, cc.CONTROL_STATE_DISABLED); } else { - this._super(node, parent, propertyName, ccColor3B, ccbReader); + cc.ControlLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader); } } }); @@ -195,7 +195,7 @@ cc.ScrollViewLoader = cc.NodeLoader.extend({ if(propertyName == PROPERTY_CONTENTSIZE){ node.setViewSize(size); }else{ - this._super(node,parent,propertyName.size,ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node,parent,propertyName.size,ccbReader); } }, @@ -204,7 +204,7 @@ cc.ScrollViewLoader = cc.NodeLoader.extend({ node.setContainer(ccbFileNode); node.updateInset(); } else { - this._super(node, parent, propertyName, ccbFileNode, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeCCBFile.call(this, node, parent, propertyName, ccbFileNode, ccbReader); } }, onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) { @@ -213,21 +213,21 @@ cc.ScrollViewLoader = cc.NodeLoader.extend({ } else if (propertyName == PROPERTY_BOUNCES) { node.setBounceable(check); } else { - this._super(node, parent, propertyName, check, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader); } }, onHandlePropTypeFloat:function (node, parent, propertyName, floatValue, ccbReader) { if (propertyName == PROPERTY_SCALE) { node.setScale(floatValue); } else { - this._super(node, parent, propertyName, floatValue, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue, ccbReader); } }, onHandlePropTypeIntegerLabeled:function (node, parent, propertyName, integerLabeled, ccbReader) { if (propertyName == PROPERTY_DIRECTION) { node.setDirection(integerLabeled); } else { - this._super(node, parent, propertyName, integerLabeled, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeIntegerLabeled.call(this, node, parent, propertyName, integerLabeled, ccbReader); } } }); @@ -253,16 +253,18 @@ cc.Scale9SpriteLoader = cc.NodeLoader.extend({ onHandlePropTypeColor3:function(node, parent, propertyName, ccColor3B,ccbReader){ if(propertyName == PROPERTY_COLOR) { - node.setColor(ccColor3B); + if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){ + node.setColor(ccColor3B); + } } else { - this._super(node, parent, propertyName, ccColor3B,ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B,ccbReader); } }, onHandlePropTypeByte:function(node, parent, propertyName, byteValue,ccbReader){ if(propertyName == PROPERTY_OPACITY) { node.setOpacity(byteValue); } else { - this._super(node, parent, propertyName, byteValue,ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue,ccbReader); } }, onHandlePropTypeBlendFunc:function(node, parent, propertyName, ccBlendFunc,ccbReader){ @@ -270,14 +272,14 @@ cc.Scale9SpriteLoader = cc.NodeLoader.extend({ // TODO Not exported by CocosBuilder yet! // node.setBlendFunc(ccBlendFunc); } else { - this._super(node, parent, propertyName, ccBlendFunc,ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc,ccbReader); } }, onHandlePropTypeSpriteFrame:function(node, parent, propertyName, spriteFrame,ccbReader){ if(propertyName == PROPERTY_SPRITEFRAME) { node.initWithSpriteFrame(spriteFrame); } else { - this._super(node, parent, propertyName, spriteFrame,ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, spriteFrame,ccbReader); } }, onHandlePropTypeSize:function(node, parent, propertyName, size,ccbReader){ @@ -286,7 +288,7 @@ cc.Scale9SpriteLoader = cc.NodeLoader.extend({ } else if(propertyName == PROPERTY_PREFEREDSIZE) { node.setPreferredSize(size); } else { - this._super(node, parent, propertyName, size,ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size,ccbReader); } }, onHandlePropTypeFloat:function(node, parent, propertyName, floatValue,ccbReader){ @@ -299,7 +301,7 @@ cc.Scale9SpriteLoader = cc.NodeLoader.extend({ } else if(propertyName == PROPERTY_INSETBOTTOM) { node.setInsetBottom(floatValue); } else { - this._super(node, parent, propertyName, floatValue,ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue,ccbReader); } } }); diff --git a/extensions/CCBReader/CCNodeLoader.js b/extensions/CCBReader/CCNodeLoader.js index 4f42cc1127..2bdbb32ddc 100644 --- a/extensions/CCBReader/CCNodeLoader.js +++ b/extensions/CCBReader/CCNodeLoader.js @@ -82,7 +82,7 @@ cc.NodeLoader = cc.Class.extend({ var setProp = false; var platform = ccbReader.readByte(); - if ((platform == CCB_PLATFORM_ALL) ||(platform == CCB_PLATFORM_IOS) ||(platform == CCB_PLATFORM_MAC) ) + if ((platform === CCB_PLATFORM_ALL) ||(platform === CCB_PLATFORM_IOS) ||(platform === CCB_PLATFORM_MAC) ) setProp = true; //forward properties for sub ccb files @@ -106,49 +106,43 @@ cc.NodeLoader = cc.Class.extend({ case CCB_PROPTYPE_POSITION: { var position = this.parsePropTypePosition(node, parent, ccbReader, propertyName); - if (setProp) { + if (setProp) this.onHandlePropTypePosition(node, parent, propertyName, position, ccbReader); - } break; } case CCB_PROPTYPE_POINT: { var point = this.parsePropTypePoint(node, parent, ccbReader); - if (setProp) { + if (setProp) this.onHandlePropTypePoint(node, parent, propertyName, point, ccbReader); - } break; } case CCB_PROPTYPE_POINTLOCK: { var pointLock = this.parsePropTypePointLock(node, parent, ccbReader); - if (setProp) { + if (setProp) this.onHandlePropTypePointLock(node, parent, propertyName, pointLock, ccbReader); - } break; } case CCB_PROPTYPE_SIZE: { var size = this.parsePropTypeSize(node, parent, ccbReader); - if (setProp) { + if (setProp) this.onHandlePropTypeSize(node, parent, propertyName, size, ccbReader); - } break; } case CCB_PROPTYPE_SCALELOCK: { var scaleLock = this.parsePropTypeScaleLock(node, parent, ccbReader, propertyName); - if (setProp) { + if (setProp) this.onHandlePropTypeScaleLock(node, parent, propertyName, scaleLock, ccbReader); - } break; } case CCB_PROPTYPE_FLOATXY: { var xy = this.parsePropTypeFloatXY(node, parent, ccbReader); - if (setProp) { + if (setProp) this.onHandlePropTypeFloatXY(node, parent, propertyName, xy, ccbReader); - } break; } @@ -350,7 +344,7 @@ cc.NodeLoader = cc.Class.extend({ var type = ccbReader.readInt(false); var containerSize = ccbReader.getAnimationManager().getContainerSize(parent); - var pt = cc.getAbsolutePosition(cc.p(x,y),type,containerSize,propertyName); + var pt = cc._getAbsolutePosition(x,y,type,containerSize,propertyName); node.setPosition(cc.getAbsolutePosition(pt,type,containerSize,propertyName)); //different to -x node.setPosition(pt); if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){ @@ -489,12 +483,9 @@ cc.NodeLoader = cc.Class.extend({ if(spriteSheet.length == 0){ spriteFile = ccbReader.getCCBRootPath() + spriteFile; var texture = cc.TextureCache.getInstance().addImage(spriteFile); - var bounds; - if(texture instanceof cc.Texture2D){ - bounds = cc.RectMake(0, 0, texture.getContentSize().width, texture.getContentSize().height); - }else{ - bounds = cc.RECT_PIXELS_TO_POINTS(bounds); - } + + var locContentSize = texture.getContentSize(); + var bounds = cc.rect(0, 0, locContentSize.width, locContentSize.height); spriteFrame = cc.SpriteFrame.createWithTexture(texture, bounds); } else { var frameCache = cc.SpriteFrameCache.getInstance(); @@ -623,12 +614,12 @@ cc.NodeLoader = cc.Class.extend({ var selectorName = ccbReader.readCachedString(); var selectorTarget = ccbReader.readInt(false); - if (selectorTarget != CCB_TARGETTYPE_NONE) { + if (selectorTarget !== CCB_TARGETTYPE_NONE) { var target = null; if(!ccbReader.isJSControlled()) { - if (selectorTarget == CCB_TARGETTYPE_DOCUMENTROOT) { + if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) { target = ccbReader.getAnimationManager().getRootNode(); - } else if (selectorTarget == CCB_TARGETTYPE_OWNER) { + } else if (selectorTarget === CCB_TARGETTYPE_OWNER) { target = ccbReader.getOwner(); } @@ -637,14 +628,13 @@ cc.NodeLoader = cc.Class.extend({ var selMenuHandler = 0; //var targetAsCCBSelectorResolver = target; - if (target != null && target.onResolveCCBCCMenuItemSelector) { + if (target != null && target.onResolveCCBCCMenuItemSelector) selMenuHandler = target.onResolveCCBCCMenuItemSelector(target, selectorName); - } + if (selMenuHandler == 0) { var ccbSelectorResolver = ccbReader.getCCBSelectorResolver(); - if (ccbSelectorResolver != null) { + if (ccbSelectorResolver != null) selMenuHandler = ccbSelectorResolver.onResolveCCBCCMenuItemSelector(target, selectorName); - } } if (selMenuHandler == 0) { @@ -659,9 +649,10 @@ cc.NodeLoader = cc.Class.extend({ cc.log("Unexpected NULL target for selector."); } } else { - if(selectorTarget == CCB_TARGETTYPE_DOCUMENTROOT){ + if(selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT){ ccbReader.addDocumentCallbackNode(node); ccbReader.addDocumentCallbackName(selectorName); + ccbReader.addDocumentCallbackControlEvents(0); } else { ccbReader.addOwnerCallbackNode(node); ccbReader.addOwnerCallbackName(selectorName); @@ -676,7 +667,7 @@ cc.NodeLoader = cc.Class.extend({ var selectorTarget = ccbReader.readInt(false); var controlEvents = ccbReader.readInt(false); - if (selectorTarget != CCB_TARGETTYPE_NONE) { + if (selectorTarget !== CCB_TARGETTYPE_NONE) { if(!ccbReader.isJSControlled()){ var target = null; if (selectorTarget == CCB_TARGETTYPE_DOCUMENTROOT) { @@ -714,6 +705,7 @@ cc.NodeLoader = cc.Class.extend({ if(selectorTarget == CCB_TARGETTYPE_DOCUMENTROOT){ ccbReader.addDocumentCallbackNode(node); ccbReader.addDocumentCallbackName(selectorName); + ccbReader.addDocumentCallbackControlEvents(controlEvents); } else { ccbReader.addOwnerCallbackNode(node); ccbReader.addOwnerCallbackName(selectorName); @@ -731,11 +723,12 @@ cc.NodeLoader = cc.Class.extend({ ccbFileName = ccbFileWithoutPathExtension + ".ccbi"; //load sub file - var path = cc.FileUtils.getInstance().fullPathFromRelativePath(ccbFileName); + var fileUtils = cc.FileUtils.getInstance(); + var path = fileUtils.fullPathFromRelativePath(ccbFileName); var myCCBReader = new cc.BuilderReader(ccbReader); var size ; - var bytes = cc.FileUtils.getInstance().getByteArrayFromFile(path,"rb", size); + var bytes = fileUtils.getByteArrayFromFile(path,"rb", size); myCCBReader.initWithData(bytes,ccbReader.getOwner()); myCCBReader.getAnimationManager().setRootContainerSize(parent.getContentSize()); @@ -845,7 +838,7 @@ cc.NodeLoader = cc.Class.extend({ onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) { if (propertyName === PROPERTY_VISIBLE) { node.setVisible(check); - } else if (propertyName == PROPERTY_IGNOREANCHORPOINTFORPOSITION) { + } else if (propertyName === PROPERTY_IGNOREANCHORPOINTFORPOSITION) { node.ignoreAnchorPointForPosition(check); } else { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); diff --git a/extensions/CCBReader/CCNodeLoaderLibrary.js b/extensions/CCBReader/CCNodeLoaderLibrary.js index 001437bf49..cff3b6996b 100644 --- a/extensions/CCBReader/CCNodeLoaderLibrary.js +++ b/extensions/CCBReader/CCNodeLoaderLibrary.js @@ -45,7 +45,7 @@ cc.NodeLoaderLibrary = cc.Class.extend({ this.registerCCNodeLoader("CCMenu", cc.MenuLoader.loader()); this.registerCCNodeLoader("CCMenuItemImage", cc.MenuItemImageLoader.loader()); this.registerCCNodeLoader("CCControlButton", cc.ControlButtonLoader.loader()); - this.registerCCNodeLoader("CCParticleSystemQuad", cc.ParticleSystemQuadLoader.loader()); + this.registerCCNodeLoader("CCParticleSystemQuad", cc.ParticleSystemLoader.loader()); }, registerCCNodeLoader:function(className,ccNodeLoader){ diff --git a/extensions/CCBReader/CCSpriteLoader.js b/extensions/CCBReader/CCSpriteLoader.js index 9674be90d0..cdf95d96c0 100644 --- a/extensions/CCBReader/CCSpriteLoader.js +++ b/extensions/CCBReader/CCSpriteLoader.js @@ -35,40 +35,45 @@ cc.SpriteLoader = cc.NodeLoader.extend({ return cc.Sprite.create(); }, - onHandlePropTypeColor3:function (node, parent, propertyName, color3BValue, ccbReader) { - if (propertyName == PROPERTY_COLOR) { - node.setColor(color3BValue); + onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) { + if (propertyName === PROPERTY_COLOR) { + if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){ + node.setColor(ccColor3B); + } } else { - this._super(node, parent, propertyName, color3BValue, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader); } }, onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) { - if (propertyName == PROPERTY_OPACITY) { + if (propertyName === PROPERTY_OPACITY) { node.setOpacity(byteValue); } else { - this._super(node, parent, propertyName, byteValue, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader); } }, onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccbBlendFunc, ccbReader) { - if (propertyName == PROPERTY_BLENDFUNC) { + if (propertyName === PROPERTY_BLENDFUNC) { node.setBlendFunc(ccbBlendFunc); } else { - this._super(node, parent, propertyName, ccbBlendFunc, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccbBlendFunc, ccbReader); } }, onHandlePropTypeSpriteFrame:function (node, parent, propertyName, ccSpriteFrame, ccbReader) { - if (propertyName == PROPERTY_DISPLAYFRAME) { - node.setDisplayFrame(ccSpriteFrame); + if (propertyName === PROPERTY_DISPLAYFRAME) { + if(ccSpriteFrame) + node.setDisplayFrame(ccSpriteFrame); + else + cc.log("ERROR: SpriteFrame is null"); } else { - this._super(node, parent, propertyName, ccSpriteFrame, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, ccSpriteFrame, ccbReader); } }, onHandlePropTypeFlip:function (node, parent, propertyName, flip, ccbReader) { - if (propertyName == PROPERTY_FLIP) { - node.setFlipX(flip[0]); - node.setFlipY(flip[1]); + if (propertyName === PROPERTY_FLIP) { + node.setFlippedX(flip[0]); + node.setFlippedY(flip[1]); } else { - this._super(node, parent, propertyName, flip, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeFlip.call(this, node, parent, propertyName, flip, ccbReader); } } }); @@ -91,22 +96,22 @@ cc.LayerLoader = cc.NodeLoader.extend({ return cc.Layer.create(); }, onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) { - if (propertyName == PROPERTY_TOUCH_ENABLED || propertyName == PROPERTY_IS_TOUCH_ENABLED) { + if (propertyName === PROPERTY_TOUCH_ENABLED || propertyName === PROPERTY_IS_TOUCH_ENABLED) { node.setTouchEnabled(check); - } else if (propertyName == PROPERTY_ACCELEROMETER_ENABLED || propertyName == PROPERTY_IS_ACCELEROMETER_ENABLED) { + } else if (propertyName === PROPERTY_ACCELEROMETER_ENABLED || propertyName === PROPERTY_IS_ACCELEROMETER_ENABLED) { node.setAccelerometerEnabled(check); - } else if (propertyName == PROPERTY_MOUSE_ENABLED || propertyName == PROPERTY_IS_MOUSE_ENABLED ) { + } else if (propertyName === PROPERTY_MOUSE_ENABLED || propertyName === PROPERTY_IS_MOUSE_ENABLED ) { node.setMouseEnabled(check); - } else if (propertyName == PROPERTY_KEYBOARD_ENABLED || propertyName == PROPERTY_IS_KEYBOARD_ENABLED) { + } else if (propertyName === PROPERTY_KEYBOARD_ENABLED || propertyName === PROPERTY_IS_KEYBOARD_ENABLED) { // TODO XXX - if(node.setKeyboardEnabled && sys.platform == "browser") { + if(node.setKeyboardEnabled && sys.platform === "browser") { node.setKeyboardEnabled(check); } else { cc.log("The property '" + PROPERTY_IS_KEYBOARD_ENABLED + "' is not supported!"); // This comes closest: ((CCLayer *)pNode).setKeypadEnabled(pCheck); } } else { - this._super(node, parent, propertyName, check, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader); } } }); @@ -122,24 +127,24 @@ cc.LayerColorLoader = cc.LayerLoader.extend({ }, onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) { - if (propertyName == PROPERTY_COLOR) { + if (propertyName === PROPERTY_COLOR) { node.setColor(ccColor3B); } else { - this._super(node, parent, propertyName, ccColor3B, ccbReader); + cc.LayerLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader); } }, onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) { - if (propertyName == PROPERTY_OPACITY) { + if (propertyName === PROPERTY_OPACITY) { node.setOpacity(byteValue); } else { - this._super(node, parent, propertyName, byteValue, ccbReader); + cc.LayerLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader); } }, onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) { - if (propertyName == PROPERTY_BLENDFUNC) { + if (propertyName === PROPERTY_BLENDFUNC) { node.setBlendFunc(ccBlendFunc); } else { - this._super(node, parent, propertyName, ccBlendFunc, ccbReader); + cc.LayerLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader); } } }); @@ -159,37 +164,37 @@ cc.LayerGradientLoader = cc.LayerLoader.extend({ return cc.LayerGradient.create(); }, onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) { - if (propertyName == PROPERTY_STARTCOLOR) { + if (propertyName === PROPERTY_STARTCOLOR) { node.setStartColor(ccColor3B); } else if (propertyName == PROPERTY_ENDCOLOR) { node.setEndColor(ccColor3B); } else { - this._super(node, parent, propertyName, ccColor3B, ccbReader); + cc.LayerLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader); } }, onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) { - if (propertyName == PROPERTY_STARTOPACITY) { + if (propertyName === PROPERTY_STARTOPACITY) { node.setStartOpacity(byteValue); - } else if (propertyName == PROPERTY_ENDOPACITY) { + } else if (propertyName === PROPERTY_ENDOPACITY) { node.setEndOpacity(byteValue); } else { - this._super(node, parent, propertyName, byteValue, ccbReader); + cc.LayerLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader); } }, onHandlePropTypePoint:function (node, parent, propertyName, point, ccbReader) { - if (propertyName == PROPERTY_VECTOR) { + if (propertyName === PROPERTY_VECTOR) { node.setVector(point); // TODO Not passed along the ccbi file. // node.setCompressedInterpolation(true); } else { - this._super(node, parent, propertyName, point, ccbReader); + cc.LayerLoader.prototype.onHandlePropTypePoint.call(this, node, parent, propertyName, point, ccbReader); } }, onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) { - if (propertyName == PROPERTY_BLENDFUNC) { + if (propertyName === PROPERTY_BLENDFUNC) { node.setBlendFunc(ccBlendFunc); } else { - this._super(node, parent, propertyName, ccBlendFunc, ccbReader); + cc.LayerLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader); } } }); @@ -217,19 +222,19 @@ cc.MenuItemLoader = cc.NodeLoader.extend({ }, onHandlePropTypeBlock:function (node, parent, propertyName, blockData, ccbReader) { - if (propertyName == PROPERTY_BLOCK) { + if (propertyName === PROPERTY_BLOCK) { if (null != blockData) { // Add this condition to allow CCMenuItemImage without target/selector predefined node.setTarget(blockData.selMenuHander, blockData.target); } } else { - this._super(node, parent, propertyName, blockData, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeBlock.call(this, node, parent, propertyName, blockData, ccbReader); } }, onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) { - if (propertyName == PROPERTY_ISENABLED) { + if (propertyName === PROPERTY_ISENABLED) { node.setEnabled(check); } else { - this._super(node, parent, propertyName, check, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader); } } }); @@ -244,20 +249,20 @@ cc.MenuItemImageLoader = cc.MenuItemLoader.extend({ }, onHandlePropTypeSpriteFrame:function (node, parent, propertyName, spriteFrame, ccbReader) { - if (propertyName == PROPERTY_NORMALDISPLAYFRAME) { + if (propertyName === PROPERTY_NORMALDISPLAYFRAME) { if (spriteFrame != null) { node.setNormalSpriteFrame(spriteFrame); } - } else if (propertyName == PROPERTY_SELECTEDDISPLAYFRAME) { + } else if (propertyName === PROPERTY_SELECTEDDISPLAYFRAME) { if (spriteFrame != null) { node.setSelectedSpriteFrame(spriteFrame); } - } else if (propertyName == PROPERTY_DISABLEDDISPLAYFRAME) { + } else if (propertyName === PROPERTY_DISABLEDDISPLAYFRAME) { if (spriteFrame != null) { node.setDisabledSpriteFrame(spriteFrame); } } else { - this._super(node, parent, propertyName, spriteFrame, ccbReader); + cc.MenuItemLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, spriteFrame, ccbReader); } } }); @@ -278,61 +283,63 @@ cc.LabelTTFLoader = cc.NodeLoader.extend({ return cc.LabelTTF.create(); }, onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) { - if (propertyName == PROPERTY_COLOR) { - node.setColor(ccColor3B); + if (propertyName === PROPERTY_COLOR) { + if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){ + node.setColor(ccColor3B); + } } else { - this._super(node, parent, propertyName, ccColor3B, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader); } }, onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) { - if (propertyName == PROPERTY_OPACITY) { + if (propertyName === PROPERTY_OPACITY) { node.setOpacity(byteValue); } else { - this._super(node, parent, propertyName, byteValue, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader); } }, onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) { - if (propertyName == PROPERTY_BLENDFUNC) { + if (propertyName === PROPERTY_BLENDFUNC) { node.setBlendFunc(ccBlendFunc); } else { - this._super(pNode, pParent, propertyName, ccBlendFunc, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader); } }, onHandlePropTypeFontTTF:function (node, parent, propertyName, fontTTF, ccbReader) { - if (propertyName == PROPERTY_FONTNAME) { + if (propertyName === PROPERTY_FONTNAME) { node.setFontName(fontTTF); } else { - this._super(node, parent, propertyName, fontTTF, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeFontTTF.call(this, node, parent, propertyName, fontTTF, ccbReader); } }, onHandlePropTypeText:function (node, parent, propertyName, textValue, ccbReader) { - if (propertyName == PROPERTY_STRING) { + if (propertyName === PROPERTY_STRING) { node.setString(textValue); } else { - this._super(node, parent, propertyName, textValue, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeText.call(this, node, parent, propertyName, textValue, ccbReader); } }, onHandlePropTypeFloatScale:function (node, parent, propertyName, floatScale, ccbReader) { - if (propertyName == PROPERTY_FONTSIZE) { + if (propertyName === PROPERTY_FONTSIZE) { node.setFontSize(floatScale); } else { - this._super(node, parent, propertyName, floatScale, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeFloatScale.call(this, node, parent, propertyName, floatScale, ccbReader); } }, onHandlePropTypeIntegerLabeled:function (node, parent, propertyName, integerLabeled, ccbReader) { - if (propertyName == PROPERTY_HORIZONTALALIGNMENT) { + if (propertyName === PROPERTY_HORIZONTALALIGNMENT) { node.setHorizontalAlignment(integerLabeled); - } else if (propertyName == PROPERTY_VERTICALALIGNMENT) { + } else if (propertyName === PROPERTY_VERTICALALIGNMENT) { node.setVerticalAlignment(integerLabeled); } else { - this._super(node, parent, propertyName, integerLabeled, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeIntegerLabeled.call(this, node, parent, propertyName, integerLabeled, ccbReader); } }, onHandlePropTypeSize:function (node, parent, propertyName, size, ccbReader) { - if (propertyName == PROPERTY_DIMENSIONS) { + if (propertyName === PROPERTY_DIMENSIONS) { node.setDimensions(size); } else { - this._super(node, parent, propertyName, size, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size, ccbReader); } } }); @@ -349,38 +356,40 @@ cc.LabelBMFontLoader = cc.NodeLoader.extend({ }, onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) { - if (propertyName == PROPERTY_COLOR) { - node.setColor(ccColor3B); + if (propertyName === PROPERTY_COLOR) { + if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){ + node.setColor(ccColor3B); + } } else { - this._super(node, parent, propertyName, ccColor3B, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader); } }, onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) { - if (propertyName == PROPERTY_OPACITY) { + if (propertyName === PROPERTY_OPACITY) { node.setOpacity(byteValue); } else { - this._super(node, parent, propertyName, byteValue, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader); } }, onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) { - if (propertyName == PROPERTY_BLENDFUNC) { + if (propertyName === PROPERTY_BLENDFUNC) { node.setBlendFunc(ccBlendFunc); } else { - this._super(node, parent, propertyName, ccBlendFunc, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader); } }, onHandlePropTypeFntFile:function (node, parent, propertyName, fntFile, ccbReader) { - if (propertyName == PROPERTY_FNTFILE) { + if (propertyName === PROPERTY_FNTFILE) { node.setFntFile(fntFile); } else { - this._super(node, parent, propertyName, fntFile, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeFntFile.call(this, node, parent, propertyName, fntFile, ccbReader); } }, onHandlePropTypeText:function (node, parent, propertyName, textValue, ccbReader) { - if (propertyName == PROPERTY_STRING) { + if (propertyName === PROPERTY_STRING) { node.setString(textValue); } else { - this._super(node, parent, propertyName, textValue, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeText.call(this, node, parent, propertyName, textValue, ccbReader); } } }); @@ -409,113 +418,113 @@ var PROPERTY_STARTRADIUS = "startRadius"; var PROPERTY_ENDRADIUS = "endRadius"; var PROPERTY_ROTATEPERSECOND = "rotatePerSecond"; -cc.ParticleSystemQuadLoader = cc.NodeLoader.extend({ +cc.ParticleSystemLoader = cc.NodeLoader.extend({ _createCCNode:function (parent, ccbReader) { - return cc.ParticleSystemQuad.create(); + return cc.ParticleSystem.create(); }, onHandlePropTypeIntegerLabeled:function (node, parent, propertyName, integerLabeled, ccbReader) { - if (propertyName == PROPERTY_EMITERMODE) { + if (propertyName === PROPERTY_EMITERMODE) { node.setEmitterMode(integerLabeled); } else { - this._super(node, parent, propertyName, integerLabeled, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeIntegerLabeled.call(this, node, parent, propertyName, integerLabeled, ccbReader); } }, onHandlePropTypePoint:function (node, parent, propertyName, point, ccbReader) { - if (propertyName == PROPERTY_POSVAR) { + if (propertyName === PROPERTY_POSVAR) { node.setPosVar(point); - } else if (propertyName == PROPERTY_GRAVITY) { + } else if (propertyName === PROPERTY_GRAVITY) { node.setGravity(point); } else { - this._super(node, parent, propertyName, point, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypePoint.call(this, node, parent, propertyName, point, ccbReader); } }, onHandlePropTypeFloat:function (node, parent, propertyName, floatValue, ccbReader) { - if (propertyName == PROPERTY_EMISSIONRATE) { + if (propertyName === PROPERTY_EMISSIONRATE) { node.setEmissionRate(floatValue); - } else if (propertyName == PROPERTY_DURATION) { + } else if (propertyName === PROPERTY_DURATION) { node.setDuration(floatValue); } else { - this._super(node, parent, propertyName, floatValue, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue, ccbReader); } }, onHandlePropTypeInteger:function (node, parent, propertyName, integerValue, ccbReader) { - if (propertyName == PROPERTY_TOTALPARTICLES) { + if (propertyName === PROPERTY_TOTALPARTICLES) { node.setTotalParticles(integerValue); } else { - this._super(node, parent, propertyName, integerValue, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeInteger.call(this, node, parent, propertyName, integerValue, ccbReader); } }, onHandlePropTypeFloatVar:function (node, parent, propertyName, floatVar, ccbReader) { - if (propertyName == PROPERTY_LIFE) { + if (propertyName === PROPERTY_LIFE) { node.setLife(floatVar[0]); node.setLifeVar(floatVar[1]); - } else if (propertyName == PROPERTY_STARTSIZE) { + } else if (propertyName === PROPERTY_STARTSIZE) { node.setStartSize(floatVar[0]); node.setStartSizeVar(floatVar[1]); - } else if (propertyName == PROPERTY_ENDSIZE) { + } else if (propertyName === PROPERTY_ENDSIZE) { node.setEndSize(floatVar[0]); node.setEndSizeVar(floatVar[1]); - } else if (propertyName == PROPERTY_STARTSPIN) { + } else if (propertyName === PROPERTY_STARTSPIN) { node.setStartSpin(floatVar[0]); node.setStartSpinVar(floatVar[1]); - } else if (propertyName == PROPERTY_ENDSPIN) { + } else if (propertyName === PROPERTY_ENDSPIN) { node.setEndSpin(floatVar[0]); node.setEndSpinVar(floatVar[1]); - } else if (propertyName == PROPERTY_ANGLE) { + } else if (propertyName === PROPERTY_ANGLE) { node.setAngle(floatVar[0]); node.setAngleVar(floatVar[1]); - } else if (propertyName == PROPERTY_SPEED) { + } else if (propertyName === PROPERTY_SPEED) { node.setSpeed(floatVar[0]); node.setSpeedVar(floatVar[1]); - } else if (propertyName == PROPERTY_TANGENTIALACCEL) { + } else if (propertyName === PROPERTY_TANGENTIALACCEL) { node.setTangentialAccel(floatVar[0]); node.setTangentialAccelVar(floatVar[1]); - } else if (propertyName == PROPERTY_RADIALACCEL) { + } else if (propertyName === PROPERTY_RADIALACCEL) { node.setRadialAccel(floatVar[0]); node.setRadialAccelVar(floatVar[1]); - } else if (propertyName == PROPERTY_STARTRADIUS) { + } else if (propertyName === PROPERTY_STARTRADIUS) { node.setStartRadius(floatVar[0]); node.setStartRadiusVar(floatVar[1]); - } else if (propertyName == PROPERTY_ENDRADIUS) { + } else if (propertyName === PROPERTY_ENDRADIUS) { node.setEndRadius(floatVar[0]); node.setEndRadiusVar(floatVar[1]); - } else if (propertyName == PROPERTY_ROTATEPERSECOND) { + } else if (propertyName === PROPERTY_ROTATEPERSECOND) { node.setRotatePerSecond(floatVar[0]); node.setRotatePerSecondVar(floatVar[1]); } else { - this._super(node, parent, propertyName, floatVar, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeFloatVar.call(this, node, parent, propertyName, floatVar, ccbReader); } }, onHandlePropTypeColor4FVar:function (node, parent, propertyName, ccColor4FVar, ccbReader) { - if (propertyName == PROPERTY_STARTCOLOR) { + if (propertyName === PROPERTY_STARTCOLOR) { node.setStartColor(ccColor4FVar[0]); node.setStartColorVar(ccColor4FVar[1]); - } else if (propertyName == PROPERTY_ENDCOLOR) { + } else if (propertyName === PROPERTY_ENDCOLOR) { node.setEndColor(ccColor4FVar[0]); node.setEndColorVar(ccColor4FVar[1]); } else { - this._super(node, parent, propertyName, ccColor4FVar, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeColor4FVar.call(this, node, parent, propertyName, ccColor4FVar, ccbReader); } }, onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) { - if (propertyName == PROPERTY_BLENDFUNC) { + if (propertyName === PROPERTY_BLENDFUNC) { node.setBlendFunc(ccBlendFunc); } else { - this._super(node, parent, propertyName, ccBlendFunc, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader); } }, onHandlePropTypeTexture:function (node, parent, propertyName, ccTexture2D, ccbReader) { - if (propertyName == PROPERTY_TEXTURE) { + if (propertyName === PROPERTY_TEXTURE) { node.setTexture(ccTexture2D); } else { - this._super(node, parent, propertyName, ccTexture2D, ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeTexture.call(this, node, parent, propertyName, ccTexture2D, ccbReader); } } }); -cc.ParticleSystemQuadLoader.loader = function () { - return new cc.ParticleSystemQuadLoader(); +cc.ParticleSystemLoader.loader = function () { + return new cc.ParticleSystemLoader(); }; diff --git a/extensions/CCEditBox.js b/extensions/CCEditBox.js index e38dac23e2..9524b3a38a 100644 --- a/extensions/CCEditBox.js +++ b/extensions/CCEditBox.js @@ -209,13 +209,12 @@ cc.EditBox = cc.ControlButton.extend({ * * Constructor. * */ ctor: function (boxSize) { - this._super(); + cc.ControlButton.prototype.ctor.call(this); this._textColor = cc.WHITE; this._placeholderColor = cc.GRAY; this.setContentSize(boxSize); this._domInputSprite = new cc.Sprite(); - this._domInputSprite.setColor(cc.BLUE); this._domInputSprite.draw = function(){ }; //redefine draw function this.addChild(this._domInputSprite); var selfPointer = this; @@ -282,13 +281,32 @@ cc.EditBox = cc.ControlButton.extend({ setFont: function (fontName, fontSize) { this._edFontSize = fontSize; this._edFontName = fontName; - if (this._edTxt.value == this._placeholderText) - this._setFontToEditBox(); + this._setFontToEditBox(); + }, + + /** + * set fontName + * @param {String} fontName + */ + setFontName: function(fontName){ + this._edFontName = fontName; + this._setFontToEditBox(); + }, + + /** + * set fontSize + * @param {Number} fontSize + */ + setFontSize: function(fontSize){ + this._edFontSize = fontSize; + this._setFontToEditBox(); }, _setFontToEditBox: function () { - this._edTxt.style.fontFamily = this._placeholderFontName; - this._edTxt.style.fontSize = this._placeholderFontSize; + if (this._edTxt.value != this._placeholderText){ + this._edTxt.style.fontFamily = this._edFontName; + this._edTxt.style.fontSize = this._edFontSize+"px"; + } }, /** @@ -364,13 +382,32 @@ cc.EditBox = cc.ControlButton.extend({ setPlaceholderFont: function (fontName, fontSize) { this._placeholderFontName = fontName; this._placeholderFontSize = fontSize; - if (this._edTxt.value == this._placeholderText) - this._setPlaceholderFontToEditText(); + this._setPlaceholderFontToEditText(); + }, + + /** + * Set the placeholder's fontName. + * @param {String} fontName + */ + setPlaceholderFont: function (fontName) { + this._placeholderFontName = fontName; + this._setPlaceholderFontToEditText(); + }, + + /** + * Set the placeholder's fontSize. + * @param {Number} fontSize + */ + setPlaceholderFont: function (fontSize) { + this._placeholderFontSize = fontSize; + this._setPlaceholderFontToEditText(); }, _setPlaceholderFontToEditText: function () { - this._edTxt.style.fontFamily = this._placeholderFontName; - this._edTxt.style.fontSize = this._placeholderFontSize; + if (this._edTxt.value == this._placeholderText){ + this._edTxt.style.fontFamily = this._placeholderFontName; + this._edTxt.style.fontSize = this._placeholderFontSize + "px"; + } }, /** @@ -412,12 +449,12 @@ cc.EditBox = cc.ControlButton.extend({ */ initWithSizeAndBackgroundSprite: function (size, normal9SpriteBg) { if (this.initWithBackgroundSprite(normal9SpriteBg)) { - this._domInputSprite.setPosition(cc.p(3, 3)); + this._domInputSprite.setPosition(3, 3); this.setZoomOnTouchDown(false); this.setPreferredSize(size); - this.setPosition(cc.p(0, 0)); - this.addTargetWithActionForControlEvent(this, this.touchDownAction, cc.CONTROL_EVENT_TOUCH_UP_INSIDE); + this.setPosition(0, 0); + this._addTargetWithActionForControlEvent(this, this.touchDownAction, cc.CONTROL_EVENT_TOUCH_UP_INSIDE); return true; } return false; @@ -498,7 +535,7 @@ cc.EditBox = cc.ControlButton.extend({ cc.EditBox.getRect = function (node) { var contentSize = node.getContentSize(); - var rect = cc.RectMake(0, 0, contentSize.width, contentSize.height); + var rect = cc.rect(0, 0, contentSize.width, contentSize.height); return cc.RectApplyAffineTransform(rect, node.nodeToWorldTransform()); }; diff --git a/extensions/CCArmature/CCArmature.js b/extensions/CocoStudio/Armature/CCArmature.js similarity index 77% rename from extensions/CCArmature/CCArmature.js rename to extensions/CocoStudio/Armature/CCArmature.js index ad54b83225..7e1e88d632 100644 --- a/extensions/CCArmature/CCArmature.js +++ b/extensions/CocoStudio/Armature/CCArmature.js @@ -35,9 +35,12 @@ cc.Armature = cc.NodeRGBA.extend({ _textureAtlas:null, _parentBone:null, _boneDic:null, - _topBoneList:[], - _armatureIndexDic:{}, - _offsetPoint:cc.p(0, 0), + _topBoneList:null, + _armatureIndexDic:null, + _offsetPoint:null, + _version:0, + _armatureTransformDirty:false, + _body:null, ctor:function () { cc.NodeRGBA.prototype.ctor.call(this); this._animation = null; @@ -50,6 +53,9 @@ cc.Armature = cc.NodeRGBA.extend({ this._topBoneList = []; this._armatureIndexDic = {}; this._offsetPoint = cc.p(0, 0); + this._version = 0; + this._armatureTransformDirty = false; + this._body = null; }, /** @@ -233,13 +239,21 @@ cc.Armature = cc.NodeRGBA.extend({ changeBoneParent:function (bone, parentName) { if (!bone) { cc.log("bone must be added to the bone dictionary!"); + return; + } + var parentBone = bone.getParentBone(); + if(parentBone){ + cc.ArrayRemoveObject(parentBone.getChildrenBone(), bone); + bone.setParentBone(null); } - cc.ArrayRemoveObject(bone.getParentBone().getChildrenBone(), bone); - bone.removeFromParent(false); + if (parentName) { var boneParent = this._boneDic[parentName]; if (boneParent) { boneParent.addChildBone(bone); + cc.ArrayRemoveObject(this._topBoneList,bone); + }else{ + this._topBoneList.push(bone); } } }, @@ -259,15 +273,21 @@ cc.Armature = cc.NodeRGBA.extend({ // Set contentsize and Calculate anchor point. var rect = this.boundingBox(); this.setContentSize(rect.size); - this._offsetPoint = cc.p(-rect.origin.x, -rect.origin.y); - this.setAnchorPoint(cc.p(this._offsetPoint.x / rect.size.width, this._offsetPoint.y / rect.size.height)); + var locOffsetPoint = this._offsetPoint; + locOffsetPoint.x = -rect.x; + locOffsetPoint.y = -rect.y; + if (rect.width != 0 && rect.height != 0) { + this.setAnchorPoint(cc.p(locOffsetPoint.x / rect.width, locOffsetPoint.y / rect.height)); + } }, update:function (dt) { this._animation.update(dt); - for (var i = 0; i < this._topBoneList.length; i++) { - this._topBoneList[i].update(dt); + var locTopBoneList = this._topBoneList; + for (var i = 0; i < locTopBoneList.length; i++) { + locTopBoneList[i].update(dt); } + this._armatureTransformDirty = false; }, nodeToParentTransform:function () { @@ -276,6 +296,7 @@ cc.Armature = cc.NodeRGBA.extend({ nodeToParentTransformWEBGL:function () { if (this._transformDirty) { + this._armatureTransformDirty = true; // Translate values var x = this._position.x; var y = this._position.y; @@ -342,6 +363,7 @@ cc.Armature = cc.NodeRGBA.extend({ if (!this._transform) this._transform = {a:1, b:0, c:0, d:1, tx:0, ty:0}; if (this._transformDirty) { + this._armatureTransformDirty = true; var t = this._transform;// quick reference // base position t.tx = this._position.x; @@ -408,10 +430,6 @@ cc.Armature = cc.NodeRGBA.extend({ if (this._additionalTransformDirty) { this._transform = cc.AffineTransformConcat(this._transform, this._additionalTransform); - //Because the cartesian coordination is inverted in html5 canvas, these needs to be inverted as well - this._transform.b *= -1; - this._transform.c *= -1; - this._additionalTransformDirty = false; } @@ -423,7 +441,36 @@ cc.Armature = cc.NodeRGBA.extend({ }, draw:function () { - cc.g_NumberOfDraws++; + //cc.g_NumberOfDraws++; + }, + + /** + * update blendType + * @param {cc.BlendType} blendType + */ + updateBlendType: function (blendType) { + var blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST); + switch (blendType) { + case cc.BlendType.NORMAL: + blendFunc.src = cc.BLEND_SRC; + blendFunc.dst = cc.BLEND_DST; + break; + case cc.BlendType.ADD: + blendFunc.src = gl.SRC_ALPHA; + blendFunc.dst = gl.ONE; + break; + case cc.BlendType.MULTIPLY: + blendFunc.src = gl.ONE_MINUS_SRC_ALPHA; + blendFunc.dst = gl.ONE_MINUS_DST_COLOR; + break; + case cc.BlendType.SCREEN: + blendFunc.src = gl.ONE; + blendFunc.dst = gl.ONE_MINUS_DST_COLOR; + break; + default: + break; + } + this.setBlendFunc(blendFunc.src, blendFunc.dst); }, /** @@ -436,22 +483,24 @@ cc.Armature = cc.NodeRGBA.extend({ var boundingBox = cc.rect(0, 0, 0, 0); for (var i = 0; i < this._children.length; i++) { var bone = this._children[i]; - var r = bone.getDisplayManager().getBoundingBox(); - if (first) { - minx = cc.rectGetMinX(r); - miny = cc.rectGetMinY(r); - maxx = cc.rectGetMaxX(r); - maxy = cc.rectGetMaxY(r); - - first = false; - } - else { - minx = cc.rectGetMinX(r) < cc.rectGetMinX(boundingBox) ? cc.rectGetMinX(r) : cc.rectGetMinX(boundingBox); - miny = cc.rectGetMinY(r) < cc.rectGetMinY(boundingBox) ? cc.rectGetMinY(r) : cc.rectGetMinY(boundingBox); - maxx = cc.rectGetMaxX(r) > cc.rectGetMaxX(boundingBox) ? cc.rectGetMaxX(r) : cc.rectGetMaxX(boundingBox); - maxy = cc.rectGetMaxY(r) > cc.rectGetMaxY(boundingBox) ? cc.rectGetMaxY(r) : cc.rectGetMaxY(boundingBox); + if (bone instanceof cc.Bone) { + var r = bone.getDisplayManager().getBoundingBox(); + if (first) { + minx = cc.rectGetMinX(r); + miny = cc.rectGetMinY(r); + maxx = cc.rectGetMaxX(r); + maxy = cc.rectGetMaxY(r); + + first = false; + } + else { + minx = cc.rectGetMinX(r) < cc.rectGetMinX(boundingBox) ? cc.rectGetMinX(r) : cc.rectGetMinX(boundingBox); + miny = cc.rectGetMinY(r) < cc.rectGetMinY(boundingBox) ? cc.rectGetMinY(r) : cc.rectGetMinY(boundingBox); + maxx = cc.rectGetMaxX(r) > cc.rectGetMaxX(boundingBox) ? cc.rectGetMaxX(r) : cc.rectGetMaxX(boundingBox); + maxy = cc.rectGetMaxY(r) > cc.rectGetMaxY(boundingBox) ? cc.rectGetMaxY(r) : cc.rectGetMaxY(boundingBox); + } + boundingBox = cc.rect(minx, miny, maxx - minx, maxy - miny); } - boundingBox = cc.rect(minx, miny, maxx - minx, maxy - miny); } return boundingBox; }, @@ -499,12 +548,60 @@ cc.Armature = cc.NodeRGBA.extend({ setBatchNode:function (batchNode) { this._batchNode = batchNode; }, - getParentBone:function () { - return this._parentBone; + + /** + * version getter + * @returns {Number} + */ + getVersion:function () { + return this._version; }, - setParentBone:function (parentBone) { - this._parentBone = parentBone; + + /** + * version setter + * @param {Number} version + */ + setVersion:function (version) { + this._version = version; + }, + + /** + * armatureTransformDirty getter + * @returns {Boolean} + */ + getArmatureTransformDirty:function () { + return this._armatureTransformDirty; + }, + getBody:function(){ + return this._body; + }, + + setBody:function(body){ + if (this._body == body) + return; + + this._body = body; + this._body.data = this; + var child,displayObject; + for (var i = 0; i < this._children.length; i++) { + child = this._children[i]; + if (child instanceof cc.Bone) { + var displayList = child.getDisplayManager().getDecorativeDisplayList(); + for (var j = 0; j < displayList.length; j++) { + displayObject = displayList[j]; + var detector = displayObject.getColliderDetector(); + if (detector) + detector.setBody(this._body); + } + } + } + }, + getShapeList:function(){ + if(this._body) + return this._body.shapeList; + return []; } + }); /** diff --git a/extensions/CCArmature/CCBone.js b/extensions/CocoStudio/Armature/CCBone.js similarity index 75% rename from extensions/CCArmature/CCBone.js rename to extensions/CocoStudio/Armature/CCBone.js index 13e2d5b7e2..d63ef0998a 100644 --- a/extensions/CCArmature/CCBone.js +++ b/extensions/CocoStudio/Armature/CCBone.js @@ -36,10 +36,11 @@ cc.Bone = cc.NodeRGBA.extend({ _tween:null, _tweenData:null, _name:"", - _childrenBone:[], + _childrenBone:null, _parentBone:null, - _selfTransformDirty:false, - _worldTransform:cc.AffineTransformMake(1, 0, 0, 1, 0, 0), + _boneTransformDirty:false, + _worldTransform:null, + _blendType:0, ctor:function () { cc.NodeRGBA.prototype.ctor.call(this); this._boneData = null; @@ -52,8 +53,9 @@ cc.Bone = cc.NodeRGBA.extend({ this._name = ""; this._childrenBone = []; this._parentBone = null; - this._selfTransformDirty = true; + this._boneTransformDirty = true; this._worldTransform = cc.AffineTransformMake(1, 0, 0, 1, 0, 0); + this._blendType=cc.BlendType.NORMAL; }, /** @@ -118,7 +120,9 @@ cc.Bone = cc.NodeRGBA.extend({ */ setArmature:function (armature) { this._armature = armature; - this._tween.setAnimation(this._armature.getAnimation()); + if(armature){ + this._tween.setAnimation(this._armature.getAnimation()); + } }, /** @@ -134,47 +138,46 @@ cc.Bone = cc.NodeRGBA.extend({ * @param dt */ update:function (dt) { - if (this._parentBone) { - this._selfTransformDirty = this._selfTransformDirty || this._parentBone.isTransformDirty(); + var locParentBone = this._parentBone; + var locArmature = this._armature; + var locTweenData = this._tweenData; + var locWorldTransform = this._worldTransform; + + if (locParentBone) { + this._boneTransformDirty = this._boneTransformDirty || locParentBone.isTransformDirty(); } - if (this._selfTransformDirty) { - var cosX = Math.cos(this._tweenData.skewX); - var sinX = Math.sin(this._tweenData.skewX); - var cosY = Math.cos(this._tweenData.skewY); - var sinY = Math.sin(this._tweenData.skewY); - - this._worldTransform.a = this._tweenData.scaleX * cosY; - this._worldTransform.b = this._tweenData.scaleX * sinY; - this._worldTransform.c = this._tweenData.scaleY * sinX; - this._worldTransform.d = this._tweenData.scaleY * cosX; - this._worldTransform.tx = this._tweenData.x; - this._worldTransform.ty = this._tweenData.y; - - this._worldTransform = cc.AffineTransformConcat(this.nodeToParentTransform(), this._worldTransform); - - if (this._parentBone) { - this._worldTransform = cc.AffineTransformConcat(this._worldTransform, this._parentBone._worldTransform); + if (this._boneTransformDirty) { + if (locArmature.getArmatureData().dataVersion >= cc.CONST_VERSION_COMBINED) { + cc.TransformHelp.nodeConcat(locTweenData, this._boneData); + locTweenData.scaleX -= 1; + locTweenData.scaleY -= 1; + } + + cc.TransformHelp.nodeToMatrix(locTweenData, locWorldTransform); + + this._worldTransform = cc.AffineTransformConcat(this.nodeToParentTransform(), locWorldTransform); + + if (locParentBone) { + this._worldTransform = cc.AffineTransformConcat(this._worldTransform, locParentBone._worldTransform); } } - cc.DisplayFactory.updateDisplay(this, this._displayManager.getCurrentDecorativeDisplay(), dt, this._selfTransformDirty); - for (var i = 0; i < this._childrenBone.length; i++) { - this._childrenBone[i].update(dt); - } + cc.DisplayFactory.updateDisplay(this, this._displayManager.getCurrentDecorativeDisplay(), dt, this._boneTransformDirty || locArmature.getArmatureTransformDirty()); - this._selfTransformDirty = false; + var locChildrenBone = this._childrenBone; + for (var i = 0; i < locChildrenBone.length; i++) { + locChildrenBone[i].update(dt); + } + this._boneTransformDirty = false; }, - old_NumberOfDraws:0, /** * Rewrite visit ,when node draw, g_NumberOfDraws is changeless */ - visit:function () { - this.old_NumberOfDraws = cc.g_NumberOfDraws++; + visit:function (ctx) { var node = this.getDisplayManager().getDisplayRenderNode(); if (node) { node.visit(ctx); } - cc.g_NumberOfDraws = this.old_NumberOfDraws; }, /** @@ -182,6 +185,7 @@ cc.Bone = cc.NodeRGBA.extend({ * @param {cc.c3b} color */ updateDisplayedColor:function (color) { + this._realColor = cc.c3b(255,255,255); cc.NodeRGBA.prototype.updateDisplayedColor.call(this, color); this.updateColor(); }, @@ -191,6 +195,7 @@ cc.Bone = cc.NodeRGBA.extend({ * @param {Number} opacity */ updateDisplayedOpacity:function (opacity) { + this._realOpacity = 255; cc.NodeRGBA.prototype.updateDisplayedOpacity.call(this, opacity); this.updateColor(); }, @@ -200,9 +205,27 @@ cc.Bone = cc.NodeRGBA.extend({ */ updateColor:function () { var display = this._displayManager.getDisplayRenderNode(); - if (display) { - display.setColor(cc.c3b(this._displayedColor.r * this._tweenData.r / 255, this._displayedColor.g * this._tweenData.g / 255, this._displayedColor.b * this._tweenData.b / 255)); - display.setOpacity(this._displayedOpacity * this._tweenData.a / 255); + if (display&&display instanceof cc.Skin) { + //display.setColor(cc.c3b(this._displayedColor.r * this._tweenData.r / 255, this._displayedColor.g * this._tweenData.g / 255, this._displayedColor.b * this._tweenData.b / 255)); + if(cc.Browser.supportWebGL){ + display.setOpacity(this._displayedOpacity * this._tweenData.a / 255); + }else{ + cc.NodeRGBA.prototype.setOpacity.call(display, this._displayedOpacity * this._tweenData.a / 255); + } + + } + }, + + /** + * update display zOrder + */ + updateZOrder: function () { + if (this._armature.getArmatureData().dataVersion >= cc.CONST_VERSION_COMBINED) { + var zorder = this._tweenData.zOrder + this._boneData.zOrder; + this.setZOrder(zorder); + } + else { + this.setZOrder(this._tweenData.zOrder); } }, @@ -219,9 +242,6 @@ cc.Bone = cc.NodeRGBA.extend({ cc.log("child already added. It can't be added again"); return; } - if (!this._childrenBone) { - this.childrenAlloc(); - } if (cc.ArrayGetIndexOfObject(this._childrenBone, child) < 0) { this._childrenBone.push(child); child.setParentBone(this); @@ -277,10 +297,6 @@ cc.Bone = cc.NodeRGBA.extend({ return this._parentBone; }, - childrenAlloc:function () { - this._childrenBone = []; - }, - /** * child armature setter * @param {cc.Armature} armature @@ -329,7 +345,7 @@ cc.Bone = cc.NodeRGBA.extend({ * @param {Boolean} */ setTransformDirty:function (dirty) { - this._selfTransformDirty = dirty; + this._boneTransformDirty = dirty; }, /** @@ -337,7 +353,7 @@ cc.Bone = cc.NodeRGBA.extend({ * @return {Boolean} */ isTransformDirty:function () { - return this._selfTransformDirty; + return this._boneTransformDirty; }, /** @@ -348,6 +364,22 @@ cc.Bone = cc.NodeRGBA.extend({ return this._worldTransform; }, + /** + * Returns the world affine transform matrix. The matrix is in Pixels. + * @returns {cc.AffineTransform} + */ + nodeToWorldTransform: function () { + return cc.AffineTransformConcat(this._worldTransform, this._armature.nodeToWorldTransform()); + }, + + /** + * get render node + * @returns {cc.Node} + */ + getDisplayRenderNode: function () { + return this._displayManager.getDisplayRenderNode(); + }, + /** * Add display and use _displayData init the display. * If index already have a display, then replace it. @@ -358,7 +390,13 @@ cc.Bone = cc.NodeRGBA.extend({ * -1 : append display from back */ addDisplay:function (displayData, index) { - this._displayManager.addDisplay(displayData, index); + index = index || 0; + return this._displayManager.addDisplay(displayData, index); + }, + + addSkin:function (skin, index) { + index = index||0; + return this._displayManager.addSkin(skin, index); }, /** @@ -425,6 +463,22 @@ cc.Bone = cc.NodeRGBA.extend({ */ getName:function () { return this._name; + }, + + /** + * blendType setter + * @param {cc.BlendType} blendType + */ + setBlendType:function (blendType) { + this._blendType = blendType; + }, + + /** + * blendType getter + * @return {cc.BlendType} + */ + getBlendType:function () { + return this._blendType; } }); diff --git a/extensions/CCArmature/animation/CCArmatureAnimation.js b/extensions/CocoStudio/Armature/animation/CCArmatureAnimation.js similarity index 68% rename from extensions/CCArmature/animation/CCArmatureAnimation.js rename to extensions/CocoStudio/Armature/animation/CCArmatureAnimation.js index 4a8890d5e5..8bcfd5100f 100644 --- a/extensions/CCArmature/animation/CCArmatureAnimation.js +++ b/extensions/CocoStudio/Armature/animation/CCArmatureAnimation.js @@ -32,7 +32,7 @@ CC_MovementEventType_LOOP_COMPLETE = 2; * @class * @extends cc.Class */ -cc.MovementEvent = cc.Class.extend({ +cc.AnimationEvent = cc.Class.extend({ _arguments:null, _callFunc:null, _selectorTarget:null, @@ -63,20 +63,22 @@ cc.ArmatureAnimation = cc.ProcessBase.extend({ _movementID:"", _prevFrameIndex:0, _toIndex:0, - _tweenList:[], - MovementEventSignal:{}, + _tweenList:null, _frameEvent:null, - + _movementEvent:null, + _speedScale:1, ctor:function () { cc.ProcessBase.prototype.ctor.call(this); this._animationData = null; - this._currentFrameData = null; + this._movementData = null; this._movementID = ""; this._armature = null; this._prevFrameIndex = 0; this._toIndex = 0; - this.MovementEventSignal = {}; - this.FrameEventSignal = {}; + this._tweenList = []; + this._frameEvent = null; + this._movementEvent = null; + this._speedScale = 1; }, /** @@ -112,20 +114,47 @@ cc.ArmatureAnimation = cc.ProcessBase.extend({ /** * scale animation play speed - * @param {Number} animationScale + * @param {Number} speedScale */ - setAnimationScale:function (animationScale) { - if (animationScale == this._animationScale) { + setSpeedScale:function (speedScale) { + if (speedScale == this._speedScale) { + return; + } + this._speedScale = speedScale; + this._processScale = !this._movementData ? this._speedScale : this._speedScale * this._movementData.scale; + var dict = this._armature.getBoneDic(); + for (var key in dict) { + var bone = dict[key]; + bone.getTween().setProcessScale(this._processScale); + if (bone.getChildArmature()) { + bone.getChildArmature().getAnimation().setProcessScale(this._processScale); + } + } + }, + + getSpeedScale:function(){ + return this._speedScale; + }, + + getAnimationScale:function(){ + return this.getSpeedScale(); + }, + setAnimationScale:function(animationScale){ + return this.setSpeedScale(animationScale); + }, + + setAnimationInternal:function (animationInternal) { + if (animationInternal == this._animationInternal) { return; } - this._animationScale = animationScale; + this._animationInternal = animationInternal; var dict = this._armature.getBoneDic(); for (var key in dict) { var bone = dict[key]; - bone.getTween().setAnimationScale(this._animationScale); + bone.getTween().setAnimationInternal(this._animationInternal); if (bone.getChildArmature()) { - bone.getChildArmature().getAnimation().setAnimationScale(this._animationScale); + bone.getChildArmature().getAnimation().setAnimationInternal(this._animationInternal); } } }, @@ -153,7 +182,6 @@ cc.ArmatureAnimation = cc.ProcessBase.extend({ * 2 : fade in and out */ play:function (animationName, durationTo, durationTween, loop, tweenEasing) { - this.stop(); if (this._animationData == null) { cc.log("this._animationData can not be null"); return; @@ -173,21 +201,23 @@ cc.ArmatureAnimation = cc.ProcessBase.extend({ loop = -1; } if (typeof tweenEasing == "undefined") { - tweenEasing = 10000; + tweenEasing = cc.TweenType.TWEEN_EASING_MAX; } + var locMovementData = this._movementData; //Get key frame count - this._rawDuration = this._movementData.duration; + this._rawDuration = locMovementData.duration; this._movementID = animationName; + this._processScale = this._speedScale * locMovementData.scale; //Further processing parameters - durationTo = (durationTo == -1) ? this._movementData.durationTo : durationTo; - durationTween = (durationTween == -1) ? this._movementData.durationTween : durationTween; - durationTween = (durationTween == 0) ? this._movementData.duration : durationTween;//todo - tweenEasing = (tweenEasing == cc.TweenType.TWEEN_EASING_MAX) ? this._movementData.tweenEasing : tweenEasing; - loop = (loop < 0) ? this._movementData.loop : loop; + durationTo = (durationTo == -1) ? locMovementData.durationTo : durationTo; + durationTween = (durationTween == -1) ? locMovementData.durationTween : durationTween; + durationTween = (durationTween == 0) ? locMovementData.duration : durationTween;//todo + tweenEasing = (tweenEasing == cc.TweenType.TWEEN_EASING_MAX) ? locMovementData.tweenEasing : tweenEasing; + loop = (loop < 0) ? locMovementData.loop : loop; cc.ProcessBase.prototype.play.call(this, animationName, durationTo, durationTween, loop, tweenEasing); - if (this._rawDuration == 1) { + if (this._rawDuration == 0) { this._loopType = CC_ANIMATION_TYPE_SINGLE_FRAME; } else { @@ -200,19 +230,25 @@ cc.ArmatureAnimation = cc.ProcessBase.extend({ } this._durationTween = durationTween; } + + this._tweenList = []; + var movementBoneData; var dict = this._armature.getBoneDic(); for (var key in dict) { var bone = dict[key]; - movementBoneData = this._movementData.getMovementBoneData(bone.getName()); + movementBoneData = locMovementData.getMovementBoneData(bone.getName()); var tween = bone.getTween(); if (movementBoneData && movementBoneData.frameList.length > 0) { this._tweenList.push(tween); + movementBoneData.duration = locMovementData.duration; tween.play(movementBoneData, durationTo, durationTween, loop, tweenEasing); - tween.setAnimationScale(this._animationScale); + tween.setProcessScale(this._processScale); + tween.setAnimationInternal(this._animationInternal); if (bone.getChildArmature()) { - bone.getChildArmature().getAnimation().setAnimationScale(this._animationScale); + bone.getChildArmature().getAnimation().setProcessScale(this._processScale); + bone.getChildArmature().getAnimation().setAnimationInternal(this._animationInternal); } } else { if (!bone.getIgnoreMovementBoneData()) { @@ -246,7 +282,7 @@ cc.ArmatureAnimation = cc.ProcessBase.extend({ } var moveNames = this._animationData.movementNames; if (animationIndex < -1 || animationIndex >= moveNames.length) { - return + return; } var animationName = moveNames[animationIndex]; this.play(animationName, durationTo, durationTween, loop, tweenEasing); @@ -261,9 +297,10 @@ cc.ArmatureAnimation = cc.ProcessBase.extend({ }, update:function (dt) { - cc.ProcessBase.prototype.update.call(this, dt); - for (var i = 0; i < this._tweenList.length; i++) { - this._tweenList[i].update(dt); + if(cc.ProcessBase.prototype.update.call(this, dt)){ + for (var i = 0; i < this._tweenList.length; i++) { + this._tweenList[i].update(dt); + } } }, @@ -271,52 +308,71 @@ cc.ArmatureAnimation = cc.ProcessBase.extend({ * update will call this handler, you can handle your logic here */ updateHandler:function () { - if (this._currentPercent >= 1) { + var locCurrentPercent = this._currentPercent; + if (locCurrentPercent >= 1) { switch (this._loopType) { case CC_ANIMATION_TYPE_NO_LOOP: this._loopType = CC_ANIMATION_TYPE_MAX; - this._currentFrame = (this._currentPercent - 1) * this._nextFrameIndex; - this._currentPercent = this._currentFrame / this._durationTween; - if (this._currentPercent < 1.0) { + this._currentFrame = (locCurrentPercent - 1) * this._nextFrameIndex; + locCurrentPercent = this._currentFrame / this._durationTween; + if (locCurrentPercent < 1.0) { this._nextFrameIndex = this._durationTween; - this.callEvent([this, CC_MovementEventType_START, this._movementID]); + this.callMovementEvent([this._armature, CC_MovementEventType_START, this._movementID]); break; } case CC_ANIMATION_TYPE_MAX: case CC_ANIMATION_TYPE_SINGLE_FRAME: - this._currentPercent = 1; + locCurrentPercent = 1; this._isComplete = true; - this.callEvent([this, CC_MovementEventType_COMPLETE, this._movementID]); + this._isPlaying = false; + this.callMovementEvent([this._armature, CC_MovementEventType_COMPLETE, this._movementID]); break; case CC_ANIMATION_TYPE_TO_LOOP_FRONT: this._loopType = CC_ANIMATION_TYPE_LOOP_FRONT; - this._currentPercent = cc.fmodf(this._currentPercent, 1); - this._currentFrame = cc.fmodf(this._currentFrame, this._nextFrameIndex); + locCurrentPercent = cc.fmodf(locCurrentPercent, 1); + this._currentFrame = this._nextFrameIndex == 0 ? 0 : cc.fmodf(this._currentFrame, this._nextFrameIndex); this._nextFrameIndex = this._durationTween > 0 ? this._durationTween : 1; - this.callEvent([this, CC_MovementEventType_START, this._movementID]); + this.callMovementEvent([this, CC_MovementEventType_START, this._movementID]); break; default: - this._currentPercent = cc.fmodf(this._currentPercent, 1); + locCurrentPercent = cc.fmodf(locCurrentPercent, 1); this._currentFrame = cc.fmodf(this._currentFrame, this._nextFrameIndex); this._toIndex = 0; - this.callEvent([this, CC_MovementEventType_LOOP_COMPLETE, this._movementID]); + this.callMovementEvent([this._armature, CC_MovementEventType_LOOP_COMPLETE, this._movementID]); break; } + this._currentPercent = locCurrentPercent; } + }, - if (this._loopType == CC_ANIMATION_TYPE_LOOP_BACK || this._loopType == CC_ANIMATION_TYPE_LOOP_FRONT) { - this.updateFrameData(this._currentPercent); - } + /** + * Get current movementID + * @returns {String} + */ + getCurrentMovementID: function () { + if (this._isComplete) + return ""; + return this._movementID; }, /** - * Update current key frame, and process auto stop, pause - * @param {Number} currentPercent + * connect a event + * @param {Object} target + * @param {function} callFunc */ - updateFrameData:function (currentPercent) { - this._prevFrameIndex = this._curFrameIndex; - this._curFrameIndex = this._rawDuration * currentPercent; - this._curFrameIndex = this._curFrameIndex % this._rawDuration; + setMovementEventCallFunc:function (callFunc, target) { + this._movementEvent = new cc.AnimationEvent(target, callFunc); + }, + + /** + * call event + * @param {Array} args + */ + callMovementEvent:function (args) { + if (this._movementEvent) { + this._movementEvent.setArguments(args); + this._movementEvent.call(); + } }, /** @@ -324,15 +380,15 @@ cc.ArmatureAnimation = cc.ProcessBase.extend({ * @param {Object} target * @param {function} callFunc */ - connectEvent:function (target, callFunc) { - this._frameEvent = new cc.MovementEvent(target, callFunc); + setFrameEventCallFunc:function (callFunc, target) { + this._frameEvent = new cc.AnimationEvent(target, callFunc); }, /** * call event * @param {Array} args */ - callEvent:function (args) { + callFrameEvent:function (args) { if (this._frameEvent) { this._frameEvent.setArguments(args); this._frameEvent.call(); diff --git a/extensions/CCArmature/animation/CCProcessBase.js b/extensions/CocoStudio/Armature/animation/CCProcessBase.js similarity index 79% rename from extensions/CCArmature/animation/CCProcessBase.js rename to extensions/CocoStudio/Armature/animation/CCProcessBase.js index 36d0f8daa2..a67ade99f6 100644 --- a/extensions/CCArmature/animation/CCProcessBase.js +++ b/extensions/CocoStudio/Armature/animation/CCProcessBase.js @@ -38,7 +38,7 @@ CC_ANIMATION_TYPE_MAX = 2;//the animation max * @extends cc.Class */ cc.ProcessBase = cc.Class.extend({ - _animationScale:1, + _processScale:1, _isComplete:true, _isPause:true, _isPlaying:false, @@ -53,7 +53,7 @@ cc.ProcessBase = cc.Class.extend({ _curFrameIndex:null, _isLoopBack:false, ctor:function () { - this._animationScale = 1; + this._processScale = 1; this._isComplete = true; this._isPause = true; this._isPlaying = false; @@ -72,15 +72,18 @@ cc.ProcessBase = cc.Class.extend({ pause:function () { this._isPause = true; + this._isPlaying = false; }, resume:function () { this._isPause = false; + this._isPlaying = true; }, stop:function () { this._isComplete = true; + this._isPlaying = false; this._currentFrame = 0; this._currentPercent = 0; }, @@ -123,29 +126,33 @@ cc.ProcessBase = cc.Class.extend({ update:function (dt) { if (this._isComplete || this._isPause) { - return; + return false; } if (this._rawDuration <= 0 || dt > 1) { - return; + return false; } - if (this._nextFrameIndex <= 0) { - this._currentFrame = this._nextFrameIndex = 1; + var locNextFrameIndex = this._nextFrameIndex; + if (locNextFrameIndex <= 0) { + this._currentPercent = 1; + this._currentFrame = 0; + }else{ + /* + * update this._currentFrame, every update add the frame passed. + * dt/this._animationInternal determine it is not a frame animation. If frame speed changed, it will not make our + * animation speed slower or quicker. + */ + this._currentFrame += this._processScale * (dt / this._animationInternal); + + this._currentPercent = this._currentFrame / locNextFrameIndex; + + /* + * if this._currentFrame is bigger or equal than this._nextFrameIndex, then reduce it util this._currentFrame is + * smaller than this._nextFrameIndex + */ + this._currentFrame = cc.fmodf(this._currentFrame, locNextFrameIndex); } - /* - * update this._currentFrame, every update add the frame passed. - * dt/this._animationInternal determine it is not a frame animation. If frame speed changed, it will not make our - * animation speed slower or quicker. - */ - this._currentFrame += this._animationScale * (dt / this._animationInternal); - - this._currentPercent = this._currentFrame / this._nextFrameIndex; - - /* - * if this._currentFrame is bigger or equal than this._nextFrameIndex, then reduce it util this._currentFrame is - * smaller than this._nextFrameIndex - */ - this._currentFrame = cc.fmodf(this._currentFrame, this._nextFrameIndex); this.updateHandler(); + return true; }, /** @@ -156,7 +163,7 @@ cc.ProcessBase = cc.Class.extend({ }, gotoFrame:function (keyFrameIndex) { this._curFrameIndex = keyFrameIndex; - this.stop(); + this.pause(); }, /** @@ -164,6 +171,7 @@ cc.ProcessBase = cc.Class.extend({ * @return {Number} */ getCurrentFrameIndex:function () { + this._curFrameIndex = this._rawDuration * this._currentPercent; return this._curFrameIndex; }, @@ -188,11 +196,14 @@ cc.ProcessBase = cc.Class.extend({ getAnimationInternal:function () { return this._animationInternal; }, - getAnimationScale:function () { - return this._animationScale; + setAnimationInternal:function(animationInternal){ + this._animationInternal = animationInternal; + }, + getProcessScale:function () { + return this._processScale; }, - setAnimationScale:function (animationScale) { - this._animationScale = animationScale; + setProcessScale:function (processScale) { + this._processScale = processScale; }, isPlaying:function () { return this._isPlaying; diff --git a/extensions/CCArmature/animation/CCTween.js b/extensions/CocoStudio/Armature/animation/CCTween.js similarity index 62% rename from extensions/CCArmature/animation/CCTween.js rename to extensions/CocoStudio/Armature/animation/CCTween.js index 4850317fb5..1a0ef754ca 100644 --- a/extensions/CCArmature/animation/CCTween.js +++ b/extensions/CocoStudio/Armature/animation/CCTween.js @@ -33,23 +33,20 @@ cc.Tween = cc.ProcessBase.extend({ _from:null, _between:null, _movementBoneData:null, - _currentKeyFrame:null, _bone:null, _frameTweenEasing:0, - _isTweenKeyFrame:false, _betweenDuration:0, _totalDuration:0, _toIndex:0, _fromIndex:0, - _animation:false, + _animation:null, ctor:function () { cc.ProcessBase.prototype.ctor.call(this); + this._tweenData = null; + this._to = null; this._from = null; this._between = null; this._bone = null; - this._currentKeyFrame = null; - this._nextKeyFrame = null; - this._editKeyFrame = null; this._movementBoneData = null; this._frameTweenEasing = cc.TweenType.Linear; this._toIndex = 0; @@ -68,6 +65,7 @@ cc.Tween = cc.ProcessBase.extend({ this._bone = bone; this._tweenData = this._bone.getTweenData(); + this._tweenData.displayIndex = -1; this._animation = this._bone.getArmature() != null ? this._bone.getArmature().getAnimation() : null; return true; }, @@ -97,38 +95,41 @@ cc.Tween = cc.ProcessBase.extend({ play:function (movementBoneData, durationTo, durationTween, loop, tweenEasing) { cc.ProcessBase.prototype.play.call(this, null, durationTo, durationTween, loop, tweenEasing); this._loopType = loop; - this._currentKeyFrame = null; - this._isTweenKeyFrame = false; this._totalDuration = 0; this._betweenDuration = 0; - this._toIndex = 0; + this._fromIndex = this._toIndex = 0; + + var difMovement = movementBoneData != this._movementBoneData; this._movementBoneData = movementBoneData; - if (this._movementBoneData.frameList.length == 1) { + this._rawDuration = this._movementBoneData.duration; + + var nextKeyFrame = this._movementBoneData.getFrameData(0); + this._tweenData.displayIndex = nextKeyFrame.displayIndex; + + if (this._bone.getArmature().getArmatureData().dataVersion >= cc.CONST_VERSION_COMBINED) { + cc.TransformHelp.nodeSub(this._tweenData, this._bone.getBoneData()); + this._tweenData.scaleX += 1; + this._tweenData.scaleY += 1; + } + + if (this._rawDuration==0) { this._loopType = CC_ANIMATION_TYPE_SINGLE_FRAME; - var nextKeyFrame = this._movementBoneData.getFrameData(0); if (durationTo == 0) { this.setBetween(nextKeyFrame, nextKeyFrame); } else { - this._tweenData.displayIndex = nextKeyFrame.displayIndex; this.setBetween(this._tweenData, nextKeyFrame); } - - this._isTweenKeyFrame = true; this._frameTweenEasing = cc.TweenType.Linear; - this._rawDuration = this._movementBoneData.duration; - this._fromIndex = this._toIndex = 0; } else if (this._movementBoneData.frameList.length > 1) { if (loop) { this._loopType = CC_ANIMATION_TYPE_TO_LOOP_BACK; - this._rawDuration = this._movementBoneData.duration; } else { this._loopType = CC_ANIMATION_TYPE_NO_LOOP; - this._rawDuration = this._movementBoneData.duration - 1; } this._durationTween = durationTween * this._movementBoneData.scale; @@ -136,87 +137,90 @@ cc.Tween = cc.ProcessBase.extend({ this.setBetween(this._tweenData, this.tweenNodeTo(this.updateFrameData(1 - this._movementBoneData.delay), this._between)); } else { - var nextKeyFrame = this._movementBoneData.getFrameData(0); - this.setBetween(this._tweenData, nextKeyFrame); - this._isTweenKeyFrame = true; + if (!difMovement || durationTo == 0) + this.setBetween(nextKeyFrame, nextKeyFrame); + else + this.setBetween(this._tweenData, nextKeyFrame); } } + this.tweenNodeTo(0); }, /** * update will call this handler, you can handle your logic here */ updateHandler:function () { - if (this._currentPercent >= 1) { - switch (this._loopType) { + var locCurrentPercent = this._currentPercent; + var locLoopType = this._loopType; + if (locCurrentPercent >= 1) { + switch (locLoopType) { case CC_ANIMATION_TYPE_SINGLE_FRAME: - this._currentPercent = 1; + locCurrentPercent = 1; this._isComplete = true; break; case CC_ANIMATION_TYPE_NO_LOOP: - this._loopType = CC_ANIMATION_TYPE_MAX; + locLoopType = CC_ANIMATION_TYPE_MAX; if (this._durationTween <= 0) { - this._currentPercent = 1; + locCurrentPercent = 1; } else { - this._currentPercent = (this._currentPercent - 1) * this._nextFrameIndex / this._durationTween; + locCurrentPercent = (locCurrentPercent - 1) * this._nextFrameIndex / this._durationTween; } - if (this._currentPercent >= 1) { - this._currentPercent = 1; + if (locCurrentPercent >= 1) { + locCurrentPercent = 1; this._isComplete = true; break; } else { this._nextFrameIndex = this._durationTween; - this._currentFrame = this._currentPercent * this._nextFrameIndex; + this._currentFrame = locCurrentPercent * this._nextFrameIndex; this._totalDuration = 0; this._betweenDuration = 0; - this._toIndex = 0; + this._fromIndex = this._toIndex = 0; break; } case CC_ANIMATION_TYPE_TO_LOOP_BACK: - this._loopType = CC_ANIMATION_TYPE_LOOP_BACK; + locLoopType = CC_ANIMATION_TYPE_LOOP_BACK; this._nextFrameIndex = this._durationTween > 0 ? this._durationTween : 1; if (this._movementBoneData.delay != 0) { this._currentFrame = (1 - this._movementBoneData.delay) * this._nextFrameIndex; - this._currentPercent = this._currentFrame / this._nextFrameIndex; + locCurrentPercent = this._currentFrame / this._nextFrameIndex; } else { - this._currentPercent = 0; + locCurrentPercent = 0; this._currentFrame = 0; } this._totalDuration = 0; this._betweenDuration = 0; - this._toIndex = 0; + this._fromIndex = this._toIndex = 0; break; case CC_ANIMATION_TYPE_MAX: - this._currentPercent = 1; + locCurrentPercent = 1; this._isComplete = true; break; default: - this._currentPercent = cc.fmodf(this._currentPercent, 1); + locCurrentPercent = cc.fmodf(locCurrentPercent, 1); this._currentFrame = cc.fmodf(this._currentFrame, this._nextFrameIndex); this._totalDuration = 0; this._betweenDuration = 0; - this._toIndex = 0; + this._fromIndex = this._toIndex = 0; break; } } - if (this._currentPercent < 1 && this._loopType < CC_ANIMATION_TYPE_TO_LOOP_BACK) { - this._currentPercent = Math.sin(this._currentPercent * cc.PI / 2); + if (locCurrentPercent < 1 && locLoopType < CC_ANIMATION_TYPE_TO_LOOP_BACK) { + locCurrentPercent = Math.sin(locCurrentPercent * cc.PI / 2); } - var percent = this._currentPercent; - if (this._loopType > CC_ANIMATION_TYPE_TO_LOOP_BACK) { - percent = this.updateFrameData(percent, true); - } - if (this._frameTweenEasing != cc.TWEEN_EASING_MAX) { - this.tweenNodeTo(percent); + this._currentPercent = locCurrentPercent; + this._loopType = locLoopType; + + if (locLoopType > CC_ANIMATION_TYPE_TO_LOOP_BACK) { + locCurrentPercent = this.updateFrameData(locCurrentPercent, true); } - else if (this._currentKeyFrame) { - this.tweenNodeTo(0); + if (this._frameTweenEasing != cc.TweenType.TWEEN_EASING_MAX) { + this.tweenNodeTo(locCurrentPercent); } }, @@ -229,12 +233,13 @@ cc.Tween = cc.ProcessBase.extend({ setBetween:function (from, to) { do { - if (to.displayIndex < 0 && from.displayIndex > 0) { - this._from.copy(from); + if (from.displayIndex < 0 && to.displayIndex >= 0) { + this._from.copy(to); this._between.subtract(to, to); break; - } else if (from.displayIndex < 0 && to.displayIndex > 0) { - this._from.copy(to); + } + if (to.displayIndex < 0 && from.displayIndex >= 0) { + this._from.copy(from); this._between.subtract(to, to); break; } @@ -250,23 +255,22 @@ cc.Tween = cc.ProcessBase.extend({ */ arriveKeyFrame:function (keyFrameData) { if (keyFrameData) { + var locBone = this._bone; var displayIndex = keyFrameData.displayIndex; - if (!this._bone.getDisplayManager().getForceChangeDisplay()) { - this._bone.getDisplayManager().changeDisplayByIndex(displayIndex, false); + var displayManager = locBone.getDisplayManager(); + if (!displayManager.getForceChangeDisplay()) { + displayManager.changeDisplayByIndex(displayIndex, false); + } - this._bone.setZOrder(keyFrameData.zOrder); - var childAramture = this._bone.getChildArmature(); + this._tweenData.zOrder = keyFrameData.zOrder; + locBone.updateZOrder(); + locBone.setBlendType(keyFrameData.blendType); + var childAramture = locBone.getChildArmature(); if (childAramture) { if (keyFrameData.movement != "") { childAramture.getAnimation().play(keyFrameData.movement); } } - if (keyFrameData.event != "") { - //this._animation.FrameEventSignal.emit(this._bone, keyFrameData.event); - } - if (keyFrameData.sound) { - //soundManager.dispatchEventWith(Event.SOUND_FRAME, m_pCurrentKeyFrame.sound); - } } }, @@ -280,73 +284,102 @@ cc.Tween = cc.ProcessBase.extend({ if (!node) { node = this._tweenData; } - node.x = this._from.x + percent * this._between.x; - node.y = this._from.y + percent * this._between.y; - node.scaleX = this._from.scaleX + percent * this._between.scaleX; - node.scaleY = this._from.scaleY + percent * this._between.scaleY; - node.skewX = this._from.skewX + percent * this._between.skewX; - node.skewY = this._from.skewY + percent * this._between.skewY; + var locFrom = this._from; + var locBetween = this._between; + node.x = locFrom.x + percent * locBetween.x; + node.y = locFrom.y + percent * locBetween.y; + node.scaleX = locFrom.scaleX + percent * locBetween.scaleX; + node.scaleY = locFrom.scaleY + percent * locBetween.scaleY; + node.skewX = locFrom.skewX + percent * locBetween.skewX; + node.skewY = locFrom.skewY + percent * locBetween.skewY; + this._bone.setTransformDirty(true); - if (this._between.isUseColorInfo) { - node.a = this._from.a + percent * this._between.a; - node.r = this._from.r + percent * this._between.r; - node.g = this._from.g + percent * this._between.g; - node.b = this._from.b + percent * this._between.b; - this._bone.updateColor(); - } + if (node && locBetween.isUseColorInfo) + this.tweenColorTo(percent, node); + return node; }, + tweenColorTo:function(percent,node){ + var locFrom = this._from; + var locBetween = this._between; + node.a = locFrom.a + percent * locBetween.a; + node.r = locFrom.r + percent * locBetween.r; + node.g = locFrom.g + percent * locBetween.g; + node.b = locFrom.b + percent * locBetween.b; + this._bone.updateColor(); + }, + /** * Calculate which frame arrived, and if current frame have event, then call the event listener * @param {Number} currentPercent * @param {Boolean} activeFrame * @return {Number} */ - updateFrameData:function (currentPercent, activeFrame) { + updateFrameData:function (currentPercent) { + if (currentPercent > 1 && this._movementBoneData.delay != 0) { + currentPercent = cc.fmodf(currentPercent,1); + } var playedTime = this._rawDuration * currentPercent; - var from; - var to; - var isListEnd; + var from, to; + var locTotalDuration = this._totalDuration,locBetweenDuration = this._betweenDuration, locToIndex = this._toIndex; // if play to current frame's front or back, then find current frame again - if (playedTime >= this._totalDuration || playedTime < this._totalDuration - this._betweenDuration) { + if (playedTime < locTotalDuration || playedTime >= locTotalDuration + locBetweenDuration) { /* * get frame length, if this._toIndex >= _length, then set this._toIndex to 0, start anew. * this._toIndex is next index will play */ var length = this._movementBoneData.frameList.length; + var frames = this._movementBoneData.frameList; + if (playedTime < frames[0].frameID){ + from = to = frames[0]; + this.setBetween(from, to); + return currentPercent; + } + else if(playedTime >= frames[length - 1].frameID){ + from = to = frames[length - 1]; + this.setBetween(from, to); + return currentPercent; + } + do { - this._betweenDuration = this._movementBoneData.getFrameData(this._toIndex).duration; - this._totalDuration += this._betweenDuration; - this._fromIndex = this._toIndex; - if (++this._toIndex >= length) { - this._toIndex = 0; + from = frames[this._fromIndex]; + locTotalDuration = from.frameID; + if (++locToIndex >= length) { + locToIndex = 0; } - } - while (playedTime >= this._totalDuration); + this._fromIndex = locToIndex; + to = frames[locToIndex]; - isListEnd = this._loopType == CC_ANIMATION_TYPE_MAX && this._toIndex == 0; + //! Guaranteed to trigger frame event + if(from.event){ + this._animation.callFrameEvent([this._bone, from.event,from.frameID, playedTime]); + } - if (isListEnd) { - to = from = this._movementBoneData.getFrameData(this._fromIndex); - } - else { - from = this._movementBoneData.getFrameData(this._fromIndex); - to = this._movementBoneData.getFrameData(this._toIndex); + if (playedTime == from.frameID) { + break; + } } + while (playedTime < from.frameID || playedTime >= to.frameID); + locBetweenDuration = to.frameID - from.frameID; this._frameTweenEasing = from.tweenEasing; this.setBetween(from, to); + this._totalDuration = locTotalDuration; + this._betweenDuration = locBetweenDuration; + this._toIndex = locToIndex; } - currentPercent = 1 - (this._totalDuration - playedTime) / this._betweenDuration; + + currentPercent = locBetweenDuration == 0 ? 0 : (playedTime - locTotalDuration) / locBetweenDuration; + /* * if frame tween easing equal to TWEEN_EASING_MAX, then it will not do tween. */ var tweenType = null; - - if (this._frameTweenEasing != cc.TweenType.TWEEN_EASING_MAX) { - tweenType = (this._tweenEasing == cc.TweenType.TWEEN_EASING_MAX) ? this._frameTweenEasing : this._tweenEasing; - if (tweenType != cc.TweenType.TWEEN_EASING_MAX) { + var locTWEEN_EASING_MAX = cc.TweenType.TWEEN_EASING_MAX; + if (this._frameTweenEasing != locTWEEN_EASING_MAX) { + tweenType = (this._tweenEasing == locTWEEN_EASING_MAX) ? this._frameTweenEasing : this._tweenEasing; + if (tweenType != locTWEEN_EASING_MAX&&tweenType != cc.TweenType.Linear) { currentPercent = cc.TweenFunction.tweenTo(0, 1, currentPercent, 1, tweenType); } } diff --git a/extensions/CCArmature/datas/CCDatas.js b/extensions/CocoStudio/Armature/datas/CCDatas.js similarity index 80% rename from extensions/CCArmature/datas/CCDatas.js rename to extensions/CocoStudio/Armature/datas/CCDatas.js index 89522d39f6..3e5bd83cef 100644 --- a/extensions/CCArmature/datas/CCDatas.js +++ b/extensions/CocoStudio/Armature/datas/CCDatas.js @@ -22,11 +22,27 @@ THE SOFTWARE. ****************************************************************************/ +cc.BlendType = { + NORMAL: 0, + LAYER: 1, + DARKEN: 2, + MULTIPLY: 3, + LIGHTEN: 4, + SCREEN: 5, + OVERLAY: 6, + HARD_LIGHT: 7, + ADD: 8, + SUBSTRACT: 9, + DIFFERENCE: 10, + INVERT: 11, + ALPHA: 12, + ERASE: 13 +}; + CC_DISPLAY_SPRITE = 0; CC_DISPLAY_ARMATURE = 1; CC_DISPLAY_PARTICLE = 2; -CC_DISPLAY_SHADER = 3; -CC_DISPLAY_MAX = 1000; +CC_DISPLAY_MAX = 3; cc.BaseData = cc.Class.extend({ x:0, @@ -38,10 +54,10 @@ cc.BaseData = cc.Class.extend({ scaleY:1, tweenRotate:0, isUseColorInfo:false, - r:0, - g:0, - b:0, - a:0, + r:255, + g:255, + b:255, + a:255, ctor:function () { this.x = 0; @@ -73,6 +89,17 @@ cc.BaseData = cc.Class.extend({ this.a = node.a; }, + setColor:function(color){ + this.r = color.r; + this.g = color.g; + this.b = color.b; + this.a = color.a; + }, + + getColor:function(){ + return cc.c4f(this.r, this.g, this.b, this.a); + }, + subtract:function (from, to) { this.x = to.x - from.x; this.y = to.y - from.y; @@ -81,12 +108,15 @@ cc.BaseData = cc.Class.extend({ this.skewX = to.skewX - from.skewX; this.skewY = to.skewY - from.skewY; - if (from.isUseColorInfo || to.isUseColorInfo) { + if (this.isUseColorInfo || from.isUseColorInfo || to.isUseColorInfo) { this.a = to.a - from.a; this.r = to.r - from.r; this.g = to.g - from.g; this.b = to.b - from.b; - this._useColorInfo = true; + this.isUseColorInfo = true; + } else { + this.a = this.r = this.g = this.b = 0; + this.isUseColorInfo = false; } if (this.skewX > cc.PI) { @@ -112,7 +142,7 @@ cc.BaseData = cc.Class.extend({ cc.DisplayData = cc.Class.extend({ displayType:CC_DISPLAY_SPRITE, ctor:function () { - this.displayType = CC_DISPLAY_SPRITE; + this.displayType = CC_DISPLAY_MAX; }, changeDisplayToTexture:function (displayName) { // remove .xxx @@ -128,8 +158,10 @@ cc.DisplayData = cc.Class.extend({ cc.SpriteDisplayData = cc.DisplayData.extend({ displayName:"", + skinData:null, ctor:function () { this.displayName = ""; + this.skinData = new cc.BaseData(); this.displayType = CC_DISPLAY_SPRITE; }, setParam:function (displayName) { @@ -138,6 +170,21 @@ cc.SpriteDisplayData = cc.DisplayData.extend({ copy:function (displayData) { this.displayName = displayData.displayName; this.displayType = displayData.displayType; + this.skinData = displayData.skinData; + } +}); + +cc.NodeDisplayData = cc.DisplayData.extend({ + node:null, + ctor:function () { + this.displayName = ""; + this.displayType = CC_DISPLAY_NODE; + this.node = null; + }, + copy:function (displayData) { + this.displayName = displayData.displayName; + this.displayType = displayData.displayType; + this.node = displayData.node; } }); @@ -194,13 +241,15 @@ cc.ShaderDisplayData = cc.DisplayData.extend({ }); cc.BoneData = cc.BaseData.extend({ - displayDataList:[], + displayDataList:null, name:"", parentName:"", + boneDataTransform:null, ctor:function () { this.displayDataList = []; this.name = ""; this.parentName = ""; + this.boneDataTransform = null; }, init:function () { @@ -216,20 +265,19 @@ cc.BoneData = cc.BaseData.extend({ }); cc.ArmatureData = cc.Class.extend({ - boneDataDic:{}, - boneList:[], + boneDataDic:null, name:"", + dataVersion:0, ctor:function () { this.boneDataDic = {}; - this.boneList = []; this.name = ""; + this.dataVersion = 0; }, init:function () { - + return true; }, addBoneData:function (boneData) { this.boneDataDic[boneData.name] = boneData; - this.boneList.push(boneData); }, getBoneDataDic:function () { return this.boneDataDic; @@ -240,13 +288,15 @@ cc.ArmatureData = cc.Class.extend({ }); cc.FrameData = cc.BaseData.extend({ - duration:1, + duration:0, tweenEasing:0, - displayIndex:0, + displayIndex:-1, movement:"", event:"", sound:"", soundEffect:"", + blendType:0, + frameID:0, ctor:function () { cc.BaseData.prototype.ctor.call(this); @@ -257,6 +307,8 @@ cc.FrameData = cc.BaseData.extend({ this.event = ""; this.sound = ""; this.soundEffect = ""; + this.blendType = cc.BlendType.NORMAL; + this.frameID = 0; }, copy:function (frameData) { @@ -264,6 +316,11 @@ cc.FrameData = cc.BaseData.extend({ this.duration = frameData.duration; this.tweenEasing = frameData.tweenEasing; this.displayIndex = frameData.displayIndex; + this.movement = frameData.movement; + this.event = frameData.event; + this.sound = frameData.sound; + this.soundEffect = frameData.soundEffect; + this.blendType = frameData.blendType; } } ); @@ -272,7 +329,7 @@ cc.MovementBoneData = cc.Class.extend({ delay:0, scale:1, duration:0, - frameList:[], + frameList:null, name:"", ctor:function () { this.delay = 0; @@ -286,7 +343,6 @@ cc.MovementBoneData = cc.Class.extend({ }, addFrameData:function (frameData) { this.frameList.push(frameData); - this.duration += frameData.duration; }, getFrameData:function (index) { return this.frameList[index]; @@ -294,8 +350,9 @@ cc.MovementBoneData = cc.Class.extend({ }); cc.MovementData = cc.Class.extend({ - movBoneDataDic:{}, + movBoneDataDic:null, duration:0, + scale:0, durationTo:0, durationTween:cc.TweenType.Linear, loop:true, @@ -304,6 +361,7 @@ cc.MovementData = cc.Class.extend({ ctor:function () { this.name = ""; this.duration = 0; + this.scale = 1; this.durationTo = 0; this.durationTween = 0; this.loop = true; @@ -320,8 +378,8 @@ cc.MovementData = cc.Class.extend({ }); cc.AnimationData = cc.Class.extend({ - moveDataDic:{}, - movementNames:[], + moveDataDic:null, + movementNames:null, name:"", ctor:function () { this.moveDataDic = {}; @@ -345,13 +403,23 @@ cc.ContourVertex2 = function (x, y) { }; cc.ContourData = cc.Class.extend({ - vertexList:[], + vertexList:null, ctor:function () { this.vertexList = []; }, init:function () { this.vertexList = []; + return true; + }, + + /** + * + * @param {cc.p} p + */ + addVertex: function (p) { + var v = cc.ContourVertex2(p.x, p.y); + this.vertexList.push(v); } }); @@ -361,7 +429,7 @@ cc.TextureData = cc.Class.extend({ pivotX:0, pivotY:0, name:"", - contourDataList:[], + contourDataList:null, ctor:function () { this.height = 0; this.width = 0; diff --git a/extensions/CCArmature/display/CCBatchNode.js b/extensions/CocoStudio/Armature/display/CCBatchNode.js similarity index 100% rename from extensions/CCArmature/display/CCBatchNode.js rename to extensions/CocoStudio/Armature/display/CCBatchNode.js diff --git a/extensions/CCArmature/display/CCDecorativeDisplay.js b/extensions/CocoStudio/Armature/display/CCDecorativeDisplay.js similarity index 97% rename from extensions/CCArmature/display/CCDecorativeDisplay.js rename to extensions/CocoStudio/Armature/display/CCDecorativeDisplay.js index 9664f7b155..f2544159db 100644 --- a/extensions/CCArmature/display/CCDecorativeDisplay.js +++ b/extensions/CocoStudio/Armature/display/CCDecorativeDisplay.js @@ -34,12 +34,9 @@ cc.DecotativeDisplay = cc.Class.extend({ }, init:function () { - return true; }, - anchorPointChanged:function (pointX, pointY) { - }, setDisplay:function (display) { this._display = display; }, diff --git a/extensions/CCArmature/display/CCDisplayFactory.js b/extensions/CocoStudio/Armature/display/CCDisplayFactory.js similarity index 71% rename from extensions/CCArmature/display/CCDisplayFactory.js rename to extensions/CocoStudio/Armature/display/CCDisplayFactory.js index 46e2ea9fa9..9def225c85 100644 --- a/extensions/CCArmature/display/CCDisplayFactory.js +++ b/extensions/CocoStudio/Armature/display/CCDisplayFactory.js @@ -59,27 +59,34 @@ cc.DisplayFactory.updateDisplay = function (bone, decoDisplay, dt, dirty) { return; } - if (ENABLE_PHYSICS_DETECT) { + if (cc.ENABLE_PHYSICS_CHIPMUNK_DETECT) { if (dirty) { var detector = decoDisplay.getColliderDetector(); - if (detector) { - var t = cc.AffineTransformConcat(bone.nodeToArmatureTransform(), bone.getArmature().nodeToWorldTransform()); + if (detector&&detector.getBody()) { + var node = decoDisplay.getDisplay(); + var displayTransform = node.nodeToParentTransform(); + var anchorPoint = node.getAnchorPointInPoints(); + anchorPoint = cc.PointApplyAffineTransform(anchorPoint, displayTransform); + displayTransform.tx = anchorPoint.x; + displayTransform.ty = anchorPoint.y; + var t = cc.AffineTransformConcat(displayTransform, bone.getArmature().nodeToParentTransform()); detector.updateTransform(t); } } } - + var display = decoDisplay.getDisplay(); switch (decoDisplay.getDisplayData().displayType) { case CC_DISPLAY_SPRITE: - this.updateSpriteDisplay(bone, decoDisplay, dt, dirty); + this.updateSpriteDisplay(bone, display, dt, dirty); break; case CC_DISPLAY_PARTICLE: - this.updateParticleDisplay(bone, decoDisplay, dt, dirty); + this.updateParticleDisplay(bone, display, dt, dirty); break; case CC_DISPLAY_ARMATURE: - this.updateArmatureDisplay(bone, decoDisplay, dt, dirty); + this.updateArmatureDisplay(bone, display, dt, dirty); break; default: + display.setAdditionalTransform(bone.nodeToArmatureTransform()); break; } }; @@ -106,40 +113,46 @@ cc.DisplayFactory.createSpriteDisplay = function (bone, decoDisplay) { else { skin = cc.Skin.createWithSpriteFrameName(textureName + ".png"); } - /*var atlas = cc.SpriteFrameCacheHelper.getInstance().getTextureAtlas(textureName + ".png"); - skin.setTextureAtlas(atlas);*/ - //todo - /*var batchNode = cc.SpriteFrameCacheHelper.getInstance().getBatchNode(textureName + ".png"); + this.initSpriteDisplay(bone, decoDisplay, displayData.displayName, skin); + skin.setBone(bone); + var armature = bone.getArmature(); + if (armature) { + if (armature.getArmatureData().dataVersion >= cc.CONST_VERSION_COMBINED) + skin.setSkinData(displayData.skinData); + else + skin.setSkinData(bone.getBoneData()); + } - skin.setBatchNode(batchNode); - skin.setTextureAtlas(batchNode.getTextureAtlas());*/ + decoDisplay.setDisplay(skin); +}; +cc.DisplayFactory.initSpriteDisplay = function(bone, decoDisplay, displayName, skin){ + var textureName = displayName; + var startPos = textureName.lastIndexOf("."); + if (startPos != -1) { + textureName = textureName.substring(0, startPos); + } var textureData = cc.ArmatureDataManager.getInstance().getTextureData(textureName); if (textureData) { //! Init display anchorPoint, every Texture have a anchor point skin.setAnchorPoint(cc.p(textureData.pivotX, textureData.pivotY)); } - skin.setBone(bone); - skin.setSkinData(bone.getBoneData()); - decoDisplay.setDisplay(skin); - - if (ENABLE_PHYSICS_DETECT) { - if (textureData && textureData.contourDataList.count() > 0) { - - //! create ContourSprite + if (cc.ENABLE_PHYSICS_CHIPMUNK_DETECT) { + if (textureData && textureData.contourDataList.length > 0) { var colliderDetector = cc.ColliderDetector.create(bone); colliderDetector.addContourDataList(textureData.contourDataList); decoDisplay.setColliderDetector(colliderDetector); } } -}; +}, -cc.DisplayFactory.updateSpriteDisplay = function (bone, decoDisplay, dt, dirty) { - var skin = decoDisplay.getDisplay(); - skin.updateSelfTransform(); +cc.DisplayFactory.updateSpriteDisplay = function (bone, skin, dt, dirty) { + if(!dirty) + return; + skin.updateBlendType(bone.getBlendType()); + skin.updateArmatureTransform(); }; - cc.DisplayFactory.addArmatureDisplay = function (bone, decoDisplay, displayData) { var adp = new cc.ArmatureDisplayData(); adp.copy(displayData); @@ -157,11 +170,9 @@ cc.DisplayFactory.createArmatureDisplay = function (bone, decoDisplay) { armature.setName(bone.getName() + "_armatureChild"); decoDisplay.setDisplay(armature); }; -cc.DisplayFactory.updateArmatureDisplay = function (bone, decoDisplay, dt, dirty) { - if (!dirty) { +cc.DisplayFactory.updateArmatureDisplay = function (bone, armature, dt, dirty) { + if (!dirty) return; - } - var armature = bone.getChildArmature(); if (armature) { armature.sortAllChildren(); armature.update(dt); @@ -176,27 +187,14 @@ cc.DisplayFactory.addParticleDisplay = function (bone, decoDisplay, displayData) }; cc.DisplayFactory.createParticleDisplay = function (bone, decoDisplay) { var displayData = decoDisplay.getDisplayData(); - var system = cc.ParticleSystemQuad.create(displayData.plist); + var system = cc.ParticleSystem.create(displayData.plist); decoDisplay.setDisplay(system); }; -cc.DisplayFactory.updateParticleDisplay = function (bone, decoDisplay, dt, dirty) { - var system = decoDisplay.getDisplay(); +cc.DisplayFactory.updateParticleDisplay = function (bone, particleSystem, dt, dirty) { var node = new cc.BaseData(); cc.TransformHelp.matrixToNode(bone.nodeToArmatureTransform(), node); - system.setPosition(cc.p(node.x, node.y)); - system.setScaleX(node.scaleX); - system.setScaleY(node.scaleY); - system.update(dt); -}; - -cc.DisplayFactory.addShaderDisplay = function (bone, decoDisplay, displayData) { - var sdp = new cc.ShaderDisplayData(); - sdp.copy(displayData); - decoDisplay.setDisplayData(sdp); - this.createShaderDisplay(bone, decoDisplay); -}; -cc.DisplayFactory.createShaderDisplay = function (bone, decoDisplay) { - var displayData = decoDisplay.getDisplayData(); - var sn = cc.ShaderNode.shaderNodeWithVertex(displayData.vert, displayData.frag); - decoDisplay.setDisplay(sn); + particleSystem.setPosition(cc.p(node.x, node.y)); + particleSystem.setScaleX(node.scaleX); + particleSystem.setScaleY(node.scaleY); + particleSystem.update(dt); }; diff --git a/extensions/CCArmature/display/CCDisplayManager.js b/extensions/CocoStudio/Armature/display/CCDisplayManager.js similarity index 70% rename from extensions/CCArmature/display/CCDisplayManager.js rename to extensions/CocoStudio/Armature/display/CCDisplayManager.js index bb8b5615ef..55550f6655 100644 --- a/extensions/CCArmature/display/CCDisplayManager.js +++ b/extensions/CocoStudio/Armature/display/CCDisplayManager.js @@ -23,7 +23,7 @@ ****************************************************************************/ cc.DisplayManager = cc.Class.extend({ - _decoDisplayList:[], + _decoDisplayList:null, _currentDecoDisplay:null, _displayRenderNode:null, _displayIndex:-1, @@ -41,15 +41,13 @@ cc.DisplayManager = cc.Class.extend({ }, init:function (bone) { - this._bone = bone; this.initDisplayList(bone.getBoneData()); return true; }, - addDisplay:function (displayData, index) { + addDisplay: function (displayData, index) { var decoDisplay = null; - if (index >= 0 && index < this._decoDisplayList.length) { decoDisplay = this._decoDisplayList[index]; } @@ -58,7 +56,11 @@ cc.DisplayManager = cc.Class.extend({ this._decoDisplayList.push(decoDisplay); } - cc.DisplayFactory.addDisplay(this._bone, decoDisplay, displayData); + if(displayData instanceof cc.DisplayData){ + cc.DisplayFactory.addDisplay(this._bone, decoDisplay, displayData); + }else{ + this._addDisplayOther(decoDisplay,displayData); + } //! if changed display index is current display index, then change current display to the new display if (index == this._displayIndex) { @@ -67,67 +69,121 @@ cc.DisplayManager = cc.Class.extend({ } }, + _addDisplayOther:function(decoDisplay,display){ + var displayData = null; + if (display instanceof cc.Skin){ + var skin = display; + skin.setBone(this._bone); + displayData = new cc.SpriteDisplayData(); + cc.DisplayFactory.initSpriteDisplay(this._bone, decoDisplay, skin.getDisplayName(), skin); + var spriteDisplayData = decoDisplay.getDisplayData(); + if (spriteDisplayData instanceof cc.SpriteDisplayData) + skin.setSkinData(spriteDisplayData.skinData); + else + skin.setSkinData(new cc.BaseData()); + } + else if (display instanceof cc.ParticleSystem){ + displayData = new cc.ParticleDisplayData(); + } + else if (display instanceof cc.Armature){ + displayData = new cc.ArmatureDisplayData(); + display.setParentBone(this._bone); + } + else { + displayData = new cc.DisplayData(); + } + decoDisplay.setDisplay(display); + decoDisplay.setDisplayData(displayData); + }, + removeDisplay:function (index) { - cc.ArrayRemoveObjectAtIndex(this._decoDisplayList, index); + //cc.ArrayRemoveObjectAtIndex(this._decoDisplayList, index); + this._decoDisplayList[index] = null; if (index == this._displayIndex) { this.setCurrentDecorativeDisplay(null); } }, + getDecorativeDisplayList:function(){ + return this._decoDisplayList; + }, + changeDisplayByIndex:function (index, force) { - if (index < -1 || index > this._decoDisplayList.length) { + if (index >= this._decoDisplayList.length) { cc.log("the index value is out of range"); return; } + this._forceChangeDisplay = force; - //if index is equal to current display index,then do nothing - if (this._displayIndex == index) { - return; - } - this._displayIndex = index; + //this._displayIndex == -1, it means you want to hide you display - if (this._displayIndex < 0) { + if (index < 0) { + this._displayIndex = index; if (this._displayRenderNode) { this._displayRenderNode.removeFromParent(true); this.setCurrentDecorativeDisplay(null); + this._displayRenderNode = null; } return; } + + //if index is equal to current display index,then do nothing + if (this._displayIndex == index) { + return; + } + + this._displayIndex = index; + var decoDisplay = this._decoDisplayList[this._displayIndex]; + + if(!decoDisplay){ + return; + } + this.setCurrentDecorativeDisplay(decoDisplay); }, setCurrentDecorativeDisplay:function (decoDisplay) { - if (ENABLE_PHYSICS_DETECT) { - if (this._currentDecoDisplay && this._currentDecoDisplay.getColliderDetector()) { - this._currentDecoDisplay.getColliderDetector().setActive(false); + var locCurrentDecoDisplay = this._currentDecoDisplay; + if (cc.ENABLE_PHYSICS_CHIPMUNK_DETECT) { + if (locCurrentDecoDisplay && locCurrentDecoDisplay.getColliderDetector()) { + locCurrentDecoDisplay.getColliderDetector().setActive(false); } } this._currentDecoDisplay = decoDisplay; - - if (ENABLE_PHYSICS_DETECT) { - if (this._currentDecoDisplay && this._currentDecoDisplay.getColliderDetector()) { - this._currentDecoDisplay.getColliderDetector().setActive(true); + locCurrentDecoDisplay = this._currentDecoDisplay; + if (cc.ENABLE_PHYSICS_CHIPMUNK_DETECT) { + if (locCurrentDecoDisplay && locCurrentDecoDisplay.getColliderDetector()) { + locCurrentDecoDisplay.getColliderDetector().setActive(true); } } - var displayRenderNode = this._currentDecoDisplay == null ? null : this._currentDecoDisplay.getDisplay(); + var displayRenderNode = locCurrentDecoDisplay == null ? null : locCurrentDecoDisplay.getDisplay(); if (this._displayRenderNode) { if (this._displayRenderNode instanceof cc.Armature) { this._bone.setChildArmature(null); } this._displayRenderNode.removeFromParent(true); this._displayRenderNode.release(); + this._displayRenderNode = null; } this._displayRenderNode = displayRenderNode; - if (this._displayRenderNode) { - if (this._displayRenderNode instanceof cc.Armature) { - this._bone.setChildArmature(this._displayRenderNode); + if (displayRenderNode) { + if (displayRenderNode instanceof cc.Armature) { + this._bone.setChildArmature(displayRenderNode); + }else if(displayRenderNode instanceof cc.ParticleSystem) { + displayRenderNode.resetSystem(); + } + if (displayRenderNode.RGBAProtocol) { + //this._displayRenderNode.setColor(this._bone.getColor()); + //this._displayRenderNode.setOpacity(this._bone.getOpacity()); } - this._displayRenderNode.retain(); + displayRenderNode.retain(); + //todo + //this._displayRenderNode.setVisible(this._visible); } }, diff --git a/extensions/CCArmature/display/CCSkin.js b/extensions/CocoStudio/Armature/display/CCSkin.js similarity index 61% rename from extensions/CCArmature/display/CCSkin.js rename to extensions/CocoStudio/Armature/display/CCSkin.js index e6c8b0874f..421f2175f2 100644 --- a/extensions/CCArmature/display/CCSkin.js +++ b/extensions/CocoStudio/Armature/display/CCSkin.js @@ -25,27 +25,38 @@ cc.Skin = cc.Sprite.extend({ _skinData:null, _bone:null, - _skinTransform:cc.AffineTransformIdentity(), + _skinTransform:null, + _displayName:"", ctor:function () { cc.Sprite.prototype.ctor.call(this); this._skinData = null; this._bone = null; + this._displayName = ""; this._skinTransform = cc.AffineTransformIdentity(); }, - + initWithSpriteFrameName:function(spriteFrameName){ + var ret = cc.Sprite.prototype.initWithSpriteFrameName.call(this,spriteFrameName); + var atlas = cc.SpriteFrameCacheHelper.getInstance().getTexureAtlasWithTexture(this._texture); + this.setTextureAtlas(atlas); + this._displayName = spriteFrameName; + return ret; + }, + initWithFile:function(spriteFrameName){ + var ret = cc.Sprite.prototype.initWithFile.call(this,spriteFrameName); + var atlas = cc.SpriteFrameCacheHelper.getInstance().getTexureAtlasWithTexture(this._texture); + this.setTextureAtlas(atlas); + this._displayName = spriteFrameName; + return ret; + }, setSkinData:function (skinData) { this._skinData = skinData; - this.setScaleX(this._skinData.scaleX); - this.setScaleY(this._skinData.scaleY); - this.setRotation(cc.RADIANS_TO_DEGREES(this._skinData.skewX)); - this.setPosition(cc.p(this._skinData.x, this._skinData.y)); + this.setScaleX(skinData.scaleX); + this.setScaleY(skinData.scaleY); + this.setRotation(cc.RADIANS_TO_DEGREES(skinData.skewX)); + this.setPosition(skinData.x, skinData.y); this._skinTransform = this.nodeToParentTransform(); - if (cc.renderContextType === cc.CANVAS) { - this._skinTransform.b *= -1; - this._skinTransform.c *= -1; - } }, getSkinData:function () { @@ -60,12 +71,8 @@ cc.Skin = cc.Sprite.extend({ return this._bone; }, - updateSelfTransform:function () { + updateArmatureTransform:function () { this._transform = cc.AffineTransformConcat(this._skinTransform, this._bone.nodeToArmatureTransform()); - if (cc.renderContextType === cc.CANVAS) { - this._transform.b *= -1; - this._transform.c *= -1; - } }, /** returns a "local" axis aligned bounding box of the node.
* The returned box is relative only to its parent. @@ -74,12 +81,59 @@ cc.Skin = cc.Sprite.extend({ getBoundingBox:function () { var rect = cc.rect(0, 0, this._contentSize.width, this._contentSize.height); var transForm = this.nodeToParentTransform(); - if (cc.renderContextType === cc.CANVAS) { - transForm = {a:transForm.a, b:-transForm.b, c:-transForm.c, d:transForm.d, tx:transForm.tx, ty:transForm.ty}; - } return cc.RectApplyAffineTransform(rect, transForm); }, + /** + * display name getter + * @returns {String} + */ + getDisplayName:function(){ + return this._displayName; + }, + + nodeToWorldTransform: function () { + return cc.AffineTransformConcat(this._transform, this._bone.getArmature().nodeToWorldTransform()); + }, + + nodeToWorldTransformAR: function () { + var displayTransform = this._transform; + var anchorPoint = this._anchorPointInPoints; + + anchorPoint = cc.PointApplyAffineTransform(anchorPoint, displayTransform); + displayTransform.tx = anchorPoint.x; + displayTransform.ty = anchorPoint.y; + + return cc.AffineTransformConcat(displayTransform, this._bone.getArmature().nodeToWorldTransform()); + }, + /** + * update blendType + * @param {cc.BlendType} blendType + */ + updateBlendType: function (blendType) { + var blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST); + switch (blendType) { + case cc.BlendType.NORMAL: + blendFunc.src = cc.BLEND_SRC; + blendFunc.dst = cc.BLEND_DST; + break; + case cc.BlendType.ADD: + blendFunc.src = gl.SRC_ALPHA; + blendFunc.dst = gl.ONE; + break; + case cc.BlendType.MULTIPLY: + blendFunc.src = gl.ONE_MINUS_SRC_ALPHA; + blendFunc.dst = gl.ONE_MINUS_DST_COLOR; + break; + case cc.BlendType.SCREEN: + blendFunc.src = gl.ONE; + blendFunc.dst = gl.ONE_MINUS_DST_COLOR; + break; + default: + break; + } + this.setBlendFunc(blendFunc.src, blendFunc.dst); + }, updateQuad:function () { return; // If it is not visible, or one of its ancestors is not visible, then do nothing: @@ -131,17 +185,21 @@ cc.Skin = cc.Sprite.extend({ } }); -cc.Skin.create = function () { - var skin = new cc.Skin(); - if (skin && skin.init()) { - return skin; +cc.Skin.create = function (fileName, rect) { + var argnum = arguments.length; + var sprite = new cc.Skin(); + if (argnum === 0) { + if (sprite.init()) + return sprite; + } else { + if (sprite && sprite.initWithFile(fileName, rect)) + return sprite; } return null; }; cc.Skin.createWithSpriteFrameName = function (pszSpriteFrameName) { var skin = new cc.Skin(); - skin.testSpriteFrameName = pszSpriteFrameName; if (skin && skin.initWithSpriteFrameName(pszSpriteFrameName)) { return skin; } diff --git a/extensions/CocoStudio/Armature/physics/CCColliderDetector.js b/extensions/CocoStudio/Armature/physics/CCColliderDetector.js new file mode 100644 index 0000000000..00044399a2 --- /dev/null +++ b/extensions/CocoStudio/Armature/physics/CCColliderDetector.js @@ -0,0 +1,176 @@ +/**************************************************************************** + Copyright (c) 2010-2012 cocos2d-x.org + + 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.ColliderBody = cc.Class.extend({ + _shape: null, + _contourData: null, + ctor: function (contourData) { + this._contourData = contourData; + }, + getContourData: function () { + return this._contourData; + }, + setContourData: function (contourData) { + this._contourData = contourData; + }, + getShape: function () { + return this._shape; + }, + setShape: function (shage) { + this._shape = shage; + } +}); +cc.ColliderDetector = cc.Class.extend({ + _colliderBodyList: null, + _bone: null, + _body: null, + _active: false, + ctor: function () { + this._colliderBodyList = []; + }, + init: function (bone) { + this._colliderBodyList = []; + if (bone) + this._bone = bone; + return true; + }, + addContourData: function (contourData) { + var colliderBody = new cc.ColliderBody(contourData); + this._colliderBodyList.push(colliderBody); + }, + addContourDataList: function (contourDataList) { + for (var i = 0; i < contourDataList.length; i++) { + this.addContourData(contourDataList[i]); + } + }, + removeContourData: function (contourData) { + var locColliderBodyList = this._colliderBodyList; + for (var i = 0; i < locColliderBodyList.length; i++) { + if(locColliderBodyList[i].getContourData()==contourData){ + locColliderBodyList.splice(i, 1); + return; + } + } + }, + removeAll: function () { + this._colliderBodyList = []; + }, + + setColliderFilter: function (filter) { + + }, + setActive: function (active) { + if (this._active == active) + return; + this._active = active; + var locBody = this._body; + var locShape; + if (locBody) { + var colliderBody = null; + if (this._active) { + for (var i = 0; i < this._colliderBodyList.length; i++) { + colliderBody = this._colliderBodyList[i]; + locShape = colliderBody.getShape(); + locBody.space.addShape(locShape); + } + } + else { + for (var i = 0; i < this._colliderBodyList.length; i++) { + colliderBody = this._colliderBodyList[i]; + locShape = colliderBody.getShape(); + locBody.space.removeShape(locShape); + } + } + } + }, + getActive: function () { + return this._active; + }, + getColliderBodyList: function () { + return this._colliderBodyList; + }, + helpPoint: cc.p(0, 0), + updateTransform: function (t) { + if (!this._active) + return; + + var colliderBody = null; + var locBody = this._body; + var locHelpPoint = this.helpPoint; + for (var i = 0; i < this._colliderBodyList.length; i++) { + colliderBody = this._colliderBodyList[i]; + var contourData = colliderBody.getContourData(); + var shape = null; + if (locBody) { + shape = colliderBody.getShape(); + locBody.p.x = t.tx; + locBody.p.y = t.ty; + locBody.p.a = t.a; + var vs = contourData.vertexList; + for (var i = 0; i < vs.length; i++) { + locHelpPoint.x = vs[i].x; + locHelpPoint.y = vs[i].y; + locHelpPoint = cc.PointApplyAffineTransform(locHelpPoint, t); + if (shape) { + var v = new cp.Vect(0, 0); + v.x = locHelpPoint.x; + v.y = locHelpPoint.y; + shape.verts[i * 2] = locHelpPoint.x - t.tx; + shape.verts[i * 2 + 1] = locHelpPoint.y - t.ty; + } + } + } + } + }, + getBody: function () { + return this._body; + }, + setBody: function (body) { + this._body = body; + var colliderBody; + for (var i = 0; i < this._colliderBodyList.length; i++) { + colliderBody = this._colliderBodyList[i]; + var contourData = colliderBody.getContourData(); + var verts = []; + var vs = contourData.vertexList; + for (var i = 0; i < vs.length; i++) { + var v = vs[i]; + verts.push(v.x); + verts.push(v.y); + } + var shape = new cp.PolyShape(this._body, verts, cp.vzero); + shape.sensor = true; + shape.data = this._bone; + this._body.space.addShape(shape); + colliderBody.setShape(shape); + } + } +}); +cc.ColliderDetector.create = function (bone) { + var colliderDetector = new cc.ColliderDetector(); + if (colliderDetector && colliderDetector.init(bone)) { + return colliderDetector; + } + return null; +}; \ No newline at end of file diff --git a/extensions/CCArmature/utils/CCArmatureDefine.js b/extensions/CocoStudio/Armature/utils/CCArmatureDefine.js similarity index 86% rename from extensions/CCArmature/utils/CCArmatureDefine.js rename to extensions/CocoStudio/Armature/utils/CCArmatureDefine.js index 0927e06b15..baf3ae4cad 100644 --- a/extensions/CCArmature/utils/CCArmatureDefine.js +++ b/extensions/CocoStudio/Armature/utils/CCArmatureDefine.js @@ -25,4 +25,12 @@ cc.MAX_VERTEXZ_VALUE = 5000000.0; cc.ARMATURE_MAX_CHILD = 50.0; cc.ARMATURE_MAX_ZORDER = 100; -cc.ARMATURE_MAX_COUNT = ((cc.MAX_VERTEXZ_VALUE) / (cc.ARMATURE_MAX_CHILD) / cc.ARMATURE_MAX_ZORDER); \ No newline at end of file +cc.ARMATURE_MAX_COUNT = ((cc.MAX_VERTEXZ_VALUE) / (cc.ARMATURE_MAX_CHILD) / cc.ARMATURE_MAX_ZORDER); +cc.AUTO_ADD_SPRITE_FRAME_NAME_PREFIX = false; +cc.ENABLE_PHYSICS_CHIPMUNK_DETECT = true; + +cc.armatureVersion = function(){ + return "0.4.0.0"; +}; + +cc.RESOURCE_TYPE["TEXT"].push("ExportJson"); \ No newline at end of file diff --git a/extensions/CCArmature/utils/CCDataReaderHelper.js b/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.js similarity index 74% rename from extensions/CCArmature/utils/CCDataReaderHelper.js rename to extensions/CocoStudio/Armature/utils/CCDataReaderHelper.js index 4695d8a957..2da264a14d 100644 --- a/extensions/CCArmature/utils/CCDataReaderHelper.js +++ b/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.js @@ -24,6 +24,7 @@ cc.CONST_VERSION = "version"; cc.CONST_VERSION_2_0 = 2.0; +cc.CONST_VERSION_COMBINED = 0.3; cc.CONST_SKELETON = "skeleton"; cc.CONST_ARMATURES = "armatures"; @@ -41,6 +42,7 @@ cc.CONST_SUB_TEXTURE = "SubTexture"; cc.CONST_A_NAME = "name"; cc.CONST_A_DURATION = "dr"; +cc.CONST_A_FRAME_INDEX = "fi"; cc.CONST_A_DURATION_TO = "to"; cc.CONST_A_DURATION_TWEEN = "drTW"; cc.CONST_A_LOOP = "lp"; @@ -66,6 +68,7 @@ cc.CONST_A_TWEEN_ROTATE = "twR"; cc.CONST_A_IS_ARMATURE = "isArmature"; cc.CONST_A_DISPLAY_TYPE = "displayType"; cc.CONST_A_MOVEMENT = "mov"; +cc.CONST_A_BLEND_TYPE = "bd"; cc.CONST_A_X = "x"; cc.CONST_A_Y = "y"; @@ -107,6 +110,7 @@ cc.CONST_MOVEMENT_FRAME_DATA = "mov_frame_data"; cc.CONST_MOVEMENT_DATA = "mov_data"; cc.CONST_ANIMATION_DATA = "animation_data"; cc.CONST_DISPLAY_DATA = "display_data"; +cc.CONST_SKIN_DATA = "skin_data"; cc.CONST_BONE_DATA = "bone_data"; cc.CONST_ARMATURE_DATA = "armature_data"; cc.CONST_CONTOUR_DATA = "contour_data"; @@ -114,16 +118,16 @@ cc.CONST_TEXTURE_DATA = "texture_data"; cc.CONST_VERTEX_POINT = "vertex"; cc.CONST_COLOR_INFO = "color"; +cc.CONST_CONFIG_FILE_PATH = "config_file_path"; cc.DataReaderHelper = cc.DataReaderHelper || {}; cc.DataReaderHelper._configFileList = []; cc.DataReaderHelper._flashToolVersion = cc.CONST_VERSION_2_0; -cc.DataReaderHelper._XMLFileList = []; -cc.DataReaderHelper._armarureDatas = {}; -cc.DataReaderHelper._animationDatas = {}; -cc.DataReaderHelper._textureDatas = {}; -cc.DataReaderHelper._json = {}; +cc.DataReaderHelper._cocoStudioVersion = cc.CONST_VERSION_COMBINED; cc.DataReaderHelper._positionReadScale = 1; +cc.DataReaderHelper._basefilePath = ""; +cc.DataReaderHelper._asyncRefCount = 0; +cc.DataReaderHelper._asyncRefTotalCount = 0; cc.DataReaderHelper.setPositionReadScale = function (scale) { this._positionReadScale = scale; @@ -135,24 +139,74 @@ cc.DataReaderHelper.getPositionReadScale = function () { cc.DataReaderHelper.clear = function () { this._configFileList = []; + this._basefilePath = ""; + cc.DataReaderHelper._asyncRefCount = 0; + cc.DataReaderHelper._asyncRefTotalCount = 0; }; -cc.DataReaderHelper.addDataFromFile = function (filePath) { - if (cc.ArrayAppendObject(this._configFileList, filePath)) { +cc.DataReaderHelper.addDataFromFile = function (filePath,isLoadSpriteFrame) { + var fileUtils = cc.FileUtils.getInstance(); + var fullFilePath = fileUtils.fullPathForFilename(filePath); + + if (cc.ArrayContainsObject(this._configFileList, fullFilePath)) { return; } - this._configFileList.push(filePath); + this._configFileList.push(fullFilePath); + + this._initBaseFilePath(filePath); - var startPos = filePath.lastIndexOf("."); - var str = filePath.substring(startPos, filePath.length); + var startPos = fullFilePath.lastIndexOf("."); + var str = fullFilePath.substring(startPos, fullFilePath.length); if (str == ".xml") { - this.addDataFromXML(filePath); + this.addDataFromXML(fullFilePath); } else if (str == ".json" || str == ".ExportJson") { - this.addDataFromJson(filePath); + this.addDataFromJson(fullFilePath,isLoadSpriteFrame); + } +}; + +cc.DataReaderHelper.addDataFromFileAsync = function (filePath,target,selector,isLoadSpriteFrame) { + var fileUtils = cc.FileUtils.getInstance(); + var fullFilePath = fileUtils.fullPathForFilename(filePath); + + if (cc.ArrayContainsObject(this._configFileList, fullFilePath)) { + if (target && selector) { + if (this._asyncRefTotalCount == 0 && this._asyncRefCount == 0) + this._asyncCallBack(target, selector, 1); + else + this._asyncCallBack(target, selector, (this._asyncRefTotalCount - this._asyncRefCount) / this._asyncRefTotalCount); + } + return; } + this._asyncRefTotalCount++; + this._asyncRefCount++; + var self = this; + var fun = function () { + self.addDataFromFile(filePath,isLoadSpriteFrame); + self._asyncRefCount--; + self._asyncCallBack(target, selector, (self._asyncRefTotalCount - self._asyncRefCount) / self._asyncRefTotalCount); + }; + cc.Director.getInstance().getScheduler().scheduleCallbackForTarget(this, fun, 0.1, false); }; + +cc.DataReaderHelper._asyncCallBack=function (target, selector,percent) { + if (target && (typeof(selector) == "string")) { + target[selector](percent); + } else if (target && (typeof(selector) == "function")) { + selector.call(target,percent); + } +}; +cc.DataReaderHelper._initBaseFilePath = function(filePath){ + //! find the base file path + this._basefilePath = filePath; + var pos = this._basefilePath.lastIndexOf("/"); + if(pos>-1) + this._basefilePath = this._basefilePath.substr(0, pos + 1); + else + this._basefilePath = ""; +}; + cc.DataReaderHelper.addDataFromXML = function (xml) { /* * Need to get the full path of the xml file, or the Tiny XML can't find the xml at IOS @@ -218,19 +272,18 @@ cc.DataReaderHelper.decodeArmature = function (armatureXML) { return armatureData; }; -cc.DataReaderHelper.decodeBone = function (_boneXML, parentXML) { +cc.DataReaderHelper.decodeBone = function (boneXML, parentXML) { - var _name = _boneXML.getAttribute(cc.CONST_A_NAME); + var _name = boneXML.getAttribute(cc.CONST_A_NAME); if (_name == "") { return; } var boneData = new cc.BoneData(); - boneData.name = _name; + boneData.parentName = boneXML.getAttribute(cc.CONST_A_PARENT) || ""; + boneData.zOrder = parseInt(boneXML.getAttribute(cc.CONST_A_Z)) || 0; - boneData.parentName = _boneXML.getAttribute(cc.CONST_A_PARENT) || ""; - - var _displaysXML = _boneXML.querySelectorAll(cc.CONST_BONE + " > " + cc.CONST_DISPLAY); + var _displaysXML = boneXML.querySelectorAll(cc.CONST_BONE + " > " + cc.CONST_DISPLAY); var _displayXML for (var i = 0; i < _displaysXML.length; i++) { @@ -265,11 +318,7 @@ cc.DataReaderHelper.decodeBoneDisplay = function (_displayXML) { cc.DataReaderHelper.decodeAnimation = function (_animationXML) { var name = _animationXML.getAttribute(cc.CONST_A_NAME); - var aniData = this._animationDatas[name]; - if (aniData) { - return; - } - aniData = new cc.AnimationData(); + var aniData = new cc.AnimationData(); var _armatureData = cc.ArmatureDataManager.getInstance().getArmatureData(name); aniData.name = name; @@ -298,16 +347,16 @@ cc.DataReaderHelper.decodeMovement = function (movementXML, _armatureData) { durationTween = parseFloat(movementXML.getAttribute(cc.CONST_A_DURATION_TWEEN)) || 0; movementData.durationTween = durationTween; - loop = parseFloat(movementXML.getAttribute(cc.CONST_A_LOOP)) || 0; + loop = parseFloat(movementXML.getAttribute(cc.CONST_A_LOOP)) || 1; movementData.loop = Boolean(loop); var easing = movementXML.getAttribute(cc.CONST_A_TWEEN_EASING); if (easing) { if (easing != cc.CONST_FL_NAN) { - tweenEasing = parseFloat(movementXML.getAttribute(cc.CONST_A_TWEEN_EASING)) || 0; + tweenEasing = parseFloat(easing) || 0; movementData.tweenEasing = tweenEasing; } else { - movementData.tweenEasing = cc.TWEEN_EASING_MAX; + movementData.tweenEasing = cc.TweenType.TWEEN_EASING_MAX; } } @@ -390,9 +439,17 @@ cc.DataReaderHelper.decodeMovementBone = function (movBoneXml, parentXml, boneDa } var frameData = this.decodeFrame(frameXML, parentFrameXML, boneData, movBoneData); movBoneData.addFrameData(frameData); + frameData.frameID = totalDuration; totalDuration += frameData.duration; + movBoneData.duration = totalDuration; } - + //todo + /*if(movBoneData.frameList.length>0){ + var frameData = new cc.FrameData(); + frameData.copy(movBoneData.frameList[movBoneData.frameList.length-1]); + frameData.frameID = movBoneData.duration; + movBoneData.addFrameData(frameData); + }*/ return movBoneData; }; @@ -400,6 +457,7 @@ cc.DataReaderHelper.decodeFrame = function (frameXML, parentFrameXml, boneData, var frameData = new cc.FrameData(); frameData.movement = frameXML.getAttribute(cc.CONST_A_MOVEMENT) || ""; frameData.event = frameXML.getAttribute(cc.CONST_A_EVENT) || ""; + frameData.blendType = parseInt(frameXML.getAttribute(cc.CONST_A_BLEND_TYPE)) || cc.BlendType.NORMAL; frameData.sound = frameXML.getAttribute(cc.CONST_A_SOUND) || ""; frameData.soundEffect = frameXML.getAttribute(cc.CONST_A_SOUND_EFFECT) || ""; @@ -424,18 +482,30 @@ cc.DataReaderHelper.decodeFrame = function (frameXML, parentFrameXml, boneData, var colorTransformXMLList = frameXML.querySelectorAll(cc.CONST_FRAME + " > " + cc.CONST_A_COLOR_TRANSFORM); if (colorTransformXMLList.length > 0) { var colorTransformXML = colorTransformXMLList[0]; - var alpha, red, green, blue = 100; - var alphaOffset, redOffset, greenOffset, blueOffset = 0; + var alpha = red = green = blue = 0; + var alphaOffset = redOffset = greenOffset = blueOffset = 100; alpha = parseFloat(colorTransformXML.getAttribute(cc.CONST_A_ALPHA)) || alpha; red = parseFloat(colorTransformXML.getAttribute(cc.CONST_A_RED)) || red; green = parseFloat(colorTransformXML.getAttribute(cc.CONST_A_GREEN)) || green; blue = parseFloat(colorTransformXML.getAttribute(cc.CONST_A_BLUE)) || blue; - alphaOffset = parseFloat(colorTransformXML.getAttribute(cc.CONST_A_ALPHA_OFFSET)) || alphaOffset; - redOffset = parseFloat(colorTransformXML.getAttribute(cc.CONST_A_RED_OFFSET)) || redOffset; - greenOffset = parseFloat(colorTransformXML.getAttribute(cc.CONST_A_GREEN_OFFSET)) || greenOffset; - blueOffset = parseFloat(colorTransformXML.getAttribute(cc.CONST_A_BLUE_OFFSET)) || blueOffset; + var str_alphaOffset = colorTransformXML.getAttribute(cc.CONST_A_ALPHA_OFFSET); + if(str_alphaOffset){ + alphaOffset = parseFloat(str_alphaOffset); + } + var str_redOffset = colorTransformXML.getAttribute(cc.CONST_A_RED_OFFSET); + if(str_redOffset){ + redOffset = parseFloat(str_redOffset); + } + var str_greenOffset = colorTransformXML.getAttribute(cc.CONST_A_GREEN_OFFSET); + if(str_redOffset){ + greenOffset = parseFloat(str_greenOffset); + } + var str_blueOffset = colorTransformXML.getAttribute(cc.CONST_A_BLUE_OFFSET); + if(str_blueOffset){ + blueOffset = parseFloat(str_blueOffset); + } frameData.a = 2.55 * alphaOffset + alpha; frameData.r = 2.55 * redOffset + red; @@ -444,13 +514,16 @@ cc.DataReaderHelper.decodeFrame = function (frameXML, parentFrameXml, boneData, frameData.isUseColorInfo = true; } + if(frameData.displayIndex==-1){ + frameData.a = 0; + } var easing = frameXML.getAttribute(cc.CONST_A_TWEEN_EASING); if (easing) { if (easing != cc.CONST_FL_NAN) { - frameData.tweenEasing = parseFloat(frameXML.getAttribute(cc.CONST_A_TWEEN_EASING)) || 0; + frameData.tweenEasing = parseFloat(easing) || 0; } else { - frameData.tweenEasing = cc.TWEEN_EASING_MAX; + frameData.tweenEasing = cc.TweenType.TWEEN_EASING_MAX; } } @@ -522,33 +595,46 @@ cc.DataReaderHelper.decodeContour = function (contourXML) { }; -cc.DataReaderHelper.addDataFromJson = function (filePath) { +cc.DataReaderHelper.addDataFromJson = function (filePath,isLoadSpriteFrame) { var fileContent = cc.FileUtils.getInstance().getTextFileData(filePath); - this.addDataFromJsonCache(fileContent); + this.addDataFromJsonCache(fileContent,isLoadSpriteFrame); }; -cc.DataReaderHelper.addDataFromJsonCache = function (content) { +cc.DataReaderHelper.addDataFromJsonCache = function (content,isLoadSpriteFrame) { var dic = JSON.parse(content); - var armatureData = dic[cc.CONST_ARMATURE_DATA] || []; - for (var i = 0; i < armatureData.length; i++) { - var armatureDic = armatureData[i]; - var armatureData = this.decodeArmatureFromJSON(armatureDic); + var armatureDataArr = dic[cc.CONST_ARMATURE_DATA] || []; + var armatureData; + for (var i = 0; i < armatureDataArr.length; i++) { + armatureData = this.decodeArmatureFromJSON(armatureDataArr[i]); cc.ArmatureDataManager.getInstance().addArmatureData(armatureData.name, armatureData); } - var animationData = dic[cc.CONST_ANIMATION_DATA] || []; - for (var i = 0; i < animationData.length; i++) { - var animationDic = animationData[i]; - var animationData = this.decodeAnimationFromJson(animationDic); + var animationDataArr = dic[cc.CONST_ANIMATION_DATA] || []; + var animationData; + for (var i = 0; i < animationDataArr.length; i++) { + animationData = this.decodeAnimationFromJson(animationDataArr[i]); cc.ArmatureDataManager.getInstance().addAnimationData(animationData.name, animationData); } - var textData = dic[cc.CONST_TEXTURE_DATA] || []; - for (var i = 0; i < textData.length; i++) { - var textureDic = textData[i]; - var textureData = this.decodeTextureFromJson(textureDic); + var textureDataArr = dic[cc.CONST_TEXTURE_DATA] || []; + var textureData; + for (var i = 0; i < textureDataArr.length; i++) { + textureData = this.decodeTextureFromJson(textureDataArr[i]); cc.ArmatureDataManager.getInstance().addTextureData(textureData.name, textureData); } + if (isLoadSpriteFrame) { + var configFiles = dic[cc.CONST_CONFIG_FILE_PATH] || []; + var locFilePath, locPos, locPlistPath, locImagePath; + for (var i = 0; i < configFiles.length; i++) { + locFilePath = configFiles[i]; + locPos = locFilePath.lastIndexOf("."); + locFilePath = locFilePath.substring(0, locPos); + locPlistPath = this._basefilePath + locFilePath + ".plist"; + locImagePath = this._basefilePath + locFilePath + ".png"; + cc.ArmatureDataManager.getInstance().addSpriteFrameFromFile(locPlistPath, locImagePath); + } + } + armatureData = null; animationData = null; textData = null; @@ -562,6 +648,8 @@ cc.DataReaderHelper.decodeArmatureFromJSON = function (json) { armatureData.name = name; } + this._cocoStudioVersion = armatureData.dataVersion = json[cc.CONST_VERSION] || 0.1; + var boneDataList = json[cc.CONST_BONE_DATA]; for (var i = 0; i < boneDataList.length; i++) { armatureData.addBoneData(this.decodeBoneFromJson(boneDataList[i])); @@ -588,21 +676,26 @@ cc.DataReaderHelper.decodeBoneDisplayFromJson = function (json) { case CC_DISPLAY_SPRITE: displayData = new cc.SpriteDisplayData(); displayData.displayName = json[cc.CONST_A_NAME] || ""; + + var dicArray = json[cc.CONST_SKIN_DATA]|| []; + var dic = dicArray[0]; + if(dic){ + displayData.skinData.x = (dic[cc.CONST_A_X]|| 0) * this._positionReadScale; + displayData.skinData.y = (dic[cc.CONST_A_Y]||0) * this._positionReadScale; + displayData.skinData.scaleX = dic[cc.CONST_A_SCALE_X]|| 1; + displayData.skinData.scaleY = dic[cc.CONST_A_SCALE_Y]|| 1; + displayData.skinData.skewX = dic[cc.CONST_A_SKEW_X]|| 0; + displayData.skinData.skewY = dic[cc.CONST_A_SKEW_Y]||0; + dic = null; + } break; case CC_DISPLAY_ARMATURE: displayData = new cc.ArmatureDisplayData(); displayData.displayName = json[cc.CONST_A_NAME] || ""; break; case CC_DISPLAY_PARTICLE: - { displayData = new cc.ParticleDisplayData(); - displayData.plist = json[cc.CONST_A_PLIST] || ""; - } - break; - case CC_DISPLAY_SHADER: - displayData = new cc.ShaderDisplayData(); - displayData.vert = json[cc.CONST_A_VERT] || ""; - displayData.frag = json[cc.CONST_A_FRAG] || ""; + displayData.plist = this._basefilePath + json[cc.CONST_A_PLIST] || ""; break; default: displayData = new cc.SpriteDisplayData(); @@ -627,10 +720,11 @@ cc.DataReaderHelper.decodeAnimationFromJson = function (json) { cc.DataReaderHelper.decodeMovementFromJson = function (json) { var movementData = new cc.MovementData(); - movementData.loop = json[cc.CONST_A_LOOP] || true; + movementData.loop = json[cc.CONST_A_LOOP] || false; movementData.durationTween = json[cc.CONST_A_DURATION_TWEEN] || 0; movementData.durationTo = json[cc.CONST_A_DURATION_TO] || 0; movementData.duration = json[cc.CONST_A_DURATION] || 0; + movementData.scale = json[cc.CONST_A_MOVEMENT_SCALE] || 1; movementData.tweenEasing = json[cc.CONST_A_TWEEN_EASING] || cc.TweenType.Linear; movementData.name = json[cc.CONST_A_NAME] || ""; @@ -649,7 +743,20 @@ cc.DataReaderHelper.decodeMovementBoneFromJson = function (json) { movementBoneData.name = json[cc.CONST_A_NAME] || ""; var frameDataList = json[cc.CONST_FRAME_DATA] || []; for (var i = 0; i < frameDataList.length; i++) { - movementBoneData.addFrameData(this.decodeFrameFromJson(frameDataList[i])); + var frameData = this.decodeFrameFromJson(frameDataList[i]); + movementBoneData.addFrameData(frameData); + if (this._cocoStudioVersion < cc.CONST_VERSION_COMBINED) { + frameData.frameID = movementBoneData.duration; + movementBoneData.duration += frameData.duration; + } + } + if (this._cocoStudioVersion < cc.CONST_VERSION_COMBINED) { + if (movementBoneData.frameList.length > 0) { + var frameData = new cc.FrameData(); + frameData.copy(movementBoneData.frameList[movementBoneData.frameList.length - 1]); + movementBoneData.addFrameData(frameData); + frameData.frameID = movementBoneData.duration; + } } return movementBoneData; }; @@ -660,7 +767,12 @@ cc.DataReaderHelper.decodeFrameFromJson = function (json) { frameData.duration = json[cc.CONST_A_DURATION] || 1; frameData.tweenEasing = json[cc.CONST_A_TWEEN_EASING] || cc.TweenType.Linear; frameData.displayIndex = json[cc.CONST_A_DISPLAY_INDEX] || 0; - + frameData.blendType = json[cc.CONST_A_BLEND_TYPE] || 0; + frameData.event = json[cc.CONST_A_EVENT] || null; + if (this._cocoStudioVersion < cc.CONST_VERSION_COMBINED) + frameData.duration = json[cc.CONST_A_DURATION] || 1; + else + frameData.frameID = json[cc.CONST_A_FRAME_INDEX] || 0; return frameData; }; diff --git a/extensions/CCArmature/utils/CCSpriteFrameCacheHelper.js b/extensions/CocoStudio/Armature/utils/CCSpriteFrameCacheHelper.js similarity index 57% rename from extensions/CCArmature/utils/CCSpriteFrameCacheHelper.js rename to extensions/CocoStudio/Armature/utils/CCSpriteFrameCacheHelper.js index 905ddcd5f5..1e6e52d011 100644 --- a/extensions/CCArmature/utils/CCSpriteFrameCacheHelper.js +++ b/extensions/CocoStudio/Armature/utils/CCSpriteFrameCacheHelper.js @@ -23,47 +23,26 @@ ****************************************************************************/ cc.SpriteFrameCacheHelper = cc.Class.extend({ - _display2ImageMap:[], - _display2TextureAtlas:null, + _textureAtlasDic:null, _imagePaths:[], - _batchNodes:null, ctor:function () { - this._display2ImageMap = []; - this._display2TextureAtlas = {}; + this._textureAtlasDic = {}; this._imagePaths = []; - this._batchNodes = {}; }, addSpriteFrameFromFile:function (plistPath, imagePath) { - var dict = cc.FileUtils.getInstance().dictionaryWithContentsOfFileThreadSafe(plistPath); - var framesDict = dict["frames"]; - for (var key in framesDict) { - var spriteFrameName = key.toString(); - this._display2ImageMap[spriteFrameName] = imagePath; - } - dict = null; cc.SpriteFrameCache.getInstance().addSpriteFrames(plistPath, imagePath); }, - getDisplayImagePath:function (_displayName) { - return this._display2ImageMap[_displayName]; - }, - getTextureAtlas:function (displayName) { - var textureName = this.getDisplayImagePath(displayName); - var atlas = this._display2TextureAtlas[textureName]; + getTexureAtlasWithTexture:function (texture) { + //todo + return null; + var textureName = texture.getName(); + var atlas = this._textureAtlasDic[textureName]; if (atlas == null) { - atlas = cc.TextureAtlas.createWithTexture(cc.TextureCache.getInstance().addImage(textureName), 20); - this._display2TextureAtlas[textureName] = atlas; + atlas = cc.TextureAtlas.createWithTexture(texture, 20); + this._textureAtlasDic[textureName] = atlas; } return atlas; - }, - getBatchNode:function (displayName) { - var textureName = this.getDisplayImagePath(displayName); - var batchNode = this._batchNodes[textureName]; - if (batchNode == null) { - var batchNode = cc.SpriteBatchNode.create(this._display2ImageMap[displayName], 40); - this._batchNodes[textureName] = batchNode; - } - return batchNode; } }); cc.SpriteFrameCacheHelper.getInstance = function () { diff --git a/extensions/CCArmature/utils/CCTransformHelp.js b/extensions/CocoStudio/Armature/utils/CCTransformHelp.js similarity index 90% rename from extensions/CCArmature/utils/CCTransformHelp.js rename to extensions/CocoStudio/Armature/utils/CCTransformHelp.js index d696354136..5cd4887b90 100644 --- a/extensions/CCArmature/utils/CCTransformHelp.js +++ b/extensions/CocoStudio/Armature/utils/CCTransformHelp.js @@ -54,7 +54,7 @@ cc.TransformHelp.nodeToMatrix = function (node, matrix) { matrix.a = node.scaleX * Math.cos(node.skewY); matrix.b = node.scaleX * Math.sin(node.skewY); matrix.c = node.scaleY * Math.sin(node.skewX); - matrix.d = node.scaleY * Math.cos(node.skewX); + matrix.d = node.scaleY * Math.cos(node.skewY); matrix.tx = node.x; matrix.ty = node.y; }; @@ -102,4 +102,18 @@ cc.TransformHelp.nodeConcat = function (target, source) { target.skewY += source.skewY; target.scaleX += source.scaleX; target.scaleY += source.scaleY; +}; + +/** + * @function + * @param {cc.BaseData} target + * @param {cc.BaseData} source + */ +cc.TransformHelp.nodeSub = function (target, source) { + target.x -= source.x; + target.y -= source.y; + target.skewX -= source.skewX; + target.skewY -= source.skewY; + target.scaleX -= source.scaleX; + target.scaleY -= source.scaleY; }; \ No newline at end of file diff --git a/extensions/CCArmature/utils/CCTweenFunction.js b/extensions/CocoStudio/Armature/utils/CCTweenFunction.js similarity index 100% rename from extensions/CCArmature/utils/CCTweenFunction.js rename to extensions/CocoStudio/Armature/utils/CCTweenFunction.js diff --git a/extensions/CCArmature/utils/CCUtilMath.js b/extensions/CocoStudio/Armature/utils/CCUtilMath.js similarity index 100% rename from extensions/CCArmature/utils/CCUtilMath.js rename to extensions/CocoStudio/Armature/utils/CCUtilMath.js diff --git a/extensions/CCArmature/utils/CSArmatureDataManager.js b/extensions/CocoStudio/Armature/utils/CSArmatureDataManager.js similarity index 61% rename from extensions/CCArmature/utils/CSArmatureDataManager.js rename to extensions/CocoStudio/Armature/utils/CSArmatureDataManager.js index 33d2e33ec8..69406e93c0 100644 --- a/extensions/CCArmature/utils/CSArmatureDataManager.js +++ b/extensions/CocoStudio/Armature/utils/CSArmatureDataManager.js @@ -51,6 +51,15 @@ cc.ArmatureDataManager = cc.Class.extend({ } }, + /** + * remove armature data + * @param {string} id + */ + removeArmatureData:function(id){ + if (this._armarureDatas.hasOwnProperty(id)) + delete this._armarureDatas[id]; + }, + /** * get armatureData by id * @param {String} id @@ -64,6 +73,14 @@ cc.ArmatureDataManager = cc.Class.extend({ return armatureData; }, + /** + * get armatureDatas + * @return {Object} + */ + getArmatureDatas:function () { + return this._armarureDatas; + }, + /** * add animation data * @param {String} id @@ -75,6 +92,15 @@ cc.ArmatureDataManager = cc.Class.extend({ } }, + /** + * remove animation data + * @param {string} id + */ + removeAnimationData:function(id){ + if (this._animationDatas.hasOwnProperty(id)) + delete this._animationDatas[id]; + }, + /** * get animationData by id * @param {String} id @@ -88,6 +114,14 @@ cc.ArmatureDataManager = cc.Class.extend({ return animationData; }, + /** + * get animationDatas + * @return {Object} + */ + getAnimationDatas:function () { + return this._animationDatas; + }, + /** * add texture data * @param {String} id @@ -100,7 +134,16 @@ cc.ArmatureDataManager = cc.Class.extend({ }, /** - * get animationData by id + * remove texture data + * @param {string} id + */ + removeTextureData:function(id){ + if (this._textureDatas.hasOwnProperty(id)) + delete this._textureDatas[id]; + }, + + /** + * get textureData by id * @param {String} id * @return {cc.TextureData} */ @@ -112,15 +155,62 @@ cc.ArmatureDataManager = cc.Class.extend({ return textureData; }, + /** + * get textureDatas + * @return {Object} + */ + getTextureDatas:function () { + return this._textureDatas; + }, + + /** + * Add ArmatureFileInfo, it is managed by CCArmatureDataManager. + * @param {String} imagePath + * @param {String} plistPath + * @param {String} configFilePath + */ + addArmatureFileInfo:function (/*imagePath,plistPath,configFilePath*/) { + var imagePath,plistPath,configFilePath; + var isLoadSpriteFrame = false; + if (arguments.length == 1) { + configFilePath = arguments[0]; + isLoadSpriteFrame = true; + } else if (arguments.length == 3){ + imagePath = arguments[0]; + plistPath = arguments[1]; + configFilePath = arguments[2]; + this.addSpriteFrameFromFile(plistPath, imagePath); + } + cc.DataReaderHelper.addDataFromFile(configFilePath,isLoadSpriteFrame); + }, + /** * Add ArmatureFileInfo, it is managed by CCArmatureDataManager. * @param {String} imagePath * @param {String} plistPath * @param {String} configFilePath + * @param {Object} target + * @param {Function} configFilePath */ - addArmatureFileInfo:function (imagePath, plistPath, configFilePath) { - cc.DataReaderHelper.addDataFromFile(configFilePath); - this.addSpriteFrameFromFile(plistPath, imagePath); + addArmatureFileInfoAsync:function (/*imagePath, plistPath, configFilePath,target,selector*/) { + var imagePath, plistPath, configFilePath,target,selector; + var isLoadSpriteFrame = false; + if (arguments.length == 3) { + configFilePath = arguments[0]; + target = arguments[1]; + selector = arguments[2]; + isLoadSpriteFrame = true; + } else if (arguments.length == 5){ + imagePath = arguments[0]; + plistPath = arguments[1]; + configFilePath = arguments[2]; + target = arguments[3]; + selector = arguments[4]; + this.addSpriteFrameFromFile(plistPath, imagePath); + } + + cc.DataReaderHelper.addDataFromFileAsync(configFilePath,target,selector,isLoadSpriteFrame); + }, /** @@ -150,6 +240,6 @@ cc.ArmatureDataManager.getInstance = function () { }; cc.ArmatureDataManager.purge = function () { cc.SpriteFrameCacheHelper.purge(); - cc.PhysicsWorld.purge(); + cc.DataReaderHelper.clear(); this._instance = null; }; \ No newline at end of file diff --git a/extensions/GUI/CCControlExtension/CCControl.js b/extensions/GUI/CCControlExtension/CCControl.js index 3acede8898..9a1a837939 100644 --- a/extensions/GUI/CCControlExtension/CCControl.js +++ b/extensions/GUI/CCControlExtension/CCControl.js @@ -1,4 +1,4 @@ -/* +/** * * Copyright (c) 2010-2012 cocos2d-x.org * Copyright 2011 Yannick Loriot. @@ -69,11 +69,10 @@ cc.Control = cc.LayerRGBA.extend({ this._isOpacityModifyRGB = opacityModifyRGB; var children = this.getChildren(); - for (var i = 0; i < children.length; i++) { + for (var i = 0, len = children.length; i < len; i++) { var selNode = children[i]; - if (selNode && selNode.RGBAProtocol) { + if (selNode && selNode.RGBAProtocol) selNode.setOpacityModifyRGB(opacityModifyRGB); - } } }, @@ -87,7 +86,7 @@ cc.Control = cc.LayerRGBA.extend({ _selected:false, _highlighted:false, - _dispatchTable:{}, + _dispatchTable:null, /** * Tells whether the control is enabled @@ -95,11 +94,7 @@ cc.Control = cc.LayerRGBA.extend({ */ setEnabled:function (enabled) { this._enabled = enabled; - if (this._enabled) { - this._state = cc.CONTROL_STATE_NORMAL; - } else { - this._state = cc.CONTROL_STATE_DISABLED; - } + this._state = enabled ? cc.CONTROL_STATE_NORMAL:cc.CONTROL_STATE_DISABLED; this.needsLayout(); }, @@ -134,21 +129,20 @@ cc.Control = cc.LayerRGBA.extend({ hasVisibleParents:function () { var parent = this.getParent(); for (var c = parent; c != null; c = c.getParent()) { - if (!c.isVisible()) { + if (!c.isVisible()) return false; - } } return true; }, ctor:function () { - this._super(); + cc.LayerRGBA.prototype.ctor.call(this); this._dispatchTable = {}; this._color = cc.white(); }, init:function () { - if (this._super()) { + if (cc.LayerRGBA.prototype.init.call(this)) { //this.setTouchEnabled(true); //m_bIsTouchEnabled=true; // Initialise instance variables @@ -161,7 +155,7 @@ cc.Control = cc.LayerRGBA.extend({ this._defaultTouchPriority = 1; this.setTouchPriority(1); // Initialise the tables - this._dispatchTable = {}; + //this._dispatchTable = {}; //dispatchTable.autorelease(); // dispatchTable_ = [[NSMutableDictionary alloc] initWithCapacity:1]; return true; @@ -169,30 +163,24 @@ cc.Control = cc.LayerRGBA.extend({ return false; }, - onEnter:function () { - this._super(); - }, - onExit:function () { - this._super(); - }, registerWithTouchDispatcher:function () { - cc.Director.getInstance().getTouchDispatcher().addTargetedDelegate(this, cc.MENU_HANDLER_PRIORITY, true); + cc.registerTargetedDelegate(this.getTouchPriority(), true, this); }, /** * Sends action messages for the given control events. * which action messages are sent. See "CCControlEvent" for bitmask constants. - * @param controlEvents A bitmask whose set flags specify the control events for + * @param {Number} controlEvents A bitmask whose set flags specify the control events for */ sendActionsForControlEvents:function (controlEvents) { // For each control events - for (var i = 0; i < cc.CONTROL_EVENT_TOTAL_NUMBER; i++) { + for (var i = 0, len = cc.CONTROL_EVENT_TOTAL_NUMBER; i < len; i++) { // If the given controlEvents bitmask contains the curent event if ((controlEvents & (1 << i))) { // Call invocations // var invocationList = this._dispatchListforControlEvent(1 << i); - for (var j = 0; j < invocationList.length; j++) { + for (var j = 0, inLen = invocationList.length; j < inLen; j++) { invocationList[j].invoke(this); } } @@ -200,69 +188,57 @@ cc.Control = cc.LayerRGBA.extend({ }, /** - * Adds a target and action for a particular event (or events) to an internal - * dispatch table. - * The action message may optionnaly include the sender and the event as - * parameters, in that order. + *

+ * Adds a target and action for a particular event (or events) to an internal
+ * dispatch table.
+ * The action message may optionally include the sender and the event as
+ * parameters, in that order.
* When you call this method, target is not retained. - * - * @param target The target objectæą©hat is, the object to which the action - * message is sent. It cannot be nil. The target is not retained. - * @param action A selector identifying an action message. It cannot be NULL. - * @param controlEvents A bitmask specifying the control events for which the - * action message is sent. See "CCControlEvent" for bitmask constants. + *

+ * @param {Object} target The target object that is, the object to which the action message is sent. It cannot be nil. The target is not retained. + * @param {function} action A selector identifying an action message. It cannot be NULL. + * @param {Number} controlEvents A bitmask specifying the control events for which the action message is sent. See "CCControlEvent" for bitmask constants. */ addTargetWithActionForControlEvents:function (target, action, controlEvents) { // For each control events - for (var i = 0; i < cc.CONTROL_EVENT_TOTAL_NUMBER; i++) { - // If the given controlEvents bitmask contains the curent event - if ((controlEvents & (1 << i))) { - this.addTargetWithActionForControlEvent(target, action, 1 << i); - } + for (var i = 0, len = cc.CONTROL_EVENT_TOTAL_NUMBER; i < len; i++) { + // If the given controlEvents bit mask contains the current event + if ((controlEvents & (1 << i))) + this._addTargetWithActionForControlEvent(target, action, 1 << i); } }, /** - * Removes a target and action for a particular event (or events) from an - * internal dispatch table. + * Removes a target and action for a particular event (or events) from an internal dispatch table. * - * @param target The target objectæą©hat is, the object to which the action - * message is sent. Pass nil to remove all targets paired with action and the - * specified control events. - * @param action A selector identifying an action message. Pass NULL to remove - * all action messages paired with target. - * @param controlEvents A bitmask specifying the control events associated with - * target and action. See "CCControlEvent" for bitmask constants. + * @param {Object} target The target object that is, the object to which the action message is sent. Pass nil to remove all targets paired with action and the specified control events. + * @param {function} action A selector identifying an action message. Pass NULL to remove all action messages paired with target. + * @param {Number} controlEvents A bitmask specifying the control events associated with target and action. See "CCControlEvent" for bitmask constants. */ removeTargetWithActionForControlEvents:function (target, action, controlEvents) { // For each control events - for (var i = 0; i < cc.CONTROL_EVENT_TOTAL_NUMBER; i++) { - // If the given controlEvents bitmask contains the curent event - if ((controlEvents & (1 << i))) { + for (var i = 0, len = cc.CONTROL_EVENT_TOTAL_NUMBER; i < len; i++) { + // If the given controlEvents bitmask contains the current event + if ((controlEvents & (1 << i))) this.removeTargetWithActionForControlEvent(target, action, 1 << i); - } } }, /** * Returns a point corresponding to the touh location converted into the * control space coordinates. - * @param touch A CCTouch object that represents a touch. + * @param {cc.Touch} touch A CCTouch object that represents a touch. */ getTouchLocation:function (touch) { var touchLocation = touch.getLocation(); // Get the touch position - touchLocation = this.convertToNodeSpace(touchLocation); // Convert to the node space of this class - - return touchLocation; + return this.convertToNodeSpace(touchLocation); // Convert to the node space of this class }, /** - * Returns a boolean value that indicates whether a touch is inside the bounds - * of the receiver. The given touch must be relative to the world. - * - * @param touch A CCTouch object that represents a touch. + * Returns a boolean value that indicates whether a touch is inside the bounds of the receiver. The given touch must be relative to the world. * - * @return YES whether a touch is inside the receiveræŠŻ rect. + * @param {cc.Touch} touch A cc.Touch object that represents a touch. + * @return {Boolean} YES whether a touch is inside the receiver's rect. */ isTouchInside:function (touch) { var touchLocation = touch.getLocation(); // Get the touch position @@ -271,57 +247,49 @@ cc.Control = cc.LayerRGBA.extend({ }, /** - * Returns an CCInvocation object able to construct messages using a given - * target-action pair. (The invocation may optionnaly include the sender and + *

+ * Returns an cc.Invocation object able to construct messages using a given
+ * target-action pair. (The invocation may optionally include the sender and
* the event as parameters, in that order) + *

+ * @param {Object} target The target object. + * @param {function} action A selector identifying an action message. + * @param {Number} controlEvent A control events for which the action message is sent. See "CCControlEvent" for constants. * - * @param target The target object. - * @param action A selector identifying an action message. - * @param controlEvent A control events for which the action message is sent. - * See "CCControlEvent" for constants. - * - * @return an CCInvocation object able to construct messages using a given - * target-action pair. + * @return {cc.Invocation} an CCInvocation object able to construct messages using a given target-action pair. */ _invocationWithTargetAndActionForControlEvent:function (target, action, controlEvent) { + return null; }, /** - * Returns the CCInvocation list for the given control event. If the list does - * not exist, it'll create an empty array before returning it. - * - * @param controlEvent A control events for which the action message is sent. - * See "CCControlEvent" for constants. + * Returns the cc.Invocation list for the given control event. If the list does not exist, it'll create an empty array before returning it. * - * @return the CCInvocation list for the given control event. + * @param {Number} controlEvent A control events for which the action message is sent. See "CCControlEvent" for constants. + * @return {cc.Invocation} the cc.Invocation list for the given control event. */ _dispatchListforControlEvent:function (controlEvent) { controlEvent = controlEvent.toString(); - if (this._dispatchTable.hasOwnProperty(controlEvent)) - return this._dispatchTable[controlEvent]; - // If the invocation list does not exist for the dispatch table, we create it - - var invocationList = []; - this._dispatchTable[controlEvent] = invocationList; - - return invocationList; + if (!this._dispatchTable.hasOwnProperty(controlEvent)) + this._dispatchTable[controlEvent] = []; + return this._dispatchTable[controlEvent]; }, /** * Adds a target and action for a particular event to an internal dispatch * table. - * The action message may optionnaly include the sender and the event as + * The action message may optionally include the sender and the event as * parameters, in that order. * When you call this method, target is not retained. * - * @param target The target objectæą©hat is, the object to which the action + * @param target The target object that is, the object to which the action * message is sent. It cannot be nil. The target is not retained. * @param action A selector identifying an action message. It cannot be NULL. * @param controlEvent A control event for which the action message is sent. * See "CCControlEvent" for constants. */ - addTargetWithActionForControlEvent:function (target, action, controlEvent) { + _addTargetWithActionForControlEvent:function (target, action, controlEvent) { // Create the invocation object var invocation = new cc.Invocation(target, action, controlEvent); @@ -331,16 +299,11 @@ cc.Control = cc.LayerRGBA.extend({ }, /** - * Removes a target and action for a particular event from an internal dispatch - * table. + * Removes a target and action for a particular event from an internal dispatch table. * - * @param target The target objectæą©hat is, the object to which the action - * message is sent. Pass nil to remove all targets paired with action and the - * specified control events. - * @param action A selector identifying an action message. Pass NULL to remove - * all action messages paired with target. - * @param controlEvent A control event for which the action message is sent. - * See "CCControlEvent" for constants. + * @param {Object} target The target object that is, the object to which the action message is sent. Pass nil to remove all targets paired with action and the specified control events. + * @param {function} action A selector identifying an action message. Pass NULL to remove all action messages paired with target. + * @param {Number} controlEvent A control event for which the action message is sent. See "CCControlEvent" for constants. */ removeTargetWithActionForControlEvent:function (target, action, controlEvent) { // Retrieve all invocations for the given control event @@ -373,7 +336,6 @@ cc.Control = cc.LayerRGBA.extend({ * Updates the control layout using its current internal state. */ needsLayout:function () { - } }); diff --git a/extensions/GUI/CCControlExtension/CCControlButton.js b/extensions/GUI/CCControlExtension/CCControlButton.js index 159996cf82..e57fcf0ec4 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.js +++ b/extensions/GUI/CCControlExtension/CCControlButton.js @@ -1,4 +1,4 @@ -/* +/** * CCControlButton.m * * Copyright (c) 2010-2012 cocos2d-x.org @@ -28,16 +28,16 @@ cc.CONTROL_ZOOM_ACTION_TAG = 0xCCCB0001; /** @class CCControlButton Button control for Cocos2D. */ cc.ControlButton = cc.Control.extend({ - _adjustBackgroundImage:false, + _doesAdjustBackgroundImage:false, _zoomOnTouchDown:false, - _preferredSize:new cc.Size(0, 0), - _labelAnchorPoint:new cc.Point(0, 0), - _currentTitle:"", - _currentTitleColor:cc.white(), + _preferredSize: null, + _labelAnchorPoint: null, + _currentTitle: null, + _currentTitleColor: null, _titleLabel:null, _backgroundSprite:null, _opacity:0, - _pushed:false, + _isPushed:false, _titleDispatchTable:null, _titleColorDispatchTable:null, _titleLabelDispatchTable:null, @@ -48,10 +48,10 @@ cc.ControlButton = cc.Control.extend({ _marginH:0, ctor:function () { - this._super(); + cc.Control.prototype.ctor.call(this); this._preferredSize = new cc.Size(0, 0); this._labelAnchorPoint = new cc.Point(0, 0); - + this._currentTitle = ""; this._currentTitleColor = cc.white(); this._titleDispatchTable = {}; this._titleColorDispatchTable = {}; @@ -60,7 +60,7 @@ cc.ControlButton = cc.Control.extend({ }, init:function () { - return this.initWithLabelAndBackgroundSprite(cc.LabelTTF.create("", "Helvetica", 12), cc.Scale9Sprite.create()); + return this.initWithLabelAndBackgroundSprite(cc.LabelTTF.create("", "Arial", 12), cc.Scale9Sprite.create()); }, needsLayout:function () { @@ -68,63 +68,74 @@ cc.ControlButton = cc.Control.extend({ return; } // Hide the background and the label - this._titleLabel.setVisible(false); - this._backgroundSprite.setVisible(false); + if(this._titleLabel) + this._titleLabel.setVisible(false); + if(this._backgroundSprite) + this._backgroundSprite.setVisible(false); // Update anchor of all labels this.setLabelAnchorPoint(this._labelAnchorPoint); // Update the label to match with the current state //CC_SAFE_RELEASE(this._currentTitle) + var locState = this._state; - this._currentTitle = this.getTitleForState(this._state); - this._currentTitleColor = this.getTitleColorForState(this._state); - - this._titleLabel = this.getTitleLabelForState(this._state); + this._currentTitle = this.getTitleForState(locState); + this._currentTitleColor = this.getTitleColorForState(locState); + this._titleLabel = this.getTitleLabelForState(locState); var label = this._titleLabel; if (label && label.setString) label.setString(this._currentTitle); + if (label && label.RGBAProtocol) + label.setColor(this._currentTitleColor); - if (this._titleLabel && this._titleLabel.RGBAProtocol) - this._titleLabel.setColor(this._currentTitleColor); - this._titleLabel.setPosition(cc.p(this.getContentSize().width / 2, this.getContentSize().height / 2)); - + var locContentSize = this.getContentSize(); + if(label) + label.setPosition(locContentSize.width / 2, locContentSize.height / 2); // Update the background sprite - this._backgroundSprite = this.getBackgroundSpriteForState(this._state); - this._backgroundSprite.setPosition(cc.p(this.getContentSize().width / 2, this.getContentSize().height / 2)); + this._backgroundSprite = this.getBackgroundSpriteForState(locState); + var locBackgroundSprite = this._backgroundSprite; + if(locBackgroundSprite) + locBackgroundSprite.setPosition(locContentSize.width / 2, locContentSize.height / 2); // Get the title label size - var titleLabelSize = this._titleLabel.getBoundingBox().size; + var titleLabelSize = label ? label.getBoundingBox().size : cc.size(0, 0); // Adjust the background image if necessary - if (this._adjustBackgroundImage) { + if (this._doesAdjustBackgroundImage) { // Add the margins - this._backgroundSprite.setContentSize(cc.SizeMake(titleLabelSize.width + this._marginH * 2, titleLabelSize.height + this._marginV * 2)); + if(locBackgroundSprite) + locBackgroundSprite.setContentSize(cc.size(titleLabelSize.width + this._marginH * 2, titleLabelSize.height + this._marginV * 2)); } else { //TODO: should this also have margins if one of the preferred sizes is relaxed? - var preferredSize = this._backgroundSprite.getPreferredSize(); - if (preferredSize.width <= 0) { - preferredSize.width = titleLabelSize.width; + if(locBackgroundSprite){ + var preferredSize = locBackgroundSprite.getPreferredSize(); + preferredSize = cc.size(preferredSize.width, preferredSize.height); + if (preferredSize.width <= 0) + preferredSize.width = titleLabelSize.width; + if (preferredSize.height <= 0) + preferredSize.height = titleLabelSize.height; + + locBackgroundSprite.setContentSize(preferredSize); } - if (preferredSize.height <= 0) { - preferredSize.height = titleLabelSize.height; - } - - this._backgroundSprite.setContentSize(preferredSize); } // Set the content size - var maxRect = cc.ControlUtils.CCRectUnion(this._titleLabel.getBoundingBox(), this._backgroundSprite.getBoundingBox()); - this.setContentSize(cc.SizeMake(maxRect.width, maxRect.height)); - - this._titleLabel.setPosition(cc.p(this.getContentSize().width / 2, this.getContentSize().height / 2)); - this._backgroundSprite.setPosition(cc.p(this.getContentSize().width / 2, this.getContentSize().height / 2)); - - // Make visible the background and the label - this._titleLabel.setVisible(true); - this._backgroundSprite.setVisible(true); + var rectTitle = label? label.getBoundingBox():cc.rect(0,0,0,0); + var rectBackground = locBackgroundSprite? locBackgroundSprite.getBoundingBox():cc.rect(0,0,0,0); + var maxRect = cc.rectUnion(rectTitle, rectBackground); + this.setContentSize(cc.size(maxRect.width, maxRect.height)); + locContentSize = this.getContentSize(); + if(label){ + label.setPosition(locContentSize.width / 2, locContentSize.height / 2); + label.setVisible(true); + } + if(locBackgroundSprite){ + locBackgroundSprite.setPosition(locContentSize.width / 2, locContentSize.height / 2); + locBackgroundSprite.setVisible(true); + } }, initWithLabelAndBackgroundSprite:function (label, backgroundSprite) { @@ -132,15 +143,23 @@ cc.ControlButton = cc.Control.extend({ cc.Assert(label != null, "node must not be nil"); cc.Assert(label != null || label.RGBAProtocol || backgroundSprite != null, ""); - this.setTouchEnabled(true); - this._pushed = false; this._parentInited = true; + + // Initialize the button state tables + this._titleDispatchTable = {}; + this._titleColorDispatchTable = {}; + this._titleLabelDispatchTable = {}; + this._backgroundSpriteDispatchTable = {}; + + this.setTouchEnabled(true); + this._isPushed = false; this._zoomOnTouchDown = true; - this._state = cc.CONTROL_STATE_INITIAL; + this._currentTitle = null; // Adjust the background image by default - this._adjustBackgroundImage = true; + this.setAdjustBackgroundImage(true); + this.setPreferredSize(cc.size(0,0)); // Zooming button by default this._zoomOnTouchDown = true; @@ -153,15 +172,7 @@ cc.ControlButton = cc.Control.extend({ this._titleLabel = label; this._backgroundSprite = backgroundSprite; - - // Initialize the button state tables - this._titleDispatchTable = {}; - this._titleColorDispatchTable = {}; - this._titleLabelDispatchTable = {}; - this._backgroundSpriteDispatchTable = {}; - // Set the default color and opacity - this.setColor(cc.c3(255, 255, 255)); this.setOpacity(255); this.setOpacityModifyRGB(true); @@ -185,7 +196,6 @@ cc.ControlButton = cc.Control.extend({ // Layout update this.needsLayout(); - return true; }//couldn't init the CCControl else @@ -202,13 +212,16 @@ cc.ControlButton = cc.Control.extend({ return this.initWithLabelAndBackgroundSprite(label, sprite); }, - /** Adjust the background image. YES by default. If the property is set to NO, the - background will use the prefered size of the background image. */ - getAdjustBackgroundImage:function () { - return this._adjustBackgroundImage; + /** + * Adjust the background image. YES by default. If the property is set to NO, the background will use the prefered size of the background image. + * @return {Boolean} + */ + doesAdjustBackgroundImage:function () { + return this._doesAdjustBackgroundImage; }, + setAdjustBackgroundImage:function (adjustBackgroundImage) { - this._adjustBackgroundImage = adjustBackgroundImage; + this._doesAdjustBackgroundImage = adjustBackgroundImage; this.needsLayout(); }, @@ -216,6 +229,7 @@ cc.ControlButton = cc.Control.extend({ getZoomOnTouchDown:function () { return this._zoomOnTouchDown; }, + setZoomOnTouchDown:function (zoomOnTouchDown) { return this._zoomOnTouchDown = zoomOnTouchDown; }, @@ -226,13 +240,13 @@ cc.ControlButton = cc.Control.extend({ }, setPreferredSize:function (size) { - if (size.width == 0 && size.height == 0) { - this._adjustBackgroundImage = true; + if (size.width === 0 && size.height === 0) { + this._doesAdjustBackgroundImage = true; } else { - this._adjustBackgroundImage = false; - for (var itemKey in this._backgroundSpriteDispatchTable) { - this._backgroundSpriteDispatchTable[itemKey].setPreferredSize(size); - } + this._doesAdjustBackgroundImage = false; + var locTable = this._backgroundSpriteDispatchTable; + for (var itemKey in locTable) + locTable[itemKey].setPreferredSize(size); } this._preferredSize = size; this.needsLayout(); @@ -243,17 +257,20 @@ cc.ControlButton = cc.Control.extend({ }, setLabelAnchorPoint:function (labelAnchorPoint) { this._labelAnchorPoint = labelAnchorPoint; - - this._titleLabel.setAnchorPoint(labelAnchorPoint); + if(this._titleLabel) + this._titleLabel.setAnchorPoint(labelAnchorPoint); }, - /** The current title that is displayed on the button. */ - getCurrentTitle:function () { + /** + * The current title that is displayed on the button. + * @return {string} + */ + _getCurrentTitle:function () { return this._currentTitle; }, /** The current color used to display the title. */ - getCurrentTitleColor:function () { + _getCurrentTitleColor:function () { return this._currentTitleColor; }, @@ -263,45 +280,51 @@ cc.ControlButton = cc.Control.extend({ }, setOpacity:function (opacity) { - this._opacity = opacity; - + // XXX fixed me if not correct + cc.Control.prototype.setOpacity.call(opacity); + /*this._opacity = opacity; var controlChildren = this.getChildren(); - for (var i = 0; i < controlChildren.length; i++) { - if (controlChildren[i] && controlChildren[i].RGBAProtocol) { - controlChildren[i].setOpacity(opacity); - } - } - for (var itemKey in this._backgroundSpriteDispatchTable) { - this._backgroundSpriteDispatchTable[itemKey].setOpacity(opacity); - } + var selChild = controlChildren[i]; + if (selChild && selChild.RGBAProtocol) + selChild.setOpacity(opacity); + }*/ + var locTable = this._backgroundSpriteDispatchTable; + for (var itemKey in locTable) + locTable[itemKey].setOpacity(opacity); }, setColor:function(color){ cc.Control.prototype.setColor.call(this,color); - for(var key in this._backgroundSpriteDispatchTable){ - this._backgroundSpriteDispatchTable[key].setColor(color); - } + var locTable = this._backgroundSpriteDispatchTable; + for(var key in locTable) + locTable[key].setColor(color); }, getColor:function(){ return this._realColor; }, + /** Flag to know if the button is currently pushed. */ - getIsPushed:function () { - return this._pushed; + isPushed:function () { + return this._isPushed; }, /* Define the button margin for Top/Bottom edge */ - getVerticalMargin:function () { + _getVerticalMargin:function () { return this._marginV; }, /* Define the button margin for Left/Right edge */ - getHorizontalOrigin:function () { + _getHorizontalOrigin:function () { return this._marginH; }, - //set the margins at once (so we only have to do one call of needsLayout) + + /** + * set the margins at once (so we only have to do one call of needsLayout) + * @param {Number} marginH + * @param {Number} marginV + */ setMargins:function (marginH, marginV) { this._marginV = marginV; this._marginH = marginH; @@ -309,26 +332,22 @@ cc.ControlButton = cc.Control.extend({ }, setEnabled:function (enabled) { - this._super(enabled); + cc.Control.prototype.setEnabled.call(this, enabled); this.needsLayout(); }, setSelected:function (enabled) { - this._super(enabled); + cc.Control.prototype.setSelected.call(this, enabled); this.needsLayout(); }, setHighlighted:function (enabled) { - if (enabled == true) { - this._state = cc.CONTROL_STATE_HIGHLIGHTED; - } - else { - this._state = cc.CONTROL_STATE_NORMAL; - } - this._super(enabled); + this._state = enabled?cc.CONTROL_STATE_HIGHLIGHTED:cc.CONTROL_STATE_NORMAL; + + cc.Control.prototype.setHighlighted.call(this, enabled); var action = this.getActionByTag(cc.CONTROL_ZOOM_ACTION_TAG); - if (action) { + if (action) this.stopAction(action); - } + this.needsLayout(); if (this._zoomOnTouchDown) { var scaleValue = (this.isHighlighted() && this.isEnabled() && !this.isSelected()) ? 1.1 : 1.0; @@ -339,33 +358,29 @@ cc.ControlButton = cc.Control.extend({ }, onTouchBegan:function (touch, event) { - if (!this.isTouchInside(touch) || !this.isEnabled()|| !this.isVisible()||!this.hasVisibleParents()) { + if (!this.isTouchInside(touch) || !this.isEnabled()|| !this.isVisible()||!this.hasVisibleParents()) return false; - } - this._pushed = true; + this._isPushed = true; this.setHighlighted(true); this.sendActionsForControlEvents(cc.CONTROL_EVENT_TOUCH_DOWN); return true; }, onTouchMoved:function (touch, event) { - if (!this._enabled || !this._pushed || this._selected) { - if (this._highlighted) { + if (!this._enabled || !this._isPushed || this._selected) { + if (this._highlighted) this.setHighlighted(false); - } return; } var isTouchMoveInside = this.isTouchInside(touch); if (isTouchMoveInside && !this._highlighted) { - this._state = cc.CONTROL_STATE_HIGHLIGHTED; this.setHighlighted(true); this.sendActionsForControlEvents(cc.CONTROL_EVENT_TOUCH_DRAG_ENTER); } else if (isTouchMoveInside && this._highlighted) { this.sendActionsForControlEvents(cc.CONTROL_EVENT_TOUCH_DRAG_INSIDE); } else if (!isTouchMoveInside && this._highlighted) { - this._state = cc.CONTROL_STATE_NORMAL; this.setHighlighted(false); this.sendActionsForControlEvents(cc.CONTROL_EVENT_TOUCH_DRAG_EXIT); } else if (!isTouchMoveInside && !this._highlighted) { @@ -373,7 +388,7 @@ cc.ControlButton = cc.Control.extend({ } }, onTouchEnded:function (touch, event) { - this._pushed = false; + this._isPushed = false; this.setHighlighted(false); if (this.isTouchInside(touch)) { @@ -384,7 +399,7 @@ cc.ControlButton = cc.Control.extend({ }, onTouchCancelled:function (touch, event) { - this._pushed = false; + this._isPushed = false; this.setHighlighted(false); this.sendActionsForControlEvents(cc.CONTROL_EVENT_TOUCH_CANCEL); }, @@ -392,127 +407,110 @@ cc.ControlButton = cc.Control.extend({ /** * Returns the title used for a state. * - * @param state The state that uses the title. Possible values are described in - * "CCControlState". - * - * @return The title for the specified state. + * @param {Number} state The state that uses the title. Possible values are described in "CCControlState". + * @return {string} The title for the specified state. */ getTitleForState:function (state) { - if (this._titleDispatchTable) { - if (this._titleDispatchTable[state]) - return this._titleDispatchTable[state]; - return this._titleDispatchTable[cc.CONTROL_STATE_NORMAL]; + var locTable = this._titleDispatchTable; + if (locTable) { + if (locTable[state]) + return locTable[state]; + return locTable[cc.CONTROL_STATE_NORMAL]; } return ""; }, /** - * Sets the title string to use for the specified state. - * If a property is not specified for a state, the default is to use - * the CCButtonStateNormal value. - * - * @param title The title string to use for the specified state. - * @param state The state that uses the specified title. The values are described - * in "CCControlState". + *

+ * Sets the title string to use for the specified state.
+ * If a property is not specified for a state, the default is to use the CCButtonStateNormal value. + *

+ * @param {string} title The title string to use for the specified state. + * @param {Number} state The state that uses the specified title. The values are described in "CCControlState". */ setTitleForState:function (title, state) { - if (title) { - this._titleDispatchTable[state] = title; - } else { - this._titleDispatchTable[state] = ""; - } + this._titleDispatchTable[state] = title || ""; // If the current state if equal to the given state we update the layout - if (this.getState() == state) { + if (this.getState() == state) this.needsLayout(); - } }, /** * Returns the title color used for a state. * - * @param state The state that uses the specified color. The values are described - * in "CCControlState". - * - * @return The color of the title for the specified state. + * @param {Number} state The state that uses the specified color. The values are described in "CCControlState". + * @return {cc.Color3B} The color of the title for the specified state. */ - getTitleColorForState:function (state) { - var returnColor = cc.white(); - do { - var colorObject = this._titleColorDispatchTable[state]; - if (colorObject) { - returnColor = colorObject; - break; - } - colorObject = this._titleColorDispatchTable[cc.CONTROL_STATE_NORMAL]; - if (colorObject) { - returnColor = colorObject; - break; - } - - } while (0); - - return returnColor; + getTitleColorForState: function (state) { + var colorObject = this._titleColorDispatchTable[state]; + if (colorObject) + return colorObject; + colorObject = this._titleColorDispatchTable[cc.CONTROL_STATE_NORMAL]; + if (colorObject) + return colorObject; + return cc.white(); }, /** * Sets the color of the title to use for the specified state. * - * @param color The color of the title to use for the specified state. - * @param state The state that uses the specified color. The values are described - * in "CCControlState". + * @param {cc.Color3B} color The color of the title to use for the specified state. + * @param {Number} state The state that uses the specified color. The values are described in "CCControlState". */ setTitleColorForState:function (color, state) { //ccColor3B* colorValue=&color; this._titleColorDispatchTable[state] = color; // If the current state if equal to the given state we update the layout - if (this.getState() == state) { + if (this.getState() == state) this.needsLayout(); - } }, /** * Returns the title label used for a state. * - * @param state The state that uses the title label. Possible values are described - * in "CCControlState". + * @param state The state that uses the title label. Possible values are described in "CCControlState". + * @return {cc.Node} the title label used for a state. */ getTitleLabelForState:function (state) { - if (this._titleLabelDispatchTable.hasOwnProperty(state) && this._titleLabelDispatchTable[state]) { - return this._titleLabelDispatchTable[state]; - } - return this._titleLabelDispatchTable[cc.CONTROL_STATE_NORMAL]; + var locTable = this._titleLabelDispatchTable; + if (locTable.hasOwnProperty(state) && locTable[state]) + return locTable[state]; + + return locTable[cc.CONTROL_STATE_NORMAL]; }, /** - * Sets the title label to use for the specified state. - * If a property is not specified for a state, the default is to use - * the CCButtonStateNormal value. + *

Sets the title label to use for the specified state.
+ * If a property is not specified for a state, the default is to use the CCButtonStateNormal value.

* - * @param title The title label to use for the specified state. - * @param state The state that uses the specified title. The values are described - * in "CCControlState". + * @param {cc.Node} titleLabel The title label to use for the specified state. + * @param {Number} state The state that uses the specified title. The values are described in "CCControlState". */ setTitleLabelForState:function (titleLabel, state) { - if (this._titleLabelDispatchTable.hasOwnProperty(state)) { - var previousLabel = this._titleLabelDispatchTable[state]; - if (previousLabel) { + var locTable = this._titleLabelDispatchTable; + if (locTable.hasOwnProperty(state)) { + var previousLabel = locTable[state]; + if (previousLabel) this.removeChild(previousLabel, true); - } } - this._titleLabelDispatchTable[state] = titleLabel; + locTable[state] = titleLabel; titleLabel.setVisible(false); titleLabel.setAnchorPoint(cc.p(0.5, 0.5)); this.addChild(titleLabel, 1); // If the current state if equal to the given state we update the layout - if (this.getState() == state) { + if (this.getState() == state) this.needsLayout(); - } }, + /** + * Sets the title TTF filename to use for the specified state. + * @param {string} fntFile + * @param {Number} state + */ setTitleTTFForState:function (fntFile, state) { var title = this.getTitleForState(state); if (!title) @@ -520,6 +518,11 @@ cc.ControlButton = cc.Control.extend({ this.setTitleLabelForState(cc.LabelTTF.create(title, fntFile, 12), state); }, + /** + * return the title TTF filename to use for the specified state. + * @param {Number} state + * @returns {string} + */ getTitleTTFForState:function (state) { var labelTTF = this.getTitleLabelForState(state); if ((labelTTF != null) && (labelTTF instanceof cc.LabelTTF)) { @@ -529,6 +532,10 @@ cc.ControlButton = cc.Control.extend({ } }, + /** + * @param {Number} size + * @param {Number} state + */ setTitleTTFSizeForState:function (size, state) { var labelTTF = this.getTitleLabelForState(state); if ((labelTTF != null) && (labelTTF instanceof cc.LabelTTF)) { @@ -536,6 +543,11 @@ cc.ControlButton = cc.Control.extend({ } }, + /** + * return the font size of LabelTTF to use for the specified state + * @param {Number} state + * @returns {Number} + */ getTitleTTFSizeForState:function (state) { var labelTTF = this.getTitleLabelForState(state); if ((labelTTF != null) && (labelTTF instanceof cc.LabelTTF)) { @@ -545,10 +557,9 @@ cc.ControlButton = cc.Control.extend({ }, /** - * Sets the font of the label, changes the label to a CCLabelBMFont if neccessary. - * @param fntFile The name of the font to change to - * @param state The state that uses the specified fntFile. The values are described - * in "CCControlState". + * Sets the font of the label, changes the label to a CCLabelBMFont if necessary. + * @param {string} fntFile The name of the font to change to + * @param {Number} state The state that uses the specified fntFile. The values are described in "CCControlState". */ setTitleBMFontForState:function (fntFile, state) { var title = this.getTitleForState(state); @@ -568,52 +579,50 @@ cc.ControlButton = cc.Control.extend({ /** * Returns the background sprite used for a state. * - * @param state The state that uses the background sprite. Possible values are - * described in "CCControlState". + * @param {Number} state The state that uses the background sprite. Possible values are described in "CCControlState". */ getBackgroundSpriteForState:function (state) { - if (this._backgroundSpriteDispatchTable.hasOwnProperty(state) && this._backgroundSpriteDispatchTable[state]) { - return this._backgroundSpriteDispatchTable[state]; + var locTable = this._backgroundSpriteDispatchTable; + if (locTable.hasOwnProperty(state) && locTable[state]) { + return locTable[state]; } - return this._backgroundSpriteDispatchTable[cc.CONTROL_STATE_NORMAL]; + return locTable[cc.CONTROL_STATE_NORMAL]; }, /** * Sets the background sprite to use for the specified button state. * - * @param sprite The background sprite to use for the specified state. - * @param state The state that uses the specified image. The values are described - * in "CCControlState". + * @param {Scale9Sprite} sprite The background sprite to use for the specified state. + * @param {Number} state The state that uses the specified image. The values are described in "CCControlState". */ setBackgroundSpriteForState:function (sprite, state) { - if (this._backgroundSpriteDispatchTable.hasOwnProperty(state)) { - var previousSprite = this._backgroundSpriteDispatchTable[state]; - if (previousSprite) { + var locTable = this._backgroundSpriteDispatchTable; + if (locTable.hasOwnProperty(state)) { + var previousSprite = locTable[state]; + if (previousSprite) this.removeChild(previousSprite, true); - } } - this._backgroundSpriteDispatchTable[state] = sprite; + locTable[state] = sprite; sprite.setVisible(false); sprite.setAnchorPoint(cc.p(0.5, 0.5)); this.addChild(sprite); - if (this._preferredSize.width != 0 || this._preferredSize.height != 0) { - sprite.setPreferredSize(this._preferredSize); + var locPreferredSize = this._preferredSize; + if (locPreferredSize.width !== 0 || locPreferredSize.height !== 0) { + sprite.setPreferredSize(locPreferredSize); } // If the current state if equal to the given state we update the layout - if (this.getState() == state) { + if (this._state === state) this.needsLayout(); - } }, /** * Sets the background spriteFrame to use for the specified button state. * - * @param spriteFrame The background spriteFrame to use for the specified state. - * @param state The state that uses the specified image. The values are described - * in "CCControlState". + * @param {SpriteFrame} spriteFrame The background spriteFrame to use for the specified state. + * @param {Number} state The state that uses the specified image. The values are described in "CCControlState". */ setBackgroundSpriteFrameForState:function (spriteFrame, state) { var sprite = cc.Scale9Sprite.createWithSpriteFrame(spriteFrame); @@ -621,7 +630,7 @@ cc.ControlButton = cc.Control.extend({ } }); -cc.ControlButton.create = function (label, backgroundSprite) { +cc.ControlButton.create = function(label, backgroundSprite) { var controlButton; if (arguments.length == 0) { controlButton = new cc.ControlButton(); @@ -632,16 +641,14 @@ cc.ControlButton.create = function (label, backgroundSprite) { } else if (arguments.length == 1) { controlButton = new cc.ControlButton(); controlButton.initWithBackgroundSprite(arguments[0]); - return controlButton; } else if (arguments.length == 2) { controlButton = new cc.ControlButton(); controlButton.initWithLabelAndBackgroundSprite(label, backgroundSprite); - return controlButton; } else if (arguments.length == 3) { controlButton = new cc.ControlButton(); controlButton.initWithTitleAndFontNameAndFontSize(arguments[0], arguments[1], arguments[2]); - return controlButton; } + return controlButton; }; diff --git a/extensions/GUI/CCControlExtension/CCControlColourPicker.js b/extensions/GUI/CCControlExtension/CCControlColourPicker.js index 024cf1dfd2..a456f5eb71 100644 --- a/extensions/GUI/CCControlExtension/CCControlColourPicker.js +++ b/extensions/GUI/CCControlExtension/CCControlColourPicker.js @@ -1,4 +1,4 @@ -/* +/** * * Copyright (c) 2010-2012 cocos2d-x.org * @@ -101,7 +101,7 @@ cc.ControlColourPicker = cc.Control.extend({ this._hsv = new cc.HSV(0, 0, 0); // Add image - this._background = cc.ControlUtils.addSpriteToTargetWithPosAndAnchor("menuColourPanelBackground.png", spriteSheet, cc.PointZero, cc.p(0.5, 0.5)); + this._background = cc.ControlUtils.addSpriteToTargetWithPosAndAnchor("menuColourPanelBackground.png", spriteSheet, cc.PointZero(), cc.p(0.5, 0.5)); var backgroundPointZero = cc.pSub(this._background.getPosition(), cc.p(this._background.getContentSize().width / 2, this._background.getContentSize().height / 2)); diff --git a/extensions/GUI/CCControlExtension/CCControlHuePicker.js b/extensions/GUI/CCControlExtension/CCControlHuePicker.js index e9a34159c8..10952b4370 100644 --- a/extensions/GUI/CCControlExtension/CCControlHuePicker.js +++ b/extensions/GUI/CCControlExtension/CCControlHuePicker.js @@ -1,4 +1,4 @@ -/* +/** * * Copyright (c) 2010-2012 cocos2d-x.org * diff --git a/extensions/GUI/CCControlExtension/CCControlPotentiometer.js b/extensions/GUI/CCControlExtension/CCControlPotentiometer.js index 693cd9646d..a7245ef9ec 100644 --- a/extensions/GUI/CCControlExtension/CCControlPotentiometer.js +++ b/extensions/GUI/CCControlExtension/CCControlPotentiometer.js @@ -1,4 +1,4 @@ -/* +/** * Copyright (c) 2012 cocos2d-x.org * http://www.cocos2d-x.org * diff --git a/extensions/GUI/CCControlExtension/CCControlSaturationBrightnessPicker.js b/extensions/GUI/CCControlExtension/CCControlSaturationBrightnessPicker.js index 66e985338a..c6ceb37226 100644 --- a/extensions/GUI/CCControlExtension/CCControlSaturationBrightnessPicker.js +++ b/extensions/GUI/CCControlExtension/CCControlSaturationBrightnessPicker.js @@ -1,4 +1,4 @@ -/* +/** * * Copyright (c) 2010-2012 cocos2d-x.org * @@ -102,7 +102,7 @@ cc.ControlSaturationBrightnessPicker = cc.Control.extend({ }, updateDraggerWithHSV:function (hsv) { // Set the position of the slider to the correct saturation and brightness - var pos = cc.PointMake(this._startPos.x + this._boxPos + (this._boxSize * (1 - hsv.s)), + var pos = cc.p(this._startPos.x + this._boxPos + (this._boxSize * (1 - hsv.s)), this._startPos.y + this._boxPos + (this._boxSize * hsv.v)); // update diff --git a/extensions/GUI/CCControlExtension/CCControlSlider.js b/extensions/GUI/CCControlExtension/CCControlSlider.js index 2b3e9bb107..33b47b644b 100644 --- a/extensions/GUI/CCControlExtension/CCControlSlider.js +++ b/extensions/GUI/CCControlExtension/CCControlSlider.js @@ -1,4 +1,4 @@ -/* +/** * * Copyright (c) 2010-2012 cocos2d-x.org * @@ -140,7 +140,7 @@ cc.ControlSlider = cc.Control.extend({ // Defines the content size var maxRect = cc.ControlUtils.CCRectUnion(backgroundSprite.getBoundingBox(), thumbSprite.getBoundingBox()); - var size = cc.SizeMake(maxRect.width, maxRect.height); + var size = cc.size(maxRect.width, maxRect.height); this.setContentSize(size); // Add the slider background @@ -224,7 +224,7 @@ cc.ControlSlider = cc.Control.extend({ // Stretches content proportional to newLevel var textureRect = this._progressSprite.getTextureRect(); - textureRect = cc.RectMake(textureRect.x, textureRect.y, pos.x, textureRect.height); + textureRect = cc.rect(textureRect.x, textureRect.y, pos.x, textureRect.height); this._progressSprite.setTextureRect(textureRect, this._progressSprite.isTextureRectRotated(), textureRect.size); }, /** Returns the value for the given location. */ diff --git a/extensions/GUI/CCControlExtension/CCControlStepper.js b/extensions/GUI/CCControlExtension/CCControlStepper.js index 4a16c0eae7..e0985fe77b 100644 --- a/extensions/GUI/CCControlExtension/CCControlStepper.js +++ b/extensions/GUI/CCControlExtension/CCControlStepper.js @@ -1,4 +1,4 @@ -/* +/** * Copyright (c) 2012 cocos2d-x.org * http://www.cocos2d-x.org * @@ -55,6 +55,7 @@ cc.ControlStepper = cc.Control.extend({ _touchedPart:cc.CONTROL_STEPPER_PARTNONE, _autorepeatCount:0, ctor:function () { + cc.Control.prototype.ctor.call(this); this._minusSprite = null; this._plusSprite = null; this._minusLabel = null; diff --git a/extensions/GUI/CCControlExtension/CCControlSwitch.js b/extensions/GUI/CCControlExtension/CCControlSwitch.js index eaa20a029d..5b52a2ba48 100644 --- a/extensions/GUI/CCControlExtension/CCControlSwitch.js +++ b/extensions/GUI/CCControlExtension/CCControlSwitch.js @@ -1,4 +1,4 @@ -/* +/** * * Copyright (c) 2010-2012 cocos2d-x.org * @@ -222,11 +222,7 @@ cc.ControlSwitchSprite = cc.Sprite.extend({ //this._maskLocation = cc.renderContext.getUniformLocation(this.getShaderProgram().getProgram(), "u_mask"); //cc.CHECK_GL_ERROR_DEBUG(); - if(cc.renderContextType==cc.CANVAS){ - this.setContentSize(cc.size(this._maskTexture.width,this._maskTexture.height)); - }else{ - this.setContentSize(this._maskTexture.getContentSize()); - } + this.setContentSize(this._maskTexture.getContentSize()); this.needsLayout(); return true; @@ -283,17 +279,10 @@ cc.ControlSwitchSprite = cc.Sprite.extend({ this._offLabel.setPosition(cc.p(this._offSprite.getPosition().x + this._thumbSprite.getContentSize().width / 6, this._offSprite.getContentSize().height / 2)); } - var rt ; - if(cc.renderContextType==cc.CANVAS){ - this._thumbSprite.setPosition(cc.p(this._onSprite.getContentSize().width + this._sliderXPosition, - this._maskTexture.height / 2)); - rt = cc.RenderTexture.create(this._maskTexture.width, this._maskTexture.height); - }else{ - this._thumbSprite.setPosition(cc.p(this._onSprite.getContentSize().width + this._sliderXPosition, - this._maskTexture.getContentSize().height / 2)); - rt = cc.RenderTexture.create(this._maskTexture.getContentSize().width, this._maskTexture.getContentSize().height); - } - + var locMaskSize = this._maskTexture.getContentSize(); + this._thumbSprite.setPosition(cc.p(this._onSprite.getContentSize().width + this._sliderXPosition, + locMaskSize.height / 2)); + var rt = cc.RenderTexture.create(locMaskSize.width, locMaskSize.height); rt.begin(); this._onSprite.visit(); @@ -307,7 +296,7 @@ cc.ControlSwitchSprite = cc.Sprite.extend({ rt.end(); this.setTexture(rt.getSprite().getTexture()); - this.setFlipY(true); + this.setFlippedY(true); }, setSliderXPosition:function (sliderXPosition) { diff --git a/extensions/GUI/CCControlExtension/CCControlUtils.js b/extensions/GUI/CCControlExtension/CCControlUtils.js index 3acd0e3483..c31fdf1db6 100644 --- a/extensions/GUI/CCControlExtension/CCControlUtils.js +++ b/extensions/GUI/CCControlExtension/CCControlUtils.js @@ -153,7 +153,6 @@ cc.ControlUtils.RGBfromHSV = function(hsvValue){ out.g = p; out.b = hsvValue.v; break; - case 5: default: out.r = hsvValue.v; out.g = p; diff --git a/extensions/GUI/CCControlExtension/CCMenuPassive.js b/extensions/GUI/CCControlExtension/CCMenuPassive.js index 5ffa14cb4e..a608ecd72a 100644 --- a/extensions/GUI/CCControlExtension/CCMenuPassive.js +++ b/extensions/GUI/CCControlExtension/CCMenuPassive.js @@ -27,14 +27,14 @@ cc.Spacer = cc.Layer.extend({}); cc.Spacer.verticalSpacer = function (space) { var pRet = new cc.Spacer(); pRet.init(); - pRet.setContentSize(cc.SizeMake(0, space)); + pRet.setContentSize(cc.size(0, space)); return pRet; }; cc.Spacer.horizontalSpacer = function (space) { var pRet = new cc.Spacer(); pRet.init(); - pRet.setContentSize(cc.SizeMake(space, 0)); + pRet.setContentSize(cc.size(space, 0)); return pRet; }; @@ -141,7 +141,7 @@ cc.MenuPassive = cc.Layer.extend({ } } } - this.setContentSize(cc.SizeMake(width, height)); + this.setContentSize(cc.size(width, height)); }, /** align items horizontally */ @@ -174,7 +174,7 @@ cc.MenuPassive = cc.Layer.extend({ } } } - this.setContentSize(cc.SizeMake(width, height)); + this.setContentSize(cc.size(width, height)); }, /** align items in rows of columns */ diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.js b/extensions/GUI/CCControlExtension/CCScale9Sprite.js index fa02e3655f..5daab20170 100644 --- a/extensions/GUI/CCControlExtension/CCScale9Sprite.js +++ b/extensions/GUI/CCControlExtension/CCScale9Sprite.js @@ -82,16 +82,17 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ _spriteFrameRotated: false, _updateCapInset: function () { - var insets; - if (this._insetLeft == 0 && this._insetTop == 0 && this._insetRight == 0 && this._insetBottom == 0) { + var insets, locInsetLeft = this._insetLeft, locInsetTop = this._insetTop, locInsetRight = this._insetRight; + var locSpriteRect = this._spriteRect, locInsetBottom = this._insetBottom; + if (locInsetLeft === 0 && locInsetTop === 0 && locInsetRight === 0 && locInsetBottom === 0) { insets = cc.RectZero(); } else { - insets = this._spriteFrameRotated ? cc.RectMake(this._insetBottom, this._insetLeft, - this._spriteRect.width - this._insetRight - this._insetLeft, - this._spriteRect.height - this._insetTop - this._insetBottom) : - cc.RectMake(this._insetLeft, this._insetTop, - this._spriteRect.width - this._insetLeft - this._insetRight, - this._spriteRect.height - this._insetTop - this._insetBottom); + insets = this._spriteFrameRotated ? cc.rect(locInsetBottom, locInsetLeft, + locSpriteRect.width - locInsetRight - locInsetLeft, + locSpriteRect.height - locInsetTop - locInsetBottom) : + cc.rect(locInsetLeft, locInsetTop, + locSpriteRect.width - locInsetLeft - locInsetRight, + locSpriteRect.height - locInsetTop - locInsetBottom); } this.setCapInsets(insets); }, @@ -105,64 +106,70 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ } var size = this._contentSize; - var sizableWidth = size.width - this._topLeft.getContentSize().width - this._topRight.getContentSize().width; - var sizableHeight = size.height - this._topLeft.getContentSize().height - this._bottomRight.getContentSize().height; - var horizontalScale = sizableWidth / this._centre.getContentSize().width; - var verticalScale = sizableHeight / this._centre.getContentSize().height; - var rescaledWidth = this._centre.getContentSize().width * horizontalScale; - var rescaledHeight = this._centre.getContentSize().height * verticalScale; + var locTopLeft = this._topLeft, locTopRight = this._topRight, locBottomRight = this._bottomRight; + var locCenter = this._centre, locCenterContentSize = this._centre.getContentSize(); - var leftWidth = this._bottomLeft.getContentSize().width; - var bottomHeight = this._bottomLeft.getContentSize().height; + var sizableWidth = size.width - locTopLeft.getContentSize().width - locTopRight.getContentSize().width; + var sizableHeight = size.height - locTopLeft.getContentSize().height - locBottomRight.getContentSize().height; + var horizontalScale = sizableWidth / locCenterContentSize.width; + var verticalScale = sizableHeight / locCenterContentSize.height; + var rescaledWidth = locCenterContentSize.width * horizontalScale; + var rescaledHeight = locCenterContentSize.height * verticalScale; + + var locBottomLeft = this._bottomLeft; + var leftWidth = locBottomLeft.getContentSize().width; + var bottomHeight = locBottomLeft.getContentSize().height; if(!cc.Browser.supportWebGL) { //browser is in canvas mode, need to manually control rounding to prevent overlapping pixels var roundedRescaledWidth = Math.round(rescaledWidth); if(rescaledWidth != roundedRescaledWidth) { rescaledWidth = roundedRescaledWidth; - horizontalScale = rescaledWidth/this._centre.getContentSize().width; + horizontalScale = rescaledWidth/locCenterContentSize.width; } var roundedRescaledHeight = Math.round(rescaledHeight); if(rescaledHeight != roundedRescaledHeight) { rescaledHeight = roundedRescaledHeight; - verticalScale = rescaledHeight/this._centre.getContentSize().height; + verticalScale = rescaledHeight/locCenterContentSize.height; } } - this._centre.setScaleX(horizontalScale); - this._centre.setScaleY(verticalScale); - - this._bottomLeft.setAnchorPoint(cc.p(0, 0)); - this._bottomRight.setAnchorPoint(cc.p(0, 0)); - this._topLeft.setAnchorPoint(cc.p(0, 0)); - this._topRight.setAnchorPoint(cc.p(0, 0)); - this._left.setAnchorPoint(cc.p(0, 0)); - this._right.setAnchorPoint(cc.p(0, 0)); - this._top.setAnchorPoint(cc.p(0, 0)); - this._bottom.setAnchorPoint(cc.p(0, 0)); - this._centre.setAnchorPoint(cc.p(0, 0)); + locCenter.setScaleX(horizontalScale); + locCenter.setScaleY(verticalScale); + + var locLeft = this._left, locRight = this._right, locTop = this._top, locBottom = this._bottom; + var tempAP = cc.p(0, 0); + locBottomLeft.setAnchorPoint(tempAP); + locBottomRight.setAnchorPoint(tempAP); + locTopLeft.setAnchorPoint(tempAP); + locTopRight.setAnchorPoint(tempAP); + locLeft.setAnchorPoint(tempAP); + locRight.setAnchorPoint(tempAP); + locTop.setAnchorPoint(tempAP); + locBottom.setAnchorPoint(tempAP); + locCenter.setAnchorPoint(tempAP); // Position corners - this._bottomLeft.setPosition(cc.p(0, 0)); - this._bottomRight.setPosition(cc.p(leftWidth + rescaledWidth, 0)); - this._topLeft.setPosition(cc.p(0, bottomHeight + rescaledHeight)); - this._topRight.setPosition(cc.p(leftWidth + rescaledWidth, bottomHeight + rescaledHeight)); + locBottomLeft.setPosition(0, 0); + locBottomRight.setPosition(leftWidth + rescaledWidth, 0); + locTopLeft.setPosition(0, bottomHeight + rescaledHeight); + locTopRight.setPosition(leftWidth + rescaledWidth, bottomHeight + rescaledHeight); // Scale and position borders - this._left.setPosition(cc.p(0, bottomHeight)); - this._left.setScaleY(verticalScale); - this._right.setPosition(cc.p(leftWidth + rescaledWidth, bottomHeight)); - this._right.setScaleY(verticalScale); - this._bottom.setPosition(cc.p(leftWidth, 0)); - this._bottom.setScaleX(horizontalScale); - this._top.setPosition(cc.p(leftWidth, bottomHeight + rescaledHeight)); - this._top.setScaleX(horizontalScale); + locLeft.setPosition(0, bottomHeight); + locLeft.setScaleY(verticalScale); + locRight.setPosition(leftWidth + rescaledWidth, bottomHeight); + locRight.setScaleY(verticalScale); + locBottom.setPosition(leftWidth, 0); + locBottom.setScaleX(horizontalScale); + locTop.setPosition(leftWidth, bottomHeight + rescaledHeight); + locTop.setScaleX(horizontalScale); // Position centre - this._centre.setPosition(cc.p(leftWidth, bottomHeight)); + locCenter.setPosition(leftWidth, bottomHeight); }, ctor: function () { - this._super(); + cc.Node.prototype.ctor.call(this); this._spriteRect = cc.RectZero(); this._capInsetsInternal = cc.RectZero(); @@ -196,9 +203,9 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ this._opacity = opacity; var scaleChildren = this._scale9Image.getChildren(); for (var i = 0; i < scaleChildren.length; i++) { - if (scaleChildren[i] && scaleChildren[i].RGBAProtocol) { - scaleChildren[i].setOpacity(this._opacity); - } + var selChild = scaleChildren[i]; + if (selChild && selChild.RGBAProtocol) + selChild.setOpacity(opacity); } }, @@ -210,9 +217,9 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ this._color = color; var scaleChildren = this._scale9Image.getChildren(); for (var i = 0; i < scaleChildren.length; i++) { - if (scaleChildren[i] && scaleChildren[i].RGBAProtocol) { - scaleChildren[i].setColor(this._color); - } + var selChild = scaleChildren[i]; + if (selChild && selChild.RGBAProtocol) + selChild.setColor(color); } }, @@ -222,6 +229,7 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ setCapInsets: function (capInsets) { var contentSize = this._contentSize; + contentSize = new cc.Size(contentSize.width,contentSize.height); this.updateWithBatchNode(this._scale9Image, this._spriteRect, this._spriteFrameRotated, capInsets); this.setContentSize(contentSize); }, @@ -293,7 +301,7 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ }, setContentSize: function (size) { - this._super(size); + cc.Node.prototype.setContentSize.call(this, size); this.m_positionsAreDirty = true; }, @@ -302,7 +310,7 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ this._updatePositions(); this.m_positionsAreDirty = false; } - this._super(); + cc.Node.prototype.visit.call(this); }, init: function () { @@ -310,7 +318,7 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ }, initWithBatchNode: function (batchNode, rect, rotated, capInsets) { - if (arguments.length == 3) { + if (arguments.length === 3) { capInsets = rotated; rotated = false; } @@ -368,6 +376,16 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ var selTexture = spriteFrame.getTexture(); cc.Assert(selTexture != null, "Texture must be not nil"); + if(!spriteFrame.textureLoaded()){ + spriteFrame.addLoadedEventListener(function(sender){ + // the texture is rotated on Canvas render mode, so isRotated always is false. + var preferredSize = this._preferredSize; + preferredSize = cc.size(preferredSize.width, preferredSize.height); + this.updateWithBatchNode(this._scale9Image, sender.getRect(), cc.Browser.supportWebGL ? sender.isRotated() : false, this._capInsets); + this.setPreferredSize(preferredSize); + this.m_positionsAreDirty = true; + },this); + } var batchNode = cc.SpriteBatchNode.createWithTexture(selTexture, 9); // the texture is rotated on Canvas render mode, so isRotated always is false. return this.initWithBatchNode(batchNode, spriteFrame.getRect(), cc.Browser.supportWebGL ? spriteFrame.isRotated() : false, capInsets); @@ -420,9 +438,8 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ this._opacityModifyRGB = value; var scaleChildren = this._scale9Image.getChildren(); if (scaleChildren) { - for (var i = 0; i < scaleChildren.length; i++) { - scaleChildren[i].setOpacityModifyRGB(this._opacityModifyRGB); - } + for (var i = 0, len = scaleChildren.length; i < len; i++) + scaleChildren[i].setOpacityModifyRGB(value); } }, @@ -443,45 +460,55 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ if (this._scale9Image != batchNode) this._scale9Image = batchNode; - this._scale9Image.removeAllChildren(true); + var locScale9Image = this._scale9Image; + locScale9Image.removeAllChildren(true); this._capInsets = capInsets; - var selTexture = this._scale9Image.getTexture(); + var selTexture = locScale9Image.getTexture(); - var rectZero = cc.RectZero(); // If there is no given rect - if (cc.rectEqualToRect(rect, rectZero)) { + if (cc._rectEqualToZero(rect)) { // Get the texture size as original - if (selTexture instanceof cc.Texture2D) { - var textureSize = selTexture.getContentSize(); - rect = cc.RectMake(0, 0, textureSize.width, textureSize.height); - } else { - rect = cc.RectMake(0, 0, selTexture.width, selTexture.height); - rect = cc.RECT_PIXELS_TO_POINTS(rect); - } + var textureSize = selTexture.getContentSize(); + rect = cc.rect(0, 0, textureSize.width, textureSize.height); } // Set the given rect's size as original size this._spriteRect = rect; var rectSize = rect.size; - this._originalSize = new cc.Size(rectSize.width, rectSize.height); - this._preferredSize = new cc.Size(rectSize.width, rectSize.height); - this._capInsetsInternal = capInsets || cc.RectZero(); + this._originalSize.width = rectSize.width; + this._originalSize.height = rectSize.height; + var locPreferredSize = this._preferredSize; + if(locPreferredSize.width === 0 && locPreferredSize.height === 0){ + locPreferredSize.width = rectSize.width; + locPreferredSize.height = rectSize.height; + } + + var locCapInsetsInternal = this._capInsetsInternal; + if(!capInsets){ + locCapInsetsInternal.x = capInsets.x; + locCapInsetsInternal.y = capInsets.y; + locCapInsetsInternal.width = capInsets.width; + locCapInsetsInternal.height = capInsets.height; + } var w = rectSize.width; var h = rectSize.height; // If there is no specified center region - if (cc.rectEqualToRect(this._capInsetsInternal, rectZero)) { + if (cc._rectEqualToZero(locCapInsetsInternal)) { // CCLog("... cap insets not specified : using default cap insets ..."); - this._capInsetsInternal = cc.rect(w / 3, h / 3, w / 3, h / 3); + locCapInsetsInternal.x = w / 3; + locCapInsetsInternal.y = h / 3; + locCapInsetsInternal.width = w / 3; + locCapInsetsInternal.height = h / 3; } - var left_w = this._capInsetsInternal.x; - var center_w = this._capInsetsInternal.width; + var left_w = locCapInsetsInternal.x; + var center_w = locCapInsetsInternal.width; var right_w = w - (left_w + center_w); - var top_h = this._capInsetsInternal.y; - var center_h = this._capInsetsInternal.height; + var top_h = locCapInsetsInternal.y; + var center_h = locCapInsetsInternal.height; var bottom_h = h - (top_h + center_h); // calculate rects @@ -490,15 +517,15 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ var y = 0.0; // top left - var lefttopbounds = cc.RectMake(x, y, left_w, top_h); + var lefttopbounds = cc.rect(x, y, left_w, top_h); // top center x += left_w; - var centertopbounds = cc.RectMake(x, y, center_w, top_h); + var centertopbounds = cc.rect(x, y, center_w, top_h); // top right x += center_w; - var righttopbounds = cc.RectMake(x, y, right_w, top_h); + var righttopbounds = cc.rect(x, y, right_w, top_h); // ... center row x = 0.0; @@ -506,15 +533,15 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ // center left y += top_h; - var leftcenterbounds = cc.RectMake(x, y, left_w, center_h); + var leftcenterbounds = cc.rect(x, y, left_w, center_h); // center center x += left_w; - var centerbounds = cc.RectMake(x, y, center_w, center_h); + var centerbounds = cc.rect(x, y, center_w, center_h); // center right x += center_w; - var rightcenterbounds = cc.RectMake(x, y, right_w, center_h); + var rightcenterbounds = cc.rect(x, y, right_w, center_h); // ... bottom row x = 0.0; @@ -523,83 +550,80 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ y += center_h; // bottom left - var leftbottombounds = cc.RectMake(x, y, left_w, bottom_h); + var leftbottombounds = cc.rect(x, y, left_w, bottom_h); // bottom center x += left_w; - var centerbottombounds = cc.RectMake(x, y, center_w, bottom_h); + var centerbottombounds = cc.rect(x, y, center_w, bottom_h); // bottom right x += center_w; - var rightbottombounds = cc.RectMake(x, y, right_w, bottom_h); + var rightbottombounds = cc.rect(x, y, right_w, bottom_h); + var t = cc.AffineTransformMakeIdentity(); if (!rotated) { // CCLog("!rotated"); - var t = cc.AffineTransformMakeIdentity(); t = cc.AffineTransformTranslate(t, rect.x, rect.y); - centerbounds = cc.RectApplyAffineTransform(centerbounds, t); - rightbottombounds = cc.RectApplyAffineTransform(rightbottombounds, t); - leftbottombounds = cc.RectApplyAffineTransform(leftbottombounds, t); - righttopbounds = cc.RectApplyAffineTransform(righttopbounds, t); - lefttopbounds = cc.RectApplyAffineTransform(lefttopbounds, t); - rightcenterbounds = cc.RectApplyAffineTransform(rightcenterbounds, t); - leftcenterbounds = cc.RectApplyAffineTransform(leftcenterbounds, t); - centerbottombounds = cc.RectApplyAffineTransform(centerbottombounds, t); - centertopbounds = cc.RectApplyAffineTransform(centertopbounds, t); + cc._RectApplyAffineTransformIn(centerbounds, t); + cc._RectApplyAffineTransformIn(rightbottombounds, t); + cc._RectApplyAffineTransformIn(leftbottombounds, t); + cc._RectApplyAffineTransformIn(righttopbounds, t); + cc._RectApplyAffineTransformIn(lefttopbounds, t); + cc._RectApplyAffineTransformIn(rightcenterbounds, t); + cc._RectApplyAffineTransformIn(leftcenterbounds, t); + cc._RectApplyAffineTransformIn(centerbottombounds, t); + cc._RectApplyAffineTransformIn(centertopbounds, t); // Centre this._centre = new cc.Sprite(); this._centre.initWithTexture(selTexture, centerbounds); - this._scale9Image.addChild(this._centre, 0, cc.POSITIONS_CENTRE); + locScale9Image.addChild(this._centre, 0, cc.POSITIONS_CENTRE); // Top this._top = new cc.Sprite(); this._top.initWithTexture(selTexture, centertopbounds); - this._scale9Image.addChild(this._top, 1, cc.POSITIONS_TOP); + locScale9Image.addChild(this._top, 1, cc.POSITIONS_TOP); // Bottom this._bottom = new cc.Sprite(); this._bottom.initWithTexture(selTexture, centerbottombounds); - this._scale9Image.addChild(this._bottom, 1, cc.POSITIONS_BOTTOM); + locScale9Image.addChild(this._bottom, 1, cc.POSITIONS_BOTTOM); // Left this._left = new cc.Sprite(); this._left.initWithTexture(selTexture, leftcenterbounds); - this._scale9Image.addChild(this._left, 1, cc.POSITIONS_LEFT); + locScale9Image.addChild(this._left, 1, cc.POSITIONS_LEFT); // Right this._right = new cc.Sprite(); this._right.initWithTexture(selTexture, rightcenterbounds); - this._scale9Image.addChild(this._right, 1, cc.POSITIONS_RIGHT); + locScale9Image.addChild(this._right, 1, cc.POSITIONS_RIGHT); // Top left this._topLeft = new cc.Sprite(); this._topLeft.initWithTexture(selTexture, lefttopbounds); - this._scale9Image.addChild(this._topLeft, 2, cc.POSITIONS_TOPLEFT); + locScale9Image.addChild(this._topLeft, 2, cc.POSITIONS_TOPLEFT); // Top right this._topRight = new cc.Sprite(); this._topRight.initWithTexture(selTexture, righttopbounds); - this._scale9Image.addChild(this._topRight, 2, cc.POSITIONS_TOPRIGHT); + locScale9Image.addChild(this._topRight, 2, cc.POSITIONS_TOPRIGHT); // Bottom left this._bottomLeft = new cc.Sprite(); this._bottomLeft.initWithTexture(selTexture, leftbottombounds); - this._scale9Image.addChild(this._bottomLeft, 2, cc.POSITIONS_BOTTOMLEFT); + locScale9Image.addChild(this._bottomLeft, 2, cc.POSITIONS_BOTTOMLEFT); // Bottom right this._bottomRight = new cc.Sprite(); this._bottomRight.initWithTexture(selTexture, rightbottombounds); - this._scale9Image.addChild(this._bottomRight, 2, cc.POSITIONS_BOTTOMRIGHT); + locScale9Image.addChild(this._bottomRight, 2, cc.POSITIONS_BOTTOMRIGHT); } else { // set up transformation of coordinates // to handle the case where the sprite is stored rotated // in the spritesheet // CCLog("rotated"); - - var t = cc.AffineTransformMakeIdentity(); - var rotatedcenterbounds = centerbounds; var rotatedrightbottombounds = rightbottombounds; var rotatedleftbottombounds = leftbottombounds; @@ -623,69 +647,88 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{ centerbottombounds = cc.RectApplyAffineTransform(centerbottombounds, t); centertopbounds = cc.RectApplyAffineTransform(centertopbounds, t); - rotatedcenterbounds.origin = {x: centerbounds.x, y: centerbounds.y}; - rotatedrightbottombounds.origin = {x: rightbottombounds.x, y: rightbottombounds.y}; - rotatedleftbottombounds.origin = {x: leftbottombounds.x, y: leftbottombounds.y}; - rotatedrighttopbounds.origin = {x: righttopbounds.x, y: righttopbounds.y}; - rotatedlefttopbounds.origin = {x: lefttopbounds.x, y: lefttopbounds.y}; - rotatedrightcenterbounds.origin = {x: rightcenterbounds.x, y: rightcenterbounds.y}; - rotatedleftcenterbounds.origin = {x: leftcenterbounds.x, y: leftcenterbounds.y}; - rotatedcenterbottombounds.origin = {x: centerbottombounds.x, y: centerbottombounds.y}; - rotatedcentertopbounds.origin = {x: centertopbounds.x, y: centertopbounds.y}; + rotatedcenterbounds.x = centerbounds.x; + rotatedcenterbounds.y = centerbounds.y; + + rotatedrightbottombounds.x = rightbottombounds.x; + rotatedrightbottombounds.y = rightbottombounds.y; + + rotatedleftbottombounds.x = leftbottombounds.x; + rotatedleftbottombounds.y = leftbottombounds.y; + + rotatedrighttopbounds.x = righttopbounds.x; + rotatedrighttopbounds.y = righttopbounds.y; + + rotatedlefttopbounds.x = lefttopbounds.x; + rotatedlefttopbounds.y = lefttopbounds.y; + + rotatedrightcenterbounds.x = rightcenterbounds.x; + rotatedrightcenterbounds.y = rightcenterbounds.y; + + rotatedleftcenterbounds.x = leftcenterbounds.x; + rotatedleftcenterbounds.y = leftcenterbounds.y; + + rotatedcenterbottombounds.x = centerbottombounds.x; + rotatedcenterbottombounds.y = centerbottombounds.y; + + rotatedcentertopbounds.x = centertopbounds.x; + rotatedcentertopbounds.y = centertopbounds.y; // Centre this._centre = new cc.Sprite(); this._centre.initWithTexture(selTexture, rotatedcenterbounds, true); - this._scale9Image.addChild(this._centre, 0, cc.POSITIONS_CENTRE); + locScale9Image.addChild(this._centre, 0, cc.POSITIONS_CENTRE); // Top this._top = new cc.Sprite(); this._top.initWithTexture(selTexture, rotatedcentertopbounds, true); - this._scale9Image.addChild(this._top, 1, cc.POSITIONS_TOP); + locScale9Image.addChild(this._top, 1, cc.POSITIONS_TOP); // Bottom this._bottom = new cc.Sprite(); this._bottom.initWithTexture(selTexture, rotatedcenterbottombounds, true); - this._scale9Image.addChild(this._bottom, 1, cc.POSITIONS_BOTTOM); + locScale9Image.addChild(this._bottom, 1, cc.POSITIONS_BOTTOM); // Left this._left = new cc.Sprite(); this._left.initWithTexture(selTexture, rotatedleftcenterbounds, true); - this._scale9Image.addChild(this._left, 1, cc.POSITIONS_LEFT); + locScale9Image.addChild(this._left, 1, cc.POSITIONS_LEFT); // Right this._right = new cc.Sprite(); this._right.initWithTexture(selTexture, rotatedrightcenterbounds, true); - this._scale9Image.addChild(this._right, 1, cc.POSITIONS_RIGHT); + locScale9Image.addChild(this._right, 1, cc.POSITIONS_RIGHT); // Top left this._topLeft = new cc.Sprite(); this._topLeft.initWithTexture(selTexture, rotatedlefttopbounds, true); - this._scale9Image.addChild(this._topLeft, 2, cc.POSITIONS_TOPLEFT); + locScale9Image.addChild(this._topLeft, 2, cc.POSITIONS_TOPLEFT); // Top right this._topRight = new cc.Sprite(); this._topRight.initWithTexture(selTexture, rotatedrighttopbounds, true); - this._scale9Image.addChild(this._topRight, 2, cc.POSITIONS_TOPRIGHT); + locScale9Image.addChild(this._topRight, 2, cc.POSITIONS_TOPRIGHT); // Bottom left this._bottomLeft = new cc.Sprite(); this._bottomLeft.initWithTexture(selTexture, rotatedleftbottombounds, true); - this._scale9Image.addChild(this._bottomLeft, 2, cc.POSITIONS_BOTTOMLEFT); + locScale9Image.addChild(this._bottomLeft, 2, cc.POSITIONS_BOTTOMLEFT); // Bottom right this._bottomRight = new cc.Sprite(); this._bottomRight.initWithTexture(selTexture, rotatedrightbottombounds, true); - this._scale9Image.addChild(this._bottomRight, 2, cc.POSITIONS_BOTTOMRIGHT); + locScale9Image.addChild(this._bottomRight, 2, cc.POSITIONS_BOTTOMRIGHT); } this.setContentSize(rect.size); - this.addChild(this._scale9Image); + this.addChild(locScale9Image); if (this._spritesGenerated) { // Restore color and opacity this.setOpacity(opacity); - this.setColor(color); + if(color.r !== 255 || color.g !== 255 || color.b !== 255){ + this.setColor(color); + } } this._spritesGenerated = true; return true; diff --git a/extensions/GUI/CCScrollView/CCScrollView.js b/extensions/GUI/CCScrollView/CCScrollView.js index a384204931..9adc7d6607 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.js +++ b/extensions/GUI/CCScrollView/CCScrollView.js @@ -38,7 +38,8 @@ var INSET_RATIO = 0.2; var MOVE_INCH = 7.0/160.0; cc.convertDistanceFromPointToInch = function(pointDis){ - var factor = (cc.EGLView.getInstance().getScaleX() + cc.EGLView.getInstance().getScaleY())/2; + var eglViewer = cc.EGLView.getInstance(); + var factor = (eglViewer.getScaleX() + eglViewer.getScaleY())/2; return (pointDis * factor) / 160; // CCDevice::getDPI() default value }; @@ -79,51 +80,58 @@ cc.ScrollView = cc.Layer.extend({ _parentScissorRect:null, _scissorRestored:false, + // cache object + _tmpViewRect:null, + ctor:function () { - this._super(); + cc.Layer.prototype.ctor.call(this); + this._contentOffset = new cc.Point(0,0); this._maxInset = new cc.Point(0, 0); this._minInset = new cc.Point(0, 0); this._scrollDistance = new cc.Point(0, 0); this._touchPoint = new cc.Point(0, 0); this._touches = []; this._viewSize = new cc.Size(0, 0); + this._parentScissorRect = new cc.Rect(0,0,0,0); + this._tmpViewRect = new cc.Rect(0,0,0,0); }, init:function () { - return this.initWithViewSize(cc.SizeMake(200, 200), null); + return this.initWithViewSize(cc.size(200, 200), null); }, registerWithTouchDispatcher:function () { - cc.Director.getInstance().getTouchDispatcher().addTargetedDelegate(this, this.getTouchPriority(), false); + cc.registerTargetedDelegate(this.getTouchPriority(), false, this); }, /** - * Returns a scroll view object + * initialized whether success or fail * @param {cc.Size} size * @param {cc.Node} container * @return {Boolean} */ initWithViewSize:function (size, container) { + var pZero = cc.p(0,0); if (cc.Layer.prototype.init.call(this)) { this._container = container; if (!this._container) { this._container = cc.Layer.create(); this._container.ignoreAnchorPointForPosition(false); - this._container.setAnchorPoint(cc.p(0.0, 0.0)); + this._container.setAnchorPoint(pZero); } this.setViewSize(size); this.setTouchEnabled(true); - this._touches = []; + this._touches.length = 0; this._delegate = null; this._bounceable = true; this._clippingToBounds = true; //this._container.setContentSize(CCSizeZero); this._direction = cc.SCROLLVIEW_DIRECTION_BOTH; - this._container.setPosition(cc.p(0.0, 0.0)); + this._container.setPosition(pZero); this._touchLength = 0.0; this.addChild(this._container); @@ -137,25 +145,27 @@ cc.ScrollView = cc.Layer.extend({ * Sets a new content offset. It ignores max/min offset. It just sets what's given. (just like UIKit's UIScrollView) * * @param {cc.Point} offset new offset - * @param {Number} animated If YES, the view scrolls to the new offset + * @param {Number} [animated=] If YES, the view scrolls to the new offset */ - setContentOffset:function (offset, animated) { + setContentOffset: function (offset, animated) { if (animated) { //animate scrolling this.setContentOffsetInDuration(offset, BOUNCE_DURATION); - } else { //set the container position directly - if (!this._bounceable) { - var minOffset = this.minContainerOffset(); - var maxOffset = this.maxContainerOffset(); + return; + } + if (!this._bounceable) { + var minOffset = this.minContainerOffset(); + var maxOffset = this.maxContainerOffset(); - offset.x = Math.max(minOffset.x, Math.min(maxOffset.x, offset.x)); - offset.y = Math.max(minOffset.y, Math.min(maxOffset.y, offset.y)); - } + offset.x = Math.max(minOffset.x, Math.min(maxOffset.x, offset.x)); + offset.y = Math.max(minOffset.y, Math.min(maxOffset.y, offset.y)); + } - this._container.setPosition(offset); - if (this._delegate != null && this._delegate.scrollViewDidScroll) { - this._delegate.scrollViewDidScroll(this); - } + this._container.setPosition(offset); + var locDelegate = this._delegate; + if (locDelegate != null && locDelegate.scrollViewDidScroll) { + locDelegate.scrollViewDidScroll(this); } + }, getContentOffset:function () { @@ -180,35 +190,34 @@ cc.ScrollView = cc.Layer.extend({ * Sets a new scale and does that for a predefined duration. * * @param {Number} scale a new scale vale - * @param {Boolean} animated if YES, scaling is animated + * @param {Boolean} [animated=null] if YES, scaling is animated */ - setZoomScale:function (scale, animated) { - if (arguments.length === 1) { - if (this._container.getScale() != scale) { - var oldCenter, newCenter; - var center; - - if (this._touchLength == 0.0) { - center = cc.p(this._viewSize.width * 0.5, this._viewSize.height * 0.5); - center = this.convertToWorldSpace(center); - } else - center = this._touchPoint; - - oldCenter = this._container.convertToNodeSpace(center); - this._container.setScale(Math.max(this._minScale, Math.min(this._maxScale, scale))); - newCenter = this._container.convertToWorldSpace(oldCenter); - - var offset = cc.pSub(center, newCenter); - if (this._delegate != null) { - this._delegate.scrollViewDidZoom(this); - } - this.setContentOffset(cc.pAdd(this._container.getPosition(), offset)); - } - } else if (arguments.length === 2) { - if (animated) - this.setZoomScaleInDuration(scale, BOUNCE_DURATION); - else - this.setZoomScale(scale); + setZoomScale: function (scale, animated) { + if (animated) { + this.setZoomScaleInDuration(scale, BOUNCE_DURATION); + return; + } + + var locContainer = this._container; + if (locContainer.getScale() != scale) { + var oldCenter, newCenter; + var center; + + if (this._touchLength == 0.0) { + var locViewSize = this._viewSize; + center = cc.p(locViewSize.width * 0.5, locViewSize.height * 0.5); + center = this.convertToWorldSpace(center); + } else + center = this._touchPoint; + + oldCenter = locContainer.convertToNodeSpace(center); + locContainer.setScale(Math.max(this._minScale, Math.min(this._maxScale, scale))); + newCenter = locContainer.convertToWorldSpace(oldCenter); + + var offset = cc.pSub(center, newCenter); + if (this._delegate != null) + this._delegate.scrollViewDidZoom(this); + this.setContentOffset(cc.pAdd(locContainer.getPosition(), offset)); } }, @@ -224,8 +233,9 @@ cc.ScrollView = cc.Layer.extend({ */ setZoomScaleInDuration:function (s, dt) { if (dt > 0) { - if (this._container.getScale() != s) { - var scaleAction = cc.ActionTween.create(dt, "zoomScale", this._container.getScale(), s); + var locScale = this._container.getScale(); + if (locScale != s) { + var scaleAction = cc.ActionTween.create(dt, "zoomScale", locScale, s); this.runAction(scaleAction); } } else { @@ -235,14 +245,18 @@ cc.ScrollView = cc.Layer.extend({ /** * Returns the current container's minimum offset. You may want this while you animate scrolling by yourself + * @return {cc.Point} Returns the current container's minimum offset. */ minContainerOffset:function () { - return cc.p(this._viewSize.width - this._container.getContentSize().width * this._container.getScaleX(), - this._viewSize.height - this._container.getContentSize().height * this._container.getScaleY()); + var locContainer = this._container; + var locContentSize = locContainer.getContentSize(), locViewSize = this._viewSize; + return cc.p(locViewSize.width - locContentSize.width * locContainer.getScaleX(), + locViewSize.height - locContentSize.height * locContainer.getScaleY()); }, /** * Returns the current container's maximum offset. You may want this while you animate scrolling by yourself + * @return {cc.Point} Returns the current container's maximum offset. */ maxContainerOffset:function () { return cc.p(0.0, 0.0); @@ -258,9 +272,9 @@ cc.ScrollView = cc.Layer.extend({ var size = this.getViewSize(); var scale = this.getZoomScale(); - var viewRect = cc.RectMake(-offset.x / scale, -offset.y / scale, size.width / scale, size.height / scale); + var viewRect = cc.rect(-offset.x / scale, -offset.y / scale, size.width / scale, size.height / scale); - return cc.CCRectIntersectsRect(viewRect, node.getBoundingBox()); + return cc.rectIntersectsRect(viewRect, node.getBoundingBox()); }, /** @@ -279,7 +293,7 @@ cc.ScrollView = cc.Layer.extend({ */ resume:function (sender) { var selChildren = this._container.getChildren(); - for (var i = 0; i < selChildren.length; i++) { + for (var i = 0, len = selChildren.length; i < len; i++) { selChildren[i].resumeSchedulerAndActions(); } @@ -328,10 +342,10 @@ cc.ScrollView = cc.Layer.extend({ this.removeAllChildren(true); this._container = container; - this._container.ignoreAnchorPointForPosition(false); - this._container.setAnchorPoint(cc.p(0.0, 0.0)); + container.ignoreAnchorPointForPosition(false); + container.setAnchorPoint(cc.p(0.0, 0.0)); - this.addChild(this._container); + this.addChild(container); this.setViewSize(this._viewSize); }, @@ -358,29 +372,32 @@ cc.ScrollView = cc.Layer.extend({ if (!this.isVisible()) return false; //var frameOriginal = this.getParent().convertToWorldSpace(this.getPosition()); - //var frame = cc.RectMake(frameOriginal.x, frameOriginal.y, this._viewSize.width, this._viewSize.height); + //var frame = cc.rect(frameOriginal.x, frameOriginal.y, this._viewSize.width, this._viewSize.height); var frame = this._getViewRect(); //dispatcher does not know about clipping. reject touches outside visible bounds. - var locPoint = this._container.convertToWorldSpace(this._container.convertTouchToNodeSpace(touch)); - if (this._touches.length > 2 || this._touchMoved || !cc.rectContainsPoint(frame, locPoint)) + var locContainer = this._container; + var locPoint = locContainer.convertToWorldSpace(locContainer.convertTouchToNodeSpace(touch)); + var locTouches = this._touches; + if (locTouches.length > 2 || this._touchMoved || !cc.rectContainsPoint(frame, locPoint)) return false; //if (!cc.ArrayContainsObject(this._touches, touch)) { - this._touches.push(touch); + locTouches.push(touch); //} - if (this._touches.length == 1) { // scrolling + if (locTouches.length == 1) { // scrolling this._touchPoint = this.convertTouchToNodeSpace(touch); this._touchMoved = false; this._dragging = true; //dragging started - this._scrollDistance = cc.p(0.0, 0.0); + this._scrollDistance.x = 0; + this._scrollDistance.y = 0; this._touchLength = 0.0; - } else if (this._touches.length == 2) { - this._touchPoint = cc.pMidpoint(this.convertTouchToNodeSpace(this._touches[0]), - this.convertTouchToNodeSpace(this._touches[1])); - this._touchLength = cc.pDistance(this._container.convertTouchToNodeSpace(this._touches[0]), - this._container.convertTouchToNodeSpace(this._touches[1])); + } else if (locTouches.length == 2) { + this._touchPoint = cc.pMidpoint(this.convertTouchToNodeSpace(locTouches[0]), + this.convertTouchToNodeSpace(locTouches[1])); + this._touchLength = cc.pDistance(locContainer.convertTouchToNodeSpace(locTouches[0]), + locContainer.convertTouchToNodeSpace(locTouches[1])); this._dragging = false; } return true; @@ -394,20 +411,20 @@ cc.ScrollView = cc.Layer.extend({ if (this._touches.length === 1 && this._dragging) { // scrolling this._touchMoved = true; //var frameOriginal = this.getParent().convertToWorldSpace(this.getPosition()); - //var frame = cc.RectMake(frameOriginal.x, frameOriginal.y, this._viewSize.width, this._viewSize.height); + //var frame = cc.rect(frameOriginal.x, frameOriginal.y, this._viewSize.width, this._viewSize.height); var frame = this._getViewRect(); //var newPoint = this.convertTouchToNodeSpace(this._touches[0]); var newPoint = this.convertTouchToNodeSpace(touch); var moveDistance = cc.pSub(newPoint, this._touchPoint); - var dis = 0.0; - if (this._direction === cc.SCROLLVIEW_DIRECTION_VERTICAL) + var dis = 0.0, locDirection = this._direction; + if (locDirection === cc.SCROLLVIEW_DIRECTION_VERTICAL) dis = moveDistance.y; - else if (this._direction === cc.SCROLLVIEW_DIRECTION_HORIZONTAL) + else if (locDirection === cc.SCROLLVIEW_DIRECTION_HORIZONTAL) dis = moveDistance.x; else - dis = Math.sqrt(moveDistance.x * moveDistance.x + moveDistance.y*moveDistance.y); + dis = Math.sqrt(moveDistance.x * moveDistance.x + moveDistance.y * moveDistance.y); if (!this._touchMoved && Math.abs(cc.convertDistanceFromPointToInch(dis)) < MOVE_INCH ){ //CCLOG("Invalid movement, distance = [%f, %f], disInch = %f", moveDistance.x, moveDistance.y); @@ -423,24 +440,25 @@ cc.ScrollView = cc.Layer.extend({ this._touchMoved = true; if (cc.rectContainsPoint(frame, this.convertToWorldSpace(newPoint))) { - switch (this._direction) { + switch (locDirection) { case cc.SCROLLVIEW_DIRECTION_VERTICAL: - moveDistance = cc.p(0.0, moveDistance.y); + moveDistance.x = 0.0; break; case cc.SCROLLVIEW_DIRECTION_HORIZONTAL: - moveDistance = cc.p(moveDistance.x, 0.0); + moveDistance.y = 0.0; break; default: break; } - var newX = this._container.getPosition().x + moveDistance.x; - var newY = this._container.getPosition().y + moveDistance.y; + var locPosition = this._container.getPosition(); + var newX = locPosition.x + moveDistance.x; + var newY = locPosition.y + moveDistance.y; this._scrollDistance = moveDistance; this.setContentOffset(cc.p(newX, newY)); } - } else if (this._touches.length == 2 && !this._dragging) { + } else if (this._touches.length === 2 && !this._dragging) { var len = cc.pDistance(this._container.convertTouchToNodeSpace(this._touches[0]), this._container.convertTouchToNodeSpace(this._touches[1])); this.setZoomScale(this.getZoomScale() * len / this._touchLength); @@ -481,12 +499,13 @@ cc.ScrollView = cc.Layer.extend({ updateInset:function () { if (this.getContainer() != null) { - this._maxInset = this.maxContainerOffset(); - this._maxInset = cc.p(this._maxInset.x + this._viewSize.width * INSET_RATIO, - this._maxInset.y + this._viewSize.height * INSET_RATIO); - this._minInset = this.minContainerOffset(); - this._minInset = cc.p(this._minInset.x - this._viewSize.width * INSET_RATIO, - this._minInset.y - this._viewSize.height * INSET_RATIO); + var locViewSize = this._viewSize; + var tempOffset = this.maxContainerOffset(); + this._maxInset.x = tempOffset.x + locViewSize.width * INSET_RATIO; + this._maxInset.y = tempOffset.y + locViewSize.height * INSET_RATIO; + tempOffset = this.minContainerOffset(); + this._minInset.x = tempOffset.x - locViewSize.width * INSET_RATIO; + this._minInset.y = tempOffset.y - locViewSize.height * INSET_RATIO; } }, @@ -507,18 +526,20 @@ cc.ScrollView = cc.Layer.extend({ return; var context = ctx || cc.renderContext; - var i; + var i, locChildren = this._children, selChild, childrenLen; if (cc.renderContextType === cc.CANVAS) { context.save(); this.transform(context); this._beforeDraw(context); - if (this._children && this._children.length > 0) { + if (locChildren && locChildren.length > 0) { + childrenLen = locChildren.length; this.sortAllChildren(); // draw children zOrder < 0 - for (i = 0; i < this._children.length; i++) { - if (this._children[i] && this._children[i]._zOrder < 0) - this._children[i].visit(context); + for (i = 0; i < childrenLen; i++) { + selChild = locChildren[i]; + if (selChild && selChild._zOrder < 0) + selChild.visit(context); else break; } @@ -526,12 +547,8 @@ cc.ScrollView = cc.Layer.extend({ this.draw(context); // self draw // draw children zOrder >= 0 - if (this._children) { - for (; i < this._children.length; i++) { - if (this._children[i] && this._children[i]._zOrder >= 0) - this._children[i].visit(context); - } - } + for (; i < childrenLen; i++) + locChildren[i].visit(context); } else this.draw(context); // self draw @@ -540,19 +557,21 @@ cc.ScrollView = cc.Layer.extend({ context.restore(); } else { cc.kmGLPushMatrix(); - if (this._grid && this._grid.isActive()) { - this._grid.beforeDraw(); + var locGrid = this._grid; + if (locGrid && locGrid.isActive()) { + locGrid.beforeDraw(); this.transformAncestors(); } this.transform(context); this._beforeDraw(context); - if (this._children) { - i = 0; + if (locChildren && locChildren.length > 0) { + childrenLen = locChildren.length; // draw children zOrder < 0 - for (; i < this._children.length; i++) { - if (this._children[i].getZOrder() < 0) - this._children[i].visit(); + for (i = 0; i < childrenLen; i++) { + selChild = locChildren[i]; + if (selChild && selChild._zOrder < 0) + selChild.visit(); else break; } @@ -561,14 +580,14 @@ cc.ScrollView = cc.Layer.extend({ this.draw(context); // draw children zOrder >= 0 - for (; i < this._children.length; i++) - this._children[i].visit(); + for (; i < childrenLen; i++) + locChildren[i].visit(); } else this.draw(context); this._afterDraw(context); - if (this._grid && this._grid.isActive()) - this._grid.afterDraw(this); + if (locGrid && locGrid.isActive()) + locGrid.afterDraw(this); cc.kmGLPopMatrix(); } @@ -586,12 +605,12 @@ cc.ScrollView = cc.Layer.extend({ if (this._container != child) { this._container.addChild(child, zOrder, tag); } else { - this._super(child, zOrder, tag); + cc.Layer.prototype.addChild.call(this, child, zOrder, tag); } }, setTouchEnabled:function (e) { - this._super(e); + cc.Layer.prototype.setTouchEnabled.call(this, e); if (!e) { this._dragging = false; this._touchMoved = false; @@ -617,16 +636,17 @@ cc.ScrollView = cc.Layer.extend({ _relocateContainer:function (animated) { var min = this.minContainerOffset(); var max = this.maxContainerOffset(); + var locDirection = this._direction; var oldPoint = this._container.getPosition(); var newX = oldPoint.x; var newY = oldPoint.y; - if (this._direction == cc.SCROLLVIEW_DIRECTION_BOTH || this._direction == cc.SCROLLVIEW_DIRECTION_HORIZONTAL) { + if (locDirection === cc.SCROLLVIEW_DIRECTION_BOTH || locDirection === cc.SCROLLVIEW_DIRECTION_HORIZONTAL) { newX = Math.max(newX, min.x); newX = Math.min(newX, max.x); } - if (this._direction == cc.SCROLLVIEW_DIRECTION_BOTH || this._direction == cc.SCROLLVIEW_DIRECTION_VERTICAL) { + if (locDirection == cc.SCROLLVIEW_DIRECTION_BOTH || locDirection == cc.SCROLLVIEW_DIRECTION_VERTICAL) { newY = Math.min(newY, max.y); newY = Math.max(newY, min.y); } @@ -648,7 +668,9 @@ cc.ScrollView = cc.Layer.extend({ } var maxInset, minInset; - this._container.setPosition(cc.pAdd(this._container.getPosition(), this._scrollDistance)); + var oldPosition = this._container.getPosition(); + var locScrollDistance = this._scrollDistance; + this._container.setPosition(oldPosition.x + locScrollDistance.x , oldPosition.y + locScrollDistance.y); if (this._bounceable) { maxInset = this._maxInset; minInset = this._minInset; @@ -662,15 +684,22 @@ cc.ScrollView = cc.Layer.extend({ newX = Math.max(newX, minInset.x); var newY = Math.min(this._container.getPosition().y, maxInset.y); newY = Math.max(newY, minInset.y);*/ - var newX = this._container.getPosition().x; - var newY = this._container.getPosition().y; + oldPosition.x = this._container.getPositionX(); + oldPosition.y = this._container.getPositionY(); + var newX = oldPosition.x; + var newY = oldPosition.y; + + //this._scrollDistance = cc.pSub(this._scrollDistance, cc.p(newX - this._container.getPosition().x, newY - this._container.getPosition().y)); + //= this._scrollDistance = cc.pSub(this._scrollDistance, cc.p(0, 0)); = do nothing + + //this._scrollDistance = cc.pMult(this._scrollDistance, SCROLL_DEACCEL_RATE); + locScrollDistance.x = locScrollDistance.x * SCROLL_DEACCEL_RATE; + locScrollDistance.y = locScrollDistance.y * SCROLL_DEACCEL_RATE; - this._scrollDistance = cc.pSub(this._scrollDistance, cc.p(newX - this._container.getPosition().x, newY - this._container.getPosition().y)); - this._scrollDistance = cc.pMult(this._scrollDistance, SCROLL_DEACCEL_RATE); this.setContentOffset(cc.p(newX, newY)); - if ((Math.abs(this._scrollDistance.x) <= SCROLL_DEACCEL_DIST && - Math.abs(this._scrollDistance.y) <= SCROLL_DEACCEL_DIST) || + if ((Math.abs(locScrollDistance.x) <= SCROLL_DEACCEL_DIST && + Math.abs(locScrollDistance.y) <= SCROLL_DEACCEL_DIST) || newY > maxInset.y || newY < minInset.y || newX > maxInset.x || newX < minInset.x || newX == maxInset.x || newX == minInset.x || @@ -710,25 +739,25 @@ cc.ScrollView = cc.Layer.extend({ this._scissorRestored = false; var frame = this._getViewRect(); - var screenPos; - var scaleValue = this.getScale(); + var scaleX = this.getScaleX(); + var scaleY = this.getScaleY(); var ctx = context || cc.renderContext; if (cc.renderContextType === cc.CANVAS) { - screenPos = this.getParent().getPosition(); - var getWidth = (this._viewSize.width * scaleValue); - var getHeight = (this._viewSize.height * scaleValue); - var startX = screenPos.x * scaleValue; - var startY = screenPos.y * scaleValue;// + this._anchorPointInPoints.y; + var getWidth = (this._viewSize.width * scaleX); + var getHeight = (this._viewSize.height * scaleY); + var startX = 0; + var startY = 0; ctx.beginPath(); ctx.rect(startX, startY, getWidth, -getHeight); ctx.clip(); ctx.closePath(); } else { - if(cc.EGLView.getInstance().isScissorEnabled()){ + var EGLViewer = cc.EGLView.getInstance(); + if(EGLViewer.isScissorEnabled()){ this._scissorRestored = true; - this._parentScissorRect = cc.EGLView.getInstance().getScissorRect(); + this._parentScissorRect = EGLViewer.getScissorRect(); //set the intersection of m_tParentScissorRect and frame as the new scissor rect if (cc.rectIntersection(frame, this._parentScissorRect)) { var locPSRect = this._parentScissorRect; @@ -736,14 +765,13 @@ cc.ScrollView = cc.Layer.extend({ var y = Math.max(frame.y, locPSRect.y); var xx = Math.min(frame.x + frame.width, locPSRect.x + locPSRect.width); var yy = Math.min(frame.y + frame.height, locPSRect.y + locPSRect.height); - cc.EGLView.getInstance().setScissorInPoints(x, y, xx - x, yy - y); + EGLViewer.setScissorInPoints(x, y, xx - x, yy - y); } }else{ ctx.enable(ctx.SCISSOR_TEST); //clip - cc.EGLView.getInstance().setScissorInPoints(frame.x, frame.y, frame.width, frame.height); + EGLViewer.setScissorInPoints(frame.x, frame.y, frame.width, frame.height); } - } } }, @@ -770,6 +798,7 @@ cc.ScrollView = cc.Layer.extend({ _getViewRect:function(){ var screenPos = this.convertToWorldSpace(cc.PointZero()); + var locViewSize = this._viewSize; var scaleX = this.getScaleX(); var scaleY = this.getScaleY(); @@ -782,15 +811,21 @@ cc.ScrollView = cc.Layer.extend({ // Support negative scaling. Not doing so causes intersectsRect calls // (eg: to check if the touch was within the bounds) to return false. // Note, CCNode::getScale will assert if X and Y scales are different. - if(scaleX<0) { - screenPos.x += this._viewSize.width*scaleX; + if (scaleX < 0) { + screenPos.x += locViewSize.width * scaleX; scaleX = -scaleX; } - if(scaleY<0) { - screenPos.y += this._viewSize.height*scaleY; + if (scaleY < 0) { + screenPos.y += locViewSize.height * scaleY; scaleY = -scaleY; } - return cc.RectMake(screenPos.x, screenPos.y, this._viewSize.width * scaleX, this._viewSize.height * scaleY); + + var locViewRect = this._tmpViewRect; + locViewRect.x = screenPos.x; + locViewRect.y = screenPos.y; + locViewRect.width = locViewSize.width * scaleX; + locViewRect.height = locViewSize.height * scaleY; + return locViewRect; } }); diff --git a/extensions/GUI/CCScrollView/CCSorting.js b/extensions/GUI/CCScrollView/CCSorting.js index ede6e0811c..205cfa8fe0 100644 --- a/extensions/GUI/CCScrollView/CCSorting.js +++ b/extensions/GUI/CCScrollView/CCSorting.js @@ -52,7 +52,7 @@ var _compareObject = function (val1, val2) { }; cc.ArrayForObjectSorting = cc.Class.extend({ - _saveObjectArr:[], + _saveObjectArr:null, ctor:function () { this._saveObjectArr = []; @@ -128,9 +128,8 @@ cc.ArrayForObjectSorting = cc.Class.extend({ var idx = this.indexOfSortedObject(foundObj); if (idx < this.count() && idx != cc.INVALID_INDEX) { foundObj = this.objectAtIndex(idx); - if (foundObj.getObjectID() != tag) { + if (foundObj.getObjectID() != tag) foundObj = null; - } } return foundObj; }, @@ -167,8 +166,9 @@ cc.ArrayForObjectSorting = cc.Class.extend({ var uPrevObjectID = 0; var uOfSortObjectID = idxObj.getObjectID(); - for (var i = 0; i < this._saveObjectArr.length; i++) { - var pSortableObj = this._saveObjectArr[i]; + var locObjectArr = this._saveObjectArr; + for (var i = 0; i < locObjectArr.length; i++) { + var pSortableObj = locObjectArr[i]; var curObjectID = pSortableObj.getObjectID(); if ((uOfSortObjectID == curObjectID) || (uOfSortObjectID >= uPrevObjectID && uOfSortObjectID < curObjectID)) { @@ -189,9 +189,10 @@ cc.ArrayForObjectSorting = cc.Class.extend({ }, lastObject:function () { - if (this._saveObjectArr.length == 0) + var locObjectArr = this._saveObjectArr; + if (locObjectArr.length == 0) return null; - return this._saveObjectArr[this._saveObjectArr.length - 1]; + return locObjectArr[locObjectArr.length - 1]; }, objectAtIndex:function (idx) { diff --git a/extensions/GUI/CCScrollView/CCTableView.js b/extensions/GUI/CCScrollView/CCTableView.js index a015bc0ee1..2156eda1f7 100644 --- a/extensions/GUI/CCScrollView/CCTableView.js +++ b/extensions/GUI/CCScrollView/CCTableView.js @@ -64,10 +64,42 @@ cc.TableViewDelegate = cc.ScrollViewDelegate.extend({ /** * Delegate to respond touch event * - * @param table table contains the given cell - * @param cell cell that is touched + * @param {cc.TableView} table table contains the given cell + * @param {cc.TableViewCell} cell cell that is touched */ tableCellTouched:function (table, cell) { + }, + + /** + * Delegate to respond a table cell press event. + * + * @param {cc.TableView} table table contains the given cell + * @param {cc.TableViewCell} cell cell that is pressed + */ + tableCellHighlight:function(table, cell){ + }, + + /** + * Delegate to respond a table cell release event + * + * @param {cc.TableView} table table contains the given cell + * @param {cc.TableViewCell} cell cell that is pressed + */ + tableCellUnhighlight:function(table, cell){ + + }, + + /** + *

+ * Delegate called when the cell is about to be recycled. Immediately
+ * after this call the cell will be removed from the scene graph and
+ * recycled. + *

+ * @param table table contains the given cell + * @param cell cell that is pressed + */ + tableCellWillRecycle:function(table, cell){ + } }); @@ -75,30 +107,39 @@ cc.TableViewDelegate = cc.ScrollViewDelegate.extend({ * Data source that governs table backend data. */ cc.TableViewDataSource = cc.Class.extend({ + /** + * cell size for a given index + * @param {cc.TableView} table table to hold the instances of Class + * @param {Number} idx the index of a cell to get a size + * @return {cc.Size} size of a cell at given index + */ + tableCellSizeForIndex:function(table, idx){ + return this.cellSizeForTable(table); + }, /** * cell height for a given table. * - * @param table table to hold the instances of Class - * @return cell size + * @param {cc.TableView} table table to hold the instances of Class + * @return {cc.Size} cell size */ cellSizeForTable:function (table) { - return 0; + return cc.SIZE_ZERO; }, /** * a cell instance at a given index - * + * @param {cc.TableView} table table to hold the instances of Class * @param idx index to search for a cell - * @return cell found at idx + * @return {cc.TableView} cell found at idx */ tableCellAtIndex:function (table, idx) { - return 0; + return null; }, /** * Returns number of cells in a given table view. - * - * @return number of cells + * @param {cc.TableView} table table to hold the instances of Class + * @return {Number} number of cells */ numberOfCellsInTableView:function (table) { return 0; @@ -120,7 +161,7 @@ cc.TableView = cc.ScrollView.extend({ _oldDirection:null, ctor:function () { - this._super(); + cc.ScrollView.prototype.ctor.call(this); this._oldDirection = cc.SCROLLVIEW_DIRECTION_NONE; }, @@ -140,11 +181,12 @@ cc.TableView = cc.ScrollView.extend({ }, _indexFromOffset:function (offset) { - var maxIdx = this._dataSource.numberOfCellsInTableView(this) - 1; + var locDataSource = this._dataSource; + var maxIdx = locDataSource.numberOfCellsInTableView(this) - 1; var offset1 = new cc.Point(offset.x, offset.y); - var cellSize = this._dataSource.cellSizeForTable(this); + var cellSize = locDataSource.cellSizeForTable(this); if (this._vOrdering == cc.TABLEVIEW_FILL_TOPDOWN) { offset1.y = this.getContainer().getContentSize().height - offset.y - cellSize.height; } @@ -175,9 +217,9 @@ cc.TableView = cc.ScrollView.extend({ var offset = this.__offsetFromIndex(index); var cellSize = this._dataSource.cellSizeForTable(this); - if (this._vOrdering == cc.TABLEVIEW_FILL_TOPDOWN) { + if (this._vOrdering === cc.TABLEVIEW_FILL_TOPDOWN) offset.y = this.getContainer().getContentSize().height - offset.y - cellSize.height; - } + return offset; }, @@ -189,10 +231,10 @@ cc.TableView = cc.ScrollView.extend({ switch (this.getDirection()) { case cc.SCROLLVIEW_DIRECTION_HORIZONTAL: - size = cc.SizeMake(cellCount * cellSize.width, cellSize.height); + size = cc.size(cellCount * cellSize.width, cellSize.height); break; default: - size = cc.SizeMake(cellSize.width, cellCount * cellSize.height); + size = cc.size(cellSize.width, cellCount * cellSize.height); break; } this.setContentSize(size); @@ -262,11 +304,7 @@ cc.TableView = cc.ScrollView.extend({ return this._tableViewDelegate; }, - setDelegate:function (delegate, isDirectCall) { - if (isDirectCall != null && isDirectCall == true) { - this._super(delegate); - return; - } + setDelegate:function (delegate) { this._tableViewDelegate = delegate; }, @@ -286,7 +324,7 @@ cc.TableView = cc.ScrollView.extend({ }, initWithViewSize:function (size, container) { - if (this._super(size, container)) { + if (cc.ScrollView.prototype.initWithViewSize.call(this, size, container)) { this._cellsUsed = new cc.ArrayForObjectSorting(); this._cellsFreed = new cc.ArrayForObjectSorting(); this._indices = new cc.Set(); @@ -294,7 +332,7 @@ cc.TableView = cc.ScrollView.extend({ this._vOrdering = cc.TABLEVIEW_FILL_BOTTOMUP; this.setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL); - this.setDelegate(this, true); + cc.ScrollView.prototype.setDelegate.call(this, this); return true; } return false; @@ -311,9 +349,8 @@ cc.TableView = cc.ScrollView.extend({ } var cell = this._cellWithIndex(idx); - if (cell) { + if (cell) this._moveCellOutOfSight(cell); - } cell = this._dataSource.tableCellAtIndex(this, idx); this._setIndexForCell(idx, cell); @@ -330,13 +367,12 @@ cc.TableView = cc.ScrollView.extend({ return; } - var newIdx; - - var cell = this._cellsUsed.objectWithObjectID(idx); + var newIdx, locCellsUsed = this._cellsUsed; + var cell = locCellsUsed.objectWithObjectID(idx); if (cell) { - newIdx = this._cellsUsed.indexOfSortedObject(cell); - for (var i = newIdx; i < this._cellsUsed.count(); i++) { - cell = this._cellsUsed.objectAtIndex(i); + newIdx = locCellsUsed.indexOfSortedObject(cell); + for (var i = newIdx; i < locCellsUsed.count(); i++) { + cell = locCellsUsed.objectAtIndex(i); this._setIndexForCell(cell.getIdx() + 1, cell); } } @@ -360,11 +396,11 @@ cc.TableView = cc.ScrollView.extend({ } var cell = this._cellWithIndex(idx); - if (!cell) { + if (!cell) return; - } - var newIdx = this._cellsUsed.indexOfSortedObject(cell); + var locCellsUsed = this._cellsUsed; + var newIdx = locCellsUsed.indexOfSortedObject(cell); //remove first this._moveCellOutOfSight(cell); @@ -372,8 +408,8 @@ cc.TableView = cc.ScrollView.extend({ this._indices.removeObject(idx); //cc.ArrayRemoveObjectAtIndex(this._indices,idx); - for (var i = this._cellsUsed.count() - 1; i > newIdx; i--) { - cell = this._cellsUsed.objectAtIndex(i); + for (var i = locCellsUsed.count() - 1; i > newIdx; i--) { + cell = locCellsUsed.objectAtIndex(i); this._setIndexForCell(cell.getIdx() - 1, cell); } }, @@ -382,22 +418,22 @@ cc.TableView = cc.ScrollView.extend({ * reloads data from data source. the view will be refreshed. */ reloadData:function () { - for (var i = 0; i < this._cellsUsed.count(); i++) { - var cell = this._cellsUsed.objectAtIndex(i); - this._cellsFreed.addObject(cell); + this._oldDirection = cc.SCROLLVIEW_DIRECTION_NONE; + var locCellsUsed = this._cellsUsed, locCellsFreed = this._cellsFreed, locContainer = this.getContainer(); + for (var i = 0; i < locCellsUsed.count(); i++) { + var cell = locCellsUsed.objectAtIndex(i); + locCellsFreed.addObject(cell); cell.reset(); - if (cell.getParent() == this.getContainer()) { - this.getContainer().removeChild(cell, true); - } + if (cell.getParent() == locContainer) + locContainer.removeChild(cell, true); } this._indices = new cc.Set(); this._cellsUsed = new cc.ArrayForObjectSorting(); this._updateContentSize(); - if (this._dataSource.numberOfCellsInTableView(this) > 0) { + if (this._dataSource.numberOfCellsInTableView(this) > 0) this.scrollViewDidScroll(this); - } }, /** @@ -426,7 +462,8 @@ cc.TableView = cc.ScrollView.extend({ }, scrollViewDidScroll:function (view) { - var countOfItems = this._dataSource.numberOfCellsInTableView(this); + var locDataSource = this._dataSource; + var countOfItems = locDataSource.numberOfCellsInTableView(this); if (0 === countOfItems) return; @@ -435,32 +472,32 @@ cc.TableView = cc.ScrollView.extend({ var idx = 0; var offset = cc.pMult(this.getContentOffset(), -1); - var maxIdx = Math.max(this._dataSource.numberOfCellsInTableView(this) - 1, 0); + var maxIdx = Math.max(locDataSource.numberOfCellsInTableView(this) - 1, 0); - var cellSize = this._dataSource.cellSizeForTable(this); - - if (this._vOrdering == cc.TABLEVIEW_FILL_TOPDOWN) { - offset.y = offset.y + this._viewSize.height / this.getContainer().getScaleY() - cellSize.height; + var cellSize = locDataSource.cellSizeForTable(this); + var locViewSize = this._viewSize, locContainer = this.getContainer(); + if (this._vOrdering === cc.TABLEVIEW_FILL_TOPDOWN) { + offset.y = offset.y + locViewSize.height / locContainer.getScaleY() - cellSize.height; } var startIdx = 0 | this._indexFromOffset(offset); - if (this._vOrdering == cc.TABLEVIEW_FILL_TOPDOWN) { - offset.y -= this._viewSize.height / this.getContainer().getScaleY(); + if (this._vOrdering === cc.TABLEVIEW_FILL_TOPDOWN) { + offset.y -= locViewSize.height / locContainer.getScaleY(); } else { - offset.y += this._viewSize.height / this.getContainer().getScaleY(); + offset.y += locViewSize.height / locContainer.getScaleY(); } - offset.x += this._viewSize.width / this.getContainer().getScaleX(); + offset.x += locViewSize.width / locContainer.getScaleX(); var endIdx = 0 | this._indexFromOffset(offset); - var cell; - if (this._cellsUsed.count() > 0) { - cell = this._cellsUsed.objectAtIndex(0); + var cell, locCellsUsed = this._cellsUsed; + if (locCellsUsed.count() > 0) { + cell = locCellsUsed.objectAtIndex(0); idx = cell.getIdx(); while (idx < startIdx) { this._moveCellOutOfSight(cell); - if (this._cellsUsed.count() > 0) { - cell = this._cellsUsed.objectAtIndex(0); + if (locCellsUsed.count() > 0) { + cell = locCellsUsed.objectAtIndex(0); idx = cell.getIdx(); } else { break; @@ -468,13 +505,13 @@ cc.TableView = cc.ScrollView.extend({ } } - if (this._cellsUsed.count() > 0) { - cell = this._cellsUsed.lastObject(); + if (locCellsUsed.count() > 0) { + cell = locCellsUsed.lastObject(); idx = cell.getIdx(); while (idx <= maxIdx && idx > endIdx) { this._moveCellOutOfSight(cell); - if (this._cellsUsed.count() > 0) { - cell = this._cellsUsed.lastObject(); + if (locCellsUsed.count() > 0) { + cell = locCellsUsed.lastObject(); idx = cell.getIdx(); } else { break; @@ -482,10 +519,10 @@ cc.TableView = cc.ScrollView.extend({ } } + var locIndices = this._indices; for (var i = startIdx; i <= endIdx; i++) { - if (this._indices.containsObject(i)) { + if (locIndices.containsObject(i)) continue; - } this.updateCellAtIndex(i); } }, @@ -494,33 +531,32 @@ cc.TableView = cc.ScrollView.extend({ }, onTouchEnded:function (touch, event) { - if (!this.isVisible()) { + if (!this.isVisible()) return; - } + if (this._touches.length == 1 && !this.isTouchMoved()) { var point = this.getContainer().convertTouchToNodeSpace(touch); - if (this._vOrdering == cc.TABLEVIEW_FILL_TOPDOWN) { + if (this._vOrdering === cc.TABLEVIEW_FILL_TOPDOWN) { var cellSize = this._dataSource.cellSizeForTable(this); point.y -= cellSize.height; } var index = 0 | this._indexFromOffset(point); var cell = this._cellWithIndex(index); - if (cell) { + if (cell) this._tableViewDelegate.tableCellTouched(this, cell); - } } - this._super(touch, event); + cc.ScrollView.prototype.onTouchEnded.call(this, touch, event); } }); /** * An initialized table view object * - * @param dataSource data source; - * @param size view size - * @param container parent object for cells - * @return table view + * @param {cc.TableViewDataSource} dataSource data source; + * @param {cc.Size} size view size + * @param {cc.Node} container parent object for cells + * @return {cc.TableView} table view */ cc.TableView.create = function (dataSource, size, container) { var table = new cc.TableView(); diff --git a/extensions/PluginX/samples/HelloSocial/cocos2d.js b/extensions/PluginX/samples/HelloSocial/cocos2d.js index f3f3a40733..851a010f79 100644 --- a/extensions/PluginX/samples/HelloSocial/cocos2d.js +++ b/extensions/PluginX/samples/HelloSocial/cocos2d.js @@ -60,6 +60,7 @@ window.addEventListener('DOMContentLoaded', function () { + this.removeEventListener('DOMContentLoaded', arguments.callee, false); //first load engine file if specified var s = d.createElement('script'); /*********Delete this section if you have packed all files into one*******/ diff --git a/index.html b/index.html index 31f2391edc..80b0b618c2 100644 --- a/index.html +++ b/index.html @@ -55,6 +55,7 @@

  • Test cases - Engine Testcases
  • Template - Cocos2d-html5 Template
  • MoonWarriors - Game
  • +
  • Fruit Attack - Game
  • Watermelon with Me - Game
  • CocosDragon - Game
  • Crystal Craze - Game
  • diff --git a/samples b/samples index 714ea94824..022292761c 160000 --- a/samples +++ b/samples @@ -1 +1 @@ -Subproject commit 714ea9482432a94a2d58ca265c97c61b5b369919 +Subproject commit 022292761c6a9d056e25cc6e844430650208513f diff --git a/template/build.xml b/template/build.xml index f230d2f633..e8394e89be 100644 --- a/template/build.xml +++ b/template/build.xml @@ -95,7 +95,6 @@ - @@ -158,27 +157,25 @@ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + diff --git a/template/cocos2d.js b/template/cocos2d.js index f657b9d7fc..ddc50c1494 100644 --- a/template/cocos2d.js +++ b/template/cocos2d.js @@ -33,6 +33,7 @@ showFPS:true, loadExtension:false, frameRate:60, + renderMode:0, //Choose of RenderMode: 0(default), 1(Canvas only), 2(WebGL only) tag:'gameCanvas', //the dom element to run cocos2d on engineDir:'../cocos2d/', //SingleEngineFile:'', @@ -58,11 +59,25 @@ window.addEventListener('DOMContentLoaded', function () { + this.removeEventListener('DOMContentLoaded', arguments.callee, false); //first load engine file if specified var s = d.createElement('script'); /*********Delete this section if you have packed all files into one*******/ if (c.SingleEngineFile && !c.engineDir) { s.src = c.SingleEngineFile; + + var loadJsImg = new Image(); + loadJsImg.src = "data:image/gif;base64,R0lGODlhEAAQALMNAD8/P7+/vyoqKlVVVX9/fxUVFUBAQGBgYMDAwC8vL5CQkP///wAAAP///wAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFAAANACwAAAAAEAAQAAAEO5DJSau9OOvNex0IMnDIsiCkiW6g6BmKYlBFkhSUEgQKlQCARG6nEBwOgl+QApMdCIRD7YZ5RjlGpCUCACH5BAUAAA0ALAAAAgAOAA4AAAQ6kLGB0JA4M7QW0hrngRllkYyhKAYqKUGguAws0ypLS8JxCLQDgXAIDg+FRKIA6v0SAECCBpXSkstMBAAh+QQFAAANACwAAAAACgAQAAAEOJDJORAac6K1kDSKYmydpASBUl0mqmRfaGTCcQgwcxDEke+9XO2WkxQSiUIuAQAkls0n7JgsWq8RACH5BAUAAA0ALAAAAAAOAA4AAAQ6kMlplDIzTxWC0oxwHALnDQgySAdBHNWFLAvCukc215JIZihVIZEogDIJACBxnCSXTcmwGK1ar1hrBAAh+QQFAAANACwAAAAAEAAKAAAEN5DJKc4RM+tDyNFTkSQF5xmKYmQJACTVpQSBwrpJNteZSGYoFWjIGCAQA2IGsVgglBOmEyoxIiMAIfkEBQAADQAsAgAAAA4ADgAABDmQSVZSKjPPBEDSGucJxyGA1XUQxAFma/tOpDlnhqIYN6MEAUXvF+zldrMBAjHoIRYLhBMqvSmZkggAIfkEBQAADQAsBgAAAAoAEAAABDeQyUmrnSWlYhMASfeFVbZdjHAcgnUQxOHCcqWylKEohqUEAYVkgEAMfkEJYrFA6HhKJsJCNFoiACH5BAUAAA0ALAIAAgAOAA4AAAQ3kMlJq704611SKloCAEk4lln3DQgyUMJxCBKyLAh1EMRR3wiDQmHY9SQslyIQUMRmlmVTIyRaIgA7"; + + var canvasNode = document.getElementById(c.tag); + canvasNode.style.backgroundColor = "black"; + canvasNode.parentNode.appendChild(loadJsImg); + + var canvasStyle = getComputedStyle?getComputedStyle(canvasNode):canvasNode.currentStyle; + loadJsImg.style.left = canvasNode.offsetLeft + (parseFloat(canvasStyle.width) - loadJsImg.width)/2 + "px"; + loadJsImg.style.top = canvasNode.offsetTop + (parseFloat(canvasStyle.height) - loadJsImg.height)/2 + "px"; + loadJsImg.style.position = "absolute"; + loadJsImg.id = "cocos2d_loadJsImg"; } else if (c.engineDir && !c.SingleEngineFile) { s.src = c.engineDir + 'platform/jsloader.js'; diff --git a/template/index.html b/template/index.html index d0fe274dbd..a5d692d68a 100644 --- a/template/index.html +++ b/template/index.html @@ -4,11 +4,12 @@ Cocos2d-html5 Hello World test - - + + + - + \ No newline at end of file diff --git a/template/main.js b/template/main.js index e2266e2522..7cccd2aaa2 100644 --- a/template/main.js +++ b/template/main.js @@ -39,8 +39,8 @@ var cocos2dApp = cc.Application.extend({ var director = cc.Director.getInstance(); var screenSize = cc.EGLView.getInstance().getFrameSize(); - var resourceSize = cc.size(800, 450); - var designSize = cc.size(800, 450); + var resourceSize = cc.size(480, 800); + var designSize = cc.size(480, 800); var searchPaths = []; var resDirOrders = []; @@ -50,24 +50,24 @@ var cocos2dApp = cc.Application.extend({ var platform = cc.Application.getInstance().getTargetPlatform(); if (platform == cc.TARGET_PLATFORM.MOBILE_BROWSER) { - if (screenSize.height > 450) { + resDirOrders.push("HD"); + } + else if (platform == cc.TARGET_PLATFORM.PC_BROWSER) { + if (screenSize.height >= 800) { resDirOrders.push("HD"); } else { - resourceSize = cc.size(400, 225); - designSize = cc.size(400, 225); + resourceSize = cc.size(320, 480); + designSize = cc.size(320, 480); resDirOrders.push("Normal"); } } - else if (platform == cc.TARGET_PLATFORM.PC_BROWSER) { - resDirOrders.push("HD"); - } cc.FileUtils.getInstance().setSearchResolutionsOrder(resDirOrders); director.setContentScaleFactor(resourceSize.width / designSize.width); - cc.EGLView.getInstance().setDesignResolutionSize(designSize.width, designSize.height, cc.RESOLUTION_POLICY.SHOW_ALL); + cc.EGLView.getInstance().setDesignResolutionSize(screenSize.width, screenSize.height, cc.RESOLUTION_POLICY.SHOW_ALL); // turn on display FPS director.setDisplayStats(this.config['showFPS']); diff --git a/template/res/HD/HelloWorld.jpg b/template/res/HD/HelloWorld.jpg new file mode 100644 index 0000000000..b886487f38 Binary files /dev/null and b/template/res/HD/HelloWorld.jpg differ diff --git a/template/res/HD/HelloWorld.png b/template/res/HD/HelloWorld.png deleted file mode 100644 index 323391cb92..0000000000 Binary files a/template/res/HD/HelloWorld.png and /dev/null differ diff --git a/template/res/Normal/HelloWorld.jpg b/template/res/Normal/HelloWorld.jpg new file mode 100644 index 0000000000..0b1badcde6 Binary files /dev/null and b/template/res/Normal/HelloWorld.jpg differ diff --git a/template/res/Normal/HelloWorld.png b/template/res/Normal/HelloWorld.png deleted file mode 100644 index 03bf58b66c..0000000000 Binary files a/template/res/Normal/HelloWorld.png and /dev/null differ diff --git a/template/src/myApp.js b/template/src/myApp.js index 44216c7123..81f2bd9fdb 100644 --- a/template/src/myApp.js +++ b/template/src/myApp.js @@ -41,7 +41,7 @@ var MyLayer = cc.Layer.extend({ // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // ask director the window size - var size = cc.Director.getInstance().getWinSize(); + var size = cc.Director.getInstance().getVisibleSize(); // add a "close" icon to exit the progress. it's an autorelease object var closeItem = cc.MenuItemImage.create( @@ -71,6 +71,7 @@ var MyLayer = cc.Layer.extend({ this.sprite = cc.Sprite.create(s_HelloWorld); this.sprite.setAnchorPoint(cc.p(0.5, 0.5)); this.sprite.setPosition(cc.p(size.width / 2, size.height / 2)); + this.sprite.setScale(size.height/this.sprite.getContentSize().height); this.addChild(this.sprite, 0); } }); diff --git a/template/src/resource.js b/template/src/resource.js index 385f14a08d..788c0b21d1 100644 --- a/template/src/resource.js +++ b/template/src/resource.js @@ -1,4 +1,4 @@ -var s_HelloWorld = "HelloWorld.png"; +var s_HelloWorld = "HelloWorld.jpg"; var s_CloseNormal = "CloseNormal.png"; var s_CloseSelected = "CloseSelected.png"; diff --git a/tools/jsdoc_toolkit/build.xml b/tools/jsdoc_toolkit/build.xml index 0f1977a8d3..c2b9c7e119 100644 --- a/tools/jsdoc_toolkit/build.xml +++ b/tools/jsdoc_toolkit/build.xml @@ -33,11 +33,13 @@ - + + + @@ -74,7 +76,6 @@ -