Line data Source code
1 :
2 : /* Copyright (c) 2007-2014, Stefan Eilemann <eile@equalizergraphics.com>
3 : *
4 : * This library is free software; you can redistribute it and/or modify it under
5 : * the terms of the GNU Lesser General Public License version 2.1 as published
6 : * by the Free Software Foundation.
7 : *
8 : * This library is distributed in the hope that it will be useful, but WITHOUT
9 : * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
10 : * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
11 : * details.
12 : *
13 : * You should have received a copy of the GNU Lesser General Public License
14 : * along with this library; if not, write to the Free Software Foundation, Inc.,
15 : * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
16 : */
17 :
18 : #ifndef LUNCHBOX_RNG_H
19 : #define LUNCHBOX_RNG_H
20 :
21 : #include <lunchbox/debug.h> // for LBASSERT
22 : #include <lunchbox/init.h> // friend function
23 : #include <lunchbox/types.h>
24 : #include <boost/noncopyable.hpp>
25 : #include <limits>
26 :
27 : namespace lunchbox
28 : {
29 : namespace detail { class RNG; }
30 :
31 : /**
32 : * A random number generator.
33 : *
34 : * Generates a set of random, or if not supported by the operating system,
35 : * pseudo-random numbers. Each instance creates its own series of numbers.
36 : * @deprecated Use Boost.Random
37 : *
38 : * Example: @include tests/rng.cpp
39 : */
40 : class RNG : public boost::noncopyable
41 : {
42 : public:
43 : /** Construct a new random number generator. @version 1.0 */
44 : LUNCHBOX_API RNG();
45 :
46 : /** Destruct the random number generator. @version 1.0 */
47 : LUNCHBOX_API ~RNG();
48 :
49 : /**
50 : * Generate a random number.
51 : *
52 : * The returned number is between min..max for integer types, and
53 : * between 0..1 for floating-point types.
54 : * @return a random number.
55 : * @version 1.0
56 : */
57 510401 : template< typename T > T get()
58 : {
59 100000 : T value;
60 510401 : if( !_get( &value, sizeof( T )))
61 0 : return T();
62 510401 : return value;
63 : }
64 :
65 : private:
66 : LUNCHBOX_API bool _get( void* data, size_t size );
67 : };
68 :
69 7 : template<> inline float RNG::get()
70 : {
71 : const float max_limits =
72 7 : static_cast< float >( std::numeric_limits< uint32_t >::max( ));
73 7 : return ((float)get< uint32_t >() / max_limits);
74 : }
75 :
76 5 : template<> inline double RNG::get()
77 : {
78 : const double max_limits =
79 5 : static_cast< double >( std::numeric_limits< uint64_t >::max( ));
80 5 : return ((double)get< uint64_t >() / max_limits);
81 : }
82 :
83 : template<> inline bool RNG::get()
84 : {
85 : return ( get< uint32_t >() & 1 );
86 : }
87 : }
88 : #endif // LUNCHBOX_RNG_H
|