Mirai's Miscellaneous Misadventures

M30 / core / text.c

// copyright 2022 zamfofex
// license: AGPLv3 or later

#include <mimimi/engines.h>
#include <mimimi/chapters.h>
#include <mimimi/fonts.h>
#include <mimimi/ground.h>
#include <mimimi/assets.h>

static void mimimi_stamp_glyph(struct mimimi_image *target, int x0, int y0, struct mimimi_image *source)
{
	for (int y1 = 0 ; y1 < source->height ; y1++)
	for (int x1 = 0 ; x1 < source->width ; x1++)
	{
		int x = x0 + x1;
		int y = y0 + y1;
		
		if (x < 0) continue;
		if (y < 0) continue;
		
		if (x >= target->width) continue;
		if (y >= target->height) continue;
		
		unsigned char color = source->colors[x1 + y1 * source->width];
		if (color == 0) continue;
		
		target->colors[x + y * target->width] = color;
	}
}

int mimimi_measure_text(struct mimimi_image *glyphs, char *text)
{
	int x = 0;
	while (*text != 0)
	{
		char ch = *text++;
		
		if (ch == 0x20)
		{
			x += 4;
			continue;
		}
		
		if (ch <= 0x20) continue;
		if (ch >= 0x7F) continue;
		
		struct mimimi_image *glyph = glyphs + (ch - 0x20);
		x += glyph->width - 1;
	}
	
	return x;
}

int mimimi_text(struct mimimi_image *image, struct mimimi_image *glyphs, int x, int y, char *text)
{
	while (*text != 0)
	{
		char ch = *text++;
		
		if (ch == 0x20)
		{
			x += 4;
			continue;
		}
		
		if (ch <= 0x20) continue;
		if (ch >= 0x7F) continue;
		
		struct mimimi_image *glyph = glyphs + (ch - 0x20);
		
		mimimi_stamp_glyph(image, x - 1, y - glyph->height + 6, glyph);
		x += glyph->width - 1;
	}
	
	return x;
}