Initial folia implementation

This commit is contained in:
Lukas Rieger (Blue) 2023-03-31 00:25:13 +02:00
parent 2554462bb4
commit 681c346da6
No known key found for this signature in database
GPG Key ID: 2D09EC5ED2687FF2
15 changed files with 1399 additions and 17 deletions

View File

@ -0,0 +1,118 @@
plugins {
java
`java-library`
id("com.diffplug.spotless") version "6.1.2"
id ("com.github.node-gradle.node") version "3.0.1"
id ("com.github.johnrengelman.shadow") version "7.1.2"
id ("com.modrinth.minotaur") version "2.+"
}
group = "de.bluecolored.bluemap.bukkit"
version = System.getProperty("bluemap.version") ?: "?" // set by BlueMapCore
val javaTarget = 17
java {
sourceCompatibility = JavaVersion.toVersion(javaTarget)
targetCompatibility = JavaVersion.toVersion(javaTarget)
}
repositories {
mavenCentral()
maven {
setUrl("https://libraries.minecraft.net")
}
maven {
setUrl("https://jitpack.io")
}
maven {
setUrl("https://repo.papermc.io/repository/maven-public/")
}
maven {
setUrl("https://oss.sonatype.org/content/repositories/snapshots")
}
}
dependencies {
api ("de.bluecolored.bluemap.common:BlueMapCommon") {
//exclude dependencies provided by bukkit
exclude( group = "com.google.guava", module = "guava" )
exclude( group = "com.google.code.gson", module = "gson" )
}
shadow ("dev.folia:folia-api:1.19.4-R0.1-SNAPSHOT")
implementation ("org.bstats:bstats-bukkit:2.2.1")
testImplementation ("org.junit.jupiter:junit-jupiter:5.8.2")
testRuntimeOnly ("org.junit.jupiter:junit-jupiter-engine:5.8.2")
}
spotless {
java {
target ("src/*/java/**/*.java")
licenseHeaderFile("../../HEADER")
indentWithSpaces()
trimTrailingWhitespace()
}
}
tasks.withType(JavaCompile::class).configureEach {
options.apply {
encoding = "utf-8"
}
}
tasks.withType(AbstractArchiveTask::class).configureEach {
isReproducibleFileOrder = true
isPreserveFileTimestamps = false
}
tasks.test {
useJUnitPlatform()
}
tasks.processResources {
from("src/main/resources") {
include("plugin.yml")
duplicatesStrategy = DuplicatesStrategy.INCLUDE
expand (
"version" to project.version
)
}
}
tasks.shadowJar {
destinationDirectory.set(file("../../build/release"))
archiveFileName.set("BlueMap-${project.version}-${project.name}.jar")
//relocate ("com.flowpowered.math", "de.bluecolored.shadow.flowpowered.math") //DON"T relocate this, because the API depends on it
relocate ("com.typesafe.config", "de.bluecolored.shadow.typesafe.config")
relocate ("net.querz.nbt", "de.bluecolored.shadow.querz.nbt")
relocate ("org.spongepowered.configurate", "de.bluecolored.shadow.configurate")
relocate ("org.bstats", "de.bluecolored.shadow.bstats")
relocate ("com.mojang.brigadier", "de.bluecolored.shadow.mojang.brigadier")
relocate ("com.github.benmanes.caffeine", "de.bluecolored.shadow.benmanes.caffeine")
relocate ("org.aopalliance", "de.bluecolored.shadow.aopalliance")
relocate ("javax.inject", "de.bluecolored.shadow.javax.inject")
relocate ("org.checkerframework", "de.bluecolored.shadow.checkerframework")
relocate ("org.codehaus", "de.bluecolored.shadow.codehaus")
relocate ("io.leangen.geantyref", "de.bluecolored.shadow.geantyref")
relocate ("com.google.errorprone", "de.bluecolored.shadow.google.errorprone")
relocate ("com.google.inject", "de.bluecolored.shadow.google.inject")
relocate ("org.apache.commons.dbcp2", "de.bluecolored.shadow.apache.commons.dbcp2")
relocate ("org.apache.commons.io", "de.bluecolored.shadow.apache.commons.io")
relocate ("org.apache.commons.lang3", "de.bluecolored.shadow.apache.commons.lang3")
relocate ("org.apache.commons.logging", "de.bluecolored.shadow.apache.commons.logging")
relocate ("org.apache.commons.pool2", "de.bluecolored.shadow.apache.commons.pool2")
}
tasks.register("release") {
dependsOn(tasks.shadowJar)
}
tasks.register("publish") {
}

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

