/* Modified from SDL_rotate.c (SDL2), from SDL_gfx by Andreas Schiffler.
 * Original copyright:
 *
 * Copyright (C) 2001-2011  Andreas Schiffler
 *
 * This software is provided 'as-is', without any express or implied
 * warranty. In no event will the authors be held liable for any damages
 * arising from the use of this software.
 *
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely, subject to the following restrictions:
 *
 * 1. The origin of this software must not be misrepresented; you must not
 * claim that you wrote the original software. If you use this software
 * in a product, an acknowledgment in the product documentation would be
 * appreciated but is not required.
 *
 * 2. Altered source versions must be plainly marked as such, and must not be
 * misrepresented as being the original software.
 *
 * 3. This notice may not be removed or altered from any source
 * distribution.
 *
 * Andreas Schiffler -- aschiffler at ferzkopp dot net
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include "image.h"


/* Number of guard rows added to destination surfaces.
 * This is a simple but effective workaround for observed issues.
 * These rows allocate extra memory and are then hidden from the surface.
 * Rows are added to the end of destination surfaces when they are allocated.
 * This catches any potential overflows which seem to happen with
 * just the right src image dimensions and scale/rotation and can lead
 * to a situation where the program can segfault.
 */
#define GUARD_ROWS (2)

/* floating point */
struct floatpoint {
  float x;
  float y;
};

void image_modif_rotatesize(int *, int *, int);
struct VG_Image * image_modif_rotflip(const struct VG_Image *, int, int, int);

static void rotate(double, double, double, double, const struct floatpoint *, double *, double *);
static double calc_floor(double);
static double calc_ceil(double);
static void rotozoomSurfaceSizeTrig(int, int, double, const struct floatpoint *, struct VG_Rect *, double *, double *);
static void computeSourceIncrements90(const struct VG_Image *, int, int, int, int, int *, int *, int *, int *);
static void transformSurfaceRGBA90(const struct VG_Image *, struct VG_Image *, int, int, int);
static void transformSurfaceRGBA(const struct VG_Image *, struct VG_Image *, int, int, int, int, int, const struct VG_Rect *, const struct floatpoint *);
static struct VG_Image * rotateSurface(const struct VG_Image *, double, int, int, int, const struct VG_Rect *, double, double, const struct floatpoint *);


/* rotate (sx, sy) by (angle, center) into (dx, dy) */
static void
rotate(double sx, double sy, double sinangle, double cosangle, const struct floatpoint *center, double *dx, double *dy)
{
  sx -= center->x;
  sy -= center->y;

  *dx = cosangle * sx - sinangle * sy;
  *dy = sinangle * sx + cosangle * sy;

  *dx += center->x;
  *dy += center->y;
} /* Ende rotate */


/* floor() */
static double
calc_floor(double x) {
  double i = (int)x;
  if (x < 0.0 && x - i < 0.0) { i -= 1.0; }
  return i;
} /* Ende calc_floor */


/* ceil() */
static double
calc_ceil(double x) {
  double i = calc_floor(x);
  if (x - i > 0.0) { i += 1.0; }
  return i;
} /* Ende calc_ceil */


/* Internal target surface sizing function for rotations with trig result return.
 * @param width The source surface width.
 * @param height The source surface height.
 * @param angle The angle to rotate in degrees.
 * @param center The center of the image
 * @param rect_dest The calculated width and height of the destination surface.
 * @param cangle The sine of the angle
 * @param sangle The cosine of the angle
 */
static void
rotozoomSurfaceSizeTrig(int width, int height, double angle, const struct floatpoint *center,
                        struct VG_Rect *rect_dest, double *cangle, double *sangle)
{
  int minx, maxx, miny, maxy;
  double x0, x1, x2, x3;
  double y0, y1, y2, y3;
  double sinangle;
  double cosangle;

  sinangle = (double)vg4->misc->sin((int)(angle + .5)) / 10000.;
  cosangle = (double)vg4->misc->cos((int)(angle + .5)) / 10000.;

