hedgewars/uRandom.pas
changeset 7389 15c3fb4882df
parent 7043 7c080e5ac8d0
child 7575 f415b3e0f3b9
equal deleted inserted replaced
7388:92535bc7e928 7389:15c3fb4882df
    33 procedure initModule;
    33 procedure initModule;
    34 procedure freeModule;
    34 procedure freeModule;
    35 
    35 
    36 procedure SetRandomSeed(Seed: shortstring); // Sets the seed that should be used for generating pseudo-random values.
    36 procedure SetRandomSeed(Seed: shortstring); // Sets the seed that should be used for generating pseudo-random values.
    37 function  GetRandomf: hwFloat; overload; // Returns a pseudo-random hwFloat.
    37 function  GetRandomf: hwFloat; overload; // Returns a pseudo-random hwFloat.
    38 function  GetRandom(m: LongWord): LongWord; overload; // Returns a positive pseudo-random integer smaller than m.
    38 function  GetRandom(m: LongWord): LongWord; overload; inline; // Returns a positive pseudo-random integer smaller than m.
       
    39 procedure AddRandomness(r: LongWord); inline;
    39 function  rndSign(num: hwFloat): hwFloat; // Returns num with a random chance of having a inverted sign.
    40 function  rndSign(num: hwFloat): hwFloat; // Returns num with a random chance of having a inverted sign.
       
    41 
    40 
    42 
    41 implementation
    43 implementation
    42 
    44 
    43 var cirbuf: array[0..63] of Longword;
    45 var cirbuf: array[0..63] of Longword;
    44     n: byte;
    46     n: byte;
    45 
    47 
    46 function GetNext: Longword;
    48 procedure AddRandomness(r: LongWord); inline;
       
    49 begin
       
    50 n:= (n + 1) and $3F;
       
    51 cirbuf[n]:= cirbuf[n] xor r
       
    52 end;
       
    53 
       
    54 function GetNext: Longword; inline;
    47 begin
    55 begin
    48 n:= (n + 1) and $3F;
    56 n:= (n + 1) and $3F;
    49 cirbuf[n]:=
    57 cirbuf[n]:=
    50            (cirbuf[(n + 40) and $3F] +           {n - 24 mod 64}
    58            (cirbuf[(n + 40) and $3F] +           {n - 24 mod 64}
    51             cirbuf[(n +  9) and $3F])            {n - 55 mod 64}
    59             cirbuf[(n +  9) and $3F])            {n - 55 mod 64}
    77 GetNext;
    85 GetNext;
    78 GetRandomf.isNegative:= false;
    86 GetRandomf.isNegative:= false;
    79 GetRandomf.QWordValue:= GetNext
    87 GetRandomf.QWordValue:= GetNext
    80 end;
    88 end;
    81 
    89 
    82 function GetRandom(m: LongWord): LongWord;
    90 function GetRandom(m: LongWord): LongWord; inline;
    83 begin
    91 begin
    84 GetNext;
    92 GetNext;
    85 GetRandom:= GetNext mod m
    93 GetRandom:= GetNext mod m
    86 end;
    94 end;
    87 
    95