/*
 *  pngrender.c
 */

/*
________________________________________________________________________________

Copyright (c) 2001 James Bursa

All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, and/or sell copies of the Software, and to permit persons
to whom the Software is furnished to do so, provided that the above
copyright notice(s) and this permission notice appear in all copies of
the Software and that both the above copyright notice(s) and this
permission notice appear in supporting documentation.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Except as contained in this notice, the name of a copyright holder
shall not be used in advertising or otherwise to promote the sale, use
or other dealings in this Software without prior written authorization
of the copyright holder.

________________________________________________________________________________

james.bursa@strcprstskrzkrk.co.uk
http://www.strcprstskrzkrk.co.uk/

________________________________________________________________________________
*/

#include <stdio.h>
#include <stdlib.h>

#include <png.h>

#include <colourtrans.h>
#include <os.h>

/********************************************************************************/

int render_png_file(const char *path, signed int x, signed int y);
int load_png_file(png_struct *png, png_info *info, const char *path);
int render_png_to_screen(png_struct *png, png_info *info, signed int value_list[],
                         signed int x, signed int y);
void png_render_32(png_byte *prows[], unsigned char *srow, signed int x0,
                   signed int y0, signed int x1, signed int y1, signed int sx,
                   unsigned int sline_length, unsigned int pchannels);
void png_render_16(png_byte *prows[], unsigned char *srow, signed int x0,
                   signed int y0, signed int x1, signed int y1, signed int sx,
                   unsigned int sline_length, unsigned int pchannels);
int png_render_8(png_byte *prows[], unsigned char *srow, signed int x0,
                 signed int y0, signed int x1, signed int y1, signed int sx,
                 unsigned int sline_length, unsigned int pchannels);
int png_render_4(png_byte *prows[], unsigned char *srow, signed int x0,
                 signed int y0, signed int x1, signed int y1, signed int sx,
                 unsigned int sline_length, unsigned int pchannels);
os_palette *read_palette();

/********************************************************************************/

