/************************************************************************
* math.c
* voxelands - 3d voxel world sandbox game
* Copyright (C) Lisa 'darkrose' Milne 2016 <lisa@ltmnet.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>
************************************************************************/

#include "common.h"

#include <math.h>
#include <time.h>
#include <stdlib.h>

/* get the next power of 2 */
int math_next_pow2(int a)
{
	int rval = 2;

	while (rval<a) {
		rval <<= 1;
	}

	return rval;
}

/* return a random number between low and high */
int math_rand_range(int low, int high)
{
	static int rand_seeded = 0;
	int x;
	int n = (high-low)+1;
	int rand_limit;
	int rand_excess;

	if (low >= high)
		return low;

	if (!rand_seeded) {
		srand((unsigned int)time(NULL));
		rand_seeded = 1;
	}

	rand_excess = ((int64_t)RAND_MAX + 1) % n;
	rand_limit = RAND_MAX - rand_excess;
	while ((x = rand()) > rand_limit);

	return (x % n)+low;
}

/* return a random number between low and high */
float math_rand_rangef(float low, float high)
{
	int r = math_rand_range(low*1000,high*1000);
	return (float)r/1000.0;
}
