/*
Copyright (c) 1998 Michael Haar, Ulrich Haar, Michael Thayer,
  Tobias Mueller, Tobias Lenz
All rights reserved.
Terroid Programming by Michael Haar, Michael Thayer, Ulrich Haar
Terroid Graphics by Ulrich Haar, Michael Haar
Terroid Music by Michael Thayer
Terroid Level design by Michael Haar, Ulrich Haar, Tobias Lenz
Terroid Beta testing by Tobias Mueller, Tobias Lenz

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice and credits, this unmodified list of conditions and the
   following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice and credits, this unmodified list of conditions and the
   following disclaimer in the documentation and/or other materials
   provided with the distribution.
3. Any credits displayed during programme execution must include the
   above or an equivalent credit list.
4. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.
5. The authors Michael Thayer and Michael Haar are to be informed,
   preferable by electronic mail, when this software is distributed
   commercially.  A single notification is required for any given
   distribution, and explicit copies of that distribution (e.g. for all
   resellers of a given Linux distribution).
6. If any modifications are made to the software, then a description of them
   must be included when the software is redistributed, or alternatively,
   the distributed binary or source code must be described as a product
   based on source code by Michael Haar, Michael Thayer and Ulrich Haar.

THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/***********************************\
* RLE Sprite manipulation functions *
* Copyright 1996 Michael Thayer     *
* Written for Digital Nightmares    *
* Compatibility :                   *
*   DOS, Linux, ...                 *
\***********************************/

#include <stdlib.h>
#include <string.h>
#include <dn.h>

/* structure :
    BYTE type =
      {
	0x00 : data ;
	0x01 : skip length bytes ;
	0x02 : next line (+ length bytes) ;
	0x03 : end ;
      }
    BYTE length ;
    BYTE data ;
*/

/* This routine needs to be fast, but not that fast. */
/* That's lucky, because it isn't. */

void rle_get(int x1, int y1, int x2, int y2, RLEBLK * dest)
{
    int i, j, k, ofs, destptr, buffsize ;
    BYTE * buff ;
    BYTE * new_buff ;

/* error checks */
    x1 = min(x1, screen_width - 1) ;
    y1 = min(y1, screen_height - 1) ;
    x1 = max(x1, 0) ;
    y1 = max(y1, 0) ;
    x2 = min(x2, screen_width - 1) ;
    y2 = min(y2, screen_height - 1) ;
    x2 = max(x2, 0) ;
    y2 = max(y2, 0) ;
    if (x1 > x2)
      {
        _m_swap(x1, x2) ;
      }
    if (y1 > y2)
      {
        _m_swap(y1, y2) ;
      }
    
    buffsize = 64 * 1024 ;
    buff = malloc(buffsize) ;
    i = y1 ;
    ofs = screen_width * i ;
    destptr = 0 ;
    j = x1 ;
    k = 0 ;
    while (i <= y2)
      {
        while (j <= x2)
          {
/* white space */
            while ( (j + k <= x2) && (k < 256)
                && ( ( (BYTE *) screen_addr)[ofs + j + k] == 0))
              {
                ++k ;
              } /* while */
            if (k && (j + k <= x2))
              {
                buff[destptr] = 1 ;
                buff[destptr + 1] = k ;
                destptr += 2 ;
              } /* if */
            j += k ;
            k = 0 ;
            if (j <= x2)
              {
/* solid space */
                while ( (j + k <= x2) && (k < 256)
                    && ( ( (BYTE *) screen_addr)[ofs + j + k] != 0))
                  {
                    ++k ;
                  } /* while */
                if (k)
                  {
                    buff[destptr] = 0 ;
                    buff[destptr + 1] = k ;
                    memcpy(buff + destptr + 2, ( (BYTE *) screen_addr) + ofs + j, k) ;
                    destptr += k + 2 ;
                    j += k ;
                    k = 0 ;
                  } /* if */
              } /* if */
          } /* while (inner) */
/* don't want any overflows */
        if (destptr > buffsize - 4096)
          {
            buffsize += 64 * 1024 ;
            new_buff = realloc(buff, buffsize) ;
            if (new_buff)
              {
                buff = new_buff ;
              }
          } /* if */
/* offset into next line */
        ofs += screen_width ;
        ++i ;
        j = x1 ;
        while ( (j + k <= x2) && (k < 256)
            && ( ( (BYTE *) screen_addr)[ofs + j + k] == 0))
          {
            ++k ;
          } /* while */
        buff[destptr] = 2 ;
        buff[destptr + 1] = k ;
        destptr += 2 ;
        j += k ;
        k = 0 ;
      } /* while (outer) */
    buff[destptr] = 3 ;
    new_buff = realloc(buff, destptr + 2) ;
    if (new_buff)
      {
        (* dest).mem = new_buff ;
      }
    else
      {
        (* dest).mem = buff ;
      }
    (* dest).w = x2 - x1 + 1 ;
    (* dest).h = y2 - y1 + 1 ;
} /* rle_get */

/* This has to be faster. A lot faster. */

