summaryrefslogtreecommitdiff
path: root/3dmath.c
blob: d729323df21c1baec8b91c3d1125edf400a625ee (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <math.h>

#define POW2(x) ((x) * (x))

float
dot(float x[3], float y[3]) {
    return x[0] * y[0] + x[1] * y[1] + x[2] * y[2];
}

void
normalize(float x[3]) {
    float len;
    int i;

    len = sqrt(dot(x, x));

    for(i = 0; i < 3; ++i)
        x[i] /= len;
}

float
sphere_intersect(float s[3], float d[3], float c[3], float r) {
    int i;
    float D;
    float v[3];

    for(i = 0; i < 3; ++i)
        v[i] = s[i] - c[i];

    D = POW2(dot(v, d)) - 4 * (dot(v, v) - POW2(r));

    if(D < 0)
        return -1;

    return 1;
}