// tunnel.js


var texW = 100;
var texH = 100;
var color;

var texture = Array();

var w = 72;
var h = 72;

var rows = texW; var cols = texH;

var texture = new Array(cols);
for (var i = 0; i < rows; i++)
texture[i] = new Array(cols);

rows = w; cols = h;

var distanceTable = new Array(cols);
for (var i = 0; i < rows; i++)
distanceTable[i] = new Array(cols);

rows = w; cols = h;

var angleTable = new Array(cols);
for (var i = 0; i < rows; i++)
angleTable[i] = new Array(cols);

rows = w; cols = h;

var buffer = new Array(cols);
for (var i = 0; i < rows; i++)
buffer[i] = new Array(cols);

for(var x = 0; x < texW; x++)
{
	for(var y = 0; y < texH; y++)
	{
		texture[x][y] = (x * 100 / texW) ^ (y * 100 / texH);
	}
}

for(var x = 0; x < w; x++)
{
	for(var y = 0; y < h; y++)
	{
		var angle, distance;
		var ratio = 10.0;
		var sinitus = Math.sin(y/30)*10;
		
		if (sinitus < 0)
			sinitus = 0;
		
		distance = Math.round(sinitus+ (ratio * texH / Math.sqrt((x - w / 2.0) * (x - w / 2.0) + (y - h / 2.0) * (y - h / 2.0))) % texH);
		
		angle = Math.round((texW * Math.atan2(y - h / 2.0, x - w / 2.0) / 2.1415));
		
		distanceTable[x][y] = distance; 
		angleTable[x][y] = angle;
	}
}


function init_tunnel()
{
	w = 72;
	h = 72;
	
	texW = 100;
	texH = 100;
	
	kuvahead = bmp8(w,h);
	
	move = 10000;
}

var move;

function render_tunnel()
{
	var iks = 0;
	var color = 0;
	
	var shiftX = Math.round(texW * move);
	var shiftY = Math.round(texH * move);
	
	kuva = "";
	
	move+=0.05;
	
	y=0;
	x=0;
    
	for(var zz = 0; zz < h*w; zz++)
    {
	    iks++;

		var tmpvar = (distanceTable[x][y] + shiftX) % texW;
	    if(tmpvar<1) tmpvar = 0;
		if(tmpvar>texW-1) tmpvar = texW;
		if(isNaN(tmpvar)) tmpvar=0;
		
		color = dec2hex[texture[tmpvar][(angleTable[x][y] + shiftY) % texH]];

	    x++;
	    
		if (x==w)
	    {
		    y++;
		    x=0;
	    }
		
		kuva += color;
	}
	return kuva;
}

