-- LUALOCALS < ---------------------------------------------------------
local PcgRandom, ipairs, math, minetest
    = PcgRandom, ipairs, math, minetest
local math_floor, math_pow
    = math.floor, math.pow
-- LUALOCALS > ---------------------------------------------------------

local dmin = {
	{2},
	{2},
	{0, 5, 2},
	{7, 5, 2},
}
local cmaj = {
	{0},
	{0},
	{-3, 2, 0},
	{5, 2, 0}
}
local keys = {
	dmin,
	dmin,
	cmaj
}

local lastsec
minetest.register_globalstep(function()
		local gt = math_floor(minetest.get_gametime() / 2)
		lastsec = lastsec or gt
		if lastsec == gt then return end

		local keypos = math_floor(gt / 16)
		local measure = math_floor(gt / 4)
		local note = gt % 4 + 1

		local key = PcgRandom(keypos):next(1, #keys)
		local motifs = keys[key]
		local motif = PcgRandom(measure):next(1, #motifs)
		local volume = PcgRandom(measure):next(1, 1000) *.0008 + 0.2
		local tone = motifs[motif][note]
		if tone then
			for _, player in ipairs(minetest.get_connected_players()) do
				local pos = player:get_pos()
				if pos.y >= 128 then
					minetest.sound_play("klots_music_flute",
						{
							to_player = player:get_player_name(),
							pitch = math_pow(2, tone / 12),
							gain = 0.02 * volume
						}, true)
				end
			end
		end
	end)