float alpha_table[] = {
      0.0,   1.0/255,   2.0/255,   3.0/255,   4.0/255,   5.0/255,
  6.0/255,   7.0/255,   8.0/255,   9.0/255,  10.0/255,  11.0/255,
 12.0/255,  13.0/255,  14.0/255,  15.0/255,  16.0/255,  17.0/255,
 18.0/255,  19.0/255,  20.0/255,  21.0/255,  22.0/255,  23.0/255,
 24.0/255,  25.0/255,  26.0/255,  27.0/255,  28.0/255,  29.0/255,
 30.0/255,  31.0/255,  32.0/255,  33.0/255,  34.0/255,  35.0/255,
 36.0/255,  37.0/255,  38.0/255,  39.0/255,  40.0/255,  41.0/255,
 42.0/255,  43.0/255,  44.0/255,  45.0/255,  46.0/255,  47.0/255,
 48.0/255,  49.0/255,  50.0/255,  51.0/255,  52.0/255,  53.0/255,
 54.0/255,  55.0/255,  56.0/255,  57.0/255,  58.0/255,  59.0/255,
 60.0/255,  61.0/255,  62.0/255,  63.0/255,  64.0/255,  65.0/255,
 66.0/255,  67.0/255,  68.0/255,  69.0/255,  70.0/255,  71.0/255,
 72.0/255,  73.0/255,  74.0/255,  75.0/255,  76.0/255,  77.0/255,
 78.0/255,  79.0/255,  80.0/255,  81.0/255,  82.0/255,  83.0/255,
 84.0/255,  85.0/255,  86.0/255,  87.0/255,  88.0/255,  89.0/255,
 90.0/255,  91.0/255,  92.0/255,  93.0/255,  94.0/255,  95.0/255,
 96.0/255,  97.0/255,  98.0/255,  99.0/255, 100.0/255, 101.0/255,
102.0/255, 103.0/255, 104.0/255, 105.0/255, 106.0/255, 107.0/255,
108.0/255, 109.0/255, 110.0/255, 111.0/255, 112.0/255, 113.0/255,
114.0/255, 115.0/255, 116.0/255, 117.0/255, 118.0/255, 119.0/255,
120.0/255, 121.0/255, 122.0/255, 123.0/255, 124.0/255, 125.0/255,
126.0/255, 127.0/255, 128.0/255, 129.0/255, 130.0/255, 131.0/255,
132.0/255, 133.0/255, 134.0/255, 135.0/255, 136.0/255, 137.0/255,
138.0/255, 139.0/255, 140.0/255, 141.0/255, 142.0/255, 143.0/255,
144.0/255, 145.0/255, 146.0/255, 147.0/255, 148.0/255, 149.0/255,
150.0/255, 151.0/255, 152.0/255, 153.0/255, 154.0/255, 155.0/255,
156.0/255, 157.0/255, 158.0/255, 159.0/255, 160.0/255, 161.0/255,
162.0/255, 163.0/255, 164.0/255, 165.0/255, 166.0/255, 167.0/255,
168.0/255, 169.0/255, 170.0/255, 171.0/255, 172.0/255, 173.0/255,
174.0/255, 175.0/255, 176.0/255, 177.0/255, 178.0/255, 179.0/255,
180.0/255, 181.0/255, 182.0/255, 183.0/255, 184.0/255, 185.0/255,
186.0/255, 187.0/255, 188.0/255, 189.0/255, 190.0/255, 191.0/255,
192.0/255, 193.0/255, 194.0/255, 195.0/255, 196.0/255, 197.0/255,
198.0/255, 199.0/255, 200.0/255, 201.0/255, 202.0/255, 203.0/255,
204.0/255, 205.0/255, 206.0/255, 207.0/255, 208.0/255, 209.0/255,
210.0/255, 211.0/255, 212.0/255, 213.0/255, 214.0/255, 215.0/255,
216.0/255, 217.0/255, 218.0/255, 219.0/255, 220.0/255, 221.0/255,
222.0/255, 223.0/255, 224.0/255, 225.0/255, 226.0/255, 227.0/255,
228.0/255, 229.0/255, 230.0/255, 231.0/255, 232.0/255, 233.0/255,
234.0/255, 235.0/255, 236.0/255, 237.0/255, 238.0/255, 239.0/255,
240.0/255, 241.0/255, 242.0/255, 243.0/255, 244.0/255, 245.0/255,
246.0/255, 247.0/255, 248.0/255, 249.0/255, 250.0/255, 251.0/255,
252.0/255, 253.0/255, 254.0/255, 1.0 };

/********************************************************************************/

int main(int argc, char *argv[])
{
  char *end;

  if (argc != 4)
  {
    fprintf(stderr, "Usage: pngrender file x y\n");
    exit(1);
  }

  return render_png_file(argv[1], strtol(argv[2], &end, 10), strtol(argv[3], &end, 10));
}

/********************************************************************************
 * render a png file to the screen
 *  => path -- filename of png file to render
 *     x, y -- position of bottom-left corner in os units from screen bottom-left
 *  <= return code:
 *       0 - OK
 *       -1 - file failed to open
 *       -2 - couldn't read header
 *       -3 - not a png
 *       -4 - bpp of png not understood
 *       -5 - malloc or colourtrans failed
 *       other - os error number from OS_ReadVduVariables
 */

int render_png_file(const char *path, signed int x, signed int y)
{
  unsigned int status;
  signed int value_list[20];
  png_struct *png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
  png_info *info = png_create_info_struct(png);
  const os_vdu_var var_list[] = {os_MODEVAR_LINE_LENGTH, os_MODEVAR_LOG2_BPP,
             os_MODEVAR_XEIG_FACTOR, os_MODEVAR_YEIG_FACTOR,
             os_VDUVAR_GWL_COL, os_VDUVAR_GWB_ROW, os_VDUVAR_GWR_COL, os_VDUVAR_GWT_ROW,
             os_VDUVAR_ORGX, os_VDUVAR_ORGY, os_VDUVAR_SCREEN_START,
             os_MODEVAR_YWIND_LIMIT, -1};
  os_error const *error;

  status = load_png_file(png, info, path);
  if (status)
  {
    png_destroy_read_struct(&png, &info, (png_info **) NULL);
    return status;
  }

  error = xos_read_vdu_variables((os_vdu_var_list *) &var_list, value_list);
  if (error)
  {
    png_destroy_read_struct(&png, &info, (png_info **) NULL);
    return error->errnum;
  }

  status = render_png_to_screen(png, info, value_list, x, y);
  png_destroy_read_struct(&png, &info, (png_info **) NULL);
  return status;
}