185
implementations/folia/gradlew vendored Normal file
View File

@ -0,0 +1,185 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MSYS* | MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

89
implementations/folia/gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,3 @@
rootProject.name = "folia"
includeBuild("../../BlueMapCommon")

View File

@ -0,0 +1,105 @@
/*
* This file is part of BlueMap, licensed under the MIT License (MIT).
*
* Copyright (c) Blue (Lukas Rieger) <https://bluecolored.de>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.bluecolored.bluemap.bukkit;
import com.flowpowered.math.vector.Vector3d;
import de.bluecolored.bluemap.common.plugin.Plugin;
import de.bluecolored.bluemap.common.plugin.text.Text;
import de.bluecolored.bluemap.common.serverinterface.CommandSource;
import de.bluecolored.bluemap.core.world.World;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import org.bukkit.Location;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import java.io.IOException;
import java.util.Optional;
public class BukkitCommandSource implements CommandSource {
private final Plugin plugin;
private final CommandSender delegate;
public BukkitCommandSource(Plugin plugin, CommandSender delegate) {
this.plugin = plugin;
this.delegate = delegate;
}
@Override
public void sendMessage(Text text) {
if (delegate instanceof Player player) {
player.sendMessage(GsonComponentSerializer.gson().deserialize(text.toJSONString()));
return;
}
delegate.sendMessage(text.toPlainString());
}
@Override
public boolean hasPermission(String permission) {
return delegate.hasPermission(permission);
}
@Override
public Optional<Vector3d> getPosition() {
Location location = getLocation();
if (location != null) {
return Optional.of(new Vector3d(location.getX(), location.getY(), location.getZ()));
}
return Optional.empty();
}
@Override
public Optional<World> getWorld() {
Location location = getLocation();
if (location != null) {
try {
var serverWorld = BukkitPlugin.getInstance().getWorld(location.getWorld());
String worldId = plugin.getBlueMap().getWorldId(serverWorld.getSaveFolder());
return Optional.ofNullable(plugin.getWorlds().get(worldId));
} catch (IOException ignore) {}
}
return Optional.empty();
}
private Location getLocation() {
Location location = null;
if (delegate instanceof Entity) {
location = ((Entity) delegate).getLocation();
}
if (delegate instanceof BlockCommandSender) {
location = ((BlockCommandSender) delegate).getBlock().getLocation();
}
return location;
}
}

View File

@ -0,0 +1,141 @@
/*
* This file is part of BlueMap, licensed under the MIT License (MIT).
*
* Copyright (c) Blue (Lukas Rieger) <https://bluecolored.de>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.bluecolored.bluemap.bukkit;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.Suggestion;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.tree.CommandNode;
import de.bluecolored.bluemap.common.plugin.Plugin;
import de.bluecolored.bluemap.common.plugin.commands.Commands;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.RemoteConsoleCommandSender;
import org.bukkit.command.defaults.BukkitCommand;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.TabCompleteEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class BukkitCommands implements Listener {
private final CommandDispatcher<CommandSender> dispatcher;
public BukkitCommands(final Plugin plugin) {
this.dispatcher = new CommandDispatcher<>();
// register commands
new Commands<>(plugin, dispatcher, bukkitSender -> {
// RCON doesn't work async, use console instead
if (bukkitSender instanceof RemoteConsoleCommandSender)
return new BukkitCommandSource(plugin, Bukkit.getConsoleSender());
return new BukkitCommandSource(plugin, bukkitSender);
});
}
public Collection<BukkitCommand> getRootCommands(){
Collection<BukkitCommand> rootCommands = new ArrayList<>();
for (CommandNode<CommandSender> node : this.dispatcher.getRoot().getChildren()) {
rootCommands.add(new CommandProxy(node.getName()));
}
return rootCommands;
}
@EventHandler
public void onTabComplete(TabCompleteEvent evt) {
try {
String input = evt.getBuffer();
if (input.length() > 0 && input.charAt(0) == '/') {
input = input.substring(1);
}
Suggestions suggestions = dispatcher.getCompletionSuggestions(dispatcher.parse(input, evt.getSender())).get(100, TimeUnit.MILLISECONDS);
List<String> completions = new ArrayList<>();
for (Suggestion suggestion : suggestions.getList()) {
String text = suggestion.getText();
if (text.indexOf(' ') == -1) {
completions.add(text);
}
}
if (!completions.isEmpty()) {
completions.sort(String::compareToIgnoreCase);
try {
evt.getCompletions().addAll(completions);
} catch (UnsupportedOperationException ex){
// fix for a bug with paper where the completion-Collection is not mutable for some reason
List<String> mutableCompletions = new ArrayList<>(evt.getCompletions());
mutableCompletions.addAll(completions);
evt.setCompletions(mutableCompletions);
}
}
} catch (InterruptedException ignore) {
Thread.currentThread().interrupt();
} catch (ExecutionException | TimeoutException ignore) {}
}
private class CommandProxy extends BukkitCommand {
protected CommandProxy(String name) {
super(name);
}
@Override
public boolean execute(CommandSender sender, String commandLabel, String[] args) {
String command = commandLabel;
if (args.length > 0) {
command += " " + StringUtils.join(args, ' ');
}
try {
return dispatcher.execute(command, sender) > 0;
} catch (CommandSyntaxException ex) {
sender.sendMessage(ChatColor.RED + ex.getRawMessage().getString());
String context = ex.getContext();
if (context != null) sender.sendMessage(ChatColor.GRAY + context);
return false;
}
}
}
}

View File

@ -0,0 +1,171 @@
/*
* This file is part of BlueMap, licensed under the MIT License (MIT).
*
* Copyright (c) Blue (Lukas Rieger) <https://bluecolored.de>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.bluecolored.bluemap.bukkit;
import com.flowpowered.math.vector.Vector3d;
import de.bluecolored.bluemap.common.serverinterface.Gamemode;
import de.bluecolored.bluemap.common.serverinterface.Player;
import de.bluecolored.bluemap.common.plugin.text.Text;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.potion.PotionEffectType;
import java.io.IOException;
import java.util.EnumMap;
import java.util.Map;
import java.util.UUID;
public class BukkitPlayer implements Player {
private static final Map<GameMode, Gamemode> GAMEMODE_MAP = new EnumMap<>(GameMode.class);
static {
GAMEMODE_MAP.put(GameMode.ADVENTURE, Gamemode.ADVENTURE);
GAMEMODE_MAP.put(GameMode.SURVIVAL, Gamemode.SURVIVAL);
GAMEMODE_MAP.put(GameMode.CREATIVE, Gamemode.CREATIVE);
GAMEMODE_MAP.put(GameMode.SPECTATOR, Gamemode.SPECTATOR);
}
private final UUID uuid;
private Text name;
private String world;
private Vector3d position;
private Vector3d rotation;
private int skyLight;
private int blockLight;
private boolean online;
private boolean sneaking;
private boolean invisible;
private boolean vanished;
private Gamemode gamemode;
public BukkitPlayer(UUID playerUUID) {
this.uuid = playerUUID;
update();
}
@Override
public UUID getUuid() {
return this.uuid;
}
@Override
public Text getName() {
return this.name;
}
@Override
public String getWorld() {
return this.world;
}
@Override
public Vector3d getPosition() {
return this.position;
}
@Override
public Vector3d getRotation() {
return rotation;
}
@Override
public int getSkyLight() {
return skyLight;
}
@Override
public int getBlockLight() {
return blockLight;
}
@Override
public boolean isOnline() {
return this.online;
}
@Override
public boolean isSneaking() {
return this.sneaking;
}
@Override
public boolean isInvisible() {
return this.invisible;
}
@Override
public boolean isVanished() {
return vanished;
}
@Override
public Gamemode getGamemode() {
return this.gamemode;
}
/**
* API access, only call on server thread!
*/
public void update() {
org.bukkit.entity.Player player = Bukkit.getPlayer(uuid);
if (player == null) {
this.online = false;
return;
}
this.gamemode = GAMEMODE_MAP.get(player.getGameMode());
if (this.gamemode == null) this.gamemode = Gamemode.SURVIVAL;
this.invisible = player.hasPotionEffect(PotionEffectType.INVISIBILITY);
//also check for "vanished" players
boolean vanished = false;
for (MetadataValue meta : player.getMetadata("vanished")) {
if (meta.asBoolean()) vanished = true;
}
this.vanished = vanished;
this.name = Text.of(player.getName());
this.online = player.isOnline();
Location location = player.getLocation();
this.position = new Vector3d(location.getX(), location.getY(), location.getZ());
this.rotation = new Vector3d(location.getPitch(), location.getYaw(), 0);
this.sneaking = player.isSneaking();
this.skyLight = player.getLocation().getBlock().getLightFromSky();
this.blockLight = player.getLocation().getBlock().getLightFromBlocks();
try {
var world = BukkitPlugin.getInstance().getWorld(player.getWorld());
this.world = BukkitPlugin.getInstance().getPlugin().getBlueMap().getWorldId(world.getSaveFolder());
} catch (IOException | NullPointerException e) { // NullPointerException -> the plugin isn't fully loaded
this.world = "unknown";
}
}
}

