If the seed you give rand is 0 it should always spit out the same numbers every time. Could it be that your system clock is somehow giving zero as the seed?
If the seed you give rand is 0 it will simply not re-seed the RNG, which means it will retain the seed it had at mission load. (Which, for single player, is the system time at the point you loaded the mission.)
I suppose it's possible that the clock is somehow returning zero. Obviously,
something is producing the bizarre behavior, whether it's the clock or my sexp logic. More testing is required.
We have actually talked about this before.
Indeed. But whereas in that previous conversation I was making a guess at the implementation, in this one I'm talking about the results of testing.
My question is, why are we reseeding the rng anyway? I can sort of see doing so in order to keep the rng in sync in multiplayer (even though that largely doesn't matter to us, since most of the important rng-related things, like sexps and AI, are handled by the server), but surely a single seed on program start should yield a sufficiently random number sequence?
Your reasoning is correct. The RNG is seeded at game startup (in game_init()) and that should be sufficient, for single player. For multiplayer, it makes sense to sync the RNG at the beginning of every mission to ensure that all clients receive the same sequence of values. However, that block of code re-seeds the RNG for single player too. That's unnecessary, but theoretically harmless.
But hold the phone,
look at this...
void __cdecl srand (
unsigned int seed
)
{
_getptd()->_holdrand = (unsigned long)seed;
}
int __cdecl rand (
void
)
{
_ptiddata ptd = _getptd();
return( ((ptd->_holdrand = ptd->_holdrand * 214013L
+ 2531011L) >> 16) & 0x7fff );
}
That calculation tosses out the least significant 16 bits of the seed. That means that, as long as you restart the mission within 65,536 seconds (which is more than 18 hours), it is as if you are using the
same seed at the beginning of every playthrough. That would give you the same sequence of numbers!
Am I reading this right? Does anyone else have an implementation of rand()?
EDIT: Well, apparently a brief search indicates rand() has all sorts of implementation problems, even more than the RAND_MAX of 0x7fff problem that was solved fairly recently. Looks like I've uncovered another rabbit hole.
EDIT2: Looks like I'm not the only one who has
noticed this, though those guys were unable to figure out the cause.
EDIT3: I'll investigate this a bit more and then I think I'll make a PR to not seed the RNG anymore on single-player mission load.