Files
Purpur/patches/server/0002-Airplane-Server-Changes.patch
BillyGalbreath 1362f49b24 Updated Upstream (Paper, Tuinity, & Airplane)
Upstream has released updates that appear to apply and compile correctly

Paper Changes:
bca97a8f7 replace spaces in world key (touches #5397)
de94f6485 Refactor chat message composition (#5396)
e27f334bb [CI-SKIP] Fix makemcdevsrc.sh for nms relocations (#5389)
ae15e85da Updated Upstream (CraftBukkit)
26fe0ac5a Only set despawnTimer for Wandering Traders spawned by MobSpawnerTrader (#5391)
b748eb7b8 Fix VanillaMobGoalTest#testBukkitMap (#5390)
18dbbb578 [Auto] Updated Upstream (CraftBukkit)
fac9cc5d5 [CI-SKIP] Ignore .gitignore
087aa70e7 Deprecate ItemStack#setLore(List<String>) and ItemStack#getLore, add Component based alternatives
9889c651c apply fixup
c310f0a61 Updated Upstream (Bukkit/CraftBukkit)
f17560ab0 wtf is this t file -jmp
347f3a9b8 fix compile
700e9e6a5 rebase
cf4dc464a Revert de5f4e469...c270abe96
6870db613 script & POM fix
743c6533c Replace ** with * (BSD/macOS)
376d7b097 Don't remove the .java
fcb3fd42a Fix macOS/BSD support
8cfc05249 Link correctly
ba1031ca7 Rename work dir
c8d844ab7 Actually fix preloading this time
e62aa5e3e Fix class preloading
1c03cf898 It's mojang math, not minecraft math
1034873df Apply fixups
39b125771 Use revision file
956150da7 Welcome to 1.16.5-R0.2
ccb217c01 Change cache keys
0d217001c more work
f6d820f07 It compiles
0f78e9525 More work
1718f61bf Updated Upstream (CraftBukkit/Spigot)
b28d46114 Update scripts for NMS repackaging

Tuinity Changes:
9bdcb9b8e Delete work dir when running jar
6351d7ca7 Update Upstream (Paper)
932c199a6 Generate md-dev correctly
bf3e73778 Make packet limiter work from IDE
1686f3861 Fix packet limiter config
f40f7b425 Update README.md styling (#264)
da1c3ace5 GH Actions Changes (#213)
5f325ecf1 Update Upstream (Paper)
0f83fe48d Update Upstream (Paper)

Airplane Changes:
f94d39947 Merge pull request #18 from notOM3GA/upstream/nms-repackage
0fc622631 Force build for Flare update
08439d6a9 Update Upstream (Tuinity)
2021-03-21 23:00:01 -05:00

2708 lines
138 KiB
Diff

From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Paul Sauve <paul@technove.co>
Date: Sat, 31 Oct 2020 19:21:42 -0500
Subject: [PATCH] Airplane Server Changes
diff --git a/pom.xml b/pom.xml
index dad9981b1cd1ca8b27a45972188fd2b92f5146e7..fc2c3714b6c772d67e258be269aa92dda80cdb12 100644
--- a/pom.xml
+++ b/pom.xml
@@ -27,8 +27,8 @@
<dependencies>
<dependency>
- <groupId>com.tuinity</groupId>
- <artifactId>tuinity-api</artifactId>
+ <groupId>gg.airplane</groupId>
+ <artifactId>airplane-api</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
@@ -159,8 +159,23 @@
<version>1.1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
+ <!-- Airplane - Flare -->
+ <dependency>
+ <groupId>com.github.technove</groupId>
+ <artifactId>Flare</artifactId>
+ <version>master-SNAPSHOT</version>
+ <scope>compile</scope>
+ </dependency>
</dependencies>
+ <repositories>
+ <!-- Airplane - Flare -->
+ <repository>
+ <id>jitpack.io</id>
+ <url>https://jitpack.io</url>
+ </repository>
+ </repositories>
+
<!-- This builds a completely 'ready to start' jar with all dependencies inside -->
<build>
<finalName>tuinity-${minecraft.version}</finalName>
diff --git a/src/main/java/com/destroystokyo/paper/Metrics.java b/src/main/java/com/destroystokyo/paper/Metrics.java
index 52c0ab1ce46e1f3233ef746d9bc699356fa9fae4..b480bd3044370b8eb733166f0c4b737344475993 100644
--- a/src/main/java/com/destroystokyo/paper/Metrics.java
+++ b/src/main/java/com/destroystokyo/paper/Metrics.java
@@ -593,7 +593,7 @@ public class Metrics {
boolean logFailedRequests = config.getBoolean("logFailedRequests", false);
// Only start Metrics, if it's enabled in the config
if (config.getBoolean("enabled", true)) {
- Metrics metrics = new Metrics("Tuinity", serverUUID, logFailedRequests, Bukkit.getLogger()); // Tuinity - we have our own bstats page
+ Metrics metrics = new Metrics("Airplane", serverUUID, logFailedRequests, Bukkit.getLogger()); // Tuinity - we have our own bstats page // Airplane
metrics.addCustomChart(new Metrics.SimplePie("minecraft_version", () -> {
String minecraftVersion = Bukkit.getVersion();
@@ -603,7 +603,7 @@ public class Metrics {
metrics.addCustomChart(new Metrics.SingleLineChart("players", () -> Bukkit.getOnlinePlayers().size()));
metrics.addCustomChart(new Metrics.SimplePie("online_mode", () -> Bukkit.getOnlineMode() || PaperConfig.isProxyOnlineMode() ? "online" : "offline"));
- metrics.addCustomChart(new Metrics.SimplePie("tuinity_version", () -> (Metrics.class.getPackage().getImplementationVersion() != null) ? Metrics.class.getPackage().getImplementationVersion() : "unknown")); // Tuinity - we have our own bstats page
+ metrics.addCustomChart(new Metrics.SimplePie("airplane_version", () -> (Metrics.class.getPackage().getImplementationVersion() != null) ? Metrics.class.getPackage().getImplementationVersion() : "unknown")); // Tuinity - we have our own bstats page // Airplane
metrics.addCustomChart(new Metrics.DrilldownPie("java_version", () -> {
Map<String, Map<String, Integer>> map = new HashMap<>();
diff --git a/src/main/java/com/destroystokyo/paper/PaperConfig.java b/src/main/java/com/destroystokyo/paper/PaperConfig.java
index c56e7fb18f9a56c8025eb70a524f028b5942da37..f39452535b2807a226ada095f5c21b19ea238e5c 100644
--- a/src/main/java/com/destroystokyo/paper/PaperConfig.java
+++ b/src/main/java/com/destroystokyo/paper/PaperConfig.java
@@ -202,6 +202,15 @@ public class PaperConfig {
public static String timingsServerName;
private static void timings() {
boolean timings = getBoolean("timings.enabled", true);
+ // Airplane start
+ boolean reallyEnableTimings = getBoolean("timings.really-enabled", false);
+ if (timings && !reallyEnableTimings) {
+ Bukkit.getLogger().log(Level.WARNING, "[Airplane] To improve performance, timings have been disabled by default");
+ Bukkit.getLogger().log(Level.WARNING, "[Airplane] You can still use timings by using /timings on, but they will not start on server startup unless you set timings.really-enabled to true in paper.yml");
+ Bukkit.getLogger().log(Level.WARNING, "[Airplane] If you would like to disable this message, either set timings.really-enabled to true or timings.enabled to false.");
+ }
+ timings = reallyEnableTimings;
+ // Airplane end
boolean verboseTimings = getBoolean("timings.verbose", true);
TimingsManager.privacy = getBoolean("timings.server-name-privacy", false);
TimingsManager.hiddenConfigs = getList("timings.hidden-config-entries", Lists.newArrayList("database", "settings.bungeecord-addresses", "settings.velocity-support.secret"));
diff --git a/src/main/java/com/destroystokyo/paper/PaperVersionFetcher.java b/src/main/java/com/destroystokyo/paper/PaperVersionFetcher.java
index 7063f1da3654b382e26b0093ad5d0ff04a2b38c2..b9c5479e5561f8fe68ea8f94fbf4e64de8a53bf9 100644
--- a/src/main/java/com/destroystokyo/paper/PaperVersionFetcher.java
+++ b/src/main/java/com/destroystokyo/paper/PaperVersionFetcher.java
@@ -28,8 +28,8 @@ public class PaperVersionFetcher implements VersionFetcher {
@Nonnull
@Override
public Component getVersionMessage(@Nonnull String serverVersion) {
- String[] parts = serverVersion.substring("git-Tuinity-".length()).split("[-\\s]"); // Tuinity
- final Component updateMessage = getUpdateStatusMessage("Spottedleaf/Tuinity", GITHUB_BRANCH_NAME, parts[0]); // Tuinity
+ String[] parts = serverVersion.substring("git-Airplane-".length()).split("[-\\s]"); // Tuinity
+ final Component updateMessage = getUpdateStatusMessage("TECHNOVE/Airplane", GITHUB_BRANCH_NAME, parts[0]); // Tuinity
final Component history = getHistory();
return history != null ? TextComponent.ofChildren(updateMessage, Component.newline(), history) : updateMessage;
diff --git a/src/main/java/com/tuinity/tuinity/util/maplist/IteratorSafeOrderedReferenceSet.java b/src/main/java/com/tuinity/tuinity/util/maplist/IteratorSafeOrderedReferenceSet.java
index be408aebbccbda46e8aa82ef337574137cfa0096..b9bdce7c7ca8b7b107b0dca165d722321c16229d 100644
--- a/src/main/java/com/tuinity/tuinity/util/maplist/IteratorSafeOrderedReferenceSet.java
+++ b/src/main/java/com/tuinity/tuinity/util/maplist/IteratorSafeOrderedReferenceSet.java
@@ -16,7 +16,7 @@ public final class IteratorSafeOrderedReferenceSet<E> {
/* list impl */
protected E[] listElements;
- protected int listSize;
+ protected int listSize; public int getListSize() { return this.listSize; } // Airplane - getter
protected final double maxFragFactor;
diff --git a/src/main/java/gg/airplane/AirplaneCommand.java b/src/main/java/gg/airplane/AirplaneCommand.java
new file mode 100644
index 0000000000000000000000000000000000000000..1fa9b40e2f89272fa8bc9d927a9a852b5eb0db22
--- /dev/null
+++ b/src/main/java/gg/airplane/AirplaneCommand.java
@@ -0,0 +1,56 @@
+package gg.airplane;
+
+import net.md_5.bungee.api.ChatColor;
+import net.minecraft.server.MinecraftServer;
+import org.bukkit.Bukkit;
+import org.bukkit.Location;
+import org.bukkit.command.Command;
+import org.bukkit.command.CommandSender;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class AirplaneCommand extends Command {
+
+ public AirplaneCommand() {
+ super("airplane");
+ this.description = "Airplane related commands";
+ this.usageMessage = "/airplane [reload | version]";
+ this.setPermission("bukkit.command.airplane");
+ }
+
+ @Override
+ public List<String> tabComplete(CommandSender sender, String alias, String[] args, Location location) throws IllegalArgumentException {
+ if (args.length == 1) {
+ return Stream.of("reload", "version")
+ .filter(arg -> arg.startsWith(args[0].toLowerCase()))
+ .collect(Collectors.toList());
+ }
+ return Collections.emptyList();
+ }
+
+ @Override
+ public boolean execute(CommandSender sender, String commandLabel, String[] args) {
+ if (!testPermission(sender)) return true;
+ String prefix = ChatColor.of("#6a7eda") + "" + ChatColor.BOLD + "Airplane ✈ " + ChatColor.of("#e8ebf9");
+
+ if (args.length != 1) {
+ sender.sendMessage(prefix + "Usage: " + usageMessage);
+ args = new String[]{"version"};
+ }
+
+ if (args[0].equalsIgnoreCase("reload")) {
+ MinecraftServer console = MinecraftServer.getServer();
+ AirplaneConfig.load();
+ console.server.reloadCount++;
+
+ Command.broadcastCommandMessage(sender, prefix + "Airplane configuration has been reloaded.");
+ } else if (args[0].equalsIgnoreCase("version")) {
+ Command.broadcastCommandMessage(sender, prefix + "This server is running " + Bukkit.getName() + " version " + Bukkit.getVersion() + " (Implementing API version " + Bukkit.getBukkitVersion() + ")");
+ }
+
+ return true;
+ }
+}
diff --git a/src/main/java/gg/airplane/AirplaneConfig.java b/src/main/java/gg/airplane/AirplaneConfig.java
new file mode 100644
index 0000000000000000000000000000000000000000..3886c731a69540f638d57a411285da289d3b704b
--- /dev/null
+++ b/src/main/java/gg/airplane/AirplaneConfig.java
@@ -0,0 +1,108 @@
+package gg.airplane;
+
+import gg.airplane.manual.ManualParser;
+import net.minecraft.server.MinecraftServer;
+import org.apache.logging.log4j.Level;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+
+public class AirplaneConfig {
+
+ private static ManualParser manual;
+
+ public static void load() {
+ try {
+ manual = new ManualParser(new File("airplane.air"));
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ manual.get("info.version", "1.0");
+ manual.setComment("info",
+ "Airplane Configuration",
+ "Read https://blog.airplane.gg/ to find out more about Airplane",
+ "Join our Discord to receive support & optimization help: https://discord.gg/3gtc45q");
+
+ for (Method method : AirplaneConfig.class.getDeclaredMethods()) {
+ if (Modifier.isStatic(method.getModifiers()) && Modifier.isPrivate(method.getModifiers())) {
+ method.setAccessible(true);
+ try {
+ method.invoke(null);
+ } catch (Throwable t) {
+ MinecraftServer.LOGGER.log(Level.WARN, "Failed to load configuration option from " + method.getName(), t);
+ }
+ }
+ }
+
+ try {
+ manual.save();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+
+ public static int maximumActivationPrio = 20;
+ public static int activationDistanceMod = 9;
+ public static boolean dynamicVillagerBehavior = true;
+ public static boolean dynamicPiglinBehavior = true;
+ public static boolean dynamicHoglinBehavior = true;
+
+ private static void dynamicActivationRange() {
+ manual.setComment("activation-range", "Optimizes how entities act when", "they're far away from the player");
+
+ maximumActivationPrio = manual.get("activation-range.max-tick-freq", maximumActivationPrio,
+ "This value defines how often in ticks, the furthest entity",
+ "will get their pathfinders and behaviors ticked. 20 = 1s");
+ activationDistanceMod = manual.get("activation-range.activation-dist-mod", activationDistanceMod,
+ "This value defines how much distance modifies an entity's",
+ "tick frequency. freq = (distanceToPlayer^2) / (2^value)",
+ "If you want further away entities to tick less often, use 8.",
+ "If you want further away entities to tick more often, try 10.");
+
+ manual.setComment("behavior-activation", "A list of entities to use the dynamic activation range", "to modify how often their behaviors are ticked");
+ dynamicVillagerBehavior = manual.get("behavior-activation.villager", dynamicVillagerBehavior);
+ dynamicPiglinBehavior = manual.get("behavior-activation.piglin", dynamicPiglinBehavior);
+ dynamicHoglinBehavior = manual.get("behavior-activation.hoglin", dynamicHoglinBehavior);
+ }
+
+
+ public static String profileWebUrl = "https://flare.airplane.gg";
+
+ private static void profilerOptions() {
+ manual.setComment("flare", "Configures Flare, the built-in profiler");
+
+ profileWebUrl = manual.get("flare.url", profileWebUrl, "Sets the server to use for profiles.");
+ }
+
+
+ public static String accessToken = "";
+
+ private static void airplaneWebServices() {
+ manual.setComment("web-services", "Options for connecting to Airplane's online utilities");
+
+ accessToken = manual.get("web-services.token", "");
+ // todo lookup token (off-thread) and let users know if their token is valid
+ if (accessToken.length() > 0) {
+ gg.airplane.flare.FlareSetup.init(); // Airplane
+ }
+ }
+
+
+ public static boolean multithreadedEntityTracker = false;
+ public static boolean entityTrackerAsyncPackets = false;
+
+ private static void entityTracker() {
+ manual.setComment("tracker", "Options to improve the performance of the entity tracker");
+
+ multithreadedEntityTracker = manual.get("tracker.multithreaded", multithreadedEntityTracker,
+ "This enables the multithreading of the tracker.");
+ entityTrackerAsyncPackets = manual.get("tracker.unsafe-async-packets", entityTrackerAsyncPackets,
+ "This option can break plugins that assume packets from the",
+ "entity tracker will be sent sync.");
+ }
+
+}
diff --git a/src/main/java/gg/airplane/AirplaneLogger.java b/src/main/java/gg/airplane/AirplaneLogger.java
new file mode 100644
index 0000000000000000000000000000000000000000..1a9d71739019d12772bec6076b195552ff6299f9
--- /dev/null
+++ b/src/main/java/gg/airplane/AirplaneLogger.java
@@ -0,0 +1,17 @@
+package gg.airplane;
+
+import org.bukkit.Bukkit;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public class AirplaneLogger extends Logger {
+ public static final AirplaneLogger LOGGER = new AirplaneLogger();
+
+ private AirplaneLogger() {
+ super("Airplane", null);
+
+ setParent(Bukkit.getLogger());
+ setLevel(Level.ALL);
+ }
+}
diff --git a/src/main/java/gg/airplane/commands/AirplaneCommands.java b/src/main/java/gg/airplane/commands/AirplaneCommands.java
new file mode 100644
index 0000000000000000000000000000000000000000..66b20250a26d005427601b1cdee43bdd9eba70cc
--- /dev/null
+++ b/src/main/java/gg/airplane/commands/AirplaneCommands.java
@@ -0,0 +1,12 @@
+package gg.airplane.commands;
+
+import gg.airplane.AirplaneCommand;
+import gg.airplane.flare.FlareCommand;
+import net.minecraft.server.MinecraftServer;
+
+public class AirplaneCommands {
+ public static void init() {
+ MinecraftServer.getServer().server.getCommandMap().register("airplane", "Airplane", new AirplaneCommand());
+ MinecraftServer.getServer().server.getCommandMap().register("flare", "Airplane", new FlareCommand());
+ }
+}
diff --git a/src/main/java/gg/airplane/compat/ServerConfigurations.java b/src/main/java/gg/airplane/compat/ServerConfigurations.java
new file mode 100644
index 0000000000000000000000000000000000000000..f4976428bc721319d2926e97cbe0f64c6e9e503c
--- /dev/null
+++ b/src/main/java/gg/airplane/compat/ServerConfigurations.java
@@ -0,0 +1,77 @@
+package gg.airplane.compat;
+
+import co.aikar.timings.TimingsManager;
+import com.google.common.io.Files;
+import org.bukkit.configuration.InvalidConfigurationException;
+import org.bukkit.configuration.file.YamlConfiguration;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Properties;
+import java.util.stream.Collectors;
+
+public class ServerConfigurations {
+
+ public static final String[] configurationFiles = new String[]{
+ "server.properties",
+ "bukkit.yml",
+ "spigot.yml",
+ "paper.yml",
+ "tuinity.yml",
+ "airplane.air"
+ };
+
+ public static String getCleanCopy(String configName) throws IOException {
+ File file = new File(configName);
+ List<String> hiddenConfigs = TimingsManager.hiddenConfigs;
+
+ if (configName.equals("airplane.air")) {
+ return Files.readLines(file, StandardCharsets.UTF_8)
+ .stream()
+ .filter(line -> !line.trim().startsWith("#"))
+ .map(line -> line.contains("token") ? " token = **" : line)
+ .collect(Collectors.joining("\n"));
+ }
+
+ switch (Files.getFileExtension(configName)) {
+ case "properties": {
+ Properties properties = new Properties();
+ try (FileInputStream inputStream = new FileInputStream(file)) {
+ properties.load(inputStream);
+ }
+ for (String hiddenConfig : hiddenConfigs) {
+ properties.remove(hiddenConfig);
+ }
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ properties.store(outputStream, "");
+ return Arrays.stream(outputStream.toString()
+ .split("\n"))
+ .filter(line -> !line.startsWith("#"))
+ .collect(Collectors.joining("\n"));
+ }
+ case "yml": {
+ YamlConfiguration configuration = new YamlConfiguration();
+ try {
+ configuration.load(file);
+ } catch (InvalidConfigurationException e) {
+ throw new IOException(e);
+ }
+ configuration.options().header(null);
+ for (String key : configuration.getKeys(true)) {
+ if (hiddenConfigs.contains(key)) {
+ configuration.set(key, null);
+ }
+ }
+ return configuration.saveToString();
+ }
+ default:
+ throw new IllegalArgumentException("Bad file type " + configName);
+ }
+ }
+
+}
diff --git a/src/main/java/gg/airplane/flare/FlareCommand.java b/src/main/java/gg/airplane/flare/FlareCommand.java
new file mode 100644
index 0000000000000000000000000000000000000000..ddc90f1589e683f452c5a74d9d2408803edea029
--- /dev/null
+++ b/src/main/java/gg/airplane/flare/FlareCommand.java
@@ -0,0 +1,149 @@
+package gg.airplane.flare;
+
+import com.google.common.collect.ImmutableList;
+import gg.airplane.AirplaneConfig;
+import gg.airplane.flare.exceptions.UserReportableException;
+import gg.airplane.flare.profiling.AsyncProfilerIntegration;
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.event.ClickEvent;
+import net.kyori.adventure.text.format.NamedTextColor;
+import net.kyori.adventure.text.format.TextColor;
+import net.kyori.adventure.text.format.TextDecoration;
+import org.bukkit.Bukkit;
+import org.bukkit.command.Command;
+import org.bukkit.command.CommandSender;
+import org.bukkit.command.ConsoleCommandSender;
+import org.bukkit.craftbukkit.scheduler.MinecraftInternalPlugin;
+import org.bukkit.util.StringUtil;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public class FlareCommand extends Command {
+
+ private static final String BASE_URL = "https://blog.airplane.gg/flare-tutorial/#setting-the-access-token";
+ private static final TextColor HEX = TextColor.fromHexString("#e3eaea");
+ private static final Component PREFIX = Component.text()
+ .append(Component.text("Flare ✈")
+ .color(TextColor.fromHexString("#6a7eda"))
+ .decoration(TextDecoration.BOLD, true)
+ .append(Component.text(" ", HEX)
+ .decoration(TextDecoration.BOLD, false)))
+ .asComponent();
+
+ public FlareCommand() {
+ super("flare", "Profile your server with Flare", "/flare", Collections.singletonList("profile"));
+ this.setPermission("airplane.flare");
+ }
+
+ @Override
+ public boolean execute(CommandSender sender, String commandLabel, String[] args) {
+ if (!testPermission(sender)) return true;
+ if (AirplaneConfig.accessToken.length() == 0) {
+ Component clickable = Component.text(BASE_URL, HEX, TextDecoration.UNDERLINED).clickEvent(ClickEvent.clickEvent(ClickEvent.Action.OPEN_URL, BASE_URL));
+
+ sender.sendMessage(PREFIX.append(Component.text("Flare currently requires an access token to use. To learn more, visit ").color(HEX).append(clickable)));
+ return true;
+ }
+
+ if (AsyncProfilerIntegration.doesNotSupportProfiling()) {
+ sender.sendMessage(PREFIX.append(
+ Component.text("Profiling is not supported in this environment, reason: " + AsyncProfilerIntegration.getDisabledReason(), NamedTextColor.RED)));
+ return true;
+ }
+ if (ProfilingManager.isProfiling()) {
+ if (args.length == 1 && args[0].equalsIgnoreCase("status")) {
+ sender.sendMessage(PREFIX.append(Component.text("Status: " + AsyncProfilerIntegration.status(), HEX)));
+ return true;
+ }
+ if (ProfilingManager.stop()) {
+ if (!(sender instanceof ConsoleCommandSender)) {
+ sender.sendMessage(PREFIX.append(Component.text("Profiling has been stopped.", HEX)));
+ }
+ } else {
+ sender.sendMessage(PREFIX.append(Component.text("Profiling has already been stopped.", HEX)));
+ }
+ } else {
+ ProfileType profileType = null;
+ if (args.length > 0) {
+ try {
+ profileType = ProfileType.valueOf(args[0].toUpperCase());
+ } catch (Exception e) {
+ sender.sendMessage(PREFIX.append(Component
+ .text("Invalid profile type ", HEX)
+ .append(Component.text(args[0], HEX, TextDecoration.BOLD)
+ .append(Component.text("!", HEX)))
+ ));
+ }
+ }
+ int interval = 5;
+ if (args.length > 1) {
+ try {
+ interval = Integer.parseInt(args[1]);
+ } catch (Exception e) {
+ sender.sendMessage(PREFIX.append(Component
+ .text("Invalid time in milliseconds ", HEX)
+ .append(Component.text(args[1], HEX, TextDecoration.BOLD)
+ .append(Component.text("!", HEX)))
+ ));
+ return true;
+ }
+ }
+ int finalInterval = interval;
+ ProfileType finalProfileType = profileType;
+ Bukkit.getScheduler().runTaskAsynchronously(new MinecraftInternalPlugin(), () -> {
+ try {
+ if (ProfilingManager.start(finalProfileType, finalInterval)) {
+ if (!(sender instanceof ConsoleCommandSender)) {
+ sender.sendMessage(PREFIX.append(Component
+ .text("Flare has been started: " + ProfilingManager.getProfilingUrl().get(), HEX)
+ .clickEvent(ClickEvent.openUrl(ProfilingManager.getProfilingUrl().get()))
+ ));
+ sender.sendMessage(PREFIX.append(Component.text(" Run /" + commandLabel + " to stop the Flare.", HEX)));
+ }
+ } else {
+ sender.sendMessage(PREFIX.append(Component
+ .text("Flare has already been started: " + ProfilingManager.getProfilingUrl().get(), HEX)
+ .clickEvent(ClickEvent.openUrl(ProfilingManager.getProfilingUrl().get()))
+ ));
+ }
+ } catch (UserReportableException e) {
+ sender.sendMessage(Component.text("Flare failed to start: " + e.getUserError(), NamedTextColor.RED));
+ e.printStackTrace();
+ }
+ });
+ }
+ return true;
+ }
+
+ @Override
+ public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException {
+ if (AsyncProfilerIntegration.doesNotSupportProfiling()) {
+ return ImmutableList.of();
+ }
+
+ List<String> list = new ArrayList<>();
+ if (AsyncProfilerIntegration.isProfiling()) {
+ if (args.length == 1) {
+ String lastWord = args[0];
+ if (StringUtil.startsWithIgnoreCase("status", lastWord)) {
+ list.add("status");
+ }
+ if (StringUtil.startsWithIgnoreCase("stop", lastWord)) {
+ list.add("stop");
+ }
+ }
+ } else {
+ if (args.length <= 1) {
+ String lastWord = args.length == 0 ? "" : args[0];
+ for (ProfileType value : ProfileType.values()) {
+ if (StringUtil.startsWithIgnoreCase(value.getInternalName(), lastWord)) {
+ list.add(value.name().toLowerCase());
+ }
+ }
+ }
+ }
+ return list;
+ }
+}
diff --git a/src/main/java/gg/airplane/flare/FlareSetup.java b/src/main/java/gg/airplane/flare/FlareSetup.java
new file mode 100644
index 0000000000000000000000000000000000000000..27ac32779e700494aeca8b425edb2871d3ec29cc
--- /dev/null
+++ b/src/main/java/gg/airplane/flare/FlareSetup.java
@@ -0,0 +1,146 @@
+package gg.airplane.flare;
+
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
+import gg.airplane.AirplaneConfig;
+import gg.airplane.AirplaneLogger;
+import gg.airplane.compat.ServerConfigurations;
+import gg.airplane.flare.profiling.AsyncProfilerIntegration;
+import net.minecraft.server.MinecraftServer;
+import org.bukkit.Bukkit;
+import org.bukkit.craftbukkit.scheduler.MinecraftInternalPlugin;
+import org.bukkit.plugin.Plugin;
+import org.bukkit.plugin.java.PluginClassLoader;
+import org.bukkit.scheduler.BukkitTask;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.logging.Level;
+
+public class FlareSetup {
+
+ public static void init() {
+ ServerConnector.connector = new ServerConnector() {
+
+ private final Cache<String, String> pluginNameCache = CacheBuilder.newBuilder()
+ .expireAfterAccess(1, TimeUnit.MINUTES)
+ .maximumSize(1024)
+ .build();
+
+ @Override
+ public String getPluginForClass(String name) {
+ if (name.contains(".") && name.charAt(0) != '/') {
+ if (name.startsWith("net.minecraft") || name.startsWith("java.") || name.startsWith("com.mojang") || name.startsWith("com.google") || name.startsWith("it.unimi") || name.startsWith("sun")) {
+ return null;
+ }
+
+ String className = name.substring(0, name.lastIndexOf("."));
+ String existing = pluginNameCache.getIfPresent(name);
+ if (existing != null) {
+ return existing.isEmpty() ? null : existing;
+ }
+
+ String newValue = "";
+
+ for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
+ ClassLoader classLoader = plugin.getClass().getClassLoader();
+ if (classLoader instanceof PluginClassLoader) {
+ try {
+ Class<?> aClass = ((PluginClassLoader) classLoader)._airplane_findClass(className);
+ if (aClass != null) {
+ newValue = plugin.getName();
+ }
+ } catch (ClassNotFoundException | IllegalAccessError e) {
+ }
+ }
+ }
+
+ pluginNameCache.put(name, newValue);
+ }
+ return null;
+ }
+
+ @Override
+ public Thread getMainThread() {
+ return MinecraftServer.getServer().serverThread;
+ }
+
+ @Override
+ public Map<String, String> getConfigurations() {
+ Map<String, String> map = new LinkedHashMap<>();
+ for (String configurationFile : ServerConfigurations.configurationFiles) {
+ try {
+ map.put(configurationFile, ServerConfigurations.getCleanCopy(configurationFile));
+ } catch (IOException e) {
+ this.log(Level.WARNING, "Failed to load config file " + configurationFile, e);
+ }
+ }
+ return map;
+ }
+
+ @Override
+ public void log(Level level, String s) {
+ AirplaneLogger.LOGGER.log(level, s);
+ }
+
+ @Override
+ public void log(Level level, String s, Throwable throwable) {
+ AirplaneLogger.LOGGER.log(level, s, throwable);
+ }
+
+ @Override
+ public String getPrimaryVersion() {
+ return Bukkit.getVersion();
+ }
+
+ @Override
+ public String getApiVersion() {
+ return "bukkit:" + Bukkit.getBukkitVersion();
+ }
+
+ @Override
+ public String getMcVersion() {
+ return Bukkit.getMinecraftVersion();
+ }
+
+ private final Map<Runnable, BukkitTask> scheduledRunnables = new HashMap<>();
+
+ @Override
+ public void schedule(Runnable runnable, long l, long l1) {
+ BukkitTask task = Bukkit.getScheduler().runTaskTimer(new MinecraftInternalPlugin(), runnable, l, l1);
+ this.scheduledRunnables.put(runnable, task);
+ }
+
+ @Override
+ public void scheduleAsync(Runnable runnable, long l, long l1) {
+ BukkitTask task = Bukkit.getScheduler().runTaskTimerAsynchronously(new MinecraftInternalPlugin(), runnable, l, l1);
+ this.scheduledRunnables.put(runnable, task);
+ }
+
+ @Override
+ public void cancel(Runnable runnable) {
+ this.scheduledRunnables.get(runnable).cancel();
+ }
+
+ @Override
+ public void runAsync(Runnable runnable) {
+ Bukkit.getScheduler().runTaskAsynchronously(new MinecraftInternalPlugin(), runnable);
+ }
+
+ @Override
+ public String getWebUrl() {
+ return AirplaneConfig.profileWebUrl;
+ }
+
+ @Override
+ public String getToken() {
+ return AirplaneConfig.accessToken;
+ }
+ };
+ AsyncProfilerIntegration.init();
+ }
+
+}
diff --git a/src/main/java/gg/airplane/flare/ProfilingManager.java b/src/main/java/gg/airplane/flare/ProfilingManager.java
new file mode 100644
index 0000000000000000000000000000000000000000..86d6650d174a7794a7ebe793cad033b42215c321
--- /dev/null
+++ b/src/main/java/gg/airplane/flare/ProfilingManager.java
@@ -0,0 +1,65 @@
+package gg.airplane.flare;
+
+import gg.airplane.AirplaneConfig;
+import gg.airplane.AirplaneLogger;
+import gg.airplane.flare.exceptions.UserReportableException;
+import gg.airplane.flare.profiling.ProfileController;
+import org.bukkit.Bukkit;
+import org.bukkit.craftbukkit.scheduler.MinecraftInternalPlugin;
+import org.bukkit.scheduler.BukkitTask;
+
+import javax.annotation.Nullable;
+import java.util.Optional;
+import java.util.logging.Level;
+
+public class ProfilingManager {
+
+ private static ProfileController currentController;
+ private static BukkitTask currentTask = null;
+
+ public static synchronized boolean isProfiling() {
+ return currentController != null;
+ }
+
+ public static synchronized Optional<String> getProfilingUrl() {
+ if (!isProfiling()) {
+ return Optional.empty();
+ }
+ return Optional.of(AirplaneConfig.profileWebUrl + "/" + currentController.getId());
+ }
+
+ public static synchronized boolean start(@Nullable ProfileType type, int interval) throws UserReportableException {
+ if (isProfiling()) {
+ return false;
+ }
+ if (Bukkit.isPrimaryThread()) {
+ throw new UserReportableException("Profiles should be started off-thread");
+ }
+ currentController = new ProfileController(type, Math.max(interval, 1)); // don't allow lower than 20ms: https://bugzilla.redhat.com/show_bug.cgi?id=645528
+ currentTask = Bukkit.getScheduler().runTaskLater(new MinecraftInternalPlugin(), ProfilingManager::stop, 20 * 60 * 15);
+ AirplaneLogger.LOGGER.log(Level.INFO, "Flare has been started: " + getProfilingUrl().orElse("An error occurred retrieving the Flare URL."));
+ return true;
+ }
+
+ public static synchronized boolean stop() {
+ if (!isProfiling()) {
+ return false;
+ }
+ AirplaneLogger.LOGGER.log(Level.INFO, "Flare has been stopped: " + getProfilingUrl().orElse("An error occurred retrieving the Flare URL."));
+ try {
+ currentController.cancel();
+ } catch (Throwable t) {
+ AirplaneLogger.LOGGER.log(Level.WARNING, "Error occurred stopping Flare", t);
+ }
+ currentController = null;
+
+ try {
+ currentTask.cancel();
+ } catch (Throwable t) {
+ AirplaneLogger.LOGGER.log(Level.WARNING, "Error occurred stopping Flare", t);
+ }
+ currentTask = null;
+ return true;
+ }
+
+}
diff --git a/src/main/java/gg/airplane/manual/ManualParser.java b/src/main/java/gg/airplane/manual/ManualParser.java
new file mode 100644
index 0000000000000000000000000000000000000000..ace29adb0f140d99a8d85ac824654beded4bf5b8
--- /dev/null
+++ b/src/main/java/gg/airplane/manual/ManualParser.java
@@ -0,0 +1,210 @@
+package gg.airplane.manual;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+// todo make this cleaner and more ergonomic to use
+// also probably needs lists eventually
+public class ManualParser {
+
+ private final File file;
+ private final Map<String, Section> sections = new LinkedHashMap<>();
+
+ private static class ManualObject {
+ public final String key;
+ public final List<String> comments;
+
+ private ManualObject(String key, List<String> comments) {
+ this.key = key;
+ this.comments = comments == null ? new ArrayList<>() : comments;
+ }
+ }
+
+ private static class Section extends ManualObject {
+ public final Map<String, Value> values;
+
+ private Section(String key, List<String> comments) {
+ super(key, comments);
+ this.values = new LinkedHashMap<>();
+ }
+
+ public void add(String key, Value value) {
+ this.values.put(key, value);
+ value.parent = this;
+ }
+
+ public Value get(String key) {
+ return this.values.computeIfAbsent(key, k -> {
+ Value value = new Value(k, null, null);
+ value.parent = this;
+ return value;
+ });
+ }
+ }
+
+ private static class Value extends ManualObject {
+ public Object value;
+ public Section parent;
+
+ private Value(String key, Object value, List<String> comments) {
+ super(key, comments);
+ this.value = value;
+ }
+ }
+
+ public ManualParser(File file) throws IOException {
+ this.file = file;
+
+ if (!file.exists()) {
+ return;
+ }
+
+ try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
+ Section currentSection = null;
+ List<String> currentComment = new ArrayList<>();
+
+ String line;
+ while ((line = reader.readLine()) != null) {
+ line = line.trim();
+
+ if (line.length() == 0) {
+ continue; // empty line
+ }
+
+ if (line.startsWith("#")) {
+ currentComment.add(line.substring(1).trim());
+ } else if (line.startsWith("[")) {
+ if (!line.endsWith("]")) {
+ throw new IllegalArgumentException("Invalid configuration, section '" + line + "' does not end with ]");
+ }
+ if (line.length() < 3) {
+ throw new IllegalArgumentException("Invalid configuration, section '" + line + "' does not have a name");
+ }
+ String sectionName = line.substring(1, line.length() - 1);
+ Section newSection = new Section(sectionName, currentComment);
+ currentComment = new ArrayList<>();
+ currentSection = newSection;
+ this.sections.put(sectionName, newSection);
+ } else {
+ if (currentSection == null) {
+ throw new IllegalArgumentException("Invalid configuration, found value outside of section " + line);
+ }
+ int equals = line.indexOf("=");
+ if (equals <= 1 || equals == line.length() - 1) {
+ throw new IllegalArgumentException("Invalid configuration, assignment invalid " + line);
+ }
+
+ String key = line.substring(0, equals).trim();
+
+ String value = line.substring(equals + 1).trim();
+ if (value.length() == 0) {
+ throw new IllegalArgumentException("Invalid configuration, value does not exist " + line);
+ }
+ if (value.startsWith("\"")) {
+ if (!value.endsWith("\"")) {
+ throw new IllegalArgumentException("Invalid configuration, value has no ending quote " + line);
+ }
+ String stringValue = value.substring(1, value.length() - 1);
+ currentSection.add(key, new Value(key, stringValue, currentComment));
+ } else if (Character.isDigit(value.charAt(0))) {
+ if (value.contains(".")) {
+ double doubleValue = Double.parseDouble(value);
+ currentSection.add(key, new Value(key, doubleValue, currentComment));
+ } else {
+ int intValue = Integer.parseInt(value);
+ currentSection.add(key, new Value(key, intValue, currentComment));
+ }
+ } else if (value.equals("true") || value.equals("false")) {
+ boolean boolValue = Boolean.parseBoolean(value);
+ currentSection.add(key, new Value(key, boolValue, currentComment));
+ } else {
+ throw new IllegalArgumentException("Invalid configuration, unknown type for " + line);
+ }
+ currentComment = new ArrayList<>();
+ }
+ }
+ }
+ }
+
+ public void save() throws IOException {
+ try (BufferedWriter writer = new BufferedWriter(new FileWriter(this.file))) {
+ for (Map.Entry<String, Section> entry : this.sections.entrySet()) {
+ Section section = entry.getValue();
+ if (section.comments != null) {
+ for (String comment : section.comments) {
+ writer.write("# " + comment + "\n");
+ }
+ }
+ writer.write("[" + section.key + "]" + "\n");
+ for (Value value : section.values.values()) {
+ if (value.comments != null) {
+ for (String comment : value.comments) {
+ writer.write(" # " + comment + "\n");
+ }
+ }
+ writer.write(" " + value.key + " = " + serialize(value.value) + "\n");
+ }
+ writer.write("\n");
+ }
+ }
+ }
+
+ private ManualObject getObject(String key) {
+ String[] split = key.split("\\.", 2);
+ if (split.length == 1) {
+ return this.sections.computeIfAbsent(key, k -> new Section(k, null));
+ }
+ return this.sections.computeIfAbsent(split[0], k -> new Section(k, null)).get(split[1]);
+ }
+
+ public void setComment(String key, String... comment) {
+ ManualObject object = this.getObject(key);
+ object.comments.clear();
+ object.comments.addAll(Arrays.asList(comment));
+ }
+
+ public <T> T get(String key, T defaultValue, String... comment) {
+ String[] split = key.split("\\.", 2);
+ if (split.length == 1) {
+ throw new IllegalArgumentException("Key " + key + " does not include section");
+ }
+ Section section = this.sections.computeIfAbsent(split[0], k -> new Section(k, null));
+ if (!section.values.containsKey(split[1])) {
+ Value value = section.get(split[1]);
+ value.value = defaultValue;
+ value.comments.addAll(Arrays.asList(comment));
+ return defaultValue;
+ }
+ Value value = section.get(split[1]);
+ if (value.comments.isEmpty()) {
+ value.comments.addAll(Arrays.asList(comment));
+ }
+ return (T) value.value;
+ }
+
+ public void set(String key, Object value) {
+ ManualObject object = getObject(key);
+ if (!(object instanceof Value)) {
+ throw new IllegalArgumentException("Invalid key for value " + key);
+ }
+ ((Value) object).value = value;
+ }
+
+ private String serialize(Object object) {
+ if (object instanceof String) {
+ return "\"" + object + "\"";
+ }
+ return String.valueOf(object);
+ }
+
+}
diff --git a/src/main/java/gg/airplane/structs/TrackQueue.java b/src/main/java/gg/airplane/structs/TrackQueue.java
new file mode 100644
index 0000000000000000000000000000000000000000..ae7c5430b4f5970ede602bb234b5ffcee424f6a7
--- /dev/null
+++ b/src/main/java/gg/airplane/structs/TrackQueue.java
@@ -0,0 +1,84 @@
+package gg.airplane.structs;
+
+import com.tuinity.tuinity.util.maplist.IteratorSafeOrderedReferenceSet;
+import net.minecraft.world.level.chunk.Chunk;
+import net.minecraft.server.MinecraftServer;
+import org.apache.logging.log4j.Level;
+
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ForkJoinPool;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * Helper class to handle processing a track queue.
+ */
+public class TrackQueue {
+
+ private final IteratorSafeOrderedReferenceSet<Chunk> chunks;
+ private final ForkJoinPool pool = new ForkJoinPool(Math.max(4, Runtime.getRuntime().availableProcessors() >> 2));
+ private final AtomicInteger taskIndex = new AtomicInteger();
+
+ private final ConcurrentLinkedQueue<Runnable> mainThreadTasks;
+
+ public TrackQueue(IteratorSafeOrderedReferenceSet<Chunk> chunks, ConcurrentLinkedQueue<Runnable> mainThreadTasks) {
+ this.chunks = chunks;
+ this.mainThreadTasks = mainThreadTasks;
+ }
+
+ public void start() {
+ int iterator = this.chunks.createRawIterator();
+ if (iterator == -1) {
+ return;
+ }
+ try {
+ this.taskIndex.set(iterator);
+
+ for (int i = 0; i < this.pool.getParallelism(); i++) {
+ this.pool.execute(this::run);
+ }
+
+ while (this.taskIndex.get() < this.chunks.getListSize()) {
+ this.runMainThreadTasks();
+ this.handleTask(); // assist
+ }
+ this.runMainThreadTasks(); // finish tasks
+ } finally {
+ this.chunks.finishRawIterator();
+ }
+ }
+
+ private void runMainThreadTasks() {
+ Runnable task;
+ while ((task = this.mainThreadTasks.poll()) != null) {
+ try {
+ task.run();
+ } catch (Throwable t) {
+ MinecraftServer.LOGGER.log(Level.WARN, "Tasks failed while ticking track queue", t);
+ }
+ }
+
+ }
+
+ private void run() {
+ while (handleTask());
+ }
+
+ private boolean handleTask() {
+ int index;
+ while ((index = this.taskIndex.getAndIncrement()) < this.chunks.getListSize()) {
+ Chunk chunk = this.chunks.rawGet(index);
+ if (chunk != null) {
+ try {
+ chunk.entityTracker.run();
+ } catch (Throwable t) {
+ MinecraftServer.LOGGER.log(Level.WARN, "Ticking tracker failed", t);
+ }
+
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+}
diff --git a/src/main/java/net/minecraft/core/BlockPosition.java b/src/main/java/net/minecraft/core/BlockPosition.java
index 8edc279e7a3fdfb7e10718f1deee34b7e3fb2f28..73ec17dea5d5668e49c9a6ad679bd3a362960c72 100644
--- a/src/main/java/net/minecraft/core/BlockPosition.java
+++ b/src/main/java/net/minecraft/core/BlockPosition.java
@@ -438,6 +438,14 @@ public class BlockPosition extends BaseBlockPosition {
public BlockPosition b(int i, int j, int k) {
return super.b(i, j, k).immutableCopy();
}
+ // Airplane start - version of b that doesn't copy
+ public BlockPosition addValues(int x, int y, int z) {
+ ((BaseBlockPosition)this).a += x;
+ ((BaseBlockPosition)this).b += y;
+ ((BaseBlockPosition)this).e += z;
+ return this;
+ }
+ // Airplane end
@Override
public BlockPosition shift(EnumDirection enumdirection, int i) {
diff --git a/src/main/java/net/minecraft/server/MinecraftServer.java b/src/main/java/net/minecraft/server/MinecraftServer.java
index e757cb5c2d50cb3a4dbe50d4726db09ab845fcbb..7cbbc1b1161f26f22a7f7832395af0d4a781cb1a 100644
--- a/src/main/java/net/minecraft/server/MinecraftServer.java
+++ b/src/main/java/net/minecraft/server/MinecraftServer.java
@@ -1636,7 +1636,7 @@ public abstract class MinecraftServer extends IAsyncTaskHandlerReentrant<TickTas
}
public String getServerModName() {
- return "Tuinity"; // Tuinity //Paper - Paper > // Spigot - Spigot > // CraftBukkit - cb > vanilla!
+ return "Airplane"; // Airplane // Tuinity //Paper - Paper > // Spigot - Spigot > // CraftBukkit - cb > vanilla!
}
public CrashReport b(CrashReport crashreport) {
diff --git a/src/main/java/net/minecraft/server/dedicated/DedicatedServer.java b/src/main/java/net/minecraft/server/dedicated/DedicatedServer.java
index d902efdb8f2d42ea4c3933f7fa76ebe135ee09db..24a46ad36613faa5f5a1a12b70f7af886e1608ae 100644
--- a/src/main/java/net/minecraft/server/dedicated/DedicatedServer.java
+++ b/src/main/java/net/minecraft/server/dedicated/DedicatedServer.java
@@ -215,6 +215,8 @@ public class DedicatedServer extends MinecraftServer implements IMinecraftServer
com.destroystokyo.paper.VersionHistoryManager.INSTANCE.getClass(); // load version history now
// Paper end
com.tuinity.tuinity.config.TuinityConfig.init((java.io.File) options.valueOf("tuinity-settings")); // Tuinity - Server Config
+ gg.airplane.AirplaneConfig.load(); // Airplane - config
+ gg.airplane.commands.AirplaneCommands.init(); // Airplane - command
this.setPVP(dedicatedserverproperties.pvp);
this.setAllowFlight(dedicatedserverproperties.allowFlight);
diff --git a/src/main/java/net/minecraft/server/level/ChunkProviderServer.java b/src/main/java/net/minecraft/server/level/ChunkProviderServer.java
index cb83f1152c52a99d25e4e80cc8bf18c6793e8b50..87c87b9767003652814c3726eece64470dbb69a8 100644
--- a/src/main/java/net/minecraft/server/level/ChunkProviderServer.java
+++ b/src/main/java/net/minecraft/server/level/ChunkProviderServer.java
@@ -1000,6 +1000,7 @@ public class ChunkProviderServer extends IChunkProvider {
}
// Paper end - optimize isOutisdeRange
this.world.getMethodProfiler().enter("pollingChunks");
+ this.world.resetIceAndSnowTick(); // Airplane - reset ice & snow tick random
int k = this.world.getGameRules().getInt(GameRules.RANDOM_TICK_SPEED);
boolean flag2 = world.ticksPerAnimalSpawns != 0L && worlddata.getTime() % world.ticksPerAnimalSpawns == 0L; // CraftBukkit
diff --git a/src/main/java/net/minecraft/server/level/EntityPlayer.java b/src/main/java/net/minecraft/server/level/EntityPlayer.java
index 59989db6dcf96a8ab5a75775bb588c31cec3418a..534c7266fe9d6f60b74a71e5e61ed248e515dffd 100644
--- a/src/main/java/net/minecraft/server/level/EntityPlayer.java
+++ b/src/main/java/net/minecraft/server/level/EntityPlayer.java
@@ -182,7 +182,7 @@ public class EntityPlayer extends EntityHuman implements ICrafting {
public NetworkManager networkManager; // Paper
public final MinecraftServer server;
public final PlayerInteractManager playerInteractManager;
- public final Deque<Integer> removeQueue = new ArrayDeque<>(); // Paper
+ public final Deque<Integer> removeQueue = new java.util.concurrent.ConcurrentLinkedDeque<>(); // Paper // Airplane concurrent deque
private final AdvancementDataPlayer advancementDataPlayer;
private final ServerStatisticManager serverStatisticManager;
private float lastHealthScored = Float.MIN_VALUE;
diff --git a/src/main/java/net/minecraft/server/level/EntityTrackerEntry.java b/src/main/java/net/minecraft/server/level/EntityTrackerEntry.java
index a1512ee8422fa39a95e4f19c86fe71b77af54ca0..c830b257054b7f8153aa9225c1f61f49a6ea0a84 100644
--- a/src/main/java/net/minecraft/server/level/EntityTrackerEntry.java
+++ b/src/main/java/net/minecraft/server/level/EntityTrackerEntry.java
@@ -75,6 +75,10 @@ public class EntityTrackerEntry {
* Requested in https://github.com/PaperMC/Paper/issues/1537 to allow intercepting packets
*/
public void sendPlayerPacket(EntityPlayer player, Packet packet) {
+ if (!gg.airplane.AirplaneConfig.entityTrackerAsyncPackets && !org.bukkit.Bukkit.isPrimaryThread()) {
+ this.b.chunkProvider.playerChunkMap.trackerEnsureMain(() -> sendPlayerPacket(player, packet));
+ return;
+ }
player.playerConnection.sendPacket(packet);
}
@@ -103,7 +107,7 @@ public class EntityTrackerEntry {
public final void tick() { this.a(); } // Paper - OBFHELPER
public void a() {
- com.tuinity.tuinity.util.TickThread.softEnsureTickThread("Tracker update"); // Tuinity
+ //com.tuinity.tuinity.util.TickThread.softEnsureTickThread("Tracker update"); // Tuinity // Airplane - allow multithreaded
List<Entity> list = this.tracker.passengers; // Paper - do not copy list
if (!list.equals(this.p)) {
@@ -117,6 +121,8 @@ public class EntityTrackerEntry {
ItemStack itemstack = entityitemframe.getItem();
if (this.tickCounter % 10 == 0 && itemstack.getItem() instanceof ItemWorldMap) { // CraftBukkit - Moved this.tickCounter % 10 logic here so item frames do not enter the other blocks
+ // Airplane start - process maps on main
+ this.b.chunkProvider.playerChunkMap.trackerEnsureMain(() -> {
WorldMap worldmap = ItemWorldMap.getSavedMap(itemstack, this.b);
Iterator iterator = this.trackedPlayers.iterator(); // CraftBukkit
@@ -130,6 +136,8 @@ public class EntityTrackerEntry {
entityplayer.playerConnection.sendPacket(packet);
}
}
+ });
+ // Airplane end
}
this.c();
@@ -264,18 +272,25 @@ public class EntityTrackerEntry {
// CraftBukkit start - Create PlayerVelocity event
boolean cancelled = false;
- if (this.tracker instanceof EntityPlayer) {
+ if (this.tracker instanceof EntityPlayer && PlayerVelocityEvent.getHandlerList().getRegisteredListeners().length > 0) { // Airplane - ensure there's listeners
+ // Airplane start - run on main thread
+ this.b.chunkProvider.playerChunkMap.trackerEnsureMain(() -> {
Player player = (Player) this.tracker.getBukkitEntity();
org.bukkit.util.Vector velocity = player.getVelocity();
PlayerVelocityEvent event = new PlayerVelocityEvent(player, velocity.clone());
this.tracker.world.getServer().getPluginManager().callEvent(event);
- if (event.isCancelled()) {
- cancelled = true;
- } else if (!velocity.equals(event.getVelocity())) {
+ if (!event.isCancelled() && !velocity.equals(event.getVelocity())) {
player.setVelocity(event.getVelocity());
}
+ if (!event.isCancelled()) {
+ this.broadcastIncludingSelf(new PacketPlayOutEntityVelocity(this.tracker)); // duplicate from !cancelled below
+ }
+
+ });
+ cancelled = true; // don't broadcast until the event has finished
+ // Airplane end
}
if (!cancelled) {
@@ -359,7 +374,9 @@ public class EntityTrackerEntry {
if (!list.isEmpty()) {
consumer.accept(new PacketPlayOutEntityEquipment(this.tracker.getId(), list));
}
+ this.b.chunkProvider.playerChunkMap.trackerEnsureMain(() -> { // Airplane
((EntityLiving) this.tracker).updateEquipment(); // CraftBukkit - SPIGOT-3789: sync again immediately after sending
+ }); // Airplane
}
// CraftBukkit start - Fix for nonsensical head yaw
@@ -437,6 +454,10 @@ public class EntityTrackerEntry {
// Paper end
private void broadcastIncludingSelf(Packet<?> packet) {
+ if (!gg.airplane.AirplaneConfig.entityTrackerAsyncPackets && !org.bukkit.Bukkit.isPrimaryThread()) {
+ this.b.chunkProvider.playerChunkMap.trackerEnsureMain(() -> broadcastIncludingSelf(packet));
+ return;
+ }
this.f.accept(packet);
if (this.tracker instanceof EntityPlayer) {
((EntityPlayer) this.tracker).playerConnection.sendPacket(packet);
diff --git a/src/main/java/net/minecraft/server/level/PlayerChunkMap.java b/src/main/java/net/minecraft/server/level/PlayerChunkMap.java
index d7eede51f1c4ebbe8e00b16efd6331c87db53bb4..c9d6ddd8874195c07b3573c6b1f61ffdcff2dddd 100644
--- a/src/main/java/net/minecraft/server/level/PlayerChunkMap.java
+++ b/src/main/java/net/minecraft/server/level/PlayerChunkMap.java
@@ -705,7 +705,9 @@ public class PlayerChunkMap extends IChunkLoader implements PlayerChunk.d {
return d2 * d2 + d3 * d3;
}
- private static int b(ChunkCoordIntPair chunkcoordintpair, EntityPlayer entityplayer, boolean flag) {
+ // Airplane start - create copy that accepts x/z instead of allocating pair
+ private static int b(ChunkCoordIntPair chunkcoordintpair, EntityPlayer entityplayer, boolean flag) { return someDistanceCalculation(chunkcoordintpair.x, chunkcoordintpair.z, entityplayer, flag); }
+ private static int someDistanceCalculation(int x, int z, EntityPlayer entityplayer, boolean flag) {
int i;
int j;
@@ -719,12 +721,16 @@ public class PlayerChunkMap extends IChunkLoader implements PlayerChunk.d {
j = MathHelper.floor(entityplayer.locZ() / 16.0D);
}
- return a(chunkcoordintpair, i, j);
+ return someOtherDistanceCalculation(x, z, i, j);
+ // Airplane end
}
- private static int a(ChunkCoordIntPair chunkcoordintpair, int i, int j) {
- int k = chunkcoordintpair.x - i;
- int l = chunkcoordintpair.z - j;
+ // Airplane start - create copy that accepts x/z instead of allocating pair
+ private static int a(ChunkCoordIntPair chunkcoordintpair, int i, int j) { return someOtherDistanceCalculation(chunkcoordintpair.x, chunkcoordintpair.z, i, j); }
+ private static int someOtherDistanceCalculation(int x, int z, int i, int j) {
+ int k = x - i;
+ int l = z - j;
+ // Airplane end
return Math.max(Math.abs(k), Math.abs(l));
}
@@ -785,6 +791,11 @@ public class PlayerChunkMap extends IChunkLoader implements PlayerChunk.d {
return (PlayerChunk) (this.hasPendingVisibleUpdate ? this.pendingVisibleChunks.get(i) : ((ProtectedVisibleChunksMap)this.visibleChunks).safeGet(i));
// Paper end
}
+ // Airplane start - since neither map can be updated during tracker tick, it's safe to allow direct retrieval here
+ private PlayerChunk trackerGetVisibleChunk(long i) {
+ return this.hasPendingVisibleUpdate ? this.pendingVisibleChunks.get(i) : ((ProtectedVisibleChunksMap) this.visibleChunks).safeGet(i);
+ }
+ // Airplane end
protected final IntSupplier getPrioritySupplier(long i) { return c(i); } // Paper - OBFHELPER
protected IntSupplier c(long i) {
@@ -2188,10 +2199,30 @@ public class PlayerChunkMap extends IChunkLoader implements PlayerChunk.d {
entity.tracker = null; // Paper - We're no longer tracked
}
+ // Airplane start - tools to ensure main thread
+ private final java.util.concurrent.ConcurrentLinkedQueue<Runnable> trackerMainQueue = new java.util.concurrent.ConcurrentLinkedQueue<>();
+ private gg.airplane.structs.TrackQueue trackQueue;
+
+ void trackerEnsureMain(Runnable runnable) {
+ if (this.world.serverThread == Thread.currentThread()) {
+ runnable.run();
+ } else {
+ this.trackerMainQueue.add(runnable);
+ }
+ }
+ // Airplane end
+
// Paper start - optimised tracker
private final void processTrackQueue() {
this.world.timings.tracker1.startTiming();
try {
+ // Airplane start - multithreaded tracker
+ if (this.trackQueue == null) this.trackQueue = new gg.airplane.structs.TrackQueue(this.world.getChunkProvider().entityTickingChunks, trackerMainQueue);
+ if (gg.airplane.AirplaneConfig.multithreadedEntityTracker) {
+ this.trackQueue.start();
+ return;
+ }
+ // Airplane end
com.tuinity.tuinity.util.maplist.IteratorSafeOrderedReferenceSet.Iterator<Chunk> iterator = this.world.getChunkProvider().entityTickingChunks.iterator();
try {
while (iterator.hasNext()) {
@@ -2457,7 +2488,7 @@ Sections go from 0..16. Now whenever a section is not empty, it can potentially
public class EntityTracker {
final EntityTrackerEntry trackerEntry; // Paper - private -> package private
- private final Entity tracker;
+ public final Entity tracker; // Airplane - public for chunk
private final int trackingDistance;
private SectionPosition e;
// Paper start
@@ -2476,7 +2507,9 @@ Sections go from 0..16. Now whenever a section is not empty, it can potentially
// Paper start - use distance map to optimise tracker
com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<EntityPlayer> lastTrackerCandidates;
- final void updatePlayers(com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<EntityPlayer> newTrackerCandidates) {
+ public synchronized final void tickEntry() { this.trackerEntry.tick(); } // Airplane - move entry tick into sync block
+
+ public synchronized final void updatePlayers(com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<EntityPlayer> newTrackerCandidates) { // Airplane
com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<EntityPlayer> oldTrackerCandidates = this.lastTrackerCandidates;
this.lastTrackerCandidates = newTrackerCandidates;
@@ -2517,7 +2550,13 @@ Sections go from 0..16. Now whenever a section is not empty, it can potentially
return this.tracker.getId();
}
- public void broadcast(Packet<?> packet) {
+ public synchronized void broadcast(Packet<?> packet) { // Airplane - synchronized for tracked player
+ // Airplane start
+ if (!gg.airplane.AirplaneConfig.entityTrackerAsyncPackets && !org.bukkit.Bukkit.isPrimaryThread()) {
+ trackerEnsureMain(() -> broadcast(packet));
+ return;
+ }
+ // Airplane end
Iterator iterator = this.trackedPlayers.iterator();
while (iterator.hasNext()) {
@@ -2529,6 +2568,12 @@ Sections go from 0..16. Now whenever a section is not empty, it can potentially
}
public void broadcastIncludingSelf(Packet<?> packet) {
+ // Airplane start
+ if (!gg.airplane.AirplaneConfig.entityTrackerAsyncPackets && !org.bukkit.Bukkit.isPrimaryThread()) {
+ trackerEnsureMain(() -> broadcastIncludingSelf(packet));
+ return;
+ }
+ // Airplane end
this.broadcast(packet);
if (this.tracker instanceof EntityPlayer) {
((EntityPlayer) this.tracker).playerConnection.sendPacket(packet);
@@ -2555,8 +2600,8 @@ Sections go from 0..16. Now whenever a section is not empty, it can potentially
}
- public void updatePlayer(EntityPlayer entityplayer) {
- org.spigotmc.AsyncCatcher.catchOp("player tracker update"); // Spigot
+ public synchronized void updatePlayer(EntityPlayer entityplayer) { // Airplane - sync for access to map
+ //org.spigotmc.AsyncCatcher.catchOp("player tracker update"); // Spigot // Airplane - allow sync for tracker
if (entityplayer != this.tracker) {
// Paper start - remove allocation of Vec3D here
//Vec3D vec3d = entityplayer.getPositionVector().d(this.tracker.getPositionVector()); // MC-155077, SPIGOT-5113
@@ -2571,11 +2616,17 @@ Sections go from 0..16. Now whenever a section is not empty, it can potentially
boolean flag1 = this.tracker.attachedToPlayer;
if (!flag1) {
+ // Airplane start - use int/longs instead of ChunkCoordIntPair
+ /*
ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(this.tracker.chunkX, this.tracker.chunkZ);
- PlayerChunk playerchunk = PlayerChunkMap.this.getVisibleChunk(chunkcoordintpair.pair());
+ */
+ int x = this.tracker.chunkX, z = this.tracker.chunkZ;
+ long chunkcoordintpair = ChunkCoordIntPair.pair(x, z);
+ PlayerChunk playerchunk = PlayerChunkMap.this.trackerGetVisibleChunk(chunkcoordintpair); // Airplane
if (playerchunk != null && playerchunk.getSendingChunk() != null && PlayerChunkMap.this.playerChunkManager.isChunkSent(entityplayer, MathHelper.floor(this.tracker.locX()) >> 4, MathHelper.floor(this.tracker.locZ()) >> 4)) { // Paper - no-tick view distance // Tuinity - don't broadcast in chunks the player hasn't received
- flag1 = PlayerChunkMap.b(chunkcoordintpair, entityplayer, false) <= PlayerChunkMap.this.viewDistance;
+ flag1 = PlayerChunkMap.someDistanceCalculation(x, z, entityplayer, false) <= PlayerChunkMap.this.viewDistance;
+ // Airplane end
}
}
@@ -2605,8 +2656,10 @@ Sections go from 0..16. Now whenever a section is not empty, it can potentially
}
private int b() {
+ // Airplane start
+ int i = this.trackingDistance; // move out of if statement
+ if (!this.tracker.passengers.isEmpty()) {
Collection<Entity> collection = this.tracker.getAllPassengers();
- int i = this.trackingDistance;
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
@@ -2618,6 +2671,8 @@ Sections go from 0..16. Now whenever a section is not empty, it can potentially
i = j;
}
}
+ }
+ // Airplane end
return this.a(i);
}
diff --git a/src/main/java/net/minecraft/server/level/WorldServer.java b/src/main/java/net/minecraft/server/level/WorldServer.java
index 46f960b9276dced41deb8f741454b6cce5a81529..9d97e2ea5c207c42f1cc9aa14bc87dc8e0a1bb1e 100644
--- a/src/main/java/net/minecraft/server/level/WorldServer.java
+++ b/src/main/java/net/minecraft/server/level/WorldServer.java
@@ -1081,11 +1081,12 @@ public class WorldServer extends World implements GeneratorAccessSeed {
// CraftBukkit end */
gameprofilerfiller.enter("checkDespawn");
+ boolean entityTickingChunk = false; if (!entity.dead) entityTickingChunk = this.getChunkProvider().isInEntityTickingChunk(entity); // Airplane - check once, chunks won't unload ticking entities
if (!entity.dead) {
entity.checkDespawn();
// Tuinity start - optimise notify()
if (entity.inChunk && entity.valid) {
- if (this.getChunkProvider().isInEntityTickingChunk(entity)) {
+ if (entityTickingChunk) { // Airplane - reuse
this.updateNavigatorsInRegion(entity);
}
} else {
@@ -1105,7 +1106,28 @@ public class WorldServer extends World implements GeneratorAccessSeed {
gameprofilerfiller.enter("tick");
if (!entity.dead && !(entity instanceof EntityComplexPart)) {
+ // Airplane start - inline this.a to prevent creation of lambda
+ /*
this.a(this::entityJoinedWorld, entity);
+ */
+ boolean doMidTick = false; // usually there's a returns in the catch, so treat it like that
+ try {
+ this.entityJoinedWorld(entity, entityTickingChunk); // Airplane - reuse
+ doMidTick = true;
+ } catch (Throwable throwable) {
+ if (throwable instanceof ThreadDeath) throw throwable; // Paper
+ // Paper start - Prevent tile entity and entity crashes
+ String msg = "Entity threw exception at " + entity.world.getWorld().getName() + ":" + entity.locX() + "," + entity.locY() + "," + entity.locZ();
+ System.err.println(msg);
+ throwable.printStackTrace();
+ getServer().getPluginManager().callEvent(new com.destroystokyo.paper.event.server.ServerExceptionEvent(new com.destroystokyo.paper.exception.ServerInternalException(msg, throwable)));
+ entity.dead = true;
+ // Paper end
+ }
+ if (doMidTick) {
+ MinecraftServer.getServer().executeMidTickTasks(); // Tuinity - execute chunk tasks mid tick
+ }
+ // Airplane end
}
gameprofilerfiller.exit();
@@ -1115,7 +1137,7 @@ public class WorldServer extends World implements GeneratorAccessSeed {
this.entitiesById.remove(entity.getId()); // Tuinity
this.unregisterEntity(entity);
} else if (entity.inChunk && entity.valid) { // Tuinity start - optimise notify()
- if (this.getChunkProvider().isInEntityTickingChunk(entity)) {
+ if (entityTickingChunk) { // Airplane - reuse
this.updateNavigatorsInRegion(entity);
}
} else {
@@ -1200,6 +1222,8 @@ public class WorldServer extends World implements GeneratorAccessSeed {
private final BiomeBase[] biomeBaseCache = new BiomeBase[1];
// Tuinity end - optimise chunk ice snow ticking
+ private int currentIceAndSnowTick = 0; protected void resetIceAndSnowTick() { this.currentIceAndSnowTick = this.randomTickRandom.nextInt(16); } // Airplane
+
public void a(Chunk chunk, int i) { final int randomTickSpeed = i; // Paper
ChunkCoordIntPair chunkcoordintpair = chunk.getPos();
boolean flag = this.isRaining();
@@ -1210,7 +1234,7 @@ public class WorldServer extends World implements GeneratorAccessSeed {
gameprofilerfiller.enter("thunder");
final BlockPosition.MutableBlockPosition blockposition = this.chunkTickMutablePosition; // Paper - use mutable to reduce allocation rate, final to force compile fail on change
- if (!this.paperConfig.disableThunder && flag && this.W() && this.random.nextInt(100000) == 0) { // Paper - Disable thunder
+ if (!this.paperConfig.disableThunder && flag && chunk.shouldDoLightning(this.random) && this.W()) { // Paper - Disable thunder // Airplane - check this.W last // Airplane - replace random with shouldDoLighting
blockposition.setValues(this.a(this.a(j, 0, k, 15))); // Paper
if (this.isRainingAt(blockposition)) {
DifficultyDamageScaler difficultydamagescaler = this.getDamageScaler(blockposition);
@@ -1234,7 +1258,7 @@ public class WorldServer extends World implements GeneratorAccessSeed {
}
gameprofilerfiller.exitEnter("iceandsnow");
- if (!this.paperConfig.disableIceAndSnow && this.randomTickRandom.nextInt(16) == 0) { // Paper - Disable ice and snow // Paper - optimise random ticking
+ if (!this.paperConfig.disableIceAndSnow && (this.currentIceAndSnowTick++ & 15) == 0) { // Paper - Disable ice and snow // Paper - optimise random ticking // Airplane - optimize further random ticking
// Paper start - optimise chunk ticking
// Tuinity start - optimise chunk ice snow ticking
BiomeBase[] biomeCache = this.biomeBaseCache;
@@ -1414,7 +1438,9 @@ public class WorldServer extends World implements GeneratorAccessSeed {
}
// Tuinity end - log detailed entity tick information
- public void entityJoinedWorld(Entity entity) {
+ // Airplane start - reuse check for in entity ticking chunk
+ public void entityJoinedWorld(Entity entity) { entityJoinedWorld(entity, this.getChunkProvider().isInEntityTickingChunk(entity)); }
+ public void entityJoinedWorld(Entity entity, boolean entityTickingChunk) { // Airplane end
// Tuinity start - log detailed entity tick information
com.tuinity.tuinity.util.TickThread.ensureTickThread("Cannot tick an entity off-main");
try {
@@ -1422,7 +1448,7 @@ public class WorldServer extends World implements GeneratorAccessSeed {
currentlyTickingEntity.lazySet(entity);
}
// Tuinity end - log detailed entity tick information
- if (!(entity instanceof EntityHuman) && !this.getChunkProvider().a(entity)) {
+ if (!(entity instanceof EntityHuman) && !entityTickingChunk) { // Airplane - reuse
this.chunkCheck(entity);
} else {
++TimingHistory.entityTicks; // Paper - timings
@@ -1448,9 +1474,14 @@ public class WorldServer extends World implements GeneratorAccessSeed {
++entity.ticksLived;
GameProfilerFiller gameprofilerfiller = this.getMethodProfiler();
+ // Airplane start - create debug lambda once, todo do we even WANT the method profiler?
+ /*
gameprofilerfiller.a(() -> {
return IRegistry.ENTITY_TYPE.getKey(entity.getEntityType()).toString();
});
+ */
+ gameprofilerfiller.a(entity.getEntityType().getEntityName);
+ // Airplane end
gameprofilerfiller.c("tickNonPassenger");
if (isActive) { // Paper - EAR 2
TimingHistory.activatedEntityTicks++; // Paper
diff --git a/src/main/java/net/minecraft/util/MathHelper.java b/src/main/java/net/minecraft/util/MathHelper.java
index cc566784c7dd21cc2c44e0f351347f657e57ddcf..e9e7fcf2b63febe2a7d055826fabb86bc13a5cf3 100644
--- a/src/main/java/net/minecraft/util/MathHelper.java
+++ b/src/main/java/net/minecraft/util/MathHelper.java
@@ -240,6 +240,7 @@ public class MathHelper {
return f - (float) d(f);
}
+ public static double getDecimals(double num) { return h(num); } // Airplane
public static double h(double d0) {
return d0 - (double) d(d0);
}
@@ -418,6 +419,7 @@ public class MathHelper {
return f1 + f * (f2 - f1);
}
+ public static double linearInterpolation(double value1, double value2, double amount) { return d(value1, value2, amount); } // Airplane - OBFHELPER
public static double d(double d0, double d1, double d2) {
return d1 + d0 * (d2 - d1);
}
@@ -434,6 +436,7 @@ public class MathHelper {
return d0 * d0 * d0 * (d0 * (d0 * 6.0D - 15.0D) + 10.0D);
}
+ public static int sign(double num) { return k(num); } // Airplane - OBFHELPER
public static int k(double d0) {
return d0 == 0.0D ? 0 : (d0 > 0.0D ? 1 : -1);
}
diff --git a/src/main/java/net/minecraft/world/entity/Entity.java b/src/main/java/net/minecraft/world/entity/Entity.java
index feab0ae1930b5271fe0d06a40c180317dcbc9d1d..c6b4af810fe3bda7797ab94316b2357178c9cd49 100644
--- a/src/main/java/net/minecraft/world/entity/Entity.java
+++ b/src/main/java/net/minecraft/world/entity/Entity.java
@@ -289,6 +289,9 @@ public abstract class Entity implements INamableTileEntity, ICommandListener, ne
public void inactiveTick() { }
// Spigot end
public boolean shouldBeRemoved; // Paper
+ // Airplane start
+ public int activatedPriority = gg.airplane.AirplaneConfig.maximumActivationPrio; // golf score
+ // Airplane end
public float getBukkitYaw() {
return this.yaw;
diff --git a/src/main/java/net/minecraft/world/entity/EntityInsentient.java b/src/main/java/net/minecraft/world/entity/EntityInsentient.java
index aae13c2e6c2a30b69c33417932c6a4d0aefeb7f5..f4440a5c4aedb1d7d303517f86a07c856dd1309b 100644
--- a/src/main/java/net/minecraft/world/entity/EntityInsentient.java
+++ b/src/main/java/net/minecraft/world/entity/EntityInsentient.java
@@ -201,10 +201,10 @@ public abstract class EntityInsentient extends EntityLiving {
@Override
public void inactiveTick() {
super.inactiveTick();
- if (this.goalSelector.inactiveTick()) {
+ if (this.goalSelector.inactiveTick(this.activatedPriority)) { // Airplane - pass activated priroity
this.goalSelector.doTick();
}
- if (this.targetSelector.inactiveTick()) {
+ if (this.targetSelector.inactiveTick(this.activatedPriority)) { // Airplane - pass activated priority
this.targetSelector.doTick();
}
}
@@ -829,9 +829,11 @@ public abstract class EntityInsentient extends EntityLiving {
this.bo.a();
this.world.getMethodProfiler().exit();
this.world.getMethodProfiler().enter("targetSelector");
+ if (this.targetSelector.inactiveTick(this.activatedPriority)) // Airplane - use this to alternate ticking
this.targetSelector.doTick();
this.world.getMethodProfiler().exit();
this.world.getMethodProfiler().enter("goalSelector");
+ if (this.goalSelector.inactiveTick(this.activatedPriority)) // Airplane - use this to alternate ticking
this.goalSelector.doTick();
this.world.getMethodProfiler().exit();
this.world.getMethodProfiler().enter("navigation");
diff --git a/src/main/java/net/minecraft/world/entity/EntityLiving.java b/src/main/java/net/minecraft/world/entity/EntityLiving.java
index 561905be42428855a07a2e63aca80d5dd63b22bf..1a7866bed9cb7f0431454d3af4733de05c0cba78 100644
--- a/src/main/java/net/minecraft/world/entity/EntityLiving.java
+++ b/src/main/java/net/minecraft/world/entity/EntityLiving.java
@@ -111,6 +111,7 @@ import net.minecraft.world.phys.AxisAlignedBB;
import net.minecraft.world.phys.MovingObjectPosition;
import net.minecraft.world.phys.MovingObjectPositionEntity;
import net.minecraft.world.phys.Vec3D;
+import net.minecraft.world.phys.shapes.VoxelShapeCollision;
import net.minecraft.world.scores.ScoreboardTeam;
import org.apache.logging.log4j.Logger;
@@ -909,11 +910,13 @@ public abstract class EntityLiving extends Entity {
}
if (entity != null) {
- ItemStack itemstack = this.getEquipment(EnumItemSlot.HEAD);
- Item item = itemstack.getItem();
+ // Airplane start - don't get equipment if not needed
+ //ItemStack itemstack = this.getEquipment(EnumItemSlot.HEAD);
+ //Item item = itemstack.getItem();
EntityTypes<?> entitytypes = entity.getEntityType();
- if (entitytypes == EntityTypes.SKELETON && item == Items.SKELETON_SKULL || entitytypes == EntityTypes.ZOMBIE && item == Items.ZOMBIE_HEAD || entitytypes == EntityTypes.CREEPER && item == Items.CREEPER_HEAD) {
+ if (entitytypes == EntityTypes.SKELETON && this.getEquipment(EnumItemSlot.HEAD).getItem() == Items.SKELETON_SKULL || entitytypes == EntityTypes.ZOMBIE && this.getEquipment(EnumItemSlot.HEAD).getItem() == Items.ZOMBIE_HEAD || entitytypes == EntityTypes.CREEPER && this.getEquipment(EnumItemSlot.HEAD).getItem() == Items.CREEPER_HEAD) {
+ // Airplane end
d0 *= 0.5D;
}
}
@@ -3101,7 +3104,7 @@ public abstract class EntityLiving extends Entity {
Vec3D vec3d = new Vec3D(this.locX(), this.getHeadY(), this.locZ());
Vec3D vec3d1 = new Vec3D(entity.locX(), entity.getHeadY(), entity.locZ());
- return this.world.rayTrace(new RayTrace(vec3d, vec3d1, RayTrace.BlockCollisionOption.COLLIDER, RayTrace.FluidCollisionOption.NONE, this)).getType() == MovingObjectPosition.EnumMovingObjectType.MISS;
+ return this.world.rayTraceDirect(vec3d, vec3d1, VoxelShapeCollision.a(this)) == MovingObjectPosition.EnumMovingObjectType.MISS; // Airplane - use direct method
}
@Override
diff --git a/src/main/java/net/minecraft/world/entity/EntityTypes.java b/src/main/java/net/minecraft/world/entity/EntityTypes.java
index 80c229c1852199fda85c03453d64cae33e413e89..7f70dda656ff9d802200f18139d2695e58c551c7 100644
--- a/src/main/java/net/minecraft/world/entity/EntityTypes.java
+++ b/src/main/java/net/minecraft/world/entity/EntityTypes.java
@@ -270,6 +270,8 @@ public class EntityTypes<T extends Entity> {
private MinecraftKey bq;
private final EntitySize br;
+ public java.util.function.Supplier<String> getEntityName = () -> IRegistry.ENTITY_TYPE.getKey(this).toString(); // Airplane - create lambda ones
+
private static <T extends Entity> EntityTypes<T> a(String s, EntityTypes.Builder entitytypes_builder) { // CraftBukkit - decompile error
return (EntityTypes) IRegistry.a((IRegistry) IRegistry.ENTITY_TYPE, s, (Object) entitytypes_builder.a(s));
}
diff --git a/src/main/java/net/minecraft/world/entity/ai/behavior/BehaviorBetterJob.java b/src/main/java/net/minecraft/world/entity/ai/behavior/BehaviorBetterJob.java
index 72f1031e95b375823790f8cac4c102ba1205c9e8..e4821c1a7ceac582b019102230dbe5221add9050 100644
--- a/src/main/java/net/minecraft/world/entity/ai/behavior/BehaviorBetterJob.java
+++ b/src/main/java/net/minecraft/world/entity/ai/behavior/BehaviorBetterJob.java
@@ -3,6 +3,7 @@ package net.minecraft.world.entity.ai.behavior;
import com.google.common.collect.ImmutableMap;
import net.minecraft.core.GlobalPos;
import net.minecraft.server.level.WorldServer;
+import net.minecraft.world.entity.EntityLiving;
import net.minecraft.world.entity.ai.memory.MemoryModuleType;
import net.minecraft.world.entity.ai.memory.MemoryStatus;
import net.minecraft.world.entity.ai.village.poi.VillagePlaceType;
@@ -21,11 +22,31 @@ public class BehaviorBetterJob extends Behavior<EntityVillager> {
protected void a(WorldServer worldserver, EntityVillager entityvillager, long i) {
GlobalPos globalpos = (GlobalPos) entityvillager.getBehaviorController().getMemory(MemoryModuleType.JOB_SITE).get();
+ // Airplane start - remove stream
+ /*
worldserver.y().c(globalpos.getBlockPosition()).ifPresent((villageplacetype) -> {
BehaviorUtil.a(entityvillager, (entityvillager1) -> {
return this.a(globalpos, villageplacetype, entityvillager1);
}).reduce(entityvillager, BehaviorBetterJob::a);
});
+ */
+ java.util.Optional<VillagePlaceType> optVillagePlaceType = worldserver.y().c(globalpos.getBlockPosition());
+ if (optVillagePlaceType.isPresent()) {
+ VillagePlaceType villageplacetype = optVillagePlaceType.get();
+ java.util.Optional<java.util.List<EntityLiving>> optList = entityvillager.getBehaviorController().getMemory(MemoryModuleType.MOBS);
+ if (optList.isPresent()) {
+ EntityVillager previous = entityvillager;
+ for (EntityLiving entityliving : optList.get()) {
+ if (entityliving instanceof EntityVillager && entityliving != entityvillager && entityliving.isAlive()) {
+ EntityVillager entityvillager1 = (EntityVillager) entityliving;
+ if (this.a(globalpos, villageplacetype, entityvillager1)) {
+ previous = a(previous, entityvillager1);
+ }
+ }
+ }
+ }
+ }
+ // Airplane end
}
private static EntityVillager a(EntityVillager entityvillager, EntityVillager entityvillager1) {
diff --git a/src/main/java/net/minecraft/world/entity/ai/behavior/BehaviorFindPosition.java b/src/main/java/net/minecraft/world/entity/ai/behavior/BehaviorFindPosition.java
index bc8786e2aaeab4dbae4e9c7666ad816bc5bfac3f..09133c5822bc1386bc3d8a5f3c94196420bbfaea 100644
--- a/src/main/java/net/minecraft/world/entity/ai/behavior/BehaviorFindPosition.java
+++ b/src/main/java/net/minecraft/world/entity/ai/behavior/BehaviorFindPosition.java
@@ -67,6 +67,7 @@ public class BehaviorFindPosition extends Behavior<EntityCreature> {
protected void a(WorldServer worldserver, EntityCreature entitycreature, long i) {
this.f = i + 20L + (long) worldserver.getRandom().nextInt(20);
+ if (entitycreature.getNavigation().isStuck()) this.f += 200L; // Airplane - wait an additional 10s to check again if they're stuck
VillagePlace villageplace = worldserver.y();
this.g.long2ObjectEntrySet().removeIf((entry) -> {
diff --git a/src/main/java/net/minecraft/world/entity/ai/goal/PathfinderGoalSelector.java b/src/main/java/net/minecraft/world/entity/ai/goal/PathfinderGoalSelector.java
index 637928664f8c7b1c694a234e507c20724294e450..f303c5d6b2e55fc9fd8b49ec21121805e7351034 100644
--- a/src/main/java/net/minecraft/world/entity/ai/goal/PathfinderGoalSelector.java
+++ b/src/main/java/net/minecraft/world/entity/ai/goal/PathfinderGoalSelector.java
@@ -44,9 +44,14 @@ public class PathfinderGoalSelector {
}
// Paper start
- public boolean inactiveTick() {
- incRate();
- return getCurRate() % getTickRate() == 0;
+ public boolean inactiveTick(int tickRate) { // Airplane - take tick rate
+ tickRate = Math.max(tickRate, getTickRate()); // Airplane
+ if (this.curRate++ % tickRate != 0) { // Airplane - use tick rate / increment curRate every tick
+ //incRate();
+ return false;
+ } else {
+ return true;
+ }
}
public boolean hasTasks() {
for (PathfinderGoalWrapped task : getTasks()) {
diff --git a/src/main/java/net/minecraft/world/entity/ai/navigation/NavigationAbstract.java b/src/main/java/net/minecraft/world/entity/ai/navigation/NavigationAbstract.java
index 148bdbc2cffb002d8b6dd05e70854ab503804949..48e6a4c588ef39a4bde067d79b96a656c68750ce 100644
--- a/src/main/java/net/minecraft/world/entity/ai/navigation/NavigationAbstract.java
+++ b/src/main/java/net/minecraft/world/entity/ai/navigation/NavigationAbstract.java
@@ -433,6 +433,7 @@ public abstract class NavigationAbstract {
}
}
+ public boolean isStuck() { return this.t(); } // Airplane - OBFHELPER
public boolean t() {
return this.t;
}
diff --git a/src/main/java/net/minecraft/world/entity/ai/targeting/PathfinderTargetCondition.java b/src/main/java/net/minecraft/world/entity/ai/targeting/PathfinderTargetCondition.java
index 88972dd8252bd2d2d8e384d616484ff682949fa8..5e8d3b84cbad299e09e8f25bfc712d11e1d1068e 100644
--- a/src/main/java/net/minecraft/world/entity/ai/targeting/PathfinderTargetCondition.java
+++ b/src/main/java/net/minecraft/world/entity/ai/targeting/PathfinderTargetCondition.java
@@ -84,9 +84,17 @@ public class PathfinderTargetCondition {
}
if (this.b > 0.0D) {
+ // Airplane start - try to return early
+ double range = (useFollowRange ? getFollowRange(entityliving) : this.b);
+ double d2 = entityliving.h(entityliving1.locX(), entityliving1.locY(), entityliving1.locZ()); // move up here to use early
+
+ if (d2 > range * range) { // if they're further than the absolute furthest allowed, they don't match
+ return false;
+ }
+
double d0 = this.g ? entityliving1.A(entityliving) : 1.0D;
- double d1 = Math.max((useFollowRange ? getFollowRange(entityliving) : this.b) * d0, 2.0D); // Paper
- double d2 = entityliving.h(entityliving1.locX(), entityliving1.locY(), entityliving1.locZ());
+ double d1 = Math.max(range * d0, 2.0D); // Paper // Airplane - reuse range calculated above
+ // Airplane end
if (d2 > d1 * d1) {
return false;
diff --git a/src/main/java/net/minecraft/world/entity/ambient/EntityBat.java b/src/main/java/net/minecraft/world/entity/ambient/EntityBat.java
index 61ebb278cf4ef57ae7a86c6c6ef1fa14559f21e2..341b95f73a839a548b202e7bf97fd18760c71fd8 100644
--- a/src/main/java/net/minecraft/world/entity/ambient/EntityBat.java
+++ b/src/main/java/net/minecraft/world/entity/ambient/EntityBat.java
@@ -10,6 +10,7 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.syncher.DataWatcher;
import net.minecraft.network.syncher.DataWatcherObject;
import net.minecraft.network.syncher.DataWatcherRegistry;
+import net.minecraft.server.MinecraftServer;
import net.minecraft.sounds.SoundEffect;
import net.minecraft.sounds.SoundEffects;
import net.minecraft.util.MathHelper;
@@ -247,13 +248,22 @@ public class EntityBat extends EntityAmbient {
}
}
+ // Airplane start - only check for spooky season once an hour
+ private static boolean isSpookySeason = false;
+ private static final int ONE_HOUR = 20 * 60 * 60;
+ private static int lastSpookyCheck = -ONE_HOUR;
private static boolean eJ() {
+ if (MinecraftServer.currentTick - lastSpookyCheck > ONE_HOUR) {
LocalDate localdate = LocalDate.now();
int i = localdate.get(ChronoField.DAY_OF_MONTH);
int j = localdate.get(ChronoField.MONTH_OF_YEAR);
+ isSpookySeason = j == 10 && i >= 20 || j == 11 && i <= 3;
+ lastSpookyCheck = MinecraftServer.currentTick;
+ }
- return j == 10 && i >= 20 || j == 11 && i <= 3;
+ return isSpookySeason;
}
+ // Airplane end
@Override
protected float b(EntityPose entitypose, EntitySize entitysize) {
diff --git a/src/main/java/net/minecraft/world/entity/monster/EntityEnderman.java b/src/main/java/net/minecraft/world/entity/monster/EntityEnderman.java
index e993b1849beb60515c51ee4f37617faab63ca223..4d7b5d47ab6bd3b1408811c3b9c157b1eb5c30ae 100644
--- a/src/main/java/net/minecraft/world/entity/monster/EntityEnderman.java
+++ b/src/main/java/net/minecraft/world/entity/monster/EntityEnderman.java
@@ -57,6 +57,7 @@ import net.minecraft.world.level.World;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.IBlockData;
+import net.minecraft.world.level.chunk.Chunk;
import net.minecraft.world.level.pathfinder.PathType;
import net.minecraft.world.phys.AxisAlignedBB;
import net.minecraft.world.phys.MovingObjectPositionBlock;
@@ -314,11 +315,18 @@ public class EntityEnderman extends EntityMonster implements IEntityAngerable {
private boolean p(double d0, double d1, double d2) {
BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(d0, d1, d2);
- while (blockposition_mutableblockposition.getY() > 0 && !this.world.getType(blockposition_mutableblockposition).getMaterial().isSolid()) {
+ // Airplane start - single chunk lookup
+ Chunk chunk = this.world.getChunkIfLoaded(blockposition_mutableblockposition);
+ if (chunk == null) {
+ return false;
+ }
+
+ while (blockposition_mutableblockposition.getY() > 0 && !chunk.getType(blockposition_mutableblockposition).getMaterial().isSolid()) { // use chunk lookup
blockposition_mutableblockposition.c(EnumDirection.DOWN);
}
- IBlockData iblockdata = this.world.getType(blockposition_mutableblockposition);
+ IBlockData iblockdata = chunk.getType(blockposition_mutableblockposition); // use chunk lookup
+ // Airplane end
boolean flag = iblockdata.getMaterial().isSolid();
boolean flag1 = iblockdata.getFluid().a((Tag) TagsFluid.WATER);
diff --git a/src/main/java/net/minecraft/world/entity/monster/hoglin/EntityHoglin.java b/src/main/java/net/minecraft/world/entity/monster/hoglin/EntityHoglin.java
index 375409f4b72edc7990da90460b30486fb2980fb6..9aa4850e021076fde306eea7eec104c31086c57f 100644
--- a/src/main/java/net/minecraft/world/entity/monster/hoglin/EntityHoglin.java
+++ b/src/main/java/net/minecraft/world/entity/monster/hoglin/EntityHoglin.java
@@ -54,7 +54,7 @@ public class EntityHoglin extends EntityAnimal implements IMonster, IOglin {
public int conversionTicks = 0;
public boolean cannotBeHunted = false;
protected static final ImmutableList<? extends SensorType<? extends Sensor<? super EntityHoglin>>> bo = ImmutableList.of(SensorType.c, SensorType.d, SensorType.n, SensorType.m);
- protected static final ImmutableList<? extends MemoryModuleType<?>> bp = ImmutableList.of(MemoryModuleType.BREED_TARGET, MemoryModuleType.MOBS, MemoryModuleType.VISIBLE_MOBS, MemoryModuleType.NEAREST_VISIBLE_PLAYER, MemoryModuleType.NEAREST_VISIBLE_TARGETABLE_PLAYER, MemoryModuleType.LOOK_TARGET, MemoryModuleType.WALK_TARGET, MemoryModuleType.CANT_REACH_WALK_TARGET_SINCE, MemoryModuleType.PATH, MemoryModuleType.ATTACK_TARGET, MemoryModuleType.ATTACK_COOLING_DOWN, MemoryModuleType.NEAREST_VISIBLE_ADULT_PIGLIN, new MemoryModuleType[]{MemoryModuleType.AVOID_TARGET, MemoryModuleType.VISIBLE_ADULT_PIGLIN_COUNT, MemoryModuleType.VISIBLE_ADULT_HOGLIN_COUNT, MemoryModuleType.NEAREST_VISIBLE_ADULT_HOGLINS, MemoryModuleType.NEAREST_VISIBLE_ADULY, MemoryModuleType.NEAREST_REPELLENT, MemoryModuleType.PACIFIED});
+ protected static final ImmutableList<MemoryModuleType<?>> bp = ImmutableList.of(MemoryModuleType.BREED_TARGET, MemoryModuleType.MOBS, MemoryModuleType.VISIBLE_MOBS, MemoryModuleType.NEAREST_VISIBLE_PLAYER, MemoryModuleType.NEAREST_VISIBLE_TARGETABLE_PLAYER, MemoryModuleType.LOOK_TARGET, MemoryModuleType.WALK_TARGET, MemoryModuleType.CANT_REACH_WALK_TARGET_SINCE, MemoryModuleType.PATH, MemoryModuleType.ATTACK_TARGET, MemoryModuleType.ATTACK_COOLING_DOWN, MemoryModuleType.NEAREST_VISIBLE_ADULT_PIGLIN, new MemoryModuleType[]{MemoryModuleType.AVOID_TARGET, MemoryModuleType.VISIBLE_ADULT_PIGLIN_COUNT, MemoryModuleType.VISIBLE_ADULT_HOGLIN_COUNT, MemoryModuleType.NEAREST_VISIBLE_ADULT_HOGLINS, MemoryModuleType.NEAREST_VISIBLE_ADULY, MemoryModuleType.NEAREST_REPELLENT, MemoryModuleType.PACIFIED}); // Airplane - decompile error
public EntityHoglin(EntityTypes<? extends EntityHoglin> entitytypes, World world) {
super(entitytypes, world);
@@ -118,15 +118,20 @@ public class EntityHoglin extends EntityAnimal implements IMonster, IOglin {
@Override
public BehaviorController<EntityHoglin> getBehaviorController() {
- return super.getBehaviorController();
+ return (BehaviorController<EntityHoglin>) super.getBehaviorController(); // Airplane - decompile error
}
+ private int behaviorTick; // Airplane
@Override
protected void mobTick() {
+ // Airplane - dynamic tick
+ if (!gg.airplane.AirplaneConfig.dynamicHoglinBehavior || this.behaviorTick++ % this.activatedPriority == 0) {
this.world.getMethodProfiler().enter("hoglinBrain");
- this.getBehaviorController().a((WorldServer) this.world, (EntityLiving) this);
+ this.getBehaviorController().a((WorldServer) this.world, (EntityHoglin) this); // Airplane - decompile error
this.world.getMethodProfiler().exit();
HoglinAI.a(this);
+ }
+ // Airplane end
if (this.isConverting()) {
++this.conversionTicks;
if (this.conversionTicks > 300) {
@@ -300,7 +305,7 @@ public class EntityHoglin extends EntityAnimal implements IMonster, IOglin {
@Override
protected SoundEffect getSoundAmbient() {
- return this.world.isClientSide ? null : (SoundEffect) HoglinAI.b(this).orElse((Object) null);
+ return this.world.isClientSide ? null : (SoundEffect) HoglinAI.b(this).orElse(null); // Airplane - decompile error
}
@Override
diff --git a/src/main/java/net/minecraft/world/entity/monster/piglin/EntityPiglin.java b/src/main/java/net/minecraft/world/entity/monster/piglin/EntityPiglin.java
index f2f65dc0612cc232009ea7ff12f5c1ba4e6b15ea..48acef830eb1d919499e9b79dc6a9af4bdf8a17b 100644
--- a/src/main/java/net/minecraft/world/entity/monster/piglin/EntityPiglin.java
+++ b/src/main/java/net/minecraft/world/entity/monster/piglin/EntityPiglin.java
@@ -188,7 +188,7 @@ public class EntityPiglin extends EntityPiglinAbstract implements ICrossbow {
@Override
public BehaviorController<EntityPiglin> getBehaviorController() {
- return super.getBehaviorController();
+ return (BehaviorController<EntityPiglin>) super.getBehaviorController(); // Airplane - compile error
}
@Override
@@ -244,12 +244,17 @@ public class EntityPiglin extends EntityPiglinAbstract implements ICrossbow {
return !this.cannotHunt;
}
+ private int behaviorTick; // Airplane
@Override
protected void mobTick() {
+ // Airplane - dynamic tick
+ if (!gg.airplane.AirplaneConfig.dynamicPiglinBehavior || this.behaviorTick++ % this.activatedPriority == 0) {
this.world.getMethodProfiler().enter("piglinBrain");
- this.getBehaviorController().a((WorldServer) this.world, (EntityLiving) this);
+ this.getBehaviorController().a((WorldServer) this.world, (EntityPiglin) this); // Airplane - compile error
this.world.getMethodProfiler().exit();
PiglinAI.b(this);
+ }
+ // Airplane end
super.mobTick();
}
@@ -386,7 +391,7 @@ public class EntityPiglin extends EntityPiglinAbstract implements ICrossbow {
@Override
protected SoundEffect getSoundAmbient() {
- return this.world.isClientSide ? null : (SoundEffect) PiglinAI.d(this).orElse((Object) null);
+ return this.world.isClientSide ? null : (SoundEffect) PiglinAI.d(this).orElse(null); // Airplane - compile error
}
@Override
diff --git a/src/main/java/net/minecraft/world/entity/npc/EntityVillager.java b/src/main/java/net/minecraft/world/entity/npc/EntityVillager.java
index 2d0b83923d58cc7b6918b4e2ff2bece13ca26899..d8028675fc82883d716bcfb44431ca6ac7dfda36 100644
--- a/src/main/java/net/minecraft/world/entity/npc/EntityVillager.java
+++ b/src/main/java/net/minecraft/world/entity/npc/EntityVillager.java
@@ -231,11 +231,17 @@ public class EntityVillager extends EntityVillagerAbstract implements Reputation
}
// Spigot End
+ private int behaviorTick = 0;
+
@Override
protected void mobTick() { mobTick(false); }
protected void mobTick(boolean inactive) {
this.world.getMethodProfiler().enter("villagerBrain");
- if (!inactive) this.getBehaviorController().a((WorldServer) this.world, this); // CraftBukkit - decompile error // Paper
+ if (!inactive) {
+ if (!gg.airplane.AirplaneConfig.dynamicVillagerBehavior || behaviorTick++ % this.activatedPriority == 0) {
+ this.getBehaviorController().a((WorldServer) this.world, this); // CraftBukkit - decompile error // Paper
+ }
+ }
this.world.getMethodProfiler().exit();
if (this.bF) {
this.bF = false;
diff --git a/src/main/java/net/minecraft/world/entity/player/EntityHuman.java b/src/main/java/net/minecraft/world/entity/player/EntityHuman.java
index 44038dd278b988508047023107683e5370af54ad..ad85dda5c50b797904824a08513fbcec042128ea 100644
--- a/src/main/java/net/minecraft/world/entity/player/EntityHuman.java
+++ b/src/main/java/net/minecraft/world/entity/player/EntityHuman.java
@@ -162,7 +162,8 @@ public abstract class EntityHuman extends EntityLiving {
protected int bG;
protected final float bH = 0.02F;
private int g;
- private GameProfile bJ; public final void setProfile(final GameProfile profile) { this.bJ = profile; } // Paper - OBFHELPER
+ private IChatBaseComponent displayName; // Airplane - cache displayName
+ private GameProfile bJ; public final void setProfile(final GameProfile profile) { this.bJ = profile; this.displayName = null; } // Paper - OBFHELPER // Airplane - use to reset displayName
private ItemStack bL;
private final ItemCooldown bM;
@Nullable
@@ -1828,7 +1829,12 @@ public abstract class EntityHuman extends EntityLiving {
@Override
public IChatBaseComponent getDisplayName() {
- return new ChatComponentText(this.bJ.getName());
+ // Airplane start - cache display name
+ if (this.displayName == null) {
+ this.displayName = new ChatComponentText(this.getProfile().getName());
+ }
+ return this.displayName;
+ // Airplane end
}
public InventoryEnderChest getEnderChest() {
diff --git a/src/main/java/net/minecraft/world/entity/player/PlayerInventory.java b/src/main/java/net/minecraft/world/entity/player/PlayerInventory.java
index 2df3ae0b72ccb5f816d55fed15396ba5a1affb7f..754a3ea18905b79ae5ae4fc2442c94f0611b6d0e 100644
--- a/src/main/java/net/minecraft/world/entity/player/PlayerInventory.java
+++ b/src/main/java/net/minecraft/world/entity/player/PlayerInventory.java
@@ -630,6 +630,8 @@ public class PlayerInventory implements IInventory, INamableTileEntity {
}
public boolean h(ItemStack itemstack) {
+ // Airplane start - skip using abstract iterators and stuff, they're generic and slow and allocating them sucks
+ /*
Iterator iterator = this.f.iterator();
while (iterator.hasNext()) {
@@ -644,6 +646,20 @@ public class PlayerInventory implements IInventory, INamableTileEntity {
}
}
}
+ */
+ List<NonNullList<ItemStack>> components = this.getComponents();
+ for (int i = 0; i < components.size(); i++) {
+ List<ItemStack> list = components.get(i);
+
+ for (int j = 0; j < list.size(); j++) {
+ ItemStack itemstack1 = list.get(j);
+
+ if (!itemstack1.isEmpty() && itemstack1.doMaterialsMatch(itemstack)) {
+ return true;
+ }
+ }
+ }
+ // Airplane end
return false;
}
diff --git a/src/main/java/net/minecraft/world/entity/projectile/EntityProjectile.java b/src/main/java/net/minecraft/world/entity/projectile/EntityProjectile.java
index e55061b6c04b4bde92404a6ef58ba9a52cd99c1d..24d205dd1f31ece82d5cf516b8642eb0172e1a97 100644
--- a/src/main/java/net/minecraft/world/entity/projectile/EntityProjectile.java
+++ b/src/main/java/net/minecraft/world/entity/projectile/EntityProjectile.java
@@ -4,6 +4,8 @@ import net.minecraft.core.BlockPosition;
import net.minecraft.core.particles.Particles;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.PacketPlayOutSpawnEntity;
+import net.minecraft.server.MinecraftServer;
+import net.minecraft.util.MathHelper;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityLiving;
import net.minecraft.world.entity.EntityTypes;
@@ -102,6 +104,37 @@ public abstract class EntityProjectile extends IProjectile {
this.setPosition(d0, d1, d2);
}
+ private static int loadedThisTick = 0;
+ private static int loadedTick;
+
+ private int buffered = 0;
+
+ // Airplane start
+ @Override
+ public void setPosition(double d0, double d1, double d2) {
+ if (loadedTick != MinecraftServer.currentTick) {
+ loadedTick = MinecraftServer.currentTick;
+ loadedThisTick = 0;
+ }
+ int previousX = MathHelper.floor(this.locX()) >> 4, previousZ = MathHelper.floor(this.locZ()) >> 4;
+ int newX = MathHelper.floor(d0) >> 4, newZ = MathHelper.floor(d2) >> 4;
+ if (previousX != newX || previousZ != newZ) {
+ boolean isLoaded = this.world.isChunkLoaded(newX, newZ);
+ if (!isLoaded) {
+ if (loadedThisTick > 10) { // Airplane 10 = max chunks to load from projectiles in a tick todo config
+ if (++buffered > 20) { // Airplane 20 = max chunks a single projectile loads overall todo config
+ this.die();
+ }
+ return;
+ }
+ loadedThisTick++;
+ }
+ buffered = 0;
+ }
+ super.setPosition(d0, d1, d2);
+ }
+ // Airplane end
+
protected float k() {
return 0.03F;
}
diff --git a/src/main/java/net/minecraft/world/item/crafting/ShapelessRecipes.java b/src/main/java/net/minecraft/world/item/crafting/ShapelessRecipes.java
index e112d149fc3a7af7f0c9a5280c94c9b03b2aba2d..d2afc367fb393c6206f9cd599d4603294d457608 100644
--- a/src/main/java/net/minecraft/world/item/crafting/ShapelessRecipes.java
+++ b/src/main/java/net/minecraft/world/item/crafting/ShapelessRecipes.java
@@ -26,8 +26,16 @@ public class ShapelessRecipes implements RecipeCrafting {
private final String group;
private final ItemStack result;
private final NonNullList<RecipeItemStack> ingredients;
+ private final boolean isBukkit; // Airplane
+ // Airplane start - add isBukkit constructor param
public ShapelessRecipes(MinecraftKey minecraftkey, String s, ItemStack itemstack, NonNullList<RecipeItemStack> nonnulllist) {
+ this(minecraftkey, s, itemstack, nonnulllist, false);
+ }
+
+ public ShapelessRecipes(MinecraftKey minecraftkey, String s, ItemStack itemstack, NonNullList<RecipeItemStack> nonnulllist, boolean isBukkit) {
+ this.isBukkit = isBukkit;
+ // Airplane end
this.key = minecraftkey;
this.group = s;
this.result = itemstack;
@@ -69,6 +77,28 @@ public class ShapelessRecipes implements RecipeCrafting {
}
public boolean a(InventoryCrafting inventorycrafting, World world) {
+ // Airplane start
+ if (!this.isBukkit) {
+ java.util.List<RecipeItemStack> ingredients = com.google.common.collect.Lists.newArrayList(this.ingredients.toArray(new RecipeItemStack[0]));
+
+ inventory: for (int index = 0; index < inventorycrafting.getSize(); index++) {
+ ItemStack itemStack = inventorycrafting.getItem(index);
+
+ if (!itemStack.isEmpty()) {
+ for (int i = 0; i < ingredients.size(); i++) {
+ if (ingredients.get(i).test(itemStack)) {
+ ingredients.remove(i);
+ continue inventory;
+ }
+ }
+ return false;
+ }
+ }
+
+ return ingredients.isEmpty();
+ }
+ // Airplane end
+
AutoRecipeStackManager autorecipestackmanager = new AutoRecipeStackManager();
int i = 0;
diff --git a/src/main/java/net/minecraft/world/level/IBlockAccess.java b/src/main/java/net/minecraft/world/level/IBlockAccess.java
index e612e1d30f76e217b1aa23488ab025adce048f57..c9198d242b9053fad6fa5b53c1894679002d50a7 100644
--- a/src/main/java/net/minecraft/world/level/IBlockAccess.java
+++ b/src/main/java/net/minecraft/world/level/IBlockAccess.java
@@ -14,9 +14,11 @@ import net.minecraft.world.level.block.state.IBlockData;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.Material;
import net.minecraft.world.phys.AxisAlignedBB;
+import net.minecraft.world.phys.MovingObjectPosition;
import net.minecraft.world.phys.MovingObjectPositionBlock;
import net.minecraft.world.phys.Vec3D;
import net.minecraft.world.phys.shapes.VoxelShape;
+import net.minecraft.world.phys.shapes.VoxelShapeCollision;
public interface IBlockAccess {
@@ -56,6 +58,15 @@ public interface IBlockAccess {
return BlockPosition.a(axisalignedbb).map(this::getType);
}
+ // Airplane start - broken down variant of below rayTraceBlock, used by World#rayTraceDirect
+ default MovingObjectPosition.EnumMovingObjectType rayTraceBlockDirect(Vec3D vec3d, Vec3D vec3d1, BlockPosition blockposition, IBlockData iblockdata, VoxelShapeCollision voxelshapecoll) {
+ VoxelShape voxelshape = RayTrace.BlockCollisionOption.COLLIDER.get(iblockdata, this, blockposition, voxelshapecoll);
+ MovingObjectPositionBlock movingobjectpositionblock = this.rayTrace(vec3d, vec3d1, blockposition, voxelshape, iblockdata);
+
+ return movingobjectpositionblock == null ? null : movingobjectpositionblock.getType();
+ }
+ // Airplane end
+
// CraftBukkit start - moved block handling into separate method for use by Block#rayTrace
default MovingObjectPositionBlock rayTraceBlock(RayTrace raytrace1, BlockPosition blockposition) {
// Paper start - Prevent raytrace from loading chunks
diff --git a/src/main/java/net/minecraft/world/level/SpawnerCreature.java b/src/main/java/net/minecraft/world/level/SpawnerCreature.java
index d497006f05f79015cd791849888832bb53f4a414..d98526785ff2fa3b72e8ffffcb89a57a2203a5c8 100644
--- a/src/main/java/net/minecraft/world/level/SpawnerCreature.java
+++ b/src/main/java/net/minecraft/world/level/SpawnerCreature.java
@@ -415,7 +415,10 @@ public final class SpawnerCreature {
}
private static List<BiomeSettingsMobs.c> a(WorldServer worldserver, StructureManager structuremanager, ChunkGenerator chunkgenerator, EnumCreatureType enumcreaturetype, BlockPosition blockposition, @Nullable BiomeBase biomebase) {
- return enumcreaturetype == EnumCreatureType.MONSTER && worldserver.getType(blockposition.down()).getBlock() == Blocks.NETHER_BRICKS && structuremanager.a(blockposition, false, StructureGenerator.FORTRESS).e() ? StructureGenerator.FORTRESS.c() : chunkgenerator.getMobsFor(biomebase != null ? biomebase : worldserver.getBiome(blockposition), structuremanager, enumcreaturetype, blockposition);
+ // Airplane start - single chunk lookup
+ Chunk chunk;
+ return enumcreaturetype == EnumCreatureType.MONSTER && (chunk = worldserver.getChunkIfLoaded(blockposition)) != null && chunk.getType(blockposition.down()).getBlock() == Blocks.NETHER_BRICKS && structuremanager.a(blockposition, false, StructureGenerator.FORTRESS).e() ? StructureGenerator.FORTRESS.c() : chunkgenerator.getMobsFor(biomebase != null ? biomebase : worldserver.getBiome(blockposition), structuremanager, enumcreaturetype, blockposition);
+ // Airplane end
}
private static BlockPosition getRandomPosition(World world, Chunk chunk) {
diff --git a/src/main/java/net/minecraft/world/level/StructureManager.java b/src/main/java/net/minecraft/world/level/StructureManager.java
index acacbf9617f99b97fc7fd2ba718775e1b3e429e9..967ae0212028d57d366497f7f25c61776c1ac3f2 100644
--- a/src/main/java/net/minecraft/world/level/StructureManager.java
+++ b/src/main/java/net/minecraft/world/level/StructureManager.java
@@ -15,6 +15,11 @@ import net.minecraft.world.level.levelgen.feature.StructureGenerator;
import net.minecraft.world.level.levelgen.structure.StructurePiece;
import net.minecraft.world.level.levelgen.structure.StructureStart;
+// Airplane start
+import it.unimi.dsi.fastutil.longs.LongIterator;
+import it.unimi.dsi.fastutil.longs.LongSet;
+// Airplane end
+
public class StructureManager {
private final GeneratorAccess a; public GeneratorAccess getLevel() { return a; } // Paper - OBFHELPER
@@ -51,13 +56,15 @@ public class StructureManager {
public java.util.List<StructureStart<?>> getFeatureStarts(SectionPosition sectionPosition, StructureGenerator<?> structureGenerator, IWorldReader world) {
// Tuinity end - add world parameter
java.util.List<StructureStart<?>> list = new ObjectArrayList<>();
- for (Long curLong: (world == null ? getLevel() : world).getChunkAt(sectionPosition.a(), sectionPosition.c(), ChunkStatus.STRUCTURE_REFERENCES).b(structureGenerator)) { // Tuinity - fix deadlock on world gen - chunk can be unloaded while generating, so we should be using the generator's regionlimitedaccess so we always get the chunk
- SectionPosition sectionPosition1 = SectionPosition.a(new ChunkCoordIntPair(curLong), 0);
+ // Airplane start - skip allocating Longs
+ (world == null ? getLevel() : world).getChunkAt(sectionPosition.a(), sectionPosition.c(), ChunkStatus.STRUCTURE_REFERENCES).b(structureGenerator).forEach((java.util.function.LongConsumer) curLong -> {
+ SectionPosition sectionPosition1 = SectionPosition.a(ChunkCoordIntPair.getX(curLong), 0, ChunkCoordIntPair.getZ(curLong)); // don't allocate ChunkCoordIntPair
StructureStart<?> structurestart = a(sectionPosition1, structureGenerator, getLevel().getChunkAt(sectionPosition1.a(), sectionPosition1.c(), ChunkStatus.STRUCTURE_STARTS));
if (structurestart != null && structurestart.e()) {
list.add(structurestart);
}
- }
+ });
+ // Airplane end
return list;
}
// Paper end
@@ -85,7 +92,18 @@ public class StructureManager {
}
public StructureStart<?> getStructureStarts(BlockPosition blockposition, boolean flag, StructureGenerator<?> structuregenerator, IWorldReader world) {
// Paper start - remove structure streams
- for (StructureStart<?> structurestart : getFeatureStarts(SectionPosition.a(blockposition), structuregenerator, world)) { // Tuinity end - add world parameter
+ // Airplane start - inline getFeatureStarts to skip creating the list
+ SectionPosition sectionPosition = SectionPosition.a(blockposition);
+
+ // use iterator here instead of forEach like in getFeatureStarts so we can return early
+ LongSet longSet = (world == null ? getLevel() : world).getChunkAt(sectionPosition.a(), sectionPosition.c(), ChunkStatus.STRUCTURE_REFERENCES).b(structuregenerator);
+ LongIterator iterator = longSet.iterator();
+ while (iterator.hasNext()) {
+ long curLong = iterator.nextLong();
+ SectionPosition sectionPosition1 = SectionPosition.a(ChunkCoordIntPair.getX(curLong), 0, ChunkCoordIntPair.getZ(curLong)); // don't allocate ChunkCoordIntPair
+ StructureStart<?> structurestart = a(sectionPosition1, structuregenerator, getLevel().getChunkAt(sectionPosition1.a(), sectionPosition1.c(), ChunkStatus.STRUCTURE_STARTS));
+ if (structurestart != null && structurestart.e()) {
+
if (structurestart.c().b(blockposition)) {
if (!flag) {
return structurestart;
@@ -96,7 +114,10 @@ public class StructureManager {
}
}
}
+
+ }
}
+ // Airplane end
return StructureStart.a;
// Paper end
}
diff --git a/src/main/java/net/minecraft/world/level/World.java b/src/main/java/net/minecraft/world/level/World.java
index c8a5d4972431ce9615312280f36181a2b9645df7..e3f1f20608cab7067674b2cdd2759a34902b6626 100644
--- a/src/main/java/net/minecraft/world/level/World.java
+++ b/src/main/java/net/minecraft/world/level/World.java
@@ -69,6 +69,8 @@ import net.minecraft.world.level.saveddata.maps.WorldMap;
import net.minecraft.world.level.storage.WorldData;
import net.minecraft.world.level.storage.WorldDataMutable;
import net.minecraft.world.phys.AxisAlignedBB;
+import net.minecraft.world.phys.MovingObjectPosition;
+import net.minecraft.world.phys.Vec3D;
import net.minecraft.world.phys.shapes.OperatorBoolean;
import net.minecraft.world.phys.shapes.VoxelShape;
import net.minecraft.world.phys.shapes.VoxelShapeCollision;
@@ -104,7 +106,7 @@ public abstract class World implements GeneratorAccess, AutoCloseable {
//public final List<TileEntity> tileEntityList = Lists.newArrayList(); // Paper - remove unused list
public final List<TileEntity> tileEntityListTick = Lists.newArrayList();
protected final List<TileEntity> tileEntityListPending = Lists.newArrayList();
- protected final java.util.Set<TileEntity> tileEntityListUnload = com.google.common.collect.Sets.newHashSet();
+ protected final java.util.Set<TileEntity> tileEntityListUnload = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>()); // Airplane - use set with faster contains
public final Thread serverThread;
private final boolean debugWorld;
private int d;
@@ -378,6 +380,91 @@ public abstract class World implements GeneratorAccess, AutoCloseable {
return null;
}
+ // Airplane start - broken down method of raytracing for EntityLiving#hasLineOfSight, replaces IBlockAccess#rayTrace(RayTrace)
+ public MovingObjectPosition.EnumMovingObjectType rayTraceDirect(Vec3D vec3d, Vec3D vec3d1, VoxelShapeCollision voxelshapecoll) {
+ // most of this code comes from IBlockAccess#a(RayTrace, BiFunction, Function), but removes the needless functions
+ if (vec3d.equals(vec3d1)) {
+ return MovingObjectPosition.EnumMovingObjectType.MISS;
+ }
+
+ double endX = MathHelper.linearInterpolation(-1.0E-7D, vec3d1.x, vec3d.x);
+ double endY = MathHelper.linearInterpolation(-1.0E-7D, vec3d1.y, vec3d.y);
+ double endZ = MathHelper.linearInterpolation(-1.0E-7D, vec3d1.z, vec3d.z);
+
+ double startX = MathHelper.linearInterpolation(-1.0E-7D, vec3d.x, vec3d1.x);
+ double startY = MathHelper.linearInterpolation(-1.0E-7D, vec3d.y, vec3d1.y);
+ double startZ = MathHelper.linearInterpolation(-1.0E-7D, vec3d.z, vec3d1.z);
+
+ int currentX = MathHelper.floor(startX);
+ int currentY = MathHelper.floor(startY);
+ int currentZ = MathHelper.floor(startZ);
+
+ BlockPosition.MutableBlockPosition currentBlock = new BlockPosition.MutableBlockPosition(currentX, currentY, currentZ);
+
+ Chunk chunk = this.getChunkIfLoaded(currentBlock);
+ if (chunk == null) {
+ return MovingObjectPosition.EnumMovingObjectType.MISS;
+ }
+
+ MovingObjectPosition.EnumMovingObjectType initialCheck = this.rayTraceBlockDirect(vec3d, vec3d1, currentBlock, chunk.getType(currentBlock), voxelshapecoll);
+
+ if (initialCheck != null) {
+ return initialCheck;
+ }
+
+ double diffX = endX - startX;
+ double diffY = endY - startY;
+ double diffZ = endZ - startZ;
+
+ int xDirection = MathHelper.sign(diffX);
+ int yDirection = MathHelper.sign(diffY);
+ int zDirection = MathHelper.sign(diffZ);
+
+ double normalizedX = xDirection == 0 ? Double.MAX_VALUE : (double) xDirection / diffX;
+ double normalizedY = yDirection == 0 ? Double.MAX_VALUE : (double) yDirection / diffY;
+ double normalizedZ = zDirection == 0 ? Double.MAX_VALUE : (double) zDirection / diffZ;
+
+ double normalizedXDirection = normalizedX * (xDirection > 0 ? 1.0D - MathHelper.getDecimals(startX) : MathHelper.getDecimals(startX));
+ double normalizedYDirection = normalizedY * (yDirection > 0 ? 1.0D - MathHelper.getDecimals(startY) : MathHelper.getDecimals(startY));
+ double normalizedZDirection = normalizedZ * (zDirection > 0 ? 1.0D - MathHelper.getDecimals(startZ) : MathHelper.getDecimals(startZ));
+
+ MovingObjectPosition.EnumMovingObjectType result;
+
+ do {
+ if (normalizedXDirection > 1.0D && normalizedYDirection > 1.0D && normalizedZDirection > 1.0D) {
+ return MovingObjectPosition.EnumMovingObjectType.MISS;
+ }
+
+ if (normalizedXDirection < normalizedYDirection) {
+ if (normalizedXDirection < normalizedZDirection) {
+ currentX += xDirection;
+ normalizedXDirection += normalizedX;
+ } else {
+ currentZ += zDirection;
+ normalizedZDirection += normalizedZ;
+ }
+ } else if (normalizedYDirection < normalizedZDirection) {
+ currentY += yDirection;
+ normalizedYDirection += normalizedY;
+ } else {
+ currentZ += zDirection;
+ normalizedZDirection += normalizedZ;
+ }
+
+ currentBlock.setValues(currentX, currentY, currentZ);
+ if (chunk.getPos().x != currentBlock.getX() >> 4 || chunk.getPos().z != currentBlock.getZ() >> 4) {
+ chunk = this.getChunkIfLoaded(currentBlock);
+ if (chunk == null) {
+ return MovingObjectPosition.EnumMovingObjectType.MISS;
+ }
+ }
+ result = this.rayTraceBlockDirect(vec3d, vec3d1, currentBlock, chunk.getType(currentBlock), voxelshapecoll);
+ } while (result == null);
+
+ return result;
+ }
+ // Airplane end
+
public static boolean isValidLocation(BlockPosition blockposition) {
return blockposition.isValidLocation(); // Paper - use better/optimized check
}
@@ -899,12 +986,17 @@ public abstract class World implements GeneratorAccess, AutoCloseable {
gameprofilerfiller.enter("blockEntities");
timings.tileEntityTick.startTiming(); // Spigot
if (!this.tileEntityListUnload.isEmpty()) {
+ // Airplane start - we just use the identitymap as the basis for the unload set now instead of copying
+ /*
// Paper start - Use alternate implementation with faster contains
java.util.Set<TileEntity> toRemove = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>());
toRemove.addAll(tileEntityListUnload);
this.tileEntityListTick.removeAll(toRemove);
// Paper end
//this.tileEntityList.removeAll(this.tileEntityListUnload); // Paper - remove unused list
+ */
+ this.tileEntityListTick.removeAll(this.tileEntityListUnload);
+ // Airplane end
this.tileEntityListUnload.clear();
}
@@ -1016,19 +1108,19 @@ public abstract class World implements GeneratorAccess, AutoCloseable {
public void a(Consumer<Entity> consumer, Entity entity) {
try {
- consumer.accept(entity);
+ consumer.accept(entity); // Airplane - error on change
} catch (Throwable throwable) {
if (throwable instanceof ThreadDeath) throw throwable; // Paper
// Paper start - Prevent tile entity and entity crashes
String msg = "Entity threw exception at " + entity.world.getWorld().getName() + ":" + entity.locX() + "," + entity.locY() + "," + entity.locZ();
System.err.println(msg);
throwable.printStackTrace();
- getServer().getPluginManager().callEvent(new ServerExceptionEvent(new ServerInternalException(msg, throwable)));
+ getServer().getPluginManager().callEvent(new ServerExceptionEvent(new ServerInternalException(msg, throwable))); // Airplane - error on change
entity.dead = true;
return;
// Paper end
}
- MinecraftServer.getServer().executeMidTickTasks(); // Tuinity - execute chunk tasks mid tick
+ MinecraftServer.getServer().executeMidTickTasks(); // Tuinity - execute chunk tasks mid tick // Airplane - error on change
}
// Paper start - Prevent armor stands from doing entity lookups
@Override
diff --git a/src/main/java/net/minecraft/world/level/block/BlockDirtSnowSpreadable.java b/src/main/java/net/minecraft/world/level/block/BlockDirtSnowSpreadable.java
index 712596420af83e6e1b9d147ae2fd8d8a1f36e1b9..9c29fa3efac7e16df81b8a44934e3286bb37f1f6 100644
--- a/src/main/java/net/minecraft/world/level/block/BlockDirtSnowSpreadable.java
+++ b/src/main/java/net/minecraft/world/level/block/BlockDirtSnowSpreadable.java
@@ -54,8 +54,14 @@ public abstract class BlockDirtSnowSpreadable extends BlockDirtSnow {
if (worldserver.getLightLevel(blockposition.up()) >= 9) {
IBlockData iblockdata1 = this.getBlockData();
+ // Airplane start - use mutable position
+ BlockPosition.MutableBlockPosition blockposition1 = new BlockPosition.MutableBlockPosition();
for (int i = 0; i < 4; ++i) {
+ blockposition1.setValues(blockposition).addValues(random.nextInt(3) - 1, random.nextInt(5) - 3, random.nextInt(3) - 1);
+ /*
BlockPosition blockposition1 = blockposition.b(random.nextInt(3) - 1, random.nextInt(5) - 3, random.nextInt(3) - 1);
+ */
+ // Airplane end
if (worldserver.getType(blockposition1).a(Blocks.DIRT) && c(iblockdata1, (IWorldReader) worldserver, blockposition1)) {
org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockSpreadEvent(worldserver, blockposition, blockposition1, (IBlockData) iblockdata1.set(BlockDirtSnowSpreadable.a, worldserver.getType(blockposition1.up()).a(Blocks.SNOW))); // CraftBukkit
diff --git a/src/main/java/net/minecraft/world/level/chunk/Chunk.java b/src/main/java/net/minecraft/world/level/chunk/Chunk.java
index 259d4ac89e84fd334ff65ea8a606e1fc50cc882b..4f5f9eb110cf71a966d1365c7813ba55b5127890 100644
--- a/src/main/java/net/minecraft/world/level/chunk/Chunk.java
+++ b/src/main/java/net/minecraft/world/level/chunk/Chunk.java
@@ -99,6 +99,38 @@ public class Chunk implements IChunkAccess {
private final ChunkCoordIntPair loc; public final long coordinateKey; public final int locX; public final int locZ; // Paper - cache coordinate key
private volatile boolean x;
+ // Airplane start - instead of using a random every time the chunk is ticked, define when lightning strikes preemptively
+ private int lightningTick;
+ // shouldDoLightning compiles down to 29 bytes, which with the default of 35 byte inlining should guarantee an inline
+ public final boolean shouldDoLightning(java.util.Random random) {
+ if (this.lightningTick-- <= 0) {
+ this.lightningTick = random.nextInt(100000) << 1;
+ return true;
+ }
+ return false;
+ }
+ // Airplane end
+
+ // Airplane start - entity tracker runnable
+ // prevents needing to allocate new lambda in processTrackQueue
+ public final Runnable entityTracker = new Runnable() {
+ @Override
+ public void run() {
+ Entity[] entities = Chunk.this.entities.getRawData();
+ for (int i = 0, len = Chunk.this.entities.size(); i < len; ++i) {
+ Entity entity = entities[i];
+ if (entity != null) {
+ PlayerChunkMap.EntityTracker tracker = ((WorldServer) Chunk.this.getWorld()).getChunkProvider().playerChunkMap.trackedEntities.get(entity.getId());
+ if (tracker != null) {
+ tracker.updatePlayers(tracker.tracker.getPlayersInTrackRange());
+ tracker.tickEntry();
+ }
+ }
+ }
+ }
+ };
+ // Airplane end
+
public Chunk(World world, ChunkCoordIntPair chunkcoordintpair, BiomeStorage biomestorage) {
this(world, chunkcoordintpair, biomestorage, ChunkConverter.a, TickListEmpty.b(), TickListEmpty.b(), 0L, (ChunkSection[]) null, (Consumer) null);
}
@@ -333,6 +365,7 @@ public class Chunk implements IChunkAccess {
// CraftBukkit start
this.bukkitChunk = new org.bukkit.craftbukkit.CraftChunk(this);
this.entitySlicesManager = new com.tuinity.tuinity.world.ChunkEntitySlices(this.world, this.loc.x, this.loc.z, 0, 15); // TODO update for 1.17 // Tuinity
+ this.lightningTick = this.world.random.nextInt(100000) << 1; // Airplane - initialize lightning tick
}
public org.bukkit.Chunk bukkitChunk;
diff --git a/src/main/java/net/minecraft/world/level/chunk/DataPaletteBlock.java b/src/main/java/net/minecraft/world/level/chunk/DataPaletteBlock.java
index a6937366cd9c9d708edb5cd1ab3ac096e7b2032e..a579c5bf9e20c74aa3bf8ef6bc00576409805ca6 100644
--- a/src/main/java/net/minecraft/world/level/chunk/DataPaletteBlock.java
+++ b/src/main/java/net/minecraft/world/level/chunk/DataPaletteBlock.java
@@ -235,12 +235,16 @@ public class DataPaletteBlock<T> implements DataPaletteExpandable<T> {
this.b();
}
+ // Airplane start - add parameter for reusing aint
public synchronized void a(NBTTagCompound nbttagcompound, String s, String s1) { // Paper - synchronize
+ a(nbttagcompound, s, s1, new int[4096]);
+ }
+ public synchronized void a(NBTTagCompound nbttagcompound, String s, String s1, int[] aint) { // Paper - synchronize // Airplane end
this.a();
DataPaletteHash<T> datapalettehash = new DataPaletteHash<>(this.d, this.i, this.c, this.e, this.f);
T t0 = this.g;
int i = datapalettehash.a(this.g);
- int[] aint = new int[4096];
+ //int[] aint = new int[4096]; // Airplane - use parameter
for (int j = 0; j < 4096; ++j) {
T t1 = this.a(j);
diff --git a/src/main/java/net/minecraft/world/level/chunk/storage/ChunkRegionLoader.java b/src/main/java/net/minecraft/world/level/chunk/storage/ChunkRegionLoader.java
index ec2b238480413ba9c123d9ddeaa787d9520e1b74..bf96f9e538fc29ca914536e8a7ce727ebe43a8b2 100644
--- a/src/main/java/net/minecraft/world/level/chunk/storage/ChunkRegionLoader.java
+++ b/src/main/java/net/minecraft/world/level/chunk/storage/ChunkRegionLoader.java
@@ -468,6 +468,7 @@ public class ChunkRegionLoader {
public static NBTTagCompound saveChunk(WorldServer worldserver, IChunkAccess ichunkaccess) {
return saveChunk(worldserver, ichunkaccess, null);
}
+ private static final ThreadLocal<int[]> paletteArray = ThreadLocal.withInitial(() -> new int[4096]); // Airplane
public static NBTTagCompound saveChunk(WorldServer worldserver, IChunkAccess ichunkaccess, AsyncSaveData asyncsavedata) {
// Paper end
// Tuinity start - rewrite light impl
@@ -498,6 +499,7 @@ public class ChunkRegionLoader {
NBTTagCompound nbttagcompound2;
+ int[] aint = paletteArray.get(); // Airplane - use cached
for (int i = -1; i < 17; ++i) { // Paper - conflict on loop parameter change
int finalI = i; // CraftBukkit - decompile errors
ChunkSection chunksection = (ChunkSection) Arrays.stream(achunksection).filter((chunksection1) -> {
@@ -518,7 +520,7 @@ public class ChunkRegionLoader {
nbttagcompound2 = new NBTTagCompound();
nbttagcompound2.setByte("Y", (byte) (i & 255));
if (chunksection != Chunk.a) {
- chunksection.getBlocks().a(nbttagcompound2, "Palette", "BlockStates");
+ chunksection.getBlocks().a(nbttagcompound2, "Palette", "BlockStates", aint); // Airplane
}
if (nibblearray != null && !nibblearray.c()) {
diff --git a/src/main/java/net/minecraft/world/level/storage/loot/LootTableInfo.java b/src/main/java/net/minecraft/world/level/storage/loot/LootTableInfo.java
index 95d0c9f22d79194ca83ca6f6a8e6d91180a3c8da..20cc04be75ab202d4c4ee9a07e9876ceff8422ca 100644
--- a/src/main/java/net/minecraft/world/level/storage/loot/LootTableInfo.java
+++ b/src/main/java/net/minecraft/world/level/storage/loot/LootTableInfo.java
@@ -43,8 +43,8 @@ public class LootTableInfo {
this.world = worldserver;
this.d = function;
this.f = function1;
- this.h = ImmutableMap.copyOf(map);
- this.i = ImmutableMap.copyOf(map1);
+ this.h = java.util.Collections.unmodifiableMap(map); // Airplane
+ this.i = java.util.Collections.unmodifiableMap(map1); // Airplane
}
public boolean hasContextParameter(LootContextParameter<?> lootcontextparameter) {
@@ -62,7 +62,7 @@ public class LootTableInfo {
@Nullable
public <T> T getContextParameter(LootContextParameter<T> lootcontextparameter) {
- return this.h.get(lootcontextparameter);
+ return (T) this.h.get(lootcontextparameter); // Airplane - compile error
}
public boolean a(LootTable loottable) {
@@ -216,7 +216,7 @@ public class LootTableInfo {
}
public <T> T a(LootContextParameter<T> lootcontextparameter) {
- T t0 = this.b.get(lootcontextparameter);
+ T t0 = (T) this.b.get(lootcontextparameter); // Airplane - compile error
if (t0 == null) {
throw new IllegalArgumentException("No parameter " + lootcontextparameter);
@@ -227,7 +227,7 @@ public class LootTableInfo {
@Nullable
public <T> T b(LootContextParameter<T> lootcontextparameter) {
- return this.b.get(lootcontextparameter);
+ return (T) this.b.get(lootcontextparameter); // Airplane - compile error
}
public LootTableInfo build(LootContextParameterSet lootcontextparameterset) {
diff --git a/src/main/java/org/bukkit/craftbukkit/CraftServer.java b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
index fd3333fef4112e6469ccd316ba2c82926c04e5db..aec6c036ed42078a6cc3540f1f6e46a551e87a2f 100644
--- a/src/main/java/org/bukkit/craftbukkit/CraftServer.java
+++ b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
@@ -232,7 +232,7 @@ import javax.annotation.Nullable; // Paper
import javax.annotation.Nonnull; // Paper
public final class CraftServer implements Server {
- private final String serverName = "Tuinity"; // Paper // Tuinity
+ private final String serverName = "Airplane"; // Paper // Tuinity // Airplane
private final String serverVersion;
private final String bukkitVersion = Versioning.getBukkitVersion();
private final Logger logger = Logger.getLogger("Minecraft");
@@ -978,6 +978,11 @@ public final class CraftServer implements Server {
plugin.getDescription().getName(),
"This plugin is not properly shutting down its async tasks when it is being shut down. This task may throw errors during the final shutdown logs and might not complete before process dies."
));
+ getLogger().log(Level.SEVERE, String.format("%s Stacktrace", worker.getThread().getName()));
+ StackTraceElement[] stackTrace = worker.getThread().getStackTrace();
+ for (StackTraceElement element : stackTrace) {
+ getLogger().log(Level.SEVERE, " " + element.toString());
+ }
}
}
// Paper end
diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapelessRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapelessRecipe.java
index de9c5ed6b03a290fe77eec719f0079fd7bd9b7f5..8c02f6fdffb59153712a3be778f9c454fd87b73b 100644
--- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapelessRecipe.java
+++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapelessRecipe.java
@@ -44,6 +44,6 @@ public class CraftShapelessRecipe extends ShapelessRecipe implements CraftRecipe
data.set(i, toNMS(ingred.get(i), true));
}
- MinecraftServer.getServer().getCraftingManager().addRecipe(new ShapelessRecipes(CraftNamespacedKey.toMinecraft(this.getKey()), this.getGroup(), CraftItemStack.asNMSCopy(this.getResult()), data));
+ MinecraftServer.getServer().getCraftingManager().addRecipe(new ShapelessRecipes(CraftNamespacedKey.toMinecraft(this.getKey()), this.getGroup(), CraftItemStack.asNMSCopy(this.getResult()), data, true)); // Airplane
}
}
diff --git a/src/main/java/org/bukkit/craftbukkit/scheduler/MinecraftInternalPlugin.java b/src/main/java/org/bukkit/craftbukkit/scheduler/MinecraftInternalPlugin.java
index 49dc0c441b9dd7e7745cf15ced67f383ebee1f99..b343d8ee7435312929558efdaf127334d8e2fff6 100644
--- a/src/main/java/org/bukkit/craftbukkit/scheduler/MinecraftInternalPlugin.java
+++ b/src/main/java/org/bukkit/craftbukkit/scheduler/MinecraftInternalPlugin.java
@@ -19,7 +19,8 @@ public class MinecraftInternalPlugin extends PluginBase {
private boolean enabled = true;
private final String pluginName;
- private PluginDescriptionFile pdf;
+ private org.bukkit.plugin.PluginLogger logger;
+ private PluginDescriptionFile pdf; // Airplane
public MinecraftInternalPlugin() {
this.pluginName = "Minecraft";
@@ -72,7 +73,12 @@ public class MinecraftInternalPlugin extends PluginBase {
@Override
public PluginLogger getLogger() {
- throw new UnsupportedOperationException("Not supported.");
+ // Airplane start
+ if (this.logger == null) {
+ this.logger = new org.bukkit.plugin.PluginLogger(this); // Airplane
+ }
+ return this.logger;
+ // Airplane end
}
@Override
@@ -82,7 +88,7 @@ public class MinecraftInternalPlugin extends PluginBase {
@Override
public Server getServer() {
- throw new UnsupportedOperationException("Not supported.");
+ return org.bukkit.Bukkit.getServer(); // Airplane - impl
}
@Override
diff --git a/src/main/java/org/bukkit/craftbukkit/util/Versioning.java b/src/main/java/org/bukkit/craftbukkit/util/Versioning.java
index 001b1e5197eaa51bfff9031aa6c69876c9a47960..1788d79ea489e446d3d9f541693d4ba3dfc26015 100644
--- a/src/main/java/org/bukkit/craftbukkit/util/Versioning.java
+++ b/src/main/java/org/bukkit/craftbukkit/util/Versioning.java
@@ -11,7 +11,7 @@ public final class Versioning {
public static String getBukkitVersion() {
String result = "Unknown-Version";
- InputStream stream = Bukkit.class.getClassLoader().getResourceAsStream("META-INF/maven/com.tuinity/tuinity-api/pom.properties"); // Tuinity
+ InputStream stream = Bukkit.class.getClassLoader().getResourceAsStream("META-INF/maven/gg.airplane/airplane-api/pom.properties"); // Tuinity // Airplane
Properties properties = new Properties();
if (stream != null) {
diff --git a/src/main/java/org/spigotmc/ActivationRange.java b/src/main/java/org/spigotmc/ActivationRange.java
index 5c2eaca0bc63c7880ee928aba6a24761737aa649..6c4c4580faef39e48de5af4db003cf2e3b8a99b5 100644
--- a/src/main/java/org/spigotmc/ActivationRange.java
+++ b/src/main/java/org/spigotmc/ActivationRange.java
@@ -47,6 +47,9 @@ import net.minecraft.world.entity.schedule.Activity;
import net.minecraft.world.entity.item.EntityFallingBlock;
import net.minecraft.world.entity.projectile.EntityEnderSignal;
// Paper end
+// Airplane start
+import net.minecraft.world.phys.Vec3D;
+// Airplane end
public class ActivationRange
{
@@ -227,7 +230,7 @@ public class ActivationRange
Chunk chunk = chunkProvider.getChunkAtIfLoadedMainThreadNoCache( i1, j1 ); // Paper
if ( chunk != null )
{
- activateChunkEntities( chunk );
+ activateChunkEntities( chunk, player.getPositionVector() ); // Airplane
}
}
}
@@ -240,7 +243,7 @@ public class ActivationRange
*
* @param chunk
*/
- private static void activateChunkEntities(Chunk chunk)
+ private static void activateChunkEntities(Chunk chunk, Vec3D playerVec) // Airplane - add player location
{
// Paper start
Entity[] rawData = chunk.entities.getRawData();
@@ -249,11 +252,19 @@ public class ActivationRange
//for ( Entity entity : (Collection<Entity>) slice )
// Paper end
{
+ // Airplane start
+ Vec3D entityVec = entity.getPositionVector();
+ double diffX = playerVec.x - entityVec.x, diffY = playerVec.y - entityVec.y, diffZ = playerVec.z - entityVec.z;
+ int priority = Math.max(1, (int) (diffX * diffX + diffY * diffY + diffZ * diffZ) >> gg.airplane.AirplaneConfig.activationDistanceMod);
if (MinecraftServer.currentTick > entity.activatedTick) {
if (entity.defaultActivationState || entity.activationType.boundingBox.c(entity.getBoundingBox())) { // Paper
entity.activatedTick = MinecraftServer.currentTick;
}
+ entity.activatedPriority = Math.min(gg.airplane.AirplaneConfig.maximumActivationPrio, priority);
+ } else {
+ entity.activatedPriority = Math.min(gg.airplane.AirplaneConfig.maximumActivationPrio, Math.min(priority, entity.activatedPriority));
}
+ // Airplane end
}
}
}