Text.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. // Copyright (c) 2008-2022 the Urho3D project
  2. // License: MIT
  3. #include "../Precompiled.h"
  4. #include "../Core/Context.h"
  5. #include "../Core/Profiler.h"
  6. #include "../GraphicsAPI/Texture2D.h"
  7. #include "../IO/Log.h"
  8. #include "../Resource/Localization.h"
  9. #include "../Resource/ResourceCache.h"
  10. #include "../Resource/ResourceEvents.h"
  11. #include "../UI/Font.h"
  12. #include "../UI/FontFace.h"
  13. #include "../UI/Text.h"
  14. #include "../DebugNew.h"
  15. namespace Urho3D
  16. {
  17. const char* textEffects[] =
  18. {
  19. "None",
  20. "Shadow",
  21. "Stroke",
  22. nullptr
  23. };
  24. static const float MIN_ROW_SPACING = 0.5f;
  25. extern const char* horizontalAlignments[];
  26. extern const char* UI_CATEGORY;
  27. Text::Text(Context* context) :
  28. UISelectable(context),
  29. fontSize_(DEFAULT_FONT_SIZE),
  30. textAlignment_(HA_LEFT),
  31. rowSpacing_(1.0f),
  32. wordWrap_(false),
  33. autoLocalizable_(false),
  34. charLocationsDirty_(true),
  35. selectionStart_(0),
  36. selectionLength_(0),
  37. textEffect_(TE_NONE),
  38. shadowOffset_(IntVector2(1, 1)),
  39. strokeThickness_(1),
  40. roundStroke_(false),
  41. effectColor_(Color::BLACK),
  42. effectDepthBias_(0.0f),
  43. rowHeight_(0)
  44. {
  45. // By default Text does not derive opacity from parent elements
  46. useDerivedOpacity_ = false;
  47. }
  48. Text::~Text() = default;
  49. void Text::RegisterObject(Context* context)
  50. {
  51. context->RegisterFactory<Text>(UI_CATEGORY);
  52. URHO3D_COPY_BASE_ATTRIBUTES(UISelectable);
  53. URHO3D_UPDATE_ATTRIBUTE_DEFAULT_VALUE("Use Derived Opacity", false);
  54. URHO3D_ACCESSOR_ATTRIBUTE("Font", GetFontAttr, SetFontAttr, ResourceRef(Font::GetTypeStatic()), AM_FILE);
  55. URHO3D_ATTRIBUTE("Font Size", fontSize_, DEFAULT_FONT_SIZE, AM_FILE);
  56. URHO3D_ACCESSOR_ATTRIBUTE("Text", GetTextAttr, SetTextAttr, String::EMPTY, AM_FILE);
  57. URHO3D_ENUM_ATTRIBUTE("Text Alignment", textAlignment_, horizontalAlignments, HA_LEFT, AM_FILE);
  58. URHO3D_ATTRIBUTE("Row Spacing", rowSpacing_, 1.0f, AM_FILE);
  59. URHO3D_ATTRIBUTE("Word Wrap", wordWrap_, false, AM_FILE);
  60. URHO3D_ACCESSOR_ATTRIBUTE("Auto Localizable", GetAutoLocalizable, SetAutoLocalizable, false, AM_FILE);
  61. URHO3D_ENUM_ATTRIBUTE("Text Effect", textEffect_, textEffects, TE_NONE, AM_FILE);
  62. URHO3D_ATTRIBUTE("Shadow Offset", shadowOffset_, IntVector2(1, 1), AM_FILE);
  63. URHO3D_ATTRIBUTE("Stroke Thickness", strokeThickness_, 1, AM_FILE);
  64. URHO3D_ATTRIBUTE("Round Stroke", roundStroke_, false, AM_FILE);
  65. URHO3D_ACCESSOR_ATTRIBUTE("Effect Color", GetEffectColor, SetEffectColor, Color::BLACK, AM_FILE);
  66. // Change the default value for UseDerivedOpacity
  67. context->GetAttribute<Text>("Use Derived Opacity")->defaultValue_ = false;
  68. }
  69. void Text::ApplyAttributes()
  70. {
  71. UISelectable::ApplyAttributes();
  72. // Localize now if attributes were loaded out-of-order
  73. if (autoLocalizable_ && stringId_.Length())
  74. {
  75. auto* l10n = GetSubsystem<Localization>();
  76. text_ = l10n->Get(stringId_);
  77. }
  78. DecodeToUnicode();
  79. fontSize_ = Max(fontSize_, 1);
  80. strokeThickness_ = Abs(strokeThickness_);
  81. ValidateSelection();
  82. UpdateText();
  83. }
  84. void Text::GetBatches(Vector<UIBatch>& batches, Vector<float>& vertexData, const IntRect& currentScissor)
  85. {
  86. FontFace* face = font_ ? font_->GetFace(fontSize_) : nullptr;
  87. if (!face)
  88. {
  89. hovering_ = false;
  90. return;
  91. }
  92. // If face has changed or char locations are not valid anymore, update before rendering
  93. if (charLocationsDirty_ || !fontFace_ || face != fontFace_)
  94. UpdateCharLocations();
  95. // If face uses mutable glyphs mechanism, reacquire glyphs before rendering to make sure they are in the texture
  96. else if (face->HasMutableGlyphs())
  97. {
  98. for (i32 i = 0; i < printText_.Size(); ++i)
  99. face->GetGlyph(printText_[i]);
  100. }
  101. // Hovering and/or whole selection batch
  102. UISelectable::GetBatches(batches, vertexData, currentScissor);
  103. // Partial selection batch
  104. if (!selected_ && selectionLength_ && charLocations_.Size() >= selectionStart_ + selectionLength_ && selectionColor_.a_ > 0.0f)
  105. {
  106. UIBatch batch(this, BLEND_ALPHA, currentScissor, nullptr, &vertexData);
  107. batch.SetColor(selectionColor_);
  108. Vector2 currentStart = charLocations_[selectionStart_].position_;
  109. Vector2 currentEnd = currentStart;
  110. for (i32 i = selectionStart_; i < selectionStart_ + selectionLength_; ++i)
  111. {
  112. // Check if row changes, and start a new quad in that case
  113. if (charLocations_[i].size_ != Vector2::ZERO)
  114. {
  115. if (charLocations_[i].position_.y_ != currentStart.y_)
  116. {
  117. batch.AddQuad(currentStart.x_, currentStart.y_, currentEnd.x_ - currentStart.x_,
  118. currentEnd.y_ - currentStart.y_, 0, 0);
  119. currentStart = charLocations_[i].position_;
  120. currentEnd = currentStart + charLocations_[i].size_;
  121. }
  122. else
  123. {
  124. currentEnd.x_ += charLocations_[i].size_.x_;
  125. currentEnd.y_ = Max(currentStart.y_ + charLocations_[i].size_.y_, currentEnd.y_);
  126. }
  127. }
  128. }
  129. if (currentEnd != currentStart)
  130. {
  131. batch.AddQuad(currentStart.x_, currentStart.y_, currentEnd.x_ - currentStart.x_, currentEnd.y_ - currentStart.y_, 0, 0);
  132. }
  133. UIBatch::AddOrMerge(batch, batches);
  134. }
  135. // Text batch
  136. TextEffect textEffect = font_->IsSDFFont() ? TE_NONE : textEffect_;
  137. const Vector<SharedPtr<Texture2D>>& textures = face->GetTextures();
  138. for (i32 n = 0; n < textures.Size() && n < pageGlyphLocations_.Size(); ++n)
  139. {
  140. // One batch per texture/page
  141. UIBatch pageBatch(this, BLEND_ALPHA, currentScissor, textures[n], &vertexData);
  142. const Vector<GlyphLocation>& pageGlyphLocation = pageGlyphLocations_[n];
  143. switch (textEffect)
  144. {
  145. case TE_NONE:
  146. ConstructBatch(pageBatch, pageGlyphLocation, 0, 0);
  147. break;
  148. case TE_SHADOW:
  149. ConstructBatch(pageBatch, pageGlyphLocation, shadowOffset_.x_, shadowOffset_.y_, &effectColor_, effectDepthBias_);
  150. ConstructBatch(pageBatch, pageGlyphLocation, 0, 0);
  151. break;
  152. case TE_STROKE:
  153. if (roundStroke_)
  154. {
  155. // Samples should be even or glyph may be redrawn in wrong x y pos making stroke corners rough
  156. // Adding to thickness helps with thickness of 1 not having enought samples for this formula
  157. // or certain fonts with reflex corners requiring more glyph samples for a smooth stroke when large
  158. int thickness = Min(strokeThickness_, fontSize_);
  159. int samples = thickness * thickness + (thickness % 2 == 0 ? 4 : 3);
  160. float angle = 360.f / samples;
  161. auto floatThickness = (float)thickness;
  162. for (int i = 0; i < samples; ++i)
  163. {
  164. float x = Cos(angle * i) * floatThickness;
  165. float y = Sin(angle * i) * floatThickness;
  166. ConstructBatch(pageBatch, pageGlyphLocation, x, y, &effectColor_, effectDepthBias_);
  167. }
  168. }
  169. else
  170. {
  171. int thickness = Min(strokeThickness_, fontSize_);
  172. int x, y;
  173. for (x = -thickness; x <= thickness; ++x)
  174. {
  175. for (y = -thickness; y <= thickness; ++y)
  176. {
  177. // Don't draw glyphs that aren't on the edges
  178. if (x > -thickness && x < thickness &&
  179. y > -thickness && y < thickness)
  180. continue;
  181. ConstructBatch(pageBatch, pageGlyphLocation, x, y, &effectColor_, effectDepthBias_);
  182. }
  183. }
  184. }
  185. ConstructBatch(pageBatch, pageGlyphLocation, 0, 0);
  186. break;
  187. }
  188. UIBatch::AddOrMerge(pageBatch, batches);
  189. }
  190. }
  191. void Text::OnResize(const IntVector2& newSize, const IntVector2& delta)
  192. {
  193. if (wordWrap_)
  194. UpdateText(true);
  195. else
  196. charLocationsDirty_ = true;
  197. }
  198. void Text::OnIndentSet()
  199. {
  200. charLocationsDirty_ = true;
  201. }
  202. bool Text::SetFont(const String& fontName, float size)
  203. {
  204. auto* cache = GetSubsystem<ResourceCache>();
  205. return SetFont(cache->GetResource<Font>(fontName), size);
  206. }
  207. bool Text::SetFont(Font* font, float size)
  208. {
  209. if (!font)
  210. {
  211. URHO3D_LOGERROR("Null font for Text");
  212. return false;
  213. }
  214. if (font != font_ || size != fontSize_)
  215. {
  216. font_ = font;
  217. fontSize_ = Max(size, 1);
  218. UpdateText();
  219. }
  220. return true;
  221. }
  222. bool Text::SetFontSize(float size)
  223. {
  224. // Initial font must be set
  225. if (!font_)
  226. return false;
  227. else
  228. return SetFont(font_, size);
  229. }
  230. void Text::DecodeToUnicode()
  231. {
  232. unicodeText_.Clear();
  233. for (i32 i = 0; i < text_.Length();)
  234. unicodeText_.Push(text_.NextUTF8Char(i));
  235. }
  236. void Text::SetText(const String& text)
  237. {
  238. if (autoLocalizable_)
  239. {
  240. stringId_ = text;
  241. auto* l10n = GetSubsystem<Localization>();
  242. text_ = l10n->Get(stringId_);
  243. }
  244. else
  245. {
  246. text_ = text;
  247. }
  248. DecodeToUnicode();
  249. ValidateSelection();
  250. UpdateText();
  251. }
  252. void Text::SetTextAlignment(HorizontalAlignment align)
  253. {
  254. if (align != textAlignment_)
  255. {
  256. textAlignment_ = align;
  257. charLocationsDirty_ = true;
  258. }
  259. }
  260. void Text::SetRowSpacing(float spacing)
  261. {
  262. if (spacing != rowSpacing_)
  263. {
  264. rowSpacing_ = Max(spacing, MIN_ROW_SPACING);
  265. UpdateText();
  266. }
  267. }
  268. void Text::SetWordwrap(bool enable)
  269. {
  270. if (enable != wordWrap_)
  271. {
  272. wordWrap_ = enable;
  273. UpdateText();
  274. }
  275. }
  276. void Text::SetAutoLocalizable(bool enable)
  277. {
  278. if (enable != autoLocalizable_)
  279. {
  280. autoLocalizable_ = enable;
  281. if (enable)
  282. {
  283. stringId_ = text_;
  284. auto* l10n = GetSubsystem<Localization>();
  285. text_ = l10n->Get(stringId_);
  286. SubscribeToEvent(E_CHANGELANGUAGE, URHO3D_HANDLER(Text, HandleChangeLanguage));
  287. }
  288. else
  289. {
  290. text_ = stringId_;
  291. stringId_ = "";
  292. UnsubscribeFromEvent(E_CHANGELANGUAGE);
  293. }
  294. DecodeToUnicode();
  295. ValidateSelection();
  296. UpdateText();
  297. }
  298. }
  299. void Text::HandleChangeLanguage(StringHash eventType, VariantMap& eventData)
  300. {
  301. auto* l10n = GetSubsystem<Localization>();
  302. text_ = l10n->Get(stringId_);
  303. DecodeToUnicode();
  304. ValidateSelection();
  305. UpdateText();
  306. }
  307. void Text::SetSelection(i32 start, i32 length)
  308. {
  309. assert(start >= 0 && length >= 0);
  310. selectionStart_ = start;
  311. selectionLength_ = length;
  312. ValidateSelection();
  313. }
  314. void Text::ClearSelection()
  315. {
  316. selectionStart_ = 0;
  317. selectionLength_ = 0;
  318. }
  319. void Text::SetTextEffect(TextEffect textEffect)
  320. {
  321. textEffect_ = textEffect;
  322. }
  323. void Text::SetEffectShadowOffset(const IntVector2& offset)
  324. {
  325. shadowOffset_ = offset;
  326. }
  327. void Text::SetEffectStrokeThickness(int thickness)
  328. {
  329. strokeThickness_ = Abs(thickness);
  330. }
  331. void Text::SetEffectRoundStroke(bool roundStroke)
  332. {
  333. roundStroke_ = roundStroke;
  334. }
  335. void Text::SetEffectColor(const Color& effectColor)
  336. {
  337. effectColor_ = effectColor;
  338. }
  339. void Text::SetEffectDepthBias(float bias)
  340. {
  341. effectDepthBias_ = bias;
  342. }
  343. float Text::GetRowWidth(i32 index) const
  344. {
  345. assert(index >= 0);
  346. return index < rowWidths_.Size() ? rowWidths_[index] : 0;
  347. }
  348. Vector2 Text::GetCharPosition(i32 index)
  349. {
  350. assert(index >= 0);
  351. if (charLocationsDirty_)
  352. UpdateCharLocations();
  353. if (charLocations_.Empty())
  354. return Vector2::ZERO;
  355. // For convenience, return the position of the text ending if index exceeded
  356. if (index > charLocations_.Size() - 1)
  357. index = charLocations_.Size() - 1;
  358. return charLocations_[index].position_;
  359. }
  360. Vector2 Text::GetCharSize(i32 index)
  361. {
  362. assert(index >= 0);
  363. if (charLocationsDirty_)
  364. UpdateCharLocations();
  365. if (charLocations_.Size() < 2)
  366. return Vector2::ZERO;
  367. // For convenience, return the size of the last char if index exceeded (last size entry is zero)
  368. if (index > charLocations_.Size() - 2)
  369. index = charLocations_.Size() - 2;
  370. return charLocations_[index].size_;
  371. }
  372. void Text::SetFontAttr(const ResourceRef& value)
  373. {
  374. auto* cache = GetSubsystem<ResourceCache>();
  375. font_ = cache->GetResource<Font>(value.name_);
  376. }
  377. ResourceRef Text::GetFontAttr() const
  378. {
  379. return GetResourceRef(font_, Font::GetTypeStatic());
  380. }
  381. void Text::SetTextAttr(const String& value)
  382. {
  383. text_ = value;
  384. if (autoLocalizable_)
  385. stringId_ = value;
  386. }
  387. String Text::GetTextAttr() const
  388. {
  389. if (autoLocalizable_ && stringId_.Length())
  390. return stringId_;
  391. else
  392. return text_;
  393. }
  394. bool Text::FilterImplicitAttributes(XMLElement& dest) const
  395. {
  396. if (!UISelectable::FilterImplicitAttributes(dest))
  397. return false;
  398. if (!IsFixedWidth())
  399. {
  400. if (!RemoveChildXML(dest, "Size"))
  401. return false;
  402. if (!RemoveChildXML(dest, "Min Size"))
  403. return false;
  404. if (!RemoveChildXML(dest, "Max Size"))
  405. return false;
  406. }
  407. return true;
  408. }
  409. void Text::UpdateText(bool onResize)
  410. {
  411. rowWidths_.Clear();
  412. printText_.Clear();
  413. if (font_)
  414. {
  415. FontFace* face = font_->GetFace(fontSize_);
  416. if (!face)
  417. return;
  418. rowHeight_ = face->GetRowHeight();
  419. int width = 0;
  420. int height = 0;
  421. int rowWidth = 0;
  422. auto rowHeight = RoundToInt(rowSpacing_ * rowHeight_);
  423. // First see if the text must be split up
  424. if (!wordWrap_)
  425. {
  426. printText_ = unicodeText_;
  427. printToText_.Resize(printText_.Size());
  428. for (i32 i = 0; i < printText_.Size(); ++i)
  429. printToText_[i] = i;
  430. }
  431. else
  432. {
  433. int maxWidth = GetWidth();
  434. i32 nextBreak = 0;
  435. i32 lineStart = 0;
  436. printToText_.Clear();
  437. for (i32 i = 0; i < unicodeText_.Size(); ++i)
  438. {
  439. i32 j;
  440. u32 c = unicodeText_[i];
  441. if (c != '\n')
  442. {
  443. bool ok = true;
  444. if (nextBreak <= i)
  445. {
  446. int futureRowWidth = rowWidth;
  447. for (j = i; j < unicodeText_.Size(); ++j)
  448. {
  449. c32 d = unicodeText_[j];
  450. if (d == ' ' || d == '\n')
  451. {
  452. nextBreak = j;
  453. break;
  454. }
  455. const FontGlyph* glyph = face->GetGlyph(d);
  456. if (glyph)
  457. {
  458. futureRowWidth += glyph->advanceX_;
  459. if (j < unicodeText_.Size() - 1)
  460. futureRowWidth += face->GetKerning(d, unicodeText_[j + 1]);
  461. }
  462. if (d == '-' && futureRowWidth <= maxWidth)
  463. {
  464. nextBreak = j + 1;
  465. break;
  466. }
  467. if (futureRowWidth > maxWidth)
  468. {
  469. ok = false;
  470. break;
  471. }
  472. }
  473. }
  474. if (!ok)
  475. {
  476. // If did not find any breaks on the line, copy until j, or at least 1 char, to prevent infinite loop
  477. if (nextBreak == lineStart)
  478. {
  479. while (i < j)
  480. {
  481. printText_.Push(unicodeText_[i]);
  482. printToText_.Push(i);
  483. ++i;
  484. }
  485. }
  486. // Eliminate spaces that have been copied before the forced break
  487. while (printText_.Size() && printText_.Back() == ' ')
  488. {
  489. printText_.Pop();
  490. printToText_.Pop();
  491. }
  492. printText_.Push('\n');
  493. printToText_.Push(Min(i, unicodeText_.Size() - 1));
  494. rowWidth = 0;
  495. nextBreak = lineStart = i;
  496. }
  497. if (i < unicodeText_.Size())
  498. {
  499. // When copying a space, position is allowed to be over row width
  500. c = unicodeText_[i];
  501. const FontGlyph* glyph = face->GetGlyph(c);
  502. if (glyph)
  503. {
  504. rowWidth += glyph->advanceX_;
  505. if (i < unicodeText_.Size() - 1)
  506. rowWidth += face->GetKerning(c, unicodeText_[i + 1]);
  507. }
  508. if (rowWidth <= maxWidth)
  509. {
  510. printText_.Push(c);
  511. printToText_.Push(i);
  512. }
  513. }
  514. }
  515. else
  516. {
  517. printText_.Push('\n');
  518. printToText_.Push(Min(i, unicodeText_.Size() - 1));
  519. rowWidth = 0;
  520. nextBreak = lineStart = i;
  521. }
  522. }
  523. }
  524. rowWidth = 0;
  525. for (i32 i = 0; i < printText_.Size(); ++i)
  526. {
  527. c32 c = printText_[i];
  528. if (c != '\n')
  529. {
  530. const FontGlyph* glyph = face->GetGlyph(c);
  531. if (glyph)
  532. {
  533. rowWidth += glyph->advanceX_;
  534. if (i < printText_.Size() - 1)
  535. rowWidth += face->GetKerning(c, printText_[i + 1]);
  536. }
  537. }
  538. else
  539. {
  540. width = Max(width, rowWidth);
  541. height += rowHeight;
  542. rowWidths_.Push(rowWidth);
  543. rowWidth = 0;
  544. }
  545. }
  546. if (rowWidth)
  547. {
  548. width = Max(width, rowWidth);
  549. height += rowHeight;
  550. rowWidths_.Push(rowWidth);
  551. }
  552. // Set at least one row height even if text is empty
  553. if (!height)
  554. height = rowHeight;
  555. // Set minimum and current size according to the text size, but respect fixed width if set
  556. if (!IsFixedWidth())
  557. {
  558. if (wordWrap_)
  559. SetMinWidth(0);
  560. else
  561. {
  562. SetMinWidth(width);
  563. SetWidth(width);
  564. }
  565. }
  566. SetFixedHeight(height);
  567. charLocationsDirty_ = true;
  568. }
  569. else
  570. {
  571. // No font, nothing to render
  572. pageGlyphLocations_.Clear();
  573. }
  574. // If wordwrap is on, parent may need layout update to correct for overshoot in size. However, do not do this when the
  575. // update is a response to resize, as that could cause infinite recursion
  576. if (wordWrap_ && !onResize)
  577. {
  578. UIElement* parent = GetParent();
  579. if (parent && parent->GetLayoutMode() != LM_FREE)
  580. parent->UpdateLayout();
  581. }
  582. }
  583. void Text::UpdateCharLocations()
  584. {
  585. // Remember the font face to see if it's still valid when it's time to render
  586. FontFace* face = font_ ? font_->GetFace(fontSize_) : nullptr;
  587. if (!face)
  588. return;
  589. fontFace_ = face;
  590. auto rowHeight = RoundToInt(rowSpacing_ * rowHeight_);
  591. // Store position & size of each character, and locations per texture page
  592. i32 numChars = unicodeText_.Size();
  593. charLocations_.Resize(numChars + 1);
  594. pageGlyphLocations_.Resize(face->GetTextures().Size());
  595. for (i32 i = 0; i < pageGlyphLocations_.Size(); ++i)
  596. pageGlyphLocations_[i].Clear();
  597. IntVector2 offset = font_->GetTotalGlyphOffset(fontSize_);
  598. i32 rowIndex = 0;
  599. i32 lastFilled = 0;
  600. float x = Round(GetRowStartPosition(rowIndex) + offset.x_);
  601. float y = Round(offset.y_);
  602. for (i32 i = 0; i < printText_.Size(); ++i)
  603. {
  604. CharLocation loc;
  605. loc.position_ = Vector2(x, y);
  606. c32 c = printText_[i];
  607. if (c != '\n')
  608. {
  609. const FontGlyph* glyph = face->GetGlyph(c);
  610. loc.size_ = Vector2(glyph ? glyph->advanceX_ : 0, rowHeight_);
  611. if (glyph)
  612. {
  613. // Store glyph's location for rendering. Verify that glyph page is valid
  614. if (glyph->page_ != NINDEX && glyph->page_ < pageGlyphLocations_.Size())
  615. pageGlyphLocations_[glyph->page_].Push(GlyphLocation(x, y, glyph));
  616. x += glyph->advanceX_;
  617. if (i < printText_.Size() - 1)
  618. x += face->GetKerning(c, printText_[i + 1]);
  619. }
  620. }
  621. else
  622. {
  623. loc.size_ = Vector2::ZERO;
  624. x = GetRowStartPosition(++rowIndex);
  625. y += rowHeight;
  626. }
  627. if (lastFilled > printToText_[i])
  628. lastFilled = printToText_[i];
  629. // Fill gaps in case characters were skipped from printing
  630. for (i32 j = lastFilled; j <= printToText_[i]; ++j)
  631. charLocations_[j] = loc;
  632. lastFilled = printToText_[i] + 1;
  633. }
  634. // Store the ending position
  635. charLocations_[numChars].position_ = Vector2(x, y);
  636. charLocations_[numChars].size_ = Vector2::ZERO;
  637. charLocationsDirty_ = false;
  638. }
  639. void Text::ValidateSelection()
  640. {
  641. i32 textLength = unicodeText_.Size();
  642. if (textLength)
  643. {
  644. if (selectionStart_ >= textLength)
  645. selectionStart_ = textLength - 1;
  646. if (selectionStart_ + selectionLength_ > textLength)
  647. selectionLength_ = textLength - selectionStart_;
  648. }
  649. else
  650. {
  651. selectionStart_ = 0;
  652. selectionLength_ = 0;
  653. }
  654. }
  655. int Text::GetRowStartPosition(i32 rowIndex) const
  656. {
  657. assert(rowIndex >= 0);
  658. float rowWidth = 0;
  659. if (rowIndex < rowWidths_.Size())
  660. rowWidth = rowWidths_[rowIndex];
  661. int ret = GetIndentWidth();
  662. switch (textAlignment_)
  663. {
  664. case HA_LEFT:
  665. break;
  666. case HA_CENTER:
  667. ret += (GetSize().x_ - rowWidth) / 2;
  668. break;
  669. case HA_RIGHT:
  670. ret += GetSize().x_ - rowWidth;
  671. break;
  672. case HA_CUSTOM:
  673. break;
  674. }
  675. return ret;
  676. }
  677. void Text::ConstructBatch(UIBatch& pageBatch, const Vector<GlyphLocation>& pageGlyphLocation, float dx, float dy, Color* color,
  678. float depthBias)
  679. {
  680. i32 startDataSize = pageBatch.vertexData_->Size();
  681. if (!color)
  682. pageBatch.SetDefaultColor();
  683. else
  684. pageBatch.SetColor(*color);
  685. for (i32 i = 0; i < pageGlyphLocation.Size(); ++i)
  686. {
  687. const GlyphLocation& glyphLocation = pageGlyphLocation[i];
  688. const FontGlyph& glyph = *glyphLocation.glyph_;
  689. pageBatch.AddQuad(dx + glyphLocation.x_ + glyph.offsetX_, dy + glyphLocation.y_ + glyph.offsetY_, glyph.width_,
  690. glyph.height_, glyph.x_, glyph.y_, glyph.texWidth_, glyph.texHeight_);
  691. }
  692. if (depthBias != 0.0f)
  693. {
  694. i32 dataSize = pageBatch.vertexData_->Size();
  695. for (i32 i = startDataSize; i < dataSize; i += UI_VERTEX_SIZE)
  696. pageBatch.vertexData_->At(i + 2) += depthBias;
  697. }
  698. }
  699. }