#include "critical_points.h" #include #include "da.h" static double angle_sweep (double a0, double a1, int ccw) { double sweep = a1 - a0; if (ccw) { while (sweep <= 0) sweep += 2*M_PI; } else { while (sweep >= 0) sweep -= 2*M_PI; } // NOTE(cmmm): might need some eps return sweep; } static struct vec2 tangent_beg (struct vec2 p0, struct path_element *pe) { ASSERT (pe); struct vec2 p1 = { pe->x, pe->y }; if (~pe->flags & PEF_ARC) return vec2_unit (vec2_sub (p1, p0)); struct vec2 c = { pe->i, pe->j }; double a0 = vec2_angle0 (vec2_sub (p0, c)); double a1 = vec2_angle0 (vec2_sub (p1, c)); double sweep = angle_sweep (a0, a1, pe->flags & PEF_CCW); double sgn = sweep < 0 ? -1 : 1; double a = a0; return (struct vec2) { -sgn*sin (a), sgn*cos (a) }; } static struct vec2 tangent_end (struct vec2 p0, struct path_element *pe) { ASSERT (pe); struct vec2 p1 = { pe->x, pe->y }; if (~pe->flags & PEF_ARC) return vec2_unit (vec2_sub (p1, p0)); struct vec2 c = { pe->i, pe->j }; double a0 = vec2_angle0 (vec2_sub (p0, c)); double a1 = vec2_angle0 (vec2_sub (p1, c)); double sweep = angle_sweep (a0, a1, pe->flags & PEF_CCW); double sgn = sweep < 0 ? -1 : 1; double a = a0 + sweep; return (struct vec2) { -sgn*sin (a), sgn*cos (a) }; } struct critical_points find_critical_points (const struct path *path) { struct critical_points cps = {0}; if (path->count == 0) return cps; struct critical_point cp = { .right = &path->items[0], .r = { .x = path->initial_x, .y = path->initial_y, } }; if (~cp.right->flags & PEF_TRAVERSING) { cp.type = CPT_BEG; cp.t_right = tangent_beg (cp.r, cp.right); DA_APPEND (cps, cp); } struct vec2 beg = cp.r; for (uint32_t i = 1; i < path->count; ++i) { cp.left = cp.right; cp.right = &path->items[i]; cp.s = beg; cp.r.x = cp.left->x; cp.r.y = cp.left->y; if (cp.left ->flags & PEF_TRAVERSING && cp.right->flags & PEF_TRAVERSING) { goto next; } struct vec2 end = { .x = cp.right->x, .y = cp.right->y, }; cp.t_left = tangent_end (beg, cp.left ); cp.t_right = tangent_beg (cp.r, cp.right); double min_turn = M_PI/16; double turn = vec2_angle (cp.t_left, cp.t_right); if (cp.left ->flags & PEF_TRAVERSING) cp.type = CPT_IN; else if (cp.right->flags & PEF_TRAVERSING) cp.type = CPT_OUT; else if (turn < min_turn) goto next; else cp.type = CPT_LOOP; DA_APPEND (cps, cp); next: beg = cp.r; } cp.left = &DA_LAST (*path); if (~cp.left->flags & PEF_TRAVERSING) { cp.type = CPT_END; cp.r.x = cp.left->x; cp.r.y = cp.left->y; cp.t_left = tangent_end (beg, cp.left); DA_APPEND (cps, cp); } return cps; }