  /*
   * Determine destination width and height by rotating a source box, at pixel center
   */
  rotate(0.5,         0.5,          sinangle, cosangle, center, &x0, &y0);
  rotate(width - 0.5, 0.5,          sinangle, cosangle, center, &x1, &y1);
  rotate(0.5,         height - 0.5, sinangle, cosangle, center, &x2, &y2);
  rotate(width - 0.5, height - 0.5, sinangle, cosangle, center, &x3, &y3);

  minx = (int)calc_floor( MINVAL( MINVAL(x0, x1), MINVAL(x2, x3) ) );
  maxx = (int)calc_ceil(  MAXVAL( MAXVAL(x0, x1), MAXVAL(x2, x3) ) );

  miny = (int)calc_floor( MINVAL( MINVAL(y0, y1), MINVAL(y2, y3) ) );
  maxy = (int)calc_ceil(  MAXVAL( MAXVAL(y0, y1), MAXVAL(y2, y3) ) );

  rect_dest->w = maxx - minx;
  rect_dest->h = maxy - miny;
  rect_dest->x = minx;
  rect_dest->y = miny;

  /* reverse the angle because our rotations are clockwise */
  *sangle = -sinangle;
  *cangle = cosangle;

  { /* The trig code below gets the wrong size (due to FP inaccuracy?) when angle is a multiple of 90 degrees */
    int angle90 = (int)(angle / 90);
    if (angle90 == angle / 90) {  /* if the angle is a multiple of 90 degrees */
      angle90 %= 4;
      if (angle90 < 0) { angle90 += 4; }  /* 0:0 deg, 1:90 deg, 2:180 deg, 3:270 deg */
      if (angle90 & 1) {
        rect_dest->w = height;
        rect_dest->h = width;
        *cangle = 0;
        *sangle = (angle90 == 1 ? -1 : 1);  /* reversed because our rotations are clockwise */
      } else {
        rect_dest->w = width;
        rect_dest->h = height;
        *cangle = (angle90 == 0 ? 1 : -1);
        *sangle = 0;
      }
    }
  }
} /* Ende rotozoomSurfaceSizeTrig */


/* Computes source pointer X/Y increments for a rotation that's a multiple of 90 degrees. */
static void
computeSourceIncrements90(const struct VG_Image *pxsrc, int bpp, int angle, int flipx, int flipy,
                          int *sincx, int *sincy, int *signx, int *signy)
{
  int row;

  row = pxsrc->img.w * bpp;
  if (flipy) { row = -row; }
  if (flipx) { bpp = -bpp; }

  switch (angle) {  /* 0:0 deg, 1:90 deg, 2:180 deg, 3:270 deg */
    case 0: *sincx = bpp; *sincy = row - pxsrc->img.w * (*sincx); *signx = *signy = 1; break;
    case 1: *sincx = -row; *sincy = bpp - (*sincx) * pxsrc->img.h; *signx = 1; *signy = -1; break;
    case 2: *sincx = -bpp; *sincy = -pxsrc->img.w * (*sincx) - row; *signx = *signy = -1; break;
    case 3: default: *sincx = row; *sincy = -(*sincx) * pxsrc->img.h - bpp; *signx = -1; *signy = 1; break;
  }
  if (flipx) { *signx = -(*signx); }
  if (flipy) { *signy = -(*signy); }
} /* Ende computeSourceIncrements90 */


