rect.c (1966B)
1 /* 2 * Copyright (c) 2021-2024 lumidify <nobody@lumidify.org> 3 * 4 * Permission to use, copy, modify, and/or distribute this software for any 5 * purpose with or without fee is hereby granted, provided that the above 6 * copyright notice and this permission notice appear in all copies. 7 * 8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 */ 16 17 #include "rect.h" 18 19 /* FIXME */ 20 #undef MAX 21 #undef MIN 22 #define MAX(a, b) ((a) > (b) ? (a) : (b)) 23 #define MIN(a, b) ((a) < (b) ? (a) : (b)) 24 25 ltk_rect 26 ltk_rect_intersect(ltk_rect r1, ltk_rect r2) { 27 ltk_rect i; 28 i.x = MAX(r1.x, r2.x); 29 i.y = MAX(r1.y, r2.y); 30 i.w = MIN(r1.x + r1.w, r2.x + r2.w) - i.x; 31 i.h = MIN(r1.y + r1.h, r2.y + r2.h) - i.y; 32 return i; 33 } 34 35 int 36 ltk_rect_fakedist(ltk_rect r1, ltk_rect r2) { 37 ltk_rect i = ltk_rect_intersect(r1, r2); 38 /* FIXME: this depends on the weird implementation of intersect above */ 39 if (i.w >= 0 && i.h >= 0) 40 return 0; 41 else if (i.w >= 0) 42 return -i.h; 43 else if (i.h >= 0) 44 return -i.w; 45 else 46 return -(i.w + i.h); 47 } 48 49 ltk_rect 50 ltk_rect_relative(ltk_rect parent, ltk_rect child) { 51 return (ltk_rect){child.x - parent.x, child.y - parent.y, child.w, child.h}; 52 } 53 54 ltk_rect 55 ltk_rect_union(ltk_rect r1, ltk_rect r2) { 56 ltk_rect u; 57 u.x = MIN(r1.x, r2.x); 58 u.y = MIN(r1.y, r2.y); 59 u.w = MAX(r1.x + r1.w, r2.x + r2.w) - u.x; 60 u.h = MAX(r1.y + r1.h, r2.y + r2.h) - u.y; 61 return u; 62 } 63 64 int 65 ltk_collide_rect(ltk_rect rect, int x, int y) { 66 return (rect.x <= x && (rect.x + rect.w) >= x && rect.y <= y 67 && (rect.y + rect.h) >= y); 68 }