JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
bbox collision detection.
[vor.git] / shape.c
1 #include <stdlib.h>
2 #include "shape.h"
3
4 void
5 get_shape(SDL_Surface *img, struct shape *s)
6 {
7         int x, y;
8         uint16_t *px, transp;
9         uint32_t bits;
10
11         if(img->format->BytesPerPixel != 2) {
12                 fprintf(stderr, "get_shape(): not a 16-bit image!\n");
13                 exit(1);
14         }
15
16         s->w = img->w; s->h = img->h;
17         s->mw = ((img->w+31)>>5) * img->h;
18         s->mask = malloc(4*s->mw);
19         if(!s->mask) {
20                 fprintf(stderr, "can't malloc bitmask");
21                 exit(1);
22         }
23
24         SDL_LockSurface(img);
25         px = img->pixels;
26         transp = img->format->colorkey;
27         bits = 0;
28         for(y=0; y<img->h; y++) {
29                 for(x=0; x<img->w; x++) {
30                         if(*px++ != transp) bits |= 1;
31                         if(x == img->w-1 || !(x+1)%32) {
32                                 *(s->mask++) = bits;
33                                 bits = 0;
34                         } else bits = bits << 1;
35                 }
36                 px = (uint16_t *) ((uint8_t *) px + img->pitch - 2*img->w);
37         }
38         SDL_UnlockSurface(img);
39 }
40
41 #ifndef max
42 #define max(a, b) ((a) > (b) ? (a) : (b))
43 #endif
44
45 #ifndef min
46 #define min(a, b) ((a) < (b) ? (a) : (b))
47 #endif
48
49 int
50 collide(int xdiff, int ydiff, struct shape *r, struct shape *s)
51 {
52         int xov, yov;
53
54         if(xdiff >= 0) xov = max(min(r->w-xdiff, s->w), 0);
55         else xov = min(-min(s->w+xdiff, r->w), 0);
56
57         if(ydiff >= 0) yov = max(min(r->h-ydiff, s->h), 0);
58         else yov = min(-min(s->h+ydiff, r->h), 0);
59
60         if(xov == 0 || yov == 0) return 0;  // bboxes hit?
61         else return 1;
62 }