Generating a random number in q3_ui

Locked
User avatar
Eraser
Posts: 19174
Joined: Fri Dec 01, 2000 8:00 am

Generating a random number in q3_ui

Post by Eraser »

I've succesfully used code like this:

Code: Select all

int i;
i = rand() % 4;
in cgame where this would generate a proper random number for me.
In q3_ui (more specifically in ui_main.c) I'm trying to use the same code to generate a random number, but for some reason, it always generates the same number for me. If I leave out the "% 4" bit, then it always generates the number 41 for me. Why is this not working? Do I need to manually initialize some seed or something somewhere? And if so, how?
Silicone_Milk
Posts: 2237
Joined: Sat Mar 12, 2005 10:49 pm

Re: Generating a random number in q3_ui

Post by Silicone_Milk »

sounds to me like it's not being seeded properly before use, like you've said.

Usually the current time on program start is used as the seed before rand() is called.

It's set such as srand(value);

I would imagine you could just include "time.h" and call srand(time(NULL)); in q3_ui's entry point.
^misantropia^
Posts: 4022
Joined: Sat Mar 12, 2005 6:24 pm

Re: Generating a random number in q3_ui

Post by ^misantropia^ »

You can't use system headers. game and cgame use level.time to seed the generator but for q3_ui you need to declare trap_RealTime():

Code: Select all

int trap_RealTime(qtime_t *qtime) {
        return syscall( UI_REAL_TIME, qtime );
}
Apropos:

Image

Image
User avatar
Eraser
Posts: 19174
Joined: Fri Dec 01, 2000 8:00 am

Re: Generating a random number in q3_ui

Post by Eraser »

Urm, what do you mean I need to declare it? It's already there in cg_syscalls.c and declared in ui_local.h
Did you mean to say I need to call it? And what is the qtime argument and what does it return?

edit:
nm, doing this seems random enough for me (i guess it returns the current UTC time?):

Code: Select all

int r;
qtime_t *qtime;
r = trap_RealTime(qtime) % 4;
Not sure if that's what you meant though
^misantropia^
Posts: 4022
Joined: Sat Mar 12, 2005 6:24 pm

Re: Generating a random number in q3_ui

Post by ^misantropia^ »

Hah, that's randomness of the kind you don't want: in your example, the engine writes data to whatever that uninitialized pointer points to.

You need to pass it a pointer to a qtime_t struct, like this:

Code: Select all

qtime_t tm;
int seed;

trap_RealTime(&tm);
seed = 1;
seed = seed * 31 + tm.tm_sec;
seed = seed * 31 + tm.tm_min;
seed = seed * 31 + tm.tm_hour;
seed = seed * 31 + tm.tm_mday;
srand(seed);
User avatar
Eraser
Posts: 19174
Joined: Fri Dec 01, 2000 8:00 am

Re: Generating a random number in q3_ui

Post by Eraser »

ok, got it to work. Thanks.
Locked