#include "shadow.hpp"

shadoverlay::shadoverlay()
{
    _canvas = 0;
    _oldCanvas = 0;
    _i = 0;
    _sunVX = 0;
    _sunVY = 1;
}

shadoverlay::~shadoverlay()
{
    if (_canvas)
        delete _canvas;
}

void shadoverlay::init(int w, int h)
{
    if (_oldCanvas)
        delete _oldCanvas;
    if (_canvas)
        delete _canvas;
    _canvas = new bool[w*h];
    _oldCanvas = new bool[w*h];
    _w = w;
    _h = h;
    clear();
    
}

bool shadoverlay::getOld(int x, int y)
{
    if (_oldCanvas)
    {
        return *(_oldCanvas + x + (y*_w));
    }
    return false;
}

bool shadoverlay::get(int x, int y)
{
    if (_canvas)
    {
        return *(_canvas + x + (y*_w));
    }
    return false;
}

void shadoverlay::put(int x, int y, bool state)
{
    if (_canvas)
    {
        *(_canvas + x + (y*_w)) = state;
    }
}

//iterator
void shadoverlay::clear()
{
    bool * tmp = _canvas;
    _canvas = _oldCanvas;
    _oldCanvas = tmp;
    if (_canvas)
        for (int i=0;i< _w*_h;i++)
            *(_canvas+i) = false;
}

void shadoverlay::reset()
{
    _i = 0;
}

void shadoverlay::next()
{
    _i++;
}

bool shadoverlay::end()
{
    return _i>=_w*_h;
}

int shadoverlay::x()
{
    return _i%_w;
}

int shadoverlay::y()
{
    return _i/_w;
}

bool shadoverlay::here()
{
    if (_canvas && _i<_w*_h)
        return *(_canvas+_i);
    return false;
}

//autodraw

//il est possible que le soleil soit à l'exterieur du canvas
void shadoverlay::setSunV(float vx, float vy)
{
    _sunVX = vx;
    _sunVY = vy;
}

int shadoverlay::getSunVX()
{
    return _sunVX;
}

int shadoverlay::getSunVY()
{
    return _sunVY;
}

void shadoverlay::plot(int x, int y)
{
    float px = x,
          py = y;
    
    while (px < _w && 
           px >= 0 && 
           py < _h && 
           py >= 0)
    {
        put((int)px, (int)py, true);
        px += _sunVX;
        py += _sunVY;
    }
}

void shadoverlay::polarPlot(int x, int y, float radian, int radius)
{
    float px = x,
          py = y;
    for (int i=0;i<radius;i++)
    {
        plot(px,py);
        px = px + sin(radian);
        py = py + cos(radian);
    }
}
