| 1 | package net.minecraft.world.level.levelgen;
|
| 2 |
|
| 3 | import com.google.common.annotations.VisibleForTesting;
|
| 4 | import com.google.common.hash.HashFunction;
|
| 5 | import com.google.common.hash.Hashing;
|
| 6 | import com.google.common.primitives.Longs;
|
| 7 | import java.nio.charset.StandardCharsets;
|
| 8 | import java.util.concurrent.atomic.AtomicLong;
|
| 9 |
|
| 10 | public final class RandomSupport {
|
| 11 | public static final long GOLDEN_RATIO_64 = -7046029254386353131L;
|
| 12 | public static final long SILVER_RATIO_64 = 7640891576956012809L;
|
| 13 | private static final HashFunction MD5_128 = Hashing.md5();
|
| 14 | private static final AtomicLong SEED_UNIQUIFIER = new AtomicLong(8682522807148012L);
|
| 15 |
|
| 16 | @VisibleForTesting
|
| 17 | public static long mixStafford13(long z) {
|
| 18 | z = (z ^ z >>> 30) * -4658895280553007687L;
|
| 19 | z = (z ^ z >>> 27) * -7723592293110705685L;
|
| 20 | return z ^ z >>> 31;
|
| 21 | }
|
| 22 |
|
| 23 | public static RandomSupport.Seed128bit upgradeSeedTo128bitUnmixed(final long legacySeed) {
|
| 24 | long lowBits = legacySeed ^ 7640891576956012809L;
|
| 25 | long highBits = lowBits + -7046029254386353131L;
|
| 26 | return new RandomSupport.Seed128bit(lowBits, highBits);
|
| 27 | }
|
| 28 |
|
| 29 | public static RandomSupport.Seed128bit upgradeSeedTo128bit(final long legacySeed) {
|
| 30 | return upgradeSeedTo128bitUnmixed(legacySeed).mixed();
|
| 31 | }
|
| 32 |
|
| 33 | public static RandomSupport.Seed128bit seedFromHashOf(final String input) {
|
| 34 | byte[] hashCode = MD5_128.hashString(input, StandardCharsets.UTF_8).asBytes();
|
| 35 | long hashLo = Longs.fromBytes(hashCode[0], hashCode[1], hashCode[2], hashCode[3], hashCode[4], hashCode[5], hashCode[6], hashCode[7]);
|
| 36 | long hashHi = Longs.fromBytes(hashCode[8], hashCode[9], hashCode[10], hashCode[11], hashCode[12], hashCode[13], hashCode[14], hashCode[15]);
|
| 37 | return new RandomSupport.Seed128bit(hashLo, hashHi);
|
| 38 | }
|
| 39 |
|
| 40 | public static long generateUniqueSeed() {
|
| 41 | return SEED_UNIQUIFIER.updateAndGet(current -> current * 1181783497276652981L) ^ System.nanoTime();
|
| 42 | }
|
| 43 |
|
| 44 | public record Seed128bit(long seedLo, long seedHi) {
|
| 45 | public RandomSupport.Seed128bit xor(final long lo, final long hi) {
|
| 46 | return new RandomSupport.Seed128bit(this.seedLo ^ lo, this.seedHi ^ hi);
|
| 47 | }
|
| 48 |
|
| 49 | public RandomSupport.Seed128bit xor(final RandomSupport.Seed128bit other) {
|
| 50 | return this.xor(other.seedLo, other.seedHi);
|
| 51 | }
|
| 52 |
|
| 53 | public RandomSupport.Seed128bit mixed() {
|
| 54 | return new RandomSupport.Seed128bit(RandomSupport.mixStafford13(this.seedLo), RandomSupport.mixStafford13(this.seedHi));
|
| 55 | }
|
| 56 | }
|
| 57 | }
|
| 58 |
|