View File

@ -0,0 +1,279 @@
/*
* This file is part of BlueMap, licensed under the MIT License (MIT).
*
* Copyright (c) Blue (Lukas Rieger) <https://bluecolored.de>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.bluecolored.bluemap.bukkit;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import de.bluecolored.bluemap.common.plugin.Plugin;
import de.bluecolored.bluemap.common.serverinterface.Player;
import de.bluecolored.bluemap.common.serverinterface.ServerEventListener;
import de.bluecolored.bluemap.common.serverinterface.ServerInterface;
import de.bluecolored.bluemap.common.serverinterface.ServerWorld;
import de.bluecolored.bluemap.core.BlueMap;
import de.bluecolored.bluemap.core.MinecraftVersion;
import de.bluecolored.bluemap.core.logger.Logger;
import de.bluecolored.bluemap.core.util.Key;
import io.papermc.paper.threadedregions.scheduler.ScheduledTask;
import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.CommandMap;
import org.bukkit.command.defaults.BukkitCommand;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BukkitPlugin extends JavaPlugin implements ServerInterface, Listener {
private static BukkitPlugin instance;
private final Plugin pluginInstance;
private final EventForwarder eventForwarder;
private final BukkitCommands commands;
private final MinecraftVersion minecraftVersion;
private final Map<UUID, Player> onlinePlayerMap;
private final List<BukkitPlayer> onlinePlayerList;
private final Collection<WeakReference<ScheduledTask>> scheduledTasks;
private final LoadingCache<World, ServerWorld> worlds;
public BukkitPlugin() {
Logger.global = new JavaLogger(getLogger());
//try to get best matching minecraft-version
MinecraftVersion version = MinecraftVersion.LATEST_SUPPORTED;
try {
String versionString = getServer().getBukkitVersion();
Matcher versionMatcher = Pattern.compile("(\\d+(?:\\.\\d+){1,2})[-_].*").matcher(versionString);
if (!versionMatcher.matches()) throw new IllegalArgumentException();
version = MinecraftVersion.of(versionMatcher.group(1));
} catch (IllegalArgumentException e) {
Logger.global.logWarning("Failed to detect the minecraft version of this server! Using latest version: " + version.getVersionString());
}
this.minecraftVersion = version;
this.onlinePlayerMap = new ConcurrentHashMap<>();
this.onlinePlayerList = Collections.synchronizedList(new ArrayList<>());
this.scheduledTasks = new ArrayList<>();
this.eventForwarder = new EventForwarder();
this.pluginInstance = new Plugin("bukkit", this);
this.commands = new BukkitCommands(this.pluginInstance);
this.worlds = Caffeine.newBuilder()
.executor(BlueMap.THREAD_POOL)
.weakKeys()
.maximumSize(1000)
.build(BukkitWorld::new);
BukkitPlugin.instance = this;
}
@Override
public void onEnable() {
//register events
getServer().getPluginManager().registerEvents(this, this);
getServer().getPluginManager().registerEvents(eventForwarder, this);
//register commands
try {
final Field bukkitCommandMap = Bukkit.getServer().getClass().getDeclaredField("commandMap");
bukkitCommandMap.setAccessible(true);
CommandMap commandMap = (CommandMap) bukkitCommandMap.get(Bukkit.getServer());
for (BukkitCommand command : commands.getRootCommands()) {
commandMap.register(command.getLabel(), command);
}
} catch(NoSuchFieldException | SecurityException | IllegalAccessException e) {
Logger.global.logError("Failed to register commands!", e);
}
//tab completions
getServer().getPluginManager().registerEvents(commands, this);
//update online-player collections
this.onlinePlayerList.clear();
this.onlinePlayerMap.clear();
for (org.bukkit.entity.Player player : getServer().getOnlinePlayers()) {
initPlayer(player);
}
//load bluemap
new Thread(() -> {
try {
Logger.global.logInfo("Loading...");
this.pluginInstance.load();
if (pluginInstance.isLoaded()) Logger.global.logInfo("Loaded!");
} catch (IOException | RuntimeException e) {
Logger.global.logError("Failed to load!", e);
this.pluginInstance.unload();
}
}, "BlueMap-Load").start();
//bstats
new Metrics(this, 5912);
}
@Override
public void onDisable() {
Logger.global.logInfo("Stopping...");
scheduledTasks.forEach(taskRef -> {
ScheduledTask task = taskRef.get();
if (task != null) task.cancel();
});
scheduledTasks.clear();
pluginInstance.unload();
Logger.global.logInfo("Saved and stopped!");
}
@Override
public MinecraftVersion getMinecraftVersion() {
return minecraftVersion;
}
@Override
public void registerListener(ServerEventListener listener) {
eventForwarder.addListener(listener);
}
@Override
public void unregisterAllListeners() {
eventForwarder.removeAllListeners();
}
@Override
public Collection<ServerWorld> getLoadedWorlds() {
Collection<ServerWorld> loadedWorlds = new ArrayList<>(3);
for (World world : Bukkit.getWorlds()) {
loadedWorlds.add(worlds.get(world));
}
return loadedWorlds;
}
@Override
public Optional<ServerWorld> getWorld(Object world) {
if (world instanceof Path)
return getWorld((Path) world);
if (world instanceof String) {
var serverWorld = Bukkit.getWorld((String) world);
if (serverWorld != null) world = serverWorld;
}
if (world instanceof String) {
var serverWorld = Bukkit.getWorld(new Key((String) world).getValue());
if (serverWorld != null) world = serverWorld;
}
if (world instanceof UUID) {
var serverWorld = Bukkit.getWorld((UUID) world);
if (serverWorld != null) world = serverWorld;
}
if (world instanceof World)
return Optional.of(getWorld((World) world));
return Optional.empty();
}
public ServerWorld getWorld(World world) {
return worlds.get(world);
}
@Override
public Path getConfigFolder() {
return getDataFolder().toPath();
}
@Override
public Optional<Path> getModsFolder() {
return Optional.of(Path.of("mods")); // in case this is a Bukkit/Forge hybrid
}
public Plugin getPlugin() {
return pluginInstance;
}
public static BukkitPlugin getInstance() {
return instance;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerJoin(PlayerJoinEvent evt) {
initPlayer(evt.getPlayer());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerLeave(PlayerQuitEvent evt) {
UUID playerUUID = evt.getPlayer().getUniqueId();
onlinePlayerMap.remove(playerUUID);
synchronized (onlinePlayerList) {
onlinePlayerList.removeIf(p -> p.getUuid().equals(playerUUID));
}
// tidy up task-references
scheduledTasks.removeIf(ref -> ref.get() == null);
}
@Override
public Collection<Player> getOnlinePlayers() {
return onlinePlayerMap.values();
}
@Override
public Optional<Player> getPlayer(UUID uuid) {
return Optional.ofNullable(onlinePlayerMap.get(uuid));
}
private void initPlayer(org.bukkit.entity.Player bukkitPlayer) {
BukkitPlayer player = new BukkitPlayer(bukkitPlayer.getUniqueId());
onlinePlayerMap.put(bukkitPlayer.getUniqueId(), player);
onlinePlayerList.add(player);
// update player every 20 seconds
bukkitPlayer.getScheduler().runAtFixedRate(this, task -> {
player.update();
scheduledTasks.add(new WeakReference<>(task));
}, () -> {}, 20, 20);
}
}

View File

@ -0,0 +1,97 @@
/*
* This file is part of BlueMap, licensed under the MIT License (MIT).
*
* Copyright (c) Blue (Lukas Rieger) <https://bluecolored.de>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.bluecolored.bluemap.bukkit;
import de.bluecolored.bluemap.common.serverinterface.Dimension;
import de.bluecolored.bluemap.common.serverinterface.ServerWorld;
import org.bukkit.World;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
public class BukkitWorld implements ServerWorld {
private final WeakReference<World> delegate;
private final Path saveFolder;
public BukkitWorld(World delegate) {
this.delegate = new WeakReference<>(delegate);
Dimension dimension = getDimension();
Path saveFolder = delegate.getWorldFolder().toPath()
.resolve(dimension.getDimensionSubPath())
.toAbsolutePath().normalize();
// fix for hybrids
if (!Files.exists(saveFolder)) {
Path direct = delegate.getWorldFolder().toPath();
if (Files.exists(direct) && direct.endsWith(dimension.getDimensionSubPath()))
saveFolder = direct;
}
this.saveFolder = saveFolder;
}
@Override
public Dimension getDimension() {
World world = delegate.get();
if (world != null) {
if (world.getEnvironment().equals(World.Environment.NETHER)) return Dimension.NETHER;
if (world.getEnvironment().equals(World.Environment.THE_END)) return Dimension.END;
}
return Dimension.OVERWORLD;
}
@Override
public Optional<String> getId() {
World world = delegate.get();
if (world != null) {
return Optional.of(world.getUID().toString());
}
return Optional.empty();
}
@Override
public Optional<String> getName() {
World world = delegate.get();
if (world != null) {
return Optional.of(world.getName());
}
return Optional.empty();
}
@Override
public boolean persistWorldChanges() throws IOException {
return false;
}
@Override
public Path getSaveFolder() {
return this.saveFolder;
}
}

View File

@ -0,0 +1,71 @@
/*
* This file is part of BlueMap, licensed under the MIT License (MIT).
*
* Copyright (c) Blue (Lukas Rieger) <https://bluecolored.de>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.bluecolored.bluemap.bukkit;
import de.bluecolored.bluemap.common.serverinterface.ServerEventListener;
import de.bluecolored.bluemap.common.plugin.text.Text;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.util.ArrayList;
import java.util.Collection;
public class EventForwarder implements Listener {
private final Collection<ServerEventListener> listeners;
public EventForwarder() {
listeners = new ArrayList<>();
}
public synchronized void addListener(ServerEventListener listener) {
listeners.add(listener);
}
public synchronized void removeAllListeners() {
listeners.clear();
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public synchronized void onPlayerJoin(PlayerJoinEvent evt) {
for (ServerEventListener listener : listeners) listener.onPlayerJoin(evt.getPlayer().getUniqueId());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public synchronized void onPlayerLeave(PlayerQuitEvent evt) {
for (ServerEventListener listener : listeners) listener.onPlayerJoin(evt.getPlayer().getUniqueId());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public synchronized void onPlayerChat(AsyncPlayerChatEvent evt) {
String message = String.format(evt.getFormat(), evt.getPlayer().getDisplayName(), evt.getMessage());
for (ServerEventListener listener : listeners) listener.onChatMessage(Text.of(message));
}
}

View File

@ -0,0 +1,70 @@
/*
* This file is part of BlueMap, licensed under the MIT License (MIT).
*
* Copyright (c) Blue (Lukas Rieger) <https://bluecolored.de>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.bluecolored.bluemap.bukkit;
import java.util.logging.Level;
import java.util.logging.Logger;
import de.bluecolored.bluemap.core.logger.AbstractLogger;
public class JavaLogger extends AbstractLogger {
private Logger out;
public JavaLogger(Logger out) {
this.out = out;
}
@Override
public void logError(String message, Throwable throwable) {
out.log(Level.SEVERE, message, throwable);
}
@Override
public void logWarning(String message) {
out.log(Level.WARNING, message);
}
@Override
public void logInfo(String message) {
out.log(Level.INFO, message);
}
@Override
public void logDebug(String message) {
if (out.isLoggable(Level.FINE)) out.log(Level.FINE, message);
}
@Override
public void noFloodDebug(String message) {
if (out.isLoggable(Level.FINE)) super.noFloodDebug(message);
}
@Override
public void noFloodDebug(String key, String message) {
if (out.isLoggable(Level.FINE)) super.noFloodDebug(key, message);
}
}

View File

@ -0,0 +1,47 @@
name: BlueMap
description: "A 3d-map of your Minecraft worlds view-able in your browser using three.js (WebGL)"
main: de.bluecolored.bluemap.bukkit.BukkitPlugin
version: "${version}"
api-version: 1.19
folia-supported: true
author: "Blue (TBlueF / Lukas Rieger)"
website: "https://github.com/BlueMap-Minecraft"
commands:
permissions:
bluemap.*:
children:
bluemap.status: true
bluemap.version: true
bluemap.help: true
bluemap.reload: true
bluemap.stop: true
bluemap.start: true
bluemap.freeze: true
bluemap.purge: true
bluemap.marker: true
bluemap.update: true
bluemap.debug: true
default: op
bluemap.status:
default: op
bluemap.version:
default: op
bluemap.help:
default: op
bluemap.reload:
default: op
bluemap.stop:
default: op
bluemap.start:
default: op
bluemap.freeze:
default: op
bluemap.purge:
default: op
bluemap.marker:
default: op
bluemap.update:
default: op
bluemap.debug:
default: op

View File

@ -1,23 +1,24 @@
rootProject.name = "BlueMap"
includeBuild("implementations/cli")
//includeBuild("implementations/cli")
includeBuild("implementations/fabric-1.15.2")
includeBuild("implementations/fabric-1.16.2")
includeBuild("implementations/fabric-1.17")
includeBuild("implementations/fabric-1.18")
includeBuild("implementations/fabric-1.19")
includeBuild("implementations/fabric-1.19.3")
includeBuild("implementations/fabric-1.19.4")
//includeBuild("implementations/fabric-1.15.2")
//includeBuild("implementations/fabric-1.16.2")
//includeBuild("implementations/fabric-1.17")
//includeBuild("implementations/fabric-1.18")
//includeBuild("implementations/fabric-1.19")
//includeBuild("implementations/fabric-1.19.3")
//includeBuild("implementations/fabric-1.19.4")
includeBuild("implementations/forge-1.16.5")
includeBuild("implementations/forge-1.17.1")
includeBuild("implementations/forge-1.18.1")
includeBuild("implementations/forge-1.19.1")
includeBuild("implementations/forge-1.19.3")
includeBuild("implementations/forge-1.19.4")
//includeBuild("implementations/forge-1.16.5")
//includeBuild("implementations/forge-1.17.1")
//includeBuild("implementations/forge-1.18.1")
//includeBuild("implementations/forge-1.19.1")
//includeBuild("implementations/forge-1.19.3")
//includeBuild("implementations/forge-1.19.4")
includeBuild("implementations/spigot")
//includeBuild("implementations/spigot")
includeBuild("implementations/folia")
includeBuild("implementations/sponge-8.0.0")
includeBuild("implementations/sponge-9.0.0")
//includeBuild("implementations/sponge-8.0.0")
//includeBuild("implementations/sponge-9.0.0")