| 1 | package net.minecraft.util.valueproviders;
|
| 2 |
|
| 3 | import com.mojang.serialization.Codec;
|
| 4 | import com.mojang.serialization.DataResult;
|
| 5 | import com.mojang.serialization.MapCodec;
|
| 6 | import com.mojang.serialization.codecs.RecordCodecBuilder;
|
| 7 | import net.minecraft.util.Mth;
|
| 8 | import net.minecraft.util.RandomSource;
|
| 9 |
|
| 10 | public record TrapezoidInt(int minInclusive, int maxInclusive, int plateau) implements IntProvider {
|
| 11 | public static final MapCodec<TrapezoidInt> MAP_CODEC = RecordCodecBuilder.<TrapezoidInt>mapCodec(
|
| 12 | i -> i.group(
|
| 13 | Codec.INT.fieldOf("min").forGetter(TrapezoidInt::minInclusive),
|
| 14 | Codec.INT.fieldOf("max").forGetter(TrapezoidInt::maxInclusive),
|
| 15 | Codec.INT.fieldOf("plateau").forGetter(TrapezoidInt::plateau)
|
| 16 | )
|
| 17 | .apply(i, TrapezoidInt::new)
|
| 18 | )
|
| 19 | .validate(
|
| 20 | c -> {
|
| 21 | if (c.maxInclusive < c.minInclusive) {
|
| 22 | return DataResult.error(() -> "Max must be larger than min: [" + c.minInclusive + ", " + c.maxInclusive + "]");
|
| 23 | } else {
|
| 24 | return c.plateau > c.maxInclusive - c.minInclusive
|
| 25 | ? DataResult.error(() -> "Plateau can at most be the full span: [" + c.minInclusive + ", " + c.maxInclusive + "]")
|
| 26 | : DataResult.success(c);
|
| 27 | }
|
| 28 | }
|
| 29 | );
|
| 30 |
|
| 31 | public static TrapezoidInt of(final int min, final int max, final int plateau) {
|
| 32 | return new TrapezoidInt(min, max, plateau);
|
| 33 | }
|
| 34 |
|
| 35 | public static IntProvider triangle(final int range) {
|
| 36 | return of(-range, range, 0);
|
| 37 | }
|
| 38 |
|
| 39 | @Override
|
| 40 | public int sample(final RandomSource random) {
|
| 41 | if (this.plateau == 0 && this.maxInclusive == -this.minInclusive) {
|
| 42 | return random.nextInt(this.maxInclusive + 1) - random.nextInt(this.maxInclusive + 1);
|
| 43 | }
|
| 44 |
|
| 45 | int range = this.maxInclusive - this.minInclusive;
|
| 46 | if (this.plateau == range) {
|
| 47 | return Mth.randomBetweenInclusive(random, this.minInclusive, this.maxInclusive);
|
| 48 | }
|
| 49 |
|
| 50 | int plateauStart = (range - this.plateau) / 2;
|
| 51 | int plateauEnd = range - plateauStart;
|
| 52 | return this.minInclusive + Mth.randomBetweenInclusive(random, 0, plateauEnd) + Mth.randomBetweenInclusive(random, 0, plateauStart);
|
| 53 | }
|
| 54 |
|
| 55 | @Override
|
| 56 | public MapCodec<TrapezoidInt> codec() {
|
| 57 | return MAP_CODEC;
|
| 58 | }
|
| 59 |
|
| 60 | @Override
|
| 61 | public String toString() {
|
| 62 | return "trapezoid(" + this.plateau + ") in [" + this.minInclusive + "-" + this.maxInclusive + "]";
|
| 63 | }
|
| 64 | }
|
| 65 |
|