/* The Segment Pixel Perfect routine by FenrirWolf 3/26/99. */

#include "allegro.h"
#include "spp.h"

int spp_detect_collision (int x1, int y1, BITMAP *sprite1,
                          int x2, int y2, BITMAP *sprite2) {

  static int has_collided ;
  static int bx1, by1, bx2, by2, bx3, by3 ; // Our rectangular intersection points

  static int x, y, lenx, leny ;  // Used for the detection loop

  has_collided = FALSE ;  // Let's start with no preconceptions

  // First, do bounding-box detection
  if (((x1 + ((BITMAP *) sprite1)->w) >= x2)  &&
       (x1 < (x2 + ((BITMAP *) sprite2)->w)) &&
      ((y1 + ((BITMAP *) sprite1)->h) >= y2)  &&
       (y1 < (y2 + ((BITMAP *) sprite2)->h))) {

    // Compute the intersection point
    bx1 = x1 - x2 ; if (bx1 < 0) bx1 = 0 ;
    by1 = y1 - y2 ; if (by1 < 0) by1 = 0 ;

    if (x1 < x2) bx2 = x2 - x1 ; else bx2 = 0 ;
    if (y1 < y2) by2 = y2 - y1 ; else by2 = 0 ;

    if (x1 > x2 + ((BITMAP *) sprite2)->w - ((BITMAP *) sprite1)->w)
      bx3 = x2 + ((BITMAP *) sprite2)->w - x1 ;
    else
      bx3 = ((BITMAP *) sprite1)->w ;

    if (y1 > y2 + ((BITMAP *) sprite2)->h - ((BITMAP *) sprite1)->h)
      by3 = y2 + ((BITMAP *) sprite2)->h - y1 ;
    else
      by3 = ((BITMAP *) sprite1)->h ;

    lenx = abs (bx2 - bx3) ;
    leny = abs (by2 - by3) ;

    // Now, do pixel-perfect detection on the intersection rectangle
    for (y = 0; y < leny; y++)
      for (x = 0; x < lenx; x++)
        if (sprite1->line[by2 + y][bx2 + x] != 0)
          if (sprite2->line[by1 + y][bx1 + x] != 0)
            has_collided = TRUE ;
  }
  return (has_collided) ;
}

