Coder Social home page Coder Social logo

fontstash's Introduction

This project is not actively maintained.

Font Stash

Font stash is light-weight online font texture atlas builder written in C. It uses stb_truetype to render fonts on demand to a texture atlas.

The code is split in two parts, the font atlas and glyph quad generator fontstash.h, and an example OpenGL backend (glstash.h.

Screenshot

screenshot of some text rendered witht the sample program

Example

// Create GL stash for 512x512 texture, our coordinate system has zero at top-left.
struct FONScontext* fs = glfonsCreate(512, 512, FONS_ZERO_TOPLEFT);

// Add font to stash.
int fontNormal = fonsAddFont(fs, "sans", "DroidSerif-Regular.ttf");

// Render some text
float dx = 10, dy = 10;
unsigned int white = glfonsRGBA(255,255,255,255);
unsigned int brown = glfonsRGBA(192,128,0,128);

fonsSetFont(fs, fontNormal);
fonsSetSize(fs, 124.0f);
fonsSetColor(fs, white);
fonsDrawText(fs, dx,dy,"The big ", NULL);

fonsSetSize(fs, 24.0f);
fonsSetColor(fs, brown);
fonsDrawText(fs, dx,dy,"brown fox", NULL);

Using Font Stash in your project

In order to use fontstash in your own project, just copy fontstash.h, stb_truetype.h, and potentially glstash.h to your project. In one C/C++ define FONTSTASH_IMPLEMENTATION before including the library to expand the font stash implementation in that file.

#include <stdio.h>					// malloc, free, fopen, fclose, ftell, fseek, fread
#include <string.h>					// memset
#define FONTSTASH_IMPLEMENTATION	// Expands implementation
#include "fontstash.h"
#include <GLFW/glfw3.h>				// Or any other GL header of your choice.
#define GLFONTSTASH_IMPLEMENTATION	// Expands implementation
#include "glfontstash.h"

Creating new rendering backend

The default rendering backend uses OpenGL to render the glyphs. If you want to render the text using some other API, or want tighter integration with your code base you can write your own rendering backend. Take a look at the glfontstash.h for reference implementation.

The rendering interface FontStash assumes access to is defined in the FONSparams structure. The renderer initialization function is assumed to fill in the FONSparams structure and call fonsCreateInternal to create the FontStash context.

struct FONSparams {
	...
	void* userPtr;
	int (*renderCreate)(void* uptr, int width, int height);
	int (*renderResize)(void* uptr, int width, int height);
	void (*renderUpdate)(void* uptr, int* rect, const unsigned char* data);
	void (*renderDraw)(void* uptr, const float* verts, const float* tcoords, const unsigned int* colors, int nverts);
	void (*renderDelete)(void* uptr);
};
  • renderCreate is called to create renderer for specific API, this is where you should create a texture of given size.
    • return 1 of success, or 0 on failure.
  • renderResize is called to resize the texture. Called when user explicitly expands or resets the atlas texture.
    • return 1 of success, or 0 on failure.
  • renderUpdate is called to update texture data
    • rect describes the region of the texture that has changed
    • data pointer to full texture data
  • renderDraw is called when the font triangles should be drawn
    • verts pointer to vertex position data, 2 floats per vertex
    • tcoords pointer to texture coordinate data, 2 floats per vertex
    • colors pointer to color data, 1 uint per vertex (or 4 bytes)
    • nverts is the number of vertices to draw
  • renderDelete is called when the renderer should be deleted
  • userPtr is passed to all calls as first parameter

FontStash uses this API as follows:

fonsDrawText() {
	foreach (glyph in input string) {
		if (internal buffer full) {
			updateTexture()
			render()
		}
		add glyph to interal draw buffer
	}
	updateTexture()
	render()
}

The size of the internal buffer is defined using FONS_VERTEX_COUNT define. The default value is 1024, you can override it when you include fontstash.h and specify the implementation:

#define FONS_VERTEX_COUNT 2048
#define FONTSTASH_IMPLEMENTATION	// Expands implementation
#include "fontstash.h"

Compiling

In order to compile the demo project, your will need to install GLFW to compile.

FontStash example project uses premake4 to build platform specific projects, now is good time to install it if you don't have it already. To build the example, navigate into the root folder in your favorite terminal, then:

  • OS X: premake4 xcode4
  • Windows: premake4 vs2010
  • Linux: premake4 gmake

See premake4 documentation for full list of supported build file types. The projects will be created in build folder. An example of building and running the example on OS X:

$ premake4 gmake
$ cd build/
$ make
$ ./example

License

The library is licensed under zlib license

Links

Uses stb_truetype for font rendering.

fontstash's People

Contributors

aktau avatar elaverick avatar elmindreda avatar johnbartholomew avatar memononen avatar mrautio avatar shinjin-cr avatar suikki avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fontstash's Issues

Blending only works partially

Thanks a lot for providing this library! We are currently converting our project to use it and it may be entirely my lack of GL understanding but I am not able to make the blending work out correctly. Some background polygons are blended correctly but some are not, see the picture. Sometimes the streets are blended correctly (see for instance the "am" of the upper amenity.restaurant) but sometimes not (see the last "a" in the same text). Every street has the same z value while the text is drawn slightly above. The code for text drawing is here: https://github.com/planetsumo/sumo/blob/master/sumo/src/utils/gui/div/GLHelper.cpp#L458 Any help is welcome!
grafik

Newline wrapping

Any plans to add text wrapping (on newline)? Specifically, in the text iteration functions used by NanoVG.

I've started to look into it, and got the simple (left-align) case working, but it gets complicated with right/center alignment. I'm not yet familiar enough with fons__decutf8() to scan for newlines without it crashing. I'd like to get your thoughts/plans before pursuing it further.

Access violation on fons__getState

Trying to incorporate the example code into a project, but when the software makes the call to fonsSetFont, I receive an access violation on fons__getState

I've included a sample of the code below

    struct FONScontext* fs = glfonsCreate(512, 512, FONS_ZERO_TOPLEFT);
int fontNormal = fonsAddFont(fs, "sans", "../DATA/Fonts/apercu-regular.ttf");
fonsSetFont(fs, fontNormal);
fonsSetSize(fs, 64.0f);
fonsDrawText(fs, dx, dy,text, NULL);

Android example with Opengl ES 2.0

Hi People, please has someone working simple example for android? Or if is someone interested in help then I can create android container for testing with ndk and opengl es 2.0, but I don't know how to integrate fontstash...

align member of fontstash_style + gcc/clang warnings

I've been adding warning flags in the Makefile and of course some stuff rolls out here and there. For example the align member of fontstash_style doesn't seem to be used anywhere (nor initialized). Is that meant to be? Or is that some sort of reminder to you that it still needs to be implemented?

Would you like to make the project as pedantic-free as possible or would you rather keep it simple?

The reason I ask is because in my project I mostly turn the warnings up to 11, so when I include external files they usually trigger a bunch of things, I like to fix it at the root if possible.

I'd also like to add a static analyzing target in the makefile for the LLVM static analyzer, which has helped me track down a lot of stuff in the past (to show that I'm not entirely crazy, John Carmack seems to agree with me :)).

