summaryrefslogtreecommitdiff
path: root/maths.c
blob: d0bccf3eaf06149ec15a7609fbf0a12fa218c007 (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
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
115
#include "maths.h"

#define sin_table_count 256

static const int sin_table[sin_table_count] = {
	0, 25, 50, 75,
	100, 125, 150, 175,
	200, 224, 249, 273,
	297, 321, 345, 369,
	392, 415, 438, 460,
	483, 505, 526, 548,
	569, 590, 610, 630,
	650, 669, 688, 706,
	724, 742, 759, 775,
	792, 807, 822, 837,
	851, 865, 878, 891,
	903, 915, 926, 936,
	946, 955, 964, 972,
	980, 987, 993, 999,
	1004, 1009, 1013, 1016,
	1019, 1021, 1023, 1024,
	1024, 1024, 1023, 1021,
	1019, 1016, 1013, 1009,
	1004, 999, 993, 987,
	980, 972, 964, 955,
	946, 936, 926, 915,
	903, 891, 878, 865,
	851, 837, 822, 807,
	792, 775, 759, 742,
	724, 706, 688, 669,
	650, 630, 610, 590,
	569, 548, 526, 505,
	483, 460, 438, 415,
	392, 369, 345, 321,
	297, 273, 249, 224,
	200, 175, 150, 125,
	100, 75, 50, 25,
	0, -25, -50, -75,
	-100, -125, -150, -175,
	-200, -224, -249, -273,
	-297, -321, -345, -369,
	-392, -415, -438, -460,
	-483, -505, -526, -548,
	-569, -590, -610, -630,
	-650, -669, -688, -706,
	-724, -742, -759, -775,
	-792, -807, -822, -837,
	-851, -865, -878, -891,
	-903, -915, -926, -936,
	-946, -955, -964, -972,
	-980, -987, -993, -999,
	-1004, -1009, -1013, -1016,
	-1019, -1021, -1023, -1024,
	-1024, -1024, -1023, -1021,
	-1019, -1016, -1013, -1009,
	-1004, -999, -993, -987,
	-980, -972, -964, -955,
	-946, -936, -926, -915,
	-903, -891, -878, -865,
	-851, -837, -822, -807,
	-792, -775, -759, -742,
	-724, -706, -688, -669,
	-650, -630, -610, -590,
	-569, -548, -526, -505,
	-483, -460, -438, -415,
	-392, -369, -345, -321,
	-297, -273, -249, -224,
	-200, -175, -150, -125,
	-100, -75, -50, -25
};

int fsqrt(int n) {
	int lo, hi, mid, i, mm;
	if (n <= 0) { return -1; }
	lo = mini(1, n);
	hi = maxi(1, n);
	while ((100 << fbits * lo * lo) >> fbits * 2)
		lo *= (10 << fbits) >> fbits;
	while ((5 * hi * hi) >> fbits * 2 > n)
		hi *= (1 << fbits) / 10;
	for (i = 0; i < 100; i++) {
		mid = ((lo + hi) * (1 << fbits)) / (2 << fbits);
		mm = mid * mid >> fbits;
		if (mm == n) return mid;
		if (mm > n)  hi = mid;
		else         lo = mid;
	}
	return mid;
}

int absolute(int x) {
	return x >= 0 ? x : -x;
}

int fsin(int t) {
	int index, sign;
	sign = t >= 0 ? 1 : -1;
	t = absolute(t);
	index = (t * (sin_table_count) / ((1 << fbits) * 2));
	index = index % sin_table_count;
	return (sign * sin_table[index]) / 2;
}

int fcos(int t) {
	return fsin((1 << fbits) / 2 - t);
}

int ftan(int t) {
	return (fsin(t) << fbits) / fcos(t);
}

int flerp(int a, int b, int t) {
	return a + ((t * (b - a)) >> fbits);
}