#include <Decoration/PineTree/PineTree.hpp>
#include <Decoration/Tree/Tree.hpp>

PineTree::PineTree(int grassID) : grassID(grassID) {}

void PineTree::build(ISculptor &sculptor, GeneratorNode node, glm::ivec3 pos)
{
    int height = 20 + node[0] % 10;
    int leafLayers = 3 + node[1] % 3;
    int leafPeriod = 3 + node[2] % 2;
    
    glm::ivec3 offset(0);
    for (offset.z = 0; offset.z < height; offset.z++)
    {
        int leafOffset = height - offset.z;

        int radiusAtThisHeight = leafOffset % leafPeriod;
        if (leafOffset < leafLayers * leafPeriod)
        {
            for (offset.x = -radiusAtThisHeight; offset.x <= radiusAtThisHeight; offset.x++)
            {
                for (offset.y = -radiusAtThisHeight; offset.y <= radiusAtThisHeight; offset.y++)
                {
                    sculptor.place(pos + offset, "main:leaves");
                }
            }
        }

        offset.x = offset.y = 0;
        sculptor.place(pos + offset, "main:pineLog", Tree::metaNaturalLogMask);
    }

    sculptor.place(pos + glm::ivec3(0, 0, height), "main:leaves");
}

double PineTree::getAverageDensity(const TerrainGenerator::Cell &cell, GeneratorNode node)
{
    if (cell.topID != grassID)
    {
        return 0.0;
    }

    if (cell.height < 24)
    {
        return 0.0;
    }

    return 1.0 * cell.fertility;
}