/********************************************************************************/

int load_png_file(png_struct *png, png_info *info, const char *path)
{
  unsigned char buf[10];
  FILE *file;

  if (!(file = fopen(path, "rb"))) return -1;
  if (fread(buf, 1, 8, file) < 8)  return -2;
  if (png_sig_cmp(buf, 0, 8) != 0) return -3;

  rewind(file);

  png_init_io(png, file);
  png_read_png(png, info,
		  PNG_TRANSFORM_STRIP_16	// Strip 16-bit samples to 8 bits
		| PNG_TRANSFORM_PACKING		// Expand 1, 2 and 4-bit samples to bytes
		| PNG_TRANSFORM_EXPAND		// Perform set_expand()
               , NULL);

  fclose(file);

  return 0;
}

/********************************************************************************/

int render_png_to_screen(png_struct *png, png_info *info, signed int value_list[],
                         signed int sx, signed int sy)
{
  unsigned char *srow;
  unsigned int pwidth, pheight, pchannels, sbpp, sline_length, ox, oy;
  signed int x0, y0, x1, y1;
  png_byte **prows;

  pchannels = png_get_channels(png, info);        /* png channels, including alpha */
  pwidth = png_get_image_width(png, info);        /* png width / pixels */
  pheight = png_get_image_height(png, info);      /* png height / pixels */
  prows = png_get_rows(png, info);                /* array of png rows data */

  sline_length = value_list[0];                   /* screen line length / bytes */
  sbpp = 1 << value_list[1];                      /* screen depth */

  ox = value_list[8] >> value_list[2];            /* graphics origin / pixels */
  oy = value_list[9] >> value_list[2];
  sx = (sx >> value_list[2]) + ox;                /* x / pixels */
  sy = (sy >> value_list[3]) + oy;                /* y / pixels */

  x0 = value_list[4] - sx;                        /* graphics window relative to */
  y0 = value_list[5] - sy;                        /* image origin / pixels */
  x1 = value_list[6] - sx;
  y1 = value_list[7] - sy;

  if (x0 < 0) x0 = 0;                             /* region of image to render */
  if (y0 < 0) y0 = 0;
  if (x1 >= pwidth) x1 = pwidth - 1;
  if (y1 >= pheight) y1 = pheight - 1;

  if (x0 >= pwidth) return 0;                     /* outside graphics window */
  if (y0 >= pheight) return 0;
  if (x1 < 0) return 0;
  if (y1 < 0) return 0;

  srow = (unsigned char *) (value_list[10] +
         (value_list[11] - sy - pheight + 1) * sline_length);

  switch (sbpp)
  {
    case 32:
      png_render_32(prows, srow, x0, pheight - 1 - y1, x1, pheight - 1 - y0,
                    sx, sline_length, pchannels);
      break;

    case 16:
      png_render_16(prows, srow, x0, pheight - 1 - y1, x1, pheight - 1 - y0,
                    sx, sline_length, pchannels);
      break;

    case 8:
      return png_render_8(prows, srow, x0, pheight - 1 - y1, x1, pheight - 1 - y0,
                          sx, sline_length, pchannels);

    case 4:
      return png_render_4(prows, srow, x0, pheight - 1 - y1, x1, pheight - 1 - y0,
                          sx, sline_length, pchannels);
  }

  return 0;
}

/********************************************************************************/

