summaryrefslogtreecommitdiff
path: root/lib/vec2.c
blob: 55f5078a89173d34ec38cc9e92b54abcfa55c629 (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
#include <assert.h>
#include <math.h>

#include "types.h"

vec2
dp_vec2_new(float x, float y)
{
	vec2 new;
	
	assert(isfinite(x));
	assert(isfinite(y));

	new.x = x;
	new.y = y;
	return new;
}

vec2
dp_vec2_add(vec2 a, vec2 b)
{
	vec2 new;
	new.x = a.x + b.x;
	new.y = a.y + b.y;
	return new;
}

vec2
dp_vec2_sub(vec2 a, vec2 b)
{
	vec2 new;
	new.x = a.x - b.x;
	new.y = a.y - b.y;
	return new;
}

vec2
dp_vec2_mul(vec2 vec, float scalar)
{
	vec2 new;
	new.x = vec.x * scalar;
	new.y = vec.y * scalar;
	return new;
}

vec2
dp_vec2_dot(vec2 a, vec2 b)
{
	vec2 dot;
	dot.x = a.x * b.x;
	dot.y = a.y * b.y;
	return dot;
}

float
dp_vec2_length(vec2 v)
{
	return sqrtf(powf(v.x, 2.f) + powf(v.y, 2.f));
}

vec2
dp_vec2_normal(vec2 v)
{
	float len = dp_vec2_length(v);
	if (len == 0.0f)
		return dp_vec2_new(0.0f, 0.0f);
	return dp_vec2_mul(v, 1.0f / len);
}