<?php
$eol = "\r\n";

// make circles
$img = imagecreatefrompng(__DIR__ . "/circle_sprites.png");
$code = '';
$colorList = array(
	0x000000 => 0,
	0x1E1E1E => 1,
	0x3E3E3E => 2,
	0x7E7E7E => 4,
	0xFFFFFF => 8,
);

for ($rl = 0; $rl < 2; $rl++) {
	for ($i = 0; $i < 11; $i++) {
		$code .= ';-----------------------' . $eol;
		$code .= 'SPR' . $i . ($rl == 1 ? 'X' : '') . $eol;
		for ($y = 0; $y < 26; $y++) {
			$line = array();
			$yy = $y + 3;
			for ($x = 0; $x < 13; $x++) {
				$xx = $i * 32 + $x * 2 + 3 - $rl; // +- $rl for buffers directions
				$color1 = imagecolorat($img, $xx, $yy);
				$color2 = imagecolorat($img, $xx + 1, $yy);
				$line[] = 16 * $colorList[$color1] + $colorList[$color2];
			}
			$line[] = 0;
			$code .= "\tDB\t" . implode(',', $line) . $eol;
		}
	}
}
file_put_contents(__DIR__ . "/circle_sprites.asm", $code);

// make palette
$colorArr = array();
$colorArr[0] = 0;
$colorArr[1] = 1;
$colorArr[2] = 3;
$colorArr[3] = 3;
for ($c = 4; $c < 8; $c++) {
	$colorArr[$c] = 7;
}
for ($c = 8; $c < 16; $c++) {
	$colorArr[$c] = 0;
}

$f = fopen(__DIR__ . "/3d_black_circles_palette.bin", "wb");
for ($c1 = 0; $c1 < 16; $c1++) {
	for ($c2 = 0; $c2 < 16; $c2++) {
		$color = 0x40 + $colorArr[$c1] + $colorArr[$c2] * 8;
		fwrite($f, chr($color));
	}
}
fclose($f);

// make 3d rotate tables
$angleSize = 128;
$maxXYZ = 21;
$minusXYZ = 21;
$minusAlpha = 21;

$zRast = -32;

$projCx = 32 + 16 + 3;
$projCy = 24 - 16 + 3;

$zxPage = array();
for ($z = 0; $z < $maxXYZ * 2 + 1; $z++) {
	$zxPage[$z] = array();
	for ($x = 0; $x < 256; $x++) {
		$zxPage[$z][$x] = 0;
	}
}


$angleHalf = $angleSize / 2;
for ($z = 0; $z < $maxXYZ * 2; $z++) {
	$zz = ($z - $minusAlpha) * 0.995;
	for ($i = 0; $i < $angleSize; $i++) {
		$zxPage[$z][$i] = round(4 * $zz * cos($i * pi() / $angleHalf));
	}
}

for ($i = 0; $i < 256; $i++) {
	$x = $i < 128 ? $i : $i - 256;
	$zxPage[$maxXYZ * 2][$i] = round($x / 4);
}


$pxMin = 9999999999;
$pxMax = 0;

for ($z = 0; $z < $maxXYZ * 2; $z++) {
	$zz = $z - $minusXYZ;
	for ($x = 0; $x < $maxXYZ * 2; $x++) {
		$xx = $x - $minusXYZ;
		$px = round($projCx + $zRast * $xx / ($zz + $zRast));
		$py = round($projCy + $zRast * $xx / ($zz + $zRast));

		$yyy = '(BUFF ' . ($py > 0 ? '+ ' : '- ') . abs($py * 64) . ')';

		$zxPage[$z][$angleSize + 2 * $x] = 'low ' . $yyy;
		$zxPage[$z][$angleSize + 2 * $x + 1] = 'high ' . $yyy;

		$pxMin = min($pxMin, $px);
		$pxMax = max($pxMax, $px);
		$zxPage[$z][$angleSize + $maxXYZ * 2 * 2 + $x] = $px;
	}
}

$code = '';
for ($z = 0; $z < $maxXYZ * 2 + 1; $z++) {
	$code .= ";------- #" . dechex($z+0xC0) . '00' . $eol;
	for ($x = 0; $x < 256; $x++) {
		$code .= "\tDB\t" . $zxPage[$z][$x] . "\t\t;#" . dechex($x) . $eol;
	}
}
file_put_contents(__DIR__ . "/3d_page.asm", $code);

echo 'projX: ' . ($angleSize + $maxXYZ * 2 * 2) . $eol;
echo 'pX: ' . $pxMin . ' .. ' . $pxMax . $eol;





echo 'ax step' . round(256 * 7/2.5) . $eol;
echo 'ay step' . round(256 * 3/2.5) . $eol;