void png_render_32(png_byte *prows[], unsigned char *srow, signed int x0,
                   signed int y0, signed int x1, signed int y1, signed int sx,
                   unsigned int sline_length, unsigned int pchannels)
{
  unsigned char pr, pg, pb, sr, sb, sg, *pbyte, *sbyte;
  unsigned int prow, pcol, palpha;
  float alphaf, ialphaf;

  for (prow = y0; prow <= y1; prow++)
  {
    pbyte = prows[prow] + (x0 * pchannels);
    sbyte = srow + sline_length * prow + (sx + x0) * 4;

    for (pcol = x0; pcol <= x1; pcol++)
    {
      pr = *pbyte++;
      if (pchannels == 1 || pchannels == 2) pg = pb = pr;                   /* greyscale */
      else { pg = *pbyte++; pb = *pbyte++; }                                   /* colour */

      palpha = (pchannels == 4 || pchannels == 2 ? *pbyte++ : 255);

      if (palpha == 0) { sbyte += 4; continue; }                    /* fully transparent */

      if (palpha != 255)                                        /* partially transparent */
      {
        alphaf = alpha_table[palpha];
        ialphaf = alpha_table[255 - palpha];

        sr = *sbyte; sg = *(sbyte + 1); sb = *(sbyte + 2);

        pr = alphaf * pr + ialphaf * sr;
        pg = alphaf * pg + ialphaf * sg;
        pb = alphaf * pb + ialphaf * sb;
      }

      *sbyte++ = pr; *sbyte++ = pg; *sbyte++ = pb; sbyte++;
    }
  }
}

/********************************************************************************/

void png_render_16(png_byte *prows[], unsigned char *srow, signed int x0,
                   signed int y0, signed int x1, signed int y1, signed int sx,
                   unsigned int sline_length, unsigned int pchannels)
{
  unsigned char pr, pg, pb, sr, sb, sg, *pbyte, *sbyte;
  unsigned int prow, pcol, palpha;
  float alphaf, ialphaf;

  for (prow = y0; prow <= y1; prow++)
  {
    pbyte = prows[prow] + (x0 * pchannels);
    sbyte = srow + sline_length * prow + (sx + x0) * 2;

    for (pcol = x0; pcol <= x1; pcol++)
    {
      pr = *pbyte++ >> 3;
      if (pchannels == 1 || pchannels == 2) pg = pb = pr;
      else { pg = *pbyte++ >> 3; pb = *pbyte++ >> 3; }

      palpha = (pchannels == 4 || pchannels == 2 ? *pbyte++ : 255);

      if (palpha == 0) { sbyte += 2; continue; }

      if (palpha != 255)
      {
        alphaf = alpha_table[palpha];
        ialphaf = alpha_table[255 - palpha];

        sr = *sbyte & 0x1f;
        sg = (*sbyte >> 5) | ((*(sbyte + 1) & 0x3) << 3);
        sb = (*(sbyte + 1) >> 2) & 0x1f;

        pr = alphaf * pr + ialphaf * sr;
        pg = alphaf * pg + ialphaf * sg;
        pb = alphaf * pb + ialphaf * sb;
      }

      *sbyte++ = (pg << 5) | pr;
      *sbyte++ = (pb << 2) | (pg >> 3);
    }
  }
}

/********************************************************************************/

int png_render_8(png_byte *prows[], unsigned char *srow, signed int x0,
                 signed int y0, signed int x1, signed int y1, signed int sx,
                 unsigned int sline_length, unsigned int pchannels)
{
  unsigned char pr, pg, pb, sr, sb, sg, *pbyte, *sbyte, map[0x1000];
  unsigned int prow, pcol, palpha, colour;
  float alphaf, ialphaf;
  os_palette *palette;
  os_colour scolour;

  palette = read_palette();
  if (!palette) return -5;

  for (colour = 0; colour < 0x1000; colour++)
  {
    map[colour] = colourtrans_return_colour_number(
          ((colour & 0xf) << 8) |           /* red */
          ((colour & 0xf) << 12) |
          (((colour >> 4) & 0xf) << 16) |    /* green */
          (((colour >> 4) & 0xf) << 20) |
          (((colour >> 8) & 0xf) << 24) |    /* blue */
          (((colour >> 8) & 0xf) << 28));
  }

  /* render image */
  for (prow = y0; prow <= y1; prow++)
  {
    pbyte = prows[prow] + (x0 * pchannels);
    sbyte = srow + sline_length * prow + sx + x0;

    for (pcol = x0; pcol <= x1; pcol++)
    {
      pr = *pbyte++;
      if (pchannels == 1 || pchannels == 2) pg = pb = pr;
      else { pg = *pbyte++; pb = *pbyte++; }

      palpha = (pchannels == 4 || pchannels == 2 ? *pbyte++ : 255);

      if (palpha == 0) { sbyte++; continue; }

      if (palpha != 255)
      {
        alphaf = alpha_table[palpha];
        ialphaf = alpha_table[255 - palpha];

        scolour = palette->entries[*sbyte];
        sr = (scolour >> 8) & 0xff;
        sg = (scolour >> 16) & 0xff;
        sb = (scolour >> 24) & 0xff;

        pr = alphaf * pr + ialphaf * sr;
        pg = alphaf * pg + ialphaf * sg;
        pb = alphaf * pb + ialphaf * sb;
      }

      *sbyte++ = map[(pr >> 4) | (pg & 0xf0) | ((pb << 4) & 0xf00)];
    }
  }

  free(palette);

  return 0;
}

