summaryrefslogtreecommitdiffstats
path: root/vector/vector.c
blob: 59f48cc987a31db5ff4e1366619c82f05b01cfd0 (plain)
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <stddef.h>
#include <stdio.h>
#include <math.h>

struct vec3 {
    double x;
    double y;
    double z;
};

struct vec3 vec3_add(struct vec3 * const v, struct vec3 * const u)
{
    struct vec3 result = {0, 0, 0};

    if (v == NULL || u == NULL)
        return result;

    result.x = v->x + u->x;
    result.y = v->y + u->y;
    result.z = v->z + u->z;

    return result;
}

struct vec3 vec3_mul(struct vec3 * const v, const double scalar)
{
    struct vec3 result = {0, 0, 0};

    if (v == NULL)
        return result;

    result.x = scalar * v->x;
    result.y = scalar * v->y;
    result.z = scalar * v->z;

    return result;
}

struct vec3 vec3_sub(struct vec3 * const v, struct vec3 * const u)
{
    struct vec3 result = {0, 0, 0};
    
    result = vec3_mul(u, -1.0);
    result = vec3_add(v, &result);

    return result;
}

double vec3_dot(struct vec3 * const v, struct vec3 * const u)
{
    if (v == NULL || u == NULL)
        return 0;

    return (v->x * u->x) + (v->y * u->y) + (v->z * u->y);
}

struct vec3 vec3_cross(struct vec3 * const v, struct vec3 * const u)
{
    struct vec3 result = {0, 0, 0};

    result.x = (v->y * u->z) - (v->z * u->y);
    result.y = (v->z * u->x) - (v->x * u->z);
    result.z = (v->x * u->y) - (v->y * u->x);

    return result;
}

double vec3_mag(struct vec3 * const v) {
    return sqrt((v->x * v->x) + (v->y * v->y) + (v->z * v->z));
}

void vec3_print(struct vec3 * const v)
{
    if (v == NULL)
        return;

    printf("<%.2f,%.2f,%.2f>\n", v->x, v->y, v->z);
}


int main(int argc, char *argv[])
{
    struct vec3 a = {1, 2, 3};
    struct vec3 b = {4, 5, 6};
    struct vec3 res;

    printf("a = ");
    vec3_print(&a);
    printf("b = ");
    vec3_print(&b);

    printf("||a|| = %f\n", vec3_mag(&a));

    printf("sum a + b     : ");
    res = vec3_add(&a, &b);
    vec3_print(&res);

    printf("sub a - b     : ");
    res = vec3_sub(&a, &b);
    vec3_print(&res);

    printf("product 3*a   : ");
    res = vec3_mul(&a, 3);
    vec3_print(&res);

    printf("dot product   : ");
    printf("%.2f\n", vec3_dot(&a, &b));

    printf("cross product : ");
    res = vec3_cross(&a, &b);
    vec3_print(&res);

    return 0;
}