rearrange some things
[voxelands-alt.git] / src / lib / math.c
blob09eb7aa68f361fd5b9cf92101a7df51801a378aa
1 /************************************************************************
2 * math.c
3 * voxelands - 3d voxel world sandbox game
4 * Copyright (C) Lisa 'darkrose' Milne 2016 <lisa@ltmnet.com>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14 * See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>
18 ************************************************************************/
20 #include "common.h"
22 #include <math.h>
23 #include <time.h>
24 #include <stdlib.h>
26 /* get the next power of 2 */
27 int math_next_pow2(int a)
29 int rval = 2;
31 while (rval<a) {
32 rval <<= 1;
35 return rval;
38 /* return a random number between low and high */
39 int math_rand_range(int low, int high)
41 static int rand_seeded = 0;
42 int x;
43 int n = (high-low)+1;
44 int rand_limit;
45 int rand_excess;
47 if (low >= high)
48 return low;
50 if (!rand_seeded) {
51 srand((unsigned int)time(NULL));
52 rand_seeded = 1;
55 rand_excess = ((int64_t)RAND_MAX + 1) % n;
56 rand_limit = RAND_MAX - rand_excess;
57 while ((x = rand()) > rand_limit);
59 return (x % n)+low;
62 /* return a random number between low and high */
63 float math_rand_rangef(float low, float high)
65 int r = math_rand_range(low*1000,high*1000);
66 return (float)r/1000.0;
69 /* convert radians to degrees */
70 float math_radians_to_degrees(float rads)
72 return rads*(180.0*M_PI);
75 /* convert degrees to radians */
76 float math_degrees_to_radians(float degrees)
78 return degrees*(M_PI/180.0);