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

#include "image.h"

void imageInit(image_t *image) {
  image->quad.verticeCount = -1;
  image->width = 1;
  image->height = 1;
  imageSetTexture(image, NULL);
}

void imageSetTexture(image_t *image, texture_t *texture) {
  imageSetTextureAndCrop(image, texture,
    0, 0,
    texture == NULL ? 0 : (float)texture->width,
    texture == NULL ? 0 : (float)texture->height
  );
}

void imageSetTextureAndCrop(image_t *image, texture_t *texture,
  float x, float y, float width, float height
) {
  float u0, u1, v0, v1;
  if(image->quad.verticeCount != -1) {
    primitiveDispose(&image->quad);
    image->quad.verticeCount = -1;
  }
  if(texture == NULL) return;

  u0 = x / texture->width;
  u1 = u0 + (width / texture->width);
  v0 = y / texture->height;
  v1 = v0 + (height / texture->height);
  
  image->texture = texture;
  quadInit(&image->quad, 0,
    0,0,u0,v0,
    1,1,u1,v1
  );
}

void imageRender(image_t *image, shader_t *shader, float x, float y) {
  if(image->texture == NULL) return;
  shaderUsePositionAndScale(shader,
    x,y,0,
    0,0,0,
    image->width, image->height, 1
  );
  shaderUseTexture(shader, image->texture);
  primitiveDraw(&image->quad, 0, -1);
}

void imageDispose(image_t *image) {
  if(image->quad.verticeCount != -1) primitiveDispose(&image->quad);
}