#include "Actor.h"

void drawActor(Object* object , u8* actorSprite)
{
    u8 cellX = object->position.x / TILE_WIDTH_BYTES;
    u8 cellY = object->position.y / TILE_HEIGHT;
    u8 previousCellX = object->previousPosition.x / TILE_WIDTH_BYTES;
    u8 previousCellY = object->previousPosition.y / TILE_HEIGHT;

    // Make sure to calculate the backbuffer width based on previous cell otherwise
    // old data can be displayed on the left side of the screen when it is first drawn
    // when coming into a room from the right.
    backbufferWidth = previousCellX == 19 ? TILE_WIDTH_BYTES : BACKBUFFER_WIDTH;

    // Populate the backbuffer from the previous actor position and draw on the screen.
    if (previousCellX != cellX || previousCellY != cellY)
    {
        populateBackbufferFromMap(previousCellX, previousCellY);
        drawBackbuffer(previousCellX, previousCellY);
    }

    // When at the right edge of the screen (x == 19) the width of the back buffer is only one cell wide.
    backbufferWidth = cellX == 19 ? TILE_WIDTH_BYTES : BACKBUFFER_WIDTH;

    // Add the sprites to the back buffer (we expand x and y to one of the 4 cells in the back buffer but the source is the map grid for the cell value).
    populateBackbufferFromMap(cellX, cellY);

    // Add the actor sprite to the back buffer.
    addSpriteToBackbuffer(object->position.x % TILE_WIDTH_BYTES, object->position.y % TILE_HEIGHT, actorSprite);

    drawBackbuffer(cellX, cellY);
}