CCLabelBMFont.js 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  1. /****************************************************************************
  2. Copyright (c) 2010-2012 cocos2d-x.org
  3. Copyright (c) 2008-2010 Ricardo Quesada
  4. Copyright (c) 2011 Zynga 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. Use any of these editors to generate BMFonts:
  22. http://glyphdesigner.71squared.com/ (Commercial, Mac OS X)
  23. http://www.n4te.com/hiero/hiero.jnlp (Free, Java)
  24. http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java)
  25. http://www.angelcode.com/products/bmfont/ (Free, Windows only)
  26. ****************************************************************************/
  27. /**
  28. * @constant
  29. * @type Number
  30. */
  31. cc.LABEL_AUTOMATIC_WIDTH = -1;
  32. cc.KerningHashElement = function (key, amount) {
  33. this.key = key || 0; //key for the hash. 16-bit for 1st element, 16-bit for 2nd element
  34. this.amount = amount || 0;
  35. };
  36. cc.FontDefHashElement = function (key, fontDef) {
  37. this.key = key || 0; // key. Font Unicode value
  38. this.fontDef = fontDef || new cc.BMFontDef(); // font definition
  39. };
  40. cc.BMFontDef = function (charID, rect, xOffset, yOffset, xAdvance) {
  41. //! ID of the character
  42. this.charID = charID || 0;
  43. //! origin and size of the font
  44. this.rect = rect || cc.rect(0, 0, 0.1, 0.1);
  45. //! The X amount the image should be offset when drawing the image (in pixels)
  46. this.xOffset = xOffset || 0;
  47. //! The Y amount the image should be offset when drawing the image (in pixels)
  48. this.yOffset = yOffset || 0;
  49. //! The amount to move the current position after drawing the character (in pixels)
  50. this.xAdvance = xAdvance || 0;
  51. };
  52. cc.BMFontPadding = function (left, top, right, bottom) {
  53. /// padding left
  54. this.left = left || 0;
  55. /// padding top
  56. this.top = top || 0;
  57. /// padding right
  58. this.right = right || 0;
  59. /// padding bottom
  60. this.bottom = bottom || 0;
  61. };
  62. /**
  63. * cc.BMFontConfiguration has parsed _configuration of the the .fnt file
  64. * @class
  65. * @extends cc.Class
  66. */
  67. cc.BMFontConfiguration = cc.Class.extend(/** @lends cc.BMFontConfiguration# */{
  68. // XXX: Creating a public interface so that the bitmapFontArray[] is acc.esible
  69. //@public
  70. /**
  71. * FNTConfig: Common Height
  72. * @type Number
  73. */
  74. commonHeight:0,
  75. /**
  76. * Padding
  77. * @type cc.BMFontPadding
  78. */
  79. padding:null,
  80. /**
  81. * atlas name
  82. * @type String
  83. */
  84. atlasName:null,
  85. /**
  86. * values for kerning
  87. * @type cc.KerningHashElement
  88. */
  89. kerningDictionary:null,
  90. /**
  91. * values for FontDef
  92. * @type cc.FontDefHashElement
  93. */
  94. fontDefDictionary:null,
  95. /**
  96. * Character Set defines the letters that actually exist in the font
  97. * @type Array
  98. */
  99. characterSet:null,
  100. /**
  101. * Constructor
  102. */
  103. ctor:function () {
  104. this.padding = new cc.BMFontPadding();
  105. this.atlasName = "";
  106. this.kerningDictionary = new cc.KerningHashElement();
  107. this.fontDefDictionary = {};
  108. this.characterSet = [];
  109. },
  110. /**
  111. * Description of BMFontConfiguration
  112. * @return {String}
  113. */
  114. description:function () {
  115. return "<cc.BMFontConfiguration | Kernings:" + this.kerningDictionary.amount + " | Image = " + this.atlasName.toString() + ">";
  116. },
  117. /**
  118. * @return {String}
  119. */
  120. getAtlasName:function () {
  121. return this.atlasName;
  122. },
  123. /**
  124. * @param {String} atlasName
  125. */
  126. setAtlasName:function (atlasName) {
  127. this.atlasName = atlasName;
  128. },
  129. /**
  130. * @return {Object}
  131. */
  132. getCharacterSet:function () {
  133. return this.characterSet;
  134. },
  135. /**
  136. * initializes a BitmapFontConfiguration with a FNT file
  137. * @param {String} FNTfile file path
  138. * @return {Boolean}
  139. */
  140. initWithFNTfile:function (FNTfile) {
  141. if(!FNTfile || FNTfile.length == 0)
  142. throw "cc.BMFontConfiguration.initWithFNTfile(): FNTfile must be non-null and must not be a empty string";
  143. this.characterSet = this._parseConfigFile(FNTfile);
  144. return this.characterSet != null;
  145. },
  146. _parseConfigFile:function (controlFile) {
  147. var fullpath = cc.FileUtils.getInstance().fullPathForFilename(controlFile);
  148. var data = cc.SAXParser.getInstance().getList(fullpath);
  149. if (!data) {
  150. cc.log("cc.BMFontConfiguration._parseConfigFile(): Error parsing FNTfile " + controlFile);
  151. return null;
  152. }
  153. var validCharsString = [];
  154. // parse spacing / padding
  155. var line, re, i;
  156. re = /padding+[a-z0-9\-= ",]+/gi;
  157. line = re.exec(data)[0];
  158. if (line) {
  159. this._parseInfoArguments(line);
  160. }
  161. re = /common lineHeight+[a-z0-9\-= ",]+/gi;
  162. line = re.exec(data)[0];
  163. if (line) {
  164. this._parseCommonArguments(line);
  165. }
  166. //re = /page id=[a-zA-Z0-9\.\-= ",]+/gi;
  167. re = /page id=[0-9]+ file="[\w\-\.]+/gi;
  168. line = re.exec(data)[0];
  169. if (line) {
  170. this._parseImageFileName(line, controlFile);
  171. }
  172. re = /chars c+[a-z0-9\-= ",]+/gi;
  173. line = re.exec(data)[0];
  174. if (line) {
  175. // Ignore this line
  176. }
  177. re = /char id=\w[a-z0-9\-= ]+/gi;
  178. line = data.match(re);
  179. if (line) {
  180. // Parse the current line and create a new CharDef
  181. for (i = 0; i < line.length; i++) {
  182. var element = new cc.FontDefHashElement();
  183. this._parseCharacterDefinition(line[i], element.fontDef);
  184. element.key = element.fontDef.charID;
  185. this.fontDefDictionary[element.key] = element;
  186. validCharsString.push(element.fontDef.charID);
  187. }
  188. }
  189. /*
  190. re = /kernings count+[a-z0-9\-= ",]+/gi;
  191. if (re.test(data)) {
  192. line = RegExp.$1[0];
  193. if (line)
  194. this._parseKerningCapacity(line);
  195. }*/
  196. re = /kerning first=\w[a-z0-9\-= ]+/gi;
  197. line = data.match(re);
  198. if (line) {
  199. for (i = 0; i < line.length; i++)
  200. this._parseKerningEntry(line[i]);
  201. }
  202. return validCharsString;
  203. },
  204. _parseCharacterDefinition:function (line, characterDefinition) {
  205. //////////////////////////////////////////////////////////////////////////
  206. // line to parse:
  207. // char id=32 x=0 y=0 width=0 height=0 xoffset=0 yoffset=44 xadvance=14 page=0 chnl=0
  208. //////////////////////////////////////////////////////////////////////////
  209. // Character ID
  210. var value = /id=(\d+)/gi.exec(line)[1];
  211. characterDefinition.charID = value.toString();
  212. // Character x
  213. value = /x=([\-\d]+)/gi.exec(line)[1];
  214. characterDefinition.rect.x = parseInt(value);
  215. // Character y
  216. value = /y=([\-\d]+)/gi.exec(line)[1];
  217. characterDefinition.rect.y = parseInt(value);
  218. // Character width
  219. value = /width=([\-\d]+)/gi.exec(line)[1];
  220. characterDefinition.rect.width = parseInt(value);
  221. // Character height
  222. value = /height=([\-\d]+)/gi.exec(line)[1];
  223. characterDefinition.rect.height = parseInt(value);
  224. // Character xoffset
  225. value = /xoffset=([\-\d]+)/gi.exec(line)[1];
  226. characterDefinition.xOffset = parseInt(value);
  227. // Character yoffset
  228. value = /yoffset=([\-\d]+)/gi.exec(line)[1];
  229. characterDefinition.yOffset = parseInt(value);
  230. // Character xadvance
  231. value = /xadvance=([\-\d]+)/gi.exec(line)[1];
  232. characterDefinition.xAdvance = parseInt(value);
  233. },
  234. _parseInfoArguments:function (line) {
  235. //////////////////////////////////////////////////////////////////////////
  236. // possible lines to parse:
  237. // info face="Script" size=32 bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1 padding=1,4,3,2 spacing=0,0 outline=0
  238. // info face="Cracked" size=36 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1
  239. //////////////////////////////////////////////////////////////////////////
  240. // padding
  241. var tmpPadding = /padding=(\d+)[,](\d+)[,](\d+)[,](\d+)/gi.exec(line);
  242. this.padding.left = tmpPadding[1];
  243. this.padding.top = tmpPadding[2];
  244. this.padding.right = tmpPadding[3];
  245. this.padding.bottom = tmpPadding[4];
  246. cc.log("cocos2d: padding: " + this.padding.left + "," + this.padding.top + "," + this.padding.right + "," + this.padding.bottom);
  247. },
  248. _parseCommonArguments:function (line) {
  249. //////////////////////////////////////////////////////////////////////////
  250. // line to parse:
  251. // common lineHeight=104 base=26 scaleW=1024 scaleH=512 pages=1 packed=0
  252. //////////////////////////////////////////////////////////////////////////
  253. var value;
  254. // Height
  255. this.commonHeight = parseInt(/lineHeight=(\d+)/gi.exec(line)[1]);
  256. if (cc.renderContextType === cc.WEBGL) {
  257. var texSize = cc.Configuration.getInstance().getMaxTextureSize();
  258. var scaleW = parseInt(/scaleW=(\d+)/gi.exec(line)[1]);
  259. var scaleH = parseInt(/scaleH=(\d+)/gi.exec(line)[1]);
  260. if(scaleW > texSize.width || scaleH > texSize.height)
  261. cc.log("cc.LabelBMFont._parseCommonArguments(): page can't be larger than supported");
  262. }
  263. // pages. sanity check
  264. value = /pages=(\d+)/gi.exec(line)[1];
  265. if(parseInt(value) !== 1)
  266. cc.log("cc.LabelBMFont._parseCommonArguments(): only supports 1 page");
  267. // packed (ignore) What does this mean ??
  268. },
  269. _parseImageFileName:function (line, fntFile) {
  270. //////////////////////////////////////////////////////////////////////////
  271. // line to parse:
  272. // page id=0 file="bitmapFontTest.png"
  273. //////////////////////////////////////////////////////////////////////////
  274. var value;
  275. // page ID. Sanity check
  276. value = /id=(\d+)/gi.exec(line)[1];
  277. if(parseInt(value) !== 0)
  278. cc.log("cc.LabelBMFont._parseImageFileName() : file could not be found");
  279. // file
  280. value = /file="([a-zA-Z0-9\-\._]+)/gi.exec(line)[1];
  281. this.atlasName = cc.FileUtils.getInstance().fullPathFromRelativeFile(value, fntFile);
  282. },
  283. _parseKerningCapacity:function (line) {
  284. },
  285. _parseKerningEntry:function (line) {
  286. //////////////////////////////////////////////////////////////////////////
  287. // line to parse:
  288. // kerning first=121 second=44 amount=-7
  289. //////////////////////////////////////////////////////////////////////////
  290. // first
  291. var value = /first=([\-\d]+)/gi.exec(line)[1];
  292. var first = parseInt(value);
  293. // second
  294. value = /second=([\-\d]+)/gi.exec(line)[1];
  295. var second = parseInt(value);
  296. // amount
  297. value = /amount=([\-\d]+)/gi.exec(line)[1];
  298. var amount = parseInt(value);
  299. var element = new cc.KerningHashElement();
  300. element.amount = amount;
  301. element.key = (first << 16) | (second & 0xffff);
  302. this.kerningDictionary[element.key] = element;
  303. },
  304. _purgeKerningDictionary:function () {
  305. this.kerningDictionary = null;
  306. },
  307. _purgeFontDefDictionary:function () {
  308. this.fontDefDictionary = null;
  309. }
  310. });
  311. /**
  312. * Create a cc.BMFontConfiguration
  313. * @param {String} FNTfile
  314. * @return {cc.BMFontConfiguration|Null} returns the configuration or null if error
  315. * @example
  316. * // Example
  317. * var conf = cc.BMFontConfiguration.create('myfont.fnt');
  318. */
  319. cc.BMFontConfiguration.create = function (FNTfile) {
  320. var ret = new cc.BMFontConfiguration();
  321. if (ret.initWithFNTfile(FNTfile)) {
  322. return ret;
  323. }
  324. return null;
  325. };
  326. /**
  327. * <p>cc.LabelBMFont is a subclass of cc.SpriteBatchNode.</p>
  328. *
  329. * <p>Features:<br/>
  330. * <ul><li>- Treats each character like a cc.Sprite. This means that each individual character can be:</li>
  331. * <li>- rotated</li>
  332. * <li>- scaled</li>
  333. * <li>- translated</li>
  334. * <li>- tinted</li>
  335. * <li>- chage the opacity</li>
  336. * <li>- It can be used as part of a menu item.</li>
  337. * <li>- anchorPoint can be used to align the "label"</li>
  338. * <li>- Supports AngelCode text format</li></ul></p>
  339. *
  340. * <p>Limitations:<br/>
  341. * - All inner characters are using an anchorPoint of (0.5, 0.5) and it is not recommend to change it
  342. * because it might affect the rendering</p>
  343. *
  344. * <p>cc.LabelBMFont implements the protocol cc.LabelProtocol, like cc.Label and cc.LabelAtlas.<br/>
  345. * cc.LabelBMFont has the flexibility of cc.Label, the speed of cc.LabelAtlas and all the features of cc.Sprite.<br/>
  346. * If in doubt, use cc.LabelBMFont instead of cc.LabelAtlas / cc.Label.</p>
  347. *
  348. * <p>Supported editors:<br/>
  349. * http://glyphdesigner.71squared.com/ (Commercial, Mac OS X)<br/>
  350. * http://www.n4te.com/hiero/hiero.jnlp (Free, Java)<br/>
  351. * http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java)<br/>
  352. * http://www.angelcode.com/products/bmfont/ (Free, Windows only)</p>
  353. * @class
  354. * @extends cc.SpriteBatchNode
  355. */
  356. cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
  357. RGBAProtocol:true,
  358. _opacityModifyRGB:false,
  359. _string:null,
  360. _configuration:null,
  361. // name of fntFile
  362. _fntFile:null,
  363. // initial string without line breaks
  364. _initialString : "",
  365. // alignment of all lines
  366. _alignment:null,
  367. // max width until a line break is added
  368. _width:0,
  369. _lineBreakWithoutSpaces:false,
  370. _imageOffset:null,
  371. _reusedChar:null,
  372. //texture RGBA
  373. _displayedOpacity:255,
  374. _realOpacity:255,
  375. _displayedColor:null,
  376. _realColor:null,
  377. _cascadeColorEnabled:false,
  378. _cascadeOpacityEnabled:false,
  379. _textureLoaded: false,
  380. _loadedEventListeners: null,
  381. _setString:function(newString, needUpdateLabel){
  382. if(!needUpdateLabel){
  383. this._string = newString;
  384. } else {
  385. this._initialString = newString;
  386. }
  387. var locChildren = this._children;
  388. if(locChildren){
  389. for(var i = 0; i< locChildren.length;i++){
  390. var selNode = locChildren[i];
  391. if(selNode)
  392. selNode.setVisible(false);
  393. }
  394. }
  395. if(this._textureLoaded){
  396. this.createFontChars();
  397. if(needUpdateLabel)
  398. this.updateLabel();
  399. }
  400. },
  401. /**
  402. * Constructor
  403. */
  404. ctor:function () {
  405. cc.SpriteBatchNode.prototype.ctor.call(this);
  406. this._imageOffset = cc.PointZero();
  407. this._string = "";
  408. this._initialString = "";
  409. this._alignment = cc.TEXT_ALIGNMENT_CENTER;
  410. this._width = -1;
  411. this._configuration = null;
  412. this._lineBreakWithoutSpaces = false;
  413. this._displayedOpacity = 255;
  414. this._realOpacity = 255;
  415. this._displayedColor = cc.white();
  416. this._realColor = cc.white();
  417. this._cascadeColorEnabled = true;
  418. this._cascadeOpacityEnabled = true;
  419. this._opacityModifyRGB = false;
  420. this._fntFile = "";
  421. this._reusedChar = [];
  422. },
  423. /**
  424. * return texture is loaded
  425. * @returns {boolean}
  426. */
  427. textureLoaded:function(){
  428. return this._textureLoaded;
  429. },
  430. /**
  431. * add texture loaded event listener
  432. * @param {Function} callback
  433. * @param {Object} target
  434. */
  435. addLoadedEventListener:function(callback, target){
  436. if(!this._loadedEventListeners)
  437. this._loadedEventListeners = [];
  438. this._loadedEventListeners.push({eventCallback:callback, eventTarget:target});
  439. },
  440. _callLoadedEventCallbacks:function(){
  441. if(!this._loadedEventListeners)
  442. return;
  443. var locListeners = this._loadedEventListeners;
  444. for(var i = 0, len = locListeners.length; i < len; i++){
  445. var selCallback = locListeners[i];
  446. cc.doCallback(selCallback.eventCallback, selCallback.eventTarget, this);
  447. }
  448. locListeners.length = 0;
  449. },
  450. /**
  451. * @param {CanvasRenderingContext2D} ctx
  452. */
  453. draw:function (ctx) {
  454. cc.SpriteBatchNode.prototype.draw.call(this, ctx);
  455. //LabelBMFont - Debug draw
  456. if (cc.LABELBMFONT_DEBUG_DRAW) {
  457. var size = this.getContentSize();
  458. var pos = cc.p(0 | ( -this._anchorPointInPoints.x), 0 | ( -this._anchorPointInPoints.y));
  459. var vertices = [cc.p(pos.x, pos.y), cc.p(pos.x + size.width, pos.y), cc.p(pos.x + size.width, pos.y + size.height), cc.p(pos.x, pos.y + size.height)];
  460. cc.drawingUtil.setDrawColor4B(0,255,0,255);
  461. cc.drawingUtil.drawPoly(vertices, 4, true);
  462. }
  463. },
  464. //TODO
  465. /**
  466. * tint this label
  467. * @param {cc.Color3B} color3
  468. */
  469. setColor:function (color3) {
  470. if (((this._realColor.r == color3.r) && (this._realColor.g == color3.g) && (this._realColor.b == color3.b)))
  471. return;
  472. this._displayedColor = {r:color3.r, g:color3.g, b:color3.b};
  473. this._realColor = {r:color3.r, g:color3.g, b:color3.b};
  474. if(this._textureLoaded){
  475. if(this._cascadeColorEnabled){
  476. var parentColor = cc.white();
  477. var locParent = this._parent;
  478. if(locParent && locParent.RGBAProtocol && locParent.isCascadeColorEnabled())
  479. parentColor = locParent.getDisplayedColor();
  480. this.updateDisplayedColor(parentColor);
  481. }
  482. }
  483. },
  484. /**
  485. * conforms to cc.RGBAProtocol protocol
  486. * @return {Boolean}
  487. */
  488. isOpacityModifyRGB:function () {
  489. return this._opacityModifyRGB;
  490. },
  491. /**
  492. * @param {Boolean} opacityModifyRGB
  493. */
  494. setOpacityModifyRGB:function (opacityModifyRGB) {
  495. this._opacityModifyRGB = opacityModifyRGB;
  496. var locChildren = this._children;
  497. if (locChildren) {
  498. for (var i = 0; i < locChildren.length; i++) {
  499. var node = locChildren[i];
  500. if (node && node.RGBAProtocol)
  501. node.setOpacityModifyRGB(this._opacityModifyRGB);
  502. }
  503. }
  504. },
  505. getOpacity:function(){
  506. return this._realOpacity;
  507. },
  508. getDisplayedOpacity:function(){
  509. return this._displayedOpacity;
  510. },
  511. /**
  512. * Override synthesized setOpacity to recurse items
  513. * @param {Number} opacity
  514. */
  515. setOpacity:function(opacity){
  516. this._displayedOpacity = this._realOpacity = opacity;
  517. if(this._cascadeOpacityEnabled){
  518. var parentOpacity = 255;
  519. var locParent = this._parent;
  520. if(locParent && locParent.RGBAProtocol && locParent.isCascadeOpacityEnabled())
  521. parentOpacity = locParent.getDisplayedOpacity();
  522. this.updateDisplayedOpacity(parentOpacity);
  523. }
  524. },
  525. updateDisplayedOpacity:function(parentOpacity){
  526. this._displayedOpacity = this._realOpacity * parentOpacity/255.0;
  527. var locChildren = this._children;
  528. for(var i = 0; i< locChildren.length; i++){
  529. var locChild = locChildren[i];
  530. if(cc.Browser.supportWebGL){
  531. locChild.updateDisplayedOpacity(this._displayedOpacity);
  532. }else{
  533. cc.NodeRGBA.prototype.updateDisplayedOpacity.call(locChild, this._displayedOpacity);
  534. locChild.setNodeDirty();
  535. }
  536. }
  537. this._changeTextureColor();
  538. },
  539. isCascadeOpacityEnabled:function(){
  540. return false;
  541. },
  542. setCascadeOpacityEnabled:function(cascadeOpacityEnabled){
  543. this._cascadeOpacityEnabled = cascadeOpacityEnabled;
  544. },
  545. getColor:function(){
  546. return this._realColor;
  547. },
  548. getDisplayedColor:function(){
  549. return this._displayedColor;
  550. },
  551. updateDisplayedColor:function(parentColor){
  552. var locDispColor = this._displayedColor;
  553. var locRealColor = this._realColor;
  554. locDispColor.r = locRealColor.r * parentColor.r/255.0;
  555. locDispColor.g = locRealColor.g * parentColor.g/255.0;
  556. locDispColor.b = locRealColor.b * parentColor.b/255.0;
  557. var locChildren = this._children;
  558. for(var i = 0;i < locChildren.length;i++){
  559. var locChild = locChildren[i];
  560. if(cc.Browser.supportWebGL){
  561. locChild.updateDisplayedColor(this._displayedColor);
  562. }else{
  563. cc.NodeRGBA.prototype.updateDisplayedColor.call(locChild, this._displayedColor);
  564. locChild.setNodeDirty();
  565. }
  566. }
  567. this._changeTextureColor();
  568. },
  569. _changeTextureColor:function(){
  570. if(cc.Browser.supportWebGL){
  571. return;
  572. }
  573. var locElement, locTexture = this.getTexture();
  574. if (locTexture && locTexture.getContentSize().width>0) {
  575. locElement = locTexture.getHtmlElementObj();
  576. if (!locElement)
  577. return;
  578. var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(this._originalTexture.getHtmlElementObj());
  579. if (cacheTextureForColor) {
  580. if (locElement instanceof HTMLCanvasElement && !this._rectRotated)
  581. cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, null, locElement);
  582. else{
  583. locElement = cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor);
  584. locTexture = new cc.Texture2D();
  585. locTexture.initWithElement(locElement);
  586. locTexture.handleLoadedTexture();
  587. this.setTexture(locTexture);
  588. }
  589. }
  590. }
  591. },
  592. isCascadeColorEnabled:function(){
  593. return false;
  594. },
  595. setCascadeColorEnabled:function(cascadeColorEnabled){
  596. this._cascadeColorEnabled = cascadeColorEnabled;
  597. },
  598. /**
  599. * init LabelBMFont
  600. */
  601. init:function () {
  602. return this.initWithString(null, null, null, null, null);
  603. },
  604. /**
  605. * init a bitmap font altas with an initial string and the FNT file
  606. * @param {String} str
  607. * @param {String} fntFile
  608. * @param {Number} width
  609. * @param {Number} alignment
  610. * @param {cc.Point} imageOffset
  611. * @return {Boolean}
  612. */
  613. initWithString:function (str, fntFile, width, alignment, imageOffset) {
  614. var theString = str || "";
  615. if(this._configuration)
  616. cc.log("cc.LabelBMFont.initWithString(): re-init is no longer supported");
  617. var texture;
  618. if (fntFile) {
  619. var newConf = cc.FNTConfigLoadFile(fntFile);
  620. if(!newConf){
  621. cc.log("cc.LabelBMFont.initWithString(): Impossible to create font. Please check file");
  622. return false;
  623. }
  624. this._configuration = newConf;
  625. this._fntFile = fntFile;
  626. texture = cc.TextureCache.getInstance().addImage(this._configuration.getAtlasName());
  627. var locIsLoaded = texture.isLoaded();
  628. this._textureLoaded = locIsLoaded;
  629. if(!locIsLoaded){
  630. texture.addLoadedEventListener(function(sender){
  631. this._textureLoaded = true;
  632. //reset the LabelBMFont
  633. this.initWithTexture(sender, this._initialString.length);
  634. this.setString(this._initialString,true);
  635. this._callLoadedEventCallbacks();
  636. }, this);
  637. }
  638. } else{
  639. texture = new cc.Texture2D();
  640. var image = new Image();
  641. texture.initWithElement(image);
  642. this._textureLoaded = false;
  643. }
  644. if (this.initWithTexture(texture, theString.length)) {
  645. this._alignment = alignment || cc.TEXT_ALIGNMENT_LEFT;
  646. this._imageOffset = imageOffset || cc.PointZero();
  647. this._width = (width == null) ? -1 : width;
  648. this._displayedOpacity = this._realOpacity = 255;
  649. this._displayedColor = cc.white();
  650. this._realColor = cc.white();
  651. this._cascadeOpacityEnabled = true;
  652. this._cascadeColorEnabled = true;
  653. this._contentSize.width = 0;
  654. this._contentSize.height = 0;
  655. this.setAnchorPoint(0.5, 0.5);
  656. if (cc.renderContextType === cc.WEBGL) {
  657. var locTexture = this._textureAtlas.getTexture();
  658. this._opacityModifyRGB = locTexture.hasPremultipliedAlpha();
  659. this._reusedChar = new cc.Sprite();
  660. this._reusedChar.initWithTexture(locTexture, cc.rect(0, 0, 0, 0), false);
  661. this._reusedChar.setBatchNode(this);
  662. }
  663. this.setString(theString,true);
  664. return true;
  665. }
  666. return false;
  667. },
  668. /**
  669. * updates the font chars based on the string to render
  670. */
  671. createFontChars:function () {
  672. var locContextType = cc.renderContextType;
  673. var locTexture = (locContextType === cc.CANVAS) ? this.getTexture() : this._textureAtlas.getTexture();
  674. var nextFontPositionX = 0;
  675. var prev = -1;
  676. var kerningAmount = 0;
  677. var tmpSize = cc.SizeZero();
  678. var longestLine = 0;
  679. var quantityOfLines = 1;
  680. var stringLen = this._string ? this._string.length : 0;
  681. if (stringLen === 0)
  682. return;
  683. var i, charSet = this._configuration.getCharacterSet();
  684. for (i = 0; i < stringLen - 1; i++) {
  685. if (this._string.charCodeAt(i) == 10)
  686. quantityOfLines++;
  687. }
  688. var totalHeight = this._configuration.commonHeight * quantityOfLines;
  689. var nextFontPositionY = -(this._configuration.commonHeight - this._configuration.commonHeight * quantityOfLines);
  690. for (i = 0; i < stringLen; i++) {
  691. var key = this._string.charCodeAt(i);
  692. if (key === 10) {
  693. //new line
  694. nextFontPositionX = 0;
  695. nextFontPositionY -= this._configuration.commonHeight;
  696. continue;
  697. }
  698. if (charSet[key] === null) {
  699. cc.log("cc.LabelBMFont: Attempted to use character not defined in this bitmap: " + this._string[i]);
  700. continue;
  701. }
  702. kerningAmount = this._kerningAmountForFirst(prev,key);
  703. var element = this._configuration.fontDefDictionary[key];
  704. if (!element) {
  705. if(key !== 0 && key !== 10)
  706. cc.log("cocos2d: LabelBMFont: character not found " + this._string[i]);
  707. continue;
  708. }
  709. var fontDef = element.fontDef;
  710. var rect = cc.rect(fontDef.rect.x, fontDef.rect.y, fontDef.rect.width, fontDef.rect.height);
  711. rect = cc.RECT_PIXELS_TO_POINTS(rect);
  712. rect.x += this._imageOffset.x;
  713. rect.y += this._imageOffset.y;
  714. var fontChar = this.getChildByTag(i);
  715. //var hasSprite = true;
  716. if (!fontChar) {
  717. fontChar = new cc.Sprite();
  718. if ((key === 32) && (locContextType === cc.CANVAS)) {
  719. fontChar.initWithTexture(locTexture, cc.RectZero(), false);
  720. } else
  721. fontChar.initWithTexture(locTexture, rect, false);
  722. fontChar._newTextureWhenChangeColor = true;
  723. this.addChild(fontChar, 0, i);
  724. } else {
  725. if ((key === 32) && (locContextType === cc.CANVAS)) {
  726. fontChar.setTextureRect(rect, false, cc.SizeZero());
  727. } else {
  728. // updating previous sprite
  729. fontChar.setTextureRect(rect, false, rect._size);
  730. // restore to default in case they were modified
  731. fontChar.setVisible(true);
  732. }
  733. }
  734. // Apply label properties
  735. fontChar.setOpacityModifyRGB(this._opacityModifyRGB);
  736. // Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on
  737. if (cc.Browser.supportWebGL) {
  738. fontChar.updateDisplayedColor(this._displayedColor);
  739. fontChar.updateDisplayedOpacity(this._displayedOpacity);
  740. } else {
  741. cc.NodeRGBA.prototype.updateDisplayedColor.call(fontChar, this._displayedColor);
  742. cc.NodeRGBA.prototype.updateDisplayedOpacity.call(fontChar, this._displayedOpacity);
  743. fontChar.setNodeDirty();
  744. }
  745. var yOffset = this._configuration.commonHeight - fontDef.yOffset;
  746. var fontPos = cc.p(nextFontPositionX + fontDef.xOffset + fontDef.rect.width * 0.5 + kerningAmount,
  747. nextFontPositionY + yOffset - rect.height * 0.5 * cc.CONTENT_SCALE_FACTOR());
  748. fontChar.setPosition(cc.POINT_PIXELS_TO_POINTS(fontPos));
  749. // update kerning
  750. nextFontPositionX += fontDef.xAdvance + kerningAmount;
  751. prev = key;
  752. if (longestLine < nextFontPositionX)
  753. longestLine = nextFontPositionX;
  754. }
  755. tmpSize.width = longestLine;
  756. tmpSize.height = totalHeight;
  757. this.setContentSize(cc.SIZE_PIXELS_TO_POINTS(tmpSize));
  758. },
  759. /**
  760. * update String
  761. * @param {Boolean} fromUpdate
  762. */
  763. updateString:function (fromUpdate) {
  764. var locChildren = this._children;
  765. if (locChildren) {
  766. for (var i = 0; i < locChildren.length; i++) {
  767. var node = locChildren[i];
  768. if (node)
  769. node.setVisible(false);
  770. }
  771. }
  772. if (this._configuration)
  773. this.createFontChars();
  774. if (!fromUpdate)
  775. this.updateLabel();
  776. },
  777. /**
  778. * get the text of this label
  779. * @return {String}
  780. */
  781. getString:function () {
  782. return this._initialString;
  783. },
  784. /**
  785. * set the text
  786. * @param {String} newString
  787. * @param {Boolean|null} needUpdateLabel
  788. */
  789. setString: function (newString, needUpdateLabel) {
  790. newString = String(newString);
  791. if(needUpdateLabel == null)
  792. needUpdateLabel = true;
  793. if (newString == null || typeof(newString) != "string")
  794. newString = newString + "";
  795. this._initialString = newString;
  796. this._setString(newString, needUpdateLabel);
  797. },
  798. /**
  799. * @deprecated
  800. * @param label
  801. */
  802. setCString:function (label) {
  803. this.setString(label,true);
  804. },
  805. /**
  806. * update Label
  807. */
  808. updateLabel:function () {
  809. this.setString(this._initialString, false);
  810. // Step 1: Make multiline
  811. if (this._width > 0) {
  812. var stringLength = this._string.length;
  813. var multiline_string = [];
  814. var last_word = [];
  815. var line = 1, i = 0, start_line = false, start_word = false, startOfLine = -1, startOfWord = -1, skip = 0, j;
  816. var characterSprite;
  817. for (j = 0; j < this._children.length; j++) {
  818. var justSkipped = 0;
  819. while (!(characterSprite = this.getChildByTag(j + skip + justSkipped)))
  820. justSkipped++;
  821. skip += justSkipped;
  822. if (i >= stringLength)
  823. break;
  824. var character = this._string[i];
  825. if (!start_word) {
  826. startOfWord = this._getLetterPosXLeft(characterSprite);
  827. start_word = true;
  828. }
  829. if (!start_line) {
  830. startOfLine = startOfWord;
  831. start_line = true;
  832. }
  833. // Newline.
  834. if (character.charCodeAt(0) == 10) {
  835. last_word.push('\n');
  836. multiline_string = multiline_string.concat(last_word);
  837. last_word.length = 0;
  838. start_word = false;
  839. start_line = false;
  840. startOfWord = -1;
  841. startOfLine = -1;
  842. j--;
  843. skip -= justSkipped;
  844. line++;
  845. if (i >= stringLength)
  846. break;
  847. character = this._string[i];
  848. if (!startOfWord) {
  849. startOfWord = this._getLetterPosXLeft(characterSprite);
  850. start_word = true;
  851. }
  852. if (!startOfLine) {
  853. startOfLine = startOfWord;
  854. start_line = true;
  855. }
  856. i++;
  857. continue;
  858. }
  859. // Whitespace.
  860. if (cc.isspace_unicode(character)) {
  861. last_word.push(character);
  862. multiline_string = multiline_string.concat(last_word);
  863. last_word.length = 0;
  864. start_word = false;
  865. startOfWord = -1;
  866. i++;
  867. continue;
  868. }
  869. // Out of bounds.
  870. if (this._getLetterPosXRight(characterSprite) - startOfLine > this._width) {
  871. if (!this._lineBreakWithoutSpaces) {
  872. last_word.push(character);
  873. var found = multiline_string.lastIndexOf(" ");
  874. if (found != -1)
  875. cc.utf8_trim_ws(multiline_string);
  876. else
  877. multiline_string = [];
  878. if (multiline_string.length > 0)
  879. multiline_string.push('\n');
  880. line++;
  881. start_line = false;
  882. startOfLine = -1;
  883. i++;
  884. } else {
  885. cc.utf8_trim_ws(last_word);
  886. last_word.push('\n');
  887. multiline_string = multiline_string.concat(last_word);
  888. last_word.length = 0;
  889. start_word = false;
  890. start_line = false;
  891. startOfWord = -1;
  892. startOfLine = -1;
  893. line++;
  894. if (i >= stringLength)
  895. break;
  896. if (!startOfWord) {
  897. startOfWord = this._getLetterPosXLeft(characterSprite);
  898. start_word = true;
  899. }
  900. if (!startOfLine) {
  901. startOfLine = startOfWord;
  902. start_line = true;
  903. }
  904. j--;
  905. }
  906. } else {
  907. // Character is normal.
  908. last_word.push(character);
  909. i++;
  910. }
  911. }
  912. multiline_string = multiline_string.concat(last_word);
  913. var len = multiline_string.length;
  914. var str_new = "";
  915. for (i = 0; i < len; ++i)
  916. str_new += multiline_string[i];
  917. str_new = str_new + String.fromCharCode(0);
  918. //this.updateString(true);
  919. this._setString(str_new, false)
  920. }
  921. // Step 2: Make alignment
  922. if (this._alignment != cc.TEXT_ALIGNMENT_LEFT) {
  923. i = 0;
  924. var lineNumber = 0;
  925. var strlen = this._string.length;
  926. var last_line = [];
  927. for (var ctr = 0; ctr < strlen; ctr++) {
  928. if (this._string[ctr].charCodeAt(0) == 10 || this._string[ctr].charCodeAt(0) == 0) {
  929. var lineWidth = 0;
  930. var line_length = last_line.length;
  931. // if last line is empty we must just increase lineNumber and work with next line
  932. if (line_length == 0) {
  933. lineNumber++;
  934. continue;
  935. }
  936. var index = i + line_length - 1 + lineNumber;
  937. if (index < 0) continue;
  938. var lastChar = this.getChildByTag(index);
  939. if (lastChar == null)
  940. continue;
  941. lineWidth = lastChar.getPositionX() + lastChar.getContentSize().width / 2;
  942. var shift = 0;
  943. switch (this._alignment) {
  944. case cc.TEXT_ALIGNMENT_CENTER:
  945. shift = this.getContentSize().width / 2 - lineWidth / 2;
  946. break;
  947. case cc.TEXT_ALIGNMENT_RIGHT:
  948. shift = this.getContentSize().width - lineWidth;
  949. break;
  950. default:
  951. break;
  952. }
  953. if (shift != 0) {
  954. for (j = 0; j < line_length; j++) {
  955. index = i + j + lineNumber;
  956. if (index < 0) continue;
  957. characterSprite = this.getChildByTag(index);
  958. if (characterSprite)
  959. characterSprite.setPosition(cc.pAdd(characterSprite.getPosition(), cc.p(shift, 0)));
  960. }
  961. }
  962. i += line_length;
  963. lineNumber++;
  964. last_line.length = 0;
  965. continue;
  966. }
  967. last_line.push(this._string[i]);
  968. }
  969. }
  970. },
  971. /**
  972. * Set text vertical alignment
  973. * @param {Number} alignment
  974. */
  975. setAlignment:function (alignment) {
  976. this._alignment = alignment;
  977. this.updateLabel();
  978. },
  979. /**
  980. * @param {Number} width
  981. */
  982. setWidth:function (width) {
  983. this._width = width;
  984. this.updateLabel();
  985. },
  986. /**
  987. * @param {Boolean} breakWithoutSpace
  988. */
  989. setLineBreakWithoutSpace:function (breakWithoutSpace) {
  990. this._lineBreakWithoutSpaces = breakWithoutSpace;
  991. this.updateLabel();
  992. },
  993. /**
  994. * @param {Number} scale
  995. * @param {Number} [scaleY=null]
  996. */
  997. setScale:function (scale, scaleY) {
  998. cc.Node.prototype.setScale.call(this, scale, scaleY);
  999. this.updateLabel();
  1000. },
  1001. /**
  1002. * @param {Number} scaleX
  1003. */
  1004. setScaleX:function (scaleX) {
  1005. cc.Node.prototype.setScaleX.call(this,scaleX);
  1006. this.updateLabel();
  1007. },
  1008. /**
  1009. * @param {Number} scaleY
  1010. */
  1011. setScaleY:function (scaleY) {
  1012. cc.Node.prototype.setScaleY.call(this,scaleY);
  1013. this.updateLabel();
  1014. },
  1015. //TODO
  1016. /**
  1017. * set fnt file path
  1018. * @param {String} fntFile
  1019. */
  1020. setFntFile:function (fntFile) {
  1021. if (fntFile != null && fntFile != this._fntFile) {
  1022. var newConf = cc.FNTConfigLoadFile(fntFile);
  1023. if(!newConf){
  1024. cc.log("cc.LabelBMFont.setFntFile() : Impossible to create font. Please check file");
  1025. return;
  1026. }
  1027. this._fntFile = fntFile;
  1028. this._configuration = newConf;
  1029. var texture = cc.TextureCache.getInstance().addImage(this._configuration.getAtlasName());
  1030. var locIsLoaded = texture.isLoaded();
  1031. this._textureLoaded = locIsLoaded;
  1032. this.setTexture(texture);
  1033. if (cc.renderContextType === cc.CANVAS)
  1034. this._originalTexture = this.getTexture();
  1035. if(!locIsLoaded){
  1036. texture.addLoadedEventListener(function(sender){
  1037. this._textureLoaded = true;
  1038. this.setTexture(sender);
  1039. this.createFontChars();
  1040. this._changeTextureColor();
  1041. this.updateLabel();
  1042. this._callLoadedEventCallbacks();
  1043. }, this);
  1044. } else {
  1045. this.createFontChars();
  1046. }
  1047. }
  1048. },
  1049. /**
  1050. * @return {String}
  1051. */
  1052. getFntFile:function () {
  1053. return this._fntFile;
  1054. },
  1055. /**
  1056. * set the AnchorPoint of the labelBMFont
  1057. * @override
  1058. * @param {cc.Point|Number} point The anchor point of labelBMFont or The anchor point.x of labelBMFont.
  1059. * @param {Number} [y] The anchor point.y of labelBMFont.
  1060. */
  1061. setAnchorPoint:function (point, y) {
  1062. cc.Node.prototype.setAnchorPoint.call(this, point, y);
  1063. this.updateLabel();
  1064. },
  1065. _atlasNameFromFntFile:function (fntFile) {
  1066. },
  1067. _kerningAmountForFirst:function (first, second) {
  1068. var ret = 0;
  1069. var key = (first << 16) | (second & 0xffff);
  1070. if (this._configuration.kerningDictionary) {
  1071. var element = this._configuration.kerningDictionary[key.toString()];
  1072. if (element)
  1073. ret = element.amount;
  1074. }
  1075. return ret;
  1076. },
  1077. _getLetterPosXLeft:function (sp) {
  1078. return sp.getPositionX() * this._scaleX - (sp.getContentSize().width * this._scaleX * sp.getAnchorPoint().x);
  1079. },
  1080. _getLetterPosXRight:function (sp) {
  1081. return sp.getPositionX() * this._scaleX + (sp.getContentSize().width * this._scaleX * (1 - sp.getAnchorPoint().x));
  1082. }
  1083. });
  1084. /**
  1085. * creates a bitmap font atlas with an initial string and the FNT file
  1086. * @param {String} str
  1087. * @param {String} fntFile
  1088. * @param {Number} width
  1089. * @param {Number} alignment
  1090. * @param {cc.Point} imageOffset
  1091. * @return {cc.LabelBMFont|Null}
  1092. * @example
  1093. * // Example 01
  1094. * var label1 = cc.LabelBMFont.create("Test case", "test.fnt");
  1095. *
  1096. * // Example 02
  1097. * var label2 = cc.LabelBMFont.create("test case", "test.fnt", 200, cc.TEXT_ALIGNMENT_LEFT);
  1098. *
  1099. * // Example 03
  1100. * var label3 = cc.LabelBMFont.create("This is a \n test case", "test.fnt", 200, cc.TEXT_ALIGNMENT_LEFT, cc.PointZero());
  1101. */
  1102. cc.LabelBMFont.create = function (str, fntFile, width, alignment, imageOffset) {
  1103. var ret = new cc.LabelBMFont();
  1104. if (str === undefined) {
  1105. if (ret && ret.init())
  1106. return ret;
  1107. return null;
  1108. }
  1109. if (ret && ret.initWithString(str, fntFile, width, alignment, imageOffset)) {
  1110. return ret;
  1111. }
  1112. return null;
  1113. };
  1114. /**
  1115. * shared instance of configuration
  1116. * @type cc.BMFontConfiguration
  1117. */
  1118. cc.LabelBMFont._configurations = null;
  1119. /**
  1120. * Load the .fnt file
  1121. * @param {String} fntFile
  1122. * @return {cc.BMFontConfiguration}
  1123. * Constructor
  1124. */
  1125. cc.FNTConfigLoadFile = function (fntFile) {
  1126. if (!cc.LabelBMFont._configurations) {
  1127. cc.LabelBMFont._configurations = {};
  1128. }
  1129. var ret = cc.LabelBMFont._configurations[fntFile];
  1130. if (!ret) {
  1131. ret = cc.BMFontConfiguration.create(fntFile);
  1132. cc.LabelBMFont._configurations[fntFile] = ret;
  1133. }
  1134. return ret;
  1135. };
  1136. /**
  1137. * Purges the cached .fnt data
  1138. */
  1139. cc.LabelBMFont.purgeCachedData = function () {
  1140. cc.FNTConfigRemoveCache();
  1141. };
  1142. /**
  1143. * Purges the FNT config cache
  1144. */
  1145. cc.FNTConfigRemoveCache = function () {
  1146. if (cc.LabelBMFont._configurations) {
  1147. cc.LabelBMFont._configurations = null;
  1148. }
  1149. };
  1150. /**
  1151. * @param {String} ch
  1152. * @return {Boolean} weather the character is a whitespace character.
  1153. */
  1154. cc.isspace_unicode = function (ch) {
  1155. ch = ch.charCodeAt(0);
  1156. return ((ch >= 9 && ch <= 13) || ch == 32 || ch == 133 || ch == 160 || ch == 5760
  1157. || (ch >= 8192 && ch <= 8202) || ch == 8232 || ch == 8233 || ch == 8239
  1158. || ch == 8287 || ch == 12288)
  1159. };
  1160. /**
  1161. * @param {Array} str
  1162. */
  1163. cc.utf8_trim_ws = function (str) {
  1164. var len = str.length;
  1165. if (len <= 0)
  1166. return;
  1167. var last_index = len - 1;
  1168. // Only start trimming if the last character is whitespace..
  1169. if (cc.isspace_unicode(str[last_index])) {
  1170. for (var i = last_index - 1; i >= 0; --i) {
  1171. if (cc.isspace_unicode(str[i])) {
  1172. last_index = i;
  1173. }
  1174. else {
  1175. break;
  1176. }
  1177. }
  1178. cc.utf8_trim_from(str, last_index);
  1179. }
  1180. };
  1181. /**
  1182. * Trims str st str=[0, index) after the operation.
  1183. * Return value: the trimmed string.
  1184. * @param {Array} str he string to trim
  1185. * @param {Number} index the index to start trimming from.
  1186. */
  1187. cc.utf8_trim_from = function (str, index) {
  1188. var len = str.length;
  1189. if (index >= len || index < 0)
  1190. return;
  1191. str.splice(index, len);
  1192. };