reformat all code

pull/329/head
dfsek 2 years ago
parent dc5e71e3de
commit b3a8f375bc
  1. 12
      .github/PULL_REQUEST_TEMPLATE.md
  2. 7
      CONTRIBUTING.md
  3. 44
      buildSrc/src/main/kotlin/AddonConfig.kt
  4. 4
      buildSrc/src/main/kotlin/DependencyConfig.kt
  5. 2
      buildSrc/src/main/kotlin/DistributionConfig.kt
  6. 4
      buildSrc/src/main/kotlin/Versions.kt
  7. 6
      common/addons/biome-provider-extrusion/src/main/java/com/dfsek/terra/addons/biome/extrusion/BiomeExtrusionProvider.java
  8. 16
      common/addons/biome-provider-extrusion/src/main/java/com/dfsek/terra/addons/biome/extrusion/api/ReplaceableBiome.java
  9. 8
      common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/BiomePipelineProvider.java
  10. 2
      common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/BiomeProviderTemplate.java
  11. 4
      common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/BiomeQueryAPIAddon.java
  12. 2
      common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/api/BiomeQueries.java
  13. 2
      common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/SingleTagQuery.java
  14. 12
      common/addons/chunk-generator-noise-3d/src/main/java/com/dfsek/terra/addons/chunkgenerator/NoiseChunkGenerator3DAddon.java
  15. 2
      common/addons/chunk-generator-noise-3d/src/main/java/com/dfsek/terra/addons/chunkgenerator/config/noise/ThreadLocalNoiseHolder.java
  16. 3
      common/addons/chunk-generator-noise-3d/src/main/java/com/dfsek/terra/addons/chunkgenerator/config/palette/BiomePaletteTemplate.java
  17. 4
      common/addons/chunk-generator-noise-3d/src/main/java/com/dfsek/terra/addons/chunkgenerator/generation/math/interpolation/ChunkInterpolator.java
  18. 1
      common/addons/chunk-generator-noise-3d/src/main/java/com/dfsek/terra/addons/chunkgenerator/generation/math/interpolation/LazilyEvaluatedInterpolator.java
  19. 2
      common/addons/chunk-generator-noise-3d/src/main/java/com/dfsek/terra/addons/chunkgenerator/generation/math/samplers/SamplerProvider.java
  20. 26
      common/addons/config-locators/src/main/java/com/dfsek/terra/addons/feature/locator/locators/SamplerLocator.java
  21. 11
      common/addons/config-noise-function/src/main/java/com/dfsek/terra/addons/noise/paralithic/defined/UserDefinedFunction.java
  22. 4
      common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/parser/Parser.java
  23. 8
      common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/parser/lang/Scope.java
  24. 1
      common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/parser/lang/constants/BooleanConstant.java
  25. 1
      common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/parser/lang/constants/NumericConstant.java
  26. 24
      common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/parser/lang/functions/Function.java
  27. 1
      common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/parser/lang/operations/BooleanOrOperation.java
  28. 20
      common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/parser/lang/operations/ConcatenationOperation.java
  29. 1
      common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/parser/lang/operations/ModuloOperation.java
  30. 1
      common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/parser/lang/operations/MultiplicationOperation.java
  31. 1
      common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/parser/lang/operations/NumberAdditionOperation.java
  32. 1
      common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/parser/lang/operations/SubtractionOperation.java
  33. 2
      common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/parser/lang/operations/statements/EqualsStatement.java
  34. 1
      common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/parser/lang/operations/statements/LessThanOrEqualsStatement.java
  35. 1
      common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/parser/lang/operations/statements/LessThanStatement.java
  36. 3
      common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/parser/lang/variables/assign/VariableAssignmentNode.java
  37. 2
      common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/parser/lang/variables/reference/VariableReferenceNode.java
  38. 3
      common/addons/structure-terrascript-loader/src/test/java/structure/ParserTest.java
  39. 14
      common/api/src/main/java/com/dfsek/terra/api/properties/Context.java
  40. 2
      common/api/src/main/java/com/dfsek/terra/api/util/GeometryUtil.java
  41. 51
      common/api/src/main/java/com/dfsek/terra/api/util/generic/pair/Pair.java
  42. 2
      common/api/src/main/java/com/dfsek/terra/api/world/biome/generation/BiomeProvider.java
  43. 6
      common/api/src/main/java/com/dfsek/terra/api/world/biome/generation/CachingBiomeProvider.java
  44. 2
      common/api/src/main/java/com/dfsek/terra/api/world/chunk/generation/util/Column.java
  45. 4
      common/api/src/main/java/com/dfsek/terra/api/world/util/Interceptors.java
  46. 6
      common/api/src/test/java/util/ColumnTest.java
  47. 3
      common/implementation/base/src/main/java/com/dfsek/terra/config/pack/ConfigPackImpl.java
  48. 6
      common/implementation/base/src/test/java/registry/RegistryTest.java
  49. 3
      common/implementation/bootstrap-addon-loader/src/main/java/com/dfsek/terra/addon/BootstrapAddonLoader.java
  50. 1
      gradle.properties
  51. 2
      platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java
  52. 39
      platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitChunkGeneratorWrapper.java
  53. 4
      platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/nms/Initializer.java
  54. 2
      platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/inventory/meta/BukkitDamageable.java
  55. 63
      platforms/bukkit/nms/v1_18_R2/src/main/java/com/dfsek/terra/bukkit/nms/v1_18_R2/AwfulBukkitHacks.java
  56. 45
      platforms/bukkit/nms/v1_18_R2/src/main/java/com/dfsek/terra/bukkit/nms/v1_18_R2/NMSBiomeInjector.java
  57. 18
      platforms/bukkit/nms/v1_18_R2/src/main/java/com/dfsek/terra/bukkit/nms/v1_18_R2/NMSChunkGeneratorDelegate.java
  58. 7
      platforms/bukkit/nms/v1_18_R2/src/main/java/com/dfsek/terra/bukkit/nms/v1_18_R2/NMSInjectListener.java
  59. 5
      platforms/bukkit/nms/v1_18_R2/src/main/java/com/dfsek/terra/bukkit/nms/v1_18_R2/Reflection.java
  60. 76
      platforms/bukkit/nms/v1_19_R1/src/main/java/com/dfsek/terra/bukkit/nms/v1_19_R1/AwfulBukkitHacks.java
  61. 16
      platforms/bukkit/nms/v1_19_R1/src/main/java/com/dfsek/terra/bukkit/nms/v1_19_R1/NMSBiomeInjector.java
  62. 11
      platforms/bukkit/nms/v1_19_R1/src/main/java/com/dfsek/terra/bukkit/nms/v1_19_R1/NMSBiomeProvider.java
  63. 22
      platforms/bukkit/nms/v1_19_R1/src/main/java/com/dfsek/terra/bukkit/nms/v1_19_R1/NMSChunkGeneratorDelegate.java
  64. 7
      platforms/bukkit/nms/v1_19_R1/src/main/java/com/dfsek/terra/bukkit/nms/v1_19_R1/NMSInjectListener.java
  65. 4
      platforms/bukkit/nms/v1_19_R1/src/main/java/com/dfsek/terra/bukkit/nms/v1_19_R1/Reflection.java
  66. 4
      platforms/bukkit/nms/v1_19_R1/src/main/java/com/dfsek/terra/bukkit/nms/v1_19_R1/Registries.java
  67. 4
      platforms/cli/src/main/java/com/dfsek/terra/cli/block/CLIBlockState.java
  68. 8
      platforms/fabric/build.gradle.kts
  69. 5
      platforms/fabric/src/main/java/com/dfsek/terra/fabric/FabricAddon.java
  70. 2
      platforms/fabric/src/main/java/com/dfsek/terra/fabric/FabricEntryPoint.java
  71. 9
      platforms/fabric/src/main/java/com/dfsek/terra/fabric/FabricPlatform.java
  72. 2
      platforms/forge/build.gradle.kts
  73. 75
      platforms/forge/src/main/java/com/dfsek/terra/forge/AwfulForgeHacks.java
  74. 5
      platforms/forge/src/main/java/com/dfsek/terra/forge/ForgeAddon.java
  75. 26
      platforms/forge/src/main/java/com/dfsek/terra/forge/ForgeEntryPoint.java
  76. 37
      platforms/forge/src/main/java/com/dfsek/terra/forge/ForgePlatform.java
  77. 10
      platforms/forge/src/main/java/com/dfsek/terra/forge/mixin/lifecycle/NoiseConfigMixin.java
  78. 33
      platforms/forge/src/main/java/com/dfsek/terra/forge/util/BiomeUtil.java
  79. 2
      platforms/forge/src/main/resources/META-INF/mods.toml
  80. 8
      platforms/forge/src/main/resources/pack.mcmeta
  81. 2
      platforms/forge/src/main/resources/terra.forge.mixins.json
  82. 8
      platforms/mixin-common/src/main/java/com/dfsek/terra/mod/MinecraftAddon.java
  83. 38
      platforms/mixin-common/src/main/java/com/dfsek/terra/mod/ModPlatform.java
  84. 2
      platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/BiomeAdditionsSoundTemplate.java
  85. 2
      platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/BiomeMoodSoundTemplate.java
  86. 4
      platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/BiomeParticleConfigTemplate.java
  87. 2
      platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/MusicSoundTemplate.java
  88. 4
      platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SoundEventTemplate.java
  89. 6
      platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/SpawnSettingsTemplate.java
  90. 2
      platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/VanillaBiomeProperties.java
  91. 1
      platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/VillagerTypeTemplate.java
  92. 4
      platforms/mixin-common/src/main/java/com/dfsek/terra/mod/data/Codecs.java
  93. 1
      platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/access/VillagerTypeAccessor.java
  94. 3
      platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/fix/BeeMoveGoalsUnsynchronizedRandomAccessFix.java
  95. 5
      platforms/mixin-common/src/main/java/com/dfsek/terra/mod/mixin/fix/NetherFossilOptimization.java
  96. 83
      platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/MinecraftUtil.java
  97. 14
      platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/PresetUtil.java
  98. 92
      platforms/mixin-common/src/main/resources/terra.common.mixins.json
  99. 8
      platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/LifecyclePlatform.java
  100. 6
      platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/NoiseConfigMixin.java
  101. Some files were not shown because too many files have changed in this diff Show More

