reformat all code

This commit is contained in:
dfsek
2022-07-06 19:28:07 -07:00
parent dc5e71e3de
commit b3a8f375bc
111 changed files with 706 additions and 653 deletions

View File

@@ -72,15 +72,19 @@
- [ ] Bug Fix <!-- Anything which fixes an issue in Terra. --> - [ ] Bug Fix <!-- Anything which fixes an issue in Terra. -->
- [ ] Build system <!-- Anything which pretain to the build system. --> - [ ] Build system <!-- Anything which pretain to the build system. -->
- [ ] Documentation <!-- Anything which adds or improves documentation for existing features. --> - [ ]
Documentation <!-- Anything which adds or improves documentation for existing features. -->
- [ ] New Feature <!-- Anything which adds new functionality to Terra. --> - [ ] New Feature <!-- Anything which adds new functionality to Terra. -->
- [ ] Performance <!-- Anything which is imrpoves the performance of Terra. --> - [ ] Performance <!-- Anything which is imrpoves the performance of Terra. -->
- [ ] Refactoring <!-- Anything which does not add any new code, only moves code around. --> - [ ]
- [ ] Repository <!-- Anything which affects the repository. Eg. changes to the `README.md` file. --> Refactoring <!-- Anything which does not add any new code, only moves code around. -->
- [ ]
Repository <!-- Anything which affects the repository. Eg. changes to the `README.md` file. -->
- [ ] Revert <!-- Anything which reverts previous commits. --> - [ ] Revert <!-- Anything which reverts previous commits. -->
- [ ] Style <!-- Anything which updates style. --> - [ ] Style <!-- Anything which updates style. -->
- [ ] Tests <!-- Anything which adds or updates tests. --> - [ ] Tests <!-- Anything which adds or updates tests. -->
- [ ] Translation <!-- Anything which is internationalizing the Terra program to other languages. --> - [ ]
Translation <!-- Anything which is internationalizing the Terra program to other languages. -->
#### Compatiblity #### Compatiblity

View File

