
local minetest, colours = minetest, colours

function qround(x)
	return x + 0.5 - (x + 0.5) % 1
end

function on_jump_land(player)
	local ppos = player:get_pos()
	local under_pos = {x = qround(ppos.x), y = math.floor(math.floor(ppos.y) + 0), z = qround(ppos.z)}
	local node_under = minetest.get_node_or_nil(under_pos)
	if node_under and minetest.registered_nodes[node_under.name] and node_under["name"] ~= "air" then
		colours.set_and_trigger(player, node_under, under_pos)
	end
end

function handle_jump(dtime)
	for _,player in ipairs(minetest.get_connected_players()) do
		local meta = player:get_meta()
		local vel = player:get_velocity()
		local did_jump = meta:get_int("did_jump")
		local jump_done = meta:get_int("jump_done")
		local y_start = meta:get_int("ystart")
		local pos = player:get_pos()
		if did_jump == 0 and vel.y > 1 then
			meta:set_int("did_jump", 1)
			meta:set_int("ystart", qround(pos.y)-1)
			meta:set_int("jump_done", 0)
		elseif did_jump == 1 and jump_done == 0 and vel.y < 0 then
			meta:set_int("jump_done", 1)
		elseif did_jump == 1 and jump_done == 0 and vel.y == 0 then
			meta:set_int("did_jump", 0)
		elseif did_jump == 1 and jump_done == 1 and vel.y >= 0 then
			-- We jumped and landed, do stuff!
			meta:set_int("did_jump", 0)
			meta:set_int("jump_done", 0)
			if math.floor(pos.y) <= y_start then
				on_jump_land(player)
			end
		end
	end
end

minetest.register_globalstep(handle_jump)
