blobwarsAttrition/src/util/maths.c

124 lines
2.0 KiB
C
Raw Permalink Normal View History

2018-01-21 10:31:38 +01:00
/*
2019-06-02 17:13:34 +02:00
Copyright (C) 2018-2019 Parallel Realities
2018-01-21 10:31:38 +01:00
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "maths.h"
2018-02-14 20:12:29 +01:00
float mod(float n, float x)
2018-01-21 10:31:38 +01:00
{
2018-02-14 20:12:29 +01:00
return fmod(fmod(n, x) + x, x);
2018-01-21 10:31:38 +01:00
}
2018-02-26 19:56:13 +01:00
float getAngle(int x1, int y1, int x2, int y2)
{
float angle = -90 + atan2(y1 - y2, x1 - x2) * (180 / PI);
return angle >= 0 ? angle : 360 + angle;
}
2018-01-21 10:31:38 +01:00
int rrnd(int low, int high)
{
return low + rand() % ((high - low) + 1);
}
2018-01-23 08:42:13 +01:00
double randF(void)
{
return (double)rand() / (double)((unsigned)RAND_MAX + 1);
}
2018-01-21 10:31:38 +01:00
int getPercent(float current, float total)
{
2018-03-04 18:03:11 +01:00
return total > 0 ? (current / total) * 100 : 0;
2018-01-21 10:31:38 +01:00
}
2018-01-21 12:12:49 +01:00
float limit(float i, float a, float b)
{
2018-01-31 09:37:01 +01:00
if (i < a)
2018-01-21 12:12:49 +01:00
{
return a;
}
2019-06-02 17:13:34 +02:00
2018-01-31 09:37:01 +01:00
if (i > b)
2018-01-21 12:12:49 +01:00
{
return b;
}
2019-06-02 17:13:34 +02:00
2018-01-21 12:12:49 +01:00
return i;
}
2018-01-21 10:31:38 +01:00
int getDistance(int x1, int y1, int x2, int y2)
{
int x, y;
2019-06-02 17:13:34 +02:00
2018-01-21 10:31:38 +01:00
x = x2 - x1;
y = y2 - y1;
2019-06-02 17:13:34 +02:00
2018-01-21 10:31:38 +01:00
return sqrt(x * x + y *y);
}
void getSlope(int x1, int y1, int x2, int y2, float *dx, float *dy)
{
int steps = MAX(abs(x1 - x2), abs(y1 - y2));
if (steps == 0)
{
*dx = *dy = 0;
return;
}
*dx = (x1 - x2);
*dx /= steps;
*dy = (y1 - y2);
*dy /= steps;
}
2018-01-23 08:42:13 +01:00
float wrap(float value, float low, float high)
{
if (value < low)
{
return high;
}
if (value > high)
{
return low;
}
return value;
}
2018-01-21 10:31:38 +01:00
unsigned long hashcode(const char *str)
{
unsigned long hash = 5381;
int c;
c = *str;
while (c)
{
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
c = *str++;
}
hash = ((hash << 5) + hash);
2019-06-02 17:13:34 +02:00
2018-01-21 10:31:38 +01:00
return hash;
}