-- LUALOCALS < ---------------------------------------------------------
local klots, math, minetest
    = klots, math, minetest
local math_abs, math_deg
    = math.abs, math.deg
-- LUALOCALS > ---------------------------------------------------------

local modname = minetest.get_current_modname()

minetest.register_on_joinplayer(function(player)
		player:set_nametag_attributes({
				text = " ",
				color = {a = 0, r = 0, g = 0, b = 0}
			})
		player:set_properties({
				visual = "mesh",
				visual_size = {x = 0.9, y = 0.9, z = 0.9},
				mesh = modname .. "_model.b3d",
				textures = {modname .. "_skin.png"}
			})
	end)

local anims = {
	stand = {x = 0, y = 0},
	walk = {x = 3, y = 27},
	walk_mine = {x = 28, y = 52},
	mine = {x = 53, y = 77},
}

local pitch_mult = 2/3
local pitch_max = 60
local pitch_min = -15
local pitch_precision = 1

klots.register_playerstep(function(player, data)
		local pitch = -math_deg(player:get_look_vertical()) * pitch_mult
		if pitch < pitch_min then pitch = pitch_min end
		if pitch > pitch_max then pitch = pitch_max end
		if not (data.headpitch and math_abs(data.headpitch - pitch)
			< pitch_precision) then
			data.headpitch = pitch
			player:set_bone_position("Head",
				{x = 0, y = 1/2, z = -pitch / 45},
				{x = pitch, y = 0, z = 0}
			)
		end

		local function setanim(anim, speedmod)
			anim.speed = 30 * (speedmod or 1)
			if data.anim and data.anim.x == anim.x
			and data.anim.y == anim.y
			and data.anim.speed == anim.speed then return end
			player:set_animation(anim, anim.speed, 0.1)
		end
		local control = player:get_player_control()
		local walking = control.up or control.down or control.left or control.right
		local flying = klots.player_control_get(player).param
		local digging = minetest.check_player_privs(player, "interact")
		and (control.LMB or control.RMB)
		if flying then
			if digging then
				return setanim(anims.mine)
			elseif walking then
				return setanim(anims.walk, 0.2)
			else
				local pos = player:get_pos()
				pos.y = pos.y - 0.25
				local node = minetest.get_node(pos)
				local def = minetest.registered_nodes[node.name]
				if def and not def.walkable then
					return setanim(anims.walk, 0.2)
				end
			end
		elseif walking then
			if digging then
				return setanim(anims.walk_mine)
			else
				return setanim(anims.walk)
			end
		elseif control.LMB or control.RMB then
			return setanim(anims.mine)
		end
		return setanim(anims.stand)
	end)
