metaforce/Runtime/CRandom16.hpp

81 lines
1.5 KiB
C++
Raw Normal View History

2015-07-28 02:24:36 +00:00
#ifndef RETRO_CRANDOM16_HPP
#define RETRO_CRANDOM16_HPP
#include "GCNTypes.hpp"
2015-07-28 02:24:36 +00:00
namespace Retro
{
class CRandom16
{
u32 m_seed;
2016-02-07 16:15:43 +00:00
static CRandom16* g_randomNumber;
2015-07-28 02:24:36 +00:00
public:
CRandom16(u32 p) : m_seed(p) {}
2015-07-28 02:24:36 +00:00
inline u32 Next()
2015-07-28 02:24:36 +00:00
{
2015-08-12 01:45:45 +00:00
m_seed = (m_seed * 0x41c64e6d) + 0x00003039;
2015-07-28 02:24:36 +00:00
return m_seed >> 16;
}
inline u32 GetSeed() const
2015-07-28 02:24:36 +00:00
{
return m_seed;
}
inline void SetSeed(u32 p)
2015-07-28 02:24:36 +00:00
{
m_seed = p;
}
inline float Float()
{
return Next() * 0.000015259022;
}
inline float Range(float min, float max)
{
return min + Float() * (max - min);
}
inline s32 Range(s32 min, s32 max)
2015-07-28 02:24:36 +00:00
{
s32 diff = max - min;
s32 rand = -1;
2015-07-28 23:53:57 +00:00
while (rand < 0)
rand = s32((Next() << 16) | Next());
2015-07-28 02:24:36 +00:00
return rand % diff + min;
}
2016-02-07 16:15:43 +00:00
static CRandom16* GetRandomNumber() {return g_randomNumber;}
static void SetRandomNumber(CRandom16* rnd) {g_randomNumber = rnd;}
2015-07-28 02:24:36 +00:00
};
class CGlobalRandom
{
CRandom16& m_random;
CGlobalRandom* m_prev;
2016-02-07 16:15:43 +00:00
static CGlobalRandom* g_currentGlobalRandom;
2015-07-28 02:24:36 +00:00
public:
CGlobalRandom(CRandom16& rand)
2016-02-07 16:15:43 +00:00
: m_random(rand), m_prev(g_currentGlobalRandom)
2015-07-28 02:24:36 +00:00
{
2016-02-07 16:15:43 +00:00
g_currentGlobalRandom = this;
2015-07-28 02:24:36 +00:00
CRandom16::SetRandomNumber(&m_random);
}
~CGlobalRandom()
{
2016-02-07 16:15:43 +00:00
g_currentGlobalRandom = m_prev;
2015-07-28 02:24:36 +00:00
if (m_prev)
CRandom16::SetRandomNumber(&m_prev->m_random);
else
CRandom16::SetRandomNumber(nullptr);
}
};
}
#endif // RETRO_CRANDOM16_HPP