Root/poly2d/v2d_intersect.c

1/*
2 * v2d_intersect.c - Intersect two lines
3 *
4 * Written 2012 by Werner Almesberger
5 * Copyright 2012 Werner Almesberger
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 */
12
13
14#include <math.h>
15
16#include "poly2d.h"
17
18
19#define EPSILON 1e-6
20
21
22/*
23 * Solve
24 *
25 * ax+by = e
26 * cx+dy = f
27 *
28 * with Cramer's rule:
29 * http://en.wikipedia.org/wiki/Cramer's_rule
30 */
31
32static int cramer2(double a, double b, double c, double d, double e, double f,
33    double *x, double *y)
34{
35    double det;
36
37    det = a*d-b*c;
38    if (fabs(det) < EPSILON)
39        return 0;
40    *x = (e*d-b*f)/det;
41    *y = (a*f-e*c)/det;
42    return 1;
43}
44
45
46int v2d_intersect(const struct v2d *a0, const struct v2d *a1,
47    const struct v2d *b0, const struct v2d *b1,
48    double *na, double *nb)
49{
50    double ax, ay, bx, by, dx, dy;
51    double a, b;
52
53    ax = a1->x-a0->x;
54    ay = a1->y-a0->y;
55
56    bx = b1->x-b0->x;
57    by = b1->y-b0->y;
58
59    dx = b0->x-a0->x;
60    dy = b0->y-a0->y;
61
62    if (!cramer2(ax, -bx, ay, -by, dx, dy, &a, &b))
63        return 0;
64    if (na)
65        *na = a;
66    if (nb)
67        *nb = b;
68    return a >= 0 && a <= 1 && b >= 0 && b <= 1 ? 1 : -1;
69}
70

Archive Download this file

Branches:
master



interactive