/* Performs a relatively fast rotation/flip when the angle is a multiple of 90 degrees. */
static void
transformSurfaceRGBA90(const struct VG_Image *pxsrc, struct VG_Image *pxdst, int angle, int flipx, int flipy)
{
  int dy, sincx, sincy, signx, signy, dincy;
  unsigned char *sp, *dp, *de;

  dincy = 0;
  sp = (unsigned char *)pxsrc->img.pixels;
  dp = (unsigned char *)pxdst->img.pixels;

  computeSourceIncrements90(pxsrc, sizeof(struct VG_PixelColor), angle, flipx, flipy, &sincx, &sincy, &signx, &signy);
  if (signx < 0) { sp += ((pxsrc->img.w - 1) * sizeof(struct VG_PixelColor)); }
  if (signy < 0) { sp += ((pxsrc->img.h - 1) * pxsrc->img.w * sizeof(struct VG_PixelColor)); }

  for (dy = 0; dy < pxdst->img.h; sp += sincy, dp += dincy, dy++) {
    if (sincx == sizeof(struct VG_PixelColor)) {  /* if advancing pxsrc and dest equally, use memcpy */
      memcpy(dp, sp, pxdst->img.w * sizeof(struct VG_PixelColor));
      sp += (pxdst->img.w * sizeof(struct VG_PixelColor));
      dp += (pxdst->img.w * sizeof(struct VG_PixelColor));
    } else {
      for (de = dp + pxdst->img.w * sizeof(struct VG_PixelColor); dp != de; sp += sincx, dp += sizeof(struct VG_PixelColor)) {
        *(struct VG_PixelColor *)dp = *(struct VG_PixelColor *)sp;
      }
    }
  }
} /* Ende transformSurfaceRGBA90 */


/* Internal 32 bit rotozoomer with optional anti-aliasing.
 *
 * Rotates and zooms 32 bit RGBA/ABGR 'pxsrc' surface to 'pxdst' surface based on the control
 * parameters by scanning the destination surface and applying optionally anti-aliasing
 * by bilinear interpolation.
 * Assumes src and dst surfaces are of 32 bit depth.
 * Assumes dst surface was allocated with the correct dimensions.
 *
 * @param src Source surface.
 * @param dst Destination surface.
 * @param isin Integer version of sine of angle.
 * @param icos Integer version of cosine of angle.
 * @param flipx Flag indicating horizontal mirroring should be applied.
 * @param flipy Flag indicating vertical mirroring should be applied.
 * @param smooth whether anti-aliasing should be used.
 * @param dst_rect destination coordinates
 * @param center true center.
 */
