Delete irrlichttypes_extrabloated.h (#15723)
[minetest.git] / src / irrlicht_changes / CGUITTFont.h
blobffdd6a6caf434f8627e21f024a7c716662a248ca
1 /*
2 CGUITTFont FreeType class for Irrlicht
3 Copyright (c) 2009-2010 John Norman
4 Copyright (c) 2016 Nathanaƫlle Courant
5 Copyright (c) 2023 Caleb Butler
6 Copyright (c) 2024 Luanti contributors
8 This software is provided 'as-is', without any express or implied
9 warranty. In no event will the authors be held liable for any
10 damages arising from the use of this software.
12 Permission is granted to anyone to use this software for any
13 purpose, including commercial applications, and to alter it and
14 redistribute it freely, subject to the following restrictions:
16 1. The origin of this software must not be misrepresented; you
17 must not claim that you wrote the original software. If you use
18 this software in a product, an acknowledgment in the product
19 documentation would be appreciated but is not required.
21 2. Altered source versions must be plainly marked as such, and
22 must not be misrepresented as being the original software.
24 3. This notice may not be removed or altered from any source
25 distribution.
27 The original version of this class can be located at:
28 http://irrlicht.suckerfreegames.com/
30 John Norman
31 john@suckerfreegames.com
34 #pragma once
36 #include <ft2build.h>
37 #include <freetype/freetype.h>
39 #include "IGUIEnvironment.h"
40 #include "IGUIFont.h"
41 #include "IVideoDriver.h"
42 #include "IrrlichtDevice.h"
43 #include "util/enriched_string.h"
44 #include "util/basic_macros.h"
46 #include <map>
47 #include <optional>
49 namespace irr
51 namespace gui
53 // Manages the FT_Face cache.
54 struct SGUITTFace : public irr::IReferenceCounted
56 private:
58 static std::map<io::path, SGUITTFace*> faces;
59 static FT_Library freetype_library;
60 static std::size_t n_faces;
62 static FT_Library getFreeTypeLibrary();
64 public:
66 SGUITTFace(std::string &&buffer);
68 ~SGUITTFace();
70 std::optional<std::string> filename;
72 FT_Face face;
73 /// Must not be deallocated until we are done with the face!
74 std::string face_buffer;
76 static SGUITTFace* createFace(std::string &&buffer);
78 static SGUITTFace* loadFace(const io::path &filename);
80 void dropFilename();
82 class CGUITTFont;
84 //! Structure representing a single TrueType glyph.
85 struct SGUITTGlyph
87 //! Constructor.
88 SGUITTGlyph() :
89 glyph_page(0),
90 source_rect(),
91 offset(),
92 advance(),
93 surface(0)
96 DISABLE_CLASS_COPY(SGUITTGlyph);
98 //! This class would be trivially copyable except for the reference count on `surface`.
99 SGUITTGlyph(SGUITTGlyph &&other) noexcept :
100 glyph_page(other.glyph_page),
101 source_rect(other.source_rect),
102 offset(other.offset),
103 advance(other.advance),
104 surface(other.surface)
106 other.surface = 0;
109 //! Destructor.
110 ~SGUITTGlyph() { unload(); }
112 //! If true, the glyph has been loaded.
113 inline bool isLoaded() const {
114 return source_rect != core::recti();
117 //! Preload the glyph.
118 //! The preload process occurs when the program tries to cache the glyph from FT_Library.
119 //! However, it simply defines the SGUITTGlyph's properties and will only create the page
120 //! textures if necessary. The actual creation of the textures should only occur right
121 //! before the batch draw call.
122 void preload(u32 char_index, FT_Face face, CGUITTFont *parent, u32 font_size, const FT_Int32 loadFlags);
124 //! Unloads the glyph.
125 void unload();
127 //! Creates the IImage object from the FT_Bitmap.
128 video::IImage* createGlyphImage(const FT_Bitmap& bits, video::IVideoDriver* driver) const;
130 //! The page the glyph is on.
131 u32 glyph_page;
133 //! The source rectangle for the glyph.
134 core::recti source_rect;
136 //! The offset of glyph when drawn.
137 core::vector2di offset;
139 //! Glyph advance information.
140 core::vector2di advance;
142 //! This is just the temporary image holder. After this glyph is paged,
143 //! it will be dropped.
144 mutable video::IImage* surface;
147 //! Holds a sheet of glyphs.
148 class CGUITTGlyphPage
150 public:
151 CGUITTGlyphPage(video::IVideoDriver* Driver, const io::path& texture_name) :texture(0), available_slots(0), used_slots(0), dirty(false), driver(Driver), name(texture_name) {}
152 ~CGUITTGlyphPage()
154 if (texture)
156 if (driver)
157 driver->removeTexture(texture);
158 else
159 texture->drop();
163 //! Create the actual page texture,
164 bool createPageTexture(const u8& pixel_mode, const core::dimension2du& texture_size)
166 if( texture )
167 return false;
169 bool flgmip = driver->getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS);
170 driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);
171 bool flgcpy = driver->getTextureCreationFlag(video::ETCF_ALLOW_MEMORY_COPY);
172 driver->setTextureCreationFlag(video::ETCF_ALLOW_MEMORY_COPY, true);
174 // Set the texture color format.
175 switch (pixel_mode)
177 case FT_PIXEL_MODE_MONO:
178 texture = driver->addTexture(texture_size, name, video::ECF_A1R5G5B5);
179 break;
180 case FT_PIXEL_MODE_GRAY:
181 default:
182 texture = driver->addTexture(texture_size, name, video::ECF_A8R8G8B8);
183 break;
186 // Restore our texture creation flags.
187 driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, flgmip);
188 driver->setTextureCreationFlag(video::ETCF_ALLOW_MEMORY_COPY, flgcpy);
190 return texture ? true : false;
193 //! Add the glyph to a list of glyphs to be paged.
194 //! This collection will be cleared after updateTexture is called.
195 void pushGlyphToBePaged(const SGUITTGlyph* glyph)
197 glyph_to_be_paged.push_back(glyph);
200 //! Updates the texture atlas with new glyphs.
201 void updateTexture()
203 if (!dirty) return;
205 void* ptr = texture->lock();
206 video::ECOLOR_FORMAT format = texture->getColorFormat();
207 core::dimension2du size = texture->getOriginalSize();
208 video::IImage* pageholder = driver->createImageFromData(format, size, ptr, true, false);
210 for (u32 i = 0; i < glyph_to_be_paged.size(); ++i)
212 const SGUITTGlyph* glyph = glyph_to_be_paged[i];
213 if (glyph && glyph->surface)
215 glyph->surface->copyTo(pageholder, glyph->source_rect.UpperLeftCorner);
216 glyph->surface->drop();
217 glyph->surface = 0;
221 pageholder->drop();
222 texture->unlock();
223 glyph_to_be_paged.clear();
224 dirty = false;
227 video::ITexture* texture;
228 u32 available_slots;
229 u32 used_slots;
230 bool dirty;
232 core::array<core::vector2di> render_positions;
233 core::array<core::recti> render_source_rects;
234 core::array<video::SColor> render_colors;
236 private:
237 core::array<const SGUITTGlyph*> glyph_to_be_paged;
238 video::IVideoDriver* driver;
239 io::path name;
242 //! Class representing a TrueType font.
243 class CGUITTFont : public IGUIFont
245 public:
246 //! Creates a new TrueType font and returns a pointer to it. The pointer must be drop()'ed when finished.
247 //! \param env The IGUIEnvironment the font loads out of.
248 //! \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.
249 //! \param antialias set the use_monochrome (opposite to antialias) flag
250 //! \param transparency set the use_transparency flag
251 //! \return Returns a pointer to a CGUITTFont. Will return 0 if the font failed to load.
252 static CGUITTFont* createTTFont(IGUIEnvironment *env,
253 SGUITTFace *face, u32 size, bool antialias = true,
254 bool transparency = true, u32 shadow = 0, u32 shadow_alpha = 255);
256 //! Destructor
257 virtual ~CGUITTFont();
259 //! Sets the amount of glyphs to batch load.
260 void setBatchLoadSize(u32 batch_size) { batch_load_size = batch_size; }
262 //! Sets the maximum texture size for a page of glyphs.
263 void setMaxPageTextureSize(const core::dimension2du& texture_size) { max_page_texture_size = texture_size; }
265 //! Get the font size.
266 u32 getFontSize() const { return size; }
268 //! Check the font's transparency.
269 bool isTransparent() const { return use_transparency; }
271 //! Check if the font auto-hinting is enabled.
272 //! Auto-hinting is FreeType's built-in font hinting engine.
273 bool useAutoHinting() const { return use_auto_hinting; }
275 //! Check if the font hinting is enabled.
276 bool useHinting() const { return use_hinting; }
278 //! Check if the font is being loaded as a monochrome font.
279 //! The font can either be a 256 color grayscale font, or a 2 color monochrome font.
280 bool useMonochrome() const { return use_monochrome; }
282 //! Tells the font to allow transparency when rendering.
283 //! Default: true.
284 //! \param flag If true, the font draws using transparency.
285 void setTransparency(const bool flag);
287 //! Tells the font to use monochrome rendering.
288 //! Default: false.
289 //! \param flag If true, the font draws using a monochrome image. If false, the font uses a grayscale image.
290 void setMonochrome(const bool flag);
292 //! Enables or disables font hinting.
293 //! Default: Hinting and auto-hinting true.
294 //! \param enable If false, font hinting is turned off. If true, font hinting is turned on.
295 //! \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.
296 void setFontHinting(const bool enable, const bool enable_auto_hinting = true);
298 //! Draws some text and clips it to the specified rectangle if wanted.
299 virtual void draw(const core::stringw& text, const core::rect<s32>& position,
300 video::SColor color, bool hcenter=false, bool vcenter=false,
301 const core::rect<s32>* clip=0) override;
303 void draw(const EnrichedString& text, const core::rect<s32>& position,
304 bool hcenter=false, bool vcenter=false,
305 const core::rect<s32>* clip=0);
307 //! Returns the dimension of a text string.
308 virtual core::dimension2du getDimension(const wchar_t* text) const override;
310 //! Calculates the index of the character in the text which is on a specific position.
311 virtual s32 getCharacterFromPos(const wchar_t* text, s32 pixel_x) const override;
313 //! Sets global kerning width for the font.
314 virtual void setKerningWidth(s32 kerning) override;
316 //! Sets global kerning height for the font.
317 virtual void setKerningHeight(s32 kerning) override;
319 //! Returns the distance between letters
320 virtual core::vector2di getKerning(const wchar_t thisLetter, const wchar_t previousLetter) const override;
322 //! Define which characters should not be drawn by the font.
323 virtual void setInvisibleCharacters(const wchar_t *s) override;
325 //! Get the last glyph page if there's still available slots.
326 //! If not, it will return zero.
327 CGUITTGlyphPage* getLastGlyphPage() const;
329 //! Create a new glyph page texture.
330 //! \param pixel_mode the pixel mode defined by FT_Pixel_Mode
331 //should be better typed. fix later.
332 CGUITTGlyphPage* createGlyphPage(const u8 pixel_mode);
334 //! Get the last glyph page's index.
335 u32 getLastGlyphPageIndex() const { return Glyph_Pages.size() - 1; }
337 //! Set font that should be used for glyphs not present in ours
338 void setFallback(gui::IGUIFont* font) { fallback = font; }
340 //! Create corresponding character's software image copy from the font,
341 //! so you can use this data just like any ordinary video::IImage.
342 //! \param ch The character you need
343 video::IImage* createTextureFromChar(const char32_t& ch);
345 //! This function is for debugging mostly. If the page doesn't exist it returns zero.
346 //! \param page_index Simply return the texture handle of a given page index.
347 video::ITexture* getPageTextureByIndex(const u32& page_index) const;
349 inline video::IVideoDriver *getDriver() const { return Driver; }
351 inline s32 getAscender() const { return font_metrics.ascender; }
353 protected:
354 bool use_monochrome;
355 bool use_transparency;
356 bool use_hinting;
357 bool use_auto_hinting;
358 u32 size;
359 u32 batch_load_size;
360 core::dimension2du max_page_texture_size;
362 private:
363 // Helper functions for the same-named public member functions above
364 // (Since std::u32string is nicer to work with than wchar_t *)
365 core::dimension2d<u32> getDimension(const std::u32string& text) const;
366 s32 getCharacterFromPos(const std::u32string& text, s32 pixel_x) const;
368 // Helper function for the above helper functions :P
369 std::u32string convertWCharToU32String(const wchar_t* const) const;
371 CGUITTFont(IGUIEnvironment *env);
372 bool load(SGUITTFace *face, const u32 size, const bool antialias, const bool transparency);
373 void reset_images();
374 void update_glyph_pages() const;
375 void update_load_flags()
377 // Set up our loading flags.
378 load_flags = FT_LOAD_DEFAULT | FT_LOAD_RENDER;
379 if (!useHinting()) load_flags |= FT_LOAD_NO_HINTING;
380 if (!useAutoHinting()) load_flags |= FT_LOAD_NO_AUTOHINT;
381 if (useMonochrome()) load_flags |= FT_LOAD_MONOCHROME | FT_LOAD_TARGET_MONO;
382 else load_flags |= FT_LOAD_TARGET_NORMAL;
384 u32 getWidthFromCharacter(char32_t c) const;
385 u32 getHeightFromCharacter(char32_t c) const;
386 u32 getGlyphIndexByChar(char32_t c) const;
387 core::vector2di getKerning(const char32_t thisLetter, const char32_t previousLetter) const;
389 video::IVideoDriver* Driver;
390 std::optional<io::path> filename;
391 FT_Face tt_face;
392 FT_Size_Metrics font_metrics;
393 FT_Int32 load_flags;
395 mutable core::array<CGUITTGlyphPage*> Glyph_Pages;
396 mutable core::array<SGUITTGlyph> Glyphs;
398 s32 GlobalKerningWidth;
399 s32 GlobalKerningHeight;
400 std::u32string Invisible;
401 u32 shadow_offset;
402 u32 shadow_alpha;
404 gui::IGUIFont* fallback;
407 } // end namespace gui
408 } // end namespace irr