If you're not ok with any of these things, then that's cool of course! I'll be just as happy to maintain a personal fork :).

fontstash improvements from other forks

Hi,

I have used a previous fork of font-stash from here:
https://github.com/akrinke/Font-Stash/

I used it at the time because it added two useful features we needed (taken from the readme):

  • Added ability to load an arbitrary number of fonts (not just four)
  • Use multiple OpenGL textures for glyph caching (not just one)

However, now we need the graphics layer abstraction that you have added to the original fontstash because of changes in the rendering code we have planned in our game (Bitfighter.)

Does the current iteration supports the two features above? And if not, would they be worthwhile to integrate?

Thanks!

Missing spacing in fons__getQuad() ?

When calculating the advance in fons__getQuad(), on line 1244:

*x += (int)(glyph->xadv / 10.0f + 0.5f);

Shouldn't the spacing be added somewhere like it is on line 1203:

*x += (int)(adv + spacing + 0.5f);

When you set -1 as letter spacing in nanovg, the result looks as if it set to 0.

Need some kind of indication when the glyph cache is full

So I started using fontstash, and I gave it a pretty small glyph cache size (128x128) because I knew I had very few different characters I needed to render, and then my thing got a little more complicated and I added a little more text, and suddenly it started just skipping characters. I thought I was going completely mad. How could it just be skipping characters? Like, it was fine except text containing the digit '5' would just leave that digit out, and sometimes it would skip '3's as well.

I spent ages tracking this down, and what was the problem? Of course it had just run out of space in the glyph cache. And with hindsight that's totally obvious -- what else could it be, right? But the trouble is that hindsight doesn't actually help to debug stuff, it only helps to make you feel dumb once you work out what the problem is.

