3dphotoshoot

view src/text.c @ 22:d7fe157c402d

fonts
author John Tsiombikas <nuclear@member.fsf.org>
date Sat, 13 Jun 2015 05:32:07 +0300
parents
children
line source
1 #include <stdio.h>
2 #include <stdarg.h>
3 #include <alloca.h>
4 #include "game.h"
5 #include "text.h"
6 #include "sdr.h"
7 #include "opengl.h"
8 #include "sanegl.h"
9 #include "drawtext/drawtext.h"
11 #define FONT_NAME "consolas_s24.glyphmap"
12 #define FONT_SIZE 24
14 static struct dtx_font *font;
15 static unsigned int prog;
16 static int uloc_color = -1;
17 static int aloc_vertex, aloc_texcoords;
18 static float color[4];
19 static int cpos[2];
20 static int line_height;
22 static int init(void)
23 {
24 if(font) return 0; /* already initialized */
26 if(!(font = dtx_open_font_glyphmap("data/" FONT_NAME))) {
27 fprintf(stderr, "failed to open font\n");
28 return -1;
29 }
30 line_height = dtx_line_height();
32 if(!(prog = create_program_load("sdr/vertex.glsl", "sdr/font.p.glsl"))) {
33 dtx_close_font(font);
34 font = 0;
35 return -1;
36 }
37 aloc_vertex = glGetAttribLocation(prog, "attr_vertex");
38 aloc_texcoords = glGetAttribLocation(prog, "attr_texcoord");
39 uloc_color = glGetUniformLocation(prog, "color");
41 return 0;
42 }
44 void text_color(float r, float g, float b, float a)
45 {
46 color[0] = r;
47 color[1] = g;
48 color[2] = b;
49 color[3] = a;
50 }
52 void text_position(int x, int y)
53 {
54 cpos[0] = x;
55 cpos[1] = y;
56 }
58 static int pre_print(void)
59 {
60 int top = win_height - line_height;
62 if(init() == -1) {
63 return -1;
64 }
66 gl_matrix_mode(GL_TEXTURE);
67 gl_push_matrix();
68 gl_load_identity();
69 gl_matrix_mode(GL_PROJECTION);
70 gl_push_matrix();
71 gl_load_identity();
72 gl_ortho(0, win_width, 0, win_height, -1, 1);
73 gl_matrix_mode(GL_MODELVIEW);
74 gl_push_matrix();
75 gl_load_identity();
76 gl_translatef(cpos[0] * dtx_glyph_width(' '), top - cpos[1] * line_height, 0);
78 glUseProgram(prog);
79 glUniform4fv(uloc_color, 1, color);
81 gl_apply_xform(prog);
83 dtx_use_font(font, FONT_SIZE);
84 dtx_vertex_attribs(aloc_vertex, aloc_texcoords);
85 return 0;
86 }
88 static void post_print(void)
89 {
90 gl_matrix_mode(GL_TEXTURE);
91 gl_pop_matrix();
92 gl_matrix_mode(GL_PROJECTION);
93 gl_pop_matrix();
94 gl_matrix_mode(GL_MODELVIEW);
95 gl_pop_matrix();
96 }
98 void text_print(const char *s)
99 {
100 if(pre_print() == -1) {
101 return;
102 }
104 dtx_string(s);
106 post_print();
107 }
109 void text_printf(const char *fmt, ...)
110 {
111 va_list ap;
112 int buf_size;
113 char *buf, tmp;
115 if(pre_print() == -1) {
116 return;
117 }
119 va_start(ap, fmt);
120 buf_size = vsnprintf(&tmp, 0, fmt, ap);
121 va_end(ap);
123 if(buf_size == -1) {
124 buf_size = 512;
125 }
127 buf = alloca(buf_size + 1);
128 va_start(ap, fmt);
129 vsnprintf(buf, buf_size + 1, fmt, ap);
130 va_end(ap);
132 dtx_string(buf);
134 post_print();
135 }