Font.cpp 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003
  1. #include "Base.h"
  2. #include "Font.h"
  3. #include "Game.h"
  4. #include "FileSystem.h"
  5. #include "Bundle.h"
  6. // Default font shaders
  7. #define FONT_VSH "res/shaders/font.vert"
  8. #define FONT_FSH "res/shaders/font.frag"
  9. namespace gameplay
  10. {
  11. static std::vector<Font*> __fontCache;
  12. static Effect* __fontEffect = NULL;
  13. Font::Font() :
  14. _format(BITMAP), _style(PLAIN), _size(0), _spacing(0.125f), _glyphs(NULL), _glyphCount(0), _texture(NULL), _batch(NULL), _cutoffParam(NULL)
  15. {
  16. }
  17. Font::~Font()
  18. {
  19. // Remove this Font from the font cache.
  20. std::vector<Font*>::iterator itr = std::find(__fontCache.begin(), __fontCache.end(), this);
  21. if (itr != __fontCache.end())
  22. {
  23. __fontCache.erase(itr);
  24. }
  25. SAFE_DELETE(_batch);
  26. SAFE_DELETE_ARRAY(_glyphs);
  27. SAFE_RELEASE(_texture);
  28. // Free child fonts
  29. for (size_t i = 0, count = _sizes.size(); i < count; ++i)
  30. {
  31. SAFE_RELEASE(_sizes[i]);
  32. }
  33. }
  34. Font* Font::create(const char* path, const char* id)
  35. {
  36. GP_ASSERT(path);
  37. // Search the font cache for a font with the given path and ID.
  38. for (size_t i = 0, count = __fontCache.size(); i < count; ++i)
  39. {
  40. Font* f = __fontCache[i];
  41. GP_ASSERT(f);
  42. if (f->_path == path && (id == NULL || f->_id == id))
  43. {
  44. // Found a match.
  45. f->addRef();
  46. return f;
  47. }
  48. }
  49. // Load the bundle.
  50. Bundle* bundle = Bundle::create(path);
  51. if (bundle == NULL)
  52. {
  53. GP_WARN("Failed to load font bundle '%s'.", path);
  54. return NULL;
  55. }
  56. Font* font = NULL;
  57. if (id == NULL)
  58. {
  59. // Get the ID of the first object in the bundle (assume it's a Font).
  60. const char* id;
  61. if ((id = bundle->getObjectId(0)) == NULL)
  62. {
  63. GP_WARN("Failed to load font without explicit id; the first object in the font bundle has a null id.");
  64. return NULL;
  65. }
  66. // Load the font using the ID of the first object in the bundle.
  67. font = bundle->loadFont(bundle->getObjectId(0));
  68. }
  69. else
  70. {
  71. // Load the font with the given ID.
  72. font = bundle->loadFont(id);
  73. }
  74. if (font)
  75. {
  76. // Add this font to the cache.
  77. __fontCache.push_back(font);
  78. }
  79. SAFE_RELEASE(bundle);
  80. return font;
  81. }
  82. Font* Font::create(const char* family, Style style, unsigned int size, Glyph* glyphs, int glyphCount, Texture* texture, Font::Format format)
  83. {
  84. GP_ASSERT(family);
  85. GP_ASSERT(glyphs);
  86. GP_ASSERT(texture);
  87. // Create the effect for the font's sprite batch.
  88. if (__fontEffect == NULL)
  89. {
  90. const char* defines = NULL;
  91. if (format == DISTANCE_FIELD)
  92. defines = "DISTANCE_FIELD";
  93. __fontEffect = Effect::createFromFile(FONT_VSH, FONT_FSH, defines);
  94. if (__fontEffect == NULL)
  95. {
  96. GP_WARN("Failed to create effect for font.");
  97. SAFE_RELEASE(texture);
  98. return NULL;
  99. }
  100. }
  101. else
  102. {
  103. __fontEffect->addRef();
  104. }
  105. // Create batch for the font.
  106. SpriteBatch* batch = SpriteBatch::create(texture, __fontEffect, 128);
  107. // Release __fontEffect since the SpriteBatch keeps a reference to it
  108. SAFE_RELEASE(__fontEffect);
  109. if (batch == NULL)
  110. {
  111. GP_WARN("Failed to create batch for font.");
  112. return NULL;
  113. }
  114. // Add linear filtering for better font quality.
  115. Texture::Sampler* sampler = batch->getSampler();
  116. sampler->setFilterMode(Texture::LINEAR_MIPMAP_LINEAR, Texture::LINEAR);
  117. sampler->setWrapMode(Texture::CLAMP, Texture::CLAMP);
  118. // Increase the ref count of the texture to retain it.
  119. texture->addRef();
  120. Font* font = new Font();
  121. font->_format = format;
  122. font->_family = family;
  123. font->_style = style;
  124. font->_size = size;
  125. font->_texture = texture;
  126. font->_batch = batch;
  127. // Copy the glyphs array.
  128. font->_glyphs = new Glyph[glyphCount];
  129. memcpy(font->_glyphs, glyphs, sizeof(Glyph) * glyphCount);
  130. font->_glyphCount = glyphCount;
  131. return font;
  132. }
  133. unsigned int Font::getSize(unsigned int index) const
  134. {
  135. GP_ASSERT(index <= _sizes.size());
  136. // index zero == this font
  137. return index == 0 ? _size : _sizes[index - 1]->_size;
  138. }
  139. unsigned int Font::getSizeCount() const
  140. {
  141. return _sizes.size() + 1; // +1 for "this" font
  142. }
  143. Font::Format Font::getFormat()
  144. {
  145. return _format;
  146. }
  147. bool Font::isCharacterSupported(int character) const
  148. {
  149. // TODO: Update this once we support unicode fonts
  150. int glyphIndex = character - 32; // HACK for ASCII
  151. return (glyphIndex >= 0 && glyphIndex < (int)_glyphCount);
  152. }
  153. void Font::start()
  154. {
  155. // no-op : fonts now are lazily started on the first draw call
  156. }
  157. void Font::lazyStart()
  158. {
  159. if (_batch->isStarted())
  160. return; // already started
  161. // Update the projection matrix for our batch to match the current viewport
  162. const Rectangle& vp = Game::getInstance()->getViewport();
  163. if (!vp.isEmpty())
  164. {
  165. Game* game = Game::getInstance();
  166. Matrix projectionMatrix;
  167. Matrix::createOrthographicOffCenter(vp.x, vp.width, vp.height, vp.y, 0, 1, &projectionMatrix);
  168. _batch->setProjectionMatrix(projectionMatrix);
  169. }
  170. _batch->start();
  171. }
  172. void Font::finish()
  173. {
  174. // Finish any font batches that have been started
  175. if (_batch->isStarted())
  176. _batch->finish();
  177. for (size_t i = 0, count = _sizes.size(); i < count; ++i)
  178. {
  179. SpriteBatch* batch = _sizes[i]->_batch;
  180. if (batch->isStarted())
  181. batch->finish();
  182. }
  183. }
  184. Font::Text* Font::createText(const char* text, const Rectangle& area, const Vector4& color, unsigned int size, Justify justify,
  185. bool wrap, bool rightToLeft, const Rectangle* clip)
  186. {
  187. GP_ASSERT(text);
  188. GP_ASSERT(_glyphs);
  189. GP_ASSERT(_batch);
  190. GP_ASSERT(_size);
  191. if (size == 0)
  192. {
  193. size = _size;
  194. }
  195. else
  196. {
  197. // Delegate to closest sized font
  198. Font* f = findClosestSize(size);
  199. if (f != this)
  200. {
  201. return f->createText(text, area, color, size, justify, wrap, rightToLeft, clip);
  202. }
  203. }
  204. float scale = (float)size / _size;
  205. int spacing = (int)(size * _spacing);
  206. int yPos = area.y;
  207. const float areaHeight = area.height - size;
  208. std::vector<int> xPositions;
  209. std::vector<unsigned int> lineLengths;
  210. getMeasurementInfo(text, area, size, justify, wrap, rightToLeft, &xPositions, &yPos, &lineLengths);
  211. Text* batch = new Text(text);
  212. batch->_font = this;
  213. batch->_font->addRef();
  214. GP_ASSERT(batch->_vertices);
  215. GP_ASSERT(batch->_indices);
  216. int xPos = area.x;
  217. std::vector<int>::const_iterator xPositionsIt = xPositions.begin();
  218. if (xPositionsIt != xPositions.end())
  219. {
  220. xPos = *xPositionsIt++;
  221. }
  222. const char* token = text;
  223. int iteration = 1;
  224. unsigned int lineLength;
  225. unsigned int currentLineLength = 0;
  226. const char* lineStart;
  227. std::vector<unsigned int>::const_iterator lineLengthsIt;
  228. if (rightToLeft)
  229. {
  230. lineStart = token;
  231. lineLengthsIt = lineLengths.begin();
  232. lineLength = *lineLengthsIt++;
  233. token += lineLength - 1;
  234. iteration = -1;
  235. }
  236. while (token[0] != 0)
  237. {
  238. // Handle delimiters until next token.
  239. if (!handleDelimiters(&token, size, iteration, area.x, &xPos, &yPos, &currentLineLength, &xPositionsIt, xPositions.end()))
  240. {
  241. break;
  242. }
  243. bool truncated = false;
  244. unsigned int tokenLength;
  245. unsigned int tokenWidth;
  246. unsigned int startIndex;
  247. if (rightToLeft)
  248. {
  249. tokenLength = getReversedTokenLength(token, text);
  250. currentLineLength += tokenLength;
  251. token -= (tokenLength - 1);
  252. tokenWidth = getTokenWidth(token, tokenLength, size, scale);
  253. iteration = -1;
  254. startIndex = tokenLength - 1;
  255. }
  256. else
  257. {
  258. tokenLength = (unsigned int)strcspn(token, " \r\n\t");
  259. tokenWidth = getTokenWidth(token, tokenLength, size, scale);
  260. iteration = 1;
  261. startIndex = 0;
  262. }
  263. // Wrap if necessary.
  264. if (wrap && (xPos + (int)tokenWidth > area.x + area.width || (rightToLeft && currentLineLength > lineLength)))
  265. {
  266. yPos += (int)size;
  267. currentLineLength = tokenLength;
  268. if (xPositionsIt != xPositions.end())
  269. {
  270. xPos = *xPositionsIt++;
  271. }
  272. else
  273. {
  274. xPos = area.x;
  275. }
  276. }
  277. bool draw = true;
  278. if (yPos < static_cast<int>(area.y))
  279. {
  280. // Skip drawing until line break or wrap.
  281. draw = false;
  282. }
  283. else if (yPos > area.y + areaHeight)
  284. {
  285. // Truncate below area's vertical limit.
  286. break;
  287. }
  288. for (int i = startIndex; i < (int)tokenLength && i >= 0; i += iteration)
  289. {
  290. char c = token[i];
  291. int glyphIndex = c - 32; // HACK for ASCII
  292. if (glyphIndex >= 0 && glyphIndex < (int)_glyphCount)
  293. {
  294. Glyph& g = _glyphs[glyphIndex];
  295. if (xPos + (int)(g.width*scale) > area.x + area.width)
  296. {
  297. // Truncate this line and go on to the next one.
  298. truncated = true;
  299. break;
  300. }
  301. else if (xPos >= area.x)
  302. {
  303. // Draw this character.
  304. if (draw)
  305. {
  306. if (clip)
  307. {
  308. _batch->addSprite(xPos, yPos, g.width * scale, size, g.uvs[0], g.uvs[1], g.uvs[2], g.uvs[3], color, *clip, &batch->_vertices[batch->_vertexCount]);
  309. }
  310. else
  311. {
  312. _batch->addSprite(xPos, yPos, g.width * scale, size, g.uvs[0], g.uvs[1], g.uvs[2], g.uvs[3], color, &batch->_vertices[batch->_vertexCount]);
  313. }
  314. if (batch->_vertexCount == 0)
  315. {
  316. // Simply copy values directly into the start of the index array
  317. batch->_indices[batch->_vertexCount] = batch->_vertexCount;
  318. batch->_indices[batch->_vertexCount + 1] = batch->_vertexCount + 1;
  319. batch->_indices[batch->_vertexCount + 2] = batch->_vertexCount + 2;
  320. batch->_indices[batch->_vertexCount + 3] = batch->_vertexCount + 3;
  321. batch->_vertexCount += 4;
  322. batch->_indexCount += 4;
  323. }
  324. else
  325. {
  326. // Create a degenerate triangle to connect separate triangle strips
  327. // by duplicating the previous and next vertices.
  328. batch->_indices[batch->_indexCount] = batch->_indices[batch->_indexCount - 1];
  329. batch->_indices[batch->_indexCount + 1] = batch->_vertexCount;
  330. // Loop through all indices and insert them, their their value offset by
  331. // 'vertexCount' so that they are relative to the first newly insertted vertex
  332. for (unsigned int i = 0; i < 4; ++i)
  333. {
  334. batch->_indices[batch->_indexCount + 2 + i] = i + batch->_vertexCount;
  335. }
  336. batch->_indexCount += 6;
  337. batch->_vertexCount += 4;
  338. }
  339. }
  340. }
  341. xPos += (int)(g.width)*scale + spacing;
  342. }
  343. }
  344. if (!truncated)
  345. {
  346. if (rightToLeft)
  347. {
  348. if (token == lineStart)
  349. {
  350. token += lineLength;
  351. // Now handle delimiters going forwards.
  352. if (!handleDelimiters(&token, size, 1, area.x, &xPos, &yPos, &currentLineLength, &xPositionsIt, xPositions.end()))
  353. {
  354. break;
  355. }
  356. if (lineLengthsIt != lineLengths.end())
  357. {
  358. lineLength = *lineLengthsIt++;
  359. }
  360. lineStart = token;
  361. token += lineLength-1;
  362. }
  363. else
  364. {
  365. token--;
  366. }
  367. }
  368. else
  369. {
  370. token += tokenLength;
  371. }
  372. }
  373. else
  374. {
  375. if (rightToLeft)
  376. {
  377. token = lineStart + lineLength;
  378. if (!handleDelimiters(&token, size, 1, area.x, &xPos, &yPos, &currentLineLength, &xPositionsIt, xPositions.end()))
  379. {
  380. break;
  381. }
  382. if (lineLengthsIt != lineLengths.end())
  383. {
  384. lineLength = *lineLengthsIt++;
  385. }
  386. lineStart = token;
  387. token += lineLength-1;
  388. }
  389. else
  390. {
  391. // Skip the rest of this line.
  392. size_t tokenLength = strcspn(token, "\n");
  393. if (tokenLength > 0)
  394. {
  395. // Get first token of next line.
  396. token += tokenLength;
  397. }
  398. }
  399. }
  400. }
  401. return batch;
  402. }
  403. Font* Font::findClosestSize(int size)
  404. {
  405. if (size == _size)
  406. return this;
  407. int diff = abs(size - (int)_size);
  408. Font* closest = this;
  409. for (size_t i = 0, count = _sizes.size(); i < count; ++i)
  410. {
  411. Font* f = _sizes[i];
  412. int d = abs(size - (int)f->_size);
  413. if (d < diff || (d == diff && f->_size > closest->_size)) // prefer scaling down instead of up
  414. {
  415. diff = d;
  416. closest = f;
  417. }
  418. }
  419. return closest;
  420. }
  421. void Font::drawText(Text* text)
  422. {
  423. GP_ASSERT(text);
  424. GP_ASSERT(text->_font);
  425. if (text->_font != this)
  426. {
  427. // Make sure we draw using the font/batch the text was created with
  428. text->_font->drawText(text);
  429. return;
  430. }
  431. GP_ASSERT(_batch);
  432. GP_ASSERT(text->_vertices);
  433. GP_ASSERT(text->_indices);
  434. lazyStart();
  435. _batch->draw(text->_vertices, text->_vertexCount, text->_indices, text->_indexCount);
  436. }
  437. void Font::drawText(const char* text, int x, int y, const Vector4& color, unsigned int size, bool rightToLeft)
  438. {
  439. GP_ASSERT(_size);
  440. GP_ASSERT(text);
  441. if (size == 0)
  442. {
  443. size = _size;
  444. }
  445. else
  446. {
  447. // Delegate to closest sized font
  448. Font* f = findClosestSize(size);
  449. if (f != this)
  450. {
  451. f->drawText(text, x, y, color, size, rightToLeft);
  452. return;
  453. }
  454. }
  455. lazyStart();
  456. float scale = (float)size / _size;
  457. int spacing = (int)(size * _spacing);
  458. const char* cursor = NULL;
  459. if (rightToLeft)
  460. {
  461. cursor = text;
  462. }
  463. int xPos = x, yPos = y;
  464. bool done = false;
  465. while (!done)
  466. {
  467. size_t length;
  468. size_t startIndex;
  469. int iteration;
  470. if (rightToLeft)
  471. {
  472. char delimiter = cursor[0];
  473. while (!done &&
  474. (delimiter == ' ' ||
  475. delimiter == '\t' ||
  476. delimiter == '\r' ||
  477. delimiter == '\n' ||
  478. delimiter == 0))
  479. {
  480. switch (delimiter)
  481. {
  482. case ' ':
  483. xPos += size >> 1;
  484. break;
  485. case '\r':
  486. case '\n':
  487. yPos += size;
  488. xPos = x;
  489. break;
  490. case '\t':
  491. xPos += (size >> 1)*4;
  492. break;
  493. case 0:
  494. done = true;
  495. break;
  496. }
  497. if (!done)
  498. {
  499. ++cursor;
  500. delimiter = cursor[0];
  501. }
  502. }
  503. length = strcspn(cursor, "\r\n");
  504. startIndex = length - 1;
  505. iteration = -1;
  506. }
  507. else
  508. {
  509. length = strlen(text);
  510. startIndex = 0;
  511. iteration = 1;
  512. }
  513. GP_ASSERT(_glyphs);
  514. GP_ASSERT(_batch);
  515. for (size_t i = startIndex; i < length; i += (size_t)iteration)
  516. {
  517. char c = 0;
  518. if (rightToLeft)
  519. {
  520. c = cursor[i];
  521. }
  522. else
  523. {
  524. c = text[i];
  525. }
  526. // Draw this character.
  527. switch (c)
  528. {
  529. case ' ':
  530. xPos += size >> 1;
  531. break;
  532. case '\r':
  533. case '\n':
  534. yPos += size;
  535. xPos = x;
  536. break;
  537. case '\t':
  538. xPos += (size >> 1)*4;
  539. break;
  540. default:
  541. int index = c - 32; // HACK for ASCII
  542. if (index >= 0 && index < (int)_glyphCount)
  543. {
  544. Glyph& g = _glyphs[index];
  545. if (getFormat() == DISTANCE_FIELD )
  546. {
  547. if (_cutoffParam == NULL)
  548. _cutoffParam = _batch->getMaterial()->getParameter("u_cutoff");
  549. // TODO: Fix me so that smaller font are much smoother
  550. _cutoffParam->setVector2(Vector2(1.0, 1.0));
  551. }
  552. _batch->draw(xPos, yPos, g.width * scale, size, g.uvs[0], g.uvs[1], g.uvs[2], g.uvs[3], color);
  553. xPos += floor(g.width * scale + spacing);
  554. break;
  555. }
  556. break;
  557. }
  558. }
  559. if (rightToLeft)
  560. {
  561. cursor += length;
  562. }
  563. else
  564. {
  565. done = true;
  566. }
  567. }
  568. }
  569. void Font::drawText(const char* text, int x, int y, float red, float green, float blue, float alpha, unsigned int size, bool rightToLeft)
  570. {
  571. drawText(text, x, y, Vector4(red, green, blue, alpha), size, rightToLeft);
  572. }
  573. void Font::drawText(const char* text, const Rectangle& area, const Vector4& color, unsigned int size, Justify justify, bool wrap, bool rightToLeft, const Rectangle* clip)
  574. {
  575. GP_ASSERT(text);
  576. GP_ASSERT(_size);
  577. if (size == 0)
  578. {
  579. size = _size;
  580. }
  581. else
  582. {
  583. // Delegate to closest sized font
  584. Font* f = findClosestSize(size);
  585. if (f != this)
  586. {
  587. f->drawText(text, area, color, size, justify, wrap, rightToLeft, clip);
  588. return;
  589. }
  590. }
  591. lazyStart();
  592. float scale = (float)size / _size;
  593. int spacing = (int)(size * _spacing);
  594. int yPos = area.y;
  595. const float areaHeight = area.height - size;
  596. std::vector<int> xPositions;
  597. std::vector<unsigned int> lineLengths;
  598. getMeasurementInfo(text, area, size, justify, wrap, rightToLeft, &xPositions, &yPos, &lineLengths);
  599. // Now we have the info we need in order to render.
  600. int xPos = area.x;
  601. std::vector<int>::const_iterator xPositionsIt = xPositions.begin();
  602. if (xPositionsIt != xPositions.end())
  603. {
  604. xPos = *xPositionsIt++;
  605. }
  606. const char* token = text;
  607. int iteration = 1;
  608. unsigned int lineLength;
  609. unsigned int currentLineLength = 0;
  610. const char* lineStart;
  611. std::vector<unsigned int>::const_iterator lineLengthsIt;
  612. if (rightToLeft)
  613. {
  614. lineStart = token;
  615. lineLengthsIt = lineLengths.begin();
  616. lineLength = *lineLengthsIt++;
  617. token += lineLength - 1;
  618. iteration = -1;
  619. }
  620. while (token[0] != 0)
  621. {
  622. // Handle delimiters until next token.
  623. if (!handleDelimiters(&token, size, iteration, area.x, &xPos, &yPos, &currentLineLength, &xPositionsIt, xPositions.end()))
  624. {
  625. break;
  626. }
  627. bool truncated = false;
  628. unsigned int tokenLength;
  629. unsigned int tokenWidth;
  630. unsigned int startIndex;
  631. if (rightToLeft)
  632. {
  633. tokenLength = getReversedTokenLength(token, text);
  634. currentLineLength += tokenLength;
  635. token -= (tokenLength - 1);
  636. tokenWidth = getTokenWidth(token, tokenLength, size, scale);
  637. iteration = -1;
  638. startIndex = tokenLength - 1;
  639. }
  640. else
  641. {
  642. tokenLength = (unsigned int)strcspn(token, " \r\n\t");
  643. tokenWidth = getTokenWidth(token, tokenLength, size, scale);
  644. iteration = 1;
  645. startIndex = 0;
  646. }
  647. // Wrap if necessary.
  648. if (wrap && (xPos + (int)tokenWidth > area.x + area.width || (rightToLeft && currentLineLength > lineLength)))
  649. {
  650. yPos += (int)size;
  651. currentLineLength = tokenLength;
  652. if (xPositionsIt != xPositions.end())
  653. {
  654. xPos = *xPositionsIt++;
  655. }
  656. else
  657. {
  658. xPos = area.x;
  659. }
  660. }
  661. bool draw = true;
  662. if (yPos < static_cast<int>(area.y - size))
  663. {
  664. // Skip drawing until line break or wrap.
  665. draw = false;
  666. }
  667. else if (yPos > area.y + areaHeight)
  668. {
  669. // Truncate below area's vertical limit.
  670. break;
  671. }
  672. GP_ASSERT(_glyphs);
  673. GP_ASSERT(_batch);
  674. for (int i = startIndex; i < (int)tokenLength && i >= 0; i += iteration)
  675. {
  676. char c = token[i];
  677. int glyphIndex = c - 32; // HACK for ASCII
  678. if (glyphIndex >= 0 && glyphIndex < (int)_glyphCount)
  679. {
  680. Glyph& g = _glyphs[glyphIndex];
  681. if (xPos + (int)(g.width*scale) > area.x + area.width)
  682. {
  683. // Truncate this line and go on to the next one.
  684. truncated = true;
  685. break;
  686. }
  687. else if (xPos >= area.x)
  688. {
  689. // Draw this character.
  690. if (draw)
  691. {
  692. if (getFormat() == DISTANCE_FIELD)
  693. {
  694. if (_cutoffParam == NULL)
  695. _cutoffParam = _batch->getMaterial()->getParameter("u_cutoff");
  696. // TODO: Fix me so that smaller font are much smoother
  697. _cutoffParam->setVector2(Vector2(1.0, 1.0));
  698. }
  699. if (clip)
  700. {
  701. _batch->draw(xPos, yPos, g.width * scale, size, g.uvs[0], g.uvs[1], g.uvs[2], g.uvs[3], color, *clip);
  702. }
  703. else
  704. {
  705. _batch->draw(xPos, yPos, g.width * scale, size, g.uvs[0], g.uvs[1], g.uvs[2], g.uvs[3], color);
  706. }
  707. }
  708. }
  709. xPos += (int)(g.width)*scale + spacing;
  710. }
  711. }
  712. if (!truncated)
  713. {
  714. if (rightToLeft)
  715. {
  716. if (token == lineStart)
  717. {
  718. token += lineLength;
  719. // Now handle delimiters going forwards.
  720. if (!handleDelimiters(&token, size, 1, area.x, &xPos, &yPos, &currentLineLength, &xPositionsIt, xPositions.end()))
  721. {
  722. break;
  723. }
  724. if (lineLengthsIt != lineLengths.end())
  725. {
  726. lineLength = *lineLengthsIt++;
  727. }
  728. lineStart = token;
  729. token += lineLength-1;
  730. }
  731. else
  732. {
  733. token--;
  734. }
  735. }
  736. else
  737. {
  738. token += tokenLength;
  739. }
  740. }
  741. else
  742. {
  743. if (rightToLeft)
  744. {
  745. token = lineStart + lineLength;
  746. if (!handleDelimiters(&token, size, 1, area.x, &xPos, &yPos, &currentLineLength, &xPositionsIt, xPositions.end()))
  747. {
  748. break;
  749. }
  750. if (lineLengthsIt != lineLengths.end())
  751. {
  752. lineLength = *lineLengthsIt++;
  753. }
  754. lineStart = token;
  755. token += lineLength-1;
  756. }
  757. else
  758. {
  759. // Skip the rest of this line.
  760. size_t tokenLength = strcspn(token, "\n");
  761. if (tokenLength > 0)
  762. {
  763. // Get first token of next line.
  764. token += tokenLength;
  765. }
  766. }
  767. }
  768. }
  769. }
  770. void Font::measureText(const char* text, unsigned int size, unsigned int* width, unsigned int* height)
  771. {
  772. GP_ASSERT(_size);
  773. GP_ASSERT(text);
  774. GP_ASSERT(width);
  775. GP_ASSERT(height);
  776. if (size == 0)
  777. {
  778. size = _size;
  779. }
  780. else
  781. {
  782. // Delegate to closest sized font
  783. Font* f = findClosestSize(size);
  784. if (f != this)
  785. {
  786. f->measureText(text, size, width, height);
  787. return;
  788. }
  789. }
  790. const size_t length = strlen(text);
  791. if (length == 0)
  792. {
  793. *width = 0;
  794. *height = 0;
  795. return;
  796. }
  797. float scale = (float)size / _size;
  798. const char* token = text;
  799. *width = 0;
  800. *height = size;
  801. // Measure a line at a time.
  802. while (token[0] != 0)
  803. {
  804. while (token[0] == '\n')
  805. {
  806. *height += size;
  807. ++token;
  808. }
  809. unsigned int tokenLength = (unsigned int)strcspn(token, "\n");
  810. unsigned int tokenWidth = getTokenWidth(token, tokenLength, size, scale);
  811. if (tokenWidth > *width)
  812. {
  813. *width = tokenWidth;
  814. }
  815. token += tokenLength;
  816. }
  817. }
  818. void Font::measureText(const char* text, const Rectangle& clip, unsigned int size, Rectangle* out, Justify justify, bool wrap, bool ignoreClip)
  819. {
  820. GP_ASSERT(_size);
  821. GP_ASSERT(text);
  822. GP_ASSERT(out);
  823. if (size == 0)
  824. {
  825. size = _size;
  826. }
  827. else
  828. {
  829. // Delegate to closest sized font
  830. Font* f = findClosestSize(size);
  831. if (f != this)
  832. {
  833. f->measureText(text, clip, size, out, justify, wrap, ignoreClip);
  834. return;
  835. }
  836. }
  837. if (strlen(text) == 0)
  838. {
  839. out->set(0, 0, 0, 0);
  840. return;
  841. }
  842. float scale = (float)size / _size;
  843. Justify vAlign = static_cast<Justify>(justify & 0xF0);
  844. if (vAlign == 0)
  845. {
  846. vAlign = ALIGN_TOP;
  847. }
  848. Justify hAlign = static_cast<Justify>(justify & 0x0F);
  849. if (hAlign == 0)
  850. {
  851. hAlign = ALIGN_LEFT;
  852. }
  853. const char* token = text;
  854. std::vector<bool> emptyLines;
  855. std::vector<Vector2> lines;
  856. unsigned int lineWidth = 0;
  857. int yPos = clip.y + size;
  858. const float viewportHeight = clip.height;
  859. if (wrap)
  860. {
  861. unsigned int delimWidth = 0;
  862. bool reachedEOF = false;
  863. while (token[0] != 0)
  864. {
  865. // Handle delimiters until next token.
  866. char delimiter = token[0];
  867. while (delimiter == ' ' ||
  868. delimiter == '\t' ||
  869. delimiter == '\r' ||
  870. delimiter == '\n' ||
  871. delimiter == 0)
  872. {
  873. switch (delimiter)
  874. {
  875. case ' ':
  876. delimWidth += size >> 1;
  877. break;
  878. case '\r':
  879. case '\n':
  880. // Add line-height to vertical cursor.
  881. yPos += size;
  882. if (lineWidth > 0)
  883. {
  884. // Determine horizontal position and width.
  885. int hWhitespace = clip.width - lineWidth;
  886. int xPos = clip.x;
  887. if (hAlign == ALIGN_HCENTER)
  888. {
  889. xPos += hWhitespace / 2;
  890. }
  891. else if (hAlign == ALIGN_RIGHT)
  892. {
  893. xPos += hWhitespace;
  894. }
  895. // Record this line's size.
  896. emptyLines.push_back(false);
  897. lines.push_back(Vector2(xPos, lineWidth));
  898. }
  899. else
  900. {
  901. // Record the existence of an empty line.
  902. emptyLines.push_back(true);
  903. lines.push_back(Vector2(FLT_MAX, 0));
  904. }
  905. lineWidth = 0;
  906. delimWidth = 0;
  907. break;
  908. case '\t':
  909. delimWidth += (size >> 1)*4;
  910. break;
  911. case 0:
  912. reachedEOF = true;
  913. break;
  914. }
  915. if (reachedEOF)
  916. {
  917. break;
  918. }
  919. token++;
  920. delimiter = token[0];
  921. }
  922. if (reachedEOF)
  923. {
  924. break;
  925. }
  926. // Measure the next token.
  927. unsigned int tokenLength = (unsigned int)strcspn(token, " \r\n\t");
  928. unsigned int tokenWidth = getTokenWidth(token, tokenLength, size, scale);
  929. // Wrap if necessary.
  930. if (lineWidth + tokenWidth + delimWidth > clip.width)
  931. {
  932. // Add line-height to vertical cursor.
  933. yPos += size;
  934. // Determine horizontal position and width.
  935. int hWhitespace = clip.width - lineWidth;
  936. int xPos = clip.x;
  937. if (hAlign == ALIGN_HCENTER)
  938. {
  939. xPos += hWhitespace / 2;
  940. }
  941. else if (hAlign == ALIGN_RIGHT)
  942. {
  943. xPos += hWhitespace;
  944. }
  945. // Record this line's size.
  946. emptyLines.push_back(false);
  947. lines.push_back(Vector2(xPos, lineWidth));
  948. lineWidth = 0;
  949. }
  950. else
  951. {
  952. lineWidth += delimWidth;
  953. }
  954. delimWidth = 0;
  955. lineWidth += tokenWidth;
  956. token += tokenLength;
  957. }
  958. }
  959. else
  960. {
  961. // Measure a whole line at a time.
  962. int emptyLinesCount = 0;
  963. while (token[0] != 0)
  964. {
  965. // Handle any number of consecutive newlines.
  966. bool nextLine = true;
  967. while (token[0] == '\n')
  968. {
  969. if (nextLine)
  970. {
  971. // Add line-height to vertical cursor.
  972. yPos += size * (emptyLinesCount+1);
  973. nextLine = false;
  974. emptyLinesCount = 0;
  975. emptyLines.push_back(false);
  976. }
  977. else
  978. {
  979. // Record the existence of an empty line.
  980. ++emptyLinesCount;
  981. emptyLines.push_back(true);
  982. lines.push_back(Vector2(FLT_MAX, 0));
  983. }
  984. token++;
  985. }
  986. // Measure the next line.
  987. unsigned int tokenLength = (unsigned int)strcspn(token, "\n");
  988. lineWidth = getTokenWidth(token, tokenLength, size, scale);
  989. // Determine horizontal position and width.
  990. int xPos = clip.x;
  991. int hWhitespace = clip.width - lineWidth;
  992. if (hAlign == ALIGN_HCENTER)
  993. {
  994. xPos += hWhitespace / 2;
  995. }
  996. else if (hAlign == ALIGN_RIGHT)
  997. {
  998. xPos += hWhitespace;
  999. }
  1000. // Record this line's size.
  1001. lines.push_back(Vector2(xPos, lineWidth));
  1002. token += tokenLength;
  1003. }
  1004. yPos += size;
  1005. }
  1006. if (wrap)
  1007. {
  1008. // Record the size of the last line.
  1009. int hWhitespace = clip.width - lineWidth;
  1010. int xPos = clip.x;
  1011. if (hAlign == ALIGN_HCENTER)
  1012. {
  1013. xPos += hWhitespace / 2;
  1014. }
  1015. else if (hAlign == ALIGN_RIGHT)
  1016. {
  1017. xPos += hWhitespace;
  1018. }
  1019. lines.push_back(Vector2(xPos, lineWidth));
  1020. }
  1021. int x = INT_MAX;
  1022. int y = clip.y;
  1023. unsigned int width = 0;
  1024. int height = yPos - clip.y;
  1025. // Calculate top of text without clipping.
  1026. int vWhitespace = viewportHeight - height;
  1027. if (vAlign == ALIGN_VCENTER)
  1028. {
  1029. y += vWhitespace / 2;
  1030. }
  1031. else if (vAlign == ALIGN_BOTTOM)
  1032. {
  1033. y += vWhitespace;
  1034. }
  1035. int clippedTop = 0;
  1036. int clippedBottom = 0;
  1037. if (!ignoreClip)
  1038. {
  1039. // Trim rect to fit text that would actually be drawn within the given clip.
  1040. if (y >= clip.y)
  1041. {
  1042. // Text goes off the bottom of the clip.
  1043. clippedBottom = (height - viewportHeight) / size + 1;
  1044. if (clippedBottom > 0)
  1045. {
  1046. // Also need to crop empty lines above non-empty lines that have been clipped.
  1047. size_t emptyIndex = emptyLines.size() - clippedBottom;
  1048. while (emptyIndex < emptyLines.size() && emptyLines[emptyIndex] == true)
  1049. {
  1050. height -= size;
  1051. emptyIndex++;
  1052. }
  1053. height -= size * clippedBottom;
  1054. }
  1055. else
  1056. {
  1057. clippedBottom = 0;
  1058. }
  1059. }
  1060. else
  1061. {
  1062. // Text goes above the top of the clip.
  1063. clippedTop = (clip.y - y) / size + 1;
  1064. if (clippedTop < 0)
  1065. {
  1066. clippedTop = 0;
  1067. }
  1068. // Also need to crop empty lines below non-empty lines that have been clipped.
  1069. size_t emptyIndex = clippedTop;
  1070. while (emptyIndex < emptyLines.size() && emptyLines[emptyIndex] == true)
  1071. {
  1072. y += size;
  1073. height -= size;
  1074. emptyIndex++;
  1075. }
  1076. if (vAlign == ALIGN_VCENTER)
  1077. {
  1078. // In this case lines may be clipped off the bottom as well.
  1079. clippedBottom = (height - viewportHeight + vWhitespace/2 + 0.01) / size + 1;
  1080. if (clippedBottom > 0)
  1081. {
  1082. emptyIndex = emptyLines.size() - clippedBottom;
  1083. while (emptyIndex < emptyLines.size() && emptyLines[emptyIndex] == true)
  1084. {
  1085. height -= size;
  1086. emptyIndex++;
  1087. }
  1088. height -= size * clippedBottom;
  1089. }
  1090. else
  1091. {
  1092. clippedBottom = 0;
  1093. }
  1094. }
  1095. y = y + size * clippedTop;
  1096. height = height - size * clippedTop;
  1097. }
  1098. }
  1099. // Determine left-most x coordinate and largest width out of lines that have not been clipped.
  1100. for (int i = clippedTop; i < (int)lines.size() - clippedBottom; ++i)
  1101. {
  1102. if (lines[i].x < x)
  1103. {
  1104. x = lines[i].x;
  1105. }
  1106. if (lines[i].y > width)
  1107. {
  1108. width = lines[i].y;
  1109. }
  1110. }
  1111. if (!ignoreClip)
  1112. {
  1113. // Guarantee that the output rect will fit within the clip.
  1114. out->x = (x >= clip.x)? x : clip.x;
  1115. out->y = (y >= clip.y)? y : clip.y;
  1116. out->width = (width <= clip.width)? width : clip.width;
  1117. out->height = (height <= viewportHeight)? height : viewportHeight;
  1118. }
  1119. else
  1120. {
  1121. out->x = x;
  1122. out->y = y;
  1123. out->width = width;
  1124. out->height = height;
  1125. }
  1126. }
  1127. void Font::getMeasurementInfo(const char* text, const Rectangle& area, unsigned int size, Justify justify, bool wrap, bool rightToLeft,
  1128. std::vector<int>* xPositions, int* yPosition, std::vector<unsigned int>* lineLengths)
  1129. {
  1130. GP_ASSERT(_size);
  1131. GP_ASSERT(text);
  1132. GP_ASSERT(yPosition);
  1133. if (size == 0)
  1134. size = _size;
  1135. float scale = (float)size / _size;
  1136. Justify vAlign = static_cast<Justify>(justify & 0xF0);
  1137. if (vAlign == 0)
  1138. {
  1139. vAlign = ALIGN_TOP;
  1140. }
  1141. Justify hAlign = static_cast<Justify>(justify & 0x0F);
  1142. if (hAlign == 0)
  1143. {
  1144. hAlign = ALIGN_LEFT;
  1145. }
  1146. const char* token = text;
  1147. const float areaHeight = area.height - size;
  1148. // For alignments other than top-left, need to calculate the y position to begin drawing from
  1149. // and the starting x position of each line. For right-to-left text, need to determine
  1150. // the number of characters on each line.
  1151. if (vAlign != ALIGN_TOP || hAlign != ALIGN_LEFT || rightToLeft)
  1152. {
  1153. int lineWidth = 0;
  1154. int delimWidth = 0;
  1155. if (wrap)
  1156. {
  1157. // Go a word at a time.
  1158. bool reachedEOF = false;
  1159. unsigned int lineLength = 0;
  1160. while (token[0] != 0)
  1161. {
  1162. unsigned int tokenWidth = 0;
  1163. // Handle delimiters until next token.
  1164. char delimiter = token[0];
  1165. while (delimiter == ' ' ||
  1166. delimiter == '\t' ||
  1167. delimiter == '\r' ||
  1168. delimiter == '\n' ||
  1169. delimiter == 0)
  1170. {
  1171. switch (delimiter)
  1172. {
  1173. case ' ':
  1174. delimWidth += size >> 1;
  1175. lineLength++;
  1176. break;
  1177. case '\r':
  1178. case '\n':
  1179. *yPosition += size;
  1180. if (lineWidth > 0)
  1181. {
  1182. addLineInfo(area, lineWidth, lineLength, hAlign, xPositions, lineLengths, rightToLeft);
  1183. }
  1184. lineWidth = 0;
  1185. lineLength = 0;
  1186. delimWidth = 0;
  1187. break;
  1188. case '\t':
  1189. delimWidth += (size >> 1)*4;
  1190. lineLength++;
  1191. break;
  1192. case 0:
  1193. reachedEOF = true;
  1194. break;
  1195. }
  1196. if (reachedEOF)
  1197. {
  1198. break;
  1199. }
  1200. token++;
  1201. delimiter = token[0];
  1202. }
  1203. if (reachedEOF || token == NULL)
  1204. {
  1205. break;
  1206. }
  1207. unsigned int tokenLength = (unsigned int)strcspn(token, " \r\n\t");
  1208. tokenWidth += getTokenWidth(token, tokenLength, size, scale);
  1209. // Wrap if necessary.
  1210. if (lineWidth + tokenWidth + delimWidth > area.width)
  1211. {
  1212. *yPosition += size;
  1213. // Push position of current line.
  1214. if (lineLength)
  1215. {
  1216. addLineInfo(area, lineWidth, lineLength-1, hAlign, xPositions, lineLengths, rightToLeft);
  1217. }
  1218. else
  1219. {
  1220. addLineInfo(area, lineWidth, tokenLength, hAlign, xPositions, lineLengths, rightToLeft);
  1221. }
  1222. // Move token to the next line.
  1223. lineWidth = 0;
  1224. lineLength = 0;
  1225. delimWidth = 0;
  1226. }
  1227. else
  1228. {
  1229. lineWidth += delimWidth;
  1230. delimWidth = 0;
  1231. }
  1232. lineWidth += tokenWidth;
  1233. lineLength += tokenLength;
  1234. token += tokenLength;
  1235. }
  1236. // Final calculation of vertical position.
  1237. int textHeight = *yPosition - area.y;
  1238. int vWhiteSpace = areaHeight - textHeight;
  1239. if (vAlign == ALIGN_VCENTER)
  1240. {
  1241. *yPosition = area.y + vWhiteSpace / 2;
  1242. }
  1243. else if (vAlign == ALIGN_BOTTOM)
  1244. {
  1245. *yPosition = area.y + vWhiteSpace;
  1246. }
  1247. // Calculation of final horizontal position.
  1248. addLineInfo(area, lineWidth, lineLength, hAlign, xPositions, lineLengths, rightToLeft);
  1249. }
  1250. else
  1251. {
  1252. // Go a line at a time.
  1253. while (token[0] != 0)
  1254. {
  1255. char delimiter = token[0];
  1256. while (delimiter == '\n')
  1257. {
  1258. *yPosition += size;
  1259. ++token;
  1260. delimiter = token[0];
  1261. }
  1262. unsigned int tokenLength = (unsigned int)strcspn(token, "\n");
  1263. if (tokenLength == 0)
  1264. {
  1265. tokenLength = (unsigned int)strlen(token);
  1266. }
  1267. int lineWidth = getTokenWidth(token, tokenLength, size, scale);
  1268. addLineInfo(area, lineWidth, tokenLength, hAlign, xPositions, lineLengths, rightToLeft);
  1269. token += tokenLength;
  1270. }
  1271. int textHeight = *yPosition - area.y;
  1272. int vWhiteSpace = areaHeight - textHeight;
  1273. if (vAlign == ALIGN_VCENTER)
  1274. {
  1275. *yPosition = area.y + vWhiteSpace / 2;
  1276. }
  1277. else if (vAlign == ALIGN_BOTTOM)
  1278. {
  1279. *yPosition = area.y + vWhiteSpace;
  1280. }
  1281. }
  1282. if (vAlign == ALIGN_TOP)
  1283. {
  1284. *yPosition = area.y;
  1285. }
  1286. }
  1287. }
  1288. float Font::getCharacterSpacing() const
  1289. {
  1290. return _spacing;
  1291. }
  1292. void Font::setCharacterSpacing(float spacing)
  1293. {
  1294. _spacing = spacing;
  1295. }
  1296. int Font::getIndexAtLocation(const char* text, const Rectangle& area, unsigned int size, const Vector2& inLocation, Vector2* outLocation,
  1297. Justify justify, bool wrap, bool rightToLeft)
  1298. {
  1299. return getIndexOrLocation(text, area, size, inLocation, outLocation, -1, justify, wrap, rightToLeft);
  1300. }
  1301. void Font::getLocationAtIndex(const char* text, const Rectangle& clip, unsigned int size, Vector2* outLocation, const unsigned int destIndex,
  1302. Justify justify, bool wrap, bool rightToLeft)
  1303. {
  1304. getIndexOrLocation(text, clip, size, *outLocation, outLocation, (const int)destIndex, justify, wrap, rightToLeft);
  1305. }
  1306. int Font::getIndexOrLocation(const char* text, const Rectangle& area, unsigned int size, const Vector2& inLocation, Vector2* outLocation,
  1307. const int destIndex, Justify justify, bool wrap, bool rightToLeft)
  1308. {
  1309. GP_ASSERT(_size);
  1310. GP_ASSERT(text);
  1311. GP_ASSERT(outLocation);
  1312. if (size == 0)
  1313. {
  1314. size = _size;
  1315. }
  1316. else
  1317. {
  1318. // Delegate to closest sized font
  1319. Font* f = findClosestSize(size);
  1320. if (f != this)
  1321. {
  1322. return f->getIndexOrLocation(text, area, size, inLocation, outLocation, destIndex, justify, wrap, rightToLeft);
  1323. }
  1324. }
  1325. unsigned int charIndex = 0;
  1326. // Essentially need to measure text until we reach inLocation.
  1327. float scale = (float)size / _size;
  1328. int spacing = (int)(size * _spacing);
  1329. int yPos = area.y;
  1330. const float areaHeight = area.height - size;
  1331. std::vector<int> xPositions;
  1332. std::vector<unsigned int> lineLengths;
  1333. getMeasurementInfo(text, area, size, justify, wrap, rightToLeft, &xPositions, &yPos, &lineLengths);
  1334. int xPos = area.x;
  1335. std::vector<int>::const_iterator xPositionsIt = xPositions.begin();
  1336. if (xPositionsIt != xPositions.end())
  1337. {
  1338. xPos = *xPositionsIt++;
  1339. }
  1340. const char* token = text;
  1341. int iteration = 1;
  1342. unsigned int lineLength;
  1343. unsigned int currentLineLength = 0;
  1344. const char* lineStart;
  1345. std::vector<unsigned int>::const_iterator lineLengthsIt;
  1346. if (rightToLeft)
  1347. {
  1348. lineStart = token;
  1349. lineLengthsIt = lineLengths.begin();
  1350. lineLength = *lineLengthsIt++;
  1351. token += lineLength - 1;
  1352. iteration = -1;
  1353. }
  1354. while (token[0] != 0)
  1355. {
  1356. // Handle delimiters until next token.
  1357. unsigned int delimLength = 0;
  1358. int result;
  1359. if (destIndex == -1)
  1360. {
  1361. result = handleDelimiters(&token, size, iteration, area.x, &xPos, &yPos, &delimLength, &xPositionsIt, xPositions.end(), &charIndex, &inLocation);
  1362. }
  1363. else
  1364. {
  1365. result = handleDelimiters(&token, size, iteration, area.x, &xPos, &yPos, &delimLength, &xPositionsIt, xPositions.end(), &charIndex, NULL, charIndex, destIndex);
  1366. }
  1367. currentLineLength += delimLength;
  1368. if (result == 0 || result == 2)
  1369. {
  1370. outLocation->x = xPos;
  1371. outLocation->y = yPos;
  1372. return charIndex;
  1373. }
  1374. if (destIndex == (int)charIndex ||
  1375. (destIndex == -1 &&
  1376. inLocation.x >= xPos && inLocation.x < xPos + spacing &&
  1377. inLocation.y >= yPos && inLocation.y < yPos + size))
  1378. {
  1379. outLocation->x = xPos;
  1380. outLocation->y = yPos;
  1381. return charIndex;
  1382. }
  1383. bool truncated = false;
  1384. unsigned int tokenLength;
  1385. unsigned int tokenWidth;
  1386. unsigned int startIndex;
  1387. if (rightToLeft)
  1388. {
  1389. tokenLength = getReversedTokenLength(token, text);
  1390. currentLineLength += tokenLength;
  1391. charIndex += tokenLength;
  1392. token -= (tokenLength - 1);
  1393. tokenWidth = getTokenWidth(token, tokenLength, size, scale);
  1394. iteration = -1;
  1395. startIndex = tokenLength - 1;
  1396. }
  1397. else
  1398. {
  1399. tokenLength = (unsigned int)strcspn(token, " \r\n\t");
  1400. tokenWidth = getTokenWidth(token, tokenLength, size, scale);
  1401. iteration = 1;
  1402. startIndex = 0;
  1403. }
  1404. // Wrap if necessary.
  1405. if (wrap && (xPos + (int)tokenWidth > area.x + area.width || (rightToLeft && currentLineLength > lineLength)))
  1406. {
  1407. yPos += size;
  1408. currentLineLength = tokenLength;
  1409. if (xPositionsIt != xPositions.end())
  1410. {
  1411. xPos = *xPositionsIt++;
  1412. }
  1413. else
  1414. {
  1415. xPos = area.x;
  1416. }
  1417. }
  1418. if (yPos > area.y + areaHeight)
  1419. {
  1420. // Truncate below area's vertical limit.
  1421. break;
  1422. }
  1423. GP_ASSERT(_glyphs);
  1424. for (int i = startIndex; i < (int)tokenLength && i >= 0; i += iteration)
  1425. {
  1426. char c = token[i];
  1427. int glyphIndex = c - 32; // HACK for ASCII
  1428. if (glyphIndex >= 0 && glyphIndex < (int)_glyphCount)
  1429. {
  1430. Glyph& g = _glyphs[glyphIndex];
  1431. if (xPos + (int)(g.width*scale) > area.x + area.width)
  1432. {
  1433. // Truncate this line and go on to the next one.
  1434. truncated = true;
  1435. break;
  1436. }
  1437. // Check against inLocation.
  1438. if (destIndex == (int)charIndex ||
  1439. (destIndex == -1 &&
  1440. inLocation.x >= xPos && inLocation.x < floor(xPos + g.width*scale + spacing) &&
  1441. inLocation.y >= yPos && inLocation.y < yPos + size))
  1442. {
  1443. outLocation->x = xPos;
  1444. outLocation->y = yPos;
  1445. return charIndex;
  1446. }
  1447. xPos += floor(g.width*scale + spacing);
  1448. charIndex++;
  1449. }
  1450. }
  1451. if (!truncated)
  1452. {
  1453. if (rightToLeft)
  1454. {
  1455. if (token == lineStart)
  1456. {
  1457. token += lineLength;
  1458. // Now handle delimiters going forwards.
  1459. if (!handleDelimiters(&token, size, 1, area.x, &xPos, &yPos, &currentLineLength, &xPositionsIt, xPositions.end()))
  1460. {
  1461. break;
  1462. }
  1463. charIndex += currentLineLength;
  1464. if (lineLengthsIt != lineLengths.end())
  1465. {
  1466. lineLength = *lineLengthsIt++;
  1467. }
  1468. lineStart = token;
  1469. token += lineLength-1;
  1470. charIndex += tokenLength;
  1471. }
  1472. else
  1473. {
  1474. token--;
  1475. }
  1476. }
  1477. else
  1478. {
  1479. token += tokenLength;
  1480. }
  1481. }
  1482. else
  1483. {
  1484. if (rightToLeft)
  1485. {
  1486. token = lineStart + lineLength;
  1487. if (!handleDelimiters(&token, size, 1, area.x, &xPos, &yPos, &currentLineLength, &xPositionsIt, xPositions.end()))
  1488. {
  1489. break;
  1490. }
  1491. if (lineLengthsIt != lineLengths.end())
  1492. {
  1493. lineLength = *lineLengthsIt++;
  1494. }
  1495. lineStart = token;
  1496. token += lineLength-1;
  1497. }
  1498. else
  1499. {
  1500. // Skip the rest of this line.
  1501. unsigned int tokenLength = (unsigned int)strcspn(token, "\n");
  1502. if (tokenLength > 0)
  1503. {
  1504. // Get first token of next line.
  1505. token += tokenLength;
  1506. charIndex += tokenLength;
  1507. }
  1508. }
  1509. }
  1510. }
  1511. if (destIndex == (int)charIndex ||
  1512. (destIndex == -1 &&
  1513. inLocation.x >= xPos && inLocation.x < xPos + spacing &&
  1514. inLocation.y >= yPos && inLocation.y < yPos + size))
  1515. {
  1516. outLocation->x = xPos;
  1517. outLocation->y = yPos;
  1518. return charIndex;
  1519. }
  1520. return -1;
  1521. }
  1522. unsigned int Font::getTokenWidth(const char* token, unsigned int length, unsigned int size, float scale)
  1523. {
  1524. GP_ASSERT(token);
  1525. GP_ASSERT(_glyphs);
  1526. if (size == 0)
  1527. size = _size;
  1528. int spacing = (int)(size * _spacing);
  1529. // Calculate width of word or line.
  1530. unsigned int tokenWidth = 0;
  1531. for (unsigned int i = 0; i < length; ++i)
  1532. {
  1533. char c = token[i];
  1534. switch (c)
  1535. {
  1536. case ' ':
  1537. tokenWidth += size >> 1;
  1538. break;
  1539. case '\t':
  1540. tokenWidth += (size >> 1)*4;
  1541. break;
  1542. default:
  1543. int glyphIndex = c - 32;
  1544. if (glyphIndex >= 0 && glyphIndex < (int)_glyphCount)
  1545. {
  1546. Glyph& g = _glyphs[glyphIndex];
  1547. tokenWidth += floor(g.width * scale + spacing);
  1548. }
  1549. break;
  1550. }
  1551. }
  1552. return tokenWidth;
  1553. }
  1554. unsigned int Font::getReversedTokenLength(const char* token, const char* bufStart)
  1555. {
  1556. GP_ASSERT(token);
  1557. GP_ASSERT(bufStart);
  1558. const char* cursor = token;
  1559. char c = cursor[0];
  1560. unsigned int length = 0;
  1561. while (cursor != bufStart && c != ' ' && c != '\r' && c != '\n' && c != '\t')
  1562. {
  1563. length++;
  1564. cursor--;
  1565. c = cursor[0];
  1566. }
  1567. if (cursor == bufStart)
  1568. {
  1569. length++;
  1570. }
  1571. return length;
  1572. }
  1573. int Font::handleDelimiters(const char** token, const unsigned int size, const int iteration, const int areaX, int* xPos, int* yPos, unsigned int* lineLength,
  1574. std::vector<int>::const_iterator* xPositionsIt, std::vector<int>::const_iterator xPositionsEnd, unsigned int* charIndex,
  1575. const Vector2* stopAtPosition, const int currentIndex, const int destIndex)
  1576. {
  1577. GP_ASSERT(token);
  1578. GP_ASSERT(*token);
  1579. GP_ASSERT(xPos);
  1580. GP_ASSERT(yPos);
  1581. GP_ASSERT(lineLength);
  1582. GP_ASSERT(xPositionsIt);
  1583. char delimiter = *token[0];
  1584. bool nextLine = true;
  1585. while (delimiter == ' ' ||
  1586. delimiter == '\t' ||
  1587. delimiter == '\r' ||
  1588. delimiter == '\n' ||
  1589. delimiter == 0)
  1590. {
  1591. if ((stopAtPosition &&
  1592. stopAtPosition->x >= *xPos && stopAtPosition->x < *xPos + ((int)size >> 1) &&
  1593. stopAtPosition->y >= *yPos && stopAtPosition->y < *yPos + (int)size) ||
  1594. (currentIndex >= 0 && destIndex >= 0 && currentIndex + (int)*lineLength == destIndex))
  1595. {
  1596. // Success + stopAtPosition was reached.
  1597. return 2;
  1598. }
  1599. switch (delimiter)
  1600. {
  1601. case ' ':
  1602. *xPos += size >> 1;
  1603. (*lineLength)++;
  1604. if (charIndex)
  1605. {
  1606. (*charIndex)++;
  1607. }
  1608. break;
  1609. case '\r':
  1610. case '\n':
  1611. *yPos += size;
  1612. // Only use next xPos for first newline character (in case of multiple consecutive newlines).
  1613. if (nextLine)
  1614. {
  1615. if (*xPositionsIt != xPositionsEnd)
  1616. {
  1617. *xPos = **xPositionsIt;
  1618. (*xPositionsIt)++;
  1619. }
  1620. else
  1621. {
  1622. *xPos = areaX;
  1623. }
  1624. nextLine = false;
  1625. *lineLength = 0;
  1626. if (charIndex)
  1627. {
  1628. (*charIndex)++;
  1629. }
  1630. }
  1631. break;
  1632. case '\t':
  1633. *xPos += (size >> 1)*4;
  1634. (*lineLength)++;
  1635. if (charIndex)
  1636. {
  1637. (*charIndex)++;
  1638. }
  1639. break;
  1640. case 0:
  1641. // EOF reached.
  1642. return 0;
  1643. }
  1644. *token += iteration;
  1645. delimiter = *token[0];
  1646. }
  1647. // Success.
  1648. return 1;
  1649. }
  1650. void Font::addLineInfo(const Rectangle& area, int lineWidth, int lineLength, Justify hAlign,
  1651. std::vector<int>* xPositions, std::vector<unsigned int>* lineLengths, bool rightToLeft)
  1652. {
  1653. int hWhitespace = area.width - lineWidth;
  1654. if (hAlign == ALIGN_HCENTER)
  1655. {
  1656. GP_ASSERT(xPositions);
  1657. (*xPositions).push_back(area.x + hWhitespace / 2);
  1658. }
  1659. else if (hAlign == ALIGN_RIGHT)
  1660. {
  1661. GP_ASSERT(xPositions);
  1662. (*xPositions).push_back(area.x + hWhitespace);
  1663. }
  1664. if (rightToLeft)
  1665. {
  1666. GP_ASSERT(lineLengths);
  1667. (*lineLengths).push_back(lineLength);
  1668. }
  1669. }
  1670. SpriteBatch* Font::getSpriteBatch(unsigned int size) const
  1671. {
  1672. if (size == 0)
  1673. return _batch;
  1674. // Find the closest sized child font
  1675. return const_cast<Font*>(this)->findClosestSize(size)->_batch;
  1676. }
  1677. Font::Justify Font::getJustify(const char* justify)
  1678. {
  1679. if (!justify)
  1680. {
  1681. return Font::ALIGN_TOP_LEFT;
  1682. }
  1683. if (strcmp(justify, "ALIGN_LEFT") == 0)
  1684. {
  1685. return Font::ALIGN_LEFT;
  1686. }
  1687. else if (strcmp(justify, "ALIGN_HCENTER") == 0)
  1688. {
  1689. return Font::ALIGN_HCENTER;
  1690. }
  1691. else if (strcmp(justify, "ALIGN_RIGHT") == 0)
  1692. {
  1693. return Font::ALIGN_RIGHT;
  1694. }
  1695. else if (strcmp(justify, "ALIGN_TOP") == 0)
  1696. {
  1697. return Font::ALIGN_TOP;
  1698. }
  1699. else if (strcmp(justify, "ALIGN_VCENTER") == 0)
  1700. {
  1701. return Font::ALIGN_VCENTER;
  1702. }
  1703. else if (strcmp(justify, "ALIGN_BOTTOM") == 0)
  1704. {
  1705. return Font::ALIGN_BOTTOM;
  1706. }
  1707. else if (strcmp(justify, "ALIGN_TOP_LEFT") == 0)
  1708. {
  1709. return Font::ALIGN_TOP_LEFT;
  1710. }
  1711. else if (strcmp(justify, "ALIGN_VCENTER_LEFT") == 0)
  1712. {
  1713. return Font::ALIGN_VCENTER_LEFT;
  1714. }
  1715. else if (strcmp(justify, "ALIGN_BOTTOM_LEFT") == 0)
  1716. {
  1717. return Font::ALIGN_BOTTOM_LEFT;
  1718. }
  1719. else if (strcmp(justify, "ALIGN_TOP_HCENTER") == 0)
  1720. {
  1721. return Font::ALIGN_TOP_HCENTER;
  1722. }
  1723. else if (strcmp(justify, "ALIGN_VCENTER_HCENTER") == 0)
  1724. {
  1725. return Font::ALIGN_VCENTER_HCENTER;
  1726. }
  1727. else if (strcmp(justify, "ALIGN_BOTTOM_HCENTER") == 0)
  1728. {
  1729. return Font::ALIGN_BOTTOM_HCENTER;
  1730. }
  1731. else if (strcmp(justify, "ALIGN_TOP_RIGHT") == 0)
  1732. {
  1733. return Font::ALIGN_TOP_RIGHT;
  1734. }
  1735. else if (strcmp(justify, "ALIGN_VCENTER_RIGHT") == 0)
  1736. {
  1737. return Font::ALIGN_VCENTER_RIGHT;
  1738. }
  1739. else if (strcmp(justify, "ALIGN_BOTTOM_RIGHT") == 0)
  1740. {
  1741. return Font::ALIGN_BOTTOM_RIGHT;
  1742. }
  1743. else
  1744. {
  1745. GP_ERROR("Failed to get corresponding font justification for unsupported value '%s'.", justify);
  1746. }
  1747. // Default.
  1748. return Font::ALIGN_TOP_LEFT;
  1749. }
  1750. Font::Text::Text(const char* text) : _text(text ? text : ""), _vertexCount(0), _vertices(NULL), _indexCount(0), _indices(NULL), _font(NULL)
  1751. {
  1752. const size_t length = strlen(text);
  1753. _vertices = new SpriteBatch::SpriteVertex[length * 4];
  1754. _indices = new unsigned short[((length - 1) * 6) + 4];
  1755. }
  1756. Font::Text::~Text()
  1757. {
  1758. SAFE_DELETE_ARRAY(_vertices);
  1759. SAFE_DELETE_ARRAY(_indices);
  1760. SAFE_RELEASE(_font);
  1761. }
  1762. const char* Font::Text::getText()
  1763. {
  1764. return _text.c_str();
  1765. }
  1766. }