static void
transformSurfaceRGBA(const struct VG_Image *pxsrc, struct VG_Image *pxdst, int isin, int icos,
                     int flipx, int flipy, VG_BOOL smooth,
                     const struct VG_Rect *rect_dest,
                     const struct floatpoint *center)
{
  int sw, sh;
  int cx, cy;
  struct VG_PixelColor c00, c01, c10, c11, cswap;
  struct VG_PixelColor *pc, *sp;
  const int fp_half = (1 << 15);

  /*
   * Variable setup
   */
  sw = pxsrc->img.w - 1;
  sh = pxsrc->img.h - 1;
  pc = pxdst->img.pixels;
  cx = (int)(center->x * 65536.0);
  cy = (int)(center->y * 65536.0);

  /*
   * Switch between interpolating and non-interpolating code
   */
  if (smooth) {
    int y;
    for (y = 0; y < pxdst->img.h; y++) {
      int x;
      double src_x = (rect_dest->x + 0 + 0.5 - center->x);
      double src_y = (rect_dest->y + y + 0.5 - center->y);
      int sdx = (int)((icos * src_x - isin * src_y) + cx - fp_half);
      int sdy = (int)((isin * src_x + icos * src_y) + cy - fp_half);
      for (x = 0; x < pxdst->img.w; x++) {
        int dx = (sdx >> 16);
        int dy = (sdy >> 16);
        if (flipx) { dx = sw - dx; }
        if (flipy) { dy = sh - dy; }
        if (dx > -1 && dy > -1 && dx < (pxsrc->img.w - 1) && dy < (pxsrc->img.h - 1)) {
          int ex, ey;
          int t1, t2;
          sp = pxsrc->img.pixels + pxsrc->img.w * dy + dx;
          c00 = *sp;
          sp += 1;
          c01 = *sp;
          sp += pxsrc->img.w;
          c11 = *sp;
          sp -= 1;
          c10 = *sp;
          if (flipx) {
            cswap = c00; c00 = c01; c01 = cswap;
            cswap = c10; c10 = c11; c11 = cswap;
          }
          if (flipy) {
            cswap = c00; c00 = c10; c10 = cswap;
            cswap = c01; c01 = c11; c11 = cswap;
          }
          /*
           * Interpolate colors
           */
          ex = (sdx & 0xffff);
          ey = (sdy & 0xffff);
          t1 = ((((c01.r - c00.r) * ex) >> 16) + c00.r) & 0xff;
          t2 = ((((c11.r - c10.r) * ex) >> 16) + c10.r) & 0xff;
          pc->r = (((t2 - t1) * ey) >> 16) + t1;
          t1 = ((((c01.g - c00.g) * ex) >> 16) + c00.g) & 0xff;
          t2 = ((((c11.g - c10.g) * ex) >> 16) + c10.g) & 0xff;
          pc->g = (((t2 - t1) * ey) >> 16) + t1;
          t1 = ((((c01.b - c00.b) * ex) >> 16) + c00.b) & 0xff;
          t2 = ((((c11.b - c10.b) * ex) >> 16) + c10.b) & 0xff;
          pc->b = (((t2 - t1) * ey) >> 16) + t1;
          t1 = ((((c01.a - c00.a) * ex) >> 16) + c00.a) & 0xff;
          t2 = ((((c11.a - c10.a) * ex) >> 16) + c10.a) & 0xff;
          pc->a = (((t2 - t1) * ey) >> 16) + t1;
        }
        sdx += icos;
        sdy += isin;
        pc++;
      }
    }
  } else {
    int y;
    for (y = 0; y < pxdst->img.h; y++) {
      int x;
      double src_x = (rect_dest->x + 0 + 0.5 - center->x);
      double src_y = (rect_dest->y + y + 0.5 - center->y);
      int sdx = (int)((icos * src_x - isin * src_y) + cx - fp_half);
      int sdy = (int)((isin * src_x + icos * src_y) + cy - fp_half);
      for (x = 0; x < pxdst->img.w; x++) {
        int dx = (sdx >> 16);
        int dy = (sdy >> 16);
        if ((unsigned int)dx < (unsigned int)pxsrc->img.w && (unsigned int)dy < (unsigned int)pxsrc->img.h) {
          if (flipx) { dx = sw - dx; }
          if (flipy) { dy = sh - dy; }
          *pc = *(pxsrc->img.pixels + pxsrc->img.w * dy + dx);
        }
        sdx += icos;
        sdy += isin;
        pc++;
      }
    }
  }
} /* Ende transformSurfaceRGBA */


/* Rotates and zooms a surface with different horizontal and vertival scaling factors and optional anti-aliasing.
 *
 * Rotates a 32-bit or 8-bit 'src' surface to newly created 'dst' surface.
 * 'angle' is the rotation in degrees, 'center' the rotation center. If 'smooth' is set
 * then the destination 32-bit surface is anti-aliased. 8-bit surfaces must have a colorkey. 32-bit
 * surfaces must have a 8888 layout with red, green, blue and alpha masks (any ordering goes).
 * The blend mode of the 'src' surface has some effects on generation of the 'dst' surface: The NONE
 * mode will set the BLEND mode on the 'dst' surface. The MOD mode either generates a white 'dst'
 * surface and sets the colorkey or fills the it with the colorkey before copying the pixels.
 * When using the NONE and MOD modes, color and alpha modulation must be applied before using this function.
 *
 * @param src The surface to rotozoom.
 * @param angle The angle to rotate in degrees.
 * @param zoomy The vertical coordinate of the center of rotation
 * @param smooth wether antialiasing is used
 * @param flipx Set to 1 to flip the image horizontally
 * @param flipy Set to 1 to flip the image vertically
 * @param rect_dest The destination rect bounding box
 * @param cangle The angle cosine
 * @param sangle The angle sine
 * @param center The true coordinate of the center of rotation
 * @param The new rotated surface.
 */
