Lunchbox  1.4.0
rng.h
00001 
00002 /* Copyright (c) 2007-2012, Stefan Eilemann <eile@equalizergraphics.com> 
00003  *
00004  * This library is free software; you can redistribute it and/or modify it under
00005  * the terms of the GNU Lesser General Public License version 2.1 as published
00006  * by the Free Software Foundation.
00007  *  
00008  * This library is distributed in the hope that it will be useful, but WITHOUT
00009  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
00010  * FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
00011  * details.
00012  * 
00013  * You should have received a copy of the GNU Lesser General Public License
00014  * along with this library; if not, write to the Free Software Foundation, Inc.,
00015  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
00016  */
00017 
00018 #ifndef LUNCHBOX_RNG_H
00019 #define LUNCHBOX_RNG_H
00020 
00021 #include <lunchbox/debug.h> // for LBASSERT
00022 #include <lunchbox/init.h>  // friend function
00023 #include <lunchbox/nonCopyable.h>
00024 #include <lunchbox/types.h>
00025 
00026 #include <limits>
00027 
00028 namespace lunchbox
00029 {
00030 namespace detail { class RNG; }
00031 
00038     class RNG : public NonCopyable
00039     {
00040     public:
00042         LUNCHBOX_API RNG();
00043 
00045         LUNCHBOX_API ~RNG();
00046 
00048         LUNCHBOX_API void reseed();
00049 
00058         template< typename T > T get()
00059         {
00060             T value;
00061             if( !_get( &value, sizeof( T )))
00062                 return 0;
00063             return value;
00064         }
00065 
00066     private:
00067         detail::RNG* const _impl;
00068 
00069         static LUNCHBOX_API bool _init();
00070         static void _exit();
00071         friend LUNCHBOX_API bool init( const int argc, char** argv );
00072         LUNCHBOX_API bool _get( void* data, size_t size );
00073     };
00074 
00075     template<> inline float RNG::get()
00076     {
00077         const float max_limits =
00078             static_cast< float >( std::numeric_limits< uint32_t >::max( ));
00079         return ( get< uint32_t >() / max_limits);
00080     }
00081     
00082     template<> inline double RNG::get()
00083     {
00084         const double max_limits =
00085             static_cast< double >( std::numeric_limits< uint64_t >::max( ));
00086         return ( get< uint64_t >() / max_limits);
00087     }
00088     
00089     template<> inline bool RNG::get()
00090     {
00091         return ( get< uint32_t >() & 1 );
00092     }
00093 }
00094 #endif  // LUNCHBOX_RNG_H