/********************************************************************************/

int png_render_4(png_byte *prows[], unsigned char *srow, signed int x0,
                 signed int y0, signed int x1, signed int y1, signed int sx,
                 unsigned int sline_length, unsigned int pchannels)
{
  unsigned char pr, pg, pb, sr, sb, sg, *pbyte, *sbyte, map[0x1000];
  unsigned int prow, pcol, palpha, spix, colour;
  float alphaf, ialphaf;
  os_palette *palette;
  os_colour scolour;

  palette = read_palette();
  if (!palette) return -5;

  for (colour = 0; colour < 0x1000; colour++)
  {
    map[colour] = colourtrans_return_colour_number(
          ((colour & 0xf) << 8) |           /* red */
          ((colour & 0xf) << 12) |
          (((colour >> 4) & 0xf) << 16) |    /* green */
          (((colour >> 4) & 0xf) << 20) |
          (((colour >> 8) & 0xf) << 24) |    /* blue */
          (((colour >> 8) & 0xf) << 28));
  }

  /* render image */
  for (prow = y0; prow <= y1; prow++)
  {
    pbyte = prows[prow] + (x0 * pchannels);
    sbyte = srow + sline_length * prow + (sx + x0) / 2;
    spix = (sx + x0) & 1;

    for (pcol = x0; pcol <= x1; pcol++)
    {
      pr = *pbyte++;
      if (pchannels == 1 || pchannels == 2) pg = pb = pr;
      else { pg = *pbyte++; pb = *pbyte++; }

      palpha = (pchannels == 4 || pchannels == 2 ? *pbyte++ : 255);

      if (palpha == 0)
      {
        spix = 1 - spix;
        if (spix == 0) sbyte++;
        continue;
      }

      if (palpha != 255)
      {
        alphaf = alpha_table[palpha];
        ialphaf = alpha_table[255 - palpha];

        scolour = (spix ? palette->entries[(*sbyte >> 4) & 0xf]
                        : palette->entries[*sbyte & 0xf]);
        sr = (scolour >> 8) & 0xff;
        sg = (scolour >> 16) & 0xff;
        sb = (scolour >> 24) & 0xff;

        pr = alphaf * pr + ialphaf * sr;
        pg = alphaf * pg + ialphaf * sg;
        pb = alphaf * pb + ialphaf * sb;
      }

      *sbyte = (spix ?
        (map[(pr >> 4) | (pg & 0xf0) | ((pb << 4) & 0xf00)] << 4) | (*sbyte & 0xf) :
         map[(pr >> 4) | (pg & 0xf0) | ((pb << 4) & 0xf00)]       | (*sbyte & 0xf0));

      spix = 1 - spix;
      if (spix == 0) sbyte++;
    }
  }

  free(palette);

  return 0;
}

/********************************************************************************
 * read screen palette
 */

os_palette *read_palette()
{
  unsigned int size;
  os_palette *palette;
  os_error const *error;

  error = xcolourtrans_read_palette((osspriteop_area const *) -1, (osspriteop_id) -1,
                                    (os_palette *) 0, 0, 0, &size);
  if (error) return 0;

  palette = malloc(size);
  if (!palette) return 0;

  error = xcolourtrans_read_palette((osspriteop_area const *) -1, (osspriteop_id) -1,
                                    palette, size, 0, NULL);
  if (error) return 0;

  return palette;
}

/********************************************************************************/
