Added algorithm comments to SDL_rand_*()

This commit is contained in:
John Kaniarz 2024-06-19 16:18:00 -04:00 committed by Sam Lantinga
parent 8f29f8cae5
commit 38cac043af
2 changed files with 14 additions and 9 deletions

View file

@ -36,7 +36,7 @@ void SDL_srand(Uint64 seed)
Uint32 SDL_rand_bits(void)
{
if(!SDL_rand_initialized) {
if (!SDL_rand_initialized) {
SDL_srand(0);
}
@ -63,6 +63,10 @@ Uint32 SDL_rand_bits(void)
Sint32 SDL_rand_n(Sint32 n)
{
// Algorithm: get 32 bits from SDL_rand_bits() and treat it as a 0.32 bit
// fixed point number. Multiply by the 31.0 bit n to get a 31.32 bit
// result. Shift right by 32 to get the 31 bit integer that we want.
// On 32-bit arch, the compiler will optimize to a single 32-bit multiply
Uint64 val = (Uint64)SDL_rand_bits() * n;
return (Sint32)(val >> 32);
@ -70,5 +74,6 @@ Sint32 SDL_rand_n(Sint32 n)
float SDL_rand_float(void)
{
return (SDL_rand_bits() >> (32-24)) * 0x1p-24f;
// Note: its using 24 bits because float has 23 bits significand + 1 implicit bit
return (SDL_rand_bits() >> (32 - 24)) * 0x1p-24f;
}

View file

@ -188,15 +188,15 @@ int main(int argc, char *argv[])
quit(2);
}
for (i = 0; i < NUM_SPRITES; ++i) {
positions[i].x = (float)(SDL_rand_n((window_w - (int)sprite_w)));
positions[i].y = (float)(SDL_rand_n((window_h - (int)sprite_h)));
positions[i].x = (float)(SDL_rand_n(window_w - (int)sprite_w));
positions[i].y = (float)(SDL_rand_n(window_h - (int)sprite_h));
positions[i].w = sprite_w;
positions[i].h = sprite_h;
velocities[i].x = 0.0f;
velocities[i].y = 0.0f;
while (velocities[i].x == 0.f && velocities[i].y == 0.f) {
velocities[i].x = (float)((SDL_rand_n((MAX_SPEED * 2 + 1))) - MAX_SPEED);
velocities[i].y = (float)((SDL_rand_n((MAX_SPEED * 2 + 1))) - MAX_SPEED);
velocities[i].x = (float)(SDL_rand_n(MAX_SPEED * 2 + 1) - MAX_SPEED);
velocities[i].y = (float)(SDL_rand_n(MAX_SPEED * 2 + 1) - MAX_SPEED);
}
}