So... I think fontstash needs to do something more useful when it can't fit a glyph into the cache texture. It doesn't have to auto-resize the texture or have some smart cache replacement policy, or even a dumb cache replacement policy. I just mean it needs to give some obvious and immediate indication that the cache texture has run out of space. Like, it could printf("FONT STASH SAYS: OH SHIT WE'RE OUT OF SPACE!\n"); or whatever.

I'd make a pull request, but I don't know how you'd prefer this error condition be handled.

some glyphs display wrong

I use fontstash to draw a str = @"i:ə:ɔ:u:ɑ:i:ɜ:ɔ:u:ɑ:iɜɔuɑ", the glyph of "ɜ" display wrong.
use "PingFangSC-Regular"
image
use "SFUIText-Light"
image
use "HelveticaNeue"
image

addtional, I suggest updating stb_trunetype to the latest version in order to support OpenType format, which internal use of the CCF table.

build failure using freetype.

static int fons__tt_init()
{
FT_Error ftError;
FONS_NOTUSED(context); ---- wrong.
ftError = FT_Init_FreeType(&ftLibrary);
return ftError == 0;
}

opengl3 example?

Is there any chance someone could either add an OpenGL 3 version of the example application or tweak the existing one to work with the new header? A naive substitution doesn't appear to produce a working test, unless I'm missing something...

No fonts, just dashes

I've pulled latest fontstash and glfw ( glfw-3.0.3 ), building the example.c file, and only seeing a blank screen with dashes on it:

image

I'm a complete opengl newbie ( though seasoned C/C++ programmer ), so any help to getting the sample text to render would be appreciated!

Thanks!

why need to xadvance * 10.0f?

why need to xadvance * 10.0f?

glyph->xadv = (short)(scale * advance * 10.0f)
*x += (int)(glyph->xadv / 10.0f + 0.5f);

glFonsCreate help!

Trying to include your library into my little game engine, but when i try to include glFontStash.h compiler (visual studio 2013) gives me hundreds of errors.
if i don't include it i can't call glFonsCreate!
i've included it so:

#include <stdio.h>                  // malloc, free, fopen, fclose, ftell, fseek, fread
#include <string.h>                 // memset
#define FONTSTASH_IMPLEMENTATION    // Expands implementation
#include "fontstash.h"
#define GLFONTSTASH_IMPLEMENTATION  // Expands implementation
#include "glfontstash.h"

Example does not build on mac

I am using 10.9 with Xcode 5.0.2 and I get this when I try to build:

