#include "KGF.h"

float MotionBlurStart=3.0;


void GBitmap::DrawTransformed(float x, float y, float w, float h, float angle, int flag) {
  al_draw_rotated_scaled_bitmap(GetBit(), (float) al_get_bitmap_width(bit)/2, (float) al_get_bitmap_height(bit)/2, x, y, ((float) w)/((float) al_get_bitmap_width(bit)), ((float) h)/((float) al_get_bitmap_height(bit)), angle, flag);
}


void GBitmap::DrawCentered(float x, float y, float w, float h, float cx, float cy, float angle, int flag) {
  al_draw_rotated_scaled_bitmap(GetBit(), cx, cy, x, y, ((float) w)/((float) al_get_bitmap_width(bit)), ((float) h)/((float) al_get_bitmap_height(bit)), angle, flag);
}



void GBitmap::DrawTransformedMotionBlur(int x, int y, int w, int h, float angle, int flag, Vec2D blur_dir, float angle_dir) {
  Vec2D norm;
  int l;

  norm = blur_dir.Normalized();
  l = RSX(blur_dir.GetMagnitude());

  l -= RSX(MotionBlurStart);

  if (l > 30) l = 30;

  if (l > 0) {
    OpacityBlendMix((1.0/(float)l)*8);
    DrawTransformed(x, y, w, h, angle, flag);

    OpacityBlendMix((1.0/(float)l)*2);
    for (int i=l; i>0; i-=1) {
      DrawTransformed((float)x-(norm.x*i), (float)y-(norm.y*i), w, h, angle, flag);
    }
  }
  else {
    DrawTransformed(x, y, w, h, angle, flag);
  }

  l = RadToAngle(angle_dir)*2;
  l -= MotionBlurStart;
  if (l > 20) l = 20;
  if (l > 0) {
    OpacityBlend((1.0/(float)l)*2);
    for (int i=l; i>0; i-=1) {
      DrawTransformed(x, y, w, h, angle-(angle_dir/l)*i*2, flag);
    }
  }

  NormalBlend();
}

void GBitmap::DrawCenteredMotionBlur(int x, int y, int w, int h,float cx, float cy, float angle, int flag, Vec2D blur_dir, float angle_dir) {
  Vec2D norm;
  int l;

  norm = blur_dir.Normalized();
  l = RSX(blur_dir.GetMagnitude());

  l -= RSX(MotionBlurStart);

  if (l > 50) l = 50;

  if (l > 0) {
    OpacityBlendMix((1.0/(float)l)*8);
    DrawCentered(x, y, w, h, cx, cy, angle, flag);

    OpacityBlendMix((1.0/(float)l)*2);
    for (int i=l; i>0; i-=1) {
      DrawCentered((float)x-(norm.x*i), (float)y-(norm.y*i), w, h, cx, cy, angle, flag);
    }
  }
  else {
    DrawCentered(x, y, w, h, cx, cy, angle, flag);
  }

  l = RadToAngle(angle_dir)*2;
  l -= MotionBlurStart;
  if (l > 0) {
    OpacityBlend((1.0/(float)l)*2);
    for (int i=l; i>0; i-=1) {
      DrawCentered(x, y, w, h, cx, cy, angle-(angle_dir/l)*i*2, flag);
    }
  }

  NormalBlend();
}


void DrawNormal() {
  al_set_target_bitmap(al_get_backbuffer());
}

void DrawTo(GBITMAP *bit) {
  al_set_target_bitmap(bit);
}


void SaveScreenshot(std::string filename) {
  /* TO DO */
}
