# random_func.cpp

Go to the documentation of this file.

    00001 /* $Id: random_func.cpp 17248 2009-08-21 20:21:05Z rubidium $ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
    00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
    00008  */
    00009
    00012 #include "../stdafx.h"
    00013 #include "random_func.hpp"
    00014 #include "bitmath_func.hpp"
    00015
    00016 Randomizer _random, _interactive_random;
    00017
    00018 uint32 Randomizer::Next()
    00019 {
    00020   const uint32 s = this->state[0];
    00021   const uint32 t = this->state[1];
    00022
    00023   this->state[0] = s + ROR(t ^ 0x1234567F, 7) + 1;
    00024   return this->state[1] = ROR(s, 3) - 1;
    00025 }
    00026
    00027 uint32 Randomizer::Next(uint16 max)
    00028 {
    00029   return GB(this->Next(), 0, 16) * max >> 16;
    00030 }
    00031
    00032 void Randomizer::SetSeed(uint32 seed)
    00033 {
    00034   this->state[0] = seed;
    00035   this->state[1] = seed;
    00036 }
    00037
    00038 void SetRandomSeed(uint32 seed)
    00039 {
    00040   _random.SetSeed(seed);
    00041   _interactive_random.SetSeed(seed * 0x1234567);
    00042 }
    00043
    00044 #ifdef RANDOM_DEBUG
    00045 #include "../network/network_internal.h"
    00046 #include "../company_func.h"
    00047
    00048 uint32 DoRandom(int line, const char *file)
    00049 {
    00050   if (_networking && (!_network_server || (NetworkClientSocket::IsValidID(0) && NetworkClientSocket::Get(0)->status != STATUS_INACTIVE))) {
    00051     printf("Random [%d/%d] %s:%d\n", _frame_counter, (byte)_current_company, file, line);
    00052   }
    00053
    00054   return _random.Next();
    00055 }
    00056
    00057 uint DoRandomRange(uint max, int line, const char *file)
    00058 {
    00059   return GB(DoRandom(line, file), 0, 16) * max >> 16;
    00060 }
    00061 #endif /* RANDOM_DEBUG */