$ make
==== Building example (debug) ====
Linking example
Undefined symbols for architecture x86_64:
"_CVDisplayLinkCreateWithCGDisplay", referenced from:
__glfwPlatformGetVideoModes in libglfw3.a(cocoa_monitor.o)
__glfwPlatformGetVideoMode in libglfw3.a(cocoa_monitor.o)
"_CVDisplayLinkGetNominalOutputVideoRefreshPeriod", referenced from:
_vidmodeFromCGDisplayMode in libglfw3.a(cocoa_monitor.o)
"_CVDisplayLinkRelease", referenced from:
__glfwPlatformGetVideoModes in libglfw3.a(cocoa_monitor.o)
__glfwPlatformGetVideoMode in libglfw3.a(cocoa_monitor.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

It now works when I add -framework CoreVideo to LDFLAGS.

glfw linker option needed on Linux

Hi, on my Arch Linux system I had to add glfw to the linker options.

Thanks

diff --git a/premake4.lua b/premake4.lua
index b52cfcc..354e52f 100644
--- a/premake4.lua
+++ b/premake4.lua
@@ -14,7 +14,7 @@ solution "fontstash"
                targetdir("build")

                configuration { "linux" }
-                        links { "X11","Xrandr", "rt", "GL", "GLU", "pthread" }
+                        links { "X11","Xrandr", "rt", "GL", "GLU", "pthread", "glfw" }

                configuration { "windows" }
                        defines { "_CRT_SECURE_NO_WARNINGS" }
@@ -40,7 +40,7 @@ solution "fontstash"
                targetdir("build")

                configuration { "linux" }
-                        links { "X11","Xrandr", "rt", "GL", "GLU", "pthread" }
+                        links { "X11","Xrandr", "rt", "GL", "GLU", "pthread", "glfw" }

                configuration { "windows" }
                        defines { "_CRT_SECURE_NO_WARNINGS" }

Can't compile example under VS2010

Downloaded both GLFW and Fontstash. Run premake4 vs2010 to generate project files.
Set paths to GLFW in VS Directories tab on the project.
Compile and get the following errors:
Warning 17 warning C4024: 'fons__blur' : different types for formal and actual parameter 2 684
Warning 13 warning C4024: 'stbtt_MakeGlyphBitmap' : different types for formal and actual parameter 2 665
Warning 12 warning C4047: 'function' : 'unsigned char *' differs in levels of indirection from 'int' 665
Warning 16 warning C4047: 'function' : 'unsigned char *' differs in levels of indirection from 'int' 684
Warning 3 warning C4047: 'return' : 'void *' differs in levels of indirection from 'int' 212
Warning 20 warning C4133: 'function' : incompatible types - from 'int *' to 'float *' 818
Warning 23 warning C4133: 'function' : incompatible types - from 'int *' to 'float *' 821
Error 6 error C2065: 'alpha' : undeclared identifier 568
Error 7 error C2065: 'alpha' : undeclared identifier 569
Error 8 error C2065: 'alpha' : undeclared identifier 570
Error 9 error C2065: 'alpha' : undeclared identifier 571
Error 15 error C2065: 'bdst' : undeclared identifier 684
Error 53 error C2065: 'black' : undeclared identifier 258
Error 49 error C2065: 'blue' : undeclared identifier 194
Error 47 error C2065: 'brown' : undeclared identifier 170
Error 11 error C2065: 'dst' : undeclared identifier 665
Error 27 error C2065: 'font' : undeclared identifier 940
Error 29 error C2065: 'font' : undeclared identifier 943
Error 32 error C2065: 'font' : undeclared identifier 945
Error 35 error C2065: 'font' : undeclared identifier 947
Error 41 error C2065: 'h' : undeclared identifier 57
Error 31 error C2065: 'isize' : undeclared identifier 943
Error 34 error C2065: 'isize' : undeclared identifier 945
Error 37 error C2065: 'isize' : undeclared identifier 947
Error 2 error C2065: 'ptr' : undeclared identifier 212
Error 40 error C2065: 'w' : undeclared identifier 57
Error 46 error C2065: 'white' : undeclared identifier 165
Error 48 error C2065: 'white' : undeclared identifier 175
Error 50 error C2065: 'white' : undeclared identifier 203
Error 51 error C2065: 'white' : undeclared identifier 216
Error 52 error C2065: 'white' : undeclared identifier 249
Error 54 error C2065: 'white' : undeclared identifier 263
Error 19 error C2065: 'width' : undeclared identifier 818
Error 21 error C2065: 'width' : undeclared identifier 819
Error 22 error C2065: 'width' : undeclared identifier 821
Error 24 error C2065: 'width' : undeclared identifier 822
Error 1 error C2143: syntax error : missing ';' before 'type' 210
Error 4 error C2143: syntax error : missing ';' before 'type' 566
Error 5 error C2143: syntax error : missing ';' before 'type' 567
Error 10 error C2143: syntax error : missing ';' before 'type' 664
Error 14 error C2143: syntax error : missing ';' before 'type' 683
Error 18 error C2143: syntax error : missing ';' before 'type' 813
Error 25 error C2143: syntax error : missing ';' before 'type' 938
Error 26 error C2143: syntax error : missing ';' before 'type' 939
Error 38 error C2143: syntax error : missing ';' before 'type' 50
Error 39 error C2143: syntax error : missing ';' before 'type' 51
Error 42 error C2143: syntax error : missing ';' before 'type' 143
Error 43 error C2143: syntax error : missing ';' before 'type' 144
Error 44 error C2143: syntax error : missing ';' before 'type' 145
Error 45 error C2143: syntax error : missing ';' before 'type' 146
Error 30 error C2223: left of '->ascender' must point to struct/union 943
Error 28 error C2223: left of '->data' must point to struct/union 940
Error 33 error C2223: left of '->descender' must point to struct/union 945
Error 36 error C2223: left of '->lineh' must point to struct/union 947

better atlas layout

I was tinkering somewhat with the code and ended up implementing the skyline bottom-left binpacking heuristic that's also used in the freetype-gl project. I find it produces nice results. Images for comparison below.

old:

screen shot 2013-11-04 at 12 14 51

skyline bottom-left:

screen shot 2013-11-04 at 12 15 11

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.