From 657217bedae4dc047333fdc61da8952a9a099999 Mon Sep 17 00:00:00 2001 From: Mark Cannon Date: Mon, 22 Aug 2011 11:45:45 -0700 Subject: [PATCH] replace math.random and math.randomseed with MersenneTwister --- Themes/_fallback/Scripts/00 init.lua | 6 ++++ src/RageUtil.cpp | 52 ++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/Themes/_fallback/Scripts/00 init.lua b/Themes/_fallback/Scripts/00 init.lua index 33c3105106..3c32232492 100644 --- a/Themes/_fallback/Scripts/00 init.lua +++ b/Themes/_fallback/Scripts/00 init.lua @@ -12,6 +12,12 @@ Trace = lua.Trace Warn = lua.Warn print = Trace +-- Use MersenneTwister in place of math.random and math.randomseed. +if MersenneTwister then + math.random = MersenneTwister.Random + math.randomseed = MersenneTwister.Seed +end + PLAYER_1 = "PlayerNumber_P1" PLAYER_2 = "PlayerNumber_P2" NUM_PLAYERS = #PlayerNumber diff --git a/src/RageUtil.cpp b/src/RageUtil.cpp index 2c9efc0be6..b550c0287e 100644 --- a/src/RageUtil.cpp +++ b/src/RageUtil.cpp @@ -5,6 +5,7 @@ #include "RageFile.h" #include "Foreach.h" #include "LocalizedString.h" +#include "LuaBinding.h" #include "LuaManager.h" #include @@ -90,6 +91,57 @@ int MersenneTwister::operator()() return Temper( m_Values[m_iNext++] ); } +/* Extend MersenneTwister into Lua space. This is intended to replace + * math.randomseed and math.random, so we conform to their behavior. */ + +namespace +{ + MersenneTwister g_LuaPRNG; + + static int Seed( lua_State *L ) + { + g_LuaPRNG.Reset( IArg(1) ); + return 0; + } + + static int Random( lua_State *L ) + { + unsigned min = 0, max = 0; + + /* [m..n] */ + if( lua_isnumber(L, 2) ) + { + min = IArg(1); + max = IArg(2); + lua_pushnumber( L, (g_LuaPRNG() % (max-min+1)) + min ); + } + /* [1..m] */ + else if( lua_isnumber(L, 1) ) + { + max = IArg(1); + lua_pushnumber( L, (g_LuaPRNG() % max) + 1 ); + } + else + /* [0..1) */ + { + /* we get values in [0..(2^32-1)]; divide by 2^32. */ + double rand = double(g_LuaPRNG()) / double(0x100000000f); + lua_pushnumber( L, rand ); + } + + return 1; + } + + const luaL_Reg MersenneTwisterTable[] = + { + LIST_METHOD( Seed ), + LIST_METHOD( Random ), + { NULL, NULL } + }; +} + +LUA_REGISTER_NAMESPACE( MersenneTwister ); + void fapproach( float& val, float other_val, float to_move ) { ASSERT_M( to_move >= 0, ssprintf("to_move: %f < 0", to_move) );