aboutsummaryrefslogtreecommitdiff
path: root/src/graphics/text.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/graphics/text.c')
-rw-r--r--src/graphics/text.c65
1 files changed, 65 insertions, 0 deletions
diff --git a/src/graphics/text.c b/src/graphics/text.c
new file mode 100644
index 0000000..204d1e0
--- /dev/null
+++ b/src/graphics/text.c
@@ -0,0 +1,65 @@
+#include "../../include/mgl/graphics/text.h"
+#include "../../include/mgl/graphics/font.h"
+#include "../../include/mgl/mgl.h"
+
+int mgl_text_init(mgl_text *self, mgl_font *font, const char *text, float x, float y) {
+ self->font = font;
+ self->text = text;
+ self->color = (mgl_color){ 1.0f, 1.0f, 1.0f, 1.0f };
+ self->position = (mgl_vec2f){ x, y };
+ return 0;
+}
+
+void mgl_text_deinit(mgl_text *self) {
+
+}
+
+static void mgl_text_draw_glyph(mgl_context *context, mgl_font_glyph *glyph, mgl_vec2f position) {
+ context->gl.glTexCoord2f(glyph->texture_position.x, glyph->texture_position.y);
+ context->gl.glVertex3f(position.x + glyph->position.x, position.y + glyph->position.y, 0.0f);
+
+ context->gl.glTexCoord2f(glyph->texture_position.x + glyph->texture_size.x, glyph->texture_position.y);
+ context->gl.glVertex3f(position.x + glyph->position.x + glyph->size.x, position.y + glyph->position.y, 0.0f);
+
+ context->gl.glTexCoord2f(glyph->texture_position.x + glyph->texture_size.x, glyph->texture_position.y + glyph->texture_size.y);
+ context->gl.glVertex3f(position.x + glyph->position.x + glyph->size.x, position.y + glyph->position.y + glyph->size.y, 0.0f);
+
+ context->gl.glTexCoord2f(glyph->texture_position.x, glyph->texture_position.y + glyph->texture_size.y);
+ context->gl.glVertex3f(position.x + glyph->position.x, position.y + glyph->position.y + glyph->size.y, 0.0f);
+}
+
+/* TODO: Use opengl buffer object instead */
+/* TODO: Cache texture bind to not bind texture if its already bound and do not bind texture 0 */
+void mgl_text_draw(mgl_context *context, mgl_text *text) {
+ const char *str = text->text;
+ mgl_font_glyph glyph;
+ mgl_vec2f position = text->position;
+ position.y += text->font->size;
+
+ context->gl.glColor4f(text->color.r, text->color.g, text->color.b, text->color.a);
+ context->gl.glBindTexture(GL_TEXTURE_2D, text->font->texture.id);
+ context->gl.glBegin(GL_QUADS);
+ while(*str) {
+ unsigned char c = *(unsigned char*)str;
+ if((c >= 32 && c < 128)) {
+ if(mgl_font_get_glyph(text->font, c, &glyph) == 0) {
+ mgl_text_draw_glyph(context, &glyph, position);
+ position.x += glyph.advance;
+ }
+ } else if(c == '\t') {
+ if(mgl_font_get_glyph(text->font, ' ', &glyph) == 0) {
+ const int tab_width = 4;
+ for(int i = 0; i < tab_width; ++i) {
+ mgl_text_draw_glyph(context, &glyph, position);
+ position.x += glyph.advance;
+ }
+ }
+ } else if(c == '\n') {
+ position.x = text->position.x;
+ position.y += text->font->size;
+ }
+ ++str;
+ }
+ context->gl.glEnd();
+ context->gl.glBindTexture(GL_TEXTURE_2D, 0);
+}