CCSpriteBatchNode.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  1. /****************************************************************************
  2. Copyright (c) 2008-2010 Ricardo Quesada
  3. Copyright (c) 2011-2012 cocos2d-x.org
  4. Copyright (c) 2013-2014 Chukong Technologies Inc.
  5. http://www.cocos2d-x.org
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. THE SOFTWARE.
  21. ****************************************************************************/
  22. /**
  23. * @constant
  24. * @type Number
  25. */
  26. cc.DEFAULT_SPRITE_BATCH_CAPACITY = 29;
  27. /**
  28. * <p>
  29. * In Canvas render mode ,cc.SpriteBatchNodeCanvas is like a normal node: if it contains children. <br/>
  30. * If its _useCache is set to true, it can cache the result that all children of SpriteBatchNode to a canvas <br/>
  31. * (often known as "batch draw").<br/>
  32. * <br/>
  33. * A cc.SpriteBatchNode can reference one and only one texture (one image file, one texture atlas).<br/>
  34. * Only the cc.Sprites that are contained in that texture can be added to the cc.SpriteBatchNode.<br/>
  35. * All cc.Sprites added to a cc.SpriteBatchNode are drawn in one WebGL draw call. <br/>
  36. * 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. <br/>
  37. * <br/>
  38. * Limitations:<br/>
  39. * - The only object that is accepted as child (or grandchild, grand-grandchild, etc...) is cc.Sprite or any subclass of cc.Sprite. <br/>
  40. * eg: particles, labels and layer can't be added to a cc.SpriteBatchNode. <br/>
  41. * - Either all its children are Aliased or Antialiased. It can't be a mix. <br/>
  42. * This is because "alias" is a property of the texture, and all the sprites share the same texture. </br>
  43. * </p>
  44. * @class
  45. * @extends cc.Node
  46. *
  47. * @param {String|cc.Texture2D} fileImage
  48. * @param {Number} capacity
  49. * @example
  50. *
  51. * // 1. create a SpriteBatchNode with image path
  52. * var spriteBatchNode = new cc.SpriteBatchNode("res/animations/grossini.png", 50);
  53. *
  54. * // 2. create a SpriteBatchNode with texture
  55. * var texture = cc.textureCache.addImage("res/animations/grossini.png");
  56. * var spriteBatchNode = new cc.SpriteBatchNode(texture,50);
  57. *
  58. * @property {cc.TextureAtlas} textureAtlas - The texture atlas
  59. * @property {Array} descendants - <@readonly> Descendants of sprite batch node
  60. */
  61. cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{
  62. textureAtlas: null,
  63. _blendFunc: null,
  64. // all descendants: chlidren, gran children, etc...
  65. _descendants: null,
  66. _className: "SpriteBatchNode",
  67. /**
  68. * <p>
  69. * This is the opposite of "addQuadFromSprite.<br/>
  70. * It add the sprite to the children and descendants array, but it doesn't update add it to the texture atlas<br/>
  71. * </p>
  72. * @param {cc.Sprite} child
  73. * @param {Number} z zOrder
  74. * @param {Number} aTag
  75. * @return {cc.SpriteBatchNode}
  76. */
  77. addSpriteWithoutQuad: function (child, z, aTag) {
  78. cc.assert(child, cc._LogInfos.SpriteBatchNode_addSpriteWithoutQuad_2);
  79. if (!(child instanceof cc.Sprite)) {
  80. cc.log(cc._LogInfos.SpriteBatchNode_addSpriteWithoutQuad);
  81. return null;
  82. }
  83. // quad index is Z
  84. child.atlasIndex = z;
  85. // XXX: optimize with a binary search
  86. var i = 0, locDescendants = this._descendants;
  87. if (locDescendants && locDescendants.length > 0) {
  88. for (var index = 0; index < locDescendants.length; index++) {
  89. var obj = locDescendants[index];
  90. if (obj && (obj.atlasIndex >= z))
  91. ++i;
  92. }
  93. }
  94. locDescendants.splice(i, 0, child);
  95. // IMPORTANT: Call super, and not self. Avoid adding it to the texture atlas array
  96. cc.Node.prototype.addChild.call(this, child, z, aTag);
  97. //#issue 1262 don't use lazy sorting, tiles are added as quads not as sprites, so sprites need to be added in order
  98. this.reorderBatch(false);
  99. return this;
  100. },
  101. // property
  102. /**
  103. * Return TextureAtlas of cc.SpriteBatchNode
  104. * @return {cc.TextureAtlas}
  105. */
  106. getTextureAtlas: function () {
  107. return this.textureAtlas;
  108. },
  109. /**
  110. * TextureAtlas of cc.SpriteBatchNode setter
  111. * @param {cc.TextureAtlas} textureAtlas
  112. */
  113. setTextureAtlas: function (textureAtlas) {
  114. if (textureAtlas != this.textureAtlas) {
  115. this.textureAtlas = textureAtlas;
  116. }
  117. },
  118. /**
  119. * Return Descendants of cc.SpriteBatchNode
  120. * @return {Array}
  121. */
  122. getDescendants: function () {
  123. return this._descendants;
  124. },
  125. /**
  126. * <p>
  127. * Initializes a cc.SpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and a capacity of children.<br/>
  128. * The capacity will be increased in 33% in runtime if it run out of space.<br/>
  129. * The file will be loaded using the TextureMgr.<br/>
  130. * Please pass parameters to constructor to initialize the sprite batch node, do not call this function yourself.
  131. * </p>
  132. * @param {String} fileImage
  133. * @param {Number} capacity
  134. * @return {Boolean}
  135. */
  136. initWithFile: function (fileImage, capacity) {
  137. var texture2D = cc.textureCache.getTextureForKey(fileImage);
  138. if (!texture2D)
  139. texture2D = cc.textureCache.addImage(fileImage);
  140. return this.initWithTexture(texture2D, capacity);
  141. },
  142. _setNodeDirtyForCache: function () {
  143. this._cacheDirty = true;
  144. },
  145. /**
  146. * <p>
  147. * initializes a cc.SpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and a capacity of children.<br/>
  148. * The capacity will be increased in 33% in runtime if it run out of space.<br/>
  149. * The file will be loaded using the TextureMgr.<br/>
  150. * Please pass parameters to constructor to initialize the sprite batch node, do not call this function yourself.
  151. * </p>
  152. * @param {String} fileImage
  153. * @param {Number} capacity
  154. * @return {Boolean}
  155. */
  156. init: function (fileImage, capacity) {
  157. var texture2D = cc.textureCache.getTextureForKey(fileImage);
  158. if (!texture2D)
  159. texture2D = cc.textureCache.addImage(fileImage);
  160. return this.initWithTexture(texture2D, capacity);
  161. },
  162. /**
  163. * Increase Atlas Capacity
  164. */
  165. increaseAtlasCapacity: function () {
  166. // if we're going beyond the current TextureAtlas's capacity,
  167. // all the previously initialized sprites will need to redo their texture coords
  168. // this is likely computationally expensive
  169. var locCapacity = this.textureAtlas.capacity;
  170. var quantity = Math.floor((locCapacity + 1) * 4 / 3);
  171. cc.log(cc._LogInfos.SpriteBatchNode_increaseAtlasCapacity, locCapacity, quantity);
  172. if (!this.textureAtlas.resizeCapacity(quantity)) {
  173. // serious problems
  174. cc.log(cc._LogInfos.SpriteBatchNode_increaseAtlasCapacity_2);
  175. }
  176. },
  177. /**
  178. * Removes a child given a certain index. It will also cleanup the running actions depending on the cleanup parameter.
  179. * @warning Removing a child from a cc.SpriteBatchNode is very slow
  180. * @param {Number} index
  181. * @param {Boolean} doCleanup
  182. */
  183. removeChildAtIndex: function (index, doCleanup) {
  184. this.removeChild(this._children[index], doCleanup);
  185. },
  186. /**
  187. * Rebuild index in order for child
  188. * @param {cc.Sprite} pobParent
  189. * @param {Number} index
  190. * @return {Number}
  191. */
  192. rebuildIndexInOrder: function (pobParent, index) {
  193. var children = pobParent.children;
  194. if (children && children.length > 0) {
  195. for (var i = 0; i < children.length; i++) {
  196. var obj = children[i];
  197. if (obj && (obj.zIndex < 0)) {
  198. index = this.rebuildIndexInOrder(obj, index);
  199. }
  200. }
  201. }
  202. // ignore self (batch node)
  203. if (!pobParent == this) {
  204. pobParent.atlasIndex = index;
  205. index++;
  206. }
  207. if (children && children.length > 0) {
  208. for (i = 0; i < children.length; i++) {
  209. obj = children[i];
  210. if (obj && (obj.zIndex >= 0)) {
  211. index = this.rebuildIndexInOrder(obj, index);
  212. }
  213. }
  214. }
  215. return index;
  216. },
  217. /**
  218. * Returns highest atlas index in child
  219. * @param {cc.Sprite} sprite
  220. * @return {Number}
  221. */
  222. highestAtlasIndexInChild: function (sprite) {
  223. var children = sprite.children;
  224. if (!children || children.length == 0)
  225. return sprite.atlasIndex;
  226. else
  227. return this.highestAtlasIndexInChild(children[children.length - 1]);
  228. },
  229. /**
  230. * Returns lowest atlas index in child
  231. * @param {cc.Sprite} sprite
  232. * @return {Number}
  233. */
  234. lowestAtlasIndexInChild: function (sprite) {
  235. var children = sprite.children;
  236. if (!children || children.length == 0)
  237. return sprite.atlasIndex;
  238. else
  239. return this.lowestAtlasIndexInChild(children[children.length - 1]);
  240. },
  241. /**
  242. * Returns atlas index for child
  243. * @param {cc.Sprite} sprite
  244. * @param {Number} nZ
  245. * @return {Number}
  246. */
  247. atlasIndexForChild: function (sprite, nZ) {
  248. var selParent = sprite.parent;
  249. var brothers = selParent.children;
  250. var childIndex = brothers.indexOf(sprite);
  251. // ignore parent Z if parent is spriteSheet
  252. var ignoreParent = selParent == this;
  253. var previous = null;
  254. if (childIndex > 0 && childIndex < cc.UINT_MAX)
  255. previous = brothers[childIndex - 1];
  256. // first child of the sprite sheet
  257. if (ignoreParent) {
  258. if (childIndex == 0)
  259. return 0;
  260. return this.highestAtlasIndexInChild(previous) + 1;
  261. }
  262. // parent is a cc.Sprite, so, it must be taken into account
  263. // first child of an cc.Sprite ?
  264. if (childIndex == 0) {
  265. // less than parent and brothers
  266. if (nZ < 0)
  267. return selParent.atlasIndex;
  268. else
  269. return selParent.atlasIndex + 1;
  270. } else {
  271. // previous & sprite belong to the same branch
  272. if ((previous.zIndex < 0 && nZ < 0) || (previous.zIndex >= 0 && nZ >= 0))
  273. return this.highestAtlasIndexInChild(previous) + 1;
  274. // else (previous < 0 and sprite >= 0 )
  275. return selParent.atlasIndex + 1;
  276. }
  277. },
  278. /**
  279. * Sprites use this to start sortChildren, don't call this manually
  280. * @param {Boolean} reorder
  281. */
  282. reorderBatch: function (reorder) {
  283. this._reorderChildDirty = reorder;
  284. },
  285. /**
  286. * Sets the source and destination blending function for the texture
  287. * @param {Number | cc.BlendFunc} src
  288. * @param {Number} dst
  289. */
  290. setBlendFunc: function (src, dst) {
  291. if (dst === undefined)
  292. this._blendFunc = src;
  293. else
  294. this._blendFunc = {src: src, dst: dst};
  295. },
  296. /**
  297. * Returns the blending function used for the texture
  298. * @return {cc.BlendFunc}
  299. */
  300. getBlendFunc: function () {
  301. return this._blendFunc;
  302. },
  303. /**
  304. * Reorder children (override reorderChild of cc.Node)
  305. * @override
  306. * @param {cc.Sprite} child
  307. * @param {Number} zOrder
  308. */
  309. reorderChild: function (child, zOrder) {
  310. cc.assert(child, cc._LogInfos.SpriteBatchNode_reorderChild_2);
  311. if (this._children.indexOf(child) === -1) {
  312. cc.log(cc._LogInfos.SpriteBatchNode_reorderChild);
  313. return;
  314. }
  315. if (zOrder === child.zIndex)
  316. return;
  317. //set the z-order and sort later
  318. cc.Node.prototype.reorderChild.call(this, child, zOrder);
  319. this.setNodeDirty();
  320. },
  321. /**
  322. * Removes a child from cc.SpriteBatchNode (override removeChild of cc.Node)
  323. * @param {cc.Sprite} child
  324. * @param {Boolean} cleanup
  325. */
  326. removeChild: function (child, cleanup) {
  327. // explicit null handling
  328. if (child == null)
  329. return;
  330. if (this._children.indexOf(child) === -1) {
  331. cc.log(cc._LogInfos.SpriteBatchNode_removeChild);
  332. return;
  333. }
  334. // cleanup before removing
  335. this.removeSpriteFromAtlas(child);
  336. cc.Node.prototype.removeChild.call(this, child, cleanup);
  337. },
  338. _mvpMatrix: null,
  339. _textureForCanvas: null,
  340. _useCache: false,
  341. _originalTexture: null,
  342. ctor: null,
  343. _ctorForCanvas: function (fileImage, capacity) {
  344. cc.Node.prototype.ctor.call(this);
  345. var texture2D;
  346. capacity = capacity || cc.DEFAULT_SPRITE_BATCH_CAPACITY;
  347. if (typeof(fileImage) == "string") {
  348. texture2D = cc.textureCache.getTextureForKey(fileImage);
  349. if (!texture2D)
  350. texture2D = cc.textureCache.addImage(fileImage);
  351. }
  352. else if (fileImage instanceof cc.Texture2D)
  353. texture2D = fileImage;
  354. texture2D && this.initWithTexture(texture2D, capacity);
  355. },
  356. _ctorForWebGL: function (fileImage, capacity) {
  357. cc.Node.prototype.ctor.call(this);
  358. this._mvpMatrix = new cc.kmMat4();
  359. var texture2D;
  360. capacity = capacity || cc.DEFAULT_SPRITE_BATCH_CAPACITY;
  361. if (typeof(fileImage) == "string") {
  362. texture2D = cc.textureCache.getTextureForKey(fileImage);
  363. if (!texture2D)
  364. texture2D = cc.textureCache.addImage(fileImage);
  365. }
  366. else if (fileImage instanceof cc.Texture2D)
  367. texture2D = fileImage;
  368. texture2D && this.initWithTexture(texture2D, capacity);
  369. },
  370. /**
  371. * <p>
  372. * Updates a quad at a certain index into the texture atlas. The CCSprite won't be added into the children array. <br/>
  373. * 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.<br/>
  374. * For example: a tile map (cc.TMXMap) or a label with lots of characters (BitmapFontAtlas)<br/>
  375. * </p>
  376. * @function
  377. * @param {cc.Sprite} sprite
  378. * @param {Number} index
  379. */
  380. updateQuadFromSprite: null,
  381. _updateQuadFromSpriteForCanvas: function (sprite, index) {
  382. cc.assert(sprite, cc._LogInfos.CCSpriteBatchNode_updateQuadFromSprite_2);
  383. if (!(sprite instanceof cc.Sprite)) {
  384. cc.log(cc._LogInfos.CCSpriteBatchNode_updateQuadFromSprite);
  385. return;
  386. }
  387. //
  388. // update the quad directly. Don't add the sprite to the scene graph
  389. //
  390. sprite.batchNode = this;
  391. sprite.atlasIndex = index;
  392. sprite.dirty = true;
  393. // UpdateTransform updates the textureAtlas quad
  394. sprite.updateTransform();
  395. },
  396. _updateQuadFromSpriteForWebGL: function (sprite, index) {
  397. cc.assert(sprite, cc._LogInfos.CCSpriteBatchNode_updateQuadFromSprite);
  398. if (!(sprite instanceof cc.Sprite)) {
  399. cc.log(cc._LogInfos.CCSpriteBatchNode_updateQuadFromSprite);
  400. return;
  401. }
  402. // make needed room
  403. var locCapacity = this.textureAtlas.capacity;
  404. while (index >= locCapacity || locCapacity == this.textureAtlas.totalQuads) {
  405. this.increaseAtlasCapacity();
  406. }
  407. //
  408. // update the quad directly. Don't add the sprite to the scene graph
  409. //
  410. sprite.batchNode = this;
  411. sprite.atlasIndex = index;
  412. sprite.dirty = true;
  413. // UpdateTransform updates the textureAtlas quad
  414. sprite.updateTransform();
  415. },
  416. _swap: function (oldIndex, newIndex) {
  417. var locDescendants = this._descendants;
  418. var locTextureAtlas = this.textureAtlas;
  419. var quads = locTextureAtlas.quads;
  420. var tempItem = locDescendants[oldIndex];
  421. var tempIteQuad = cc.V3F_C4B_T2F_QuadCopy(quads[oldIndex]);
  422. //update the index of other swapped item
  423. locDescendants[newIndex].atlasIndex = oldIndex;
  424. locDescendants[oldIndex] = locDescendants[newIndex];
  425. locTextureAtlas.updateQuad(quads[newIndex], oldIndex);
  426. locDescendants[newIndex] = tempItem;
  427. locTextureAtlas.updateQuad(tempIteQuad, newIndex);
  428. },
  429. /**
  430. * <p>
  431. * Inserts a quad at a certain index into the texture atlas. The cc.Sprite won't be added into the children array. <br/>
  432. * 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. <br/>
  433. * For example: a tile map (cc.TMXMap) or a label with lots of characters (cc.LabelBMFont)
  434. * </p>
  435. * @function
  436. * @param {cc.Sprite} sprite
  437. * @param {Number} index
  438. */
  439. insertQuadFromSprite: null,
  440. _insertQuadFromSpriteForCanvas: function (sprite, index) {
  441. cc.assert(sprite, cc._LogInfos.CCSpriteBatchNode_insertQuadFromSprite_2);
  442. if (!(sprite instanceof cc.Sprite)) {
  443. cc.log(cc._LogInfos.CCSpriteBatchNode_insertQuadFromSprite);
  444. return;
  445. }
  446. //
  447. // update the quad directly. Don't add the sprite to the scene graph
  448. //
  449. sprite.batchNode = this;
  450. sprite.atlasIndex = index;
  451. // XXX: updateTransform will update the textureAtlas too, using updateQuad.
  452. // XXX: so, it should be AFTER the insertQuad
  453. sprite.dirty = true;
  454. sprite.updateTransform();
  455. sprite._setCachedParent(this);
  456. this._children.splice(index, 0, sprite);
  457. },
  458. _insertQuadFromSpriteForWebGL: function (sprite, index) {
  459. cc.assert(sprite, cc._LogInfos.Sprite_insertQuadFromSprite_2);
  460. if (!(sprite instanceof cc.Sprite)) {
  461. cc.log(cc._LogInfos.Sprite_insertQuadFromSprite);
  462. return;
  463. }
  464. // make needed room
  465. var locTextureAtlas = this.textureAtlas;
  466. while (index >= locTextureAtlas.capacity || locTextureAtlas.capacity === locTextureAtlas.totalQuads)
  467. this.increaseAtlasCapacity();
  468. //
  469. // update the quad directly. Don't add the sprite to the scene graph
  470. //
  471. sprite.batchNode = this;
  472. sprite.atlasIndex = index;
  473. locTextureAtlas.insertQuad(sprite.quad, index);
  474. // XXX: updateTransform will update the textureAtlas too, using updateQuad.
  475. // XXX: so, it should be AFTER the insertQuad
  476. sprite.dirty = true;
  477. sprite.updateTransform();
  478. },
  479. _updateAtlasIndex: function (sprite, curIndex) {
  480. var count = 0;
  481. var pArray = sprite.children;
  482. if (pArray)
  483. count = pArray.length;
  484. var oldIndex = 0;
  485. if (count === 0) {
  486. oldIndex = sprite.atlasIndex;
  487. sprite.atlasIndex = curIndex;
  488. sprite.arrivalOrder = 0;
  489. if (oldIndex != curIndex)
  490. this._swap(oldIndex, curIndex);
  491. curIndex++;
  492. } else {
  493. var needNewIndex = true;
  494. if (pArray[0].zIndex >= 0) {
  495. //all children are in front of the parent
  496. oldIndex = sprite.atlasIndex;
  497. sprite.atlasIndex = curIndex;
  498. sprite.arrivalOrder = 0;
  499. if (oldIndex != curIndex)
  500. this._swap(oldIndex, curIndex);
  501. curIndex++;
  502. needNewIndex = false;
  503. }
  504. for (var i = 0; i < pArray.length; i++) {
  505. var child = pArray[i];
  506. if (needNewIndex && child.zIndex >= 0) {
  507. oldIndex = sprite.atlasIndex;
  508. sprite.atlasIndex = curIndex;
  509. sprite.arrivalOrder = 0;
  510. if (oldIndex != curIndex) {
  511. this._swap(oldIndex, curIndex);
  512. }
  513. curIndex++;
  514. needNewIndex = false;
  515. }
  516. curIndex = this._updateAtlasIndex(child, curIndex);
  517. }
  518. if (needNewIndex) {
  519. //all children have a zOrder < 0)
  520. oldIndex = sprite.atlasIndex;
  521. sprite.atlasIndex = curIndex;
  522. sprite.arrivalOrder = 0;
  523. if (oldIndex != curIndex) {
  524. this._swap(oldIndex, curIndex);
  525. }
  526. curIndex++;
  527. }
  528. }
  529. return curIndex;
  530. },
  531. _updateBlendFunc: function () {
  532. if (!this.textureAtlas.texture.hasPremultipliedAlpha()) {
  533. this._blendFunc.src = cc.SRC_ALPHA;
  534. this._blendFunc.dst = cc.ONE_MINUS_SRC_ALPHA;
  535. }
  536. },
  537. /**
  538. * <p>
  539. * Initializes a cc.SpriteBatchNode with a texture2d and capacity of children.<br/>
  540. * The capacity will be increased in 33% in runtime if it run out of space.<br/>
  541. * Please pass parameters to constructor to initialize the sprite batch node, do not call this function yourself.
  542. * </p>
  543. * @function
  544. * @param {cc.Texture2D} tex
  545. * @param {Number} [capacity]
  546. * @return {Boolean}
  547. */
  548. initWithTexture: null,
  549. _initWithTextureForCanvas: function (tex, capacity) {
  550. this._children = [];
  551. this._descendants = [];
  552. this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST);
  553. this._originalTexture = tex;
  554. this._textureForCanvas = tex;
  555. return true;
  556. },
  557. _initWithTextureForWebGL: function (tex, capacity) {
  558. this._children = [];
  559. this._descendants = [];
  560. this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST);
  561. capacity = capacity || cc.DEFAULT_SPRITE_BATCH_CAPACITY;
  562. this.textureAtlas = new cc.TextureAtlas();
  563. this.textureAtlas.initWithTexture(tex, capacity);
  564. this._updateBlendFunc();
  565. this.shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR);
  566. return true;
  567. },
  568. /**
  569. * Insert a child
  570. * @param {cc.Sprite} sprite The child sprite
  571. * @param {Number} index The insert index
  572. */
  573. insertChild: function (sprite, index) {
  574. sprite.batchNode = this;
  575. sprite.atlasIndex = index;
  576. sprite.dirty = true;
  577. var locTextureAtlas = this.textureAtlas;
  578. if (locTextureAtlas.totalQuads >= locTextureAtlas.capacity)
  579. this.increaseAtlasCapacity();
  580. locTextureAtlas.insertQuad(sprite.quad, index);
  581. this._descendants.splice(index, 0, sprite);
  582. // update indices
  583. var i = index + 1, locDescendant = this._descendants;
  584. if (locDescendant && locDescendant.length > 0) {
  585. for (; i < locDescendant.length; i++)
  586. locDescendant[i].atlasIndex++;
  587. }
  588. // add children recursively
  589. var locChildren = sprite.children, child;
  590. if (locChildren) {
  591. for (i = 0, l = locChildren.length || 0; i < l; i++) {
  592. child = locChildren[i];
  593. if (child) {
  594. var getIndex = this.atlasIndexForChild(child, child.zIndex);
  595. this.insertChild(child, getIndex);
  596. }
  597. }
  598. }
  599. },
  600. /**
  601. * Add child at the end, faster than insert child
  602. * @function
  603. * @param {cc.Sprite} sprite
  604. */
  605. appendChild: null,
  606. _appendChildForCanvas: function (sprite) {
  607. this._reorderChildDirty = true;
  608. sprite.batchNode = this;
  609. sprite.dirty = true;
  610. this._descendants.push(sprite);
  611. var index = this._descendants.length - 1;
  612. sprite.atlasIndex = index;
  613. // add children recursively
  614. var children = sprite.children;
  615. for (var i = 0, l = children.length || 0; i < l; i++)
  616. this.appendChild(children[i]);
  617. },
  618. _appendChildForWebGL: function (sprite) {
  619. this._reorderChildDirty = true;
  620. sprite.batchNode = this;
  621. sprite.dirty = true;
  622. this._descendants.push(sprite);
  623. var index = this._descendants.length - 1;
  624. sprite.atlasIndex = index;
  625. var locTextureAtlas = this.textureAtlas;
  626. if (locTextureAtlas.totalQuads == locTextureAtlas.capacity)
  627. this.increaseAtlasCapacity();
  628. locTextureAtlas.insertQuad(sprite.quad, index);
  629. // add children recursively
  630. var children = sprite.children;
  631. for (var i = 0, l = children.length || 0; i < l; i++)
  632. this.appendChild(children[i]);
  633. },
  634. /**
  635. * Removes sprite from TextureAtlas
  636. * @function
  637. * @param {cc.Sprite} sprite
  638. */
  639. removeSpriteFromAtlas: null,
  640. _removeSpriteFromAtlasForCanvas: function (sprite) {
  641. // Cleanup sprite. It might be reused (issue #569)
  642. sprite.batchNode = null;
  643. var locDescendants = this._descendants;
  644. var index = locDescendants.indexOf(sprite);
  645. if (index != -1) {
  646. locDescendants.splice(index, 1)
  647. // update all sprites beyond this one
  648. var len = locDescendants.length;
  649. for (; index < len; ++index) {
  650. var s = locDescendants[index];
  651. s.atlasIndex--;
  652. }
  653. }
  654. // remove children recursively
  655. var children = sprite.children;
  656. if (children) {
  657. for (var i = 0, l = children.length || 0; i < l; i++)
  658. children[i] && this.removeSpriteFromAtlas(children[i]);
  659. }
  660. },
  661. _removeSpriteFromAtlasForWebGL: function (sprite) {
  662. this.textureAtlas.removeQuadAtIndex(sprite.atlasIndex); // remove from TextureAtlas
  663. // Cleanup sprite. It might be reused (issue #569)
  664. sprite.batchNode = null;
  665. var locDescendants = this._descendants;
  666. var index = locDescendants.indexOf(sprite);
  667. if (index != -1) {
  668. locDescendants.splice(index, 1);
  669. // update all sprites beyond this one
  670. var len = locDescendants.length;
  671. for (; index < len; ++index) {
  672. var s = locDescendants[index];
  673. s.atlasIndex--;
  674. }
  675. }
  676. // remove children recursively
  677. var children = sprite.children;
  678. if (children) {
  679. for (var i = 0, l = children.length || 0; i < l; i++)
  680. children[i] && this.removeSpriteFromAtlas(children[i]);
  681. }
  682. },
  683. // CCTextureProtocol
  684. /**
  685. * Returns texture of the sprite batch node
  686. * @function
  687. * @return {cc.Texture2D|HTMLImageElement|HTMLCanvasElement}
  688. */
  689. getTexture: null,
  690. _getTextureForCanvas: function () {
  691. return this._textureForCanvas;
  692. },
  693. _getTextureForWebGL: function () {
  694. return this.textureAtlas.texture;
  695. },
  696. /**
  697. * Sets the texture of the sprite batch node.
  698. * @function
  699. * @param {cc.Texture2D} texture
  700. */
  701. setTexture: null,
  702. _setTextureForCanvas: function (texture) {
  703. this._textureForCanvas = texture;
  704. var locChildren = this._children;
  705. for (var i = 0; i < locChildren.length; i++)
  706. locChildren[i].texture = texture;
  707. },
  708. _setTextureForWebGL: function (texture) {
  709. this.textureAtlas.texture = texture;
  710. this._updateBlendFunc();
  711. },
  712. /**
  713. * Don't call visit on its children ( override visit of cc.Node )
  714. * @function
  715. * @override
  716. * @param {CanvasRenderingContext2D} ctx
  717. */
  718. visit: null,
  719. _visitForCanvas: function (ctx) {
  720. var context = ctx || cc._renderContext;
  721. // quick return if not visible
  722. if (!this._visible)
  723. return;
  724. context.save();
  725. this.transform(ctx);
  726. var i, locChildren = this._children;
  727. if (locChildren) {
  728. this.sortAllChildren();
  729. for (i = 0; i < locChildren.length; i++) {
  730. if (locChildren[i])
  731. locChildren[i].visit(context);
  732. }
  733. }
  734. context.restore();
  735. },
  736. _visitForWebGL: function (ctx) {
  737. var gl = ctx || cc._renderContext;
  738. // CAREFUL:
  739. // This visit is almost identical to CocosNode#visit
  740. // with the exception that it doesn't call visit on it's children
  741. //
  742. // The alternative is to have a void CCSprite#visit, but
  743. // although this is less mantainable, is faster
  744. //
  745. if (!this._visible)
  746. return;
  747. cc.kmGLPushMatrix();
  748. var locGrid = this.grid;
  749. if (locGrid && locGrid.isActive()) {
  750. locGrid.beforeDraw();
  751. this.transformAncestors();
  752. }
  753. this.sortAllChildren();
  754. this.transform(gl);
  755. this.draw(gl);
  756. if (locGrid && locGrid.isActive())
  757. locGrid.afterDraw(this);
  758. cc.kmGLPopMatrix();
  759. this.arrivalOrder = 0;
  760. },
  761. /**
  762. * Add child to the sprite batch node (override addChild of cc.Node)
  763. * @function
  764. * @override
  765. * @param {cc.Sprite} child
  766. * @param {Number} [zOrder]
  767. * @param {Number} [tag]
  768. */
  769. addChild: null,
  770. _addChildForCanvas: function (child, zOrder, tag) {
  771. cc.assert(child != null, cc._LogInfos.CCSpriteBatchNode_addChild_3);
  772. if (!(child instanceof cc.Sprite)) {
  773. cc.log(cc._LogInfos.CCSpriteBatchNode_addChild);
  774. return;
  775. }
  776. zOrder = (zOrder == null) ? child.zIndex : zOrder;
  777. tag = (tag == null) ? child.tag : tag;
  778. cc.Node.prototype.addChild.call(this, child, zOrder, tag);
  779. this.appendChild(child);
  780. this.setNodeDirty();
  781. },
  782. _addChildForWebGL: function (child, zOrder, tag) {
  783. cc.assert(child != null, cc._LogInfos.Sprite_addChild_6);
  784. if (!(child instanceof cc.Sprite)) {
  785. cc.log(cc._LogInfos.Sprite_addChild_4);
  786. return;
  787. }
  788. if (child.texture != this.textureAtlas.texture) { // check cc.Sprite is using the same texture id
  789. cc.log(cc._LogInfos.Sprite_addChild_5);
  790. return;
  791. }
  792. zOrder = (zOrder == null) ? child.zIndex : zOrder;
  793. tag = (tag == null) ? child.tag : tag;
  794. cc.Node.prototype.addChild.call(this, child, zOrder, tag);
  795. this.appendChild(child);
  796. this.setNodeDirty();
  797. },
  798. /**
  799. * Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter. <br/>
  800. * (override removeAllChildren of cc.Node)
  801. * @function
  802. * @param {Boolean} cleanup
  803. */
  804. removeAllChildren: null,
  805. _removeAllChildrenForCanvas: function (cleanup) {
  806. // Invalidate atlas index. issue #569
  807. // useSelfRender should be performed on all descendants. issue #1216
  808. var locDescendants = this._descendants;
  809. if (locDescendants && locDescendants.length > 0) {
  810. for (var i = 0, len = locDescendants.length; i < len; i++) {
  811. if (locDescendants[i])
  812. locDescendants[i].batchNode = null;
  813. }
  814. }
  815. cc.Node.prototype.removeAllChildren.call(this, cleanup);
  816. this._descendants.length = 0;
  817. },
  818. _removeAllChildrenForWebGL: function (cleanup) {
  819. // Invalidate atlas index. issue #569
  820. // useSelfRender should be performed on all descendants. issue #1216
  821. var locDescendants = this._descendants;
  822. if (locDescendants && locDescendants.length > 0) {
  823. for (var i = 0, len = locDescendants.length; i < len; i++) {
  824. if (locDescendants[i])
  825. locDescendants[i].batchNode = null;
  826. }
  827. }
  828. cc.Node.prototype.removeAllChildren.call(this, cleanup);
  829. this._descendants.length = 0;
  830. this.textureAtlas.removeAllQuads();
  831. },
  832. /**
  833. * Sort all children nodes (override draw of cc.Node)
  834. */
  835. sortAllChildren: null,
  836. _sortAllChildrenForCanvas: function () {
  837. if (this._reorderChildDirty) {
  838. var i, j = 0, locChildren = this._children;
  839. var length = locChildren.length, tempChild;
  840. //insertion sort
  841. for (i = 1; i < length; i++) {
  842. var tempItem = locChildren[i];
  843. j = i - 1;
  844. tempChild = locChildren[j];
  845. //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
  846. while (j >= 0 && ( tempItem._localZOrder < tempChild._localZOrder ||
  847. ( tempItem._localZOrder == tempChild._localZOrder && tempItem.arrivalOrder < tempChild.arrivalOrder ))) {
  848. locChildren[j + 1] = tempChild;
  849. j = j - 1;
  850. tempChild = locChildren[j];
  851. }
  852. locChildren[j + 1] = tempItem;
  853. }
  854. //sorted now check all children
  855. if (locChildren.length > 0) {
  856. //first sort all children recursively based on zOrder
  857. this._arrayMakeObjectsPerformSelector(locChildren, cc.Node._StateCallbackType.sortAllChildren);
  858. }
  859. this._reorderChildDirty = false;
  860. }
  861. },
  862. _sortAllChildrenForWebGL: function () {
  863. if (this._reorderChildDirty) {
  864. var childrenArr = this._children;
  865. var i, j = 0, length = childrenArr.length, tempChild;
  866. //insertion sort
  867. for (i = 1; i < length; i++) {
  868. var tempItem = childrenArr[i];
  869. j = i - 1;
  870. tempChild = childrenArr[j];
  871. //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
  872. while (j >= 0 && ( tempItem._localZOrder < tempChild._localZOrder ||
  873. ( tempItem._localZOrder == tempChild._localZOrder && tempItem.arrivalOrder < tempChild.arrivalOrder ))) {
  874. childrenArr[j + 1] = tempChild;
  875. j = j - 1;
  876. tempChild = childrenArr[j];
  877. }
  878. childrenArr[j + 1] = tempItem;
  879. }
  880. //sorted now check all children
  881. if (childrenArr.length > 0) {
  882. //first sort all children recursively based on zOrder
  883. this._arrayMakeObjectsPerformSelector(childrenArr, cc.Node._StateCallbackType.sortAllChildren);
  884. var index = 0;
  885. //fast dispatch, give every child a new atlasIndex based on their relative zOrder (keep parent -> child relations intact)
  886. // and at the same time reorder descedants and the quads to the right index
  887. for (i = 0; i < childrenArr.length; i++)
  888. index = this._updateAtlasIndex(childrenArr[i], index);
  889. }
  890. this._reorderChildDirty = false;
  891. }
  892. },
  893. /**
  894. * Draw the sprite batch node (override draw of cc.Node)
  895. * @function
  896. */
  897. draw: null,
  898. _drawForWebGL: function () {
  899. // Optimization: Fast Dispatch
  900. if (this.textureAtlas.totalQuads === 0)
  901. return;
  902. //cc.nodeDrawSetup(this);
  903. this._shaderProgram.use();
  904. this._shaderProgram.setUniformForModelViewAndProjectionMatrixWithMat4();
  905. this._arrayMakeObjectsPerformSelector(this._children, cc.Node._StateCallbackType.updateTransform);
  906. cc.glBlendFunc(this._blendFunc.src, this._blendFunc.dst);
  907. this.textureAtlas.drawQuads();
  908. }
  909. });
  910. var _p = cc.SpriteBatchNode.prototype;
  911. if (cc._renderType === cc._RENDER_TYPE_WEBGL) {
  912. _p.ctor = _p._ctorForWebGL;
  913. _p.updateQuadFromSprite = _p._updateQuadFromSpriteForWebGL;
  914. _p.insertQuadFromSprite = _p._insertQuadFromSpriteForWebGL;
  915. _p.initWithTexture = _p._initWithTextureForWebGL;
  916. _p.appendChild = _p._appendChildForWebGL;
  917. _p.removeSpriteFromAtlas = _p._removeSpriteFromAtlasForWebGL;
  918. _p.getTexture = _p._getTextureForWebGL;
  919. _p.setTexture = _p._setTextureForWebGL;
  920. _p.visit = _p._visitForWebGL;
  921. _p.addChild = _p._addChildForWebGL;
  922. _p.removeAllChildren = _p._removeAllChildrenForWebGL;
  923. _p.sortAllChildren = _p._sortAllChildrenForWebGL;
  924. _p.draw = _p._drawForWebGL;
  925. } else {
  926. _p.ctor = _p._ctorForCanvas;
  927. _p.updateQuadFromSprite = _p._updateQuadFromSpriteForCanvas;
  928. _p.insertQuadFromSprite = _p._insertQuadFromSpriteForCanvas;
  929. _p.initWithTexture = _p._initWithTextureForCanvas;
  930. _p.appendChild = _p._appendChildForCanvas;
  931. _p.removeSpriteFromAtlas = _p._removeSpriteFromAtlasForCanvas;
  932. _p.getTexture = _p._getTextureForCanvas;
  933. _p.setTexture = _p._setTextureForCanvas;
  934. _p.visit = _p._visitForCanvas;
  935. _p.removeAllChildren = _p._removeAllChildrenForCanvas;
  936. _p.addChild = _p._addChildForCanvas;
  937. _p.sortAllChildren = _p._sortAllChildrenForCanvas;
  938. _p.draw = cc.Node.prototype.draw;
  939. }
  940. // Override properties
  941. cc.defineGetterSetter(_p, "texture", _p.getTexture, _p.setTexture);
  942. // Extended properties
  943. /** @expose */
  944. _p.descendants;
  945. cc.defineGetterSetter(_p, "descendants", _p.getDescendants);
  946. /**
  947. * <p>
  948. * creates a cc.SpriteBatchNodeCanvas with a file image (.png, .jpg etc) with a default capacity of 29 children.<br/>
  949. * The capacity will be increased in 33% in runtime if it run out of space.<br/>
  950. * The file will be loaded using the TextureMgr.<br/>
  951. * </p>
  952. * @deprecated since v3.0, please use new construction instead
  953. * @see cc.SpriteBatchNode
  954. * @param {String|cc.Texture2D} fileImage
  955. * @param {Number} capacity
  956. * @return {cc.SpriteBatchNode}
  957. */
  958. cc.SpriteBatchNode.create = function (fileImage, capacity) {
  959. return new cc.SpriteBatchNode(fileImage, capacity);
  960. };
  961. /**
  962. * @deprecated since v3.0, please use new construction instead
  963. * @see cc.SpriteBatchNode
  964. * @function
  965. */
  966. cc.SpriteBatchNode.createWithTexture = cc.SpriteBatchNode.create;