random.C

00001 /*
00002  * This file is part of the "Archon" framework.
00003  * (http://files3d.sourceforge.net)
00004  *
00005  * Copyright © 2002 by Kristian Spangsege and Brian Kristiansen.
00006  *
00007  * Permission to use, copy, modify, and distribute this software and
00008  * its documentation under the terms of the GNU General Public License is
00009  * hereby granted. No representations are made about the suitability of
00010  * this software for any purpose. It is provided "as is" without express
00011  * or implied warranty. See the GNU General Public License
00012  * (http://www.gnu.org/copyleft/gpl.html) for more details.
00013  *
00014  * The characters in this file are ISO8859-1 encoded.
00015  *
00016  * The documentation in this file is in "Doxygen" style
00017  * (http://www.doxygen.org).
00018  */
00019 
00020 #include <stdlib.h>
00021 #include <time.h>
00022 #include <unistd.h>
00023 #include <math.h>
00024 
00025 #include <archon/util/random.H>
00026 
00027 static bool initialized;
00028 
00029 static void init()
00030 {
00031 
00032   time_t t;
00033 
00034   /* Initialize random number generator */
00035   time(&t);
00036   srand(static_cast<unsigned>(t) + static_cast<unsigned>(getpid()));
00037 
00038   initialized = true;
00039 }
00040 
00041 namespace Archon
00042 {
00043   namespace Utilities
00044   {
00045     int drawInt(int bound)
00046     {
00047       if(!initialized) init();
00048       return static_cast<int>(static_cast<double>(bound)*rand()/(RAND_MAX+1.0));
00049     }
00050 
00051     double drawFloat()
00052     {
00053       if(!initialized) init();
00054       return rand()/static_cast<double>(RAND_MAX);
00055     }
00056 
00057     double drawFloatOpen()
00058     {
00059       if(!initialized) init();
00060       return rand()/(RAND_MAX+1.0);
00061     }
00062 
00063     Math::Vector3 drawUnitVector3()
00064     {
00065       Math::Vector3 w;
00066       w[2] = drawFloat() * 2 - 1;
00067       double r = sqrt(1 - w[2] * w[2]);
00068       double a = drawFloatOpen() * 2 * M_PI;
00069       w[0] = r * cos(a);
00070       w[1] = r * sin(a);
00071       return w;
00072     }
00073   }
00074 }
00075 

Generated on Sun Jul 30 22:55:45 2006 for Archon by  doxygen 1.4.4