shithub: map

ref: a0578c7de4163344d936ea78191a836556495bba
dir: /img.c/

View raw version
#include <u.h>
#include <libc.h>
#include <draw.h>
#include <memdraw.h>
#include "dat.h"
#include "fns.h"

extern Image *mapimage;
extern int tilesize;
extern Point drawoffset;

ImageUpdated callbackfunc;

void
loadtile(GBundle b, Point pos)
{
	Image *loaded;
	int fd;
	char file[32];
	Rectangle r;
	
	r = Rect(0, 0, 256, 256);
	
	snprint(file, sizeof file, "/mnt/map/%d/%d/%d", b.z, b.x, b.y);
	debugprint("loading file: %s\n", file);
	
	fd = open(file, OREAD);
	if (fd < 0) {
		fprint(2, "unable to load tile %d/%d/%d: %r\n", b.z, b.x, b.y);
		return;
	}
	
	loaded = readimage(display, fd, 0);
	close(fd);
	
	lockmapimage();
	draw(mapimage, rectaddpt(r, pos), loaded, nil, ZP);
	if (debug) {
		snprint(file, sizeof file, "%d / %d", b.x, b.y);
		border(mapimage, rectaddpt(r, pos), 1, display->black, ZP);
		string(mapimage, pos, display->black, ZP, font, file);
	}
	unlockmapimage();
	
	freeimage(loaded);
}

static void
collapsebundle(GBundle *b, int mod)
{
	while (b->x < 0)
		b->x += mod;
	while (b->y < 0)
		b->y += mod;
	
	b->x = b->x % mod;
	b->y = b->y % mod;
}

void
requestimage(GBundle from, ImageUpdated cb)
{
	GBundle b;
	int numx, numy, mod;
	b.z = from.z;
	callbackfunc = cb;
	
	mod = 1;
	for (int i = 0; i < b.z; i++)
		mod *= 2;
	
	lockmapimage();
	if (!mapimage) {
		unlockmapimage();
		debugprint("cannot load tiles: no mapimage\n");
		return;
	}
	numx = Dx(mapimage->r)/tilesize + 1;
	numy = Dy(mapimage->r)/tilesize + 1;
	unlockmapimage();
	
	debugprint("loading tiles from %d/%d\n", from.x, from.y);
	
	for (int x = 0; x < numx; x++) {
		for (int y = 0; y < numy; y++) {
			b.x = from.x + x;
			b.y = from.y + y;
			collapsebundle(&b, mod);
			loadtile(b, Pt(
				x * tilesize,
				y * tilesize)
			);
		}
	}
	
	if (callbackfunc)
		callbackfunc();
}