hexyz is tower defense game, and a lua library for dealing with hexagonal grids
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
2.2 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. RANDOM_CALLS_COUNT = 0
  2. -- https://stackoverflow.com/a/32387452/12464892
  3. local function bitwise_and(a, b)
  4. local result = 0
  5. local bit = 1
  6. while a > 0 and b > 0 do
  7. if a % 2 == 1 and b % 2 == 1 then
  8. result = result + bit
  9. end
  10. bit = bit * 2 -- shift left
  11. a = math.floor(a/2) -- shift-right
  12. b = math.floor(b/2)
  13. end
  14. return result
  15. end
  16. -- https://stackoverflow.com/a/20177466/12464892
  17. local A1, A2 = 727595, 798405 -- 5^17=D20*A1+A2
  18. local D20, D40 = 1048576, 1099511627776 -- 2^20, 2^40
  19. local X1, X2 = 0, 1
  20. local function rand()
  21. local U = X2*A2
  22. local V = (X1*A2 + X2*A1) % D20
  23. V = (V*D20 + U) % D40
  24. X1 = math.floor(V/D20)
  25. X2 = V - X1*D20
  26. return V/D40
  27. end
  28. local SEED_BOUNDS = 2^20 - 1
  29. local function randomseed2(seed)
  30. -- 0 <= X1 <= 2^20-1, 1 <= X2 <= 2^20-1 (must be odd!)
  31. -- ensure the number is odd, and within bounds of the generator
  32. local seed = bitwise_and(seed, 1)
  33. local v = math.clamp(math.abs(seed), 0, SEED_BOUNDS)
  34. X1 = v
  35. X2 = v + 1
  36. end
  37. local R = math.random
  38. local RS = math.randomseed
  39. local function random(n, m)
  40. RANDOM_CALLS_COUNT = RANDOM_CALLS_COUNT + 1
  41. local r
  42. if n then
  43. if m then
  44. r = R(n, m)
  45. else
  46. r = R(n)
  47. end
  48. else
  49. r = R()
  50. end
  51. return r
  52. end
  53. math.randomseed = function(seed)
  54. RANDOM_CALLS_COUNT = 0
  55. R = am.rand(seed)
  56. math.random = random
  57. end
  58. -- whenever we refer to math.random, actually use the function 'random' above
  59. math.random = random
  60. function g_octave_noise(x, y, num_octaves, seed)
  61. local seed = seed or os.time()
  62. local noise = 0
  63. for oct = 1, num_octaves do
  64. local f = 1/4^oct
  65. local l = 2^oct
  66. local pos = vec2(x + seed, y + seed)
  67. noise = noise + f * math.simplex(pos * l)
  68. end
  69. return noise
  70. end
  71. -- @TODO test, fix
  72. function poisson_knuth(lambda)
  73. local e = 2.71828
  74. local L = e^-lambda
  75. local k = 0
  76. local p = 1
  77. while p > L do
  78. k = k + 1
  79. p = p * math.random()
  80. end
  81. return k - 1
  82. end
  83. -- seed the random number generator with the current time
  84. -- os.clock() is better if the program has been running for a little bit.
  85. math.randomseed(os.time())