require("lualibs.common")

print "hello from lua"

--boardname = "simplesub.map"
boardname = "newboard-maki.map"



-- gets called when board is loaded. gets a table as parameter which describes player position
function init(initpos, hotload)
	print(string.format("init called! %f,%f,%f", initpos.x, initpos.y, initpos.z ) )
	if not hotload then
		mypos = initpos
	end
end


ang = 0.0
yvel = 0

gip = 0
curframe = 0

onground = false


function sclfunc(p)
	--return (x - midpx)*scl + scrx, (y - midpy)*scl + scry
	--print("dumppi",dump(p))
	s1 = p - midp
	s2 = s1*scl
	s3 = s2 + scrpos
	return s3
end

-- gets called every frame before drawrooms. returns a table with camera position
function frame()
	--print("frame called!")


	turnspeed = 6
	speed = 0.004
	upspeed = 50
	if (getkeystatus(0x2a)) then
		speed = 0.009
		turnspeed = 15
	end

	if onground then -- go ahead and jump
		upspeed=200
	end

	wantmoveforward = 0
	wantmoveang = 0
	wantmoveup = 0

	angrad = mypos.ang * math.pi / 1024.0
	dirx = math.cos(angrad)
	diry = math.sin(angrad)

	if (getkeystatus(0xc8)) then
		wantmoveforward = speed
	end
	if (getkeystatus(0xd0)) then
		wantmoveforward = -speed
	end

	if (getkeystatus(0xcb)) then
		wantmoveang = -turnspeed
	end

	if (getkeystatus(0xcd)) then
		wantmoveang = turnspeed
	end

	if (getkeystatus(0x1e)) then
		wantmoveup = -upspeed
	end

	if (getkeystatus(0x2c)) then
		wantmoveup = upspeed
	end



--	mypos.x = mypos.x + dirx * wantmoveforward
--	mypos.y = mypos.y + diry * wantmoveforward

	mypos.ang = mypos.ang + wantmoveang


--//clipmove(long *x, long *y, long *z, short *sectnum,
--//			long xvect, long yvect,
--         //long walldist, long ceildist, long flordist,
--//			unsigned long cliptype)

	--print("pos bef",mypos.x, mypos.y, mypos.z, mypos.sect)

	vx = dirx * wantmoveforward * 16384
	vy = diry * wantmoveforward * 16384

	--print("vel",vx,vy)

	mypos.x, mypos.y, mypos.z, mypos.sect, hit = clipmove(
		mypos.x, mypos.y, mypos.z, mypos.sect,
		vx,vy,
		128, 128, 128, 65537)

	yvel = wantmoveup

	mypos.z = mypos.z + yvel

	--print("pos aft",mypos.x, mypos.y, mypos.z, mypos.sect, "hit", hit)

	ceilz, _ , florz, _ = getzrange(mypos.x, mypos.y, mypos.z, mypos.sect, 128, 65535)
	--print("ceil, flor", ceilz, florz)

	florz = florz - 300
	ceilz = ceilz + 300

	if mypos.z > florz then
		mypos.z = florz
		yvel = 0
		onground = true
	elseif mypos.z < ceilz then
		mypos.z = ceilz
		yvel = 0
	else
		onground = false
	end



	drawrooms(mypos.x, mypos.y, mypos.z, mypos.ang, 100, mypos.sect)
	drawmasks()
	--drawmapview(mypos.x, mypos.y, 900, mypos.ang)



end
