
local grassnodelist = {
    "aom_flora:grass_0",
    "aom_flora:grass_1",
    "aom_flora:grass_2",
    "aom_flora:grass_3",
}

local function get_grass(pos, node)
    local ndef = core.registered_nodes[node.name]
    if ndef and ndef._get_grass_decor then
        return ndef._get_grass_decor(pos, node)
    end
    return grassnodelist[math.random(1, #grassnodelist)]
end

local np = {
    offset = 0.4,
    scale = 0.5,
    spread = {x = 2, y = 2, z = 2},
    seed = 54256,
    octaves = 2,
    persist = 0.01,
    lacunarity = 2.317,
}

local iperlin = PerlinNoise(np)

local mg_name = core.get_mapgen_setting("mg_name")
if mg_name and (mg_name ~= "flat") and (mg_name ~= "singlenode") then
    core.register_abm({
        nodenames = {"group:grass_block"},
        neighbors = {"air"},
        -- interval = 1.0,
        -- chance = 4,
        interval = 30.0,
        chance = 300,
        action = function(pos, node, active_object_count, active_object_count_wider)
            local p = vector.offset(pos, 0, 1, 0)
            local f = iperlin:get_3d(p)
            if iperlin:get_3d(p) < 0.55 then return end
            if core.get_item_group(node.name, "full_solid") == 0 then return end
            if (core.get_node_light(p, 0.5) or 0) < 4 then return end
            local n = core.get_node(p)
            if (n.name ~= "air") then return end
            f = ((f * 433494437) % 28657) / 28657
            local shape = math.floor(f * 3) + 8 + 32 + (math.floor(f * 2)*16)
            core.set_node(p, {
                name = get_grass(pos, node),
                param2 = shape
            })
        end
    })
    core.register_abm({
        nodenames = {"group:grass"},
        -- interval = 1.0,
        -- chance = 4,
        interval = 30.0,
        chance = 300,
        action = function(pos, node, active_object_count, active_object_count_wider)
            if iperlin:get_3d(pos) < 0.55 then
                core.set_node(pos, {name="air"})
                return
            end
        end
    })
end