void rle_put(int x, int y, RLEBLK * src)
{
    #define Src ( (* src).mem)
    BYTE * Dest ;
    int ofs, i, j ;
    
    i = y ;
    j = 0 ;
    ofs = 0 ;
    while (i < clip_y1)
      {
        switch (Src[ofs])
          {
            case 0:
              ofs += Src[ofs + 1] + 2 ;
              break ;
            case 1:
              ofs += 2 ;
              break ;
            case 2:
              ++i ;
              j = Src[ofs + 1] ;
              ofs += 2 ;
              break ;
            default:
              return ;
          } /* switch */
      } /* while (upper clipping) */
    if (i > clip_y2)
      {
        return ;
      } /* if */
    Dest = ( (BYTE *) screen_addr) + (i * screen_width) ;
    j += x ;

    if ( (x < clip_x1) || (x + (* src).w > clip_x2))
      {
        while (i <= clip_y2)
          {
            while (j < clip_x1)
              {
                switch (Src[ofs])
                  {
                    case 0:
                      if ( (Src[ofs + 1] + j - clip_x1) > 0)
                        {
                          memcpy(Dest + clip_x1, Src + ofs + 2 - (j - clip_x1),
                              Src[ofs + 1] + j - clip_x1) ;
                        } /* if */
                      j += Src[ofs + 1] ;
                      ofs += Src[ofs + 1] + 2 ;
                      break ;
                    case 1:
                      j += Src[ofs + 1] ;
                      ofs += 2 ;
                      break ;
                    case 2:
                      ++i ;
                      if (i > clip_y2)
                        {
                          return ;
                        } /* if */
                      Dest += screen_width ;
                      j = Src[ofs + 1] + x ;
                      ofs += 2 ;
                      break ;
                    default:
                      return ;
                  } /* switch */
              } /* while (left clipping) */
            while ( (j >= clip_x1) && (j <= clip_x2))
              {
                switch (Src[ofs])
                  {
                    case 0:
                      if ( (j + Src[ofs + 1]) <= clip_x2)
                        {
                          memcpy(Dest + j, Src + ofs + 2, Src[ofs + 1]) ;
                        } /* if */
                      else
                        {
                          memcpy(Dest + j, Src + ofs + 2, clip_x2 - j + 1) ;
                        } /* else (clip right) */
                      j += Src[ofs + 1] ;
                      ofs += Src[ofs + 1] + 2 ;
                      break ;
                    case 1:
                      j += Src[ofs + 1] ;
                      ofs += 2 ;
                      break ;
                    case 2:
                      ++i ;
                      if (i > clip_y2)
                        {
                          return ;
                        } /* if */
                      Dest += screen_width ;
                      j = Src[ofs + 1] + x ;
                      ofs += 2 ;
                      break ;
                    default:
                      return ;
                  } /* switch */
              } /* while (centre - unclipped) */
            while (j > clip_x2)
              {
                switch (Src[ofs])
                  {
                    case 0:
                      ofs += Src[ofs + 1] + 2 ;
                      break ;
                    case 1:
                      ofs += 2 ;
                      break ;
                    case 2:
                      ++i ;
                      if (i > clip_y2)
                        {
                          return ;
                        } /* if */
                      Dest += screen_width ;
                      j = Src[ofs + 1] + x ;
                      ofs += 2 ;
                      break ;
                    default:
                      return ;
                  } /* switch */
              } /* while (right clipping) */
          } /* while (lower clipping) */
      } /* if (horizontal clipping required) */
    else
      {
        while (1)
          {
            switch (Src[ofs])
              {
                case 0:
                  memcpy(Dest + j, Src + ofs + 2, Src[ofs + 1]) ;
                  j += Src[ofs + 1] ;
                  ofs += Src[ofs + 1] + 2 ;
                  break ;
                case 1:
                  j += Src[ofs + 1] ;
                  ofs += 2 ;
                  break ;
                case 2:
                  ++i ;
                  if (i > clip_y2)
                    {
                      return ;
                    } /* if */
                  Dest += screen_width ;
                  j = Src[ofs + 1] + x ;
                  ofs += 2 ;
                  break ;
                default:
                  return ;
              } /* switch */
          } /* while (lower clipping) */
      } /* else (no horizontal clipping) */
} /* rle_put */

/* OK, hopefully that will work and will be fast enough */

/* Test programme */
/*
int main(void)
{
    RLEBLK block ;
    int i, x, y ;
    
    init_gfx(0x13) ;
    if (!load_pic("endgegn1.pix", screen_addr, alt_rgb))
      {
        exit_gfx() ;
        return(1) ;
      }
    SetPalette(alt_rgb) ;
    rle_get(6, 5, 170, 162, & block) ;
    i = timer() ;
    x = -131 ;
    y = -70 ;
    while (!keyTest(KEY_SPACE))
      {
        cls(0) ;
        rle_put(x, y, & block) ;
        Copy2Screen() ;
        while (i == timer()) ;
        i = timer() ;
        x +=4 ;
        if (x > 320)
          {
            x = -131 ;
            y += 10 ;
            if (y > 200)
              {
                y = -70 ;
              }
          }
      }
    exit_gfx() ;
    return(0) ;
}
*/
