├── bin ├── dejavu-sans_0.png ├── DroidSerif-Bold.ttf ├── DroidSansJapanese.ttf ├── DroidSerif-Italic.ttf ├── DroidSerif-Regular.ttf ├── README.txt ├── dejavu-sans.bmfc └── NOTICE ├── stb_truetype.c ├── Makefile ├── fontstash.h ├── README.md ├── main.c ├── fontstash.c └── stb_truetype.h /bin/dejavu-sans_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akrinke/Font-Stash/HEAD/bin/dejavu-sans_0.png -------------------------------------------------------------------------------- /bin/DroidSerif-Bold.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akrinke/Font-Stash/HEAD/bin/DroidSerif-Bold.ttf -------------------------------------------------------------------------------- /bin/DroidSansJapanese.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akrinke/Font-Stash/HEAD/bin/DroidSansJapanese.ttf -------------------------------------------------------------------------------- /bin/DroidSerif-Italic.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akrinke/Font-Stash/HEAD/bin/DroidSerif-Italic.ttf -------------------------------------------------------------------------------- /bin/DroidSerif-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akrinke/Font-Stash/HEAD/bin/DroidSerif-Regular.ttf -------------------------------------------------------------------------------- /stb_truetype.c: -------------------------------------------------------------------------------- 1 | #define STB_TRUETYPE_IMPLEMENTATION 2 | 3 | #define STBTT_malloc(x,u) malloc(x) 4 | #define STBTT_free(x,u) free(x) 5 | #define STBTT_assert(...) do {} while(0) 6 | 7 | #include "stb_truetype.h" 8 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | PROGRAM = fontstash 2 | C_FILES := $(wildcard *.c) 3 | CC = gcc 4 | CFLAGS = -std=c99 -Wall -pedantic -Wno-unused-but-set-variable 5 | CFLAGS += `sdl-config --cflags` `pkg-config --cflags SDL_image` 6 | LDFLAGS = `sdl-config --libs` `pkg-config --libs SDL_image` -lGL -lm 7 | 8 | all: 9 | $(CC) -o bin/$(PROGRAM) $(CFLAGS) $(C_FILES) $(LDFLAGS) 10 | 11 | debug: 12 | $(CC) -o bin/$(PROGRAM) -ggdb $(CFLAGS) $(C_FILES) $(LDFLAGS) 13 | 14 | run: all 15 | cd bin && ./$(PROGRAM) 16 | -------------------------------------------------------------------------------- /bin/README.txt: -------------------------------------------------------------------------------- 1 | Copyright (C) 2008 The Android Open Source Project 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | 15 | ########## 16 | 17 | This directory contains the fonts for the platform. They are licensed 18 | under the Apache 2 license. 19 | -------------------------------------------------------------------------------- /bin/dejavu-sans.bmfc: -------------------------------------------------------------------------------- 1 | # AngelCode Bitmap Font Generator configuration file 2 | fileVersion=1 3 | 4 | # font settings 5 | fontName=DejaVu Sans 6 | charSet=0 7 | fontSize=18 8 | aa=1 9 | scaleH=100 10 | useSmoothing=1 11 | isBold=1 12 | isItalic=0 13 | useUnicode=1 14 | disableBoxChars=1 15 | outputInvalidCharGlyph=0 16 | 17 | # character alignment 18 | paddingDown=0 19 | paddingUp=0 20 | paddingRight=0 21 | paddingLeft=0 22 | spacingHoriz=1 23 | spacingVert=1 24 | useFixedHeight=0 25 | 26 | # output file 27 | outWidth=512 28 | outHeight=512 29 | outBitDepth=8 30 | fontDescFormat=0 31 | fourChnlPacked=0 32 | textureFormat=png 33 | textureCompression=0 34 | alphaChnl=0 35 | redChnl=4 36 | greenChnl=4 37 | blueChnl=4 38 | invA=0 39 | invR=0 40 | invG=0 41 | invB=0 42 | 43 | # outline 44 | outlineThickness=0 45 | 46 | # selected chars 47 | chars=32-126,160-591,880-887,890-894,900-906,908,910-929,931-1309,1312-1317,1542-1543,1545-1546,1548,1557 48 | chars=1563,1567,1569-1594,1600-1621,1623,1626,1632-1648,1652,1657-1727,1734,1740,1742,1749,1776-1785,8192 49 | chars=8193-8292,8298-8305,8308-8334,8336-8340,8352-8373,8376-8377,8592-8703,9632-9884,9888-9912,9920-9923 50 | chars=9985-9988,9990-9993,9996-10023,10025-10059,10061,10063-10066,10070,10072-10078,10081-10132,10136 51 | chars=10137-10159,10161-10174 52 | 53 | # imported icon images 54 | -------------------------------------------------------------------------------- /fontstash.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2011 Andreas Krinke andreas.krinke@gmx.de 3 | // Copyright (c) 2009 Mikko Mononen memon@inside.org 4 | // 5 | // This software is provided 'as-is', without any express or implied 6 | // warranty. In no event will the authors be held liable for any damages 7 | // arising from the use of this software. 8 | // Permission is granted to anyone to use this software for any purpose, 9 | // including commercial applications, and to alter it and redistribute it 10 | // freely, subject to the following restrictions: 11 | // 1. The origin of this software must not be misrepresented; you must not 12 | // claim that you wrote the original software. If you use this software 13 | // in a product, an acknowledgment in the product documentation would be 14 | // appreciated but is not required. 15 | // 2. Altered source versions must be plainly marked as such, and must not be 16 | // misrepresented as being the original software. 17 | // 3. This notice may not be removed or altered from any source distribution. 18 | // 19 | 20 | #ifndef FONTSTASH_H 21 | #define FONTSTASH_H 22 | 23 | #define STH_ESUCCESS 0 24 | // error opening file 25 | #define STH_EFILEIO -1 26 | // error initializing truetype font 27 | #define STH_ETTFINIT -2 28 | // invalid argument 29 | #define STH_EINVAL -3 30 | // not enough memory 31 | #define STH_ENOMEM -4 32 | 33 | struct sth_stash* sth_create(int cachew, int cacheh); 34 | 35 | int sth_add_font(struct sth_stash* stash, const char* path); 36 | int sth_add_font_from_memory(struct sth_stash* stash, unsigned char* buffer); 37 | 38 | int sth_add_bitmap_font(struct sth_stash* stash, int ascent, int descent, int line_gap); 39 | int sth_add_glyph_for_codepoint(struct sth_stash* stash, int idx, GLuint id, unsigned int codepoint, 40 | short size, short base, int x, int y, int w, int h, 41 | float xoffset, float yoffset, float xadvance); 42 | int sth_add_glyph_for_char(struct sth_stash* stash, int idx, GLuint id, const char* s, 43 | short size, short base, int x, int y, int w, int h, 44 | float xoffset, float yoffset, float xadvance); 45 | 46 | void sth_begin_draw(struct sth_stash* stash); 47 | void sth_end_draw(struct sth_stash* stash); 48 | 49 | void sth_draw_text(struct sth_stash* stash, 50 | int idx, float size, 51 | float x, float y, const char* string, float* dx); 52 | 53 | void sth_dim_text(struct sth_stash* stash, int idx, float size, const char* string, 54 | float* minx, float* miny, float* maxx, float* maxy); 55 | 56 | void sth_vmetrics(struct sth_stash* stash, 57 | int idx, float size, 58 | float* ascender, float* descender, float * lineh); 59 | 60 | void sth_delete(struct sth_stash* stash); 61 | 62 | #endif // FONTSTASH_H 63 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Font Stash: Dynamic font glyph cache for OpenGL 2 | 3 | Font Stash enables easy string rendering in OpenGL applications. It supports truetype fonts and UTF-8 encoded localized strings. All glyphs are cached in OpenGL texture atlases. Font rasterization is done using Sean Barrett's [stb_truetype.h](http://nothings.org/). 4 | 5 | Font Stash was originally created and [published](http://digestingduck.blogspot.com/2009/08/font-stash.html) by [Mikko Mononen](http://digestingduck.blogspot.com). 6 | 7 | ## Major changes to the original version 8 | 9 | * Bitmap font support 10 | * Truetype font loading from memory 11 | * Added ability to load an arbitrary number of fonts (not just four) 12 | * Use multiple OpenGL textures for glyph caching (not just one) 13 | 14 | ## Road map 15 | 16 | * Freetype2 support (for glyph outlines) 17 | 18 | ## Screenshot 19 | 20 | ![Screenshot](https://github.com/akrinke/Font-Stash/wiki/screenshot.png) 21 | 22 | ## Usage 23 | 24 | ```c 25 | #include "fontstash.h" 26 | 27 | ... 28 | /* create a font stash with a maximum texture size of 512 x 512 */ 29 | struct sth_stash* stash = sth_create(512, 512); 30 | /* load truetype font */ 31 | int droid = sth_add_font(stash, "DroidSerif-Regular.ttf"); 32 | /* position of the text */ 33 | float x = 10, y = 10; 34 | ... 35 | /* draw text during your OpenGL render loop */ 36 | sth_begin_draw(stash); 37 | /* position: (x, y); font size: 24 */ 38 | sth_draw_text(stash, droid, 24.0f, x, y, "Hello world!", &x); 39 | /* now, the float x contains the x position of the next char */ 40 | sth_end_draw(stash); 41 | ... 42 | 43 | ``` 44 | 45 | ## Bitmap fonts 46 | 47 | Bitmap fonts can be generated using the [AngelCode Bitmap Font Generator](http://www.angelcode.com/products/bmfont/). It's a Windows program that runs under Linux using Wine. This program generates one or more image files and a text file (*.fnt) containing the bounding box coordinates of all individual glyphs. These coordinates are used to reference the glyphs using Font Stash. 48 | 49 | ## License 50 | 51 | The files fontstash.c, fontstash.h and main.c are licensed unter the zlib license: 52 | 53 | Copyright (c) 2011 Andreas Krinke andreas.krinke@gmx.de 54 | Copyright (c) 2009 Mikko Mononen memon@inside.org 55 | 56 | This software is provided 'as-is', without any express or implied 57 | warranty. In no event will the authors be held liable for any damages 58 | arising from the use of this software. 59 | Permission is granted to anyone to use this software for any purpose, 60 | including commercial applications, and to alter it and redistribute it 61 | freely, subject to the following restrictions: 62 | 1. The origin of this software must not be misrepresented; you must not 63 | claim that you wrote the original software. If you use this software 64 | in a product, an acknowledgment in the product documentation would be 65 | appreciated but is not required. 66 | 2. Altered source versions must be plainly marked as such, and must not be 67 | misrepresented as being the original software. 68 | 3. This notice may not be removed or altered from any source distribution. 69 | 70 | For UTF-8 decoding, Font Stash uses Björn Höhrmann's [Flexible and Economical UTF-8 Decoder](http://bjoern.hoehrmann.de/utf-8/decoder/dfa/) (included in fontstash.c). 71 | His code is licensed under the MIT license: 72 | 73 | Copyright (c) 2008-2009 Bjoern Hoehrmann 74 | 75 | Permission is hereby granted, free of charge, to any person obtaining a copy 76 | of this software and associated documentation files (the "Software"), to deal 77 | in the Software without restriction, including without limitation the rights 78 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 79 | copies of the Software, and to permit persons to whom the Software is 80 | furnished to do so, subject to the following conditions: 81 | 82 | The above copyright notice and this permission notice shall be included in 83 | all copies or substantial portions of the Software. 84 | 85 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 86 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 87 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 88 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 89 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 90 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 91 | THE SOFTWARE. 92 | 93 | Finally, Font Stash uses Sean Barrett's public domain truetype font rasterizer [stb_truetype.h](http://nothings.org/). 94 | 95 | -------------------------------------------------------------------------------- /main.c: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2011 Andreas Krinke andreas.krinke@gmx.de 3 | // Copyright (c) 2009 Mikko Mononen memon@inside.org 4 | // 5 | // This software is provided 'as-is', without any express or implied 6 | // warranty. In no event will the authors be held liable for any damages 7 | // arising from the use of this software. 8 | // Permission is granted to anyone to use this software for any purpose, 9 | // including commercial applications, and to alter it and redistribute it 10 | // freely, subject to the following restrictions: 11 | // 1. The origin of this software must not be misrepresented; you must not 12 | // claim that you wrote the original software. If you use this software 13 | // in a product, an acknowledgment in the product documentation would be 14 | // appreciated but is not required. 15 | // 2. Altered source versions must be plainly marked as such, and must not be 16 | // misrepresented as being the original software. 17 | // 3. This notice may not be removed or altered from any source distribution. 18 | // 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include "SDL.h" 25 | #include "SDL_image.h" 26 | 27 | #ifdef __MACOSX__ 28 | #include "SDL_Opengl.h" 29 | #else 30 | #include "SDL_opengl.h" 31 | #endif 32 | 33 | #include "fontstash.h" 34 | 35 | int main(int argc, char *argv[]) 36 | { 37 | int done; 38 | SDL_Event event; 39 | SDL_Surface* screen; 40 | int width, height; 41 | struct sth_stash* stash = 0; 42 | FILE* fp = 0; 43 | int datasize; 44 | unsigned char* data; 45 | float sx,sy,dx,dy,lh; 46 | int droidRegular, droidItalic, droidBold, droidJapanese, dejavu; 47 | SDL_Surface* surface; 48 | GLuint texture; 49 | 50 | if (SDL_Init(SDL_INIT_EVERYTHING) < 0) 51 | { 52 | fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError()); 53 | return -1; 54 | } 55 | 56 | 57 | 58 | // Init OpenGL 59 | SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); 60 | SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); 61 | SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); 62 | SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); 63 | SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); 64 | SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); 65 | 66 | width = 800; 67 | height = 600; 68 | screen = SDL_SetVideoMode(width, height, 0, SDL_OPENGL); 69 | if (!screen) 70 | { 71 | fprintf(stderr, "Could not initialise SDL opengl\n"); 72 | return -1; 73 | } 74 | 75 | SDL_WM_SetCaption("FontStash Demo", 0); 76 | 77 | stash = sth_create(512,512); 78 | if (!stash) 79 | { 80 | fprintf(stderr, "Could not create stash.\n"); 81 | return -1; 82 | } 83 | 84 | // Load the first truetype font from memory (just because we can). 85 | fp = fopen("DroidSerif-Regular.ttf", "rb"); 86 | if (!fp) goto error_add_font; 87 | fseek(fp, 0, SEEK_END); 88 | datasize = (int)ftell(fp); 89 | fseek(fp, 0, SEEK_SET); 90 | data = (unsigned char*)malloc(datasize); 91 | if (data == NULL) goto error_add_font; 92 | fread(data, 1, datasize, fp); 93 | fclose(fp); 94 | fp = 0; 95 | 96 | if (!(droidRegular = sth_add_font_from_memory(stash, data))) 97 | goto error_add_font; 98 | 99 | // Load the remaining truetype fonts directly. 100 | if (!(droidItalic = sth_add_font(stash,"DroidSerif-Italic.ttf"))) 101 | goto error_add_font; 102 | if (!(droidBold = sth_add_font(stash,"DroidSerif-Bold.ttf"))) 103 | goto error_add_font; 104 | if (!(droidJapanese = sth_add_font(stash,"DroidSansJapanese.ttf"))) 105 | goto error_add_font; 106 | 107 | // Load a bitmap font 108 | surface = IMG_Load("dejavu-sans_0.png"); 109 | if (surface == NULL) 110 | { 111 | fprintf(stderr, "%s.\n", IMG_GetError()); 112 | return -1; 113 | } 114 | glGenTextures(1, &texture); 115 | glBindTexture(GL_TEXTURE_2D, texture); 116 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); 117 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); 118 | if (SDL_MUSTLOCK(surface)) SDL_LockSurface(surface); 119 | glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA8, surface->w, surface->h, 0, GL_ALPHA, GL_UNSIGNED_BYTE, surface->pixels); 120 | if (SDL_MUSTLOCK(surface)) SDL_UnlockSurface(surface); 121 | SDL_FreeSurface(surface); 122 | dejavu = sth_add_bitmap_font(stash, 17, -4, 2); 123 | sth_add_glyph_for_char(stash, dejavu, texture, "T", 18, 14, 363, 331, 10, 11, 0, 3, 10); 124 | sth_add_glyph_for_char(stash, dejavu, texture, "h", 18, 14, 225, 382, 8, 11, 1, 3, 10); 125 | sth_add_glyph_for_char(stash, dejavu, texture, "i", 18, 14, 478, 377, 2, 11, 1, 3, 4); 126 | sth_add_glyph_for_char(stash, dejavu, texture, "s", 18, 14, 199, 455, 7, 8, 1, 6, 9); 127 | sth_add_glyph_for_char(stash, dejavu, texture, " ", 18, 14, 66, 185, 1, 1, 0, 14, 5); 128 | sth_add_glyph_for_char(stash, dejavu, texture, "a", 18, 14, 18, 459, 8, 8, 1, 6, 10); 129 | sth_add_glyph_for_char(stash, dejavu, texture, "b", 18, 14, 198, 383, 8, 11, 1, 3, 10); 130 | sth_add_glyph_for_char(stash, dejavu, texture, "t", 18, 14, 436, 377, 5, 11, 1, 3, 6); 131 | sth_add_glyph_for_char(stash, dejavu, texture, "m", 18, 14, 494, 429, 12, 8, 2, 6, 16); 132 | sth_add_glyph_for_char(stash, dejavu, texture, "p", 18, 14, 436, 353, 8, 11, 1, 6, 10); 133 | sth_add_glyph_for_char(stash, dejavu, texture, "f", 18, 14, 442, 377, 5, 11, 1, 3, 7); 134 | sth_add_glyph_for_char(stash, dejavu, texture, "o", 18, 14, 483, 438, 8, 8, 1, 6, 10); 135 | sth_add_glyph_for_char(stash, dejavu, texture, "n", 18, 14, 0, 459, 8, 8, 1, 6, 10); 136 | sth_add_glyph_for_char(stash, dejavu, texture, ".", 18, 14, 285, 476, 2, 3, 1, 11, 6); 137 | 138 | done = 0; 139 | while (!done) 140 | { 141 | while (SDL_PollEvent(&event)) 142 | { 143 | switch (event.type) 144 | { 145 | case SDL_MOUSEMOTION: 146 | break; 147 | case SDL_MOUSEBUTTONDOWN: 148 | break; 149 | case SDL_KEYDOWN: 150 | if (event.key.keysym.sym == SDLK_ESCAPE) 151 | done = 1; 152 | break; 153 | case SDL_QUIT: 154 | done = 1; 155 | break; 156 | default: 157 | break; 158 | } 159 | } 160 | 161 | // Update and render 162 | glViewport(0, 0, width, height); 163 | glClearColor(0.3f, 0.3f, 0.32f, 1.0f); 164 | glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); 165 | glEnable(GL_BLEND); 166 | glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); 167 | glDisable(GL_TEXTURE_2D); 168 | glMatrixMode(GL_PROJECTION); 169 | glLoadIdentity(); 170 | glOrtho(0,width,0,height,-1,1); 171 | glMatrixMode(GL_MODELVIEW); 172 | glLoadIdentity(); 173 | glDisable(GL_DEPTH_TEST); 174 | glColor4ub(255,255,255,255); 175 | glEnable(GL_BLEND); 176 | glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); 177 | 178 | sx = 100; sy = 250; 179 | 180 | sth_begin_draw(stash); 181 | 182 | dx = sx; dy = sy; 183 | sth_draw_text(stash, droidRegular, 24.0f, dx, dy, "The quick ", &dx); 184 | sth_draw_text(stash, droidItalic, 48.0f, dx, dy, "brown ", &dx); 185 | sth_draw_text(stash, droidRegular, 24.0f, dx, dy, "fox ", &dx); 186 | sth_vmetrics(stash, droidItalic, 24, NULL, NULL, &lh); 187 | dx = sx; 188 | dy -= lh*1.2f; 189 | sth_draw_text(stash, droidItalic, 24.0f, dx, dy, "jumps over ", &dx); 190 | sth_draw_text(stash, droidBold, 24.0f, dx, dy, "the lazy ", &dx); 191 | sth_draw_text(stash, droidRegular, 24.0f, dx, dy, "dog.", &dx); 192 | dx = sx; 193 | dy -= lh*1.2f; 194 | sth_draw_text(stash, droidRegular, 12.0f, dx, dy, "Now is the time for all good men to come to the aid of the party.", &dx); 195 | sth_vmetrics(stash, droidItalic, 12, NULL, NULL, &lh); 196 | dx = sx; 197 | dy -= lh*1.2f*2; 198 | sth_draw_text(stash, droidItalic, 18.0f, dx, dy, "Ég get etið gler án þess að meiða mig.", &dx); 199 | sth_vmetrics(stash, droidItalic, 18, NULL, NULL, &lh); 200 | dx = sx; 201 | dy -= lh*1.2f; 202 | sth_draw_text(stash, droidJapanese, 18.0f, dx, dy, "私はガラスを食べられます。それは私を傷つけません。", &dx); 203 | dx = sx; 204 | dy -= lh*1.2f*2; 205 | sth_draw_text(stash, dejavu, 18.0f, dx, dy, "This is a bitmap font.", &dx); 206 | 207 | sth_end_draw(stash); 208 | 209 | glEnable(GL_DEPTH_TEST); 210 | SDL_GL_SwapBuffers(); 211 | } 212 | 213 | sth_delete(stash); 214 | free(data); 215 | SDL_Quit(); 216 | return 0; 217 | 218 | error_add_font: 219 | fprintf(stderr, "Could not add font.\n"); 220 | return -1; 221 | } 222 | -------------------------------------------------------------------------------- /bin/NOTICE: -------------------------------------------------------------------------------- 1 | 2 | Copyright (c) 2005-2008, The Android Open Source Project 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | 13 | 14 | Apache License 15 | Version 2.0, January 2004 16 | http://www.apache.org/licenses/ 17 | 18 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 19 | 20 | 1. Definitions. 21 | 22 | "License" shall mean the terms and conditions for use, reproduction, 23 | and distribution as defined by Sections 1 through 9 of this document. 24 | 25 | "Licensor" shall mean the copyright owner or entity authorized by 26 | the copyright owner that is granting the License. 27 | 28 | "Legal Entity" shall mean the union of the acting entity and all 29 | other entities that control, are controlled by, or are under common 30 | control with that entity. For the purposes of this definition, 31 | "control" means (i) the power, direct or indirect, to cause the 32 | direction or management of such entity, whether by contract or 33 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 34 | outstanding shares, or (iii) beneficial ownership of such entity. 35 | 36 | "You" (or "Your") shall mean an individual or Legal Entity 37 | exercising permissions granted by this License. 38 | 39 | "Source" form shall mean the preferred form for making modifications, 40 | including but not limited to software source code, documentation 41 | source, and configuration files. 42 | 43 | "Object" form shall mean any form resulting from mechanical 44 | transformation or translation of a Source form, including but 45 | not limited to compiled object code, generated documentation, 46 | and conversions to other media types. 47 | 48 | "Work" shall mean the work of authorship, whether in Source or 49 | Object form, made available under the License, as indicated by a 50 | copyright notice that is included in or attached to the work 51 | (an example is provided in the Appendix below). 52 | 53 | "Derivative Works" shall mean any work, whether in Source or Object 54 | form, that is based on (or derived from) the Work and for which the 55 | editorial revisions, annotations, elaborations, or other modifications 56 | represent, as a whole, an original work of authorship. For the purposes 57 | of this License, Derivative Works shall not include works that remain 58 | separable from, or merely link (or bind by name) to the interfaces of, 59 | the Work and Derivative Works thereof. 60 | 61 | "Contribution" shall mean any work of authorship, including 62 | the original version of the Work and any modifications or additions 63 | to that Work or Derivative Works thereof, that is intentionally 64 | submitted to Licensor for inclusion in the Work by the copyright owner 65 | or by an individual or Legal Entity authorized to submit on behalf of 66 | the copyright owner. For the purposes of this definition, "submitted" 67 | means any form of electronic, verbal, or written communication sent 68 | to the Licensor or its representatives, including but not limited to 69 | communication on electronic mailing lists, source code control systems, 70 | and issue tracking systems that are managed by, or on behalf of, the 71 | Licensor for the purpose of discussing and improving the Work, but 72 | excluding communication that is conspicuously marked or otherwise 73 | designated in writing by the copyright owner as "Not a Contribution." 74 | 75 | "Contributor" shall mean Licensor and any individual or Legal Entity 76 | on behalf of whom a Contribution has been received by Licensor and 77 | subsequently incorporated within the Work. 78 | 79 | 2. Grant of Copyright License. Subject to the terms and conditions of 80 | this License, each Contributor hereby grants to You a perpetual, 81 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 82 | copyright license to reproduce, prepare Derivative Works of, 83 | publicly display, publicly perform, sublicense, and distribute the 84 | Work and such Derivative Works in Source or Object form. 85 | 86 | 3. Grant of Patent License. Subject to the terms and conditions of 87 | this License, each Contributor hereby grants to You a perpetual, 88 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 89 | (except as stated in this section) patent license to make, have made, 90 | use, offer to sell, sell, import, and otherwise transfer the Work, 91 | where such license applies only to those patent claims licensable 92 | by such Contributor that are necessarily infringed by their 93 | Contribution(s) alone or by combination of their Contribution(s) 94 | with the Work to which such Contribution(s) was submitted. If You 95 | institute patent litigation against any entity (including a 96 | cross-claim or counterclaim in a lawsuit) alleging that the Work 97 | or a Contribution incorporated within the Work constitutes direct 98 | or contributory patent infringement, then any patent licenses 99 | granted to You under this License for that Work shall terminate 100 | as of the date such litigation is filed. 101 | 102 | 4. Redistribution. You may reproduce and distribute copies of the 103 | Work or Derivative Works thereof in any medium, with or without 104 | modifications, and in Source or Object form, provided that You 105 | meet the following conditions: 106 | 107 | (a) You must give any other recipients of the Work or 108 | Derivative Works a copy of this License; and 109 | 110 | (b) You must cause any modified files to carry prominent notices 111 | stating that You changed the files; and 112 | 113 | (c) You must retain, in the Source form of any Derivative Works 114 | that You distribute, all copyright, patent, trademark, and 115 | attribution notices from the Source form of the Work, 116 | excluding those notices that do not pertain to any part of 117 | the Derivative Works; and 118 | 119 | (d) If the Work includes a "NOTICE" text file as part of its 120 | distribution, then any Derivative Works that You distribute must 121 | include a readable copy of the attribution notices contained 122 | within such NOTICE file, excluding those notices that do not 123 | pertain to any part of the Derivative Works, in at least one 124 | of the following places: within a NOTICE text file distributed 125 | as part of the Derivative Works; within the Source form or 126 | documentation, if provided along with the Derivative Works; or, 127 | within a display generated by the Derivative Works, if and 128 | wherever such third-party notices normally appear. The contents 129 | of the NOTICE file are for informational purposes only and 130 | do not modify the License. You may add Your own attribution 131 | notices within Derivative Works that You distribute, alongside 132 | or as an addendum to the NOTICE text from the Work, provided 133 | that such additional attribution notices cannot be construed 134 | as modifying the License. 135 | 136 | You may add Your own copyright statement to Your modifications and 137 | may provide additional or different license terms and conditions 138 | for use, reproduction, or distribution of Your modifications, or 139 | for any such Derivative Works as a whole, provided Your use, 140 | reproduction, and distribution of the Work otherwise complies with 141 | the conditions stated in this License. 142 | 143 | 5. Submission of Contributions. Unless You explicitly state otherwise, 144 | any Contribution intentionally submitted for inclusion in the Work 145 | by You to the Licensor shall be under the terms and conditions of 146 | this License, without any additional terms or conditions. 147 | Notwithstanding the above, nothing herein shall supersede or modify 148 | the terms of any separate license agreement you may have executed 149 | with Licensor regarding such Contributions. 150 | 151 | 6. Trademarks. This License does not grant permission to use the trade 152 | names, trademarks, service marks, or product names of the Licensor, 153 | except as required for reasonable and customary use in describing the 154 | origin of the Work and reproducing the content of the NOTICE file. 155 | 156 | 7. Disclaimer of Warranty. Unless required by applicable law or 157 | agreed to in writing, Licensor provides the Work (and each 158 | Contributor provides its Contributions) on an "AS IS" BASIS, 159 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 160 | implied, including, without limitation, any warranties or conditions 161 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 162 | PARTICULAR PURPOSE. You are solely responsible for determining the 163 | appropriateness of using or redistributing the Work and assume any 164 | risks associated with Your exercise of permissions under this License. 165 | 166 | 8. Limitation of Liability. In no event and under no legal theory, 167 | whether in tort (including negligence), contract, or otherwise, 168 | unless required by applicable law (such as deliberate and grossly 169 | negligent acts) or agreed to in writing, shall any Contributor be 170 | liable to You for damages, including any direct, indirect, special, 171 | incidental, or consequential damages of any character arising as a 172 | result of this License or out of the use or inability to use the 173 | Work (including but not limited to damages for loss of goodwill, 174 | work stoppage, computer failure or malfunction, or any and all 175 | other commercial damages or losses), even if such Contributor 176 | has been advised of the possibility of such damages. 177 | 178 | 9. Accepting Warranty or Additional Liability. While redistributing 179 | the Work or Derivative Works thereof, You may choose to offer, 180 | and charge a fee for, acceptance of support, warranty, indemnity, 181 | or other liability obligations and/or rights consistent with this 182 | License. However, in accepting such obligations, You may act only 183 | on Your own behalf and on Your sole responsibility, not on behalf 184 | of any other Contributor, and only if You agree to indemnify, 185 | defend, and hold each Contributor harmless for any liability 186 | incurred by, or claims asserted against, such Contributor by reason 187 | of your accepting any such warranty or additional liability. 188 | 189 | END OF TERMS AND CONDITIONS 190 | 191 | -------------------------------------------------------------------------------- /fontstash.c: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2011-2013 Andreas Krinke andreas.krinke@gmx.de 3 | // Copyright (c) 2009 Mikko Mononen memon@inside.org 4 | // 5 | // This software is provided 'as-is', without any express or implied 6 | // warranty. In no event will the authors be held liable for any damages 7 | // arising from the use of this software. 8 | // Permission is granted to anyone to use this software for any purpose, 9 | // including commercial applications, and to alter it and redistribute it 10 | // freely, subject to the following restrictions: 11 | // 1. The origin of this software must not be misrepresented; you must not 12 | // claim that you wrote the original software. If you use this software 13 | // in a product, an acknowledgment in the product documentation would be 14 | // appreciated but is not required. 15 | // 2. Altered source versions must be plainly marked as such, and must not be 16 | // misrepresented as being the original software. 17 | // 3. This notice may not be removed or altered from any source distribution. 18 | // 19 | 20 | #include 21 | #include 22 | #include 23 | #include /* @rlyeh: floorf() */ 24 | 25 | #include /* @rlyeh: before including GL. doesnt hurt and makes life better */ 26 | 27 | #ifdef __MACOSX__ 28 | #include 29 | #else 30 | #include 31 | #endif 32 | 33 | /* @rlyeh: removed STB_TRUETYPE_IMPLENTATION. We link it externally */ 34 | #include "stb_truetype.h" 35 | 36 | #include "fontstash.h" 37 | 38 | #define HASH_LUT_SIZE 256 39 | #define MAX_ROWS 128 40 | #define VERT_COUNT (6*128) 41 | #define VERT_STRIDE (sizeof(float)*4) 42 | 43 | #define TTFONT_FILE 1 44 | #define TTFONT_MEM 2 45 | #define BMFONT 3 46 | 47 | static int idx = 1; 48 | 49 | static unsigned int hashint(unsigned int a) 50 | { 51 | a += ~(a<<15); 52 | a ^= (a>>10); 53 | a += (a<<3); 54 | a ^= (a>>6); 55 | a += ~(a<<11); 56 | a ^= (a>>16); 57 | return a; 58 | } 59 | 60 | 61 | struct sth_quad 62 | { 63 | float x0,y0,s0,t0; 64 | float x1,y1,s1,t1; 65 | }; 66 | 67 | struct sth_row 68 | { 69 | short x,y,h; 70 | }; 71 | 72 | struct sth_glyph 73 | { 74 | unsigned int codepoint; 75 | short size; 76 | struct sth_texture* texture; 77 | int x0,y0,x1,y1; 78 | float xadv,xoff,yoff; 79 | int next; 80 | }; 81 | 82 | struct sth_font 83 | { 84 | int idx; 85 | int type; 86 | stbtt_fontinfo font; 87 | unsigned char* data; 88 | struct sth_glyph* glyphs; 89 | int lut[HASH_LUT_SIZE]; 90 | int nglyphs; 91 | float ascender; 92 | float descender; 93 | float lineh; 94 | struct sth_font* next; 95 | }; 96 | 97 | struct sth_texture 98 | { 99 | GLuint id; 100 | // TODO: replace rows with pointer 101 | struct sth_row rows[MAX_ROWS]; 102 | int nrows; 103 | float verts[4*VERT_COUNT]; 104 | int nverts; 105 | struct sth_texture* next; 106 | }; 107 | 108 | struct sth_stash 109 | { 110 | int tw,th; 111 | float itw,ith; 112 | GLubyte *empty_data; 113 | struct sth_texture* tt_textures; 114 | struct sth_texture* bm_textures; 115 | struct sth_font* fonts; 116 | int drawing; 117 | }; 118 | 119 | 120 | 121 | // Copyright (c) 2008-2009 Bjoern Hoehrmann 122 | // See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details. 123 | 124 | #define UTF8_ACCEPT 0 125 | #define UTF8_REJECT 1 126 | 127 | static const unsigned char utf8d[] = { 128 | 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 00..1f 129 | 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 20..3f 130 | 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 40..5f 131 | 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 60..7f 132 | 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, // 80..9f 133 | 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, // a0..bf 134 | 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // c0..df 135 | 0xa,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x4,0x3,0x3, // e0..ef 136 | 0xb,0x6,0x6,0x6,0x5,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8, // f0..ff 137 | 0x0,0x1,0x2,0x3,0x5,0x8,0x7,0x1,0x1,0x1,0x4,0x6,0x1,0x1,0x1,0x1, // s0..s0 138 | 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,1, // s1..s2 139 | 1,2,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1, // s3..s4 140 | 1,2,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,3,1,3,1,1,1,1,1,1, // s5..s6 141 | 1,3,1,1,1,1,1,3,1,3,1,1,1,1,1,1,1,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // s7..s8 142 | }; 143 | 144 | static unsigned int decutf8(unsigned int* state, unsigned int* codep, unsigned int byte) 145 | { 146 | unsigned int type = utf8d[byte]; 147 | *codep = (*state != UTF8_ACCEPT) ? 148 | (byte & 0x3fu) | (*codep << 6) : 149 | (0xff >> type) & (byte); 150 | *state = utf8d[256 + *state*16 + type]; 151 | return *state; 152 | } 153 | 154 | 155 | 156 | struct sth_stash* sth_create(int cachew, int cacheh) 157 | { 158 | struct sth_stash* stash = NULL; 159 | GLubyte* empty_data = NULL; 160 | struct sth_texture* texture = NULL; 161 | 162 | // Allocate memory for the font stash. 163 | stash = (struct sth_stash*)malloc(sizeof(struct sth_stash)); 164 | if (stash == NULL) goto error; 165 | memset(stash,0,sizeof(struct sth_stash)); 166 | 167 | // Create data for clearing the textures 168 | empty_data = malloc(cachew * cacheh); 169 | if (empty_data == NULL) goto error; 170 | memset(empty_data, 0, cachew * cacheh); 171 | 172 | // Allocate memory for the first texture 173 | texture = (struct sth_texture*)malloc(sizeof(struct sth_texture)); 174 | if (texture == NULL) goto error; 175 | memset(texture,0,sizeof(struct sth_texture)); 176 | 177 | // Create first texture for the cache. 178 | stash->tw = cachew; 179 | stash->th = cacheh; 180 | stash->itw = 1.0f/cachew; 181 | stash->ith = 1.0f/cacheh; 182 | stash->empty_data = empty_data; 183 | stash->tt_textures = texture; 184 | glGenTextures(1, &texture->id); 185 | if (!texture->id) goto error; 186 | glBindTexture(GL_TEXTURE_2D, texture->id); 187 | glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, cachew, cacheh, 0, GL_ALPHA, GL_UNSIGNED_BYTE, empty_data); 188 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 189 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 190 | 191 | return stash; 192 | 193 | error: 194 | if (stash != NULL) 195 | free(stash); 196 | if (empty_data != NULL) 197 | free(empty_data); 198 | if (texture != NULL) 199 | free(texture); 200 | return NULL; 201 | } 202 | 203 | int sth_add_font_from_memory(struct sth_stash* stash, unsigned char* buffer) 204 | { 205 | int ret, i, ascent, descent, fh, lineGap; 206 | struct sth_font* fnt = NULL; 207 | 208 | fnt = (struct sth_font*)malloc(sizeof(struct sth_font)); 209 | if (fnt == NULL) 210 | { 211 | ret = STH_ENOMEM; 212 | goto error; 213 | } 214 | memset(fnt,0,sizeof(struct sth_font)); 215 | 216 | // Init hash lookup. 217 | for (i = 0; i < HASH_LUT_SIZE; ++i) fnt->lut[i] = -1; 218 | 219 | fnt->data = buffer; 220 | 221 | // Init stb_truetype 222 | if (!stbtt_InitFont(&fnt->font, fnt->data, 0)) 223 | { 224 | ret = STH_ETTFINIT; 225 | goto error; 226 | } 227 | 228 | // Store normalized line height. The real line height is got 229 | // by multiplying the lineh by font size. 230 | stbtt_GetFontVMetrics(&fnt->font, &ascent, &descent, &lineGap); 231 | fh = ascent - descent; 232 | fnt->ascender = (float)ascent / (float)fh; 233 | fnt->descender = (float)descent / (float)fh; 234 | fnt->lineh = (float)(fh + lineGap) / (float)fh; 235 | 236 | fnt->idx = idx; 237 | fnt->type = TTFONT_MEM; 238 | fnt->next = stash->fonts; 239 | stash->fonts = fnt; 240 | 241 | return idx++; 242 | 243 | error: 244 | if (fnt) { 245 | if (fnt->glyphs) free(fnt->glyphs); 246 | free(fnt); 247 | } 248 | return ret; 249 | } 250 | 251 | int sth_add_font(struct sth_stash* stash, const char* path) 252 | { 253 | FILE* fp = 0; 254 | int ret, datasize; 255 | unsigned char* data = NULL; 256 | int idx; 257 | 258 | // Read in the font data. 259 | fp = fopen(path, "rb"); 260 | if (!fp) 261 | { 262 | ret = STH_EFILEIO; 263 | goto error; 264 | } 265 | fseek(fp,0,SEEK_END); 266 | datasize = (int)ftell(fp); 267 | fseek(fp,0,SEEK_SET); 268 | data = (unsigned char*)malloc(datasize); 269 | if (data == NULL) 270 | { 271 | ret = STH_ENOMEM; 272 | goto error; 273 | } 274 | fread(data, 1, datasize, fp); 275 | fclose(fp); 276 | fp = 0; 277 | 278 | idx = sth_add_font_from_memory(stash, data); 279 | // Modify type of the loaded font. 280 | if (idx) 281 | stash->fonts->type = TTFONT_FILE; 282 | else 283 | free(data); 284 | 285 | return idx; 286 | 287 | error: 288 | if (data) free(data); 289 | if (fp) fclose(fp); 290 | return ret; 291 | } 292 | 293 | int sth_add_bitmap_font(struct sth_stash* stash, int ascent, int descent, int line_gap) 294 | { 295 | int ret, i, fh; 296 | struct sth_font* fnt = NULL; 297 | 298 | fnt = (struct sth_font*)malloc(sizeof(struct sth_font)); 299 | if (fnt == NULL) 300 | { 301 | ret = STH_ENOMEM; 302 | goto error; 303 | } 304 | memset(fnt,0,sizeof(struct sth_font)); 305 | 306 | // Init hash lookup. 307 | for (i = 0; i < HASH_LUT_SIZE; ++i) fnt->lut[i] = -1; 308 | 309 | // Store normalized line height. The real line height is got 310 | // by multiplying the lineh by font size. 311 | fh = ascent - descent; 312 | fnt->ascender = (float)ascent / (float)fh; 313 | fnt->descender = (float)descent / (float)fh; 314 | fnt->lineh = (float)(fh + line_gap) / (float)fh; 315 | 316 | fnt->idx = idx; 317 | fnt->type = BMFONT; 318 | fnt->next = stash->fonts; 319 | stash->fonts = fnt; 320 | 321 | return idx++; 322 | 323 | error: 324 | if (fnt) free(fnt); 325 | return ret; 326 | } 327 | 328 | int sth_add_glyph_for_codepoint(struct sth_stash* stash, 329 | int idx, 330 | GLuint id, 331 | unsigned int codepoint, 332 | short size, short base, 333 | int x, int y, int w, int h, 334 | float xoffset, float yoffset, float xadvance) 335 | { 336 | struct sth_texture* texture = NULL; 337 | struct sth_font* fnt = NULL; 338 | struct sth_glyph* glyph = NULL; 339 | 340 | if (stash == NULL) 341 | return STH_EINVAL; 342 | texture = stash->bm_textures; 343 | while (texture != NULL && texture->id != id) texture = texture->next; 344 | if (texture == NULL) 345 | { 346 | // Create new texture 347 | texture = (struct sth_texture*)malloc(sizeof(struct sth_texture)); 348 | if (texture == NULL) 349 | return STH_ENOMEM; 350 | memset(texture, 0, sizeof(struct sth_texture)); 351 | texture->id = id; 352 | texture->next = stash->bm_textures; 353 | stash->bm_textures = texture; 354 | } 355 | 356 | fnt = stash->fonts; 357 | while (fnt != NULL && fnt->idx != idx) fnt = fnt->next; 358 | if (fnt == NULL) 359 | return STH_EINVAL; 360 | if (fnt->type != BMFONT) 361 | return STH_EINVAL; 362 | 363 | // Alloc space for new glyph. 364 | fnt->nglyphs++; 365 | fnt->glyphs = (struct sth_glyph *)realloc(fnt->glyphs, fnt->nglyphs*sizeof(struct sth_glyph)); /* @rlyeh: explicit cast needed in C++ */ 366 | if (!fnt->glyphs) 367 | return STH_ENOMEM; 368 | 369 | // Init glyph. 370 | glyph = &fnt->glyphs[fnt->nglyphs-1]; 371 | memset(glyph, 0, sizeof(struct sth_glyph)); 372 | glyph->codepoint = codepoint; 373 | glyph->size = size; 374 | glyph->texture = texture; 375 | glyph->x0 = x; 376 | glyph->y0 = y; 377 | glyph->x1 = glyph->x0+w; 378 | glyph->y1 = glyph->y0+h; 379 | glyph->xoff = xoffset; 380 | glyph->yoff = yoffset - base; 381 | glyph->xadv = xadvance; 382 | 383 | // Find code point and size. 384 | h = hashint(codepoint) & (HASH_LUT_SIZE-1); 385 | // Insert char to hash lookup. 386 | glyph->next = fnt->lut[h]; 387 | fnt->lut[h] = fnt->nglyphs-1; 388 | 389 | return STH_ESUCCESS; 390 | } 391 | 392 | inline int sth_add_glyph_for_char(struct sth_stash* stash, 393 | int idx, 394 | GLuint id, 395 | const char* s, 396 | short size, short base, 397 | int x, int y, int w, int h, 398 | float xoffset, float yoffset, float xadvance) 399 | { 400 | unsigned int codepoint; 401 | unsigned int state = 0; 402 | 403 | for (; *s; ++s) 404 | { 405 | if (!decutf8(&state, &codepoint, *(unsigned char*)s)) 406 | break; 407 | } 408 | if (state != UTF8_ACCEPT) 409 | return STH_EINVAL; 410 | 411 | return sth_add_glyph_for_codepoint(stash, idx, id, codepoint, size, base, x, y, w, h, xoffset, yoffset, xadvance); 412 | } 413 | 414 | static struct sth_glyph* get_glyph(struct sth_stash* stash, struct sth_font* fnt, unsigned int codepoint, short isize) 415 | { 416 | int i,g,advance,lsb,x0,y0,x1,y1,gw,gh; 417 | float scale; 418 | struct sth_texture* texture = NULL; 419 | struct sth_glyph* glyph = NULL; 420 | unsigned char* bmp = NULL; 421 | unsigned int h; 422 | float size = isize/10.0f; 423 | int rh; 424 | struct sth_row* br = NULL; 425 | 426 | // Find code point and size. 427 | h = hashint(codepoint) & (HASH_LUT_SIZE-1); 428 | i = fnt->lut[h]; 429 | while (i != -1) 430 | { 431 | if (fnt->glyphs[i].codepoint == codepoint && (fnt->type == BMFONT || fnt->glyphs[i].size == isize)) 432 | return &fnt->glyphs[i]; 433 | i = fnt->glyphs[i].next; 434 | } 435 | // Could not find glyph. 436 | 437 | // For bitmap fonts: ignore this glyph. 438 | if (fnt->type == BMFONT) 439 | return 0; 440 | 441 | // For truetype fonts: create this glyph. 442 | scale = stbtt_ScaleForPixelHeight(&fnt->font, size); 443 | g = stbtt_FindGlyphIndex(&fnt->font, codepoint); 444 | if(!g) 445 | return 0; /* @rlyeh: glyph not found, ie, arab chars */ 446 | stbtt_GetGlyphHMetrics(&fnt->font, g, &advance, &lsb); 447 | stbtt_GetGlyphBitmapBox(&fnt->font, g, scale,scale, &x0,&y0,&x1,&y1); 448 | gw = x1-x0; 449 | gh = y1-y0; 450 | 451 | // Check if glyph is larger than maximum texture size 452 | if (gw >= stash->tw || gh >= stash->th) 453 | return 0; 454 | 455 | // Find texture and row where the glyph can be fit. 456 | br = NULL; 457 | rh = (gh+7) & ~7; 458 | texture = stash->tt_textures; 459 | while(br == NULL) 460 | { 461 | for (i = 0; i < texture->nrows; ++i) 462 | { 463 | if (texture->rows[i].h == rh && texture->rows[i].x+gw+1 <= stash->tw) 464 | br = &texture->rows[i]; 465 | } 466 | 467 | // If no row is found, there are 3 possibilities: 468 | // - add new row 469 | // - try next texture 470 | // - create new texture 471 | if (br == NULL) 472 | { 473 | short py = 0; 474 | // Check that there is enough space. 475 | if (texture->nrows) 476 | { 477 | py = texture->rows[texture->nrows-1].y + texture->rows[texture->nrows-1].h+1; 478 | if (py+rh > stash->th) 479 | { 480 | if (texture->next != NULL) 481 | { 482 | texture = texture->next; 483 | } 484 | else 485 | { 486 | // Create new texture 487 | texture->next = (struct sth_texture*)malloc(sizeof(struct sth_texture)); 488 | texture = texture->next; 489 | if (texture == NULL) goto error; 490 | memset(texture,0,sizeof(struct sth_texture)); 491 | glGenTextures(1, &texture->id); 492 | if (!texture->id) goto error; 493 | glBindTexture(GL_TEXTURE_2D, texture->id); 494 | glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, stash->tw,stash->th, 0, GL_ALPHA, GL_UNSIGNED_BYTE, stash->empty_data); 495 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 496 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 497 | } 498 | continue; 499 | } 500 | } 501 | // Init and add row 502 | br = &texture->rows[texture->nrows]; 503 | br->x = 0; 504 | br->y = py; 505 | br->h = rh; 506 | texture->nrows++; 507 | } 508 | } 509 | 510 | // Alloc space for new glyph. 511 | fnt->nglyphs++; 512 | fnt->glyphs = (struct sth_glyph *)realloc(fnt->glyphs, fnt->nglyphs*sizeof(struct sth_glyph)); /* @rlyeh: explicit cast needed in C++ */ 513 | if (!fnt->glyphs) 514 | return 0; 515 | 516 | // Init glyph. 517 | glyph = &fnt->glyphs[fnt->nglyphs-1]; 518 | memset(glyph, 0, sizeof(struct sth_glyph)); 519 | glyph->codepoint = codepoint; 520 | glyph->size = isize; 521 | glyph->texture = texture; 522 | glyph->x0 = br->x; 523 | glyph->y0 = br->y; 524 | glyph->x1 = glyph->x0+gw; 525 | glyph->y1 = glyph->y0+gh; 526 | glyph->xadv = scale * advance; 527 | glyph->xoff = (float)x0; 528 | glyph->yoff = (float)y0; 529 | glyph->next = 0; 530 | 531 | // Advance row location. 532 | br->x += gw+1; 533 | 534 | // Insert char to hash lookup. 535 | glyph->next = fnt->lut[h]; 536 | fnt->lut[h] = fnt->nglyphs-1; 537 | 538 | // Rasterize 539 | bmp = (unsigned char*)malloc(gw*gh); 540 | if (bmp) 541 | { 542 | stbtt_MakeGlyphBitmap(&fnt->font, bmp, gw,gh,gw, scale,scale, g); 543 | // Update texture 544 | glBindTexture(GL_TEXTURE_2D, texture->id); 545 | glPixelStorei(GL_UNPACK_ALIGNMENT,1); 546 | glTexSubImage2D(GL_TEXTURE_2D, 0, glyph->x0,glyph->y0, gw,gh, GL_ALPHA,GL_UNSIGNED_BYTE,bmp); 547 | free(bmp); 548 | } 549 | 550 | return glyph; 551 | 552 | error: 553 | if (texture) 554 | free(texture); 555 | return 0; 556 | } 557 | 558 | static int get_quad(struct sth_stash* stash, struct sth_font* fnt, struct sth_glyph* glyph, short isize, float* x, float* y, struct sth_quad* q) 559 | { 560 | int rx,ry; 561 | float scale = 1.0f; 562 | 563 | if (fnt->type == BMFONT) scale = isize/(glyph->size*10.0f); 564 | 565 | rx = floorf(*x + scale * glyph->xoff); 566 | ry = floorf(*y - scale * glyph->yoff); 567 | 568 | q->x0 = rx; 569 | q->y0 = ry; 570 | q->x1 = rx + scale * (glyph->x1 - glyph->x0); 571 | q->y1 = ry - scale * (glyph->y1 - glyph->y0); 572 | 573 | q->s0 = (glyph->x0) * stash->itw; 574 | q->t0 = (glyph->y0) * stash->ith; 575 | q->s1 = (glyph->x1) * stash->itw; 576 | q->t1 = (glyph->y1) * stash->ith; 577 | 578 | *x += scale * glyph->xadv; 579 | 580 | return 1; 581 | } 582 | 583 | static float* setv(float* v, float x, float y, float s, float t) 584 | { 585 | v[0] = x; 586 | v[1] = y; 587 | v[2] = s; 588 | v[3] = t; 589 | return v+4; 590 | } 591 | 592 | static void flush_draw(struct sth_stash* stash) 593 | { 594 | struct sth_texture* texture = stash->tt_textures; 595 | short tt = 1; 596 | while (texture) 597 | { 598 | if (texture->nverts > 0) 599 | { 600 | glBindTexture(GL_TEXTURE_2D, texture->id); 601 | glEnable(GL_TEXTURE_2D); 602 | glEnableClientState(GL_VERTEX_ARRAY); 603 | glEnableClientState(GL_TEXTURE_COORD_ARRAY); 604 | glVertexPointer(2, GL_FLOAT, VERT_STRIDE, texture->verts); 605 | glTexCoordPointer(2, GL_FLOAT, VERT_STRIDE, texture->verts+2); 606 | glDrawArrays(GL_QUADS, 0, texture->nverts); 607 | glDisable(GL_TEXTURE_2D); 608 | glDisableClientState(GL_VERTEX_ARRAY); 609 | glDisableClientState(GL_TEXTURE_COORD_ARRAY); 610 | texture->nverts = 0; 611 | } 612 | texture = texture->next; 613 | if (!texture && tt) 614 | { 615 | texture = stash->bm_textures; 616 | tt = 0; 617 | } 618 | } 619 | } 620 | 621 | void sth_begin_draw(struct sth_stash* stash) 622 | { 623 | if (stash == NULL) 624 | return; 625 | if (stash->drawing) 626 | flush_draw(stash); 627 | stash->drawing = 1; 628 | } 629 | 630 | void sth_end_draw(struct sth_stash* stash) 631 | { 632 | if (stash == NULL) 633 | return; 634 | if (!stash->drawing) 635 | return; 636 | 637 | /* 638 | // Debug dump. 639 | if (stash->nverts+6 < VERT_COUNT) 640 | { 641 | float x = 500, y = 100; 642 | float* v = &stash->verts[stash->nverts*4]; 643 | 644 | v = setv(v, x, y, 0, 0); 645 | v = setv(v, x+stash->tw, y, 1, 0); 646 | v = setv(v, x+stash->tw, y+stash->th, 1, 1); 647 | 648 | v = setv(v, x, y, 0, 0); 649 | v = setv(v, x+stash->tw, y+stash->th, 1, 1); 650 | v = setv(v, x, y+stash->th, 0, 1); 651 | 652 | stash->nverts += 6; 653 | } 654 | */ 655 | 656 | flush_draw(stash); 657 | stash->drawing = 0; 658 | } 659 | 660 | void sth_draw_text(struct sth_stash* stash, 661 | int idx, float size, 662 | float x, float y, 663 | const char* s, float* dx) 664 | { 665 | unsigned int codepoint; 666 | struct sth_glyph* glyph = NULL; 667 | struct sth_texture* texture = NULL; 668 | unsigned int state = 0; 669 | struct sth_quad q; 670 | short isize = (short)(size*10.0f); 671 | float* v; 672 | struct sth_font* fnt = NULL; 673 | 674 | if (stash == NULL) 675 | return; 676 | 677 | fnt = stash->fonts; 678 | while(fnt != NULL && fnt->idx != idx) fnt = fnt->next; 679 | if (fnt == NULL) 680 | return; 681 | if (fnt->type != BMFONT && !fnt->data) 682 | return; 683 | 684 | for (; *s; ++s) 685 | { 686 | if (decutf8(&state, &codepoint, *(unsigned char*)s)) 687 | continue; 688 | glyph = get_glyph(stash, fnt, codepoint, isize); 689 | if (!glyph) 690 | continue; 691 | texture = glyph->texture; 692 | if (texture->nverts+4 >= VERT_COUNT) 693 | flush_draw(stash); 694 | 695 | if (!get_quad(stash, fnt, glyph, isize, &x, &y, &q)) 696 | continue; 697 | 698 | v = &texture->verts[texture->nverts*4]; 699 | 700 | v = setv(v, q.x0, q.y0, q.s0, q.t0); 701 | v = setv(v, q.x1, q.y0, q.s1, q.t0); 702 | v = setv(v, q.x1, q.y1, q.s1, q.t1); 703 | v = setv(v, q.x0, q.y1, q.s0, q.t1); 704 | 705 | texture->nverts += 4; 706 | } 707 | 708 | if (dx) *dx = x; 709 | } 710 | 711 | void sth_dim_text(struct sth_stash* stash, 712 | int idx, float size, 713 | const char* s, 714 | float* minx, float* miny, float* maxx, float* maxy) 715 | { 716 | unsigned int codepoint; 717 | struct sth_glyph* glyph = NULL; 718 | unsigned int state = 0; 719 | struct sth_quad q; 720 | short isize = (short)(size*10.0f); 721 | struct sth_font* fnt = NULL; 722 | float x = 0, y = 0; 723 | 724 | *minx = *maxx = *miny = *maxy = 0; /* @rlyeh: reset vars before failing */ 725 | 726 | if (stash == NULL) 727 | return; 728 | fnt = stash->fonts; 729 | while(fnt != NULL && fnt->idx != idx) 730 | fnt = fnt->next; 731 | if (fnt == NULL) 732 | return; 733 | if (fnt->type != BMFONT && !fnt->data) 734 | return; 735 | 736 | for (; *s; ++s) 737 | { 738 | if (decutf8(&state, &codepoint, *(unsigned char*)s)) 739 | continue; 740 | glyph = get_glyph(stash, fnt, codepoint, isize); 741 | if (!glyph) 742 | continue; 743 | if (!get_quad(stash, fnt, glyph, isize, &x, &y, &q)) 744 | continue; 745 | if (q.x0 < *minx) *minx = q.x0; 746 | if (q.x1 > *maxx) *maxx = q.x1; 747 | if (q.y1 < *miny) *miny = q.y1; 748 | if (q.y0 > *maxy) *maxy = q.y0; 749 | } 750 | if (floorf(x) > *maxx) *maxx = floorf(x); 751 | } 752 | 753 | void sth_vmetrics(struct sth_stash* stash, 754 | int idx, float size, 755 | float* ascender, float* descender, float* lineh) 756 | { 757 | struct sth_font* fnt = NULL; 758 | 759 | if (stash == NULL) 760 | return; 761 | fnt = stash->fonts; 762 | while(fnt != NULL && fnt->idx != idx) fnt = fnt->next; 763 | if (fnt == NULL) 764 | return; 765 | if (fnt->type != BMFONT && !fnt->data) 766 | return; 767 | if (ascender) 768 | *ascender = fnt->ascender*size; 769 | if (descender) 770 | *descender = fnt->descender*size; 771 | if (lineh) 772 | *lineh = fnt->lineh*size; 773 | } 774 | 775 | void sth_delete(struct sth_stash* stash) 776 | { 777 | struct sth_texture* tex = NULL; 778 | struct sth_texture* curtex = NULL; 779 | struct sth_font* fnt = NULL; 780 | struct sth_font* curfnt = NULL; 781 | 782 | if (!stash) 783 | return; 784 | 785 | tex = stash->tt_textures; 786 | while(tex != NULL) { 787 | curtex = tex; 788 | tex = tex->next; 789 | if (curtex->id) 790 | glDeleteTextures(1, &curtex->id); 791 | free(curtex); 792 | } 793 | 794 | tex = stash->bm_textures; 795 | while(tex != NULL) { 796 | curtex = tex; 797 | tex = tex->next; 798 | if (curtex->id) 799 | glDeleteTextures(1, &curtex->id); 800 | free(curtex); 801 | } 802 | 803 | fnt = stash->fonts; 804 | while(fnt != NULL) { 805 | curfnt = fnt; 806 | fnt = fnt->next; 807 | if (curfnt->glyphs) 808 | free(curfnt->glyphs); 809 | if (curfnt->type == TTFONT_FILE && curfnt->data) 810 | free(curfnt->data); 811 | free(curfnt); 812 | } 813 | free(stash->empty_data); 814 | free(stash); 815 | } 816 | -------------------------------------------------------------------------------- /stb_truetype.h: -------------------------------------------------------------------------------- 1 | // stb_truetype.h - v0.6c - public domain 2 | // authored from 2009-2012 by Sean Barrett / RAD Game Tools 3 | // 4 | // This library processes TrueType files: 5 | // parse files 6 | // extract glyph metrics 7 | // extract glyph shapes 8 | // render glyphs to one-channel bitmaps with antialiasing (box filter) 9 | // 10 | // Todo: 11 | // non-MS cmaps 12 | // crashproof on bad data 13 | // hinting? (no longer patented) 14 | // cleartype-style AA? 15 | // optimize: use simple memory allocator for intermediates 16 | // optimize: build edge-list directly from curves 17 | // optimize: rasterize directly from curves? 18 | // 19 | // ADDITIONAL CONTRIBUTORS 20 | // 21 | // Mikko Mononen: compound shape support, more cmap formats 22 | // Tor Andersson: kerning, subpixel rendering 23 | // 24 | // Bug/warning reports: 25 | // "Zer" on mollyrocket (with fix) 26 | // Cass Everitt 27 | // stoiko (Haemimont Games) 28 | // Brian Hook 29 | // Walter van Niftrik 30 | // 31 | // VERSION HISTORY 32 | // 33 | // 0.6c (2012-07-24) improve documentation 34 | // 0.6b (2012-07-20) fix a few more warnings 35 | // 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels, 36 | // stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty 37 | // 0.5 (2011-12-09) bugfixes: 38 | // subpixel glyph renderer computed wrong bounding box 39 | // first vertex of shape can be off-curve (FreeSans) 40 | // 0.4b (2011-12-03) fixed an error in the font baking example 41 | // 0.4 (2011-12-01) kerning, subpixel rendering (tor) 42 | // bugfixes for: 43 | // codepoint-to-glyph conversion using table fmt=12 44 | // codepoint-to-glyph conversion using table fmt=4 45 | // stbtt_GetBakedQuad with non-square texture (Zer) 46 | // updated Hello World! sample to use kerning and subpixel 47 | // fixed some warnings 48 | // 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM) 49 | // userdata, malloc-from-userdata, non-zero fill (STB) 50 | // 0.2 (2009-03-11) Fix unsigned/signed char warnings 51 | // 0.1 (2009-03-09) First public release 52 | // 53 | // LICENSE 54 | // 55 | // This software is in the public domain. Where that dedication is not 56 | // recognized, you are granted a perpetual, irrevokable license to copy 57 | // and modify this file as you see fit. 58 | // 59 | // USAGE 60 | // 61 | // Include this file in whatever places neeed to refer to it. In ONE C/C++ 62 | // file, write: 63 | // #define STB_TRUETYPE_IMPLEMENTATION 64 | // before the #include of this file. This expands out the actual 65 | // implementation into that C/C++ file. 66 | // 67 | // Simple 3D API (don't ship this, but it's fine for tools and quick start, 68 | // and you can cut and paste from it to move to more advanced) 69 | // stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture 70 | // stbtt_GetBakedQuad() -- compute quad to draw for a given char 71 | // 72 | // "Load" a font file from a memory buffer (you have to keep the buffer loaded) 73 | // stbtt_InitFont() 74 | // stbtt_GetFontOffsetForIndex() -- use for TTC font collections 75 | // 76 | // Render a unicode codepoint to a bitmap 77 | // stbtt_GetCodepointBitmap() -- allocates and returns a bitmap 78 | // stbtt_MakeCodepointBitmap() -- renders into bitmap you provide 79 | // stbtt_GetCodepointBitmapBox() -- how big the bitmap must be 80 | // 81 | // Character advance/positioning 82 | // stbtt_GetCodepointHMetrics() 83 | // stbtt_GetFontVMetrics() 84 | // stbtt_GetCodepointKernAdvance() 85 | // 86 | // ADDITIONAL DOCUMENTATION 87 | // 88 | // Immediately after this block comment are a series of sample programs. 89 | // 90 | // After the sample programs is the "header file" section. This section 91 | // includes documentation for each API function. 92 | // 93 | // Some important concepts to understand to use this library: 94 | // 95 | // Codepoint 96 | // Characters are defined by unicode codepoints, e.g. 65 is 97 | // uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is 98 | // the hiragana for "ma". 99 | // 100 | // Glyph 101 | // A visual character shape (every codepoint is rendered as 102 | // some glyph) 103 | // 104 | // Glyph index 105 | // A font-specific integer ID representing a glyph 106 | // 107 | // Baseline 108 | // Glyph shapes are defined relative to a baseline, which is the 109 | // bottom of uppercase characters. Characters extend both above 110 | // and below the baseline. 111 | // 112 | // Current Point 113 | // As you draw text to the screen, you keep track of a "current point" 114 | // which is the origin of each character. The current point's vertical 115 | // position is the baseline. Even "baked fonts" use this model. 116 | // 117 | // Vertical Font Metrics 118 | // The vertical qualities of the font, used to vertically position 119 | // and space the characters. See docs for stbtt_GetFontVMetrics. 120 | // 121 | // Font Size in Pixels or Points 122 | // The preferred interface for specifying font sizes in stb_truetype 123 | // is to specify how tall the font's vertical extent should be in pixels. 124 | // If that sounds good enough, skip the next paragraph. 125 | // 126 | // Most font APIs instead use "points", which are a common typographic 127 | // measurement for describing font size, defined as 72 points per inch. 128 | // stb_truetype provides a point API for compatibility. However, true 129 | // "per inch" conventions don't make much sense on computer displays 130 | // since they different monitors have different number of pixels per 131 | // inch. For example, Windows traditionally uses a convention that 132 | // there are 96 pixels per inch, thus making 'inch' measurements have 133 | // nothing to do with inches, and thus effectively defining a point to 134 | // be 1.333 pixels. Additionally, the TrueType font data provides 135 | // an explicit scale factor to scale a given font's glyphs to points, 136 | // but the author has observed that this scale factor is often wrong 137 | // for non-commercial fonts, thus making fonts scaled in points 138 | // according to the TrueType spec incoherently sized in practice. 139 | // 140 | // ADVANCED USAGE 141 | // 142 | // Quality: 143 | // 144 | // - Use the functions with Subpixel at the end to allow your characters 145 | // to have subpixel positioning. Since the font is anti-aliased, not 146 | // hinted, this is very import for quality. (This is not possible with 147 | // baked fonts.) 148 | // 149 | // - Kerning is now supported, and if you're supporting subpixel rendering 150 | // then kerning is worth using to give your text a polished look. 151 | // 152 | // Performance: 153 | // 154 | // - Convert Unicode codepoints to glyph indexes and operate on the glyphs; 155 | // if you don't do this, stb_truetype is forced to do the conversion on 156 | // every call. 157 | // 158 | // - There are a lot of memory allocations. We should modify it to take 159 | // a temp buffer and allocate from the temp buffer (without freeing), 160 | // should help performance a lot. 161 | // 162 | // NOTES 163 | // 164 | // The system uses the raw data found in the .ttf file without changing it 165 | // and without building auxiliary data structures. This is a bit inefficient 166 | // on little-endian systems (the data is big-endian), but assuming you're 167 | // caching the bitmaps or glyph shapes this shouldn't be a big deal. 168 | // 169 | // It appears to be very hard to programmatically determine what font a 170 | // given file is in a general way. I provide an API for this, but I don't 171 | // recommend it. 172 | // 173 | // 174 | // SOURCE STATISTICS (based on v0.6c, 2050 LOC) 175 | // 176 | // Documentation & header file 520 LOC \___ 660 LOC documentation 177 | // Sample code 140 LOC / 178 | // Truetype parsing 620 LOC ---- 620 LOC TrueType 179 | // Software rasterization 240 LOC \ . 180 | // Curve tesselation 120 LOC \__ 550 LOC Bitmap creation 181 | // Bitmap management 100 LOC / 182 | // Baked bitmap interface 70 LOC / 183 | // Font name matching & access 150 LOC ---- 150 184 | // C runtime library abstraction 60 LOC ---- 60 185 | 186 | 187 | ////////////////////////////////////////////////////////////////////////////// 188 | ////////////////////////////////////////////////////////////////////////////// 189 | //// 190 | //// SAMPLE PROGRAMS 191 | //// 192 | // 193 | // Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless 194 | // 195 | #if 0 196 | #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation 197 | #include "stb_truetype.h" 198 | 199 | char ttf_buffer[1<<20]; 200 | unsigned char temp_bitmap[512*512]; 201 | 202 | stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs 203 | GLstbtt_uint ftex; 204 | 205 | void my_stbtt_initfont(void) 206 | { 207 | fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb")); 208 | stbtt_BakeFontBitmap(data,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits! 209 | // can free ttf_buffer at this point 210 | glGenTextures(1, &ftex); 211 | glBindTexture(GL_TEXTURE_2D, ftex); 212 | glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap); 213 | // can free temp_bitmap at this point 214 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 215 | } 216 | 217 | void my_stbtt_print(float x, float y, char *text) 218 | { 219 | // assume orthographic projection with units = screen pixels, origin at top left 220 | glBindTexture(GL_TEXTURE_2D, ftex); 221 | glBegin(GL_QUADS); 222 | while (*text) { 223 | if (*text >= 32 && *text < 128) { 224 | stbtt_aligned_quad q; 225 | stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl,0=old d3d 226 | glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0); 227 | glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0); 228 | glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1); 229 | glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1); 230 | } 231 | ++text; 232 | } 233 | glEnd(); 234 | } 235 | #endif 236 | // 237 | // 238 | ////////////////////////////////////////////////////////////////////////////// 239 | // 240 | // Complete program (this compiles): get a single bitmap, print as ASCII art 241 | // 242 | #if 0 243 | #include 244 | #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation 245 | #include "stb_truetype.h" 246 | 247 | char ttf_buffer[1<<25]; 248 | 249 | int main(int argc, char **argv) 250 | { 251 | stbtt_fontinfo font; 252 | unsigned char *bitmap; 253 | int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20); 254 | 255 | fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); 256 | 257 | stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); 258 | bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); 259 | 260 | for (j=0; j < h; ++j) { 261 | for (i=0; i < w; ++i) 262 | putchar(" .:ioVM@"[bitmap[j*w+i]>>5]); 263 | putchar('\n'); 264 | } 265 | return 0; 266 | } 267 | #endif 268 | // 269 | // Output: 270 | // 271 | // .ii. 272 | // @@@@@@. 273 | // V@Mio@@o 274 | // :i. V@V 275 | // :oM@@M 276 | // :@@@MM@M 277 | // @@o o@M 278 | // :@@. M@M 279 | // @@@o@@@@ 280 | // :M@@V:@@. 281 | // 282 | ////////////////////////////////////////////////////////////////////////////// 283 | // 284 | // Complete program: print "Hello World!" banner, with bugs 285 | // 286 | #if 0 287 | char buffer[24<<20]; 288 | unsigned char screen[20][79]; 289 | 290 | int main(int arg, char **argv) 291 | { 292 | stbtt_fontinfo font; 293 | int i,j,ascent,baseline,ch=0; 294 | float scale, xpos=0; 295 | char *text = "Heljo World!"; 296 | 297 | fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb")); 298 | stbtt_InitFont(&font, buffer, 0); 299 | 300 | scale = stbtt_ScaleForPixelHeight(&font, 15); 301 | stbtt_GetFontVMetrics(&font, &ascent,0,0); 302 | baseline = (int) (ascent*scale); 303 | 304 | while (text[ch]) { 305 | int advance,lsb,x0,y0,x1,y1; 306 | float x_shift = xpos - (float) floor(xpos); 307 | stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb); 308 | stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1); 309 | stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]); 310 | // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong 311 | // because this API is really for baking character bitmaps into textures. if you want to render 312 | // a sequence of characters, you really need to render each bitmap to a temp buffer, then 313 | // "alpha blend" that into the working buffer 314 | xpos += (advance * scale); 315 | if (text[ch+1]) 316 | xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]); 317 | ++ch; 318 | } 319 | 320 | for (j=0; j < 20; ++j) { 321 | for (i=0; i < 78; ++i) 322 | putchar(" .:ioVM@"[screen[j][i]>>5]); 323 | putchar('\n'); 324 | } 325 | 326 | return 0; 327 | } 328 | #endif 329 | 330 | 331 | ////////////////////////////////////////////////////////////////////////////// 332 | ////////////////////////////////////////////////////////////////////////////// 333 | //// 334 | //// INTEGRATION WITH YOUR CODEBASE 335 | //// 336 | //// The following sections allow you to supply alternate definitions 337 | //// of C library functions used by stb_truetype. 338 | 339 | #ifdef STB_TRUETYPE_IMPLEMENTATION 340 | // #define your own (u)stbtt_int8/16/32 before including to override this 341 | #ifndef stbtt_uint8 342 | typedef unsigned char stbtt_uint8; 343 | typedef signed char stbtt_int8; 344 | typedef unsigned short stbtt_uint16; 345 | typedef signed short stbtt_int16; 346 | typedef unsigned int stbtt_uint32; 347 | typedef signed int stbtt_int32; 348 | #endif 349 | 350 | typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1]; 351 | typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1]; 352 | 353 | // #define your own STBTT_sort() to override this to avoid qsort 354 | #ifndef STBTT_sort 355 | #include 356 | #define STBTT_sort(data,num_items,item_size,compare_func) qsort(data,num_items,item_size,compare_func) 357 | #endif 358 | 359 | // #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h 360 | #ifndef STBTT_ifloor 361 | #include 362 | #define STBTT_ifloor(x) ((int) floor(x)) 363 | #define STBTT_iceil(x) ((int) ceil(x)) 364 | #endif 365 | 366 | // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h 367 | #ifndef STBTT_malloc 368 | #include 369 | #define STBTT_malloc(x,u) malloc(x) 370 | #define STBTT_free(x,u) free(x) 371 | #endif 372 | 373 | #ifndef STBTT_assert 374 | #include 375 | #define STBTT_assert(x) assert(x) 376 | #endif 377 | 378 | #ifndef STBTT_strlen 379 | #include 380 | #define STBTT_strlen(x) strlen(x) 381 | #endif 382 | 383 | #ifndef STBTT_memcpy 384 | #include 385 | #define STBTT_memcpy memcpy 386 | #define STBTT_memset memset 387 | #endif 388 | #endif 389 | 390 | /////////////////////////////////////////////////////////////////////////////// 391 | /////////////////////////////////////////////////////////////////////////////// 392 | //// 393 | //// INTERFACE 394 | //// 395 | //// 396 | 397 | #ifndef __STB_INCLUDE_STB_TRUETYPE_H__ 398 | #define __STB_INCLUDE_STB_TRUETYPE_H__ 399 | 400 | #ifdef __cplusplus 401 | extern "C" { 402 | #endif 403 | 404 | ////////////////////////////////////////////////////////////////////////////// 405 | // 406 | // TEXTURE BAKING API 407 | // 408 | // If you use this API, you only have to call two functions ever. 409 | // 410 | 411 | typedef struct 412 | { 413 | unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap 414 | float xoff,yoff,xadvance; 415 | } stbtt_bakedchar; 416 | 417 | extern int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) 418 | float pixel_height, // height of font in pixels 419 | unsigned char *pixels, int pw, int ph, // bitmap to be filled in 420 | int first_char, int num_chars, // characters to bake 421 | stbtt_bakedchar *chardata); // you allocate this, it's num_chars long 422 | // if return is positive, the first unused row of the bitmap 423 | // if return is negative, returns the negative of the number of characters that fit 424 | // if return is 0, no characters fit and no rows were used 425 | // This uses a very crappy packing. 426 | 427 | typedef struct 428 | { 429 | float x0,y0,s0,t0; // top-left 430 | float x1,y1,s1,t1; // bottom-right 431 | } stbtt_aligned_quad; 432 | 433 | extern void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, // same data as above 434 | int char_index, // character to display 435 | float *xpos, float *ypos, // pointers to current position in screen pixel space 436 | stbtt_aligned_quad *q, // output: quad to draw 437 | int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier 438 | // Call GetBakedQuad with char_index = 'character - first_char', and it 439 | // creates the quad you need to draw and advances the current position. 440 | // 441 | // The coordinate system used assumes y increases downwards. 442 | // 443 | // Characters will extend both above and below the current position; 444 | // see discussion of "BASELINE" above. 445 | // 446 | // It's inefficient; you might want to c&p it and optimize it. 447 | 448 | 449 | ////////////////////////////////////////////////////////////////////////////// 450 | // 451 | // FONT LOADING 452 | // 453 | // 454 | 455 | extern int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); 456 | // Each .ttf/.ttc file may have more than one font. Each font has a sequential 457 | // index number starting from 0. Call this function to get the font offset for 458 | // a given index; it returns -1 if the index is out of range. A regular .ttf 459 | // file will only define one font and it always be at offset 0, so it will 460 | // return '0' for index 0, and -1 for all other indices. You can just skip 461 | // this step if you know it's that kind of font. 462 | 463 | 464 | // The following structure is defined publically so you can declare one on 465 | // the stack or as a global or etc, but you should treat it as opaque. 466 | typedef struct stbtt_fontinfo 467 | { 468 | void * userdata; 469 | unsigned char * data; // pointer to .ttf file 470 | int fontstart; // offset of start of font 471 | 472 | int numGlyphs; // number of glyphs, needed for range checking 473 | 474 | int loca,head,glyf,hhea,hmtx,kern; // table locations as offset from start of .ttf 475 | int index_map; // a cmap mapping for our chosen character encoding 476 | int indexToLocFormat; // format needed to map from glyph index to glyph 477 | } stbtt_fontinfo; 478 | 479 | extern int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset); 480 | // Given an offset into the file that defines a font, this function builds 481 | // the necessary cached info for the rest of the system. You must allocate 482 | // the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't 483 | // need to do anything special to free it, because the contents are pure 484 | // value data with no additional data structures. Returns 0 on failure. 485 | 486 | 487 | ////////////////////////////////////////////////////////////////////////////// 488 | // 489 | // CHARACTER TO GLYPH-INDEX CONVERSIOn 490 | 491 | int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); 492 | // If you're going to perform multiple operations on the same character 493 | // and you want a speed-up, call this function with the character you're 494 | // going to process, then use glyph-based functions instead of the 495 | // codepoint-based functions. 496 | 497 | 498 | ////////////////////////////////////////////////////////////////////////////// 499 | // 500 | // CHARACTER PROPERTIES 501 | // 502 | 503 | extern float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels); 504 | // computes a scale factor to produce a font whose "height" is 'pixels' tall. 505 | // Height is measured as the distance from the highest ascender to the lowest 506 | // descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics 507 | // and computing: 508 | // scale = pixels / (ascent - descent) 509 | // so if you prefer to measure height by the ascent only, use a similar calculation. 510 | 511 | extern float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); 512 | // computes a scale factor to produce a font whose EM size is mapped to 513 | // 'pixels' tall. This is probably what traditional APIs compute, but 514 | // I'm not positive. 515 | 516 | extern void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap); 517 | // ascent is the coordinate above the baseline the font extends; descent 518 | // is the coordinate below the baseline the font extends (i.e. it is typically negative) 519 | // lineGap is the spacing between one row's descent and the next row's ascent... 520 | // so you should advance the vertical position by "*ascent - *descent + *lineGap" 521 | // these are expressed in unscaled coordinates, so you must multiply by 522 | // the scale factor for a given size 523 | 524 | extern void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); 525 | // the bounding box around all possible characters 526 | 527 | extern void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); 528 | // leftSideBearing is the offset from the current horizontal position to the left edge of the character 529 | // advanceWidth is the offset from the current horizontal position to the next horizontal position 530 | // these are expressed in unscaled coordinates 531 | 532 | extern int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2); 533 | // an additional amount to add to the 'advance' value between ch1 and ch2 534 | // @TODO; for now always returns 0! 535 | 536 | extern int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1); 537 | // Gets the bounding box of the visible part of the glyph, in unscaled coordinates 538 | 539 | extern void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); 540 | extern int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); 541 | extern int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); 542 | // as above, but takes one or more glyph indices for greater efficiency 543 | 544 | 545 | ////////////////////////////////////////////////////////////////////////////// 546 | // 547 | // GLYPH SHAPES (you probably don't need these, but they have to go before 548 | // the bitmaps for C declaration-order reasons) 549 | // 550 | 551 | #ifndef STBTT_vmove // you can predefine these to use different values (but why?) 552 | enum { 553 | STBTT_vmove=1, 554 | STBTT_vline, 555 | STBTT_vcurve 556 | }; 557 | #endif 558 | 559 | #ifndef stbtt_vertex // you can predefine this to use different values 560 | // (we share this with other code at RAD) 561 | #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file 562 | typedef struct 563 | { 564 | stbtt_vertex_type x,y,cx,cy; 565 | unsigned char type,padding; 566 | } stbtt_vertex; 567 | #endif 568 | 569 | extern int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index); 570 | // returns non-zero if nothing is drawn for this glyph 571 | 572 | extern int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices); 573 | extern int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices); 574 | // returns # of vertices and fills *vertices with the pointer to them 575 | // these are expressed in "unscaled" coordinates 576 | 577 | extern void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices); 578 | // frees the data allocated above 579 | 580 | ////////////////////////////////////////////////////////////////////////////// 581 | // 582 | // BITMAP RENDERING 583 | // 584 | 585 | extern void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata); 586 | // frees the bitmap allocated below 587 | 588 | extern unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff); 589 | // allocates a large-enough single-channel 8bpp bitmap and renders the 590 | // specified character/glyph at the specified scale into it, with 591 | // antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque). 592 | // *width & *height are filled out with the width & height of the bitmap, 593 | // which is stored left-to-right, top-to-bottom. 594 | // 595 | // xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap 596 | 597 | extern unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff); 598 | // the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel 599 | // shift for the character 600 | 601 | extern void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint); 602 | // the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap 603 | // in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap 604 | // is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the 605 | // width and height and positioning info for it first. 606 | 607 | extern void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint); 608 | // same as stbtt_MakeCodepointBitmap, but you can specify a subpixel 609 | // shift for the character 610 | 611 | extern void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); 612 | // get the bbox of the bitmap centered around the glyph origin; so the 613 | // bitmap width is ix1-ix0, height is iy1-iy0, and location to place 614 | // the bitmap top left is (leftSideBearing*scale,iy0). 615 | // (Note that the bitmap uses y-increases-down, but the shape uses 616 | // y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.) 617 | 618 | extern void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); 619 | // same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel 620 | // shift for the character 621 | 622 | // the following functions are equivalent to the above functions, but operate 623 | // on glyph indices instead of Unicode codepoints (for efficiency) 624 | extern unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff); 625 | extern unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff); 626 | extern void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph); 627 | extern void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph); 628 | extern void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); 629 | extern void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); 630 | 631 | 632 | // @TODO: don't expose this structure 633 | typedef struct 634 | { 635 | int w,h,stride; 636 | unsigned char *pixels; 637 | } stbtt__bitmap; 638 | 639 | extern void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata); 640 | 641 | ////////////////////////////////////////////////////////////////////////////// 642 | // 643 | // Finding the right font... 644 | // 645 | // You should really just solve this offline, keep your own tables 646 | // of what font is what, and don't try to get it out of the .ttf file. 647 | // That's because getting it out of the .ttf file is really hard, because 648 | // the names in the file can appear in many possible encodings, in many 649 | // possible languages, and e.g. if you need a case-insensitive comparison, 650 | // the details of that depend on the encoding & language in a complex way 651 | // (actually underspecified in truetype, but also gigantic). 652 | // 653 | // But you can use the provided functions in two possible ways: 654 | // stbtt_FindMatchingFont() will use *case-sensitive* comparisons on 655 | // unicode-encoded names to try to find the font you want; 656 | // you can run this before calling stbtt_InitFont() 657 | // 658 | // stbtt_GetFontNameString() lets you get any of the various strings 659 | // from the file yourself and do your own comparisons on them. 660 | // You have to have called stbtt_InitFont() first. 661 | 662 | 663 | extern int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags); 664 | // returns the offset (not index) of the font that matches, or -1 if none 665 | // if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold". 666 | // if you use any other flag, use a font name like "Arial"; this checks 667 | // the 'macStyle' header field; i don't know if fonts set this consistently 668 | #define STBTT_MACSTYLE_DONTCARE 0 669 | #define STBTT_MACSTYLE_BOLD 1 670 | #define STBTT_MACSTYLE_ITALIC 2 671 | #define STBTT_MACSTYLE_UNDERSCORE 4 672 | #define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0 673 | 674 | extern int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2); 675 | // returns 1/0 whether the first string interpreted as utf8 is identical to 676 | // the second string interpreted as big-endian utf16... useful for strings from next func 677 | 678 | extern const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID); 679 | // returns the string (which may be big-endian double byte, e.g. for unicode) 680 | // and puts the length in bytes in *length. 681 | // 682 | // some of the values for the IDs are below; for more see the truetype spec: 683 | // http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html 684 | // http://www.microsoft.com/typography/otspec/name.htm 685 | 686 | enum { // platformID 687 | STBTT_PLATFORM_ID_UNICODE =0, 688 | STBTT_PLATFORM_ID_MAC =1, 689 | STBTT_PLATFORM_ID_ISO =2, 690 | STBTT_PLATFORM_ID_MICROSOFT =3 691 | }; 692 | 693 | enum { // encodingID for STBTT_PLATFORM_ID_UNICODE 694 | STBTT_UNICODE_EID_UNICODE_1_0 =0, 695 | STBTT_UNICODE_EID_UNICODE_1_1 =1, 696 | STBTT_UNICODE_EID_ISO_10646 =2, 697 | STBTT_UNICODE_EID_UNICODE_2_0_BMP=3, 698 | STBTT_UNICODE_EID_UNICODE_2_0_FULL=4 699 | }; 700 | 701 | enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT 702 | STBTT_MS_EID_SYMBOL =0, 703 | STBTT_MS_EID_UNICODE_BMP =1, 704 | STBTT_MS_EID_SHIFTJIS =2, 705 | STBTT_MS_EID_UNICODE_FULL =10 706 | }; 707 | 708 | enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes 709 | STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4, 710 | STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5, 711 | STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6, 712 | STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7 713 | }; 714 | 715 | enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID... 716 | // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs 717 | STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410, 718 | STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411, 719 | STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412, 720 | STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419, 721 | STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409, 722 | STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D 723 | }; 724 | 725 | enum { // languageID for STBTT_PLATFORM_ID_MAC 726 | STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11, 727 | STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23, 728 | STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32, 729 | STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 , 730 | STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 , 731 | STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33, 732 | STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19 733 | }; 734 | 735 | #ifdef __cplusplus 736 | } 737 | #endif 738 | 739 | #endif // __STB_INCLUDE_STB_TRUETYPE_H__ 740 | 741 | /////////////////////////////////////////////////////////////////////////////// 742 | /////////////////////////////////////////////////////////////////////////////// 743 | //// 744 | //// IMPLEMENTATION 745 | //// 746 | //// 747 | 748 | #ifdef STB_TRUETYPE_IMPLEMENTATION 749 | 750 | ////////////////////////////////////////////////////////////////////////// 751 | // 752 | // accessors to parse data from file 753 | // 754 | 755 | // on platforms that don't allow misaligned reads, if we want to allow 756 | // truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE 757 | 758 | #define ttBYTE(p) (* (stbtt_uint8 *) (p)) 759 | #define ttCHAR(p) (* (stbtt_int8 *) (p)) 760 | #define ttFixed(p) ttLONG(p) 761 | 762 | #if defined(STB_TRUETYPE_BIGENDIAN) && !defined(ALLOW_UNALIGNED_TRUETYPE) 763 | 764 | #define ttUSHORT(p) (* (stbtt_uint16 *) (p)) 765 | #define ttSHORT(p) (* (stbtt_int16 *) (p)) 766 | #define ttULONG(p) (* (stbtt_uint32 *) (p)) 767 | #define ttLONG(p) (* (stbtt_int32 *) (p)) 768 | 769 | #else 770 | 771 | stbtt_uint16 ttUSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; } 772 | stbtt_int16 ttSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; } 773 | stbtt_uint32 ttULONG(const stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } 774 | stbtt_int32 ttLONG(const stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } 775 | 776 | #endif 777 | 778 | #define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)) 779 | #define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3]) 780 | 781 | static int stbtt__isfont(const stbtt_uint8 *font) 782 | { 783 | // check the version number 784 | if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1 785 | if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this! 786 | if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF 787 | if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0 788 | return 0; 789 | } 790 | 791 | // @OPTIMIZE: binary search 792 | static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag) 793 | { 794 | stbtt_int32 num_tables = ttUSHORT(data+fontstart+4); 795 | stbtt_uint32 tabledir = fontstart + 12; 796 | stbtt_int32 i; 797 | for (i=0; i < num_tables; ++i) { 798 | stbtt_uint32 loc = tabledir + 16*i; 799 | if (stbtt_tag(data+loc+0, tag)) 800 | return ttULONG(data+loc+8); 801 | } 802 | return 0; 803 | } 804 | 805 | int stbtt_GetFontOffsetForIndex(const unsigned char *font_collection, int index) 806 | { 807 | // if it's just a font, there's only one valid index 808 | if (stbtt__isfont(font_collection)) 809 | return index == 0 ? 0 : -1; 810 | 811 | // check if it's a TTC 812 | if (stbtt_tag(font_collection, "ttcf")) { 813 | // version 1? 814 | if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { 815 | stbtt_int32 n = ttLONG(font_collection+8); 816 | if (index >= n) 817 | return -1; 818 | return ttULONG(font_collection+12+index*14); 819 | } 820 | } 821 | return -1; 822 | } 823 | 824 | int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data2, int fontstart) 825 | { 826 | stbtt_uint8 *data = (stbtt_uint8 *) data2; 827 | stbtt_uint32 cmap, t; 828 | stbtt_int32 i,numTables; 829 | 830 | info->data = data; 831 | info->fontstart = fontstart; 832 | 833 | cmap = stbtt__find_table(data, fontstart, "cmap"); // required 834 | info->loca = stbtt__find_table(data, fontstart, "loca"); // required 835 | info->head = stbtt__find_table(data, fontstart, "head"); // required 836 | info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required 837 | info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required 838 | info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required 839 | info->kern = stbtt__find_table(data, fontstart, "kern"); // not required 840 | if (!cmap || !info->loca || !info->head || !info->glyf || !info->hhea || !info->hmtx) 841 | return 0; 842 | 843 | t = stbtt__find_table(data, fontstart, "maxp"); 844 | if (t) 845 | info->numGlyphs = ttUSHORT(data+t+4); 846 | else 847 | info->numGlyphs = 0xffff; 848 | 849 | // find a cmap encoding table we understand *now* to avoid searching 850 | // later. (todo: could make this installable) 851 | // the same regardless of glyph. 852 | numTables = ttUSHORT(data + cmap + 2); 853 | info->index_map = 0; 854 | for (i=0; i < numTables; ++i) { 855 | stbtt_uint32 encoding_record = cmap + 4 + 8 * i; 856 | // find an encoding we understand: 857 | switch(ttUSHORT(data+encoding_record)) { 858 | case STBTT_PLATFORM_ID_MICROSOFT: 859 | switch (ttUSHORT(data+encoding_record+2)) { 860 | case STBTT_MS_EID_UNICODE_BMP: 861 | case STBTT_MS_EID_UNICODE_FULL: 862 | // MS/Unicode 863 | info->index_map = cmap + ttULONG(data+encoding_record+4); 864 | break; 865 | } 866 | break; 867 | } 868 | } 869 | if (info->index_map == 0) 870 | return 0; 871 | 872 | info->indexToLocFormat = ttUSHORT(data+info->head + 50); 873 | return 1; 874 | } 875 | 876 | int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint) 877 | { 878 | stbtt_uint8 *data = info->data; 879 | stbtt_uint32 index_map = info->index_map; 880 | 881 | stbtt_uint16 format = ttUSHORT(data + index_map + 0); 882 | if (format == 0) { // apple byte encoding 883 | stbtt_int32 bytes = ttUSHORT(data + index_map + 2); 884 | if (unicode_codepoint < bytes-6) 885 | return ttBYTE(data + index_map + 6 + unicode_codepoint); 886 | return 0; 887 | } else if (format == 6) { 888 | stbtt_uint32 first = ttUSHORT(data + index_map + 6); 889 | stbtt_uint32 count = ttUSHORT(data + index_map + 8); 890 | if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count) 891 | return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2); 892 | return 0; 893 | } else if (format == 2) { 894 | STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean 895 | return 0; 896 | } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges 897 | stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1; 898 | stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1; 899 | stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10); 900 | stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1; 901 | stbtt_uint16 item, offset, start, end; 902 | 903 | // do a binary search of the segments 904 | stbtt_uint32 endCount = index_map + 14; 905 | stbtt_uint32 search = endCount; 906 | 907 | if (unicode_codepoint > 0xffff) 908 | return 0; 909 | 910 | // they lie from endCount .. endCount + segCount 911 | // but searchRange is the nearest power of two, so... 912 | if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2)) 913 | search += rangeShift*2; 914 | 915 | // now decrement to bias correctly to find smallest 916 | search -= 2; 917 | while (entrySelector) { 918 | stbtt_uint16 start, end; 919 | searchRange >>= 1; 920 | start = ttUSHORT(data + search + 2 + segcount*2 + 2); 921 | end = ttUSHORT(data + search + 2); 922 | start = ttUSHORT(data + search + searchRange*2 + segcount*2 + 2); 923 | end = ttUSHORT(data + search + searchRange*2); 924 | if (unicode_codepoint > end) 925 | search += searchRange*2; 926 | --entrySelector; 927 | } 928 | search += 2; 929 | 930 | item = (stbtt_uint16) ((search - endCount) >> 1); 931 | 932 | STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item)); 933 | start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); 934 | end = ttUSHORT(data + index_map + 14 + 2 + 2*item); 935 | if (unicode_codepoint < start) 936 | return 0; 937 | 938 | offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); 939 | if (offset == 0) 940 | return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); 941 | 942 | return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); 943 | } else if (format == 12 || format == 13) { 944 | stbtt_uint32 ngroups = ttULONG(data+index_map+12); 945 | stbtt_int32 low,high; 946 | low = 0; high = (stbtt_int32)ngroups; 947 | // Binary search the right group. 948 | while (low < high) { 949 | stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high 950 | stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12); 951 | stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4); 952 | if ((stbtt_uint32) unicode_codepoint < start_char) 953 | high = mid; 954 | else if ((stbtt_uint32) unicode_codepoint > end_char) 955 | low = mid+1; 956 | else { 957 | stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8); 958 | if (format == 12) 959 | return start_glyph + unicode_codepoint-start_char; 960 | else // format == 13 961 | return start_glyph; 962 | } 963 | } 964 | return 0; // not found 965 | } 966 | // @TODO 967 | STBTT_assert(0); 968 | return 0; 969 | } 970 | 971 | int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices) 972 | { 973 | return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices); 974 | } 975 | 976 | static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy) 977 | { 978 | v->type = type; 979 | v->x = (stbtt_int16) x; 980 | v->y = (stbtt_int16) y; 981 | v->cx = (stbtt_int16) cx; 982 | v->cy = (stbtt_int16) cy; 983 | } 984 | 985 | static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index) 986 | { 987 | int g1,g2; 988 | 989 | if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range 990 | if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format 991 | 992 | if (info->indexToLocFormat == 0) { 993 | g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2; 994 | g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2; 995 | } else { 996 | g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4); 997 | g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4); 998 | } 999 | 1000 | return g1==g2 ? -1 : g1; // if length is 0, return -1 1001 | } 1002 | 1003 | int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) 1004 | { 1005 | int g = stbtt__GetGlyfOffset(info, glyph_index); 1006 | if (g < 0) return 0; 1007 | 1008 | if (x0) *x0 = ttSHORT(info->data + g + 2); 1009 | if (y0) *y0 = ttSHORT(info->data + g + 4); 1010 | if (x1) *x1 = ttSHORT(info->data + g + 6); 1011 | if (y1) *y1 = ttSHORT(info->data + g + 8); 1012 | return 1; 1013 | } 1014 | 1015 | int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1) 1016 | { 1017 | return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1); 1018 | } 1019 | 1020 | int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index) 1021 | { 1022 | stbtt_int16 numberOfContours; 1023 | int g = stbtt__GetGlyfOffset(info, glyph_index); 1024 | if (g < 0) return 1; 1025 | numberOfContours = ttSHORT(info->data + g); 1026 | return numberOfContours == 0; 1027 | } 1028 | 1029 | static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off, 1030 | stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy) 1031 | { 1032 | if (start_off) { 1033 | if (was_off) 1034 | stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy); 1035 | stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy); 1036 | } else { 1037 | if (was_off) 1038 | stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy); 1039 | else 1040 | stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0); 1041 | } 1042 | return num_vertices; 1043 | } 1044 | 1045 | int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) 1046 | { 1047 | stbtt_int16 numberOfContours; 1048 | stbtt_uint8 *endPtsOfContours; 1049 | stbtt_uint8 *data = info->data; 1050 | stbtt_vertex *vertices=0; 1051 | int num_vertices=0; 1052 | int g = stbtt__GetGlyfOffset(info, glyph_index); 1053 | 1054 | *pvertices = NULL; 1055 | 1056 | if (g < 0) return 0; 1057 | 1058 | numberOfContours = ttSHORT(data + g); 1059 | 1060 | if (numberOfContours > 0) { 1061 | stbtt_uint8 flags=0,flagcount; 1062 | stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0; 1063 | stbtt_int32 x,y,cx,cy,sx,sy, scx,scy; 1064 | stbtt_uint8 *points; 1065 | endPtsOfContours = (data + g + 10); 1066 | ins = ttUSHORT(data + g + 10 + numberOfContours * 2); 1067 | points = data + g + 10 + numberOfContours * 2 + 2 + ins; 1068 | 1069 | n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2); 1070 | 1071 | m = n + 2*numberOfContours; // a loose bound on how many vertices we might need 1072 | vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata); 1073 | if (vertices == 0) 1074 | return 0; 1075 | 1076 | next_move = 0; 1077 | flagcount=0; 1078 | 1079 | // in first pass, we load uninterpreted data into the allocated array 1080 | // above, shifted to the end of the array so we won't overwrite it when 1081 | // we create our final data starting from the front 1082 | 1083 | off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated 1084 | 1085 | // first load flags 1086 | 1087 | for (i=0; i < n; ++i) { 1088 | if (flagcount == 0) { 1089 | flags = *points++; 1090 | if (flags & 8) 1091 | flagcount = *points++; 1092 | } else 1093 | --flagcount; 1094 | vertices[off+i].type = flags; 1095 | } 1096 | 1097 | // now load x coordinates 1098 | x=0; 1099 | for (i=0; i < n; ++i) { 1100 | flags = vertices[off+i].type; 1101 | if (flags & 2) { 1102 | stbtt_int16 dx = *points++; 1103 | x += (flags & 16) ? dx : -dx; // ??? 1104 | } else { 1105 | if (!(flags & 16)) { 1106 | x = x + (stbtt_int16) (points[0]*256 + points[1]); 1107 | points += 2; 1108 | } 1109 | } 1110 | vertices[off+i].x = (stbtt_int16) x; 1111 | } 1112 | 1113 | // now load y coordinates 1114 | y=0; 1115 | for (i=0; i < n; ++i) { 1116 | flags = vertices[off+i].type; 1117 | if (flags & 4) { 1118 | stbtt_int16 dy = *points++; 1119 | y += (flags & 32) ? dy : -dy; // ??? 1120 | } else { 1121 | if (!(flags & 32)) { 1122 | y = y + (stbtt_int16) (points[0]*256 + points[1]); 1123 | points += 2; 1124 | } 1125 | } 1126 | vertices[off+i].y = (stbtt_int16) y; 1127 | } 1128 | 1129 | // now convert them to our format 1130 | num_vertices=0; 1131 | sx = sy = cx = cy = scx = scy = 0; 1132 | for (i=0; i < n; ++i) { 1133 | flags = vertices[off+i].type; 1134 | x = (stbtt_int16) vertices[off+i].x; 1135 | y = (stbtt_int16) vertices[off+i].y; 1136 | 1137 | if (next_move == i) { 1138 | if (i != 0) 1139 | num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); 1140 | 1141 | // now start the new one 1142 | start_off = !(flags & 1); 1143 | if (start_off) { 1144 | // if we start off with an off-curve point, then when we need to find a point on the curve 1145 | // where we can start, and we need to save some state for when we wraparound. 1146 | scx = x; 1147 | scy = y; 1148 | if (!(vertices[off+i+1].type & 1)) { 1149 | // next point is also a curve point, so interpolate an on-point curve 1150 | sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1; 1151 | sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1; 1152 | } else { 1153 | // otherwise just use the next point as our start point 1154 | sx = (stbtt_int32) vertices[off+i+1].x; 1155 | sy = (stbtt_int32) vertices[off+i+1].y; 1156 | ++i; // we're using point i+1 as the starting point, so skip it 1157 | } 1158 | } else { 1159 | sx = x; 1160 | sy = y; 1161 | } 1162 | stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0); 1163 | was_off = 0; 1164 | next_move = 1 + ttUSHORT(endPtsOfContours+j*2); 1165 | ++j; 1166 | } else { 1167 | if (!(flags & 1)) { // if it's a curve 1168 | if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint 1169 | stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy); 1170 | cx = x; 1171 | cy = y; 1172 | was_off = 1; 1173 | } else { 1174 | if (was_off) 1175 | stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy); 1176 | else 1177 | stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0); 1178 | was_off = 0; 1179 | } 1180 | } 1181 | } 1182 | num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); 1183 | } else if (numberOfContours == -1) { 1184 | // Compound shapes. 1185 | int more = 1; 1186 | stbtt_uint8 *comp = data + g + 10; 1187 | num_vertices = 0; 1188 | vertices = 0; 1189 | while (more) { 1190 | stbtt_uint16 flags, gidx; 1191 | int comp_num_verts = 0, i; 1192 | stbtt_vertex *comp_verts = 0, *tmp = 0; 1193 | float mtx[6] = {1,0,0,1,0,0}, m, n; 1194 | 1195 | flags = ttSHORT(comp); comp+=2; 1196 | gidx = ttSHORT(comp); comp+=2; 1197 | 1198 | if (flags & 2) { // XY values 1199 | if (flags & 1) { // shorts 1200 | mtx[4] = ttSHORT(comp); comp+=2; 1201 | mtx[5] = ttSHORT(comp); comp+=2; 1202 | } else { 1203 | mtx[4] = ttCHAR(comp); comp+=1; 1204 | mtx[5] = ttCHAR(comp); comp+=1; 1205 | } 1206 | } 1207 | else { 1208 | // @TODO handle matching point 1209 | STBTT_assert(0); 1210 | } 1211 | if (flags & (1<<3)) { // WE_HAVE_A_SCALE 1212 | mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; 1213 | mtx[1] = mtx[2] = 0; 1214 | } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE 1215 | mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; 1216 | mtx[1] = mtx[2] = 0; 1217 | mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; 1218 | } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO 1219 | mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; 1220 | mtx[1] = ttSHORT(comp)/16384.0f; comp+=2; 1221 | mtx[2] = ttSHORT(comp)/16384.0f; comp+=2; 1222 | mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; 1223 | } 1224 | 1225 | // Find transformation scales. 1226 | m = (float) sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]); 1227 | n = (float) sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]); 1228 | 1229 | // Get indexed glyph. 1230 | comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts); 1231 | if (comp_num_verts > 0) { 1232 | // Transform vertices. 1233 | for (i = 0; i < comp_num_verts; ++i) { 1234 | stbtt_vertex* v = &comp_verts[i]; 1235 | stbtt_vertex_type x,y; 1236 | x=v->x; y=v->y; 1237 | v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); 1238 | v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); 1239 | x=v->cx; y=v->cy; 1240 | v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); 1241 | v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); 1242 | } 1243 | // Append vertices. 1244 | tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata); 1245 | if (!tmp) { 1246 | if (vertices) STBTT_free(vertices, info->userdata); 1247 | if (comp_verts) STBTT_free(comp_verts, info->userdata); 1248 | return 0; 1249 | } 1250 | if (num_vertices > 0) memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex)); 1251 | memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex)); 1252 | if (vertices) STBTT_free(vertices, info->userdata); 1253 | vertices = tmp; 1254 | STBTT_free(comp_verts, info->userdata); 1255 | num_vertices += comp_num_verts; 1256 | } 1257 | // More components ? 1258 | more = flags & (1<<5); 1259 | } 1260 | } else if (numberOfContours < 0) { 1261 | // @TODO other compound variations? 1262 | STBTT_assert(0); 1263 | } else { 1264 | // numberOfCounters == 0, do nothing 1265 | } 1266 | 1267 | *pvertices = vertices; 1268 | return num_vertices; 1269 | } 1270 | 1271 | void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing) 1272 | { 1273 | stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34); 1274 | if (glyph_index < numOfLongHorMetrics) { 1275 | if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index); 1276 | if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2); 1277 | } else { 1278 | if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1)); 1279 | if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics)); 1280 | } 1281 | } 1282 | 1283 | int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) 1284 | { 1285 | stbtt_uint8 *data = info->data + info->kern; 1286 | stbtt_uint32 needle, straw; 1287 | int l, r, m; 1288 | 1289 | // we only look at the first table. it must be 'horizontal' and format 0. 1290 | if (!info->kern) 1291 | return 0; 1292 | if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 1293 | return 0; 1294 | if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format 1295 | return 0; 1296 | 1297 | l = 0; 1298 | r = ttUSHORT(data+10) - 1; 1299 | needle = glyph1 << 16 | glyph2; 1300 | while (l <= r) { 1301 | m = (l + r) >> 1; 1302 | straw = ttULONG(data+18+(m*6)); // note: unaligned read 1303 | if (needle < straw) 1304 | r = m - 1; 1305 | else if (needle > straw) 1306 | l = m + 1; 1307 | else 1308 | return ttSHORT(data+22+(m*6)); 1309 | } 1310 | return 0; 1311 | } 1312 | 1313 | int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2) 1314 | { 1315 | if (!info->kern) // if no kerning table, don't waste time looking up both codepoint->glyphs 1316 | return 0; 1317 | return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2)); 1318 | } 1319 | 1320 | void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing) 1321 | { 1322 | stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing); 1323 | } 1324 | 1325 | void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap) 1326 | { 1327 | if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4); 1328 | if (descent) *descent = ttSHORT(info->data+info->hhea + 6); 1329 | if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8); 1330 | } 1331 | 1332 | void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1) 1333 | { 1334 | *x0 = ttSHORT(info->data + info->head + 36); 1335 | *y0 = ttSHORT(info->data + info->head + 38); 1336 | *x1 = ttSHORT(info->data + info->head + 40); 1337 | *y1 = ttSHORT(info->data + info->head + 42); 1338 | } 1339 | 1340 | float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) 1341 | { 1342 | int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); 1343 | return (float) height / fheight; 1344 | } 1345 | 1346 | float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) 1347 | { 1348 | int unitsPerEm = ttUSHORT(info->data + info->head + 18); 1349 | return pixels / unitsPerEm; 1350 | } 1351 | 1352 | void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v) 1353 | { 1354 | STBTT_free(v, info->userdata); 1355 | } 1356 | 1357 | ////////////////////////////////////////////////////////////////////////////// 1358 | // 1359 | // antialiasing software rasterizer 1360 | // 1361 | 1362 | void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) 1363 | { 1364 | int x0,y0,x1,y1; 1365 | if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) 1366 | x0=y0=x1=y1=0; // e.g. space character 1367 | // now move to integral bboxes (treating pixels as little squares, what pixels get touched)? 1368 | if (ix0) *ix0 = STBTT_ifloor(x0 * scale_x + shift_x); 1369 | if (iy0) *iy0 = -STBTT_iceil (y1 * scale_y + shift_y); 1370 | if (ix1) *ix1 = STBTT_iceil (x1 * scale_x + shift_x); 1371 | if (iy1) *iy1 = -STBTT_ifloor(y0 * scale_y + shift_y); 1372 | } 1373 | void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) 1374 | { 1375 | stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1); 1376 | } 1377 | 1378 | void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) 1379 | { 1380 | stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1); 1381 | } 1382 | 1383 | void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) 1384 | { 1385 | stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1); 1386 | } 1387 | 1388 | typedef struct stbtt__edge { 1389 | float x0,y0, x1,y1; 1390 | int invert; 1391 | } stbtt__edge; 1392 | 1393 | typedef struct stbtt__active_edge 1394 | { 1395 | int x,dx; 1396 | float ey; 1397 | struct stbtt__active_edge *next; 1398 | int valid; 1399 | } stbtt__active_edge; 1400 | 1401 | #define FIXSHIFT 10 1402 | #define FIX (1 << FIXSHIFT) 1403 | #define FIXMASK (FIX-1) 1404 | 1405 | static stbtt__active_edge *new_active(stbtt__edge *e, int off_x, float start_point, void *userdata) 1406 | { 1407 | stbtt__active_edge *z = (stbtt__active_edge *) STBTT_malloc(sizeof(*z), userdata); // @TODO: make a pool of these!!! 1408 | float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); 1409 | STBTT_assert(e->y0 <= start_point); 1410 | if (!z) return z; 1411 | // round dx down to avoid going too far 1412 | if (dxdy < 0) 1413 | z->dx = -STBTT_ifloor(FIX * -dxdy); 1414 | else 1415 | z->dx = STBTT_ifloor(FIX * dxdy); 1416 | z->x = STBTT_ifloor(FIX * (e->x0 + dxdy * (start_point - e->y0))); 1417 | z->x -= off_x * FIX; 1418 | z->ey = e->y1; 1419 | z->next = 0; 1420 | z->valid = e->invert ? 1 : -1; 1421 | return z; 1422 | } 1423 | 1424 | // note: this routine clips fills that extend off the edges... ideally this 1425 | // wouldn't happen, but it could happen if the truetype glyph bounding boxes 1426 | // are wrong, or if the user supplies a too-small bitmap 1427 | static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight) 1428 | { 1429 | // non-zero winding fill 1430 | int x0=0, w=0; 1431 | 1432 | while (e) { 1433 | if (w == 0) { 1434 | // if we're currently at zero, we need to record the edge start point 1435 | x0 = e->x; w += e->valid; 1436 | } else { 1437 | int x1 = e->x; w += e->valid; 1438 | // if we went to zero, we need to draw 1439 | if (w == 0) { 1440 | int i = x0 >> FIXSHIFT; 1441 | int j = x1 >> FIXSHIFT; 1442 | 1443 | if (i < len && j >= 0) { 1444 | if (i == j) { 1445 | // x0,x1 are the same pixel, so compute combined coverage 1446 | scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> FIXSHIFT); 1447 | } else { 1448 | if (i >= 0) // add antialiasing for x0 1449 | scanline[i] = scanline[i] + (stbtt_uint8) (((FIX - (x0 & FIXMASK)) * max_weight) >> FIXSHIFT); 1450 | else 1451 | i = -1; // clip 1452 | 1453 | if (j < len) // add antialiasing for x1 1454 | scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & FIXMASK) * max_weight) >> FIXSHIFT); 1455 | else 1456 | j = len; // clip 1457 | 1458 | for (++i; i < j; ++i) // fill pixels between x0 and x1 1459 | scanline[i] = scanline[i] + (stbtt_uint8) max_weight; 1460 | } 1461 | } 1462 | } 1463 | } 1464 | 1465 | e = e->next; 1466 | } 1467 | } 1468 | 1469 | static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) 1470 | { 1471 | stbtt__active_edge *active = NULL; 1472 | int y,j=0; 1473 | int max_weight = (255 / vsubsample); // weight per vertical scanline 1474 | int s; // vertical subsample index 1475 | unsigned char scanline_data[512], *scanline; 1476 | 1477 | if (result->w > 512) 1478 | scanline = (unsigned char *) STBTT_malloc(result->w, userdata); 1479 | else 1480 | scanline = scanline_data; 1481 | 1482 | y = off_y * vsubsample; 1483 | e[n].y0 = (off_y + result->h) * (float) vsubsample + 1; 1484 | 1485 | while (j < result->h) { 1486 | STBTT_memset(scanline, 0, result->w); 1487 | for (s=0; s < vsubsample; ++s) { 1488 | // find center of pixel for this scanline 1489 | float scan_y = y + 0.5f; 1490 | stbtt__active_edge **step = &active; 1491 | 1492 | // update all active edges; 1493 | // remove all active edges that terminate before the center of this scanline 1494 | while (*step) { 1495 | stbtt__active_edge * z = *step; 1496 | if (z->ey <= scan_y) { 1497 | *step = z->next; // delete from list 1498 | STBTT_assert(z->valid); 1499 | z->valid = 0; 1500 | STBTT_free(z, userdata); 1501 | } else { 1502 | z->x += z->dx; // advance to position for current scanline 1503 | step = &((*step)->next); // advance through list 1504 | } 1505 | } 1506 | 1507 | // resort the list if needed 1508 | for(;;) { 1509 | int changed=0; 1510 | step = &active; 1511 | while (*step && (*step)->next) { 1512 | if ((*step)->x > (*step)->next->x) { 1513 | stbtt__active_edge *t = *step; 1514 | stbtt__active_edge *q = t->next; 1515 | 1516 | t->next = q->next; 1517 | q->next = t; 1518 | *step = q; 1519 | changed = 1; 1520 | } 1521 | step = &(*step)->next; 1522 | } 1523 | if (!changed) break; 1524 | } 1525 | 1526 | // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline 1527 | while (e->y0 <= scan_y) { 1528 | if (e->y1 > scan_y) { 1529 | stbtt__active_edge *z = new_active(e, off_x, scan_y, userdata); 1530 | // find insertion point 1531 | if (active == NULL) 1532 | active = z; 1533 | else if (z->x < active->x) { 1534 | // insert at front 1535 | z->next = active; 1536 | active = z; 1537 | } else { 1538 | // find thing to insert AFTER 1539 | stbtt__active_edge *p = active; 1540 | while (p->next && p->next->x < z->x) 1541 | p = p->next; 1542 | // at this point, p->next->x is NOT < z->x 1543 | z->next = p->next; 1544 | p->next = z; 1545 | } 1546 | } 1547 | ++e; 1548 | } 1549 | 1550 | // now process all active edges in XOR fashion 1551 | if (active) 1552 | stbtt__fill_active_edges(scanline, result->w, active, max_weight); 1553 | 1554 | ++y; 1555 | } 1556 | STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w); 1557 | ++j; 1558 | } 1559 | 1560 | while (active) { 1561 | stbtt__active_edge *z = active; 1562 | active = active->next; 1563 | STBTT_free(z, userdata); 1564 | } 1565 | 1566 | if (scanline != scanline_data) 1567 | STBTT_free(scanline, userdata); 1568 | } 1569 | 1570 | static int stbtt__edge_compare(const void *p, const void *q) 1571 | { 1572 | stbtt__edge *a = (stbtt__edge *) p; 1573 | stbtt__edge *b = (stbtt__edge *) q; 1574 | 1575 | if (a->y0 < b->y0) return -1; 1576 | if (a->y0 > b->y0) return 1; 1577 | return 0; 1578 | } 1579 | 1580 | typedef struct 1581 | { 1582 | float x,y; 1583 | } stbtt__point; 1584 | 1585 | static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata) 1586 | { 1587 | float y_scale_inv = invert ? -scale_y : scale_y; 1588 | stbtt__edge *e; 1589 | int n,i,j,k,m; 1590 | int vsubsample = result->h < 8 ? 15 : 5; 1591 | // vsubsample should divide 255 evenly; otherwise we won't reach full opacity 1592 | 1593 | // now we have to blow out the windings into explicit edge lists 1594 | n = 0; 1595 | for (i=0; i < windings; ++i) 1596 | n += wcount[i]; 1597 | 1598 | e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel 1599 | if (e == 0) return; 1600 | n = 0; 1601 | 1602 | m=0; 1603 | for (i=0; i < windings; ++i) { 1604 | stbtt__point *p = pts + m; 1605 | m += wcount[i]; 1606 | j = wcount[i]-1; 1607 | for (k=0; k < wcount[i]; j=k++) { 1608 | int a=k,b=j; 1609 | // skip the edge if horizontal 1610 | if (p[j].y == p[k].y) 1611 | continue; 1612 | // add edge from j to k to the list 1613 | e[n].invert = 0; 1614 | if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) { 1615 | e[n].invert = 1; 1616 | a=j,b=k; 1617 | } 1618 | e[n].x0 = p[a].x * scale_x + shift_x; 1619 | e[n].y0 = p[a].y * y_scale_inv * vsubsample + shift_y; 1620 | e[n].x1 = p[b].x * scale_x + shift_x; 1621 | e[n].y1 = p[b].y * y_scale_inv * vsubsample + shift_y; 1622 | ++n; 1623 | } 1624 | } 1625 | 1626 | // now sort the edges by their highest point (should snap to integer, and then by x) 1627 | STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); 1628 | 1629 | // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule 1630 | stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata); 1631 | 1632 | STBTT_free(e, userdata); 1633 | } 1634 | 1635 | static void stbtt__add_point(stbtt__point *points, int n, float x, float y) 1636 | { 1637 | if (!points) return; // during first pass, it's unallocated 1638 | points[n].x = x; 1639 | points[n].y = y; 1640 | } 1641 | 1642 | // tesselate until threshhold p is happy... @TODO warped to compensate for non-linear stretching 1643 | static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n) 1644 | { 1645 | // midpoint 1646 | float mx = (x0 + 2*x1 + x2)/4; 1647 | float my = (y0 + 2*y1 + y2)/4; 1648 | // versus directly drawn line 1649 | float dx = (x0+x2)/2 - mx; 1650 | float dy = (y0+y2)/2 - my; 1651 | if (n > 16) // 65536 segments on one curve better be enough! 1652 | return 1; 1653 | if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA 1654 | stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1); 1655 | stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1); 1656 | } else { 1657 | stbtt__add_point(points, *num_points,x2,y2); 1658 | *num_points = *num_points+1; 1659 | } 1660 | return 1; 1661 | } 1662 | 1663 | // returns number of contours 1664 | stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata) 1665 | { 1666 | stbtt__point *points=0; 1667 | int num_points=0; 1668 | 1669 | float objspace_flatness_squared = objspace_flatness * objspace_flatness; 1670 | int i,n=0,start=0, pass; 1671 | 1672 | // count how many "moves" there are to get the contour count 1673 | for (i=0; i < num_verts; ++i) 1674 | if (vertices[i].type == STBTT_vmove) 1675 | ++n; 1676 | 1677 | *num_contours = n; 1678 | if (n == 0) return 0; 1679 | 1680 | *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata); 1681 | 1682 | if (*contour_lengths == 0) { 1683 | *num_contours = 0; 1684 | return 0; 1685 | } 1686 | 1687 | // make two passes through the points so we don't need to realloc 1688 | for (pass=0; pass < 2; ++pass) { 1689 | float x=0,y=0; 1690 | if (pass == 1) { 1691 | points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata); 1692 | if (points == NULL) goto error; 1693 | } 1694 | num_points = 0; 1695 | n= -1; 1696 | for (i=0; i < num_verts; ++i) { 1697 | switch (vertices[i].type) { 1698 | case STBTT_vmove: 1699 | // start the next contour 1700 | if (n >= 0) 1701 | (*contour_lengths)[n] = num_points - start; 1702 | ++n; 1703 | start = num_points; 1704 | 1705 | x = vertices[i].x, y = vertices[i].y; 1706 | stbtt__add_point(points, num_points++, x,y); 1707 | break; 1708 | case STBTT_vline: 1709 | x = vertices[i].x, y = vertices[i].y; 1710 | stbtt__add_point(points, num_points++, x, y); 1711 | break; 1712 | case STBTT_vcurve: 1713 | stbtt__tesselate_curve(points, &num_points, x,y, 1714 | vertices[i].cx, vertices[i].cy, 1715 | vertices[i].x, vertices[i].y, 1716 | objspace_flatness_squared, 0); 1717 | x = vertices[i].x, y = vertices[i].y; 1718 | break; 1719 | } 1720 | } 1721 | (*contour_lengths)[n] = num_points - start; 1722 | } 1723 | 1724 | return points; 1725 | error: 1726 | STBTT_free(points, userdata); 1727 | STBTT_free(*contour_lengths, userdata); 1728 | *contour_lengths = 0; 1729 | *num_contours = 0; 1730 | return NULL; 1731 | } 1732 | 1733 | void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata) 1734 | { 1735 | float scale = scale_x > scale_y ? scale_y : scale_x; 1736 | int winding_count, *winding_lengths; 1737 | stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata); 1738 | if (windings) { 1739 | stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata); 1740 | STBTT_free(winding_lengths, userdata); 1741 | STBTT_free(windings, userdata); 1742 | } 1743 | } 1744 | 1745 | void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata) 1746 | { 1747 | STBTT_free(bitmap, userdata); 1748 | } 1749 | 1750 | unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff) 1751 | { 1752 | int ix0,iy0,ix1,iy1; 1753 | stbtt__bitmap gbm; 1754 | stbtt_vertex *vertices; 1755 | int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); 1756 | 1757 | if (scale_x == 0) scale_x = scale_y; 1758 | if (scale_y == 0) { 1759 | if (scale_x == 0) return NULL; 1760 | scale_y = scale_x; 1761 | } 1762 | 1763 | stbtt_GetGlyphBitmapBox(info, glyph, scale_x, scale_y, &ix0,&iy0,&ix1,&iy1); 1764 | 1765 | // now we get the size 1766 | gbm.w = (ix1 - ix0); 1767 | gbm.h = (iy1 - iy0); 1768 | gbm.pixels = NULL; // in case we error 1769 | 1770 | if (width ) *width = gbm.w; 1771 | if (height) *height = gbm.h; 1772 | if (xoff ) *xoff = ix0; 1773 | if (yoff ) *yoff = iy0; 1774 | 1775 | if (gbm.w && gbm.h) { 1776 | gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata); 1777 | if (gbm.pixels) { 1778 | gbm.stride = gbm.w; 1779 | 1780 | stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata); 1781 | } 1782 | } 1783 | STBTT_free(vertices, info->userdata); 1784 | return gbm.pixels; 1785 | } 1786 | 1787 | unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff) 1788 | { 1789 | return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff); 1790 | } 1791 | 1792 | void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph) 1793 | { 1794 | int ix0,iy0; 1795 | stbtt_vertex *vertices; 1796 | int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); 1797 | stbtt__bitmap gbm; 1798 | 1799 | stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0); 1800 | gbm.pixels = output; 1801 | gbm.w = out_w; 1802 | gbm.h = out_h; 1803 | gbm.stride = out_stride; 1804 | 1805 | if (gbm.w && gbm.h) 1806 | stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata); 1807 | 1808 | STBTT_free(vertices, info->userdata); 1809 | } 1810 | 1811 | void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph) 1812 | { 1813 | stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph); 1814 | } 1815 | 1816 | unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff) 1817 | { 1818 | return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff); 1819 | } 1820 | 1821 | void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint) 1822 | { 1823 | stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint)); 1824 | } 1825 | 1826 | unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff) 1827 | { 1828 | return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff); 1829 | } 1830 | 1831 | void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint) 1832 | { 1833 | stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint); 1834 | } 1835 | 1836 | ////////////////////////////////////////////////////////////////////////////// 1837 | // 1838 | // bitmap baking 1839 | // 1840 | // This is SUPER-CRAPPY packing to keep source code small 1841 | 1842 | extern int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) 1843 | float pixel_height, // height of font in pixels 1844 | unsigned char *pixels, int pw, int ph, // bitmap to be filled in 1845 | int first_char, int num_chars, // characters to bake 1846 | stbtt_bakedchar *chardata) 1847 | { 1848 | float scale; 1849 | int x,y,bottom_y, i; 1850 | stbtt_fontinfo f; 1851 | stbtt_InitFont(&f, data, offset); 1852 | STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels 1853 | x=y=1; 1854 | bottom_y = 1; 1855 | 1856 | scale = stbtt_ScaleForPixelHeight(&f, pixel_height); 1857 | 1858 | for (i=0; i < num_chars; ++i) { 1859 | int advance, lsb, x0,y0,x1,y1,gw,gh; 1860 | int g = stbtt_FindGlyphIndex(&f, first_char + i); 1861 | stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb); 1862 | stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1); 1863 | gw = x1-x0; 1864 | gh = y1-y0; 1865 | if (x + gw + 1 >= pw) 1866 | y = bottom_y, x = 1; // advance to next row 1867 | if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row 1868 | return -i; 1869 | STBTT_assert(x+gw < pw); 1870 | STBTT_assert(y+gh < ph); 1871 | stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g); 1872 | chardata[i].x0 = (stbtt_int16) x; 1873 | chardata[i].y0 = (stbtt_int16) y; 1874 | chardata[i].x1 = (stbtt_int16) (x + gw); 1875 | chardata[i].y1 = (stbtt_int16) (y + gh); 1876 | chardata[i].xadvance = scale * advance; 1877 | chardata[i].xoff = (float) x0; 1878 | chardata[i].yoff = (float) y0; 1879 | x = x + gw + 2; 1880 | if (y+gh+2 > bottom_y) 1881 | bottom_y = y+gh+2; 1882 | } 1883 | return bottom_y; 1884 | } 1885 | 1886 | void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule) 1887 | { 1888 | float d3d_bias = opengl_fillrule ? 0 : -0.5f; 1889 | float ipw = 1.0f / pw, iph = 1.0f / ph; 1890 | stbtt_bakedchar *b = chardata + char_index; 1891 | int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5); 1892 | int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5); 1893 | 1894 | q->x0 = round_x + d3d_bias; 1895 | q->y0 = round_y + d3d_bias; 1896 | q->x1 = round_x + b->x1 - b->x0 + d3d_bias; 1897 | q->y1 = round_y + b->y1 - b->y0 + d3d_bias; 1898 | 1899 | q->s0 = b->x0 * ipw; 1900 | q->t0 = b->y0 * iph; 1901 | q->s1 = b->x1 * ipw; 1902 | q->t1 = b->y1 * iph; 1903 | 1904 | *xpos += b->xadvance; 1905 | } 1906 | 1907 | ////////////////////////////////////////////////////////////////////////////// 1908 | // 1909 | // font name matching -- recommended not to use this 1910 | // 1911 | 1912 | // check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string 1913 | static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(const stbtt_uint8 *s1, stbtt_int32 len1, const stbtt_uint8 *s2, stbtt_int32 len2) 1914 | { 1915 | stbtt_int32 i=0; 1916 | 1917 | // convert utf16 to utf8 and compare the results while converting 1918 | while (len2) { 1919 | stbtt_uint16 ch = s2[0]*256 + s2[1]; 1920 | if (ch < 0x80) { 1921 | if (i >= len1) return -1; 1922 | if (s1[i++] != ch) return -1; 1923 | } else if (ch < 0x800) { 1924 | if (i+1 >= len1) return -1; 1925 | if (s1[i++] != 0xc0 + (ch >> 6)) return -1; 1926 | if (s1[i++] != 0x80 + (ch & 0x3f)) return -1; 1927 | } else if (ch >= 0xd800 && ch < 0xdc00) { 1928 | stbtt_uint32 c; 1929 | stbtt_uint16 ch2 = s2[2]*256 + s2[3]; 1930 | if (i+3 >= len1) return -1; 1931 | c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; 1932 | if (s1[i++] != 0xf0 + (c >> 18)) return -1; 1933 | if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1; 1934 | if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1; 1935 | if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1; 1936 | s2 += 2; // plus another 2 below 1937 | len2 -= 2; 1938 | } else if (ch >= 0xdc00 && ch < 0xe000) { 1939 | return -1; 1940 | } else { 1941 | if (i+2 >= len1) return -1; 1942 | if (s1[i++] != 0xe0 + (ch >> 12)) return -1; 1943 | if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1; 1944 | if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1; 1945 | } 1946 | s2 += 2; 1947 | len2 -= 2; 1948 | } 1949 | return i; 1950 | } 1951 | 1952 | int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) 1953 | { 1954 | return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((const stbtt_uint8*) s1, len1, (const stbtt_uint8*) s2, len2); 1955 | } 1956 | 1957 | // returns results in whatever encoding you request... but note that 2-byte encodings 1958 | // will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare 1959 | const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID) 1960 | { 1961 | stbtt_int32 i,count,stringOffset; 1962 | stbtt_uint8 *fc = font->data; 1963 | stbtt_uint32 offset = font->fontstart; 1964 | stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); 1965 | if (!nm) return NULL; 1966 | 1967 | count = ttUSHORT(fc+nm+2); 1968 | stringOffset = nm + ttUSHORT(fc+nm+4); 1969 | for (i=0; i < count; ++i) { 1970 | stbtt_uint32 loc = nm + 6 + 12 * i; 1971 | if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2) 1972 | && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) { 1973 | *length = ttUSHORT(fc+loc+8); 1974 | return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10)); 1975 | } 1976 | } 1977 | return NULL; 1978 | } 1979 | 1980 | static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id) 1981 | { 1982 | stbtt_int32 i; 1983 | stbtt_int32 count = ttUSHORT(fc+nm+2); 1984 | stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4); 1985 | 1986 | for (i=0; i < count; ++i) { 1987 | stbtt_uint32 loc = nm + 6 + 12 * i; 1988 | stbtt_int32 id = ttUSHORT(fc+loc+6); 1989 | if (id == target_id) { 1990 | // find the encoding 1991 | stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4); 1992 | 1993 | // is this a Unicode encoding? 1994 | if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) { 1995 | stbtt_int32 slen = ttUSHORT(fc+loc+8), off = ttUSHORT(fc+loc+10); 1996 | 1997 | // check if there's a prefix match 1998 | stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen); 1999 | if (matchlen >= 0) { 2000 | // check for target_id+1 immediately following, with same encoding & language 2001 | if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) { 2002 | stbtt_int32 slen = ttUSHORT(fc+loc+12+8), off = ttUSHORT(fc+loc+12+10); 2003 | if (slen == 0) { 2004 | if (matchlen == nlen) 2005 | return 1; 2006 | } else if (matchlen < nlen && name[matchlen] == ' ') { 2007 | ++matchlen; 2008 | if (stbtt_CompareUTF8toUTF16_bigendian((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen)) 2009 | return 1; 2010 | } 2011 | } else { 2012 | // if nothing immediately following 2013 | if (matchlen == nlen) 2014 | return 1; 2015 | } 2016 | } 2017 | } 2018 | 2019 | // @TODO handle other encodings 2020 | } 2021 | } 2022 | return 0; 2023 | } 2024 | 2025 | static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags) 2026 | { 2027 | stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name); 2028 | stbtt_uint32 nm,hd; 2029 | if (!stbtt__isfont(fc+offset)) return 0; 2030 | 2031 | // check italics/bold/underline flags in macStyle... 2032 | if (flags) { 2033 | hd = stbtt__find_table(fc, offset, "head"); 2034 | if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0; 2035 | } 2036 | 2037 | nm = stbtt__find_table(fc, offset, "name"); 2038 | if (!nm) return 0; 2039 | 2040 | if (flags) { 2041 | // if we checked the macStyle flags, then just check the family and ignore the subfamily 2042 | if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1; 2043 | if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1; 2044 | if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; 2045 | } else { 2046 | if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1; 2047 | if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1; 2048 | if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; 2049 | } 2050 | 2051 | return 0; 2052 | } 2053 | 2054 | int stbtt_FindMatchingFont(const unsigned char *font_collection, const char *name_utf8, stbtt_int32 flags) 2055 | { 2056 | stbtt_int32 i; 2057 | for (i=0;;++i) { 2058 | stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i); 2059 | if (off < 0) return off; 2060 | if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags)) 2061 | return off; 2062 | } 2063 | } 2064 | 2065 | #endif // STB_TRUETYPE_IMPLEMENTATION 2066 | --------------------------------------------------------------------------------