//****************************************************************************
void init_sp_bb( apvector<spr_mask> & mask_list  )
// This function initializes the bounding box used to do the initial collision detection
{
	int i,c,z;

	for ( i =0; i < mask_list.length(); i++)
	{
		mask_list[i].bb_height=0;
  		mask_list[i].bb_width=0;
  		mask_list[i].max_chunk=0;
      for ( c = 0; c < NUM_Y; c++ )
   		for ( z = 0; z < NUM_CHUNKS; z++)
			    mask_list[i].sp_mask[c][z]=0;
	}
}
//****************************************************************************
void mk_spr_mask (BITMAP *s3, spr_mask & mask)
// This function produces the masks that do the pixel perfect collision detection
{
	int bb_height=0;
 	int bb_width=0;
 	int x1, y1, z;
 	int p;

 	for (y1=0; y1<NUM_Y; y1++)
	{

	  for(z=0; z<NUM_CHUNKS; z++)
     {
			for (x1=(z*32); x1<((z*32)+32); x1++)
         {
				p=getpixel(s3,x1,y1);
			   if (p>0)
     			{
      			if (z> mask.max_chunk)
               	( mask.max_chunk = z);
      			if (y1>bb_height)
               	bb_height=y1;
			      if (x1>bb_width)
               	bb_width=x1;
      			mask.sp_mask[y1][z]+=0x80000000 >> (x1 - ((z+1)*32));
			   }
			}
		}
	}
	mask.bb_height=bb_height;
	mask.bb_width=bb_width;
}
//****************************************************************************
int check_ppcollision (const spr_mask & mask1 , int spr1x, int spr1y, const spr_mask & mask2, int spr2x, int spr2y)
// this is the function that actually checks collisions
{
   int dx1, dx2, dy1, dy2, ddy1, ddy2;
	int spr1_chunk, spr2_chunk;
   int dx1_chunk, dx2_chunk;

	if ((spr1x>spr2x+ mask2.bb_width) || (spr2x > spr1x + mask1.bb_width) ||
     (spr1y>spr2y+ mask2.bb_height) || (spr2y> spr1y + mask1.bb_height))
   {
   	return 0;
	}
  	else
   {
   	if (spr1x>spr2x)
	   {
   		dx1=0;
      	dx2=spr1x-spr2x;
	   }
   	else
	   {
   	  dx1=spr2x-spr1x;
	     dx2=0;
   	}
  		if (spr1y>spr2y)
      {
		   dy1=0;
     		dy2=spr1y-spr2y;
	   }
   	else
      {
     		dy1=(spr2y-spr1y);
     		dy2=0;
   	}

      spr1_chunk = dx1 / 32;
    	spr2_chunk = dx2 / 32;
	   dx1_chunk = dx1 - (32 * spr1_chunk);
   	dx2_chunk = dx2 - (32 * spr2_chunk);

	   while((spr1_chunk <= mask1.max_chunk) & (spr2_chunk <= mask2.max_chunk))
      {
	    	ddy1 = dy1;
   		ddy2 = dy2;

    		while((ddy1<=mask1.bb_height)&&(ddy2<=mask2.bb_height))
         {
				if ((mask1.sp_mask[ddy1][spr1_chunk]<<dx1_chunk) & (mask2.sp_mask[ddy2][spr2_chunk]<<dx2_chunk))
			      return 1;
		      ddy1++;
     			ddy2++;
		   }

    		if((!dx1_chunk) && (!dx2_chunk))
         {
		      spr1_chunk++;
     			spr2_chunk++;
		   }
   		else if(!dx1_chunk)
         {
		      spr2_chunk++;
       		dx1_chunk = 32 - dx2_chunk;
       		dx2_chunk = 0;
		   }
    	   else if(!dx2_chunk)
         {
			   spr1_chunk++;
			   dx2_chunk = 32 - dx1_chunk;
			   dx1_chunk = 0;
  			}
	   }
   return 0; 
	}
}
//****************************************************************************

