1.1 --- a/core/logic/smn_float.cpp Mon Oct 26 23:51:39 2009 -0700
1.2 +++ b/core/logic/smn_float.cpp Mon Oct 26 23:59:59 2009 -0700
1.3 @@ -1,5 +1,5 @@
1.4 /**
1.5 - * vim: set ts=4 :
1.6 + * vim: set ts=4 sw=4 tw=99 :
1.7 * =============================================================================
1.8 * SourceMod
1.9 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
1.10 @@ -33,6 +33,8 @@
1.11 #include <string.h>
1.12 #include <stdlib.h>
1.13 #include "common_logic.h"
1.14 +#include "MersenneTwister.h"
1.15 +#include <IPluginSys.h>
1.16
1.17 /****************************************
1.18 * *
1.19 @@ -285,6 +287,68 @@
1.20 }
1.21 #endif
1.22
1.23 +class RandomHelpers :
1.24 + public SMGlobalClass,
1.25 + public IPluginsListener
1.26 +{
1.27 +public:
1.28 + void OnSourceModAllInitialized()
1.29 + {
1.30 + pluginsys->AddPluginsListener(this);
1.31 + }
1.32 +
1.33 + void OnSourceModShutdown()
1.34 + {
1.35 + pluginsys->RemovePluginsListener(this);
1.36 + }
1.37 +
1.38 + void OnPluginDestroyed(IPlugin *plugin)
1.39 + {
1.40 + MTRand *mtrand;
1.41 + if (plugin->GetProperty("core.logic.mtrand", (void**)&mtrand, true))
1.42 + {
1.43 + delete mtrand;
1.44 + }
1.45 + }
1.46 +
1.47 + MTRand *RandObjForPlugin(IPluginContext *ctx)
1.48 + {
1.49 + IPlugin *plugin = pluginsys->FindPluginByContext(ctx->GetContext());
1.50 + MTRand *mtrand;
1.51 + if (!plugin->GetProperty("core.logic.mtrand", (void**)&mtrand))
1.52 + {
1.53 + mtrand = new MTRand();
1.54 + plugin->SetProperty("core.logic.mtrand", mtrand);
1.55 + }
1.56 + return mtrand;
1.57 + }
1.58 +} s_RandHelpers;
1.59 +
1.60 +static cell_t GetURandomInt(IPluginContext *ctx, const cell_t *params)
1.61 +{
1.62 + MTRand *randobj = s_RandHelpers.RandObjForPlugin(ctx);
1.63 + /* Note the sign bit must be stripped off because cell_t is signed,
1.64 + * and this guarantees a range of [0,max_int]
1.65 + */
1.66 + return randobj->randInt() & 0x7FFFFFFF;
1.67 +}
1.68 +
1.69 +static cell_t GetURandomFloat(IPluginContext *ctx, const cell_t *params)
1.70 +{
1.71 + MTRand *randobj = s_RandHelpers.RandObjForPlugin(ctx);
1.72 + return sp_ftoc((float)randobj->rand());
1.73 +}
1.74 +
1.75 +static cell_t SetURandomSeed(IPluginContext *ctx, const cell_t *params)
1.76 +{
1.77 + MTRand *randobj = s_RandHelpers.RandObjForPlugin(ctx);
1.78 + cell_t *addr;
1.79 + ctx->LocalToPhysAddr(params[1], &addr);
1.80 + /* We're 32-bit only. */
1.81 + randobj->seed((MTRand::uint32*)addr, params[2]);
1.82 + return 1;
1.83 +}
1.84 +
1.85 REGISTER_NATIVES(floatnatives)
1.86 {
1.87 {"float", sm_float},
1.88 @@ -310,5 +374,9 @@
1.89 {"ArcCosine", sm_ArcCosine},
1.90 {"ArcSine", sm_ArcSine},
1.91 {"ArcTangent2", sm_ArcTangent2},
1.92 + {"GetURandomInt", GetURandomInt},
1.93 + {"GetURandomFloat", GetURandomFloat},
1.94 + {"SetURandomSeed", SetURandomSeed},
1.95 {NULL, NULL}
1.96 };
1.97 +