]> git.lizzy.rs Git - dragonfireclient.git/blob - src/cguittfont/CGUITTFont.h
Add colored text (not only colored chat).
[dragonfireclient.git] / src / cguittfont / CGUITTFont.h
1 /*
2    CGUITTFont FreeType class for Irrlicht
3    Copyright (c) 2009-2010 John Norman
4    Copyright (c) 2016 NathanaĆ«l Courant
5
6    This software is provided 'as-is', without any express or implied
7    warranty. In no event will the authors be held liable for any
8    damages arising from the use of this software.
9
10    Permission is granted to anyone to use this software for any
11    purpose, including commercial applications, and to alter it and
12    redistribute it freely, subject to the following restrictions:
13
14    1. The origin of this software must not be misrepresented; you
15       must not claim that you wrote the original software. If you use
16       this software in a product, an acknowledgment in the product
17       documentation would be appreciated but is not required.
18
19    2. Altered source versions must be plainly marked as such, and
20       must not be misrepresented as being the original software.
21
22    3. This notice may not be removed or altered from any source
23       distribution.
24
25    The original version of this class can be located at:
26    http://irrlicht.suckerfreegames.com/
27
28    John Norman
29    john@suckerfreegames.com
30 */
31
32 #ifndef __C_GUI_TTFONT_H_INCLUDED__
33 #define __C_GUI_TTFONT_H_INCLUDED__
34
35 #include <irrlicht.h>
36 #include <ft2build.h>
37 #include <vector>
38 #include "util/enriched_string.h"
39 #include FT_FREETYPE_H
40
41 namespace irr
42 {
43 namespace gui
44 {
45         struct SGUITTFace;
46         class CGUITTFont;
47
48         //! Class to assist in deleting glyphs.
49         class CGUITTAssistDelete
50         {
51                 public:
52                         template <class T, typename TAlloc>
53                         static void Delete(core::array<T, TAlloc>& a)
54                         {
55                                 TAlloc allocator;
56                                 allocator.deallocate(a.pointer());
57                         }
58         };
59
60         //! Structure representing a single TrueType glyph.
61         struct SGUITTGlyph
62         {
63                 //! Constructor.
64                 SGUITTGlyph() : isLoaded(false), glyph_page(0), surface(0), parent(0) {}
65
66                 //! Destructor.
67                 ~SGUITTGlyph() { unload(); }
68
69                 //! Preload the glyph.
70                 //!     The preload process occurs when the program tries to cache the glyph from FT_Library.
71                 //! However, it simply defines the SGUITTGlyph's properties and will only create the page
72                 //! textures if necessary.  The actual creation of the textures should only occur right
73                 //! before the batch draw call.
74                 void preload(u32 char_index, FT_Face face, video::IVideoDriver* driver, u32 font_size, const FT_Int32 loadFlags);
75
76                 //! Unloads the glyph.
77                 void unload();
78
79                 //! Creates the IImage object from the FT_Bitmap.
80                 video::IImage* createGlyphImage(const FT_Bitmap& bits, video::IVideoDriver* driver) const;
81
82                 //! If true, the glyph has been loaded.
83                 bool isLoaded;
84
85                 //! The page the glyph is on.
86                 u32 glyph_page;
87
88                 //! The source rectangle for the glyph.
89                 core::recti source_rect;
90
91                 //! The offset of glyph when drawn.
92                 core::vector2di offset;
93
94                 //! Glyph advance information.
95                 FT_Vector advance;
96
97                 //! This is just the temporary image holder.  After this glyph is paged,
98                 //! it will be dropped.
99                 mutable video::IImage* surface;
100
101                 //! The pointer pointing to the parent (CGUITTFont)
102                 CGUITTFont* parent;
103         };
104
105         //! Holds a sheet of glyphs.
106         class CGUITTGlyphPage
107         {
108                 public:
109                         CGUITTGlyphPage(video::IVideoDriver* Driver, const io::path& texture_name) :texture(0), available_slots(0), used_slots(0), dirty(false), driver(Driver), name(texture_name) {}
110                         ~CGUITTGlyphPage()
111                         {
112                                 if (texture)
113                                 {
114                                         if (driver)
115                                                 driver->removeTexture(texture);
116                                         else texture->drop();
117                                 }
118                         }
119
120                         //! Create the actual page texture,
121                         bool createPageTexture(const u8& pixel_mode, const core::dimension2du& texture_size)
122                         {
123                                 if( texture )
124                                         return false;
125
126                                 bool flgmip = driver->getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS);
127                                 driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);
128
129                                 // Set the texture color format.
130                                 switch (pixel_mode)
131                                 {
132                                         case FT_PIXEL_MODE_MONO:
133                                                 texture = driver->addTexture(texture_size, name, video::ECF_A1R5G5B5);
134                                                 break;
135                                         case FT_PIXEL_MODE_GRAY:
136                                         default:
137                                                 texture = driver->addTexture(texture_size, name, video::ECF_A8R8G8B8);
138                                                 break;
139                                 }
140
141                                 // Restore our texture creation flags.
142                                 driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, flgmip);
143                                 return texture ? true : false;
144                         }
145
146                         //! Add the glyph to a list of glyphs to be paged.
147                         //! This collection will be cleared after updateTexture is called.
148                         void pushGlyphToBePaged(const SGUITTGlyph* glyph)
149                         {
150                                 glyph_to_be_paged.push_back(glyph);
151                         }
152
153                         //! Updates the texture atlas with new glyphs.
154                         void updateTexture()
155                         {
156                                 if (!dirty) return;
157
158                                 void* ptr = texture->lock();
159                                 video::ECOLOR_FORMAT format = texture->getColorFormat();
160                                 core::dimension2du size = texture->getOriginalSize();
161                                 video::IImage* pageholder = driver->createImageFromData(format, size, ptr, true, false);
162
163                                 for (u32 i = 0; i < glyph_to_be_paged.size(); ++i)
164                                 {
165                                         const SGUITTGlyph* glyph = glyph_to_be_paged[i];
166                                         if (glyph && glyph->isLoaded)
167                                         {
168                                                 if (glyph->surface)
169                                                 {
170                                                         glyph->surface->copyTo(pageholder, glyph->source_rect.UpperLeftCorner);
171                                                         glyph->surface->drop();
172                                                         glyph->surface = 0;
173                                                 }
174                                                 else
175                                                 {
176                                                         ; // TODO: add error message?
177                                                         //currently, if we failed to create the image, just ignore this operation.
178                                                 }
179                                         }
180                                 }
181
182                                 pageholder->drop();
183                                 texture->unlock();
184                                 glyph_to_be_paged.clear();
185                                 dirty = false;
186                         }
187
188                         video::ITexture* texture;
189                         u32 available_slots;
190                         u32 used_slots;
191                         bool dirty;
192
193                         core::array<core::vector2di> render_positions;
194                         core::array<core::recti> render_source_rects;
195
196                 private:
197                         core::array<const SGUITTGlyph*> glyph_to_be_paged;
198                         video::IVideoDriver* driver;
199                         io::path name;
200         };
201
202         //! Class representing a TrueType font.
203         class CGUITTFont : public IGUIFont
204         {
205                 public:
206                         //! Creates a new TrueType font and returns a pointer to it.  The pointer must be drop()'ed when finished.
207                         //! \param env The IGUIEnvironment the font loads out of.
208                         //! \param filename The filename of the font.
209                         //! \param size The size of the font glyphs in pixels.  Since this is the size of the individual glyphs, the true height of the font may change depending on the characters used.
210                         //! \param antialias set the use_monochrome (opposite to antialias) flag
211                         //! \param transparency set the use_transparency flag
212                         //! \return Returns a pointer to a CGUITTFont.  Will return 0 if the font failed to load.
213                         static CGUITTFont* createTTFont(IGUIEnvironment *env, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true, const u32 shadow = 0, const u32 shadow_alpha = 255);
214                         static CGUITTFont* createTTFont(IrrlichtDevice *device, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true);
215                         static CGUITTFont* create(IGUIEnvironment *env, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true);
216                         static CGUITTFont* create(IrrlichtDevice *device, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true);
217
218                         //! Destructor
219                         virtual ~CGUITTFont();
220
221                         //! Sets the amount of glyphs to batch load.
222                         virtual void setBatchLoadSize(u32 batch_size) { batch_load_size = batch_size; }
223
224                         //! Sets the maximum texture size for a page of glyphs.
225                         virtual void setMaxPageTextureSize(const core::dimension2du& texture_size) { max_page_texture_size = texture_size; }
226
227                         //! Get the font size.
228                         virtual u32 getFontSize() const { return size; }
229
230                         //! Check the font's transparency.
231                         virtual bool isTransparent() const { return use_transparency; }
232
233                         //! Check if the font auto-hinting is enabled.
234                         //! Auto-hinting is FreeType's built-in font hinting engine.
235                         virtual bool useAutoHinting() const { return use_auto_hinting; }
236
237                         //! Check if the font hinting is enabled.
238                         virtual bool useHinting()        const { return use_hinting; }
239
240                         //! Check if the font is being loaded as a monochrome font.
241                         //! The font can either be a 256 color grayscale font, or a 2 color monochrome font.
242                         virtual bool useMonochrome()  const { return use_monochrome; }
243
244                         //! Tells the font to allow transparency when rendering.
245                         //! Default: true.
246                         //! \param flag If true, the font draws using transparency.
247                         virtual void setTransparency(const bool flag);
248
249                         //! Tells the font to use monochrome rendering.
250                         //! Default: false.
251                         //! \param flag If true, the font draws using a monochrome image.  If false, the font uses a grayscale image.
252                         virtual void setMonochrome(const bool flag);
253
254                         //! Enables or disables font hinting.
255                         //! Default: Hinting and auto-hinting true.
256                         //! \param enable If false, font hinting is turned off. If true, font hinting is turned on.
257                         //! \param enable_auto_hinting If true, FreeType uses its own auto-hinting algorithm.  If false, it tries to use the algorithm specified by the font.
258                         virtual void setFontHinting(const bool enable, const bool enable_auto_hinting = true);
259
260                         //! Draws some text and clips it to the specified rectangle if wanted.
261                         virtual void draw(const core::stringw& text, const core::rect<s32>& position,
262                                 video::SColor color, bool hcenter=false, bool vcenter=false,
263                                 const core::rect<s32>* clip=0);
264                         
265                         virtual void draw(const EnrichedString& text, const core::rect<s32>& position,
266                                 video::SColor color, bool hcenter=false, bool vcenter=false,
267                                 const core::rect<s32>* clip=0);
268
269                         //! Returns the dimension of a character produced by this font.
270                         virtual core::dimension2d<u32> getCharDimension(const wchar_t ch) const;
271
272                         //! Returns the dimension of a text string.
273                         virtual core::dimension2d<u32> getDimension(const wchar_t* text) const;
274                         virtual core::dimension2d<u32> getDimension(const core::ustring& text) const;
275
276                         //! Calculates the index of the character in the text which is on a specific position.
277                         virtual s32 getCharacterFromPos(const wchar_t* text, s32 pixel_x) const;
278                         virtual s32 getCharacterFromPos(const core::ustring& text, s32 pixel_x) const;
279
280                         //! Sets global kerning width for the font.
281                         virtual void setKerningWidth(s32 kerning);
282
283                         //! Sets global kerning height for the font.
284                         virtual void setKerningHeight(s32 kerning);
285
286                         //! Gets kerning values (distance between letters) for the font. If no parameters are provided,
287                         virtual s32 getKerningWidth(const wchar_t* thisLetter=0, const wchar_t* previousLetter=0) const;
288                         virtual s32 getKerningWidth(const uchar32_t thisLetter=0, const uchar32_t previousLetter=0) const;
289
290                         //! Returns the distance between letters
291                         virtual s32 getKerningHeight() const;
292
293                         //! Define which characters should not be drawn by the font.
294                         virtual void setInvisibleCharacters(const wchar_t *s);
295                         virtual void setInvisibleCharacters(const core::ustring& s);
296
297                         //! Get the last glyph page if there's still available slots.
298                         //! If not, it will return zero.
299                         CGUITTGlyphPage* getLastGlyphPage() const;
300
301                         //! Create a new glyph page texture.
302                         //! \param pixel_mode the pixel mode defined by FT_Pixel_Mode
303                         //should be better typed. fix later.
304                         CGUITTGlyphPage* createGlyphPage(const u8& pixel_mode);
305
306                         //! Get the last glyph page's index.
307                         u32 getLastGlyphPageIndex() const { return Glyph_Pages.size() - 1; }
308
309                         //! Create corresponding character's software image copy from the font,
310                         //! so you can use this data just like any ordinary video::IImage.
311                         //! \param ch The character you need
312                         virtual video::IImage* createTextureFromChar(const uchar32_t& ch);
313
314                         //! This function is for debugging mostly. If the page doesn't exist it returns zero.
315                         //! \param page_index Simply return the texture handle of a given page index.
316                         virtual video::ITexture* getPageTextureByIndex(const u32& page_index) const;
317
318                         //! Add a list of scene nodes generated by putting font textures on the 3D planes.
319                         virtual core::array<scene::ISceneNode*> addTextSceneNode
320                                 (const wchar_t* text, scene::ISceneManager* smgr, scene::ISceneNode* parent = 0,
321                                  const video::SColor& color = video::SColor(255, 0, 0, 0), bool center = false );
322
323                 protected:
324                         bool use_monochrome;
325                         bool use_transparency;
326                         bool use_hinting;
327                         bool use_auto_hinting;
328                         u32 size;
329                         u32 batch_load_size;
330                         core::dimension2du max_page_texture_size;
331
332                 private:
333                         // Manages the FreeType library.
334                         static FT_Library c_library;
335                         static core::map<io::path, SGUITTFace*> c_faces;
336                         static bool c_libraryLoaded;
337                         static scene::IMesh* shared_plane_ptr_;
338                         static scene::SMesh  shared_plane_;
339
340                         CGUITTFont(IGUIEnvironment *env);
341                         bool load(const io::path& filename, const u32 size, const bool antialias, const bool transparency);
342                         void reset_images();
343                         void update_glyph_pages() const;
344                         void update_load_flags()
345                         {
346                                 // Set up our loading flags.
347                                 load_flags = FT_LOAD_DEFAULT | FT_LOAD_RENDER;
348                                 if (!useHinting()) load_flags |= FT_LOAD_NO_HINTING;
349                                 if (!useAutoHinting()) load_flags |= FT_LOAD_NO_AUTOHINT;
350                                 if (useMonochrome()) load_flags |= FT_LOAD_MONOCHROME | FT_LOAD_TARGET_MONO | FT_RENDER_MODE_MONO;
351                                 else load_flags |= FT_LOAD_TARGET_NORMAL;
352                         }
353                         u32 getWidthFromCharacter(wchar_t c) const;
354                         u32 getWidthFromCharacter(uchar32_t c) const;
355                         u32 getHeightFromCharacter(wchar_t c) const;
356                         u32 getHeightFromCharacter(uchar32_t c) const;
357                         u32 getGlyphIndexByChar(wchar_t c) const;
358                         u32 getGlyphIndexByChar(uchar32_t c) const;
359                         core::vector2di getKerning(const wchar_t thisLetter, const wchar_t previousLetter) const;
360                         core::vector2di getKerning(const uchar32_t thisLetter, const uchar32_t previousLetter) const;
361                         core::dimension2d<u32> getDimensionUntilEndOfLine(const wchar_t* p) const;
362
363                         void createSharedPlane();
364
365                         irr::IrrlichtDevice* Device;
366                         gui::IGUIEnvironment* Environment;
367                         video::IVideoDriver* Driver;
368                         io::path filename;
369                         FT_Face tt_face;
370                         FT_Size_Metrics font_metrics;
371                         FT_Int32 load_flags;
372
373                         mutable core::array<CGUITTGlyphPage*> Glyph_Pages;
374                         mutable core::array<SGUITTGlyph> Glyphs;
375
376                         s32 GlobalKerningWidth;
377                         s32 GlobalKerningHeight;
378                         core::ustring Invisible;
379                         u32 shadow_offset;
380                         u32 shadow_alpha;
381         };
382
383 } // end namespace gui
384 } // end namespace irr
385
386 #endif // __C_GUI_TTFONT_H_INCLUDED__