Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <sys/mman.h>
- #include <SDL.h>
- #define STB_TRUETYPE_IMPLEMENTATION
- #include "stb_truetype.h"
- int main(int argc, char **argv) {
- if (argc != 2) {
- printf("usage: fonttest <text>\n");
- exit(-1);
- }
- int fontfd = open("/usr/share/fonts/truetype/msttcorefonts/arialbd.ttf", O_RDONLY);
- if (fontfd < 0) {
- perror("couldn't open font file");
- exit(1);
- }
- struct stat st;
- if (fstat(fontfd, &st) < 0) {
- perror("couldn't stat font file");
- close(fontfd);
- exit(1);
- }
- void *fontdata = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fontfd, 0);
- if (!fontdata) {
- perror("couldn't map font file");
- close(fontfd);
- exit(1);
- }
- if (SDL_Init(SDL_INIT_VIDEO) < 0) {
- fprintf(stderr, "sdl init failed: %s\n", SDL_GetError());
- munmap(fontdata, st.st_size);
- close(fontfd);
- exit(1);
- }
- SDL_Surface *glyphdata = SDL_CreateRGBSurface(SDL_SWSURFACE, 512, 512, 8, 0, 0, 0, 0);
- if (!glyphdata) {
- fprintf(stderr, "couldn't create sdl buffer: %s\n", SDL_GetError());
- munmap(fontdata, st.st_size);
- close(fontfd);
- SDL_Quit();
- exit(1);
- }
- SDL_Color colors[256];
- for(int i = 0; i < 256; i++){
- colors[i].r=i;
- colors[i].g=i;
- colors[i].b=i;
- }
- SDL_SetPalette(glyphdata, SDL_LOGPAL|SDL_PHYSPAL, colors, 0, 256);
- stbtt_bakedchar cdata[96];
- stbtt_BakeFontBitmap(fontdata, stbtt_GetFontOffsetForIndex(fontdata, 0), 32.0, glyphdata->pixels, 512, 512, 32, 96, cdata);
- munmap(fontdata, st.st_size);
- close(fontfd);
- SDL_Surface *s = SDL_SetVideoMode(640, 480, 32, 0);
- if (!s) {
- fprintf(stderr, "sdl video mode init failed: %s\n", SDL_GetError());
- SDL_FreeSurface(glyphdata);
- SDL_Quit();
- exit(1);
- }
- float x = 0, y = 0;
- for (char *c = argv[1]; *c; c++) {
- stbtt_aligned_quad q;
- stbtt_GetBakedQuad(cdata, 512, 512, *c-32, &x, &y, &q, 1);
- int w = q.x1-q.x0;
- int h = q.y1-q.y0;
- SDL_Rect src = { .x = q.s0*512, .y = q.t0*512, .w = w, .h = h };
- SDL_Rect dest = { .x = q.x0, .y = 32+q.y0, .w = w, .h = h };
- SDL_BlitSurface(glyphdata, &src, s, &dest);
- }
- SDL_FreeSurface(glyphdata);
- SDL_Event e;
- while(SDL_WaitEvent(&e) && e.type != SDL_KEYDOWN && e.key.keysym.sym != SDLK_ESCAPE );
- SDL_FreeSurface(s);
- SDL_Quit();
- exit(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement