/**
 * Copyright (c) 2021 Dominic Masters
 * 
 * This software is released under the MIT License.
 * https://opensource.org/licenses/MIT
 */

#include "tileset.h"

void tilesetInit(tileset_t *tileset,
  int32_t columns, int32_t rows,
  int32_t width, int32_t height,
  int32_t gapX, int32_t gapY,
  int32_t borderX, int32_t borderY
) {
  float tdivX, tdivY;
  int32_t x, y, i;

  tileset->count = rows * columns;
  tileset->divisions = malloc(sizeof(tilesetdiv_t) * tileset->count);
  
  tileset->columns = columns;
  tileset->rows = rows;

  // Calculate division sizes (pixels)
  tileset->divX = (width - (borderX * 2) - (gapX * (columns - 1))) / columns;
  tileset->divY = (height - (borderY * 2) - (gapY * (rows - 1))) / rows;

  // Calculate the division sizes (units)
  tdivX = tileset->divX / width;
  tdivY = tileset->divY / height;

  // Calculate the divisions (in units)
  i = -1;
  for(y = 0; y < rows; y++) {
    for(x = 0; x < columns; x++) {
      tileset->divisions[++i].x0 = (
        borderX + (tileset->divX * x) + (gapX * x)
      ) / width;
      tileset->divisions[i].x1 = tileset->divisions[i].x0 + tdivX;
      
      tileset->divisions[i].y0 = (
        borderY + (tileset->divY * y) + (gapY * y)
      ) / height;
      tileset->divisions[i].y1 = tileset->divisions[i].y0 + tdivY;
    }
  }
}

tilesetdiv_t tilesetGetDivision(tileset_t *tileset,int32_t column,int32_t row) {
  return tileset->divisions[
    (column % tileset->columns) + (row * tileset->columns)
  ];
}

void tilesetDispose(tileset_t *tileset) {
  free(tileset->divisions);
}