BsTextData.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #pragma once
  4. #include "BsCorePrerequisites.h"
  5. #include "Text/BsFontDesc.h"
  6. #include "Math/BsVector2I.h"
  7. namespace bs
  8. {
  9. /** @addtogroup Implementation
  10. * @{
  11. */
  12. /**
  13. * This object takes as input a string, a font and optionally some constraints (like word wrap) and outputs a set of
  14. * character data you may use for rendering or metrics.
  15. */
  16. class TextDataBase
  17. {
  18. protected:
  19. /**
  20. * Represents a single word as a set of characters, or optionally just a blank space of a certain length.
  21. *
  22. * @note Due to the way allocation is handled, this class is not allowed to have a destructor.
  23. */
  24. class TextWord
  25. {
  26. public:
  27. /**
  28. * Initializes the word and signals if it just a space (or multiple spaces), or an actual word with letters.
  29. */
  30. void init(bool spacer);
  31. /**
  32. * Appends a new character to the word.
  33. *
  34. * @param[in] charIdx Sequential index of the character in the original string.
  35. * @param[in] desc Character description from the font.
  36. * @return How many pixels did the added character expand the word by.
  37. */
  38. UINT32 addChar(UINT32 charIdx, const CharDesc& desc);
  39. /** Adds a space to the word. Word must have previously have been declared as a "spacer". */
  40. void addSpace(UINT32 spaceWidth);
  41. /** Returns the width of the word in pixels. */
  42. UINT32 getWidth() const { return mWidth; }
  43. /** Returns height of the word in pixels. */
  44. UINT32 getHeight() const { return mHeight; }
  45. /**
  46. * Calculates new width of the word if we were to add the provided character, without actually adding it.
  47. *
  48. * @param[in] desc Character description from the font.
  49. * @return Width of the word in pixels with the character appended to it.
  50. */
  51. UINT32 calcWidthWithChar(const CharDesc& desc);
  52. /**
  53. * Returns true if word is a spacer. Spacers contain just a space of a certain length with no actual characters.
  54. */
  55. bool isSpacer() const { return mSpacer; }
  56. /** Returns the number of characters in the word. */
  57. UINT32 getNumChars() const { return mLastChar == nullptr ? 0 : (mCharsEnd - mCharsStart + 1); }
  58. /** Returns the index of the starting character in the word. */
  59. UINT32 getCharsStart() const { return mCharsStart; }
  60. /** Returns the index of the last character in the word. */
  61. UINT32 getCharsEnd() const { return mCharsEnd; }
  62. /**
  63. * Calculates width of the character by which it would expand the width of the word if it was added to it.
  64. *
  65. * @param[in] prevDesc Descriptor of the character preceding the one we need the width for. Can be null.
  66. * @param[in] desc Character description from the font.
  67. * @return How many pixels would the added character expand the word by.
  68. */
  69. static UINT32 calcCharWidth(const CharDesc* prevDesc, const CharDesc& desc);
  70. private:
  71. UINT32 mCharsStart, mCharsEnd;
  72. UINT32 mWidth;
  73. UINT32 mHeight;
  74. const CharDesc* mLastChar;
  75. bool mSpacer;
  76. UINT32 mSpaceWidth;
  77. };
  78. /**
  79. * Contains information about a single texture page that contains rendered character data.
  80. *
  81. * @note Due to the way allocation is handled, this class is not allowed to have a destructor.
  82. */
  83. struct PageInfo
  84. {
  85. UINT32 numQuads;
  86. HTexture texture;
  87. };
  88. public:
  89. /**
  90. * Represents a single line as a set of words.
  91. *
  92. * @note Due to the way allocation is handled, this class is not allowed to have a destructor.
  93. */
  94. class BS_CORE_EXPORT TextLine
  95. {
  96. public:
  97. /** Returns width of the line in pixels. */
  98. UINT32 getWidth() const { return mWidth; }
  99. /** Returns height of the line in pixels. */
  100. UINT32 getHeight() const { return mHeight; }
  101. /** Returns an offset used to separate two lines. */
  102. UINT32 getYOffset() const { return mTextData->getLineHeight(); }
  103. /**
  104. * Calculates new width of the line if we were to add the provided character, without actually adding it.
  105. *
  106. * @param[in] desc Character description from the font.
  107. * @return Width of the line in pixels with the character appended to it.
  108. */
  109. UINT32 calcWidthWithChar(const CharDesc& desc);
  110. /**
  111. * Fills the vertex/uv/index buffers for the specified page, with all the character data needed for rendering.
  112. *
  113. * @param[in] page The page.
  114. * @param[out] vertices Pre-allocated array where character vertices will be written.
  115. * @param[out] uvs Pre-allocated array where character uv coordinates will be written.
  116. * @param[out] indexes Pre-allocated array where character indices will be written.
  117. * @param[in] offset Offsets the location at which the method writes to the buffers. Counted as number
  118. * of quads.
  119. * @param[in] size Total number of quads that can fit into the specified buffers.
  120. * @return Number of quads that were written.
  121. */
  122. UINT32 fillBuffer(UINT32 page, Vector2* vertices, Vector2* uvs, UINT32* indexes, UINT32 offset, UINT32 size) const;
  123. /** Checks are we at a word boundary (meaning the next added character will start a new word). */
  124. bool isAtWordBoundary() const;
  125. /** Returns the total number of characters on this line. */
  126. UINT32 getNumChars() const;
  127. /**
  128. * Query if this line was created explicitly due to a newline character. As opposed to a line that was created
  129. * because a word couldn't fit on the previous line.
  130. */
  131. bool hasNewlineChar() const { return mHasNewline; }
  132. private:
  133. friend class TextDataBase;
  134. /**
  135. * Appends a new character to the line.
  136. *
  137. * @param[in] charIdx Sequential index of the character in the original string.
  138. * @param[in] desc Character description from the font.
  139. */
  140. void add(UINT32 charIdx, const CharDesc& charDesc);
  141. /** Appends a space to the line. */
  142. void addSpace(UINT32 spaceWidth);
  143. /**
  144. * Adds a new word to the line.
  145. *
  146. * @param[in] wordIdx Sequential index of the word in the original string. Spaces are counted as words as
  147. * well.
  148. * @param[in] word Description of the word.
  149. */
  150. void addWord(UINT32 wordIdx, const TextWord& word);
  151. /** Initializes the line. Must be called after construction. */
  152. void init(TextDataBase* textData);
  153. /**
  154. * Finalizes the line. Do not add new characters/words after a line has been finalized.
  155. *
  156. * @param[in] hasNewlineChar Set to true if line was create due to an explicit newline char. As opposed to a
  157. * line that was created because a word couldn't fit on the previous line.
  158. */
  159. void finalize(bool hasNewlineChar);
  160. /** Returns true if the line contains no words. */
  161. bool isEmpty() const { return mIsEmpty; }
  162. /** Removes last word from the line and returns its sequential index. */
  163. UINT32 removeLastWord();
  164. /** Calculates the line width and height in pixels. */
  165. void calculateBounds();
  166. private:
  167. TextDataBase* mTextData;
  168. UINT32 mWordsStart, mWordsEnd;
  169. UINT32 mWidth;
  170. UINT32 mHeight;
  171. bool mIsEmpty;
  172. bool mHasNewline;
  173. };
  174. public:
  175. /**
  176. * Initializes a new text data using the specified string and font. Text will attempt to fit into the provided area.
  177. * If enabled it will wrap words to new line when they don't fit. Individual words will be broken into multiple
  178. * pieces if they don't fit on a single line when word break is enabled, otherwise they will be clipped. If the
  179. * specified area is zero size then the text will not be clipped or word wrapped in any way.
  180. *
  181. * After this object is constructed you may call various getter methods to get needed information.
  182. */
  183. BS_CORE_EXPORT TextDataBase(const WString& text, const HFont& font, UINT32 fontSize,
  184. UINT32 width = 0, UINT32 height = 0, bool wordWrap = false, bool wordBreak = true);
  185. BS_CORE_EXPORT virtual ~TextDataBase() { }
  186. /** Returns the number of lines that were generated. */
  187. BS_CORE_EXPORT UINT32 getNumLines() const { return mNumLines; }
  188. /** Returns the number of font pages references by the used characters. */
  189. BS_CORE_EXPORT UINT32 getNumPages() const { return mNumPageInfos; }
  190. /** Returns the height of a line in pixels. */
  191. BS_CORE_EXPORT UINT32 getLineHeight() const;
  192. /** Gets information describing a single line at the specified index. */
  193. BS_CORE_EXPORT const TextLine& getLine(UINT32 idx) const { return mLines[idx]; }
  194. /** Returns font texture for the provided page index. */
  195. BS_CORE_EXPORT const HTexture& getTextureForPage(UINT32 page) const;
  196. /** Returns the number of quads used by all the characters in the provided page. */
  197. BS_CORE_EXPORT UINT32 getNumQuadsForPage(UINT32 page) const { return mPageInfos[page].numQuads; }
  198. /** Returns the width of the actual text in pixels. */
  199. BS_CORE_EXPORT UINT32 getWidth() const;
  200. /** Returns the height of the actual text in pixels. */
  201. BS_CORE_EXPORT UINT32 getHeight() const;
  202. protected:
  203. /**
  204. * Copies internally stored data in temporary buffers to a persistent buffer.
  205. *
  206. * @param[in] text Text originally used for creating the internal temporary buffer data.
  207. * @param[in] buffer Memory location to copy the data to. If null then no data will be copied and the
  208. * parameter @p size will contain the required buffer size.
  209. * @param[in] size Size of the provided memory buffer, or if the buffer is null, this will contain the
  210. * required buffer size after method exists.
  211. * @param[in] freeTemporary If true the internal temporary data will be freed after copying.
  212. *
  213. * @note Must be called after text data has been constructed and is in the temporary buffers.
  214. */
  215. BS_CORE_EXPORT void generatePersistentData(const WString& text, UINT8* buffer, UINT32& size, bool freeTemporary = true);
  216. private:
  217. friend class TextLine;
  218. /** Returns Y offset that determines the line on which the characters are placed. In pixels. */
  219. INT32 getBaselineOffset() const;
  220. /** Returns the width of a single space in pixels. */
  221. UINT32 getSpaceWidth() const;
  222. /** Gets a description of a single character referenced by its sequential index based on the original string. */
  223. const CharDesc& getChar(UINT32 idx) const { return *mChars[idx]; }
  224. /** Gets a description of a single word referenced by its sequential index based on the original string. */
  225. const TextWord& getWord(UINT32 idx) const { return mWords[idx]; }
  226. protected:
  227. const CharDesc** mChars;
  228. UINT32 mNumChars;
  229. TextWord* mWords;
  230. UINT32 mNumWords;
  231. TextLine* mLines;
  232. UINT32 mNumLines;
  233. PageInfo* mPageInfos;
  234. UINT32 mNumPageInfos;
  235. HFont mFont;
  236. SPtr<const FontBitmap> mFontData;
  237. // Static buffers used to reduce runtime memory allocation
  238. protected:
  239. /** Stores per-thread memory buffers used to reduce memory allocation. */
  240. // Note: I could replace this with the global frame allocator to avoid the extra logic
  241. struct BufferData
  242. {
  243. BufferData();
  244. ~BufferData();
  245. /**
  246. * Allocates a new word and adds it to the buffer. Returns index of the word in the word buffer.
  247. *
  248. * @param[in] spacer Specify true if the word is only to contain spaces. (Spaces are considered a special
  249. * type of word).
  250. */
  251. UINT32 allocWord(bool spacer);
  252. /** Allocates a new line and adds it to the buffer. Returns index of the line in the line buffer. */
  253. UINT32 allocLine(TextDataBase* textData);
  254. /**
  255. * Increments the count of characters for the referenced page, and optionally creates page info if it doesn't
  256. * already exist.
  257. */
  258. void addCharToPage(UINT32 page, const FontBitmap& fontData);
  259. /** Resets all allocation counters, but doesn't actually release memory. */
  260. void deallocAll();
  261. TextWord* WordBuffer;
  262. UINT32 WordBufferSize;
  263. UINT32 NextFreeWord;
  264. TextLine* LineBuffer;
  265. UINT32 LineBufferSize;
  266. UINT32 NextFreeLine;
  267. PageInfo* PageBuffer;
  268. UINT32 PageBufferSize;
  269. UINT32 NextFreePageInfo;
  270. };
  271. static BS_THREADLOCAL BufferData* MemBuffer;
  272. /** Allocates an initial set of buffers that will be reused while parsing text data. */
  273. static void initAlloc();
  274. };
  275. /** @} */
  276. /** @addtogroup Text
  277. * @{
  278. */
  279. /** @copydoc TextDataBase */
  280. template<class Alloc = GenAlloc>
  281. class TextData : public TextDataBase
  282. {
  283. public:
  284. /** @copydoc TextDataBase::TextDataBase */
  285. TextData(const WString& text, const HFont& font, UINT32 fontSize,
  286. UINT32 width = 0, UINT32 height = 0, bool wordWrap = false, bool wordBreak = true)
  287. :TextDataBase(text, font, fontSize, width, height, wordWrap, wordBreak), mData(nullptr)
  288. {
  289. UINT32 totalBufferSize = 0;
  290. generatePersistentData(text, nullptr, totalBufferSize);
  291. mData = (UINT8*)bs_alloc<Alloc>(totalBufferSize);
  292. generatePersistentData(text, (UINT8*)mData, totalBufferSize);
  293. }
  294. ~TextData()
  295. {
  296. if (mData != nullptr)
  297. bs_free<Alloc>(mData);
  298. }
  299. private:
  300. UINT8* mData;
  301. };
  302. /** @} */
  303. }