Merge branch 'dev/26.3-wyck' into dev/26.3-port

This commit is contained in:
Zoe Gidiere committed 2026-11-07 17:26:05 -07:00
commit 60f3641039
75 files changed
+919 -2289

No files matched your search

+1 -5
View File
@@ -15,7 +15,7 @@ allprojects {
tasks.withType<JavaCompile>().configureEach {
options.isFork = true
options.isIncremental = true
options.release.set(21)
options.release.set(25)
}
tasks.withType<Test>().configureEach {
@@ -48,10 +48,6 @@ afterEvaluate {
forSubProjects(":common:addons") {
apply(plugin = "com.gradleup.shadow")
tasks.named("build") {
finalizedBy(tasks.named("shadowJar"))
}
dependencies {
"compileOnly"(project(":common:api"))
"testImplementation"(project(":common:api"))
+1 -2
View File
@@ -22,9 +22,8 @@ repositories {
dependencies {
//TODO Allow pulling from Versions.kt
implementation("com.gradleup.shadow", "shadow-gradle-plugin", "8.3.9")
implementation("com.gradleup.shadow", "shadow-gradle-plugin", "9.3.1")
implementation("io.papermc.paperweight.userdev", "io.papermc.paperweight.userdev.gradle.plugin", "2.0.0-beta.21")
implementation("org.ow2.asm", "asm", "9.9")
implementation("org.ow2.asm", "asm-tree", "9.9")
implementation("com.dfsek.tectonic", "common", "4.3.1")
@@ -57,6 +57,9 @@ fun Project.configureDependencies() {
maven("https://s01.oss.sonatype.org/content/repositories/snapshots/") {
name = "Sonatype Snapshots"
}
maven("https://repo.wyck.dev/snapshots") {
name = "Wyck Snapshots"
}
maven("https://repo.onarandombox.com/multiverse-releases") {
name = "onarandombox"
}
@@ -1,5 +1,4 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import io.papermc.paperweight.util.path
import java.io.File
import java.io.FileWriter
import java.net.URL
@@ -81,7 +80,7 @@ fun Project.configureDistribution() {
doLast {
// https://github.com/johnrengelman/shadow/issues/111
val dest = tasks.named<ShadowJar>("shadowJar").get().archiveFile.get().path
val dest = tasks.named<ShadowJar>("shadowJar").get().archiveFile.get().asFile.toPath()
installAddonsInto(dest)
}
}
@@ -91,7 +90,7 @@ fun Project.configureDistribution() {
dependsOn(compileAddons)
doLast {
val dest = tasks.named<Jar>("jar").get().archiveFile.get().path
val dest = tasks.named<Jar>("jar").get().archiveFile.get().asFile.toPath()
installAddonsInto(dest)
}
}
@@ -161,7 +160,7 @@ fun Project.configureDistribution() {
tasks.named<ShadowJar>("shadowJar") {
// Tell shadow to download the packs
dependsOn(downloadDefaultPacks)
configurations = listOf(project.configurations["shaded"])
configurations.set(listOf(project.configurations["shaded"]))
archiveClassifier.set("shaded")
version = project.version
relocate("org.apache.commons", "com.dfsek.terra.lib.commons")
+4 -9
View File
@@ -19,7 +19,7 @@ object Versions {
const val slf4j = "2.0.17"
object Internal {
const val shadow = "8.3.9"
const val shadow = "9.3.1"
const val apacheText = "1.14.0"
const val apacheIO = "2.20.0"
const val guava = "33.5.0-jre"
@@ -59,16 +59,11 @@ object Versions {
// }
object Bukkit {
const val minecraft = "26.1.2"
const val nms = "$minecraft-R0.1"
const val paperBuild = "26.1.2.build.60-stable"
const val minecraft = "26.3"
const val paperBuild = "$minecraft.build.244-stable"
const val paper = paperBuild
const val paperLib = "1.0.8"
const val reflectionRemapper = "0.1.3"
const val paperDevBundle = paperBuild
const val paperDevBundle26_3 = "26.3.build.156-beta"
const val runPaper = "3.0.2"
const val paperWeight = "2.0.0-beta.21"
const val wyck = "4.0.0-837d6ec"
const val cloud = "2.0.1"
const val multiverse = "5.3.0"
}
@@ -89,6 +89,11 @@ public abstract class AbstractPlatform implements Platform {
private static final MutableBoolean LOADED = new MutableBoolean(false);
private static final String moonrise = "Moonrise";
private static final String PACK_LOAD_FAILURE_QUOTE = """
> I felt a great disturbance in the JVM, as if millions of plugins suddenly cried out in stack traces and were suddenly silenced.
> I fear something terrible has happened.
> - Astrash
""".strip();
private final EventManager eventManager = new EventManagerImpl();
private final ConfigRegistry configRegistry = new ConfigRegistry();
private final MetaConfigRegistry metaConfigRegistry = new MetaConfigRegistry();
@@ -215,6 +220,7 @@ public abstract class AbstractPlatform implements Platform {
return false;
} catch(PackLoadFailuresException e) {
e.getExceptions().forEach(ex -> logger.error("Failed to load config pack", ex));
logger.error(PACK_LOAD_FAILURE_QUOTE);
return false;
}
return true;
@@ -231,6 +237,7 @@ public abstract class AbstractPlatform implements Platform {
return false;
} catch(PackLoadFailuresException e) {
e.getExceptions().forEach(ex -> logger.error("Failed to meta load config pack", ex));
logger.error(PACK_LOAD_FAILURE_QUOTE);
return false;
}
return true;
@@ -0,0 +1,93 @@
package com.dfsek.terra.registry;
import com.google.errorprone.annotations.MustBeClosed;
import org.intellij.lang.annotations.Pattern;
import org.jspecify.annotations.Nullable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Stream;
/**
* A file-discoverable registry that can be extended by system properties
* <br>
* The main use-case for this is to allow for customized locations of file-system-based key entries,
* such as putting config packs into custom locations.
* <br>
* Two system properties are used to define the search path:
* <br>
* <code>terra.registry.{searchPathName}.searchPath</code> is a list of "parent folder" paths (like the pack directory) that
* will be searched for contained files.
* <br>
* <code>terra.registry.{searchPathName}.extraPath</code> is a list of files that will be directly evaluated for membership and
* as such will be directly treated as members of the registry.
* <br>
* These system properties are formatted like UNIX-style paths, with each path separated by a colon (':') character.
*/
public interface ExtensibleRegistry {
/**
* Get a lowercase search path name for this registry that will get plugged into
* <br>
* <code>terra.registry.{searchPathName}.searchPath</code>
* <br>
* and
* <br>
* <code>terra.registry.{searchPathName}.extraPath</code>
*/
@Pattern("^[a-z._]+$")
String getRegistryName();
/**
* Check if a path may be a member of this registry heuristically.
*
* @param path Path to check
*
* @return True if the path is a member of this registry.
*/
boolean validatePathIsMember(Path path);
default @MustBeClosed Stream<Path> getMemberPaths(Path baseSearchPath) {
String basePropertyName = "terra.registry." + getRegistryName();
Stream<Path> searchPath = Stream.concat(
parseValidPaths(System.getProperty(basePropertyName + ".search-path")),
Stream.of(baseSearchPath)
);
Stream<Path> extraPath = parseValidPaths(System.getProperty(basePropertyName + ".extra-path"));
return Stream.concat(
searchPath
.filter(Files::isDirectory)
.flatMap(ExtensibleRegistry::listDirectory),
extraPath
)
.filter(this::validatePathIsMember);
}
private static Stream<Path> parseValidPaths(@Nullable String paths) {
return Stream.ofNullable(paths)
.flatMap(p -> Arrays.stream(p.split(":")))
.filter(v -> !v.isBlank())
.map(v -> {
try {
return Path.of(v).toAbsolutePath().normalize();
} catch (Exception e) {
return null;
}
})
.filter(Objects::nonNull);
}
private static Stream<Path> listDirectory(Path dir) {
try {
return Files.list(dir);
} catch(IOException e) {
return Stream.empty();
}
}
}
@@ -29,13 +29,14 @@ import com.dfsek.terra.api.Platform;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.util.reflection.TypeKey;
import com.dfsek.terra.config.pack.ConfigPackImpl;
import com.dfsek.terra.registry.ExtensibleRegistry;
import com.dfsek.terra.registry.OpenRegistryImpl;
/**
* Class to hold config packs
*/
public class ConfigRegistry extends OpenRegistryImpl<ConfigPack> {
public class ConfigRegistry extends OpenRegistryImpl<ConfigPack> implements ExtensibleRegistry {
public ConfigRegistry() {
super(TypeKey.of(ConfigPack.class));
@@ -45,7 +46,7 @@ public class ConfigRegistry extends OpenRegistryImpl<ConfigPack> {
Path packsDirectory = platform.getDataFolder().toPath().resolve("packs");
Files.createDirectories(packsDirectory);
List<Exception> failedLoads = new CopyOnWriteArrayList<>();
try(Stream<Path> packs = Files.list(packsDirectory)) {
try(Stream<Path> packs = getMemberPaths(packsDirectory)) {
packs.parallel().forEach(path -> {
try {
ConfigPack pack = new ConfigPackImpl(path, platform);
@@ -60,6 +61,16 @@ public class ConfigRegistry extends OpenRegistryImpl<ConfigPack> {
}
}
@Override
public String getRegistryName() {
return "config";
}
@Override
public boolean validatePathIsMember(Path path) {
return Files.isDirectory(path)|| path.getFileName().toString().endsWith(".zip");
}
public static class PackLoadFailuresException extends Exception {
@Serial
private static final long serialVersionUID = 538998844645186306L;
@@ -28,6 +28,7 @@ import com.dfsek.terra.api.Platform;
import com.dfsek.terra.api.config.MetaPack;
import com.dfsek.terra.api.util.reflection.TypeKey;
import com.dfsek.terra.config.pack.MetaPackImpl;
import com.dfsek.terra.registry.ExtensibleRegistry;
import com.dfsek.terra.registry.OpenRegistryImpl;
import com.dfsek.terra.registry.master.ConfigRegistry.PackLoadFailuresException;
@@ -35,7 +36,7 @@ import com.dfsek.terra.registry.master.ConfigRegistry.PackLoadFailuresException;
/**
* Class to hold config packs
*/
public class MetaConfigRegistry extends OpenRegistryImpl<MetaPack> {
public class MetaConfigRegistry extends OpenRegistryImpl<MetaPack> implements ExtensibleRegistry {
public MetaConfigRegistry() {
super(TypeKey.of(MetaPack.class));
@@ -45,8 +46,8 @@ public class MetaConfigRegistry extends OpenRegistryImpl<MetaPack> {
Path packsDirectory = platform.getDataFolder().toPath().resolve("metapacks");
Files.createDirectories(packsDirectory);
List<IOException> failedLoads = new ArrayList<>();
try(Stream<Path> packs = Files.list(packsDirectory)) {
packs.forEach(path -> {
try(Stream<Path> paths = getMemberPaths(packsDirectory)) {
paths.forEach(path -> {
try {
MetaPack pack = new MetaPackImpl(path, platform, configRegistry);
registerChecked(pack.getRegistryKey(), pack);
@@ -59,4 +60,14 @@ public class MetaConfigRegistry extends OpenRegistryImpl<MetaPack> {
throw new PackLoadFailuresException(failedLoads);
}
}
@Override
public String getRegistryName() {
return "metaconfig";
}
@Override
public boolean validatePathIsMember(Path path) {
return Files.isDirectory(path) || path.getFileName().toString().endsWith(".zip");
}
}
+3 -11
View File
@@ -1,17 +1,9 @@
plugins {
id("io.papermc.paperweight.userdev")
id("xyz.jpenilla.run-paper") version Versions.Bukkit.runPaper
}
dependencies {
// Required for :platforms:bukkit:runDevBundleServer task
paperweight.paperDevBundle(Versions.Bukkit.paperDevBundle)
shaded(project(":platforms:bukkit:common"))
shaded(project(path = ":platforms:bukkit:nms:common", configuration = "runtimeElements"))
shaded(project(path = ":platforms:bukkit:nms:26.1", configuration = "runtimeElements"))
shaded(project(path = ":platforms:bukkit:nms:26.3", configuration = "runtimeElements"))
shaded("xyz.jpenilla", "reflection-remapper", Versions.Bukkit.reflectionRemapper)
}
tasks.withType<JavaCompile>().configureEach {
@@ -20,7 +12,6 @@ tasks.withType<JavaCompile>().configureEach {
tasks {
shadowJar {
relocate("io.papermc.lib", "com.dfsek.terra.lib.paperlib")
relocate("com.google.common", "com.dfsek.terra.lib.google.common")
relocate("org.apache.logging.slf4j", "com.dfsek.terra.lib.slf4j-over-log4j")
exclude("org/slf4j/**")
@@ -38,8 +29,9 @@ tasks {
pluginJars(shadowJar.get().archiveFile)
downloadPlugins {
modrinth("viaversion", "5.5.0")
modrinth("viabackwards", "5.5.0")
modrinth("viaversion", "5.12.2")
modrinth("viabackwards", "5.12.2")
modrinth("wyck", Versions.Bukkit.wyck)
}
}
}
+2 -2
View File
@@ -10,9 +10,9 @@ dependencies {
compileOnly("io.papermc.paper", "paper-api", Versions.Bukkit.paper)
compileOnly("org.mvplugins.multiverse.core", "multiverse-core", Versions.Bukkit.multiverse)
compileOnly("dev.wyck", "Wyck", Versions.Bukkit.wyck)
shadedApi("io.papermc", "paperlib", Versions.Bukkit.paperLib)
compileOnly("org.mvplugins.multiverse.core", "multiverse-core", Versions.Bukkit.multiverse)
shadedApi("com.google.guava", "guava", Versions.Libraries.Internal.guava)
@@ -4,17 +4,20 @@ import ca.solostudios.strata.Versions;
import ca.solostudios.strata.version.Version;
import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.event.events.config.ConfigurationLoadEvent;
import com.dfsek.terra.api.event.events.config.pack.ConfigPackPreLoadEvent;
import com.dfsek.terra.api.event.functional.FunctionalEventHandler;
import com.dfsek.terra.api.world.biome.Biome;
import com.dfsek.terra.bukkit.config.PreLoadCompatibilityOptions;
import com.dfsek.terra.bukkit.config.VanillaBiomeProperties;
public class BukkitAddon implements BaseAddon {
private static final Version VERSION = Versions.getVersion(1, 0, 0);
protected final PlatformImpl terraBukkitPlugin;
protected final BukkitPlatform terraBukkitPlugin;
public BukkitAddon(PlatformImpl terraBukkitPlugin) {
public BukkitAddon(BukkitPlatform terraBukkitPlugin) {
this.terraBukkitPlugin = terraBukkitPlugin;
}
@@ -25,6 +28,16 @@ public class BukkitAddon implements BaseAddon {
.register(this, ConfigPackPreLoadEvent.class)
.then(event -> event.getPack().getContext().put(event.loadTemplate(new PreLoadCompatibilityOptions())))
.global();
terraBukkitPlugin.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(this, ConfigurationLoadEvent.class)
.then(event -> {
if(event.is(Biome.class)) {
event.getLoadedObject(Biome.class).getContext().put(event.load(new VanillaBiomeProperties()));
}
})
.global();
}
@Override
@@ -18,7 +18,6 @@
package com.dfsek.terra.bukkit;
import com.dfsek.seismic.type.vector.Vector3;
import io.papermc.lib.PaperLib;
import org.bukkit.Location;
import com.dfsek.terra.api.entity.Entity;
@@ -45,14 +44,14 @@ public class BukkitEntity implements Entity {
@Override
public void position(Vector3 location) {
PaperLib.teleportAsync(entity, BukkitAdapter.adapt(location).toLocation(entity.getWorld()));
entity.teleportAsync(BukkitAdapter.adapt(location).toLocation(entity.getWorld()));
}
@Override
public void world(ServerWorld world) {
Location newLoc = entity.getLocation().clone();
newLoc.setWorld(BukkitAdapter.adapt(world));
PaperLib.teleportAsync(entity, newLoc);
entity.teleportAsync(newLoc);
}
@Override
@@ -20,16 +20,43 @@ package com.dfsek.terra.bukkit;
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.addon.BaseAddon;
import com.dfsek.terra.bukkit.config.BiomeAdditionsSoundTemplate;
import com.dfsek.terra.bukkit.config.BiomeMoodSoundTemplate;
import com.dfsek.terra.bukkit.config.BiomeParticleConfigTemplate;
import com.dfsek.terra.bukkit.config.EntityTypeTemplate;
import com.dfsek.terra.bukkit.config.MusicSoundTemplate;
import com.dfsek.terra.bukkit.config.SoundEventTemplate;
import com.dfsek.terra.bukkit.config.SpawnCostConfig;
import com.dfsek.terra.bukkit.config.SpawnEntryConfig;
import com.dfsek.terra.bukkit.config.SpawnSettingsTemplate;
import com.dfsek.terra.bukkit.config.SpawnTypeConfig;
import com.dfsek.terra.bukkit.config.VillagerTypeTemplate;
import dev.wyck.biome.TemperatureModifier;
import dev.wyck.biome.entity.MobCategory;
import dev.wyck.biome.entity.MobSpawnSettings;
import dev.wyck.environment.GrassColorModifier;
import dev.wyck.environment.particle.ParticleCatalog;
import dev.wyck.environment.sounds.AmbientAdditionsSettings;
import dev.wyck.environment.sounds.AmbientMoodSettings;
import dev.wyck.environment.sounds.Music;
import dev.wyck.environment.sounds.SoundEvent;
import dev.wyck.keys.ResourceKey;
import io.papermc.paper.registry.RegistryAccess;
import io.papermc.paper.registry.RegistryKey;
import org.bukkit.Bukkit;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Villager;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.List;
import java.util.Locale;
import com.dfsek.terra.AbstractPlatform;
import com.dfsek.terra.api.block.state.BlockState;
@@ -39,11 +66,12 @@ import com.dfsek.terra.api.world.biome.PlatformBiome;
import com.dfsek.terra.bukkit.generator.BukkitChunkGeneratorWrapper;
import com.dfsek.terra.bukkit.handles.BukkitItemHandle;
import com.dfsek.terra.bukkit.handles.BukkitWorldHandle;
import com.dfsek.terra.bukkit.world.BiomeHandler;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
public class PlatformImpl extends AbstractPlatform {
private static final Logger LOGGER = LoggerFactory.getLogger(PlatformImpl.class);
public class BukkitPlatform extends AbstractPlatform {
private static final Logger LOGGER = LoggerFactory.getLogger(BukkitPlatform.class);
private final ItemHandle itemHandle = new BukkitItemHandle();
@@ -53,7 +81,7 @@ public class PlatformImpl extends AbstractPlatform {
private int generationThreads;
public PlatformImpl(TerraBukkitPlugin plugin) {
public BukkitPlatform(TerraBukkitPlugin plugin) {
generationThreads = getMoonriseGenerationThreadsWithReflection();
if(generationThreads == 0) {
generationThreads = 1;
@@ -70,6 +98,8 @@ public class PlatformImpl extends AbstractPlatform {
public boolean reload() {
getTerraConfig().load(this);
boolean succeed = loadConfigPacks();
BiomeHandler.registerBiomes(getRawConfigRegistry());
BiomeHandler.addToVanillaTags(getRawConfigRegistry());
Bukkit.getWorlds().forEach(world -> {
if(world.getGenerator() instanceof BukkitChunkGeneratorWrapper wrapper) {
@@ -88,6 +118,11 @@ public class PlatformImpl extends AbstractPlatform {
return "Bukkit";
}
@Override
protected Iterable<BaseAddon> platformAddon() {
return List.of(new BukkitAddon(this));
}
@Override
public void runPossiblyUnsafeTask(@NotNull Runnable runnable) {
plugin.getGlobalRegionScheduler().run(plugin, task -> runnable.run());
@@ -118,13 +153,36 @@ public class PlatformImpl extends AbstractPlatform {
super.register(registry);
registry.registerLoader(BlockState.class, (type, o, loader, depthTracker) -> handle.createBlockState((String) o))
.registerLoader(PlatformBiome.class, (type, o, loader, depthTracker) -> parseBiome((String) o, depthTracker))
.registerLoader(EntityType.class, (type, o, loader, depthTracker) -> EntityType.valueOf((String) o));
.registerLoader(ResourceKey.class, (type, o, loader, depthTracker) -> {
NamespacedKey key = NamespacedKey.fromString(((String) o).toLowerCase(Locale.ROOT));
if(key == null) throw new LoadException("Invalid identifier: " + o, depthTracker);
return ResourceKey.of(key);
})
.registerLoader(GrassColorModifier.class,
(type, o, loader, depthTracker) -> GrassColorModifier.valueOf(((String) o).toUpperCase(
Locale.ROOT)))
.registerLoader(TemperatureModifier.class,
(type, o, loader, depthTracker) -> TemperatureModifier.valueOf(((String) o).toUpperCase(
Locale.ROOT)))
.registerLoader(MobCategory.class, (type, o, loader, depthTracker) -> MobCategory.valueOf((String) o))
.registerLoader(ParticleCatalog.class, BiomeParticleConfigTemplate::new)
.registerLoader(SoundEvent.class, SoundEventTemplate::new)
.registerLoader(AmbientMoodSettings.class, BiomeMoodSoundTemplate::new)
.registerLoader(AmbientAdditionsSettings.class, BiomeAdditionsSoundTemplate::new)
.registerLoader(Music.class, MusicSoundTemplate::new)
.registerLoader(EntityType.class, EntityTypeTemplate::new)
.registerLoader(SpawnCostConfig.class, SpawnCostConfig::new)
.registerLoader(SpawnEntryConfig.class, SpawnEntryConfig::new)
.registerLoader(SpawnTypeConfig.class, SpawnTypeConfig::new)
.registerLoader(MobSpawnSettings.class, SpawnSettingsTemplate::new)
.registerLoader(Villager.Type.class, VillagerTypeTemplate::new);
}
protected BukkitPlatformBiome parseBiome(String id, DepthTracker depthTracker) throws LoadException {
NamespacedKey key = NamespacedKey.fromString(id);
if(key == null || !key.namespace().equals("minecraft")) throw new LoadException("Invalid biome identifier " + id, depthTracker);
return new BukkitPlatformBiome(RegistryAccess.registryAccess().getRegistry(RegistryKey.BIOME).getOrThrow(key));
org.bukkit.block.Biome biome = RegistryAccess.registryAccess().getRegistry(RegistryKey.BIOME).get(key);
if(biome == null) throw new LoadException("No such biome " + id, depthTracker);
return new BukkitPlatformBiome(biome);
}
}
@@ -18,7 +18,6 @@
package com.dfsek.terra.bukkit;
import com.dfsek.seismic.type.vector.Vector3;
import io.papermc.lib.PaperLib;
import org.bukkit.Location;
import com.dfsek.terra.api.entity.Player;
@@ -46,14 +45,14 @@ public class BukkitPlayer implements Player {
@Override
public void position(Vector3 location) {
PaperLib.teleportAsync(delegate, BukkitAdapter.adapt(location).toLocation(delegate.getWorld()));
delegate.teleportAsync(BukkitAdapter.adapt(location).toLocation(delegate.getWorld()));
}
@Override
public void world(ServerWorld world) {
Location newLoc = delegate.getLocation().clone();
newLoc.setWorld(BukkitAdapter.adapt(world));
PaperLib.teleportAsync(delegate, newLoc);
delegate.teleportAsync(newLoc);
}
@Override
@@ -1,7 +1,7 @@
package com.dfsek.terra.bukkit;
import io.papermc.paper.command.brigadier.CommandSourceStack;
import org.bukkit.ChatColor;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import java.util.Optional;
@@ -12,6 +12,12 @@ import com.dfsek.terra.bukkit.world.BukkitAdapter;
public class CloudCommandSender implements CommandSender {
private static final LegacyComponentSerializer LEGACY_AMPERSAND = LegacyComponentSerializer.builder()
.character(LegacyComponentSerializer.AMPERSAND_CHAR)
.hexColors()
.useUnusualXRepeatedCharacterHexFormat()
.build();
private final CommandSourceStack delegate;
public CloudCommandSender(CommandSourceStack delegate) {
@@ -20,7 +26,7 @@ public class CloudCommandSender implements CommandSender {
@Override
public void sendMessage(String message) {
delegate.getSender().sendMessage(ChatColor.translateAlternateColorCodes('&', message));
delegate.getSender().sendMessage(LEGACY_AMPERSAND.deserialize(message));
}
@Override
@@ -1,66 +0,0 @@
package com.dfsek.terra.bukkit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import com.dfsek.terra.bukkit.util.VersionUtil;
import com.dfsek.terra.bukkit.util.BukkitNMSAccess;
import com.dfsek.terra.bukkit.util.BukkitUtils;
public interface NMSInitializer {
List<String> SUPPORTED_VERSIONS = List.of("v26.1.2", "v26.2", "v26.3");
String MINECRAFT_VERSION = VersionUtil.getMinecraftVersionInfo().toString();
String TERRA_PACKAGE = NMSInitializer.class.getPackageName();
static PlatformImpl init(TerraBukkitPlugin plugin) {
Logger logger = LoggerFactory.getLogger(NMSInitializer.class);
if(!SUPPORTED_VERSIONS.contains(MINECRAFT_VERSION)) {
logger.error("You are running your server on Minecraft version {} which is not supported by this version of Terra.",
MINECRAFT_VERSION);
String bypassKey = "IKnowThereAreNoNMSBindingsFor" + MINECRAFT_VERSION.replace(".", "_") + "ButIWillProceedAnyway";
if(System.getProperty(bypassKey) == null) {
logger.error("Because of this **TERRA HAS BEEN DISABLED**.");
logger.error("Do not come ask us why it is not working.");
logger.error("If you wish to proceed anyways, you can add the JVM System Property \"{}\" to enable the plugin.", bypassKey);
return null;
} else {
logger.error("");
logger.error("");
for(int i = 0; i < 20; i++) {
logger.error("PROCEEDING WITH AN EXISTING TERRA WORLD WILL RESULT IN CORRUPTION!!!");
}
logger.error("");
logger.error("");
logger.error("We will not give you any support for issues that may arise.");
logger.error("Since you enabled the \"{}\" flag, we won't disable Terra. But be warned.", bypassKey);
}
}
return constructPlatform(plugin);
}
private static PlatformImpl constructPlatform(TerraBukkitPlugin plugin) {
try {
String bindingsVersion = switch(MINECRAFT_VERSION) {
case "v26.3" -> "v26_3";
case "v26.1.2", "v26.2" -> "v26_1";
default -> "v26_1";
};
Class<?> platformClass = Class.forName(TERRA_PACKAGE + ".nms." + bindingsVersion + ".NMSPlatform");
PlatformImpl platform = (PlatformImpl) platformClass
.getConstructor(TerraBukkitPlugin.class)
.newInstance(plugin);
if(platform instanceof BukkitNMSAccess nmsAccess) {
BukkitUtils.setNMSAccess(nmsAccess);
}
return platform;
} catch(ReflectiveOperationException e) {
throw new RuntimeException("Error initializing NMS bindings. Report this to Terra.", e);
}
}
}
@@ -17,7 +17,8 @@
package com.dfsek.terra.bukkit;
import io.papermc.paper.threadedregions.scheduler.AsyncScheduler;
import io.papermc.paper.ServerBuildInfo;
import io.papermc.paper.ServerBuildInfo.StringRepresentation;
import io.papermc.paper.threadedregions.scheduler.GlobalRegionScheduler;
import org.bukkit.Bukkit;
import org.bukkit.generator.ChunkGenerator;
@@ -32,40 +33,31 @@ import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.dfsek.terra.api.command.CommandSender;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.event.events.platform.CommandRegistrationEvent;
import com.dfsek.terra.api.event.events.platform.PlatformInitializationEvent;
import com.dfsek.terra.bukkit.generator.BukkitChunkGeneratorWrapper;
import com.dfsek.terra.bukkit.listeners.BiomeListener;
import com.dfsek.terra.bukkit.listeners.CommonListener;
import com.dfsek.terra.bukkit.util.PaperUtil;
import com.dfsek.terra.bukkit.util.VersionUtil;
import com.dfsek.terra.bukkit.world.BiomeHandler;
import com.dfsek.terra.bukkit.world.BukkitAdapter;
public class TerraBukkitPlugin extends JavaPlugin {
private static final Logger logger = LoggerFactory.getLogger(TerraBukkitPlugin.class);
private final Map<String, com.dfsek.terra.api.world.chunk.generation.ChunkGenerator> generatorMap = new HashMap<>();
private PlatformImpl platform;
private AsyncScheduler asyncScheduler = this.getServer().getAsyncScheduler();
private GlobalRegionScheduler globalRegionScheduler = this.getServer().getGlobalRegionScheduler();
private BukkitPlatform platform;
@Override
public void onEnable() {
if(!doVersionCheck()) {
return;
}
logServerVersion();
platform = NMSInitializer.init(this);
if(platform == null) {
Bukkit.getPluginManager().disablePlugin(this);
return;
}
platform.getEventManager().callEvent(new PlatformInitializationEvent());
platform = new BukkitPlatform(this);
platform.getEventManager().callEvent(new PlatformInitializationEvent()); // Loads config packs
BiomeHandler.registerBiomes(platform.getRawConfigRegistry());
BiomeHandler.addToVanillaTags(platform.getRawConfigRegistry());
try {
PaperCommandManager<CommandSender> commandManager = getCommandSenderPaperCommandManager();
@@ -84,7 +76,7 @@ public class TerraBukkitPlugin extends JavaPlugin {
}
Bukkit.getPluginManager().registerEvents(new CommonListener(platform), this); // Register master event listener
PaperUtil.checkPaper(this);
Bukkit.getPluginManager().registerEvents(new BiomeListener(platform), this);
}
@NotNull
@@ -101,80 +93,14 @@ public class TerraBukkitPlugin extends JavaPlugin {
return commandManager;
}
public PlatformImpl getPlatform() {
public BukkitPlatform getPlatform() {
return platform;
}
@SuppressWarnings({ "deprecation", "AccessOfSystemProperties" })
private boolean doVersionCheck() {
logger.info("Running on Minecraft version {} with server implementation {}.", VersionUtil.getMinecraftVersionInfo(),
Bukkit.getServer().getName());
if(!VersionUtil.getSpigotVersionInfo().isSpigot())
logger.error("YOU ARE RUNNING A CRAFTBUKKIT OR BUKKIT SERVER. PLEASE UPGRADE TO PAPER.");
if(!VersionUtil.getSpigotVersionInfo().isPaper())
logger.error("YOU ARE RUNNING A SPIGOT SERVER. PLEASE UPGRADE TO PAPER.");
if(VersionUtil.getSpigotVersionInfo().isMohist()) {
if(System.getProperty("IKnowMohistCausesLotsOfIssuesButIWillUseItAnyways") == null) {
Runnable runnable = () -> { // scary big block of text
logger.error("""
.----------------------------------------------------------------------------------.
| |
| ⚠ !! Warning !! ⚠ |
| |
| You are currently using Mohist. |
| |
| Do not use Mohist. |
| |
| The concept of combining the rigid Bukkit platform, which assumes a 100% |
| Vanilla server, with the flexible Forge platform, which allows changing |
| core components of the game, simply does not work. These platforms are |
| incompatible at a conceptual level, the only way to combine them would |
| be to make incompatible changes to both. As a result, Mohist's Bukkit |
| API implementation is not compliant. This will cause many plugins to |
| break. Rather than fix their platform, Mohist has chosen to distribute |
| unofficial builds of plugins they deem to be "fixed". These builds are not |
| "fixed", they are simply hacked together to work with Mohist's half-baked |
| Bukkit implementation. To distribute these as "fixed" versions implies that: |
| - These builds are endorsed by the original developers. (They are not) |
| - The issue is on the plugin's end, not Mohist's. (It is not. The issue |
| is that Mohist chooses to not create a compliant Bukkit implementation) |
| Please, do not use Mohist. It causes issues with most plugins, and rather |
| than fixing their platform, Mohist has chosen to distribute unofficial |
| hacked-together builds of plugins, calling them "fixed". If you want |
| to use a server API with Forge mods, look at the Sponge project, an |
| API that is designed to be implementation-agnostic, with first-party |
| support for the Forge mod loader. You are bound to encounter issues if |
| you use Terra with Mohist. We will provide NO SUPPORT for servers running |
| Mohist. If you wish to proceed anyways, you can add the JVM System Property |
| "IKnowMohistCausesLotsOfIssuesButIWillUseItAnyways" to enable the plugin. No |
| support will be provided for servers running Mohist. |
| |
| Because of this **TERRA HAS BEEN DISABLED**. |
| Do not come ask us why it is not working. |
| |
|----------------------------------------------------------------------------------|
""".strip());
};
runnable.run();
asyncScheduler.runDelayed(this, task -> runnable.run(), 200L, TimeUnit.SECONDS);
// Bukkit.shutdown(); // we're not *that* evil
Bukkit.getPluginManager().disablePlugin(this);
return false;
} else {
logger.warn("""
You are using Mohist, so we will not give you any support for issues that may arise.
Since you enabled the "IKnowMohistCausesLotsOfIssuesButIWillUseItAnyways" flag, we won't disable Terra. But be warned.
> I felt a great disturbance in the JVM, as if millions of plugins suddenly cried out in stack traces and were suddenly silenced.
> I fear something terrible has happened.
> - Astrash
""".strip());
}
}
return true;
private void logServerVersion() {
ServerBuildInfo buildInfo = ServerBuildInfo.buildInfo();
logger.info("Running on Minecraft version {} with server implementation {} {}.", buildInfo.minecraftVersionName(),
buildInfo.brandName(), buildInfo.asString(StringRepresentation.VERSION_SIMPLE));
}
@Override
@@ -188,11 +114,7 @@ public class TerraBukkitPlugin extends JavaPlugin {
}), platform.getRawConfigRegistry().getByID(id).orElseThrow(), platform.getWorldHandle().air());
}
public AsyncScheduler getAsyncScheduler() {
return asyncScheduler;
}
public GlobalRegionScheduler getGlobalRegionScheduler() {
return globalRegionScheduler;
return getServer().getGlobalRegionScheduler();
}
}
@@ -1,11 +1,10 @@
package com.dfsek.terra.bukkit.nms.config;
package com.dfsek.terra.bukkit.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.core.registries.BuiltInRegistries;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.attribute.AmbientAdditionsSettings;
import dev.wyck.environment.sounds.AmbientAdditionsSettings;
import dev.wyck.environment.sounds.SoundEvent;
public class BiomeAdditionsSoundTemplate implements ObjectTemplate<AmbientAdditionsSettings> {
@@ -22,7 +21,10 @@ public class BiomeAdditionsSoundTemplate implements ObjectTemplate<AmbientAdditi
if(sound == null || soundChance == null) {
return null;
} else {
return new AmbientAdditionsSettings(BuiltInRegistries.SOUND_EVENT.wrapAsHolder(sound), soundChance);
return AmbientAdditionsSettings.builder()
.soundEvent(sound)
.tickChance(soundChance)
.build();
}
}
}
@@ -1,11 +1,10 @@
package com.dfsek.terra.bukkit.nms.config;
package com.dfsek.terra.bukkit.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.core.registries.BuiltInRegistries;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.attribute.AmbientMoodSettings;
import dev.wyck.environment.sounds.AmbientMoodSettings;
import dev.wyck.environment.sounds.SoundEvent;
public class BiomeMoodSoundTemplate implements ObjectTemplate<AmbientMoodSettings> {
@@ -30,8 +29,12 @@ public class BiomeMoodSoundTemplate implements ObjectTemplate<AmbientMoodSetting
if(sound == null || soundCultivationTicks == null || soundSpawnRange == null || soundExtraDistance == null) {
return null;
} else {
return new AmbientMoodSettings(BuiltInRegistries.SOUND_EVENT.wrapAsHolder(sound), soundCultivationTicks, soundSpawnRange,
soundExtraDistance);
return AmbientMoodSettings.builder()
.soundEvent(sound)
.tickDelay(soundCultivationTicks)
.blockSearchExtent(soundSpawnRange)
.soundPositionOffset(soundExtraDistance)
.build();
}
}
}
@@ -0,0 +1,42 @@
package com.dfsek.terra.bukkit.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 com.mojang.brigadier.exceptions.CommandSyntaxException;
import dev.wyck.environment.particle.AmbientParticle;
import dev.wyck.environment.particle.ParticleCatalog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import com.dfsek.terra.bukkit.util.VanillaParticles;
public class BiomeParticleConfigTemplate implements ObjectTemplate<ParticleCatalog> {
private static final Logger LOGGER = LoggerFactory.getLogger(BiomeParticleConfigTemplate.class);
@Value("particle")
@Default
private String particle = null;
@Value("probability")
@Default
private Float probability = 0.1f;
@Override
public ParticleCatalog get() {
if(particle == null) {
return null;
}
try {
AmbientParticle parsed = VanillaParticles.parse(particle, probability);
return parsed == null ? null : new ParticleCatalog(List.of(parsed));
} catch(CommandSyntaxException | RuntimeException e) {
LOGGER.warn("Skipping particle \"{}\": {}", particle, e.getMessage());
return null;
}
}
}
@@ -0,0 +1,22 @@
package com.dfsek.terra.bukkit.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 dev.wyck.keys.ResourceKey;
import io.papermc.paper.registry.RegistryAccess;
import io.papermc.paper.registry.RegistryKey;
import org.bukkit.entity.EntityType;
public class EntityTypeTemplate implements ObjectTemplate<EntityType> {
@Value("id")
@Default
private ResourceKey id = null;
@Override
public EntityType get() {
return RegistryAccess.registryAccess().getRegistry(RegistryKey.ENTITY_TYPE)
.getOrThrow(id);
}
}
@@ -1,11 +1,10 @@
package com.dfsek.terra.bukkit.nms.config;
package com.dfsek.terra.bukkit.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.core.registries.BuiltInRegistries;
import net.minecraft.sounds.Music;
import net.minecraft.sounds.SoundEvent;
import dev.wyck.environment.sounds.Music;
import dev.wyck.environment.sounds.SoundEvent;
public class MusicSoundTemplate implements ObjectTemplate<Music> {
@@ -30,7 +29,12 @@ public class MusicSoundTemplate implements ObjectTemplate<Music> {
if(sound == null || minDelay == null || maxDelay == null || replaceCurrentMusic == null) {
return null;
} else {
return new Music(BuiltInRegistries.SOUND_EVENT.wrapAsHolder(sound), minDelay, maxDelay, replaceCurrentMusic);
return Music.builder()
.sound(sound)
.minDelay(minDelay)
.maxDelay(maxDelay)
.replaceCurrentMusic(replaceCurrentMusic)
.build();
}
}
}
@@ -1,16 +1,16 @@
package com.dfsek.terra.bukkit.nms.config;
package com.dfsek.terra.bukkit.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.resources.Identifier;
import net.minecraft.sounds.SoundEvent;
import dev.wyck.environment.sounds.SoundEvent;
import dev.wyck.keys.ResourceKey;
public class SoundEventTemplate implements ObjectTemplate<SoundEvent> {
@Value("id")
@Default
private Identifier id = null;
private ResourceKey id = null;
@Value("distance-to-travel")
@Default
@@ -21,9 +21,9 @@ public class SoundEventTemplate implements ObjectTemplate<SoundEvent> {
if(id == null) {
return null;
} else if(distanceToTravel == null) {
return SoundEvent.createVariableRangeEvent(id);
return SoundEvent.variableRange(id);
} else {
return SoundEvent.createFixedRangeEvent(id, distanceToTravel);
return SoundEvent.fixedRange(id, distanceToTravel);
}
}
}
@@ -1,15 +1,15 @@
package com.dfsek.terra.bukkit.nms.config;
package com.dfsek.terra.bukkit.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.world.entity.EntityType;
import org.bukkit.entity.EntityType;
public class SpawnCostConfig implements ObjectTemplate<SpawnCostConfig> {
@Value("type")
@Default
private EntityType<?> type = null;
private EntityType type = null;
@Value("mass")
@Default
@@ -19,7 +19,7 @@ public class SpawnCostConfig implements ObjectTemplate<SpawnCostConfig> {
@Default
private Double gravity = null;
public EntityType<?> getType() {
public EntityType getType() {
return type;
}
@@ -1,17 +1,19 @@
package com.dfsek.terra.bukkit.nms.config;
package com.dfsek.terra.bukkit.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.world.entity.EntityType;
import com.dfsek.terra.api.util.range.Range;
import dev.wyck.worldgen.valueproviders.IntProvider;
import org.bukkit.entity.EntityType;
public class SpawnEntryConfig implements ObjectTemplate<SpawnEntryConfig> {
@Value("type")
@Default
private EntityType<?> type = null;
private EntityType type = null;
@Value("weight")
@Default
@@ -25,16 +27,12 @@ public class SpawnEntryConfig implements ObjectTemplate<SpawnEntryConfig> {
return weight;
}
public EntityType<?> getType() {
public EntityType getType() {
return type;
}
public int getMinCount() {
return groupSize.getMin();
}
public int getMaxCount() {
return groupSize.getMax();
public IntProvider getCount() {
return IntProvider.uniform(groupSize.getMin(), groupSize.getMax());
}
@Override
@@ -0,0 +1,54 @@
package com.dfsek.terra.bukkit.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 dev.wyck.biome.entity.MobCategory;
import dev.wyck.biome.entity.MobSpawnSettings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
public class SpawnSettingsTemplate implements ObjectTemplate<MobSpawnSettings> {
private static final Logger LOGGER = LoggerFactory.getLogger(SpawnSettingsTemplate.class);
private static final AtomicBoolean PROBABILITY_WARNING_LOGGED = new AtomicBoolean(false);
@Value("spawns")
@Default
private List<SpawnTypeConfig> spawns = null;
@Value("costs")
@Default
private List<SpawnCostConfig> costs = null;
@Value("probability")
@Default
private Float probability = null;
@Override
public MobSpawnSettings get() {
MobSpawnSettings.Builder builder = MobSpawnSettings.builder();
if(spawns != null) {
for(SpawnTypeConfig spawn : spawns) {
MobCategory group = spawn.getGroup();
for(SpawnEntryConfig entry : spawn.getEntries()) {
builder.addSpawn(entry.getType(), group, entry.getWeight(), entry.getCount());
}
}
}
if(costs != null) {
for(SpawnCostConfig cost : costs) {
builder.addMobSpawnCost(cost.getType(), cost.getMass(), cost.getGravity());
}
}
if(probability != null && PROBABILITY_WARNING_LOGGED.compareAndSet(false, true)) {
LOGGER.warn("Biome spawning.probability is ignored on this server version.");
}
return builder.build();
}
}
@@ -1,9 +1,9 @@
package com.dfsek.terra.bukkit.nms.config;
package com.dfsek.terra.bukkit.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.world.entity.MobCategory;
import dev.wyck.biome.entity.MobCategory;
import java.util.List;
@@ -1,21 +1,22 @@
package com.dfsek.terra.bukkit.nms.config;
package com.dfsek.terra.bukkit.config;
import com.dfsek.tectonic.api.config.template.ConfigTemplate;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import net.minecraft.resources.ResourceKey;
import net.minecraft.sounds.Music;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.attribute.AmbientAdditionsSettings;
import net.minecraft.world.attribute.AmbientMoodSettings;
import net.minecraft.world.attribute.AmbientParticle;
import net.minecraft.world.entity.npc.villager.VillagerType;
import net.minecraft.world.level.biome.Biome.TemperatureModifier;
import net.minecraft.world.level.biome.BiomeSpecialEffects.GrassColorModifier;
import net.minecraft.world.level.biome.MobSpawnSettings;
import com.dfsek.terra.api.properties.Properties;
import dev.wyck.biome.TemperatureModifier;
import dev.wyck.biome.entity.MobSpawnSettings;
import dev.wyck.environment.GrassColorModifier;
import dev.wyck.environment.particle.AmbientParticle;
import dev.wyck.environment.particle.ParticleCatalog;
import dev.wyck.environment.sounds.AmbientAdditionsSettings;
import dev.wyck.environment.sounds.AmbientMoodSettings;
import dev.wyck.environment.sounds.Music;
import dev.wyck.environment.sounds.SoundEvent;
import org.bukkit.entity.Villager;
public class VanillaBiomeProperties implements ConfigTemplate, Properties {
@Value("colors.grass")
@@ -52,7 +53,7 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties {
@Value("particles")
@Default
private AmbientParticle particleConfig = null;
private ParticleCatalog particleConfig = null;
@Value("climate.precipitation")
@Default
@@ -96,7 +97,7 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties {
@Value("villager-type")
@Default
private ResourceKey<VillagerType> villagerType = null;
private Villager.Type villagerType = null;
public Integer getFogColor() {
return fogColor;
@@ -130,7 +131,7 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties {
return grassColorModifier;
}
public AmbientParticle getParticleConfig() {
public ParticleCatalog getParticles() {
return particleConfig;
}
@@ -174,7 +175,7 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties {
return spawnSettings;
}
public ResourceKey<VillagerType> getVillagerType() {
public Villager.Type getVillagerType() {
return villagerType;
}
}
@@ -0,0 +1,22 @@
package com.dfsek.terra.bukkit.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 dev.wyck.keys.ResourceKey;
import io.papermc.paper.registry.RegistryAccess;
import io.papermc.paper.registry.RegistryKey;
import org.bukkit.entity.Villager;
public class VillagerTypeTemplate implements ObjectTemplate<Villager.Type> {
@Value("id")
@Default
private ResourceKey id = null;
@Override
public Villager.Type get() {
return RegistryAccess.registryAccess().getRegistry(RegistryKey.VILLAGER_TYPE)
.getOrThrow(id);
}
}
@@ -10,6 +10,8 @@ import java.util.stream.StreamSupport;
import com.dfsek.terra.api.Handle;
import com.dfsek.terra.api.world.biome.Biome;
import com.dfsek.terra.bukkit.world.BukkitBiomeInfo;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
public class BukkitBiomeProvider extends BiomeProvider implements Handle {
@@ -19,17 +21,23 @@ public class BukkitBiomeProvider extends BiomeProvider implements Handle {
@Override
public @NotNull org.bukkit.block.Biome getBiome(@NotNull WorldInfo worldInfo, int x, int y, int z) {
Biome biome = delegate.getBiome(x, y, z, worldInfo.getSeed());
return (org.bukkit.block.Biome) biome.getPlatformBiome().getHandle();
return toBukkit(delegate.getBiome(x, y, z, worldInfo.getSeed()));
}
@Override
public @NotNull List<org.bukkit.block.Biome> getBiomes(@NotNull WorldInfo worldInfo) {
return StreamSupport.stream(delegate.getBiomes().spliterator(), false)
.map(terraBiome -> (org.bukkit.block.Biome) terraBiome.getPlatformBiome().getHandle())
.map(BukkitBiomeProvider::toBukkit)
.collect(Collectors.toList());
}
private static org.bukkit.block.Biome toBukkit(Biome biome) {
BukkitPlatformBiome platformBiome = (BukkitPlatformBiome) biome.getPlatformBiome();
return platformBiome.getContext().has(BukkitBiomeInfo.class)
? platformBiome.getContext().get(BukkitBiomeInfo.class).bukkitBiome()
: platformBiome.getHandle();
}
@Override
public Object getHandle() {
return delegate;
@@ -17,7 +17,12 @@
package com.dfsek.terra.bukkit.generator;
import org.bukkit.HeightMap;
import org.bukkit.Material;
import org.bukkit.Tag;
import org.bukkit.World;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Waterlogged;
import org.bukkit.generator.BiomeProvider;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.WorldInfo;
@@ -33,8 +38,9 @@ import com.dfsek.terra.api.block.state.BlockState;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.world.chunk.generation.ChunkGenerator;
import com.dfsek.terra.api.world.chunk.generation.util.GeneratorWrapper;
import com.dfsek.terra.api.world.info.WorldProperties;
import com.dfsek.terra.bukkit.util.BukkitUtils;
import com.dfsek.terra.bukkit.world.BukkitWorldProperties;
import com.dfsek.terra.bukkit.world.block.data.BukkitBlockState;
public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGenerator implements GeneratorWrapper {
@@ -67,6 +73,32 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener
delegate.generateChunkData(new BukkitProtoChunk(chunkData), properties, pack.getBiomeProvider(), x, z);
}
@Override
public int getBaseHeight(@NotNull WorldInfo worldInfo, @NotNull Random random, int x, int z, @NotNull HeightMap heightMap) {
BukkitWorldProperties properties = new BukkitWorldProperties(worldInfo);
com.dfsek.terra.api.world.biome.generation.BiomeProvider biomeProvider = pack.getBiomeProvider();
int y = properties.getMaxHeight();
while(y > properties.getMinHeight() &&
!isHeightmapBlock(heightMap, ((BukkitBlockState) delegate.getBlock(properties, x, y - 1, z, biomeProvider)).getHandle())) {
y--;
}
return y;
}
private static boolean isHeightmapBlock(HeightMap heightMap, BlockData data) {
Material material = data.getMaterial();
return switch(heightMap) {
case WORLD_SURFACE, WORLD_SURFACE_WG -> !material.isAir();
case OCEAN_FLOOR, OCEAN_FLOOR_WG -> material.isSolid();
case MOTION_BLOCKING -> material.isSolid() || hasFluid(data);
case MOTION_BLOCKING_NO_LEAVES -> (material.isSolid() || hasFluid(data)) && !Tag.LEAVES.isTagged(material);
};
}
private static boolean hasFluid(BlockData data) {
return BukkitUtils.isLiquid(data) || (data instanceof Waterlogged waterlogged && waterlogged.isWaterlogged());
}
@Override
public @NotNull List<BlockPopulator> getDefaultPopulators(@NotNull World world) {
return List.of(blockPopulator);
@@ -106,22 +138,4 @@ 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();
}
}
}
@@ -17,17 +17,18 @@
package com.dfsek.terra.bukkit.handles;
import io.papermc.paper.registry.RegistryAccess;
import io.papermc.paper.registry.RegistryKey;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.Registry;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import com.dfsek.terra.api.handle.ItemHandle;
import com.dfsek.terra.api.inventory.Item;
import com.dfsek.terra.api.inventory.item.Enchantment;
import com.dfsek.terra.bukkit.util.MinecraftUtils;
import com.dfsek.terra.bukkit.world.BukkitAdapter;
@@ -40,12 +41,16 @@ public class BukkitItemHandle implements ItemHandle {
@Override
public Enchantment getEnchantment(String id) {
return BukkitAdapter.adapt(
org.bukkit.enchantments.Enchantment.getByKey(NamespacedKey.minecraft(MinecraftUtils.stripMinecraftNamespace(id))));
NamespacedKey key = NamespacedKey.fromString(id);
return BukkitAdapter.adapt(key == null ? null : enchantments().get(key));
}
@Override
public Set<Enchantment> getEnchantments() {
return Arrays.stream(org.bukkit.enchantments.Enchantment.values()).map(BukkitAdapter::adapt).collect(Collectors.toSet());
return enchantments().stream().map(BukkitAdapter::adapt).collect(Collectors.toSet());
}
private static Registry<org.bukkit.enchantments.Enchantment> enchantments() {
return RegistryAccess.registryAccess().getRegistry(RegistryKey.ENCHANTMENT);
}
}
@@ -19,7 +19,6 @@ package com.dfsek.terra.bukkit.handles;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.block.data.BlockData;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -30,8 +29,6 @@ import com.dfsek.terra.api.handle.WorldHandle;
import com.dfsek.terra.bukkit.util.BukkitUtils;
import com.dfsek.terra.bukkit.world.block.data.BukkitBlockState;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class BukkitWorldHandle implements WorldHandle {
@@ -44,18 +41,13 @@ public class BukkitWorldHandle implements WorldHandle {
@Override
public synchronized @NotNull BlockState createBlockState(@NotNull String data) {
// BlockData can't hold block entity NBT.
int nbtStart = data.indexOf('{');
String state = nbtStart >= 0 ? data.substring(0, nbtStart) : data;
try {
org.bukkit.block.data.BlockData bukkitData = Bukkit.createBlockData(data); // somehow bukkit managed to make this not thread safe! :)
return BukkitBlockState.newInstance(bukkitData);
} catch (Exception ignored) {
try {
Class<?> hacks = Class.forName("com.dfsek.terra.bukkit.nms.AwfulBukkitHacks");
Method method = hacks.getMethod("createBlockState", String.class);
Object result = method.invoke(null, data);
return BukkitBlockState.newInstance((BlockData) result);
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalArgumentException("Invalid block state data: " + data);
}
return BukkitBlockState.newInstance(Bukkit.createBlockData(state)); // somehow bukkit managed to make this not thread safe! :)
} catch(IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid block state data: " + data, e);
}
}
@@ -0,0 +1,73 @@
package com.dfsek.terra.bukkit.listeners;
import io.papermc.paper.event.server.ServerResourcesReloadedEvent;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Villager;
import org.bukkit.entity.ZombieVillager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.entity.EntityBreedEvent;
import java.util.Set;
import com.dfsek.terra.bukkit.BukkitPlatform;
import com.dfsek.terra.bukkit.world.BiomeHandler;
public class BiomeListener implements Listener {
private static final Set<SpawnReason> BIOME_TYPED_VILLAGER_REASONS = Set.of(
SpawnReason.SPAWNER_EGG, SpawnReason.DISPENSE_EGG, SpawnReason.SPAWNER, SpawnReason.COMMAND);
private final BukkitPlatform platform;
public BiomeListener(BukkitPlatform platform) {
this.platform = platform;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onResourcesReloaded(ServerResourcesReloadedEvent event) {
BiomeHandler.addToVanillaTags(platform.getRawConfigRegistry());
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreatureSpawn(CreatureSpawnEvent event) {
SpawnReason reason = event.getSpawnReason();
if(event.getEntity() instanceof Villager villager && BIOME_TYPED_VILLAGER_REASONS.contains(reason)) {
applyBiomeType(villager);
} else if(event.getEntity() instanceof ZombieVillager zombieVillager && reason != SpawnReason.INFECTION) {
Villager.Type type = biomeType(zombieVillager);
if(type != null && zombieVillager.getVillagerType() == Villager.Type.PLAINS) {
zombieVillager.setVillagerType(type);
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBreed(EntityBreedEvent event) {
if(event.getEntity() instanceof Villager child && isNotPlains(event.getMother()) && isNotPlains(event.getFather())) {
applyBiomeType(child);
}
}
private static void applyBiomeType(Villager villager) {
Villager.Type type = biomeType(villager);
if(type != null && villager.getVillagerType() == Villager.Type.PLAINS) {
villager.setVillagerType(type);
}
}
private static Villager.Type biomeType(Entity entity) {
Location location = entity.getLocation();
if(!entity.getWorld().isChunkLoaded(location.getBlockX() >> 4, location.getBlockZ() >> 4)) return null;
return BiomeHandler.getVillagerType(entity.getWorld().getBiome(location));
}
private static boolean isNotPlains(LivingEntity parent) {
return parent instanceof Villager villager && villager.getVillagerType() != Villager.Type.PLAINS;
}
}
@@ -17,6 +17,7 @@
package com.dfsek.terra.bukkit.listeners;
import dev.wyck.keys.ResourceKey;
import org.bukkit.NamespacedKey;
import org.bukkit.World;
import org.bukkit.entity.Entity;
@@ -85,10 +86,10 @@ public class CommonListener implements Listener {
return;
}
NamespacedKey biomeKey = wolf.getWorld().getBiome(wolf.getLocation()).getKey();
ResourceKey biomeKey = ResourceKey.of(wolf.getWorld().getBiome(wolf.getLocation()).getKey());
pack.getBiomeProvider().stream()
.filter(biome -> {
NamespacedKey key = ((BukkitPlatformBiome) biome.getPlatformBiome()).getContext()
ResourceKey key = ((BukkitPlatformBiome) biome.getPlatformBiome()).getContext()
.get(BukkitBiomeInfo.class)
.biomeKey();
return key.equals(biomeKey);
@@ -1,104 +0,0 @@
/*
* This file is part of Terra.
*
* Terra is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Terra is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Terra. If not, see <https://www.gnu.org/licenses/>.
*/
package com.dfsek.terra.bukkit.listeners;
import org.bukkit.entity.Villager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntitySpawnEvent;
import org.bukkit.event.entity.VillagerAcquireTradeEvent;
import org.bukkit.event.entity.VillagerCareerChangeEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.dfsek.terra.api.Platform;
/**
* Listener to load on Spigot servers, contains Villager crash prevention and hacky ender eye redirection.
* <p>
* (This is currently loaded on all servers; once Paper accepts the StructureLocateEvent PR this will only be loaded on servers without
* StructureLocateEvent).
*/
public class SpigotListener implements Listener {
private static final Logger logger = LoggerFactory.getLogger(SpigotListener.class);
private final Platform platform;
public SpigotListener(Platform platform) {
this.platform = platform;
}
@EventHandler(priority = EventPriority.NORMAL)
public void onEnderEye(EntitySpawnEvent e) {
/*
Entity entity = e.getEntity();
if(e.getEntityType() == EntityType.ENDER_SIGNAL) {
logger.info("Detected Ender Signal...");
World w = BukkitAdapter.adapt(e.getEntity().getWorld());
EnderSignal signal = (EnderSignal) entity;
ConfiguredStructure config = tw.getConfig().getRegistry(TerraStructure.class).get(w.getConfig().getLocatable().get
("STRONGHOLD"));
if(config != null) {
logger.info("Overriding Ender Signal...");
AsyncStructureFinder finder = new AsyncStructureFinder(tw.getBiomeProvider(), config, BukkitAdapter.adapt(e.getLocation()
.toVector()), tw.getWorld(), 0, 500, location -> {
if(location != null)
signal.setTargetLocation(BukkitAdapter.adapt(location).toLocation(e.getLocation().getWorld()));
logger.info("Location: {}", location);
}, main);
finder.run(); // Do this synchronously so eye doesn't change direction several ticks after spawning.
} else
logger.warn("No overrides are defined for Strongholds. Ender Signals will not work correctly.");
}
*/
}
@EventHandler
public void onCartographerChange(VillagerAcquireTradeEvent e) {
if(!(e.getEntity() instanceof Villager))
return;
if(((Villager) e.getEntity()).getProfession() == Villager.Profession.CARTOGRAPHER) {
logger.error("""
.------------------------------------------------------------------------.
| Prevented server crash by stopping Cartographer villager from |
| spawning. Please upgrade to Paper, which has a StructureLocateEvent |
| that fixes this issue at the source, and doesn't require us to do |
| stupid band-aids. |
|------------------------------------------------------------------------|
""".strip());
e.setCancelled(true); // Cancel leveling if the villager is a Cartographer, to prevent crashing server.
}
}
@EventHandler
public void onCartographerLevel(VillagerCareerChangeEvent e) {
if(e.getProfession() == Villager.Profession.CARTOGRAPHER) {
logger.error("""
.------------------------------------------------------------------------.
| Prevented server crash by stopping Cartographer villager from leveling |
| up. Please upgrade to Paper, which has a StructureLocateEvent that |
| fixes this issue at the source, and doesn't require us to do stupid |
| band-aids. |
|------------------------------------------------------------------------|
""".strip());
e.getEntity().setProfession(Villager.Profession.NITWIT); // Give villager new profession to prevent server crash.
e.setCancelled(true);
}
}
}
@@ -1,16 +0,0 @@
package com.dfsek.terra.bukkit.util;
import org.bukkit.Location;
import org.bukkit.block.CreatureSpawner;
import com.dfsek.terra.api.entity.EntityType;
import com.dfsek.terra.api.entity.EntityTypeExtended;
public interface BukkitNMSAccess {
EntityType getEntityType(String data);
org.bukkit.entity.Entity spawnEntity(Object target, Location location, EntityType type);
void setSpawnerEntity(CreatureSpawner spawner, EntityTypeExtended type);
}
@@ -1,62 +1,82 @@
package com.dfsek.terra.bukkit.util;
import io.papermc.paper.registry.RegistryAccess;
import io.papermc.paper.registry.RegistryKey;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.Registry;
import org.bukkit.RegionAccessor;
import org.bukkit.World;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntitySnapshot;
import org.bukkit.generator.LimitedRegion;
import java.math.BigDecimal;
import java.util.Locale;
import com.dfsek.terra.api.entity.EntityType;
import com.dfsek.terra.api.entity.EntityTypeExtended;
import com.dfsek.terra.bukkit.world.entity.BukkitEntityType;
import com.dfsek.terra.bukkit.world.entity.BukkitEntityTypeExtended;
public class BukkitUtils {
private static volatile BukkitNMSAccess nmsAccess;
public static boolean isLiquid(BlockData blockState) {
Material material = blockState.getMaterial();
return material == Material.WATER || material == Material.LAVA;
}
public static void setNMSAccess(BukkitNMSAccess access) {
nmsAccess = access;
public static EntityType getEntityType(String data) {
int nbtStart = data.indexOf('{');
String id = nbtStart >= 0 ? data.substring(0, nbtStart) : data;
NamespacedKey key = NamespacedKey.fromString(id.toLowerCase(Locale.ROOT));
org.bukkit.entity.EntityType type = key == null ? null : RegistryAccess.registryAccess().getRegistry(RegistryKey.ENTITY_TYPE).get(key);
if(type == null) throw new IllegalArgumentException("Invalid entity identifier " + data);
if(nbtStart < 0) return new BukkitEntityType(type);
String snbt = data.substring(nbtStart);
createSnapshot(type, snbt, null); // fail on invalid SNBT while the pack loads
return new BukkitEntityTypeExtended(type, snbt);
}
public static EntityType getEntityType(String id) {
BukkitNMSAccess access = nmsAccess;
return access == null ? getBukkitEntityType(id) : access.getEntityType(id);
}
public static org.bukkit.entity.Entity spawnEntity(Object region, org.bukkit.Location location, EntityType entityType) {
if(entityType instanceof EntityTypeExtended) {
BukkitNMSAccess access = nmsAccess;
if(access == null) throw new IllegalStateException("Entity NBT loading requires Terra's NMS bindings");
return access.spawnEntity(region, location, entityType);
public static Entity spawnEntity(RegionAccessor region, Location location, EntityType entityType) {
if(entityType instanceof BukkitEntityTypeExtended extended) {
World world = region instanceof LimitedRegion limitedRegion ? limitedRegion.getWorld() : (World) region;
// LimitedRegion only accepts entities already inside it.
Entity entity = createSnapshot(extended.getHandle(), (String) extended.getData().getHandle(), location).createEntity(world);
return region.addEntity(entity);
}
org.bukkit.entity.EntityType bukkitType = ((BukkitEntityType) entityType).getHandle();
if(region instanceof org.bukkit.generator.LimitedRegion limitedRegion) {
return limitedRegion.spawnEntity(location, bukkitType);
}
return ((org.bukkit.World) region).spawnEntity(location, bukkitType);
return region.spawnEntity(location, ((BukkitEntityType) entityType).getHandle());
}
public static void setSpawnerEntity(CreatureSpawner spawner, EntityTypeExtended type) {
BukkitNMSAccess access = nmsAccess;
if(access == null) throw new IllegalStateException("Entity NBT loading requires Terra's NMS bindings");
access.setSpawnerEntity(spawner, type);
if(!(type instanceof BukkitEntityTypeExtended extended)) {
throw new IllegalArgumentException("Expected a Bukkit entity type with NBT data");
}
spawner.setSpawnedEntity(createSnapshot(extended.getHandle(), (String) extended.getData().getHandle(), null));
}
private static EntityType getBukkitEntityType(String data) {
int nbtStart = data.indexOf('{');
if(nbtStart >= 0) {
throw new IllegalArgumentException("Entity NBT loading requires Terra's NMS bindings: " + data);
}
private static EntitySnapshot createSnapshot(org.bukkit.entity.EntityType type, String snbt, Location position) {
String body = snbt.strip();
if(!body.startsWith("{") || !body.endsWith("}")) throw new IllegalArgumentException("Invalid entity NBT: " + snbt);
body = body.substring(1, body.length() - 1).strip();
NamespacedKey key = NamespacedKey.fromString(data);
org.bukkit.entity.EntityType type = key == null ? null : Registry.ENTITY_TYPE.get(key);
if(type == null) throw new IllegalArgumentException("Invalid entity identifier " + data);
return new BukkitEntityType(type);
StringBuilder compound = new StringBuilder("{id:\"").append(type.getKey()).append('"');
if(position != null) {
compound.append(",Pos:[").append(snbtDouble(position.getX())).append(',').append(snbtDouble(position.getY()))
.append(',').append(snbtDouble(position.getZ())).append(']');
}
if(!body.isEmpty()) compound.append(',').append(body);
compound.append('}');
return Bukkit.getEntityFactory().createEntitySnapshot(compound.toString());
}
private static String snbtDouble(double value) {
return BigDecimal.valueOf(value).toPlainString() + "d";
}
}
@@ -1,25 +0,0 @@
/*
* This file is part of Terra.
*
* Terra is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Terra is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Terra. If not, see <https://www.gnu.org/licenses/>.
*/
package com.dfsek.terra.bukkit.util;
public final class MinecraftUtils {
public static String stripMinecraftNamespace(String in) {
if(in.startsWith("minecraft:")) return in.substring("minecraft:".length());
return in;
}
}
@@ -1,37 +0,0 @@
/*
* This file is part of Terra.
*
* Terra is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Terra is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Terra. If not, see <https://www.gnu.org/licenses/>.
*/
package com.dfsek.terra.bukkit.util;
import io.papermc.lib.PaperLib;
import java.util.concurrent.TimeUnit;
import com.dfsek.terra.bukkit.TerraBukkitPlugin;
import static io.papermc.lib.PaperLib.suggestPaper;
public final class PaperUtil {
public static void checkPaper(TerraBukkitPlugin plugin) {
plugin.getAsyncScheduler().runDelayed(plugin, task -> {
if(!PaperLib.isPaper()) {
suggestPaper(plugin);
}
}, 100L, TimeUnit.SECONDS);
}
}
@@ -0,0 +1,86 @@
package com.dfsek.terra.bukkit.util;
import com.mojang.brigadier.LiteralMessage;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import dev.wyck.environment.particle.AmbientParticle;
import org.bukkit.Bukkit;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
public final class VanillaParticles {
private static final Logger LOGGER = LoggerFactory.getLogger(VanillaParticles.class);
private static final SimpleCommandExceptionType TRAILING_DATA = new SimpleCommandExceptionType(
new LiteralMessage("Unexpected text after the particle"));
private VanillaParticles() {
}
public static @Nullable AmbientParticle parse(String particle, float probability) throws CommandSyntaxException {
Handles handles = Holder.HANDLES;
if(handles == null) return null;
StringReader reader = new StringReader(particle.strip());
Object options;
Object ambient;
try {
options = handles.readParticle.invokeExact(reader, handles.registries);
ambient = handles.ambientParticle.invokeExact(options, probability);
} catch(CommandSyntaxException | RuntimeException | Error e) {
throw e;
} catch(Throwable e) {
throw new IllegalStateException(e);
}
if(reader.canRead()) throw TRAILING_DATA.createWithContext(reader);
return AmbientParticle.decode(ambient);
}
private static @Nullable Handles resolve() {
String step = "net.minecraft.server.MinecraftServer";
try {
ClassLoader loader = Bukkit.getServer().getClass().getClassLoader();
MethodHandles.Lookup lookup = MethodHandles.publicLookup();
Class<?> server = Class.forName(step, false, loader);
step = "MinecraftServer.getServer()";
Object instance = lookup.findStatic(server, "getServer", MethodType.methodType(server)).invoke();
if(instance == null) throw new IllegalStateException("the server has not started");
step = "MinecraftServer.registryAccess()";
Object registries = lookup.findVirtual(server, "registryAccess",
MethodType.methodType(Class.forName("net.minecraft.core.RegistryAccess$Frozen", false, loader))).invoke(instance);
step = "ParticleArgument.readParticle(StringReader, HolderLookup.Provider)";
Class<?> provider = Class.forName("net.minecraft.core.HolderLookup$Provider", false, loader);
Class<?> options = Class.forName("net.minecraft.core.particles.ParticleOptions", false, loader);
MethodHandle readParticle = lookup.findStatic(Class.forName("net.minecraft.commands.arguments.ParticleArgument", false, loader),
"readParticle", MethodType.methodType(options, StringReader.class, provider))
.asType(MethodType.methodType(Object.class, StringReader.class, Object.class));
step = "AmbientParticle(ParticleOptions, float)";
MethodHandle ambientParticle = lookup.findConstructor(Class.forName("net.minecraft.world.attribute.AmbientParticle", false, loader),
MethodType.methodType(void.class, options, float.class))
.asType(MethodType.methodType(Object.class, Object.class, float.class));
return new Handles(readParticle, registries, ambientParticle);
} catch(Throwable e) {
LOGGER.warn("Biome particles are disabled: could not find vanilla's {} ({}). " +
"This Minecraft version is probably not supported yet.", step, e.toString());
return null;
}
}
private record Handles(MethodHandle readParticle, Object registries, MethodHandle ambientParticle) {
}
private static final class Holder {
private static final @Nullable Handles HANDLES = resolve();
}
}
@@ -1,134 +0,0 @@
package com.dfsek.terra.bukkit.util;
import io.papermc.lib.PaperLib;
import org.bukkit.Bukkit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class VersionUtil {
public static final SpigotVersionInfo SPIGOT_VERSION_INFO;
public static final MinecraftVersionInfo MINECRAFT_VERSION_INFO;
private static final Logger logger = LoggerFactory.getLogger(VersionUtil.class);
static {
SPIGOT_VERSION_INFO = new SpigotVersionInfo();
MinecraftVersionInfo mcVersionInfo;
try {
mcVersionInfo = new MinecraftVersionInfo();
} catch(Throwable t) {
logger.error("Error while parsing minecraft version info. Continuing launch, but setting all versions to -1.");
mcVersionInfo = new MinecraftVersionInfo(-1, -1, -1);
}
MINECRAFT_VERSION_INFO = mcVersionInfo;
}
public static MinecraftVersionInfo getMinecraftVersionInfo() {
return MINECRAFT_VERSION_INFO;
}
public static SpigotVersionInfo getSpigotVersionInfo() {
return SPIGOT_VERSION_INFO;
}
public static final class SpigotVersionInfo {
private final boolean spigot;
private final boolean paper;
private final boolean mohist;
public SpigotVersionInfo() {
logger.debug("Parsing spigot version info...");
paper = PaperLib.isPaper();
spigot = PaperLib.isSpigot();
boolean isMohist = false;
try {
Class.forName("com.mohistmc.MohistMC");
// it's mohist
isMohist = true;
} catch(ClassNotFoundException ignore) { }
this.mohist = isMohist;
logger.debug("Spigot version info parsed successfully.");
}
public boolean isPaper() {
return paper;
}
public boolean isMohist() {
return mohist;
}
public boolean isSpigot() {
return spigot;
}
}
public static final class MinecraftVersionInfo {
private static final Logger logger = LoggerFactory.getLogger(MinecraftVersionInfo.class);
private static final Pattern VERSION_PATTERN = Pattern.compile("(\\d+)\\.(\\d+)(?:\\.(\\d+))?");
private final int major;
private final int minor;
private final int patch;
private MinecraftVersionInfo() {
this(Bukkit.getServer().getBukkitVersion().split("-")[0]);
}
private MinecraftVersionInfo(int major, int minor, int patch) {
this.major = major;
this.minor = minor;
this.patch = patch;
}
private MinecraftVersionInfo(String versionString) {
Matcher versionMatcher = VERSION_PATTERN.matcher(versionString);
if(versionMatcher.find()) {
major = Integer.parseInt(versionMatcher.group(1));
minor = Integer.parseInt(versionMatcher.group(2));
patch = versionMatcher.group(3) != null ? Integer.parseInt(versionMatcher.group(3)) : -1;
} else {
logger.warn("Error while parsing minecraft version info. Continuing launch, but setting all versions to -1.");
major = -1;
minor = -1;
patch = -1;
}
}
@Override
public String toString() {
if(major == -1 && minor == -1 && patch == -1)
return "Unknown";
if(patch >= 0) {
return String.format("v%d.%d.%d", major, minor, patch);
} else {
return String.format("v%d.%d", major, minor);
}
}
public int getMajor() {
return major;
}
public int getMinor() {
return minor;
}
public int getPatch() {
return patch;
}
}
}
@@ -0,0 +1,170 @@
package com.dfsek.terra.bukkit.world;
import dev.wyck.biome.Biome;
import dev.wyck.biome.BiomeSpecialEffects;
import dev.wyck.biome.ClimateSettings;
import dev.wyck.environment.attribute.EnvironmentAttributeMap;
import dev.wyck.environment.attribute.EnvironmentAttributeSupplier;
import dev.wyck.environment.attribute.EnvironmentAttributes;
import dev.wyck.environment.sounds.AmbientSounds;
import dev.wyck.environment.sounds.BackgroundMusic;
import dev.wyck.keys.ResourceKey;
import dev.wyck.registry.BiomeRegistry;
import dev.wyck.tags.TagSet;
import io.papermc.paper.registry.RegistryAccess;
import io.papermc.paper.registry.RegistryKey;
import io.papermc.paper.registry.TypedKey;
import io.papermc.paper.registry.tag.Tag;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Villager;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.properties.Context;
import com.dfsek.terra.bukkit.config.VanillaBiomeProperties;
import com.dfsek.terra.registry.master.ConfigRegistry;
public final class BiomeHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(BiomeHandler.class);
private static final Map<NamespacedKey, Villager.Type> VILLAGER_TYPES = new ConcurrentHashMap<>();
private BiomeHandler() { }
public static void registerBiomes(ConfigRegistry configRegistry) {
org.bukkit.Registry<org.bukkit.block.Biome> bukkitRegistry = RegistryAccess.registryAccess().getRegistry(RegistryKey.BIOME);
List<Biome> toRegister = new ArrayList<>();
List<Runnable> afterRegistration = new ArrayList<>();
configRegistry.forEach(pack -> pack.getRegistry(com.dfsek.terra.api.world.biome.Biome.class).forEach((key, biome) -> {
BukkitPlatformBiome platformBiome = (BukkitPlatformBiome) biome.getPlatformBiome();
ResourceKey vanillaKey = ResourceKey.of(platformBiome.getHandle().getKey());
ResourceKey terraKey = ResourceKey.of("terra", createBiomeID(pack, key));
NamespacedKey bukkitKey = new NamespacedKey(terraKey.namespace(), terraKey.path());
VanillaBiomeProperties properties = biome.getContext().has(VanillaBiomeProperties.class)
? biome.getContext().get(VanillaBiomeProperties.class)
: new VanillaBiomeProperties();
if(bukkitRegistry.get(bukkitKey) == null) {
toRegister.add(createBiome(terraKey, getBiomeOrThrow(vanillaKey), properties));
}
afterRegistration.add(() -> {
org.bukkit.block.Biome bukkitBiome = bukkitRegistry.getOrThrow(bukkitKey);
platformBiome.getContext().put(new BukkitBiomeInfo(terraKey, vanillaKey, bukkitBiome));
if(properties.getVillagerType() != null) {
VILLAGER_TYPES.put(bukkitKey, properties.getVillagerType());
}
});
}));
LOGGER.info("Registering {} custom biomes through Wyck...", toRegister.size());
BiomeRegistry.registry().register(toRegister);
afterRegistration.forEach(Runnable::run);
}
public static void addToVanillaTags(ConfigRegistry configRegistry) {
Map<TypedKey<org.bukkit.block.Biome>, Set<Biome>> terraBiomesByVanilla = new HashMap<>();
configRegistry.forEach(pack -> pack.getRegistry(com.dfsek.terra.api.world.biome.Biome.class).forEach(biome -> {
Context context = ((BukkitPlatformBiome) biome.getPlatformBiome()).getContext();
if(context.has(BukkitBiomeInfo.class)) {
BukkitBiomeInfo info = context.get(BukkitBiomeInfo.class);
TypedKey<org.bukkit.block.Biome> vanillaKey = TypedKey.create(RegistryKey.BIOME, info.vanillaKey().key());
terraBiomesByVanilla.computeIfAbsent(vanillaKey, k -> new HashSet<>()).add(Biome.reference(info.biomeKey()));
}
}));
org.bukkit.Registry<org.bukkit.block.Biome> bukkitRegistry = RegistryAccess.registryAccess().getRegistry(RegistryKey.BIOME);
int count = 0;
for(Tag<org.bukkit.block.Biome> tag : bukkitRegistry.getTags()) {
Set<Biome> members = new HashSet<>();
terraBiomesByVanilla.forEach((vanillaKey, terraBiomes) -> {
if(tag.contains(vanillaKey)) {
members.addAll(terraBiomes);
}
});
if(!members.isEmpty()) {
TagSet.ofBiomes(ResourceKey.of(tag.tagKey().key()), members).append();
count++;
}
}
LOGGER.info("Added Terra biomes to {} vanilla biome tags.", count);
}
public static @Nullable Villager.Type getVillagerType(org.bukkit.block.Biome biome) {
return VILLAGER_TYPES.get(biome.getKey());
}
public static Biome getBiomeOrThrow(ResourceKey key) {
return Biome.reference(key).wrap();
}
public static Biome createBiome(ResourceKey key, Biome vanilla, VanillaBiomeProperties properties) {
EnvironmentAttributeMap attributes = vanilla.attributes();
attributes = override(attributes, EnvironmentAttributes.FOG_COLOR, properties.getFogColor());
attributes = override(attributes, EnvironmentAttributes.WATER_FOG_COLOR, properties.getWaterFogColor());
attributes = override(attributes, EnvironmentAttributes.SKY_COLOR, properties.getSkyColor());
attributes = override(attributes, EnvironmentAttributes.AMBIENT_PARTICLES, properties.getParticles());
attributes = override(attributes, EnvironmentAttributes.MUSIC_VOLUME, properties.getMusicVolume());
attributes = override(attributes, EnvironmentAttributes.NATURAL_MOB_SPAWNS, properties.getSpawnSettings());
if(properties.getMusic() != null) {
attributes = attributes.with(EnvironmentAttributes.BACKGROUND_MUSIC,
BackgroundMusic.builder().defaultMusic(properties.getMusic()).build());
}
if(properties.getLoopSound() != null || properties.getMoodSound() != null || properties.getAdditionsSound() != null) {
AmbientSounds sounds = Objects.requireNonNullElse(attributes.get(EnvironmentAttributes.AMBIENT_SOUNDS), AmbientSounds.EMPTY);
attributes = attributes.with(EnvironmentAttributes.AMBIENT_SOUNDS, AmbientSounds.of(
properties.getLoopSound() != null ? properties.getLoopSound() : sounds.loop().orElse(null),
properties.getMoodSound() != null ? properties.getMoodSound() : sounds.mood().orElse(null),
properties.getAdditionsSound() != null ? List.of(properties.getAdditionsSound()) : sounds.additions()));
}
ClimateSettings climate = vanilla.climateSettings();
BiomeSpecialEffects effects = vanilla.specialEffects();
return Biome.builder(key)
.attributes(attributes)
.climateSettings(ClimateSettings.builder()
.hasPrecipitation(Objects.requireNonNullElse(properties.getPrecipitation(), climate.hasPrecipitation()))
.temperature(Objects.requireNonNullElse(properties.getTemperature(), climate.temperature()))
.temperatureModifier(Objects.requireNonNullElse(properties.getTemperatureModifier(), climate.temperatureModifier()))
.downfall(Objects.requireNonNullElse(properties.getDownfall(), climate.downfall()))
.build())
.specialEffects(BiomeSpecialEffects.builder()
.waterColor(Objects.requireNonNullElse(properties.getWaterColor(), effects.waterColor()))
.grassColorModifier(Objects.requireNonNullElse(properties.getGrassColorModifier(), effects.grassColorModifier()))
.grassColorOverride(orElse(properties.getGrassColor(), effects.grassColorOverride().orElse(null)))
.foliageColorOverride(orElse(properties.getFoliageColor(), effects.foliageColorOverride().orElse(null)))
.dryFoliageColorOverride(orElse(properties.getDryFoliageColor(), effects.dryFoliageColorOverride().orElse(null)))
.build())
.build();
}
public static String createBiomeID(ConfigPack pack, com.dfsek.terra.api.registry.key.RegistryKey biomeID) {
return pack.getID().toLowerCase(Locale.ROOT)
+ "/" + biomeID.getNamespace().toLowerCase(Locale.ROOT)
+ "/" + biomeID.getID().toLowerCase(Locale.ROOT);
}
private static <T> EnvironmentAttributeMap override(EnvironmentAttributeMap map, EnvironmentAttributeSupplier<T> attribute,
@Nullable T value) {
return value == null ? map : map.with(attribute, value);
}
private static @Nullable Integer orElse(@Nullable Integer value, @Nullable Integer fallback) {
return value != null ? value : fallback;
}
}
@@ -1,9 +1,9 @@
package com.dfsek.terra.bukkit.world;
import org.bukkit.NamespacedKey;
import dev.wyck.keys.ResourceKey;
import com.dfsek.terra.api.properties.Properties;
public record BukkitBiomeInfo(NamespacedKey biomeKey) implements Properties {
public record BukkitBiomeInfo(ResourceKey biomeKey, ResourceKey vanillaKey, org.bukkit.block.Biome bukkitBiome) implements Properties {
}
@@ -17,31 +17,39 @@
package com.dfsek.terra.bukkit.world.block.state;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.block.sign.Side;
import org.bukkit.block.sign.SignSide;
import org.jetbrains.annotations.NotNull;
import com.dfsek.terra.api.block.entity.SerialState;
import com.dfsek.terra.api.block.entity.Sign;
@SuppressWarnings("deprecation")
public class BukkitSign extends BukkitBlockEntity implements Sign {
private static final LegacyComponentSerializer LEGACY = LegacyComponentSerializer.legacySection();
protected BukkitSign(org.bukkit.block.Sign block) {
super(block);
}
@Override
public void setLine(int index, @NotNull String line) throws IndexOutOfBoundsException {
((org.bukkit.block.Sign) getHandle()).setLine(index, line);
front().line(index, LEGACY.deserialize(line));
}
@Override
public @NotNull String[] getLines() {
return ((org.bukkit.block.Sign) getHandle()).getLines();
return front().lines().stream().map(LEGACY::serialize).toArray(String[]::new);
}
@Override
public @NotNull String getLine(int index) throws IndexOutOfBoundsException {
return ((org.bukkit.block.Sign) getHandle()).getLine(index);
return LEGACY.serialize(front().line(index));
}
private SignSide front() {
return ((org.bukkit.block.Sign) getHandle()).getSide(Side.FRONT);
}
@Override
@@ -4,6 +4,12 @@ version: "@VERSION@"
load: "STARTUP"
authors: [ "dfsek", "duplexsystem", "Astrash", "solonovamax", "Sancires", "Aureus", "RogueShade", "OakLoaf" ]
website: "@WIKI@"
api-version: "1.21.1"
api-version: "26.3"
description: "@DESCRIPTION@"
folia-supported: true
dependencies:
server:
Wyck:
load: BEFORE
required: true
join-classpath: true
@@ -1,13 +0,0 @@
plugins {
id("io.papermc.paperweight.userdev")
}
tasks.withType<JavaCompile>().configureEach {
options.release = 25
}
dependencies {
compileOnly(project(":platforms:bukkit:common"))
compileOnly(project(":platforms:bukkit:nms:common"))
paperweight.paperDevBundle(Versions.Bukkit.paperDevBundle)
}
@@ -1,72 +0,0 @@
package com.dfsek.terra.bukkit.nms.v26_1;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.level.levelgen.Beardifier;
import net.minecraft.world.level.levelgen.DensityFunction.SinglePointContext;
import net.minecraft.world.level.StructureManager;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.MobSpawnSettings;
import net.minecraft.world.level.biome.MobSpawnSettings.SpawnerData;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.attribute.EnvironmentAttributes;
import net.minecraft.world.attribute.modifier.AttributeModifier;
import com.dfsek.terra.api.world.biome.generation.BiomeProvider;
import com.dfsek.terra.api.world.chunk.generation.ChunkGenerator;
import com.dfsek.terra.api.world.info.WorldProperties;
import com.dfsek.terra.bukkit.config.PreLoadCompatibilityOptions;
import com.dfsek.terra.bukkit.nms.NMSStructureBeardifier;
import com.dfsek.terra.bukkit.nms.NMSVersionBindings;
import com.dfsek.terra.bukkit.nms.config.VanillaBiomeProperties;
public final class Bindings implements NMSVersionBindings {
@Override
public void addSpawn(MobSpawnSettings.Builder builder, MobCategory category, EntityType<?> type, int weight,
int minCount, int maxCount) {
builder.addSpawn(category, weight, new SpawnerData(type, minCount, maxCount));
}
@Override
public void addSpawnCost(MobSpawnSettings.Builder builder, EntityType<?> type, double mass, double gravity) {
builder.addMobCharge(type, mass, gravity);
}
@Override
public boolean setCreatureGenerationProbability(MobSpawnSettings.Builder builder, float probability) {
builder.creatureGenerationProbability(probability);
return true;
}
@Override
public void copyVanillaSpawnSettings(Biome.BiomeBuilder builder, Biome biome) {
builder.mobSpawnSettings(biome.getMobSettings());
}
@Override
public void setSpawnSettings(Biome.BiomeBuilder builder, MobSpawnSettings settings) {
builder.mobSpawnSettings(settings);
}
@Override
public void applyBiomeColorOverrides(Biome.BiomeBuilder builder, VanillaBiomeProperties properties) {
if(properties.getFogColor() != null) {
builder.modifyAttribute(EnvironmentAttributes.FOG_COLOR, AttributeModifier.override(), properties.getFogColor());
}
if(properties.getWaterFogColor() != null) {
builder.modifyAttribute(EnvironmentAttributes.WATER_FOG_COLOR, AttributeModifier.override(), properties.getWaterFogColor());
}
if(properties.getSkyColor() != null) {
builder.modifyAttribute(EnvironmentAttributes.SKY_COLOR, AttributeModifier.override(), properties.getSkyColor());
}
}
@Override
public void applyStructureBeard(ChunkGenerator generator, StructureManager structures, ChunkAccess chunk, WorldProperties world,
BiomeProvider biomeProvider, PreLoadCompatibilityOptions options) {
Beardifier beardifier = Beardifier.forStructuresInChunk(structures, chunk.getPos());
NMSStructureBeardifier.apply(generator, chunk, world, biomeProvider, options,
(x, y, z) -> beardifier.compute(new SinglePointContext(x, y, z)));
}
}
@@ -1,11 +0,0 @@
package com.dfsek.terra.bukkit.nms.v26_1;
import com.dfsek.terra.bukkit.TerraBukkitPlugin;
import com.dfsek.terra.bukkit.nms.NMSPlatformBase;
public final class NMSPlatform extends NMSPlatformBase {
public NMSPlatform(TerraBukkitPlugin plugin) {
super(plugin, new Bindings());
}
}
@@ -1,13 +0,0 @@
plugins {
id("io.papermc.paperweight.userdev")
}
tasks.withType<JavaCompile>().configureEach {
options.release = 25
}
dependencies {
compileOnly(project(":platforms:bukkit:common"))
compileOnly(project(":platforms:bukkit:nms:common"))
paperweight.paperDevBundle(Versions.Bukkit.paperDevBundle26_3)
}
@@ -1,95 +0,0 @@
package com.dfsek.terra.bukkit.nms.v26_3;
import net.minecraft.util.valueproviders.UniformInt;
import net.minecraft.world.attribute.EnvironmentAttributes;
import net.minecraft.world.attribute.modifier.AttributeModifier;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.level.StructureManager;
import net.minecraft.world.level.levelgen.Beardifier;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.MobSpawnSettings;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.levelgen.densityfunction.SamplerContext;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.world.biome.generation.BiomeProvider;
import com.dfsek.terra.api.world.chunk.generation.ChunkGenerator;
import com.dfsek.terra.api.world.info.WorldProperties;
import com.dfsek.terra.bukkit.config.PreLoadCompatibilityOptions;
import com.dfsek.terra.bukkit.nms.NMSBiomeProvider;
import com.dfsek.terra.bukkit.nms.NMSChunkGeneratorDelegate;
import com.dfsek.terra.bukkit.nms.NMSStructureBeardifier;
import com.dfsek.terra.bukkit.nms.NMSVersionBindings;
import com.dfsek.terra.bukkit.nms.config.VanillaBiomeProperties;
public final class Bindings implements NMSVersionBindings {
@Override
public NMSBiomeProvider createBiomeProvider(BiomeProvider delegate, long seed) {
return new BiomeProvider26_3(delegate, seed);
}
@Override
public NMSChunkGeneratorDelegate createChunkGenerator(
net.minecraft.world.level.chunk.ChunkGenerator vanilla, ConfigPack pack,
NMSBiomeProvider biomeProvider, long seed) {
return new ChunkGenerator26_3(vanilla, pack, biomeProvider, seed, this);
}
@Override
public void addSpawn(MobSpawnSettings.Builder builder, MobCategory category, EntityType<?> type, int weight,
int minCount, int maxCount) {
builder.addSpawn(type, category, weight, UniformInt.of(minCount, maxCount));
}
@Override
public void addSpawnCost(MobSpawnSettings.Builder builder, EntityType<?> type, double mass, double gravity) {
builder.addMobSpawnCost(type, mass, gravity);
}
@Override
public boolean setCreatureGenerationProbability(MobSpawnSettings.Builder builder, float probability) {
return false;
}
@Override
public void copyVanillaSpawnSettings(Biome.BiomeBuilder builder, Biome biome) {
// 26.3 stores natural spawn settings in the biome's environment attributes,
// which NMSBiomeInjector already copies into its builder.
}
@Override
public void setSpawnSettings(Biome.BiomeBuilder builder, MobSpawnSettings settings) {
builder.setAttribute(EnvironmentAttributes.NATURAL_MOB_SPAWNS, settings);
}
@Override
public void applyBiomeColorOverrides(Biome.BiomeBuilder builder, VanillaBiomeProperties properties) {
if(properties.getFogColor() != null) {
builder.modifyAttribute(EnvironmentAttributes.FOG_COLOR, AttributeModifier.override(), color(properties.getFogColor()));
}
if(properties.getWaterFogColor() != null) {
builder.modifyAttribute(EnvironmentAttributes.WATER_FOG_COLOR, AttributeModifier.override(), color(properties.getWaterFogColor()));
}
if(properties.getSkyColor() != null) {
builder.modifyAttribute(EnvironmentAttributes.SKY_COLOR, AttributeModifier.override(), color(properties.getSkyColor()));
}
}
private static org.joml.Vector3f color(int rgb) {
return new org.joml.Vector3f(
((rgb >>> 16) & 0xFF) / 255.0f,
((rgb >>> 8) & 0xFF) / 255.0f,
(rgb & 0xFF) / 255.0f
);
}
@Override
public void applyStructureBeard(ChunkGenerator generator, StructureManager structures, ChunkAccess chunk, WorldProperties world,
BiomeProvider biomeProvider, PreLoadCompatibilityOptions options) {
Beardifier beardifier = Beardifier.forStructuresInChunk(structures, chunk.getPos());
NMSStructureBeardifier.apply(generator, chunk, world, biomeProvider, options,
(x, y, z) -> beardifier.sampleValue(SamplerContext.EMPTY_UNCACHED, x, y, z));
}
}
@@ -1,20 +0,0 @@
package com.dfsek.terra.bukkit.nms.v26_3;
import net.minecraft.world.level.biome.BiomeResolver;
import net.minecraft.world.level.biome.Climate.Sampler;
import org.jetbrains.annotations.NotNull;
import com.dfsek.terra.api.world.biome.generation.BiomeProvider;
import com.dfsek.terra.bukkit.nms.NMSBiomeProvider;
public final class BiomeProvider26_3 extends NMSBiomeProvider {
public BiomeProvider26_3(BiomeProvider delegate, long seed) {
super(delegate, seed);
}
@Override
public @NotNull BiomeResolver createResolver(@NotNull Sampler sampler) {
return (x, y, z) -> getNoiseBiome(x, y, z, sampler);
}
}
@@ -1,48 +0,0 @@
package com.dfsek.terra.bukkit.nms.v26_3;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.server.level.WorldGenRegion;
import net.minecraft.world.level.StructureManager;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeManager;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.levelgen.RandomState;
import net.minecraft.world.level.levelgen.blending.Blender;
import net.minecraft.world.level.levelgen.densityfunction.SamplerContext;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.bukkit.nms.NMSBiomeProvider;
import com.dfsek.terra.bukkit.nms.NMSChunkGeneratorDelegate;
import com.dfsek.terra.bukkit.nms.NMSVersionBindings;
public final class ChunkGenerator26_3 extends NMSChunkGeneratorDelegate {
private final ChunkGenerator vanilla;
public ChunkGenerator26_3(ChunkGenerator vanilla, ConfigPack pack, NMSBiomeProvider biomeProvider, long seed,
NMSVersionBindings bindings) {
super(vanilla, pack, biomeProvider, seed, bindings);
this.vanilla = vanilla;
}
@Override
public CompletableFuture<ChunkAccess> buildTerrain(ChunkAccess chunk, Blender blender, RandomState randomState,
StructureManager structures, BiomeManager biomeManager,
WorldGenRegion region, Set<Holder<Biome>> biomes) {
return vanilla.buildTerrain(chunk, blender, randomState, structures, biomeManager, region, biomes)
.thenApply(result -> {
applyStructureBeard(structures, result);
return result;
});
}
@Override
public void addDebugScreenInfo(List<String> text, RandomState randomState, BlockPos pos, SamplerContext context) {
}
}
@@ -1,11 +0,0 @@
package com.dfsek.terra.bukkit.nms.v26_3;
import com.dfsek.terra.bukkit.TerraBukkitPlugin;
import com.dfsek.terra.bukkit.nms.NMSPlatformBase;
public final class NMSPlatform extends NMSPlatformBase {
public NMSPlatform(TerraBukkitPlugin plugin) {
super(plugin, new Bindings());
}
}
-17
View File
@@ -1,17 +0,0 @@
plugins {
`java-library`
}
subprojects {
group = "com.dfsek.terra.bukkit.nms"
}
tasks.withType<JavaCompile>().configureEach {
options.release = 25
}
dependencies {
api(project(path = ":platforms:bukkit:nms:common", configuration = "runtimeElements"))
api(project(path = ":platforms:bukkit:nms:26.1", configuration = "runtimeElements"))
api(project(path = ":platforms:bukkit:nms:26.3", configuration = "runtimeElements"))
}
@@ -1,17 +0,0 @@
plugins {
id("io.papermc.paperweight.userdev")
}
tasks.withType<JavaCompile>().configureEach {
options.release = 25
}
dependencies {
compileOnly(project(":platforms:bukkit:common"))
compileOnly("xyz.jpenilla", "reflection-remapper", Versions.Bukkit.reflectionRemapper)
paperweight.paperDevBundle(Versions.Bukkit.paperDevBundle)
}
tasks.withType<Jar>().configureEach {
archiveBaseName.set("terra-bukkit-nms-common")
}
@@ -1,283 +0,0 @@
package com.dfsek.terra.bukkit.nms;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.commands.arguments.blocks.BlockStateParser;
import net.minecraft.commands.arguments.blocks.BlockStateParser.BlockResult;
import net.minecraft.core.Holder;
import net.minecraft.core.Holder.Reference;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.HolderSet.Named;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.RegistrationInfo;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.TagParser;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.tags.TagKey;
import net.minecraft.world.entity.EntitySpawnReason;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.npc.villager.VillagerType;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.Block;
import org.bukkit.Bukkit;
import org.bukkit.NamespacedKey;
import org.bukkit.Registry;
import org.bukkit.World;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.block.data.BlockData;
import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.craftbukkit.CraftWorld;
import org.bukkit.craftbukkit.block.data.CraftBlockData;
import org.bukkit.craftbukkit.entity.CraftEntitySnapshot;
import org.bukkit.craftbukkit.generator.CraftLimitedRegion;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import com.dfsek.terra.api.entity.EntityTypeExtended;
import com.dfsek.terra.bukkit.world.BukkitBiomeInfo;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.bukkit.nms.config.VanillaBiomeProperties;
import com.dfsek.terra.bukkit.world.entity.BukkitEntityType;
import com.dfsek.terra.bukkit.world.entity.BukkitEntityTypeExtended;
import com.dfsek.terra.registry.master.ConfigRegistry;
public class AwfulBukkitHacks {
private static final Logger LOGGER = LoggerFactory.getLogger(AwfulBukkitHacks.class);
private static final Map<Identifier, List<Identifier>> terraBiomeMap = new HashMap<>();
public static void registerBiomes(ConfigRegistry configRegistry, NMSVersionBindings bindings) {
try {
LOGGER.info("Hacking biome registry...");
MappedRegistry<Biome> biomeRegistry = (MappedRegistry<Biome>) RegistryFetcher.biomeRegistry();
// Unfreeze the biome registry to allow modification
Reflection.MAPPED_REGISTRY.setFrozen(biomeRegistry, false);
// Register the terra biomes to the registry
configRegistry.forEach(pack -> pack.getRegistry(com.dfsek.terra.api.world.biome.Biome.class).forEach((key, biome) -> {
try {
BukkitPlatformBiome platformBiome = (BukkitPlatformBiome) biome.getPlatformBiome();
NamespacedKey vanillaBukkitKey = platformBiome.getHandle().getKey();
Identifier vanillaMinecraftKey = Identifier.fromNamespaceAndPath(vanillaBukkitKey.getNamespace(),
vanillaBukkitKey.getKey());
VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class);
Biome platform = NMSBiomeInjector.createBiome(biomeRegistry.get(vanillaMinecraftKey).orElseThrow().value(),
vanillaBiomeProperties, bindings);
Identifier delegateMinecraftKey = Identifier.fromNamespaceAndPath("terra",
NMSBiomeInjector.createBiomeID(pack, key));
NamespacedKey delegateBukkitKey = NamespacedKey.fromString(delegateMinecraftKey.toString());
ResourceKey<Biome> delegateKey = ResourceKey.create(Registries.BIOME, delegateMinecraftKey);
Reference<Biome> holder = biomeRegistry.register(delegateKey, platform, RegistrationInfo.BUILT_IN);
Reflection.REFERENCE.invokeBindValue(holder, platform); // IMPORTANT: bind holder.
platformBiome.getContext().put(new BukkitBiomeInfo(delegateBukkitKey));
platformBiome.getContext().put(new NMSBiomeInfo(delegateKey));
Map<ResourceKey<Biome>, ResourceKey<VillagerType>> villagerMap = Reflection.VILLAGER_TYPE.getByBiome();
villagerMap.put(delegateKey,
Objects.requireNonNullElse(vanillaBiomeProperties.getVillagerType(),
villagerMap.getOrDefault(delegateKey, VillagerType.PLAINS)));
terraBiomeMap.computeIfAbsent(vanillaMinecraftKey, i -> new ArrayList<>()).add(delegateKey.identifier());
LOGGER.debug("Registered biome: " + delegateKey);
} catch(NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}));
Reflection.MAPPED_REGISTRY.setFrozen(biomeRegistry, true); // freeze registry again :)
LOGGER.info("Doing tag garbage....");
Map<TagKey<Biome>, List<Holder<Biome>>> collect = biomeRegistry
.getTags() // streamKeysAndEntries
.collect(HashMap::new,
(map, pair) ->
map.put(pair.key(), new ArrayList<>(Reflection.HOLDER_SET.invokeContents(pair).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 for {}): {}",
vanilla.unwrapKey().orElseThrow().identifier(),
terra.unwrapKey().orElseThrow().identifier(),
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)));
resetTags(biomeRegistry);
bindTags(biomeRegistry, collect);
} catch(SecurityException | IllegalArgumentException exception) {
throw new RuntimeException(exception);
}
}
private static <T> void bindTags(MappedRegistry<T> registry, Map<TagKey<T>, List<Holder<T>>> tagEntries) {
Map<Reference<T>, List<TagKey<T>>> map = new IdentityHashMap<>();
Reflection.MAPPED_REGISTRY.getByKey(registry).values().forEach(entry -> map.put(entry, new ArrayList<>()));
tagEntries.forEach((tag, entries) -> {
for(Holder<T> holder : entries) {
// if (!holder.canSerializeIn(registry.asLookup())) {
// throw new IllegalStateException("Can't create named set " + tag + " containing value " + holder + "
// from outside registry " + this);
// }
if(!(holder instanceof Holder.Reference<T> reference)) {
throw new IllegalStateException("Found direct holder " + holder + " value in tag " + tag);
}
map.get(reference).add(tag);
}
});
// Set<TagKey<T>> set = Sets.difference(registry.tags.keySet(), tagEntries.keySet());
// if (!set.isEmpty()) {
// LOGGER.warn(
// "Not all defined tags for registry {} are present in data pack: {}",
// registry.key(),
// set.stream().map(tag -> tag.location().toString()).sorted().collect(Collectors.joining(", "))
// );
// }
Map<TagKey<T>, Named<T>> map2 = new IdentityHashMap<>(registry.getTags().collect(Collectors.toMap(
Named::key,
(named) -> named
)));
tagEntries.forEach((tag, entries) -> Reflection.HOLDER_SET.invokeBind(
map2.computeIfAbsent(tag, key -> Reflection.MAPPED_REGISTRY.invokeCreateTag(registry, key)), entries));
map.forEach(Reflection.HOLDER_REFERENCE::invokeBindTags);
Reflection.MAPPED_REGISTRY.setAllTags(registry, Reflection.MAPPED_REGISTRY_TAG_SET.invokeFromMap(map2));
}
private static void resetTags(MappedRegistry<?> registry) {
registry.getTags().forEach(entryList -> Reflection.HOLDER_SET.invokeBind(entryList, List.of()));
Reflection.MAPPED_REGISTRY.getByKey(registry).values().forEach(
entry -> Reflection.HOLDER_REFERENCE.invokeBindTags(entry, Set.of()));
}
// used by BukkitWorldHandle
public static BlockData createBlockState(@NotNull String data) throws CommandSyntaxException {
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
HolderLookup.Provider lookup = server.registryAccess();
final HolderLookup<Block> blocks = lookup.lookupOrThrow(Registries.BLOCK);
BlockResult result = BlockStateParser.parseForBlock(blocks, new StringReader(data), true);
return CraftBlockData.createData(result.blockState());
}
public static com.dfsek.terra.api.entity.EntityType getEntityType(@NotNull String data) {
StringReader reader = new StringReader(data);
Identifier identifier;
CompoundTag entityNbt = null;
try {
identifier = Identifier.read(reader);
if(reader.canRead()) {
if(reader.peek() != '{') throw new IllegalArgumentException("Unexpected data after entity identifier: " + data);
entityNbt = TagParser.parseCompoundAsArgument(reader);
if(reader.canRead()) throw new IllegalArgumentException("Unexpected data after entity NBT: " + data);
entityNbt.putString("id", identifier.toString());
}
} catch(CommandSyntaxException e) {
throw new IllegalArgumentException("Invalid entity data: " + data, e);
}
if(BuiltInRegistries.ENTITY_TYPE.getOptional(identifier).isEmpty()) {
throw new IllegalArgumentException("Unknown entity type: " + identifier);
}
NamespacedKey key = NamespacedKey.fromString(identifier.toString());
org.bukkit.entity.EntityType bukkitType = key == null ? null : Registry.ENTITY_TYPE.get(key);
if(bukkitType == null) throw new IllegalArgumentException("Bukkit has no entity type for " + identifier);
if(entityNbt == null) return new BukkitEntityType(bukkitType);
return new BukkitEntityTypeExtended(bukkitType, entityNbt.toString());
}
public static org.bukkit.entity.Entity spawnEntity(Object target, org.bukkit.Location location,
com.dfsek.terra.api.entity.EntityType type) {
if(!(type instanceof BukkitEntityTypeExtended extended)) {
throw new IllegalArgumentException("Expected a Bukkit entity type with NBT data");
}
CompoundTag nbt = parseEntityNbt(extended);
CraftLimitedRegion limitedRegion = target instanceof CraftLimitedRegion region ? region : null;
World world = limitedRegion == null ? (World) target : limitedRegion.getWorld();
if(!(world instanceof CraftWorld craftWorld)) throw new IllegalArgumentException("Unsupported Bukkit world: " + world);
ServerLevel level = craftWorld.getHandle();
String entityIDText = nbt.getString("id")
.orElseThrow(() -> new IllegalArgumentException("Missing entity identifier in NBT"));
Identifier entityID;
try {
entityID = Identifier.read(new StringReader(entityIDText));
} catch(CommandSyntaxException e) {
throw new IllegalArgumentException("Invalid entity identifier in NBT: " + entityIDText, e);
}
EntityType<?> entityType = BuiltInRegistries.ENTITY_TYPE.getOptional(entityID)
.orElseThrow(() -> new IllegalArgumentException("Unknown entity type in NBT: " + entityID));
net.minecraft.world.entity.Entity entity = EntityType.loadEntityRecursive(entityType, nbt, level, EntitySpawnReason.STRUCTURE, loaded -> {
loaded.snapTo(location.getX(), location.getY(), location.getZ(), loaded.getYRot(), loaded.getXRot());
return loaded;
});
if(entity == null) throw new IllegalArgumentException("Could not load entity from NBT: " + nbt);
if(limitedRegion != null) {
limitedRegion.addEntityWithPassengers(entity, CreatureSpawnEvent.SpawnReason.CUSTOM);
} else if(!level.tryAddFreshEntityWithPassengers(entity, CreatureSpawnEvent.SpawnReason.CUSTOM)) {
throw new IllegalStateException("Could not add entity to world: " + nbt);
}
return entity.getBukkitEntity();
}
public static void setSpawnerEntity(CreatureSpawner spawner, EntityTypeExtended type) {
if(!(type instanceof BukkitEntityTypeExtended extended)) {
throw new IllegalArgumentException("Expected a Bukkit entity type with NBT data");
}
spawner.setSpawnedEntity(CraftEntitySnapshot.create(parseEntityNbt(extended), extended.getHandle()));
}
private static CompoundTag parseEntityNbt(BukkitEntityTypeExtended extended) {
Object rawData = extended.getData().getHandle();
if(!(rawData instanceof String snbt)) throw new IllegalArgumentException("Bukkit entity data must contain SNBT text");
try {
return TagParser.parseCompoundFully(snbt);
} catch(CommandSyntaxException e) {
throw new IllegalArgumentException("Invalid entity NBT: " + snbt, e);
}
}
}
@@ -1,31 +0,0 @@
package com.dfsek.terra.bukkit.nms;
import com.dfsek.terra.api.event.events.config.ConfigurationLoadEvent;
import com.dfsek.terra.api.event.functional.FunctionalEventHandler;
import com.dfsek.terra.api.world.biome.Biome;
import com.dfsek.terra.bukkit.BukkitAddon;
import com.dfsek.terra.bukkit.PlatformImpl;
import com.dfsek.terra.bukkit.nms.config.VanillaBiomeProperties;
public class NMSAddon extends BukkitAddon {
public NMSAddon(PlatformImpl platform) {
super(platform);
}
@Override
public void initialize() {
super.initialize();
terraBukkitPlugin.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(this, ConfigurationLoadEvent.class)
.then(event -> {
if(event.is(Biome.class)) {
event.getLoadedObject(Biome.class).getContext().put(event.load(new VanillaBiomeProperties()));
}
})
.global();
}
}
@@ -1,10 +0,0 @@
package com.dfsek.terra.bukkit.nms;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.level.biome.Biome;
import com.dfsek.terra.api.properties.Properties;
public record NMSBiomeInfo(ResourceKey<Biome> biomeKey) implements Properties {
}
@@ -1,131 +0,0 @@
package com.dfsek.terra.bukkit.nms;
import com.dfsek.terra.api.registry.key.RegistryKey;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.resources.Identifier;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.attribute.AmbientAdditionsSettings;
import net.minecraft.world.attribute.AmbientMoodSettings;
import net.minecraft.world.attribute.AmbientSounds;
import net.minecraft.world.attribute.BackgroundMusic;
import net.minecraft.world.attribute.EnvironmentAttribute;
import net.minecraft.world.attribute.EnvironmentAttributeMap;
import net.minecraft.world.attribute.EnvironmentAttributeMap.Entry;
import net.minecraft.world.attribute.EnvironmentAttributes;
import net.minecraft.world.attribute.modifier.AttributeModifier;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.Biome.BiomeBuilder;
import net.minecraft.world.level.biome.BiomeGenerationSettings;
import net.minecraft.world.level.biome.MobSpawnSettings;
import net.minecraft.world.level.biome.BiomeSpecialEffects;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.bukkit.nms.config.VanillaBiomeProperties;
public class NMSBiomeInjector {
public static <T> Optional<Holder<T>> getEntry(Registry<T> registry, Identifier identifier) {
return registry.getOptional(identifier).flatMap(registry::getResourceKey).flatMap(registry::get);
}
public static Biome createBiome(Biome vanilla, VanillaBiomeProperties vanillaBiomeProperties, NMSVersionBindings bindings)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Biome.BiomeBuilder builder = new Biome.BiomeBuilder();
BiomeSpecialEffects.Builder effects = new BiomeSpecialEffects.Builder();
EnvironmentAttributeMap attributes = vanilla.getAttributes();
builder.putAttributes(attributes);
bindings.applyBiomeColorOverrides(builder, vanillaBiomeProperties);
if(vanillaBiomeProperties.getMusicVolume() != null) {
builder.modifyAttribute(EnvironmentAttributes.MUSIC_VOLUME, AttributeModifier.override(), vanillaBiomeProperties.getMusicVolume());
}
effects.waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.getWaterColor()));
effects.grassColorModifier(
Objects.requireNonNullElse(vanillaBiomeProperties.getGrassColorModifier(), vanilla.getSpecialEffects().grassColorModifier()));
if(vanillaBiomeProperties.getGrassColor() == null) {
vanilla.getSpecialEffects().grassColorOverride().ifPresent(effects::grassColorOverride);
} else {
effects.grassColorOverride(vanillaBiomeProperties.getGrassColor());
}
if(vanillaBiomeProperties.getFoliageColor() == null) {
vanilla.getSpecialEffects().foliageColorOverride().ifPresent(effects::foliageColorOverride);
} else {
effects.foliageColorOverride(vanillaBiomeProperties.getFoliageColor());
}
if(vanillaBiomeProperties.getParticleConfig() != null) {
builder.modifyAttribute(EnvironmentAttributes.AMBIENT_PARTICLES, AttributeModifier.override(),
List.of(vanillaBiomeProperties.getParticleConfig()));
}
Optional<Holder<SoundEvent>> loop = Optional.empty();
Optional<AmbientMoodSettings> mood = Optional.empty();
List<AmbientAdditionsSettings> additions = Collections.emptyList();
AmbientSounds sounds = getAttribute(attributes, EnvironmentAttributes.AMBIENT_SOUNDS);
if(sounds != null) {
loop = sounds.loop();
mood = sounds.mood();
additions = sounds.additions();
}
if(vanillaBiomeProperties.getLoopSound() != null) {
loop = RegistryFetcher.soundEventRegistry()
.get(vanillaBiomeProperties.getLoopSound().location())
.map(ref -> ref);
}
if(vanillaBiomeProperties.getMoodSound() != null) {
mood = Optional.ofNullable(vanillaBiomeProperties.getMoodSound());
}
if(vanillaBiomeProperties.getAdditionsSound() != null) {
additions = Collections.singletonList(vanillaBiomeProperties.getAdditionsSound());
}
builder.modifyAttribute(EnvironmentAttributes.AMBIENT_SOUNDS, AttributeModifier.override(),
new AmbientSounds(loop, mood, additions));
if(vanillaBiomeProperties.getMusic() != null) {
builder.modifyAttribute(EnvironmentAttributes.BACKGROUND_MUSIC, AttributeModifier.override(),
new BackgroundMusic(vanillaBiomeProperties.getMusic()));
}
builder.hasPrecipitation(Objects.requireNonNullElse(vanillaBiomeProperties.getPrecipitation(), vanilla.hasPrecipitation()));
builder.temperature(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperature(), vanilla.getBaseTemperature()));
builder.downfall(Objects.requireNonNullElse(vanillaBiomeProperties.getDownfall(), vanilla.climateSettings.downfall()));
builder.temperatureAdjustment(
Objects.requireNonNullElse(vanillaBiomeProperties.getTemperatureModifier(), vanilla.climateSettings.temperatureModifier()));
MobSpawnSettings spawnSettings = vanillaBiomeProperties.getSpawnSettings();
if(spawnSettings == null) {
bindings.copyVanillaSpawnSettings(builder, vanilla);
} else {
bindings.setSpawnSettings(builder, spawnSettings);
}
return builder.specialEffects(effects.build()).generationSettings(new BiomeGenerationSettings.PlainBuilder().build()).build();
}
public static String createBiomeID(ConfigPack pack, RegistryKey biomeID) {
return pack.getID().toLowerCase() + "/" + biomeID.getNamespace().toLowerCase(Locale.ROOT) + "/" + biomeID.getID().toLowerCase(
Locale.ROOT);
}
private static <T> T getAttribute(EnvironmentAttributeMap attributes, EnvironmentAttribute<T> key) {
Entry<T, ?> entry = attributes.get(key);
return entry == null ? null : entry.applyModifier(key.defaultValue());
}
}
@@ -1,53 +0,0 @@
package com.dfsek.terra.bukkit.nms;
import com.mojang.serialization.MapCodec;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeSource;
import net.minecraft.world.level.biome.Climate.Sampler;
import org.jetbrains.annotations.NotNull;
import java.util.stream.Stream;
import com.dfsek.terra.api.world.biome.generation.BiomeProvider;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
public class NMSBiomeProvider extends BiomeSource {
private final BiomeProvider delegate;
private final long seed;
private final Registry<Biome> biomeRegistry = RegistryFetcher.biomeRegistry();
public NMSBiomeProvider(BiomeProvider delegate, long seed) {
super();
this.delegate = delegate;
this.seed = seed;
}
@Override
protected Stream<Holder<Biome>> collectPossibleBiomes() {
return delegate.stream()
.map(biome -> RegistryFetcher.biomeRegistry()
.getOrThrow(((BukkitPlatformBiome) biome.getPlatformBiome()).getContext()
.get(NMSBiomeInfo.class)
.biomeKey()));
}
@Override
protected @NotNull MapCodec<? extends BiomeSource> codec() {
return MapCodec.assumeMapUnsafe(BiomeSource.CODEC);
// return MapCodec.unit(null);
// BuiltInRegistries.BIOME_SOURCE.byNameCodec().dispatchMap(this::codec, Function.identity());
// BuiltInRegistries.BIOME_SOURCE.byNameCodec().dispatchStable(BiomeSource::codec, Function.identity());
// return BiomeSource.CODEC;
}
@Override
public @NotNull Holder<Biome> getNoiseBiome(int x, int y, int z, @NotNull Sampler sampler) {
return biomeRegistry.getOrThrow(((BukkitPlatformBiome) delegate.getBiome(x << 2, y << 2, z << 2, seed)
.getPlatformBiome()).getContext()
.get(NMSBiomeInfo.class)
.biomeKey());
}
}
@@ -1,142 +0,0 @@
package com.dfsek.terra.bukkit.nms;
import com.mojang.serialization.MapCodec;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.WorldGenRegion;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.LevelHeightAccessor;
import net.minecraft.world.level.NoiseColumn;
import net.minecraft.world.level.StructureManager;
import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.biome.BiomeManager;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.levelgen.Heightmap.Types;
import net.minecraft.world.level.levelgen.RandomState;
import net.minecraft.world.level.levelgen.blending.Blender;
import org.bukkit.craftbukkit.block.data.CraftBlockData;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.world.biome.generation.BiomeProvider;
import com.dfsek.terra.api.world.info.WorldProperties;
import com.dfsek.terra.bukkit.config.PreLoadCompatibilityOptions;
public class NMSChunkGeneratorDelegate extends ChunkGenerator {
private final com.dfsek.terra.api.world.chunk.generation.ChunkGenerator delegate;
private final ChunkGenerator vanilla;
private final ConfigPack pack;
private final NMSVersionBindings bindings;
private final long seed;
public NMSChunkGeneratorDelegate(ChunkGenerator vanilla, ConfigPack pack, NMSBiomeProvider biomeProvider, long seed,
NMSVersionBindings bindings) {
super(biomeProvider);
this.delegate = pack.getGeneratorProvider().newInstance(pack);
this.vanilla = vanilla;
this.pack = pack;
this.seed = seed;
this.bindings = bindings;
}
@Override
protected @NotNull MapCodec<? extends ChunkGenerator> codec() {
return MapCodec.assumeMapUnsafe(ChunkGenerator.CODEC);
}
@Override
public void applyCarvers(@NotNull WorldGenRegion chunkRegion, long seed, @NotNull RandomState noiseConfig, @NotNull BiomeManager world,
@NotNull StructureManager structureAccessor, @NotNull ChunkAccess chunk) {
// no-op
}
@Override
public void buildSurface(@NotNull WorldGenRegion region, @NotNull StructureManager structures, @NotNull RandomState noiseConfig,
@NotNull ChunkAccess chunk) {
// no-op
}
@Override
public void applyBiomeDecoration(@NotNull WorldGenLevel world, @NotNull ChunkAccess chunk,
@NotNull StructureManager structureAccessor) {
vanilla.applyBiomeDecoration(world, chunk, structureAccessor);
}
@Override
public void spawnOriginalMobs(@NotNull WorldGenRegion region) {
vanilla.spawnOriginalMobs(region);
}
@Override
public int getGenDepth() {
return vanilla.getGenDepth();
}
@Override
public CompletableFuture<ChunkAccess> fillFromNoise(@NotNull Blender blender,
@NotNull RandomState noiseConfig,
@NotNull StructureManager structureAccessor, @NotNull ChunkAccess chunk) {
return vanilla.fillFromNoise(blender, noiseConfig, structureAccessor, chunk)
.thenApply(c -> {
applyStructureBeard(structureAccessor, chunk);
return c;
});
}
protected void applyStructureBeard(StructureManager structureAccessor, ChunkAccess chunk) {
LevelAccessor level = Reflection.STRUCTURE_MANAGER.getLevel(structureAccessor);
BiomeProvider biomeProvider = pack.getBiomeProvider();
PreLoadCompatibilityOptions compatibilityOptions = pack.getContext().get(PreLoadCompatibilityOptions.class);
if(compatibilityOptions.isBeard()) {
bindings.applyStructureBeard(delegate, structureAccessor, chunk,
new com.dfsek.terra.bukkit.world.BukkitWorldProperties(level.getMinecraftWorld().getWorld()),
biomeProvider, compatibilityOptions);
}
}
@Override
public int getSeaLevel() {
return vanilla.getSeaLevel();
}
@Override
public int getMinY() {
return vanilla.getMinY();
}
@Override
public int getBaseHeight(int x, int z, @NotNull Types heightmap, @NotNull LevelHeightAccessor world, @NotNull RandomState noiseConfig) {
WorldProperties properties = new NMSWorldProperties(seed, world);
int y = properties.getMaxHeight();
BiomeProvider biomeProvider = pack.getBiomeProvider();
while(y > properties.getMinHeight() && !heightmap.isOpaque().test(
((CraftBlockData) delegate.getBlock(properties, x, y - 1, z, biomeProvider).getHandle()).getState())) {
y--;
}
return y;
}
@Override
public @NotNull NoiseColumn getBaseColumn(int x, int z, @NotNull LevelHeightAccessor world, @NotNull RandomState noiseConfig) {
BlockState[] array = new BlockState[world.getHeight()];
WorldProperties properties = new NMSWorldProperties(seed, world);
BiomeProvider biomeProvider = pack.getBiomeProvider();
for(int y = properties.getMaxHeight() - 1; y >= properties.getMinHeight(); y--) {
array[y - properties.getMinHeight()] = ((CraftBlockData) delegate.getBlock(properties, x, y, z, biomeProvider)
.getHandle()).getState();
}
return new NoiseColumn(properties.getMinHeight(), array);
}
@Override
public void addDebugScreenInfo(@NotNull List<String> text, @NotNull RandomState noiseConfig, @NotNull BlockPos pos) {
}
}
@@ -1,66 +0,0 @@
package com.dfsek.terra.bukkit.nms;
import net.minecraft.server.level.ChunkMap;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.chunk.status.WorldGenContext;
import org.bukkit.World;
import org.bukkit.craftbukkit.CraftWorld;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.WorldInitEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.bukkit.generator.BukkitChunkGeneratorWrapper;
public class NMSInjectListener implements Listener {
private static final Logger LOGGER = LoggerFactory.getLogger(NMSInjectListener.class);
private static final Set<World> INJECTED = new HashSet<>();
private static final ReentrantLock INJECT_LOCK = new ReentrantLock();
private final NMSVersionBindings bindings;
public NMSInjectListener(NMSVersionBindings bindings) {
this.bindings = bindings;
}
@EventHandler
public void onWorldInit(WorldInitEvent event) {
if(!INJECTED.contains(event.getWorld()) &&
event.getWorld().getGenerator() instanceof BukkitChunkGeneratorWrapper bukkitChunkGeneratorWrapper) {
INJECT_LOCK.lock();
try {
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 = bindings.createBiomeProvider(pack.getBiomeProvider(), craftWorld.getSeed());
ChunkMap chunkMap = serverWorld.getChunkSource().chunkMap;
WorldGenContext worldGenContext = Reflection.CHUNKMAP.getWorldGenContext(chunkMap);
Reflection.CHUNKMAP.setWorldGenContext(chunkMap, new WorldGenContext(
worldGenContext.level(),
bindings.createChunkGenerator(vanilla, pack, provider, craftWorld.getSeed()),
worldGenContext.structureManager(),
worldGenContext.lightEngine(),
worldGenContext.mainThreadExecutor(),
worldGenContext.unsavedListener()
));
INJECTED.add(event.getWorld());
LOGGER.info("Successfully injected into world.");
} finally {
INJECT_LOCK.unlock();
}
}
}
}
@@ -1,121 +0,0 @@
package com.dfsek.terra.bukkit.nms;
import com.dfsek.tectonic.api.TypeRegistry;
import com.dfsek.tectonic.api.exception.LoadException;
import net.minecraft.resources.Identifier;
import net.minecraft.sounds.Music;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.attribute.AmbientAdditionsSettings;
import net.minecraft.world.attribute.AmbientMoodSettings;
import net.minecraft.world.attribute.AmbientParticle;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.entity.npc.villager.VillagerType;
import net.minecraft.world.level.biome.Biome.Precipitation;
import net.minecraft.world.level.biome.Biome.TemperatureModifier;
import net.minecraft.world.level.biome.BiomeSpecialEffects.GrassColorModifier;
import net.minecraft.world.level.biome.MobSpawnSettings;
import org.bukkit.Bukkit;
import org.bukkit.block.CreatureSpawner;
import java.util.List;
import java.util.Locale;
import com.dfsek.terra.addon.InternalAddon;
import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.entity.EntityTypeExtended;
import com.dfsek.terra.api.event.events.platform.PlatformInitializationEvent;
import com.dfsek.terra.api.event.functional.FunctionalEventHandler;
import com.dfsek.terra.api.world.biome.PlatformBiome;
import com.dfsek.terra.bukkit.PlatformImpl;
import com.dfsek.terra.bukkit.TerraBukkitPlugin;
import com.dfsek.terra.bukkit.util.BukkitNMSAccess;
import com.dfsek.terra.bukkit.nms.config.BiomeAdditionsSoundTemplate;
import com.dfsek.terra.bukkit.nms.config.BiomeMoodSoundTemplate;
import com.dfsek.terra.bukkit.nms.config.BiomeParticleConfigTemplate;
import com.dfsek.terra.bukkit.nms.config.EntityTypeTemplate;
import com.dfsek.terra.bukkit.nms.config.MusicSoundTemplate;
import com.dfsek.terra.bukkit.nms.config.SoundEventTemplate;
import com.dfsek.terra.bukkit.nms.config.SpawnCostConfig;
import com.dfsek.terra.bukkit.nms.config.SpawnEntryConfig;
import com.dfsek.terra.bukkit.nms.config.SpawnSettingsTemplate;
import com.dfsek.terra.bukkit.nms.config.SpawnTypeConfig;
import com.dfsek.terra.bukkit.nms.config.VillagerTypeTemplate;
public class NMSPlatformBase extends PlatformImpl implements BukkitNMSAccess {
private final NMSVersionBindings bindings;
public NMSPlatformBase(TerraBukkitPlugin plugin, NMSVersionBindings bindings) {
super(plugin);
this.bindings = bindings;
Bukkit.getPluginManager().registerEvents(new NMSInjectListener(bindings), plugin);
}
@Override
public com.dfsek.terra.api.entity.EntityType getEntityType(String data) {
return AwfulBukkitHacks.getEntityType(data);
}
@Override
public org.bukkit.entity.Entity spawnEntity(Object target, org.bukkit.Location location,
com.dfsek.terra.api.entity.EntityType type) {
return AwfulBukkitHacks.spawnEntity(target, location, type);
}
@Override
public void setSpawnerEntity(CreatureSpawner spawner, EntityTypeExtended type) {
AwfulBukkitHacks.setSpawnerEntity(spawner, type);
}
@Override
public void register(TypeRegistry registry) {
super.register(registry);
registry.registerLoader(PlatformBiome.class, (type, o, loader, depthTracker) -> parseBiome((String) o, depthTracker))
.registerLoader(Identifier.class, (type, o, loader, depthTracker) -> {
Identifier identifier = Identifier.tryParse((String) o);
if(identifier == null)
throw new LoadException("Invalid identifier: " + o, depthTracker);
return identifier;
})
.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(MobCategory.class, (type, o, loader, depthTracker) -> MobCategory.valueOf((String) o))
.registerLoader(AmbientParticle.class, BiomeParticleConfigTemplate::new)
.registerLoader(SoundEvent.class, SoundEventTemplate::new)
.registerLoader(AmbientMoodSettings.class, BiomeMoodSoundTemplate::new)
.registerLoader(AmbientAdditionsSettings.class, BiomeAdditionsSoundTemplate::new)
.registerLoader(Music.class, MusicSoundTemplate::new)
.registerLoader(EntityType.class, EntityTypeTemplate::new)
.registerLoader(SpawnCostConfig.class, SpawnCostConfig::new)
.registerLoader(SpawnEntryConfig.class, SpawnEntryConfig::new)
.registerLoader(SpawnTypeConfig.class, SpawnTypeConfig::new)
.registerLoader(MobSpawnSettings.class, () -> new SpawnSettingsTemplate(bindings))
.registerLoader(VillagerType.class, VillagerTypeTemplate::new);
}
@Override
protected InternalAddon load() {
InternalAddon internalAddon = super.load();
this.getEventManager().getHandler(FunctionalEventHandler.class)
.register(internalAddon, PlatformInitializationEvent.class)
.priority(1)
.then(event -> AwfulBukkitHacks.registerBiomes(this.getRawConfigRegistry(), bindings))
.global();
return internalAddon;
}
@Override
protected Iterable<BaseAddon> platformAddon() {
return List.of(new NMSAddon(this));
}
}
@@ -1,52 +0,0 @@
package com.dfsek.terra.bukkit.nms;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.chunk.ChunkAccess;
import org.bukkit.craftbukkit.block.data.CraftBlockData;
import com.dfsek.terra.api.world.biome.generation.BiomeProvider;
import com.dfsek.terra.api.world.chunk.generation.ChunkGenerator;
import com.dfsek.terra.api.world.info.WorldProperties;
import com.dfsek.terra.bukkit.config.PreLoadCompatibilityOptions;
import com.dfsek.terra.bukkit.world.block.data.BukkitBlockState;
public final class NMSStructureBeardifier {
private NMSStructureBeardifier() { }
public static void apply(ChunkGenerator delegate, ChunkAccess chunk, WorldProperties world,
BiomeProvider biomeProvider, PreLoadCompatibilityOptions compatibilityOptions,
StructureDensitySampler sampler) {
double threshold = compatibilityOptions.getBeardThreshold();
double airThreshold = compatibilityOptions.getAirThreshold();
int chunkX = chunk.getPos().x() << 4;
int chunkZ = chunk.getPos().z() << 4;
for(int x = 0; x < 16; x++) {
for(int z = 0; z < 16; z++) {
int depth = 0;
for(int y = world.getMaxHeight() - 1; y >= world.getMinHeight(); y--) {
int worldX = x + chunkX;
int worldZ = z + chunkZ;
double density = sampler.sample(worldX, y, worldZ);
if(density > threshold) {
chunk.setBlockState(new BlockPos(x, y, z), ((CraftBlockData) ((BukkitBlockState) delegate
.getPalette(worldX, y, worldZ, world, biomeProvider)
.get(depth, worldX, y, worldZ, world.getSeed())).getHandle()).getState(), 0);
depth++;
} else if(density < airThreshold) {
chunk.setBlockState(new BlockPos(x, y, z), Blocks.AIR.defaultBlockState(), 0);
} else {
depth = 0;
}
}
}
}
}
@FunctionalInterface
public interface StructureDensitySampler {
double sample(int x, int y, int z);
}
}
@@ -1,44 +0,0 @@
package com.dfsek.terra.bukkit.nms;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.level.StructureManager;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.Biome.BiomeBuilder;
import net.minecraft.world.level.biome.MobSpawnSettings;
import net.minecraft.world.level.chunk.ChunkAccess;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.world.biome.generation.BiomeProvider;
import com.dfsek.terra.api.world.chunk.generation.ChunkGenerator;
import com.dfsek.terra.api.world.info.WorldProperties;
import com.dfsek.terra.bukkit.config.PreLoadCompatibilityOptions;
import com.dfsek.terra.bukkit.nms.config.VanillaBiomeProperties;
public interface NMSVersionBindings {
default NMSBiomeProvider createBiomeProvider(BiomeProvider delegate, long seed) {
return new NMSBiomeProvider(delegate, seed);
}
default NMSChunkGeneratorDelegate createChunkGenerator(net.minecraft.world.level.chunk.ChunkGenerator vanilla,
ConfigPack pack,
NMSBiomeProvider biomeProvider, long seed) {
return new NMSChunkGeneratorDelegate(vanilla, pack, biomeProvider, seed, this);
}
void addSpawn(MobSpawnSettings.Builder builder, MobCategory category, EntityType<?> type, int weight, int minCount, int maxCount);
void addSpawnCost(MobSpawnSettings.Builder builder, EntityType<?> type, double mass, double gravity);
boolean setCreatureGenerationProbability(MobSpawnSettings.Builder builder, float probability);
void copyVanillaSpawnSettings(BiomeBuilder builder, Biome biome);
void setSpawnSettings(BiomeBuilder builder, MobSpawnSettings settings);
void applyBiomeColorOverrides(BiomeBuilder builder, VanillaBiomeProperties properties);
void applyStructureBeard(ChunkGenerator generator, StructureManager structures, ChunkAccess chunk, WorldProperties world,
BiomeProvider biomeProvider, PreLoadCompatibilityOptions options);
}
@@ -1,36 +0,0 @@
package com.dfsek.terra.bukkit.nms;
import net.minecraft.world.level.LevelHeightAccessor;
import com.dfsek.terra.api.world.info.WorldProperties;
public class NMSWorldProperties implements WorldProperties {
private final long seed;
private final LevelHeightAccessor height;
public NMSWorldProperties(long seed, LevelHeightAccessor height) {
this.seed = seed;
this.height = height;
}
@Override
public Object getHandle() {
return height;
}
@Override
public long getSeed() {
return seed;
}
@Override
public int getMaxHeight() {
return height.getMaxY();
}
@Override
public int getMinHeight() {
return height.getMinY();
}
}
@@ -1,139 +0,0 @@
package com.dfsek.terra.bukkit.nms;
import net.minecraft.core.Holder;
import net.minecraft.core.Holder.Reference;
import net.minecraft.core.HolderSet;
import net.minecraft.core.MappedRegistry;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.level.ChunkMap;
import net.minecraft.tags.TagKey;
import net.minecraft.world.entity.npc.villager.VillagerType;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.StructureManager;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.chunk.status.WorldGenContext;
import xyz.jpenilla.reflectionremapper.ReflectionRemapper;
import xyz.jpenilla.reflectionremapper.proxy.ReflectionProxyFactory;
import xyz.jpenilla.reflectionremapper.proxy.annotation.FieldGetter;
import xyz.jpenilla.reflectionremapper.proxy.annotation.FieldSetter;
import xyz.jpenilla.reflectionremapper.proxy.annotation.MethodName;
import xyz.jpenilla.reflectionremapper.proxy.annotation.Proxies;
import xyz.jpenilla.reflectionremapper.proxy.annotation.Static;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class Reflection {
public static final MappedRegistryProxy MAPPED_REGISTRY;
public static final MappedRegistryTagSetProxy MAPPED_REGISTRY_TAG_SET;
public static final StructureManagerProxy STRUCTURE_MANAGER;
public static final ReferenceProxy REFERENCE;
public static final ChunkMapProxy CHUNKMAP;
public static final HolderReferenceProxy HOLDER_REFERENCE;
public static final HolderSetNamedProxy HOLDER_SET;
public static final BiomeProxy BIOME;
public static final VillagerTypeProxy VILLAGER_TYPE;
static {
ReflectionRemapper reflectionRemapper = ReflectionRemapper.forReobfMappingsInPaperJar();
ReflectionProxyFactory reflectionProxyFactory = ReflectionProxyFactory.create(reflectionRemapper,
Reflection.class.getClassLoader());
MAPPED_REGISTRY = reflectionProxyFactory.reflectionProxy(MappedRegistryProxy.class);
MAPPED_REGISTRY_TAG_SET = reflectionProxyFactory.reflectionProxy(MappedRegistryTagSetProxy.class);
STRUCTURE_MANAGER = reflectionProxyFactory.reflectionProxy(StructureManagerProxy.class);
REFERENCE = reflectionProxyFactory.reflectionProxy(ReferenceProxy.class);
CHUNKMAP = reflectionProxyFactory.reflectionProxy(ChunkMapProxy.class);
HOLDER_REFERENCE = reflectionProxyFactory.reflectionProxy(HolderReferenceProxy.class);
HOLDER_SET = reflectionProxyFactory.reflectionProxy(HolderSetNamedProxy.class);
BIOME = reflectionProxyFactory.reflectionProxy(BiomeProxy.class);
VILLAGER_TYPE = reflectionProxyFactory.reflectionProxy(VillagerTypeProxy.class);
}
@Proxies(MappedRegistry.class)
public interface MappedRegistryProxy {
@FieldGetter("byKey")
<T> Map<ResourceKey<T>, Reference<T>> getByKey(MappedRegistry<T> instance);
@FieldSetter("allTags")
<T> void setAllTags(MappedRegistry<T> instance, Object obj);
@FieldSetter("frozen")
void setFrozen(MappedRegistry<?> instance, boolean frozen);
@MethodName("createTag")
<T> HolderSet.Named<T> invokeCreateTag(MappedRegistry<T> instance, TagKey<T> tag);
}
@Proxies(className = "net.minecraft.core.MappedRegistry$TagSet")
public interface MappedRegistryTagSetProxy {
@MethodName("fromMap")
@Static
<T> Object invokeFromMap(Map<TagKey<T>, HolderSet.Named<T>> map);
}
@Proxies(StructureManager.class)
public interface StructureManagerProxy {
@FieldGetter("level")
LevelAccessor getLevel(StructureManager instance);
}
@Proxies(Holder.Reference.class)
public interface ReferenceProxy {
@MethodName("bindValue")
<T> void invokeBindValue(Reference<T> instance, T value);
@MethodName("bindTags")
<T> void invokeBindTags(Reference<T> instance, Collection<TagKey<T>> tags);
}
@Proxies(ChunkMap.class)
public interface ChunkMapProxy {
@FieldGetter("worldGenContext")
WorldGenContext getWorldGenContext(ChunkMap instance);
@FieldSetter("worldGenContext")
void setWorldGenContext(ChunkMap instance, WorldGenContext worldGenContext);
}
@Proxies(Holder.Reference.class)
public interface HolderReferenceProxy {
@MethodName("bindTags")
<T> void invokeBindTags(Holder.Reference<T> instance, Collection<TagKey<T>> tags);
}
@Proxies(HolderSet.Named.class)
public interface HolderSetNamedProxy {
@MethodName("bind")
<T> void invokeBind(HolderSet.Named<T> instance, List<Holder<T>> entries);
@MethodName("contents")
<T> List<Holder<T>> invokeContents(HolderSet.Named<T> instance);
}
@Proxies(Biome.class)
public interface BiomeProxy {
@MethodName("getGrassColorFromTexture")
int invokeGrassColorFromTexture(Biome instance);
}
@Proxies(VillagerType.class)
public interface VillagerTypeProxy {
@Static
@FieldGetter("BY_BIOME")
Map<ResourceKey<Biome>, ResourceKey<VillagerType>> getByBiome();
}
}
@@ -1,25 +0,0 @@
package com.dfsek.terra.bukkit.nms;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.level.biome.Biome;
public class RegistryFetcher {
private static <T> Registry<T> getRegistry(ResourceKey<Registry<T>> key) {
return MinecraftServer.getServer()
.registryAccess()
.lookupOrThrow(key);
}
public static Registry<Biome> biomeRegistry() {
return getRegistry(Registries.BIOME);
}
public static Registry<SoundEvent> soundEventRegistry() {
return getRegistry(Registries.SOUND_EVENT);
}
}
@@ -1,71 +0,0 @@
package com.dfsek.terra.bukkit.nms.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 com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.commands.arguments.ParticleArgument;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.world.attribute.AmbientParticle;
import java.util.stream.Stream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BiomeParticleConfigTemplate implements ObjectTemplate<AmbientParticle> {
private static final Pattern LEGACY_BLOCK_PARTICLE = Pattern.compile(
"^((?:[a-z0-9_.-]+:)?[a-z0-9_./-]+)\\{block_state:\\{Name:((?:[a-z0-9_.-]+:)?[a-z0-9_./-]+)\\}\\}$"
);
@Value("particle")
@Default
private String particle = null;
@Value("probability")
@Default
private Float probability = 0.1f;
@Override
public AmbientParticle get() {
if(particle == null) {
return null;
}
try {
return new AmbientParticle(parseParticle(particle), probability);
} catch(CommandSyntaxException e) {
String normalized = normalizeLegacyBlockParticle(particle);
if(normalized == null) {
throw new RuntimeException(e);
}
try {
return new AmbientParticle(parseParticle(normalized), probability);
} catch(CommandSyntaxException fallbackException) {
fallbackException.addSuppressed(e);
throw new RuntimeException(fallbackException);
}
}
}
private static net.minecraft.core.particles.ParticleOptions parseParticle(String value) throws CommandSyntaxException {
return ParticleArgument.readParticle(new StringReader(value),
HolderLookup.Provider.create(Stream.of(BuiltInRegistries.PARTICLE_TYPE)));
}
private static String normalizeLegacyBlockParticle(String value) {
Matcher matcher = LEGACY_BLOCK_PARTICLE.matcher(value);
if(!matcher.matches()) {
return null;
}
String block = matcher.group(2);
if(!block.contains(":")) {
block = "minecraft:" + block;
}
return matcher.group(1) + "{block_state:\"" + block + "\"}";
}
}
@@ -1,20 +0,0 @@
package com.dfsek.terra.bukkit.nms.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.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.world.entity.EntityType;
public class EntityTypeTemplate implements ObjectTemplate<EntityType<?>> {
@Value("id")
@Default
private Identifier id = null;
@Override
public EntityType<?> get() {
return BuiltInRegistries.ENTITY_TYPE.get(id).orElseThrow().value();
}
}
@@ -1,58 +0,0 @@
package com.dfsek.terra.bukkit.nms.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.world.entity.MobCategory;
import net.minecraft.world.level.biome.MobSpawnSettings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import com.dfsek.terra.bukkit.nms.NMSVersionBindings;
public class SpawnSettingsTemplate implements ObjectTemplate<MobSpawnSettings> {
private static final Logger LOGGER = LoggerFactory.getLogger(SpawnSettingsTemplate.class);
private static final AtomicBoolean PROBABILITY_WARNING_LOGGED = new AtomicBoolean();
private final NMSVersionBindings bindings;
@Value("spawns")
@Default
private List<SpawnTypeConfig> spawns = List.of();
@Value("costs")
@Default
private List<SpawnCostConfig> costs = List.of();
@Value("probability")
@Default
private Float probability = null;
public SpawnSettingsTemplate(NMSVersionBindings bindings) {
this.bindings = bindings;
}
@Override
public MobSpawnSettings get() {
MobSpawnSettings.Builder builder = new MobSpawnSettings.Builder();
for(SpawnTypeConfig spawn : spawns) {
MobCategory category = spawn.getGroup();
for(SpawnEntryConfig entry : spawn.getEntries()) {
bindings.addSpawn(builder, category, entry.getType(), entry.getWeight(), entry.getMinCount(), entry.getMaxCount());
}
}
for(SpawnCostConfig cost : costs) {
bindings.addSpawnCost(builder, cost.getType(), cost.getMass(), cost.getGravity());
}
if(probability != null && !bindings.setCreatureGenerationProbability(builder, probability) &&
PROBABILITY_WARNING_LOGGED.compareAndSet(false, true)) {
LOGGER.warn("This server version ignores biome creature-generation probability values.");
}
return builder.build();
}
}
@@ -1,21 +0,0 @@
package com.dfsek.terra.bukkit.nms.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.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.entity.npc.villager.VillagerType;
public class VillagerTypeTemplate implements ObjectTemplate<ResourceKey<VillagerType>> {
@Value("id")
@Default
private Identifier id = null;
@Override
public ResourceKey<VillagerType> get() {
return ResourceKey.create(BuiltInRegistries.VILLAGER_TYPE.key(), id);
}
}
-2
View File
@@ -18,8 +18,6 @@ includeImmediateChildren(file("common/addons"), "addon")
includeImmediateChildren(file("platforms"), "platform")
includeImmediateChildren(file("platforms/bukkit/nms"), "Bukkit NMS")
include(":platforms:bukkit:common")
include(":platforms:minestom:example")