@ -72,15 +72,19 @@
- [ ] Bug Fix <!-- Anything which fixes an issue in Terra. -->
- [ ] 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. -->
- [ ] 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. -->
- [ ] Style <!-- Anything which updates style. -->
- [ ] 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

@ -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!!!
> **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
@ -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)
.
> **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

@ -12,30 +12,30 @@ import kotlin.streams.asStream
*/
fun Project.addonDir(dir: File, task: Task) {
val moveAddons = tasks.register("moveAddons" + task.name) {
dependsOn("compileAddons")
doLast {
dir.parentFile.mkdirs()
matchingAddons(dir) {
it.name.startsWith("Terra-") // Assume everything that starts with Terra- is a core addon.
}.forEach {
println("Deleting old addon: " + it.absolutePath)
it.delete()
}
forSubProjects(":common:addons") {
val jar = tasks.named("shadowJar").get() as ShadowJar
val boot = if (extra.has("bootstrap") && extra.get("bootstrap") as Boolean) "bootstrap/" else ""
val target = File(dir, boot + jar.archiveFileName.get())
val base = "${jar.archiveBaseName.get()}-${version}"
println("Copying addon ${jar.archiveFileName.get()} to ${target.absolutePath}. Base name: $base")
jar.archiveFile.orNull?.asFile?.copyTo(target)
}
dependsOn("compileAddons")
doLast {
dir.parentFile.mkdirs()
matchingAddons(dir) {
it.name.startsWith("Terra-") // Assume everything that starts with Terra- is a core addon.
}.forEach {
println("Deleting old addon: " + it.absolutePath)
it.delete()
}
forSubProjects(":common:addons") {
val jar = tasks.named("shadowJar").get() as ShadowJar
val boot = if (extra.has("bootstrap") && extra.get("bootstrap") as Boolean) "bootstrap/" else ""
val target = File(dir, boot + jar.archiveFileName.get())
val base = "${jar.archiveBaseName.get()}-${version}"
println("Copying addon ${jar.archiveFileName.get()} to ${target.absolutePath}. Base name: $base")
jar.archiveFile.orNull?.asFile?.copyTo(target)
}
}
}
task.dependsOn(moveAddons)
}

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

@ -53,7 +53,7 @@ fun Project.configureDistribution() {
val boot = if (extra.has("bootstrap") && extra.get("bootstrap") as Boolean) "bootstrap/" else ""
val addonPath = fs.getPath("/addons/$boot${jar.archiveFileName.get()}")
if (!Files.exists(addonPath)) {
Files.createDirectories(addonPath.parent)
Files.createFile(addonPath)

@ -33,10 +33,10 @@ object Versions {
const val minecraft = "1.19"
const val yarn = "$minecraft+build.1"
const val fabricLoader = "0.14.2"
const val architecuryLoom = "0.12.0-SNAPSHOT"
const val architecturyPlugin = "3.4-SNAPSHOT"
const val loomQuiltflower = "1.7.1"
const val lazyDfu = "0.1.2"

@ -28,7 +28,7 @@ public class BiomeExtrusionProvider implements BiomeProvider {
@Override
public Biome getBiome(int x, int y, int z, long seed) {
Biome delegated = delegate.getBiome(x, y, z, seed);
return extrude(delegated, x, y, z, seed);
}
@ -42,8 +42,8 @@ public class BiomeExtrusionProvider implements BiomeProvider {
@Override
public Column<Biome> getColumn(int x, int z, long seed, int min, int max) {
return delegate.getBaseBiome(x, z, seed)
.map(base -> (Column<Biome>) new BaseBiomeColumn(this, base, min, max, x, z, seed))
.orElseGet(() -> BiomeProvider.super.getColumn(x, z, seed, min, max));
.map(base -> (Column<Biome>) new BaseBiomeColumn(this, base, min, max, x, z, seed))
.orElseGet(() -> BiomeProvider.super.getColumn(x, z, seed, min, max));
}
@Override

@ -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.
*/
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);
default Biome get() {
@ -20,12 +28,4 @@ public sealed interface ReplaceableBiome permits PresentBiome, SelfBiome {
}
boolean isSelf();
static ReplaceableBiome of(Biome biome) {
return new PresentBiome(biome);
}
static ReplaceableBiome self() {
return SelfBiome.INSTANCE;
}
}

@ -81,11 +81,11 @@ public class BiomePipelineProvider implements BiomeProvider {
public Biome getBiome(int x, int z, long seed) {
x += mutator.noise(seed + 1, x, z) * noiseAmp;
z += mutator.noise(seed + 2, x, z) * noiseAmp;
x /= resolution;
z /= resolution;
int fdX = FastMath.floorDiv(x, pipeline.getSize());
int fdZ = FastMath.floorDiv(z, pipeline.getSize());
return holderCache.get(new SeededVector(fdX, fdZ, seed)).getBiome(x - fdX * pipeline.getSize(),
@ -120,7 +120,7 @@ public class BiomePipelineProvider implements BiomeProvider {
}
return false;
}
@Override
public int hashCode() {
int code = x;

@ -22,7 +22,7 @@ public abstract class BiomeProviderTemplate implements ObjectTemplate<BiomeProvi
@Default
@Description("""
The resolution at which to sample biomes.
Larger values are quadratically faster, but produce lower quality results.
For example, a value of 3 would sample every 3 blocks.""")
protected @Meta int resolution = 1;

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

@ -8,7 +8,7 @@ import com.dfsek.terra.api.world.biome.Biome;
public final class BiomeQueries {
private BiomeQueries() {
}
public static Predicate<Biome> has(String tag) {

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

@ -49,9 +49,9 @@ public class NoiseChunkGenerator3DAddon implements AddonInitializer {
.getOrCreateRegistry(ChunkGeneratorProvider.class)
.register(addon.key("NOISE_3D"),
pack -> new NoiseChunkGenerator3D(pack, platform, config.getElevationBlend(),
config.getHorizontalRes(),
config.getVerticalRes(), noisePropertiesPropertyKey,
paletteInfoPropertyKey));
config.getHorizontalRes(),
config.getVerticalRes(), noisePropertiesPropertyKey,
paletteInfoPropertyKey));
event.getPack()
.applyLoader(SlantLayer.class, SlantLayer::new);
})
@ -62,8 +62,10 @@ public class NoiseChunkGenerator3DAddon implements AddonInitializer {
.register(addon, ConfigurationLoadEvent.class)
.then(event -> {
if(event.is(Biome.class)) {
event.getLoadedObject(Biome.class).getContext().put(paletteInfoPropertyKey, event.load(new BiomePaletteTemplate(platform)).get());
event.getLoadedObject(Biome.class).getContext().put(noisePropertiesPropertyKey, event.load(new BiomeNoiseConfigTemplate()).get());
event.getLoadedObject(Biome.class).getContext().put(paletteInfoPropertyKey,
event.load(new BiomePaletteTemplate(platform)).get());
event.getLoadedObject(Biome.class).getContext().put(noisePropertiesPropertyKey,
event.load(new BiomeNoiseConfigTemplate()).get());
}
})
.failThrough();

@ -12,7 +12,7 @@ public class ThreadLocalNoiseHolder {
if(holder.init && holder.y == y && holder.z == z && holder.x == x && holder.seed == seed) {
return holder.noise;
}
double noise = sampler.noise(seed, x, y, z);
holder.noise = noise;
holder.x = x;

@ -83,6 +83,7 @@ public class BiomePaletteTemplate implements ObjectTemplate<PaletteInfo> {
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);
}
}

@ -87,10 +87,10 @@ public class ChunkInterpolator {
for(int zi = -blend; zi <= blend; zi++) {
int blendX = (xi * step);
int blendZ = (zi * step);
int localIndex = (scaledX + maxBlend + blendX) + maxBlendAndChunk * (scaledZ + maxBlend + blendZ);
Column<Biome> column = columns[localIndex];
if(column == null) {
column = provider.getColumn(absoluteX + blendX, absoluteZ + blendZ, seed, min, max);
columns[localIndex] = column;

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

@ -53,7 +53,7 @@ public class SamplerProvider {
public Sampler3D getChunk(int cx, int cz, WorldProperties world, BiomeProvider provider) {
WorldContext context = new WorldContext(cx, cz, world.getSeed(), world.getMinHeight(), world.getMaxHeight());
return cache.get(context, c -> new Sampler3D(c.cx, c.cz, c.seed, c.minHeight, c.maxHeight, provider,
elevationSmooth, noisePropertiesKey, maxBlend));
elevationSmooth, noisePropertiesKey, maxBlend));
}
private record WorldContext(int cx, int cz, long seed, int minHeight, int maxHeight) {

@ -23,6 +23,19 @@ public class SamplerLocator implements Locator {
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
public BinaryColumn getSuitableCoordinates(Column<?> column) {
BinaryColumnBuilder results = column.newBinaryColumn();
@ -36,17 +49,4 @@ public class SamplerLocator implements Locator {
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;
}
}
}

@ -23,11 +23,10 @@ import com.dfsek.terra.addons.noise.config.templates.FunctionTemplate;
public class UserDefinedFunction implements DynamicFunction {
private static final Map<FunctionTemplate, UserDefinedFunction> CACHE = new HashMap<>();
private final Expression expression;
private final int args;
private static final Map<FunctionTemplate, UserDefinedFunction> CACHE = new HashMap<>();
protected UserDefinedFunction(Expression expression, int args) {
this.expression = expression;
this.args = args;
@ -38,17 +37,17 @@ public class UserDefinedFunction implements DynamicFunction {
if(function == null) {
Parser parser = new Parser();
Scope parent = new Scope();
Scope functionScope = new Scope().withParent(parent);
template.getArgs().forEach(functionScope::addInvocationVariable);
for(Entry<String, FunctionTemplate> entry : template.getFunctions().entrySet()) {
String id = entry.getKey();
FunctionTemplate nest = entry.getValue();
parser.registerFunction(id, newInstance(nest));
}
function = new UserDefinedFunction(parser.parse(template.getFunction(), functionScope), template.getArgs().size());
CACHE.put(template, function);
}

@ -338,9 +338,9 @@ public class Parser {
Returnable<?> value = parseExpression(tokens, true, scopeBuilder);
ParserUtil.checkReturnType(value, returnType);
String id = identifier.getContent();
return switch(value.returnType()) {
case NUMBER -> new NumAssignmentNode((Returnable<Number>) value, identifier.getPosition(), scopeBuilder.num(id));
case STRING -> new StrAssignmentNode((Returnable<String>) value, identifier.getPosition(), scopeBuilder.str(id));

@ -46,9 +46,8 @@ public class Scope {
}
public static final class ScopeBuilder {
private int numSize, boolSize, strSize = 0;
private final Map<String, Pair<Integer, ReturnType>> indices;
private int numSize, boolSize, strSize = 0;
private ScopeBuilder parent;
public ScopeBuilder() {
@ -77,6 +76,7 @@ public class Scope {
}
return id;
}
public int num(String id) {
int num = numSize;
indices.put(check(id), Pair.of(num, ReturnType.NUMBER));
@ -107,14 +107,14 @@ public class Scope {
parent.updateBoolSize(size);
}
}
private void updateNumSize(int size) {
this.numSize = FastMath.max(numSize, size);
if(parent != null) {
parent.updateNumSize(size);
}
}
private void updateStrSize(int size) {
this.strSize = FastMath.max(strSize, size);
if(parent != null) {

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

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

@ -14,30 +14,30 @@ import com.dfsek.terra.addons.terrascript.tokenizer.Position;
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<>() {
@Override
public ReturnType returnType() {
return null;
}
@Override
public Object apply(ImplementationArguments implementationArguments, Scope scope) {
return null;
}
@Override
public Position getPosition() {
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);
}
}

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

@ -18,16 +18,6 @@ public class ConcatenationOperation extends BinaryOperation<Object, Object> {
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) {
String s = object.toString();
if(object instanceof Double) {
@ -38,4 +28,14 @@ public class ConcatenationOperation extends BinaryOperation<Object, Object> {
}
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));
}
}

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

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

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

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

@ -42,7 +42,7 @@ public class EqualsStatement extends BinaryOperation<Object, Boolean> {
if(leftValue instanceof Number l && rightValue instanceof Number r) {
return FastMath.abs(l.doubleValue() - r.doubleValue()) <= EPSILON;
}
return leftValue.equals(rightValue);
}
}

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

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

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

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

@ -30,7 +30,8 @@ import com.dfsek.terra.addons.terrascript.tokenizer.Position;
public class ParserTest {
@Test
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>() {
@Override

@ -14,10 +14,15 @@ import java.util.concurrent.atomic.AtomicReference;
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 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")
public <T extends Properties> T get(Class<T> clazz) {
@ -33,11 +38,6 @@ public class Context {
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) {
list.updateAndGet(p -> {
if(p.length == size.get()) return p;

@ -7,7 +7,7 @@ import com.dfsek.terra.api.util.vector.Vector3Int;
public final class GeometryUtil {
private GeometryUtil() {
}
public static void sphere(Vector3Int origin, int radius, Consumer<Vector3Int> action) {

@ -22,6 +22,11 @@ public final class Pair<L, R> {
private final L left;
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) {
return pair -> of(function.apply(pair.left), pair.right);
}
@ -54,11 +59,6 @@ public final class Pair<L, R> {
return pair -> pair.left;
}
private Pair(L left, R right) {
this.left = left;
this.right = right;
}
@Contract("_, _ -> new")
public static <L1, R1> Pair<L1, R1> of(L1 left, R1 right) {
return new Pair<>(left, right);
@ -96,62 +96,63 @@ public final class Pair<L, R> {
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> {
private L left;
private R right;
private Mutable(L left, R right) {
this.left = left;
this.right = right;
}
@NotNull
@Contract("_, _ -> new")
public static <L1, R1> Pair.Mutable<L1, R1> of(L1 left, R1 right) {
return new Mutable<>(left, right);
}
@Contract("-> new")
public Pair<L, R> immutable() {
return Pair.of(left, right);
}
public L getLeft() {
return left;
}
public void setLeft(L left) {
this.left = left;
}
public R getRight() {
return right;
}
public void setRight(R right) {
this.right = right;
}
@Override
public int hashCode() {
return Objects.hash(left, right);
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Mutable<?, ?> that)) return false;
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);
}
}

@ -97,7 +97,7 @@ public interface BiomeProvider {
}
return new CachingBiomeProvider(this);
}
default int resolution() {
return 1;

@ -30,12 +30,12 @@ public class CachingBiomeProvider implements BiomeProvider, Handle {
.initialCapacity(98304)
.maximumSize(98304) // 1 full chunk (high res)
.build(vec -> delegate.getBiome(vec.x * res, vec.y * res, vec.z * res, vec.seed));
this.baseCache = Caffeine
.newBuilder()
.maximumSize(256) // 1 full chunk (high res)
.build(vec -> delegate.getBaseBiome(vec.x * res, vec.z * res, vec.seed));
}
@Override
@ -80,6 +80,8 @@ public class CachingBiomeProvider implements BiomeProvider, Handle {
return 31 * code + ((int) (seed ^ (seed >>> 32)));
}
}
private record SeededVector2(int x, int z, long seed) {
@Override
public boolean equals(Object obj) {

@ -38,7 +38,7 @@ public class Column<T extends WritableWorld> {
this.max = max;
this.min = min;
}
public int getX() {
return x;

@ -4,9 +4,9 @@ public final class Interceptors {
private static final ReadInterceptor READ_THROUGH = ((x, y, z, world) -> world.getBlockState(x, y, z));
private static final WriteInterceptor WRITE_THROUGH = ((x, y, z, block, world, physics) -> world.setBlockState(x, y, z, block,
physics));
private Interceptors() {
}
public static ReadInterceptor readThrough() {

@ -86,17 +86,17 @@ public class ColumnTest {
public int getMaxY() {
return max;
}
@Override
public int getX() {
return 0;
}
@Override
public int getZ() {
return 0;
}
@Override
public T get(int y) {
return p.apply(y);

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

@ -50,7 +50,7 @@ public class RegistryTest {
test.registerChecked(RegistryKey.parse("test:test"), "bazinga2");
fail("Shouldn't be able to re-register with #registerChecked!");
} catch(DuplicateEntryException ignore) {
}
}
@ -66,7 +66,7 @@ public class RegistryTest {
test.register(RegistryKey.parse("test:test"), "bazinga2");
fail("Shouldn't be able to re-register in CheckedRegistry!");
} catch(DuplicateEntryException ignore) {
}
}
@ -90,7 +90,7 @@ public class RegistryTest {
test.getByID("test");
fail("Shouldn't be able to get with ambiguous ID!");
} catch(IllegalArgumentException ignore) {
}
}
}

@ -84,7 +84,7 @@ public class BootstrapAddonLoader implements BootstrapBaseAddon<BootstrapBaseAdd
Path bootstrapFolder = addonsFolder.resolve("bootstrap");
Files.createDirectories(bootstrapFolder);
logger.debug("Loading bootstrap addons from {}", bootstrapFolder);
try(Stream<Path> bootstrapAddons = Files.walk(bootstrapFolder, 1, FileVisitOption.FOLLOW_LINKS)) {
return bootstrapAddons.filter(path -> path.toFile().isFile())
.filter(path -> path.toFile().canRead())
@ -96,6 +96,7 @@ public class BootstrapAddonLoader implements BootstrapBaseAddon<BootstrapBaseAdd
throw new UncheckedIOException(e);
}
}
@Override
public String getID() {
return "BOOTSTRAP";

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

@ -91,7 +91,7 @@ public class TerraBukkitPlugin extends JavaPlugin {
Bukkit.getPluginManager().registerEvents(new CommonListener(), this); // Register master event listener
PaperUtil.checkPaper(this);
Initializer.init(platform);
}

@ -46,23 +46,7 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener
private ChunkGenerator delegate;
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) {
this.delegate = delegate;
this.pack = pack;
@ -108,13 +92,12 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener
public boolean shouldGenerateDecorations() {
return true;
}
@Override
public boolean shouldGenerateMobs() {
return true;
}
@Override
public boolean shouldGenerateStructures() {
return true;
@ -133,4 +116,22 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener
public ChunkGenerator getHandle() {
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();
}
}
}

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

@ -17,8 +17,6 @@
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.bukkit.world.inventory.BukkitItemMeta;

@ -1,8 +1,5 @@
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.mojang.serialization.Lifecycle;
import net.minecraft.core.Holder;
@ -23,6 +20,9 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.registry.master.ConfigRegistry;
public class AwfulBukkitHacks {
private static final Logger LOGGER = LoggerFactory.getLogger(NMSBiomeInjector.class);
@ -44,9 +44,11 @@ public class AwfulBukkitHacks {
Biome platform = NMSBiomeInjector.createBiome(
biome,
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);
biomeRegistry.register(delegateKey, platform, Lifecycle.stable());
@ -73,28 +75,35 @@ public class AwfulBukkitHacks {
terraBiomeMap
.forEach((vb, terraBiomes) ->
NMSBiomeInjector.getEntry(biomeRegistry, vb)
.ifPresentOrElse(
vanilla -> terraBiomes
.forEach(tb -> NMSBiomeInjector.getEntry(biomeRegistry, tb)
.ifPresentOrElse(
terra -> {
LOGGER.debug(vanilla.unwrapKey().orElseThrow().location() +
" (vanilla for " +
terra.unwrapKey().orElseThrow().location() +
": " +
vanilla.tags().toList());
vanilla.tags()
.forEach(
tag -> collect
.computeIfAbsent(tag,
t -> new ArrayList<>())
.add(terra));
},
() -> LOGGER.error(
"No such biome: {}",
tb))),
() -> LOGGER.error("No vanilla biome: {}", vb)));
.ifPresentOrElse(
vanilla -> terraBiomes
.forEach(tb -> NMSBiomeInjector.getEntry(biomeRegistry, tb)
.ifPresentOrElse(
terra -> {
LOGGER.debug(
vanilla.unwrapKey()
.orElseThrow()
.location() +
" (vanilla for " +
terra.unwrapKey()
.orElseThrow()
.location() +
": " +
vanilla.tags()
.toList());
vanilla.tags()
.forEach(
tag -> collect
.computeIfAbsent(
tag,
t -> new ArrayList<>())
.add(terra));
},
() -> LOGGER.error(
"No such biome: {}",
tb))),
() -> LOGGER.error("No vanilla biome: {}", vb)));
biomeRegistry.resetTags(); // clearTags
biomeRegistry.bindTags(ImmutableMap.copyOf(collect)); // populateTags

@ -1,33 +1,17 @@
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.MappedRegistry;
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.tags.TagKey;
import net.minecraft.world.level.biome.Biome;
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.Map;
import java.util.Objects;
import java.util.Optional;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.bukkit.config.VanillaBiomeProperties;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.registry.master.ConfigRegistry;
public class NMSBiomeInjector {
@ -45,33 +29,32 @@ public class NMSBiomeInjector {
builder.biomeCategory(Reflection.BIOME.getBiomeCategory(vanilla))
.precipitation(vanilla.getPrecipitation()) // getPrecipitation
.mobSpawnSettings(vanilla.getMobSettings())
.generationSettings(vanilla.getGenerationSettings())
.temperature(vanilla.getBaseTemperature())
.downfall(vanilla.getDownfall());
.mobSpawnSettings(vanilla.getMobSettings())
.generationSettings(vanilla.getGenerationSettings())
.temperature(vanilla.getBaseTemperature())
.downfall(vanilla.getDownfall());
BiomeSpecialEffects.Builder effects = new BiomeSpecialEffects.Builder();
effects.grassColorModifier(vanilla.getSpecialEffects().getGrassColorModifier());
VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class);
effects.fogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanilla.getFogColor()))
.waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.getWaterColor()))
.waterFogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterFogColor(), vanilla.getWaterFogColor()))
.skyColor(Objects.requireNonNullElse(vanillaBiomeProperties.getSkyColor(), vanilla.getSkyColor()));
if(vanillaBiomeProperties.getFoliageColor() == null) {
vanilla.getSpecialEffects().getFoliageColorOverride().ifPresent(effects::foliageColorOverride);
} else {
effects.foliageColorOverride(vanillaBiomeProperties.getFoliageColor());
}
if(vanillaBiomeProperties.getGrassColor() == null) {
vanilla.getSpecialEffects().getGrassColorOverride().ifPresent(effects::grassColorOverride);
} else {
@ -83,7 +66,7 @@ public class NMSBiomeInjector {
vanilla.getAmbientMood().ifPresent(effects::ambientMoodSound);
vanilla.getBackgroundMusic().ifPresent(effects::backgroundMusic);
vanilla.getAmbientParticle().ifPresent(effects::ambientParticle);
builder.specialEffects(effects.build());
return builder.build(); // build()

@ -49,17 +49,14 @@ import com.dfsek.terra.api.world.info.WorldProperties;
public class NMSChunkGeneratorDelegate extends ChunkGenerator {
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 com.dfsek.terra.api.world.chunk.generation.ChunkGenerator delegate;
private final ChunkGenerator vanilla;
private final ConfigPack pack;
private final long seed;
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) {
super(Registries.structureSet(), Optional.empty(), biomeProvider, biomeProvider, seed);
@ -71,13 +68,15 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
}
@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) {
// no-op
}
@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);
}
@ -87,7 +86,8 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
}
@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) {
return vanilla.fillFromNoise(executor, blender, structureAccessor, chunk);
}
@ -161,8 +161,6 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
return ringPositions.getOrDefault(concentricringsstructureplacement, EMPTY).value();
}
private volatile boolean rings = false;
@Override
public synchronized void ensureStructuresGenerated() {
if(!this.rings) {

@ -25,15 +25,16 @@ public class NMSInjectListener implements Listener {
@EventHandler
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();
INJECTED.add(event.getWorld());
LOGGER.info("Preparing to take over the world: {}", event.getWorld().getName());
CraftWorld craftWorld = (CraftWorld) event.getWorld();
ServerLevel serverWorld = craftWorld.getHandle();
ConfigPack pack = bukkitChunkGeneratorWrapper.getPack();
ChunkGenerator vanilla = serverWorld.getChunkSource().getGenerator();
NMSBiomeProvider provider = new NMSBiomeProvider(pack.getBiomeProvider(), vanilla.getBiomeSource(), craftWorld.getSeed());
NMSChunkGeneratorDelegate custom = new NMSChunkGeneratorDelegate(vanilla, pack, provider, craftWorld.getSeed());

@ -15,18 +15,21 @@ public class Reflection {
static {
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);
BIOME = reflectionProxyFactory.reflectionProxy(BiomeProxy.class);
}
@Proxies(MappedRegistry.class)
public interface MappedRegistryProxy {
@FieldSetter("frozen")
void setFrozen(MappedRegistry<?> instance, boolean frozen);
}
@Proxies(Biome.class)
public interface BiomeProxy {
@FieldGetter("biomeCategory")

@ -1,7 +1,5 @@
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.mojang.serialization.Lifecycle;
import net.minecraft.core.Holder;
@ -17,7 +15,15 @@ import org.bukkit.NamespacedKey;
import org.slf4j.Logger;
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 {
private static final Logger LOGGER = LoggerFactory.getLogger(AwfulBukkitHacks.class);
@ -39,10 +45,11 @@ public class AwfulBukkitHacks {
Biome platform = NMSBiomeInjector.createBiome(
biome,
Objects.requireNonNull(biomeRegistry.get(vanillaMinecraftKey)) // get
);
);
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);
biomeRegistry.register(delegateKey, platform, Lifecycle.stable());
@ -62,35 +69,42 @@ public class AwfulBukkitHacks {
Map<TagKey<Biome>, List<Holder<Biome>>> collect = biomeRegistry
.getTags() // streamKeysAndEntries
.collect(HashMap::new,
(map, pair) ->
map.put(pair.getFirst(), new ArrayList<>(pair.getSecond().stream().toList())),
HashMap::putAll);
(map, pair) ->
map.put(pair.getFirst(), new ArrayList<>(pair.getSecond().stream().toList())),
HashMap::putAll);
terraBiomeMap
.forEach((vb, terraBiomes) ->
NMSBiomeInjector.getEntry(biomeRegistry, vb)
.ifPresentOrElse(
vanilla -> terraBiomes
.forEach(tb -> NMSBiomeInjector.getEntry(biomeRegistry, tb)
.ifPresentOrElse(
terra -> {
LOGGER.debug(vanilla.unwrapKey().orElseThrow().location() +
" (vanilla for " +
terra.unwrapKey().orElseThrow().location() +
": " +
vanilla.tags().toList());
vanilla.tags()
.forEach(
tag -> collect
.computeIfAbsent(tag,
t -> new ArrayList<>())
.add(terra));
},
() -> LOGGER.error(
"No such biome: {}",
tb))),
() -> LOGGER.error("No vanilla biome: {}", vb)));
NMSBiomeInjector.getEntry(biomeRegistry, vb)
.ifPresentOrElse(
vanilla -> terraBiomes
.forEach(tb -> NMSBiomeInjector.getEntry(biomeRegistry, tb)
.ifPresentOrElse(
terra -> {
LOGGER.debug(
vanilla.unwrapKey()
.orElseThrow()
.location() +
" (vanilla for " +
terra.unwrapKey()
.orElseThrow()
.location() +
": " +
vanilla.tags()
.toList());
vanilla.tags()
.forEach(
tag -> collect
.computeIfAbsent(
tag,
t -> new ArrayList<>())
.add(terra));
},
() -> LOGGER.error(
"No such biome: {}",
tb))),
() -> LOGGER.error("No vanilla biome: {}", vb)));
biomeRegistry.resetTags();
biomeRegistry.bindTags(ImmutableMap.copyOf(collect));

@ -1,33 +1,17 @@
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.MappedRegistry;
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.tags.TagKey;
import net.minecraft.world.level.biome.Biome;
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.Map;
import java.util.Objects;
import java.util.Optional;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.bukkit.config.VanillaBiomeProperties;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.registry.master.ConfigRegistry;
public class NMSBiomeInjector {

@ -18,7 +18,11 @@ public class NMSBiomeProvider extends BiomeSource {
private final Registry<Biome> biomeRegistry = Registries.biomeRegistry();
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.seed = seed;
}
@ -30,6 +34,9 @@ public class NMSBiomeProvider extends BiomeSource {
@Override
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());
}
}

@ -55,6 +55,8 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
private final ConfigPack pack;
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) {
super(Registries.structureSet(), Optional.empty(), biomeProvider);
@ -137,19 +139,16 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
.getHandle()).getState();
}
return new NoiseColumn(getMinY(), array);
*/
return vanilla.getBaseColumn(x, z, world, noiseConfig);
}
@Override
public void addDebugScreenInfo(@NotNull List<String> text, @NotNull RandomState noiseConfig, @NotNull BlockPos pos) {
}
private volatile boolean rings = false;
private final Map<ConcentricRingsStructurePlacement, Lazy<List<ChunkPos>>> ringPositions = new Object2ObjectArrayMap<>();
@Override
public void ensureStructuresGenerated(@NotNull RandomState noiseConfig) {
if(!this.rings) {
@ -161,7 +160,8 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
}
@Override
public List<ChunkPos> getRingPositionsFor(@NotNull ConcentricRingsStructurePlacement structurePlacement, @NotNull RandomState noiseConfig) {
public List<ChunkPos> getRingPositionsFor(@NotNull ConcentricRingsStructurePlacement structurePlacement,
@NotNull RandomState noiseConfig) {
ensureStructuresGenerated(noiseConfig);
return ringPositions.get(structurePlacement).value();
}
@ -179,13 +179,15 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
}
}
if (match) {
if (holder.placement() instanceof ConcentricRingsStructurePlacement concentricringsstructureplacement) {
this.ringPositions.put(concentricringsstructureplacement, Lazy.lazy(() -> this.generateRingPositions(holder, noiseConfig, concentricringsstructureplacement)));
if(match) {
if(holder.placement() instanceof ConcentricRingsStructurePlacement concentricringsstructureplacement) {
this.ringPositions.put(concentricringsstructureplacement, Lazy.lazy(
() -> this.generateRingPositions(holder, noiseConfig, concentricringsstructureplacement)));
}
}
});
}
private List<ChunkPos> generateRingPositions(StructureSet holder, RandomState randomstate,
ConcentricRingsStructurePlacement concentricringsstructureplacement) { // Spigot
if(concentricringsstructureplacement.count() == 0) {

@ -25,15 +25,16 @@ public class NMSInjectListener implements Listener {
@EventHandler
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();
INJECTED.add(event.getWorld());
LOGGER.info("Preparing to take over the world: {}", event.getWorld().getName());
CraftWorld craftWorld = (CraftWorld) event.getWorld();
ServerLevel serverWorld = craftWorld.getHandle();
ConfigPack pack = bukkitChunkGeneratorWrapper.getPack();
ChunkGenerator vanilla = serverWorld.getChunkSource().getGenerator();
NMSBiomeProvider provider = new NMSBiomeProvider(pack.getBiomeProvider(), craftWorld.getSeed());
NMSChunkGeneratorDelegate custom = new NMSChunkGeneratorDelegate(vanilla, pack, provider, craftWorld.getSeed());

@ -12,11 +12,13 @@ public class Reflection {
static {
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);
}
@Proxies(MappedRegistry.class)
public interface MappedRegistryProxy {
@FieldSetter("frozen")

@ -16,8 +16,8 @@ public class Registries {
return dedicatedserver
.registryAccess()
.registryOrThrow( // getRegistry
key
);
key
);
}
public static Registry<Biome> biomeRegistry() {

@ -16,9 +16,9 @@ public class CLIBlockState implements BlockState {
public CLIBlockState(String value) {
this.value = value;
if(value.contains("[")) {
} else {
}
this.isAir = value.startsWith("minecraft:air");
this.nbt = new CompoundTag();

@ -25,7 +25,13 @@ dependencies {
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)
modImplementation(module)
include(module)

@ -3,12 +3,13 @@ package com.dfsek.terra.fabric;
import com.dfsek.terra.mod.MinecraftAddon;
import com.dfsek.terra.mod.ModPlatform;
public class FabricAddon extends MinecraftAddon {
public class FabricAddon extends MinecraftAddon {
public FabricAddon(ModPlatform modPlatform) {
super(modPlatform);
}
@Override
public String getID() {
return "terra-fabric";

@ -32,7 +32,7 @@ public class FabricEntryPoint implements ModInitializer {
private static final Logger logger = LoggerFactory.getLogger(FabricEntryPoint.class);
private static final FabricPlatform TERRA_PLUGIN = new FabricPlatform();
@Override
public void onInitialize() {
logger.info("Initializing Terra Fabric mod...");

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

@ -70,7 +70,7 @@ tasks {
)
}
}
remapJar {
inputFile.set(shadowJar.get().archiveFile)
archiveFileName.set("${rootProject.name.capitalize()}-${project.version}.jar")

@ -1,32 +1,22 @@
package com.dfsek.terra.forge;
import com.dfsek.terra.AbstractPlatform;
import cpw.mods.cl.ModuleClassLoader;
import net.minecraftforge.fml.loading.FMLLoader;
import org.burningwave.core.classes.Classes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
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.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Stream;
import com.dfsek.terra.AbstractPlatform;
import com.dfsek.terra.api.addon.bootstrap.BootstrapAddonClassLoader;
@ -73,7 +63,7 @@ public final class AwfulForgeHacks {
}
public static void loadAllTerraClasses() {
if (FMLLoader.isProduction()) {
if(FMLLoader.isProduction()) {
try(JarFile jar = getTerraJar()) {
jar.stream()
.forEach(jarEntry -> {
@ -96,45 +86,52 @@ public final class AwfulForgeHacks {
}
} else {
// 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<>();
Path terraRoot = Path.of(System.getProperty("user.dir")).getParent().getParent().getParent();
Path commonRoot = terraRoot.resolve("common");
Path implementationRoot = commonRoot.resolve("implementation");
pathsToLoad.add(commonRoot.resolve("api"));
pathsToLoad.add(implementationRoot.resolve("base"));
pathsToLoad.add(implementationRoot.resolve("bootstrap-addon-loader"));
for (Path path : pathsToLoad) {
for(Path path : pathsToLoad) {
try {
Path target = path.resolve("build").resolve("classes").resolve("java").resolve("main");
BootstrapAddonClassLoader cl = new BootstrapAddonClassLoader(new URL[] { path.toUri().toURL()});
Classes.Loaders omegaCL = Classes.Loaders.create();
BootstrapAddonClassLoader cl = new BootstrapAddonClassLoader(new URL[]{ path.toUri().toURL() });
Classes.Loaders omegaCL = Classes.Loaders.create();
Files.walk(target, Integer.MAX_VALUE, FileVisitOption.FOLLOW_LINKS)
.filter(it -> it.getFileName().toString().endsWith(".class"))
.map(Path::toFile)
.forEach(it -> {
String name = it.getAbsolutePath().replace(target + "/", "").replace('\\', '.').replace('/', '.');
name = name.substring(0, name.length() - 6);
LOGGER.info("Loading class {}", name);
try {
Class.forName(name);
} catch(ClassNotFoundException e) {
try {
String pathToJar = cl.loadClass(name).getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
cl.addURL(new URL("jar:file:" + pathToJar + "!/"));
Class newClassLoad = Class.forName(name, true, cl);
omegaCL.loadOrDefine(newClassLoad, AbstractPlatform.class.getClassLoader());
} catch(ClassNotFoundException | URISyntaxException | IOException ex) {
throw new RuntimeException(ex);
}
}
});
.filter(it -> it.getFileName().toString().endsWith(".class"))
.map(Path::toFile)
.forEach(it -> {
String name = it.getAbsolutePath().replace(target + "/", "").replace('\\', '.').replace('/', '.');
name = name.substring(0, name.length() - 6);
LOGGER.info("Loading class {}", name);
try {
Class.forName(name);
} catch(ClassNotFoundException e) {
try {
String pathToJar = cl.loadClass(name)
.getProtectionDomain()
.getCodeSource()
.getLocation()
.toURI()
.getPath();
cl.addURL(new URL("jar:file:" + pathToJar + "!/"));
Class newClassLoad = Class.forName(name, true, cl);
omegaCL.loadOrDefine(newClassLoad, AbstractPlatform.class.getClassLoader());
} catch(ClassNotFoundException | URISyntaxException | IOException ex) {
throw new RuntimeException(ex);
}
}
});
} catch(IOException e) {
throw new IllegalStateException("Could not load all Terra classes", e);
}

@ -3,12 +3,13 @@ package com.dfsek.terra.forge;
import com.dfsek.terra.mod.MinecraftAddon;
import com.dfsek.terra.mod.ModPlatform;
public class ForgeAddon extends MinecraftAddon {
public class ForgeAddon extends MinecraftAddon {
public ForgeAddon(ModPlatform modPlatform) {
super(modPlatform);
}
@Override
public String getID() {
return "terra-forge";

@ -43,28 +43,24 @@ import com.dfsek.terra.mod.data.Codecs;
@Mod("terra")
@EventBusSubscriber(bus = Bus.MOD)
public class ForgeEntryPoint {
private final RegistrySanityCheck sanityCheck = new RegistrySanityCheck();
static {
AwfulForgeHacks.loadAllTerraClasses();
TERRA_PLUGIN = new ForgePlatform();
}
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;
static {
AwfulForgeHacks.loadAllTerraClasses();
TERRA_PLUGIN = new ForgePlatform();
}
private final RegistrySanityCheck sanityCheck = new RegistrySanityCheck();
public ForgeEntryPoint() {
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
modEventBus.register(this);
}
public static ForgePlatform getPlatform() {
return TERRA_PLUGIN;
}
public static void initialize(RegisterHelper<Biome> helper) {
getPlatform().getEventManager().callEvent(
new PlatformInitializationEvent());
@ -75,10 +71,12 @@ public class ForgeEntryPoint {
public void registerBiomes(RegisterEvent event) {
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(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));
}
}

@ -43,33 +43,33 @@ import com.dfsek.terra.mod.generation.MinecraftChunkGeneratorWrapper;
public class ForgePlatform extends ModPlatform {
private static final Logger LOGGER = LoggerFactory.getLogger(ForgePlatform.class);
private final Lazy<File> dataFolder = Lazy.lazy(() -> new File("./config/Terra"));
public ForgePlatform() {
CommonPlatform.initialize(this);
load();
}
@Override
public MinecraftServer getServer() {
return ServerLifecycleHooks.getCurrentServer();
}
@Override
public boolean reload() {
getTerraConfig().load(this);
getRawConfigRegistry().clear();
boolean succeed = getRawConfigRegistry().loadAll(this);
MinecraftServer server = getServer();
if (server != null) {
if(server != null) {
server.reloadResources(server.getDataPackManager().getNames()).exceptionally(throwable -> {
LOGGER.warn("Failed to execute reload", throwable);
return null;
}).join();
//BiomeUtil.registerBiomes();
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 -> {
chunkGeneratorWrapper.setPack(pack);
LOGGER.info("Replaced pack in chunk generator for world {}", world);
@ -79,34 +79,35 @@ public class ForgePlatform extends ModPlatform {
}
return succeed;
}
@Override
protected Iterable<BaseAddon> platformAddon() {
List<BaseAddon> addons = new ArrayList<>();
super.platformAddon().forEach(addons::add);
String mcVersion = MinecraftVersion.CURRENT.getReleaseTarget();
try {
addons.add(new EphemeralAddon(Versions.parseVersion(mcVersion), "minecraft"));
} catch (ParseException e) {
} catch(ParseException e) {
try {
addons.add(new EphemeralAddon(Versions.parseVersion(mcVersion + ".0"), "minecraft"));
} catch (ParseException ex) {
} catch(ParseException ex) {
LOGGER.warn("Failed to parse Minecraft version", e);
}
}
FMLLoader.getLoadingModList().getMods().forEach(mod -> {
String id = mod.getModId();
if (id.equals("terra") || id.equals("minecraft") || id.equals("java")) return;
Version version = Versions.getVersion(mod.getVersion().getMajorVersion(), mod.getVersion().getMinorVersion(), mod.getVersion().getIncrementalVersion());
if(id.equals("terra") || id.equals("minecraft") || id.equals("java")) return;
Version version = Versions.getVersion(mod.getVersion().getMajorVersion(), mod.getVersion().getMinorVersion(),
mod.getVersion().getIncrementalVersion());
addons.add(new EphemeralAddon(version, "forge:" + id));
});
return addons;
}
@Override
public @NotNull String platformName() {
return "Forge";
@ -116,7 +117,7 @@ public class ForgePlatform extends ModPlatform {
public @NotNull File getDataFolder() {
return dataFolder.value();
}
@Override
public BaseAddon getPlatformAddon() {
return new ForgeAddon(this);

@ -24,7 +24,15 @@ public class NoiseConfigMixin {
@Final
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,
DensityFunction densityFunction4, DensityFunction densityFunction5, DensityFunction densityFunction6,
List<NoiseHypercube> list) {

@ -1,8 +1,5 @@
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.registry.BuiltinRegistries;
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.mod.config.PreLoadCompatibilityOptions;
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;
@ -32,7 +31,7 @@ public final class BiomeUtil {
private BiomeUtil() {
}
public static void registerBiomes(RegisterHelper<net.minecraft.world.biome.Biome> helper) {
logger.info("Registering biomes...");
@ -51,29 +50,41 @@ public final class BiomeUtil {
* @param pack The ConfigPack this biome belongs to.
*/
private static void registerBiome(Biome biome, ConfigPack pack,
com.dfsek.terra.api.registry.key.RegistryKey id, RegisterHelper<net.minecraft.world.biome.Biome> helper) {
RegistryKey<net.minecraft.world.biome.Biome> vanilla = ((ProtoPlatformBiome) biome.getPlatformBiome()) .get(BuiltinRegistries.BIOME);
com.dfsek.terra.api.registry.key.RegistryKey id,
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()) {
((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(vanilla);
} else {
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));
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 {
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();
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);
}

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

@ -1,6 +1,6 @@
{
"pack": {
"description": "Terra Resources",
"pack_format": 9
}
"pack": {
"description": "Terra Resources",
"pack_format": 9
}
}

@ -4,7 +4,7 @@
"package": "com.dfsek.terra.forge.mixin",
"compatibilityLevel": "JAVA_17",
"mixins": [
"lifecycle.NoiseConfigMixin"
"lifecycle.NoiseConfigMixin"
],
"client": [
],

@ -61,10 +61,10 @@ public abstract class MinecraftAddon implements BaseAddon {
.getHandler(FunctionalEventHandler.class)
.register(this, ConfigurationLoadEvent.class)
.then(event -> {
if(event.is(Biome.class)) {
event.getLoadedObject(Biome.class).getContext().put(event.load(new VanillaBiomeProperties()));
}
})
if(event.is(Biome.class)) {
event.getLoadedObject(Biome.class).getContext().put(event.load(new VanillaBiomeProperties()));
}
})
.global();
}

@ -3,17 +3,6 @@ package com.dfsek.terra.mod;
import com.dfsek.tectonic.api.TypeRegistry;
import com.dfsek.tectonic.api.depth.DepthTracker;
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.SpawnGroup;
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.SpawnEntry;
import net.minecraft.world.gen.WorldPreset;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Locale;
@ -38,6 +28,8 @@ import java.util.function.BiConsumer;
import com.dfsek.terra.AbstractPlatform;
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.mod.config.BiomeAdditionsSoundTemplate;
import com.dfsek.terra.mod.config.BiomeMoodSoundTemplate;
@ -49,17 +41,19 @@ import com.dfsek.terra.mod.config.SoundEventTemplate;
import com.dfsek.terra.mod.config.SpawnCostConfig;
import com.dfsek.terra.mod.config.SpawnEntryTemplate;
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.VillagerTypeTemplate;
import com.dfsek.terra.mod.handle.MinecraftItemHandle;
import com.dfsek.terra.mod.handle.MinecraftWorldHandle;
import com.dfsek.terra.mod.util.PresetUtil;
import org.jetbrains.annotations.NotNull;
public abstract class ModPlatform extends AbstractPlatform {
public abstract MinecraftServer getServer();
private final ItemHandle itemHandle = new MinecraftItemHandle();
private final WorldHandle worldHandle = new MinecraftWorldHandle();
public abstract MinecraftServer getServer();
public void registerWorldTypes(BiConsumer<Identifier, WorldPreset> registerFunction) {
getRawConfigRegistry()
@ -78,10 +72,12 @@ public abstract class ModPlatform extends AbstractPlatform {
})
.registerLoader(Precipitation.class, (type, o, loader, depthTracker) -> Precipitation.valueOf(((String) o).toUpperCase(
Locale.ROOT)))
.registerLoader(GrassColorModifier.class, (type, o, loader, depthTracker) -> GrassColorModifier.valueOf(((String) o).toUpperCase(
Locale.ROOT)))
.registerLoader(GrassColorModifier.class, (type, o, loader, depthTracker) -> TemperatureModifier.valueOf(((String) o).toUpperCase(
Locale.ROOT)))
.registerLoader(GrassColorModifier.class,
(type, o, loader, depthTracker) -> GrassColorModifier.valueOf(((String) o).toUpperCase(
Locale.ROOT)))
.registerLoader(GrassColorModifier.class,
(type, o, loader, depthTracker) -> TemperatureModifier.valueOf(((String) o).toUpperCase(
Locale.ROOT)))
.registerLoader(BiomeParticleConfig.class, BiomeParticleConfigTemplate::new)
.registerLoader(SoundEvent.class, SoundEventTemplate::new)
.registerLoader(BiomeMoodSound.class, BiomeMoodSoundTemplate::new)
@ -101,12 +97,12 @@ public abstract class ModPlatform extends AbstractPlatform {
if(BuiltinRegistries.BIOME.get(identifier) == null) throw new LoadException("Invalid Biome ID: " + identifier, tracker); // failure.
return new ProtoPlatformBiome(identifier);
}
@Override
protected Iterable<BaseAddon> platformAddon() {
return List.of(getPlatformAddon());
}
protected abstract BaseAddon getPlatformAddon();
@Override

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

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

@ -17,10 +17,10 @@ public class BiomeParticleConfigTemplate implements ObjectTemplate<BiomeParticle
@Value("probability")
@Default
private Integer probability = null;
@Override
public BiomeParticleConfig get() {
if (particle == null || probability == null) {
if(particle == null || probability == null) {
return null;
}

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

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

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

@ -93,7 +93,7 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties {
public Integer getGrassColor() {
return grassColor;
}
public Integer getFogColor() {
return fogColor;
}

@ -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.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import net.minecraft.entity.EntityType;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
import net.minecraft.village.VillagerType;

@ -31,8 +31,8 @@ public final class Codecs {
.getConfigRegistry()
.get(id)
.orElseThrow(() -> new IllegalArgumentException(
"No such config pack " +
id)))));
"No such config pack " +
id)))));
public static final Codec<TerraBiomeSource> TERRA_BIOME_SOURCE = RecordCodecBuilder
.create(instance -> instance.group(RegistryOps.createRegistryCodec(Registry.BIOME_KEY)

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

@ -20,7 +20,8 @@ import com.dfsek.terra.mod.CommonPlatform;
MoveToFlowerGoal.class
})
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) {
return new CheckedRandom(CommonPlatform.get().getServer().getTicks()); // replace with new random seeded by tick time.
}

@ -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.
*
* Currently, on Fabric, Terra cannot be specified as a Nether generator. TODO: logic to turn fossils back on if chunk generator is in nether.
* <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.
*/
@Mixin(NetherFossilStructure.class)
public class NetherFossilOptimization {

@ -1,7 +1,5 @@
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.MobSpawnerBlockEntity;
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.RegistryEntry;
import net.minecraft.util.registry.RegistryKey;
import net.minecraft.village.VillagerType;
import net.minecraft.world.WorldAccess;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.Biome.Builder;
@ -69,18 +66,23 @@ public final class MinecraftUtil {
TERRA_BIOME_MAP
.forEach((vb, terraBiomes) ->
biomes.getOrEmpty(vb)
.ifPresentOrElse(vanilla -> terraBiomes
.forEach(tb -> biomes.getOrEmpty(tb)
.ifPresentOrElse(
terra -> {
List<ConfiguredFeature<?, ?>> flowerFeatures = List.copyOf(vanilla.getGenerationSettings().getFlowerFeatures());
logger.debug("Injecting flora into biome {} : {}", tb, flowerFeatures);
((FloraFeatureHolder) terra.getGenerationSettings()).setFloraFeatures(flowerFeatures);
},
() -> logger.error(
"No such biome: {}",
tb))),
() -> logger.error("No vanilla biome: {}", vb)));
.ifPresentOrElse(vanilla -> terraBiomes
.forEach(tb -> biomes.getOrEmpty(tb)
.ifPresentOrElse(
terra -> {
List<ConfiguredFeature<?, ?>> flowerFeatures = List.copyOf(
vanilla.getGenerationSettings()
.getFlowerFeatures());
logger.debug("Injecting flora into biome" +
" {} : {}", tb,
flowerFeatures);
((FloraFeatureHolder) terra.getGenerationSettings()).setFloraFeatures(
flowerFeatures);
},
() -> logger.error(
"No such biome: {}",
tb))),
() -> logger.error("No vanilla biome: {}", vb)));
}
@ -92,70 +94,73 @@ public final class MinecraftUtil {
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();
BiomeEffects.Builder effects = new BiomeEffects.Builder();
net.minecraft.world.biome.Biome.Builder builder = new Builder();
effects.waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.getWaterColor()))
.waterFogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterFogColor(), vanilla.getWaterFogColor()))
.fogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanilla.getFogColor()))
.skyColor(Objects.requireNonNullElse(vanillaBiomeProperties.getSkyColor(), vanilla.getSkyColor()))
.grassColorModifier(
Objects.requireNonNullElse(vanillaBiomeProperties.getGrassColorModifier(), vanilla.getEffects().getGrassColorModifier()));
if (vanillaBiomeProperties.getFoliageColor() == null) {
Objects.requireNonNullElse(vanillaBiomeProperties.getGrassColorModifier(),
vanilla.getEffects().getGrassColorModifier()));
if(vanillaBiomeProperties.getFoliageColor() == null) {
vanilla.getEffects().getFoliageColor().ifPresent(effects::foliageColor);
} else {
effects.foliageColor(vanillaBiomeProperties.getFoliageColor());
}
if (vanillaBiomeProperties.getGrassColor() == null) {
if(vanillaBiomeProperties.getGrassColor() == null) {
vanilla.getEffects().getGrassColor().ifPresent(effects::grassColor);
} else {
effects.grassColor(vanillaBiomeProperties.getGrassColor());
}
if (vanillaBiomeProperties.getParticleConfig() == null) {
if(vanillaBiomeProperties.getParticleConfig() == null) {
vanilla.getEffects().getParticleConfig().ifPresent(effects::particleConfig);
} else {
effects.particleConfig(vanillaBiomeProperties.getParticleConfig());
}
if (vanillaBiomeProperties.getLoopSound() == null) {
if(vanillaBiomeProperties.getLoopSound() == null) {
vanilla.getEffects().getLoopSound().ifPresent(effects::loopSound);
} else {
effects.loopSound(vanillaBiomeProperties.getLoopSound());
}
if (vanillaBiomeProperties.getMoodSound() == null) {
if(vanillaBiomeProperties.getMoodSound() == null) {
vanilla.getEffects().getMoodSound().ifPresent(effects::moodSound);
} else {
effects.moodSound(vanillaBiomeProperties.getMoodSound());
}
if (vanillaBiomeProperties.getAdditionsSound() == null) {
if(vanillaBiomeProperties.getAdditionsSound() == null) {
vanilla.getEffects().getAdditionsSound().ifPresent(effects::additionsSound);
} else {
effects.additionsSound(vanillaBiomeProperties.getAdditionsSound());
}
if (vanillaBiomeProperties.getMusic() == null) {
if(vanillaBiomeProperties.getMusic() == null) {
vanilla.getEffects().getMusic().ifPresent(effects::music);
} else {
effects.music(vanillaBiomeProperties.getMusic());
}
builder.precipitation(Objects.requireNonNullElse(vanillaBiomeProperties.getPrecipitation(), vanilla.getPrecipitation()));
builder.temperature(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperature(), vanilla.getTemperature()));
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()));
return builder

@ -40,7 +40,7 @@ public class PresetUtil {
Registry<StructureSet> structureSetRegistry = BuiltinRegistries.STRUCTURE_SET;
Registry<NoiseParameters> noiseParametersRegistry = BuiltinRegistries.NOISE_PARAMETERS;
Registry<Biome> biomeRegistry = BuiltinRegistries.BIOME;
RegistryEntry<DimensionType> theNetherDimensionType = dimensionTypeRegistry.getOrCreateEntry(DimensionTypes.THE_NETHER);
RegistryEntry<ChunkGeneratorSettings>
netherChunkGeneratorSettings = chunkGeneratorSettingsRegistry.getOrCreateEntry(ChunkGeneratorSettings.NETHER);
@ -57,19 +57,19 @@ public class PresetUtil {
new NoiseChunkGenerator(structureSetRegistry, noiseParametersRegistry,
new TheEndBiomeSource(biomeRegistry),
endChunkGeneratorSettings));
RegistryEntry<DimensionType> overworldDimensionType = dimensionTypeRegistry.getOrCreateEntry(DimensionTypes.OVERWORLD);
RegistryEntry<ChunkGeneratorSettings> overworld = chunkGeneratorSettingsRegistry.getOrCreateEntry(ChunkGeneratorSettings.OVERWORLD);
Identifier generatorID = Identifier.of("terra", pack.getID().toLowerCase(Locale.ROOT) + "/" + pack.getNamespace().toLowerCase(
Locale.ROOT));
PRESETS.add(generatorID);
TerraBiomeSource biomeSource = new TerraBiomeSource(biomeRegistry, pack);
ChunkGenerator generator = new MinecraftChunkGeneratorWrapper(structureSetRegistry, biomeSource, pack, overworld);
DimensionOptions dimensionOptions = new DimensionOptions(overworldDimensionType, generator);
WorldPreset preset = new WorldPreset(
Map.of(

@ -1,49 +1,49 @@
{
"required": true,
"minVersion": "0.8",
"package": "com.dfsek.terra.mod.mixin",
"compatibilityLevel": "JAVA_17",
"mixins": [
"access.BiomeAccessor",
"access.MobSpawnerLogicAccessor",
"access.StateAccessor",
"access.StructureAccessorAccessor",
"access.VillagerTypeAccessor",
"fix.BeeMoveGoalsUnsynchronizedRandomAccessFix",
"fix.NetherFossilOptimization",
"implementations.compat.GenerationSettingsFloraFeaturesMixin",
"implementations.terra.BiomeMixin",
"implementations.terra.HandleImplementationMixin",
"implementations.terra.block.BlockMixin",
"implementations.terra.block.entity.BlockEntityMixin",
"implementations.terra.block.entity.LootableContainerBlockEntityMixin",
"implementations.terra.block.entity.MobSpawnerBlockEntityMixin",
"implementations.terra.block.entity.SignBlockEntityMixin",
"implementations.terra.block.state.BlockStateMixin",
"implementations.terra.block.state.PropertyMixin",
"implementations.terra.chunk.ChunkRegionMixin",
"implementations.terra.chunk.WorldChunkMixin",
"implementations.terra.chunk.data.ProtoChunkMixin",
"implementations.terra.entity.EntityMixin",
"implementations.terra.entity.EntityTypeMixin",
"implementations.terra.entity.PlayerEntityMixin",
"implementations.terra.entity.ServerCommandSourceMixin",
"implementations.terra.inventory.LockableContainerBlockEntityMixin",
"implementations.terra.inventory.item.ItemMixin",
"implementations.terra.inventory.item.ItemStackMixin",
"implementations.terra.inventory.meta.EnchantmentMixin",
"implementations.terra.inventory.meta.ItemStackDamageableMixin",
"implementations.terra.inventory.meta.ItemStackMetaMixin",
"implementations.terra.world.ChunkRegionMixin",
"implementations.terra.world.ServerWorldMixin",
"lifecycle.DataPackContentsMixin"
],
"client": [
],
"server": [
],
"injectors": {
"defaultRequire": 1
},
"required": true,
"minVersion": "0.8",
"package": "com.dfsek.terra.mod.mixin",
"compatibilityLevel": "JAVA_17",
"mixins": [
"access.BiomeAccessor",
"access.MobSpawnerLogicAccessor",
"access.StateAccessor",
"access.StructureAccessorAccessor",
"access.VillagerTypeAccessor",
"fix.BeeMoveGoalsUnsynchronizedRandomAccessFix",
"fix.NetherFossilOptimization",
"implementations.compat.GenerationSettingsFloraFeaturesMixin",
"implementations.terra.BiomeMixin",
"implementations.terra.HandleImplementationMixin",
"implementations.terra.block.BlockMixin",
"implementations.terra.block.entity.BlockEntityMixin",
"implementations.terra.block.entity.LootableContainerBlockEntityMixin",
"implementations.terra.block.entity.MobSpawnerBlockEntityMixin",
"implementations.terra.block.entity.SignBlockEntityMixin",
"implementations.terra.block.state.BlockStateMixin",
"implementations.terra.block.state.PropertyMixin",
"implementations.terra.chunk.ChunkRegionMixin",
"implementations.terra.chunk.WorldChunkMixin",
"implementations.terra.chunk.data.ProtoChunkMixin",
"implementations.terra.entity.EntityMixin",
"implementations.terra.entity.EntityTypeMixin",
"implementations.terra.entity.PlayerEntityMixin",
"implementations.terra.entity.ServerCommandSourceMixin",
"implementations.terra.inventory.LockableContainerBlockEntityMixin",
"implementations.terra.inventory.item.ItemMixin",
"implementations.terra.inventory.item.ItemStackMixin",
"implementations.terra.inventory.meta.EnchantmentMixin",
"implementations.terra.inventory.meta.ItemStackDamageableMixin",
"implementations.terra.inventory.meta.ItemStackMetaMixin",
"implementations.terra.world.ChunkRegionMixin",
"implementations.terra.world.ServerWorldMixin",
"lifecycle.DataPackContentsMixin"
],
"client": [
],
"server": [
],
"injectors": {
"defaultRequire": 1
},
"refmap": "terra.common.refmap.json"
}

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

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

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save