From 9fd2d7bdaf24a3984e6ad129e0c7afacd6a9ebd4 Mon Sep 17 00:00:00 2001 From: Matthias Kruk Date: Wed, 19 May 2021 08:23:05 +0900 Subject: [PATCH] common: Add functions for comparing geoms and pointers The loop_find() function needs a fallback comparison function to use if no other comparison function was provided. This commit adds a comparison function that compares two pointers. Further, this commit adds a function that calculates the intersecting area of two geometries. --- common.c | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ common.h | 10 ++++++++++ 2 files changed, 66 insertions(+) create mode 100644 common.c diff --git a/common.c b/common.c new file mode 100644 index 0000000..2c6058d --- /dev/null +++ b/common.c @@ -0,0 +1,56 @@ +#include "common.h" + +#ifndef MIN +#define MIN(X,Y) ((X) < (Y) ? (X) : (Y)) +#endif /* !defined(MIN) */ + +#ifndef MAX +#define MAX(X,Y) ((X) > (Y) ? (X) : (Y)) +#endif /* !defined(MAX) */ + +int cmp_pointer(void *left, void *right) +{ + return(left == right); +} + +int geom_intersects(struct geom *first, struct geom *second) +{ + int top; + int bottom; + int left; + int right; + int width; + int height; + + /* + * left + * | right + * | | + * v v + * +----------+ + * | | + * | +---+------+ <-- top + * | | | | + * +------+---+ | <-- bottom + * | | + * +----------+ + * + * This function calculated the area of the intersection of + * the two rectangles. If the area is zero, the rectangles + * do not intersect. + */ + + top = MAX(first->y, + second->y); + bottom = MIN(first->y + first->h, + second->y + second->h); + left = MAX(first->x, + second->x); + right = MIN(first->x + first->w, + second->x + second->w); + + width = MAX(0, right - left); + height = MAX(0, bottom - top); + + return(width * height); +} diff --git a/common.h b/common.h index 3bb5368..e041a23 100644 --- a/common.h +++ b/common.h @@ -8,4 +8,14 @@ struct geom { unsigned int h; }; +#ifndef FALSE +#define FALSE 0 +#endif +#ifndef TRUE +#define TRUE (!FALSE) +#endif + +int cmp_pointer(void *left, void *right); +int geom_intersects(struct geom *left, struct geom *right); + #endif /* COMMON_H */ -- 2.47.3