static struct VG_Image *
rotateSurface(const struct VG_Image *pxsrc, double angle, VG_BOOL smooth, int flipx, int flipy,
        const struct VG_Rect *rect_dest, double cangle, double sangle, const struct floatpoint *center)
{
    struct VG_Image *pxdst;
    int angle90;
    double sangleinv, cangleinv;

    /* Calculate target factors from sine/cosine and zoom */
    sangleinv = sangle * 65536.0;
    cangleinv = cangle * 65536.0;

    /* Alloc space to completely contain the rotated surface */
    pxdst = vg4->image->create(rect_dest->w, rect_dest->h + GUARD_ROWS);
    pxdst->img.h = rect_dest->h;

    /* check if the rotation is a multiple of 90 degrees so we can take a fast path and also somewhat reduce
     * the off-by-one problem in transformSurfaceRGBA that expresses itself when the rotation is near
     * multiples of 90 degrees.
     */
    angle90 = (int)(angle / 90);
    if (angle90 == angle / 90) {
      angle90 %= 4;
      if (angle90 < 0) { angle90 += 4; }  /* 0:0 deg, 1:90 deg, 2:180 deg, 3:270 deg */
    } else {
      angle90 = -1;
    }

    /* Call the 32-bit transformation routine to do the rotation */
    if (angle90 >= 0) {
        transformSurfaceRGBA90(pxsrc, pxdst, angle90, flipx, flipy);
    } else {
        transformSurfaceRGBA(pxsrc, pxdst, (int)sangleinv, (int)cangleinv,
                             flipx, flipy, smooth, rect_dest, center);
    }

    return pxdst;
} /* Ende rotateSurface */


/* image_modif_rotatesize:
 * return new size of rotated image
 * @param width   width of image and for returning new width
 * @param height  height of image and for returning new height
 * @param angle   angle to rotate
 */
void
image_modif_rotatesize(int *width, int *height, int angle)
{
  struct VG_Rect rect_src, rect_dest;
  struct floatpoint center;
  double cangle, sangle;

  if (width == NULL || height == NULL) { return; }

  angle %= 360;
  if (angle < 0) { angle += 360; }

  rect_src.x = rect_src.y = 0;
  rect_src.w = *width;
  rect_src.h = *height;

  center.x = rect_src.w / 2;
  center.y = rect_src.h / 2;

  rotozoomSurfaceSizeTrig(rect_src.w, rect_src.h, (double)angle, &center, &rect_dest, &cangle, &sangle);

  *width = rect_dest.w;
  *height = rect_dest.h + GUARD_ROWS;
} /* Ende image_modif_rotatesize */


/* image_modif_rotflip:
 * return new rotated and flipped image
 * @param pxsrc   image
 * @param angle   angle to rotate
 * @param flip    from VG_AXES
 * @param smooth  whether using linear scaling
 * @return  new image, or NULL = no change
 */
struct VG_Image *
image_modif_rotflip(const struct VG_Image *pxsrc, int angle, int flip, VG_BOOL smooth)
{
  struct VG_Rect rect_src, rect_dest;
  struct floatpoint center;
  struct VG_Image *pxdst;
  double cangle, sangle;

  if (pxsrc == NULL) { outerr("image NULL"); return NULL; }

  angle %= 360;
  if (angle < 0) { angle += 360; }

  rect_src.x = rect_src.y = 0;
  rect_src.w = pxsrc->img.w;
  rect_src.h = pxsrc->img.h;

  center.x = pxsrc->img.w / 2;
  center.y = pxsrc->img.h / 2;

  rotozoomSurfaceSizeTrig(rect_src.w, rect_src.h, (double)angle, &center, &rect_dest, &cangle, &sangle);

  /* flip horizontal = flip at vertical axe, flip vertical = flip at horizontal axe */
  pxdst = rotateSurface(pxsrc, (double)angle, smooth, flip & VG_AXE_VERTICAL, flip & VG_AXE_HORIZONTAL,
                        &rect_dest, cangle, sangle, &center);

  return pxdst;
} /* Ende image_modif_rotflip */
