<?php

$eol = "\r\n";

$canvasSizeX = 32;
$canvasSizeY = 24;

$img = imagecreatefrompng(__DIR__ . '/duo_tunnel_cafe_64x64.png');

/* make zx page */
$zxPage = array();
for ($y = 0; $y < 64; $y++) {
	$zxPage[$y] = array();
	for ($x = 0; $x < 256; $x++) {
		$zxPage[$y][$x] = 0;
	}
}

/* make texture in zx page */
$zxColorList = array(
	0x000000 => 0x00,
	0xFF0000 => 0x42 + 2*8,
	0xCB00CB => 0x03 + 3*8,
	0xFF00FF => 0x43 + 3*8,
	0x00CB00 => 0x04 + 4*8,
	0x00FF00 => 0x44 + 4*8,
	0xCBCB00 => 0x06 + 6*8,
	0xFFFF00 => 0x46 + 6*8,
	0xCBCBCB => 0x07 + 7*8,
	0xFFFFFF => 0x47 + 7*8,
);

for ($y = 0; $y < 64; $y++) {
	for ($x = 0; $x < 64; $x++) {
		$color = imagecolorat($img, $x, $y);
		$zxColor = $zxColorList[$color];
		$zxPage[$y][$x + 192] = $zxColor;
	}
}

$tY = 64 * 0.25;
$tX = 64 * 1.25;

for ($y = 0; $y < $canvasSizeY * 2; $y++) {
	$yy = $y - $canvasSizeY;
	for ($x = 0; $x < $canvasSizeX * 2; $x++) {
		$xx = $x - $canvasSizeX;
		//--- texture Y
		$calcU = round(256 * ($tY * atan2($yy, $xx) / pi()));
		//--- texture X
		$sqrt = sqrt(pow($xx, 2) + pow($yy, 2));
		if ($sqrt == 0) {
			$sqrt = 1;
		}
		$calcV = round(256 * $tX / pow($sqrt, 0.25));

		$low = $calcV & 255;
		$hi = floor($calcV/256);
		$zxPage[$x][$y*2] = $low;
		$zxPage[$x][$y*2+1] = $hi;

		$low = $calcU & 255;
		$hi = floor($calcU/256);
		$zxPage[$x][96 + $y*2] = $low;
		$zxPage[$x][96 + $y*2+1] = $hi;
	}
}


$f = fopen(__DIR__ . '/duo_tunnel_tbl.bin', 'wb');
for ($y = 0; $y < 64; $y++) {
	for ($x = 0; $x < 256; $x++) {
		fwrite($f, chr($zxPage[$y][$x]));
	}
}
fclose($f);

echo 'cos table' . $eol;
$rX = 12;
$rY = 10;
$fx = fopen(__DIR__ . '/duo_tunnel_cos_x.bin', 'wb');
$fy = fopen(__DIR__ . '/duo_tunnel_sin_y.bin', 'wb');
for ($i = 0; $i < 256; $i++) {
	$x = floor($canvasSizeX/2 + $rX * cos($i * pi() / 128));
	fwrite($fx, chr($x));
	$y = floor($canvasSizeY/2 + $rY * sin($i * pi() / 128));
	fwrite($fy, chr($y));
}

		
fclose($fy);
fclose($fx);