3 Licenced under Academic Free License version 3.0
4 Review OpenUsbLd README & LICENSE files for further details.
7 #include "include/integers.h"
8 #include "include/usbld.h"
9 #include "include/fntsys.h"
10 #include "include/renderman.h"
11 #include "include/ioman.h"
12 #include "include/utf8.h"
13 #include "include/util.h"
14 #include "include/atlas.h"
18 #include FT_FREETYPE_H
20 extern void* freesansfont_raw
;
21 extern int size_freesansfont_raw
;
23 /// Maximal count of atlases per font
25 /// Atlas width in pixels
26 #define ATLAS_WIDTH 128
27 /// Atlas height in pixels
28 #define ATLAS_HEIGHT 128
31 static FT_Library font_library
;
33 static int gCharHeight
;
35 static s32 gFontSemaId
;
36 static ee_sema_t gFontSema
;
38 static GSCLUT fontClut
;
40 /** Single entry in the glyph cache */
43 // size in pixels of the glyph
45 // offsetting of the glyph
47 // advancements in pixels after rendering this glyph
50 // atlas for which the allocation was done
53 // atlas allocation position
54 struct atlas_allocation_t
*allocation
;
56 } fnt_glyph_cache_entry_t
;
58 /** A whole font definition */
60 /** GLYPH CACHE. Every glyph in the ASCII range is cached when first used
61 * this means no additional memory aside from the one needed to render the
62 * character set is used.
64 fnt_glyph_cache_entry_t
**glyphCache
;
66 /// Maximal font cache page index
72 /// Nonzero if font is used
75 /// Nonzero for custom fonts
78 /// Texture atlases (default to NULL)
79 atlas_t
*atlases
[ATLAS_MAX
];
81 /// Pointer to data, if allocation takeover was selected (will be freed)
85 #define FNT_MAX_COUNT (16)
87 /// Array of font definitions
88 static font_t fonts
[FNT_MAX_COUNT
];
90 static rm_quad_t quad
;
91 static uint32_t codepoint
, state
;
92 static fnt_glyph_cache_entry_t
* glyph
;
93 static FT_Bool use_kerning
;
94 static FT_UInt glyph_index
, previous
;
95 static FT_Vector delta
;
97 #define GLYPH_CACHE_PAGE_SIZE 256
99 #define GLYPH_PAGE_OK(font,page) ((pageid <= font->cacheMaxPageID) && (font->glyphCache[page]))
101 static int fntPrepareGlyphCachePage(font_t
*font
, int pageid
) {
102 if (pageid
> font
->cacheMaxPageID
) {
103 fnt_glyph_cache_entry_t
**np
= realloc(font
->glyphCache
, (pageid
+ 1) * sizeof(fnt_glyph_cache_entry_t
*));
108 font
->glyphCache
= np
;
111 for (page
= font
->cacheMaxPageID
+ 1; page
<= pageid
; ++page
)
112 font
->glyphCache
[page
] = NULL
;
114 font
->cacheMaxPageID
= pageid
;
117 // if it already was allocated, skip this
118 if (font
->glyphCache
[pageid
])
122 font
->glyphCache
[pageid
] = malloc(sizeof(fnt_glyph_cache_entry_t
) * GLYPH_CACHE_PAGE_SIZE
);
125 for (i
= 0; i
< GLYPH_CACHE_PAGE_SIZE
; ++i
) {
126 font
->glyphCache
[pageid
][i
].isValid
= 0;
127 font
->glyphCache
[pageid
][i
].atlas
= NULL
;
128 font
->glyphCache
[pageid
][i
].allocation
= NULL
;
134 static void fntResetFontDef(font_t
*fnt
) {
135 LOG("fntResetFontDef\n");
136 fnt
->glyphCache
= NULL
;
137 fnt
->cacheMaxPageID
= -1;
142 for(aid
= 0; aid
< ATLAS_MAX
; ++aid
)
143 fnt
->atlases
[aid
] = NULL
;
148 static void fntPrepareCLUT() {
149 fontClut
.PSM
= GS_PSM_T8
;
150 fontClut
.ClutPSM
= GS_PSM_CT32
;
151 fontClut
.Clut
= memalign(128, 256 * 4);
152 fontClut
.VramClut
= 0;
154 // generate the clut table
156 u32
*clut
= fontClut
.Clut
;
157 for (i
= 0; i
< 256; ++i
) {
158 u8 alpha
= i
> 0x080 ? 0x080 : i
;
160 *clut
= alpha
<< 24 | i
<< 16 | i
<< 8 | i
;
165 static void fntDestroyCLUT() {
167 fontClut
.Clut
= NULL
;
172 int error
= FT_Init_FreeType(&font_library
);
175 // just report over the ps2link
176 LOG("Freetype init failed with %x!\n", error
);
182 gFontSema
.init_count
= 1;
183 gFontSema
.max_count
= 1;
184 gFontSema
.option
= 0;
185 gFontSemaId
= CreateSema(&gFontSema
);
188 for (i
= 0; i
< FNT_MAX_COUNT
; ++i
)
189 fntResetFontDef(&fonts
[i
]);
191 // load the default font (will be id=0)
192 fntLoad(NULL
, -1, 0);
195 static void fntCacheFlushPage(fnt_glyph_cache_entry_t
*page
) {
196 LOG("fntCacheFlushPage\n");
199 for (i
= 0; i
< GLYPH_CACHE_PAGE_SIZE
; ++i
, ++page
) {
201 // we're not doing any atlasFree or such - atlas has to be rebuild
202 page
->allocation
= NULL
;
207 static void fntCacheFlush(font_t
*fnt
) {
208 LOG("fntCacheFlush\n");
212 // Release all the glyphs from the cache
213 for (i
= 0; i
<= fnt
->cacheMaxPageID
; ++i
) {
214 if (fnt
->glyphCache
[i
]) {
215 fntCacheFlushPage(fnt
->glyphCache
[i
]);
216 free(fnt
->glyphCache
[i
]);
217 fnt
->glyphCache
[i
] = NULL
;
221 free(fnt
->glyphCache
);
222 fnt
->glyphCache
= NULL
;
223 fnt
->cacheMaxPageID
= -1;
225 // free all atlasses too, they're invalid now anyway
227 for(aid
= 0; aid
< ATLAS_MAX
; ++aid
) {
228 atlasFree(fnt
->atlases
[aid
]);
229 fnt
->atlases
[aid
] = NULL
;
233 static int fntNewFont() {
236 for (i
= 0; i
< FNT_MAX_COUNT
; ++i
) {
237 if (fonts
[i
].isValid
== 0) {
238 fntResetFontDef(&fonts
[i
]);
246 void fntDeleteFont(font_t
*font
) {
247 LOG("fntDeleteFont\n");
249 // skip already deleted fonts
253 // free the glyph cache, atlases, unload the font
256 FT_Done_Face(font
->face
);
260 font
->dataPtr
= NULL
;
266 int fntLoadSlot(font_t
*fnt
, void* buffer
, int bufferSize
) {
267 LOG("fntLoadSlot\n");
270 buffer
= &freesansfont_raw
;
271 bufferSize
= size_freesansfont_raw
;
275 // load the font via memory handle
276 int error
= FT_New_Memory_Face(font_library
, (FT_Byte
*) buffer
, bufferSize
, 0, &fnt
->face
);
279 // just report over the ps2link
280 LOG("Freetype: Font loading failed with %x!\n", error
);
287 error
= FT_Set_Char_Size(fnt
->face
, 0, gCharHeight
* 16, 300, 300);
288 /*error = FT_Set_Pixel_Sizes( face,
290 gCharHeight ); // pixel_height*/
293 // just report over the ps2link
294 LOG("Freetype: Error setting font pixel size with %x!\n", error
);
303 int fntLoad(void* buffer
, int bufferSize
, int takeover
) {
306 // we need a new slot in the font array
307 int fontID
= fntNewFont();
309 if (fontID
== FNT_ERROR
)
312 font_t
*fnt
= &fonts
[fontID
];
314 if (fntLoadSlot(fnt
, buffer
, bufferSize
) == FNT_ERROR
)
318 fnt
->dataPtr
= buffer
;
323 int fntLoadFile(char* path
) {
324 LOG("fntLoadFile\n");
325 // load the buffer with font
327 void* customFont
= readFile(path
, -1, &size
);
332 int fontID
= fntLoad(customFont
, size
, 1);
337 void fntRelease(int id
) {
339 if (id
< FNT_MAX_COUNT
)
340 fntDeleteFont(&fonts
[id
]);
343 /** Terminates the font rendering system */
346 // release all the fonts
348 for (id
= 0; id
< FNT_MAX_COUNT
; ++id
)
349 fntDeleteFont(&fonts
[id
]);
351 // deinit freetype system
352 FT_Done_FreeType(font_library
);
354 DeleteSema(gFontSemaId
);
359 static atlas_t
*fntNewAtlas() {
360 atlas_t
*atl
= atlasNew(ATLAS_WIDTH
, ATLAS_HEIGHT
, GS_PSM_T8
);
362 atl
->surface
.ClutPSM
= GS_PSM_CT32
;
363 atl
->surface
.Clut
= (u32
*)(&fontClut
);
368 static int fntGlyphAtlasPlace(font_t
*fnt
, fnt_glyph_cache_entry_t
* glyph
) {
369 FT_GlyphSlot slot
= fnt
->face
->glyph
;
371 //LOG("fntGlyphAtlasPlace: Placing the glyph... %d x %d\n", slot->bitmap.width, slot->bitmap.rows);
373 if (slot
->bitmap
.width
== 0 || slot
->bitmap
.rows
== 0) {
374 // no bitmap glyph, just skip
380 for (aid
= 0; aid
< ATLAS_MAX
; ++aid
) {
381 //LOG(" * Placing aid %d...\n", aid);
382 atlas_t
**atl
= &fnt
->atlases
[aid
];
383 if (!*atl
) { // atlas slot not yet used
384 //LOG(" * aid %d is new...\n", aid);
385 *atl
= fntNewAtlas();
389 atlasPlace(*atl
, slot
->bitmap
.width
, slot
->bitmap
.rows
, slot
->bitmap
.buffer
);
391 if (glyph
->allocation
) {
392 //LOG(" * found placement\n", aid);
399 LOG(" * ! no atlas free\n", aid
);
403 /** Internal method. Makes sure the bitmap data for particular character are pre-rendered to the glyph cache */
404 static fnt_glyph_cache_entry_t
* fntCacheGlyph(font_t
*fnt
, uint32_t gid
) {
405 // calc page id and in-page index from glyph id
406 int pageid
= gid
/ GLYPH_CACHE_PAGE_SIZE
;
407 int idx
= gid
% GLYPH_CACHE_PAGE_SIZE
;
409 // do not call on every char of every font rendering call
410 if (!GLYPH_PAGE_OK(fnt
,pageid
))
411 if (!fntPrepareGlyphCachePage(fnt
, pageid
)) // failed to prepare the page...
414 fnt_glyph_cache_entry_t
*page
= fnt
->glyphCache
[pageid
];
416 /* Should never happen.
417 if (!page) // safeguard
421 fnt_glyph_cache_entry_t
* glyph
= &page
[idx
];
426 // not cached but valid. Cache
428 LOG("FNT: Face is NULL!\n");
431 int error
= FT_Load_Char(fnt
->face
, gid
, FT_LOAD_RENDER
);
434 LOG("FNT: Error loading glyph - %d\n", error
);
438 // find atlas placement for the glyph
439 if (!fntGlyphAtlasPlace(fnt
, glyph
))
442 FT_GlyphSlot slot
= fnt
->face
->glyph
;
443 glyph
->width
= slot
->bitmap
.width
;
444 glyph
->height
= slot
->bitmap
.rows
;
445 glyph
->shx
= slot
->advance
.x
;
446 glyph
->shy
= slot
->advance
.y
;
447 glyph
->ox
= slot
->bitmap_left
;
448 glyph
->oy
= gCharHeight
- slot
->bitmap_top
;
455 void fntSetAspectRatio(float aw
, float ah
) {
456 LOG("fntSetAspectRatio\n");
457 // flush cache - it will be invalid after the setting
460 for (i
= 0; i
< FNT_MAX_COUNT
; ++i
) {
461 if (fonts
[i
].isValid
)
462 fntCacheFlush(&fonts
[i
]);
465 // set new aspect ratio (Is this correct, I wonder?)
466 // TODO: error = FT_Set_Char_Size(face, 0, gCharHeight*64, ah*300, aw*300);
469 static void fntRenderGlyph(fnt_glyph_cache_entry_t
* glyph
, int pen_x
, int pen_y
) {
470 // only if glyph has atlas placement
471 if (glyph
->allocation
) {
472 /* TODO: Ineffective on many parts:
473 * 1. Usage of floats for UV - fixed point should suffice (and is used internally by GS for UV)
475 * 2. GS_SETREG_TEX0 for every quad - why? gsKit should only set texture if demanded
476 * We should prepare a special fnt render method that would step over most of the
477 * performance problems under - begining with rmSetupQuad and continuing into gsKit
478 * - this method would handle the preparetion of the quads and GS upload itself,
479 * without the use of prim_quad_texture and rmSetupQuad...
481 * 3. We should use clut to keep the memory allocations sane - we're linear in the 32bit buffers
482 * anyway, no reason to waste like we do!
484 quad
.ul
.x
= pen_x
+ glyph
->ox
;
485 quad
.br
.x
= quad
.ul
.x
+ glyph
->width
;
486 quad
.ul
.y
= pen_y
+ glyph
->oy
;
487 quad
.br
.y
= quad
.ul
.y
+ glyph
->height
;
489 // UV is our own, custom thing here
490 quad
.txt
= &glyph
->atlas
->surface
;
491 quad
.ul
.u
= glyph
->allocation
->x
;
492 quad
.br
.u
= quad
.ul
.u
+ glyph
->width
;
493 quad
.ul
.v
= glyph
->allocation
->y
;
494 quad
.br
.v
= quad
.ul
.v
+ glyph
->height
;
501 int fntRenderString(int font
, int x
, int y
, short aligned
, size_t width
, size_t height
, const unsigned char* string
, u64 colour
) {
502 // wait for font lock to unlock
503 WaitSema(gFontSemaId
);
504 font_t
*fnt
= &fonts
[font
];
505 SignalSema(gFontSemaId
);
509 x
-= min(fntCalcDimensions(font
, string
), width
) >> 1;
511 x
-= fntCalcDimensions(font
, string
) >> 1;
513 y
-= MENU_ITEM_HEIGHT
>> 1;
516 rmApplyShiftRatio(&y
);
520 int xmax
= x
+ width
;
521 int ymax
= y
+ height
;
523 use_kerning
= FT_HAS_KERNING(fnt
->face
);
527 // Note: We need to change this so that we'll accumulate whole word before doing a layout with it
528 // for now this method breaks on any character - which is a bit ugly
530 // I don't want to do anything complicated though so I'd say
531 // we should instead have a dynamic layout routine that'll replace spaces with newlines as appropriate
532 // because that'll make the code run only once per N frames, not every frame
534 // cache glyphs and render as we go
535 for (; *string
; ++string
) {
536 if (utf8Decode(&state
, &codepoint
, *string
)) // accumulate the codepoint value
539 glyph
= fntCacheGlyph(fnt
, codepoint
);
544 if (use_kerning
&& previous
) {
545 glyph_index
= FT_Get_Char_Index(fnt
->face
, codepoint
);
547 FT_Get_Kerning(fnt
->face
, previous
, glyph_index
, FT_KERNING_DEFAULT
, &delta
);
548 pen_x
+= delta
.x
>> 6;
550 previous
= glyph_index
;
554 if (codepoint
== '\n') {
556 y
+= MENU_ITEM_HEIGHT
; // hmax is too tight and unordered, generally
560 if (y
> ymax
) // stepped over the max
563 if (pen_x
+ glyph
->width
> xmax
) {
564 pen_x
= xmax
+ 1; // to be sure no other cahr will be written (even not a smaller one just following)
569 fntRenderGlyph(glyph
, pen_x
, y
);
570 pen_x
+= glyph
->shx
>> 6;
577 static void fntRenderSubRTL(font_t
*fnt
, const unsigned char* startRTL
, const unsigned char* string
, fnt_glyph_cache_entry_t
* glyph
, int x
, int y
) {
579 x
-= glyph
->shx
>> 6;
580 fntRenderGlyph(glyph
, x
, y
);
583 for (; startRTL
!= string
; ++startRTL
) {
584 if (utf8Decode(&state
, &codepoint
, *startRTL
))
587 glyph
= fntCacheGlyph(fnt
, codepoint
);
591 if (use_kerning
&& previous
) {
592 glyph_index
= FT_Get_Char_Index(fnt
->face
, codepoint
);
594 FT_Get_Kerning(fnt
->face
, previous
, glyph_index
, FT_KERNING_DEFAULT
, &delta
);
597 previous
= glyph_index
;
600 x
-= glyph
->shx
>> 6;
601 fntRenderGlyph(glyph
, x
, y
);
605 int fntRenderString(int font
, int x
, int y
, short aligned
, size_t width
, size_t height
, const unsigned char* string
, u64 colour
) {
606 // wait for font lock to unlock
607 WaitSema(gFontSemaId
);
608 font_t
*fnt
= &fonts
[font
];
609 SignalSema(gFontSemaId
);
613 x
-= min(fntCalcDimensions(font
, string
), width
) >> 1;
615 x
-= fntCalcDimensions(font
, string
) >> 1;
617 y
-= MENU_ITEM_HEIGHT
>> 1;
620 rmApplyShiftRatio(&y
);
624 /*int xmax = x + width;
625 int ymax = y + height;*/
627 use_kerning
= FT_HAS_KERNING(fnt
->face
);
632 int delta_x
, pen_xRTL
= 0;
633 fnt_glyph_cache_entry_t
* glyphRTL
= NULL
;
634 const unsigned char* startRTL
= NULL
;
636 // cache glyphs and render as we go
637 for (; *string
; ++string
) {
638 if (utf8Decode(&state
, &codepoint
, *string
)) // accumulate the codepoint value
641 glyph
= fntCacheGlyph(fnt
, codepoint
);
647 if (use_kerning
&& previous
) {
648 glyph_index
= FT_Get_Char_Index(fnt
->face
, codepoint
);
650 FT_Get_Kerning(fnt
->face
, previous
, glyph_index
, FT_KERNING_DEFAULT
, &delta
);
651 delta_x
= delta
.x
>> 6;
653 previous
= glyph_index
;
658 if (codepoint == '\n') {
660 y += MENU_ITEM_HEIGHT; // hmax is too tight and unordered, generally
664 if ((x + glyph_w > xmax) || (y > ymax)) // stepped over the max
668 if (codepoint
> 0xFF) {
673 startRTL
= string
+ 1;
675 } else if ((codepoint
> 96 && codepoint
< 123) || (codepoint
> 64 && codepoint
< 91)) {
676 if (inRTL
) { // render RTL
679 fntRenderSubRTL(fnt
, startRTL
, string
, glyphRTL
, pen_xRTL
, y
);
684 pen_xRTL
+= delta_x
+ (glyph
->shx
>> 6);
687 fntRenderGlyph(glyph
, pen_x
, y
);
688 pen_x
+= glyph
->shx
>> 6;
695 fntRenderSubRTL(fnt
, startRTL
, string
, glyphRTL
, pen_xRTL
, y
);
702 void fntFitString(int font
, unsigned char *string
, size_t width
) {
704 unsigned char *str
= string
;
705 size_t spacewidth
= fntCalcDimensions(font
, " ");
706 unsigned char *psp
= NULL
;
709 // scan forward to the next whitespace
710 unsigned char *sp
= str
;
711 for (; *sp
&& *sp
!= ' ' && *sp
!= '\n'; ++sp
);
713 // store what was there before
714 unsigned char osp
= *sp
;
716 // newline resets the situation
724 // terminate after the word
727 // Calc the font's width...
728 // NOTE: The word was terminated, so we're seeing a single word
730 size_t ww
= fntCalcDimensions(font
, str
);
732 if (cw
+ ww
> width
) {
734 // we have a prev space to utilise (wrap on it)
740 // no prev. space to hijack, must break after the word
741 // this will mean overflowed text...
756 int fntCalcDimensions(int font
, const unsigned char* str
) {
759 WaitSema(gFontSemaId
);
760 font_t
*fnt
= &fonts
[font
];
761 SignalSema(gFontSemaId
);
764 uint32_t state
= UTF8_ACCEPT
;
765 FT_Bool use_kerning
= FT_HAS_KERNING(fnt
->face
);
766 FT_UInt glyph_index
, previous
= 0;
769 // cache glyphs and render as we go
770 for (; *str
; ++str
) {
771 if (utf8Decode(&state
, &codepoint
, *str
)) // accumulate the codepoint value
774 // Could just as well only get the glyph dimensions
775 // but it is probable the glyphs will be needed anyway
776 fnt_glyph_cache_entry_t
* glyph
= fntCacheGlyph(fnt
, codepoint
);
781 if (use_kerning
&& previous
) {
782 glyph_index
= FT_Get_Char_Index(fnt
->face
, codepoint
);
784 FT_Get_Kerning(fnt
->face
, previous
, glyph_index
, FT_KERNING_DEFAULT
, &delta
);
787 previous
= glyph_index
;
790 w
+= glyph
->shx
>> 6;
796 void fntReplace(int id
, void* buffer
, int bufferSize
, int takeover
, int asDefault
) {
797 font_t
*fnt
= &fonts
[id
];
799 font_t ndefault
, old
;
800 fntResetFontDef(&ndefault
);
801 fntLoadSlot(&ndefault
, buffer
, bufferSize
);
802 ndefault
.isDefault
= asDefault
;
804 // copy over the new font definition
805 // we have to lock this phase, as the old font may still be used
806 WaitSema(gFontSemaId
);
807 memcpy(&old
, fnt
, sizeof(font_t
));
808 memcpy(fnt
, &ndefault
, sizeof(font_t
));
811 fnt
->dataPtr
= buffer
;
813 SignalSema(gFontSemaId
);
815 // delete the old font
819 void fntSetDefault(int id
) {
820 font_t
*fnt
= &fonts
[id
];
826 font_t ndefault
, old
;
827 fntResetFontDef(&ndefault
);
828 fntLoadSlot(&ndefault
, NULL
, -1);
830 // copy over the new font definition
831 // we have to lock this phase, as the old font may still be used
832 // Note: No check for concurrency is done here, which is kinda funky!
833 WaitSema(gFontSemaId
);
834 memcpy(&old
, fnt
, sizeof(font_t
));
835 memcpy(fnt
, &ndefault
, sizeof(font_t
));
836 SignalSema(gFontSemaId
);
838 // delete the old font