@@ -63,7 +63,8 @@ to [Terra global moderation team](CODE_OF_CONDUCT.md#Reporting).
## I don't want to read this whole thing I just have a question!!! ## I don't want to read this whole thing I just have a question!!!
> **Note:** Please don't file an issue to ask a question. You'll get faster results by using the resources below. > **Note:** Please don't file an issue to ask a question. You'll get faster
> results by using the resources below.
We have an official discord server where you can request help from various users We have an official discord server where you can request help from various users
@@ -103,7 +104,9 @@ you don't need to create one. When you are creating a bug report,
please [include as many details as possible](#how-do-i-submit-a-good-bug-report) please [include as many details as possible](#how-do-i-submit-a-good-bug-report)
. .
> **Note:** If you find a **Closed** issue that seems like it is the same thing that you're experiencing, open a new issue and include a link to the original issue in the body of your new one. > **Note:** If you find a **Closed** issue that seems like it is the same thing
> that you're experiencing, open a new issue and include a link to the original
> issue in the body of your new one.
#### Before Submitting A Bug Report #### Before Submitting A Bug Report

View File

@@ -39,10 +39,10 @@ fun Project.configureDependencies() {
maven("https://papermc.io/repo/repository/maven-public/") { maven("https://papermc.io/repo/repository/maven-public/") {
name = "PaperMC" name = "PaperMC"
} }
maven ( "https://files.minecraftforge.net/maven/" ) { maven("https://files.minecraftforge.net/maven/") {
name = "Forge" name = "Forge"
} }
maven ("https://maven.quiltmc.org/repository/release/") { maven("https://maven.quiltmc.org/repository/release/") {
name = "Quilt" name = "Quilt"
} }
maven("https://jitpack.io") { maven("https://jitpack.io") {

View File

@@ -10,6 +10,14 @@ import com.dfsek.terra.api.world.biome.Biome;
* Basically just a specialised implementation of {@link Optional} for biomes where a biome may be a "self" reference. * Basically just a specialised implementation of {@link Optional} for biomes where a biome may be a "self" reference.
*/ */
public sealed interface ReplaceableBiome permits PresentBiome, SelfBiome { public sealed interface ReplaceableBiome permits PresentBiome, SelfBiome {
static ReplaceableBiome of(Biome biome) {
return new PresentBiome(biome);
}
static ReplaceableBiome self() {
return SelfBiome.INSTANCE;
}
Biome get(Biome existing); Biome get(Biome existing);
default Biome get() { default Biome get() {
@@ -20,12 +28,4 @@ public sealed interface ReplaceableBiome permits PresentBiome, SelfBiome {
} }
boolean isSelf(); boolean isSelf();
static ReplaceableBiome of(Biome biome) {
return new PresentBiome(biome);
}
static ReplaceableBiome self() {
return SelfBiome.INSTANCE;
}
} }

View File

@@ -16,14 +16,12 @@ import com.dfsek.terra.api.world.biome.Biome;
public class BiomeQueryAPIAddon implements AddonInitializer { public class BiomeQueryAPIAddon implements AddonInitializer {
public static PropertyKey<BiomeTagHolder> BIOME_TAG_KEY = Context.create(BiomeTagHolder.class);
@Inject @Inject
private Platform platform; private Platform platform;
@Inject @Inject
private BaseAddon addon; private BaseAddon addon;
public static PropertyKey<BiomeTagHolder> BIOME_TAG_KEY = Context.create(BiomeTagHolder.class);
@Override @Override
public void initialize() { public void initialize() {

View File

@@ -7,8 +7,8 @@ import com.dfsek.terra.api.world.biome.Biome;
public class SingleTagQuery implements Predicate<Biome> { public class SingleTagQuery implements Predicate<Biome> {
private int tagIndex = -1;
private final String tag; private final String tag;
private int tagIndex = -1;
public SingleTagQuery(String tag) { public SingleTagQuery(String tag) {
this.tag = tag; this.tag = tag;

View File

@@ -62,8 +62,10 @@ public class NoiseChunkGenerator3DAddon implements AddonInitializer {
.register(addon, ConfigurationLoadEvent.class) .register(addon, ConfigurationLoadEvent.class)
.then(event -> { .then(event -> {
if(event.is(Biome.class)) { if(event.is(Biome.class)) {
event.getLoadedObject(Biome.class).getContext().put(paletteInfoPropertyKey, event.load(new BiomePaletteTemplate(platform)).get()); event.getLoadedObject(Biome.class).getContext().put(paletteInfoPropertyKey,
event.getLoadedObject(Biome.class).getContext().put(noisePropertiesPropertyKey, event.load(new BiomeNoiseConfigTemplate()).get()); event.load(new BiomePaletteTemplate(platform)).get());
event.getLoadedObject(Biome.class).getContext().put(noisePropertiesPropertyKey,
event.load(new BiomeNoiseConfigTemplate()).get());
} }
}) })
.failThrough(); .failThrough();

View File

@@ -83,6 +83,7 @@ public class BiomePaletteTemplate implements ObjectTemplate<PaletteInfo> {
slantLayers.put(threshold, layer.getPalette()); slantLayers.put(threshold, layer.getPalette());
} }
return new PaletteInfo(builder.build(), SlantHolder.of(slantLayers, minThreshold), oceanPalette, seaLevel, slantDepth, updatePalette); return new PaletteInfo(builder.build(), SlantHolder.of(slantLayers, minThreshold), oceanPalette, seaLevel, slantDepth,
updatePalette);
} }
} }

View File

@@ -25,6 +25,7 @@ public class LazilyEvaluatedInterpolator {
private final int min, max; private final int min, max;
private final int zMul, yMul; private final int zMul, yMul;
public LazilyEvaluatedInterpolator(BiomeProvider biomeProvider, int cx, int cz, int max, public LazilyEvaluatedInterpolator(BiomeProvider biomeProvider, int cx, int cz, int max,
PropertyKey<BiomeNoiseProperties> noisePropertiesKey, int min, int horizontalRes, int verticalRes, PropertyKey<BiomeNoiseProperties> noisePropertiesKey, int min, int horizontalRes, int verticalRes,
long seed) { long seed) {

View File

@@ -23,6 +23,19 @@ public class SamplerLocator implements Locator {
this.samplers = samplers; this.samplers = samplers;
} }
private static int floorToInt(double value) {
int valueInt = (int) value;
if(value < 0.0) {
if(value == (double) valueInt) {
return valueInt;
} else {
return valueInt == Integer.MIN_VALUE ? valueInt : valueInt - 1;
}
} else {
return valueInt;
}
}
@Override @Override
public BinaryColumn getSuitableCoordinates(Column<?> column) { public BinaryColumn getSuitableCoordinates(Column<?> column) {
BinaryColumnBuilder results = column.newBinaryColumn(); BinaryColumnBuilder results = column.newBinaryColumn();
@@ -36,17 +49,4 @@ public class SamplerLocator implements Locator {
return results.build(); return results.build();
} }
private static int floorToInt(double value) {
int valueInt = (int)value;
if (value < 0.0) {
if (value == (double)valueInt) {
return valueInt;
} else {
return valueInt == Integer.MIN_VALUE ? valueInt : valueInt - 1;
}
} else {
return valueInt;
}
}
} }

View File

@@ -23,11 +23,10 @@ import com.dfsek.terra.addons.noise.config.templates.FunctionTemplate;
public class UserDefinedFunction implements DynamicFunction { public class UserDefinedFunction implements DynamicFunction {
private static final Map<FunctionTemplate, UserDefinedFunction> CACHE = new HashMap<>();
private final Expression expression; private final Expression expression;
private final int args; private final int args;
private static final Map<FunctionTemplate, UserDefinedFunction> CACHE = new HashMap<>();
protected UserDefinedFunction(Expression expression, int args) { protected UserDefinedFunction(Expression expression, int args) {
this.expression = expression; this.expression = expression;
this.args = args; this.args = args;

View File

@@ -46,9 +46,8 @@ public class Scope {
} }
public static final class ScopeBuilder { public static final class ScopeBuilder {
private int numSize, boolSize, strSize = 0;
private final Map<String, Pair<Integer, ReturnType>> indices; private final Map<String, Pair<Integer, ReturnType>> indices;
private int numSize, boolSize, strSize = 0;
private ScopeBuilder parent; private ScopeBuilder parent;
public ScopeBuilder() { public ScopeBuilder() {
@@ -77,6 +76,7 @@ public class Scope {
} }
return id; return id;
} }
public int num(String id) { public int num(String id) {
int num = numSize; int num = numSize;
indices.put(check(id), Pair.of(num, ReturnType.NUMBER)); indices.put(check(id), Pair.of(num, ReturnType.NUMBER));

View File

@@ -14,6 +14,7 @@ import com.dfsek.terra.addons.terrascript.tokenizer.Position;
public class BooleanConstant extends ConstantExpression<Boolean> { public class BooleanConstant extends ConstantExpression<Boolean> {
private final boolean constant; private final boolean constant;
public BooleanConstant(Boolean constant, Position position) { public BooleanConstant(Boolean constant, Position position) {
super(constant, position); super(constant, position);
this.constant = constant; this.constant = constant;

View File

@@ -15,6 +15,7 @@ import com.dfsek.terra.addons.terrascript.tokenizer.Position;
public class NumericConstant extends ConstantExpression<Number> { public class NumericConstant extends ConstantExpression<Number> {
private final double constant; private final double constant;
public NumericConstant(Number constant, Position position) { public NumericConstant(Number constant, Position position) {
super(constant, position); super(constant, position);
this.constant = constant.doubleValue(); this.constant = constant.doubleValue();

View File

@@ -14,16 +14,6 @@ import com.dfsek.terra.addons.terrascript.tokenizer.Position;
public interface Function<T> extends Returnable<T> { public interface Function<T> extends Returnable<T> {
@Override
default double applyDouble(ImplementationArguments implementationArguments, Scope scope) {
return ((Number) apply(implementationArguments, scope)).doubleValue();
}
@Override
default boolean applyBoolean(ImplementationArguments implementationArguments, Scope scope) {
return (Boolean) apply(implementationArguments, scope);
}
Function<?> NULL = new Function<>() { Function<?> NULL = new Function<>() {
@Override @Override
public ReturnType returnType() { public ReturnType returnType() {
@@ -40,4 +30,14 @@ public interface Function<T> extends Returnable<T> {
return null; return null;
} }
}; };
@Override
default double applyDouble(ImplementationArguments implementationArguments, Scope scope) {
return ((Number) apply(implementationArguments, scope)).doubleValue();
}
@Override
default boolean applyBoolean(ImplementationArguments implementationArguments, Scope scope) {
return (Boolean) apply(implementationArguments, scope);
}
} }

View File

@@ -27,6 +27,7 @@ public class BooleanOrOperation extends BinaryOperation<Boolean, Boolean> {
public boolean applyBoolean(ImplementationArguments implementationArguments, Scope scope) { public boolean applyBoolean(ImplementationArguments implementationArguments, Scope scope) {
return left.applyBoolean(implementationArguments, scope) || right.applyBoolean(implementationArguments, scope); return left.applyBoolean(implementationArguments, scope) || right.applyBoolean(implementationArguments, scope);
} }
@Override @Override
public ReturnType returnType() { public ReturnType returnType() {
return ReturnType.BOOLEAN; return ReturnType.BOOLEAN;

View File

@@ -18,16 +18,6 @@ public class ConcatenationOperation extends BinaryOperation<Object, Object> {
super(left, right, position); super(left, right, position);
} }
@Override
public Returnable.ReturnType returnType() {
return Returnable.ReturnType.STRING;
}
@Override
public Object apply(ImplementationArguments implementationArguments, Scope scope) {
return toString(left.apply(implementationArguments, scope)) + toString(right.apply(implementationArguments, scope));
}
private static String toString(Object object) { private static String toString(Object object) {
String s = object.toString(); String s = object.toString();
if(object instanceof Double) { if(object instanceof Double) {
@@ -38,4 +28,14 @@ public class ConcatenationOperation extends BinaryOperation<Object, Object> {
} }
return s; return s;
} }
@Override
public Returnable.ReturnType returnType() {
return Returnable.ReturnType.STRING;
}
@Override
public Object apply(ImplementationArguments implementationArguments, Scope scope) {
return toString(left.apply(implementationArguments, scope)) + toString(right.apply(implementationArguments, scope));
}
} }

View File

@@ -27,6 +27,7 @@ public class ModuloOperation extends BinaryOperation<Number, Number> {
public double applyDouble(ImplementationArguments implementationArguments, Scope scope) { public double applyDouble(ImplementationArguments implementationArguments, Scope scope) {
return left.applyDouble(implementationArguments, scope) % right.applyDouble(implementationArguments, scope); return left.applyDouble(implementationArguments, scope) % right.applyDouble(implementationArguments, scope);
} }
@Override @Override
public ReturnType returnType() { public ReturnType returnType() {
return ReturnType.NUMBER; return ReturnType.NUMBER;

View File

@@ -27,6 +27,7 @@ public class MultiplicationOperation extends BinaryOperation<Number, Number> {
public double applyDouble(ImplementationArguments implementationArguments, Scope scope) { public double applyDouble(ImplementationArguments implementationArguments, Scope scope) {
return left.applyDouble(implementationArguments, scope) * right.applyDouble(implementationArguments, scope); return left.applyDouble(implementationArguments, scope) * right.applyDouble(implementationArguments, scope);
} }
@Override @Override
public ReturnType returnType() { public ReturnType returnType() {
return ReturnType.NUMBER; return ReturnType.NUMBER;

View File

@@ -27,6 +27,7 @@ public class NumberAdditionOperation extends BinaryOperation<Number, Number> {
public double applyDouble(ImplementationArguments implementationArguments, Scope scope) { public double applyDouble(ImplementationArguments implementationArguments, Scope scope) {
return left.applyDouble(implementationArguments, scope) + right.applyDouble(implementationArguments, scope); return left.applyDouble(implementationArguments, scope) + right.applyDouble(implementationArguments, scope);
} }
@Override @Override
public ReturnType returnType() { public ReturnType returnType() {
return ReturnType.NUMBER; return ReturnType.NUMBER;

View File

@@ -27,6 +27,7 @@ public class SubtractionOperation extends BinaryOperation<Number, Number> {
public double applyDouble(ImplementationArguments implementationArguments, Scope scope) { public double applyDouble(ImplementationArguments implementationArguments, Scope scope) {
return left.applyDouble(implementationArguments, scope) - right.applyDouble(implementationArguments, scope); return left.applyDouble(implementationArguments, scope) - right.applyDouble(implementationArguments, scope);
} }
@Override @Override
public ReturnType returnType() { public ReturnType returnType() {
return ReturnType.NUMBER; return ReturnType.NUMBER;

View File

@@ -29,6 +29,7 @@ public class LessThanOrEqualsStatement extends BinaryOperation<Number, Boolean>
public boolean applyBoolean(ImplementationArguments implementationArguments, Scope scope) { public boolean applyBoolean(ImplementationArguments implementationArguments, Scope scope) {
return left.applyDouble(implementationArguments, scope) <= right.applyDouble(implementationArguments, scope); return left.applyDouble(implementationArguments, scope) <= right.applyDouble(implementationArguments, scope);
} }
@Override @Override
public Returnable.ReturnType returnType() { public Returnable.ReturnType returnType() {
return Returnable.ReturnType.BOOLEAN; return Returnable.ReturnType.BOOLEAN;

View File

@@ -29,6 +29,7 @@ public class LessThanStatement extends BinaryOperation<Number, Boolean> {
public boolean applyBoolean(ImplementationArguments implementationArguments, Scope scope) { public boolean applyBoolean(ImplementationArguments implementationArguments, Scope scope) {
return left.applyDouble(implementationArguments, scope) < right.applyDouble(implementationArguments, scope); return left.applyDouble(implementationArguments, scope) < right.applyDouble(implementationArguments, scope);
} }
@Override @Override
public Returnable.ReturnType returnType() { public Returnable.ReturnType returnType() {
return Returnable.ReturnType.BOOLEAN; return Returnable.ReturnType.BOOLEAN;

View File

@@ -14,9 +14,8 @@ import com.dfsek.terra.addons.terrascript.tokenizer.Position;
public abstract class VariableAssignmentNode<T> implements Item<T> { public abstract class VariableAssignmentNode<T> implements Item<T> {
protected final Returnable<T> value; protected final Returnable<T> value;
private final Position position;
protected final int index; protected final int index;
private final Position position;
public VariableAssignmentNode(Returnable<T> value, Position position, int index) { public VariableAssignmentNode(Returnable<T> value, Position position, int index) {

View File

@@ -12,9 +12,9 @@ import com.dfsek.terra.addons.terrascript.tokenizer.Position;
public abstract class VariableReferenceNode<T> implements Returnable<T> { public abstract class VariableReferenceNode<T> implements Returnable<T> {
protected final int index;
private final Position position; private final Position position;
private final ReturnType type; private final ReturnType type;
protected final int index;
public VariableReferenceNode(Position position, ReturnType type, int index) { public VariableReferenceNode(Position position, ReturnType type, int index) {
this.position = position; this.position = position;

View File

@@ -30,7 +30,8 @@ import com.dfsek.terra.addons.terrascript.tokenizer.Position;
public class ParserTest { public class ParserTest {
@Test @Test
public void parse() throws IOException, ParseException { public void parse() throws IOException, ParseException {
Parser parser = new Parser(IOUtils.toString(Objects.requireNonNull(getClass().getResourceAsStream("/test.tesf")), Charset.defaultCharset())); Parser parser = new Parser(
IOUtils.toString(Objects.requireNonNull(getClass().getResourceAsStream("/test.tesf")), Charset.defaultCharset()));
parser.registerFunction("test", new FunctionBuilder<Test1>() { parser.registerFunction("test", new FunctionBuilder<Test1>() {
@Override @Override

View File

@@ -14,10 +14,15 @@ import java.util.concurrent.atomic.AtomicReference;
public class Context { public class Context {
private final Map<Class<? extends Properties>, Properties> map = new HashMap<>();
private final AtomicReference<Properties[]> list = new AtomicReference<>(new Properties[size.get()]);
private static final AtomicInteger size = new AtomicInteger(0); private static final AtomicInteger size = new AtomicInteger(0);
private static final Map<Class<? extends Properties>, PropertyKey<?>> properties = new HashMap<>(); private static final Map<Class<? extends Properties>, PropertyKey<?>> properties = new HashMap<>();
private final Map<Class<? extends Properties>, Properties> map = new HashMap<>();
private final AtomicReference<Properties[]> list = new AtomicReference<>(new Properties[size.get()]);
@SuppressWarnings("unchecked")
public static <T extends Properties> PropertyKey<T> create(Class<T> clazz) {
return (PropertyKey<T>) properties.computeIfAbsent(clazz, c -> new PropertyKey<>(size.getAndIncrement(), clazz));
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T extends Properties> T get(Class<T> clazz) { public <T extends Properties> T get(Class<T> clazz) {
@@ -33,11 +38,6 @@ public class Context {
return this; return this;
} }
@SuppressWarnings("unchecked")
public static <T extends Properties> PropertyKey<T> create(Class<T> clazz) {
return (PropertyKey<T>) properties.computeIfAbsent(clazz, c -> new PropertyKey<>(size.getAndIncrement(), clazz));
}
public <T extends Properties> Context put(PropertyKey<T> key, T properties) { public <T extends Properties> Context put(PropertyKey<T> key, T properties) {
list.updateAndGet(p -> { list.updateAndGet(p -> {
if(p.length == size.get()) return p; if(p.length == size.get()) return p;

View File

@@ -22,6 +22,11 @@ public final class Pair<L, R> {
private final L left; private final L left;
private final R right; private final R right;
private Pair(L left, R right) {
this.left = left;
this.right = right;
}
public static <L, R, T> Function<Pair<L, R>, Pair<T, R>> mapLeft(Function<L, T> function) { public static <L, R, T> Function<Pair<L, R>, Pair<T, R>> mapLeft(Function<L, T> function) {
return pair -> of(function.apply(pair.left), pair.right); return pair -> of(function.apply(pair.left), pair.right);
} }
@@ -54,11 +59,6 @@ public final class Pair<L, R> {
return pair -> pair.left; return pair -> pair.left;
} }
private Pair(L left, R right) {
this.left = left;
this.right = right;
}
@Contract("_, _ -> new") @Contract("_, _ -> new")
public static <L1, R1> Pair<L1, R1> of(L1 left, R1 right) { public static <L1, R1> Pair<L1, R1> of(L1 left, R1 right) {
return new Pair<>(left, right); return new Pair<>(left, right);
@@ -96,6 +96,17 @@ public final class Pair<L, R> {
return Objects.equals(this.left, that.left) && Objects.equals(this.right, that.right); return Objects.equals(this.left, that.left) && Objects.equals(this.right, that.right);
} }
public Pair<L, R> apply(BiConsumer<L, R> consumer) {
consumer.accept(this.left, this.right);
return this;
}
@Override
public String toString() {
return String.format("{%s,%s}", left, right);
}
public static class Mutable<L, R> { public static class Mutable<L, R> {
private L left; private L left;
private R right; private R right;
@@ -144,14 +155,4 @@ public final class Pair<L, R> {
return Objects.equals(this.left, that.left) && Objects.equals(this.right, that.right); return Objects.equals(this.left, that.left) && Objects.equals(this.right, that.right);
} }
} }
public Pair<L, R> apply(BiConsumer<L, R> consumer) {
consumer.accept(this.left, this.right);
return this;
}
@Override
public String toString() {
return String.format("{%s,%s}", left, right);
}
} }

View File

@@ -80,6 +80,8 @@ public class CachingBiomeProvider implements BiomeProvider, Handle {
return 31 * code + ((int) (seed ^ (seed >>> 32))); return 31 * code + ((int) (seed ^ (seed >>> 32)));
} }
} }
private record SeededVector2(int x, int z, long seed) { private record SeededVector2(int x, int z, long seed) {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {

View File

@@ -231,7 +231,8 @@ public class ConfigPackImpl implements ConfigPack {
ConfigPackPostTemplate packPostTemplate = new ConfigPackPostTemplate(); ConfigPackPostTemplate packPostTemplate = new ConfigPackPostTemplate();
selfLoader.load(packPostTemplate, packManifest); selfLoader.load(packPostTemplate, packManifest);
seededBiomeProvider = template.getBiomeCache() ? packPostTemplate.getProviderBuilder().caching() : packPostTemplate.getProviderBuilder(); seededBiomeProvider =
template.getBiomeCache() ? packPostTemplate.getProviderBuilder().caching() : packPostTemplate.getProviderBuilder();
checkDeadEntries(); checkDeadEntries();
} }

View File

@@ -96,6 +96,7 @@ public class BootstrapAddonLoader implements BootstrapBaseAddon<BootstrapBaseAdd
throw new UncheckedIOException(e); throw new UncheckedIOException(e);
} }
} }
@Override @Override
public String getID() { public String getID() {
return "BOOTSTRAP"; return "BOOTSTRAP";

View File

@@ -4,7 +4,6 @@ terra.source=https://github.com/PolyhedralDev/Terra
terra.issues=https://github.com/PolyhedralDev/Terra/issues terra.issues=https://github.com/PolyhedralDev/Terra/issues
terra.wiki=https://github.com/PolyhedralDev/Terra/wiki terra.wiki=https://github.com/PolyhedralDev/Terra/wiki
terra.license=MIT terra.license=MIT
# Gradle options # Gradle options
org.gradle.jvmargs=-Xmx4096M -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC org.gradle.jvmargs=-Xmx4096M -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC
org.gradle.vfs.watch=true org.gradle.vfs.watch=true

View File

@@ -46,22 +46,6 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener
private ChunkGenerator delegate; private ChunkGenerator delegate;
private ConfigPack pack; private ConfigPack pack;
private record SeededVector(int x, int z, WorldProperties worldProperties) {
@Override
public boolean equals(Object obj) {
if(obj instanceof SeededVector that) {
return this.z == that.z && this.x == that.x && this.worldProperties.equals(that.worldProperties);
}
return false;
}
@Override
public int hashCode() {
int code = x;
code = 31 * code + z;
return 31 * code + worldProperties.hashCode();
}
}
public BukkitChunkGeneratorWrapper(ChunkGenerator delegate, ConfigPack pack, BlockState air) { public BukkitChunkGeneratorWrapper(ChunkGenerator delegate, ConfigPack pack, BlockState air) {
this.delegate = delegate; this.delegate = delegate;
@@ -109,7 +93,6 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener
return true; return true;
} }
@Override @Override
public boolean shouldGenerateMobs() { public boolean shouldGenerateMobs() {
return true; return true;
@@ -133,4 +116,22 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener
public ChunkGenerator getHandle() { public ChunkGenerator getHandle() {
return delegate; return delegate;
} }
private record SeededVector(int x, int z, WorldProperties worldProperties) {
@Override
public boolean equals(Object obj) {
if(obj instanceof SeededVector that) {
return this.z == that.z && this.x == that.x && this.worldProperties.equals(that.worldProperties);
}
return false;
}
@Override
public int hashCode() {
int code = x;
code = 31 * code + z;
return 31 * code + worldProperties.hashCode();
}
}
} }

View File

@@ -11,8 +11,6 @@ public interface Initializer {
String NMS = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; String NMS = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3];
String TERRA_PACKAGE = Initializer.class.getPackageName(); String TERRA_PACKAGE = Initializer.class.getPackageName();
void initialize(PlatformImpl plugin);
static void init(PlatformImpl platform) { static void init(PlatformImpl platform) {
Logger logger = LoggerFactory.getLogger(Initializer.class); Logger logger = LoggerFactory.getLogger(Initializer.class);
try { try {
@@ -37,4 +35,6 @@ public interface Initializer {
logger.error("This is usually due to running Terra on an unsupported Minecraft version."); logger.error("This is usually due to running Terra on an unsupported Minecraft version.");
} }
} }
void initialize(PlatformImpl plugin);
} }

View File

@@ -17,8 +17,6 @@
package com.dfsek.terra.bukkit.world.inventory.meta; package com.dfsek.terra.bukkit.world.inventory.meta;
import org.bukkit.inventory.meta.ItemMeta;
import com.dfsek.terra.api.inventory.item.Damageable; import com.dfsek.terra.api.inventory.item.Damageable;
import com.dfsek.terra.bukkit.world.inventory.BukkitItemMeta; import com.dfsek.terra.bukkit.world.inventory.BukkitItemMeta;

View File

@@ -1,8 +1,5 @@
package com.dfsek.terra.bukkit.nms.v1_18_R2; package com.dfsek.terra.bukkit.nms.v1_18_R2;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.registry.master.ConfigRegistry;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.mojang.serialization.Lifecycle; import com.mojang.serialization.Lifecycle;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
@@ -23,6 +20,9 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.registry.master.ConfigRegistry;
public class AwfulBukkitHacks { public class AwfulBukkitHacks {
private static final Logger LOGGER = LoggerFactory.getLogger(NMSBiomeInjector.class); private static final Logger LOGGER = LoggerFactory.getLogger(NMSBiomeInjector.class);
@@ -46,7 +46,9 @@ public class AwfulBukkitHacks {
biomeRegistry.get(vanillaMinecraftKey) // get biomeRegistry.get(vanillaMinecraftKey) // get
); );
ResourceKey<Biome> delegateKey = ResourceKey.create(Registry.BIOME_REGISTRY, new ResourceLocation("terra", NMSBiomeInjector.createBiomeID(pack, key))); ResourceKey<Biome> delegateKey = ResourceKey.create(Registry.BIOME_REGISTRY, new ResourceLocation("terra",
NMSBiomeInjector.createBiomeID(
pack, key)));
BuiltinRegistries.register(BuiltinRegistries.BIOME, delegateKey, platform); BuiltinRegistries.register(BuiltinRegistries.BIOME, delegateKey, platform);
biomeRegistry.register(delegateKey, platform, Lifecycle.stable()); biomeRegistry.register(delegateKey, platform, Lifecycle.stable());
@@ -78,16 +80,23 @@ public class AwfulBukkitHacks {
.forEach(tb -> NMSBiomeInjector.getEntry(biomeRegistry, tb) .forEach(tb -> NMSBiomeInjector.getEntry(biomeRegistry, tb)
.ifPresentOrElse( .ifPresentOrElse(
terra -> { terra -> {
LOGGER.debug(vanilla.unwrapKey().orElseThrow().location() + LOGGER.debug(
vanilla.unwrapKey()
.orElseThrow()
.location() +
" (vanilla for " + " (vanilla for " +
terra.unwrapKey().orElseThrow().location() + terra.unwrapKey()
.orElseThrow()
.location() +
": " + ": " +
vanilla.tags().toList()); vanilla.tags()
.toList());
vanilla.tags() vanilla.tags()
.forEach( .forEach(
tag -> collect tag -> collect
.computeIfAbsent(tag, .computeIfAbsent(
tag,
t -> new ArrayList<>()) t -> new ArrayList<>())
.add(terra)); .add(terra));
}, },

View File

@@ -1,33 +1,17 @@
package com.dfsek.terra.bukkit.nms.v1_18_R2; package com.dfsek.terra.bukkit.nms.v1_18_R2;
import com.google.common.collect.ImmutableMap;
import com.mojang.serialization.Lifecycle;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.core.WritableRegistry;
import net.minecraft.data.BuiltinRegistries;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeSpecialEffects; import net.minecraft.world.level.biome.BiomeSpecialEffects;
import org.bukkit.NamespacedKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.bukkit.config.VanillaBiomeProperties; import com.dfsek.terra.bukkit.config.VanillaBiomeProperties;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.registry.master.ConfigRegistry;
public class NMSBiomeInjector { public class NMSBiomeInjector {
@@ -51,7 +35,6 @@ public class NMSBiomeInjector {
.downfall(vanilla.getDownfall()); .downfall(vanilla.getDownfall());
BiomeSpecialEffects.Builder effects = new BiomeSpecialEffects.Builder(); BiomeSpecialEffects.Builder effects = new BiomeSpecialEffects.Builder();
effects.grassColorModifier(vanilla.getSpecialEffects().getGrassColorModifier()); effects.grassColorModifier(vanilla.getSpecialEffects().getGrassColorModifier());

View File

@@ -49,17 +49,14 @@ import com.dfsek.terra.api.world.info.WorldProperties;
public class NMSChunkGeneratorDelegate extends ChunkGenerator { public class NMSChunkGeneratorDelegate extends ChunkGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(NMSChunkGeneratorDelegate.class); private static final Logger LOGGER = LoggerFactory.getLogger(NMSChunkGeneratorDelegate.class);
private static final Lazy<List<ChunkPos>> EMPTY = Lazy.lazy(List::of);
private final NMSBiomeProvider biomeSource; private final NMSBiomeProvider biomeSource;
private final com.dfsek.terra.api.world.chunk.generation.ChunkGenerator delegate; private final com.dfsek.terra.api.world.chunk.generation.ChunkGenerator delegate;
private final ChunkGenerator vanilla; private final ChunkGenerator vanilla;
private final ConfigPack pack; private final ConfigPack pack;
private final long seed; private final long seed;
private final Map<ConcentricRingsStructurePlacement, Lazy<List<ChunkPos>>> ringPositions = new Object2ObjectArrayMap<>(); private final Map<ConcentricRingsStructurePlacement, Lazy<List<ChunkPos>>> ringPositions = new Object2ObjectArrayMap<>();
private static final Lazy<List<ChunkPos>> EMPTY = Lazy.lazy(List::of); private volatile boolean rings = false;
public NMSChunkGeneratorDelegate(ChunkGenerator vanilla, ConfigPack pack, NMSBiomeProvider biomeProvider, long seed) { public NMSChunkGeneratorDelegate(ChunkGenerator vanilla, ConfigPack pack, NMSBiomeProvider biomeProvider, long seed) {
super(Registries.structureSet(), Optional.empty(), biomeProvider, biomeProvider, seed); super(Registries.structureSet(), Optional.empty(), biomeProvider, biomeProvider, seed);
@@ -71,13 +68,15 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
} }
@Override @Override
public void applyCarvers(@NotNull WorldGenRegion chunkRegion, long seed, @NotNull BiomeManager biomeAccess, @NotNull StructureFeatureManager structureAccessor, public void applyCarvers(@NotNull WorldGenRegion chunkRegion, long seed, @NotNull BiomeManager biomeAccess,
@NotNull StructureFeatureManager structureAccessor,
@NotNull ChunkAccess chunk, GenerationStep.@NotNull Carving generationStep) { @NotNull ChunkAccess chunk, GenerationStep.@NotNull Carving generationStep) {
// no-op // no-op
} }
@Override @Override
public void applyBiomeDecoration(@NotNull WorldGenLevel world, @NotNull ChunkAccess chunk, @NotNull StructureFeatureManager structureAccessor) { public void applyBiomeDecoration(@NotNull WorldGenLevel world, @NotNull ChunkAccess chunk,
@NotNull StructureFeatureManager structureAccessor) {
vanilla.applyBiomeDecoration(world, chunk, structureAccessor); vanilla.applyBiomeDecoration(world, chunk, structureAccessor);
} }
@@ -87,7 +86,8 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
} }
@Override @Override
public @NotNull CompletableFuture<ChunkAccess> fillFromNoise(@NotNull Executor executor, @NotNull Blender blender, @NotNull StructureFeatureManager structureAccessor, public @NotNull CompletableFuture<ChunkAccess> fillFromNoise(@NotNull Executor executor, @NotNull Blender blender,
@NotNull StructureFeatureManager structureAccessor,
@NotNull ChunkAccess chunk) { @NotNull ChunkAccess chunk) {
return vanilla.fillFromNoise(executor, blender, structureAccessor, chunk); return vanilla.fillFromNoise(executor, blender, structureAccessor, chunk);
} }
@@ -161,8 +161,6 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
return ringPositions.getOrDefault(concentricringsstructureplacement, EMPTY).value(); return ringPositions.getOrDefault(concentricringsstructureplacement, EMPTY).value();
} }
private volatile boolean rings = false;
@Override @Override
public synchronized void ensureStructuresGenerated() { public synchronized void ensureStructuresGenerated() {
if(!this.rings) { if(!this.rings) {

View File

@@ -25,7 +25,8 @@ public class NMSInjectListener implements Listener {
@EventHandler @EventHandler
public void onWorldInit(WorldInitEvent event) { public void onWorldInit(WorldInitEvent event) {
if (!INJECTED.contains(event.getWorld()) && event.getWorld().getGenerator() instanceof BukkitChunkGeneratorWrapper bukkitChunkGeneratorWrapper) { if(!INJECTED.contains(event.getWorld()) &&
event.getWorld().getGenerator() instanceof BukkitChunkGeneratorWrapper bukkitChunkGeneratorWrapper) {
INJECT_LOCK.lock(); INJECT_LOCK.lock();
INJECTED.add(event.getWorld()); INJECTED.add(event.getWorld());
LOGGER.info("Preparing to take over the world: {}", event.getWorld().getName()); LOGGER.info("Preparing to take over the world: {}", event.getWorld().getName());

View File

@@ -15,18 +15,21 @@ public class Reflection {
static { static {
ReflectionRemapper reflectionRemapper = ReflectionRemapper.forReobfMappingsInPaperJar(); ReflectionRemapper reflectionRemapper = ReflectionRemapper.forReobfMappingsInPaperJar();
ReflectionProxyFactory reflectionProxyFactory = ReflectionProxyFactory.create(reflectionRemapper, Reflection.class.getClassLoader()); ReflectionProxyFactory reflectionProxyFactory = ReflectionProxyFactory.create(reflectionRemapper,
Reflection.class.getClassLoader());
MAPPED_REGISTRY = reflectionProxyFactory.reflectionProxy(MappedRegistryProxy.class); MAPPED_REGISTRY = reflectionProxyFactory.reflectionProxy(MappedRegistryProxy.class);
BIOME = reflectionProxyFactory.reflectionProxy(BiomeProxy.class); BIOME = reflectionProxyFactory.reflectionProxy(BiomeProxy.class);
} }
@Proxies(MappedRegistry.class) @Proxies(MappedRegistry.class)
public interface MappedRegistryProxy { public interface MappedRegistryProxy {
@FieldSetter("frozen") @FieldSetter("frozen")
void setFrozen(MappedRegistry<?> instance, boolean frozen); void setFrozen(MappedRegistry<?> instance, boolean frozen);
} }
@Proxies(Biome.class) @Proxies(Biome.class)
public interface BiomeProxy { public interface BiomeProxy {
@FieldGetter("biomeCategory") @FieldGetter("biomeCategory")

View File

@@ -1,7 +1,5 @@
package com.dfsek.terra.bukkit.nms.v1_19_R1; package com.dfsek.terra.bukkit.nms.v1_19_R1;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.registry.master.ConfigRegistry;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.mojang.serialization.Lifecycle; import com.mojang.serialization.Lifecycle;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
@@ -17,7 +15,15 @@ import org.bukkit.NamespacedKey;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.*; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.registry.master.ConfigRegistry;
public class AwfulBukkitHacks { public class AwfulBukkitHacks {
private static final Logger LOGGER = LoggerFactory.getLogger(AwfulBukkitHacks.class); private static final Logger LOGGER = LoggerFactory.getLogger(AwfulBukkitHacks.class);
@@ -42,7 +48,8 @@ public class AwfulBukkitHacks {
); );
ResourceKey<Biome> delegateKey = ResourceKey.create(Registry.BIOME_REGISTRY, ResourceKey<Biome> delegateKey = ResourceKey.create(Registry.BIOME_REGISTRY,
new ResourceLocation("terra", NMSBiomeInjector.createBiomeID(pack, key))); new ResourceLocation("terra",
NMSBiomeInjector.createBiomeID(pack, key)));
BuiltinRegistries.register(BuiltinRegistries.BIOME, delegateKey, platform); BuiltinRegistries.register(BuiltinRegistries.BIOME, delegateKey, platform);
biomeRegistry.register(delegateKey, platform, Lifecycle.stable()); biomeRegistry.register(delegateKey, platform, Lifecycle.stable());
@@ -74,16 +81,23 @@ public class AwfulBukkitHacks {
.forEach(tb -> NMSBiomeInjector.getEntry(biomeRegistry, tb) .forEach(tb -> NMSBiomeInjector.getEntry(biomeRegistry, tb)
.ifPresentOrElse( .ifPresentOrElse(
terra -> { terra -> {
LOGGER.debug(vanilla.unwrapKey().orElseThrow().location() + LOGGER.debug(
vanilla.unwrapKey()
.orElseThrow()
.location() +
" (vanilla for " + " (vanilla for " +
terra.unwrapKey().orElseThrow().location() + terra.unwrapKey()
.orElseThrow()
.location() +
": " + ": " +
vanilla.tags().toList()); vanilla.tags()
.toList());
vanilla.tags() vanilla.tags()
.forEach( .forEach(
tag -> collect tag -> collect
.computeIfAbsent(tag, .computeIfAbsent(
tag,
t -> new ArrayList<>()) t -> new ArrayList<>())
.add(terra)); .add(terra));
}, },

View File

@@ -1,33 +1,17 @@
package com.dfsek.terra.bukkit.nms.v1_19_R1; package com.dfsek.terra.bukkit.nms.v1_19_R1;
import com.google.common.collect.ImmutableMap;
import com.mojang.serialization.Lifecycle;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.core.WritableRegistry;
import net.minecraft.data.BuiltinRegistries;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeSpecialEffects; import net.minecraft.world.level.biome.BiomeSpecialEffects;
import org.bukkit.NamespacedKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.bukkit.config.VanillaBiomeProperties; import com.dfsek.terra.bukkit.config.VanillaBiomeProperties;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.registry.master.ConfigRegistry;
public class NMSBiomeInjector { public class NMSBiomeInjector {

View File

@@ -18,7 +18,11 @@ public class NMSBiomeProvider extends BiomeSource {
private final Registry<Biome> biomeRegistry = Registries.biomeRegistry(); private final Registry<Biome> biomeRegistry = Registries.biomeRegistry();
public NMSBiomeProvider(BiomeProvider delegate, long seed) { public NMSBiomeProvider(BiomeProvider delegate, long seed) {
super(delegate.stream().map(biome -> Registries.biomeRegistry().getHolderOrThrow(((BukkitPlatformBiome) biome.getPlatformBiome()).getContext().get(NMSBiomeInfo.class).biomeKey()))); super(delegate.stream()
.map(biome -> Registries.biomeRegistry()
.getHolderOrThrow(((BukkitPlatformBiome) biome.getPlatformBiome()).getContext()
.get(NMSBiomeInfo.class)
.biomeKey())));
this.delegate = delegate; this.delegate = delegate;
this.seed = seed; this.seed = seed;
} }
@@ -30,6 +34,9 @@ public class NMSBiomeProvider extends BiomeSource {
@Override @Override
public @NotNull Holder<Biome> getNoiseBiome(int x, int y, int z, @NotNull Sampler sampler) { public @NotNull Holder<Biome> getNoiseBiome(int x, int y, int z, @NotNull Sampler sampler) {
return biomeRegistry.getHolderOrThrow(((BukkitPlatformBiome) delegate.getBiome(x << 2, y << 2, z << 2, seed).getPlatformBiome()).getContext().get(NMSBiomeInfo.class).biomeKey()); return biomeRegistry.getHolderOrThrow(((BukkitPlatformBiome) delegate.getBiome(x << 2, y << 2, z << 2, seed)
.getPlatformBiome()).getContext()
.get(NMSBiomeInfo.class)
.biomeKey());
} }
} }

View File

@@ -55,6 +55,8 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
private final ConfigPack pack; private final ConfigPack pack;
private final long seed; private final long seed;
private final Map<ConcentricRingsStructurePlacement, Lazy<List<ChunkPos>>> ringPositions = new Object2ObjectArrayMap<>();
private volatile boolean rings = false;
public NMSChunkGeneratorDelegate(ChunkGenerator vanilla, ConfigPack pack, NMSBiomeProvider biomeProvider, long seed) { public NMSChunkGeneratorDelegate(ChunkGenerator vanilla, ConfigPack pack, NMSBiomeProvider biomeProvider, long seed) {
super(Registries.structureSet(), Optional.empty(), biomeProvider); super(Registries.structureSet(), Optional.empty(), biomeProvider);
@@ -147,9 +149,6 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
} }
private volatile boolean rings = false;
private final Map<ConcentricRingsStructurePlacement, Lazy<List<ChunkPos>>> ringPositions = new Object2ObjectArrayMap<>();
@Override @Override
public void ensureStructuresGenerated(@NotNull RandomState noiseConfig) { public void ensureStructuresGenerated(@NotNull RandomState noiseConfig) {
if(!this.rings) { if(!this.rings) {
@@ -161,7 +160,8 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
} }
@Override @Override
public List<ChunkPos> getRingPositionsFor(@NotNull ConcentricRingsStructurePlacement structurePlacement, @NotNull RandomState noiseConfig) { public List<ChunkPos> getRingPositionsFor(@NotNull ConcentricRingsStructurePlacement structurePlacement,
@NotNull RandomState noiseConfig) {
ensureStructuresGenerated(noiseConfig); ensureStructuresGenerated(noiseConfig);
return ringPositions.get(structurePlacement).value(); return ringPositions.get(structurePlacement).value();
} }
@@ -179,13 +179,15 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
} }
} }
if (match) { if(match) {
if (holder.placement() instanceof ConcentricRingsStructurePlacement concentricringsstructureplacement) { if(holder.placement() instanceof ConcentricRingsStructurePlacement concentricringsstructureplacement) {
this.ringPositions.put(concentricringsstructureplacement, Lazy.lazy(() -> this.generateRingPositions(holder, noiseConfig, concentricringsstructureplacement))); this.ringPositions.put(concentricringsstructureplacement, Lazy.lazy(
() -> this.generateRingPositions(holder, noiseConfig, concentricringsstructureplacement)));
} }
} }
}); });
} }
private List<ChunkPos> generateRingPositions(StructureSet holder, RandomState randomstate, private List<ChunkPos> generateRingPositions(StructureSet holder, RandomState randomstate,
ConcentricRingsStructurePlacement concentricringsstructureplacement) { // Spigot ConcentricRingsStructurePlacement concentricringsstructureplacement) { // Spigot
if(concentricringsstructureplacement.count() == 0) { if(concentricringsstructureplacement.count() == 0) {

View File

@@ -25,7 +25,8 @@ public class NMSInjectListener implements Listener {
@EventHandler @EventHandler
public void onWorldInit(WorldInitEvent event) { public void onWorldInit(WorldInitEvent event) {
if (!INJECTED.contains(event.getWorld()) && event.getWorld().getGenerator() instanceof BukkitChunkGeneratorWrapper bukkitChunkGeneratorWrapper) { if(!INJECTED.contains(event.getWorld()) &&
event.getWorld().getGenerator() instanceof BukkitChunkGeneratorWrapper bukkitChunkGeneratorWrapper) {
INJECT_LOCK.lock(); INJECT_LOCK.lock();
INJECTED.add(event.getWorld()); INJECTED.add(event.getWorld());
LOGGER.info("Preparing to take over the world: {}", event.getWorld().getName()); LOGGER.info("Preparing to take over the world: {}", event.getWorld().getName());

View File

@@ -12,11 +12,13 @@ public class Reflection {
static { static {
ReflectionRemapper reflectionRemapper = ReflectionRemapper.forReobfMappingsInPaperJar(); ReflectionRemapper reflectionRemapper = ReflectionRemapper.forReobfMappingsInPaperJar();
ReflectionProxyFactory reflectionProxyFactory = ReflectionProxyFactory.create(reflectionRemapper, Reflection.class.getClassLoader()); ReflectionProxyFactory reflectionProxyFactory = ReflectionProxyFactory.create(reflectionRemapper,
Reflection.class.getClassLoader());
MAPPED_REGISTRY = reflectionProxyFactory.reflectionProxy(MappedRegistryProxy.class); MAPPED_REGISTRY = reflectionProxyFactory.reflectionProxy(MappedRegistryProxy.class);
} }
@Proxies(MappedRegistry.class) @Proxies(MappedRegistry.class)
public interface MappedRegistryProxy { public interface MappedRegistryProxy {
@FieldSetter("frozen") @FieldSetter("frozen")

View File

@@ -25,7 +25,13 @@ dependencies {
modImplementation("net.fabricmc:fabric-loader:${Versions.Fabric.fabricLoader}") modImplementation("net.fabricmc:fabric-loader:${Versions.Fabric.fabricLoader}")
setOf("fabric-lifecycle-events-v1", "fabric-resource-loader-v0", "fabric-api-base", "fabric-command-api-v2", "fabric-networking-api-v1").forEach { apiModule -> setOf(
"fabric-lifecycle-events-v1",
"fabric-resource-loader-v0",
"fabric-api-base",
"fabric-command-api-v2",
"fabric-networking-api-v1"
).forEach { apiModule ->
val module = fabricApi.module(apiModule, Versions.Fabric.fabricAPI) val module = fabricApi.module(apiModule, Versions.Fabric.fabricAPI)
modImplementation(module) modImplementation(module)
include(module) include(module)

View File

@@ -3,6 +3,7 @@ package com.dfsek.terra.fabric;
import com.dfsek.terra.mod.MinecraftAddon; import com.dfsek.terra.mod.MinecraftAddon;
import com.dfsek.terra.mod.ModPlatform; import com.dfsek.terra.mod.ModPlatform;
public class FabricAddon extends MinecraftAddon { public class FabricAddon extends MinecraftAddon {
public FabricAddon(ModPlatform modPlatform) { public FabricAddon(ModPlatform modPlatform) {

View File

@@ -20,9 +20,6 @@ package com.dfsek.terra.fabric;
import ca.solostudios.strata.Versions; import ca.solostudios.strata.Versions;
import ca.solostudios.strata.parser.tokenizer.ParseException; import ca.solostudios.strata.parser.tokenizer.ParseException;
import ca.solostudios.strata.version.Version; import ca.solostudios.strata.version.Version;
import com.dfsek.terra.lifecycle.LifecyclePlatform;
import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.FabricLoader;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger; import org.slf4j.Logger;
@@ -35,8 +32,7 @@ import java.util.stream.Stream;
import com.dfsek.terra.addon.EphemeralAddon; import com.dfsek.terra.addon.EphemeralAddon;
import com.dfsek.terra.api.addon.BaseAddon; import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.util.generic.Lazy; import com.dfsek.terra.lifecycle.LifecyclePlatform;
import com.dfsek.terra.mod.CommonPlatform;
public class FabricPlatform extends LifecyclePlatform { public class FabricPlatform extends LifecyclePlatform {
@@ -59,6 +55,7 @@ public class FabricPlatform extends LifecyclePlatform {
return Stream.empty(); return Stream.empty();
}).collect(Collectors.toList()); }).collect(Collectors.toList());
} }
@Override @Override
public @NotNull String platformName() { public @NotNull String platformName() {
return "Fabric"; return "Fabric";

View File

@@ -1,32 +1,22 @@
package com.dfsek.terra.forge; package com.dfsek.terra.forge;
import com.dfsek.terra.AbstractPlatform;
import cpw.mods.cl.ModuleClassLoader;
import net.minecraftforge.fml.loading.FMLLoader; import net.minecraftforge.fml.loading.FMLLoader;
import org.burningwave.core.classes.Classes; import org.burningwave.core.classes.Classes;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.nio.file.FileVisitOption; import java.nio.file.FileVisitOption;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.jar.JarEntry;
import java.util.jar.JarFile; import java.util.jar.JarFile;
import java.util.stream.Stream; import java.util.stream.Stream;
import com.dfsek.terra.AbstractPlatform;
import com.dfsek.terra.api.addon.bootstrap.BootstrapAddonClassLoader; import com.dfsek.terra.api.addon.bootstrap.BootstrapAddonClassLoader;
@@ -73,7 +63,7 @@ public final class AwfulForgeHacks {
} }
public static void loadAllTerraClasses() { public static void loadAllTerraClasses() {
if (FMLLoader.isProduction()) { if(FMLLoader.isProduction()) {
try(JarFile jar = getTerraJar()) { try(JarFile jar = getTerraJar()) {
jar.stream() jar.stream()
.forEach(jarEntry -> { .forEach(jarEntry -> {
@@ -96,7 +86,9 @@ public final class AwfulForgeHacks {
} }
} else { } else {
// Forgive me for what I'm about to do... // Forgive me for what I'm about to do...
LOGGER.warn("I felt a great disturbance in the JVM, as if millions of class not found exceptions suddenly cried out in terror and were suddenly silenced."); LOGGER.warn(
"I felt a great disturbance in the JVM, as if millions of class not found exceptions suddenly cried out in terror and" +
" were suddenly silenced.");
ArrayList<Path> pathsToLoad = new ArrayList<>(); ArrayList<Path> pathsToLoad = new ArrayList<>();
Path terraRoot = Path.of(System.getProperty("user.dir")).getParent().getParent().getParent(); Path terraRoot = Path.of(System.getProperty("user.dir")).getParent().getParent().getParent();
@@ -106,11 +98,11 @@ public final class AwfulForgeHacks {
pathsToLoad.add(commonRoot.resolve("api")); pathsToLoad.add(commonRoot.resolve("api"));
pathsToLoad.add(implementationRoot.resolve("base")); pathsToLoad.add(implementationRoot.resolve("base"));
pathsToLoad.add(implementationRoot.resolve("bootstrap-addon-loader")); pathsToLoad.add(implementationRoot.resolve("bootstrap-addon-loader"));
for (Path path : pathsToLoad) { for(Path path : pathsToLoad) {
try { try {
Path target = path.resolve("build").resolve("classes").resolve("java").resolve("main"); Path target = path.resolve("build").resolve("classes").resolve("java").resolve("main");
BootstrapAddonClassLoader cl = new BootstrapAddonClassLoader(new URL[] { path.toUri().toURL()}); BootstrapAddonClassLoader cl = new BootstrapAddonClassLoader(new URL[]{ path.toUri().toURL() });
Classes.Loaders omegaCL = Classes.Loaders.create(); Classes.Loaders omegaCL = Classes.Loaders.create();
Files.walk(target, Integer.MAX_VALUE, FileVisitOption.FOLLOW_LINKS) Files.walk(target, Integer.MAX_VALUE, FileVisitOption.FOLLOW_LINKS)
@@ -124,7 +116,12 @@ public final class AwfulForgeHacks {
Class.forName(name); Class.forName(name);
} catch(ClassNotFoundException e) { } catch(ClassNotFoundException e) {
try { try {
String pathToJar = cl.loadClass(name).getProtectionDomain().getCodeSource().getLocation().toURI().getPath(); String pathToJar = cl.loadClass(name)
.getProtectionDomain()
.getCodeSource()
.getLocation()
.toURI()
.getPath();
cl.addURL(new URL("jar:file:" + pathToJar + "!/")); cl.addURL(new URL("jar:file:" + pathToJar + "!/"));
Class newClassLoad = Class.forName(name, true, cl); Class newClassLoad = Class.forName(name, true, cl);

View File

@@ -3,6 +3,7 @@ package com.dfsek.terra.forge;
import com.dfsek.terra.mod.MinecraftAddon; import com.dfsek.terra.mod.MinecraftAddon;
import com.dfsek.terra.mod.ModPlatform; import com.dfsek.terra.mod.ModPlatform;
public class ForgeAddon extends MinecraftAddon { public class ForgeAddon extends MinecraftAddon {
public ForgeAddon(ModPlatform modPlatform) { public ForgeAddon(ModPlatform modPlatform) {

View File

@@ -43,28 +43,24 @@ import com.dfsek.terra.mod.data.Codecs;
@Mod("terra") @Mod("terra")
@EventBusSubscriber(bus = Bus.MOD) @EventBusSubscriber(bus = Bus.MOD)
public class ForgeEntryPoint { public class ForgeEntryPoint {
private final RegistrySanityCheck sanityCheck = new RegistrySanityCheck(); public static final String MODID = "terra";
private static final Logger logger = LoggerFactory.getLogger(ForgeEntryPoint.class);
private static final ForgePlatform TERRA_PLUGIN;
static { static {
AwfulForgeHacks.loadAllTerraClasses(); AwfulForgeHacks.loadAllTerraClasses();
TERRA_PLUGIN = new ForgePlatform(); TERRA_PLUGIN = new ForgePlatform();
} }
private final RegistrySanityCheck sanityCheck = new RegistrySanityCheck();
public static final String MODID = "terra";
private static final Logger logger = LoggerFactory.getLogger(ForgeEntryPoint.class);
private static final ForgePlatform TERRA_PLUGIN;
public static ForgePlatform getPlatform() {
return TERRA_PLUGIN;
}
public ForgeEntryPoint() { public ForgeEntryPoint() {
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
modEventBus.register(this); modEventBus.register(this);
} }
public static ForgePlatform getPlatform() {
return TERRA_PLUGIN;
}
public static void initialize(RegisterHelper<Biome> helper) { public static void initialize(RegisterHelper<Biome> helper) {
getPlatform().getEventManager().callEvent( getPlatform().getEventManager().callEvent(
new PlatformInitializationEvent()); new PlatformInitializationEvent());
@@ -75,10 +71,12 @@ public class ForgeEntryPoint {
public void registerBiomes(RegisterEvent event) { public void registerBiomes(RegisterEvent event) {
event.register(Keys.BLOCKS, helper -> sanityCheck.progress(RegistryStep.BLOCK, () -> logger.debug("Block registration detected."))); event.register(Keys.BLOCKS, helper -> sanityCheck.progress(RegistryStep.BLOCK, () -> logger.debug("Block registration detected.")));
event.register(Keys.BIOMES, helper -> sanityCheck.progress(RegistryStep.BIOME, () -> initialize(helper))); event.register(Keys.BIOMES, helper -> sanityCheck.progress(RegistryStep.BIOME, () -> initialize(helper)));
event.register(Registry.WORLD_PRESET_KEY, helper -> sanityCheck.progress(RegistryStep.WORLD_TYPE, () -> TERRA_PLUGIN.registerWorldTypes(helper::register))); event.register(Registry.WORLD_PRESET_KEY,
helper -> sanityCheck.progress(RegistryStep.WORLD_TYPE, () -> TERRA_PLUGIN.registerWorldTypes(helper::register)));
event.register(Registry.CHUNK_GENERATOR_KEY, helper -> helper.register(new Identifier("terra:terra"), Codecs.MINECRAFT_CHUNK_GENERATOR_WRAPPER)); event.register(Registry.CHUNK_GENERATOR_KEY,
helper -> helper.register(new Identifier("terra:terra"), Codecs.MINECRAFT_CHUNK_GENERATOR_WRAPPER));
event.register(Registry.BIOME_SOURCE_KEY, helper -> helper.register(new Identifier("terra:terra"), Codecs.TERRA_BIOME_SOURCE)); event.register(Registry.BIOME_SOURCE_KEY, helper -> helper.register(new Identifier("terra:terra"), Codecs.TERRA_BIOME_SOURCE));
} }
} }

View File

@@ -62,14 +62,14 @@ public class ForgePlatform extends ModPlatform {
MinecraftServer server = getServer(); MinecraftServer server = getServer();
if (server != null) { if(server != null) {
server.reloadResources(server.getDataPackManager().getNames()).exceptionally(throwable -> { server.reloadResources(server.getDataPackManager().getNames()).exceptionally(throwable -> {
LOGGER.warn("Failed to execute reload", throwable); LOGGER.warn("Failed to execute reload", throwable);
return null; return null;
}).join(); }).join();
//BiomeUtil.registerBiomes(); //BiomeUtil.registerBiomes();
server.getWorlds().forEach(world -> { server.getWorlds().forEach(world -> {
if (world.getChunkManager().getChunkGenerator() instanceof MinecraftChunkGeneratorWrapper chunkGeneratorWrapper) { if(world.getChunkManager().getChunkGenerator() instanceof MinecraftChunkGeneratorWrapper chunkGeneratorWrapper) {
getConfigRegistry().get(chunkGeneratorWrapper.getPack().getRegistryKey()).ifPresent(pack -> { getConfigRegistry().get(chunkGeneratorWrapper.getPack().getRegistryKey()).ifPresent(pack -> {
chunkGeneratorWrapper.setPack(pack); chunkGeneratorWrapper.setPack(pack);
LOGGER.info("Replaced pack in chunk generator for world {}", world); LOGGER.info("Replaced pack in chunk generator for world {}", world);
@@ -89,18 +89,19 @@ public class ForgePlatform extends ModPlatform {
String mcVersion = MinecraftVersion.CURRENT.getReleaseTarget(); String mcVersion = MinecraftVersion.CURRENT.getReleaseTarget();
try { try {
addons.add(new EphemeralAddon(Versions.parseVersion(mcVersion), "minecraft")); addons.add(new EphemeralAddon(Versions.parseVersion(mcVersion), "minecraft"));
} catch (ParseException e) { } catch(ParseException e) {
try { try {
addons.add(new EphemeralAddon(Versions.parseVersion(mcVersion + ".0"), "minecraft")); addons.add(new EphemeralAddon(Versions.parseVersion(mcVersion + ".0"), "minecraft"));
} catch (ParseException ex) { } catch(ParseException ex) {
LOGGER.warn("Failed to parse Minecraft version", e); LOGGER.warn("Failed to parse Minecraft version", e);
} }
} }
FMLLoader.getLoadingModList().getMods().forEach(mod -> { FMLLoader.getLoadingModList().getMods().forEach(mod -> {
String id = mod.getModId(); String id = mod.getModId();
if (id.equals("terra") || id.equals("minecraft") || id.equals("java")) return; if(id.equals("terra") || id.equals("minecraft") || id.equals("java")) return;
Version version = Versions.getVersion(mod.getVersion().getMajorVersion(), mod.getVersion().getMinorVersion(), mod.getVersion().getIncrementalVersion()); Version version = Versions.getVersion(mod.getVersion().getMajorVersion(), mod.getVersion().getMinorVersion(),
mod.getVersion().getIncrementalVersion());
addons.add(new EphemeralAddon(version, "forge:" + id)); addons.add(new EphemeralAddon(version, "forge:" + id));
}); });

View File

@@ -24,7 +24,15 @@ public class NoiseConfigMixin {
@Final @Final
private long legacyWorldSeed; private long legacyWorldSeed;
@Redirect(method = "<init>(Lnet/minecraft/world/gen/chunk/ChunkGeneratorSettings;Lnet/minecraft/util/registry/Registry;J)V", at = @At(value = "NEW", target = "(Lnet/minecraft/world/gen/densityfunction/DensityFunction;Lnet/minecraft/world/gen/densityfunction/DensityFunction;Lnet/minecraft/world/gen/densityfunction/DensityFunction;Lnet/minecraft/world/gen/densityfunction/DensityFunction;Lnet/minecraft/world/gen/densityfunction/DensityFunction;Lnet/minecraft/world/gen/densityfunction/DensityFunction;Ljava/util/List;)Lnet/minecraft/world/biome/source/util/MultiNoiseUtil$MultiNoiseSampler;")) @Redirect(method = "<init>(Lnet/minecraft/world/gen/chunk/ChunkGeneratorSettings;Lnet/minecraft/util/registry/Registry;J)V",
at = @At(value = "NEW",
target = "(Lnet/minecraft/world/gen/densityfunction/DensityFunction;" +
"Lnet/minecraft/world/gen/densityfunction/DensityFunction;" +
"Lnet/minecraft/world/gen/densityfunction/DensityFunction;" +
"Lnet/minecraft/world/gen/densityfunction/DensityFunction;" +
"Lnet/minecraft/world/gen/densityfunction/DensityFunction;" +
"Lnet/minecraft/world/gen/densityfunction/DensityFunction;Ljava/util/List;)" +
"Lnet/minecraft/world/biome/source/util/MultiNoiseUtil$MultiNoiseSampler;"))
private MultiNoiseSampler t(DensityFunction densityFunction, DensityFunction densityFunction2, DensityFunction densityFunction3, private MultiNoiseSampler t(DensityFunction densityFunction, DensityFunction densityFunction2, DensityFunction densityFunction3,
DensityFunction densityFunction4, DensityFunction densityFunction5, DensityFunction densityFunction6, DensityFunction densityFunction4, DensityFunction densityFunction5, DensityFunction densityFunction6,
List<NoiseHypercube> list) { List<NoiseHypercube> list) {

View File

@@ -1,8 +1,5 @@
package com.dfsek.terra.forge.util; package com.dfsek.terra.forge.util;
import com.dfsek.terra.mod.config.VanillaBiomeProperties;
import com.dfsek.terra.mod.mixin.access.VillagerTypeAccessor;
import net.minecraft.util.Identifier; import net.minecraft.util.Identifier;
import net.minecraft.util.registry.BuiltinRegistries; import net.minecraft.util.registry.BuiltinRegistries;
import net.minecraft.util.registry.Registry; import net.minecraft.util.registry.Registry;
@@ -22,6 +19,8 @@ import com.dfsek.terra.api.world.biome.Biome;
import com.dfsek.terra.forge.ForgeEntryPoint; import com.dfsek.terra.forge.ForgeEntryPoint;
import com.dfsek.terra.mod.config.PreLoadCompatibilityOptions; import com.dfsek.terra.mod.config.PreLoadCompatibilityOptions;
import com.dfsek.terra.mod.config.ProtoPlatformBiome; import com.dfsek.terra.mod.config.ProtoPlatformBiome;
import com.dfsek.terra.mod.config.VanillaBiomeProperties;
import com.dfsek.terra.mod.mixin.access.VillagerTypeAccessor;
import com.dfsek.terra.mod.util.MinecraftUtil; import com.dfsek.terra.mod.util.MinecraftUtil;
@@ -51,8 +50,9 @@ public final class BiomeUtil {
* @param pack The ConfigPack this biome belongs to. * @param pack The ConfigPack this biome belongs to.
*/ */
private static void registerBiome(Biome biome, ConfigPack pack, private static void registerBiome(Biome biome, ConfigPack pack,
com.dfsek.terra.api.registry.key.RegistryKey id, RegisterHelper<net.minecraft.world.biome.Biome> helper) { com.dfsek.terra.api.registry.key.RegistryKey id,
RegistryKey<net.minecraft.world.biome.Biome> vanilla = ((ProtoPlatformBiome) biome.getPlatformBiome()) .get(BuiltinRegistries.BIOME); RegisterHelper<net.minecraft.world.biome.Biome> helper) {
RegistryKey<net.minecraft.world.biome.Biome> vanilla = ((ProtoPlatformBiome) biome.getPlatformBiome()).get(BuiltinRegistries.BIOME);
if(pack.getContext().get(PreLoadCompatibilityOptions.class).useVanillaBiomes()) { if(pack.getContext().get(PreLoadCompatibilityOptions.class).useVanillaBiomes()) {
@@ -60,20 +60,31 @@ public final class BiomeUtil {
} else { } else {
VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class); VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class);
net.minecraft.world.biome.Biome minecraftBiome = MinecraftUtil.createBiome(biome, ForgeRegistries.BIOMES.getDelegateOrThrow(vanilla).value(), vanillaBiomeProperties); net.minecraft.world.biome.Biome minecraftBiome = MinecraftUtil.createBiome(biome,
ForgeRegistries.BIOMES.getDelegateOrThrow(vanilla)
.value(),
vanillaBiomeProperties);
Identifier identifier = new Identifier("terra", MinecraftUtil.createBiomeID(pack, id)); Identifier identifier = new Identifier("terra", MinecraftUtil.createBiomeID(pack, id));
if(ForgeRegistries.BIOMES.containsKey(identifier)) { if(ForgeRegistries.BIOMES.containsKey(identifier)) {
((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(ForgeRegistries.BIOMES.getHolder(identifier).orElseThrow().getKey().orElseThrow()); ((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(ForgeRegistries.BIOMES.getHolder(identifier)
.orElseThrow()
.getKey()
.orElseThrow());
} else { } else {
helper.register(MinecraftUtil.registerKey(identifier).getValue(), minecraftBiome); helper.register(MinecraftUtil.registerKey(identifier).getValue(), minecraftBiome);
((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(ForgeRegistries.BIOMES.getHolder(identifier).orElseThrow().getKey().orElseThrow()); ((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(ForgeRegistries.BIOMES.getHolder(identifier)
.orElseThrow()
.getKey()
.orElseThrow());
} }
Map villagerMap = VillagerTypeAccessor.getBiomeTypeToIdMap(); Map villagerMap = VillagerTypeAccessor.getBiomeTypeToIdMap();
villagerMap.put(RegistryKey.of(Registry.BIOME_KEY, identifier), Objects.requireNonNullElse(vanillaBiomeProperties.getVillagerType(), villagerMap.getOrDefault(vanilla, VillagerType.PLAINS))); villagerMap.put(RegistryKey.of(Registry.BIOME_KEY, identifier),
Objects.requireNonNullElse(vanillaBiomeProperties.getVillagerType(),
villagerMap.getOrDefault(vanilla, VillagerType.PLAINS)));
MinecraftUtil.TERRA_BIOME_MAP.computeIfAbsent(vanilla.getValue(), i -> new ArrayList<>()).add(identifier); MinecraftUtil.TERRA_BIOME_MAP.computeIfAbsent(vanilla.getValue(), i -> new ArrayList<>()).add(identifier);
} }

View File

@@ -1,7 +1,7 @@
modLoader = "javafml" modLoader = "javafml"
loaderVersion = "[41,)" loaderVersion = "[41,)"
license = "GNU General Public License, v3.0" license = "GNU General Public License, v3.0"
issueTrackerURL="https://github.com/PolyhedralDev/Terra/issues" issueTrackerURL = "https://github.com/PolyhedralDev/Terra/issues"
[[mods]] [[mods]]
modId = "terra" modId = "terra"

View File

@@ -3,17 +3,6 @@ package com.dfsek.terra.mod;
import com.dfsek.tectonic.api.TypeRegistry; import com.dfsek.tectonic.api.TypeRegistry;
import com.dfsek.tectonic.api.depth.DepthTracker; import com.dfsek.tectonic.api.depth.DepthTracker;
import com.dfsek.tectonic.api.exception.LoadException; import com.dfsek.tectonic.api.exception.LoadException;
import com.dfsek.terra.api.handle.ItemHandle;
import com.dfsek.terra.api.handle.WorldHandle;
import com.dfsek.terra.mod.config.SpawnSettingsTemplate;
import com.dfsek.terra.mod.handle.MinecraftItemHandle;
import com.dfsek.terra.mod.handle.MinecraftWorldHandle;
import com.dfsek.terra.mod.config.VillagerTypeTemplate;
import net.minecraft.entity.EntityType; import net.minecraft.entity.EntityType;
import net.minecraft.entity.SpawnGroup; import net.minecraft.entity.SpawnGroup;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
@@ -31,6 +20,7 @@ import net.minecraft.world.biome.BiomeParticleConfig;
import net.minecraft.world.biome.SpawnSettings; import net.minecraft.world.biome.SpawnSettings;
import net.minecraft.world.biome.SpawnSettings.SpawnEntry; import net.minecraft.world.biome.SpawnSettings.SpawnEntry;
import net.minecraft.world.gen.WorldPreset; import net.minecraft.world.gen.WorldPreset;
import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@@ -38,6 +28,8 @@ import java.util.function.BiConsumer;
import com.dfsek.terra.AbstractPlatform; import com.dfsek.terra.AbstractPlatform;
import com.dfsek.terra.api.addon.BaseAddon; import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.handle.ItemHandle;
import com.dfsek.terra.api.handle.WorldHandle;
import com.dfsek.terra.api.world.biome.PlatformBiome; import com.dfsek.terra.api.world.biome.PlatformBiome;
import com.dfsek.terra.mod.config.BiomeAdditionsSoundTemplate; import com.dfsek.terra.mod.config.BiomeAdditionsSoundTemplate;
import com.dfsek.terra.mod.config.BiomeMoodSoundTemplate; import com.dfsek.terra.mod.config.BiomeMoodSoundTemplate;
@@ -49,18 +41,20 @@ import com.dfsek.terra.mod.config.SoundEventTemplate;
import com.dfsek.terra.mod.config.SpawnCostConfig; import com.dfsek.terra.mod.config.SpawnCostConfig;
import com.dfsek.terra.mod.config.SpawnEntryTemplate; import com.dfsek.terra.mod.config.SpawnEntryTemplate;
import com.dfsek.terra.mod.config.SpawnGroupTemplate; import com.dfsek.terra.mod.config.SpawnGroupTemplate;
import com.dfsek.terra.mod.config.SpawnSettingsTemplate;
import com.dfsek.terra.mod.config.SpawnTypeConfig; import com.dfsek.terra.mod.config.SpawnTypeConfig;
import com.dfsek.terra.mod.config.VillagerTypeTemplate;
import com.dfsek.terra.mod.handle.MinecraftItemHandle;
import com.dfsek.terra.mod.handle.MinecraftWorldHandle;
import com.dfsek.terra.mod.util.PresetUtil; import com.dfsek.terra.mod.util.PresetUtil;
import org.jetbrains.annotations.NotNull;
public abstract class ModPlatform extends AbstractPlatform { public abstract class ModPlatform extends AbstractPlatform {
public abstract MinecraftServer getServer();
private final ItemHandle itemHandle = new MinecraftItemHandle(); private final ItemHandle itemHandle = new MinecraftItemHandle();
private final WorldHandle worldHandle = new MinecraftWorldHandle(); private final WorldHandle worldHandle = new MinecraftWorldHandle();
public abstract MinecraftServer getServer();
public void registerWorldTypes(BiConsumer<Identifier, WorldPreset> registerFunction) { public void registerWorldTypes(BiConsumer<Identifier, WorldPreset> registerFunction) {
getRawConfigRegistry() getRawConfigRegistry()
.forEach(pack -> PresetUtil.createDefault(pack).apply(registerFunction)); .forEach(pack -> PresetUtil.createDefault(pack).apply(registerFunction));
@@ -78,9 +72,11 @@ public abstract class ModPlatform extends AbstractPlatform {
}) })
.registerLoader(Precipitation.class, (type, o, loader, depthTracker) -> Precipitation.valueOf(((String) o).toUpperCase( .registerLoader(Precipitation.class, (type, o, loader, depthTracker) -> Precipitation.valueOf(((String) o).toUpperCase(
Locale.ROOT))) Locale.ROOT)))
.registerLoader(GrassColorModifier.class, (type, o, loader, depthTracker) -> GrassColorModifier.valueOf(((String) o).toUpperCase( .registerLoader(GrassColorModifier.class,
(type, o, loader, depthTracker) -> GrassColorModifier.valueOf(((String) o).toUpperCase(
Locale.ROOT))) Locale.ROOT)))
.registerLoader(GrassColorModifier.class, (type, o, loader, depthTracker) -> TemperatureModifier.valueOf(((String) o).toUpperCase( .registerLoader(GrassColorModifier.class,
(type, o, loader, depthTracker) -> TemperatureModifier.valueOf(((String) o).toUpperCase(
Locale.ROOT))) Locale.ROOT)))
.registerLoader(BiomeParticleConfig.class, BiomeParticleConfigTemplate::new) .registerLoader(BiomeParticleConfig.class, BiomeParticleConfigTemplate::new)
.registerLoader(SoundEvent.class, SoundEventTemplate::new) .registerLoader(SoundEvent.class, SoundEventTemplate::new)

View File

@@ -18,7 +18,7 @@ public class BiomeAdditionsSoundTemplate implements ObjectTemplate<BiomeAddition
@Override @Override
public BiomeAdditionsSound get() { public BiomeAdditionsSound get() {
if (sound == null || soundChance == null) { if(sound == null || soundChance == null) {
return null; return null;
} else { } else {
return new BiomeAdditionsSound(sound, soundChance); return new BiomeAdditionsSound(sound, soundChance);

View File

@@ -26,7 +26,7 @@ public class BiomeMoodSoundTemplate implements ObjectTemplate<BiomeMoodSound> {
@Override @Override
public BiomeMoodSound get() { public BiomeMoodSound get() {
if (sound == null || soundCultivationTicks == null || soundSpawnRange == null || soundExtraDistance == null) { if(sound == null || soundCultivationTicks == null || soundSpawnRange == null || soundExtraDistance == null) {
return null; return null;
} else { } else {
return new BiomeMoodSound(sound, soundCultivationTicks, soundSpawnRange, soundExtraDistance); return new BiomeMoodSound(sound, soundCultivationTicks, soundSpawnRange, soundExtraDistance);

View File

@@ -20,7 +20,7 @@ public class BiomeParticleConfigTemplate implements ObjectTemplate<BiomeParticle
@Override @Override
public BiomeParticleConfig get() { public BiomeParticleConfig get() {
if (particle == null || probability == null) { if(particle == null || probability == null) {
return null; return null;
} }

View File

@@ -26,7 +26,7 @@ public class MusicSoundTemplate implements ObjectTemplate<MusicSound> {
@Override @Override
public MusicSound get() { public MusicSound get() {
if (sound == null || minDelay == null || maxDelay == null || replaceCurrentMusic == null) { if(sound == null || minDelay == null || maxDelay == null || replaceCurrentMusic == null) {
return null; return null;
} else { } else {
return new MusicSound(sound, minDelay, maxDelay, replaceCurrentMusic); return new MusicSound(sound, minDelay, maxDelay, replaceCurrentMusic);

View File

@@ -18,9 +18,9 @@ public class SoundEventTemplate implements ObjectTemplate<SoundEvent> {
@Override @Override
public SoundEvent get() { public SoundEvent get() {
if (id == null) { if(id == null) {
return null; return null;
} else if (distanceToTravel == null) { } else if(distanceToTravel == null) {
return new SoundEvent(id); return new SoundEvent(id);
} else { } else {
return new SoundEvent(id, distanceToTravel); return new SoundEvent(id, distanceToTravel);

View File

@@ -24,13 +24,13 @@ public class SpawnSettingsTemplate implements ObjectTemplate<SpawnSettings> {
@Override @Override
public SpawnSettings get() { public SpawnSettings get() {
SpawnSettings.Builder builder = new SpawnSettings.Builder(); SpawnSettings.Builder builder = new SpawnSettings.Builder();
for (SpawnTypeConfig spawn : spawns) { for(SpawnTypeConfig spawn : spawns) {
builder.spawn(spawn.getGroup(), spawn.getEntry()); builder.spawn(spawn.getGroup(), spawn.getEntry());
} }
for (SpawnCostConfig cost: costs) { for(SpawnCostConfig cost : costs) {
builder.spawnCost(cost.getType(), cost.getMass(), cost.getGravity()); builder.spawnCost(cost.getType(), cost.getMass(), cost.getGravity());
} }
if (probability != null) { if(probability != null) {
builder.creatureSpawnProbability(probability); builder.creatureSpawnProbability(probability);
} }

View File

@@ -3,7 +3,6 @@ package com.dfsek.terra.mod.config;
import com.dfsek.tectonic.api.config.template.annotations.Default; import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value; import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate; import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import net.minecraft.entity.EntityType;
import net.minecraft.util.Identifier; import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry; import net.minecraft.util.registry.Registry;
import net.minecraft.village.VillagerType; import net.minecraft.village.VillagerType;

View File

@@ -8,6 +8,7 @@ import org.spongepowered.asm.mixin.gen.Accessor;
import java.util.Map; import java.util.Map;
@Mixin(VillagerType.class) @Mixin(VillagerType.class)
public interface VillagerTypeAccessor { public interface VillagerTypeAccessor {
@Accessor("BIOME_TO_TYPE") @Accessor("BIOME_TO_TYPE")

View File

@@ -20,7 +20,8 @@ import com.dfsek.terra.mod.CommonPlatform;
MoveToFlowerGoal.class MoveToFlowerGoal.class
}) })
public class BeeMoveGoalsUnsynchronizedRandomAccessFix { public class BeeMoveGoalsUnsynchronizedRandomAccessFix {
@Redirect(method = "<init>", at = @At(value = "FIELD", target = "Lnet/minecraft/world/World;random:Lnet/minecraft/util/math/random/Random;")) @Redirect(method = "<init>",
at = @At(value = "FIELD", target = "Lnet/minecraft/world/World;random:Lnet/minecraft/util/math/random/Random;"))
public Random redirectRandomAccess(World instance) { public Random redirectRandomAccess(World instance) {
return new CheckedRandom(CommonPlatform.get().getServer().getTicks()); // replace with new random seeded by tick time. return new CheckedRandom(CommonPlatform.get().getServer().getTicks()); // replace with new random seeded by tick time.
} }

View File

@@ -15,8 +15,9 @@ import com.dfsek.terra.mod.generation.MinecraftChunkGeneratorWrapper;
/** /**
* Disable fossil generation in Terra worlds, as they are very expensive due to consistently triggering cache misses. * Disable fossil generation in Terra worlds, as they are very expensive due to consistently triggering cache misses.
* * <p>
* Currently, on Fabric, Terra cannot be specified as a Nether generator. TODO: logic to turn fossils back on if chunk generator is in nether. * Currently, on Fabric, Terra cannot be specified as a Nether generator. TODO: logic to turn fossils back on if chunk generator is in
* nether.
*/ */
@Mixin(NetherFossilStructure.class) @Mixin(NetherFossilStructure.class)
public class NetherFossilOptimization { public class NetherFossilOptimization {

View File

@@ -1,7 +1,5 @@
package com.dfsek.terra.mod.util; package com.dfsek.terra.mod.util;
import com.dfsek.terra.mod.mixin.access.VillagerTypeAccessor;
import net.minecraft.block.entity.LootableContainerBlockEntity; import net.minecraft.block.entity.LootableContainerBlockEntity;
import net.minecraft.block.entity.MobSpawnerBlockEntity; import net.minecraft.block.entity.MobSpawnerBlockEntity;
import net.minecraft.block.entity.SignBlockEntity; import net.minecraft.block.entity.SignBlockEntity;
@@ -10,7 +8,6 @@ import net.minecraft.util.math.BlockPos;
import net.minecraft.util.registry.Registry; import net.minecraft.util.registry.Registry;
import net.minecraft.util.registry.RegistryEntry; import net.minecraft.util.registry.RegistryEntry;
import net.minecraft.util.registry.RegistryKey; import net.minecraft.util.registry.RegistryKey;
import net.minecraft.village.VillagerType;
import net.minecraft.world.WorldAccess; import net.minecraft.world.WorldAccess;
import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.Biome.Builder; import net.minecraft.world.biome.Biome.Builder;
@@ -73,9 +70,14 @@ public final class MinecraftUtil {
.forEach(tb -> biomes.getOrEmpty(tb) .forEach(tb -> biomes.getOrEmpty(tb)
.ifPresentOrElse( .ifPresentOrElse(
terra -> { terra -> {
List<ConfiguredFeature<?, ?>> flowerFeatures = List.copyOf(vanilla.getGenerationSettings().getFlowerFeatures()); List<ConfiguredFeature<?, ?>> flowerFeatures = List.copyOf(
logger.debug("Injecting flora into biome {} : {}", tb, flowerFeatures); vanilla.getGenerationSettings()
((FloraFeatureHolder) terra.getGenerationSettings()).setFloraFeatures(flowerFeatures); .getFlowerFeatures());
logger.debug("Injecting flora into biome" +
" {} : {}", tb,
flowerFeatures);
((FloraFeatureHolder) terra.getGenerationSettings()).setFloraFeatures(
flowerFeatures);
}, },
() -> logger.error( () -> logger.error(
"No such biome: {}", "No such biome: {}",
@@ -92,7 +94,8 @@ public final class MinecraftUtil {
return RegistryKey.of(Registry.BIOME_KEY, identifier); return RegistryKey.of(Registry.BIOME_KEY, identifier);
} }
public static Biome createBiome(com.dfsek.terra.api.world.biome.Biome biome, Biome vanilla, VanillaBiomeProperties vanillaBiomeProperties) { public static Biome createBiome(com.dfsek.terra.api.world.biome.Biome biome, Biome vanilla,
VanillaBiomeProperties vanillaBiomeProperties) {
GenerationSettings.Builder generationSettings = new GenerationSettings.Builder(); GenerationSettings.Builder generationSettings = new GenerationSettings.Builder();
BiomeEffects.Builder effects = new BiomeEffects.Builder(); BiomeEffects.Builder effects = new BiomeEffects.Builder();
@@ -104,45 +107,46 @@ public final class MinecraftUtil {
.fogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanilla.getFogColor())) .fogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanilla.getFogColor()))
.skyColor(Objects.requireNonNullElse(vanillaBiomeProperties.getSkyColor(), vanilla.getSkyColor())) .skyColor(Objects.requireNonNullElse(vanillaBiomeProperties.getSkyColor(), vanilla.getSkyColor()))
.grassColorModifier( .grassColorModifier(
Objects.requireNonNullElse(vanillaBiomeProperties.getGrassColorModifier(), vanilla.getEffects().getGrassColorModifier())); Objects.requireNonNullElse(vanillaBiomeProperties.getGrassColorModifier(),
vanilla.getEffects().getGrassColorModifier()));
if (vanillaBiomeProperties.getFoliageColor() == null) { if(vanillaBiomeProperties.getFoliageColor() == null) {
vanilla.getEffects().getFoliageColor().ifPresent(effects::foliageColor); vanilla.getEffects().getFoliageColor().ifPresent(effects::foliageColor);
} else { } else {
effects.foliageColor(vanillaBiomeProperties.getFoliageColor()); effects.foliageColor(vanillaBiomeProperties.getFoliageColor());
} }
if (vanillaBiomeProperties.getGrassColor() == null) { if(vanillaBiomeProperties.getGrassColor() == null) {
vanilla.getEffects().getGrassColor().ifPresent(effects::grassColor); vanilla.getEffects().getGrassColor().ifPresent(effects::grassColor);
} else { } else {
effects.grassColor(vanillaBiomeProperties.getGrassColor()); effects.grassColor(vanillaBiomeProperties.getGrassColor());
} }
if (vanillaBiomeProperties.getParticleConfig() == null) { if(vanillaBiomeProperties.getParticleConfig() == null) {
vanilla.getEffects().getParticleConfig().ifPresent(effects::particleConfig); vanilla.getEffects().getParticleConfig().ifPresent(effects::particleConfig);
} else { } else {
effects.particleConfig(vanillaBiomeProperties.getParticleConfig()); effects.particleConfig(vanillaBiomeProperties.getParticleConfig());
} }
if (vanillaBiomeProperties.getLoopSound() == null) { if(vanillaBiomeProperties.getLoopSound() == null) {
vanilla.getEffects().getLoopSound().ifPresent(effects::loopSound); vanilla.getEffects().getLoopSound().ifPresent(effects::loopSound);
} else { } else {
effects.loopSound(vanillaBiomeProperties.getLoopSound()); effects.loopSound(vanillaBiomeProperties.getLoopSound());
} }
if (vanillaBiomeProperties.getMoodSound() == null) { if(vanillaBiomeProperties.getMoodSound() == null) {
vanilla.getEffects().getMoodSound().ifPresent(effects::moodSound); vanilla.getEffects().getMoodSound().ifPresent(effects::moodSound);
} else { } else {
effects.moodSound(vanillaBiomeProperties.getMoodSound()); effects.moodSound(vanillaBiomeProperties.getMoodSound());
} }
if (vanillaBiomeProperties.getAdditionsSound() == null) { if(vanillaBiomeProperties.getAdditionsSound() == null) {
vanilla.getEffects().getAdditionsSound().ifPresent(effects::additionsSound); vanilla.getEffects().getAdditionsSound().ifPresent(effects::additionsSound);
} else { } else {
effects.additionsSound(vanillaBiomeProperties.getAdditionsSound()); effects.additionsSound(vanillaBiomeProperties.getAdditionsSound());
} }
if (vanillaBiomeProperties.getMusic() == null) { if(vanillaBiomeProperties.getMusic() == null) {
vanilla.getEffects().getMusic().ifPresent(effects::music); vanilla.getEffects().getMusic().ifPresent(effects::music);
} else { } else {
effects.music(vanillaBiomeProperties.getMusic()); effects.music(vanillaBiomeProperties.getMusic());
@@ -154,7 +158,8 @@ public final class MinecraftUtil {
builder.downfall(Objects.requireNonNullElse(vanillaBiomeProperties.getDownfall(), vanilla.getDownfall())); builder.downfall(Objects.requireNonNullElse(vanillaBiomeProperties.getDownfall(), vanilla.getDownfall()));
builder.temperatureModifier(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperatureModifier(), ((BiomeAccessor)((Object)vanilla)).getWeather().temperatureModifier())); builder.temperatureModifier(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperatureModifier(),
((BiomeAccessor) ((Object) vanilla)).getWeather().temperatureModifier()));
builder.spawnSettings(Objects.requireNonNullElse(vanillaBiomeProperties.getSpawnSettings(), vanilla.getSpawnSettings())); builder.spawnSettings(Objects.requireNonNullElse(vanillaBiomeProperties.getSpawnSettings(), vanilla.getSpawnSettings()));

View File

@@ -28,15 +28,15 @@ public abstract class LifecyclePlatform extends ModPlatform {
load(); load();
} }
public static void setServer(MinecraftServer server) {
LifecyclePlatform.server = server;
}
@Override @Override
public MinecraftServer getServer() { public MinecraftServer getServer() {
return server; return server;
} }
public static void setServer(MinecraftServer server) {
LifecyclePlatform.server = server;
}
@Override @Override
public boolean reload() { public boolean reload() {
getTerraConfig().load(this); getTerraConfig().load(this);

View File

@@ -24,8 +24,10 @@ public class NoiseConfigMixin {
@Final @Final
private MultiNoiseSampler multiNoiseSampler; private MultiNoiseSampler multiNoiseSampler;
@Inject(method = "<init>(Lnet/minecraft/world/gen/chunk/ChunkGeneratorSettings;Lnet/minecraft/util/registry/Registry;J)V", at = @At("TAIL")) @Inject(method = "<init>(Lnet/minecraft/world/gen/chunk/ChunkGeneratorSettings;Lnet/minecraft/util/registry/Registry;J)V",
private void mapMultiNoise(ChunkGeneratorSettings chunkGeneratorSettings, Registry<DoublePerlinNoiseSampler.NoiseParameters> noiseRegistry, long seed, CallbackInfo ci) { at = @At("TAIL"))
private void mapMultiNoise(ChunkGeneratorSettings chunkGeneratorSettings,
Registry<DoublePerlinNoiseSampler.NoiseParameters> noiseRegistry, long seed, CallbackInfo ci) {
SeedHack.register(multiNoiseSampler, seed); SeedHack.register(multiNoiseSampler, seed);
} }
} }

View File

@@ -1,13 +1,13 @@
package com.dfsek.terra.lifecycle.mixin; package com.dfsek.terra.lifecycle.mixin;
import com.dfsek.terra.lifecycle.util.RegistryUtil;
import net.minecraft.util.registry.Registry; import net.minecraft.util.registry.Registry;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.dfsek.terra.lifecycle.util.RegistryUtil;
@Mixin(Registry.class) @Mixin(Registry.class)
public class RegistryMixin { public class RegistryMixin {

View File

@@ -1,9 +1,5 @@
package com.dfsek.terra.lifecycle.util; package com.dfsek.terra.lifecycle.util;
import com.dfsek.terra.mod.config.VanillaBiomeProperties;
import com.dfsek.terra.mod.mixin.access.VillagerTypeAccessor;
import net.minecraft.util.Identifier; import net.minecraft.util.Identifier;
import net.minecraft.util.registry.BuiltinRegistries; import net.minecraft.util.registry.BuiltinRegistries;
import net.minecraft.util.registry.Registry; import net.minecraft.util.registry.Registry;
@@ -21,6 +17,8 @@ import com.dfsek.terra.api.world.biome.Biome;
import com.dfsek.terra.mod.CommonPlatform; import com.dfsek.terra.mod.CommonPlatform;
import com.dfsek.terra.mod.config.PreLoadCompatibilityOptions; import com.dfsek.terra.mod.config.PreLoadCompatibilityOptions;
import com.dfsek.terra.mod.config.ProtoPlatformBiome; import com.dfsek.terra.mod.config.ProtoPlatformBiome;
import com.dfsek.terra.mod.config.VanillaBiomeProperties;
import com.dfsek.terra.mod.mixin.access.VillagerTypeAccessor;
import com.dfsek.terra.mod.util.MinecraftUtil; import com.dfsek.terra.mod.util.MinecraftUtil;
@@ -58,7 +56,8 @@ public final class BiomeUtil {
} else { } else {
VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class); VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class);
net.minecraft.world.biome.Biome minecraftBiome = MinecraftUtil.createBiome(biome, registry.get(vanilla), vanillaBiomeProperties); net.minecraft.world.biome.Biome minecraftBiome = MinecraftUtil.createBiome(biome, registry.get(vanilla),
vanillaBiomeProperties);
Identifier identifier = new Identifier("terra", MinecraftUtil.createBiomeID(pack, id)); Identifier identifier = new Identifier("terra", MinecraftUtil.createBiomeID(pack, id));
@@ -69,13 +68,16 @@ public final class BiomeUtil {
.orElseThrow()); .orElseThrow());
} else { } else {
((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(BuiltinRegistries.add(registry, ((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(BuiltinRegistries.add(registry,
MinecraftUtil.registerKey(identifier).getValue(), MinecraftUtil.registerKey(identifier)
.getValue(),
minecraftBiome).getKey().orElseThrow()); minecraftBiome).getKey().orElseThrow());
} }
Map villagerMap = VillagerTypeAccessor.getBiomeTypeToIdMap(); Map villagerMap = VillagerTypeAccessor.getBiomeTypeToIdMap();
villagerMap.put(RegistryKey.of(Registry.BIOME_KEY, identifier), Objects.requireNonNullElse(vanillaBiomeProperties.getVillagerType(), villagerMap.getOrDefault(vanilla, VillagerType.PLAINS))); villagerMap.put(RegistryKey.of(Registry.BIOME_KEY, identifier),
Objects.requireNonNullElse(vanillaBiomeProperties.getVillagerType(),
villagerMap.getOrDefault(vanilla, VillagerType.PLAINS)));
MinecraftUtil.TERRA_BIOME_MAP.computeIfAbsent(vanilla.getValue(), i -> new ArrayList<>()).add(identifier); MinecraftUtil.TERRA_BIOME_MAP.computeIfAbsent(vanilla.getValue(), i -> new ArrayList<>()).add(identifier);
} }

View File

@@ -1,10 +1,10 @@
package com.dfsek.terra.lifecycle.util; package com.dfsek.terra.lifecycle.util;
import net.minecraft.util.registry.BuiltinRegistries;
import com.dfsek.terra.api.event.events.platform.PlatformInitializationEvent; import com.dfsek.terra.api.event.events.platform.PlatformInitializationEvent;
import com.dfsek.terra.mod.CommonPlatform; import com.dfsek.terra.mod.CommonPlatform;
import net.minecraft.util.registry.BuiltinRegistries;
public final class LifecycleUtil { public final class LifecycleUtil {
private LifecycleUtil() { private LifecycleUtil() {

View File

@@ -1,10 +1,10 @@
package com.dfsek.terra.lifecycle.util; package com.dfsek.terra.lifecycle.util;
import com.dfsek.terra.mod.data.Codecs;
import net.minecraft.util.Identifier; import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry; import net.minecraft.util.registry.Registry;
import com.dfsek.terra.mod.data.Codecs;
public final class RegistryUtil { public final class RegistryUtil {
private RegistryUtil() { private RegistryUtil() {

View File

@@ -4,39 +4,40 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.URL; import java.net.URL;
/** /**
* So you want to Mixin into Authlib/Brigadier/DataFixerUpper, on Fabric you'll need this guy. * So you want to Mixin into Authlib/Brigadier/DataFixerUpper, on Fabric you'll need this guy.
* *
* <p>YOU SHOULD ONLY USE THIS CLASS DURING "preLaunch" and ONLY TARGET A CLASS WHICH IS NOT ANY CLASS YOU MIXIN TO. * <p>YOU SHOULD ONLY USE THIS CLASS DURING "preLaunch" and ONLY TARGET A CLASS WHICH IS NOT ANY CLASS YOU MIXIN TO.
* * <p>
* This will likely not work on Gson because FabricLoader has some special logic related to Gson. * This will likely not work on Gson because FabricLoader has some special logic related to Gson.
*/ */
public final class AwfulQuiltHacks { public final class AwfulQuiltHacks {
private AwfulQuiltHacks() {}
private static final ClassLoader KNOT_CLASSLOADER = Thread.currentThread().getContextClassLoader(); private static final ClassLoader KNOT_CLASSLOADER = Thread.currentThread().getContextClassLoader();
private static final Method ADD_URL_METHOD; private static final Method ADD_URL_METHOD;
static { static {
Method tempAddUrlMethod = null; Method tempAddUrlMethod = null;
try { try {
tempAddUrlMethod = KNOT_CLASSLOADER.getClass().getMethod("addURL", URL.class); tempAddUrlMethod = KNOT_CLASSLOADER.getClass().getMethod("addURL", URL.class);
tempAddUrlMethod.setAccessible(true); tempAddUrlMethod.setAccessible(true);
} catch (ReflectiveOperationException e) { } catch(ReflectiveOperationException e) {
throw new RuntimeException("Failed to load Classloader fields", e); throw new RuntimeException("Failed to load Classloader fields", e);
} }
ADD_URL_METHOD = tempAddUrlMethod; ADD_URL_METHOD = tempAddUrlMethod;
} }
private AwfulQuiltHacks() { }
/** /**
* Hackily load the package which a mixin may exist within. * Hackily load the package which a mixin may exist within.
* * <p>
* YOU SHOULD NOT TARGET A CLASS WHICH YOU MIXIN TO. * YOU SHOULD NOT TARGET A CLASS WHICH YOU MIXIN TO.
* *
* @param pathOfAClass The path of any class within the package. * @param pathOfAClass The path of any class within the package.
*/ */
public static void hackilyLoadForMixin(String pathOfAClass) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException { public static void hackilyLoadForMixin(String pathOfAClass)
throws ClassNotFoundException, InvocationTargetException, IllegalAccessException {
URL url = Class.forName(pathOfAClass).getProtectionDomain().getCodeSource().getLocation(); URL url = Class.forName(pathOfAClass).getProtectionDomain().getCodeSource().getLocation();
ADD_URL_METHOD.invoke(KNOT_CLASSLOADER, url); ADD_URL_METHOD.invoke(KNOT_CLASSLOADER, url);
} }

View File

@@ -3,6 +3,7 @@ package com.dfsek.terra.quilt;
import com.dfsek.terra.mod.MinecraftAddon; import com.dfsek.terra.mod.MinecraftAddon;
import com.dfsek.terra.mod.ModPlatform; import com.dfsek.terra.mod.ModPlatform;
public class QuiltAddon extends MinecraftAddon { public class QuiltAddon extends MinecraftAddon {
public QuiltAddon(ModPlatform modPlatform) { public QuiltAddon(ModPlatform modPlatform) {

View File

@@ -33,6 +33,7 @@ public class QuiltEntryPoint implements ModInitializer {
private static final Logger logger = LoggerFactory.getLogger(QuiltEntryPoint.class); private static final Logger logger = LoggerFactory.getLogger(QuiltEntryPoint.class);
private static final QuiltPlatform TERRA_PLUGIN = new QuiltPlatform(); private static final QuiltPlatform TERRA_PLUGIN = new QuiltPlatform();
@Override @Override
public void onInitialize(ModContainer container) { public void onInitialize(ModContainer container) {
logger.info("Initializing Terra Quilt mod..."); logger.info("Initializing Terra Quilt mod...");

View File

@@ -32,7 +32,6 @@ import java.util.stream.Stream;
import com.dfsek.terra.addon.EphemeralAddon; import com.dfsek.terra.addon.EphemeralAddon;
import com.dfsek.terra.api.addon.BaseAddon; import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.util.generic.Lazy;
import com.dfsek.terra.lifecycle.LifecyclePlatform; import com.dfsek.terra.lifecycle.LifecyclePlatform;

View File

@@ -11,7 +11,7 @@ import java.lang.reflect.InvocationTargetException;
public class QuiltPreLaunchEntryPoint implements PreLaunchEntrypoint { public class QuiltPreLaunchEntryPoint implements PreLaunchEntrypoint {
@Override @Override
public void onPreLaunch(ModContainer mod) { public void onPreLaunch(ModContainer mod) {
if (QuiltLoader.isDevelopmentEnvironment()) { if(QuiltLoader.isDevelopmentEnvironment()) {
try { try {
AwfulQuiltHacks.hackilyLoadForMixin(BrigadierMappingBuilder.class.getName()); AwfulQuiltHacks.hackilyLoadForMixin(BrigadierMappingBuilder.class.getName());
} catch(ClassNotFoundException | InvocationTargetException | IllegalAccessException e) { } catch(ClassNotFoundException | InvocationTargetException | IllegalAccessException e) {