diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md deleted file mode 100644 index cbd9470d3ad..00000000000 --- a/.github/CONTRIBUTING.md +++ /dev/null @@ -1,107 +0,0 @@ -How to submit a bug report ---- - -Before creating an issue, make sure: - 1. Your title and content is not confusing or content-less. - 2. All text is written in proper English. - -If it's a bug or problem: - 1. This bug can be reproduced. - 2. This bug can be found in the latest build. - 3. Dumps, backtraces or files are provided. - 4. It's you yourself who first found this bug. - -If it's advice or a feature request: - 1. This feature does not exist in the latest build. - 2. This feature is logical and clear-cut. - 3. It's you yourself who first came up with the idea. - -Nukkit will create a bug report for EVERY exception and error detected, and there are some columns you need to fill out in the report. If multiple exceptions are triggered, you should combine the stacktrace into one report and then submit the report. - -In the report, you can see if the error is caused by Nukkit or a plugin. However, when "PLUGIN ERROR" is "false" and there are plugins running, it does not necessarily indicate that the error is caused by Nukkit. - -To submit bugs and problems, please upload the automatically generated report. Make sure you have filled in all blanks in the template. Please provide **as much information as you could**, or our developers might got stuck or confused when looking into your issue. - -To submit feature requests and suggestions, please explicitly describe the feature you want or your suggestion. - -**Note that the Issues section on GitHub is not for contents that are not related to the two categories listed above. Irrelevant issues will be closed. Please visit our forums for other kinds of discussions.** - -Example ---- - -### Issue Description - -It seems that the player you are manipulating does not seem to be moving from other people, and it seems that you are not moving from others. - -I do not know because I have not logged in to anything other than my server, but it works normally with Wi-Fi multi. - -### OS and Versions - -* Nukkit Version: https://github.com/Nukkit/Nukkit/pull/1517 - -* Java Version: -``` -java version "9" -Java(TM) SE Runtime Environment (build 9+175) -Java HotSpot(TM) 64-Bit Server VM (build 9+175, mixed mode) -``` - -* Host Configuration: - - -| Item | Value | -|:----:|:-----:| -| Host OS | Microsoft Windows [10.0.10240] | -| Memory(RAM) | 4 GB | -| Storage Size | 1 TB | -| Storage Type | SSD | -| CPU Type | Intel Xeon X5650 | -| CPU Core Count | 12 cores 24 threads | -| Upstream Bandwidth | 100 Mbps | - -* Client Configuration: - -| Item | Value | -|:----:|:-----:| -| Client Edition | Android | -| Client Version | 1.0.4 | - -``` -### Issue Description - -It seems that the player you are manipulating does not seem to be moving from other people, and it seems that you are not moving from others. - -I do not know because I have not logged in to anything other than my server, but it works normally with Wi-Fi multi. - -### OS and Versions - -* Nukkit Version: https://github.com/Nukkit/Nukkit/pull/1517 - -* Java Version: - -java version "9" -Java(TM) SE Runtime Environment (build 9+175) -Java HotSpot(TM) 64-Bit Server VM (build 9+175, mixed mode) - - -* Host Configuration: - - -| Item | Value | -|:----:|:-----:| -| Host OS | Microsoft Windows [10.0.10240] | -| Memory(RAM) | 4 GB | -| Storage Size | 1 TB | -| Storage Type | SSD | -| CPU Type | Intel Xeon X5650 | -| CPU Core Count | 12 cores 24 threads | -| Upstream Bandwidth | 100 Mbps | - -* Client Configuration: - -| Item | Value | -|:----:|:-----:| -| Client Edition | Android | -| Client Version | 1.0.4 | - -``` diff --git a/.gitignore b/.gitignore index 201025d9bd4..5ff03a35fde 100644 --- a/.gitignore +++ b/.gitignore @@ -246,7 +246,7 @@ rebel-remote.xml # Nukkit generated files banned-ips.json banned-players.json -nukkit.yml +/nukkit.yml ops.txt server.log server.properties @@ -265,6 +265,9 @@ creativeitems.json recipes.json data/ data/* +material_tags.txt +item_types.txt +block_types.txt run/ diff --git a/.gitmodules b/.gitmodules index febb0db9cb2..e69de29bb2d 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +0,0 @@ -[submodule "src/main/resources/lang"] - path = src/main/resources/lang - url = https://github.com/NukkitX/Languages.git diff --git a/README.md b/README.md index a87814192a7..620b263e8c4 100644 --- a/README.md +++ b/README.md @@ -7,29 +7,24 @@ Introduction ------------- -Nukkit is nuclear-powered server software for Minecraft: Pocket Edition. +Nukkit is nuclear-powered server software for Minecraft Bedrock Edition. It has a few key advantages over other server software: * Written in Java, Nukkit is faster and more stable. * Having a friendly structure, it's easy to contribute to Nukkit's development and rewrite plugins from other platforms into Nukkit plugins. -Nukkit is **under improvement** yet, we welcome contributions. +Nukkit is under improvement yet, we welcome contributions. Links -------------------- -* __[News](https://nukkitx.com)__ -* __[Forums](https://nukkitx.com/forums)__ +* __[Forums](https://cloudburstmc.org/forums/)__ * __[Discord](https://discord.gg/5PzMkyK)__ -* __[Download](https://ci.nukkitx.com/job/NukkitX/job/Nukkit/job/master)__ -* __[Plugins](https://nukkitx.com/resources/categories/nukkit-plugins.1)__ -* __[Wiki](https://nukkitx.com/wiki/nukkit)__ +* __[Wiki](https://cloudburstmc.org/wiki/nukkit)__ +* __[Download Nukkit](https://ci.opencollab.dev/job/NukkitX/job/Nukkit/job/master/)__ +* __[Download Plugins](https://cloudburstmc.org/resources/categories/nukkit-plugins.1/)__ -Contributing -------------- -Please read the [CONTRIBUTING](.github/CONTRIBUTING.md) guide before submitting any issue. Issues with insufficient information or in the wrong format will be closed and will not be reviewed. - -Build JAR file +Compile Nukkit ------------- - `git clone https://github.com/CloudburstMC/Nukkit` - `cd Nukkit` @@ -38,6 +33,8 @@ Build JAR file The compiled JAR can be found in the `target/` directory. +Note: You don't need to compile Nukkit yourself if you don't intend to modify the code. You can find precompiled JARs on Jenkins. + Running ------------- Simply run `java -jar nukkit-1.0-SNAPSHOT.jar`. @@ -114,3 +111,8 @@ Testing after deployment: Completely remove the chart: `helm uninstall nukkit` + +Pterodactyl Panel +------------- + +[Download the official egg](https://raw.githubusercontent.com/parkervcp/eggs/master/game_eggs/minecraft/bedrock/nukkit/egg-nukkit.json) diff --git a/build.gradle.kts b/build.gradle.kts index e2b8dda8c2f..7f4ac433fc1 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,4 +1,5 @@ import com.github.jengelman.gradle.plugins.shadow.transformers.Log4j2PluginsCacheFileTransformer +import org.gradle.internal.impldep.org.junit.experimental.categories.Categories.CategoryFilter.exclude @Suppress("DSL_SCOPE_VIOLATION") // https://youtrack.jetbrains.com/issue/IDEA-262280 @@ -12,7 +13,7 @@ plugins { group = "cn.nukkit" version = "1.0-SNAPSHOT" -description = "Nuclear powered server software for Minecraft: Bedrock Edition" +description = "Nuclear powered server software for Minecraft Bedrock Edition" repositories { mavenLocal() @@ -23,16 +24,32 @@ repositories { dependencies { api(libs.network) - api(libs.natives) + api(libs.epoll) api(libs.fastutil) + api(libs.bundles.fastutilmaps) api(libs.guava) api(libs.gson) api(libs.snakeyaml) api(libs.leveldb) + api(libs.leveldbjni) { + exclude(group = "com.google.guava", module = "guava") + exclude(group = "io.netty", module = "netty-buffer") + exclude(group = "org.iq80.snappy", module = "snappy") + exclude(group = "org.iq80.leveldb", module = "leveldb") + } + api(libs.snappy) api(libs.jwt) api(libs.bundles.terminal) api(libs.bundles.log4j) api(libs.jopt.simple) + api(libs.blockstateupdater) + api(libs.lmbda) { + exclude(group = "org.checkerframework", module = "checker-qual") + } + api(libs.noise) { + exclude(group = "net.daporkchop.lib", module = "common") + exclude(group = "net.daporkchop.lib", module = "math") + } compileOnly(libs.lombok) annotationProcessor(libs.lombok) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index bd557a11fc9..69c8c43f68f 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -2,18 +2,28 @@ junit = "5.9.2" log4j = "2.20.0" jline = "3.22.0" +fastutilmaps = "8.5.13-SNAPSHOT" [libraries] -network = { group = "com.nukkitx.network", name = "raknet", version = "1.6.28-SNAPSHOT" } -natives = { group = "com.nukkitx", name = "natives", version = "1.0.3" } +network = { group = "org.cloudburstmc.netty", name = "netty-transport-raknet", version = "1.0.0.CR3-SNAPSHOT" } +epoll = { group = "io.netty", name = "netty-transport-native-epoll", version = "4.1.101.Final" } fastutil = { group = "com.nukkitx", name = "fastutil-lite", version = "8.1.1" } -guava = { group = "com.google.guava", name = "guava", version = "30.1.1-jre" } +fastutil-long-long-maps = { group = "org.cloudburstmc.fastutil.maps", name = "long-long-maps", version.ref = "fastutilmaps" } +fastutil-int-short-maps = { group = "org.cloudburstmc.fastutil.maps", name = "int-short-maps", version.ref = "fastutilmaps" } +fastutil-object-int-maps = { group = "org.cloudburstmc.fastutil.maps", name = "object-int-maps", version.ref = "fastutilmaps" } +fastutil-object-object-maps = { group = "org.cloudburstmc.fastutil.maps", name = "object-object-maps", version.ref = "fastutilmaps" } +guava = { group = "com.google.guava", name = "guava", version = "33.2.1-jre" } gson = { group = "com.google.code.gson", name = "gson", version = "2.10.1" } snakeyaml = { group = "org.yaml", name = "snakeyaml", version = "1.33" } -leveldb = { group = "org.iq80.leveldb", name = "leveldb", version = "0.11-SNAPSHOT" } -jwt = { group = "com.nimbusds", name = "nimbus-jose-jwt", version = "9.13" } +leveldb = { group = "org.iq80.leveldb", name = "leveldb", version = "0.11.1-SNAPSHOT" } +leveldbjni = { group = "net.daporkchop", name = "leveldb-mcpe-jni", version = "0.0.10-SNAPSHOT" } +snappy = { group = "org.xerial.snappy", name = "snappy-java", version = "1.1.10.7" } +jwt = { group = "com.nimbusds", name = "nimbus-jose-jwt", version = "9.23" } jopt-simple = { group = "net.sf.jopt-simple", name = "jopt-simple", version = "5.0.4" } -lombok = { group = "org.projectlombok", name = "lombok", version = "1.18.26" } +blockstateupdater = { group = "org.cloudburstmc", name = "block-state-updater", version = "1.21.30-SNAPSHOT" } +lmbda = { group = "org.lanternpowered", name = "lmbda", version = "2.0.0" } +noise = { group = "net.daporkchop.lib", name = "noise", version = "0.5.6-SNAPSHOT" } +lombok = { group = "org.projectlombok", name = "lombok", version = "1.18.34" } # Logging dependencies log4j-api = { group = "org.apache.logging.log4j", name = "log4j-api", version.ref = "log4j" } @@ -33,6 +43,7 @@ junit-jupiter-engine = { group = "org.junit.jupiter", name = "junit-jupiter-engi log4j = [ "log4j-api", "log4j-core" ] terminal = [ "jline-terminal", "jline-terminal-jna", "jline-reader", "terminal-console" ] junit = [ "junit-jupiter-api", "junit-jupiter-engine" ] +fastutilmaps = [ "fastutil-long-long-maps", "fastutil-int-short-maps", "fastutil-object-int-maps", "fastutil-object-object-maps" ] [plugins] shadow = { id = "com.github.johnrengelman.shadow", version = "8.0.0" } diff --git a/nukkit.yml.default b/nukkit.yml.default index 3d4d2aae20f..1d1e15fcf88 100644 --- a/nukkit.yml.default +++ b/nukkit.yml.default @@ -1,4 +1,2 @@ settings: - # Multi-language setting - # Available: eng, chs, cht, jpn, rus, spa, pol, bra, kor, ukr, deu language: "eng" diff --git a/src/main/java/cn/nukkit/Achievement.java b/src/main/java/cn/nukkit/Achievement.java index 2adcd738f0e..cb59c31130f 100644 --- a/src/main/java/cn/nukkit/Achievement.java +++ b/src/main/java/cn/nukkit/Achievement.java @@ -5,13 +5,21 @@ import java.util.HashMap; /** - * Created by CreeperFace on 9. 11. 2016. + * Achievement list and functions + * + * @author CreeperFace */ public class Achievement { + /** + * All known achievements. + *

+ * Based on ... + */ public static final HashMap achievements = new HashMap() { { - put("mineWood", new Achievement("Getting Wood")); + put("openInventory", new Achievement("Taking Inventory")); + put("mineWood", new Achievement("Getting Wood", "openInventory")); put("buildWorkBench", new Achievement("Benchmarking", "mineWood")); put("buildPickaxe", new Achievement("Time to Mine!", "buildWorkBench")); put("buildFurnace", new Achievement("Hot Topic", "buildPickaxe")); @@ -20,18 +28,44 @@ public class Achievement { put("makeBread", new Achievement("Bake Bread", "buildHoe")); put("bakeCake", new Achievement("The Lie", "buildHoe")); put("buildBetterPickaxe", new Achievement("Getting an Upgrade", "buildPickaxe")); + put("cookFish", new Achievement("Delicious Fish", "buildFurnace")); + put("onARail", new Achievement("On A Rail", "acquireIron")); put("buildSword", new Achievement("Time to Strike!", "buildWorkBench")); + put("killEnemy", new Achievement("Monster Hunter", "buildSword")); + put("killCow", new Achievement("Cow Tipper", "buildSword")); + put("flyPig", new Achievement("When Pigs Fly", "killCow")); + put("snipeSkeleton", new Achievement("Sniper Duel", "killEnemy")); put("diamonds", new Achievement("DIAMONDS!", "acquireIron")); + put("portal", new Achievement("We Need to Go Deeper", "diamonds")); + put("ghast", new Achievement("Return to Sender", "portal")); + put("blazeRod", new Achievement("Into Fire", "portal")); + put("potion", new Achievement("Local Brewery", "blazeRod")); + put("theEnd", new Achievement("The End?", "blazeRod")); + put("theEnd2", new Achievement("The End.", "theEnd")); + put("enchantments", new Achievement("Enchanter", "diamonds")); + put("overkill", new Achievement("Overkill", "enchantments")); + put("bookcase", new Achievement("Librarian", "enchantments")); + put("exploreAllBiomes", new Achievement("Adventuring Time", "theEnd")); //TODO + put("spawnWither", new Achievement("The Beginning?", "theEnd")); + put("killWither", new Achievement("The Beginning.", "spawnWither")); + put("fullBeacon", new Achievement("Beaconator", "killWither")); + put("breedCow", new Achievement("Repopulation", "killCow")); + put("diamondsToYou", new Achievement("Diamonds to you!", "diamonds")); + put("overpowered", new Achievement("Overpowered", "buildBetterPickaxe")); } }; + /** + * Broadcasts achievement get message if player does not have the achievement yet. Returns true if broadcast. + */ public static boolean broadcast(Player player, String achievementId) { if (!achievements.containsKey(achievementId)) { return false; } - String translation = Server.getInstance().getLanguage().translateString("chat.type.achievement", player.getDisplayName(), TextFormat.GREEN + achievements.get(achievementId).getMessage() + TextFormat.RESET); - if (Server.getInstance().getPropertyBoolean("announce-player-achievements", true)) { + String translation = TextFormat.WHITE + Server.getInstance().getLanguage().translateString("chat.type.achievement", player.getDisplayName(), TextFormat.GREEN + "[" + achievements.get(achievementId).message + "]", null); + + if (Server.getInstance().announceAchievements) { Server.getInstance().broadcastMessage(translation); } else { player.sendMessage(translation); @@ -39,6 +73,12 @@ public static boolean broadcast(Player player, String achievementId) { return true; } + /** + * Register an achievement + * @param name save id + * @param achievement achievement + * @return true if successful, false if save id is already in use + */ public static boolean add(String name, Achievement achievement) { if (achievements.containsKey(name)) { return false; @@ -51,6 +91,10 @@ public static boolean add(String name, Achievement achievement) { public final String message; public final String[] requires; + /** + * @param message achievement name displayed in achievement get message + * @param requires save IDs of achievements player must complete before this achievement can be completed + */ public Achievement(String message, String... requires) { this.message = message; this.requires = requires; @@ -60,13 +104,16 @@ public String getMessage() { return message; } + /** + * Broadcasts achievement get message + */ public void broadcast(Player player) { - String translation = Server.getInstance().getLanguage().translateString("chat.type.achievement", player.getDisplayName(), TextFormat.GREEN + this.getMessage(), null); + String translation = TextFormat.WHITE + Server.getInstance().getLanguage().translateString("chat.type.achievement", player.getDisplayName(), TextFormat.GREEN + "[" + this.message + "]", null); - if (Server.getInstance().getPropertyBoolean("announce-player-achievements", true)) { + if (Server.getInstance().announceAchievements) { Server.getInstance().broadcastMessage(translation); } else { player.sendMessage(translation); } } -} \ No newline at end of file +} diff --git a/src/main/java/cn/nukkit/AdventureSettings.java b/src/main/java/cn/nukkit/AdventureSettings.java index a862ca762da..c5b2f0de7e2 100644 --- a/src/main/java/cn/nukkit/AdventureSettings.java +++ b/src/main/java/cn/nukkit/AdventureSettings.java @@ -9,8 +9,10 @@ import java.util.Map; /** + * Adventure settings + * + * @author MagicDroidX * Nukkit Project - * Author: MagicDroidX */ public class AdventureSettings implements Cloneable { @@ -20,7 +22,7 @@ public class AdventureSettings implements Cloneable { public static final int PERMISSION_AUTOMATION = 3; public static final int PERMISSION_ADMIN = 4; - private Map values = new EnumMap<>(Type.class); + private final Map values = new EnumMap<>(Type.class); private Player player; @@ -38,11 +40,24 @@ public AdventureSettings clone(Player newPlayer) { } } + /** + * Set an adventure setting value + * + * @param type adventure setting + * @param value new value + * @return AdventureSettings + */ public AdventureSettings set(Type type, boolean value) { this.values.put(type, value); return this; } + /** + * Get an adventure setting value + * + * @param type adventure setting + * @return value + */ public boolean get(Type type) { Boolean value = this.values.get(type); return value == null ? type.getDefaultValue() : value; @@ -63,7 +78,7 @@ void update(boolean reset) { UpdateAbilitiesPacket packet = new UpdateAbilitiesPacket(); packet.setEntityId(player.getId()); packet.setCommandPermission(player.isOp() ? UpdateAbilitiesPacket.CommandPermission.OPERATOR : UpdateAbilitiesPacket.CommandPermission.NORMAL); - packet.setPlayerPermission(player.isOp() && !player.isSpectator() ? UpdateAbilitiesPacket.PlayerPermission.OPERATOR : UpdateAbilitiesPacket.PlayerPermission.MEMBER); + packet.setPlayerPermission(player.isOp() && !player.isSpectator() ? UpdateAbilitiesPacket.PlayerPermission.OPERATOR : UpdateAbilitiesPacket.PlayerPermission.MEMBER); // Spectator: fix operators being able to break blocks on spectator mode AbilityLayer layer = new AbilityLayer(); layer.setLayerType(AbilityLayer.Type.BASE); @@ -91,17 +106,25 @@ void update(boolean reset) { layer.setFlySpeed(Player.DEFAULT_FLY_SPEED); packet.getAbilityLayers().add(layer); - if (this.get(Type.NO_CLIP)) { - AbilityLayer layer2 = new AbilityLayer(); - layer2.setLayerType(AbilityLayer.Type.SPECTATOR); + if (player.isSpectator()) { + AbilityLayer spectator = new AbilityLayer(); + spectator.setLayerType(AbilityLayer.Type.SPECTATOR); + + spectator.getAbilitiesSet().addAll(PlayerAbility.VALUES); + spectator.getAbilitiesSet().remove(PlayerAbility.FLY_SPEED); + spectator.getAbilitiesSet().remove(PlayerAbility.WALK_SPEED); + + for (Type type : Type.values()) { + if (type.isAbility() && this.get(type)) { + spectator.getAbilityValues().add(type.getAbility()); + } + } - layer2.getAbilitiesSet().addAll(PlayerAbility.VALUES); - layer2.getAbilitiesSet().remove(PlayerAbility.FLY_SPEED); - layer2.getAbilitiesSet().remove(PlayerAbility.WALK_SPEED); + if (player.isOp()) { + layer.getAbilityValues().add(PlayerAbility.OPERATOR_COMMANDS); + } - layer2.getAbilityValues().add(PlayerAbility.FLYING); - layer2.getAbilityValues().add(PlayerAbility.NO_CLIP); - packet.getAbilityLayers().add(layer2); + packet.getAbilityLayers().add(spectator); } UpdateAdventureSettingsPacket adventurePacket = new UpdateAdventureSettingsPacket(); @@ -113,17 +136,21 @@ void update(boolean reset) { player.dataPacket(packet); player.dataPacket(adventurePacket); + if (reset) { player.resetInAirTicks(); } } + /** + * List of adventure settings + */ public enum Type { - WORLD_IMMUTABLE(false), - NO_PVM(false), + WORLD_IMMUTABLE(null, false), + NO_PVM(null, false), NO_MVP(PlayerAbility.INVULNERABLE, false), - SHOW_NAME_TAGS(false), - AUTO_JUMP(true), + SHOW_NAME_TAGS(null, false), + AUTO_JUMP(null, true), ALLOW_FLIGHT(PlayerAbility.MAY_FLY, false), NO_CLIP(PlayerAbility.NO_CLIP, false), WORLD_BUILDER(PlayerAbility.WORLD_BUILDER, false), @@ -145,24 +172,34 @@ public enum Type { private final PlayerAbility ability; private final boolean defaultValue; - Type(boolean defaultValue) { - this.defaultValue = defaultValue; - this.ability = null; - } - Type(PlayerAbility ability, boolean defaultValue) { this.ability = ability; this.defaultValue = defaultValue; } + /** + * Get default value + * + * @return default value + */ public boolean getDefaultValue() { return this.defaultValue; } + /** + * Get player ability type + * + * @return player ability type + */ public PlayerAbility getAbility() { return this.ability; } + /** + * Check whether adventure setting is a valid player ability + * + * @return is a valid player ability + */ public boolean isAbility() { return this.ability != null; } diff --git a/src/main/java/cn/nukkit/IPlayer.java b/src/main/java/cn/nukkit/IPlayer.java index d940e26ab74..caa23ba4126 100644 --- a/src/main/java/cn/nukkit/IPlayer.java +++ b/src/main/java/cn/nukkit/IPlayer.java @@ -6,77 +6,63 @@ import java.util.UUID; /** - * 用来描述一个玩家和获得这个玩家相应信息的接口。
* An interface to describe a player and get its information. - * - *

这个玩家可以在线,也可以是不在线。
- * This player can be online or offline.

+ *

+ * This player can be online or offline. * * @author MagicDroidX(code) @ Nukkit Project * @author 粉鞋大妈(javadoc) @ Nukkit Project * @see cn.nukkit.Player * @see cn.nukkit.OfflinePlayer - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public interface IPlayer extends ServerOperator, Metadatable { /** - * 返回这个玩家是否在线。
* Returns if this player is online. * * @return 这个玩家是否在线。
If this player is online. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ boolean isOnline(); /** - * 返回这个玩家的名称。
* Returns the name of this player. - * - *

如果是在线的玩家,这个函数只会返回登录名字。如果要返回显示的名字,参见{@link cn.nukkit.Player#getDisplayName}
+ *

+ * 如果是在线的玩家,这个函数只会返回登录名字。如果要返回显示的名字,参见{@link cn.nukkit.Player#getDisplayName}
* Notice that this will only return its login name. If you need its display name, turn to - * {@link cn.nukkit.Player#getDisplayName}

+ * {@link cn.nukkit.Player#getDisplayName} * * @return 这个玩家的名称。
The name of this player. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ String getName(); - + UUID getUniqueId(); /** - * 返回这个玩家是否被封禁(ban)。
* Returns if this player is banned. * * @return 这个玩家的名称。
The name of this player. * @see #setBanned - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ boolean isBanned(); /** - * 设置这个玩家是否被封禁(ban)。
* Sets this player to be banned or to be pardoned. * * @param value 如果为{@code true},封禁这个玩家。如果为{@code false},解封这个玩家。
* {@code true} for ban and {@code false} for pardon. * @see #isBanned - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ void setBanned(boolean value); /** - * 返回这个玩家是否已加入白名单。
* Returns if this player is pardoned by whitelist. * * @return 这个玩家是否已加入白名单。
If this player is pardoned by whitelist. * @see cn.nukkit.Server#isWhitelisted - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ boolean isWhitelisted(); /** - * 把这个玩家加入白名单,或者取消这个玩家的白名单。
* Adds this player to the white list, or removes it from the whitelist. * * @param value 如果为{@code true},把玩家加入白名单。如果为{@code false},取消这个玩家的白名单。
@@ -84,59 +70,45 @@ public interface IPlayer extends ServerOperator, Metadatable { * @see #isWhitelisted * @see cn.nukkit.Server#addWhitelist * @see cn.nukkit.Server#removeWhitelist - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ void setWhitelisted(boolean value); /** - * 得到这个接口的{@code Player}对象。
* Returns a {@code Player} object for this interface. * * @return 这个接口的 {@code Player}对象。
a {@code Player} object for this interface. * @see cn.nukkit.Server#getPlayerExact - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ Player getPlayer(); /** - * 返回玩家所在的服务器。
* Returns the server carrying this player. * * @return 玩家所在的服务器。
the server carrying this player. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ Server getServer(); /** - * 得到这个玩家第一次游戏的时间。
* Returns the time this player first played in this server. * * @return Unix时间(以秒为单位。
Unix time in seconds. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ Long getFirstPlayed(); /** - * 得到这个玩家上次加入游戏的时间。
* Returns the time this player last joined in this server. * * @return Unix时间(以秒为单位。
Unix time in seconds. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ Long getLastPlayed(); /** - * 返回这个玩家以前是否来过服务器。
* Returns if this player has played in this server before. - * - *

如果想得到这个玩家是不是第一次玩,可以使用:
+ *

* If you want to know if this player is the first time playing in this server, you can use:
- *

- *
if(!player.hasPlayerBefore()) {...}
+ *
if (!player.hasPlayerBefore()) {...}
* * @return 这个玩家以前是不是玩过游戏。
If this player has played in this server before. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ boolean hasPlayedBefore(); - } diff --git a/src/main/java/cn/nukkit/InterruptibleThread.java b/src/main/java/cn/nukkit/InterruptibleThread.java index c36cdf2f743..02fe8d9ca09 100644 --- a/src/main/java/cn/nukkit/InterruptibleThread.java +++ b/src/main/java/cn/nukkit/InterruptibleThread.java @@ -1,17 +1,14 @@ package cn.nukkit; /** - * 描述一个可以被中断的线程的接口。
* An interface to describe a thread that can be interrupted. - * - *

在Nukkit服务器停止时,Nukkit会找到所有实现了{@code InterruptibleThread}的线程,并逐一中断。
+ *

* When a Nukkit server is stopping, Nukkit finds all threads implements {@code InterruptibleThread}, - * and interrupt them one by one.

+ * and interrupt them one by one. * * @author MagicDroidX(code) @ Nukkit Project * @author 粉鞋大妈(javadoc) @ Nukkit Project * @see cn.nukkit.scheduler.AsyncWorker - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public interface InterruptibleThread { } diff --git a/src/main/java/cn/nukkit/Nukkit.java b/src/main/java/cn/nukkit/Nukkit.java index c90a0e9665d..14ccb42917d 100644 --- a/src/main/java/cn/nukkit/Nukkit.java +++ b/src/main/java/cn/nukkit/Nukkit.java @@ -1,6 +1,5 @@ package cn.nukkit; -import cn.nukkit.network.protocol.ProtocolInfo; import cn.nukkit.utils.ServerKiller; import com.google.common.base.Preconditions; import io.netty.util.ResourceLeakDetector; @@ -13,7 +12,6 @@ import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.LoggerConfig; import java.io.IOException; @@ -30,52 +28,47 @@ */ /** - * Nukkit启动类,包含{@code main}函数。
- * The launcher class of Nukkit, including the {@code main} function. + * The launcher class of Nukkit, including the {@code main} function * * @author MagicDroidX(code) @ Nukkit Project * @author 粉鞋大妈(javadoc) @ Nukkit Project - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ @Log4j2 public class Nukkit { public final static Properties GIT_INFO = getGitInfo(); public final static String VERSION = getVersion(); - public final static String API_VERSION = "1.0.15"; - public final static String CODENAME = ""; - @Deprecated - public final static String MINECRAFT_VERSION = ProtocolInfo.MINECRAFT_VERSION; - @Deprecated - public final static String MINECRAFT_VERSION_NETWORK = ProtocolInfo.MINECRAFT_VERSION_NETWORK; - - public final static String PATH = System.getProperty("user.dir") + "/"; - public final static String DATA_PATH = System.getProperty("user.dir") + "/"; + public final static String API_VERSION = "1.1.0"; + public final static String PATH = System.getProperty("user.dir") + '/'; + public final static String DATA_PATH = System.getProperty("user.dir") + '/'; public final static String PLUGIN_PATH = DATA_PATH + "plugins"; - public static final long START_TIME = System.currentTimeMillis(); - public static boolean ANSI = true; - public static boolean TITLE = false; - public static boolean shortTitle = requiresShortTitle(); + /** + * Server start time + */ + public final static long START_TIME = System.currentTimeMillis(); + /** + * Console title enabled + */ + public static boolean TITLE = true; + /** + * Debug logging level + */ public static int DEBUG = 1; public static void main(String[] args) { - // Force IPv4 since Nukkit is not compatible with IPv6 System.setProperty("java.net.preferIPv4Stack" , "true"); System.setProperty("log4j.skipJansi", "false"); - System.getProperties().putIfAbsent("io.netty.allocator.type", "unpooled"); // Disable memory pooling unless specified - // Force Mapped ByteBuffers for LevelDB till fixed. - System.setProperty("leveldb.mmap", "true"); + // Disable memory pooling unless specified + System.getProperties().putIfAbsent("io.netty.allocator.type", "unpooled"); - // Netty logger for debug info - InternalLoggerFactory.setDefaultFactory(Log4J2LoggerFactory.INSTANCE); - ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID); + // Force Mapped ByteBuffers for LevelDB till fixed + System.setProperty("leveldb.mmap", "true"); // Define args OptionParser parser = new OptionParser(); parser.allowsUnrecognizedOptions(); OptionSpec helpSpec = parser.accepts("help", "Shows this page").forHelp(); - OptionSpec ansiSpec = parser.accepts("disable-ansi", "Disables console coloring"); OptionSpec titleSpec = parser.accepts("enable-title", "Enables title at the top of the window"); OptionSpec vSpec = parser.accepts("v", "Set verbosity of logging").withRequiredArg().ofType(String.class); OptionSpec verbositySpec = parser.accepts("verbosity", "Set verbosity of logging").withRequiredArg().ofType(String.class); @@ -88,13 +81,14 @@ public static void main(String[] args) { try { // Display help page parser.printHelpOn(System.out); - } catch (IOException e) { - // ignore + } catch (IOException ignored) { } return; } - ANSI = !options.has(ansiSpec); + InternalLoggerFactory.setDefaultFactory(Log4J2LoggerFactory.INSTANCE); + ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID); + TITLE = options.has(titleSpec); String verbosity = options.valueOf(vSpec); @@ -106,8 +100,7 @@ public static void main(String[] args) { try { Level level = Level.valueOf(verbosity); setLogLevel(level); - } catch (Exception e) { - // ignore + } catch (Exception ignored) { } } @@ -115,7 +108,7 @@ public static void main(String[] args) { try { if (TITLE) { - System.out.print((char) 0x1b + "]0;Nukkit is starting up..." + (char) 0x07); + System.out.print((char) 0x1b + "]0;Nukkit " + getVersion() + (char) 0x07); } new Server(PATH, DATA_PATH, PLUGIN_PATH, language); } catch (Throwable t) { @@ -125,7 +118,7 @@ public static void main(String[] args) { if (TITLE) { System.out.print((char) 0x1b + "]0;Stopping Server..." + (char) 0x07); } - log.info("Stopping other threads"); + log.info("Stopping other threads..."); for (Thread thread : java.lang.Thread.getAllStackTraces().keySet()) { if (!(thread instanceof InterruptibleThread)) { @@ -137,7 +130,7 @@ public static void main(String[] args) { } } - ServerKiller killer = new ServerKiller(8); + ServerKiller killer = new ServerKiller(10); killer.start(); if (TITLE) { @@ -146,21 +139,17 @@ public static void main(String[] args) { System.exit(0); } - private static boolean requiresShortTitle() { - //Shorter title for windows 8/2012 - String osName = System.getProperty("os.name").toLowerCase(); - return osName.contains("windows") &&(osName.contains("windows 8") || osName.contains("2012")); - } - private static Properties getGitInfo() { InputStream gitFileStream = Nukkit.class.getClassLoader().getResourceAsStream("git.properties"); if (gitFileStream == null) { + log.debug("Unable to find git.properties"); return null; } Properties properties = new Properties(); try { properties.load(gitFileStream); } catch (IOException e) { + log.debug("Unable to load git.properties", e); return null; } return properties; @@ -170,7 +159,7 @@ private static String getVersion() { StringBuilder version = new StringBuilder(); version.append("git-"); String commitId; - if (GIT_INFO == null || (commitId = GIT_INFO.getProperty("git.commit.id.abbrev")) == null) { + if (GIT_INFO == null || (commitId = GIT_INFO.getProperty("git.commit.id.abbrev")) == null || commitId.isEmpty()) { return version.append("null").toString(); } return version.append(commitId).toString(); @@ -179,16 +168,12 @@ private static String getVersion() { public static void setLogLevel(Level level) { Preconditions.checkNotNull(level, "level"); LoggerContext ctx = (LoggerContext) LogManager.getContext(false); - Configuration log4jConfig = ctx.getConfiguration(); - LoggerConfig loggerConfig = log4jConfig.getLoggerConfig(org.apache.logging.log4j.LogManager.ROOT_LOGGER_NAME); + LoggerConfig loggerConfig = ctx.getConfiguration().getLoggerConfig(org.apache.logging.log4j.LogManager.ROOT_LOGGER_NAME); loggerConfig.setLevel(level); ctx.updateLoggers(); } public static Level getLogLevel() { - LoggerContext ctx = (LoggerContext) LogManager.getContext(false); - Configuration log4jConfig = ctx.getConfiguration(); - LoggerConfig loggerConfig = log4jConfig.getLoggerConfig(org.apache.logging.log4j.LogManager.ROOT_LOGGER_NAME); - return loggerConfig.getLevel(); + return ((LoggerContext) LogManager.getContext(false)).getConfiguration().getLoggerConfig(org.apache.logging.log4j.LogManager.ROOT_LOGGER_NAME).getLevel(); } } diff --git a/src/main/java/cn/nukkit/OfflinePlayer.java b/src/main/java/cn/nukkit/OfflinePlayer.java index 66c8c9d39cb..18c45cf292c 100644 --- a/src/main/java/cn/nukkit/OfflinePlayer.java +++ b/src/main/java/cn/nukkit/OfflinePlayer.java @@ -8,27 +8,24 @@ import java.util.UUID; /** - * 描述一个不在线的玩家的类。
- * Describes an offline player. + * Describes an offline player * * @author MagicDroidX(code) @ Nukkit Project * @author 粉鞋大妈(javadoc) @ Nukkit Project * @see cn.nukkit.Player - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public class OfflinePlayer implements IPlayer { + private final Server server; private final CompoundTag namedTag; /** - * 初始化这个{@code OfflinePlayer}对象。
* Initializes the object {@code OfflinePlayer}. * * @param server 这个玩家所在服务器的{@code Server}对象。
* The server this player is in, as a {@code Server} object. * @param uuid 这个玩家的UUID。
* UUID of this player. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public OfflinePlayer(Server server, UUID uuid) { this(server, uuid, null); @@ -49,6 +46,7 @@ public OfflinePlayer(Server server, UUID uuid, String name) { } else { throw new IllegalArgumentException("Name and UUID cannot both be null"); } + if (nbt == null) { nbt = new CompoundTag(); } @@ -57,7 +55,9 @@ public OfflinePlayer(Server server, UUID uuid, String name) { if (uuid != null) { this.namedTag.putLong("UUIDMost", uuid.getMostSignificantBits()); this.namedTag.putLong("UUIDLeast", uuid.getLeastSignificantBits()); - } else { + } + + if (name != null && (uuid == null || !this.namedTag.contains("NameTag"))) { this.namedTag.putString("NameTag", name); } } @@ -173,5 +173,4 @@ public boolean hasMetadata(String metadataKey) { public void removeMetadata(String metadataKey, Plugin owningPlugin) { this.server.getPlayerMetadata().removeMetadata(this, metadataKey, owningPlugin); } - } diff --git a/src/main/java/cn/nukkit/Player.java b/src/main/java/cn/nukkit/Player.java index 51d94ed114f..a8024ccac01 100644 --- a/src/main/java/cn/nukkit/Player.java +++ b/src/main/java/cn/nukkit/Player.java @@ -4,15 +4,19 @@ import cn.nukkit.block.*; import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.blockentity.BlockEntityItemFrame; +import cn.nukkit.blockentity.BlockEntityLectern; import cn.nukkit.blockentity.BlockEntitySpawnable; import cn.nukkit.command.Command; import cn.nukkit.command.CommandSender; import cn.nukkit.command.data.CommandDataVersions; import cn.nukkit.entity.*; +import cn.nukkit.entity.custom.EntityManager; import cn.nukkit.entity.data.*; import cn.nukkit.entity.item.*; import cn.nukkit.entity.projectile.EntityArrow; +import cn.nukkit.entity.projectile.EntityProjectile; import cn.nukkit.entity.projectile.EntityThrownTrident; +import cn.nukkit.event.block.WaterFrostEvent; import cn.nukkit.event.entity.*; import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; import cn.nukkit.event.entity.EntityDamageEvent.DamageModifier; @@ -30,27 +34,26 @@ import cn.nukkit.form.window.FormWindow; import cn.nukkit.form.window.FormWindowCustom; import cn.nukkit.inventory.*; -import cn.nukkit.inventory.transaction.CraftingTransaction; -import cn.nukkit.inventory.transaction.EnchantTransaction; -import cn.nukkit.inventory.transaction.InventoryTransaction; -import cn.nukkit.inventory.transaction.RepairItemTransaction; +import cn.nukkit.inventory.transaction.*; import cn.nukkit.inventory.transaction.action.InventoryAction; import cn.nukkit.inventory.transaction.data.ReleaseItemData; import cn.nukkit.inventory.transaction.data.UseItemData; import cn.nukkit.inventory.transaction.data.UseItemOnEntityData; import cn.nukkit.item.*; +import cn.nukkit.item.custom.CustomItemManager; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.lang.TextContainer; import cn.nukkit.lang.TranslationContainer; import cn.nukkit.level.*; import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.format.generic.BaseFullChunk; +import cn.nukkit.level.particle.ItemBreakParticle; import cn.nukkit.level.particle.PunchBlockParticle; import cn.nukkit.math.*; import cn.nukkit.metadata.MetadataValue; import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.*; import cn.nukkit.network.CompressionProvider; -import cn.nukkit.network.Network; import cn.nukkit.network.SourceInterface; import cn.nukkit.network.encryption.PrepareEncryptionTask; import cn.nukkit.network.protocol.*; @@ -65,33 +68,40 @@ import cn.nukkit.resourcepacks.ResourcePack; import cn.nukkit.scheduler.AsyncTask; import cn.nukkit.utils.*; -import co.aikar.timings.Timing; -import co.aikar.timings.Timings; import com.google.common.base.Strings; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; +import com.google.common.collect.Sets; import io.netty.util.internal.PlatformDependent; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; -import it.unimi.dsi.fastutil.longs.Long2ObjectLinkedOpenHashMap; -import it.unimi.dsi.fastutil.longs.Long2ObjectMap; -import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; -import it.unimi.dsi.fastutil.longs.LongIterator; -import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.longs.*; import it.unimi.dsi.fastutil.objects.ObjectIterator; +import lombok.Getter; +import lombok.Setter; import lombok.extern.log4j.Log4j2; +import javax.annotation.Nullable; +import java.awt.*; +import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; +import java.lang.reflect.Field; import java.net.InetSocketAddress; import java.nio.ByteOrder; +import java.util.List; import java.util.*; +import java.util.Queue; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; +import java.util.stream.Stream; /** + * The Player class + * * @author MagicDroidX & Box * Nukkit Project */ @@ -102,19 +112,17 @@ public class Player extends EntityHuman implements CommandSender, InventoryHolde public static final int CREATIVE = 1; public static final int ADVENTURE = 2; public static final int SPECTATOR = 3; - public static final int VIEW = SPECTATOR; - - public static final int SURVIVAL_SLOTS = 36; - public static final int CREATIVE_SLOTS = 112; public static final int CRAFTING_SMALL = 0; public static final int CRAFTING_BIG = 1; public static final int CRAFTING_ANVIL = 2; public static final int CRAFTING_ENCHANT = 3; public static final int CRAFTING_BEACON = 4; + public static final int CRAFTING_SMITHING = 1003; + public static final int CRAFTING_LOOM = 1004; public static final float DEFAULT_SPEED = 0.1f; - public static final float MAXIMUM_SPEED = 0.5f; + public static final float MAXIMUM_SPEED = 6f; // TODO: Decrease when block collisions are fixed public static final float DEFAULT_FLY_SPEED = 0.05f; public static final int PERMISSION_CUSTOM = 3; @@ -125,41 +133,34 @@ public class Player extends EntityHuman implements CommandSender, InventoryHolde public static final int ANVIL_WINDOW_ID = 2; public static final int ENCHANT_WINDOW_ID = 3; public static final int BEACON_WINDOW_ID = 4; + public static final int LOOM_WINDOW_ID = 2; + public static final int SMITHING_WINDOW_ID = 6; - protected static final int RESOURCE_PACK_CHUNK_SIZE = 8 * 1024; // 8KB + protected static final int RESOURCE_PACK_CHUNK_SIZE = 8192; // 8KB protected final SourceInterface interfaz; protected final NetworkPlayerSession networkSession; + @Deprecated + public long creationTime; public boolean playedBefore; - public boolean spawned = false; - public boolean loggedIn = false; - public boolean locallyInitialized = false; - private boolean loginVerified = false; - private int unverifiedPackets; + public boolean spawned; + public boolean loggedIn; + private boolean loginVerified; private boolean loginPacketReceived; - private boolean awaitingEncryptionHandshake; + protected boolean networkSettingsRequested; public int gamemode; - public long lastBreak; - private BlockVector3 lastBreakPosition = new BlockVector3(); - - protected int windowCnt = 4; + protected long randomClientId; + private String unverifiedUsername = ""; protected final BiMap windows = HashBiMap.create(); - protected final BiMap windowIndex = windows.inverse(); protected final Set permanentWindows = new IntOpenHashSet(); + @Getter private boolean inventoryOpen; + protected int windowCnt = 4; protected int closingWindowId = Integer.MIN_VALUE; - protected int messageCounter = 2; - - private String clientSecret; - - public Vector3 speed = null; - - private final Queue clientMovements = PlatformDependent.newMpscQueue(4); - public final HashSet achievements = new HashSet<>(); public int craftingType = CRAFTING_SMALL; @@ -169,63 +170,58 @@ public class Player extends EntityHuman implements CommandSender, InventoryHolde protected CraftingTransaction craftingTransaction; protected EnchantTransaction enchantTransaction; protected RepairItemTransaction repairItemTransaction; - - public long creationTime = 0; - - protected long randomClientId; - - protected Vector3 forceMovement = null; - - protected Vector3 teleportPosition = null; + protected LoomTransaction loomTransaction; + protected SmithingTransaction smithingTransaction; + + public Vector3 speed; + protected Vector3 forceMovement; + protected Vector3 teleportPosition; + protected Vector3 newPosition; + protected Vector3 sleeping; + private Vector3 lastRightClickPos; + private final Queue clientMovements = PlatformDependent.newMpscQueue(4); protected boolean connected = true; protected final InetSocketAddress socketAddress; protected boolean removeFormat = true; protected String username; - private String unverifiedUsername = ""; protected String iusername; protected String displayName; - protected int startAction = -1; - - protected Vector3 sleeping = null; - protected Long clientID = null; - - private int loaderId; - + private boolean hasSpawnChunks; + private final int loaderId; + private int chunksSent; + protected int nextChunkOrderRun = 1; + protected int chunkRadius; + protected int viewDistance; public final Map usedChunks = new Long2ObjectOpenHashMap<>(); - - protected int chunkLoadCount = 0; protected final Long2ObjectLinkedOpenHashMap loadQueue = new Long2ObjectLinkedOpenHashMap<>(); - protected int nextChunkOrderRun = 1; protected final Map hiddenPlayers = new HashMap<>(); - protected Vector3 newPosition = null; - - protected int chunkRadius; - protected int viewDistance; - protected final int chunksPerTick; - protected final int spawnThreshold; + protected Position spawnPosition; - protected Position spawnPosition = null; - - protected int inAirTicks = 0; - protected int startAirTicks = 5; + protected int inAirTicks; + protected int startAirTicks = 10; protected AdventureSettings adventureSettings; - protected boolean checkMovement = true; + private PermissibleBase perm; - private PermissibleBase perm = null; + /** + * Option not to update shield blocking status. + */ + @Getter + @Setter + private boolean canTickShield = true; - private int exp = 0; - private int expLevel = 0; + private int exp; + private int expLevel; - protected PlayerFood foodData = null; + protected PlayerFood foodData; - private Entity killer = null; + private Entity killer; private final AtomicReference locale = new AtomicReference<>(null); @@ -235,68 +231,164 @@ public class Player extends EntityHuman implements CommandSender, InventoryHolde protected boolean enableClientCommand = true; - private BlockEnderChest viewingEnderChest = null; - - protected int lastEnderPearl = 20; - protected int lastChorusFruitTeleport = 20; + private BlockEnderChest viewingEnderChest; private LoginChainData loginChainData; - public Block breakingBlock = null; - private PlayerBlockActionData lastBlockAction; - - public int pickedXPOrb = 0; + public int pickedXPOrb; + private boolean canPickupXP = true; - protected int formWindowCount = 0; + protected int formWindowCount; protected Map formWindows = new Int2ObjectOpenHashMap<>(); protected Map serverSettings = new Int2ObjectOpenHashMap<>(); protected Map dummyBossBars = new Long2ObjectLinkedOpenHashMap<>(); - private AsyncTask preLoginEventTask = null; - protected boolean shouldLogin = false; - - public EntityFishingHook fishing = null; + private AsyncTask preLoginEventTask; + protected boolean shouldLogin; - public long lastSkinChange; - - protected double lastRightClickTime = 0.0; - protected Vector3 lastRightClickPos = null; + private static Stream pkIDs; + protected int startAction = -1; + private int lastEmote; + protected int lastEnderPearl = 20; + protected int lastChorusFruitTeleport = 20; + protected int lastFireworkBoost = 20; + public long lastSkinChange = -1; + private double lastRightClickTime; + public long lastBreak = -1; // When last block break was started + private BlockVector3 lastBreakPosition = new BlockVector3(); + public Block breakingBlock; // Block player is breaking currently + private BlockFace breakingBlockFace; // Block face player is breaking currently + private PlayerBlockActionData lastBlockAction; + public EntityFishingHook fishing; + @Getter + private boolean formOpen; + private boolean flySneaking; + public boolean locallyInitialized; + private boolean foodEnabled = true; + protected boolean checkMovement = true; private int timeSinceRest; + private boolean inSoulSand; + private boolean dimensionChangeInProgress; + private boolean awaitingDimensionAck; + private boolean awaitingEncryptionHandshake; + private int riderJumpTick; + private int riptideTicks; + private int blockingDelay; + private int fireworkBoostTicks; + private int fireworkBoostLevel; + + @Setter + private boolean needSendData; + private boolean needSendAdventureSettings; + private boolean needSendFoodLevel; + @Setter + private boolean needSendInventory; + private boolean needSendHeldItem; + private boolean needSendRotation; + private boolean dimensionFix560; + + /** + * Save last crossbow load tick (used to prevent loading a crossbow launching it immediately afterward) + */ + private int crossbowLoadTick; + /** + * Packets that can be received before the player has logged in + */ + private static final Set PRE_LOGIN_PACKETS = Sets.newHashSet(ProtocolInfo.BATCH_PACKET, ProtocolInfo.LOGIN_PACKET, ProtocolInfo.REQUEST_NETWORK_SETTINGS_PACKET, ProtocolInfo.REQUEST_CHUNK_RADIUS_PACKET, ProtocolInfo.SET_LOCAL_PLAYER_AS_INITIALIZED_PACKET, ProtocolInfo.RESOURCE_PACK_CHUNK_REQUEST_PACKET, ProtocolInfo.RESOURCE_PACK_CLIENT_RESPONSE_PACKET, ProtocolInfo.CLIENT_CACHE_STATUS_PACKET, ProtocolInfo.PACKET_VIOLATION_WARNING_PACKET, ProtocolInfo.CLIENT_TO_SERVER_HANDSHAKE_PACKET); + /** + * Default kick message for flying + */ + private static final String MSG_FLYING_NOT_ENABLED = "Flying is not enabled on this server"; + /** + * Get action start tick + * @return action start tick, -1 = no action in progress + */ public int getStartActionTick() { return startAction; } + /** + * Set action start tick to current tick + */ public void startAction() { this.startAction = this.server.getTick(); } + /** + * Reset action start tick + */ public void stopAction() { this.startAction = -1; } + /** + * Get last tick an ender pearl was used + * @return last ender pearl used tick + */ public int getLastEnderPearlThrowingTick() { return lastEnderPearl; } + /** + * Set last ender pearl throw tick to current tick + */ public void onThrowEnderPearl() { this.lastEnderPearl = this.server.getTick(); } + /** + * Get last chorus fruit teleport tick + * @return last chorus fruit teleport tick + */ public int getLastChorusFruitTeleport() { return lastChorusFruitTeleport; } + /** + * Set last chorus fruit teleport tick to current tick + */ public void onChorusFruitTeleport() { this.lastChorusFruitTeleport = this.server.getTick(); } + /** + * Get last tick firework boost for elytra was used + * @return last firework boost tick + */ + public int getLastFireworkBoostTick() { + return lastFireworkBoost; + } + + /** + * Set last firework boost tick to current tick + */ + public void onFireworkBoost(int boostLevel) { + this.lastFireworkBoost = this.server.getTick(); + this.fireworkBoostLevel = boostLevel; + this.fireworkBoostTicks = boostLevel == 3 ? 44 : boostLevel == 2 ? 29 : 23; + } + + /** + * Set last spin attack tick to current tick + */ + public void onSpinAttack(int riptideLevel) { + this.riptideTicks = 50 + (riptideLevel << 5); + } + + /** + * Get ender chest the player is viewing + * @return the ender chest player is viewing or null if player is not viewing an ender chest + */ public BlockEnderChest getViewingEnderChest() { return viewingEnderChest; } + /** + * Add player to ender chest viewers + */ public void setViewingEnderChest(BlockEnderChest chest) { if (chest == null && this.viewingEnderChest != null) { this.viewingEnderChest.getViewers().remove(this); @@ -306,12 +398,17 @@ public void setViewingEnderChest(BlockEnderChest chest) { this.viewingEnderChest = chest; } + /** + * Get player quit message + * @return quit message + */ public TranslationContainer getLeaveMessage() { - return new TranslationContainer(TextFormat.YELLOW + "%multiplayer.player.left", this.getDisplayName()); + return new TranslationContainer(TextFormat.YELLOW + "%multiplayer.player.left", this.displayName); } + @Deprecated public String getClientSecret() { - return clientSecret; + return null; } /** @@ -326,30 +423,30 @@ public Long getClientId() { @Override public boolean isBanned() { - return this.server.getNameBans().isBanned(this.getName()); + return this.server.getNameBans().isBanned(this.username); } @Override public void setBanned(boolean value) { if (value) { - this.server.getNameBans().addBan(this.getName(), null, null, null); - this.kick(PlayerKickEvent.Reason.NAME_BANNED, "Banned by admin"); + this.server.getNameBans().addBan(this.username, null, null, null); + this.kick(PlayerKickEvent.Reason.NAME_BANNED, "You are banned!"); } else { - this.server.getNameBans().remove(this.getName()); + this.server.getNameBans().remove(this.username); } } @Override public boolean isWhitelisted() { - return this.server.isWhitelisted(this.getName().toLowerCase()); + return this.server.isWhitelisted(this.iusername); } @Override public void setWhitelisted(boolean value) { if (value) { - this.server.addWhitelist(this.getName().toLowerCase()); + this.server.addWhitelist(this.iusername); } else { - this.server.removeWhitelist(this.getName().toLowerCase()); + this.server.removeWhitelist(this.iusername); } } @@ -373,87 +470,145 @@ public boolean hasPlayedBefore() { return this.playedBefore; } + /** + * Get current adventure settings + * @return adventure settings + */ public AdventureSettings getAdventureSettings() { return adventureSettings; } + /** + * Set and send adventure settings + * @param adventureSettings new adventure settings + */ public void setAdventureSettings(AdventureSettings adventureSettings) { this.adventureSettings = adventureSettings.clone(this); this.adventureSettings.update(); } + /** + * Reset in air ticks + */ public void resetInAirTicks() { + if (this.inAirTicks != 0) { + this.startAirTicks = 10; + } this.inAirTicks = 0; } + /** + * Set allow flight adventure setting + * @param value allow flight enabled + */ @Deprecated public void setAllowFlight(boolean value) { - this.getAdventureSettings().set(Type.ALLOW_FLIGHT, value); - this.getAdventureSettings().update(); + this.adventureSettings.set(Type.ALLOW_FLIGHT, value); + this.adventureSettings.update(); } + /** + * Check wether allow flight adventure setting is enabled + * @return allow flight enabled + */ @Deprecated public boolean getAllowFlight() { - return this.getAdventureSettings().get(Type.ALLOW_FLIGHT); + return this.adventureSettings.get(Type.ALLOW_FLIGHT); } + /** + * Set can modify world adventure setting(s) + * @param value can modify world + */ public void setAllowModifyWorld(boolean value) { - this.getAdventureSettings().set(Type.WORLD_IMMUTABLE, !value); - this.getAdventureSettings().set(Type.MINE, value); - this.getAdventureSettings().set(Type.BUILD, value); - this.getAdventureSettings().update(); + this.adventureSettings.set(Type.WORLD_IMMUTABLE, !value); + this.adventureSettings.set(Type.MINE, value); + this.adventureSettings.set(Type.BUILD, value); + this.adventureSettings.update(); } + /** + * Set can interact adventure setting(s) + * @param value can interact + */ public void setAllowInteract(boolean value) { - setAllowInteract(value, value); + this.setAllowInteract(value, value); } + /** + * Set can interact adventure setting(s) + * @param value can interact + * @param containers can open containers + */ public void setAllowInteract(boolean value, boolean containers) { - this.getAdventureSettings().set(Type.WORLD_IMMUTABLE, !value); - this.getAdventureSettings().set(Type.DOORS_AND_SWITCHED, value); - this.getAdventureSettings().set(Type.OPEN_CONTAINERS, containers); - this.getAdventureSettings().update(); + this.adventureSettings.set(Type.WORLD_IMMUTABLE, !value); + this.adventureSettings.set(Type.DOORS_AND_SWITCHED, value); + this.adventureSettings.set(Type.OPEN_CONTAINERS, containers); + this.adventureSettings.update(); } + /** + * Set auto jump adventure setting (adventureSettings.set(Type.AUTO_JUMP) + adventureSettings.update()) + * @param value auto jump enabled + */ @Deprecated public void setAutoJump(boolean value) { - this.getAdventureSettings().set(Type.AUTO_JUMP, value); - this.getAdventureSettings().update(); + this.adventureSettings.set(Type.AUTO_JUMP, value); + this.adventureSettings.update(); } + /** + * Check whether auto jump adventure setting is enabled (adventureSettings.get(Type.AUTO_JUMP)) + * @return auto jump enabled + */ @Deprecated public boolean hasAutoJump() { - return this.getAdventureSettings().get(Type.AUTO_JUMP); + return this.adventureSettings.get(Type.AUTO_JUMP); } @Override public void spawnTo(Player player) { - if (this.spawned && player.spawned && this.isAlive() && player.getLevel() == this.level && player.canSee(this) && !this.isSpectator()) { + if (this.spawned && player.spawned && this.isAlive() && player.isAlive() && player.getLevel() == this.level && player.canSee(this) && !this.isSpectator()) { super.spawnTo(player); } } - @Override - public Server getServer() { - return this.server; - } - + /** + * Check whether player can use text formatting + * @return player can use text formatting + */ public boolean getRemoveFormat() { return removeFormat; } + /** + * Make player unable to use text formatting (color codes etc.) + */ public void setRemoveFormat() { this.setRemoveFormat(true); } + /** + * Set whether player can use text formatting (color codes etc.) + * @param remove remove formatting from received texts + */ public void setRemoveFormat(boolean remove) { this.removeFormat = remove; } + /** + * Check whether player can see another player (not hidden) + * @param player target player + * @return player can see the target player + */ public boolean canSee(Player player) { return !this.hiddenPlayers.containsKey(player.getUniqueId()); } + /** + * Hide this player from target player + * @param player target player + */ public void hidePlayer(Player player) { if (this == player) { return; @@ -462,6 +617,10 @@ public void hidePlayer(Player player) { player.despawnFrom(this); } + /** + * Allow target player to see this player + * @param player target player + */ public void showPlayer(Player player) { if (this == player) { return; @@ -477,14 +636,26 @@ public boolean canCollideWith(Entity entity) { return false; } + /** + * Check whether player can pick up xp orbs + * @return can pick up xp orbs + */ + public boolean canPickupXP() { + return this.canPickupXP; + } + + /** + * Set whether player can pick up xp orbs + * @param canPickupXP can pick up xp orbs + */ + public void setCanPickupXP(boolean canPickupXP) { + this.canPickupXP = canPickupXP; + } + @Override public void resetFallDistance() { super.resetFallDistance(); - if (this.inAirTicks != 0) { - this.startAirTicks = 5; - } - this.inAirTicks = 0; - this.highestPosition = this.y; + this.resetInAirTicks(); } @Override @@ -494,7 +665,7 @@ public boolean isOnline() { @Override public boolean isOp() { - return this.server.isOp(this.getName()); + return this.server.isOp(this.username); } @Override @@ -504,13 +675,13 @@ public void setOp(boolean value) { } if (value) { - this.server.addOp(this.getName()); + this.server.addOp(this.username); } else { - this.server.removeOp(this.getName()); + this.server.removeOp(this.username); } this.recalculatePermissions(); - this.getAdventureSettings().update(); + this.adventureSettings.update(); this.sendCommandData(); } @@ -573,13 +744,21 @@ public void recalculatePermissions() { this.server.getPluginManager().subscribeToPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE, this); } - if (this.isEnableClientCommand() && spawned) this.sendCommandData(); + if (this.enableClientCommand && spawned) this.sendCommandData(); } + /** + * Are commands enabled for this player on the client side + * @return commands enabled + */ public boolean isEnableClientCommand() { return this.enableClientCommand; } + /** + * Set commands enabled client side. This does not necessarily prevent commands from being used. + * @param enable can use commands + */ public void setEnableClientCommand(boolean enable) { this.enableClientCommand = enable; SetCommandsEnabledPacket pk = new SetCommandsEnabledPacket(); @@ -588,26 +767,26 @@ public void setEnableClientCommand(boolean enable) { if (enable) this.sendCommandData(); } + /** + * Send updated command data (AvailableCommandsPacket) + */ public void sendCommandData() { - if (!spawned) { - return; - } AvailableCommandsPacket pk = new AvailableCommandsPacket(); Map data = new HashMap<>(); - int count = 0; + for (Command command : this.server.getCommandMap().getCommands().values()) { - if ("help".equals(command.getName())) { - continue; // The client will add this - } - if (!command.testPermissionSilent(this) || !command.isRegistered()) { - continue; + if (command.isRegistered()) { + if ("help".equals(command.getName())) { + continue; // The client will add this + } + CommandDataVersions commandData = command.generateCustomCommandData(this); + if (commandData != null) { // No permission + data.put(command.getName(), commandData); + } } - ++count; - CommandDataVersions data0 = command.generateCustomCommandData(this); - data.put(command.getName(), data0); } - if (count > 0) { - //TODO: structure checking + + if (!data.isEmpty()) { pk.commands = data; this.dataPacket(pk); } @@ -624,25 +803,13 @@ public Player(SourceInterface interfaz, Long clientID, InetSocketAddress socketA this.networkSession = interfaz.getSession(socketAddress); this.perm = new PermissibleBase(this); this.server = Server.getInstance(); - this.lastBreak = -1; this.socketAddress = socketAddress; - this.clientID = clientID; this.loaderId = Level.generateChunkLoaderId(this); - this.chunksPerTick = this.server.getConfig("chunk-sending.per-tick", 4); - this.spawnThreshold = this.server.getConfig("chunk-sending.spawn-threshold", 56); - this.spawnPosition = null; this.gamemode = this.server.getGamemode(); this.setLevel(this.server.getDefaultLevel()); this.viewDistance = this.server.getViewDistance(); - this.chunkRadius = viewDistance; - //this.newPosition = new Vector3(0, 0, 0); + this.chunkRadius = this.viewDistance; this.boundingBox = new SimpleAxisAlignedBB(0, 0, 0, 0, 0, 0); - this.lastSkinChange = -1; - - this.uuid = null; - this.rawUUID = null; - - this.creationTime = System.currentTimeMillis(); } @Override @@ -656,26 +823,51 @@ public boolean isPlayer() { return true; } + /** + * Remove achievement from player if the player has it + * @param achievementId achievement id + */ public void removeAchievement(String achievementId) { achievements.remove(achievementId); } + /** + * Check whether player has an achievement + * @param achievementId achievement id + * @return has achievement + */ public boolean hasAchievement(String achievementId) { return achievements.contains(achievementId); } + /** + * Check whether player is still connected + * @return connected + */ public boolean isConnected() { return connected; } + /** + * Get player's display name. Default value is player's username. + * @return display name + */ public String getDisplayName() { return this.displayName; } + /** + * Set player's display name + * @param displayName display name + */ public void setDisplayName(String displayName) { + if (displayName == null) { + displayName = ""; + server.getLogger().debug("Warning: setDisplayName: argument is null", new Throwable("")); + } this.displayName = displayName; if (this.spawned) { - this.server.updatePlayerListData(this.getUniqueId(), this.getId(), this.getDisplayName(), this.getSkin(), this.getLoginChainData().getXUID()); + this.server.updatePlayerListData(this.getUniqueId(), this.getId(), this.displayName, this.getSkin(), this.loginChainData.getXUID()); } } @@ -683,30 +875,62 @@ public void setDisplayName(String displayName) { public void setSkin(Skin skin) { super.setSkin(skin); if (this.spawned) { - this.server.updatePlayerListData(this.getUniqueId(), this.getId(), this.getDisplayName(), skin, this.getLoginChainData().getXUID()); + this.server.updatePlayerListData(this.getUniqueId(), this.getId(), this.displayName, skin, this.loginChainData.getXUID()); } } + /** + * Get player's host address + * @return host address + */ public String getAddress() { return this.socketAddress.getAddress().getHostAddress(); } + /** + * Get the port of player's connection + * @return port + */ public int getPort() { return this.socketAddress.getPort(); } + /** + * Get player's socket address + * @return socket address + */ public InetSocketAddress getSocketAddress() { return this.socketAddress; } + /** + * Get most recent position of received movements + * @return next position or current position if no next position has been received + */ public Position getNextPosition() { return this.newPosition != null ? new Position(this.newPosition.x, this.newPosition.y, this.newPosition.z, this.level) : this.getPosition(); } + public AxisAlignedBB getNextPositionBB() { + if (this.newPosition == null) { + return this.boundingBox; + } + Vector3 diff = this.newPosition.subtract(this); + return this.boundingBox.getOffsetBoundingBox(diff.x, diff.y, diff.z); + } + + /** + * Check whether player is sleeping + * @return is sleeping + */ public boolean isSleeping() { return this.sleeping != null; } + /** + * Get in air ticks + * @return in air ticks + */ public int getInAirTicks() { return this.inAirTicks; } @@ -714,33 +938,58 @@ public int getInAirTicks() { /** * Returns whether the player is currently using an item (right-click and hold). * - * @return bool + * @return whether the player is currently using an item */ public boolean isUsingItem() { - return this.getDataFlag(DATA_FLAGS, DATA_FLAG_ACTION) && this.startAction > -1; + return this.startAction > -1 && this.getDataFlag(DATA_FLAGS, DATA_FLAG_ACTION); } + /** + * Set using item flag + * @param value is using item + */ public void setUsingItem(boolean value) { this.startAction = value ? this.server.getTick() : -1; this.setDataFlag(DATA_FLAGS, DATA_FLAG_ACTION, value); } + /** + * Get interaction button text + * @return button text + */ public String getButtonText() { return this.buttonText; } + /** + * Set interaction button text + * @param text button text + */ public void setButtonText(String text) { - if (this.buttonText.equals(text)) { - return; + if (text == null) { + text = ""; + server.getLogger().debug("Warning: setButtonText: argument is null", new Throwable("")); + } + if (!text.equals(buttonText)) { + this.buttonText = text; + this.setDataPropertyAndSendOnlyToSelf(new StringEntityData(Entity.DATA_INTERACTIVE_TAG, this.buttonText)); } - this.buttonText = text; - this.setDataProperty(new StringEntityData(Entity.DATA_INTERACTIVE_TAG, this.buttonText)); } + /** + * Unload a chunk on current level + * @param x chunk x + * @param z chunk z + */ public void unloadChunk(int x, int z) { this.unloadChunk(x, z, null); } + /** + * Unload a chunk on given level + * @param x chunk x + * @param z chunk z + */ public void unloadChunk(int x, int z, Level level) { level = level == null ? this.level : level; long index = Level.chunkHash(x, z); @@ -757,24 +1006,69 @@ public void unloadChunk(int x, int z, Level level) { this.loadQueue.remove(index); } + /** + * Unload all loaded chunks + * @param online player is online; send entity despawn packets + */ + private void unloadChunks(boolean online) { + for (long index : this.usedChunks.keySet()) { + int chunkX = Level.getHashX(index); + int chunkZ = Level.getHashZ(index); + this.level.unregisterChunkLoader(this, chunkX, chunkZ); + + for (Entity entity : level.getChunkEntities(chunkX, chunkZ).values()) { + if (entity != this) { + if (online) { + entity.despawnFrom(this); + } else { + entity.hasSpawned.remove(loaderId); + } + } + } + } + + this.usedChunks.clear(); + this.loadQueue.clear(); + } + + /** + * Get player's spawn position + * @return player's spawn position or server's default (safe) spawn position if not set + */ public Position getSpawn() { - if (this.spawnPosition != null && this.spawnPosition.getLevel() != null) { - return this.spawnPosition; + if (this.spawnPosition != null && this.spawnPosition.getLevel() != null && this.spawnPosition.getLevel().getProvider() != null) { + return this.spawnPosition.add(0.5, 0, 0.5); } else { return this.server.getDefaultLevel().getSafeSpawn(); } } + /** + * Get player's spawn position + * @return player's spawn position or null if not set + */ + @Nullable + public Position getSpawnPosition() { + return this.spawnPosition; + } + + /** + * Send a chunk packet + * @param x chunk x + * @param z xhunk z + * @param packet chunk packet + */ public void sendChunk(int x, int z, DataPacket packet) { if (!this.connected) { return; } - this.usedChunks.put(Level.chunkHash(x, z), Boolean.TRUE); - this.chunkLoadCount++; + this.usedChunks.put(Level.chunkHash(x, z), true); this.dataPacket(packet); + this.chunksSent++; + if (this.spawned) { for (Entity entity : this.level.getChunkEntities(x, z).values()) { if (this != entity && !entity.closed && entity.isAlive()) { @@ -782,30 +1076,33 @@ public void sendChunk(int x, int z, DataPacket packet) { } } } - } - public void sendChunk(int x, int z, int subChunkCount, byte[] payload) { - if (!this.connected) { - return; + // Hack: Fix dimension screen issues + if (this.dimensionFix560) { + this.dimensionFix560 = false; + PlayerActionPacket pap = new PlayerActionPacket(); + pap.action = PlayerActionPacket.ACTION_DIMENSION_CHANGE_ACK; + pap.entityId = this.getId(); + this.dataPacket(pap); } + } - this.usedChunks.put(Level.chunkHash(x, z), true); - this.chunkLoadCount++; - - LevelChunkPacket pk = new LevelChunkPacket(); - pk.chunkX = x; - pk.chunkZ = z; - pk.subChunkCount = subChunkCount; - pk.data = payload; - - this.dataPacket(pk); - - if (this.spawned) { - for (Entity entity : this.level.getChunkEntities(x, z).values()) { - if (this != entity && !entity.closed && entity.isAlive()) { - entity.spawnTo(this); - } - } + /** + * Send a chunk packet + * @param x chunk x + * @param z xhunk z + * @param subChunkCount sub chunk count + * @param payload packet payload + */ + public void sendChunk(int x, int z, int subChunkCount, byte[] payload, int dimension) { + if (this.connected) { + LevelChunkPacket pk = new LevelChunkPacket(); + pk.chunkX = x; + pk.chunkZ = z; + pk.dimension = dimension; + pk.subChunkCount = subChunkCount; + pk.data = payload; + this.sendChunk(x, z, pk); } } @@ -814,35 +1111,38 @@ protected void sendNextChunk() { return; } - Timings.playerChunkSendTimer.startTiming(); - if (!loadQueue.isEmpty()) { int count = 0; ObjectIterator> iter = loadQueue.long2ObjectEntrySet().fastIterator(); while (iter.hasNext()) { - Long2ObjectMap.Entry entry = iter.next(); - long index = entry.getLongKey(); - - if (count >= this.chunksPerTick) { + if (count >= server.chunksPerTick) { break; } + + Long2ObjectMap.Entry entry = iter.next(); + long index = entry.getLongKey(); int chunkX = Level.getHashX(index); int chunkZ = Level.getHashZ(index); ++count; - this.usedChunks.put(index, false); - this.level.registerChunkLoader(this, chunkX, chunkZ, false); + try { + this.usedChunks.put(index, false); + this.level.registerChunkLoader(this, chunkX, chunkZ, false); - if (!this.level.populateChunk(chunkX, chunkZ)) { - if (this.spawned && this.teleportPosition == null) { - continue; - } else { - break; - } - } + if (!this.level.populateChunk(chunkX, chunkZ)) { + if (this.spawned && this.teleportPosition == null) { + continue; + } else { + break; + } + } - iter.remove(); + iter.remove(); + } catch (Exception ex) { + server.getLogger().logException(ex); + return; + } PlayerChunkRequestEvent ev = new PlayerChunkRequestEvent(this, chunkX, chunkZ); this.server.getPluginManager().callEvent(ev); @@ -851,51 +1151,68 @@ protected void sendNextChunk() { } } } - if (this.chunkLoadCount >= this.spawnThreshold && !this.spawned && this.teleportPosition == null) { - this.doFirstSpawn(); + + if (!this.hasSpawnChunks && this.chunksSent >= server.spawnThreshold) { + this.hasSpawnChunks = true; + + this.sendPlayStatus(PlayStatusPacket.PLAYER_SPAWN); } - Timings.playerChunkSendTimer.stopTiming(); } protected void doFirstSpawn() { - this.spawned = true; - - this.inventory.sendContents(this); - this.inventory.sendArmorContents(this); - this.offhandInventory.sendContents(this); - this.setEnableClientCommand(true); + if (this.spawned) { + return; + } - SetTimePacket setTimePacket = new SetTimePacket(); - setTimePacket.time = this.level.getTime(); - this.dataPacket(setTimePacket); + this.noDamageTicks = 60; + this.setAirTicks(400); - Position pos = this.level.getSafeSpawn(this); + if (this.hasPermission(Server.BROADCAST_CHANNEL_USERS)) { + this.server.getPluginManager().subscribeToPermission(Server.BROADCAST_CHANNEL_USERS, this); + } - PlayerRespawnEvent respawnEvent = new PlayerRespawnEvent(this, pos, true); + if (this.hasPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE)) { + this.server.getPluginManager().subscribeToPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE, this); + } + boolean dead = this.getHealth() < 1; + Position spawn = dead ? this.getSpawn() : this; + PlayerRespawnEvent respawnEvent = new PlayerRespawnEvent(this, spawn.level.getSafeSpawn(spawn), true); this.server.getPluginManager().callEvent(respawnEvent); - pos = respawnEvent.getRespawnPosition(); + this.spawned = true; + + if (dead) { + if (this.server.isHardcore()) { + this.setBanned(true); + return; + } + + this.teleport(respawnEvent.getRespawnPosition(), null); + + // TODO: should probably respawn() here + this.setHealth(this.getMaxHealth()); + this.foodData.setLevel(20, 20); + this.sendData(this); + } else { + this.setPosition(respawnEvent.getRespawnPosition()); + this.sendPosition(respawnEvent.getRespawnPosition(), yaw, pitch, MovePlayerPacket.MODE_TELEPORT); + this.forceMovement = this.teleportPosition = respawnEvent.getRespawnPosition(); - this.sendPlayStatus(PlayStatusPacket.PLAYER_SPAWN); + this.getLevel().sendTime(this); + this.getLevel().sendWeather(this); + } PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(this, - new TranslationContainer(TextFormat.YELLOW + "%multiplayer.player.joined", new String[]{ - this.getDisplayName() - }) + new TranslationContainer(TextFormat.YELLOW + "%multiplayer.player.joined", new String[]{this.displayName}) ); this.server.getPluginManager().callEvent(playerJoinEvent); - if (playerJoinEvent.getJoinMessage().toString().trim().length() > 0) { + if (!playerJoinEvent.getJoinMessage().toString().trim().isEmpty()) { this.server.broadcastMessage(playerJoinEvent.getJoinMessage()); } - this.noDamageTicks = 60; - - this.getServer().sendRecipeList(this); - - for (long index : this.usedChunks.keySet()) { int chunkX = Level.getHashX(index); int chunkZ = Level.getHashZ(index); @@ -906,37 +1223,18 @@ protected void doFirstSpawn() { } } - int experience = this.getExperience(); - if (experience != 0) { - this.sendExperience(experience); - } - - int level = this.getExperienceLevel(); - if (level != 0) { - this.sendExperienceLevel(this.getExperienceLevel()); - } - - this.teleport(pos, null); // Prevent PlayerTeleportEvent during player spawn + // Prevent PlayerTeleportEvent during player spawn + //this.teleport(pos, null); if (!this.isSpectator()) { this.spawnToAll(); } - //todo Updater - - //Weather - this.getLevel().sendWeather(this); - - //FoodLevel - PlayerFood food = this.getFoodData(); - if (food.getLevel() != food.getMaxLevel()) { - food.sendFoodLevel(); - } - - if (this.getHealth() < 1) { - this.respawn(); + if (!this.locallyInitialized) { + // Not really needed anymore but it's here for plugin compatibility + this.server.getPluginManager().callEvent(new PlayerLocallyInitializedEvent(this)); + this.locallyInitialized = true; } - } protected boolean orderChunks() { @@ -944,21 +1242,17 @@ protected boolean orderChunks() { return false; } - Timings.playerChunkOrderTimer.startTiming(); - - this.nextChunkOrderRun = 200; + this.nextChunkOrderRun = 20; loadQueue.clear(); Long2ObjectOpenHashMap lastChunk = new Long2ObjectOpenHashMap<>(this.usedChunks); - int centerX = (int) this.x >> 4; - int centerZ = (int) this.z >> 4; + int centerX = this.getChunkX(); + int centerZ = this.getChunkZ(); - int radius = spawned ? this.chunkRadius : (int) Math.ceil(Math.sqrt(spawnThreshold)); + int radius = spawned ? this.chunkRadius : server.spawnThresholdRadius; int radiusSqr = radius * radius; - - long index; for (int x = 0; x <= radius; x++) { int xx = x * x; @@ -967,43 +1261,43 @@ protected boolean orderChunks() { if (distanceSqr > radiusSqr) continue; /* Top right quadrant */ - if(this.usedChunks.get(index = Level.chunkHash(centerX + x, centerZ + z)) != Boolean.TRUE) { + if (this.usedChunks.get(index = Level.chunkHash(centerX + x, centerZ + z)) != Boolean.TRUE) { this.loadQueue.put(index, Boolean.TRUE); } lastChunk.remove(index); /* Top left quadrant */ - if(this.usedChunks.get(index = Level.chunkHash(centerX - x - 1, centerZ + z)) != Boolean.TRUE) { + if (this.usedChunks.get(index = Level.chunkHash(centerX - x - 1, centerZ + z)) != Boolean.TRUE) { this.loadQueue.put(index, Boolean.TRUE); } lastChunk.remove(index); /* Bottom right quadrant */ - if(this.usedChunks.get(index = Level.chunkHash(centerX + x, centerZ - z - 1)) != Boolean.TRUE) { + if (this.usedChunks.get(index = Level.chunkHash(centerX + x, centerZ - z - 1)) != Boolean.TRUE) { this.loadQueue.put(index, Boolean.TRUE); } lastChunk.remove(index); /* Bottom left quadrant */ - if(this.usedChunks.get(index = Level.chunkHash(centerX - x - 1, centerZ - z - 1)) != Boolean.TRUE) { + if (this.usedChunks.get(index = Level.chunkHash(centerX - x - 1, centerZ - z - 1)) != Boolean.TRUE) { this.loadQueue.put(index, Boolean.TRUE); } lastChunk.remove(index); - if(x != z){ + if (x != z) { /* Top right quadrant mirror */ - if(this.usedChunks.get(index = Level.chunkHash(centerX + z, centerZ + x)) != Boolean.TRUE) { + if (this.usedChunks.get(index = Level.chunkHash(centerX + z, centerZ + x)) != Boolean.TRUE) { this.loadQueue.put(index, Boolean.TRUE); } lastChunk.remove(index); /* Top left quadrant mirror */ - if(this.usedChunks.get(index = Level.chunkHash(centerX - z - 1, centerZ + x)) != Boolean.TRUE) { + if (this.usedChunks.get(index = Level.chunkHash(centerX - z - 1, centerZ + x)) != Boolean.TRUE) { this.loadQueue.put(index, Boolean.TRUE); } lastChunk.remove(index); /* Bottom right quadrant mirror */ - if(this.usedChunks.get(index = Level.chunkHash(centerX + z, centerZ - x - 1)) != Boolean.TRUE) { + if (this.usedChunks.get(index = Level.chunkHash(centerX + z, centerZ - x - 1)) != Boolean.TRUE) { this.loadQueue.put(index, Boolean.TRUE); } lastChunk.remove(index); /* Bottom left quadrant mirror */ - if(this.usedChunks.get(index = Level.chunkHash(centerX - z - 1, centerZ - x - 1)) != Boolean.TRUE) { + if (this.usedChunks.get(index = Level.chunkHash(centerX - z - 1, centerZ - x - 1)) != Boolean.TRUE) { this.loadQueue.put(index, Boolean.TRUE); } lastChunk.remove(index); @@ -1020,59 +1314,59 @@ protected boolean orderChunks() { if (!loadQueue.isEmpty()) { NetworkChunkPublisherUpdatePacket packet = new NetworkChunkPublisherUpdatePacket(); packet.position = this.asBlockVector3(); - packet.radius = viewDistance << 4; + packet.radius = this.chunkRadius << 4; this.dataPacket(packet); } - Timings.playerChunkOrderTimer.stopTiming(); return true; } + /** + * This method no longer has special function. Calls dataPacket(). + * @param packet data packet + * @return return value of dataPacket() + */ @Deprecated public boolean batchDataPacket(DataPacket packet) { return this.dataPacket(packet); } /** - * 0 is true - * -1 is false - * other is identifer - * @param packet packet to send - * @return packet successfully sent + * Send a data packet + * @param packet data packet + * @return sent */ public boolean dataPacket(DataPacket packet) { if (!this.connected) { return false; } - try (Timing ignored = Timings.getSendDataPacketTiming(packet)) { - DataPacketSendEvent ev = new DataPacketSendEvent(this, packet); - this.server.getPluginManager().callEvent(ev); - if (ev.isCancelled()) { - return false; - } + DataPacket dataPacket = packet.clone(); - if (log.isTraceEnabled() && !server.isIgnoredPacket(packet.getClass())) { - log.trace("Outbound {}: {}", this.getName(), packet); - } + DataPacketSendEvent ev = new DataPacketSendEvent(this, dataPacket); + this.server.getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + return false; + } + + if (Nukkit.DEBUG > 2 && !server.isIgnoredPacket(packet.getClass())) { + log.trace("Outbound {}: {}", this.getName(), dataPacket); + } - this.networkSession.sendPacket(packet); + if (dataPacket instanceof BatchPacket) { + this.networkSession.sendPacket(dataPacket); + } else { + // Make sure packets always go to BatchingHelper so they are not reordered + this.server.batchPackets(new Player[]{this}, new DataPacket[]{dataPacket}); } return true; } @Deprecated public int dataPacket(DataPacket packet, boolean needACK) { - return dataPacket(packet) ? 1 : 0; + return this.dataPacket(packet) ? 1 : 0; } - /** - * 0 is true - * -1 is false - * other is identifer - * @param packet packet to send - * @return packet successfully sent - */ @Deprecated public boolean directDataPacket(DataPacket packet) { return this.dataPacket(packet); @@ -1080,23 +1374,43 @@ public boolean directDataPacket(DataPacket packet) { @Deprecated public int directDataPacket(DataPacket packet, boolean needACK) { - return this.dataPacket(packet) ? 1 : 0; + return this.directDataPacket(packet) ? 1 : 0; } public void forceDataPacket(DataPacket packet, Runnable callback) { + DataPacketSendEvent ev = new DataPacketSendEvent(this, packet); + this.server.getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + return; + } + + if (Nukkit.DEBUG > 2 && !server.isIgnoredPacket(packet.getClass())) { + log.trace("Outbound {}: {}", this.getName(), packet); + } + this.networkSession.sendImmediatePacket(packet, (callback == null ? () -> {} : callback)); } + /** + * Get network latency + * @return network latency in milliseconds + */ public int getPing() { return this.interfaz.getNetworkLatency(this); } + /** + * Attempt to sleep at position + * @param pos position + * @return successfully set sleeping + */ public boolean sleepOn(Vector3 pos) { if (!this.isOnline()) { return false; } - for (Entity p : this.level.getNearbyEntities(this.boundingBox.grow(2, 1, 2), this)) { + Entity[] e = this.level.getNearbyEntities(this.boundingBox.grow(2, 1, 2), this); + for (Entity p : e) { if (p instanceof Player) { if (((Player) p).sleeping != null && pos.distance(((Player) p).sleeping) <= 0.1) { return false; @@ -1116,15 +1430,21 @@ public boolean sleepOn(Vector3 pos) { this.setDataProperty(new IntPositionEntityData(DATA_PLAYER_BED_POSITION, (int) pos.x, (int) pos.y, (int) pos.z)); this.setDataFlag(DATA_PLAYER_FLAGS, DATA_PLAYER_FLAG_SLEEP, true); - this.setSpawn(pos); + if (!pos.equals(this.getSpawnPosition())) { + this.setSpawn(pos); + this.sendMessage("§7%tile.bed.respawnSet", true); + } this.level.sleepTicks = 60; - this.timeSinceRest = 0; return true; } + /** + * Set player's spawn position + * @param pos spawn position + */ public void setSpawn(Vector3 pos) { Level level; if (!(pos instanceof Position)) { @@ -1132,15 +1452,26 @@ public void setSpawn(Vector3 pos) { } else { level = ((Position) pos).getLevel(); } - this.spawnPosition = new Position(pos.x, pos.y, pos.z, level); + this.spawnPosition = pos instanceof Block ? ((Block) pos).clone().setLevel(level) : new Position(pos.x, pos.y, pos.z, level); + this.sendSpawnPos((int) pos.x, (int) pos.y, (int) pos.z, level.getDimension()); + } + + /** + * Internal: Send player spawn position + */ + private void sendSpawnPos(int x, int y, int z, int dimension) { SetSpawnPositionPacket pk = new SetSpawnPositionPacket(); pk.spawnType = SetSpawnPositionPacket.TYPE_PLAYER_SPAWN; - pk.x = (int) this.spawnPosition.x; - pk.y = (int) this.spawnPosition.y; - pk.z = (int) this.spawnPosition.z; + pk.x = x; + pk.y = y; + pk.z = z; + pk.dimension = dimension; this.dataPacket(pk); } + /** + * Stop sleeping. Does nothing if the player is not sleeping. + */ public void stopSleep() { if (this.sleeping != null) { this.server.getPluginManager().callEvent(new PlayerBedLeaveEvent(this, this.level.getBlock(this.sleeping))); @@ -1149,7 +1480,6 @@ public void stopSleep() { this.setDataProperty(new IntPositionEntityData(DATA_PLAYER_BED_POSITION, 0, 0, 0)); this.setDataFlag(DATA_PLAYER_FLAGS, DATA_PLAYER_FLAG_SLEEP, false); - this.level.sleepTicks = 0; AnimatePacket pk = new AnimatePacket(); @@ -1159,8 +1489,21 @@ public void stopSleep() { } } + /** + * Get sleeping position + * @return current sleeping position or null if not sleeping + */ + public Vector3 getSleepingPos() { + return this.sleeping; + } + + /** + * Attempts to award an achievement + * @param achievementId achievement id + * @return new achievement awarded + */ public boolean awardAchievement(String achievementId) { - if (!Server.getInstance().getPropertyBoolean("achievements", true)) { + if (!server.achievementsEnabled) { return false; } @@ -1187,6 +1530,15 @@ public boolean awardAchievement(String achievementId) { return true; } + /** + * Get player's gamemode: + * 0 = survival + * 1 = creative + * 2 = adventure + * 3 = spectator + * + * @return gamemode (number) + */ public int getGamemode() { return gamemode; } @@ -1194,8 +1546,6 @@ public int getGamemode() { /** * Returns a client-friendly gamemode of the specified real gamemode * This function takes care of handling gamemodes known to MCPE (as of 1.1.0.3, that includes Survival, Creative and Adventure) - *

- * TODO: remove this when Spectator Mode gets added properly to MCPE */ private static int getClientFriendlyGamemode(int gamemode) { gamemode &= 0x03; @@ -1205,32 +1555,46 @@ private static int getClientFriendlyGamemode(int gamemode) { return gamemode; } + /** + * Set player's gamemode + * @param gamemode new gamemode + * @return gamemode changed + */ public boolean setGamemode(int gamemode) { return this.setGamemode(gamemode, false, null); } + /** + * Set player's gamemode + * @param gamemode new gamemode + * @param clientSide whether change was client initiated + * @return gamemode changed + */ public boolean setGamemode(int gamemode, boolean clientSide) { return this.setGamemode(gamemode, clientSide, null); } + /** + * Set player's gamemode + * @param gamemode new gamemode + * @param clientSide whether change was client initiated + * @param newSettings updated adventure settings for the new gamemode; calculated automatically if null + * @return gamemode changed + */ public boolean setGamemode(int gamemode, boolean clientSide, AdventureSettings newSettings) { if (gamemode < 0 || gamemode > 3 || this.gamemode == gamemode) { return false; } if (newSettings == null) { - newSettings = this.getAdventureSettings().clone(this); + newSettings = this.adventureSettings.clone(this); newSettings.set(Type.WORLD_IMMUTABLE, (gamemode & 0x02) > 0); newSettings.set(Type.MINE, (gamemode & 0x02) <= 0); newSettings.set(Type.BUILD, (gamemode & 0x02) <= 0); newSettings.set(Type.NO_PVM, gamemode == SPECTATOR); newSettings.set(Type.ALLOW_FLIGHT, (gamemode & 0x01) > 0); newSettings.set(Type.NO_CLIP, gamemode == SPECTATOR); - if (gamemode == SPECTATOR) { - newSettings.set(Type.FLYING, true); - } else if ((gamemode & 0x1) == 0) { - newSettings.set(Type.FLYING, false); - } + newSettings.set(Type.FLYING, (gamemode & 0x1) == 1); } PlayerGameModeChangeEvent ev; @@ -1263,18 +1627,11 @@ public boolean setGamemode(int gamemode, boolean clientSide, AdventureSettings n if (this.isSpectator()) { this.teleport(this, null); - this.setDataFlag(DATA_FLAGS, DATA_FLAG_SILENT, true); - this.setDataFlag(DATA_FLAGS, DATA_FLAG_HAS_COLLISION, false); - /*InventoryContentPacket inventoryContentPacket = new InventoryContentPacket(); - inventoryContentPacket.inventoryId = InventoryContentPacket.SPECIAL_CREATIVE; - this.dataPacket(inventoryContentPacket);*/ + this.setDataFlag(DATA_FLAGS, DATA_FLAG_SILENT, true, false); + this.setDataFlag(DATA_FLAGS, DATA_FLAG_HAS_COLLISION, false); // Sends both } else { - this.setDataFlag(DATA_FLAGS, DATA_FLAG_SILENT, false); - this.setDataFlag(DATA_FLAGS, DATA_FLAG_HAS_COLLISION, true); - /*InventoryContentPacket inventoryContentPacket = new InventoryContentPacket(); - inventoryContentPacket.inventoryId = InventoryContentPacket.SPECIAL_CREATIVE; - inventoryContentPacket.slots = Item.getCreativeItems().toArray(new Item[0]); - this.dataPacket(inventoryContentPacket);*/ + this.setDataFlag(DATA_FLAGS, DATA_FLAG_SILENT, false, false); + this.setDataFlag(DATA_FLAGS, DATA_FLAG_HAS_COLLISION, true); // Sends both } this.resetFallDistance(); @@ -1288,23 +1645,42 @@ public boolean setGamemode(int gamemode, boolean clientSide, AdventureSettings n return true; } + /** + * Send adventure settings (adventureSettings.update()) + */ @Deprecated public void sendSettings() { - this.getAdventureSettings().update(); + this.adventureSettings.update(); } + /** + * Check player game mode + * @return whether player is in survival mode + */ public boolean isSurvival() { return this.gamemode == SURVIVAL; } + /** + * Check player game mode + * @return whether player is in creative mode + */ public boolean isCreative() { return this.gamemode == CREATIVE; } + /** + * Check player game mode + * @return whether player is in spectator mode + */ public boolean isSpectator() { return this.gamemode == SPECTATOR; } + /** + * Check player game mode + * @return whether player is in adventure mode + */ public boolean isAdventure() { return this.gamemode == ADVENTURE; } @@ -1312,45 +1688,16 @@ public boolean isAdventure() { @Override public Item[] getDrops() { if (!this.isCreative() && !this.isSpectator()) { - return super.getDrops(); - } - - return new Item[0]; - } - - @Override - public boolean fastMove(double dx, double dy, double dz) { - if (dx == 0 && dy == 0 && dz == 0) { - return true; - } - - Timings.entityMoveTimer.startTiming(); - - AxisAlignedBB newBB = this.boundingBox.getOffsetBoundingBox(dx, dy, dz); - - if (this.isSpectator() || server.getAllowFlight() || !this.level.hasCollision(this, newBB.shrink(0, this.getStepHeight(), 0), false)) { - this.boundingBox = newBB; - } - - this.x = (this.boundingBox.getMinX() + this.boundingBox.getMaxX()) / 2; - this.y = this.boundingBox.getMinY() - this.ySize; - this.z = (this.boundingBox.getMinZ() + this.boundingBox.getMaxZ()) / 2; - - this.checkChunks(); - - if (!this.isSpectator()) { - if (!this.onGround || dy != 0) { - AxisAlignedBB bb = this.boundingBox.clone(); - bb.setMinY(bb.getMinY() - 0.75); - - this.onGround = this.level.getCollisionBlocks(bb).length > 0; + if (this.inventory != null) { + List drops = new ArrayList<>(this.inventory.getContents().values()); + drops.addAll(this.offhandInventory.getContents().values()); + //drops.addAll(this.playerUIInventory.getContents().values()); // handled in resetCraftingGridType + return drops.toArray(new Item[0]); } - this.isCollided = this.onGround; - this.updateFallState(this.onGround); + return new Item[0]; } - Timings.entityMoveTimer.stopTiming(); - return true; + return new Item[0]; } @Override @@ -1376,7 +1723,7 @@ protected void checkGroundState(double movX, double movY, double movZ, double dx for (int z = minZ; z <= maxZ; ++z) { for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { - Block block = this.level.getBlock(this.temporalVector.setComponents(x, y, z)); + Block block = this.level.getBlock(chunk, x, y, z, true); if (!block.canPassThrough() && block.collidesWithBB(realBB)) { onGround = true; @@ -1395,189 +1742,383 @@ protected void checkGroundState(double movX, double movY, double movZ, double dx @Override protected void checkBlockCollision() { if (this.isSpectator()) { - if (this.blocksAround == null) { - this.blocksAround = new ArrayList<>(); - } - if (this.collisionBlocks == null) { - this.collisionBlocks = new ArrayList<>(); - } return; } - boolean portal = false; + boolean netherPortal = false; + boolean endPortal = false; for (Block block : this.getCollisionBlocks()) { + if (block.getLevel().getProvider() == null) { + break; + } + if (block.getId() == Block.NETHER_PORTAL) { - portal = true; + netherPortal = true; + continue; + } else if (block.getId() == Block.END_PORTAL) { + endPortal = true; continue; } block.onEntityCollide(this); } - if (portal) { - if (this.isCreative() && this.inPortalTicks < 80) { - this.inPortalTicks = 80; - } else { - this.inPortalTicks++; + if (endPortal) { + inEndPortalTicks++; + } else { + this.inEndPortalTicks = 0; + } + + if (inEndPortalTicks == 1 && EnumLevel.THE_END.getLevel() != null) { + EntityPortalEnterEvent ev = new EntityPortalEnterEvent(this, EntityPortalEnterEvent.PortalType.END); + this.getServer().getPluginManager().callEvent(ev); + + if (!ev.isCancelled()) { + int oldDimension = this.getLevel().getDimension(); + if (oldDimension == Level.DIMENSION_THE_END) { + Position spawn; + if ((spawn = this.getSpawn()).getLevel().getDimension() == Level.DIMENSION_OVERWORLD) { + if (this.teleport(spawn, TeleportCause.END_PORTAL)) { + this.awardAchievement("theEnd2"); + } + } else { + if (this.teleport(this.getServer().getDefaultLevel().getSafeSpawn(), TeleportCause.END_PORTAL)) { + this.awardAchievement("theEnd2"); + } + } + } else { + Level end = this.getServer().getLevelByName("the_end"); + if (end != null) { + Position pos = new Position(100.5, 49, 0.5, end); + + FullChunk chunk = end.getChunk(pos.getChunkX(), pos.getChunkZ(), false); + if (chunk == null || !chunk.isGenerated()) { + end.generateChunk(pos.getChunkX(), pos.getChunkZ(), true); + + int x = pos.getFloorX(); + int y = pos.getFloorY(); + int z = pos.getFloorZ(); + for (int xx = x - 2; xx < x + 3; xx++) { + for (int zz = z - 2; zz < z + 3; zz++) { + end.setBlockAt(xx, y - 1, zz, BlockID.OBSIDIAN); + for (int yy = y; yy < y + 4; yy++) { + end.setBlockAt(xx, yy, zz, BlockID.AIR); + } + } + } + } + + if (this.teleport(pos, TeleportCause.END_PORTAL) && oldDimension == Level.DIMENSION_OVERWORLD) { + this.awardAchievement("theEnd"); + } + } + } } + } + + if (netherPortal) { + this.inPortalTicks++; } else { this.inPortalTicks = 0; + this.portalPos = null; + } + + if (this.server.isNetherAllowed()) { + if (this.inPortalTicks == (this.gamemode == CREATIVE ? 1 : 40) && this.portalPos == null) { + Position portalPos = this.level.calculatePortalMirror(this); + if (portalPos == null) { + return; + } + + for (int x = -1; x < 2; x++) { + for (int z = -1; z < 2; z++) { + int chunkX = (portalPos.getChunkX()) + x, chunkZ = (portalPos.getChunkZ()) + z; + FullChunk chunk = portalPos.level.getChunk(chunkX, chunkZ, false); + if (chunk == null || !(chunk.isGenerated() || chunk.isPopulated())) { + portalPos.level.generateChunk(chunkX, chunkZ, true); + } + } + } + this.portalPos = portalPos; + } + + if (this.inPortalTicks == (this.gamemode == CREATIVE ? 1 : 80)) { + EntityPortalEnterEvent ev = new EntityPortalEnterEvent(this, EntityPortalEnterEvent.PortalType.NETHER); + this.getServer().getPluginManager().callEvent(ev); + + if (ev.isCancelled()) { + this.portalPos = null; + return; + } + + int oldDimension = this.getLevel().getDimension(); + Position foundPortal = BlockNetherPortal.findNearestPortal(this.portalPos); + if (foundPortal == null) { + BlockNetherPortal.spawnPortal(this.portalPos); + if (this.teleport(this.portalPos.add(1.5, 1, 0.5), TeleportCause.NETHER_PORTAL) && oldDimension == Level.DIMENSION_OVERWORLD) { + this.awardAchievement("portal"); + } + } else { + if (this.teleport(BlockNetherPortal.getSafePortal(foundPortal), TeleportCause.NETHER_PORTAL) && oldDimension == Level.DIMENSION_OVERWORLD) { + this.awardAchievement("portal"); + } + } + this.portalPos = null; + } } } + /** + * Internal: Check nearby entities and try to pick them up + */ protected void checkNearEntities() { - for (Entity entity : this.level.getNearbyEntities(this.boundingBox.grow(1, 0.5, 1), this)) { - entity.scheduleUpdate(); - - if (!entity.isAlive() || !this.isAlive()) { + Entity[] e = this.level.getNearbyEntities(this.boundingBox.grow(1, 0.5, 1), this); + for (Entity entity : e) { + if (!entity.isAlive()) { continue; } + // Update pickup delay + if (entity.updateMode % 3 == 2) { + entity.scheduleUpdate(); + } + this.pickupEntity(entity, true); } } - protected void handleMovement(Vector3 clientPos) { + /** + * Internal: Process player movement + * + * @param newPos client position + */ + protected void handleMovement(Vector3 newPos) { if (!this.isAlive() || !this.spawned || this.teleportPosition != null || this.isSleeping()) { return; } - boolean invalidMotion = false; - double distance = clientPos.distanceSquared(this); - if (distance > 128) { - invalidMotion = true; - } else if (!this.level.isChunkGenerated(clientPos.getChunkX(), clientPos.getChunkZ())) { - invalidMotion = true; - this.nextChunkOrderRun = 0; - } + double distanceSquared = newPos.distanceSquared(this); + if (distanceSquared == 0) { + if (this.lastYaw != this.yaw || this.lastPitch != this.pitch) { + this.lastYaw = this.yaw; + this.lastPitch = this.pitch; + this.needSendRotation = true; + } - if (invalidMotion) { - this.revertClientMotion(this.getLocation()); + if (this.speed == null) speed = new Vector3(0, 0, 0); + else this.speed.setComponents(0, 0, 0); return; } - double diffX = clientPos.getX() - this.x; - double diffY = clientPos.getY() - this.y; - double diffZ = clientPos.getZ() - this.z; + int maxDist = 9; + if (this.riptideTicks > 95 || newPos.y - this.y < 2 || this.isOnLadder()) { // TODO: Remove ladder/vines check when block collisions are fixed + maxDist = 49; + } - // Client likes to clip into few blocks like stairs or slabs - // This should help reduce the server mis-prediction at least a bit - diffY += this.ySize * (1 - 0.4D); + if (distanceSquared > maxDist) { + this.revertClientMotion(this); + server.getLogger().debug(username + ": distanceSquared=" + distanceSquared + " > maxDist=" + maxDist); + return; + } - this.fastMove(diffX, diffY, diffZ); + if (this.chunk == null || !this.chunk.isGenerated()) { + BaseFullChunk chunk = this.level.getChunk(newPos.getChunkX(), newPos.getChunkZ(), false); + if (chunk == null || !chunk.isGenerated()) { + this.nextChunkOrderRun = 0; + this.revertClientMotion(this); + return; + } else { + if (this.chunk != null) { + this.chunk.removeEntity(this); + } + this.chunk = chunk; + } + } - double corrX = this.x - clientPos.getX(); - double corrY = this.y - clientPos.getY(); - double corrZ = this.z - clientPos.getZ(); + double dx = newPos.x - this.x; + double dy = newPos.y - this.y; + double dz = newPos.z - this.z; - double yS = this.getStepHeight() + this.ySize; - if (corrY >= -yS || corrY <= yS) { - corrY = 0; - } + //the client likes to clip into blocks like stairs, but we do full server-side prediction of that without + //help from the client's position changes, so we deduct the expected clip height from the moved distance. + dy += this.ySize * (1 - STEP_CLIP_MULTIPLIER); // FIXME: ySize is always 0 - if (this.checkMovement && (Math.abs(corrX) > 0.5 || Math.abs(corrY) > 0.5 || Math.abs(corrZ) > 0.5) && - this.riding == null && !this.hasEffect(Effect.LEVITATION) && !this.hasEffect(Effect.SLOW_FALLING)) { - double diff = corrX * corrX + corrZ * corrZ; - if (diff > 0.5) { - PlayerInvalidMoveEvent event = new PlayerInvalidMoveEvent(this, true); - this.getServer().getPluginManager().callEvent(event); - if (!event.isCancelled() && (invalidMotion = event.isRevert())) { - this.server.getLogger().warning(this.getServer().getLanguage().translateString("nukkit.player.invalidMove", this.getName())); + if (this.checkMovement && this.riptideTicks <= 0 && this.riding == null && !this.isGliding() && !this.getAllowFlight()) { + double hSpeed = dx * dx + dz * dz; + if (hSpeed > MAXIMUM_SPEED) { + PlayerInvalidMoveEvent ev; + this.getServer().getPluginManager().callEvent(ev = new PlayerInvalidMoveEvent(this, true)); + if (!ev.isCancelled()) { + server.getLogger().debug(username + ": hSpeed=" + hSpeed + " > MAXIMUM_SPEED=" + MAXIMUM_SPEED); + this.revertClientMotion(this); + return; } } + } - if (!invalidMotion) { - this.x = clientPos.getX(); - this.y = clientPos.getY(); - this.z = clientPos.getZ(); - double radius = this.getWidth() / 2; - this.boundingBox.setBounds(this.x - radius, this.y, this.z - radius, this.x + radius, this.y + this.getHeight(), this.z + radius); - } + // Replacement for this.fastMove(dx, dy, dz) start + if (this.isSpectator() || !this.level.hasCollision(this, this.boundingBox.getOffsetBoundingBox(dx, dy, dz).shrink(0.1, this.getStepHeight(), 0.1), false)) { + this.x = newPos.x; + this.y = newPos.y; + this.z = newPos.z; + + this.boundingBox.setBounds(this.x - 0.3, this.y, this.z - 0.3, this.x + 0.3, this.y + this.getHeight(), this.z + 0.3); } - if (invalidMotion) { - this.revertClientMotion(this.getLocation()); - return; + this.checkChunks(); + + if (!this.isSpectator() && (!this.onGround || dy != 0)) { + AxisAlignedBB bb = this.boundingBox.clone(); + bb.setMinY(bb.getMinY() - 0.75); + + // Hack: fix fall damage from walls while falling + if (Math.abs(dy) > 0.01) { + bb.setMinX(bb.getMinX() + 0.1); + bb.setMaxX(bb.getMaxX() - 0.1); + bb.setMinZ(bb.getMinZ() + 0.1); + bb.setMaxZ(bb.getMaxZ() - 0.1); + } + + this.onGround = this.level.hasCollisionBlocks(this, bb); } - Location source = new Location(this.lastX, this.lastY, this.lastZ, this.lastYaw, this.lastPitch, this.level); - Location target = this.getLocation(); - double delta = Math.pow(this.lastX - target.getX(), 2) + Math.pow(this.lastY - target.getY(), 2) + Math.pow(this.lastZ - target.getZ(), 2); - double deltaAngle = Math.abs(this.lastYaw - target.getYaw()) + Math.abs(this.lastPitch - target.getPitch()); + this.isCollided = this.onGround; + this.updateFallState(this.onGround); + // Replacement for this.fastMove(dx, dy, dz) end + + Location from = new Location( + this.lastX, + this.lastY, + this.lastZ, + this.lastYaw, + this.lastPitch, + this.level); + Location to = this.getLocation(); + + if (!this.firstMove) { + PlayerMoveEvent moveEvent = new PlayerMoveEvent(this, from, to); + this.server.getPluginManager().callEvent(moveEvent); + + if (moveEvent.isCancelled()) { + this.teleport(from, null); + return; + } + + this.lastX = to.x; + this.lastY = to.y; + this.lastZ = to.z; - if (delta > 0.0005 || deltaAngle > 1) { - boolean isFirst = this.firstMove; - this.firstMove = false; + this.lastYaw = to.yaw; + this.lastPitch = to.pitch; - this.lastX = target.x; - this.lastY = target.y; - this.lastZ = target.z; - this.lastYaw = target.yaw; - this.lastPitch = target.pitch; + this.blocksAround = null; + this.collisionBlocks = null; - if (!isFirst) { - List blocksAround = null; - if (this.blocksAround != null) { - blocksAround = new ObjectArrayList<>(this.blocksAround); - } - List collidingBlocks = null; - if (this.collisionBlocks != null) { - collidingBlocks = new ObjectArrayList<>(this.collisionBlocks); - } + if (!to.equals(moveEvent.getTo())) { // If plugins modify the destination + this.teleport(moveEvent.getTo(), null); + } else { + this.addMovement(this.x, this.y, this.z, this.yaw, this.pitch, this.yaw); + } + } else { + this.lastX = to.x; + this.lastY = to.y; + this.lastZ = to.z; + + this.lastYaw = to.yaw; + this.lastPitch = to.pitch; + } + + this.firstMove = false; - PlayerMoveEvent event = new PlayerMoveEvent(this, source, target); - this.blocksAround = null; - this.collisionBlocks = null; - this.server.getPluginManager().callEvent(event); + if (this.speed == null) speed = new Vector3(from.x - to.x, from.y - to.y, from.z - to.z); + else this.speed.setComponents(from.x - to.x, from.y - to.y, from.z - to.z); - if (!(invalidMotion = event.isCancelled())) { - if (!target.equals(event.getTo())) { - this.teleport(event.getTo(), null); + if (this.riding == null && this.inventory != null) { + if (this.isFoodEnabled() && this.getServer().getDifficulty() > 0) { + if (distanceSquared >= 0.05) { + double jump = 0; + double swimming = this.isInsideOfWater() ? 0.01 * distanceSquared : 0; + double dd = distanceSquared; + if (swimming != 0) dd = 0; + if (this.isSprinting()) { + if (this.inAirTicks == 3 && swimming == 0) { + jump = 0.2; + } + this.foodData.updateFoodExpLevel(0.1 * dd + jump + swimming); } else { - this.addMovement(this.x, this.y, this.z, this.yaw, this.pitch, this.yaw); + if (this.inAirTicks == 3 && swimming == 0) { + jump = 0.05; + } + this.foodData.updateFoodExpLevel(jump + swimming); } - } else { - this.blocksAround = blocksAround; - this.collisionBlocks = collidingBlocks; } } - if (this.speed == null) { - this.speed = new Vector3(source.x - target.x, source.y - target.y, source.z - target.z); - } else { - this.speed.setComponents(source.x - target.x, source.y - target.y, source.z - target.z); + Item boots = this.inventory.getBootsFast(); + + Enchantment frostWalker = boots.getEnchantment(Enchantment.ID_FROST_WALKER); + if (frostWalker != null && frostWalker.getLevel() > 0 && !this.isSpectator() && this.y > this.level.getMinBlockY() && this.y <= this.level.getMaxBlockY()) { + int radius = 2 + frostWalker.getLevel(); + for (int coordX = this.getFloorX() - radius; coordX < this.getFloorX() + radius + 1; coordX++) { + for (int coordZ = this.getFloorZ() - radius; coordZ < this.getFloorZ() + radius + 1; coordZ++) { + Block block = level.getBlock(this.chunk, coordX, this.getFloorY() - 1, coordZ, true); + if ((block.getId() == Block.STILL_WATER || block.getId() == Block.WATER && block.getDamage() == 0) && block.up().getId() == Block.AIR) { + WaterFrostEvent waterFrostEvent = new WaterFrostEvent(block); + server.getPluginManager().callEvent(waterFrostEvent); + if (!waterFrostEvent.isCancelled()) { + level.setBlockAt((int) block.x, (int) block.y, (int) block.z, Block.ICE_FROSTED, 0); + level.scheduleUpdate(level.getBlock(this.chunk, block.getFloorX(), block.getFloorY(), block.getFloorZ(), true), Utils.random.nextInt(20, 40)); + } + } + } + } } - } else { - if (this.speed == null) speed = new Vector3(0, 0, 0); - else this.speed.setComponents(0, 0, 0); - } - if ((this.isFoodEnabled() || this.getServer().getDifficulty() == 0) && distance >= 0.05 && this.riding == null) { - double jump = 0; - double swimming = this.isInsideOfWater() ? 0.015 * distance : 0; - double distance2 = distance; - if (swimming != 0) distance2 = 0; - if (this.isSprinting()) { - if (this.inAirTicks == 3 && swimming == 0) { - jump = 0.2; - } - this.getFoodData().updateFoodExpLevel(0.1 * distance2 + jump + swimming); - } else { - if (this.inAirTicks == 3 && swimming == 0) { - jump = 0.05; + Enchantment soulSpeedEnchantment = boots.getEnchantment(Enchantment.ID_SOUL_SPEED); + if (soulSpeedEnchantment != null && soulSpeedEnchantment.getLevel() > 0) { + int down = this.getLevel().getBlockIdAt(chunk, getFloorX(), getFloorY() - 1, getFloorZ()); + if (this.inSoulSand && down != BlockID.SOUL_SAND) { + this.inSoulSand = false; + this.setMovementSpeed(DEFAULT_SPEED, true); + } else if (!this.inSoulSand && down == BlockID.SOUL_SAND) { + this.inSoulSand = true; + float soulSpeed = (soulSpeedEnchantment.getLevel() * 0.105f) + 1.3f; + this.setMovementSpeed(DEFAULT_SPEED * soulSpeed, true); } - this.getFoodData().updateFoodExpLevel(jump + swimming); } } this.forceMovement = null; - if (distance != 0 && this.nextChunkOrderRun > 20) { + if (distanceSquared != 0 && this.nextChunkOrderRun > 20) { this.nextChunkOrderRun = 20; } + this.needSendRotation = false; // Sent with movement + this.resetClientMovement(); } + @Override + public void recalculateBoundingBox(boolean send) { + double height = isSwimming() || isGliding() || isCrawling() ? 0.6 : isSneaking() ? 1.5 : 1.8; + this.boundingBox.setBounds( + this.x - 0.3, + this.y + this.ySize, + z - 0.3, + x + 0.3, + y + height + this.ySize, + z + 0.3 + ); + + if (send) { + FloatEntityData bbH = new FloatEntityData(DATA_BOUNDING_BOX_HEIGHT, (float) height); + FloatEntityData bbW = new FloatEntityData(DATA_BOUNDING_BOX_WIDTH, this.getWidth()); + this.dataProperties.put(bbH); + this.dataProperties.put(bbW); + sendData(this.hasSpawned.values().toArray(new Player[0]), new EntityMetadata().put(bbH).put(bbW)); + } + } + protected void resetClientMovement() { this.newPosition = null; } @@ -1588,11 +2129,10 @@ protected void revertClientMotion(Location originalPos) { this.lastZ = originalPos.getZ(); this.lastYaw = originalPos.getYaw(); this.lastPitch = originalPos.getPitch(); - Vector3 syncPos = originalPos.add(0, 0.00001, 0); + this.needSendRotation = false; this.sendPosition(syncPos, originalPos.getYaw(), originalPos.getPitch(), MovePlayerPacket.MODE_RESET); this.forceMovement = syncPos; - if (this.speed == null) { this.speed = new Vector3(0, 0, 0); } else { @@ -1600,31 +2140,25 @@ protected void revertClientMotion(Location originalPos) { } } - @Override - public double getStepHeight() { - return 0.6f; - } - @Override public void addMovement(double x, double y, double z, double yaw, double pitch, double headYaw) { - this.sendPosition(new Vector3(x, y, z), yaw, pitch, MovePlayerPacket.MODE_NORMAL, this.getViewers().values().toArray(new Player[0])); + this.sendPositionToViewers(x, y, z, yaw, pitch, headYaw); } @Override public boolean setMotion(Vector3 motion) { if (super.setMotion(motion)) { - if (this.chunk != null) { - this.addMotion(this.motionX, this.motionY, this.motionZ); //Send to others + if (this.chunk != null && this.spawned) { + this.addMotion(this.motionX, this.motionY, this.motionZ); // Send to others SetEntityMotionPacket pk = new SetEntityMotionPacket(); pk.eid = this.id; pk.motionX = (float) motion.x; pk.motionY = (float) motion.y; pk.motionZ = (float) motion.z; - this.dataPacket(pk); //Send to self + this.dataPacket(pk); } if (this.motionY > 0) { - //todo: check this this.startAirTicks = (int) ((-(Math.log(this.getGravity() / (this.getGravity() + this.getDrag() * this.motionY))) / this.getDrag()) * 2 + 5); } @@ -1634,15 +2168,41 @@ public boolean setMotion(Vector3 motion) { return false; } + /** + * Set player's server side motion. Does not send updated motion to client. + * @param motion new motion vector + */ + public void setMotionLocally(Vector3 motion) { + if (!this.justCreated) { + EntityMotionEvent ev = new EntityMotionEvent(this, motion); + this.server.getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + return; + } + } + + this.motionX = motion.x; + this.motionY = motion.y; + this.motionZ = motion.z; + + if (this.motionY > 0) { + this.startAirTicks = (int) ((-(Math.log(this.getGravity() / (this.getGravity() + this.getDrag() * this.motionY))) / this.getDrag()) * 2 + 5); + } + } + + /** + * Send all default attributes + */ public void sendAttributes() { + int healthMax = this.getMaxHealth(); UpdateAttributesPacket pk = new UpdateAttributesPacket(); pk.entityId = this.getId(); pk.entries = new Attribute[]{ - Attribute.getAttribute(Attribute.MAX_HEALTH).setMaxValue(this.getMaxHealth()).setValue(health > 0 ? (health < getMaxHealth() ? health : getMaxHealth()) : 0), - Attribute.getAttribute(Attribute.MAX_HUNGER).setValue(this.getFoodData().getLevel()), - Attribute.getAttribute(Attribute.MOVEMENT_SPEED).setValue(this.getMovementSpeed()), - Attribute.getAttribute(Attribute.EXPERIENCE_LEVEL).setValue(this.getExperienceLevel()), - Attribute.getAttribute(Attribute.EXPERIENCE).setValue(((float) this.getExperience()) / calculateRequireExperience(this.getExperienceLevel())) + Attribute.getAttribute(Attribute.MAX_HEALTH).setMaxValue(healthMax).setValue(health > 0 ? (health < healthMax ? health : healthMax) : 0), + Attribute.getAttribute(Attribute.MAX_HUNGER).setValue(this.foodData.getLevel()).setDefaultValue(this.foodData.getMaxLevel()), + Attribute.getAttribute(Attribute.MOVEMENT_SPEED).setValue(this.getMovementSpeed()).setDefaultValue(this.getMovementSpeed()), + Attribute.getAttribute(Attribute.EXPERIENCE_LEVEL).setValue(this.expLevel), + Attribute.getAttribute(Attribute.EXPERIENCE).setValue(((float) this.exp) / calculateRequireExperience(this.expLevel)) }; this.dataPacket(pk); } @@ -1659,21 +2219,23 @@ public boolean onUpdate(int currentTick) { return true; } - this.messageCounter = 2; - this.lastUpdate = currentTick; - if (this.fishing != null && this.server.getTick() % 20 == 0) { - if (this.distance(fishing) > 33) { + if (this.riptideTicks > 0) { + this.riptideTicks -= tickDiff; + } + + if (this.fishing != null && this.age % 10 == 0) { + if (this.distanceSquared(fishing) > 1089) { // 33 blocks this.stopFishing(false); } } if (!this.isAlive() && this.spawned) { - ++this.deadTicks; - if (this.deadTicks >= 10) { - this.despawnFromAll(); - } + //++this.deadTicks; + //if (this.deadTicks >= 10) { + this.despawnFromAll(); // HACK: fix "dead" players + //} return true; } @@ -1682,96 +2244,162 @@ public boolean onUpdate(int currentTick) { this.handleMovement(this.clientMovements.poll()); } - if (!this.isSpectator()) { + if (this.needSendRotation) { + this.addMovement(this.x, this.y, this.z, this.yaw, this.pitch, this.yaw); + this.needSendRotation = false; + } + + this.motionX = this.motionY = this.motionZ = 0; // HACK: fix player knockback being messed up + + if (!this.isSpectator() && this.isAlive()) { this.checkNearEntities(); } this.entityBaseTick(tickDiff); if (this.getServer().getDifficulty() == 0 && this.level.getGameRules().getBoolean(GameRule.NATURAL_REGENERATION)) { - if (this.getHealth() < this.getMaxHealth() && this.ticksLived % 20 == 0) { + if (this.getHealth() < this.getRealMaxHealth() && this.age % 20 == 0) { this.heal(1); } - PlayerFood foodData = this.getFoodData(); - - if (foodData.getLevel() < 20 && this.ticksLived % 10 == 0) { - foodData.addFoodLevel(1, 0); + if (this.foodData.getLevel() < 20 && this.age % 10 == 0) { + this.foodData.addFoodLevel(1, 0); } } - if (this.isOnFire() && this.lastUpdate % 10 == 0) { + if (this.isOnFire() && this.age % 10 == 0) { if (this.isCreative() && !this.isInsideOfFire()) { this.extinguish(); - } else if (this.getLevel().isRaining()) { - if (this.getLevel().canBlockSeeSky(this)) { - this.extinguish(); - } + } else if (this.getLevel().isRaining() && this.canSeeSky()) { + this.extinguish(); } } if (!this.isSpectator() && this.speed != null) { if (this.onGround) { + + // 1.20.10 doesn't stop it automatically if (this.isGliding()) { this.setGliding(false); } this.resetFallDistance(); } else { - if (this.checkMovement && !this.isGliding() && !server.getAllowFlight() && !this.getAdventureSettings().get(Type.ALLOW_FLIGHT) && this.inAirTicks > 20 && !this.isSleeping() && !this.isImmobile() && !this.isSwimming() && this.riding == null && !this.hasEffect(Effect.LEVITATION) && !this.hasEffect(Effect.SLOW_FALLING)) { + if (this.checkMovement && this.riptideTicks < 1 && !this.isGliding() && !server.getAllowFlight() && this.inAirTicks > 20 && !this.getAllowFlight() && !this.isSleeping() && !this.isImmobile() && !this.isSwimming() && this.riding == null && !this.hasEffect(Effect.LEVITATION) && !this.hasEffect(Effect.SLOW_FALLING) && this.speed != null && !(this.speed.x == 0 && this.speed.y == 0 && this.speed.z == 0)) { double expectedVelocity = (-this.getGravity()) / ((double) this.getDrag()) - ((-this.getGravity()) / ((double) this.getDrag())) * Math.exp(-((double) this.getDrag()) * ((double) (this.inAirTicks - this.startAirTicks))); - double diff = (this.speed.y - expectedVelocity) * (this.speed.y - expectedVelocity); - - int block = this.getLevelBlock().getId(); - boolean ignore = block == Block.LADDER || block == Block.VINES || block == Block.COBWEB; - - if (!this.hasEffect(Effect.JUMP) && diff > 0.6 && expectedVelocity < this.speed.y && !ignore) { - if (this.inAirTicks < 150) { - this.setMotion(new Vector3(0, expectedVelocity, 0)); - } else if (this.kick(PlayerKickEvent.Reason.FLYING_DISABLED, "Flying is not enabled on this server")) { + double diff = Math.abs(Math.abs(expectedVelocity) - Math.abs(this.speed.y)); + + if (diff > 1 && expectedVelocity < 0) { + if (this.inAirTicks < 200) { + PlayerInvalidMoveEvent ev = new PlayerInvalidMoveEvent(this, true); + this.getServer().getPluginManager().callEvent(ev); + if (!ev.isCancelled()) { + this.startAirTicks = this.inAirTicks - 10; + this.setMotion(new Vector3(0, expectedVelocity, 0)); + } + } else if (this.kick(PlayerKickEvent.Reason.FLYING_DISABLED, MSG_FLYING_NOT_ENABLED, true)) { return false; } } - if (ignore) { - this.resetFallDistance(); - } } if (this.y > highestPosition) { this.highestPosition = this.y; } - if (this.isGliding()) this.resetFallDistance(); - - ++this.inAirTicks; - + if (this.isSwimming() || this.isOnLadder() || (this.isGliding() && this.getPitch() <= 40 && Math.abs(this.speed.y) < 0.5)) { + this.resetFallDistance(); + } else if (this.isGliding()) { + this.resetInAirTicks(); + } else { + ++this.inAirTicks; + } } - if (this.isSurvival() || this.isAdventure()) { - if (this.getFoodData() != null) this.getFoodData().update(tickDiff); + if (this.foodData != null) { + this.foodData.update(tickDiff); } } + } - if (!this.isSleeping()) { - this.timeSinceRest++; + if (this.age % 20 == 0) { + if (this.isGliding()) { + PlayerInventory inv = this.getInventory(); + if (inv != null) { + Item elytra = inv.getChestplate(); + if (elytra == null || elytra.getId() != ItemID.ELYTRA) { + this.setGliding(false); + } else if ((this.gamemode & 0x01) == 0 && this.age % (20 * (elytra.getEnchantmentLevel(Enchantment.ID_DURABILITY) + 1)) == 0) { + elytra.setDamage(elytra.getDamage() + 1); + if (elytra.getDamage() >= elytra.getMaxDurability()) { + this.setGliding(false); + } + inv.setChestplate(elytra); + } + } } } + if (this.fireworkBoostTicks > 0) { + this.fireworkBoostTicks -= tickDiff; + + double multiplier = 1 + 0.25 * (this.fireworkBoostLevel < 1 ? 0.25 : this.fireworkBoostLevel); + this.setMotion(new Vector3( + -Math.sin(Math.toRadians(this.yaw)) * Math.cos(Math.toRadians(this.pitch)) * multiplier, + -Math.sin(Math.toRadians(this.pitch)) * multiplier, + Math.cos(Math.toRadians(this.yaw)) * Math.cos(Math.toRadians(this.pitch)) * multiplier)); + } + + if (this.age % 5 == 0 && this.isBreakingBlock() && !this.isCreative()) { + //this.level.addLevelSoundEvent(this.breakingBlock, LevelSoundEventPacket.SOUND_HIT, blockRuntimeId); + this.level.addParticle(new PunchBlockParticle(this.breakingBlock, this.breakingBlock, this.breakingBlockFace)); + } + this.checkTeleportPosition(); - if (this.spawned && this.dummyBossBars.size() > 0 && currentTick % 100 == 0) { + if (this.spawned && !this.dummyBossBars.isEmpty() && currentTick % 100 == 0) { this.dummyBossBars.values().forEach(DummyBossBar::updateBossEntityPosition); } + this.tickShield(tickDiff); + + if (!this.isSleeping()) { + this.timeSinceRest += tickDiff; + } + return true; } + /** + * Update shield blocking status + */ + private void tickShield(int tickDiff) { + if (!this.canTickShield) { + return; + } + if (this.blockingDelay > 0) { + this.blockingDelay -= tickDiff; + } + boolean shieldInHand = this.getInventory().getItemInHandFast().getId() == ItemID.SHIELD; + boolean shieldInOffhand = this.getOffhandInventory().getItemFast(0).getId() == ItemID.SHIELD; + if (this.isBlocking()) { + if (!this.isSneaking() || (!shieldInHand && !shieldInOffhand)) { + this.setBlocking(false); + } + } else if (this.blockingDelay <= 0 && this.isSneaking() && (shieldInHand || shieldInOffhand)) { + this.setBlocking(true); + } + } + + /** + * Update interaction button text + */ public void checkInteractNearby() { int interactDistance = isCreative() ? 5 : 3; if (canInteract(this, interactDistance)) { - if (getEntityPlayerLookingAt(interactDistance) != null) { - EntityInteractable onInteract = getEntityPlayerLookingAt(interactDistance); - String buttonText = onInteract.getInteractButtonText(this); + EntityInteractable e = getEntityPlayerLookingAt(interactDistance); + if (e != null) { + String buttonText = e.getInteractButtonText(this); if (buttonText == null) { buttonText = ""; } @@ -1791,8 +2419,6 @@ public void checkInteractNearby() { * @return Entity|null either NULL if no entity is found or an instance of the entity */ public EntityInteractable getEntityPlayerLookingAt(int maxDistance) { - timing.startTiming(); - EntityInteractable entity = null; // just a fix because player MAY not be fully initialized @@ -1812,17 +2438,13 @@ public EntityInteractable getEntityPlayerLookingAt(int maxDistance) { } } } - } catch (Exception ex) { - // nothing to log here! - } + } catch (Exception ignored) {} } - timing.stopTiming(); - return entity; } - private EntityInteractable getEntityAtPosition(Entity[] nearbyEntities, int x, int y, int z) { + private static EntityInteractable getEntityAtPosition(Entity[] nearbyEntities, int x, int y, int z) { for (Entity nearestEntity : nearbyEntities) { if (nearestEntity.getFloorX() == x && nearestEntity.getFloorY() == y && nearestEntity.getFloorZ() == z && nearestEntity instanceof EntityInteractable @@ -1833,6 +2455,9 @@ private EntityInteractable getEntityAtPosition(Entity[] nearbyEntities, int x, i return null; } + /** + * Internal: Process chunk sending + */ public void checkNetwork() { if (!this.isOnline()) { return; @@ -1847,68 +2472,122 @@ public void checkNetwork() { } } + /** + * Check whether target is too far away to be interacted with + * @param pos target position + * @param maxDistance maximum distance + * @return can interact + */ public boolean canInteract(Vector3 pos, double maxDistance) { return this.canInteract(pos, maxDistance, 6.0); } + /** + * Check whether target is too far away to be interacted with + * @param pos target position + * @param maxDistance maximum distance + * @param maxDiff maximum diff + * @return can interact + */ public boolean canInteract(Vector3 pos, double maxDistance, double maxDiff) { if (this.distanceSquared(pos) > maxDistance * maxDistance) { return false; } Vector2 dV = this.getDirectionPlane(); - double dot = dV.dot(new Vector2(this.x, this.z)); - double dot1 = dV.dot(new Vector2(pos.x, pos.z)); - return (dot1 - dot) >= -maxDiff; + return (dV.dot(new Vector2(pos.x, pos.z)) - dV.dot(new Vector2(this.x, this.z))) >= -maxDiff; + } + + private boolean canInteractEntity(Vector3 pos, double maxDistanceSquared) { + if (this.distanceSquared(pos) > maxDistanceSquared) { + return false; + } + + Vector2 dV = this.getDirectionPlane(); + return (dV.dot(new Vector2(pos.x, pos.z)) - dV.dot(new Vector2(this.x, this.z))) >= -0.87; + } + + protected void processPreLogin() { + this.loginVerified = true; + final Player playerInstance = this; + + this.preLoginEventTask = new AsyncTask() { + private PlayerAsyncPreLoginEvent event; + + @Override + public void onRun() { + this.event = new PlayerAsyncPreLoginEvent(username, uuid, loginChainData, skin, playerInstance.getAddress(), playerInstance.getPort()); + server.getPluginManager().callEvent(this.event); + } + + @Override + public void onCompletion(Server server) { + if (!playerInstance.connected) { + return; + } + + if (this.event.getLoginResult() == LoginResult.KICK) { + playerInstance.close(this.event.getKickMessage(), this.event.getKickMessage()); + } else if (playerInstance.shouldLogin) { + try { + playerInstance.setSkin(this.event.getSkin()); + playerInstance.completeLoginSequence(); + for (Consumer action : this.event.getScheduledActions()) { + action.accept(server); + } + } catch (Exception ex) { + server.getLogger().logException(ex); + playerInstance.close("", "Internal Server Error"); + } + } + } + }; + + this.server.getScheduler().scheduleAsyncTask(null, this.preLoginEventTask); + + try { + this.processLogin(); + } catch (Exception ex) { + this.server.getLogger().logException(ex); + this.close("", "Internal Server Error"); + } } protected void processLogin() { - if (!this.server.isWhitelisted((this.getName()).toLowerCase())) { + String lowerName = this.iusername; + if (!this.server.isWhitelisted(lowerName)) { this.kick(PlayerKickEvent.Reason.NOT_WHITELISTED, "Server is white-listed"); - return; } else if (this.isBanned()) { - String reason = this.server.getNameBans().getEntires().get(this.getName().toLowerCase()).getReason(); - this.kick(PlayerKickEvent.Reason.NAME_BANNED, !reason.isEmpty() ? "You are banned. Reason: " + reason : "You are banned"); + String reason = this.server.getNameBans().getEntires().get(lowerName).getReason(); + this.kick(PlayerKickEvent.Reason.NAME_BANNED, "You are banned!" + (reason.isEmpty() ? "" : (" Reason: " + reason))); return; } else if (this.server.getIPBans().isBanned(this.getAddress())) { - String reason = this.server.getIPBans().getEntires().get(this.getAddress()).getReason(); - this.kick(PlayerKickEvent.Reason.IP_BANNED, !reason.isEmpty() ? "You are banned. Reason: " + reason : "You are banned"); + this.kick(PlayerKickEvent.Reason.IP_BANNED, "Your IP is banned!"); return; } - if (this.hasPermission(Server.BROADCAST_CHANNEL_USERS)) { - this.server.getPluginManager().subscribeToPermission(Server.BROADCAST_CHANNEL_USERS, this); - } - if (this.hasPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE)) { - this.server.getPluginManager().subscribeToPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE, this); - } - - Player oldPlayer = null; - for (Player p : new ArrayList<>(this.server.getOnlinePlayers().values())) { - if (p != this && p.getName() != null && p.getName().equalsIgnoreCase(this.getName()) || - this.getUniqueId().equals(p.getUniqueId())) { - oldPlayer = p; - break; + for (Player p : new ArrayList<>(this.server.playerList.values())) { + if (p != this && p.username != null) { + if (p.username.equalsIgnoreCase(this.username) || this.getUniqueId().equals(p.getUniqueId())) { + p.close("", "disconnectionScreen.loggedinOtherLocation"); + break; + } } } - CompoundTag nbt; - if (oldPlayer != null) { - oldPlayer.saveNBT(); - nbt = oldPlayer.namedTag; - oldPlayer.close("", "disconnectionScreen.loggedinOtherLocation"); - } else { - File legacyDataFile = new File(server.getDataPath() + "players/" + this.username.toLowerCase() + ".dat"); - File dataFile = new File(server.getDataPath() + "players/" + this.uuid.toString() + ".dat"); - if (legacyDataFile.exists() && !dataFile.exists()) { - nbt = this.server.getOfflinePlayerData(this.username, false); - if (!legacyDataFile.delete()) { - log.warn("Could not delete legacy player data for {}", this.username); - } - } else { - nbt = this.server.getOfflinePlayerData(this.uuid, true); + CompoundTag nbt; + File legacyDataFile = new File(server.getDataPath() + "players/" + lowerName + ".dat"); + File dataFile = new File(server.getDataPath() + "players/" + this.uuid.toString() + ".dat"); + + boolean dataFound = dataFile.exists(); + if (!dataFound && legacyDataFile.exists()) { + nbt = this.server.getOfflinePlayerData(lowerName, false); + if (!legacyDataFile.delete()) { + this.server.getLogger().warning("Could not delete legacy player data for " + this.username); } + } else { + nbt = this.server.getOfflinePlayerData(this.uuid, !dataFound); } if (nbt == null) { @@ -1916,47 +2595,60 @@ protected void processLogin() { return; } - if (loginChainData.isXboxAuthed() && server.getPropertyBoolean("xbox-auth") || !server.getPropertyBoolean("xbox-auth")) { + if (loginChainData.isXboxAuthed() || !server.xboxAuth) { server.updateName(this.uuid, this.username); } this.playedBefore = (nbt.getLong("lastPlayed") - nbt.getLong("firstPlayed")) > 1; - nbt.putString("NameTag", this.username); - int exp = nbt.getInt("EXP"); - int expLevel = nbt.getInt("expLevel"); - this.setExperience(exp, expLevel); + this.setExperience(nbt.getInt("EXP"), nbt.getInt("expLevel")); - this.gamemode = nbt.getInt("playerGameType") & 0x03; if (this.server.getForceGamemode()) { this.gamemode = this.server.getGamemode(); nbt.putInt("playerGameType", this.gamemode); + } else { + this.gamemode = nbt.getInt("playerGameType") & 0x03; } this.adventureSettings = new AdventureSettings(this) .set(Type.WORLD_IMMUTABLE, isAdventure() || isSpectator()) .set(Type.MINE, !isAdventure() && !isSpectator()) .set(Type.BUILD, !isAdventure() && !isSpectator()) - .set(Type.NO_PVM, this.isSpectator()) + .set(Type.NO_PVM, isSpectator()) .set(Type.AUTO_JUMP, true) .set(Type.ALLOW_FLIGHT, isCreative() || isSpectator()) .set(Type.NO_CLIP, isSpectator()) .set(Type.FLYING, isSpectator()); Level level; - if ((level = this.server.getLevelByName(nbt.getString("Level"))) == null) { + if ((level = this.server.getLevelByName(nbt.getString("Level"))) == null || nbt.getShort("Health") < 1) { this.setLevel(this.server.getDefaultLevel()); nbt.putString("Level", this.level.getName()); + Vector3 sp = this.level.getProvider().getSpawn(); nbt.getList("Pos", DoubleTag.class) - .add(new DoubleTag("0", this.level.getSpawnLocation().x)) - .add(new DoubleTag("1", this.level.getSpawnLocation().y)) - .add(new DoubleTag("2", this.level.getSpawnLocation().z)); + .add(new DoubleTag("0", sp.x)) + .add(new DoubleTag("1", sp.y)) + .add(new DoubleTag("2", sp.z)); } else { this.setLevel(level); } + if (nbt.contains("SpawnLevel")) { + Level spawnLevel = server.getLevelByName(nbt.getString("SpawnLevel")); + if (spawnLevel != null) { + this.spawnPosition = new Position( + nbt.getInt("SpawnX"), + nbt.getInt("SpawnY"), + nbt.getInt("SpawnZ"), + spawnLevel + ); + } + } + + this.timeSinceRest = nbt.getInt("TimeSinceRest"); + for (Tag achievement : nbt.getCompound("Achievements").getAllTags()) { if (!(achievement instanceof ByteTag)) { continue; @@ -1978,21 +2670,20 @@ protected void processLogin() { } this.sendPlayStatus(PlayStatusPacket.LOGIN_SUCCESS); - this.server.onPlayerLogin(this); ListTag posList = nbt.getList("Pos", DoubleTag.class); - super.init(this.level.getChunk((int) posList.get(0).data >> 4, (int) posList.get(2).data >> 4, true), nbt); + super.init(this.level.getChunk(NukkitMath.floorDouble(posList.get(0).data) >> 4, NukkitMath.floorDouble(posList.get(2).data) >> 4, true), nbt); if (!this.namedTag.contains("foodLevel")) { this.namedTag.putInt("foodLevel", 20); } - int foodLevel = this.namedTag.getInt("foodLevel"); + if (!this.namedTag.contains("foodSaturationLevel")) { this.namedTag.putFloat("foodSaturationLevel", 20); } - float foodSaturationLevel = this.namedTag.getFloat("foodSaturationLevel"); - this.foodData = new PlayerFood(this, foodLevel, foodSaturationLevel); + + this.foodData = new PlayerFood(this, this.namedTag.getInt("foodLevel"), this.namedTag.getFloat("foodSaturationLevel")); if (this.isSpectator()) { this.keepMovement = true; @@ -2001,11 +2692,6 @@ protected void processLogin() { this.forceMovement = this.teleportPosition = this.getPosition(); - if (!this.namedTag.contains("TimeSinceRest")) { - this.namedTag.putInt("TimeSinceRest", 0); - } - this.timeSinceRest = this.namedTag.getInt("TimeSinceRest"); - ResourcePacksInfoPacket infoPacket = new ResourcePacksInfoPacket(); infoPacket.resourcePackEntries = this.server.getResourcePackManager().getResourceStack(); infoPacket.mustAccept = this.server.getForceResources(); @@ -2013,6 +2699,11 @@ protected void processLogin() { } protected void completeLoginSequence() { + if (this.loggedIn) { + this.server.getLogger().warning("Tried to call completeLoginSequence but player is already logged in: " + this.username); + return; + } + PlayerLoginEvent ev; this.server.getPluginManager().callEvent(ev = new PlayerLoginEvent(this, "Plugin reason")); if (ev.isCancelled()) { @@ -2020,15 +2711,10 @@ protected void completeLoginSequence() { return; } - Level level = this.server.getLevelByName(this.namedTag.getString("SpawnLevel")); - if(level != null){ - this.spawnPosition = new Position(this.namedTag.getInt("SpawnX"), this.namedTag.getInt("SpawnY"), this.namedTag.getInt("SpawnZ"), level); - }else{ - this.spawnPosition = this.level.getSafeSpawn(); + if (this.isClosed() || !this.isConnected()) { + return; // Player was probably disconnected by a plugin } - spawnPosition = this.getSpawn(); - StartGamePacket startGamePacket = new StartGamePacket(); startGamePacket.entityUniqueId = this.id; startGamePacket.entityRuntimeId = this.id; @@ -2038,174 +2724,232 @@ protected void completeLoginSequence() { startGamePacket.z = (float) this.z; startGamePacket.yaw = (float) this.yaw; startGamePacket.pitch = (float) this.pitch; - startGamePacket.seed = -1; - startGamePacket.dimension = /*(byte) (this.level.getDimension() & 0xff)*/0; + startGamePacket.dimension = (byte) (this.level.getDimension() & 0xff); startGamePacket.worldGamemode = getClientFriendlyGamemode(this.gamemode); startGamePacket.difficulty = this.server.getDifficulty(); - startGamePacket.spawnX = spawnPosition.getFloorX(); - startGamePacket.spawnY = spawnPosition.getFloorY(); - startGamePacket.spawnZ = spawnPosition.getFloorZ(); - startGamePacket.hasAchievementsDisabled = true; - startGamePacket.dayCycleStopTime = -1; - startGamePacket.rainLevel = 0; - startGamePacket.lightningLevel = 0; - startGamePacket.commandsEnabled = this.isEnableClientCommand(); - startGamePacket.gameRules = getLevel().getGameRules(); - startGamePacket.levelId = ""; + if (this.level.getProvider() == null || this.level.getProvider().getSpawn() == null) { + startGamePacket.spawnX = (int) this.x; + startGamePacket.spawnY = (int) this.y; + startGamePacket.spawnZ = (int) this.z; + } else { + Vector3 spawn = this.level.getProvider().getSpawn(); + startGamePacket.spawnX = (int) spawn.x; + startGamePacket.spawnY = (int) spawn.y; + startGamePacket.spawnZ = (int) spawn.z; + } + startGamePacket.commandsEnabled = this.enableClientCommand; + startGamePacket.gameRules = this.getLevel().getGameRules(); startGamePacket.worldName = this.getServer().getNetwork().getName(); - startGamePacket.generator = 1; //0 old, 1 infinite, 2 flat - startGamePacket.isMovementServerAuthoritative = true; - this.dataPacket(startGamePacket); + if (this.getLevel().isRaining()) { + startGamePacket.rainLevel = this.getLevel().getRainTime(); + if (this.getLevel().isThundering()) { + startGamePacket.lightningLevel = this.getLevel().getThunderTime(); + } + } - this.dataPacket(new BiomeDefinitionListPacket()); - this.dataPacket(new AvailableEntityIdentifiersPacket()); - this.inventory.sendCreativeContents(); - this.getAdventureSettings().update(); + this.forceDataPacket(startGamePacket, null); - this.sendAttributes(); + this.loggedIn = true; - this.sendPotionEffects(this); + this.server.getLogger().info(this.getServer().getLanguage().translateString("nukkit.player.logIn", + TextFormat.AQUA + this.username + TextFormat.WHITE, + this.getAddress(), + String.valueOf(this.getPort()), + String.valueOf(this.id), + this.level.getName(), + String.valueOf(this.getFloorX()), + String.valueOf(this.getFloorY()), + String.valueOf(this.getFloorZ()))); + + this.setDataFlag(DATA_FLAGS, DATA_FLAG_CAN_CLIMB, true, false); + this.setDataFlag(DATA_FLAGS, DATA_FLAG_CAN_SHOW_NAMETAG, true, false); + this.setDataProperty(new ByteEntityData(DATA_ALWAYS_SHOW_NAMETAG, 1), false); if (this.isSpectator()) { - this.setDataFlag(DATA_FLAGS, DATA_FLAG_SILENT, true); - this.setDataFlag(DATA_FLAGS, DATA_FLAG_HAS_COLLISION, false); + this.setDataFlag(DATA_FLAGS, DATA_FLAG_SILENT, true, false); + this.setDataFlag(DATA_FLAGS, DATA_FLAG_HAS_COLLISION, false, false); } - this.sendData(this); - this.loggedIn = true; + if (CustomItemManager.get().hasCustomItems()) { + this.dataPacket(CustomItemManager.get().getCachedPacket()); + } + this.dataPacket(BiomeDefinitionListPacket.getCachedPacket()); + this.dataPacket(EntityManager.get().getCachedPacket()); + + this.sendSpawnPos((int) this.x, (int) this.y, (int) this.z, this.level.getDimension()); + this.getLevel().sendTime(this); + + SetDifficultyPacket difficultyPacket = new SetDifficultyPacket(); + difficultyPacket.difficulty = this.server.getDifficulty(); + this.dataPacket(difficultyPacket); + + SetCommandsEnabledPacket commandsPacket = new SetCommandsEnabledPacket(); + commandsPacket.enabled = this.isEnableClientCommand(); + this.dataPacket(commandsPacket); - this.level.sendTime(this); + this.adventureSettings.update(); + + GameRulesChangedPacket gameRulesPK = new GameRulesChangedPacket(); + gameRulesPK.gameRulesMap = level.getGameRules().getGameRules(); + this.dataPacket(gameRulesPK); + this.server.sendFullPlayerListData(this); this.sendAttributes(); - this.setNameTagVisible(true); - this.setNameTagAlwaysVisible(true); - this.setCanClimb(true); - this.server.getLogger().info(this.getServer().getLanguage().translateString("nukkit.player.logIn", - TextFormat.AQUA + this.username + TextFormat.WHITE, - this.getAddress(), - String.valueOf(this.getPort()), - String.valueOf(this.id), - this.level.getName(), - String.valueOf(NukkitMath.round(this.x, 4)), - String.valueOf(NukkitMath.round(this.y, 4)), - String.valueOf(NukkitMath.round(this.z, 4)))); + this.inventory.sendCreativeContents(); + this.sendAllInventories(); + this.inventory.sendHeldItem(this); + this.server.sendRecipeList(this); + + if (this.isEnableClientCommand()) { + this.sendCommandData(); + } + + this.sendPotionEffects(this); + this.sendData(this); if (this.isOp() || this.hasPermission("nukkit.textcolor")) { this.setRemoveFormat(false); } - this.server.addOnlinePlayer(this); this.server.onPlayerCompleteLoginSequence(this); } + /** + * Handling received data packets + * @param packet packet + */ public void handleDataPacket(DataPacket packet) { if (!connected) { return; } byte pid = packet.pid(); - if (!loginVerified && pid != ProtocolInfo.LOGIN_PACKET && pid != ProtocolInfo.BATCH_PACKET && pid != ProtocolInfo.REQUEST_NETWORK_SETTINGS_PACKET && pid != ProtocolInfo.CLIENT_TO_SERVER_HANDSHAKE_PACKET) { + if (!loginVerified && pid != ProtocolInfo.LOGIN_PACKET && pid != ProtocolInfo.REQUEST_NETWORK_SETTINGS_PACKET && pid != ProtocolInfo.BATCH_PACKET && pid != ProtocolInfo.CLIENT_TO_SERVER_HANDSHAKE_PACKET) { server.getLogger().warning("Ignoring " + packet.getClass().getSimpleName() + " from " + getAddress() + " due to player not verified yet"); - if (unverifiedPackets++ > 100) { - this.close("", "Too many failed login attempts"); - } return; } - try (Timing ignored = Timings.getReceiveDataPacketTiming(packet)) { - DataPacketReceiveEvent ev = new DataPacketReceiveEvent(this, packet); - this.server.getPluginManager().callEvent(ev); - if (ev.isCancelled()) { - return; - } + if (!loggedIn && !PRE_LOGIN_PACKETS.contains(pid)) { + server.getLogger().warning("Ignoring " + packet.getClass().getSimpleName() + " from " + username + " due to player not logged in yet"); + return; + } - if (log.isTraceEnabled() && !server.isIgnoredPacket(packet.getClass())) { - log.trace("Inbound {}: {}", this.getName(), packet); - } + DataPacketReceiveEvent ev = new DataPacketReceiveEvent(this, packet); + this.server.getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + return; + } - BlockFace face; + if (Nukkit.DEBUG > 2 && !server.isIgnoredPacket(packet.getClass())) { + log.trace("Inbound {}: {}", this.getName(), packet); + } - packetswitch: - switch (pid) { - case ProtocolInfo.REQUEST_NETWORK_SETTINGS_PACKET: - if (this.loginPacketReceived) { - this.getServer().getLogger().debug(username + ": got a RequestNetworkSettingsPacket but player is already logged in"); - return; - } + switch (pid) { + case ProtocolInfo.REQUEST_NETWORK_SETTINGS_PACKET: + this.networkSettingsRequested = true; - int protocolVersion = ((RequestNetworkSettingsPacket) packet).protocolVersion; + if (this.getNetworkSession().getCompression() != CompressionProvider.NONE) { + this.getServer().getLogger().debug((this.username == null ? this.unverifiedUsername : this.username) + + ": got a RequestNetworkSettingsPacket but compression is already set"); + return; + } - if (!ProtocolInfo.SUPPORTED_PROTOCOLS.contains(protocolVersion)) { - String message; - if (protocolVersion < ProtocolInfo.CURRENT_PROTOCOL) { - message = "disconnectionScreen.outdatedClient"; - } else { - message = "disconnectionScreen.outdatedServer"; - } - this.close("", message, true); - break; - } + RequestNetworkSettingsPacket networkSettingsRequest = (RequestNetworkSettingsPacket) packet; - NetworkSettingsPacket settingsPacket = new NetworkSettingsPacket(); - settingsPacket.compressionAlgorithm = PacketCompressionAlgorithm.ZLIB; - settingsPacket.compressionThreshold = 1; // compress everything - this.forceDataPacket(settingsPacket, () -> { - this.networkSession.setCompression(CompressionProvider.ZLIB); - }); - break; - case ProtocolInfo.LOGIN_PACKET: - if (this.loginPacketReceived) { - this.close("", "Invalid login packet"); - return; + if (!ProtocolInfo.SUPPORTED_PROTOCOLS.contains(networkSettingsRequest.protocolVersion)) { + String message; + if (networkSettingsRequest.protocolVersion < ProtocolInfo.CURRENT_PROTOCOL) { + message = "disconnectionScreen.outdatedClient"; + } else { + message = "disconnectionScreen.outdatedServer"; } + this.close("", message, true); + this.server.getLogger().debug(getAddress() + " disconnected with unsupported protocol " + networkSettingsRequest.protocolVersion); + return; + } - this.loginPacketReceived = true; + NetworkSettingsPacket settingsPacket = new NetworkSettingsPacket(); + settingsPacket.compressionAlgorithm = server.useSnappy ? PacketCompressionAlgorithm.SNAPPY : PacketCompressionAlgorithm.ZLIB; + settingsPacket.compressionThreshold = server.networkCompressionThreshold; + this.forceDataPacket(settingsPacket, () -> this.networkSession.setCompression(server.useSnappy ? CompressionProvider.SNAPPY : CompressionProvider.ZLIB_RAW)); + return; + case ProtocolInfo.LOGIN_PACKET: + if (this.loginPacketReceived) { + this.close("", "Invalid login packet"); + return; + } - LoginPacket loginPacket = (LoginPacket) packet; + this.loginPacketReceived = true; - this.unverifiedUsername = TextFormat.clean(loginPacket.username); + LoginPacket loginPacket = (LoginPacket) packet; + this.unverifiedUsername = TextFormat.clean(loginPacket.username); - if (loginPacket.skin == null) { - this.close("", "disconnectionScreen.invalidSkin"); - return; - } + if (!this.networkSettingsRequested) { + this.close("", "Invalid login sequence: login packet before network settings"); + return; + } - if (this.server.getOnlinePlayers().size() >= this.server.getMaxPlayers() && this.kick(PlayerKickEvent.Reason.SERVER_FULL, "disconnectionScreen.serverFull", false)) { - return; + if (!ProtocolInfo.SUPPORTED_PROTOCOLS.contains(loginPacket.getProtocol())) { + String message; + if (loginPacket.getProtocol() < ProtocolInfo.CURRENT_PROTOCOL) { + message = "disconnectionScreen.outdatedClient"; + } else { + message = "disconnectionScreen.outdatedServer"; } + this.close("", message, true); + this.server.getLogger().debug(getAddress() + " disconnected with unsupported protocol " + loginPacket.getProtocol()); + return; + } - this.loginChainData = ClientChainData.read(loginPacket); + if (loginPacket.skin == null) { + this.close("", "disconnectionScreen.invalidSkin"); + return; + } - if (!loginChainData.isXboxAuthed() && server.getPropertyBoolean("xbox-auth")) { - this.close("", "disconnectionScreen.notAuthenticated"); - break; - } + if (this.server.getOnlinePlayersCount() >= this.server.getMaxPlayers() && this.kick(PlayerKickEvent.Reason.SERVER_FULL, "disconnectionScreen.serverFull", false)) { + return; + } - // Do not set username before the user is authenticated - this.username = this.unverifiedUsername; - this.unverifiedUsername = null; - this.displayName = this.username; - this.iusername = this.username.toLowerCase(); - this.setDataProperty(new StringEntityData(DATA_NAMETAG, this.username), false); + try { + // TODO: Why do we read this separately? + this.loginChainData = ClientChainData.read(loginPacket); + } catch (ClientChainData.TooBigSkinException ex) { + this.close("", "disconnectionScreen.invalidSkin"); + return; + } - this.randomClientId = loginPacket.clientId; + server.getLogger().debug("Name: " + this.unverifiedUsername + " Protocol: " + loginPacket.getProtocol() + " Version: " + loginChainData.getGameVersion()); - this.uuid = loginPacket.clientUUID; - this.rawUUID = Binary.writeUUID(this.uuid); + if (!loginChainData.isXboxAuthed() && server.xboxAuth) { + this.close("", "disconnectionScreen.notAuthenticated"); + return; + } - boolean valid = true; - int len = loginPacket.username.length(); - if (len > 16 || len < 3 || loginPacket.username.trim().isEmpty()) { - valid = false; - } + // Do not set username before the user is authenticated + this.username = this.unverifiedUsername; + this.unverifiedUsername = null; + this.displayName = this.username; + this.iusername = this.username.toLowerCase(); + this.setDataProperty(new StringEntityData(DATA_NAMETAG, this.username), false); + + this.randomClientId = loginPacket.clientId; + this.uuid = loginPacket.clientUUID; + this.rawUUID = Binary.writeUUID(this.uuid); + + boolean valid = true; + int len = loginPacket.username.length(); + if (len > 16 || len < 3 || loginPacket.username.trim().isEmpty()) { + valid = false; + } - for (int i = 0; i < len && valid; i++) { + if (valid) { + for (int i = 0; i < len; i++) { char c = loginPacket.username.charAt(i); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || - c == '_' || c == ' ' + c == '_' || (c == ' ' && i != 0 && i != len - 1) ) { continue; } @@ -2213,923 +2957,1127 @@ public void handleDataPacket(DataPacket packet) { valid = false; break; } + } - if (!valid || Objects.equals(this.iusername, "rcon") || Objects.equals(this.iusername, "console")) { - this.close("", "disconnectionScreen.invalidName"); - - break; - } - - if (!loginPacket.skin.isValid()) { - this.close("", "disconnectionScreen.invalidSkin"); - break; - } else { - this.setSkin(loginPacket.skin); - } - - PlayerPreLoginEvent playerPreLoginEvent; - this.server.getPluginManager().callEvent(playerPreLoginEvent = new PlayerPreLoginEvent(this, "Plugin reason")); - if (playerPreLoginEvent.isCancelled()) { - this.close("", playerPreLoginEvent.getKickMessage()); + if (!valid || Objects.equals(this.iusername, "rcon") || Objects.equals(this.iusername, "console")) { + this.close("", "disconnectionScreen.invalidName"); + return; + } - break; - } + Skin skin = loginPacket.skin; + if (!skin.isValid()) { + this.close("", "disconnectionScreen.invalidSkin"); + return; + } + this.setSkin(skin); - if (server.encryptionEnabled) { - this.getServer().getScheduler().scheduleAsyncTask(new PrepareEncryptionTask(this) { + PlayerPreLoginEvent playerPreLoginEvent; + this.server.getPluginManager().callEvent(playerPreLoginEvent = new PlayerPreLoginEvent(this, "Plugin reason")); + if (playerPreLoginEvent.isCancelled()) { + this.close("", playerPreLoginEvent.getKickMessage()); + return; + } - @Override - public void onCompletion(Server server) { - if (!Player.this.connected) { - return; - } + if (server.encryptionEnabled) { + this.getServer().getScheduler().scheduleAsyncTask(null, new PrepareEncryptionTask(this) { - if (this.getHandshakeJwt() == null || this.getEncryptionKey() == null || this.getEncryptionCipher() == null || this.getDecryptionCipher() == null) { - Player.this.close("Failed to enable encryption"); - return; - } + @Override + public void onCompletion(Server server) { + if (!Player.this.connected) { + return; + } - ServerToClientHandshakePacket handshakePacket = new ServerToClientHandshakePacket(); - handshakePacket.jwt = this.getHandshakeJwt(); - Player.this.forceDataPacket(handshakePacket, () -> { - Player.this.awaitingEncryptionHandshake = true; - Player.this.networkSession.setEncryption(this.getEncryptionKey(), this.getEncryptionCipher(), this.getDecryptionCipher()); - }); + if (this.getHandshakeJwt() == null || this.getEncryptionKey() == null || this.getEncryptionCipher() == null || this.getDecryptionCipher() == null) { + Player.this.close("Failed to enable encryption"); + return; } - }); - } else { - this.processPreLogin(); - } - break; - case ProtocolInfo.CLIENT_TO_SERVER_HANDSHAKE_PACKET: - if (!this.awaitingEncryptionHandshake) { - this.close("Invalid encryption handshake"); - return; - } - this.awaitingEncryptionHandshake = false; + ServerToClientHandshakePacket handshakePacket = new ServerToClientHandshakePacket(); + handshakePacket.jwt = this.getHandshakeJwt(); + Player.this.forceDataPacket(handshakePacket, () -> { + Player.this.awaitingEncryptionHandshake = true; + Player.this.networkSession.setEncryption(this.getEncryptionKey(), this.getEncryptionCipher(), this.getDecryptionCipher()); + }); + } + }); + } else { this.processPreLogin(); + } + return; + case ProtocolInfo.CLIENT_TO_SERVER_HANDSHAKE_PACKET: + if (!this.awaitingEncryptionHandshake) { + this.close("Invalid encryption handshake"); return; - case ProtocolInfo.RESOURCE_PACK_CLIENT_RESPONSE_PACKET: - ResourcePackClientResponsePacket responsePacket = (ResourcePackClientResponsePacket) packet; - switch (responsePacket.responseStatus) { - case ResourcePackClientResponsePacket.STATUS_REFUSED: - this.close("", "disconnectionScreen.noReason"); - break; - case ResourcePackClientResponsePacket.STATUS_SEND_PACKS: - for (ResourcePackClientResponsePacket.Entry entry : responsePacket.packEntries) { - ResourcePack resourcePack = this.server.getResourcePackManager().getPackById(entry.uuid); - if (resourcePack == null) { - this.close("", "disconnectionScreen.resourcePack"); - break; - } - - ResourcePackDataInfoPacket dataInfoPacket = new ResourcePackDataInfoPacket(); - dataInfoPacket.packId = resourcePack.getPackId(); - dataInfoPacket.maxChunkSize = RESOURCE_PACK_CHUNK_SIZE; - dataInfoPacket.chunkCount = MathHelper.ceil(resourcePack.getPackSize() / (float) RESOURCE_PACK_CHUNK_SIZE); - dataInfoPacket.compressedPackSize = resourcePack.getPackSize(); - dataInfoPacket.sha256 = resourcePack.getSha256(); - this.dataPacket(dataInfoPacket); - } - break; - case ResourcePackClientResponsePacket.STATUS_HAVE_ALL_PACKS: - ResourcePackStackPacket stackPacket = new ResourcePackStackPacket(); - stackPacket.mustAccept = this.server.getForceResources(); - stackPacket.resourcePackStack = this.server.getResourcePackManager().getResourceStack(); - this.dataPacket(stackPacket); - break; - case ResourcePackClientResponsePacket.STATUS_COMPLETED: - this.shouldLogin = true; + } - if (this.preLoginEventTask.isFinished()) { - this.preLoginEventTask.onCompletion(server); + this.awaitingEncryptionHandshake = false; + this.processPreLogin(); + return; + case ProtocolInfo.RESOURCE_PACK_CLIENT_RESPONSE_PACKET: + if (this.spawned) { + this.getServer().getLogger().debug(username + ": ResourcePackClientResponsePacket after player spawned"); + return; + } + ResourcePackClientResponsePacket responsePacket = (ResourcePackClientResponsePacket) packet; + switch (responsePacket.responseStatus) { + case ResourcePackClientResponsePacket.STATUS_REFUSED: + this.close("", "disconnectionScreen.noReason"); + return; + case ResourcePackClientResponsePacket.STATUS_SEND_PACKS: + for (ResourcePackClientResponsePacket.Entry entry : responsePacket.packEntries) { + ResourcePack resourcePack = this.server.getResourcePackManager().getPackById(entry.uuid); + if (resourcePack == null) { + this.close("", "disconnectionScreen.resourcePack"); + return; } - break; - } - break; - case ProtocolInfo.RESOURCE_PACK_CHUNK_REQUEST_PACKET: - ResourcePackChunkRequestPacket requestPacket = (ResourcePackChunkRequestPacket) packet; - ResourcePack resourcePack = this.server.getResourcePackManager().getPackById(requestPacket.packId); - if (resourcePack == null) { - this.close("", "disconnectionScreen.resourcePack"); - break; - } - - ResourcePackChunkDataPacket dataPacket = new ResourcePackChunkDataPacket(); - dataPacket.packId = resourcePack.getPackId(); - dataPacket.chunkIndex = requestPacket.chunkIndex; - dataPacket.data = resourcePack.getPackChunk(RESOURCE_PACK_CHUNK_SIZE * requestPacket.chunkIndex, RESOURCE_PACK_CHUNK_SIZE); - dataPacket.progress = (long) RESOURCE_PACK_CHUNK_SIZE * requestPacket.chunkIndex; - this.dataPacket(dataPacket); - break; - case ProtocolInfo.SET_LOCAL_PLAYER_AS_INITIALIZED_PACKET: - if (this.locallyInitialized) { - break; - } - this.locallyInitialized = true; - PlayerLocallyInitializedEvent locallyInitializedEvent = new PlayerLocallyInitializedEvent(this); - this.server.getPluginManager().callEvent(locallyInitializedEvent); - break; - case ProtocolInfo.PLAYER_SKIN_PACKET: - PlayerSkinPacket skinPacket = (PlayerSkinPacket) packet; - Skin skin = skinPacket.skin; - - if (!skin.isValid()) { - this.getServer().getLogger().debug(username + ": PlayerSkinPacket with invalid skin"); - break; - } - - PlayerChangeSkinEvent playerChangeSkinEvent = new PlayerChangeSkinEvent(this, skin); - playerChangeSkinEvent.setCancelled(TimeUnit.SECONDS.toMillis(this.server.getPlayerSkinChangeCooldown()) > System.currentTimeMillis() - this.lastSkinChange); - this.server.getPluginManager().callEvent(playerChangeSkinEvent); - if (!playerChangeSkinEvent.isCancelled()) { - this.lastSkinChange = System.currentTimeMillis(); - this.setSkin(skin); - } - break; - case ProtocolInfo.PACKET_VIOLATION_WARNING_PACKET: - log.warn("Violation warning from {}: {}", this.getName(), packet.toString()); - break; - case ProtocolInfo.EMOTE_PACKET: - if (!this.spawned) { + ResourcePackDataInfoPacket dataInfoPacket = new ResourcePackDataInfoPacket(); + dataInfoPacket.packId = resourcePack.getPackId(); + dataInfoPacket.maxChunkSize = RESOURCE_PACK_CHUNK_SIZE; + dataInfoPacket.chunkCount = MathHelper.ceil(resourcePack.getPackSize() / (float) RESOURCE_PACK_CHUNK_SIZE); + dataInfoPacket.compressedPackSize = resourcePack.getPackSize(); + dataInfoPacket.sha256 = resourcePack.getSha256(); + this.dataPacket(dataInfoPacket); + } return; - } - EmotePacket emotePacket = (EmotePacket) packet; - if (emotePacket.runtimeId != this.id) { - server.getLogger().warning(this.username + " sent EmotePacket with invalid entity id: " + emotePacket.runtimeId + " != " + this.id); + case ResourcePackClientResponsePacket.STATUS_HAVE_ALL_PACKS: + ResourcePackStackPacket stackPacket = new ResourcePackStackPacket(); + stackPacket.mustAccept = this.server.getForceResources() && !this.server.forceResourcesAllowOwnPacks; // Option not to disable client's own packs + stackPacket.resourcePackStack = this.server.getResourcePackManager().getResourceStack(); + this.dataPacket(stackPacket); return; - } - for (Player viewer : this.getViewers().values()) { - viewer.dataPacket(emotePacket); - } - return; - case ProtocolInfo.PLAYER_INPUT_PACKET: - if (!this.isAlive() || !this.spawned) { - break; - } - PlayerInputPacket ipk = (PlayerInputPacket) packet; - if (riding instanceof EntityMinecartAbstract) { - ((EntityMinecartAbstract) riding).setCurrentSpeed(ipk.motionY); - } - break; - case ProtocolInfo.MOVE_PLAYER_PACKET: - if (this.teleportPosition != null) { - break; - } + case ResourcePackClientResponsePacket.STATUS_COMPLETED: + this.shouldLogin = true; - MovePlayerPacket movePlayerPacket = (MovePlayerPacket) packet; - Vector3 newPos = new Vector3(movePlayerPacket.x, movePlayerPacket.y - this.getEyeHeight(), movePlayerPacket.z); - - double dis = newPos.distanceSquared(this); - if (dis == 0 && movePlayerPacket.yaw % 360 == this.yaw && movePlayerPacket.pitch % 360 == this.pitch) { - break; - } - - if (dis > 100) { - this.sendPosition(this, movePlayerPacket.yaw, movePlayerPacket.pitch, MovePlayerPacket.MODE_RESET); - break; - } + if (this.preLoginEventTask.isFinished()) { + this.preLoginEventTask.onCompletion(server); + } + return; + } + return; + case ProtocolInfo.RESOURCE_PACK_CHUNK_REQUEST_PACKET: + ResourcePackChunkRequestPacket requestPacket = (ResourcePackChunkRequestPacket) packet; + ResourcePack resourcePack = this.server.getResourcePackManager().getPackById(requestPacket.packId); + if (resourcePack == null) { + this.close("", "disconnectionScreen.resourcePack"); + return; + } - boolean revert = false; - if (!this.isAlive() || !this.spawned) { - revert = true; - this.forceMovement = new Vector3(this.x, this.y, this.z); - } + ResourcePackChunkDataPacket dataPacket = new ResourcePackChunkDataPacket(); + dataPacket.packId = resourcePack.getPackId(); + dataPacket.chunkIndex = requestPacket.chunkIndex; + dataPacket.data = resourcePack.getPackChunk(RESOURCE_PACK_CHUNK_SIZE * requestPacket.chunkIndex, RESOURCE_PACK_CHUNK_SIZE); + dataPacket.progress = (long) RESOURCE_PACK_CHUNK_SIZE * requestPacket.chunkIndex; + this.dataPacket(dataPacket); + return; + case ProtocolInfo.PLAYER_SKIN_PACKET: + PlayerSkinPacket skinPacket = (PlayerSkinPacket) packet; + skin = skinPacket.skin; - if (this.forceMovement != null && (newPos.distanceSquared(this.forceMovement) > 0.1 || revert)) { - this.sendPosition(this.forceMovement, movePlayerPacket.yaw, movePlayerPacket.pitch, MovePlayerPacket.MODE_RESET); - } else { + if (!skin.isValid()) { + this.close("", "disconnectionScreen.invalidSkin"); + return; + } - movePlayerPacket.yaw %= 360; - movePlayerPacket.pitch %= 360; + PlayerChangeSkinEvent playerChangeSkinEvent = new PlayerChangeSkinEvent(this, skin); + playerChangeSkinEvent.setCancelled(TimeUnit.SECONDS.toMillis(this.server.getPlayerSkinChangeCooldown()) > System.currentTimeMillis() - this.lastSkinChange); + this.server.getPluginManager().callEvent(playerChangeSkinEvent); + if (!playerChangeSkinEvent.isCancelled()) { + this.lastSkinChange = System.currentTimeMillis(); + this.setSkin(skin); + } + return; + case ProtocolInfo.PLAYER_AUTH_INPUT_PACKET: + if (!this.spawned) { + return; + } - if (movePlayerPacket.yaw < 0) { - movePlayerPacket.yaw += 360; + PlayerAuthInputPacket authPacket = (PlayerAuthInputPacket) packet; + if (!authPacket.getBlockActionData().isEmpty()) { + for (PlayerBlockActionData action : authPacket.getBlockActionData().values()) { + BlockVector3 blockPos = action.getPosition(); + BlockFace blockFace = BlockFace.fromIndex(action.getFacing()); + if (this.lastBlockAction != null && this.lastBlockAction.getAction() == PlayerActionType.PREDICT_DESTROY_BLOCK && + action.getAction() == PlayerActionType.CONTINUE_DESTROY_BLOCK) { + this.onBlockBreakStart(blockPos, blockFace); } - this.setRotation(movePlayerPacket.yaw, movePlayerPacket.pitch); - this.newPosition = newPos; - this.forceMovement = null; - } - break; - case ProtocolInfo.PLAYER_AUTH_INPUT_PACKET: - PlayerAuthInputPacket authPacket = (PlayerAuthInputPacket) packet; - - if (!authPacket.getBlockActionData().isEmpty()) { - for (PlayerBlockActionData action : authPacket.getBlockActionData().values()) { - BlockVector3 blockPos = action.getPosition(); - BlockFace blockFace = BlockFace.fromIndex(action.getFacing()); - if (this.lastBlockAction != null && this.lastBlockAction.getAction() == PlayerActionType.PREDICT_DESTROY_BLOCK && - action.getAction() == PlayerActionType.CONTINUE_DESTROY_BLOCK) { - this.onBlockBreakStart(blockPos.asVector3(), blockFace); - } - - BlockVector3 lastBreakPos = this.lastBlockAction == null ? null : this.lastBlockAction.getPosition(); - if (lastBreakPos != null && (lastBreakPos.getX() != blockPos.getX() || - lastBreakPos.getY() != blockPos.getY() || lastBreakPos.getZ() != blockPos.getZ())) { - this.onBlockBreakAbort(lastBreakPos.asVector3(), BlockFace.DOWN); - this.onBlockBreakStart(blockPos.asVector3(), blockFace); - } + BlockVector3 lastBreakPos = this.lastBlockAction == null ? null : this.lastBlockAction.getPosition(); + if (lastBreakPos != null && (lastBreakPos.getX() != blockPos.getX() || + lastBreakPos.getY() != blockPos.getY() || lastBreakPos.getZ() != blockPos.getZ())) { + this.onBlockBreakAbort(lastBreakPos, BlockFace.DOWN); + this.onBlockBreakStart(blockPos, blockFace); + } - switch (action.getAction()) { - case START_DESTROY_BLOCK: - this.onBlockBreakStart(blockPos.asVector3(), blockFace); - break; - case ABORT_DESTROY_BLOCK: - case STOP_DESTROY_BLOCK: - this.onBlockBreakAbort(blockPos.asVector3(), blockFace); - break; - case CONTINUE_DESTROY_BLOCK: - this.onBlockBreakContinue(blockPos.asVector3(), blockFace); - break; - case PREDICT_DESTROY_BLOCK: - this.onBlockBreakAbort(blockPos.asVector3(), blockFace); - this.onBlockBreakComplete(blockPos, blockFace); - break; - } - this.lastBlockAction = action; + switch (action.getAction()) { + case START_DESTROY_BLOCK: + this.onBlockBreakStart(blockPos, blockFace); + break; + case ABORT_DESTROY_BLOCK: + //case STOP_DESTROY_BLOCK: + this.onBlockBreakAbort(blockPos, blockFace); + break; + case CONTINUE_DESTROY_BLOCK: + // When player moves cursor to another block + break; + case PREDICT_DESTROY_BLOCK: + //this.onBlockBreakAbort(blockPos, blockFace); + this.onBlockBreakComplete(blockPos, blockFace); + break; } + this.lastBlockAction = action; } + } - if (this.teleportPosition != null) { - return; - } + if (this.teleportPosition != null) { + return; + } - if (this.riding instanceof EntityMinecartAbstract) { - double inputY = authPacket.getMotion().getY(); - if (inputY >= -1.001 && inputY <= 1.001) { - ((EntityMinecartAbstract) riding).setCurrentSpeed(inputY); - } - } else if (this.riding instanceof EntityBoat && authPacket.getInputData().contains(AuthInputAction.IN_CLIENT_PREDICTED_IN_VEHICLE)) { - if (this.riding.getId() == authPacket.getPredictedVehicle() && this.riding.isControlling(this)) { - if (this.temporalVector.setComponents(authPacket.getPosition().getX(), authPacket.getPosition().getY(), authPacket.getPosition().getZ()).distanceSquared(this.riding) < 100) { - ((EntityBoat) this.riding).onInput(authPacket.getPosition().getX(), authPacket.getPosition().getY(), authPacket.getPosition().getZ(), authPacket.getHeadYaw()); - } - } + if (this.riding instanceof EntityControllable && riding.isControlling(this)) { + boolean jumping = authPacket.getInputData().contains(AuthInputAction.JUMPING); + if (jumping && this.riderJumpTick <= 0) { + this.riderJumpTick = server.getTick(); + } else if (!jumping && this.riderJumpTick > 0) { + ((EntityControllable) riding).onJump(this, server.getTick() - this.riderJumpTick); + this.riderJumpTick = 0; } - - if (!this.isSpectator() && authPacket.getInputData().contains(AuthInputAction.MISSED_SWING)) { - level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_ATTACK_NODAMAGE, -1, "minecraft:player", false, false); + double inputX = authPacket.getMotion().getX(); + double inputY = authPacket.getMotion().getY(); + if (inputX >= -1.001 && inputX <= 1.001 && inputY >= -1.001 && inputY <= 1.001) { + ((EntityControllable) riding).onPlayerInput(this, inputX, inputY); } - - if (authPacket.getInputData().contains(AuthInputAction.START_SPRINTING)) { - PlayerToggleSprintEvent event = new PlayerToggleSprintEvent(this, true); - this.server.getPluginManager().callEvent(event); - if (event.isCancelled()) { - this.sendData(this); - } else { - this.setSprinting(true); + } else if (this.riding instanceof EntityBoat && authPacket.getInputData().contains(AuthInputAction.IN_CLIENT_PREDICTED_IN_VEHICLE)) { + if (this.riding.getId() == authPacket.getPredictedVehicle() && this.riding.isControlling(this)) { + if (this.temporalVector.setComponents(authPacket.getPosition().getX(), authPacket.getPosition().getY(), authPacket.getPosition().getZ()).distanceSquared(this.riding) < 16) { + ((EntityBoat) this.riding).onInput(authPacket.getPosition().getX(), authPacket.getPosition().getY(), authPacket.getPosition().getZ(), authPacket.getHeadYaw()); } } + } - if (authPacket.getInputData().contains(AuthInputAction.STOP_SPRINTING)) { - PlayerToggleSprintEvent event = new PlayerToggleSprintEvent(this, false); - this.server.getPluginManager().callEvent(event); - if (event.isCancelled()) { - this.sendData(this); - } else { - this.setSprinting(false); - } - } + if (!this.isSpectator() && authPacket.getInputData().contains(AuthInputAction.MISSED_SWING)) { + level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_ATTACK_NODAMAGE, -1, "minecraft:player", false, false); + } - if (authPacket.getInputData().contains(AuthInputAction.START_SNEAKING)) { - PlayerToggleSneakEvent event = new PlayerToggleSneakEvent(this, true); - this.server.getPluginManager().callEvent(event); - if (event.isCancelled()) { - this.sendData(this); - } else { - this.setSneaking(true); - } + if (authPacket.getInputData().contains(AuthInputAction.START_SPRINTING)) { + PlayerToggleSprintEvent playerToggleSprintEvent = new PlayerToggleSprintEvent(this, true); + if ((this.foodData.getLevel() <= 6 && !this.getAdventureSettings().get(Type.FLYING)) || + this.riding != null || this.sleeping != null || this.hasEffect(Effect.BLINDNESS) || + (this.isSneaking() && !authPacket.getInputData().contains(AuthInputAction.STOP_SNEAKING))) { + playerToggleSprintEvent.setCancelled(true); } - - if (authPacket.getInputData().contains(AuthInputAction.STOP_SNEAKING)) { - PlayerToggleSneakEvent event = new PlayerToggleSneakEvent(this, false); - this.server.getPluginManager().callEvent(event); - if (event.isCancelled()) { - this.sendData(this); - } else { - this.setSneaking(false); - } + this.server.getPluginManager().callEvent(playerToggleSprintEvent); + if (playerToggleSprintEvent.isCancelled()) { + this.needSendData = true; + } else { + this.setSprinting(true, false); } + this.setUsingItem(false); + } - if (authPacket.getInputData().contains(AuthInputAction.START_JUMPING)) { - PlayerJumpEvent playerJumpEvent = new PlayerJumpEvent(this); - this.server.getPluginManager().callEvent(playerJumpEvent); + if (authPacket.getInputData().contains(AuthInputAction.STOP_SPRINTING)) { + PlayerToggleSprintEvent playerToggleSprintEvent = new PlayerToggleSprintEvent(this, false); + this.server.getPluginManager().callEvent(playerToggleSprintEvent); + if (playerToggleSprintEvent.isCancelled()) { + this.needSendData = true; + } else { + this.setSprinting(false, false); } + } - if (authPacket.getInputData().contains(AuthInputAction.START_GLIDING)) { - PlayerToggleGlideEvent playerToggleGlideEvent = new PlayerToggleGlideEvent(this, true); - this.server.getPluginManager().callEvent(playerToggleGlideEvent); - if (playerToggleGlideEvent.isCancelled()) { - this.sendData(this); - } else { - this.setGliding(true); - } + if (authPacket.getInputData().contains(AuthInputAction.START_SNEAKING)) { + PlayerToggleSneakEvent playerToggleSneakEvent = new PlayerToggleSneakEvent(this, true); + if (this.riding != null || this.sleeping != null) { + playerToggleSneakEvent.setCancelled(true); } - - if (authPacket.getInputData().contains(AuthInputAction.STOP_GLIDING)) { - PlayerToggleGlideEvent playerToggleGlideEvent = new PlayerToggleGlideEvent(this, false); - this.server.getPluginManager().callEvent(playerToggleGlideEvent); - if (playerToggleGlideEvent.isCancelled()) { - this.sendData(this); - } else { - this.setGliding(false); - } + this.server.getPluginManager().callEvent(playerToggleSneakEvent); + if (playerToggleSneakEvent.isCancelled()) { + this.needSendData = true; + } else { + this.setSneaking(true); } + } - if (authPacket.getInputData().contains(AuthInputAction.START_SWIMMING)) { - PlayerToggleSwimEvent ptse = new PlayerToggleSwimEvent(this, true); - this.server.getPluginManager().callEvent(ptse); - if (ptse.isCancelled()) { - this.sendData(this); - } else { - this.setSwimming(true); - } + if (authPacket.getInputData().contains(AuthInputAction.STOP_SNEAKING)) { + PlayerToggleSneakEvent playerToggleSneakEvent = new PlayerToggleSneakEvent(this, false); + this.server.getPluginManager().callEvent(playerToggleSneakEvent); + if (playerToggleSneakEvent.isCancelled()) { + this.needSendData = true; + } else { + this.setSneaking(false); } + } - if (authPacket.getInputData().contains(AuthInputAction.STOP_SWIMMING)) { - PlayerToggleSwimEvent ptse = new PlayerToggleSwimEvent(this, false); - this.server.getPluginManager().callEvent(ptse); - if (ptse.isCancelled()) { - this.sendData(this); - } else { - this.setSwimming(false); - } + if (authPacket.getInputData().contains(AuthInputAction.START_CRAWLING)) { + PlayerToggleCrawlEvent playerToggleCrawlEvent = new PlayerToggleCrawlEvent(this, true); + if (this.riding != null || this.sleeping != null) { + playerToggleCrawlEvent.setCancelled(true); } - - if (authPacket.getInputData().contains(AuthInputAction.START_FLYING)) { - if (!server.getAllowFlight() && !this.getAdventureSettings().get(Type.ALLOW_FLIGHT)) { - this.kick(PlayerKickEvent.Reason.FLYING_DISABLED, "Flying is not enabled on this server"); - break; - } - PlayerToggleFlightEvent playerToggleFlightEvent = new PlayerToggleFlightEvent(this, true); - if (this.isSpectator()) { - playerToggleFlightEvent.setCancelled(); - } - this.getServer().getPluginManager().callEvent(playerToggleFlightEvent); - if (playerToggleFlightEvent.isCancelled()) { - this.getAdventureSettings().update(false); - } else { - this.getAdventureSettings().set(AdventureSettings.Type.FLYING, playerToggleFlightEvent.isFlying()); - } + this.server.getPluginManager().callEvent(playerToggleCrawlEvent); + if (playerToggleCrawlEvent.isCancelled()) { + this.needSendData = true; + } else { + this.setCrawling(true); } + } - if (authPacket.getInputData().contains(AuthInputAction.STOP_FLYING)) { - PlayerToggleFlightEvent playerToggleFlightEvent = new PlayerToggleFlightEvent(this, false); - if (this.isSpectator()) { - playerToggleFlightEvent.setCancelled(); - } - this.getServer().getPluginManager().callEvent(playerToggleFlightEvent); - if (playerToggleFlightEvent.isCancelled()) { - this.getAdventureSettings().update(false); - } else { - this.getAdventureSettings().set(AdventureSettings.Type.FLYING, playerToggleFlightEvent.isFlying()); - } + if (authPacket.getInputData().contains(AuthInputAction.STOP_CRAWLING)) { + PlayerToggleCrawlEvent playerToggleCrawlEvent = new PlayerToggleCrawlEvent(this, false); + this.server.getPluginManager().callEvent(playerToggleCrawlEvent); + if (playerToggleCrawlEvent.isCancelled()) { + this.needSendData = true; + } else { + this.setCrawling(false); } + } - Vector3 clientPosition = authPacket.getPosition().subtract(0, this.riding == null ? this.getBaseOffset() : this.riding.getMountedOffset(this).getY(), 0).asVector3(); + if (authPacket.getInputData().contains(AuthInputAction.START_JUMPING)) { + this.server.getPluginManager().callEvent(new PlayerJumpEvent(this)); + } - double distSqrt = clientPosition.distanceSquared(this); - if (distSqrt == 0.0 && authPacket.getYaw() % 360 == this.yaw && authPacket.getPitch() % 360 == this.pitch) { - break; + if (authPacket.getInputData().contains(AuthInputAction.START_GLIDING)) { + boolean withoutElytra = false; + Item chestplate = this.getInventory().getChestplateFast(); + if (chestplate == null || chestplate.getId() != ItemID.ELYTRA || chestplate.getDamage() >= chestplate.getMaxDurability()) { + withoutElytra = true; + } + if (withoutElytra && !server.getAllowFlight()) { + this.kick(PlayerKickEvent.Reason.FLYING_DISABLED, MSG_FLYING_NOT_ENABLED, true); + return; + } + PlayerToggleGlideEvent playerToggleGlideEvent = new PlayerToggleGlideEvent(this, true); + if (this.riding != null || this.sleeping != null || withoutElytra) { + playerToggleGlideEvent.setCancelled(true); } + this.server.getPluginManager().callEvent(playerToggleGlideEvent); + if (playerToggleGlideEvent.isCancelled()) { + this.needSendData = true; + } else { + this.setGliding(true); + } + } - if (distSqrt > 100) { - this.sendPosition(this, authPacket.getYaw(), authPacket.getPitch(), MovePlayerPacket.MODE_RESET); - break; + if (authPacket.getInputData().contains(AuthInputAction.STOP_GLIDING)) { + PlayerToggleGlideEvent playerToggleGlideEvent = new PlayerToggleGlideEvent(this, false); + this.server.getPluginManager().callEvent(playerToggleGlideEvent); + if (playerToggleGlideEvent.isCancelled()) { + this.needSendData = true; + } else { + this.setGliding(false); } + } - boolean revertMotion = false; - if (!this.isAlive() || !this.spawned) { - revertMotion = true; - this.forceMovement = new Vector3(this.x, this.y, this.z); + if (authPacket.getInputData().contains(AuthInputAction.START_SWIMMING)) { + PlayerToggleSwimEvent ptse = new PlayerToggleSwimEvent(this, true); + if (this.riding != null || this.sleeping != null || !this.isInsideOfWater()) { + ptse.setCancelled(true); + } + this.server.getPluginManager().callEvent(ptse); + if (ptse.isCancelled()) { + this.needSendData = true; + } else { + this.setSwimming(true); } + this.setUsingItem(false); + } - if (this.forceMovement != null && (clientPosition.distanceSquared(this.forceMovement) > 0.1 || revertMotion)) { - this.sendPosition(this.forceMovement, authPacket.getYaw(), authPacket.getPitch(), MovePlayerPacket.MODE_RESET); + if (authPacket.getInputData().contains(AuthInputAction.STOP_SWIMMING)) { + PlayerToggleSwimEvent ptse = new PlayerToggleSwimEvent(this, false); + this.server.getPluginManager().callEvent(ptse); + if (ptse.isCancelled()) { + this.needSendData = true; } else { - float yaw = authPacket.getYaw() % 360; - float pitch = authPacket.getPitch() % 360; - if (yaw < 0) { - yaw += 360; - } + this.setSwimming(false); + } + } - this.setRotation(yaw, pitch); - this.newPosition = clientPosition; - this.clientMovements.offer(clientPosition); - this.forceMovement = null; + if (authPacket.getInputData().contains(AuthInputAction.STOP_SPIN_ATTACK)) { + PlayerToggleSpinAttackEvent playerToggleSpinAttackEvent = new PlayerToggleSpinAttackEvent(this, false); + this.server.getPluginManager().callEvent(playerToggleSpinAttackEvent); + if (playerToggleSpinAttackEvent.isCancelled()) { + this.needSendData = true; + } else { + this.setSpinAttack(false); } - break; - case ProtocolInfo.MOB_EQUIPMENT_PACKET: - if (!this.spawned || !this.isAlive()) { + } + + if (authPacket.getInputData().contains(AuthInputAction.START_FLYING)) { + if (!server.getAllowFlight() && !this.adventureSettings.get(Type.ALLOW_FLIGHT)) { + this.kick(PlayerKickEvent.Reason.FLYING_DISABLED, MSG_FLYING_NOT_ENABLED, true); break; } + PlayerToggleFlightEvent playerToggleFlightEvent = new PlayerToggleFlightEvent(this, true); + server.getPluginManager().callEvent(playerToggleFlightEvent); + if (playerToggleFlightEvent.isCancelled()) { + this.needSendAdventureSettings = true; + } else { + this.adventureSettings.set(AdventureSettings.Type.FLYING, playerToggleFlightEvent.isFlying()); + } + } - MobEquipmentPacket mobEquipmentPacket = (MobEquipmentPacket) packet; + if (authPacket.getInputData().contains(AuthInputAction.STOP_FLYING)) { + PlayerToggleFlightEvent playerToggleFlightEvent = new PlayerToggleFlightEvent(this, false); + if (this.isSpectator()) { + playerToggleFlightEvent.setCancelled(true); + } + server.getPluginManager().callEvent(playerToggleFlightEvent); + if (playerToggleFlightEvent.isCancelled()) { + this.needSendAdventureSettings = true; + } else { + this.adventureSettings.set(AdventureSettings.Type.FLYING, playerToggleFlightEvent.isFlying()); + } + } - Inventory inv = this.getWindowById(mobEquipmentPacket.windowId); + if (this.adventureSettings.get(AdventureSettings.Type.FLYING)) { + this.flySneaking = authPacket.getInputData().contains(AuthInputAction.SNEAKING); + } - if (inv == null) { - this.server.getLogger().debug(this.getName() + " has no open container with window ID " + mobEquipmentPacket.windowId); - return; - } + Vector3 clientPosition = authPacket.getPosition().subtract(0, this.riding == null ? this.getBaseOffset() : this.riding.getMountedOffset(this).getY(), 0).asVector3(); - Item item = inv.getItem(mobEquipmentPacket.hotbarSlot); + double distSqrt = clientPosition.distanceSquared(this); + if (distSqrt > 100) { // Notice: This is the distance to player's position on server side. There are likely still unhandled previous movements when next move packet is received. + this.sendPosition(this, authPacket.getYaw(), authPacket.getPitch(), MovePlayerPacket.MODE_RESET); + server.getLogger().debug(username + ": move " + distSqrt + " > 100"); + return; + } - if (!item.equals(mobEquipmentPacket.item)) { - this.server.getLogger().debug(this.getName() + " tried to equip " + mobEquipmentPacket.item + " but have " + item + " in target slot"); - inv.sendContents(this); - return; - } + boolean revertMotion = false; + if (!this.isAlive() || !this.spawned) { + revertMotion = true; + this.forceMovement = this; + } - if (inv instanceof PlayerInventory) { - ((PlayerInventory) inv).equipItem(mobEquipmentPacket.hotbarSlot); + if (this.forceMovement != null && (revertMotion || clientPosition.distanceSquared(this.forceMovement) > 0.1)) { + this.sendPosition(this.forceMovement, authPacket.getYaw(), authPacket.getPitch(), MovePlayerPacket.MODE_RESET); + } else { + float yaw = authPacket.getYaw() % 360; + float pitch = authPacket.getPitch() % 360; + if (yaw < 0) { + yaw += 360; } - this.setDataFlag(Player.DATA_FLAGS, Player.DATA_FLAG_ACTION, false); + this.setRotation(yaw, pitch); + this.newPosition = clientPosition; + this.clientMovements.offer(clientPosition); + this.forceMovement = null; + } + return; + case ProtocolInfo.MOB_EQUIPMENT_PACKET: + if (!this.spawned || !this.isAlive()) { + return; + } - break; - case ProtocolInfo.PLAYER_ACTION_PACKET: - PlayerActionPacket playerActionPacket = (PlayerActionPacket) packet; - if (!this.spawned || !this.isAlive() && playerActionPacket.action != PlayerActionPacket.ACTION_RESPAWN) { - break; - } + MobEquipmentPacket mobEquipmentPacket = (MobEquipmentPacket) packet; - switch (playerActionPacket.action) { - case PlayerActionPacket.ACTION_STOP_SLEEPING: - this.stopSleep(); - break; - case PlayerActionPacket.ACTION_RESPAWN: - if (!this.spawned || this.isAlive() || !this.isOnline()) { - break; - } - this.respawn(); - break; - case PlayerActionPacket.ACTION_DIMENSION_CHANGE_ACK: - this.sendPosition(this, this.yaw, this.pitch, MovePlayerPacket.MODE_RESET); - break; - } + if (mobEquipmentPacket.windowId != ContainerIds.INVENTORY) { + return; + } - this.setUsingItem(false); - break; - case ProtocolInfo.MOB_ARMOR_EQUIPMENT_PACKET: - break; - case ProtocolInfo.MODAL_FORM_RESPONSE_PACKET: - if (!this.spawned || !this.isAlive()) { - break; - } + if (this.inventory == null) { + return; + } - ModalFormResponsePacket modalFormPacket = (ModalFormResponsePacket) packet; + this.inventory.equipItem(mobEquipmentPacket.hotbarSlot); + this.setUsingItem(false); + return; + case ProtocolInfo.PLAYER_ACTION_PACKET: + PlayerActionPacket playerActionPacket = (PlayerActionPacket) packet; + if (!this.spawned || (!this.isAlive() && playerActionPacket.action != PlayerActionPacket.ACTION_RESPAWN)) { + return; + } - if (formWindows.containsKey(modalFormPacket.formId)) { - FormWindow window = formWindows.remove(modalFormPacket.formId); - window.setResponse(modalFormPacket.data.trim()); + playerActionPacket.entityId = this.id; - for (FormResponseHandler handler : window.getHandlers()) { - handler.handle(this, modalFormPacket.formId); + stopItemHold: + switch (playerActionPacket.action) { + case PlayerActionPacket.ACTION_START_BREAK: + break stopItemHold; + case PlayerActionPacket.ACTION_ABORT_BREAK: + //case PlayerActionPacket.ACTION_STOP_BREAK: // This could be used instead of inventory transaction when the breaking is done? + return; + case PlayerActionPacket.ACTION_STOP_SLEEPING: + this.stopSleep(); + return; + case PlayerActionPacket.ACTION_RESPAWN: + if (!this.spawned || this.isAlive() || !this.isOnline()) { + return; } + this.respawn(); + break stopItemHold; + case PlayerActionPacket.ACTION_JUMP: + return; + case PlayerActionPacket.ACTION_START_SPRINT: + break stopItemHold; + case PlayerActionPacket.ACTION_STOP_SPRINT: + return; + case PlayerActionPacket.ACTION_START_SNEAK: + return; + case PlayerActionPacket.ACTION_STOP_SNEAK: + return; + case PlayerActionPacket.ACTION_DIMENSION_CHANGE_ACK: + if (this.awaitingDimensionAck) { + this.sendPosition(this, this.yaw, this.pitch, MovePlayerPacket.MODE_RESET); + this.dummyBossBars.values().forEach(DummyBossBar::reshow); + this.awaitingDimensionAck = false; + } else { + this.getServer().getLogger().debug(username + ": got a dimension change ack but no dimension change is in progress"); + } + return; + case PlayerActionPacket.ACTION_START_GLIDE: + return; + case PlayerActionPacket.ACTION_STOP_GLIDE: + return; + case PlayerActionPacket.ACTION_CONTINUE_BREAK: + // When player moves cursor to another block + return; + case PlayerActionPacket.ACTION_START_SWIMMING: + break stopItemHold; + case PlayerActionPacket.ACTION_STOP_SWIMMING: + return; + } - PlayerFormRespondedEvent event = new PlayerFormRespondedEvent(this, modalFormPacket.formId, window); - getServer().getPluginManager().callEvent(event); - } else if (serverSettings.containsKey(modalFormPacket.formId)) { - FormWindow window = serverSettings.get(modalFormPacket.formId); - window.setResponse(modalFormPacket.data.trim()); + this.setUsingItem(false); + return; + case ProtocolInfo.MODAL_FORM_RESPONSE_PACKET: + this.formOpen = false; - for (FormResponseHandler handler : window.getHandlers()) { - handler.handle(this, modalFormPacket.formId); - } + if (!this.spawned || !this.isAlive()) { + return; + } + + ModalFormResponsePacket modalFormPacket = (ModalFormResponsePacket) packet; - PlayerSettingsRespondedEvent event = new PlayerSettingsRespondedEvent(this, modalFormPacket.formId, window); - getServer().getPluginManager().callEvent(event); + if (formWindows.containsKey(modalFormPacket.formId)) { + FormWindow window = formWindows.remove(modalFormPacket.formId); + window.setResponse(modalFormPacket.data.trim()); - //Set back new settings if not been cancelled - if (!event.isCancelled() && window instanceof FormWindowCustom) - ((FormWindowCustom) window).setElementsFromResponse(); + for (FormResponseHandler handler : window.getHandlers()) { + handler.handle(this, modalFormPacket.formId); } - break; + PlayerFormRespondedEvent event = new PlayerFormRespondedEvent(this, modalFormPacket.formId, window); + getServer().getPluginManager().callEvent(event); + } else if (serverSettings.containsKey(modalFormPacket.formId)) { + FormWindow window = serverSettings.get(modalFormPacket.formId); + window.setResponse(modalFormPacket.data.trim()); - case ProtocolInfo.INTERACT_PACKET: - if (!this.spawned || !this.isAlive()) { - break; + for (FormResponseHandler handler : window.getHandlers()) { + handler.handle(this, modalFormPacket.formId); } - InteractPacket interactPacket = (InteractPacket) packet; + PlayerSettingsRespondedEvent event = new PlayerSettingsRespondedEvent(this, modalFormPacket.formId, window); + getServer().getPluginManager().callEvent(event); - if (interactPacket.target == 0 && interactPacket.action == InteractPacket.ACTION_MOUSEOVER) { - this.setButtonText(""); - break; - } + if (!event.isCancelled() && window instanceof FormWindowCustom) + ((FormWindowCustom) window).setElementsFromResponse(); + } - Entity targetEntity = interactPacket.target == this.getId() ? this : this.level.getEntity(interactPacket.target); + return; + case ProtocolInfo.INTERACT_PACKET: + if (!this.spawned || !this.isAlive()) { + return; + } - if (targetEntity == null || !this.isAlive() || !targetEntity.isAlive()) { - break; - } + InteractPacket interactPacket = (InteractPacket) packet; - if (targetEntity instanceof EntityItem || targetEntity instanceof EntityArrow || targetEntity instanceof EntityXPOrb) { - this.kick(PlayerKickEvent.Reason.INVALID_PVE, "Attempting to interact with an invalid entity"); - this.server.getLogger().warning(this.getServer().getLanguage().translateString("nukkit.player.invalidEntity", this.getName())); - break; - } + if (interactPacket.target == 0 && interactPacket.action == InteractPacket.ACTION_MOUSEOVER) { + this.setButtonText(""); + return; + } - switch (interactPacket.action) { - case InteractPacket.ACTION_MOUSEOVER: - String buttonText = ""; - if (targetEntity instanceof EntityInteractable) { - buttonText = ((EntityInteractable) targetEntity).getInteractButtonText(this); - if (buttonText == null) { - buttonText = ""; - } - } - this.setButtonText(buttonText); + Entity targetEntity = interactPacket.target == this.getId() ? this : this.level.getEntity(interactPacket.target); - this.getServer().getPluginManager().callEvent(new PlayerMouseOverEntityEvent(this, targetEntity)); - break; - case InteractPacket.ACTION_VEHICLE_EXIT: - if (!(targetEntity instanceof EntityRideable) || this.riding != targetEntity) { - break; - } + if (targetEntity == null || !this.isAlive() || !targetEntity.isAlive()) { + if (targetEntity != null || interactPacket.action != InteractPacket.ACTION_OPEN_INVENTORY) { + return; + } + } - ((EntityRideable) riding).dismountEntity(this); - break; - case InteractPacket.ACTION_OPEN_INVENTORY: - if (targetEntity != this) { - break; - } - if (!this.inventoryOpen && this.inventory.open(this)) { + if (targetEntity instanceof EntityItem || targetEntity instanceof EntityArrow || targetEntity instanceof EntityXPOrb) { + this.kick(PlayerKickEvent.Reason.INVALID_PVE); + return; + } + + switch (interactPacket.action) { + case InteractPacket.ACTION_OPEN_INVENTORY: + if (!this.inventoryOpen) { + if (this.riding instanceof EntityChestBoat && this.riding == targetEntity) { + this.addWindow(((InventoryHolder) targetEntity).getInventory()); + } else if (this.inventory.open(this)) { this.inventoryOpen = true; + this.awardAchievement("openInventory"); } - break; - } - break; - case ProtocolInfo.BLOCK_PICK_REQUEST_PACKET: - BlockPickRequestPacket pickRequestPacket = (BlockPickRequestPacket) packet; - Block block = this.level.getBlock(pickRequestPacket.x, pickRequestPacket.y, pickRequestPacket.z, false); - if (block.distanceSquared(this) > 1000) { - this.getServer().getLogger().debug(username + ": Block pick request for a block too far away"); + } return; - } - item = block.toItem(); - - if (pickRequestPacket.addUserData) { - BlockEntity blockEntity = this.getLevel().getBlockEntity(new Vector3(pickRequestPacket.x, pickRequestPacket.y, pickRequestPacket.z)); - if (blockEntity != null) { - CompoundTag nbt = blockEntity.getCleanedNBT(); - if (nbt != null) { - item.setCustomBlockData(nbt); - item.setLore("+(DATA)"); + case InteractPacket.ACTION_MOUSEOVER: + String buttonText = ""; + if (targetEntity instanceof EntityInteractable) { + buttonText = ((EntityInteractable) targetEntity).getInteractButtonText(this); + if (buttonText == null) { + buttonText = ""; } } - } + this.setButtonText(buttonText); + this.getServer().getPluginManager().callEvent(new PlayerMouseOverEntityEvent(this, targetEntity)); + return; + case InteractPacket.ACTION_VEHICLE_EXIT: + if (!(targetEntity instanceof EntityRideable) || this.riding != targetEntity) { + return; + } - PlayerBlockPickEvent pickEvent = new PlayerBlockPickEvent(this, block, item); - if (this.isSpectator()) { - log.debug("Got block-pick request from " + this.getName() + " when in spectator mode"); - pickEvent.setCancelled(); + this.riderJumpTick = 0; + ((EntityRideable) riding).dismountEntity(this); + return; + } + return; + case ProtocolInfo.BLOCK_PICK_REQUEST_PACKET: + if (!this.spawned || !this.isAlive() || this.inventory == null || this.inventoryOpen) { + return; + } + + BlockPickRequestPacket pickRequestPacket = (BlockPickRequestPacket) packet; + Block block = this.level.getBlock(chunk, pickRequestPacket.x, pickRequestPacket.y, pickRequestPacket.z, false); + if (block.distanceSquared(this) > 1000) { + this.getServer().getLogger().debug(username + ": block pick request for a block too far away"); + return; + } + Item item = block.toItem(); + if (pickRequestPacket.addUserData && this.isCreative()) { + BlockEntity blockEntity = this.getLevel().getBlockEntityIfLoaded(this.chunk, this.temporalVector.setComponents(pickRequestPacket.x, pickRequestPacket.y, pickRequestPacket.z)); + if (blockEntity != null) { + CompoundTag nbt = blockEntity.getCleanedNBT(); + if (nbt != null) { + item.setCustomBlockData(nbt); + item.setLore("+(DATA)"); + } } + } - this.server.getPluginManager().callEvent(pickEvent); - - if (!pickEvent.isCancelled()) { - boolean itemExists = false; - int itemSlot = -1; - for (int slot = 0; slot < this.inventory.getSize(); slot++) { - if (this.inventory.getItem(slot).equals(pickEvent.getItem())) { - if (slot < this.inventory.getHotbarSize()) { - this.inventory.setHeldItemSlot(slot); - } else { - itemSlot = slot; - } - itemExists = true; - break; + PlayerBlockPickEvent pickEvent = new PlayerBlockPickEvent(this, block, item); + if (this.isSpectator()) { + pickEvent.setCancelled(); + } + + this.server.getPluginManager().callEvent(pickEvent); + + if (!pickEvent.isCancelled()) { + boolean itemExists = false; + int itemSlot = -1; + for (int slot = 0; slot < this.inventory.getSize(); slot++) { + if (this.inventory.getItem(slot).equals(pickEvent.getItem())) { + if (slot < this.inventory.getHotbarSize()) { + this.inventory.setHeldItemSlot(slot); + } else { + itemSlot = slot; } + itemExists = true; + break; } + } - for (int slot = 0; slot < this.inventory.getHotbarSize(); slot++) { - if (this.inventory.getItem(slot).isNull()) { - if (!itemExists && this.isCreative()) { - this.inventory.setHeldItemSlot(slot); - this.inventory.setItemInHand(pickEvent.getItem()); - break packetswitch; - } else if (itemSlot > -1) { - this.inventory.setHeldItemSlot(slot); - this.inventory.setItemInHand(this.inventory.getItem(itemSlot)); - this.inventory.clear(itemSlot, true); - break packetswitch; - } + if (!itemExists && !this.isCreative()) { + return; + } + + for (int slot = 0; slot < this.inventory.getHotbarSize(); slot++) { + if (this.inventory.getItem(slot).isNull()) { + if (!itemExists && this.isCreative()) { + this.inventory.setHeldItemSlot(slot); + this.inventory.setItemInHand(pickEvent.getItem()); + return; + } else if (itemSlot > -1) { + this.inventory.setHeldItemSlot(slot); + this.inventory.setItemInHand(this.inventory.getItem(itemSlot)); + this.inventory.clear(itemSlot, true); + return; } } + } - if (!itemExists && this.isCreative()) { - Item itemInHand = this.inventory.getItemInHand(); - this.inventory.setItemInHand(pickEvent.getItem()); - if (!this.inventory.isFull()) { - for (int slot = 0; slot < this.inventory.getSize(); slot++) { - if (this.inventory.getItem(slot).isNull()) { - this.inventory.setItem(slot, itemInHand); - break; - } + if (!itemExists && this.isCreative()) { + Item itemInHand = this.inventory.getItemInHand(); + this.inventory.setItemInHand(pickEvent.getItem()); + if (!this.inventory.isFull()) { + for (int slot = 0; slot < this.inventory.getSize(); slot++) { + if (this.inventory.getItem(slot).isNull()) { + this.inventory.setItem(slot, itemInHand); + return; } } - } else if (itemSlot > -1) { - Item itemInHand = this.inventory.getItemInHand(); - this.inventory.setItemInHand(this.inventory.getItem(itemSlot)); - this.inventory.setItem(itemSlot, itemInHand); } + } else if (itemSlot > -1) { + Item itemInHand = this.inventory.getItemInHand(); + this.inventory.setItemInHand(this.inventory.getItem(itemSlot)); + this.inventory.setItem(itemSlot, itemInHand); } - break; - case ProtocolInfo.ANIMATE_PACKET: - if (!this.spawned || !this.isAlive()) { - break; - } + } + return; + case ProtocolInfo.ANIMATE_PACKET: + if (!this.spawned || !this.isAlive()) { + return; + } - AnimatePacket animatePacket = (AnimatePacket) packet; - PlayerAnimationEvent animationEvent = new PlayerAnimationEvent(this, animatePacket.action); + AnimatePacket animatePacket = (AnimatePacket) packet; - // prevent client send illegal packet to server and broadcast to other client and make other client crash - if(animatePacket.action == null // illegal action id - || animatePacket.action == AnimatePacket.Action.WAKE_UP // these actions are only for server to client - || animatePacket.action == AnimatePacket.Action.CRITICAL_HIT - || animatePacket.action == AnimatePacket.Action.MAGIC_CRITICAL_HIT) { - break; // maybe we should cancel the event here? but if client send too many packets, server will lag - } + if (animatePacket.action != AnimatePacket.Action.SWING_ARM && + !(this.riding != null && (animatePacket.action == AnimatePacket.Action.ROW_LEFT || animatePacket.action == AnimatePacket.Action.ROW_RIGHT))) { + return; + } - this.server.getPluginManager().callEvent(animationEvent); - if (animationEvent.isCancelled()) { - break; - } + PlayerAnimationEvent animationEvent = new PlayerAnimationEvent(this, animatePacket.action); + this.server.getPluginManager().callEvent(animationEvent); + if (animationEvent.isCancelled()) { + return; + } - AnimatePacket.Action animation = animationEvent.getAnimationType(); + AnimatePacket.Action animation = animationEvent.getAnimationType(); - switch (animation) { - case ROW_RIGHT: - case ROW_LEFT: - if (this.riding instanceof EntityBoat) { - ((EntityBoat) this.riding).onPaddle(animation, ((AnimatePacket) packet).rowingTime); - } - break; - } + switch (animation) { + case ROW_RIGHT: + case ROW_LEFT: + if (this.riding instanceof EntityBoat) { + ((EntityBoat) this.riding).onPaddle(animation, animatePacket.rowingTime); + } + break; + } - animatePacket.eid = this.getId(); - animatePacket.action = animationEvent.getAnimationType(); - Server.broadcastPacket(this.getViewers().values(), animatePacket); - break; - case ProtocolInfo.SET_HEALTH_PACKET: - //use UpdateAttributePacket instead - break; + animatePacket = new AnimatePacket(); + animatePacket.eid = this.getId(); + animatePacket.action = animationEvent.getAnimationType(); + Server.broadcastPacket(this.getViewers().values(), animatePacket); + return; + case ProtocolInfo.ENTITY_EVENT_PACKET: + if (!this.spawned || !this.isAlive()) { + return; + } - case ProtocolInfo.ENTITY_EVENT_PACKET: - if (!this.spawned || !this.isAlive()) { - break; - } - EntityEventPacket entityEventPacket = (EntityEventPacket) packet; - if (entityEventPacket.event != EntityEventPacket.ENCHANT) - this.craftingType = CRAFTING_SMALL; - //this.resetCraftingGridType(); + EntityEventPacket entityEventPacket = (EntityEventPacket) packet; + if (entityEventPacket.event != EntityEventPacket.ENCHANT) { + this.craftingType = CRAFTING_SMALL; + } - if (entityEventPacket.event == EntityEventPacket.EATING_ITEM) { + switch (entityEventPacket.event) { + case EntityEventPacket.EATING_ITEM: if (entityEventPacket.data == 0 || entityEventPacket.eid != this.id) { - break; + this.getServer().getLogger().debug(username + ": entity event eid mismatch"); + return; } entityEventPacket.eid = this.id; entityEventPacket.isEncoded = false; - this.dataPacket(entityEventPacket); Server.broadcastPacket(this.getViewers().values(), entityEventPacket); - } else if (entityEventPacket.event == EntityEventPacket.ENCHANT) { + return; + case EntityEventPacket.ENCHANT: if (entityEventPacket.eid != this.id) { - break; + this.getServer().getLogger().debug(username + ": entity event eid mismatch"); + return; } Inventory inventory = this.getWindowById(ANVIL_WINDOW_ID); if (inventory instanceof AnvilInventory) { ((AnvilInventory) inventory).setCost(-entityEventPacket.data); } - } - break; - case ProtocolInfo.COMMAND_REQUEST_PACKET: - if (!this.spawned || !this.isAlive()) { - break; - } - this.craftingType = CRAFTING_SMALL; - CommandRequestPacket commandRequestPacket = (CommandRequestPacket) packet; - PlayerCommandPreprocessEvent playerCommandPreprocessEvent = new PlayerCommandPreprocessEvent(this, commandRequestPacket.command); - this.server.getPluginManager().callEvent(playerCommandPreprocessEvent); - if (playerCommandPreprocessEvent.isCancelled()) { - break; - } + return; + } + return; + case ProtocolInfo.COMMAND_REQUEST_PACKET: + if (!this.spawned || !this.isAlive()) { + return; + } - Timings.playerCommandTimer.startTiming(); - this.server.dispatchCommand(playerCommandPreprocessEvent.getPlayer(), playerCommandPreprocessEvent.getMessage().substring(1)); - Timings.playerCommandTimer.stopTiming(); - break; - case ProtocolInfo.TEXT_PACKET: - if (!this.spawned || !this.isAlive()) { - break; - } + this.resetCraftingGridType(); - TextPacket textPacket = (TextPacket) packet; + CommandRequestPacket commandRequestPacket = (CommandRequestPacket) packet; + PlayerCommandPreprocessEvent playerCommandPreprocessEvent = new PlayerCommandPreprocessEvent(this, commandRequestPacket.command + ' '); + this.server.getPluginManager().callEvent(playerCommandPreprocessEvent); + if (playerCommandPreprocessEvent.isCancelled()) { + return; + } - if (textPacket.type == TextPacket.TYPE_CHAT) { - String chatMessage = textPacket.message; - int breakLine = chatMessage.indexOf('\n'); - // Chat messages shouldn't contain break lines so ignore text afterwards - if (breakLine != -1) { - chatMessage = chatMessage.substring(0, breakLine); - } - this.chat(chatMessage); - } - break; - case ProtocolInfo.CONTAINER_CLOSE_PACKET: - ContainerClosePacket containerClosePacket = (ContainerClosePacket) packet; - if (!this.spawned || containerClosePacket.windowId == ContainerIds.INVENTORY && !inventoryOpen) { - break; - } + this.server.dispatchCommand(playerCommandPreprocessEvent.getPlayer(), playerCommandPreprocessEvent.getMessage().substring(1)); + return; + case ProtocolInfo.TEXT_PACKET: + if (!this.spawned || !this.isAlive()) { + return; + } + + TextPacket textPacket = (TextPacket) packet; - if (this.windowIndex.containsKey(containerClosePacket.windowId)) { - this.server.getPluginManager().callEvent(new InventoryCloseEvent(this.windowIndex.get(containerClosePacket.windowId), this)); - if (containerClosePacket.windowId == ContainerIds.INVENTORY) this.inventoryOpen = false; - this.closingWindowId = containerClosePacket.windowId; - this.removeWindow(this.windowIndex.get(containerClosePacket.windowId), true); - this.closingWindowId = Integer.MIN_VALUE; + if (textPacket.type == TextPacket.TYPE_CHAT && textPacket.message.length() < 512) { + String chatMessage = textPacket.message; + int breakLine = chatMessage.indexOf('\n'); + // Chat messages shouldn't contain break lines so ignore text afterwards + if (breakLine != -1) { + chatMessage = chatMessage.substring(0, breakLine); } - if (containerClosePacket.windowId == -1) { - this.craftingType = CRAFTING_SMALL; - this.resetCraftingGridType(); - this.addWindow(this.craftingGrid, ContainerIds.NONE); - ContainerClosePacket pk = new ContainerClosePacket(); - pk.wasServerInitiated = false; - pk.windowId = -1; - this.dataPacket(pk); - } else { // Close bugged inventory - ContainerClosePacket pk = new ContainerClosePacket(); - pk.windowId = containerClosePacket.windowId; - pk.wasServerInitiated = false; - this.dataPacket(pk); + this.chat(chatMessage); + } + return; + case ProtocolInfo.CONTAINER_CLOSE_PACKET: + ContainerClosePacket containerClosePacket = (ContainerClosePacket) packet; + if (!this.spawned || (containerClosePacket.windowId == ContainerIds.INVENTORY && !inventoryOpen)) { + return; + } - for (Inventory open : new ArrayList<>(this.windows.keySet())) { - if (open instanceof ContainerInventory) { - this.removeWindow(open); - } + if (this.windowIndex.containsKey(containerClosePacket.windowId)) { + this.server.getPluginManager().callEvent(new InventoryCloseEvent(this.windowIndex.get(containerClosePacket.windowId), this)); + if (containerClosePacket.windowId == ContainerIds.INVENTORY) this.inventoryOpen = false; + this.closingWindowId = containerClosePacket.windowId; + this.removeWindow(this.windowIndex.get(containerClosePacket.windowId), true); + this.closingWindowId = Integer.MIN_VALUE; + } + + if (containerClosePacket.windowId == -1) { + this.resetCraftingGridType(); + this.addWindow(this.craftingGrid, ContainerIds.NONE); + ContainerClosePacket pk = new ContainerClosePacket(); + pk.windowId = -1; + pk.wasServerInitiated = false; + this.dataPacket(pk); + } else { // TODO: check this + ContainerClosePacket pk = new ContainerClosePacket(); + pk.windowId = containerClosePacket.windowId; + pk.wasServerInitiated = false; + this.dataPacket(pk); + + for (Inventory open : new ArrayList<>(this.windows.keySet())) { + if (open instanceof ContainerInventory) { + this.removeWindow(open); } } - break; - case ProtocolInfo.CRAFTING_EVENT_PACKET: - break; - case ProtocolInfo.BLOCK_ENTITY_DATA_PACKET: - if (!this.spawned || !this.isAlive()) { - break; - } + } + return; + case ProtocolInfo.BLOCK_ENTITY_DATA_PACKET: + if (!this.spawned || !this.isAlive()) { + return; + } - BlockEntityDataPacket blockEntityDataPacket = (BlockEntityDataPacket) packet; - this.craftingType = CRAFTING_SMALL; - this.resetCraftingGridType(); + BlockEntityDataPacket blockEntityDataPacket = (BlockEntityDataPacket) packet; + this.resetCraftingGridType(); - Vector3 pos = new Vector3(blockEntityDataPacket.x, blockEntityDataPacket.y, blockEntityDataPacket.z); - if (pos.distanceSquared(this) > 10000) { - break; + Vector3 pos = this.temporalVector.setComponents(blockEntityDataPacket.x, blockEntityDataPacket.y, blockEntityDataPacket.z); + if (pos.distanceSquared(this) > 2500) { + if (Nukkit.DEBUG > 1) { + server.getLogger().debug(username + ": BlockEntityDataPacket target too far " + pos); } + return; + } - BlockEntity t = this.level.getBlockEntity(pos); - if (t instanceof BlockEntitySpawnable) { - CompoundTag nbt; - try { - nbt = NBTIO.read(blockEntityDataPacket.namedTag, ByteOrder.LITTLE_ENDIAN, true); - } catch (IOException e) { - throw new RuntimeException(e); - } + BlockEntity t = this.level.getBlockEntity(pos); + if (t instanceof BlockEntitySpawnable) { + CompoundTag nbt; + try { + nbt = NBTIO.read(blockEntityDataPacket.namedTag, ByteOrder.LITTLE_ENDIAN, true); + } catch (IOException e) { + throw new RuntimeException(e); + } - if (!((BlockEntitySpawnable) t).updateCompoundTag(nbt, this)) { - ((BlockEntitySpawnable) t).spawnTo(this); - } + if (!((BlockEntitySpawnable) t).updateCompoundTag(nbt, this)) { + ((BlockEntitySpawnable) t).spawnTo(this); } - break; - case ProtocolInfo.REQUEST_CHUNK_RADIUS_PACKET: - RequestChunkRadiusPacket requestChunkRadiusPacket = (RequestChunkRadiusPacket) packet; - ChunkRadiusUpdatedPacket chunkRadiusUpdatePacket = new ChunkRadiusUpdatedPacket(); - this.chunkRadius = Math.max(3, Math.min(requestChunkRadiusPacket.radius, this.viewDistance)); - chunkRadiusUpdatePacket.radius = this.chunkRadius; - this.dataPacket(chunkRadiusUpdatePacket); - break; - case ProtocolInfo.SET_PLAYER_GAME_TYPE_PACKET: - SetPlayerGameTypePacket setPlayerGameTypePacket = (SetPlayerGameTypePacket) packet; - if (setPlayerGameTypePacket.gamemode != this.gamemode) { - if (!this.hasPermission("nukkit.command.gamemode")) { - SetPlayerGameTypePacket setPlayerGameTypePacket1 = new SetPlayerGameTypePacket(); - setPlayerGameTypePacket1.gamemode = this.gamemode & 0x01; - this.dataPacket(setPlayerGameTypePacket1); - this.getAdventureSettings().update(false); - break; + } + return; + case ProtocolInfo.REQUEST_CHUNK_RADIUS_PACKET: + RequestChunkRadiusPacket requestChunkRadiusPacket = (RequestChunkRadiusPacket) packet; + ChunkRadiusUpdatedPacket chunkRadiusUpdatePacket = new ChunkRadiusUpdatedPacket(); + this.chunkRadius = Math.max(3, Math.min(requestChunkRadiusPacket.radius, this.viewDistance)); + chunkRadiusUpdatePacket.radius = this.chunkRadius; + this.dataPacket(chunkRadiusUpdatePacket); + return; + case ProtocolInfo.SET_PLAYER_GAME_TYPE_PACKET: + if (!this.spawned) { + return; + } + + SetPlayerGameTypePacket setPlayerGameTypePacket = (SetPlayerGameTypePacket) packet; + if (setPlayerGameTypePacket.gamemode != this.gamemode) { + if (!this.hasPermission("nukkit.command.gamemode")) { + if (!this.isOp()) { + this.kick(PlayerKickEvent.Reason.INVALID_PACKET, "Invalid SetPlayerGameTypePacket", true); } - this.setGamemode(setPlayerGameTypePacket.gamemode, true); - Command.broadcastCommandMessage(this, new TranslationContainer("commands.gamemode.success.self", Server.getGamemodeString(this.gamemode))); + return; } - break; - case ProtocolInfo.MAP_INFO_REQUEST_PACKET: - MapInfoRequestPacket pk = (MapInfoRequestPacket) packet; - Item mapItem = null; + this.setGamemode(setPlayerGameTypePacket.gamemode, true); + Command.broadcastCommandMessage(this, new TranslationContainer("commands.gamemode.success.self", Server.getGamemodeString(this.gamemode))); + } + return; + case ProtocolInfo.MAP_INFO_REQUEST_PACKET: + if (this.inventory == null) { + return; + } - for (Item item1 : this.offhandInventory.getContents().values()) { + MapInfoRequestPacket pk = (MapInfoRequestPacket) packet; + + Item mapItem = null; + + for (Item item1 : this.offhandInventory.getContents().values()) { + if (item1 instanceof ItemMap && ((ItemMap) item1).getMapId() == pk.mapId) { + mapItem = item1; + } + } + + if (mapItem == null) { + for (Item item1 : this.inventory.getContents().values()) { if (item1 instanceof ItemMap && ((ItemMap) item1).getMapId() == pk.mapId) { mapItem = item1; } } + } - if (mapItem == null) { - for (Item item1 : this.inventory.getContents().values()) { - if (item1 instanceof ItemMap && ((ItemMap) item1).getMapId() == pk.mapId) { - mapItem = item1; + if (mapItem == null) { + for (BlockEntity be : this.level.getBlockEntities().values()) { + if (be instanceof BlockEntityItemFrame) { + BlockEntityItemFrame itemFrame1 = (BlockEntityItemFrame) be; + + if (itemFrame1.getItem() instanceof ItemMap && ((ItemMap) itemFrame1.getItem()).getMapId() == pk.mapId) { + ((ItemMap) itemFrame1.getItem()).sendImage(this); + return; } } } + } else { + PlayerMapInfoRequestEvent event = new PlayerMapInfoRequestEvent(this, mapItem); + getServer().getPluginManager().callEvent(event); - if (mapItem == null) { - for (BlockEntity be : this.level.getBlockEntities().values()) { - if (be instanceof BlockEntityItemFrame) { - BlockEntityItemFrame itemFrame1 = (BlockEntityItemFrame) be; + if (!event.isCancelled()) { + ItemMap map = (ItemMap) mapItem; + if (map.trySendImage(this)) { + return; + } + try { + BufferedImage image = new BufferedImage(128, 128, BufferedImage.TYPE_INT_RGB); + Graphics2D graphics = image.createGraphics(); + + int worldX = (Math.floorDiv(this.getFloorX(), 128)) << 7; + int worldZ = (Math.floorDiv(this.getFloorZ(), 128)) << 7; + for (int x = 0; x < 128; x++) { + int avgY = 0; + for (int y = -1; y < 128; y++) { + if (this.getLevel().getDimension() == Level.DIMENSION_NETHER) { + if (y == -1) { + continue; + } + graphics.setColor(colorizeMapColor(new SplittableRandom((((long) (worldZ + y) & 0x3ffffff) << 26) + ((long) (worldX + x) & 0x3ffffff)).nextBoolean() ? BlockColor.STONE_BLOCK_COLOR : BlockColor.DIRT_BLOCK_COLOR, 1)); + } else { + if (y == -1) { // Hack: Make sure we have average world height for the first row + avgY = this.getLevel().getHighestBlockAt(worldX + x, worldZ, false); + continue; + } - if (itemFrame1.getItem() instanceof ItemMap && ((ItemMap) itemFrame1.getItem()).getMapId() == pk.mapId) { - ((ItemMap) itemFrame1.getItem()).sendImage(this); - break; + int worldY = this.getLevel().getHighestBlockAt(worldX + x, worldZ + y, false); + double avgYDifference = (worldY - avgY) * 4 / 5 + ((x + y & 1) - 0.5) * 0.4; // 4d / 5d would provide more detail but is that better? + int colorDepth = 1; + if (avgYDifference > 0.6) { + colorDepth = 2; + } + if (avgYDifference < -0.6) { + colorDepth = 0; + } + avgY = worldY; + graphics.setColor(colorizeMapColor(this.getLevel().getMapColorAt(worldX + x, worldY, worldZ + y), colorDepth)); + } + + graphics.fillRect(x, y, x + 1, y + 1); } } + + map.setImage(image); + map.sendImage(this); + } catch (Exception ex) { + this.getServer().getLogger().debug(username + ": there was an error while generating map image", ex); } } + } + + return; + case ProtocolInfo.INVENTORY_TRANSACTION_PACKET: + if (this.isSpectator()) { + this.needSendInventory = true; + return; + } - if (mapItem != null) { - PlayerMapInfoRequestEvent event; - getServer().getPluginManager().callEvent(event = new PlayerMapInfoRequestEvent(this, mapItem)); + InventoryTransactionPacket transactionPacket = (InventoryTransactionPacket) packet; + + Inventory inv; + if ((transactionPacket.transactionType == InventoryTransactionPacket.TYPE_MISMATCH || + (transactionPacket.transactionType == InventoryTransactionPacket.TYPE_NORMAL && this.isCreative() && Arrays.stream(transactionPacket.actions).anyMatch(action -> action.sourceType == NetworkInventoryAction.SOURCE_TODO))) + && (inv = getWindowById(SMITHING_WINDOW_ID)) instanceof SmithingInventory) { + + SmithingInventory smithingInventory = (SmithingInventory) inv; + if (!smithingInventory.getResult().isNull()) { + InventoryTransactionPacket fixedPacket = new InventoryTransactionPacket(); + fixedPacket.isRepairItemPart = true; + fixedPacket.actions = new NetworkInventoryAction[6]; + + Item fromIngredient = smithingInventory.getIngredient().clone(); + Item toIngredient = fromIngredient.decrement(1); + + Item fromEquipment = smithingInventory.getEquipment().clone(); + Item toEquipment = fromEquipment.decrement(1); + + Item fromResult = Item.get(Item.AIR); + Item toResult = smithingInventory.getResult().clone(); + + NetworkInventoryAction action = new NetworkInventoryAction(); + action.windowId = ContainerIds.UI; + action.inventorySlot = SmithingInventory.SMITHING_INGREDIENT_UI_SLOT; + action.oldItem = fromIngredient.clone(); + action.newItem = toIngredient.clone(); + fixedPacket.actions[0] = action; + + action = new NetworkInventoryAction(); + action.windowId = ContainerIds.UI; + action.inventorySlot = SmithingInventory.SMITHING_EQUIPMENT_UI_SLOT; + action.oldItem = fromEquipment.clone(); + action.newItem = toEquipment.clone(); + fixedPacket.actions[1] = action; + + if (this.getLoginChainData().getUIProfile() == 0) { + // We can't know whether shift click was used so we must make sure we won't overwrite item in cursor inventory + Item[] drops = this.inventory.addItem(this.playerUIInventory.getItemFast(0)); // Cloned in addItem + this.playerUIInventory.getCursorInventory().clear(0); + + for (Item drop : drops) { + this.level.dropItem(this, drop); + } - if (!event.isCancelled()) { - ((ItemMap) mapItem).sendImage(this); + action = new NetworkInventoryAction(); + action.windowId = ContainerIds.UI; + action.inventorySlot = 0; // cursor + action.oldItem = Item.get(Item.AIR); + action.newItem = toResult.clone(); + fixedPacket.actions[2] = action; + } else { + int emptyPlayerSlot = -1; + for (int slot = 0; slot < inventory.getSize(); slot++) { + if (inventory.getItemFast(slot).isNull()) { + emptyPlayerSlot = slot; + break; + } + } + if (emptyPlayerSlot == -1) { + this.needSendInventory = true; + return; + } else { + action = new NetworkInventoryAction(); + action.windowId = ContainerIds.INVENTORY; + action.inventorySlot = emptyPlayerSlot; + action.oldItem = Item.get(Item.AIR); + action.newItem = toResult.clone(); + fixedPacket.actions[2] = action; + } } - } - break; - case ProtocolInfo.LEVEL_SOUND_EVENT_PACKET_V1: - case ProtocolInfo.LEVEL_SOUND_EVENT_PACKET_V2: - case ProtocolInfo.LEVEL_SOUND_EVENT_PACKET: - if (!this.isSpectator()) { - this.level.addChunkPacket(this.getChunkX(), this.getChunkZ(), packet); - } - break; - case ProtocolInfo.INVENTORY_TRANSACTION_PACKET: - if (this.isSpectator()) { - this.sendAllInventories(); - break; + action = new NetworkInventoryAction(); + action.sourceType = NetworkInventoryAction.SOURCE_TODO; + action.windowId = NetworkInventoryAction.SOURCE_TYPE_ANVIL_RESULT; + action.inventorySlot = 2; // result + action.oldItem = toResult.clone(); + action.newItem = fromResult.clone(); + fixedPacket.actions[3] = action; + + action = new NetworkInventoryAction(); + action.sourceType = NetworkInventoryAction.SOURCE_TODO; + action.windowId = NetworkInventoryAction.SOURCE_TYPE_ANVIL_INPUT; + action.inventorySlot = 0; // equipment + action.oldItem = toEquipment.clone(); + action.newItem = fromEquipment.clone(); + fixedPacket.actions[4] = action; + + action = new NetworkInventoryAction(); + action.sourceType = NetworkInventoryAction.SOURCE_TODO; + action.windowId = NetworkInventoryAction.SOURCE_TYPE_ANVIL_MATERIAL; + action.inventorySlot = 1; // material + action.oldItem = toIngredient.clone(); + action.newItem = fromIngredient.clone(); + fixedPacket.actions[5] = action; + + transactionPacket = fixedPacket; } + } - InventoryTransactionPacket transactionPacket = (InventoryTransactionPacket) packet; - - List actions = new ArrayList<>(); - for (NetworkInventoryAction networkInventoryAction : transactionPacket.actions) { - InventoryAction a = networkInventoryAction.createInventoryAction(this); - - if (a == null) { - this.getServer().getLogger().debug("Unmatched inventory action from " + this.getName() + ": " + networkInventoryAction); - this.sendAllInventories(); - break packetswitch; - } + List actions = new ArrayList<>(); + for (NetworkInventoryAction networkInventoryAction : transactionPacket.actions) { + InventoryAction a = networkInventoryAction.createInventoryAction(this); - actions.add(a); + if (a == null) { + this.getServer().getLogger().debug("Unmatched inventory action from " + this.username + ": " + networkInventoryAction); + this.needSendInventory = true; + return; } - if (transactionPacket.isCraftingPart) { - if (this.craftingTransaction == null) { - this.craftingTransaction = new CraftingTransaction(this, actions); + actions.add(a); + } + + if (transactionPacket.isCraftingPart) { + if (LoomTransaction.checkForItemPart(actions)) { + if (this.loomTransaction == null) { + this.loomTransaction = new LoomTransaction(this, actions); } else { for (InventoryAction action : actions) { - this.craftingTransaction.addAction(action); + this.loomTransaction.addAction(action); + } + } + if (this.loomTransaction.canExecute()) { + if (this.loomTransaction.execute()) { + level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_BLOCK_LOOM_USE); } } + this.loomTransaction = null; + return; + } - if (this.craftingTransaction.getPrimaryOutput() != null && this.craftingTransaction.canExecute()) { - //we get the actions for this in several packets, so we can't execute it until we get the result + if (this.craftingTransaction == null) { + this.craftingTransaction = new CraftingTransaction(this, actions); + } else { + for (InventoryAction action : actions) { + this.craftingTransaction.addAction(action); + } + } + if (this.craftingTransaction.getPrimaryOutput() != null && this.craftingTransaction.canExecute()) { + try { this.craftingTransaction.execute(); - this.craftingTransaction = null; + } catch (Exception e) { + this.server.getLogger().debug(username + ": executing crafting transaction failed"); } - - return; - } else if (transactionPacket.isEnchantingPart) { - if (this.enchantTransaction == null) { - this.enchantTransaction = new EnchantTransaction(this, actions); + this.craftingTransaction = null; + } + return; + } else if (transactionPacket.isEnchantingPart) { + if (this.enchantTransaction == null) { + this.enchantTransaction = new EnchantTransaction(this, actions); + } else { + for (InventoryAction action : actions) { + this.enchantTransaction.addAction(action); + } + } + if (this.enchantTransaction.canExecute()) { + this.enchantTransaction.execute(); + this.enchantTransaction = null; + } + return; + } else if (transactionPacket.isRepairItemPart) { + if (SmithingTransaction.checkForItemPart(actions)) { + if (this.smithingTransaction == null) { + this.smithingTransaction = new SmithingTransaction(this, actions); } else { for (InventoryAction action : actions) { - this.enchantTransaction.addAction(action); + this.smithingTransaction.addAction(action); } } - if (this.enchantTransaction.canExecute()) { - this.enchantTransaction.execute(); - this.enchantTransaction = null; + if (this.smithingTransaction.canExecute()) { + if (this.smithingTransaction.execute()) { + Collection players = level.getChunkPlayers(getChunkX(), getChunkZ()).values(); + players.remove(this); + if (!players.isEmpty()) { + level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_BLOCK_SMITHING_TABLE_USE); + } + } + this.smithingTransaction = null; } - return; - } else if (transactionPacket.isRepairItemPart) { + } else { if (this.repairItemTransaction == null) { this.repairItemTransaction = new RepairItemTransaction(this, actions); } else { @@ -3141,493 +4089,729 @@ public void onCompletion(Server server) { this.repairItemTransaction.execute(); this.repairItemTransaction = null; } - return; - } else if (this.craftingTransaction != null) { - if (craftingTransaction.checkForCraftingPart(actions)) { - for (InventoryAction action : actions) { - craftingTransaction.addAction(action); - } + } + return; + } else if (this.craftingTransaction != null) { + if (craftingTransaction.checkForCraftingPart(actions)) { + if (craftingType == CRAFTING_LOOM) { + craftingTransaction = null; return; - } else { - this.server.getLogger().debug("Got unexpected normal inventory action with incomplete crafting transaction from " + this.getName() + ", refusing to execute crafting"); - this.removeAllWindows(false); - this.sendAllInventories(); - this.craftingTransaction = null; } - } else if (this.enchantTransaction != null) { - if (enchantTransaction.checkForEnchantPart(actions)) { - for (InventoryAction action : actions) { - enchantTransaction.addAction(action); - } - return; - } else { - this.server.getLogger().debug("Got unexpected normal inventory action with incomplete enchanting transaction from " + this.getName() + ", refusing to execute enchant " + transactionPacket.toString()); - this.removeAllWindows(false); - this.sendAllInventories(); - this.enchantTransaction = null; + for (InventoryAction action : actions) { + craftingTransaction.addAction(action); } - } else if (this.repairItemTransaction != null) { - if (RepairItemTransaction.checkForRepairItemPart(actions)) { - for (InventoryAction action : actions) { - this.repairItemTransaction.addAction(action); - } - return; - } else { - this.server.getLogger().debug("Got unexpected normal inventory action with incomplete repair item transaction from " + this.getName() + ", refusing to execute repair item " + transactionPacket.toString()); - this.removeAllWindows(false); - this.sendAllInventories(); - this.repairItemTransaction = null; + return; + } else { + this.server.getLogger().debug("Got unexpected normal inventory action with incomplete crafting transaction from " + this.username + ", refusing to execute crafting"); + this.removeAllWindows(false); + this.needSendInventory = true; + this.craftingTransaction = null; + } + } else if (this.enchantTransaction != null) { + if (enchantTransaction.checkForEnchantPart(actions)) { + for (InventoryAction action : actions) { + enchantTransaction.addAction(action); + } + return; + } else { + this.server.getLogger().debug("Got unexpected normal inventory action with incomplete enchanting transaction from " + this.username + ", refusing to execute enchant " + transactionPacket.toString()); + this.removeAllWindows(false); + this.enchantTransaction = null; + this.needSendInventory = true; + } + } else if (this.repairItemTransaction != null) { + if (RepairItemTransaction.checkForRepairItemPart(actions)) { + for (InventoryAction action : actions) { + this.repairItemTransaction.addAction(action); + } + return; + } else { + this.server.getLogger().debug("Got unexpected normal inventory action with incomplete repair item transaction from " + this.username + ", refusing to execute repair item " + transactionPacket.toString()); + this.removeAllWindows(false); + this.repairItemTransaction = null; + this.needSendInventory = true; + } + } else if (this.smithingTransaction != null) { + if (SmithingTransaction.checkForItemPart(actions)) { + for (InventoryAction action : actions) { + this.smithingTransaction.addAction(action); } + return; + } else { + this.server.getLogger().debug("Got unexpected normal inventory action with incomplete repair item transaction from " + this.username + ", refusing to execute smithing " + transactionPacket.toString()); + this.removeAllWindows(false); + this.smithingTransaction = null; + this.needSendInventory = true; } + } - switch (transactionPacket.transactionType) { - case InventoryTransactionPacket.TYPE_NORMAL: - InventoryTransaction transaction = new InventoryTransaction(this, actions); + switch (transactionPacket.transactionType) { + case InventoryTransactionPacket.TYPE_NORMAL: + InventoryTransaction transaction = new InventoryTransaction(this, actions); - if (!transaction.execute()) { - this.server.getLogger().debug("Failed to execute inventory transaction from " + this.getName() + " with actions: " + Arrays.toString(transactionPacket.actions)); - break packetswitch; //oops! - } + if (!transaction.execute()) { + this.server.getLogger().debug("Failed to execute inventory transaction from " + this.username + " with actions: " + Arrays.toString(transactionPacket.actions)); + return; + } - //TODO: fix achievement for getting iron from furnace + return; + case InventoryTransactionPacket.TYPE_MISMATCH: + if (transactionPacket.actions.length > 0) { + this.server.getLogger().debug("Expected 0 actions for mismatch, got " + transactionPacket.actions.length + ", " + Arrays.toString(transactionPacket.actions)); + } + this.needSendInventory = true; + return; + case InventoryTransactionPacket.TYPE_USE_ITEM: + UseItemData useItemData = (UseItemData) transactionPacket.transactionData; + BlockVector3 blockVector = useItemData.blockPos; + BlockFace face = useItemData.face; + int type = useItemData.actionType; - break packetswitch; - case InventoryTransactionPacket.TYPE_MISMATCH: - if (transactionPacket.actions.length > 0) { - this.server.getLogger().debug("Expected 0 actions for mismatch, got " + transactionPacket.actions.length + ", " + Arrays.toString(transactionPacket.actions)); - } - this.sendAllInventories(); + this.setShieldBlockingDelay(5); - break packetswitch; - case InventoryTransactionPacket.TYPE_USE_ITEM: - UseItemData useItemData = (UseItemData) transactionPacket.transactionData; + boolean itemSent = false; // Fix inventory desync but only send the slot once - BlockVector3 blockVector = useItemData.blockPos; - face = useItemData.face; + if (inventory.getHeldItemIndex() != useItemData.hotbarSlot) { + inventory.equipItem(useItemData.hotbarSlot); - int type = useItemData.actionType; - switch (type) { - case InventoryTransactionPacket.USE_ITEM_ACTION_CLICK_BLOCK: - // Remove if client bug is ever fixed - boolean spamBug = (lastRightClickPos != null && System.currentTimeMillis() - lastRightClickTime < 100.0 && blockVector.distanceSquared(lastRightClickPos) < 0.00001); - lastRightClickPos = blockVector.asVector3(); - lastRightClickTime = System.currentTimeMillis(); - if (spamBug) { - return; - } + itemSent = true; // Assume that the item is still correct even if the selected slot is not + } - this.setDataFlag(DATA_FLAGS, DATA_FLAG_ACTION, false); + switch (type) { + case InventoryTransactionPacket.USE_ITEM_ACTION_CLICK_BLOCK: + // Hack: Fix client spamming right clicks + if ((lastRightClickPos != null && this.getInventory().getItemInHandFast().getBlockId() == BlockID.AIR && System.currentTimeMillis() - lastRightClickTime < 200.0 && blockVector.distanceSquared(lastRightClickPos) < 0.00001)) { + return; + } - if (this.canInteract(blockVector.add(0.5, 0.5, 0.5), this.isCreative() ? 14 : 8)) { - if (this.isCreative()) { - Item i = inventory.getItemInHand(); - if (this.level.useItemOn(blockVector.asVector3(), i, face, useItemData.clickPos.x, useItemData.clickPos.y, useItemData.clickPos.z, this) != null) { - break packetswitch; - } - } else if (inventory.getItemInHand().equals(useItemData.itemInHand)) { - Item i = inventory.getItemInHand(); - Item oldItem = i.clone(); - //TODO: Implement adventure mode checks - if ((i = this.level.useItemOn(blockVector.asVector3(), i, face, useItemData.clickPos.x, useItemData.clickPos.y, useItemData.clickPos.z, this)) != null) { - if (!i.equals(oldItem) || i.getCount() != oldItem.getCount()) { - if (oldItem.getId() == i.getId() || i.getId() == 0) { - inventory.setItemInHand(i); - } else { - server.getLogger().debug("Tried to set item " + i.getId() + " but " + this.username + " had item " + oldItem.getId() + " in their hand slot"); - } - inventory.sendHeldItem(this.getViewers().values()); - } - break packetswitch; - } - } - } + lastRightClickPos = blockVector.asVector3(); + lastRightClickTime = System.currentTimeMillis(); - inventory.sendHeldItem(this); + this.breakingBlock = null; - if (blockVector.distanceSquared(this) > 10000) { - break packetswitch; - } + this.setUsingItem(false); - Block target = this.level.getBlock(blockVector.asVector3()); - block = target.getSide(face); + // We don't seem to verify useItemData.clickPos so don't use it for anything important + if (this.canInteract(blockVector.add(0.5, 0.5, 0.5), this.isCreative() ? 14 : 8)) { + Item i = inventory.getItemInHand(); + if (this.isCreative()) { + if (this.level.useItemOn(blockVector.asVector3(), i, face, useItemData.clickPos.x, useItemData.clickPos.y, useItemData.clickPos.z, this) != null) { + return; + } + } else { + Item oldItem = i.clone(); // This must be cloned - this.level.sendBlocks(new Player[]{this}, new Block[]{target, block}, UpdateBlockPacket.FLAG_ALL_PRIORITY); - break packetswitch; - case InventoryTransactionPacket.USE_ITEM_ACTION_BREAK_BLOCK: - if (!this.spawned || !this.isAlive()) { - break packetswitch; - } - - System.out.println("USE_ITEM_ACTION_BREAK_BLOCK"); - - this.resetCraftingGridType(); - - Item i = this.getInventory().getItemInHand(); - - Item oldItem = i.clone(); - - if (this.canInteract(blockVector.add(0.5, 0.5, 0.5), this.isCreative() ? 14 : 8) && (i = this.level.useBreakOn(blockVector.asVector3(), face, i, this, true)) != null) { - if (this.isSurvival()) { - this.getFoodData().updateFoodExpLevel(0.005); - if (!i.equals(oldItem) || i.getCount() != oldItem.getCount()) { + if ((i = this.level.useItemOn(blockVector.asVector3(), i, face, useItemData.clickPos.x, useItemData.clickPos.y, useItemData.clickPos.z, this)) != null) { + if (i.getCount() != oldItem.getCount() || i.getDamage() != oldItem.getDamage() || !i.equals(oldItem)) { // Quick checks first if (oldItem.getId() == i.getId() || i.getId() == 0) { inventory.setItemInHand(i); - } else { + + itemSent = true; + } else if (Nukkit.DEBUG > 1) { server.getLogger().debug("Tried to set item " + i.getId() + " but " + this.username + " had item " + oldItem.getId() + " in their hand slot"); } - inventory.sendHeldItem(this.getViewers().values()); } + + if (!itemSent && !oldItem.equals(useItemData.itemInHand)) { + this.needSendHeldItem = true; + } + return; } - break packetswitch; } + } + + this.needSendHeldItem = true; + + if (blockVector.distanceSquared(this) > 10000) { + return; + } + + Block target = this.level.getBlock(blockVector.asVector3()); + block = target.getSide(face); + + this.level.sendBlocks(this, new Block[]{target, block}, UpdateBlockPacket.FLAG_ALL_PRIORITY); + + if (target instanceof BlockDoor) { + BlockDoor door = (BlockDoor) target; - inventory.sendContents(this); - inventory.sendHeldItem(this); + Block part; - if (blockVector.distanceSquared(this) < 10000) { - target = this.level.getBlock(blockVector.asVector3()); - this.level.sendBlocks(new Player[]{this}, new Block[]{target}, UpdateBlockPacket.FLAG_ALL_PRIORITY); + if ((door.getDamage() & 0x08) > 0) { + part = target.down(); - BlockEntity blockEntity = this.level.getBlockEntity(blockVector.asVector3()); - if (blockEntity instanceof BlockEntitySpawnable) { - ((BlockEntitySpawnable) blockEntity).spawnTo(this); + if (part.getId() == target.getId()) { + target = part; + + this.level.sendBlocks(this, new Block[]{target}, UpdateBlockPacket.FLAG_ALL_PRIORITY); } } + } + return; + case InventoryTransactionPacket.USE_ITEM_ACTION_BREAK_BLOCK: + return; + case InventoryTransactionPacket.USE_ITEM_ACTION_CLICK_AIR: + if (!this.spawned || !this.isAlive()) { + return; + } - break packetswitch; - case InventoryTransactionPacket.USE_ITEM_ACTION_CLICK_AIR: - Vector3 directionVector = this.getDirectionVector(); + if (inventory.getHeldItemIndex() != useItemData.hotbarSlot) { + this.inventory.equipItem(useItemData.hotbarSlot); - if (this.isCreative()) { - item = this.inventory.getItemInHand(); - } else if (!this.inventory.getItemInHand().equals(useItemData.itemInHand)) { - this.inventory.sendHeldItem(this); - break packetswitch; - } else { - item = this.inventory.getItemInHand(); - } + this.crossbowLoadTick = 0; + } + + item = this.inventory.getItemInHand(); + + this.breakingBlock = null; - PlayerInteractEvent interactEvent = new PlayerInteractEvent(this, item, directionVector, face, Action.RIGHT_CLICK_AIR); + Vector3 directionVector = this.getDirectionVector(); + PlayerInteractEvent interactEvent = new PlayerInteractEvent(this, item, directionVector, face, Action.RIGHT_CLICK_AIR); + this.server.getPluginManager().callEvent(interactEvent); - this.server.getPluginManager().callEvent(interactEvent); + if (interactEvent.isCancelled()) { + this.needSendHeldItem = true; + return; + } - if (interactEvent.isCancelled()) { - this.inventory.sendHeldItem(this); - break packetswitch; + if (item instanceof ItemCrossbow) { + ItemCrossbow crossbow = ((ItemCrossbow) item); + if (crossbow.isLoaded()) { + if (this.crossbowLoadTick + 5 < this.server.getTick()) { + crossbow.launchArrow(this); + } + } else { + if (this.isUsingItem()) { + // Used item + int ticksUsed = this.server.getTick() - this.startAction; + this.crossbowLoadTick = this.server.getTick(); + this.setUsingItem(false); + item.onUse(this, ticksUsed); // Load crossbow + } else { + this.setUsingItem(true); + this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_CROSSBOW_LOADING_START); + } } + return; + } - if (item.onClickAir(this, directionVector)) { - if (!this.isCreative()) { - if (item.getId() == 0 || this.inventory.getItemInHand().getId() == item.getId()) { - this.inventory.setItemInHand(item); - } else { - server.getLogger().debug("Tried to set item " + item.getId() + " but " + this.username + " had item " + this.inventory.getItemInHand().getId() + " in their hand slot"); + int oldCount = item.getCount(); + int oldDamage = item.getDamage(); + if (item.onClickAir(this, directionVector)) { + if (this.isSurvival() || this.isAdventure()) { + // Don't set the item if not changed + // Update this to use equals() if NBT is ever modified in onClickAir + if (item.getId() == 0 || ((item.getCount() != oldCount || item.getDamage() != oldDamage) && this.inventory.getItemInHandFast().getId() == item.getId())) { + if (item instanceof ItemFishingRod && item.getDamage() >= item.getMaxDurability()) { + this.level.addSound(this, Sound.RANDOM_BREAK); + this.level.addParticle(new ItemBreakParticle(this, item)); + item = Item.get(Item.AIR); } - } - if (!this.isUsingItem()) { - this.setUsingItem(true); - break packetswitch; + this.inventory.setItemInHand(item); } + } + if (this.isUsingItem()) { // Used item int ticksUsed = this.server.getTick() - this.startAction; this.setUsingItem(false); - if (!item.onUse(this, ticksUsed)) { - this.inventory.sendContents(this); + this.needSendHeldItem = true; } + } else { + this.setUsingItem(true); } + } - break packetswitch; - default: - //unknown - break; - } - break; - case InventoryTransactionPacket.TYPE_USE_ITEM_ON_ENTITY: - UseItemOnEntityData useItemOnEntityData = (UseItemOnEntityData) transactionPacket.transactionData; - - Entity target = this.level.getEntity(useItemOnEntityData.entityRuntimeId); - if (target == null) { return; - } + } + return; + case InventoryTransactionPacket.TYPE_USE_ITEM_ON_ENTITY: + UseItemOnEntityData useItemOnEntityData = (UseItemOnEntityData) transactionPacket.transactionData; - type = useItemOnEntityData.actionType; + Entity target = this.level.getEntity(useItemOnEntityData.entityRuntimeId); + if (target == null) { + return; + } - if (!useItemOnEntityData.itemInHand.equalsExact(this.inventory.getItemInHand())) { - this.inventory.sendHeldItem(this); - } + type = useItemOnEntityData.actionType; - item = this.inventory.getItemInHand(); + if (inventory.getHeldItemIndex() != useItemOnEntityData.hotbarSlot) { + inventory.equipItem(useItemOnEntityData.hotbarSlot); + } - switch (type) { - case InventoryTransactionPacket.USE_ITEM_ON_ENTITY_ACTION_INTERACT: - PlayerInteractEntityEvent playerInteractEntityEvent = new PlayerInteractEntityEvent(this, target, item, useItemOnEntityData.clickPos); - if (this.isSpectator()) playerInteractEntityEvent.setCancelled(); - getServer().getPluginManager().callEvent(playerInteractEntityEvent); + item = this.inventory.getItemInHand(); - if (playerInteractEntityEvent.isCancelled()) { - break; - } - if (target.onInteract(this, item, useItemOnEntityData.clickPos) && this.isSurvival()) { - if (item.isTool()) { - if (item.useOn(target) && item.getDamage() >= item.getMaxDurability()) { - item = new ItemBlock(Block.get(BlockID.AIR)); - } - } else { - if (item.count > 1) { - item.count--; - } else { - item = new ItemBlock(Block.get(BlockID.AIR)); - } - } + switch (type) { + case InventoryTransactionPacket.USE_ITEM_ON_ENTITY_ACTION_INTERACT: + if (this.distanceSquared(target) > 1000) { + this.getServer().getLogger().debug(username + ": target entity is too far away"); + return; + } - if (item.getId() == 0 || this.inventory.getItemInHand().getId() == item.getId()) { - this.inventory.setItemInHand(item); - } else { - server.getLogger().debug("Tried to set item " + item.getId() + " but " + this.username + " had item " + this.inventory.getItemInHand().getId() + " in their hand slot"); + this.breakingBlock = null; + + this.setUsingItem(false); + + PlayerInteractEntityEvent playerInteractEntityEvent = new PlayerInteractEntityEvent(this, target, item, useItemOnEntityData.clickPos); + if (this.isSpectator()) playerInteractEntityEvent.setCancelled(); + getServer().getPluginManager().callEvent(playerInteractEntityEvent); + + if (playerInteractEntityEvent.isCancelled()) { + return; + } + + if (target.onInteract(this, item, useItemOnEntityData.clickPos) && (this.isSurvival() || this.isAdventure())) { + if (item.isTool()) { + if (item.useOn(target) && item.getDamage() >= item.getMaxDurability()) { + level.addSound(this, Sound.RANDOM_BREAK); + level.addParticle(new ItemBreakParticle(this, item)); + item = Item.get(Item.AIR); } - } - break; - case InventoryTransactionPacket.USE_ITEM_ON_ENTITY_ACTION_ATTACK: - if (!this.canInteract(target, isCreative() ? 8 : 5)) { - break; - } else if (target instanceof Player) { - if ((((Player) target).getGamemode() & 0x01) > 0) { - break; - } else if (!this.server.getPropertyBoolean("pvp")) { - break; + } else { + if (item.count > 1) { + item.count--; + } else { + item = Item.get(Item.AIR); } } - Enchantment[] enchantments = item.getEnchantments(); + if (item.getId() == 0 || this.inventory.getItemInHandFast().getId() == item.getId()) { + this.inventory.setItemInHand(item); + } else if (Nukkit.DEBUG > 1) { + server.getLogger().debug("Tried to set item " + item.getId() + " but " + this.username + " had item " + this.inventory.getItemInHandFast().getId() + " in their hand slot"); + } + } + return; + case InventoryTransactionPacket.USE_ITEM_ON_ENTITY_ACTION_ATTACK: + if (target.getId() == this.getId()) { + this.kick(PlayerKickEvent.Reason.INVALID_PVP, "Tried to attack invalid player"); + return; + } - float itemDamage = item.getAttackDamage(); - for (Enchantment enchantment : enchantments) { - itemDamage += enchantment.getDamageBonus(target); + if (!this.canInteractEntity(target, isCreative() ? 64 : 25)) { // 8 : 5 + return; + } else if (target instanceof Player) { + if ((((Player) target).gamemode & 0x01) > 0) { + return; + } else if (!this.server.pvpEnabled) { + return; } + } - Map damage = new EnumMap<>(DamageModifier.class); - damage.put(DamageModifier.BASE, itemDamage); + this.breakingBlock = null; - float knockBack = 0.3f; - Enchantment knockBackEnchantment = item.getEnchantment(Enchantment.ID_KNOCKBACK); - if (knockBackEnchantment != null) { - knockBack += knockBackEnchantment.getLevel() * 0.1f; - } + this.setUsingItem(false); + + if (this.sleeping != null) { + this.getServer().getLogger().debug(username + ": USE_ITEM_ON_ENTITY_ACTION_ATTACK while sleeping"); + return; + } + + if (this.inventoryOpen) { + this.getServer().getLogger().debug(username + ": USE_ITEM_ON_ENTITY_ACTION_ATTACK while viewing inventory"); + return; + } - EntityDamageByEntityEvent entityDamageByEntityEvent = new EntityDamageByEntityEvent(this, target, DamageCause.ENTITY_ATTACK, damage, knockBack, enchantments); - if (this.isSpectator()) entityDamageByEntityEvent.setCancelled(); - if ((target instanceof Player) && !this.level.getGameRules().getBoolean(GameRule.PVP)) { - entityDamageByEntityEvent.setCancelled(); + this.setShieldBlockingDelay(5); + + if (server.attackStopSprint) { + this.setSprinting(false); + } + + Enchantment[] enchantments = item.getEnchantments(); + + float itemDamage = item.getAttackDamage(); + for (Enchantment enchantment : enchantments) { + itemDamage += enchantment.getDamageBonus(target); + } + + Map damage = new EnumMap<>(DamageModifier.class); + damage.put(DamageModifier.BASE, itemDamage); + + float knockBack = 0.3f; + Enchantment knockBackEnchantment = item.getEnchantment(Enchantment.ID_KNOCKBACK); + if (knockBackEnchantment != null) { + knockBack += knockBackEnchantment.getLevel() * 0.1f; + } + + EntityDamageByEntityEvent entityDamageByEntityEvent = new EntityDamageByEntityEvent(this, target, DamageCause.ENTITY_ATTACK, damage, knockBack, enchantments); + entityDamageByEntityEvent.setWeapon(item); + + if (this.isSpectator()) { + entityDamageByEntityEvent.setCancelled(); + } + if ((target instanceof Player) && !this.level.getGameRules().getBoolean(GameRule.PVP)) { + entityDamageByEntityEvent.setCancelled(); + } + + if (!target.attack(entityDamageByEntityEvent)) { + if (item.isTool() && !this.isCreative()) { + this.needSendHeldItem = true; } + return; + } + + for (Enchantment enchantment : item.getEnchantments()) { + enchantment.doPostAttack(this, target); + } - if (!target.attack(entityDamageByEntityEvent)) { - if (item.isTool() && this.isSurvival()) { - this.inventory.sendContents(this); + if (item.isTool() && !this.isCreative()) { + if (item.useOn(target) && item.getDamage() >= item.getMaxDurability()) { + level.addSound(this, Sound.RANDOM_BREAK); + level.addParticle(new ItemBreakParticle(this, item)); + this.inventory.clear(this.inventory.getHeldItemIndex(), true); + } else { + if (item.getId() == 0 || this.inventory.getItemInHandFast().getId() == item.getId()) { + this.inventory.setItemInHand(item); + } else if (Nukkit.DEBUG > 1) { + server.getLogger().debug("Tried to set item " + item.getId() + " but " + this.username + " had item " + this.inventory.getItemInHandFast().getId() + " in their hand slot"); } - break; } + } + return; + } - for (Enchantment enchantment : item.getEnchantments()) { - enchantment.doPostAttack(this, target); - } + return; + case InventoryTransactionPacket.TYPE_RELEASE_ITEM: + if (this.isSpectator()) { + this.needSendInventory = true; + return; + } + ReleaseItemData releaseItemData = (ReleaseItemData) transactionPacket.transactionData; - if (item.isTool() && (this.isSurvival() || this.isAdventure())) { - if (item.useOn(target) && item.getDamage() >= item.getMaxDurability()) { - this.inventory.setItemInHand(Item.get(0)); - } else { - if (item.getId() == 0 || this.inventory.getItemInHand().getId() == item.getId()) { - this.inventory.setItemInHand(item); - } else { - server.getLogger().debug("Tried to set item " + item.getId() + " but " + this.username + " had item " + this.inventory.getItemInHand().getId() + " in their hand slot"); - } + try { + type = releaseItemData.actionType; + switch (type) { + case InventoryTransactionPacket.RELEASE_ITEM_ACTION_RELEASE: + if (this.isUsingItem()) { + int ticksUsed = this.server.getTick() - this.startAction; + if (!this.inventory.getItemInHand().onRelease(this, ticksUsed)) { + this.needSendHeldItem = true; } + this.setUsingItem(false); + } else { + this.needSendHeldItem = true; } return; + case InventoryTransactionPacket.RELEASE_ITEM_ACTION_CONSUME: + return; default: - break; //unknown + this.getServer().getLogger().debug(username + ": unknown release item action type: " + type); } + } finally { + this.setUsingItem(false); + } + return; + default: + this.needSendHeldItem = true; + } + return; + case ProtocolInfo.PLAYER_HOTBAR_PACKET: + if (!this.spawned || !this.isAlive()) { + return; + } - break; - case InventoryTransactionPacket.TYPE_RELEASE_ITEM: - if (this.isSpectator()) { - this.sendAllInventories(); - break packetswitch; - } - ReleaseItemData releaseItemData = (ReleaseItemData) transactionPacket.transactionData; + PlayerHotbarPacket hotbarPacket = (PlayerHotbarPacket) packet; - try { - type = releaseItemData.actionType; - switch (type) { - case InventoryTransactionPacket.RELEASE_ITEM_ACTION_RELEASE: - if (this.isUsingItem()) { - item = this.inventory.getItemInHand(); + if (hotbarPacket.windowId != ContainerIds.INVENTORY) { + return; + } - int ticksUsed = this.server.getTick() - this.startAction; - if (!item.onRelease(this, ticksUsed)) { - this.inventory.sendContents(this); - } + if (this.inventory == null) { + return; + } - this.setUsingItem(false); - } else { - this.inventory.sendContents(this); - } - return; - case InventoryTransactionPacket.RELEASE_ITEM_ACTION_CONSUME: - log.debug("Unexpected release item action consume from {}", this::getName); - return; - default: - break; - } - } finally { - this.setUsingItem(false); - } - break; - default: - this.inventory.sendContents(this); - break; - } - break; - case ProtocolInfo.PLAYER_HOTBAR_PACKET: - PlayerHotbarPacket hotbarPacket = (PlayerHotbarPacket) packet; + this.inventory.equipItem(hotbarPacket.selectedHotbarSlot); + this.setUsingItem(false); + return; + case ProtocolInfo.SERVER_SETTINGS_REQUEST_PACKET: + PlayerServerSettingsRequestEvent settingsRequestEvent = new PlayerServerSettingsRequestEvent(this, new HashMap<>(this.serverSettings)); + this.getServer().getPluginManager().callEvent(settingsRequestEvent); + + if (!settingsRequestEvent.isCancelled()) { + settingsRequestEvent.getSettings().forEach((id, window) -> { + ServerSettingsResponsePacket re = new ServerSettingsResponsePacket(); + re.formId = id; + re.data = window.getJSONData(); + this.dataPacket(re); + }); + } + return; + case ProtocolInfo.SET_LOCAL_PLAYER_AS_INITIALIZED_PACKET: + if (this.locallyInitialized) { + return; + } + this.doFirstSpawn(); + return; + case ProtocolInfo.RESPAWN_PACKET: + if (this.isAlive()) { + return; + } - if (hotbarPacket.windowId != ContainerIds.INVENTORY) { - return; //In PE this should never happen - } + RespawnPacket respawnPacket = (RespawnPacket) packet; + if (respawnPacket.respawnState == RespawnPacket.STATE_CLIENT_READY_TO_SPAWN) { + RespawnPacket respawn1 = new RespawnPacket(); + respawn1.x = (float) this.getX(); + respawn1.y = (float) this.getY(); + respawn1.z = (float) this.getZ(); + respawn1.respawnState = RespawnPacket.STATE_READY_TO_SPAWN; + this.dataPacket(respawn1); + } + return; + case ProtocolInfo.BOOK_EDIT_PACKET: + if (!this.spawned) { + return; + } - this.inventory.equipItem(hotbarPacket.selectedHotbarSlot); - break; - case ProtocolInfo.SERVER_SETTINGS_REQUEST_PACKET: - PlayerServerSettingsRequestEvent settingsRequestEvent = new PlayerServerSettingsRequestEvent(this, new HashMap<>(this.serverSettings)); - this.getServer().getPluginManager().callEvent(settingsRequestEvent); - - if (!settingsRequestEvent.isCancelled()) { - settingsRequestEvent.getSettings().forEach((id, window) -> { - ServerSettingsResponsePacket re = new ServerSettingsResponsePacket(); - re.formId = id; - re.data = window.getJSONData(); - this.dataPacket(re); - }); - } - break; - case ProtocolInfo.RESPAWN_PACKET: - if (this.isAlive()) { + if (this.inventory == null) { + return; + } + + BookEditPacket bookEditPacket = (BookEditPacket) packet; + Item oldBook = this.inventory.getItem(bookEditPacket.inventorySlot); + if (oldBook.getId() != Item.BOOK_AND_QUILL) { + this.getServer().getLogger().debug(username + ": BookEditPacket for invalid item: expected Book & Quill (386), got " + oldBook.getId()); + return; + } + + if (bookEditPacket.text != null && bookEditPacket.text.length() > 256) { + this.getServer().getLogger().debug(username + ": BookEditPacket with too long text"); + return; + } + + Item newBook = oldBook.clone(); + boolean success; + switch (bookEditPacket.action) { + case REPLACE_PAGE: + success = ((ItemBookAndQuill) newBook).setPageText(bookEditPacket.pageNumber, bookEditPacket.text); break; + case ADD_PAGE: + success = ((ItemBookAndQuill) newBook).insertPage(bookEditPacket.pageNumber, bookEditPacket.text); + break; + case DELETE_PAGE: + success = ((ItemBookAndQuill) newBook).deletePage(bookEditPacket.pageNumber); + break; + case SWAP_PAGES: + success = ((ItemBookAndQuill) newBook).swapPages(bookEditPacket.pageNumber, bookEditPacket.secondaryPageNumber); + break; + case SIGN_BOOK: + newBook = Item.get(Item.WRITTEN_BOOK, 0, 1, oldBook.getCompoundTag()); + if (bookEditPacket.title == null || bookEditPacket.author == null || bookEditPacket.xuid == null || bookEditPacket.title.length() > 64 || bookEditPacket.author.length() > 64 || bookEditPacket.xuid.length() > 64) { + this.getServer().getLogger().debug(username + ": invalid BookEditPacket action SIGN_BOOK: title/author/xuid is too long"); + return; + } + success = ((ItemBookWritten) newBook).signBook(bookEditPacket.title, bookEditPacket.author, bookEditPacket.xuid, ItemBookWritten.GENERATION_ORIGINAL); + break; + default: + this.getServer().getLogger().debug(username + ": BookEditPacket unknown action: " + bookEditPacket.action); + return; + } + + if (success) { + PlayerEditBookEvent editBookEvent = new PlayerEditBookEvent(this, oldBook, newBook, bookEditPacket.action); + this.server.getPluginManager().callEvent(editBookEvent); + if (!editBookEvent.isCancelled()) { + this.inventory.setItem(bookEditPacket.inventorySlot, editBookEvent.getNewBook()); } - RespawnPacket respawnPacket = (RespawnPacket) packet; - if (respawnPacket.respawnState == RespawnPacket.STATE_CLIENT_READY_TO_SPAWN) { - RespawnPacket respawn1 = new RespawnPacket(); - respawn1.x = (float) this.getX(); - respawn1.y = (float) this.getY(); - respawn1.z = (float) this.getZ(); - respawn1.respawnState = RespawnPacket.STATE_READY_TO_SPAWN; - this.dataPacket(respawn1); + } + return; + case ProtocolInfo.PACKET_VIOLATION_WARNING_PACKET: + PacketViolationWarningPacket PVWpk = (PacketViolationWarningPacket) packet; + if (pkIDs == null) { + pkIDs = Arrays.stream(ProtocolInfo.class.getDeclaredFields()).filter(field -> field.getType() == Byte.TYPE); + } + Optional PVWpkName = pkIDs + .filter(field -> { + try { + return field.getByte(null) == ((PacketViolationWarningPacket) packet).packetId; + } catch (IllegalAccessException e) { + return false; + } + }).map(Field::getName).findFirst(); + this.getServer().getLogger().warning("PacketViolationWarningPacket" + PVWpkName.map(name -> " for " + name).orElse(" UNKNOWN") + " from " + this.username + ": " + PVWpk.toString()); + return; + case ProtocolInfo.EMOTE_PACKET: + if (!this.spawned || server.getTick() - this.lastEmote < 20 || this.isSpectator()) { + return; + } + this.lastEmote = server.getTick(); + EmotePacket emotePacket = (EmotePacket) packet; + if (emotePacket.runtimeId != this.id) { + this.getServer().getLogger().debug(username + ": EmotePacket eid mismatch"); + return; + } else if (emotePacket.emoteID == null || emotePacket.emoteID.isEmpty() || emotePacket.emoteID.length() > 100) { + this.getServer().getLogger().debug(username + " EmotePacket invalid emote id: " + emotePacket.emoteID); + return; + } + EmotePacket cleanEmotePacket = new EmotePacket(); + cleanEmotePacket.runtimeId = emotePacket.runtimeId; + cleanEmotePacket.emoteID = emotePacket.emoteID; + Server.broadcastPacket(this.getViewers().values(), cleanEmotePacket); + return; + case ProtocolInfo.LECTERN_UPDATE_PACKET: + if (!this.spawned) { + return; + } + + LecternUpdatePacket lecternUpdatePacket = (LecternUpdatePacket) packet; + Vector3 lecternPos = lecternUpdatePacket.blockPosition.asVector3(); + if (lecternPos.distanceSquared(this) > 4096) { + return; + } + if (!lecternUpdatePacket.dropBook) { + BlockEntity blockEntityLectern = this.level.getBlockEntityIfLoaded(this.chunk, lecternPos); + if (blockEntityLectern instanceof BlockEntityLectern) { + BlockEntityLectern lectern = (BlockEntityLectern) blockEntityLectern; + if (lectern.getRawPage() != lecternUpdatePacket.page) { + lectern.setRawPage(lecternUpdatePacket.page); + } } - break; - case ProtocolInfo.BOOK_EDIT_PACKET: - BookEditPacket bookEditPacket = (BookEditPacket) packet; - Item oldBook = this.inventory.getItem(bookEditPacket.inventorySlot); - if (oldBook.getId() != Item.BOOK_AND_QUILL) { - return; + } + return; + case ProtocolInfo.SET_DIFFICULTY_PACKET: + if (!this.spawned) { + return; + } + + if (!this.hasPermission("nukkit.command.difficulty")) { + if (!this.isOp()) { + this.kick(PlayerKickEvent.Reason.INVALID_PACKET, "Invalid SetDifficultyPacket", true); } + return; + } + server.setDifficulty(((SetDifficultyPacket) packet).difficulty); + Command.broadcastCommandMessage(this, new TranslationContainer("commands.difficulty.success", String.valueOf(server.getDifficulty()))); - if (bookEditPacket.text != null && bookEditPacket.text.length() > 256) { - this.getServer().getLogger().debug(username + ": BookEditPacket with too long text"); - return; + SetDifficultyPacket difficultyPacket = new SetDifficultyPacket(); + difficultyPacket.difficulty = server.getDifficulty(); + Server.broadcastPacket(server.getOnlinePlayers().values(), difficultyPacket); + return; + case ProtocolInfo.REQUEST_PERMISSIONS_PACKET: + if (!this.spawned) { + return; + } + + if (!this.isOp()) { + this.kick(PlayerKickEvent.Reason.INVALID_PACKET, "Invalid RequestPermissionsPacket", true); + return; + } + this.sendMessage(TextFormat.RED + "Unimplemented feature: REQUEST_PERMISSIONS_PACKET"); // TODO + return; + case ProtocolInfo.SET_DEFAULT_GAME_TYPE_PACKET: + if (!this.spawned) { + return; + } + + if (!this.hasPermission("nukkit.command.defaultgamemode")) { + if (!this.isOp()) { + this.kick(PlayerKickEvent.Reason.INVALID_PACKET, "Invalid SetDefaultGameTypePacket", true); } + return; + } + int gamemode = ((SetDefaultGameTypePacket) packet).gamemode & 0b11; + server.gamemode = gamemode; + server.setPropertyInt("gamemode", gamemode); + Command.broadcastCommandMessage(this, new TranslationContainer("commands.defaultgamemode.success", new String[]{Server.getGamemodeString(server.getDefaultGamemode())})); + + SetDefaultGameTypePacket gameTypePacket = new SetDefaultGameTypePacket(); + gameTypePacket.gamemode = server.getDefaultGamemode(); + Server.broadcastPacket(server.getOnlinePlayers().values(), gameTypePacket); + return; + case ProtocolInfo.SETTINGS_COMMAND_PACKET: + if (!this.spawned) { + return; + } - Item newBook = oldBook.clone(); - boolean success; - switch (bookEditPacket.action) { - case REPLACE_PAGE: - success = ((ItemBookAndQuill) newBook).setPageText(bookEditPacket.pageNumber, bookEditPacket.text); - break; - case ADD_PAGE: - success = ((ItemBookAndQuill) newBook).insertPage(bookEditPacket.pageNumber, bookEditPacket.text); - break; - case DELETE_PAGE: - success = ((ItemBookAndQuill) newBook).deletePage(bookEditPacket.pageNumber); - break; - case SWAP_PAGES: - success = ((ItemBookAndQuill) newBook).swapPages(bookEditPacket.pageNumber, bookEditPacket.secondaryPageNumber); - break; - case SIGN_BOOK: - if (bookEditPacket.title == null || bookEditPacket.author == null || bookEditPacket.xuid == null || bookEditPacket.title.length() > 64 || bookEditPacket.author.length() > 64 || bookEditPacket.xuid.length() > 64) { - this.getServer().getLogger().debug(username + ": Invalid BookEditPacket action SIGN_BOOK: title/author/xuid is too long"); - return; - } - newBook = Item.get(Item.WRITTEN_BOOK, 0, 1, oldBook.getCompoundTag()); - success = ((ItemBookWritten) newBook).signBook(bookEditPacket.title, bookEditPacket.author, bookEditPacket.xuid, ItemBookWritten.GENERATION_ORIGINAL); - break; - default: - return; + if (!this.hasPermission("nukkit.command.gamerule")) { + if (!this.isOp()) { + this.kick(PlayerKickEvent.Reason.INVALID_PACKET, "Invalid SettingsCommandPacket", true); } + return; + } + String command = ((SettingsCommandPacket) packet).command; + if (command.startsWith("/gamerule")) { + server.dispatchCommand(this, command.substring(1)); + } else { + this.getServer().getLogger().debug(username + ": SettingsCommandPacket unsupported command: " + command); + } + return; + } + } + + private void setShieldBlockingDelay(int delay) { + if (this.isBlocking()) { + this.setBlocking(false); + this.blockingDelay = delay; + } + } + + @Override + protected void onBlock(Entity damager, EntityDamageBlockedEvent event, EntityDamageEvent source) { + super.onBlock(damager, event, source); - if (success) { - PlayerEditBookEvent editBookEvent = new PlayerEditBookEvent(this, oldBook, newBook, bookEditPacket.action); - this.server.getPluginManager().callEvent(editBookEvent); - if (!editBookEvent.isCancelled()) { - this.inventory.setItem(bookEditPacket.inventorySlot, editBookEvent.getNewBook()); - } - } - break; - case ProtocolInfo.FILTER_TEXT_PACKET: - FilterTextPacket filterTextPacket = (FilterTextPacket) packet; - if (filterTextPacket.text == null || filterTextPacket.text.length() > 64) { - this.getServer().getLogger().debug(username + ": FilterTextPacket with too long text"); - return; - } - FilterTextPacket textResponsePacket = new FilterTextPacket(); - textResponsePacket.text = filterTextPacket.text; - textResponsePacket.fromServer = true; - this.dataPacket(textResponsePacket); - break; - case ProtocolInfo.SET_DIFFICULTY_PACKET: - if (!this.spawned || !this.hasPermission("nukkit.command.difficulty")) { - return; - } - server.setDifficulty(((SetDifficultyPacket) packet).difficulty); - SetDifficultyPacket difficultyPacket = new SetDifficultyPacket(); - difficultyPacket.difficulty = server.getDifficulty(); - Server.broadcastPacket(server.getOnlinePlayers().values(), difficultyPacket); - Command.broadcastCommandMessage(this, new TranslationContainer("commands.difficulty.success", String.valueOf(server.getDifficulty()))); - break; - default: - break; - } + if (source.getWeapon() != null && source.getWeapon().isAxe()) { + this.setShieldBlockingDelay(100); + this.startItemCooldown(100, "shield"); } } - private void onBlockBreakContinue(Vector3 pos, BlockFace face) { + public void startItemCooldown(int cooldownDuration, String itemCategory) { + PlayerStartItemCooldownPacket pk = new PlayerStartItemCooldownPacket(); + pk.itemCategory = itemCategory; + pk.cooldownDuration = cooldownDuration; + this.dataPacket(pk); + } + + private void onBlockBreakAbort(BlockVector3 blockPos, BlockFace face) { if (this.isBreakingBlock()) { - Block block = this.level.getBlock(pos, false); - this.level.addParticle(new PunchBlockParticle(pos, block, face)); + LevelEventPacket pk = new LevelEventPacket(); + pk.evid = LevelEventPacket.EVENT_BLOCK_STOP_BREAK; + pk.x = (float) breakingBlock.x; + pk.y = (float) breakingBlock.y; + pk.z = (float) breakingBlock.z; + pk.data = 0; + this.getLevel().addChunkPacket((int) breakingBlock.x >> 4, (int) breakingBlock.z >> 4, pk); } + this.breakingBlock = null; } - private void onBlockBreakStart(Vector3 pos, BlockFace face) { - BlockVector3 blockPos = pos.asBlockVector3(); + private void onBlockBreakStart(BlockVector3 blockPos, BlockFace face) { + if (this.isSpectator()) { + return; + } + + boolean posEquals = lastBreakPosition.equals(blockPos); + this.lastBreakPosition = blockPos; long currentBreak = System.currentTimeMillis(); // HACK: Client spams multiple left clicks so we need to skip them. - if ((this.lastBreakPosition.equals(blockPos) && (currentBreak - this.lastBreak) < 10) || pos.distanceSquared(this) > 100) { + if (posEquals && (currentBreak - this.lastBreak) < 10) { + return; + } else if (blockPos.distanceSquared(this) > 100) { + this.breakingBlock = null; return; } - Block target = this.level.getBlock(pos); - PlayerInteractEvent playerInteractEvent = new PlayerInteractEvent(this, this.inventory.getItemInHand(), target, face, - target.getId() == 0 ? Action.LEFT_CLICK_AIR : Action.LEFT_CLICK_BLOCK); + // Reset current block break + this.breakingBlock = null; + + this.setUsingItem(false); + + Item handItem = this.inventory.getItemInHand(); + Block target = this.level.getBlock(chunk, blockPos.x, blockPos.y, blockPos.z, false); + PlayerInteractEvent playerInteractEvent = new PlayerInteractEvent(this, handItem, target, face, target.getId() == 0 ? Action.LEFT_CLICK_AIR : Action.LEFT_CLICK_BLOCK); this.getServer().getPluginManager().callEvent(playerInteractEvent); if (playerInteractEvent.isCancelled()) { - this.inventory.sendHeldItem(this); + this.needSendHeldItem = true; return; } switch (target.getId()) { + case Block.AIR: + return; case Block.NOTEBLOCK: ((BlockNoteblock) target).emitSound(); - return; + break; // note blocks can be broken case Block.DRAGON_EGG: if (!this.isCreative()) { ((BlockDragonEgg) target).teleport(); @@ -3635,90 +4819,74 @@ private void onBlockBreakStart(Vector3 pos, BlockFace face) { } break; case Block.ITEM_FRAME_BLOCK: - BlockEntity itemFrame = this.level.getBlockEntity(pos); + case Block.GLOW_FRAME: + BlockEntity itemFrame = this.level.getBlockEntityIfLoaded(this.chunk, this.temporalVector.setComponents(blockPos.x, blockPos.y, blockPos.z)); if (itemFrame instanceof BlockEntityItemFrame && ((BlockEntityItemFrame) itemFrame).dropItem(this)) { return; } break; + case Block.LECTERN: + BlockEntity lectern = this.level.getBlockEntityIfLoaded(this.chunk, this.temporalVector.setComponents(blockPos.x, blockPos.y, blockPos.z)); + if (lectern instanceof BlockEntityLectern && ((BlockEntityLectern) lectern).dropBook(this)) { + return; + } + break; } - Block block = target.getSide(face); - if (block.getId() == Block.FIRE) { + int bid = this.level.getBlockIdAt(this.chunk, blockPos.x + face.getXOffset(), blockPos.y + face.getYOffset(), blockPos.z + face.getZOffset()); + if (bid == Block.FIRE || bid == Block.SOUL_FIRE) { + Vector3 block = this.temporalVector.setComponents(blockPos.x + face.getXOffset(), blockPos.y + face.getYOffset(), blockPos.z + face.getZOffset()); this.level.setBlock(block, Block.get(BlockID.AIR), true); this.level.addLevelSoundEvent(block, LevelSoundEventPacket.SOUND_EXTINGUISH_FIRE); return; } if (!this.isCreative()) { - double breakTime = Math.ceil(target.getBreakTime(this.inventory.getItemInHand(), this) * 20); - if (breakTime > 0) { + double breakTime = target.getBreakTime(handItem, this); + int breakTimeTicks = (int) (breakTime * 20 + 0.5); + if (breakTimeTicks > 0) { LevelEventPacket pk = new LevelEventPacket(); pk.evid = LevelEventPacket.EVENT_BLOCK_START_BREAK; - pk.x = (float) pos.x; - pk.y = (float) pos.y; - pk.z = (float) pos.z; - pk.data = (int) (65535 / breakTime); - this.getLevel().addChunkPacket(pos.getFloorX() >> 4, pos.getFloorZ() >> 4, pk); + pk.x = (float) blockPos.x; + pk.y = (float) blockPos.y; + pk.z = (float) blockPos.z; + pk.data = 65535 / breakTimeTicks; + this.getLevel().addChunkPacket(blockPos.x >> 4, blockPos.z >> 4, pk); } } this.breakingBlock = target; + this.breakingBlockFace = face; this.lastBreak = currentBreak; - this.lastBreakPosition = blockPos; - } - - private void onBlockBreakAbort(Vector3 pos, BlockFace face) { - if (pos.distanceSquared(this) < 100) { - LevelEventPacket pk = new LevelEventPacket(); - pk.evid = LevelEventPacket.EVENT_BLOCK_STOP_BREAK; - pk.x = (float) pos.x; - pk.y = (float) pos.y; - pk.z = (float) pos.z; - pk.data = 0; - this.getLevel().addChunkPacket(pos.getFloorX() >> 4, pos.getFloorZ() >> 4, pk); - } - this.breakingBlock = null; } - private void onBlockBreakComplete(BlockVector3 blockPos, BlockFace face) { + private void onBlockBreakComplete(BlockVector3 blockPos, BlockFace face) { // From InventoryTransactionPacket.USE_ITEM_ACTION_BREAK_BLOCK if (!this.spawned || !this.isAlive()) { return; } - this.resetCraftingGridType(); - - Item handItem = this.getInventory().getItemInHand(); - Item clone = handItem.clone(); - - boolean canInteract = this.canInteract(blockPos.add(0.5, 0.5, 0.5), this.isCreative() ? 14 : 8); - if (canInteract) { - handItem = this.level.useBreakOn(blockPos.asVector3(), face, handItem, this, true); - if (handItem == null) { - this.level.sendBlocks(new Player[]{this}, new Block[]{this.level.getBlock(blockPos.asVector3())}, UpdateBlockPacket.FLAG_ALL_PRIORITY); - } else if (this.isSurvival()) { - this.getFoodData().updateFoodExpLevel(0.005); - if (handItem.equals(clone) && handItem.getCount() == clone.getCount()) { - return; - } - - if (clone.getId() == handItem.getId() || handItem.getId() == 0) { - inventory.setItemInHand(handItem); - } else { - server.getLogger().debug("Tried to set item " + handItem.getId() + " but " + this.username + " had item " + clone.getId() + " in their hand slot"); + Item i = this.getInventory().getItemInHand(); + Item oldItem = i.clone(); + if (this.canInteract(blockPos.add(0.5, 0.5, 0.5), this.isCreative() ? 14 : 8) && (i = this.level.useBreakOn(blockPos.asVector3(), face, i, this, true)) != null) { + if (this.isSurvival() || this.isAdventure()) { + this.foodData.updateFoodExpLevel(0.005); + if (i.getCount() != oldItem.getCount() || i.getDamage() != oldItem.getDamage() || !i.equals(oldItem)) { + if (i.getId() == 0 || oldItem.getId() == i.getId()) { + inventory.setItemInHand(i); + + // setItem can only send armor to others, I wonder why this isn't needed at other places though + inventory.sendHeldItem(this.getViewers().values()); + } else if (Nukkit.DEBUG > 1) { + server.getLogger().debug("Tried to set item " + i.getId() + " but " + this.username + " had item " + oldItem.getId() + " in their hand slot"); + } } - inventory.sendHeldItem(this.getViewers().values()); } return; } - - inventory.sendContents(this); - inventory.sendHeldItem(this); - - if (blockPos.distanceSquared(this) < 100) { - Block target = this.level.getBlock(blockPos.asVector3()); - this.level.sendBlocks(new Player[]{this}, new Block[]{target}, UpdateBlockPacket.FLAG_ALL_PRIORITY); - - BlockEntity blockEntity = this.level.getBlockEntity(blockPos.asVector3()); + this.needSendHeldItem = true; + if (blockPos.distanceSquared(this) < 10000) { + this.level.sendBlocks(this, new Block[]{this.level.getBlock(blockPos.asVector3(), false)}, UpdateBlockPacket.FLAG_ALL_PRIORITY); + BlockEntity blockEntity = this.level.getBlockEntityIfLoaded(this.chunk, blockPos.asVector3()); if (blockEntity instanceof BlockEntitySpawnable) { ((BlockEntitySpawnable) blockEntity).spawnTo(this); } @@ -3726,29 +4894,51 @@ private void onBlockBreakComplete(BlockVector3 blockPos, BlockFace face) { } /** - * Sends a chat message as this player. If the message begins with a / (forward-slash) it will be treated - * as a command. + * Adjust map color to height map + * + * @param color block color + * @param colorLevel color level + * @return adjusted Color + */ + private static Color colorizeMapColor(BlockColor color, int colorLevel) { + int colorDepth; + + if (colorLevel == 2) { + colorDepth = 255; + } else if (colorLevel == 1) { + colorDepth = 220; + } else if (colorLevel == 0) { + colorDepth = 180; + } else { + throw new IllegalArgumentException("Invalid colorLevel: " + colorLevel); + } + + int r = color.getRed() * colorDepth / 255; + int g = color.getGreen() * colorDepth / 255; + int b = color.getBlue() * colorDepth / 255; + + return new Color(r, g, b); + } + + /** + * Sends a chat message as this player + * * @param message message to send * @return successful */ public boolean chat(String message) { - if (!this.spawned || !this.isAlive()) { - return false; - } - this.resetCraftingGridType(); - this.craftingType = CRAFTING_SMALL; if (this.removeFormat) { message = TextFormat.clean(message, true); } for (String msg : message.split("\n")) { - if (!msg.trim().isEmpty() && msg.length() <= 512 && this.messageCounter-- > 0) { + if (!msg.trim().isEmpty() && msg.length() < 512) { PlayerChatEvent chatEvent = new PlayerChatEvent(this, msg); this.server.getPluginManager().callEvent(chatEvent); if (!chatEvent.isCancelled()) { - this.server.broadcastMessage(this.getServer().getLanguage().translateString(chatEvent.getFormat(), new String[]{chatEvent.getPlayer().getDisplayName(), chatEvent.getMessage()}), chatEvent.getRecipients()); + this.server.broadcastMessage(this.getServer().getLanguage().translateString(chatEvent.getFormat(), new String[]{chatEvent.getPlayer().displayName, chatEvent.getMessage()}), chatEvent.getRecipients()); } } } @@ -3780,6 +4970,13 @@ public boolean kick(PlayerKickEvent.Reason reason, boolean isAdmin) { return this.kick(reason, reason.toString(), isAdmin); } + /** + * Kick the player + * @param reason reason + * @param reasonString reason string + * @param isAdmin display "kicked" or only reason string + * @return PlayerKickEvent not cancelled + */ public boolean kick(PlayerKickEvent.Reason reason, String reasonString, boolean isAdmin) { PlayerKickEvent ev; this.server.getPluginManager().callEvent(ev = new PlayerKickEvent(this, reason, reasonString, this.getLeaveMessage())); @@ -3787,7 +4984,7 @@ public boolean kick(PlayerKickEvent.Reason reason, String reasonString, boolean String message; if (isAdmin) { if (!this.isBanned()) { - message = "Kicked by admin." + (!reasonString.isEmpty() ? " Reason: " + reasonString : ""); + message = "Kicked!" + (!reasonString.isEmpty() ? " Reason: " + reasonString : ""); } else { message = reasonString; } @@ -3807,7 +5004,12 @@ public boolean kick(PlayerKickEvent.Reason reason, String reasonString, boolean return false; } + /** + * Set view distance + * @param distance view distance + */ public void setViewDistance(int distance) { + this.viewDistance = distance; this.chunkRadius = distance; ChunkRadiusUpdatedPacket pk = new ChunkRadiusUpdatedPacket(); @@ -3816,15 +5018,37 @@ public void setViewDistance(int distance) { this.dataPacket(pk); } + /** + * Get view distance (client may have updated this within the limits) + * @return view distance + */ public int getViewDistance() { return this.chunkRadius; } + /** + * Get maximum view distance. Use getViewDistance() to get the view distance possibly updated by client. + * @return view distance + */ + public int getMaximumViewDistance() { + return this.viewDistance; + } + @Override public void sendMessage(String message) { + this.sendMessage(message, false); + } + + /** + * Send a message + * @param message message + * @param isLocalized message has a translation + */ + public void sendMessage(String message, boolean isLocalized) { TextPacket pk = new TextPacket(); pk.type = TextPacket.TYPE_RAW; pk.message = this.server.getLanguage().translateString(message); + pk.isLocalized = isLocalized; this.dataPacket(pk); } @@ -3834,7 +5058,7 @@ public void sendMessage(TextContainer message) { this.sendTranslation(message.getText(), ((TranslationContainer) message).getParameters()); return; } - this.sendMessage(message.getText()); + this.sendMessage(message.getText(), false); } public void sendTranslation(String message) { @@ -3843,17 +5067,16 @@ public void sendTranslation(String message) { public void sendTranslation(String message, String[] parameters) { TextPacket pk = new TextPacket(); - if (!this.server.isLanguageForced()) { + if (this.server.isLanguageForced()) { + pk.type = TextPacket.TYPE_RAW; + pk.message = this.server.getLanguage().translateString(message, parameters); + } else { pk.type = TextPacket.TYPE_TRANSLATION; pk.message = this.server.getLanguage().translateString(message, parameters, "nukkit."); for (int i = 0; i < parameters.length; i++) { parameters[i] = this.server.getLanguage().translateString(parameters[i], parameters, "nukkit."); - } pk.parameters = parameters; - } else { - pk.type = TextPacket.TYPE_RAW; - pk.message = this.server.getLanguage().translateString(message, parameters); } this.dataPacket(pk); } @@ -3871,16 +5094,16 @@ public void sendChat(String source, String message) { } public void sendPopup(String message) { - this.sendPopup(message, ""); - } - - public void sendPopup(String message, String subtitle) { TextPacket pk = new TextPacket(); pk.type = TextPacket.TYPE_POPUP; pk.message = message; this.dataPacket(pk); } + public void sendPopup(String message, String subtitle) { + this.sendPopup(message); + } + public void sendTip(String message) { TextPacket pk = new TextPacket(); pk.type = TextPacket.TYPE_TIP; @@ -3888,6 +5111,9 @@ public void sendTip(String message) { this.dataPacket(pk); } + /** + * Remove currently playing title + */ public void clearTitle() { SetTitlePacket pk = new SetTitlePacket(); pk.type = SetTitlePacket.TYPE_CLEAR; @@ -3919,7 +5145,6 @@ public void setTitleAnimationTimes(int fadein, int duration, int fadeout) { this.dataPacket(pk); } - private void setTitle(String text) { SetTitlePacket packet = new SetTitlePacket(); packet.text = text; @@ -3940,7 +5165,7 @@ public void sendTitle(String title, String subtitle, int fadeIn, int stay, int f if (!Strings.isNullOrEmpty(subtitle)) { this.setSubtitle(subtitle); } - // title won't send if an empty string is used. + // Title won't send if an empty string is used this.setTitle(Strings.isNullOrEmpty(title) ? " " : title); } @@ -3958,6 +5183,11 @@ public void sendActionBar(String title, int fadein, int duration, int fadeout) { this.dataPacket(pk); } + /** + * Send toast notification for 1.19+ client + * @param title toast title + * @param content toast text + */ public void sendToast(String title, String content) { ToastRequestPacket pk = new ToastRequestPacket(); pk.title = title; @@ -3990,27 +5220,39 @@ public void close(TextContainer message, String reason) { this.close(message, reason, true); } + /** + * Close and disconnect the player + * @param message message + * @param reason reason + * @param notify send disconnection screen + */ public void close(TextContainer message, String reason, boolean notify) { if (this.connected && !this.closed) { - if (notify && reason.length() > 0) { + if (notify && !reason.isEmpty()) { DisconnectPacket pk = new DisconnectPacket(); pk.message = reason; this.forceDataPacket(pk, null); } this.connected = false; + + // Do all inventory changes before the last save + this.resetCraftingGridType(); + this.removeAllWindows(true); + + if (this.fishing != null) { + this.stopFishing(false); + } + PlayerQuitEvent ev = null; - if (this.getName() != null && this.getName().length() > 0) { + if (this.username != null && !this.username.isEmpty()) { this.server.getPluginManager().callEvent(ev = new PlayerQuitEvent(this, message, true, reason)); if (this.loggedIn && ev.getAutoSave()) { this.save(); } - if (this.fishing != null) { - this.stopFishing(false); - } } - for (Player player : new ArrayList<>(this.server.getOnlinePlayers().values())) { + for (Player player : this.server.getOnlinePlayers().values()) { if (!player.canSee(this)) { player.showPlayer(this); } @@ -4018,31 +5260,18 @@ public void close(TextContainer message, String reason, boolean notify) { this.hiddenPlayers.clear(); - this.removeAllWindows(true); - - for (long index : new ArrayList<>(this.usedChunks.keySet())) { - int chunkX = Level.getHashX(index); - int chunkZ = Level.getHashZ(index); - this.level.unregisterChunkLoader(this, chunkX, chunkZ); - this.usedChunks.remove(index); - - for (Entity entity : level.getChunkEntities(chunkX, chunkZ).values()) { - if (entity != this) { - entity.getViewers().remove(getLoaderId()); - } - } - } + this.unloadChunks(false); super.close(); this.interfaz.close(this, notify ? reason : ""); + this.server.removeOnlinePlayer(this); + if (this.loggedIn) { - this.server.removeOnlinePlayer(this); + this.loggedIn = false; } - this.loggedIn = false; - if (ev != null && !Objects.equals(this.username, "") && this.spawned && !Objects.equals(ev.getQuitMessage().toString(), "")) { this.server.broadcastMessage(ev.getQuitMessage()); } @@ -4050,15 +5279,13 @@ public void close(TextContainer message, String reason, boolean notify) { this.server.getPluginManager().unsubscribeFromPermission(Server.BROADCAST_CHANNEL_USERS, this); this.spawned = false; this.server.getLogger().info(this.getServer().getLanguage().translateString("nukkit.player.logOut", - TextFormat.AQUA + (this.getName() == null ? this.unverifiedUsername : this.getName()) + TextFormat.WHITE, + TextFormat.AQUA + (this.username == null ? this.unverifiedUsername : this.username) + TextFormat.WHITE, this.getAddress(), String.valueOf(this.getPort()), this.getServer().getLanguage().translateString(reason))); + this.windows.clear(); - this.usedChunks.clear(); - this.loadQueue.clear(); this.hasSpawned.clear(); - this.spawnPosition = null; if (this.riding instanceof EntityRideable) { this.riding.passengers.remove(this); @@ -4072,33 +5299,50 @@ public void close(TextContainer message, String reason, boolean notify) { this.perm = null; } - if (this.inventory != null) { - this.inventory = null; - } - + this.inventory = null; this.chunk = null; this.server.removePlayer(this); + + if (this.loggedIn) { + this.server.getLogger().warning("Player is still logged in: " + (this.username == null ? this.unverifiedUsername : this.username)); + this.interfaz.close(this, notify ? reason : ""); + this.server.removeOnlinePlayer(this); + this.loggedIn = false; + } + + this.clientMovements.clear(); } + /** + * Save player data to disk + */ public void save() { this.save(false); } + /** + * Save player data to disk + * @param async save asynchronously + */ public void save(boolean async) { if (this.closed) { throw new IllegalStateException("Tried to save closed player"); } + if (!this.server.shouldSavePlayerData) { + return; + } + super.saveNBT(); if (this.level != null) { this.namedTag.putString("Level", this.level.getFolderName()); if (this.spawnPosition != null && this.spawnPosition.getLevel() != null) { this.namedTag.putString("SpawnLevel", this.spawnPosition.getLevel().getFolderName()); - this.namedTag.putInt("SpawnX", (int) this.spawnPosition.x); - this.namedTag.putInt("SpawnY", (int) this.spawnPosition.y); - this.namedTag.putInt("SpawnZ", (int) this.spawnPosition.z); + this.namedTag.putInt("SpawnX", this.spawnPosition.getFloorX()); + this.namedTag.putInt("SpawnY", this.spawnPosition.getFloorY()); + this.namedTag.putInt("SpawnZ", this.spawnPosition.getFloorZ()); } CompoundTag achievements = new CompoundTag(); @@ -4113,11 +5357,11 @@ public void save(boolean async) { this.namedTag.putString("lastIP", this.getAddress()); - this.namedTag.putInt("EXP", this.getExperience()); - this.namedTag.putInt("expLevel", this.getExperienceLevel()); + this.namedTag.putInt("EXP", this.exp); + this.namedTag.putInt("expLevel", this.expLevel); - this.namedTag.putInt("foodLevel", this.getFoodData().getLevel()); - this.namedTag.putFloat("foodSaturationLevel", this.getFoodData().getFoodSaturationLevel()); + this.namedTag.putInt("foodLevel", this.foodData.getLevel()); + this.namedTag.putFloat("foodSaturationLevel", this.foodData.getFoodSaturationLevel()); this.namedTag.putInt("TimeSinceRest", this.timeSinceRest); @@ -4127,6 +5371,10 @@ public void save(boolean async) { } } + /** + * Get player's username + * @return username + */ public String getName() { return this.username; } @@ -4143,24 +5391,27 @@ public void kill() { EntityDamageEvent cause = this.getLastDamageCause(); if (showMessages) { - params.add(this.getDisplayName()); + params.add(this.displayName); switch (cause == null ? DamageCause.CUSTOM : cause.getCause()) { case ENTITY_ATTACK: + case THORNS: if (cause instanceof EntityDamageByEntityEvent) { Entity e = ((EntityDamageByEntityEvent) cause).getDamager(); killer = e; if (e instanceof Player) { message = "death.attack.player"; - params.add(((Player) e).getDisplayName()); + params.add(((Player) e).displayName); break; } else if (e instanceof EntityLiving) { message = "death.attack.mob"; params.add(!Objects.equals(e.getNameTag(), "") ? e.getNameTag() : e.getName()); break; } else { - params.add("Unknown"); + message = "death.attack.generic"; } + } else { + message = "death.attack.generic"; } break; case PROJECTILE: @@ -4169,14 +5420,16 @@ public void kill() { killer = e; if (e instanceof Player) { message = "death.attack.arrow"; - params.add(((Player) e).getDisplayName()); + params.add(((Player) e).displayName); } else if (e instanceof EntityLiving) { message = "death.attack.arrow"; params.add(!Objects.equals(e.getNameTag(), "") ? e.getNameTag() : e.getName()); break; } else { - params.add("Unknown"); + message = "death.attack.generic"; } + } else { + message = "death.attack.generic"; } break; case VOID: @@ -4195,14 +5448,13 @@ public void kill() { break; case LAVA: - Block block = this.level.getBlock(new Vector3(this.x, this.y - 1, this.z)); - if (block.getId() == Block.MAGMA) { - message = "death.attack.lava.magma"; - break; - } message = "death.attack.lava"; break; + case MAGMA: + message = "death.attack.magma"; + break; + case FIRE: message = "death.attack.onFire"; break; @@ -4222,7 +5474,13 @@ public void kill() { message = "death.attack.cactus"; } else if (id == Block.ANVIL) { message = "death.attack.anvil"; + } else if (id == Block.SWEET_BERRY_BUSH) { + message = "death.attack.sweetBerry"; + } else { + message = "death.attack.generic"; } + } else { + message = "death.attack.generic"; } break; @@ -4233,11 +5491,14 @@ public void kill() { killer = e; if (e instanceof Player) { message = "death.attack.explosion.player"; - params.add(((Player) e).getDisplayName()); + params.add(((Player) e).displayName); } else if (e instanceof EntityLiving) { message = "death.attack.explosion.player"; params.add(!Objects.equals(e.getNameTag(), "") ? e.getNameTag() : e.getName()); break; + } else if (e instanceof EntityFirework && cause.getEntity() instanceof Player) { + params.add(((Player) cause.getEntity()).displayName); + message = "death.attack.fireworks"; } else { message = "death.attack.explosion"; } @@ -4260,10 +5521,11 @@ public void kill() { } } - PlayerDeathEvent ev = new PlayerDeathEvent(this, this.getDrops(), new TranslationContainer(message, params.toArray(new String[0])), this.expLevel); - ev.setKeepExperience(this.level.gameRules.getBoolean(GameRule.KEEP_INVENTORY)); - ev.setKeepInventory(ev.getKeepExperience()); + this.resetCraftingGridType(); // This must be called before getDrops() for UI inventories to be handled properly + PlayerDeathEvent ev = new PlayerDeathEvent(this, this.getDrops(), new TranslationContainer(message, params.toArray(new String[0])), this.expLevel); + ev.setKeepInventory(this.level.gameRules.getBoolean(GameRule.KEEP_INVENTORY)); + ev.setKeepExperience(ev.getKeepInventory()); // Same as above this.server.getPluginManager().callEvent(ev); if (!ev.isCancelled()) { @@ -4272,9 +5534,10 @@ public void kill() { } this.health = 0; - this.extinguish(); this.scheduleUpdate(); + //this.resetCraftingGridType(); + if (!ev.getKeepInventory() && this.level.getGameRules().getBoolean(GameRule.DO_ENTITY_DROPS)) { for (Item item : ev.getDrops()) { if (!item.hasEnchantment(Enchantment.ID_VANISHING_CURSE)) { @@ -4285,9 +5548,9 @@ public void kill() { if (this.inventory != null) { this.inventory.clearAll(); } - if (this.offhandInventory != null) { - this.offhandInventory.clearAll(); - } + + // Offhand inventory is already cleared in inventory.clearAll() + // UI inventories are handled in resetCraftingGridType() } if (!ev.getKeepExperience() && this.level.getGameRules().getBoolean(GameRule.DO_ENTITY_DROPS)) { @@ -4299,28 +5562,29 @@ public void kill() { this.setExperience(0, 0); } - this.timeSinceRest = 0; - - if (showMessages && !ev.getDeathMessage().toString().isEmpty()) { - this.server.broadcast(ev.getDeathMessage(), Server.BROADCAST_CHANNEL_USERS); + if (level.getGameRules().getBoolean(GameRule.DO_IMMEDIATE_RESPAWN)) { + this.respawn(); + } else { + if (showMessages && !ev.getDeathMessage().toString().isEmpty()) { + this.server.broadcast(ev.getDeathMessage(), Server.BROADCAST_CHANNEL_USERS); - DeathInfoPacket pk = new DeathInfoPacket(); - if (ev.getDeathMessage() instanceof TranslationContainer) { - pk.messageTranslationKey = this.server.getLanguage().translateString(ev.getDeathMessage().getText(), ((TranslationContainer) ev.getDeathMessage()).getParameters(), null); - } else { - pk.messageTranslationKey = ev.getDeathMessage().getText(); + DeathInfoPacket pk = new DeathInfoPacket(); + if (ev.getDeathMessage() instanceof TranslationContainer) { + pk.messageTranslationKey = this.server.getLanguage().translateString(ev.getDeathMessage().getText(), ((TranslationContainer) ev.getDeathMessage()).getParameters(), null); + } else { + pk.messageTranslationKey = ev.getDeathMessage().getText(); + } + this.dataPacket(pk); } + + RespawnPacket pk = new RespawnPacket(); + Position pos = this.getSpawn(); + pk.x = (float) pos.x; + pk.y = (float) pos.y; + pk.z = (float) pos.z; + pk.respawnState = RespawnPacket.STATE_SEARCHING_FOR_SPAWN; this.dataPacket(pk); } - - RespawnPacket pk = new RespawnPacket(); - Position pos = this.getSpawn(); - pk.x = (float) pos.x; - pk.y = (float) pos.y; - pk.z = (float) pos.z; - pk.respawnState = RespawnPacket.STATE_SEARCHING_FOR_SPAWN; - - this.dataPacket(pk); } } @@ -4330,7 +5594,6 @@ protected void respawn() { return; } - this.craftingType = CRAFTING_SMALL; this.resetCraftingGridType(); PlayerRespawnEvent playerRespawnEvent = new PlayerRespawnEvent(this, this.getSpawn()); @@ -4338,34 +5601,59 @@ protected void respawn() { Position respawnPos = playerRespawnEvent.getRespawnPosition(); - this.sendExperience(); - this.sendExperienceLevel(); + this.teleport(respawnPos, null); + + this.sendBothExperience(this.exp, this.expLevel); - this.setSprinting(false); + this.setSprinting(false, false); this.setSneaking(false); this.setSwimming(false); this.setGliding(false); + this.setCrawling(false); + this.extinguish(); this.setDataProperty(new ShortEntityData(Player.DATA_AIR, 400), false); + this.airTicks = 400; this.deadTicks = 0; this.noDamageTicks = 60; + this.timeSinceRest = 0; this.removeAllEffects(EntityPotionEffectEvent.Cause.DEATH); this.setHealth(this.getMaxHealth()); - this.getFoodData().setLevel(20, 20); + this.foodData.setLevel(20, 20); this.sendData(this); this.setMovementSpeed(DEFAULT_SPEED); - this.getAdventureSettings().update(); + this.adventureSettings.update(); this.inventory.sendContents(this); this.inventory.sendArmorContents(this); this.offhandInventory.sendContents(this); - this.teleport(respawnPos, null); this.spawnToAll(); this.scheduleUpdate(); + + if (this.spawnPosition instanceof BlockRespawnAnchor && this.spawnPosition.level.getProvider() != null) { + Block anchor = this.spawnPosition.level.getBlock(this.spawnPosition); + if (anchor instanceof BlockRespawnAnchor) { + int chargeLevel = anchor.getDamage(); + + if (chargeLevel > 0) { + anchor.setDamage(chargeLevel - 1); + anchor.level.setBlock(anchor, anchor); + + anchor.level.addLevelSoundEvent(anchor, LevelSoundEventPacket.SOUND_RESPAWN_ANCHOR_DEPLETE); + } + + if (chargeLevel <= 1) { + this.setSpawn(server.getDefaultLevel().getSafeSpawn()); + } + + } else { + this.setSpawn(server.getDefaultLevel().getSafeSpawn()); + } + } } @Override @@ -4375,11 +5663,12 @@ public void setHealth(float health) { } super.setHealth(health); - //TODO: Remove it in future! This a hack to solve the client-side absorption bug! WFT Mojang (Half a yellow heart cannot be shown, we can test it in local gaming) - Attribute attr = Attribute.getAttribute(Attribute.MAX_HEALTH).setMaxValue(this.getAbsorption() % 2 != 0 ? this.getMaxHealth() + 1 : this.getMaxHealth()).setValue(health > 0 ? (health < getMaxHealth() ? health : getMaxHealth()) : 0); + + // HACK: solve the client-side absorption bug if (this.spawned) { UpdateAttributesPacket pk = new UpdateAttributesPacket(); - pk.entries = new Attribute[]{attr}; + int max = this.getMaxHealth(); + pk.entries = new Attribute[]{Attribute.getAttribute(Attribute.MAX_HEALTH).setMaxValue(max).setValue(this.health > 0 ? (this.health < max ? this.health : max) : 0)}; pk.entityId = this.id; this.dataPacket(pk); } @@ -4389,53 +5678,76 @@ public void setHealth(float health) { public void setMaxHealth(int maxHealth) { super.setMaxHealth(maxHealth); - Attribute attr = Attribute.getAttribute(Attribute.MAX_HEALTH).setMaxValue(this.getAbsorption() % 2 != 0 ? this.getMaxHealth() + 1 : this.getMaxHealth()).setValue(health > 0 ? (health < getMaxHealth() ? health : getMaxHealth()) : 0); if (this.spawned) { UpdateAttributesPacket pk = new UpdateAttributesPacket(); - pk.entries = new Attribute[]{attr}; + int max = this.getMaxHealth(); + pk.entries = new Attribute[]{Attribute.getAttribute(Attribute.MAX_HEALTH).setMaxValue(max).setValue(this.health > 0 ? (this.health < max ? this.health : max) : 0)}; pk.entityId = this.id; this.dataPacket(pk); } } + /** + * Get experience + * @return experience (non-full levels) + */ public int getExperience() { return this.exp; } + /** + * Get experience level + * @return experience level + */ public int getExperienceLevel() { return this.expLevel; } + /** + * Give the player more experience + * @param add experience to add + */ public void addExperience(int add) { if (add == 0) return; - int now = this.getExperience(); - int added = now + add; - int level = this.getExperienceLevel(); + int added = this.exp + add; + int level = this.expLevel; int most = calculateRequireExperience(level); - while (added >= most) { //Level Up! - added = added - most; + while (added >= most) { + added -= most; level++; most = calculateRequireExperience(level); } this.setExperience(added, level); } + /** + * Calculate experience required for the level + * @param level level + * @return required experience + */ public static int calculateRequireExperience(int level) { if (level >= 30) { return 112 + (level - 30) * 9; } else if (level >= 15) { return 37 + (level - 15) * 5; } else { - return 7 + level * 2; + return 7 + (level << 1); } } + /** + * Set player's experience + * @param exp experience (non-full levels) + */ public void setExperience(int exp) { - setExperience(exp, this.getExperienceLevel()); + setExperience(exp, this.expLevel); } - //todo something on performance, lots of exp orbs then lots of packets, could crash client - + /** + * Set player's experience and experience level + * @param exp experience (non-full levels) + * @param level experience level + */ public void setExperience(int exp, int level) { PlayerExperienceChangeEvent ev = new PlayerExperienceChangeEvent(this, this.exp, this.expLevel, exp, level); this.server.getPluginManager().callEvent(ev); @@ -4447,32 +5759,61 @@ public void setExperience(int exp, int level) { this.exp = ev.getNewExperience(); this.expLevel = ev.getNewExperienceLevel(); - this.sendExperienceLevel(this.expLevel); - this.sendExperience(this.exp); + this.sendBothExperience(this.exp, this.expLevel); } + /** + * Send experience (non-full levels) + */ public void sendExperience() { - sendExperience(this.getExperience()); + sendExperience(this.exp); } + /** + * Send experience (non-full levels) + * @param exp experience + */ public void sendExperience(int exp) { if (this.spawned) { - float percent = ((float) exp) / calculateRequireExperience(this.getExperienceLevel()); - percent = Math.max(0f, Math.min(1f, percent)); - this.setAttribute(Attribute.getAttribute(Attribute.EXPERIENCE).setValue(percent)); + this.setAttribute(Attribute.getAttribute(Attribute.EXPERIENCE).setValue(Math.max(0f, Math.min(1f, ((float) exp) / calculateRequireExperience(this.expLevel))))); } } + /** + * Send experience level + */ public void sendExperienceLevel() { - sendExperienceLevel(this.getExperienceLevel()); + sendExperienceLevel(this.expLevel); } + /** + * Send experience level + * @param level experience level + */ public void sendExperienceLevel(int level) { if (this.spawned) { this.setAttribute(Attribute.getAttribute(Attribute.EXPERIENCE_LEVEL).setValue(level)); } } + /** + * Send both player's experience and experience level in one packet + * @param exp experience (non-full levels) + * @param level experience level + */ + private void sendBothExperience(int exp, int level) { + if (this.spawned) { + UpdateAttributesPacket pk = new UpdateAttributesPacket(); + pk.entries = new Attribute[]{Attribute.getAttribute(Attribute.EXPERIENCE_LEVEL).setValue(level), Attribute.getAttribute(Attribute.EXPERIENCE).setValue(Math.max(0f, Math.min(1f, ((float) exp) / calculateRequireExperience(this.expLevel))))}; + pk.entityId = this.id; + this.dataPacket(pk); + } + } + + /** + * Send updated attribute + * @param attribute attribute + */ public void setAttribute(Attribute attribute) { UpdateAttributesPacket pk = new UpdateAttributesPacket(); pk.entries = new Attribute[]{attribute}; @@ -4485,50 +5826,59 @@ public void setMovementSpeed(float speed) { setMovementSpeed(speed, true); } + /** + * Set player's movement speed + * @param speed speed + * @param send send updated speed to player + */ public void setMovementSpeed(float speed, boolean send) { + if (speed < 0) { // Apparently effects can break this? + server.getLogger().debug("Invalid setMovementSpeed: " + speed); + return; + } super.setMovementSpeed(speed); if (this.spawned && send) { - this.sendMovementSpeed(speed); + this.setAttribute(Attribute.getAttribute(Attribute.MOVEMENT_SPEED).setValue(speed).setDefaultValue(speed)); } } - public void sendMovementSpeed(float speed){ + /** + * Send movement speed attribute + * @param speed speed + */ + public void sendMovementSpeed(float speed) { Attribute attribute = Attribute.getAttribute(Attribute.MOVEMENT_SPEED).setValue(speed); this.setAttribute(attribute); } + /** + * Get the entity which killed the player + * @return entity which killed the player or null + */ public Entity getKiller() { return killer; } @Override public boolean attack(EntityDamageEvent source) { - if (!this.isAlive()) { + if (!spawned || closed || !this.isAlive()) { return false; } if (this.isSpectator() || (this.isCreative() && source.getCause() != DamageCause.SUICIDE)) { - //source.setCancelled(); + source.setCancelled(); return false; - } else if (this.getAdventureSettings().get(Type.ALLOW_FLIGHT) && source.getCause() == DamageCause.FALL) { - //source.setCancelled(); + } else if (source.getCause() == DamageCause.FALL && this.getAllowFlight()) { + source.setCancelled(); return false; - } else if (source.getCause() == DamageCause.FALL) { - if (this.getLevel().getBlock(this.getPosition().floor().add(0.5, -1, 0.5)).getId() == Block.SLIME_BLOCK) { - if (!this.isSneaking()) { - //source.setCancelled(); - this.resetFallDistance(); - return false; - } - } } - if (super.attack(source)) { //!source.isCancelled() + if (super.attack(source)) { if (this.getLastDamageCause() == source && this.spawned) { if (source instanceof EntityDamageByEntityEvent) { Entity damager = ((EntityDamageByEntityEvent) source).getDamager(); if (damager instanceof Player) { - ((Player) damager).getFoodData().updateFoodExpLevel(0.1); + ((Player) damager).foodData.updateFoodExpLevel(0.1); } } EntityEventPacket pk = new EntityEventPacket(); @@ -4554,15 +5904,17 @@ public boolean dropItem(Item item) { } if (item.isNull()) { - this.server.getLogger().debug(this.getName() + " attempted to drop a null item (" + item + ")"); + this.server.getLogger().debug(this.username + " attempted to drop a null item (" + item + ')'); return true; } - Vector3 motion = this.getDirectionVector().multiply(0.4); - - this.level.dropItem(this.add(0, 1.3, 0), item, motion, 40); + this.setUsingItem(false); - this.setDataFlag(DATA_FLAGS, DATA_FLAG_ACTION, false); + Vector3 motion = this.getDirectionVector().multiply(0.4); + EntityItem entityItem = this.level.dropAndGetItem(this.add(0, 1.3, 0), item, motion, 40); + if (entityItem != null) { + entityItem.droppedBy = this; + } return true; } @@ -4578,15 +5930,18 @@ public EntityItem dropAndGetItem(Item item) { } if (item.isNull()) { - this.server.getLogger().debug(this.getName() + " attempted to drop a null item (" + item + ")"); + this.server.getLogger().debug(this.getName() + " attempted to drop a null item (" + item + ')'); return null; } - Vector3 motion = this.getDirectionVector().multiply(0.4); - - this.setDataFlag(DATA_FLAGS, DATA_FLAG_ACTION, false); + this.setUsingItem(false); - return this.level.dropAndGetItem(this.add(0, 1.3, 0), item, motion, 40); + Vector3 motion = this.getDirectionVector().multiply(0.4); + EntityItem entityItem = this.level.dropAndGetItem(this.add(0, 1.3, 0), item, motion, 40); + if (entityItem != null) { + entityItem.droppedBy = this; + } + return entityItem; } public void sendPosition(Vector3 pos) { @@ -4605,49 +5960,90 @@ public void sendPosition(Vector3 pos, double yaw, double pitch, int mode) { this.sendPosition(pos, yaw, pitch, mode, null); } + /** + * Send player's position and rotation + * @param pos position + * @param yaw yaw + * @param pitch pitch + * @param mode movement mode + * @param targets receivers + */ public void sendPosition(Vector3 pos, double yaw, double pitch, int mode, Player[] targets) { MovePlayerPacket pk = new MovePlayerPacket(); pk.eid = this.getId(); pk.x = (float) pos.x; - pk.y = (float) (pos.y + this.getEyeHeight()); + pk.y = (float) (pos.y + this.getBaseOffset()); pk.z = (float) pos.z; pk.headYaw = (float) yaw; pk.pitch = (float) pitch; pk.yaw = (float) yaw; - pk.mode = mode; + pk.mode = mode; + pk.onGround = this.onGround; + + if (this.riding != null) { + pk.ridingEid = this.riding.getId(); + pk.mode = MovePlayerPacket.MODE_PITCH; + } + + this.ySize = 0; + + if (targets != null) { + Server.broadcastPacket(targets, pk); + } else { + this.clientMovements.clear(); + + this.dataPacket(pk); + } + } + + /** + * Internal: Broadcast player movement to viewers + * @param x x + * @param y y + * @param z z + * @param yaw yaw + * @param pitch pitch + * @param headYaw headYaw + */ + private void sendPositionToViewers(double x, double y, double z, double yaw, double pitch, double headYaw) { + MovePlayerPacket pk = new MovePlayerPacket(); + pk.eid = this.getId(); + pk.x = (float) x; + pk.y = (float) (y + this.getBaseOffset()); + pk.z = (float) z; + pk.headYaw = (float) headYaw; + pk.pitch = (float) pitch; + pk.yaw = (float) yaw; + pk.mode = MovePlayerPacket.MODE_NORMAL; + pk.onGround = this.onGround; + if (this.riding != null) { pk.ridingEid = this.riding.getId(); pk.mode = MovePlayerPacket.MODE_PITCH; } - if (targets != null) { - Server.broadcastPacket(targets, pk); - } else { - this.clientMovements.clear(); + this.ySize = 0; - this.dataPacket(pk); - } + Server.broadcastPacket(this.getViewers().values(), pk); } @Override protected void checkChunks() { - if (this.chunk == null || (this.chunk.getX() != ((int) this.x >> 4) || this.chunk.getZ() != ((int) this.z >> 4))) { + if (this.chunk == null || (this.chunk.getX() != this.getChunkX() || this.chunk.getZ() != this.getChunkZ())) { if (this.chunk != null) { this.chunk.removeEntity(this); } - this.chunk = this.level.getChunk((int) this.x >> 4, (int) this.z >> 4, true); + this.chunk = this.level.getChunk(this.getChunkX(), this.getChunkZ(), true); if (!this.justCreated) { - Map newChunk = this.level.getChunkPlayers((int) this.x >> 4, (int) this.z >> 4); - newChunk.remove(this.getLoaderId()); + Map newChunk = this.level.getChunkPlayers(this.getChunkX(), this.getChunkZ()); + newChunk.remove(this.loaderId); - //List reload = new ArrayList<>(); for (Player player : new ArrayList<>(this.hasSpawned.values())) { - if (!newChunk.containsKey(player.getLoaderId())) { + if (!newChunk.containsKey(player.loaderId)) { this.despawnFrom(player); } else { - newChunk.remove(player.getLoaderId()); - //reload.add(player); + newChunk.remove(player.loaderId); } } @@ -4665,9 +6061,13 @@ protected void checkChunks() { } protected boolean checkTeleportPosition() { + return checkTeleportPosition(false); + } + + protected boolean checkTeleportPosition(boolean enderPearl) { if (this.teleportPosition != null) { - int chunkX = (int) this.teleportPosition.x >> 4; - int chunkZ = (int) this.teleportPosition.z >> 4; + int chunkX = this.teleportPosition.getChunkX(); + int chunkZ = this.teleportPosition.getChunkZ(); for (int X = -1; X <= 1; ++X) { for (int Z = -1; Z <= 1; ++Z) { @@ -4679,7 +6079,9 @@ protected boolean checkTeleportPosition() { } this.spawnToAll(); - this.forceMovement = this.teleportPosition; + if (!enderPearl) { + this.forceMovement = this.teleportPosition; + } this.teleportPosition = null; return true; } @@ -4688,13 +6090,8 @@ protected boolean checkTeleportPosition() { } protected void sendPlayStatus(int status) { - sendPlayStatus(status, false); - } - - protected void sendPlayStatus(int status, boolean immediate) { PlayStatusPacket pk = new PlayStatusPacket(); pk.status = status; - this.dataPacket(pk); } @@ -4704,90 +6101,59 @@ public boolean teleport(Location location, TeleportCause cause) { return false; } - Location from = this.getLocation(); Location to = location; if (cause != null) { + Location from = this.getLocation(); PlayerTeleportEvent event = new PlayerTeleportEvent(this, from, to, cause); this.server.getPluginManager().callEvent(event); if (event.isCancelled()) return false; to = event.getTo(); } - //TODO Remove it! A hack to solve the client-side teleporting bug! (inside into the block) + // HACK: solve the client-side teleporting bug (inside into the block) if (super.teleport(to.getY() == to.getFloorY() ? to.add(0, 0.00001, 0) : to, null)) { // null to prevent fire of duplicate EntityTeleportEvent this.removeAllWindows(); + this.formOpen = false; - this.teleportPosition = new Vector3(this.x, this.y, this.z); - this.forceMovement = this.teleportPosition; - this.sendPosition(this, this.yaw, this.pitch, MovePlayerPacket.MODE_TELEPORT); + this.teleportPosition = this; + if (cause != PlayerTeleportEvent.TeleportCause.ENDER_PEARL) { + this.forceMovement = this.teleportPosition; + } - this.checkTeleportPosition(); + if (this.dimensionChangeInProgress) { + this.dimensionChangeInProgress = false; + } else { + this.sendPosition(this, this.yaw, this.pitch, MovePlayerPacket.MODE_TELEPORT); + this.checkTeleportPosition(cause == PlayerTeleportEvent.TeleportCause.ENDER_PEARL); + this.dummyBossBars.values().forEach(DummyBossBar::reshow); + } this.resetFallDistance(); this.nextChunkOrderRun = 0; this.resetClientMovement(); - //DummyBossBar - this.getDummyBossBars().values().forEach(DummyBossBar::reshow); - //Weather - this.getLevel().sendWeather(this); - //Update time - this.getLevel().sendTime(this); + this.stopFishing(false); return true; } return false; } - protected void forceSendEmptyChunks() { - int chunkPositionX = this.getFloorX() >> 4; - int chunkPositionZ = this.getFloorZ() >> 4; - for (int x = -chunkRadius; x < chunkRadius; x++) { - for (int z = -chunkRadius; z < chunkRadius; z++) { - LevelChunkPacket chunk = new LevelChunkPacket(); - chunk.chunkX = chunkPositionX + x; - chunk.chunkZ = chunkPositionZ + z; - chunk.data = new byte[0]; - this.dataPacket(chunk); - } - } - } - + /** + * deprecated: use teleport() with null cause instead + */ + @Deprecated public void teleportImmediate(Location location) { this.teleportImmediate(location, TeleportCause.PLUGIN); } + /** + * deprecated: use teleport() with null cause instead + */ + @Deprecated public void teleportImmediate(Location location, TeleportCause cause) { - Location from = this.getLocation(); - if (super.teleport(location, cause)) { - this.removeAllWindows(); - - if (from.getLevel().getId() != location.getLevel().getId()) { //Different level, update compass position - SetSpawnPositionPacket pk = new SetSpawnPositionPacket(); - pk.spawnType = SetSpawnPositionPacket.TYPE_WORLD_SPAWN; - Position spawn = location.getLevel().getSpawnLocation(); - pk.x = spawn.getFloorX(); - pk.y = spawn.getFloorY(); - pk.z = spawn.getFloorZ(); - dataPacket(pk); - } - - this.forceMovement = new Vector3(this.x, this.y, this.z); - this.sendPosition(this, this.yaw, this.pitch, MovePlayerPacket.MODE_RESET); - - this.resetFallDistance(); - this.orderChunks(); - this.nextChunkOrderRun = 0; - this.resetClientMovement(); - - //DummyBossBar - this.getDummyBossBars().values().forEach(DummyBossBar::reshow); - //Weather - this.getLevel().sendWeather(this); - //Update time - this.getLevel().sendTime(this); - } + this.teleport(location, null); } /** @@ -4810,12 +6176,13 @@ public int showFormWindow(FormWindow window) { * @return form id to use in {@link PlayerFormRespondedEvent} */ public int showFormWindow(FormWindow window, int id) { + if (formOpen) return 0; ModalFormRequestPacket packet = new ModalFormRequestPacket(); packet.formId = id; packet.data = window.getJSONData(); this.formWindows.put(packet.formId, window); - this.dataPacket(packet); + this.formOpen = true; return id; } @@ -4842,8 +6209,7 @@ public int addServerSettings(FormWindow window) { */ @Deprecated public long createBossBar(String text, int length) { - DummyBossBar bossBar = new DummyBossBar.Builder(this).text(text).length(length).build(); - return this.createBossBar(bossBar); + return this.createBossBar(new DummyBossBar.Builder(this).text(text).length(length).build()); } /** @@ -4909,6 +6275,11 @@ public void removeBossBar(long bossBarId) { } } + /** + * Get window id of an open Inventory + * @param inventory inventory + * @return id of the inventory window or -1 if player doesn't have the window open + */ public int getWindowId(Inventory inventory) { if (this.windows.containsKey(inventory)) { return this.windows.get(inventory); @@ -4917,6 +6288,11 @@ public int getWindowId(Inventory inventory) { return -1; } + /** + * Get on open inventory by window id + * @param id window id + * @return inventory (if open) or null + */ public Inventory getWindowById(int id) { return this.windowIndex.get(id); } @@ -4977,13 +6353,14 @@ public void removeWindow(Inventory inventory) { protected void removeWindow(Inventory inventory, boolean isResponse) { inventory.close(this); - // TODO: This needs a proper fix - // Requiring isResponse here causes issues with inventory events and an item duplication glitch - if (/*isResponse &&*/ !this.permanentWindows.contains(this.getWindowId(inventory))) { + if (/*isResponse &&*/ !this.permanentWindows.contains(this.getWindowId(inventory))) { // Possible dupe this.windows.remove(inventory); } } + /** + * Send contents of all open inventories to the player + */ public void sendAllInventories() { for (Inventory inv : this.windows.keySet()) { inv.sendContents(this); @@ -5003,72 +6380,120 @@ protected void addDefaultWindows() { this.craftingGrid = this.playerUIInventory.getCraftingGrid(); this.addWindow(this.craftingGrid, ContainerIds.NONE); - - //TODO: more windows } + /** + * Get player's ui inventory + * @return ui inventory + */ public PlayerUIInventory getUIInventory() { return playerUIInventory; } + /** + * Get player's cursor inventory + * @return cursor inventory + */ public PlayerCursorInventory getCursorInventory() { return this.playerUIInventory.getCursorInventory(); } + /** + * Get player's crafting grid + * @return crafting grid + */ public CraftingGrid getCraftingGrid() { return this.craftingGrid; } + /** + * Set player's crafting grid + * @param grid crafting grid + */ public void setCraftingGrid(CraftingGrid grid) { this.craftingGrid = grid; this.addWindow(grid, ContainerIds.NONE); } + /** + * Resets crafting grid type and moves all UI inventory contents back to player inventory or drops them. + */ public void resetCraftingGridType() { - if (this.craftingGrid != null) { - Item[] drops = this.inventory.addItem(this.craftingGrid.getContents().values().toArray(new Item[0])); + if (this.playerUIInventory != null) { + Item[] drops; + + if (this.craftingGrid != null) { + drops = this.inventory.addItem(this.craftingGrid.getContents().values().toArray(new Item[0])); + this.craftingGrid.clearAll(); - if (drops.length > 0) { for (Item drop : drops) { - this.dropItem(drop); + this.level.dropItem(this, drop); } } - drops = this.inventory.addItem(this.getCursorInventory().getItem(0)); - if (drops.length > 0) { - for (Item drop : drops) { - this.dropItem(drop); - } + drops = this.inventory.addItem(this.playerUIInventory.getCursorInventory().getItemFast(0)); // cloned in addItem + this.playerUIInventory.getCursorInventory().clear(0); + + for (Item drop : drops) { + this.level.dropItem(this, drop); } + // Don't trust the client to handle this + this.moveBlockUIContents(Player.ANVIL_WINDOW_ID); // LOOM_WINDOW_ID is the same as ANVIL_WINDOW_ID? + this.moveBlockUIContents(Player.ENCHANT_WINDOW_ID); + this.moveBlockUIContents(Player.BEACON_WINDOW_ID); + this.moveBlockUIContents(Player.SMITHING_WINDOW_ID); this.playerUIInventory.clearAll(); - if (this.craftingGrid instanceof BigCraftingGrid) { + if (this.craftingGrid instanceof BigCraftingGrid && this.connected) { this.craftingGrid = this.playerUIInventory.getCraftingGrid(); this.addWindow(this.craftingGrid, ContainerIds.NONE); -// -// ContainerClosePacket pk = new ContainerClosePacket(); //be sure, big crafting is really closed -// pk.windowId = ContainerIds.NONE; -// this.dataPacket(pk); } + } + + this.craftingType = CRAFTING_SMALL; + } - this.craftingType = CRAFTING_SMALL; + /** + * Move all block UI contents back to player inventory or drop them + * @param window window id + */ + private void moveBlockUIContents(int window) { + Inventory inventory = this.getWindowById(window); + if (inventory != null && !(inventory instanceof ContainerInventory)) { + Item[] drops = this.inventory.addItem(inventory.getContents().values().toArray(new Item[0])); + inventory.clearAll(); + for (Item drop : drops) { + this.level.dropItem(this, drop); + } } } + /** + * Remove all windows + */ public void removeAllWindows() { removeAllWindows(false); } + /** + * Remove all windows + * @param permanent remove permanent windows + */ public void removeAllWindows(boolean permanent) { for (Entry entry : new ArrayList<>(this.windowIndex.entrySet())) { if (!permanent && this.permanentWindows.contains(entry.getKey())) { continue; } + this.removeWindow(entry.getValue()); } } + /** + * Get id of the window client has requested to be closed + * @return window id or Integer.MIN_VALUE if no window is being closed + */ public int getClosingWindowId() { return this.closingWindowId; } @@ -5098,24 +6523,22 @@ public void onChunkChanged(FullChunk chunk) { this.usedChunks.remove(Level.chunkHash(chunk.getX(), chunk.getZ())); } + /* Note: Update Level useChunkLoaderApi checks if more ChunkLoader API is ever used here */ + @Override public void onChunkLoaded(FullChunk chunk) { - } @Override public void onChunkPopulated(FullChunk chunk) { - } @Override public void onChunkUnloaded(FullChunk chunk) { - } @Override public void onBlockChanged(Vector3 block) { - } @Override @@ -5125,131 +6548,205 @@ public int getLoaderId() { @Override public boolean isLoaderActive() { - return this.isConnected(); + return this.connected; } - - public static BatchPacket getChunkCacheFromData(int chunkX, int chunkZ, int subChunkCount, byte[] payload) { + /** + * Get chunk cache from data + * @param chunkX chunk x + * @param chunkZ chunk z + * @param subChunkCount sub chunk count + * @param payload data + * @return BatchPacket + */ + public static BatchPacket getChunkCacheFromData(int chunkX, int chunkZ, int subChunkCount, byte[] payload, int dimension) { LevelChunkPacket pk = new LevelChunkPacket(); pk.chunkX = chunkX; pk.chunkZ = chunkZ; + pk.dimension = dimension; pk.subChunkCount = subChunkCount; pk.data = payload; - pk.encode(); + pk.tryEncode(); - BatchPacket batch = new BatchPacket(); - byte[][] batchPayload = new byte[2][]; byte[] buf = pk.getBuffer(); - batchPayload[0] = Binary.writeUnsignedVarInt(buf.length); - batchPayload[1] = buf; - byte[] data = Binary.appendBytes(batchPayload); + BinaryStream batched = new BinaryStream(new byte[5 + buf.length]).reset(); + batched.putUnsignedVarInt(buf.length); + batched.put(buf); try { - batch.payload = Network.deflateRaw(data, Server.getInstance().networkCompressionLevel); + byte[] bytes = batched.getBuffer(); + BatchPacket compress = new BatchPacket(); + if (Server.getInstance().useSnappy) { + compress.payload = SnappyCompression.compress(bytes); + } else { + compress.payload = Zlib.deflateRaw(bytes, Server.getInstance().networkCompressionLevel); + } + return compress; } catch (Exception e) { throw new RuntimeException(e); } - return batch; } - private boolean foodEnabled = true; - + /** + * Check whether food is enabled or not + * @return food enabled + */ public boolean isFoodEnabled() { return !(this.isCreative() || this.isSpectator()) && this.foodEnabled; } + /** + * Enable or disable food + * @param foodEnabled food enabled + */ public void setFoodEnabled(boolean foodEnabled) { this.foodEnabled = foodEnabled; } + /** + * Get player's food data + * @return food data + */ public PlayerFood getFoodData() { return this.foodData; } - //todo a lot on dimension + /** + * Send dimension change + * @param dimension dimension id + */ + public void setDimension(int dimension) { + if (!this.loggedIn) { + return; // Do not send ChangeDimensionPacket before StartGamePacket + } - private void setDimension(int dimension) { - ChangeDimensionPacket pk = new ChangeDimensionPacket(); - pk.dimension = dimension; - pk.x = (float) this.x; - pk.y = (float) this.y; - pk.z = (float) this.z; - this.dataPacket(pk); - } + this.dimensionChangeInProgress = true; + this.awaitingDimensionAck = true; - @Override - public boolean switchLevel(Level level) { - Level oldLevel = this.level; - if (super.switchLevel(level)) { - SetSpawnPositionPacket spawnPosition = new SetSpawnPositionPacket(); - spawnPosition.spawnType = SetSpawnPositionPacket.TYPE_WORLD_SPAWN; - Position spawn = level.getSpawnLocation(); - spawnPosition.x = spawn.getFloorX(); - spawnPosition.y = spawn.getFloorY(); - spawnPosition.z = spawn.getFloorZ(); - this.dataPacket(spawnPosition); - - // Remove old chunks - for (long index : new ArrayList<>(this.usedChunks.keySet())) { - int chunkX = Level.getHashX(index); - int chunkZ = Level.getHashZ(index); - this.unloadChunk(chunkX, chunkZ, oldLevel); - } - this.usedChunks.clear(); + ChangeDimensionPacket changeDimensionPacket = new ChangeDimensionPacket(); + changeDimensionPacket.dimension = dimension; + changeDimensionPacket.x = (float) this.x; + changeDimensionPacket.y = (float) this.y; + changeDimensionPacket.z = (float) this.z; + changeDimensionPacket.respawn = !this.isAlive(); + this.dataPacket(changeDimensionPacket); - SetTimePacket setTime = new SetTimePacket(); - setTime.time = level.getTime(); - this.dataPacket(setTime); + NetworkChunkPublisherUpdatePacket chunkPublisherUpdatePacket = new NetworkChunkPublisherUpdatePacket(); + chunkPublisherUpdatePacket.position = this.asBlockVector3(); + chunkPublisherUpdatePacket.radius = this.chunkRadius << 4; + this.dataPacket(chunkPublisherUpdatePacket); - GameRulesChangedPacket gameRulesChanged = new GameRulesChangedPacket(); - gameRulesChanged.gameRules = level.getGameRules(); - this.dataPacket(gameRulesChanged); - return true; - } + this.dimensionFix560 = true; + } - return false; + @Override + protected void preSwitchLevel() { + this.unloadChunks(true); + } + + @Override + protected void afterSwitchLevel() { + // Send spawn to update compass position + SetSpawnPositionPacket spawnPosition = new SetSpawnPositionPacket(); + spawnPosition.spawnType = SetSpawnPositionPacket.TYPE_WORLD_SPAWN; + Vector3 spawn = level.getProvider().getSpawn(); + spawnPosition.x = spawn.getFloorX(); + spawnPosition.y = spawn.getFloorY(); + spawnPosition.z = spawn.getFloorZ(); + spawnPosition.dimension = level.getDimension(); + this.dataPacket(spawnPosition); + + // Update time and weather + level.sendTime(this); + level.sendWeather(this); + + // Update game rules + GameRulesChangedPacket packet = new GameRulesChangedPacket(); + packet.gameRulesMap = level.getGameRules().getGameRules(); + this.dataPacket(packet); } + /** + * Enable or disable movement check + * @param checkMovement movement check enabled + */ public void setCheckMovement(boolean checkMovement) { this.checkMovement = checkMovement; } + /** + * @return player movement checks enabled + */ public boolean isCheckingMovement() { return this.checkMovement; } + /** + * Set locale + * @param locale locale + */ public synchronized void setLocale(Locale locale) { this.locale.set(locale); } + /** + * Get locale + * @return locale + */ public synchronized Locale getLocale() { return this.locale.get(); } @Override public void setSprinting(boolean value) { + this.setSprinting(value, true); + } + + /** + * Update movement speed to start/stop sprinting + * @param value sprinting + * @param send send updated speed to client + */ + public void setSprinting(boolean value, boolean send) { if (isSprinting() != value) { super.setSprinting(value); - - if(this.hasEffect(Effect.SPEED)) { - float movementSpeed = this.getMovementSpeed(); - this.sendMovementSpeed(value ? movementSpeed * 1.3f : movementSpeed); - } + this.setMovementSpeed(value ? getMovementSpeed() * 1.3f : getMovementSpeed() / 1.3f, send); } } + /** + * Transfer player to other server + * @param address target server address + */ public void transfer(InetSocketAddress address) { - String hostName = address.getAddress().getHostAddress(); - int port = address.getPort(); + transfer(address.getAddress().getHostAddress(), address.getPort()); + } + + /** + * Transfer player to other server + * @param hostName target server address + * @param port target server port + */ + public void transfer(String hostName, int port) { TransferPacket pk = new TransferPacket(); pk.address = hostName; pk.port = port; this.dataPacket(pk); } + /** + * Get player's LoginChainData + * @return login chain data + */ public LoginChainData getLoginChainData() { return this.loginChainData; } + /** + * Try to pick up an entity + * @param entity target + * @param near near + * @return success + */ public boolean pickupEntity(Entity entity, boolean near) { if (!this.spawned || !this.isAlive() || !this.isOnline() || this.isSpectator() || entity.isClosed()) { return false; @@ -5257,19 +6754,25 @@ public boolean pickupEntity(Entity entity, boolean near) { if (near) { if (entity instanceof EntityArrow && ((EntityArrow) entity).hadCollision) { - ItemArrow item = new ItemArrow(); + EntityArrow a = ((EntityArrow) entity); + ItemArrow item = (ItemArrow) Item.get(Item.ARROW, a.getData()); if (!this.isCreative() && !this.inventory.canAddItem(item)) { return false; } - InventoryPickupArrowEvent ev = new InventoryPickupArrowEvent(this.inventory, (EntityArrow) entity); + InventoryPickupArrowEvent ev = new InventoryPickupArrowEvent(this.inventory, a); - int pickupMode = ((EntityArrow) entity).getPickupMode(); - if (pickupMode == EntityArrow.PICKUP_NONE || (pickupMode == EntityArrow.PICKUP_CREATIVE && !this.isCreative())) { + int pickupMode = a.getPickupMode(); + if (pickupMode == EntityArrow.PICKUP_NONE_REMOVE || pickupMode == EntityArrow.PICKUP_NONE || (pickupMode == EntityArrow.PICKUP_CREATIVE && !this.isCreative())) { ev.setCancelled(); } this.server.getPluginManager().callEvent(ev); + + if (pickupMode == EntityArrow.PICKUP_NONE_REMOVE) { + entity.close(); + } + if (ev.isCancelled()) { return false; } @@ -5281,12 +6784,31 @@ public boolean pickupEntity(Entity entity, boolean near) { this.dataPacket(pk); if (!this.isCreative()) { - this.inventory.addItem(item.clone()); + this.inventory.addItem(item); } entity.close(); return true; - } else if (entity instanceof EntityThrownTrident && ((EntityThrownTrident) entity).hadCollision) { + } else if (entity instanceof EntityThrownTrident) { + if (!((EntityThrownTrident) entity).hadCollision) { + if (entity.noClip) { + if (!this.equals(((EntityProjectile) entity).shootingEntity)) { + return false; + } + } else { + return false; + } + } + + if (!((EntityThrownTrident) entity).shotByPlayer()) { + return false; + } + Item item = ((EntityThrownTrident) entity).getItem(); + + if (((EntityProjectile) entity).shootingEntity != null && item.hasEnchantment(Enchantment.ID_TRIDENT_LOYALTY) && !this.equals(((EntityProjectile) entity).shootingEntity)) { + return false; + } + if (!this.isCreative() && !this.inventory.canAddItem(item)) { return false; } @@ -5294,11 +6816,16 @@ public boolean pickupEntity(Entity entity, boolean near) { InventoryPickupTridentEvent ev = new InventoryPickupTridentEvent(this.inventory, (EntityThrownTrident) entity); int pickupMode = ((EntityThrownTrident) entity).getPickupMode(); - if (pickupMode == EntityThrownTrident.PICKUP_NONE || (pickupMode == EntityThrownTrident.PICKUP_CREATIVE && !this.isCreative())) { + if (pickupMode == EntityArrow.PICKUP_NONE_REMOVE || pickupMode == EntityThrownTrident.PICKUP_NONE || (pickupMode == EntityThrownTrident.PICKUP_CREATIVE && !this.isCreative())) { ev.setCancelled(); } this.server.getPluginManager().callEvent(ev); + + if (pickupMode == EntityArrow.PICKUP_NONE_REMOVE) { + entity.close(); + } + if (ev.isCancelled()) { return false; } @@ -5310,13 +6837,20 @@ public boolean pickupEntity(Entity entity, boolean near) { this.dataPacket(pk); if (!this.isCreative()) { - this.inventory.addItem(item.clone()); + int favSlot = ((EntityThrownTrident) entity).getFavoredSlot(); + if (favSlot != -1 && !this.isCreative() && inventory.getItemFast(favSlot).getId() == Item.AIR) { + this.inventory.setItem(favSlot, item.clone()); + } else { + this.inventory.addItem(item); // cloned in addItem + } } + entity.close(); return true; } else if (entity instanceof EntityItem) { - if (((EntityItem) entity).getPickupDelay() <= 0) { - Item item = ((EntityItem) entity).getItem(); + EntityItem entityItem = (EntityItem) entity; + if (entityItem.getPickupDelay() <= 0) { + Item item = entityItem.getItem(); if (item != null) { if (!this.isCreative() && !this.inventory.canAddItem(item)) { @@ -5324,7 +6858,7 @@ public boolean pickupEntity(Entity entity, boolean near) { } InventoryPickupItemEvent ev; - this.server.getPluginManager().callEvent(ev = new InventoryPickupItemEvent(this.inventory, (EntityItem) entity)); + this.server.getPluginManager().callEvent(ev = new InventoryPickupItemEvent(this.inventory, entityItem)); if (ev.isCancelled()) { return false; } @@ -5335,7 +6869,16 @@ public boolean pickupEntity(Entity entity, boolean near) { this.awardAchievement("mineWood"); break; case Item.DIAMOND: - this.awardAchievement("diamond"); + this.awardAchievement("diamonds"); + if (entityItem.droppedBy != null && entityItem.droppedBy != this) { + entityItem.droppedBy.awardAchievement("diamondsToYou"); + } + break; + case Item.LEATHER: + this.awardAchievement("killCow"); + break; + case Item.BLAZE_ROD: + this.awardAchievement("blazeRod"); break; } @@ -5345,7 +6888,7 @@ public boolean pickupEntity(Entity entity, boolean near) { Server.broadcastPacket(entity.getViewers().values(), pk); this.dataPacket(pk); - this.inventory.addItem(item.clone()); + this.inventory.addItem(item); // cloned in addItem entity.close(); return true; } @@ -5353,37 +6896,49 @@ public boolean pickupEntity(Entity entity, boolean near) { } } - int tick = this.getServer().getTick(); - if (pickedXPOrb < tick && entity instanceof EntityXPOrb && this.boundingBox.isVectorInside(entity)) { + if (this.pickedXPOrb < this.server.getTick() && entity instanceof EntityXPOrb) { EntityXPOrb xpOrb = (EntityXPOrb) entity; - if (xpOrb.getPickupDelay() <= 0) { + if (xpOrb.getPickupDelay() <= 0 && this.boundingBox.isVectorInside(entity)) { int exp = xpOrb.getExp(); - entity.kill(); + entity.close(); this.getLevel().addLevelEvent(this, LevelEventPacket.EVENT_SOUND_EXPERIENCE_ORB); - pickedXPOrb = tick; + this.pickedXPOrb = this.server.getTick(); - //Mending - ArrayList itemsWithMending = new ArrayList<>(); + IntArrayList itemsWithMending = new IntArrayList(); for (int i = 0; i < 4; i++) { - if (inventory.getArmorItem(i).getEnchantment((short)Enchantment.ID_MENDING) != null) { - itemsWithMending.add(inventory.getSize() + i); + if (this.inventory.getArmorItem(i).hasEnchantment(Enchantment.ID_MENDING)) { + itemsWithMending.add(this.inventory.getSize() + i); } } - if (inventory.getItemInHand().getEnchantment((short)Enchantment.ID_MENDING) != null) { - itemsWithMending.add(inventory.getHeldItemIndex()); + + if (this.inventory.getItemInHandFast().hasEnchantment(Enchantment.ID_MENDING)) { + itemsWithMending.add(this.inventory.getHeldItemIndex()); + } + + Item offhand = this.getOffhandInventory().getItem(0); + if (offhand.getId() == Item.SHIELD && offhand.hasEnchantment(Enchantment.ID_MENDING)) { + itemsWithMending.add(-1); } - if (itemsWithMending.size() > 0) { - Random rand = new Random(); - Integer itemToRepair = itemsWithMending.get(rand.nextInt(itemsWithMending.size())); - Item toRepair = inventory.getItem(itemToRepair); - if (toRepair instanceof ItemTool || toRepair instanceof ItemArmor) { - if (toRepair.getDamage() > 0) { - int dmg = toRepair.getDamage() - 2; + + if (!itemsWithMending.isEmpty()) { + int itemToRepair = itemsWithMending.getInt(Utils.random.nextInt(itemsWithMending.size())); + boolean isOffhand = itemToRepair == -1; + + Item repaired = isOffhand ? offhand : this.inventory.getItem(itemToRepair); + if (repaired instanceof ItemDurable) { + if (repaired.getDamage() > 0) { + int dmg = repaired.getDamage() - (exp << 1); // repair 2 points per xp if (dmg < 0) { dmg = 0; } - toRepair.setDamage(dmg); - inventory.setItem(itemToRepair, toRepair); + + repaired.setDamage(dmg); + + if (isOffhand) { + this.getOffhandInventory().setItem(0, repaired); + } else { + this.inventory.setItem(itemToRepair, repaired); + } return true; } } @@ -5415,6 +6970,11 @@ public boolean equals(Object obj) { return Objects.equals(this.getUniqueId(), other.getUniqueId()) && this.getId() == other.getId(); } + /** + * Check if the player is currently breaking a block + * + * @return is breaking a block + */ public boolean isBreakingBlock() { return this.breakingBlock != null; } @@ -5447,7 +7007,7 @@ public void startFishing(Item fishingRod) { .add(new FloatTag("", (float) yaw)) .add(new FloatTag("", (float) pitch))); double f = 1.1; - EntityFishingHook fishingHook = new EntityFishingHook(chunk, nbt, this); + EntityFishingHook fishingHook = (EntityFishingHook) Entity.createEntity(EntityFishingHook.NETWORK_ID, chunk, nbt, this); fishingHook.setMotion(new Vector3(-Math.sin(Math.toRadians(yaw)) * Math.cos(Math.toRadians(pitch)) * f * f, -Math.sin(Math.toRadians(pitch)) * f * f, Math.cos(Math.toRadians(yaw)) * Math.cos(Math.toRadians(pitch)) * f * f)); ProjectileLaunchEvent ev = new ProjectileLaunchEvent(fishingHook); @@ -5482,58 +7042,112 @@ public boolean doesTriggerPressurePlate() { return this.gamemode != SPECTATOR; } - @Override - public String toString() { - return "Player(name='" + getName() + - "', location=" + super.toString() + - ')'; - } - + /** + * Get ticks since sleeping in the current world last time + * + * @return ticks since sleeping + */ public int getTimeSinceRest() { return timeSinceRest; } - public void setTimeSinceRest(int timeSinceRest) { - this.timeSinceRest = timeSinceRest; + /** + * Set ticks since sleeping in the current world last time + * + * @param ticks ticks since sleeping + */ + public void setTimeSinceRest(int ticks) { + this.timeSinceRest = ticks; } - public NetworkPlayerSession getNetworkSession() { - return this.networkSession; + @Override + public String toString() { + return "Player(name='" + getName() + "', location=" + super.toString() + ')'; } - protected void processPreLogin() { - this.loginVerified = true; - final Player playerInstance = this; + @Override + public void setAirTicks(int ticks) { + if (this.airTicks != ticks) { + if (this.spawned || ticks > this.airTicks) { // Don't consume air before spawned + this.airTicks = ticks; + this.setDataPropertyAndSendOnlyToSelf(new ShortEntityData(DATA_AIR, ticks)); + } + } + } - this.preLoginEventTask = new AsyncTask() { - private PlayerAsyncPreLoginEvent event; + /** + * Send current held item to client + */ + private void syncHeldItem() { + InventorySlotPacket pk = new InventorySlotPacket(); + pk.slot = this.inventory.getHeldItemIndex(); + pk.item = this.inventory.getItem(pk.slot); + pk.inventoryId = ContainerIds.INVENTORY; + this.dataPacket(pk); + } - @Override - public void onRun() { - this.event = new PlayerAsyncPreLoginEvent(username, uuid, loginChainData, playerInstance.getSkin(), playerInstance.getAddress(), playerInstance.getPort()); - server.getPluginManager().callEvent(this.event); - } + /** + * Run every tick to send updated data if needed + */ + void resetPacketCounters() { + if (this.needSendAdventureSettings) { + this.needSendAdventureSettings = false; + this.adventureSettings.update(false); + } + if (this.needSendData) { + this.needSendData = false; + this.sendData(this); // Send data only once even if multiple actions fail + } + if (this.needSendFoodLevel) { + this.needSendFoodLevel = false; + this.foodData.sendFoodLevel(); + } + if (this.needSendInventory && this.spawned) { + this.needSendInventory = false; + this.getCursorInventory().sendContents(this); + this.sendAllInventories(); + } + if (this.needSendHeldItem && this.spawned) { + this.needSendHeldItem = false; + this.syncHeldItem(); + } + } - @Override - public void onCompletion(Server server) { - if (!playerInstance.connected) { - return; - } + /** + * Check whether player can eat (difficulty, gamemode, current food level) + * + * @param update send current food level to client + * @return can eat + */ + public boolean canEat(boolean update) { + if (this.foodData.getLevel() < this.foodData.getMaxLevel() || this.isCreative() || this.server.getDifficulty() == 0) { + return true; + } + if (update) { + this.needSendFoodLevel = true; + } + return false; + } - if (this.event.getLoginResult() == LoginResult.KICK) { - playerInstance.close(this.event.getKickMessage(), this.event.getKickMessage()); - } else if (playerInstance.shouldLogin) { - playerInstance.setSkin(this.event.getSkin()); - playerInstance.completeLoginSequence(); - for (Consumer action : this.event.getScheduledActions()) { - action.accept(server); - } - } - } - }; + /** + * Get Player's NetworkPlayerSession + * + * @return network session + */ + public NetworkPlayerSession getNetworkSession() { + return this.networkSession; + } + + @Override + public final boolean canSaveToStorage() { + return false; + } - this.server.getScheduler().scheduleAsyncTask(this.preLoginEventTask); - this.processLogin(); + /** + * Whether interactions should be handled as if player is sneaking + */ + public boolean sneakToBlockInteract() { + return this.isSneaking() || this.flySneaking; } /** @@ -5548,6 +7162,13 @@ public void setHudElementVisibility(boolean visible, HudElement... elements) { this.dataPacket(pk); } + @Override + public void setGliding(boolean value) { + this.fireworkBoostTicks = 0; + + super.setGliding(value); + } + /** * Close form windows sent with showFormWindow */ diff --git a/src/main/java/cn/nukkit/PlayerFood.java b/src/main/java/cn/nukkit/PlayerFood.java index 90ff6a9a9ca..ee91b07608d 100644 --- a/src/main/java/cn/nukkit/PlayerFood.java +++ b/src/main/java/cn/nukkit/PlayerFood.java @@ -9,22 +9,22 @@ import cn.nukkit.potion.Effect; /** + * This class handles player's food. + *

* Created by funcraft on 2015/11/11. */ public class PlayerFood { - private int foodLevel = 20; - private final int maxFoodLevel; - private float foodSaturationLevel = 20f; - private int foodTickTimer = 0; - private double foodExpLevel = 0; + private int foodLevel; + private float foodSaturationLevel; + private int foodTickTimer; + private double foodExpLevel; private final Player player; public PlayerFood(Player player, int foodLevel, float foodSaturationLevel) { this.player = player; this.foodLevel = foodLevel; - this.maxFoodLevel = 20; this.foodSaturationLevel = foodSaturationLevel; } @@ -37,7 +37,7 @@ public int getLevel() { } public int getMaxLevel() { - return this.maxFoodLevel; + return 20; } public void setLevel(int foodLevel) { @@ -53,16 +53,16 @@ public void setLevel(int foodLevel, float saturationLevel) { foodLevel = 0; } - if (foodLevel <= 6 && !(this.getLevel() <= 6)) { - if (this.getPlayer().isSprinting()) { - this.getPlayer().setSprinting(false); + if (foodLevel <= 6 && !(this.foodLevel <= 6)) { + if (this.player.isSprinting()) { + this.player.setSprinting(false); } } - PlayerFoodLevelChangeEvent ev = new PlayerFoodLevelChangeEvent(this.getPlayer(), foodLevel, saturationLevel); - this.getPlayer().getServer().getPluginManager().callEvent(ev); + PlayerFoodLevelChangeEvent ev = new PlayerFoodLevelChangeEvent(this.player, foodLevel, saturationLevel); + this.player.getServer().getPluginManager().callEvent(ev); if (ev.isCancelled()) { - this.sendFoodLevel(this.getLevel()); + this.sendFoodLevel(this.foodLevel); return; } int foodLevel0 = ev.getFoodLevel(); @@ -81,10 +81,10 @@ public float getFoodSaturationLevel() { } public void setFoodSaturationLevel(float fsl) { - if (fsl > this.getLevel()) fsl = this.getLevel(); + if (fsl > this.foodLevel) fsl = this.foodLevel; if (fsl < 0) fsl = 0; - PlayerFoodLevelChangeEvent ev = new PlayerFoodLevelChangeEvent(this.getPlayer(), this.getLevel(), fsl); - this.getPlayer().getServer().getPluginManager().callEvent(ev); + PlayerFoodLevelChangeEvent ev = new PlayerFoodLevelChangeEvent(this.player, this.foodLevel, fsl); + this.player.getServer().getPluginManager().callEvent(ev); if (ev.isCancelled()) { return; } @@ -97,8 +97,8 @@ public void useHunger() { } public void useHunger(int amount) { - float sfl = this.getFoodSaturationLevel(); - int foodLevel = this.getLevel(); + float sfl = this.foodSaturationLevel; + int foodLevel = this.foodLevel; if (sfl > 0) { float newSfl = sfl - amount; if (newSfl < 0) newSfl = 0; @@ -113,11 +113,11 @@ public void addFoodLevel(Food food) { } public void addFoodLevel(int foodLevel, float fsl) { - this.setLevel(this.getLevel() + foodLevel, this.getFoodSaturationLevel() + fsl); + this.setLevel(this.foodLevel + foodLevel, this.foodSaturationLevel + fsl); } public void sendFoodLevel() { - this.sendFoodLevel(this.getLevel()); + this.sendFoodLevel(this.foodLevel); } public void reset() { @@ -129,51 +129,52 @@ public void reset() { } public void sendFoodLevel(int foodLevel) { - if (this.getPlayer().spawned) { - this.getPlayer().setAttribute(Attribute.getAttribute(Attribute.MAX_HUNGER).setValue(foodLevel)); + if (this.player.spawned) { + this.player.setAttribute(Attribute.getAttribute(Attribute.MAX_HUNGER).setValue(foodLevel).setDefaultValue(getMaxLevel())); } } public void update(int tickDiff) { - if (!this.getPlayer().isFoodEnabled()) return; - if (this.getPlayer().isAlive()) { + if (!this.player.isFoodEnabled()) return; + if (this.player.isAlive()) { int diff = Server.getInstance().getDifficulty(); - if (this.getLevel() > 17) { + if (this.foodLevel > 17 || diff == 0) { this.foodTickTimer += tickDiff; if (this.foodTickTimer >= 80) { - if (this.getPlayer().getHealth() < this.getPlayer().getMaxHealth()) { - EntityRegainHealthEvent ev = new EntityRegainHealthEvent(this.getPlayer(), 1, EntityRegainHealthEvent.CAUSE_EATING); - this.getPlayer().heal(ev); - //this.updateFoodExpLevel(3); + if (this.player.getHealth() < this.player.getRealMaxHealth()) { + EntityRegainHealthEvent ev = new EntityRegainHealthEvent(this.player, 1, EntityRegainHealthEvent.CAUSE_EATING); + this.player.heal(ev); + this.updateFoodExpLevel(6); } this.foodTickTimer = 0; } - } else if (this.getLevel() == 0) { + } else if (this.foodLevel == 0) { this.foodTickTimer += tickDiff; if (this.foodTickTimer >= 80) { - EntityDamageEvent ev = new EntityDamageEvent(this.getPlayer(), DamageCause.HUNGER, 1); - float now = this.getPlayer().getHealth(); + EntityDamageEvent ev = new EntityDamageEvent(this.player, DamageCause.HUNGER, 1); + float now = this.player.getHealth(); if (diff == 1) { - if (now > 10) this.getPlayer().attack(ev); + if (now > 10) this.player.attack(ev); } else if (diff == 2) { - if (now > 1) this.getPlayer().attack(ev); + if (now > 1) this.player.attack(ev); } else { - this.getPlayer().attack(ev); + this.player.attack(ev); } this.foodTickTimer = 0; } } - if (this.getPlayer().hasEffect(Effect.HUNGER)) { - this.updateFoodExpLevel(0.1 * (this.getPlayer().getEffect(Effect.HUNGER).getAmplifier() + 1)); + Effect hunger = this.player.getEffect(Effect.HUNGER); + if (hunger != null) { + this.updateFoodExpLevel(0.1 * (hunger.getAmplifier() + 1)); } } } public void updateFoodExpLevel(double use) { - if (!this.getPlayer().isFoodEnabled()) return; + if (!this.player.isFoodEnabled()) return; if (Server.getInstance().getDifficulty() == 0) return; - if (this.getPlayer().hasEffect(Effect.SATURATION)) return; + if (this.player.hasEffect(Effect.SATURATION)) return; this.foodExpLevel += use; if (this.foodExpLevel > 4) { this.useHunger(1); @@ -199,4 +200,9 @@ public void setFoodLevel(int foodLevel) { public void setFoodLevel(int foodLevel, float saturationLevel) { setLevel(foodLevel, saturationLevel); } + + @Override + public String toString() { + return "PlayerFood(player= " + player + ", foodLevel=" + foodLevel + ", foodSaturationLevel=" + foodSaturationLevel + ", foodTickTimer=" + foodTickTimer + ", foodExpLevel=" + foodExpLevel + ")"; + } } diff --git a/src/main/java/cn/nukkit/Server.java b/src/main/java/cn/nukkit/Server.java index e871f05dc07..ce46f7893bd 100644 --- a/src/main/java/cn/nukkit/Server.java +++ b/src/main/java/cn/nukkit/Server.java @@ -4,9 +4,11 @@ import cn.nukkit.blockentity.*; import cn.nukkit.command.*; import cn.nukkit.console.NukkitConsole; +import cn.nukkit.dispenser.DispenseBehaviorRegister; import cn.nukkit.entity.Attribute; import cn.nukkit.entity.Entity; import cn.nukkit.entity.EntityHuman; +import cn.nukkit.entity.custom.EntityManager; import cn.nukkit.entity.data.Skin; import cn.nukkit.entity.item.*; import cn.nukkit.entity.mob.*; @@ -16,7 +18,6 @@ import cn.nukkit.event.HandlerList; import cn.nukkit.event.level.LevelInitEvent; import cn.nukkit.event.level.LevelLoadEvent; -import cn.nukkit.event.server.BatchPacketsEvent; import cn.nukkit.event.server.PlayerDataSerializeEvent; import cn.nukkit.event.server.QueryRegenerateEvent; import cn.nukkit.event.server.ServerStopEvent; @@ -24,6 +25,7 @@ import cn.nukkit.inventory.Recipe; import cn.nukkit.item.Item; import cn.nukkit.item.RuntimeItems; +import cn.nukkit.item.custom.CustomItemManager; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.lang.BaseLang; import cn.nukkit.lang.TextContainer; @@ -31,18 +33,14 @@ import cn.nukkit.level.EnumLevel; import cn.nukkit.level.GlobalBlockPalette; import cn.nukkit.level.Level; -import cn.nukkit.level.Position; import cn.nukkit.level.biome.EnumBiome; import cn.nukkit.level.format.LevelProvider; import cn.nukkit.level.format.LevelProviderManager; import cn.nukkit.level.format.anvil.Anvil; -import cn.nukkit.level.format.leveldb.LevelDB; -import cn.nukkit.level.format.mcregion.McRegion; -import cn.nukkit.level.generator.Flat; -import cn.nukkit.level.generator.Generator; -import cn.nukkit.level.generator.Nether; -import cn.nukkit.level.generator.Normal; +import cn.nukkit.level.format.leveldb.LevelDBProvider; +import cn.nukkit.level.generator.*; import cn.nukkit.math.NukkitMath; +import cn.nukkit.math.Vector3; import cn.nukkit.metadata.EntityMetadataStore; import cn.nukkit.metadata.LevelMetadataStore; import cn.nukkit.metadata.PlayerMetadataStore; @@ -52,11 +50,11 @@ import cn.nukkit.nbt.tag.DoubleTag; import cn.nukkit.nbt.tag.FloatTag; import cn.nukkit.nbt.tag.ListTag; -import cn.nukkit.network.CompressBatchedTask; +import cn.nukkit.network.BatchingHelper; import cn.nukkit.network.Network; import cn.nukkit.network.RakNetInterface; import cn.nukkit.network.SourceInterface; -import cn.nukkit.network.protocol.BatchPacket; +import cn.nukkit.network.protocol.BiomeDefinitionListPacket; import cn.nukkit.network.protocol.DataPacket; import cn.nukkit.network.protocol.PlayerListPacket; import cn.nukkit.network.protocol.ProtocolInfo; @@ -81,7 +79,6 @@ import cn.nukkit.scheduler.Task; import cn.nukkit.utils.*; import cn.nukkit.utils.bugreport.ExceptionHandler; -import co.aikar.timings.Timings; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import io.netty.buffer.ByteBuf; @@ -91,13 +88,8 @@ import org.iq80.leveldb.Options; import org.iq80.leveldb.impl.Iq80DBFactory; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.UnknownHostException; +import java.io.*; +import java.net.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; @@ -106,107 +98,75 @@ import java.util.regex.Pattern; /** + * The main server class + * * @author MagicDroidX * @author Box */ @Log4j2 public class Server { + /** + * Permission to receive admin broadcasts such as command usage. + */ public static final String BROADCAST_CHANNEL_ADMINISTRATIVE = "nukkit.broadcast.admin"; + /** + * Permission to receive common broadcasts such as join/quit/death/achievement messages. + */ public static final String BROADCAST_CHANNEL_USERS = "nukkit.broadcast.user"; - private static Server instance = null; - - private BanList banByName; - - private BanList banByIP; - - private Config operators; - - private Config whitelist; + private static Server instance; - private AtomicBoolean isRunning = new AtomicBoolean(true); + private final BanList banByName; + private final BanList banByIP; + private final Config operators; + private final Config whitelist; + private final Config properties; + private final Config config; - private boolean hasStopped = false; - - private PluginManager pluginManager; + private final String filePath; + private final String dataPath; + private final String pluginPath; - private ServerScheduler scheduler; + private final PluginManager pluginManager; + private final ServerScheduler scheduler; + private final BaseLang baseLang; + private final NukkitConsole console; + private final ConsoleThread consoleThread; + private final SimpleCommandMap commandMap; + private final CraftingManager craftingManager; + private final ResourcePackManager resourcePackManager; + private final ConsoleCommandSender consoleSender; + private boolean hasStopped; + private final AtomicBoolean isRunning = new AtomicBoolean(true); private int tickCounter; - private long nextTick; - private final float[] tickAverage = {20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20}; - private final float[] useAverage = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - private float maxTick = 20; - - private float maxUse = 0; - - private final NukkitConsole console; - private final ConsoleThread consoleThread; - - private SimpleCommandMap commandMap; - - private CraftingManager craftingManager; - - private ResourcePackManager resourcePackManager; - - private ConsoleCommandSender consoleSender; - - private int maxPlayers; - - private boolean autoSave = true; - - private RCON rcon; - - private EntityMetadataStore entityMetadata; - - private PlayerMetadataStore playerMetadata; - - private LevelMetadataStore levelMetadata; - - private Network network; - - private boolean networkCompressionAsync; - public int networkCompressionLevel; - private int networkZlibProvider; - public int networkCompressionThreshold; - public boolean encryptionEnabled; - - private boolean autoTickRate; - private int autoTickRateLimit; - private boolean alwaysTickPlayers; + private float maxUse; private int baseTickRate; - private Boolean getAllowFlight = null; - private int difficulty = Integer.MAX_VALUE; - private int defaultGamemode = Integer.MAX_VALUE; - - private int autoSaveTicker = 0; - private int autoSaveTicks = 6000; - - private BaseLang baseLang; - - private boolean forceLanguage; - - private UUID serverID; - - private final String filePath; - private final String dataPath; - private final String pluginPath; - + private int autoSaveTicker; + private int maxPlayers; // setMaxPlayers + private boolean autoSave = true; // setAutoSave + private int difficulty; // setDifficulty + int spawnThresholdRadius; + private String ip; + private int port; + private final UUID serverID = UUID.randomUUID(); + private RCON rcon; + private final Network network; private QueryHandler queryHandler; - private QueryRegenerateEvent queryRegenerateEvent; - - private Config properties; - private Config config; + private final EntityMetadataStore entityMetadata; + private final PlayerMetadataStore playerMetadata; + private final LevelMetadataStore levelMetadata; private final Map players = new HashMap<>(); + final Map playerList = new HashMap<>(); - private final Map playerList = new HashMap<>(); + private static final Pattern UUID_PATTERN = Pattern.compile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}.dat$"); private final Map levels = new HashMap() { public Level put(Integer key, Level value) { @@ -214,13 +174,11 @@ public Level put(Integer key, Level value) { levelArray = levels.values().toArray(new Level[0]); return result; } - public boolean remove(Object key, Object value) { boolean result = super.remove(key, value); levelArray = levels.values().toArray(new Level[0]); return result; } - public Level remove(Object key) { Level result = super.remove(key); levelArray = levels.values().toArray(new Level[0]); @@ -229,23 +187,140 @@ public Level remove(Object key) { }; private Level[] levelArray = new Level[0]; - private final ServiceManager serviceManager = new NKServiceManager(); - - private Level defaultLevel = null; - - private boolean allowNether; - + private Level defaultLevel; private final Thread currentThread; - private Watchdog watchdog; - - private DB nameLookup; - + private final DB nameLookup; private PlayerDataSerializer playerDataSerializer; - + private final BatchingHelper batchingHelper; private final Set ignoredPackets = new HashSet<>(); + /** + * The server's MOTD. Remember to call network.setName() when updated. + */ + private String motd; + /** + * Default player data saving enabled. + */ + boolean shouldSavePlayerData; + /** + * Anti fly checks enabled. + */ + private boolean allowFlight; + /** + * Hardcore mode enabled. + */ + private boolean isHardcore; + /** + * Force resource packs. + */ + private boolean forceResources; + /** + * Force player gamemode to default on every join. + */ + private boolean forceGamemode; + /** + * Whitelist enabled. + */ + public boolean whitelistEnabled; + /** + * Xbox authentication enabled. + */ + public boolean xboxAuth; + /** + * Server side achievements enabled. + */ + boolean achievementsEnabled; + /** + * Pvp enabled. Can be changed per world using game rules. + */ + boolean pvpEnabled; + /** + * Announce server side announcements to all players. + */ + boolean announceAchievements; + /** + * How many chunks are sent to player per tick. + */ + public int chunksPerTick; + /** + * How many chunks needs to be sent before the player can spawn. + */ + int spawnThreshold; + /** + * Zlib compression level for sent packets. + */ + public int networkCompressionLevel; + /** + * Maximum view distance in chunks. + */ + private int viewDistance; + /** + * Server's default gamemode. + */ + public int gamemode; + /** + * Minimum amount of time between player skin changes. + */ + private int skinChangeCooldown; + /** + * Spawn protection radius. + */ + private int spawnRadius; + /** + * How often auto save should happen. + */ + private int autoSaveTicks; + /** + * Limit automatic tick rate. + */ + private int autoTickRateLimit; + /** + * Showing plugins in query enabled. + */ + public boolean queryPlugins; + /** + * Chunk caching enabled. + */ + public boolean cacheChunks; + /** + * Whether attacking an entity should stop player from sprinting. + */ + boolean attackStopSprint; + /** + * Enable automatic tick rate adjustments. + */ + private boolean autoTickRate; + /** + * Force server side translations. + */ + private boolean forceLanguage; + /** + * Always tick players. + */ + private boolean alwaysTickPlayers; + /** + * Don't disable client's own packs when force-resources is enabled. + */ + boolean forceResourcesAllowOwnPacks; + /** + * Enable encryption. + */ + boolean encryptionEnabled; + /** + * Use Snappy for packet compression for 1.19.30+ clients. + */ + public final boolean useSnappy; + /** + * Batch packets smaller than this will not be compressed. + */ + public int networkCompressionThreshold; + /** + * Temporary disable world saving to allow safe backup of leveldb worlds. + */ + public boolean holdWorldSave; + Server(final String filePath, String dataPath, String pluginPath, String predefinedLanguage) { Preconditions.checkState(instance == null, "Already initialized!"); currentThread = Thread.currentThread(); // Saves the current thread instance as a reference, used in Server#isPrimaryThread() @@ -253,27 +328,28 @@ public Level remove(Object key) { this.filePath = filePath; if (!new File(dataPath + "worlds/").exists()) { + //noinspection ResultOfMethodCallIgnored new File(dataPath + "worlds/").mkdirs(); } if (!new File(dataPath + "players/").exists()) { + //noinspection ResultOfMethodCallIgnored new File(dataPath + "players/").mkdirs(); } if (!new File(pluginPath).exists()) { + //noinspection ResultOfMethodCallIgnored new File(pluginPath).mkdirs(); } - this.dataPath = new File(dataPath).getAbsolutePath() + "/"; - this.pluginPath = new File(pluginPath).getAbsolutePath() + "/"; - - this.console = new NukkitConsole(this); - this.consoleThread = new ConsoleThread(); - this.consoleThread.start(); + this.dataPath = new File(dataPath).getAbsolutePath() + '/'; + this.pluginPath = new File(pluginPath).getAbsolutePath() + '/'; this.playerDataSerializer = new DefaultPlayerDataSerializer(this); - //todo: VersionString 现在不必要 + this.console = new NukkitConsole(); + this.consoleThread = new ConsoleThread(); + this.consoleThread.start(); if (!new File(this.dataPath + "nukkit.yml").exists()) { this.getLogger().info(TextFormat.GREEN + "Welcome! Please choose a language first!"); @@ -320,14 +396,12 @@ public Level remove(Object key) { } catch (IOException e) { throw new RuntimeException(e); } - } - this.console.setExecutingCommands(true); - - log.info("Loading {} ...", TextFormat.GREEN + "nukkit.yml" + TextFormat.WHITE); this.config = new Config(this.dataPath + "nukkit.yml", Config.YAML); + log.info("Loading server properties..."); + Nukkit.DEBUG = NukkitMath.clamp(this.getConfig("debug.level", 1), 1, 3); int logLevel = (Nukkit.DEBUG + 3) * 100; @@ -339,53 +413,21 @@ public Level remove(Object key) { } } - ignoredPackets.addAll(getConfig().getStringList("debug.ignored-packets")); - ignoredPackets.add("BatchPacket"); - - log.info("Loading {} ...", TextFormat.GREEN + "server.properties" + TextFormat.WHITE); - this.properties = new Config(this.dataPath + "server.properties", Config.PROPERTIES, new ConfigSection() { - { - put("motd", "A Nukkit Powered Server"); - put("sub-motd", "https://nukkitx.com"); - put("server-port", 19132); - put("server-ip", "0.0.0.0"); - put("view-distance", 10); - put("white-list", false); - put("achievements", true); - put("announce-player-achievements", true); - put("spawn-protection", 16); - put("max-players", 20); - put("allow-flight", false); - put("spawn-animals", true); - put("spawn-mobs", true); - put("gamemode", 0); - put("force-gamemode", false); - put("hardcore", false); - put("pvp", true); - put("difficulty", 1); - put("generator-settings", ""); - put("level-name", "world"); - put("level-seed", ""); - put("level-type", "DEFAULT"); - put("allow-nether", true); - put("enable-query", true); - put("enable-rcon", false); - put("rcon.password", Base64.getEncoder().encodeToString(UUID.randomUUID().toString().replace("-", "").getBytes()).substring(3, 13)); - put("auto-save", true); - put("force-resources", false); - put("xbox-auth", true); - } - }); + this.ignoredPackets.addAll(getConfig().getStringList("debug.ignored-packets")); - // Allow Nether? (determines if we create a nether world if one doesn't exist on startup) - this.allowNether = this.properties.getBoolean("allow-nether", true); + this.properties = new Config(this.dataPath + "server.properties", Config.PROPERTIES, new ServerProperties()); + + // Should not be modified after startup + this.useSnappy = this.getConfig("network.compression-use-snappy", false); - this.forceLanguage = this.getConfig("settings.force-language", false); this.baseLang = new BaseLang(this.getConfig("settings.language", BaseLang.FALLBACK_LANGUAGE)); + + this.loadSettings(); + log.info(this.getLanguage().translateString("language.selected", new String[]{getLanguage().getName(), getLanguage().getLang()})); log.info(getLanguage().translateString("nukkit.server.start", TextFormat.AQUA + this.getVersion() + TextFormat.RESET)); - Object poolSize = this.getConfig("settings.async-workers", (Object) "auto"); + Object poolSize = this.getConfig("settings.async-workers", "auto"); if (!(poolSize instanceof Integer)) { try { poolSize = Integer.valueOf((String) poolSize); @@ -396,30 +438,17 @@ public Level remove(Object key) { ServerScheduler.WORKERS = (int) poolSize; - this.networkZlibProvider = this.getConfig("network.zlib-provider", 2); - Zlib.setProvider(this.networkZlibProvider); - - this.networkCompressionLevel = this.getConfig("network.compression-level", 7); - this.networkCompressionAsync = this.getConfig("network.async-compression", true); - this.networkCompressionThreshold = this.getConfig("network.batch-threshold", 256); - this.encryptionEnabled = this.getConfig("network.encryption", false); - - if (!this.encryptionEnabled) { - this.getLogger().warning("Encryption is not enabled. For better security, it's recommended to enable it (network.encryption=true in nukkit.yml) if you don't use a proxy software."); - } + this.scheduler = new ServerScheduler(); - this.autoTickRate = this.getConfig("level-settings.auto-tick-rate", true); - this.autoTickRateLimit = this.getConfig("level-settings.auto-tick-rate-limit", 20); - this.alwaysTickPlayers = this.getConfig("level-settings.always-tick-players", false); - this.baseTickRate = this.getConfig("level-settings.base-tick-rate", 1); + this.console.setExecutingCommands(true); // Scheduler needs to be ready - this.scheduler = new ServerScheduler(); + this.batchingHelper = new BatchingHelper(); if (this.getPropertyBoolean("enable-rcon", false)) { try { - this.rcon = new RCON(this, this.getPropertyString("rcon.password", ""), (!this.getIp().equals("")) ? this.getIp() : "0.0.0.0", this.getPropertyInt("rcon.port", this.getPort())); + this.rcon = new RCON(this, this.getPropertyString("rcon.password", ""), (!this.getIp().isEmpty()) ? this.getIp() : "0.0.0.0", this.getPropertyInt("rcon.port", this.getPort())); } catch (IllegalArgumentException e) { - log.error(getLanguage().translateString(e.getMessage(), e.getCause().getMessage())); + log.error(baseLang.translateString(e.getMessage(), e.getCause().getMessage())); } } @@ -434,58 +463,33 @@ public Level remove(Object key) { this.banByIP = new BanList(this.dataPath + "banned-ips.json"); this.banByIP.load(); - this.maxPlayers = this.getPropertyInt("max-players", 20); - this.setAutoSave(this.getPropertyBoolean("auto-save", true)); - - if (this.getPropertyBoolean("hardcore", false) && this.getDifficulty() < 3) { - this.setPropertyInt("difficulty", 3); - } - - boolean bugReport; - if (this.getConfig().exists("settings.bug-report")) { - bugReport = this.getConfig().getBoolean("settings.bug-report"); - this.getProperties().remove("bug-report"); - } else { - bugReport = this.getPropertyBoolean("bug-report", true); //backwards compat - } - if (bugReport) { - ExceptionHandler.registerExceptionHandler(); - } - - log.info(this.getLanguage().translateString("nukkit.server.networkStart", new String[]{this.getIp().equals("") ? "*" : this.getIp(), String.valueOf(this.getPort())})); - this.serverID = UUID.randomUUID(); - - this.network = new Network(this); - this.network.setName(this.getMotd()); - this.network.setSubName(this.getSubMotd()); - - log.info(this.getLanguage().translateString("nukkit.server.info", this.getName(), TextFormat.YELLOW + this.getNukkitVersion() + TextFormat.WHITE, TextFormat.AQUA + this.getCodename() + TextFormat.WHITE, this.getApiVersion())); - log.info(this.getLanguage().translateString("nukkit.server.license", this.getName())); - this.consoleSender = new ConsoleCommandSender(); this.commandMap = new SimpleCommandMap(this); - // Initialize metrics - new NukkitMetrics(this); - - this.registerEntities(); - this.registerBlockEntities(); + registerEntities(); + registerBlockEntities(); Block.init(); Enchantment.init(); + GlobalBlockPalette.init(); RuntimeItems.init(); Item.init(); - EnumBiome.values(); //load class, this also registers biomes + //noinspection ResultOfMethodCallIgnored + EnumBiome.values(); Effect.init(); Potion.init(); Attribute.init(); - GlobalBlockPalette.getOrCreateRuntimeId(0, 0); //Force it to load + DispenseBehaviorRegister.init(); + //noinspection ResultOfMethodCallIgnored + EntityManager.get(); + //noinspection ResultOfMethodCallIgnored + BiomeDefinitionListPacket.getCachedPacket(); - // Convert legacy data before plugins get the chance to mess with it. + // Convert legacy data before plugins get the chance to mess with it try { nameLookup = Iq80DBFactory.factory.open(new File(dataPath, "players"), new Options() - .createIfMissing(true) - .compressionType(CompressionType.ZLIB_RAW)); + .createIfMissing(true) + .compressionType(CompressionType.ZLIB_RAW)); } catch (IOException e) { throw new RuntimeException(e); } @@ -500,34 +504,66 @@ public Level remove(Object key) { this.pluginManager = new PluginManager(this, this.commandMap); this.pluginManager.subscribeToPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE, this.consoleSender); - this.pluginManager.registerInterface(JavaPluginLoader.class); this.queryRegenerateEvent = new QueryRegenerateEvent(this, 5); + log.info(this.baseLang.translateString("nukkit.server.networkStart", new String[]{this.getIp().isEmpty() ? "*" : this.getIp(), String.valueOf(this.getPort())})); + this.network = new Network(this); + this.network.setName(this.getMotd()); + this.network.setSubName(this.getSubMotd()); this.network.registerInterface(new RakNetInterface(this)); - this.pluginManager.loadPlugins(this.pluginPath); + if (!this.encryptionEnabled) { + this.getLogger().warning("Encryption is not enabled! For better security, it's recommended to enable it (network.encryption: true in nukkit.yml) if you don't use a proxy software."); + } + + if (!this.xboxAuth) { + this.getLogger().warning("Xbox authentication is not enabled! It's recommended to enable it (xbox-auth=on in server.properties) if you don't use a proxy software or an authentication plugin."); + } + + log.info(this.getLanguage().translateString("nukkit.server.info", this.getName(), TextFormat.YELLOW + this.getNukkitVersion() + TextFormat.WHITE, TextFormat.AQUA + this.getCodename() + TextFormat.WHITE, this.getApiVersion())); + log.info(this.getLanguage().translateString("nukkit.server.license", this.getName())); + + ExceptionHandler.registerExceptionHandler(); + this.pluginManager.loadPlugins(this.pluginPath); this.enablePlugins(PluginLoadOrder.STARTUP); + boolean regenerateItemPalette = false; + + if (CustomItemManager.get().closeRegistry()) { + regenerateItemPalette = true; + } + + if (regenerateItemPalette) { + RuntimeItems.getMapping().generatePalette(); + } + + EntityManager.get().closeRegistry(); + + Item.initCreativeItems(); + + craftingManager.rebuildPacket(); + LevelProviderManager.addProvider(this, Anvil.class); - LevelProviderManager.addProvider(this, McRegion.class); - LevelProviderManager.addProvider(this, LevelDB.class); + LevelProviderManager.addProvider(this, LevelDBProvider.class); Generator.addGenerator(Flat.class, "flat", Generator.TYPE_FLAT); Generator.addGenerator(Normal.class, "normal", Generator.TYPE_INFINITE); Generator.addGenerator(Normal.class, "default", Generator.TYPE_INFINITE); Generator.addGenerator(Nether.class, "nether", Generator.TYPE_NETHER); - //todo: add old generator and hell generator + Generator.addGenerator(TheEnd.class, "the_end", Generator.TYPE_THE_END); + Generator.addGenerator(cn.nukkit.level.generator.Void.class, "void", Generator.TYPE_VOID); for (String name : this.getConfig("worlds", new HashMap()).keySet()) { if (!this.loadLevel(name)) { long seed; + String seedString = String.valueOf(this.getConfig("worlds." + name + ".seed", System.currentTimeMillis())); try { - seed = ((Integer) this.getConfig("worlds." + name + ".seed")).longValue(); - } catch (Exception e) { - seed = System.currentTimeMillis(); + seed = Long.parseLong(seedString); + } catch (NumberFormatException e) { + seed = seedString.hashCode(); } Map options = new HashMap<>(); @@ -569,20 +605,22 @@ public Level remove(Object key) { this.setDefaultLevel(this.getLevelByName(defaultName)); } - this.properties.save(true); - - if (this.getDefaultLevel() == null) { - this.getLogger().emergency(this.getLanguage().translateString("nukkit.level.defaultError")); + if (this.defaultLevel == null) { + this.getLogger().emergency(this.baseLang.translateString("nukkit.level.defaultError")); this.forceShutdown(); - return; } - EnumLevel.initLevels(); + this.properties.save(true); - if (this.getConfig("ticks-per.autosave", 6000) > 0) { - this.autoSaveTicks = this.getConfig("ticks-per.autosave", 6000); - } + //for (Map.Entry entry : this.getLevels().entrySet()) { + Level level = this.defaultLevel;//entry.getValue(); + this.getLogger().debug("Preparing spawn region for level " + level.getName()); + Vector3 spawn = level.getProvider().getSpawn(); + level.populateChunk(spawn.getChunkX(), spawn.getChunkZ(), true); + //} + + EnumLevel.initLevels(); this.enablePlugins(PluginLoadOrder.POSTWORLD); @@ -591,13 +629,18 @@ public Level remove(Object key) { this.watchdog.start(); } + // Initialize metrics + new NukkitMetrics(this); + this.start(); } + @SuppressWarnings("UnusedReturnValue") public int broadcastMessage(String message) { return this.broadcast(message, BROADCAST_CHANNEL_USERS); } + @SuppressWarnings("UnusedReturnValue") public int broadcastMessage(TextContainer message) { return this.broadcast(message, BROADCAST_CHANNEL_USERS); } @@ -610,6 +653,7 @@ public int broadcastMessage(String message, CommandSender[] recipients) { return recipients.length; } + @SuppressWarnings("UnusedReturnValue") public int broadcastMessage(String message, Collection recipients) { for (CommandSender recipient : recipients) { recipient.sendMessage(message); @@ -678,66 +722,14 @@ public static void broadcastPacket(Player[] players, DataPacket packet) { } } - @Deprecated public void batchPackets(Player[] players, DataPacket[] packets) { - this.batchPackets(players, packets, false); - } - - @Deprecated - public void batchPackets(Player[] players, DataPacket[] packets, boolean forceSync) { - if (players == null || packets == null || players.length == 0 || packets.length == 0) { - return; - } - - BatchPacketsEvent ev = new BatchPacketsEvent(players, packets, forceSync); - getPluginManager().callEvent(ev); - if (ev.isCancelled()) { - return; - } - - Timings.playerNetworkSendTimer.startTiming(); - byte[][] payload = new byte[packets.length * 2][]; - for (int i = 0; i < packets.length; i++) { - DataPacket p = packets[i]; - int idx = i * 2; - p.tryEncode(); - byte[] buf = p.getBuffer(); - payload[idx] = Binary.writeUnsignedVarInt(buf.length); - payload[idx + 1] = buf; - packets[i] = null; - } - - List targets = new ArrayList<>(); - for (Player p : players) { - if (p.isConnected()) { - targets.add(p.getSocketAddress()); - } - } - - if (!forceSync && this.networkCompressionAsync) { - this.getScheduler().scheduleAsyncTask(new CompressBatchedTask(payload, targets, this.networkCompressionLevel)); - } else { - try { - byte[] data = Binary.appendBytes(payload); - this.broadcastPacketsCallback(Network.deflateRaw(data, this.networkCompressionLevel), targets); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - Timings.playerNetworkSendTimer.stopTiming(); - } - - public void broadcastPacketsCallback(byte[] data, List targets) { - BatchPacket pk = new BatchPacket(); - pk.payload = data; - - for (InetSocketAddress i : targets) { - if (this.players.containsKey(i)) { - this.players.get(i).dataPacket(pk); - } - } + this.batchingHelper.batchPackets(this, players, packets); } + /** + * Enable all plugins with matching load order + * @param type load order + */ public void enablePlugins(PluginLoadOrder type) { for (Plugin plugin : new ArrayList<>(this.pluginManager.getPlugins().values())) { if (!plugin.isEnabled() && type == plugin.getDescription().getOrder()) { @@ -751,21 +743,33 @@ public void enablePlugins(PluginLoadOrder type) { } } + /** + * Enable a plugin + * @param plugin plugin + */ public void enablePlugin(Plugin plugin) { this.pluginManager.enablePlugin(plugin); } + /** + * Disable all loaded plugins + */ public void disablePlugins() { this.pluginManager.disablePlugins(); } + /** + * Run a command as CommandSender. Use server.getConsoleSender() to run as CONSOLE. + * @param sender command sender + * @param commandLine command without slash + * @return command was found and attempted to be executed + */ public boolean dispatchCommand(CommandSender sender, String commandLine) throws ServerException { // First we need to check if this command is on the main thread or not, if not, warn the user if (!this.isPrimaryThread()) { - getLogger().warning("Command Dispatched Async: " + commandLine); - getLogger().warning("Please notify author of plugin causing this execution to fix this bug!", new Throwable()); - // TODO: We should sync the command to the main thread too! + getLogger().warning("Command dispatched asynchronously: " + commandLine); } + if (sender == null) { throw new ServerException("CommandSender is not valid"); } @@ -779,57 +783,68 @@ public boolean dispatchCommand(CommandSender sender, String commandLine) throws return false; } - //todo: use ticker to check console + /** + * Get server console CommandSender + * @return ConsoleCommandSender + */ public ConsoleCommandSender getConsoleSender() { return consoleSender; } + /** + * Reload the server. Notice: may cause issues with some plugins. + */ public void reload() { - log.info("Reloading..."); - log.info("Saving levels..."); - for (Level level : this.levelArray) { level.save(); } - this.pluginManager.disablePlugins(); this.pluginManager.clearPlugins(); this.commandMap.clearCommands(); - log.info("Reloading properties..."); + log.info("Reloading server properties..."); this.properties.reload(); - this.maxPlayers = this.getPropertyInt("max-players", 20); - - if (this.getPropertyBoolean("hardcore", false) && this.getDifficulty() < 3) { - this.setPropertyInt("difficulty", difficulty = 3); - } + this.loadSettings(); this.banByIP.load(); this.banByName.load(); this.reloadWhitelist(); this.operators.reload(); - for (BanEntry entry : this.getIPBans().getEntires().values()) { + for (BanEntry entry : this.banByIP.getEntires().values()) { try { - this.getNetwork().blockAddress(InetAddress.getByName(entry.getName()), -1); - } catch (UnknownHostException e) { - // ignore - } + this.network.blockAddress(InetAddress.getByName(entry.getName())); + } catch (UnknownHostException ignore) {} } + log.info("Reloading plugins..."); this.pluginManager.registerInterface(JavaPluginLoader.class); this.pluginManager.loadPlugins(this.pluginPath); this.enablePlugins(PluginLoadOrder.STARTUP); this.enablePlugins(PluginLoadOrder.POSTWORLD); - Timings.reset(); } + /** + * Mark the server to be shut down. + */ public void shutdown() { isRunning.compareAndSet(true, false); } + /** + * Shut down the server immediately. + */ public void forceShutdown() { + this.forceShutdown(this.getConfig("settings.shutdown-message", "Server closed")); + } + + /** + * Shut down the server immediately. + * + * @param reason message that shows to players on disconnect + */ + public void forceShutdown(String reason) { if (this.hasStopped) { return; } @@ -840,103 +855,117 @@ public void forceShutdown() { this.hasStopped = true; ServerStopEvent serverStopEvent = new ServerStopEvent(); - getPluginManager().callEvent(serverStopEvent); + pluginManager.callEvent(serverStopEvent); + + if (this.holdWorldSave) { + this.getLogger().warning("World save hold was not released! Any backup currently being taken may be invalid"); + } if (this.rcon != null) { + this.getLogger().debug("Closing RCON..."); this.rcon.close(); } + this.getLogger().debug("Disconnecting all players..."); for (Player player : new ArrayList<>(this.players.values())) { - player.close(player.getLeaveMessage(), this.getConfig("settings.shutdown-message", "Server closed")); + player.close(player.getLeaveMessage(), reason); } - this.getLogger().debug("Disabling all plugins"); - this.pluginManager.disablePlugins(); + this.getLogger().debug("Disabling all plugins..."); + this.disablePlugins(); - this.getLogger().debug("Removing event handlers"); + this.getLogger().debug("Removing event handlers..."); HandlerList.unregisterAll(); - this.getLogger().debug("Stopping all tasks"); + this.getLogger().debug("Stopping all tasks..."); this.scheduler.cancelAllTasks(); this.scheduler.mainThreadHeartbeat(Integer.MAX_VALUE); - this.getLogger().debug("Unloading all levels"); + this.getLogger().debug("Unloading all levels..."); for (Level level : this.levelArray) { this.unloadLevel(level, true); + this.nextTick = System.currentTimeMillis(); // Fix Watchdog killing the server while saving worlds } - this.getLogger().debug("Closing console"); + this.getLogger().debug("Closing console..."); this.consoleThread.interrupt(); - this.getLogger().debug("Stopping network interfaces"); + this.getLogger().debug("Closing BatchingHelper..."); + this.batchingHelper.shutdown(); + + this.getLogger().debug("Stopping network interfaces..."); for (SourceInterface interfaz : this.network.getInterfaces()) { interfaz.shutdown(); this.network.unregisterInterface(interfaz); } if (nameLookup != null) { + this.getLogger().debug("Closing name lookup DB..."); nameLookup.close(); } - this.getLogger().debug("Disabling timings"); - Timings.stopServer(); if (this.watchdog != null) { + this.getLogger().debug("Stopping Watchdog..."); this.watchdog.kill(); } - //todo other things } catch (Exception e) { log.fatal("Exception happened while shutting down, exiting the process", e); System.exit(1); } } + /** + * Internal: Start the server + */ public void start() { - if (this.getPropertyBoolean("enable-query", true)) { + if (this.getPropertyBoolean("enable-query", false)) { this.queryHandler = new QueryHandler(); } - for (BanEntry entry : this.getIPBans().getEntires().values()) { + for (BanEntry entry : this.banByIP.getEntires().values()) { try { - this.network.blockAddress(InetAddress.getByName(entry.getName()), -1); - } catch (UnknownHostException e) { - // ignore - } + this.network.blockAddress(InetAddress.getByName(entry.getName())); + } catch (UnknownHostException ignore) {} } - //todo send usage setting this.tickCounter = 0; - log.info(this.getLanguage().translateString("nukkit.server.defaultGameMode", getGamemodeString(this.getGamemode()))); + //log.info(this.getLanguage().translateString("nukkit.server.defaultGameMode", getGamemodeString(this.getGamemode()))); - log.info(this.getLanguage().translateString("nukkit.server.startFinished", String.valueOf((double) (System.currentTimeMillis() - Nukkit.START_TIME) / 1000))); + log.info(this.baseLang.translateString("nukkit.server.startFinished", String.valueOf((double) (System.currentTimeMillis() - Nukkit.START_TIME) / 1000))); this.tickProcessor(); this.forceShutdown(); } + private static final byte[] QUERY_PREFIX = {(byte) 0xfe, (byte) 0xfd}; + + /** + * Internal: Handle query + * @param address sender address + * @param payload payload + */ public void handlePacket(InetSocketAddress address, ByteBuf payload) { try { - if (!payload.isReadable(3)) { + if (this.queryHandler == null || !payload.isReadable(3)) { return; } byte[] prefix = new byte[2]; payload.readBytes(prefix); - - if (!Arrays.equals(prefix, new byte[]{(byte) 0xfe, (byte) 0xfd})) { - return; - } - if (this.queryHandler != null) { + if (Arrays.equals(prefix, QUERY_PREFIX)) { this.queryHandler.handle(address, payload); } } catch (Exception e) { log.error("Error whilst handling packet", e); - - this.network.blockAddress(address.getAddress(), -1); + this.network.blockAddress(address.getAddress(), 300); } } private int lastLevelGC; + /** + * Internal: Tick the server + */ public void tickProcessor() { this.nextTick = System.currentTimeMillis(); try { @@ -950,22 +979,25 @@ public void tickProcessor() { if (next - 0.1 > current) { long allocated = next - current - 1; - { // Instead of wasting time, do something potentially useful - int offset = 0; - for (int i = 0; i < levelArray.length; i++) { - offset = (i + lastLevelGC) % levelArray.length; - Level level = levelArray[offset]; + // Instead of wasting time, do something potentially useful + int offset = 0; + for (int i = 0; i < levelArray.length; i++) { + offset = (i + lastLevelGC) % levelArray.length; + Level level = levelArray[offset]; + if (!level.isBeingConverted) { level.doGarbageCollection(allocated - 1); - allocated = next - System.currentTimeMillis(); - if (allocated <= 0) { - break; - } } - lastLevelGC = offset + 1; + allocated = next - System.currentTimeMillis(); + if (allocated <= 0) break; } + lastLevelGC = offset + 1; if (allocated > 0) { - Thread.sleep(allocated, 900000); + try { + Thread.sleep(allocated, 900000); + } catch (Exception e) { + this.getLogger().logException(e); + } } } } catch (RuntimeException e) { @@ -979,11 +1011,8 @@ public void tickProcessor() { } public void onPlayerCompleteLoginSequence(Player player) { - this.sendFullPlayerListData(player); - } - - public void onPlayerLogin(Player player) { - + this.playerList.put(player.getUniqueId(), player); + this.updatePlayerListData(player.getUniqueId(), player.getId(), player.getDisplayName(), player.getSkin(), player.getLoginChainData().getXUID()); } public void addPlayer(InetSocketAddress socketAddress, Player player) { @@ -999,9 +1028,7 @@ public void removeOnlinePlayer(Player player) { if (player.getUniqueId() == null) { return; } - if (this.playerList.containsKey(player.getUniqueId())) { - this.playerList.remove(player.getUniqueId()); - + if (this.playerList.remove(player.getUniqueId()) != null) { PlayerListPacket pk = new PlayerListPacket(); pk.type = PlayerListPacket.TYPE_REMOVE; pk.entries = new PlayerListPacket.Entry[]{new PlayerListPacket.Entry(player.getUniqueId())}; @@ -1026,7 +1053,7 @@ public void updatePlayerListData(UUID uuid, long entityId, String name, Skin ski PlayerListPacket pk = new PlayerListPacket(); pk.type = PlayerListPacket.TYPE_ADD; pk.entries = new PlayerListPacket.Entry[]{new PlayerListPacket.Entry(uuid, entityId, name, skin, xboxUserId)}; - Server.broadcastPacket(players, pk); + this.batchPackets(players, new DataPacket[]{pk}); // This is sent "directly" so it always gets through before possible TYPE_REMOVE packet for NPCs etc. } public void updatePlayerListData(UUID uuid, long entityId, String name, Skin skin, String xboxUserId, Collection players) { @@ -1060,13 +1087,12 @@ public void sendFullPlayerListData(Player player) { pk.type = PlayerListPacket.TYPE_ADD; pk.entries = this.playerList.values().stream() .map(p -> new PlayerListPacket.Entry( - p.getUniqueId(), - p.getId(), - p.getDisplayName(), - p.getSkin(), - p.getLoginChainData().getXUID())) + p.getUniqueId(), + p.getId(), + p.getDisplayName(), + p.getSkin(), + p.getLoginChainData().getXUID())) .toArray(PlayerListPacket.Entry[]::new); - player.dataPacket(pk); } @@ -1074,23 +1100,20 @@ public void sendRecipeList(Player player) { player.dataPacket(CraftingManager.packet); } - private void checkTickUpdates(int currentTick, long tickTime) { - for (Player p : new ArrayList<>(this.players.values())) { - /*if (!p.loggedIn && (tickTime - p.creationTime) >= 10000 && p.kick(PlayerKickEvent.Reason.LOGIN_TIMEOUT, "Login timeout")) { - continue; - } - - client freezes when applying resource packs - todo: fix*/ - - if (this.alwaysTickPlayers) { + private void checkTickUpdates(int currentTick) { + if (this.alwaysTickPlayers) { + for (Player p : new ArrayList<>(this.players.values())) { p.onUpdate(currentTick); } } - //Do level ticks + for (Player p : this.getOnlinePlayers().values()) { + p.resetPacketCounters(); + } + + // Do level ticks for (Level level : this.levelArray) { - if (level.getTickRate() > this.baseTickRate && --level.tickRateCounter > 0) { + if (level.isBeingConverted || (level.getTickRate() > this.baseTickRate && --level.tickRateCounter > 0)) { continue; } @@ -1111,74 +1134,72 @@ private void checkTickUpdates(int currentTick, long tickTime) { } else if (tickMs >= 50) { if (level.getTickRate() == this.baseTickRate) { level.setTickRate(Math.max(this.baseTickRate + 1, Math.min(this.autoTickRateLimit, tickMs / 50))); - this.getLogger().debug("Level \"" + level.getName() + "\" took " + NukkitMath.round(tickMs, 2) + "ms, setting tick rate to " + level.getTickRate() + " ticks"); + this.getLogger().debug("Level \"" + level.getName() + "\" took " + tickMs + "ms, setting tick rate to " + level.getTickRate() + " ticks"); } else if ((tickMs / level.getTickRate()) >= 50 && level.getTickRate() < this.autoTickRateLimit) { level.setTickRate(level.getTickRate() + 1); - this.getLogger().debug("Level \"" + level.getName() + "\" took " + NukkitMath.round(tickMs, 2) + "ms, setting tick rate to " + level.getTickRate() + " ticks"); + this.getLogger().debug("Level \"" + level.getName() + "\" took " + tickMs + "ms, setting tick rate to " + level.getTickRate() + " ticks"); } level.tickRateCounter = level.getTickRate(); } } } catch (Exception e) { - log.error(this.getLanguage().translateString("nukkit.level.tickError", - new String[]{level.getFolderName(), Utils.getExceptionMessage(e)})); + log.error(this.baseLang.translateString("nukkit.level.tickError", new String[]{level.getFolderName(), Utils.getExceptionMessage(e)})); } } } public void doAutoSave() { - if (this.getAutoSave()) { - Timings.levelSaveTimer.startTiming(); - for (Player player : new ArrayList<>(this.players.values())) { + if (this.autoSave) { + log.debug("Running auto save..."); + + for (Player player : this.players.values()) { if (player.isOnline()) { player.save(true); - } else if (!player.isConnected()) { - this.removePlayer(player); } } for (Level level : this.levelArray) { - level.save(); + if (level.getAutoSave()) { + if (level.getProvider() != null) { + try { + level.save(); + } catch (Exception ex) { + getLogger().error("Failed to auto save " + level.getName(), ex); + } + } + } } - Timings.levelSaveTimer.stopTiming(); } } - private boolean tick() { + private void tick() { long tickTime = System.currentTimeMillis(); - // TODO long time = tickTime - this.nextTick; if (time < -25) { try { Thread.sleep(Math.max(5, -time - 25)); } catch (InterruptedException e) { - Server.getInstance().getLogger().logException(e); + this.getLogger().logException(e); } } long tickTimeNano = System.nanoTime(); if ((tickTime - this.nextTick) < -25) { - return false; + return; } - Timings.fullServerTickTimer.startTiming(); - ++this.tickCounter; - Timings.connectionTimer.startTiming(); this.network.processInterfaces(); if (this.rcon != null) { this.rcon.check(); } - Timings.connectionTimer.stopTiming(); - Timings.schedulerTimer.startTiming(); this.scheduler.mainThreadHeartbeat(this.tickCounter); - Timings.schedulerTimer.stopTiming(); - this.checkTickUpdates(this.tickCounter, tickTime); + this.checkTickUpdates(this.tickCounter); for (Player player : new ArrayList<>(this.players.values())) { player.checkNetwork(); @@ -1186,13 +1207,14 @@ private boolean tick() { if ((this.tickCounter & 0b1111) == 0) { this.titleTick(); - this.network.resetStatistics(); + + //this.network.resetStatistics(); // Unnecessary since addStatistics is not used in the new raknet this.maxTick = 20; this.maxUse = 0; if ((this.tickCounter & 0b111111111) == 0) { try { - this.getPluginManager().callEvent(this.queryRegenerateEvent = new QueryRegenerateEvent(this, 5)); + this.pluginManager.callEvent(this.queryRegenerateEvent = new QueryRegenerateEvent(this, 5)); if (this.queryHandler != null) { this.queryHandler.regenerateInfo(); } @@ -1201,25 +1223,23 @@ private boolean tick() { } } - this.getNetwork().updateName(); + this.network.updateName(); } - if (this.autoSave && ++this.autoSaveTicker >= this.autoSaveTicks) { + if (++this.autoSaveTicker >= this.autoSaveTicks) { this.autoSaveTicker = 0; this.doAutoSave(); } if (this.tickCounter % 100 == 0) { for (Level level : this.levelArray) { - level.doChunkGarbageCollection(); + if (!level.isBeingConverted) { + level.doChunkGarbageCollection(); + } } } - Timings.fullServerTickTimer.stopTiming(); - //long now = System.currentTimeMillis(); long nowNano = System.nanoTime(); - //float tick = Math.min(20, 1000 / Math.max(1, now - tickTime)); - //float use = Math.min(1, (now - tickTime) / 50); float tick = (float) Math.min(20, 1000000000 / Math.max(1000000, ((double) nowNano - tickTimeNano))); float use = (float) Math.min(1, ((double) (nowNano - tickTimeNano)) / 50000000); @@ -1243,36 +1263,26 @@ private boolean tick() { } else { this.nextTick += 50; } - - return true; } public long getNextTick() { return nextTick; } - // TODO: Fix title tick - public void titleTick() { - if (!Nukkit.ANSI || !Nukkit.TITLE) { + private void titleTick() { + if (!Nukkit.TITLE) { return; } - Runtime runtime = Runtime.getRuntime(); double used = NukkitMath.round((double) (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024, 2); double max = NukkitMath.round(((double) runtime.maxMemory()) / 1024 / 1024, 2); - String usage = Math.round(used / max * 100) + "%"; - String title = (char) 0x1b + "]0;" + this.getName() + " " - + this.getNukkitVersion() - + " | Online " + this.players.size() + "/" + this.getMaxPlayers() - + " | Memory " + usage; - if (!Nukkit.shortTitle) { - title += " | U " + NukkitMath.round((this.network.getUpload() / 1024 * 1000), 2) - + " D " + NukkitMath.round((this.network.getDownload() / 1024 * 1000), 2) + " kB/s"; - } - title += " | TPS " + this.getTicksPerSecond() - + " | Load " + this.getTickUsage() + "%" + (char) 0x07; - - System.out.print(title); + System.out.print((char) 0x1b + "]0;Nukkit " + Nukkit.VERSION + + " | Online " + this.playerList.size() + '/' + this.maxPlayers + + " | Memory " + Math.round(used / max * 100) + '%' + + /*" | U " + NukkitMath.round((this.network.getUpload() / 1024 * 1000), 2) + + " D " + NukkitMath.round((this.network.getDownload() / 1024 * 1000), 2) + " kB/s" +*/ + " | TPS " + this.getTicksPerSecond() + + " | Load " + this.getTickUsage() + '%' + (char) 0x07); } public QueryRegenerateEvent getQueryInformation() { @@ -1292,7 +1302,7 @@ public String getNukkitVersion() { } public String getCodename() { - return Nukkit.CODENAME; + return ""; } public String getVersion() { @@ -1324,15 +1334,15 @@ public void setMaxPlayers(int maxPlayers) { } public int getPort() { - return this.getPropertyInt("server-port", 19132); + return port; } public int getViewDistance() { - return this.getPropertyInt("view-distance", 10); + return viewDistance; } public String getIp() { - return this.getPropertyString("server-ip", "0.0.0.0"); + return ip; } public UUID getServerUniqueId() { @@ -1351,23 +1361,15 @@ public void setAutoSave(boolean autoSave) { } public String getLevelType() { - return this.getPropertyString("level-type", "DEFAULT"); - } - - public boolean getGenerateStructures() { - return this.getPropertyBoolean("generate-structures", true); + return this.getPropertyString("level-type", "default"); } public int getGamemode() { - try { - return this.getPropertyInt("gamemode", 0) & 0b11; - } catch (NumberFormatException exception) { - return getGamemodeFromString(this.getPropertyString("gamemode")) & 0b11; - } + return gamemode; } public boolean getForceGamemode() { - return this.getPropertyBoolean("force-gamemode", false); + return this.forceGamemode; } public static String getGamemodeString(int mode) { @@ -1394,23 +1396,22 @@ public static int getGamemodeFromString(String str) { case "survival": case "s": return Player.SURVIVAL; - case "1": case "creative": case "c": return Player.CREATIVE; - case "2": case "adventure": case "a": return Player.ADVENTURE; - case "3": case "spectator": case "spc": case "view": case "v": return Player.SPECTATOR; + case "default": + return Server.getInstance().getDefaultGamemode(); } return -1; } @@ -1421,17 +1422,14 @@ public static int getDifficultyFromString(String str) { case "peaceful": case "p": return 0; - case "1": case "easy": case "e": return 1; - case "2": case "normal": case "n": return 2; - case "3": case "hard": case "h": @@ -1441,9 +1439,6 @@ public static int getDifficultyFromString(String str) { } public int getDifficulty() { - if (this.difficulty == Integer.MAX_VALUE) { - this.difficulty = getDifficultyFromString(this.getPropertyString("difficulty", "1")); - } return this.difficulty; } @@ -1456,45 +1451,45 @@ public void setDifficulty(int difficulty) { } public boolean hasWhitelist() { - return this.getPropertyBoolean("white-list", false); + return this.whitelistEnabled; } public int getSpawnRadius() { - return this.getPropertyInt("spawn-protection", 16); + return spawnRadius; } public boolean getAllowFlight() { - if (getAllowFlight == null) { - getAllowFlight = this.getPropertyBoolean("allow-flight", false); - } - return getAllowFlight; + return allowFlight; } public boolean isHardcore() { - return this.getPropertyBoolean("hardcore", false); + return this.isHardcore; } public int getDefaultGamemode() { - if (this.defaultGamemode == Integer.MAX_VALUE) { - this.defaultGamemode = this.getGamemode(); - } - return this.defaultGamemode; + return this.getGamemode(); } + /** + * Get MOTD + * @return motd + */ public String getMotd() { - return this.getPropertyString("motd", "A Nukkit Powered Server"); + return motd; } + /** + * Get Sub-MOTD (level name) + * @return sub-motd + */ public String getSubMotd() { - String subMotd = this.getPropertyString("sub-motd", "https://nukkitx.com"); - if (subMotd.isEmpty()) { - subMotd = "https://nukkitx.com"; // The client doesn't allow empty sub-motd in 1.16.210 - } - return subMotd; + String sub = this.getPropertyString("sub-motd", "Powered by Nukkit"); + if (sub.isEmpty()) sub = "Powered by Nukkit"; + return sub; } public boolean getForceResources() { - return this.getPropertyBoolean("force-resources", false); + return this.forceResources; } public MainLogger getLogger() { @@ -1529,14 +1524,29 @@ public ServerScheduler getScheduler() { return scheduler; } + /** + * Get current tick + * + * @return current tick + */ public int getTick() { return tickCounter; } + /** + * Get ticks per second + * + * @return TPS + */ public float getTicksPerSecond() { return ((float) Math.round(this.maxTick * 100)) / 100; } + /** + * Get average ticks per second + * + * @return average TPS + */ public float getTicksPerSecondAverage() { float sum = 0; int count = this.tickAverage.length; @@ -1546,36 +1556,81 @@ public float getTicksPerSecondAverage() { return (float) NukkitMath.round(sum / count, 2); } + /** + * Get main thread load + * + * @return tick usage % + */ public float getTickUsage() { return (float) NukkitMath.round(this.maxUse * 100, 2); } + /** + * Get average main thread load + * + * @return average main thread load + */ public float getTickUsageAverage() { float sum = 0; - int count = this.useAverage.length; for (float aUseAverage : this.useAverage) { sum += aUseAverage; } - return ((float) Math.round(sum / count * 100)) / 100; + return ((float) Math.round(sum / this.useAverage.length * 100)) / 100; } + /** + * Get command map + * + * @return command map + */ public SimpleCommandMap getCommandMap() { return commandMap; } + /** + * Get all online players + * + * @return online players + */ public Map getOnlinePlayers() { return ImmutableMap.copyOf(playerList); } + /** + * Get online player count + * + * @return online player count + */ + public int getOnlinePlayersCount() { + return this.playerList.size(); + } + + /** + * Register a recipe to CraftingManager. + * Please use getCraftingManager().registerRecipe(protocol, recipe) instead + * @param recipe recipe + */ public void addRecipe(Recipe recipe) { this.craftingManager.registerRecipe(recipe); } + /** + * Get an online player by uuid + * + * @param uuid uuid + * @return Optional Player + */ public Optional getPlayer(UUID uuid) { Preconditions.checkNotNull(uuid, "uuid"); return Optional.ofNullable(playerList.get(uuid)); } + /** + * Get known player uuid by player name + * + * @param name player name + * @return Optional UUID + */ public Optional lookupName(String name) { byte[] nameBytes = name.toLowerCase().getBytes(StandardCharsets.UTF_8); byte[] uuidBytes = nameLookup.get(nameBytes); @@ -1584,7 +1639,7 @@ public Optional lookupName(String name) { } if (uuidBytes.length != 16) { - log.warn("Invalid uuid in name lookup database detected! Removing"); + log.warn("Invalid uuid in name lookup database, removing: " + name); nameLookup.delete(nameBytes); return Optional.empty(); } @@ -1605,12 +1660,12 @@ void updateName(UUID uuid, String name) { @Deprecated public IPlayer getOfflinePlayer(final String name) { - IPlayer result = this.getPlayerExact(name.toLowerCase()); + IPlayer result = this.getPlayerExact(name); if (result != null) { return result; } - return lookupName(name).map(uuid -> new OfflinePlayer(this, uuid)) + return lookupName(name).map(uuid -> new OfflinePlayer(this, uuid, name)) .orElse(new OfflinePlayer(this, name)); } @@ -1658,8 +1713,7 @@ private CompoundTag getOfflinePlayerDataInternal(String name, boolean runEvent, return NBTIO.readCompressed(dataStream.get()); } } catch (IOException e) { - log.warn(this.getLanguage().translateString("nukkit.data.playerCorrupted", name)); - log.throwing(e); + log.warn(this.getLanguage().translateString("nukkit.data.playerCorrupted", name), e); } finally { if (dataStream.isPresent()) { try { @@ -1674,10 +1728,11 @@ private CompoundTag getOfflinePlayerDataInternal(String name, boolean runEvent, if (this.shouldSavePlayerData()) { log.info(this.getLanguage().translateString("nukkit.data.playerNotFound", name)); } - Position spawn = this.getDefaultLevel().getSafeSpawn(); + Vector3 spawn = this.getDefaultLevel().getProvider().getSpawn(); + long time = System.currentTimeMillis(); nbt = new CompoundTag() - .putLong("firstPlayed", System.currentTimeMillis() / 1000) - .putLong("lastPlayed", System.currentTimeMillis() / 1000) + .putLong("firstPlayed", time / 1000) + .putLong("lastPlayed", time / 1000) .putList(new ListTag("Pos") .add(new DoubleTag("0", spawn.x)) .add(new DoubleTag("1", spawn.y)) @@ -1695,7 +1750,7 @@ private CompoundTag getOfflinePlayerDataInternal(String name, boolean runEvent, .add(new FloatTag("1", 0))) .putFloat("FallDistance", 0) .putShort("Fire", 0) - .putShort("Air", 300) + .putShort("Air", 400) .putBoolean("OnGround", true) .putBoolean("Invulnerable", false); @@ -1722,48 +1777,62 @@ public void saveOfflinePlayerData(String name, CompoundTag tag, boolean async) { } private void saveOfflinePlayerData(String name, CompoundTag tag, boolean async, boolean runEvent) { - String nameLower = name.toLowerCase(); if (this.shouldSavePlayerData()) { + String nameLower = name.toLowerCase(); PlayerDataSerializeEvent event = new PlayerDataSerializeEvent(nameLower, playerDataSerializer); if (runEvent) { pluginManager.callEvent(event); } - this.getScheduler().scheduleTask(new Task() { - boolean hasRun = false; + if (async) { + this.getScheduler().scheduleTask(null, new Task() { + private volatile boolean hasRun = false; - @Override - public void onRun(int currentTick) { - this.onCancel(); - } + @Override + public void onRun(int currentTick) { + this.onCancel(); + } - //doing it like this ensures that the playerdata will be saved in a server shutdown - @Override - public void onCancel() { - if (!this.hasRun) { - this.hasRun = true; - saveOfflinePlayerDataInternal(event.getSerializer(), tag, nameLower, event.getUuid().orElse(null)); + // Doing it like this ensures that the player data will be saved in a server shutdown + @Override + public void onCancel() { + if (!this.hasRun) { + this.hasRun = true; + saveOfflinePlayerDataInternal(event.getSerializer(), tag, nameLower, event.getUuid().orElse(null)); + } } - } - }, async); + }, true); + } else { + saveOfflinePlayerDataInternal(event.getSerializer(), tag, nameLower, event.getUuid().orElse(null)); + } } } + /** + * Internal: Save offline player data + * + * @param serializer serializer + * @param tag compound tag + * @param name player name + * @param uuid player uuid + */ private void saveOfflinePlayerDataInternal(PlayerDataSerializer serializer, CompoundTag tag, String name, UUID uuid) { try (OutputStream dataStream = serializer.write(name, uuid)) { NBTIO.writeGZIPCompressed(tag, dataStream, ByteOrder.BIG_ENDIAN); } catch (Exception e) { - log.error(this.getLanguage().translateString("nukkit.data.saveError", name, e)); + log.error(this.getLanguage().translateString("nukkit.data.saveError", name, e), e); } } + /** + * Internal: Convert legacy player saves to the uuid based saving + */ private void convertLegacyPlayerData() { File dataDirectory = new File(getDataPath(), "players/"); - Pattern uuidPattern = Pattern.compile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}.dat$"); File[] files = dataDirectory.listFiles(file -> { String name = file.getName(); - return !uuidPattern.matcher(name).matches() && name.endsWith(".dat"); + return !UUID_PATTERN.matcher(name).matches() && name.endsWith(".dat"); }); if (files == null) { @@ -1806,6 +1875,12 @@ private void convertLegacyPlayerData() { } } + /** + * Get an online player by name + * + * @param name player name + * @return Player or null + */ public Player getPlayer(String name) { Player found = null; name = name.toLowerCase(); @@ -1826,10 +1901,15 @@ public Player getPlayer(String name) { return found; } + /** + * Get an online player by exact player name + * + * @param name exact player name + * @return Player or null + */ public Player getPlayerExact(String name) { - name = name.toLowerCase(); for (Player player : this.getOnlinePlayers().values()) { - if (player.getName().toLowerCase().equals(name)) { + if (player.getName().equalsIgnoreCase(name)) { return player; } } @@ -1837,6 +1917,12 @@ public Player getPlayerExact(String name) { return null; } + /** + * Get players that match with the name + * + * @param partialName name + * @return matching players + */ public Player[] matchPlayer(String partialName) { partialName = partialName.toLowerCase(); List matchedPlayer = new ArrayList<>(); @@ -1851,46 +1937,79 @@ public Player[] matchPlayer(String partialName) { return matchedPlayer.toArray(new Player[0]); } + /** + * Internal: Remove a player from the server + * + * @param player player + */ public void removePlayer(Player player) { - Player toRemove = this.players.remove(player.getSocketAddress()); - if (toRemove != null) { + if (this.players.remove(player.getSocketAddress()) != null) { return; } for (InetSocketAddress socketAddress : new ArrayList<>(this.players.keySet())) { - Player p = this.players.get(socketAddress); - if (player == p) { + if (player == this.players.get(socketAddress)) { this.players.remove(socketAddress); break; } } } + /** + * Get all levels + * + * @return levels + */ public Map getLevels() { return levels; } + /** + * Get default level + * + * @return default level + */ public Level getDefaultLevel() { return defaultLevel; } + /** + * Change the default level + * + * @param defaultLevel new default level + */ public void setDefaultLevel(Level defaultLevel) { if (defaultLevel == null || (this.isLevelLoaded(defaultLevel.getFolderName()) && defaultLevel != this.defaultLevel)) { this.defaultLevel = defaultLevel; } } + /** + * Check whether a level is loaded + * + * @param name level name + * @return is loaded + */ public boolean isLevelLoaded(String name) { return this.getLevelByName(name) != null; } + /** + * Get a level by ID + * + * @param levelId level ID + * @return Level or null + */ public Level getLevel(int levelId) { - if (this.levels.containsKey(levelId)) { - return this.levels.get(levelId); - } - return null; + return this.levels.get(levelId); } + /** + * Get a level by name + * + * @param name level name + * @return Level or null + */ public Level getLevelByName(String name) { for (Level level : this.levelArray) { if (level.getFolderName().equalsIgnoreCase(name)) { @@ -1901,28 +2020,54 @@ public Level getLevelByName(String name) { return null; } + /** + * Unload a level. + * Notice that the default level cannot be unloaded without forceUnload=true + * + * @param level Level + * @return unloaded + */ + @SuppressWarnings("UnusedReturnValue") public boolean unloadLevel(Level level) { return this.unloadLevel(level, false); } + /** + * Unload a level + *

+ * Notice: the default level cannot be unloaded without forceUnload=true + * + * @param level Level + * @param forceUnload force unload (ignore cancelled events and default level) + * @return unloaded + */ public boolean unloadLevel(Level level, boolean forceUnload) { - if (level == this.getDefaultLevel() && !forceUnload) { + if (level == this.defaultLevel && !forceUnload) { throw new IllegalStateException("The default level cannot be unloaded while running, please switch levels."); } return level.unload(forceUnload); - } + /** + * Load a level by name + * + * @param name level name + * @return loaded + */ public boolean loadLevel(String name) { if (Objects.equals(name.trim(), "")) { throw new LevelException("Invalid empty level name"); } + + if (!this.isPrimaryThread()) { + getLogger().warning("Level loaded asynchronously: " + name); + } + if (this.isLevelLoaded(name)) { return true; } else if (!this.isLevelGenerated(name)) { - log.warn(this.getLanguage().translateString("nukkit.level.notFound", name)); - + log.warn(this.baseLang.translateString("nukkit.level.notFound", name)); return false; } @@ -1931,14 +2076,13 @@ public boolean loadLevel(String name) { if (name.contains("/") || name.contains("\\")) { path = name; } else { - path = this.getDataPath() + "worlds/" + name + "/"; + path = this.dataPath + "worlds/" + name + '/'; } Class provider = LevelProviderManager.getProvider(path); if (provider == null) { - log.error(this.getLanguage().translateString("nukkit.level.loadError", new String[]{name, "Unknown provider"})); - + log.error(this.baseLang.translateString("nukkit.level.loadError", new String[]{name, "Unknown provider"})); return false; } @@ -1946,37 +2090,76 @@ public boolean loadLevel(String name) { try { level = new Level(this, name, path, provider); } catch (Exception e) { - log.error(this.getLanguage().translateString("nukkit.level.loadError", new String[]{name, e.getMessage()})); + log.error(this.baseLang.translateString("nukkit.level.loadError", new String[]{name, e.getMessage()})); return false; } - this.levels.put(level.getId(), level); - level.initLevel(); - this.getPluginManager().callEvent(new LevelLoadEvent(level)); + this.levels.put(level.getId(), level); level.setTickRate(this.baseTickRate); + this.pluginManager.callEvent(new LevelLoadEvent(level)); return true; } + /** + * Generate a new level + * + * @param name level name + * @return generated + */ public boolean generateLevel(String name) { - return this.generateLevel(name, new java.util.Random().nextLong()); + return this.generateLevel(name, Utils.random.nextLong()); } + /** + * Generate a new level + * + * @param name level name + * @param seed level seed + * @return generated + */ public boolean generateLevel(String name, long seed) { return this.generateLevel(name, seed, null); } + /** + * Generate a new level + * + * @param name level name + * @param seed level seed + * @param generator level generator + * @return generated + */ public boolean generateLevel(String name, long seed, Class generator) { return this.generateLevel(name, seed, generator, new HashMap<>()); } + /** + * Generate a new level + * + * @param name level name + * @param seed level seed + * @param generator level generator + * @param options level generator options + * @return generated + */ public boolean generateLevel(String name, long seed, Class generator, Map options) { return generateLevel(name, seed, generator, options, null); } + /** + * Generate a new level + * + * @param name level name + * @param seed level seed + * @param generator level generator + * @param options level generator options + * @param provider level provider + * @return generated + */ public boolean generateLevel(String name, long seed, Class generator, Map options, Class provider) { if (Objects.equals(name.trim(), "") || this.isLevelGenerated(name)) { return false; @@ -1991,7 +2174,7 @@ public boolean generateLevel(String name, long seed, Class } if (provider == null) { - provider = LevelProviderManager.getProviderByName(this.getConfig().get("level-settings.default-format", "anvil")); + provider = LevelProviderManager.getProviderByName("leveldb"); } String path; @@ -1999,7 +2182,7 @@ public boolean generateLevel(String name, long seed, Class if (name.contains("/") || name.contains("\\")) { path = name; } else { - path = this.getDataPath() + "worlds/" + name + "/"; + path = this.dataPath + "worlds/" + name + '/'; } Level level; @@ -2007,51 +2190,28 @@ public boolean generateLevel(String name, long seed, Class provider.getMethod("generate", String.class, String.class, long.class, Class.class, Map.class).invoke(null, path, name, seed, generator, options); level = new Level(this, name, path, provider); - this.levels.put(level.getId(), level); level.initLevel(); + + this.levels.put(level.getId(), level); + level.setTickRate(this.baseTickRate); } catch (Exception e) { - log.error(this.getLanguage().translateString("nukkit.level.generationError", new String[]{name, Utils.getExceptionMessage(e)})); + log.error(this.baseLang.translateString("nukkit.level.generationError", new String[]{name, Utils.getExceptionMessage(e)})); return false; } - this.getPluginManager().callEvent(new LevelInitEvent(level)); - - this.getPluginManager().callEvent(new LevelLoadEvent(level)); - - /*this.getLogger().notice(this.getLanguage().translateString("nukkit.level.backgroundGeneration", name)); - - int centerX = (int) level.getSpawnLocation().getX() >> 4; - int centerZ = (int) level.getSpawnLocation().getZ() >> 4; - - TreeMap order = new TreeMap<>(); - - for (int X = -3; X <= 3; ++X) { - for (int Z = -3; Z <= 3; ++Z) { - int distance = X * X + Z * Z; - int chunkX = X + centerX; - int chunkZ = Z + centerZ; - order.put(Level.chunkHash(chunkX, chunkZ), distance); - } - } - - List> sortList = new ArrayList<>(order.entrySet()); - - Collections.sort(sortList, new Comparator>() { - @Override - public int compare(Map.Entry o1, Map.Entry o2) { - return o2.getValue() - o1.getValue(); - } - }); - - for (String index : order.keySet()) { - Chunk.Entry entry = Level.getChunkXZ(index); - level.populateChunk(entry.chunkX, entry.chunkZ, true); - }*/ + this.pluginManager.callEvent(new LevelInitEvent(level)); + this.pluginManager.callEvent(new LevelLoadEvent(level)); return true; } + /** + * Check whether a level by name is generated + * + * @param name level name + * @return level found + */ public boolean isLevelGenerated(String name) { if (Objects.equals(name.trim(), "")) { return false; @@ -2063,7 +2223,7 @@ public boolean isLevelGenerated(String name) { if (name.contains("/") || name.contains("\\")) { path = name; } else { - path = this.getDataPath() + "worlds/" + name + "/"; + path = this.dataPath + "worlds/" + name + '/'; } return LevelProviderManager.getProvider(path) != null; @@ -2072,19 +2232,38 @@ public boolean isLevelGenerated(String name) { return true; } + /** + * Get BaseLang (server's default language) + * + * @return BaseLang + */ public BaseLang getLanguage() { return baseLang; } + /** + * Is forcing language enabled + * + * @return force-language enabled + */ public boolean isLanguageForced() { return forceLanguage; } + /** + * Get Network + * + * @return Network + */ public Network getNetwork() { return network; } - //Revising later... + /** + * Get nukkit.yml + * + * @return config + */ public Config getConfig() { return this.config; } @@ -2099,50 +2278,125 @@ public T getConfig(String variable, T defaultValue) { return value == null ? defaultValue : (T) value; } + /** + * Get server.properties + * + * @return server.properties as a Config + */ public Config getProperties() { return this.properties; } + /** + * Get a value from server.properties + * + * @param variable key + * @return value + */ public Object getProperty(String variable) { return this.getProperty(variable, null); } + /** + * Get a value from server.properties + * + * @param variable key + * @param defaultValue default value + * @return value + */ public Object getProperty(String variable, Object defaultValue) { - return this.properties.exists(variable) ? this.properties.get(variable) : defaultValue; + Object value = this.properties.get(variable); + return value == null ? defaultValue : value; } + /** + * Set a string value in server.properties + * + * @param variable key + * @param value value + */ public void setPropertyString(String variable, String value) { this.properties.set(variable, value); this.properties.save(); } - public String getPropertyString(String variable) { - return this.getPropertyString(variable, null); + /** + * Get a string value from server.properties + * + * @param key key + * @return value + */ + public String getPropertyString(String key) { + return this.getPropertyString(key, null); } + /** + * Get a string value from server.properties + * + * @param key key + * @param defaultValue default value + * @return value + */ public String getPropertyString(String key, String defaultValue) { - return this.properties.exists(key) ? this.properties.get(key).toString() : defaultValue; + Object value = this.properties.get(key); + return value == null ? defaultValue : value.toString(); } + /** + * Get an int value from server.properties + * + * @param variable key + * @return value + */ public int getPropertyInt(String variable) { return this.getPropertyInt(variable, null); } + /** + * Get an int value from server.properties + * + * @param variable key + * @param defaultValue default value + * @return value + */ public int getPropertyInt(String variable, Integer defaultValue) { - return this.properties.exists(variable) ? (!this.properties.get(variable).equals("") ? Integer.parseInt(String.valueOf(this.properties.get(variable))) : defaultValue) : defaultValue; + Object value = this.properties.get(variable); + return value == null || (value instanceof String && ((String) value).isEmpty()) ? defaultValue : Integer.parseInt(String.valueOf(value)); } + /** + * Set an int value in server.properties + * + * @param variable key + * @param value value + */ public void setPropertyInt(String variable, int value) { this.properties.set(variable, value); this.properties.save(); } + /** + * Get a boolean value from server.properties + * + * @param variable key + * @return value + */ public boolean getPropertyBoolean(String variable) { return this.getPropertyBoolean(variable, null); } + /** + * Get a boolean value from server.properties + * + * @param variable key + * @param defaultValue default value + * @return value + */ public boolean getPropertyBoolean(String variable, Object defaultValue) { - Object value = this.properties.exists(variable) ? this.properties.get(variable) : defaultValue; + Object value = this.properties.get(variable); + if (value == null) { + value = defaultValue; + } if (value instanceof Boolean) { return (Boolean) value; } @@ -2156,11 +2410,23 @@ public boolean getPropertyBoolean(String variable, Object defaultValue) { return false; } + /** + * Set a boolean value in server.properties + * + * @param variable key + * @param value value + */ public void setPropertyBoolean(String variable, boolean value) { this.properties.set(variable, value ? "1" : "0"); this.properties.save(); } + /** + * Get plugin commands + * + * @param name command name + * @return PluginIdentifiableCommand or null + */ public PluginIdentifiableCommand getPluginCommand(String name) { Command command = this.commandMap.getCommand(name); if (command instanceof PluginIdentifiableCommand) { @@ -2170,14 +2436,29 @@ public PluginIdentifiableCommand getPluginCommand(String name) { } } + /** + * Get list of banned players + * + * @return ban list + */ public BanList getNameBans() { return this.banByName; } + /** + * Get list of IP bans + * + * @return IP bans + */ public BanList getIPBans() { return this.banByIP; } + /** + * Give player the operator status + * + * @param name player name + */ public void addOp(String name) { this.operators.set(name.toLowerCase(), true); Player player = this.getPlayerExact(name); @@ -2187,6 +2468,11 @@ public void addOp(String name) { this.operators.save(true); } + /** + * Remove player's operator status + * + * @param name player name + */ public void removeOp(String name) { this.operators.remove(name.toLowerCase()); Player player = this.getPlayerExact(name); @@ -2196,43 +2482,78 @@ public void removeOp(String name) { this.operators.save(); } + /** + * Add a player to whitelist + * + * @param name player name + */ public void addWhitelist(String name) { this.whitelist.set(name.toLowerCase(), true); this.whitelist.save(true); } + /** + * Remove a player from whitelist + * + * @param name player name + */ public void removeWhitelist(String name) { this.whitelist.remove(name.toLowerCase()); this.whitelist.save(true); } + /** + * Check whether a player is whitelisted + * + * @param name player name + * @return is whitelisted or whitelist is not enabled + */ public boolean isWhitelisted(String name) { return !this.hasWhitelist() || this.operators.exists(name, true) || this.whitelist.exists(name, true); } + /** + * Check whether a player is an operator + * + * @param name player name + * @return is operator + */ public boolean isOp(String name) { return name != null && this.operators.exists(name, true); } + /** + * Get whitelist config + * + * @return whitelist + */ public Config getWhitelist() { return whitelist; } + /** + * Get operator list config + * + * @return operators + */ public Config getOps() { return operators; } + /** + * Reload whitelist + */ public void reloadWhitelist() { this.whitelist.reload(); } - public ServiceManager getServiceManager() { - return serviceManager; - } - + /** + * Load command aliases from nukkit.yml + */ public Map> getCommandAliases() { Object section = this.getConfig("aliases"); Map> result = new LinkedHashMap<>(); + if (section instanceof Map) { for (Map.Entry entry : (Set) ((Map) section).entrySet()) { List commands = new ArrayList<>(); @@ -2249,51 +2570,84 @@ public Map> getCommandAliases() { } return result; + } + /** + * Get service manager + * + * @return service manager + */ + public ServiceManager getServiceManager() { + return serviceManager; } + /** + * Should player data saving be enabled + * + * @return player data saving enabled + */ public boolean shouldSavePlayerData() { - return this.getConfig("player.save-player-data", true); + return shouldSavePlayerData; } + /** + * How often player is allowed to change skin in game (in seconds) + * + * @return skin change cooldown + */ public int getPlayerSkinChangeCooldown() { - return this.getConfig("player.skin-change-cooldown", 30); + return skinChangeCooldown; } /** - * Checks the current thread against the expected primary thread for the - * server. + * Checks the current thread against the expected primary thread for the server. *

- * Note: this method should not be used to indicate the current - * synchronized state of the runtime. A current thread matching the main - * thread indicates that it is synchronized, but a mismatch does not - * preclude the same assumption. + * Note: this method should not be used to indicate the current synchronized state of the runtime. A current thread matching the main thread indicates that it is synchronized, but a mismatch does not preclude the same assumption. * - * @return true if the current thread matches the expected primary thread, - * false otherwise + * @return true if the current thread matches the expected primary thread, false otherwise */ public final boolean isPrimaryThread() { - return (Thread.currentThread() == currentThread); + return Thread.currentThread() == currentThread; } + /** + * Get server's primary thread + * + * @return primary thread + */ public Thread getPrimaryThread() { return currentThread; } - private void registerEntities() { - Entity.registerEntity("Lightning", EntityLightning.class); - Entity.registerEntity("Arrow", EntityArrow.class); - Entity.registerEntity("EnderPearl", EntityEnderPearl.class); - Entity.registerEntity("FallingSand", EntityFallingBlock.class); - Entity.registerEntity("Firework", EntityFirework.class); + /** + * Internal method to register all default entities + */ + private static void registerEntities() { + //Items Entity.registerEntity("Item", EntityItem.class); Entity.registerEntity("Painting", EntityPainting.class); + Entity.registerEntity("XpOrb", EntityXPOrb.class); + Entity.registerEntity("ArmorStand", EntityArmorStand.class); + Entity.registerEntity("EndCrystal", EntityEndCrystal.class); + Entity.registerEntity("FallingSand", EntityFallingBlock.class); Entity.registerEntity("PrimedTnt", EntityPrimedTNT.class); + Entity.registerEntity("Firework", EntityFirework.class); + //Projectiles + Entity.registerEntity("Arrow", EntityArrow.class); Entity.registerEntity("Snowball", EntitySnowball.class); + Entity.registerEntity("EnderPearl", EntityEnderPearl.class); + Entity.registerEntity("ThrownExpBottle", EntityExpBottle.class); + Entity.registerEntity("ThrownPotion", EntityPotion.class); + Entity.registerEntity("Egg", EntityEgg.class); + Entity.registerEntity("ThrownLingeringPotion", EntityPotionLingering.class); + Entity.registerEntity("ThrownTrident", EntityThrownTrident.class); + Entity.registerEntity("FishingHook", EntityFishingHook.class); + Entity.registerEntity("EnderEye", EntityEnderEye.class); + Entity.registerEntity("AreaEffectCloud", EntityAreaEffectCloud.class); //Monsters Entity.registerEntity("Blaze", EntityBlaze.class); - Entity.registerEntity("CaveSpider", EntityCaveSpider.class); Entity.registerEntity("Creeper", EntityCreeper.class); + Entity.registerEntity("CaveSpider", EntityCaveSpider.class); Entity.registerEntity("Drowned", EntityDrowned.class); Entity.registerEntity("ElderGuardian", EntityElderGuardian.class); Entity.registerEntity("EnderDragon", EntityEnderDragon.class); @@ -2301,92 +2655,94 @@ private void registerEntities() { Entity.registerEntity("Endermite", EntityEndermite.class); Entity.registerEntity("Evoker", EntityEvoker.class); Entity.registerEntity("Ghast", EntityGhast.class); - Entity.registerEntity("GlowSquid", EntityGlowSquid.class); Entity.registerEntity("Guardian", EntityGuardian.class); - Entity.registerEntity("Hoglin", EntityHoglin.class); Entity.registerEntity("Husk", EntityHusk.class); Entity.registerEntity("MagmaCube", EntityMagmaCube.class); Entity.registerEntity("Phantom", EntityPhantom.class); - Entity.registerEntity("Piglin", EntityPiglin.class); - Entity.registerEntity("PiglinBrute", EntityPiglinBrute.class); - Entity.registerEntity("Pillager", EntityPillager.class); Entity.registerEntity("Ravager", EntityRavager.class); Entity.registerEntity("Shulker", EntityShulker.class); Entity.registerEntity("Silverfish", EntitySilverfish.class); Entity.registerEntity("Skeleton", EntitySkeleton.class); + Entity.registerEntity("SkeletonHorse", EntitySkeletonHorse.class); Entity.registerEntity("Slime", EntitySlime.class); - Entity.registerEntity("SnowGolem", EntitySnowGolem.class); Entity.registerEntity("Spider", EntitySpider.class); Entity.registerEntity("Stray", EntityStray.class); - Entity.registerEntity("Vex", EntityVex.class); Entity.registerEntity("Vindicator", EntityVindicator.class); - Entity.registerEntity("Warden", EntityWarden.class); - Entity.registerEntity("Witch", EntityWitch.class); - Entity.registerEntity("Wither", EntityWither.class); + Entity.registerEntity("Vex", EntityVex.class); Entity.registerEntity("WitherSkeleton", EntityWitherSkeleton.class); + Entity.registerEntity("Wither", EntityWither.class); + Entity.registerEntity("Witch", EntityWitch.class); + Entity.registerEntity("ZombiePigman", EntityZombiePigman.class); + Entity.registerEntity("ZombieVillager", EntityZombieVillagerV1.class); Entity.registerEntity("Zombie", EntityZombie.class); + Entity.registerEntity("Pillager", EntityPillager.class); + Entity.registerEntity("ZombieVillagerV2", EntityZombieVillager.class); + Entity.registerEntity("Hoglin", EntityHoglin.class); + Entity.registerEntity("Piglin", EntityPiglin.class); Entity.registerEntity("Zoglin", EntityZoglin.class); - Entity.registerEntity("ZombiePigman", EntityZombiePigman.class); - Entity.registerEntity("ZombieVillager", EntityZombieVillager.class); - Entity.registerEntity("ZombieVillagerV1", EntityZombieVillagerV1.class); + Entity.registerEntity("PiglinBrute", EntityPiglinBrute.class); + Entity.registerEntity("Warden", EntityWarden.class); + Entity.registerEntity("Breeze", EntityBreeze.class); + Entity.registerEntity("Bogged", EntityBogged.class); //Passive - Entity.registerEntity("Allay", EntityAllay.class); - Entity.registerEntity("Axolotl", EntityAxolotl.class); Entity.registerEntity("Bat", EntityBat.class); - Entity.registerEntity("Bee", EntityBee.class); Entity.registerEntity("Cat", EntityCat.class); Entity.registerEntity("Chicken", EntityChicken.class); Entity.registerEntity("Cod", EntityCod.class); Entity.registerEntity("Cow", EntityCow.class); Entity.registerEntity("Dolphin", EntityDolphin.class); Entity.registerEntity("Donkey", EntityDonkey.class); - Entity.registerEntity("Fox", EntityFox.class); - Entity.registerEntity("Frog", EntityFrog.class); - Entity.registerEntity("Goat", EntityGoat.class); Entity.registerEntity("Horse", EntityHorse.class); + Entity.registerEntity("IronGolem", EntityIronGolem.class); Entity.registerEntity("Llama", EntityLlama.class); Entity.registerEntity("Mooshroom", EntityMooshroom.class); Entity.registerEntity("Mule", EntityMule.class); - Entity.registerEntity("Ocelot", EntityOcelot.class); Entity.registerEntity("Panda", EntityPanda.class); Entity.registerEntity("Parrot", EntityParrot.class); - Entity.registerEntity("Pig", EntityPig.class); Entity.registerEntity("PolarBear", EntityPolarBear.class); + Entity.registerEntity("Pig", EntityPig.class); Entity.registerEntity("Pufferfish", EntityPufferfish.class); Entity.registerEntity("Rabbit", EntityRabbit.class); Entity.registerEntity("Salmon", EntitySalmon.class); Entity.registerEntity("Sheep", EntitySheep.class); - Entity.registerEntity("SkeletonHorse", EntitySkeletonHorse.class); Entity.registerEntity("Squid", EntitySquid.class); - Entity.registerEntity("Strider", EntityStrider.class); - Entity.registerEntity("Tadpole", EntityTadpole.class); + Entity.registerEntity("SnowGolem", EntitySnowGolem.class); Entity.registerEntity("TropicalFish", EntityTropicalFish.class); Entity.registerEntity("Turtle", EntityTurtle.class); - Entity.registerEntity("Villager", EntityVillager.class); - Entity.registerEntity("VillagerV1", EntityVillagerV1.class); - Entity.registerEntity("WanderingTrader", EntityWanderingTrader.class); Entity.registerEntity("Wolf", EntityWolf.class); + Entity.registerEntity("Ocelot", EntityOcelot.class); + Entity.registerEntity("Villager", EntityVillagerV1.class); Entity.registerEntity("ZombieHorse", EntityZombieHorse.class); - //Projectile - Entity.registerEntity("Egg", EntityEgg.class); - Entity.registerEntity("ThrownExpBottle", EntityExpBottle.class); - Entity.registerEntity("ThrownPotion", EntityPotion.class); - Entity.registerEntity("ThrownTrident", EntityThrownTrident.class); - Entity.registerEntity("XpOrb", EntityXPOrb.class); - - Entity.registerEntity("Human", EntityHuman.class, true); - //Vehicle - Entity.registerEntity("Boat", EntityBoat.class); + Entity.registerEntity("WanderingTrader", EntityWanderingTrader.class); + Entity.registerEntity("VillagerV2", EntityVillager.class); + Entity.registerEntity("Fox", EntityFox.class); + Entity.registerEntity("Bee", EntityBee.class); + Entity.registerEntity("Strider", EntityStrider.class); + Entity.registerEntity("Goat", EntityGoat.class); + Entity.registerEntity("Axolotl", EntityAxolotl.class); + Entity.registerEntity("GlowSquid", EntityGlowSquid.class); + Entity.registerEntity("Allay", EntityAllay.class); + Entity.registerEntity("Frog", EntityFrog.class); + Entity.registerEntity("Tadpole", EntityTadpole.class); + Entity.registerEntity("Camel", EntityCamel.class); + Entity.registerEntity("Sniffer", EntitySniffer.class); + Entity.registerEntity("Armadillo", EntityArmadillo.class); + //Vehicles + Entity.registerEntity("MinecartRideable", EntityMinecartEmpty.class); Entity.registerEntity("MinecartChest", EntityMinecartChest.class); Entity.registerEntity("MinecartHopper", EntityMinecartHopper.class); - Entity.registerEntity("MinecartRideable", EntityMinecartEmpty.class); Entity.registerEntity("MinecartTnt", EntityMinecartTNT.class); - - Entity.registerEntity("EndCrystal", EntityEndCrystal.class); - Entity.registerEntity("FishingHook", EntityFishingHook.class); + Entity.registerEntity("Boat", EntityBoat.class); + Entity.registerEntity("ChestBoat", EntityChestBoat.class); + //Others + Entity.registerEntity("Human", EntityHuman.class, true); + Entity.registerEntity("Lightning", EntityLightning.class); } - private void registerBlockEntities() { + /** + * Internal method to register all default block entities + */ + private static void registerBlockEntities() { BlockEntity.registerBlockEntity(BlockEntity.FURNACE, BlockEntityFurnace.class); BlockEntity.registerBlockEntity(BlockEntity.CHEST, BlockEntityChest.class); BlockEntity.registerBlockEntity(BlockEntity.SIGN, BlockEntitySign.class); @@ -2395,6 +2751,7 @@ private void registerBlockEntities() { BlockEntity.registerBlockEntity(BlockEntity.FLOWER_POT, BlockEntityFlowerPot.class); BlockEntity.registerBlockEntity(BlockEntity.BREWING_STAND, BlockEntityBrewingStand.class); BlockEntity.registerBlockEntity(BlockEntity.ITEM_FRAME, BlockEntityItemFrame.class); + BlockEntity.registerBlockEntity(BlockEntity.GLOW_ITEM_FRAME, BlockEntityItemFrameGlow.class); BlockEntity.registerBlockEntity(BlockEntity.CAULDRON, BlockEntityCauldron.class); BlockEntity.registerBlockEntity(BlockEntity.ENDER_CHEST, BlockEntityEnderChest.class); BlockEntity.registerBlockEntity(BlockEntity.BEACON, BlockEntityBeacon.class); @@ -2405,29 +2762,160 @@ private void registerBlockEntities() { BlockEntity.registerBlockEntity(BlockEntity.JUKEBOX, BlockEntityJukebox.class); BlockEntity.registerBlockEntity(BlockEntity.SHULKER_BOX, BlockEntityShulkerBox.class); BlockEntity.registerBlockEntity(BlockEntity.BANNER, BlockEntityBanner.class); + BlockEntity.registerBlockEntity(BlockEntity.DROPPER, BlockEntityDropper.class); + BlockEntity.registerBlockEntity(BlockEntity.DISPENSER, BlockEntityDispenser.class); + BlockEntity.registerBlockEntity(BlockEntity.MOB_SPAWNER, BlockEntitySpawner.class); BlockEntity.registerBlockEntity(BlockEntity.MUSIC, BlockEntityMusic.class); + BlockEntity.registerBlockEntity(BlockEntity.CAMPFIRE, BlockEntityCampfire.class); + BlockEntity.registerBlockEntity(BlockEntity.BARREL, BlockEntityBarrel.class); + BlockEntity.registerBlockEntity(BlockEntity.LECTERN, BlockEntityLectern.class); + BlockEntity.registerBlockEntity(BlockEntity.BLAST_FURNACE, BlockEntityBlastFurnace.class); + BlockEntity.registerBlockEntity(BlockEntity.SMOKER, BlockEntitySmoker.class); + BlockEntity.registerBlockEntity(BlockEntity.BELL, BlockEntityBell.class); + BlockEntity.registerBlockEntity(BlockEntity.PERSISTENT_CONTAINER, PersistentDataContainerBlockEntity.class); } + /** + * Is nether enabled on this server + * + * @return nether enabled + */ public boolean isNetherAllowed() { - return this.allowNether; + return EnumLevel.NETHER.getLevel() != null; } + /** + * Get player data serializer that is used to save player data + * + * @return player data serializer + */ public PlayerDataSerializer getPlayerDataSerializer() { return playerDataSerializer; } + /** + * Set player data serializer that is used to save player data + * + * @param playerDataSerializer player data serializer + */ public void setPlayerDataSerializer(PlayerDataSerializer playerDataSerializer) { this.playerDataSerializer = Preconditions.checkNotNull(playerDataSerializer, "playerDataSerializer"); } - public boolean isIgnoredPacket(Class clazz) { + boolean isIgnoredPacket(Class clazz) { return this.ignoredPackets.contains(clazz.getSimpleName()); } + /** + * Get the Server instance + * + * @return Server + */ public static Server getInstance() { return instance; } + /** + * Load server config + */ + private void loadSettings() { + /* nukkit.yml */ + + this.forceLanguage = this.getConfig("settings.force-language", false); + this.queryPlugins = this.getConfig("settings.query-plugins", true); + + this.networkCompressionThreshold = this.getConfig("network.batch-threshold", 256); + this.networkCompressionLevel = Math.max(Math.min(this.getConfig("network.compression-level", 5), 9), 0); + this.encryptionEnabled = this.getConfig("network.encryption", false); + + this.autoTickRate = this.getConfig("level-settings.auto-tick-rate", true); + this.autoTickRateLimit = this.getConfig("level-settings.auto-tick-rate-limit", 20); + this.baseTickRate = this.getConfig("level-settings.base-tick-rate", 1); + this.alwaysTickPlayers = this.getConfig("level-settings.always-tick-players", false); + + this.autoSaveTicks = this.getConfig("ticks-per.autosave", 6000); + + this.shouldSavePlayerData = this.getConfig("player.save-player-data", true); + this.skinChangeCooldown = this.getConfig("player.skin-change-cooldown", 15); + this.attackStopSprint = this.getConfig("player.attack-stop-sprint", true); + + this.chunksPerTick = this.getConfig("chunk-sending.per-tick", 4); + this.spawnThreshold = this.getConfig("spawn-threshold", 56); + this.cacheChunks = this.getConfig("cache-chunks", false); + + this.spawnThresholdRadius = (int) Math.ceil(Math.sqrt(this.spawnThreshold)); + + /* server.properties */ + + this.maxPlayers = this.getPropertyInt("max-players", 20); + this.xboxAuth = this.getPropertyBoolean("xbox-auth", true); + this.achievementsEnabled = this.getPropertyBoolean("achievements", true); + this.pvpEnabled = this.getPropertyBoolean("pvp", true); + this.announceAchievements = this.getPropertyBoolean("announce-player-achievements", true); + this.allowFlight = this.getPropertyBoolean("allow-flight", false); + this.isHardcore = this.getPropertyBoolean("hardcore", false); + this.forceResources = this.getPropertyBoolean("force-resources", false); + this.forceResourcesAllowOwnPacks = this.getPropertyBoolean("force-resources-allow-client-packs", false); + this.whitelistEnabled = this.getPropertyBoolean("white-list", false); + this.forceGamemode = this.getPropertyBoolean("force-gamemode", false); + this.motd = this.getPropertyString("motd", "A Minecraft Server"); + this.viewDistance = this.getPropertyInt("view-distance", 10); + this.port = this.getPropertyInt("server-port", 19132); + this.ip = this.getPropertyString("server-ip", "0.0.0.0"); + this.spawnRadius = this.getPropertyInt("spawn-protection", 16); + + this.setAutoSave(this.getPropertyBoolean("auto-save", true)); + + try { + this.gamemode = this.getPropertyInt("gamemode", 0) & 0b11; + } catch (NumberFormatException exception) { + this.gamemode = getGamemodeFromString(this.getPropertyString("gamemode", "0")) & 0b11; + } + + if (this.isHardcore && this.difficulty < 3) { + this.setDifficulty(3); + } else { + this.setDifficulty(getDifficultyFromString(this.getPropertyString("difficulty", "2"))); + } + } + + /** + * This class contains all default server.properties values. + */ + private static class ServerProperties extends ConfigSection { + { + put("motd", "A Minecraft Server"); + put("sub-motd", "Powered by Nukkit"); + put("server-port", 19132); + put("server-ip", "0.0.0.0"); + put("view-distance", 10); + put("achievements", true); + put("announce-player-achievements", true); + put("spawn-protection", 16); + put("gamemode", 0); + put("force-gamemode", false); + put("difficulty", 2); + put("hardcore", false); + put("pvp", true); + put("white-list", false); + put("generator-settings", ""); + put("level-name", "world"); + put("level-seed", ""); + put("level-type", "default"); + put("enable-rcon", false); + put("rcon.password", Base64.getEncoder().encodeToString(UUID.randomUUID().toString().replace("-", "").getBytes()).substring(3, 13)); + put("force-resources", false); + put("force-resources-allow-client-packs", false); + put("xbox-auth", true); + put("auto-save", true); + put("force-language", false); + put("enable-query", false); + put("allow-flight", false); + put("allow-nether", true); + put("allow-the-end", true); + } + } + private class ConsoleThread extends Thread implements InterruptibleThread { @Override diff --git a/src/main/java/cn/nukkit/api/API.java b/src/main/java/cn/nukkit/api/API.java deleted file mode 100644 index 9276ee5bbe4..00000000000 --- a/src/main/java/cn/nukkit/api/API.java +++ /dev/null @@ -1,130 +0,0 @@ -package cn.nukkit.api; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import static cn.nukkit.api.API.Definition.UNIVERSAL; -import static cn.nukkit.api.API.Usage.BLEEDING; - -/** - * Describes an API element. - * - * @author Lin Mulan, Nukkit Project - * @see Usage - * @see Definition - */ -@Retention(RetentionPolicy.SOURCE) -@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE, ElementType.TYPE}) -@API(usage = BLEEDING, definition = UNIVERSAL) -@SuppressWarnings("unused") -public @interface API { - - /** - * Indicates the level of stability of an API element. - * The stability also describes when to use this API element. - * - * @return The stability - * @see Usage - */ - Usage usage(); - - /** - * Indicates definition or the platforms this API element supports. - * - * @return The definition - * @see Definition - */ - Definition definition(); - - /** - * Enum constant for API usage. Indicates when to use this API element. - * - * @see #DEPRECATED - * @see #INCUBATING - * @see #BLEEDING - * @see #EXPERIMENTAL - * @see #MAINTAINED - * @see #STABLE - */ - enum Usage { - - /** - * Should no longer be used, might disappear in the next minor release. - */ - DEPRECATED, - - /** - * Intended for features in drafts. Should only be used for tests. - * - *

Might contains notable new features, but will be moved to a new package before remarking to {@link #BLEEDING}. - * Could be unsafe, might be removed without prior notice. Warnings will be send if used. - */ - INCUBATING, - - /** - * Intended for features in early development. Should only be used for tests. - * - *

Might be unwrapped, unsafe or have unchecked parameters. - * Further contribution was demanded to enhance, strengthen or simplify before remarking to {@link #EXPERIMENTAL}. - * Might be removed or modified without prior notice. - */ - BLEEDING, - - /** - * Intended for new, experimental features where we are looking for feedback. - * At least stable for development. - * - *

Use with caution, might be remarked to {@link #MAINTAINED} or {@link #STABLE} in the future, - * but also might be removed without prior notice. - */ - EXPERIMENTAL, - - /** - * Intended for features that was tested, documented and at least stable for production use. - * - *

These features will not be modified in a backwards-incompatible way for at least next minor release - * of the current major version. Will be remarked to {@link #DEPRECATED} first if scheduled for removal. - */ - MAINTAINED, - - /** - * Intended for features that was tested, documented and is preferred in production use. - * - *

Will not be changed in a backwards-incompatible way in the current version. - */ - STABLE - } - - /** - * Enum constant for API definition. Indicates which client platform this API element supports. - * - * @see #INTERNAL - * @see #PLATFORM_NATIVE - * @see #UNIVERSAL - */ - enum Definition { - - /** - * Intended for features should only be used by Nukkit itself. - * Should not be used in production. - */ - INTERNAL, - - /** - * Intended for features only available on one or several client platforms. - * - *

By using {@code PLATFORM_NATIVE} features, program will lose some cross-platform features provided. - * Might not available in some client platforms. Read the documents carefully before using this API element. - */ - PLATFORM_NATIVE, - - /** - * Intended for features implemented in all client platforms. - * - *

Preferred to use for production use, but sometimes be lack of platform-native features. - */ - UNIVERSAL - } -} diff --git a/src/main/java/cn/nukkit/block/Block.java b/src/main/java/cn/nukkit/block/Block.java index c5cc814492e..e405c0759ec 100644 --- a/src/main/java/cn/nukkit/block/Block.java +++ b/src/main/java/cn/nukkit/block/Block.java @@ -10,6 +10,7 @@ import cn.nukkit.level.Level; import cn.nukkit.level.MovingObjectPosition; import cn.nukkit.level.Position; +import cn.nukkit.level.persistence.PersistentDataContainer; import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.math.BlockFace; import cn.nukkit.math.Vector3; @@ -18,6 +19,8 @@ import cn.nukkit.plugin.Plugin; import cn.nukkit.potion.Effect; import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.material.BlockType; +import cn.nukkit.utils.material.MaterialType; import java.lang.reflect.Constructor; import java.util.List; @@ -25,305 +28,89 @@ import java.util.Optional; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class Block extends Position implements Metadatable, Cloneable, AxisAlignedBB, BlockID { - public static Class[] list = null; - public static Block[] fullList = null; - public static int[] light = null; - public static int[] lightFilter = null; - public static boolean[] solid = null; - public static double[] hardness = null; - public static boolean[] transparent = null; + + @SuppressWarnings("UnnecessaryBoxing") + public static final int MAX_BLOCK_ID = Integer.valueOf("2048"); + public static final int DATA_BITS = 6; + public static final int DATA_SIZE = 1 << DATA_BITS; + public static final int DATA_MASK = DATA_SIZE - 1; + + public static final BlockLayer LAYER_NORMAL = BlockLayer.NORMAL; + public static final BlockLayer LAYER_WATERLOGGED = BlockLayer.WATERLOGGED; + + @SuppressWarnings("rawtypes") + public static Class[] list; + public static Block[] fullList; + public static int[] light; + public static int[] lightFilter; + public static boolean[] solid; + public static double[] hardness; + public static boolean[] transparent; + public static boolean[] hasMeta; + + private BlockLayer layer = LAYER_NORMAL; + + private BlockType materialType; + /** - * if a block has can have variants + * A commonly used block face pattern */ - public static boolean[] hasMeta = null; + protected static final int[] FACES2534 = {2, 5, 3, 4}; + + protected Block() { - protected Block() {} + } - @SuppressWarnings("unchecked") public static void init() { if (list == null) { - list = new Class[256]; - fullList = new Block[4096]; - light = new int[256]; - lightFilter = new int[256]; - solid = new boolean[256]; - hardness = new double[256]; - transparent = new boolean[256]; - hasMeta = new boolean[256]; - - list[AIR] = BlockAir.class; //0 - list[STONE] = BlockStone.class; //1 - list[GRASS] = BlockGrass.class; //2 - list[DIRT] = BlockDirt.class; //3 - list[COBBLESTONE] = BlockCobblestone.class; //4 - list[PLANKS] = BlockPlanks.class; //5 - list[SAPLING] = BlockSapling.class; //6 - list[BEDROCK] = BlockBedrock.class; //7 - list[WATER] = BlockWater.class; //8 - list[STILL_WATER] = BlockWaterStill.class; //9 - list[LAVA] = BlockLava.class; //10 - list[STILL_LAVA] = BlockLavaStill.class; //11 - list[SAND] = BlockSand.class; //12 - list[GRAVEL] = BlockGravel.class; //13 - list[GOLD_ORE] = BlockOreGold.class; //14 - list[IRON_ORE] = BlockOreIron.class; //15 - list[COAL_ORE] = BlockOreCoal.class; //16 - list[WOOD] = BlockWood.class; //17 - list[LEAVES] = BlockLeaves.class; //18 - list[SPONGE] = BlockSponge.class; //19 - list[GLASS] = BlockGlass.class; //20 - list[LAPIS_ORE] = BlockOreLapis.class; //21 - list[LAPIS_BLOCK] = BlockLapis.class; //22 - list[DISPENSER] = BlockDispenser.class; //23 - list[SANDSTONE] = BlockSandstone.class; //24 - list[NOTEBLOCK] = BlockNoteblock.class; //25 - list[BED_BLOCK] = BlockBed.class; //26 - list[POWERED_RAIL] = BlockRailPowered.class; //27 - list[DETECTOR_RAIL] = BlockRailDetector.class; //28 - list[STICKY_PISTON] = BlockPistonSticky.class; //29 - list[COBWEB] = BlockCobweb.class; //30 - list[TALL_GRASS] = BlockTallGrass.class; //31 - list[DEAD_BUSH] = BlockDeadBush.class; //32 - list[PISTON] = BlockPiston.class; //33 - list[PISTON_HEAD] = BlockPistonHead.class; //34 - list[WOOL] = BlockWool.class; //35 - list[DANDELION] = BlockDandelion.class; //37 - list[FLOWER] = BlockFlower.class; //38 - list[BROWN_MUSHROOM] = BlockMushroomBrown.class; //39 - list[RED_MUSHROOM] = BlockMushroomRed.class; //40 - list[GOLD_BLOCK] = BlockGold.class; //41 - list[IRON_BLOCK] = BlockIron.class; //42 - list[DOUBLE_STONE_SLAB] = BlockDoubleSlabStone.class; //43 - list[STONE_SLAB] = BlockSlabStone.class; //44 - list[BRICKS_BLOCK] = BlockBricks.class; //45 - list[TNT] = BlockTNT.class; //46 - list[BOOKSHELF] = BlockBookshelf.class; //47 - list[MOSS_STONE] = BlockMossStone.class; //48 - list[OBSIDIAN] = BlockObsidian.class; //49 - list[TORCH] = BlockTorch.class; //50 - list[FIRE] = BlockFire.class; //51 - list[MONSTER_SPAWNER] = BlockMobSpawner.class; //52 - list[WOOD_STAIRS] = BlockStairsWood.class; //53 - list[CHEST] = BlockChest.class; //54 - list[REDSTONE_WIRE] = BlockRedstoneWire.class; //55 - list[DIAMOND_ORE] = BlockOreDiamond.class; //56 - list[DIAMOND_BLOCK] = BlockDiamond.class; //57 - list[WORKBENCH] = BlockCraftingTable.class; //58 - list[WHEAT_BLOCK] = BlockWheat.class; //59 - list[FARMLAND] = BlockFarmland.class; //60 - list[FURNACE] = BlockFurnace.class; //61 - list[BURNING_FURNACE] = BlockFurnaceBurning.class; //62 - list[SIGN_POST] = BlockSignPost.class; //63 - list[WOOD_DOOR_BLOCK] = BlockDoorWood.class; //64 - list[LADDER] = BlockLadder.class; //65 - list[RAIL] = BlockRail.class; //66 - list[COBBLESTONE_STAIRS] = BlockStairsCobblestone.class; //67 - list[WALL_SIGN] = BlockWallSign.class; //68 - list[LEVER] = BlockLever.class; //69 - list[STONE_PRESSURE_PLATE] = BlockPressurePlateStone.class; //70 - list[IRON_DOOR_BLOCK] = BlockDoorIron.class; //71 - list[WOODEN_PRESSURE_PLATE] = BlockPressurePlateWood.class; //72 - list[REDSTONE_ORE] = BlockOreRedstone.class; //73 - list[GLOWING_REDSTONE_ORE] = BlockOreRedstoneGlowing.class; //74 - list[UNLIT_REDSTONE_TORCH] = BlockRedstoneTorchUnlit.class; - list[REDSTONE_TORCH] = BlockRedstoneTorch.class; //76 - list[STONE_BUTTON] = BlockButtonStone.class; //77 - list[SNOW_LAYER] = BlockSnowLayer.class; //78 - list[ICE] = BlockIce.class; //79 - list[SNOW_BLOCK] = BlockSnow.class; //80 - list[CACTUS] = BlockCactus.class; //81 - list[CLAY_BLOCK] = BlockClay.class; //82 - list[SUGARCANE_BLOCK] = BlockSugarcane.class; //83 - list[JUKEBOX] = BlockJukebox.class; //84 - list[FENCE] = BlockFence.class; //85 - list[PUMPKIN] = BlockPumpkin.class; //86 - list[NETHERRACK] = BlockNetherrack.class; //87 - list[SOUL_SAND] = BlockSoulSand.class; //88 - list[GLOWSTONE_BLOCK] = BlockGlowstone.class; //89 - list[NETHER_PORTAL] = BlockNetherPortal.class; //90 - list[LIT_PUMPKIN] = BlockPumpkinLit.class; //91 - list[CAKE_BLOCK] = BlockCake.class; //92 - list[UNPOWERED_REPEATER] = BlockRedstoneRepeaterUnpowered.class; //93 - list[POWERED_REPEATER] = BlockRedstoneRepeaterPowered.class; //94 - list[INVISIBLE_BEDROCK] = BlockBedrockInvisible.class; //95 - list[TRAPDOOR] = BlockTrapdoor.class; //96 - list[MONSTER_EGG] = BlockMonsterEgg.class; //97 - list[STONE_BRICKS] = BlockBricksStone.class; //98 - list[BROWN_MUSHROOM_BLOCK] = BlockHugeMushroomBrown.class; //99 - list[RED_MUSHROOM_BLOCK] = BlockHugeMushroomRed.class; //100 - list[IRON_BARS] = BlockIronBars.class; //101 - list[GLASS_PANE] = BlockGlassPane.class; //102 - list[MELON_BLOCK] = BlockMelon.class; //103 - list[PUMPKIN_STEM] = BlockStemPumpkin.class; //104 - list[MELON_STEM] = BlockStemMelon.class; //105 - list[VINE] = BlockVine.class; //106 - list[FENCE_GATE] = BlockFenceGate.class; //107 - list[BRICK_STAIRS] = BlockStairsBrick.class; //108 - list[STONE_BRICK_STAIRS] = BlockStairsStoneBrick.class; //109 - list[MYCELIUM] = BlockMycelium.class; //110 - list[WATER_LILY] = BlockWaterLily.class; //111 - list[NETHER_BRICKS] = BlockBricksNether.class; //112 - list[NETHER_BRICK_FENCE] = BlockFenceNetherBrick.class; //113 - list[NETHER_BRICKS_STAIRS] = BlockStairsNetherBrick.class; //114 - list[NETHER_WART_BLOCK] = BlockNetherWart.class; //115 - list[ENCHANTING_TABLE] = BlockEnchantingTable.class; //116 - list[BREWING_STAND_BLOCK] = BlockBrewingStand.class; //117 - list[CAULDRON_BLOCK] = BlockCauldron.class; //118 - list[END_PORTAL] = BlockEndPortal.class; //119 - list[END_PORTAL_FRAME] = BlockEndPortalFrame.class; //120 - list[END_STONE] = BlockEndStone.class; //121 - list[DRAGON_EGG] = BlockDragonEgg.class; //122 - list[REDSTONE_LAMP] = BlockRedstoneLamp.class; //123 - list[LIT_REDSTONE_LAMP] = BlockRedstoneLampLit.class; //124 - //TODO: list[DROPPER] = BlockDropper.class; //125 - list[ACTIVATOR_RAIL] = BlockRailActivator.class; //126 - list[COCOA] = BlockCocoa.class; //127 - list[SANDSTONE_STAIRS] = BlockStairsSandstone.class; //128 - list[EMERALD_ORE] = BlockOreEmerald.class; //129 - list[ENDER_CHEST] = BlockEnderChest.class; //130 - list[TRIPWIRE_HOOK] = BlockTripWireHook.class; - list[TRIPWIRE] = BlockTripWire.class; //132 - list[EMERALD_BLOCK] = BlockEmerald.class; //133 - list[SPRUCE_WOOD_STAIRS] = BlockStairsSpruce.class; //134 - list[BIRCH_WOOD_STAIRS] = BlockStairsBirch.class; //135 - list[JUNGLE_WOOD_STAIRS] = BlockStairsJungle.class; //136 - - list[BEACON] = BlockBeacon.class; //138 - list[STONE_WALL] = BlockWall.class; //139 - list[FLOWER_POT_BLOCK] = BlockFlowerPot.class; //140 - list[CARROT_BLOCK] = BlockCarrot.class; //141 - list[POTATO_BLOCK] = BlockPotato.class; //142 - list[WOODEN_BUTTON] = BlockButtonWooden.class; //143 - list[SKULL_BLOCK] = BlockSkull.class; //144 - list[ANVIL] = BlockAnvil.class; //145 - list[TRAPPED_CHEST] = BlockTrappedChest.class; //146 - list[LIGHT_WEIGHTED_PRESSURE_PLATE] = BlockWeightedPressurePlateLight.class; //147 - list[HEAVY_WEIGHTED_PRESSURE_PLATE] = BlockWeightedPressurePlateHeavy.class; //148 - list[UNPOWERED_COMPARATOR] = BlockRedstoneComparatorUnpowered.class; //149 - list[POWERED_COMPARATOR] = BlockRedstoneComparatorPowered.class; //149 - list[DAYLIGHT_DETECTOR] = BlockDaylightDetector.class; //151 - list[REDSTONE_BLOCK] = BlockRedstone.class; //152 - list[QUARTZ_ORE] = BlockOreQuartz.class; //153 - list[HOPPER_BLOCK] = BlockHopper.class; //154 - list[QUARTZ_BLOCK] = BlockQuartz.class; //155 - list[QUARTZ_STAIRS] = BlockStairsQuartz.class; //156 - list[DOUBLE_WOOD_SLAB] = BlockDoubleSlabWood.class; //157 - list[WOOD_SLAB] = BlockSlabWood.class; //158 - list[STAINED_TERRACOTTA] = BlockTerracottaStained.class; //159 - list[STAINED_GLASS_PANE] = BlockGlassPaneStained.class; //160 - - list[LEAVES2] = BlockLeaves2.class; //161 - list[WOOD2] = BlockWood2.class; //162 - list[ACACIA_WOOD_STAIRS] = BlockStairsAcacia.class; //163 - list[DARK_OAK_WOOD_STAIRS] = BlockStairsDarkOak.class; //164 - list[SLIME_BLOCK] = BlockSlime.class; //165 - - list[IRON_TRAPDOOR] = BlockTrapdoorIron.class; //167 - list[PRISMARINE] = BlockPrismarine.class; //168 - list[SEA_LANTERN] = BlockSeaLantern.class; //169 - list[HAY_BALE] = BlockHayBale.class; //170 - list[CARPET] = BlockCarpet.class; //171 - list[TERRACOTTA] = BlockTerracotta.class; //172 - list[COAL_BLOCK] = BlockCoal.class; //173 - list[PACKED_ICE] = BlockIcePacked.class; //174 - list[DOUBLE_PLANT] = BlockDoublePlant.class; //175 - list[STANDING_BANNER] = BlockBanner.class; //176 - list[WALL_BANNER] = BlockWallBanner.class; //177 - list[DAYLIGHT_DETECTOR_INVERTED] = BlockDaylightDetectorInverted.class; //178 - list[RED_SANDSTONE] = BlockRedSandstone.class; //179 - list[RED_SANDSTONE_STAIRS] = BlockStairsRedSandstone.class; //180 - list[DOUBLE_RED_SANDSTONE_SLAB] = BlockDoubleSlabRedSandstone.class; //181 - list[RED_SANDSTONE_SLAB] = BlockSlabRedSandstone.class; //182 - list[FENCE_GATE_SPRUCE] = BlockFenceGateSpruce.class; //183 - list[FENCE_GATE_BIRCH] = BlockFenceGateBirch.class; //184 - list[FENCE_GATE_JUNGLE] = BlockFenceGateJungle.class; //185 - list[FENCE_GATE_DARK_OAK] = BlockFenceGateDarkOak.class; //186 - list[FENCE_GATE_ACACIA] = BlockFenceGateAcacia.class; //187 - - list[SPRUCE_DOOR_BLOCK] = BlockDoorSpruce.class; //193 - list[BIRCH_DOOR_BLOCK] = BlockDoorBirch.class; //194 - list[JUNGLE_DOOR_BLOCK] = BlockDoorJungle.class; //195 - list[ACACIA_DOOR_BLOCK] = BlockDoorAcacia.class; //196 - list[DARK_OAK_DOOR_BLOCK] = BlockDoorDarkOak.class; //197 - list[GRASS_PATH] = BlockGrassPath.class; //198 - list[ITEM_FRAME_BLOCK] = BlockItemFrame.class; //199 - list[CHORUS_FLOWER] = BlockChorusFlower.class; //200 - list[PURPUR_BLOCK] = BlockPurpur.class; //201 - - list[PURPUR_STAIRS] = BlockStairsPurpur.class; //203 - - list[UNDYED_SHULKER_BOX] = BlockUndyedShulkerBox.class; //205 - list[END_BRICKS] = BlockBricksEndStone.class; //206 - - list[END_ROD] = BlockEndRod.class; //208 - list[END_GATEWAY] = BlockEndGateway.class; //209 - - list[MAGMA] = BlockMagma.class; //213 - list[BLOCK_NETHER_WART_BLOCK] = BlockNetherWartBlock.class; //214 - list[RED_NETHER_BRICK] = BlockBricksRedNether.class; //215 - list[BONE_BLOCK] = BlockBone.class; //216 - - list[SHULKER_BOX] = BlockShulkerBox.class; //218 - list[PURPLE_GLAZED_TERRACOTTA] = BlockTerracottaGlazedPurple.class; //219 - list[WHITE_GLAZED_TERRACOTTA] = BlockTerracottaGlazedWhite.class; //220 - list[ORANGE_GLAZED_TERRACOTTA] = BlockTerracottaGlazedOrange.class; //221 - list[MAGENTA_GLAZED_TERRACOTTA] = BlockTerracottaGlazedMagenta.class; //222 - list[LIGHT_BLUE_GLAZED_TERRACOTTA] = BlockTerracottaGlazedLightBlue.class; //223 - list[YELLOW_GLAZED_TERRACOTTA] = BlockTerracottaGlazedYellow.class; //224 - list[LIME_GLAZED_TERRACOTTA] = BlockTerracottaGlazedLime.class; //225 - list[PINK_GLAZED_TERRACOTTA] = BlockTerracottaGlazedPink.class; //226 - list[GRAY_GLAZED_TERRACOTTA] = BlockTerracottaGlazedGray.class; //227 - list[SILVER_GLAZED_TERRACOTTA] = BlockTerracottaGlazedSilver.class; //228 - list[CYAN_GLAZED_TERRACOTTA] = BlockTerracottaGlazedCyan.class; //229 - - list[BLUE_GLAZED_TERRACOTTA] = BlockTerracottaGlazedBlue.class; //231 - list[BROWN_GLAZED_TERRACOTTA] = BlockTerracottaGlazedBrown.class; //232 - list[GREEN_GLAZED_TERRACOTTA] = BlockTerracottaGlazedGreen.class; //233 - list[RED_GLAZED_TERRACOTTA] = BlockTerracottaGlazedRed.class; //234 - list[BLACK_GLAZED_TERRACOTTA] = BlockTerracottaGlazedBlack.class; //235 - list[CONCRETE] = BlockConcrete.class; //236 - list[CONCRETE_POWDER] = BlockConcretePowder.class; //237 - - list[CHORUS_PLANT] = BlockChorusPlant.class; //240 - list[STAINED_GLASS] = BlockGlassStained.class; //241 - list[PODZOL] = BlockPodzol.class; //243 - list[BEETROOT_BLOCK] = BlockBeetroot.class; //244 - list[STONECUTTER] = BlockStonecutter.class; //245 - list[GLOWING_OBSIDIAN] = BlockObsidianGlowing.class; //246 - //list[NETHER_REACTOR] = BlockNetherReactor.class; //247 Should not be removed - - //TODO: list[PISTON_EXTENSION] = BlockPistonExtension.class; //250 - - list[OBSERVER] = BlockObserver.class; //251 - - for (int id = 0; id < 256; id++) { - Class c = list[id]; + list = new Class[MAX_BLOCK_ID]; + fullList = new Block[MAX_BLOCK_ID * DATA_SIZE]; + light = new int[MAX_BLOCK_ID]; + lightFilter = new int[MAX_BLOCK_ID]; + solid = new boolean[MAX_BLOCK_ID]; + hardness = new double[MAX_BLOCK_ID]; + transparent = new boolean[MAX_BLOCK_ID]; + hasMeta = new boolean[MAX_BLOCK_ID]; + + Blocks.init(); + + for (int id = 0; id < MAX_BLOCK_ID; id++) { + Class c = list[id]; if (c != null) { Block block; try { block = (Block) c.newInstance(); try { + @SuppressWarnings("rawtypes") Constructor constructor = c.getDeclaredConstructor(int.class); constructor.setAccessible(true); - for (int data = 0; data < 16; ++data) { - fullList[(id << 4) | data] = (Block) constructor.newInstance(data); + for (int data = 0; data < (1 << DATA_BITS); ++data) { + int fullId = (id << DATA_BITS) | data; + Block blockState; + try { + blockState = (Block) constructor.newInstance(data); + if (blockState.getDamage() != data) { + blockState = new BlockUnknown(id, data); + } + } catch (Exception e) { + Server.getInstance().getLogger().error("Error while registering " + c.getName(), e); + blockState = new BlockUnknown(id, data); + } + fullList[fullId] = blockState; } hasMeta[id] = true; } catch (NoSuchMethodException ignore) { - for (int data = 0; data < 16; ++data) { - fullList[(id << 4) | data] = block; + for (int data = 0; data < DATA_SIZE; ++data) { + int fullId = (id << DATA_BITS) | data; + fullList[fullId] = block; } } } catch (Exception e) { - Server.getInstance().getLogger().error("Error while registering " + c.getName(), e); - for (int data = 0; data < 16; ++data) { - fullList[(id << 4) | data] = new BlockUnknown(id, data); - } - return; + throw new RuntimeException("Error while registering " + c.getName(), e); } solid[id] = block.isSolid(); @@ -338,7 +125,11 @@ public static void init() { } else { lightFilter[id] = 1; } - } else { + } else if (block instanceof BlockSlime) { + lightFilter[id] = 1; + } else if (id == CAULDRON_BLOCK) { + lightFilter[id] = 3; + }else { lightFilter[id] = 15; } } else { @@ -346,56 +137,147 @@ public static void init() { } } else { lightFilter[id] = 1; - for (int data = 0; data < 16; ++data) { - fullList[(id << 4) | data] = new BlockUnknown(id, data); + for (int data = 0; data < DATA_SIZE; ++data) { + fullList[(id << DATA_BITS) | data] = new BlockUnknown(id, data); } } } } } + public static Block get(MaterialType type) { + return get(type, 0); + } + + public static Block get(MaterialType type, Integer meta) { + if (!(type instanceof BlockType)) { + throw new IllegalArgumentException("Expected BlockType, got " + type.getClass().getSimpleName()); + } + return get(type.getLegacyId(), meta); + } + public static Block get(int id) { - return fullList[id << 4].clone(); + if (id < 0) { + id = 255 - id; + } + + return fullList[id << DATA_BITS].clone(); } public static Block get(int id, Integer meta) { - if (meta != null) { - return fullList[(id << 4) + meta].clone(); - } else { - return fullList[id << 4].clone(); + if (id < 0) { + id = 255 - id; } + + int fullId = meta == null ? (id << DATA_BITS ) : ((id << DATA_BITS) | meta); + + return fullList[fullId].clone(); } public static Block get(int id, Integer meta, Position pos) { - Block block = fullList[(id << 4) | (meta == null ? 0 : meta)].clone(); + return get(id, meta, pos, LAYER_NORMAL); + } + + public static Block get(int id, Integer meta, Position pos, BlockLayer layer) { + if (id < 0) { + id = 255 - id; + } + + Block block; + if (meta != null && meta > DATA_SIZE) { + block = fullList[id << DATA_BITS].clone(); + block.setDamage(meta); + } else { + block = fullList[(id << DATA_BITS) | (meta == null ? 0 : meta)].clone(); + } + if (pos != null) { block.x = pos.x; block.y = pos.y; block.z = pos.z; block.level = pos.level; + block.layer = layer; } return block; } public static Block get(int id, int data) { - return fullList[(id << 4) + data].clone(); + if (id < 0) { + id = 255 - id; + } + + int fullId = (id << DATA_BITS ) | data; + + return fullList[fullId].clone(); } public static Block get(int fullId, Level level, int x, int y, int z) { + return get(fullId, level, x, y, z, LAYER_NORMAL); + } + + public static Block get(int fullId, Level level, int x, int y, int z, BlockLayer layer) { Block block = fullList[fullId].clone(); + block.x = x; block.y = y; block.z = z; block.level = level; + block.layer = layer; return block; } + public static int getBlockLight(int blockId) { + return light[blockId]; + } + + public static int getBlockLightFilter(int blockId) { + return lightFilter[blockId]; + } + + public static boolean isBlockSolidById(int blockId) { + return solid[blockId]; + } + + public static boolean isBlockTransparentById(int blockId) { + return transparent[blockId]; + } + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - return this.getLevel().setBlock(this, this, true, true); + return this.canPlaceOn(block.down(), target) && this.getLevel().setBlock(this, this, true, true); } - //http://minecraft.gamepedia.com/Breaking - public boolean canHarvestWithHand() { //used for calculating breaking time + public boolean canPlaceOn(Block floor, Position pos) { + return this.canBePlaced(); + } + + public boolean canHarvest(Item item) { + return this.canHarvestWithHand() || this.getToolTier() == 0 || this.getToolType() == ItemTool.TYPE_NONE || correctTool0(this.getToolType(), item, this.getId()) && item.getTier() >= this.getToolType(); + } + + public WaterloggingType getWaterloggingType() { + return WaterloggingType.NO_WATERLOGGING; + } + + public enum WaterloggingType { + /** + * Block is not waterloggable + */ + NO_WATERLOGGING, + /** + * If possible, water will be set to second layer when the block is placed into water + */ + WHEN_PLACED_IN_WATER, + /** + * Water will flow into the block and water will be set to second layer + */ + FLOW_INTO_BLOCK + } + + public final boolean canWaterloggingFlowInto() { + return this.canBeFlowedInto() || this.getWaterloggingType() == WaterloggingType.FLOW_INTO_BLOCK; + } + + public boolean canHarvestWithHand() { return true; } @@ -407,6 +289,10 @@ public int tickRate() { return 10; } + public boolean onBreak(Item item, Player player) { + return this.onBreak(item); + } + public boolean onBreak(Item item) { return this.getLevel().setBlock(this, Block.get(BlockID.AIR), true, true); } @@ -443,6 +329,10 @@ public int getToolType() { return ItemTool.TYPE_NONE; } + public int getToolTier() { + return 0; + } + public double getFrictionFactor() { return 0.6; } @@ -487,6 +377,10 @@ public boolean canBePushed() { return true; } + public boolean breakWhenPushed() { + return false; + } + public boolean hasComparatorInputOverride() { return false; } @@ -507,14 +401,30 @@ public BlockColor getColor() { public abstract int getId(); + public BlockType getBlockType() { + if (this.materialType == null) { + this.materialType = BlockTypes.getFromLegacy(this.getId()); + } + return this.materialType; + } + /** * The full id is a combination of the id and data. * @return full id */ public int getFullId() { - return (getId() << 4); + return getId() << DATA_BITS; + } + + public int getItemId() { + int id = this.getId(); + if (id > 255) { + return 255 - id; + } + return id; } + public void addVelocityToEntity(Entity entity, Vector3 vector) { } @@ -524,7 +434,6 @@ public int getDamage() { } public void setDamage(int meta) { - // Do nothing } public final void setDamage(Integer meta) { @@ -539,13 +448,14 @@ final public void position(Position v) { } public Item[] getDrops(Item item) { - if (this.getId() < 0 || this.getId() > list.length) { //Unknown blocks + if (this.getId() < 0 || this.getId() > list.length) { return new Item[0]; - } else { - return new Item[]{ - this.toItem() - }; } + + if (this.canHarvestWithHand() || this.canHarvest(item)) { + return new Item[]{this.toItem()}; + } + return new Item[0]; } private static double toolBreakTimeBonus0(int toolType, int toolTier, int blockId) { @@ -596,7 +506,20 @@ private static int toolType0(Item item) { return ItemTool.TYPE_NONE; } - private static boolean correctTool0(int blockToolType, Item item) { + private static boolean correctTool0(int blockToolType, Item item, int blockId) { + if (item.isShears() && (blockId == COBWEB || blockId == LEAVES || blockId == LEAVES2)) { + return true; + } + + if ((blockId == LEAVES && item.isHoe()) || + (blockId == LEAVES2 && item.isHoe())) { + return (blockToolType == ItemTool.TYPE_SHEARS && item.isHoe()); + } + + return correctTool(blockToolType, item); + } + + private static boolean correctTool(int blockToolType, Item item) { return (blockToolType == ItemTool.TYPE_SWORD && item.isSword()) || (blockToolType == ItemTool.TYPE_SHOVEL && item.isShovel()) || (blockToolType == ItemTool.TYPE_PICKAXE && item.isPickaxe()) || @@ -630,7 +553,7 @@ public double getBreakTime(Item item, Player player) { } int blockId = getId(); - boolean correctTool = correctTool0(getToolType(), item) + boolean correctTool = correctTool0(getToolType(), item, blockId) || item.isShears() && (blockId == COBWEB || blockId == LEAVES || blockId == LEAVES2); boolean canHarvestWithHand = canHarvestWithHand(); int itemToolType = toolType0(item); @@ -648,9 +571,9 @@ public double getBreakTime(Item item, Player player) { } /** - * @deprecated This function is lack of Player class and is not accurate enough, use #getBreakTime(Item, Player) - * @param item item used - * @return break time + * Deprecated: This function lacks the Player and is not accurate enough, use getBreakTime(Item, Player) instead + * @param item item used to break the block + * @return break time in seconds */ @Deprecated public double getBreakTime(Item item) { @@ -663,9 +586,8 @@ public double getBreakTime(Item item) { (this.getToolType() == ItemTool.TYPE_AXE && item.isAxe()) || (this.getToolType() == ItemTool.TYPE_SHOVEL && item.isShovel()) || (this.getToolType() == ItemTool.TYPE_HOE && item.isHoe()) - ) { - int tier = item.getTier(); - switch (tier) { + ) { + switch (item.getTier()) { case ItemTool.TIER_WOODEN: base /= 2; break; @@ -702,24 +624,23 @@ public boolean canBeBrokenWith(Item item) { } public Block getSide(BlockFace face) { - if (this.isValid()) { - return this.getLevel().getBlock((int) x + face.getXOffset(), (int) y + face.getYOffset(), (int) z + face.getZOffset()); - } - return this.getSide(face, 1); + return this.getSide(this.layer, face, 1); } public Block getSide(BlockFace face, int step) { + return this.getSide(this.layer, face, step); + } + + public Block getSide(BlockLayer layer, BlockFace face) { + return this.getSide(layer, face, 1); + } + + public Block getSide(BlockLayer layer, BlockFace face, int step) { if (this.isValid()) { - if (step == 1) { - return this.getLevel().getBlock((int) x + face.getXOffset(), (int) y + face.getYOffset(), (int) z + face.getZOffset()); - } else { - return this.getLevel().getBlock((int) x + face.getXOffset() * step, (int) y + face.getYOffset() * step, (int) z + face.getZOffset() * step); - } + return this.getLevel().getBlock(super.getSide(face, step), layer, true); } - Block block = Block.get(Item.AIR, 0); - block.x = (int) x + face.getXOffset() * step; - block.y = (int) y + face.getYOffset() * step; - block.z = (int) z + face.getZOffset() * step; + Block block = Block.get(Item.AIR, 0, Position.fromObject(new Vector3(this.x, this.y, this.z).getSide(face, step))); + block.layer = layer; return block; } @@ -731,6 +652,10 @@ public Block up(int step) { return getSide(BlockFace.UP, step); } + public Block up(int step, BlockLayer layer) { + return this.getSide(layer, BlockFace.UP, step); + } + public Block down() { return down(1); } @@ -739,6 +664,10 @@ public Block down(int step) { return getSide(BlockFace.DOWN, step); } + public Block down(int step, BlockLayer layer) { + return this.getSide(layer, BlockFace.DOWN, step); + } + public Block north() { return north(1); } @@ -747,6 +676,10 @@ public Block north(int step) { return getSide(BlockFace.NORTH, step); } + public Block north(int step, BlockLayer layer) { + return this.getSide(layer, BlockFace.NORTH, step); + } + public Block south() { return south(1); } @@ -755,6 +688,10 @@ public Block south(int step) { return getSide(BlockFace.SOUTH, step); } + public Block south(int step, BlockLayer layer) { + return this.getSide(layer, BlockFace.SOUTH, step); + } + public Block east() { return east(1); } @@ -763,6 +700,10 @@ public Block east(int step) { return getSide(BlockFace.EAST, step); } + public Block east(int step, BlockLayer layer) { + return this.getSide(layer, BlockFace.EAST, step); + } + public Block west() { return west(1); } @@ -771,9 +712,13 @@ public Block west(int step) { return getSide(BlockFace.WEST, step); } + public Block west(int step, BlockLayer layer) { + return this.getSide(layer, BlockFace.WEST, step); + } + @Override public String toString() { - return "Block[" + this.getName() + "] (" + this.getId() + ":" + this.getDamage() + ")"; + return "Block[" + this.getName() + '|' + this.layer + "] (" + this.getId() + ':' + this.getDamage() + ')'; } public boolean collidesWithBB(AxisAlignedBB bb) { @@ -786,7 +731,6 @@ public boolean collidesWithBB(AxisAlignedBB bb, boolean collisionBB) { } public void onEntityCollide(Entity entity) { - } public AxisAlignedBB getBoundingBox() { @@ -801,6 +745,10 @@ protected AxisAlignedBB recalculateBoundingBox() { return this; } + protected AxisAlignedBB recalculateCollisionBoundingBox() { + return this.getBoundingBox(); + } + @Override public double getMinX() { return this.x; @@ -831,10 +779,6 @@ public double getMaxZ() { return this.z + 1; } - protected AxisAlignedBB recalculateCollisionBoundingBox() { - return getBoundingBox(); - } - public MovingObjectPosition calculateIntercept(Vector3 pos1, Vector3 pos2) { AxisAlignedBB bb = this.getBoundingBox(); if (bb == null) { @@ -967,7 +911,7 @@ public boolean isPowerSource() { } public String getLocationHash() { - return this.getFloorX() + ":" + this.getFloorY() + ":" + this.getFloorZ(); + return this.getFloorX() + ":" + this.getFloorY() + ':' + this.getFloorZ(); } public int getDropExp() { @@ -993,4 +937,93 @@ public Item toItem() { public boolean canSilkTouch() { return false; } + + public void setLayer(BlockLayer layer) { + this.layer = layer; + } + + public BlockLayer getLayer() { + return this.layer; + } + + protected static boolean canConnectToFullSolid(Block down) { + if (down.isTransparent()) { + switch (down.getId()) { + case BEACON: + case ICE: + case GLASS: + case STAINED_GLASS: + case BARRIER: + case GLOWSTONE: + case SEA_LANTERN: + case MANGROVE_ROOTS: + case MUDDY_MANGROVE_ROOTS: + return true; + } + return false; + } + return true; + } + + protected static boolean canStayOnFullSolid(Block down) { + if (canConnectToFullSolid(down)) { + return true; + } + switch (down.getId()) { + case SCAFFOLDING: + case HOPPER_BLOCK: + return true; + } + if (down instanceof BlockSlab) { + return ((BlockSlab) down).hasTopBit(); + } + return down instanceof BlockTrapdoor && ((BlockTrapdoor) down).isTop() && !((BlockTrapdoor) down).isOpen(); + } + + protected static boolean canStayOnFullNonSolid(Block down) { + if (canStayOnFullSolid(down)) { + return true; + } + switch (down.getId()) { + case COMPOSTER: + case CAULDRON_BLOCK: + case LAVA_CAULDRON: + return true; + } + return false; + } + + protected boolean isNarrowSurface() { + return this instanceof BlockGlassPane || this instanceof BlockFence || this instanceof BlockWall || this instanceof BlockChain || this instanceof BlockIronBars; + } + + public boolean alwaysDropsOnExplosion() { + return false; + } + + /** + * Returns true for WATER and STILL_WATER, false for others + */ + public static boolean isWater(int id) { + return id == WATER || id == STILL_WATER; + } + + public Block setUpdatePos(Vector3 pos) { + return this; // Only need to save this for observers + } + + public PersistentDataContainer getPersistentDataContainer() { + if (!this.isValid()) { + throw new IllegalStateException("Block does not have valid level"); + } + return this.level.getPersistentDataContainer(this); + } + + @SuppressWarnings("unused") + public boolean hasPersistentDataContainer() { + if (!this.isValid()) { + throw new IllegalStateException("Block does not have valid level"); + } + return this.level.hasPersistentDataContainer(this); + } } diff --git a/src/main/java/cn/nukkit/block/BlockAcaciaSignStanding.java b/src/main/java/cn/nukkit/block/BlockAcaciaSignStanding.java new file mode 100644 index 00000000000..da53929096d --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockAcaciaSignStanding.java @@ -0,0 +1,45 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; + +public class BlockAcaciaSignStanding extends BlockSignPost { + + public BlockAcaciaSignStanding() { + this(0); + } + + public BlockAcaciaSignStanding(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Acacia Sign Post"; + } + + @Override + public int getId() { + return ACACIA_STANDING_SIGN; + } + + @Override + public Item toItem() { + return Item.get(ItemID.ACACIA_SIGN); + } + + @Override + protected int getPostId() { + return ACACIA_STANDING_SIGN; + } + + @Override + protected int getWallId() { + return ACACIA_WALL_SIGN; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockAcaciaWallSign.java b/src/main/java/cn/nukkit/block/BlockAcaciaWallSign.java new file mode 100644 index 00000000000..05c1946614c --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockAcaciaWallSign.java @@ -0,0 +1,40 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; + +public class BlockAcaciaWallSign extends BlockWallSign { + + public BlockAcaciaWallSign() { + this(0); + } + + public BlockAcaciaWallSign(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Acacia Wall Sign"; + } + + @Override + public int getId() { + return ACACIA_WALL_SIGN; + } + + @Override + public Item toItem() { + return Item.get(ItemID.ACACIA_SIGN); + } + + @Override + protected int getPostId() { + return ACACIA_STANDING_SIGN; + } + + @Override + protected int getWallId() { + return ACACIA_WALL_SIGN; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockAir.java b/src/main/java/cn/nukkit/block/BlockAir.java index 1fe3b4167ec..f19ca3032d5 100644 --- a/src/main/java/cn/nukkit/block/BlockAir.java +++ b/src/main/java/cn/nukkit/block/BlockAir.java @@ -5,13 +5,11 @@ import cn.nukkit.utils.BlockColor; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockAir extends BlockTransparent { - public BlockAir() {} - @Override public int getId() { return AIR; diff --git a/src/main/java/cn/nukkit/block/BlockAllow.java b/src/main/java/cn/nukkit/block/BlockAllow.java new file mode 100644 index 00000000000..c3e71784320 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockAllow.java @@ -0,0 +1,41 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; + +public class BlockAllow extends BlockSolid { + + @Override + public int getId() { + return ALLOW; + } + + @Override + public double getHardness() { + return -1; + } + + @Override + public double getResistance() { + return 18000000; + } + + @Override + public String getName() { + return "Allow"; + } + + @Override + public boolean isBreakable(Item item) { + return false; + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockAmethyst.java b/src/main/java/cn/nukkit/block/BlockAmethyst.java new file mode 100644 index 00000000000..add8cd19147 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockAmethyst.java @@ -0,0 +1,46 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; + +public class BlockAmethyst extends BlockSolid { + + public BlockAmethyst() { + // Does nothing + } + + @Override + public String getName() { + return "Amethyst Block"; + } + + @Override + public int getId() { + return AMETHYST_BLOCK; + } + + @Override + public double getHardness() { + return 1.5; + } + + @Override + public double getResistance() { + return 1.5; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + // TODO: + /*@Override + public boolean isLavaResistant() { + return true; + }*/ +} diff --git a/src/main/java/cn/nukkit/block/BlockAmethystBud.java b/src/main/java/cn/nukkit/block/BlockAmethystBud.java new file mode 100644 index 00000000000..3bac780bdb4 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockAmethystBud.java @@ -0,0 +1,113 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.math.AxisAlignedBB; +import cn.nukkit.math.BlockFace; +import cn.nukkit.math.SimpleAxisAlignedBB; +import cn.nukkit.utils.Faceable; + +public abstract class BlockAmethystBud extends BlockTransparentMeta implements Faceable { + + public BlockAmethystBud() { + this(0); + } + + public BlockAmethystBud(int meta) { + super(meta); + } + + protected abstract String getSizeName(); + + @Override + public String getName() { + return this.getSizeName() + " Amethyst Bud"; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (Block.canConnectToFullSolid(this.getSide(face.getOpposite()))) { + this.setDamage(face.getIndex()); + return this.getLevel().setBlock(this, this, true, true); + } + return false; + } + + @Override + public BlockFace getBlockFace() { + return BlockFace.fromIndex(this.getDamage()); + } + + public void setBlockFace(BlockFace face) { + this.setDamage(face.getIndex()); + } + + @Override + protected AxisAlignedBB recalculateBoundingBox() { + switch (this.getBlockFace()) { + case UP: + return boundingBox(this.getCrystalOffset(), 0, this.getCrystalOffset(), 16 - this.getCrystalOffset(), + this.getCrystalHeight(), 16 - this.getCrystalOffset()); + case DOWN: + return boundingBox(this.getCrystalOffset(), 16 - this.getCrystalHeight(), this.getCrystalOffset(), + 16 - this.getCrystalOffset(), 16, 16 - this.getCrystalOffset()); + case NORTH: + return boundingBox(this.getCrystalOffset(), this.getCrystalOffset(), 16 - this.getCrystalHeight(), + 16 - this.getCrystalOffset(), 16 - this.getCrystalOffset(), 16); + case SOUTH: + return boundingBox(this.getCrystalOffset(), this.getCrystalOffset(), 0, + 16 - this.getCrystalOffset(), 16 - this.getCrystalOffset(), this.getCrystalHeight()); + case EAST: + return boundingBox(0, this.getCrystalOffset(), this.getCrystalOffset(), + this.getCrystalHeight(), 16 - this.getCrystalOffset(), 16 - this.getCrystalOffset()); + case WEST: + return boundingBox(16 - this.getCrystalHeight(), this.getCrystalOffset(), this.getCrystalHeight(), + 16, 16 - this.getCrystalOffset(), 16 - this.getCrystalOffset()); + } + return super.recalculateBoundingBox(); + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public double getHardness() { + return 1.5; + } + + @Override + public double getResistance() { + return 1.5; + } + + @Override + public boolean breakWhenPushed() { + return true; + } + + protected abstract int getCrystalHeight(); + protected abstract int getCrystalOffset(); + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId()), 0, 1); + } + + protected static AxisAlignedBB boundingBox(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + return new SimpleAxisAlignedBB(minX / 16.0D, minY / 16.0D, minZ / 16.0D, maxX / 16.0D, maxY / 16.0D, maxZ / 16.0D); + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public Item[] getDrops(Item item) { + return new Item[0]; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockAmethystBudLarge.java b/src/main/java/cn/nukkit/block/BlockAmethystBudLarge.java new file mode 100644 index 00000000000..ef9f7fea2e6 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockAmethystBudLarge.java @@ -0,0 +1,37 @@ +package cn.nukkit.block; + +public class BlockAmethystBudLarge extends BlockAmethystBud { + + public BlockAmethystBudLarge() { + this(0); + } + + public BlockAmethystBudLarge(int meta) { + super(meta); + } + + @Override + public int getId() { + return LARGE_AMETHYST_BUD; + } + + @Override + protected String getSizeName() { + return "Large"; + } + + @Override + protected int getCrystalHeight() { + return 5; + } + + @Override + protected int getCrystalOffset() { + return 3; + } + + @Override + public int getLightLevel() { + return 4; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockAmethystBudMedium.java b/src/main/java/cn/nukkit/block/BlockAmethystBudMedium.java new file mode 100644 index 00000000000..5afdae1b0c5 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockAmethystBudMedium.java @@ -0,0 +1,37 @@ +package cn.nukkit.block; + +public class BlockAmethystBudMedium extends BlockAmethystBud { + + public BlockAmethystBudMedium() { + this(0); + } + + public BlockAmethystBudMedium(int meta) { + super(meta); + } + + @Override + public int getId() { + return MEDIUM_AMETHYST_BUD; + } + + @Override + protected String getSizeName() { + return "Medium"; + } + + @Override + protected int getCrystalHeight() { + return 4; + } + + @Override + protected int getCrystalOffset() { + return 3; + } + + @Override + public int getLightLevel() { + return 2; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockAmethystBudSmall.java b/src/main/java/cn/nukkit/block/BlockAmethystBudSmall.java new file mode 100644 index 00000000000..434e4d9a8e3 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockAmethystBudSmall.java @@ -0,0 +1,37 @@ +package cn.nukkit.block; + +public class BlockAmethystBudSmall extends BlockAmethystBud { + + public BlockAmethystBudSmall() { + this(0); + } + + public BlockAmethystBudSmall(int meta) { + super(meta); + } + + @Override + public int getId() { + return SMALL_AMETHYST_BUD; + } + + @Override + protected String getSizeName() { + return "Small"; + } + + @Override + protected int getCrystalHeight() { + return 3; + } + + @Override + protected int getCrystalOffset() { + return 4; + } + + @Override + public int getLightLevel() { + return 1; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockAmethystCluster.java b/src/main/java/cn/nukkit/block/BlockAmethystCluster.java new file mode 100644 index 00000000000..6a0c27a1757 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockAmethystCluster.java @@ -0,0 +1,80 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.math.NukkitMath; + +import java.util.concurrent.ThreadLocalRandom; + +public class BlockAmethystCluster extends BlockAmethystBud { + + public BlockAmethystCluster() { + this(0); + } + + public BlockAmethystCluster(int meta) { + super(meta); + } + + @Override + public int getId() { + return AMETHYST_CLUSTER; + } + + @Override + protected int getCrystalHeight() { + return 7; + } + + @Override + protected int getCrystalOffset() { + return 7; + } + + @Override + protected String getSizeName() { + return "Cluster"; + } + + @Override + public String getName() { + return "Amethyst Cluster"; + } + + @Override + public int getLightLevel() { + return 5; + } + + @Override + public Item[] getDrops(Item item) { + if (!item.isPickaxe()) { + return new Item[]{Item.get(ItemID.AMETHYST_SHARD, 0, 2)}; + } + + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; + } + + int amount = 4; + int fortuneLevel = NukkitMath.clamp(item.getEnchantmentLevel(Enchantment.ID_FORTUNE_DIGGING), 0, 3); + if (fortuneLevel > 0) { + int rand = ThreadLocalRandom.current().nextInt(100); + if (fortuneLevel == 1 && rand <= 33) { + amount = 8; + } else if (fortuneLevel == 2 && rand <= 25) { + amount = rand <= 12 ? 8 : 12; + } else if (fortuneLevel == 3 && rand <= 20) { + if (rand <= 6) { + amount = 8; + } else if (rand <= 13) { + amount = 12; + } else { + amount = 16; + } + } + } + return new Item[]{Item.get(ItemID.AMETHYST_SHARD, 0, amount)}; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockAncientDebris.java b/src/main/java/cn/nukkit/block/BlockAncientDebris.java new file mode 100644 index 00000000000..990e3ee1bd6 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockAncientDebris.java @@ -0,0 +1,46 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockAncientDebris extends BlockSolid { + + public BlockAncientDebris() { + super(); + } + + @Override + public int getId() { + return ANCIENT_DEBRIS; + } + + @Override + public String getName() { + return "Ancient Debris"; + } + + @Override + public double getResistance() { + return 1200; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public double getHardness() { + return 30; + } + + @Override + public BlockColor getColor() { + return BlockColor.BLACK_BLOCK_COLOR; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockAnvil.java b/src/main/java/cn/nukkit/block/BlockAnvil.java index 6694f517c13..466a86065bd 100644 --- a/src/main/java/cn/nukkit/block/BlockAnvil.java +++ b/src/main/java/cn/nukkit/block/BlockAnvil.java @@ -6,15 +6,18 @@ import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemTool; import cn.nukkit.math.BlockFace; +import cn.nukkit.network.protocol.LevelEventPacket; import cn.nukkit.utils.BlockColor; import cn.nukkit.utils.Faceable; /** * Created by Pub4Game on 27.12.2015. */ -public class BlockAnvil extends BlockFallable implements Faceable { +public class BlockAnvil extends BlockFallableMeta implements Faceable { - private static final String[] NAMES = new String[]{ + private static final int[] FACES = {1, 2, 3, 0}; + + private static final String[] NAMES = { "Anvil", "Anvil", "Anvil", @@ -29,29 +32,17 @@ public class BlockAnvil extends BlockFallable implements Faceable { "Very Damaged Anvil" }; - private int meta; - public BlockAnvil() { this(0); } public BlockAnvil(int meta) { - this.meta = meta; + super(meta); } @Override public int getFullId() { - return (getId() << 4) + getDamage(); - } - - @Override - public final int getDamage() { - return this.meta; - } - - @Override - public final void setDamage(int meta) { - this.meta = meta; + return (getId() << DATA_BITS) + getDamage(); } @Override @@ -91,19 +82,16 @@ public String getName() { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - if (!target.isTransparent() || target.getId() == Block.SNOW_LAYER) { - int damage = this.getDamage(); - int[] faces = {1, 2, 3, 0}; - this.setDamage(faces[player != null ? player.getDirection().getHorizontalIndex() : 0]); - if (damage >= 4 && damage <= 7) { - this.setDamage(this.getDamage() | 0x04); - } else if (damage >= 8 && damage <= 11) { - this.setDamage(this.getDamage() | 0x08); - } - this.getLevel().setBlock(block, this, true); - return true; + int damage = this.getDamage(); + this.setDamage(FACES[player != null ? player.getDirection().getHorizontalIndex() : 0]); + if (damage >= 4 && damage <= 7) { + this.setDamage(this.getDamage() | 0x04); + } else if (damage >= 8 && damage <= 11) { + this.setDamage(this.getDamage() | 0x08); } - return false; + this.getLevel().setBlock(this, this, true, true); + this.getLevel().addLevelEvent(this, LevelEventPacket.EVENT_SOUND_ANVIL_FALL); + return true; } @Override @@ -128,7 +116,7 @@ public Item toItem() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ this.toItem() }; @@ -175,4 +163,9 @@ public double getMaxZ() { public boolean isSolid() { return false; } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } } diff --git a/src/main/java/cn/nukkit/block/BlockAzalea.java b/src/main/java/cn/nukkit/block/BlockAzalea.java new file mode 100644 index 00000000000..396e7c5f88d --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockAzalea.java @@ -0,0 +1,100 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; +import cn.nukkit.level.Position; +import cn.nukkit.math.AxisAlignedBB; + +public class BlockAzalea extends BlockTransparent { + + public BlockAzalea() { + // Does nothing + } + + @Override + public String getName() { + return "Azalea"; + } + + @Override + public int getId() { + return AZALEA; + } + + @Override + public boolean canPlaceOn(Block floor, Position pos) { + // Azaleas can be placed on grass blocks, dirt, coarse dirt, rooted dirt, podzol, moss blocks, farmland, mud, muddy mangrove roots and clay. + switch (floor.getId()) { + case GRASS: + case DIRT: + case ROOTED_DIRT: + case PODZOL: + case MOSS_BLOCK: + case FARMLAND: + case MUD: + case CLAY_BLOCK: + return true; + } + return false; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_NONE; + } + + @Override + public boolean canHarvestWithHand() { + return true; + } + + @Override + public boolean canBeClimbed() { + return true; + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + public boolean canBeFlowedInto() { + return true; + } + + @Override + public boolean canPassThrough() { + return true; + } + + @Override + public double getHardness() { + return 0; + } + + @Override + public double getResistance() { + return 0; + } + + @Override + public boolean isSolid() { + return false; + } + + @Override + protected AxisAlignedBB recalculateBoundingBox() { + return null; + } + + @Override + public boolean breakWhenPushed() { + return true; + } + + @Override + public Item[] getDrops(Item item) { + return new Item[0]; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockAzaleaFlowering.java b/src/main/java/cn/nukkit/block/BlockAzaleaFlowering.java new file mode 100644 index 00000000000..abc85214985 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockAzaleaFlowering.java @@ -0,0 +1,17 @@ +package cn.nukkit.block; + +public class BlockAzaleaFlowering extends BlockAzalea { + + public BlockAzaleaFlowering() { + } + + @Override + public String getName() { + return "Flowering Azalea"; + } + + @Override + public int getId() { + return FLOWERING_AZALEA; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockAzaleaLeaves.java b/src/main/java/cn/nukkit/block/BlockAzaleaLeaves.java new file mode 100644 index 00000000000..0f8769d9d0b --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockAzaleaLeaves.java @@ -0,0 +1,93 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.math.BlockFace; + +import java.util.concurrent.ThreadLocalRandom; + +public class BlockAzaleaLeaves extends BlockLeaves { + + public BlockAzaleaLeaves() { + this(0); + } + + public BlockAzaleaLeaves(int meta) { + super(meta); + } + + @Override + public int getId() { + return AZALEA_LEAVES; + } + + @Override + public String getName() { + return "Azalea Leaves"; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + this.setPersistent(true); + return super.place(item, block, target, face, fx, fy, fz, player); + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public Item[] getDrops(Item item) { + if (item.isShears() || item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{ this.toItem() }; + } + + ThreadLocalRandom random = ThreadLocalRandom.current(); + if (random.nextInt(20) != 0) { + return new Item[0]; + } + + int chance = random.nextInt(4); + if (chance == 0 || chance == 1) { + return new Item[]{ Item.get(random.nextBoolean() ? Item.AZALEA : Item.FLOWERING_AZALEA, 0, 1) }; + } else if (chance == 2) { + return new Item[]{ Item.get(Item.SAPLING, random.nextInt(0, 6), 1) }; + } else { + return new Item[]{ Item.get(Item.STICK, 0, random.nextInt(1, 2)) }; + } + } + + @Override + protected void setOnDecayDamage() { + this.setCheckDecay(false); + } + + @Override + protected boolean canDropApple() { + return false; + } + + @Override + public boolean isPersistent() { + return (this.getDamage() & 2) >>> 1 == 1; + } + + @Override + public void setPersistent(boolean persistent) { + int value = (persistent ? 1 : 0) << 1; + this.setDamage(this.getDamage() & ~1 | (value & 2)); + } + + @Override + public boolean isCheckDecay() { + return (this.getDamage() & 1) == 1; + } + + @Override + public void setCheckDecay(boolean updateBit) { + this.setDamage(this.getDamage() & ~1 | ((updateBit ? 1 : 0) & 1)); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockAzaleaLeavesFlowered.java b/src/main/java/cn/nukkit/block/BlockAzaleaLeavesFlowered.java new file mode 100644 index 00000000000..b66f01f7a5d --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockAzaleaLeavesFlowered.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockAzaleaLeavesFlowered extends BlockAzaleaLeaves { + + public BlockAzaleaLeavesFlowered() { + this(0); + } + + public BlockAzaleaLeavesFlowered(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Flowering Azalea Leaves"; + } + + @Override + public int getId() { + return AZALEA_LEAVES_FLOWERED; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBamboo.java b/src/main/java/cn/nukkit/block/BlockBamboo.java new file mode 100644 index 00000000000..92de7f62e45 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBamboo.java @@ -0,0 +1,320 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.event.block.BlockGrowEvent; +import cn.nukkit.item.*; +import cn.nukkit.level.Level; +import cn.nukkit.level.particle.BoneMealParticle; +import cn.nukkit.math.BlockFace; +import cn.nukkit.math.MathHelper; +import cn.nukkit.network.protocol.AnimatePacket; +import cn.nukkit.utils.BlockColor; + +import java.util.concurrent.ThreadLocalRandom; + +public class BlockBamboo extends BlockTransparentMeta { + + public static final int LEAF_SIZE_NONE = 0; + public static final int LEAF_SIZE_SMALL = 1; + public static final int LEAF_SIZE_LARGE = 2; + + public BlockBamboo() { + this(0); + } + + public BlockBamboo(int meta) { + super(meta); + } + + @Override + public int getId() { + return BAMBOO; + } + + @Override + public String getName() { + return "Bamboo"; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + if (this.isSupportInvalid()) { + this.level.scheduleUpdate(this, 0); + } + return type; + } else if (type == Level.BLOCK_UPDATE_SCHEDULED) { + this.level.useBreakOn(this, null, null, true); + } else if (type == Level.BLOCK_UPDATE_RANDOM) { + Block up; + int time = level.getTime() % Level.TIME_FULL; + boolean canGrow = time < 13184 || time > 22800; + if (this.getAge() == 0 && (up = this.up()).getId() == AIR && canGrow/*this.level.getFullLight(up) >= BlockCrops.MINIMUM_LIGHT_LEVEL*/ && ThreadLocalRandom.current().nextInt(3) == 0) { + this.grow(up); + } + return type; + } + return 0; + } + + public boolean grow(Block up) { + BlockBamboo newState = (BlockBamboo) Block.get(Block.BAMBOO); + if (this.isThick()) { + newState.setThick(true); + newState.setLeafSize(LEAF_SIZE_LARGE); + } else { + newState.setLeafSize(LEAF_SIZE_SMALL); + } + BlockGrowEvent blockGrowEvent = new BlockGrowEvent(up, newState); + level.getServer().getPluginManager().callEvent(blockGrowEvent); + if (!blockGrowEvent.isCancelled()) { + Block newState1 = blockGrowEvent.getNewState(); + newState1.x = x; + newState1.y = up.y; + newState1.z = z; + newState1.level = level; + newState1.place(this.toItem(), up, this, BlockFace.DOWN, 0.5, 0.5, 0.5, null); + return true; + } + return false; + } + + private int countHeight() { + int count = 0; + Block opt; + Block down = this; + while ((opt = down.down()).getId() == BAMBOO) { + down = opt; + if (++count >= 16) { + break; + } + } + return count; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + Block down = this.down(); + int downId = down.getId(); + if (downId != BAMBOO && downId != BAMBOO_SAPLING) { + BlockBambooSapling sampling = (BlockBambooSapling) Block.get(Block.BAMBOO_SAPLING); + sampling.x = x; + sampling.y = y; + sampling.z = z; + sampling.level = level; + return sampling.place(item, block, target, face, fx, fy, fz, player); + } + + boolean canGrow = true; + + if (downId == BAMBOO_SAPLING) { + if (player != null) { + AnimatePacket animatePacket = new AnimatePacket(); + animatePacket.action = AnimatePacket.Action.SWING_ARM; + animatePacket.eid = player.getId(); + this.getLevel().addChunkPacket(player.getChunkX(), player.getChunkZ(), animatePacket); + } + this.setLeafSize(LEAF_SIZE_SMALL); + } if (down instanceof BlockBamboo) { + BlockBamboo bambooDown = (BlockBamboo) down; + canGrow = bambooDown.getAge() == 0; + boolean thick = bambooDown.isThick(); + if (!thick) { + boolean setThick = true; + for (int i = 2; i <= 3; i++) { + if (this.getSide(BlockFace.DOWN, i).getId() != BAMBOO) { + setThick = false; + } + } + if (setThick) { + this.setThick(true); + this.setLeafSize(LEAF_SIZE_LARGE); + bambooDown.setLeafSize(LEAF_SIZE_SMALL); + bambooDown.setThick(true); + bambooDown.setAge(1); + this.level.setBlock(bambooDown, bambooDown, false, true); + while ((down = down.down()) instanceof BlockBamboo) { + bambooDown = (BlockBamboo) down; + bambooDown.setThick(true); + bambooDown.setLeafSize(LEAF_SIZE_NONE); + bambooDown.setAge(1); + this.level.setBlock(bambooDown, bambooDown, false, true); + } + } else { + this.setLeafSize(LEAF_SIZE_SMALL); + bambooDown.setAge(1); + this.level.setBlock(bambooDown, bambooDown, false, true); + } + } else { + this.setThick(true); + this.setLeafSize(LEAF_SIZE_LARGE); + this.setAge(0); + bambooDown.setLeafSize(LEAF_SIZE_LARGE); + bambooDown.setAge(1); + this.level.setBlock(bambooDown, bambooDown, false, true); + down = bambooDown.down(); + if (down instanceof BlockBamboo) { + bambooDown = (BlockBamboo) down; + bambooDown.setLeafSize(LEAF_SIZE_SMALL); + bambooDown.setAge(1); + this.level.setBlock(bambooDown, bambooDown, false, true); + down = bambooDown.down(); + if (down instanceof BlockBamboo) { + bambooDown = (BlockBamboo) down; + bambooDown.setLeafSize(LEAF_SIZE_NONE); + bambooDown.setAge(1); + this.level.setBlock(bambooDown, bambooDown, false, true); + } + } + } + } else if (this.isSupportInvalid()) { + return false; + } + + int height = canGrow? this.countHeight() : 0; + if (!canGrow || height >= 15 || height >= 11 && ThreadLocalRandom.current().nextFloat() < 0.25F) { + this.setAge(1); + } + + this.level.setBlock(this, this, false, true); + return true; + } + + @Override + public boolean onBreak(Item item) { + Block down = this.down(); + if (down instanceof BlockBamboo) { + BlockBamboo bambooDown = (BlockBamboo) down; + int height = bambooDown.countHeight(); + if (height < 15 && (height < 11 || !(ThreadLocalRandom.current().nextFloat() < 0.25F))) { + bambooDown.setAge(0); + this.level.setBlock(bambooDown, bambooDown, false, true); + } + } + return super.onBreak(item); + } + + @Override + public boolean canPassThrough() { + return true; + } + + private boolean isSupportInvalid() { + int downId = this.down().getId(); + return downId != BAMBOO && downId != DIRT && downId != GRASS && downId != SAND && downId != GRAVEL && downId != PODZOL && downId != BAMBOO_SAPLING; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public BlockColor getColor() { + return BlockColor.FOLIAGE_BLOCK_COLOR; + } + + @Override + public double getHardness() { + return 1; + } + + @Override + public double getResistance() { + return 2; + } + + public boolean isThick() { + return (this.getDamage() & 0x1) == 0x1; + } + + public void setThick(boolean thick) { + this.setDamage(this.getDamage() & (15 ^ 0x1) | (thick? 0x1 : 0x0)); + } + + @Override + public int getToolType() { + return ItemTool.TYPE_AXE; + } + + public int getLeafSize() { + return (this.getDamage() >> 1) & 0x3; + } + + public void setLeafSize(int leafSize) { + leafSize = MathHelper.clamp(leafSize, LEAF_SIZE_NONE, LEAF_SIZE_LARGE) & 0b11; + this.setDamage(this.getDamage() & (15 ^ 0b110) | (leafSize << 1)); + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (item.getId() == ItemID.DYE && item.getDamage() == ItemDye.BONE_MEAL) { + int top = (int) y; + int count = 1; + + for (int i = 1; i <= 16; i++) { + int id = this.level.getBlockIdAt(this.getFloorX(), this.getFloorY() - i, this.getFloorZ()); + if (id == BAMBOO) { + count++; + } else { + break; + } + } + + for (int i = 1; i <= 16; i++) { + int id = this.level.getBlockIdAt(this.getFloorX(), this.getFloorY() + i, this.getFloorZ()); + if (id == BAMBOO) { + top++; + count++; + } else { + break; + } + } + + if (count >= 15) { + return false; + } + + boolean success = false; + + Block block = this.up(top - (int)y + 1); + if (block.getId() == BlockID.AIR) { + success = this.grow(block); + } + + if (success) { + if (player != null && !player.isCreative()) { + item.count--; + } + level.addParticle(new BoneMealParticle(this)); + } + + return true; + } + return false; + } + + public int getAge() { + return (this.getDamage() & 0x8) >> 3; + } + + public void setAge(int age) { + age = MathHelper.clamp(age, 0, 1) << 3; + this.setDamage(this.getDamage() & (15 ^ 0b1000) | age); + } + + @Override + public boolean isSolid() { + return false; + } + + @Override + public boolean breakWhenPushed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBambooSapling.java b/src/main/java/cn/nukkit/block/BlockBambooSapling.java new file mode 100644 index 00000000000..65925ee3c21 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBambooSapling.java @@ -0,0 +1,174 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.event.block.BlockGrowEvent; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemDye; +import cn.nukkit.item.ItemID; +import cn.nukkit.level.Level; +import cn.nukkit.level.particle.BoneMealParticle; +import cn.nukkit.math.BlockFace; +import cn.nukkit.math.MathHelper; +import cn.nukkit.utils.BlockColor; + +import java.util.concurrent.ThreadLocalRandom; + +public class BlockBambooSapling extends BlockFlowable { + + public BlockBambooSapling() { + this(0); + } + + public BlockBambooSapling(int meta) { + super(meta); + } + + @Override + public int getId() { + return BAMBOO_SAPLING; + } + + @Override + public String getName() { + return "Bamboo Sapling"; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + if (isSupportInvalid()) { + level.useBreakOn(this, null, null, true); + } else { + Block up = up(); + if (up.getId() == BAMBOO) { + BlockBamboo upperBamboo = (BlockBamboo) up; + BlockBamboo newState = (BlockBamboo) Block.get(Block.BAMBOO); + newState.setThick(upperBamboo.isThick()); + level.setBlock(this, newState, true, true); + } + } + return type; + } else if (type == Level.BLOCK_UPDATE_RANDOM) { + Block up; + int time = level.getTime() % Level.TIME_FULL; + boolean canGrow = time < 13184 || time > 22800; + if (getAge() == 0 && (up = this.up()).getId() == AIR && canGrow/*level.getFullLight(up) >= BlockCrops.MINIMUM_LIGHT_LEVEL*/ && ThreadLocalRandom.current().nextInt(3) == 0) { + BlockBamboo newState = (BlockBamboo) Block.get(Block.BAMBOO); + newState.setLeafSize(BlockBamboo.LEAF_SIZE_SMALL); + BlockGrowEvent blockGrowEvent = new BlockGrowEvent(up, newState); + level.getServer().getPluginManager().callEvent(blockGrowEvent); + if (!blockGrowEvent.isCancelled()) { + Block newState1 = blockGrowEvent.getNewState(); + newState1.y = up.y; + newState1.x = x; + newState1.z = z; + newState1.level = level; + newState1.place(toItem(), up, this, BlockFace.DOWN, 0.5, 0.5, 0.5, null); + } + } + return type; + } + return 0; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (isSupportInvalid()) { + return false; + } + + if (this.getLevelBlock() instanceof BlockLiquid) { + return false; + } + + this.level.setBlock(this, this, true, true); + return true; + } + + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (item.getId() == ItemID.DYE && item.getDamage() == ItemDye.BONE_MEAL) { + boolean success = false; + Block block = this.up(); + if (block.getId() == AIR) { + success = this.grow(block); + } + + if (success) { + if (player != null && (player.gamemode & 0x01) == 0) { + item.count--; + } + + this.level.addParticle(new BoneMealParticle(this)); + } + + return true; + } + return false; + } + + public boolean grow(Block up) { + BlockBamboo bamboo = (BlockBamboo) Block.get(Block.BAMBOO); + bamboo.x = x; + bamboo.y = y; + bamboo.z = z; + bamboo.level = level; + return bamboo.grow(up); + } + + private boolean isSupportInvalid() { + int downId = down().getId(); + return downId != DIRT && downId != GRASS && downId != SAND && downId != GRAVEL && downId != PODZOL; + } + + public int getAge() { + return getDamage() & 0x1; + } + + public void setAge(int age) { + age = MathHelper.clamp(age, 0, 1) & 0x1; + setDamage(getDamage() & (15 ^ 0x1) | age); + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(BAMBOO), 0); + } + + @Override + public double getMinX() { + return this.x + 0.125; + } + + @Override + public double getMinZ() { + return this.z + 0.125; + } + + @Override + public double getMaxX() { + return this.x + 0.875; + } + + @Override + public double getMaxY() { + return this.y + 0.875; + } + + @Override + public double getMaxZ() { + return this.z + 0.875; + } + + @Override + public BlockColor getColor() { + return BlockColor.FOLIAGE_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBanner.java b/src/main/java/cn/nukkit/block/BlockBanner.java index 2c4e293b72d..d870e12fdce 100644 --- a/src/main/java/cn/nukkit/block/BlockBanner.java +++ b/src/main/java/cn/nukkit/block/BlockBanner.java @@ -17,9 +17,6 @@ import cn.nukkit.utils.DyeColor; import cn.nukkit.utils.Faceable; -/** - * Created by PetteriM1 - */ public class BlockBanner extends BlockTransparentMeta implements Faceable { public BlockBanner() { @@ -56,7 +53,7 @@ public String getName() { } @Override - protected AxisAlignedBB recalculateBoundingBox() { + public AxisAlignedBB getBoundingBox() { return null; } @@ -71,29 +68,34 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl if (face == BlockFace.UP) { this.setDamage(NukkitMath.floorDouble(((player.yaw + 180) * 16 / 360) + 0.5) & 0x0f); this.getLevel().setBlock(block, this, true); + } else if (target.canBeReplaced()) { + this.setDamage(NukkitMath.floorDouble(((player.yaw + 180) * 16 / 360) + 0.5) & 0x0f); + this.getLevel().setBlock(target, this, true); } else { this.setDamage(face.getIndex()); - this.getLevel().setBlock(block, Block.get(BlockID.WALL_BANNER, this.getDamage()), true); + this.getLevel().setBlock(block, Block.get(WALL_BANNER, this.getDamage()), true); } CompoundTag nbt = BlockEntity.getDefaultCompound(this, BlockEntity.BANNER) .putInt("Base", item.getDamage() & 0xf); Tag type = item.getNamedTagEntry("Type"); + if (type instanceof IntTag) { nbt.put("Type", type); } + Tag patterns = item.getNamedTagEntry("Patterns"); if (patterns instanceof ListTag) { nbt.put("Patterns", patterns); } - BlockEntityBanner banner = (BlockEntityBanner) BlockEntity.createBlockEntity(BlockEntity.BANNER, this.getChunk(), nbt); - return banner != null; + BlockEntity.createBlockEntity(BlockEntity.BANNER, this.getChunk(), nbt); + return true; } return false; } - + @Override public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_NORMAL) { @@ -154,4 +156,14 @@ public DyeColor getDyeColor() { public boolean isSolid() { return false; } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockBarrel.java b/src/main/java/cn/nukkit/block/BlockBarrel.java new file mode 100644 index 00000000000..97bb9fe49f3 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBarrel.java @@ -0,0 +1,171 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.blockentity.BlockEntity; +import cn.nukkit.blockentity.BlockEntityBarrel; +import cn.nukkit.inventory.ContainerInventory; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.math.BlockFace; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.ListTag; +import cn.nukkit.nbt.tag.StringTag; +import cn.nukkit.nbt.tag.Tag; +import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.Faceable; + +import java.util.Map; + +public class BlockBarrel extends BlockSolidMeta implements Faceable { + + public BlockBarrel() { + this(0); + } + + public BlockBarrel(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Barrel"; + } + + @Override + public int getId() { + return BARREL; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (Math.abs(player.x - this.x) < 2 && Math.abs(player.z - this.z) < 2) { + double y = player.y + player.getEyeHeight(); + if (y - this.y > 2) { + this.setDamage(BlockFace.UP.getIndex()); + } else if (this.y - y > 0) { + this.setDamage(BlockFace.DOWN.getIndex()); + } else { + this.setDamage(player.getHorizontalFacing().getOpposite().getIndex()); + } + } else { + this.setDamage(player.getHorizontalFacing().getOpposite().getIndex()); + } + + this.level.setBlock(block, this, true, true); + + CompoundTag nbt = new CompoundTag("") + .putList(new ListTag<>("Items")) + .putString("id", BlockEntity.BARREL) + .putInt("x", (int) this.x) + .putInt("y", (int) this.y) + .putInt("z", (int) this.z); + + if (item.hasCustomName()) { + nbt.putString("CustomName", item.getCustomName()); + } + + if (item.hasCustomBlockData()) { + Map customData = item.getCustomBlockData().getTags(); + for (Map.Entry tag : customData.entrySet()) { + nbt.put(tag.getKey(), tag.getValue()); + } + } + + BlockEntity.createBlockEntity(BlockEntity.BARREL, this.getChunk(), nbt); + return true; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (player == null) { + return false; + } + + BlockEntity blockEntity = level.getBlockEntity(this); + if (!(blockEntity instanceof BlockEntityBarrel)) { + return false; + } + + BlockEntityBarrel barrel = (BlockEntityBarrel) blockEntity; + + if (barrel.namedTag.contains("Lock") && barrel.namedTag.get("Lock") instanceof StringTag) { + if (!barrel.namedTag.getString("Lock").equals(item.getCustomName())) { + return true; + } + } + + player.addWindow(barrel.getInventory()); + + return true; + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public double getHardness() { + return 2.5; + } + + @Override + public double getResistance() { + return 12.5; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_AXE; + } + + @Override + public BlockColor getColor() { + return BlockColor.WOOD_BLOCK_COLOR; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(BARREL)); + } + + @Override + public BlockFace getBlockFace() { + int index = getDamage() & 0x7; + return BlockFace.fromIndex(index); + } + + public void setBlockFace(BlockFace face) { + this.setDamage((this.getDamage() & 0x8) | (face.getIndex() & 0x7)); + } + + public boolean isOpen() { + return (this.getDamage() & 0x8) == 0x8; + } + + public void setOpen(boolean open) { + this.setDamage((this.getDamage() & 0x7) | (open? 0x8 : 0x0)); + } + + @Override + public boolean hasComparatorInputOverride() { + return true; + } + + @Override + public int getComparatorInputOverride() { + BlockEntity blockEntity = this.level.getBlockEntity(this); + + if (blockEntity instanceof BlockEntityBarrel) { + return ContainerInventory.calculateRedstone(((BlockEntityBarrel) blockEntity).getInventory()); + } + + return super.getComparatorInputOverride(); + } + + @Override + public boolean canBePushed() { + return false; // prevent item loss issue with pistons until a working implementation + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBarrier.java b/src/main/java/cn/nukkit/block/BlockBarrier.java new file mode 100644 index 00000000000..5d73f67917b --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBarrier.java @@ -0,0 +1,57 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.utils.BlockColor; + +public class BlockBarrier extends BlockTransparent { + + @Override + public String getName() { + return "Barrier"; + } + + @Override + public int getId() { + return BARRIER; + } + + @Override + public double getResistance() { + return 18000000; + } + + @Override + public double getHardness() { + return -1; + } + + @Override + public boolean isBreakable(Item item) { + return false; + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public boolean canBeFlowedInto() { + return false; + } + + @Override + public BlockColor getColor() { + return BlockColor.TRANSPARENT_BLOCK_COLOR; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBasalt.java b/src/main/java/cn/nukkit/block/BlockBasalt.java new file mode 100644 index 00000000000..f8a03e5475e --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBasalt.java @@ -0,0 +1,97 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.BlockColor; + +public class BlockBasalt extends BlockSolidMeta { + + public BlockBasalt() { + this(0); + } + + public BlockBasalt(int meta) { + super(meta); + } + + @Override + public double getHardness() { + return 1.25; + } + + @Override + public double getResistance() { + return 4.2; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + this.setPillarAxis(face.getAxis()); + this.getLevel().setBlock(block, this, true, true); + return true; + } + + public void setPillarAxis(BlockFace.Axis axis) { + switch (axis) { + case Y: + this.setDamage(0); + break; + case X: + this.setDamage(1); + break; + case Z: + this.setDamage(2); + break; + } + } + + public BlockFace.Axis getPillarAxis() { + switch (this.getDamage() % 3) { + case 2: + return BlockFace.Axis.Z; + case 1: + return BlockFace.Axis.X; + case 0: + default: + return BlockFace.Axis.Y; + } + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public String getName() { + return "Basalt"; + } + + @Override + public int getId() { + return BlockID.BASALT; + } + + @Override + public Item[] getDrops(Item item) { + if (item.isPickaxe()) { + return new Item[]{ + toItem() + }; + } else { + return new Item[0]; + } + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public BlockColor getColor() { + return BlockColor.GRAY_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBasaltSmooth.java b/src/main/java/cn/nukkit/block/BlockBasaltSmooth.java new file mode 100644 index 00000000000..6e1394b16fe --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBasaltSmooth.java @@ -0,0 +1,60 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockBasaltSmooth extends BlockSolid { + + @Override + public String getName() { + return "Smooth Basalt"; + } + + @Override + public int getId() { + return SMOOTH_BASALT; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public double getHardness() { + return 1.25; + } + + @Override + public double getResistance() { + return 4.2; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public Item[] getDrops(Item item) { + if (item.isPickaxe()) { + return new Item[]{ + toItem() + }; + } else { + return new Item[0]; + } + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public BlockColor getColor() { + return BlockColor.GRAY_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBeacon.java b/src/main/java/cn/nukkit/block/BlockBeacon.java index 8a52c099ef9..6bba6e6309b 100644 --- a/src/main/java/cn/nukkit/block/BlockBeacon.java +++ b/src/main/java/cn/nukkit/block/BlockBeacon.java @@ -11,13 +11,10 @@ import cn.nukkit.utils.BlockColor; /** - * author: Angelic47 Nukkit Project + * @author Angelic47 Nukkit Project */ public class BlockBeacon extends BlockTransparent { - public BlockBeacon() { - } - @Override public int getId() { return BEACON; @@ -57,19 +54,8 @@ public boolean canBeActivated() { public boolean onActivate(Item item, Player player) { if (player != null) { BlockEntity t = this.getLevel().getBlockEntity(this); - BlockEntityBeacon beacon; - if (t instanceof BlockEntityBeacon) { - beacon = (BlockEntityBeacon) t; - } else { - CompoundTag nbt = new CompoundTag("") - .putString("id", BlockEntity.BEACON) - .putInt("x", (int) this.x) - .putInt("y", (int) this.y) - .putInt("z", (int) this.z); - beacon = (BlockEntityBeacon) BlockEntity.createBlockEntity(BlockEntity.BEACON, this.getLevel().getChunk((int) (this.x) >> 4, (int) (this.z) >> 4), nbt); - if (beacon == null) { - return false; - } + if (!(t instanceof BlockEntityBeacon)) { + return false; } player.addWindow(new BeaconInventory(player.getUIInventory(), this), Player.BEACON_WINDOW_ID); @@ -79,21 +65,18 @@ public boolean onActivate(Item item, Player player) { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - boolean blockSuccess = super.place(item, block, target, face, fx, fy, fz, player); - - if (blockSuccess) { + if (this.getLevel().setBlock(this, this, true, true)) { CompoundTag nbt = new CompoundTag("") .putString("id", BlockEntity.BEACON) .putInt("x", (int) this.x) .putInt("y", (int) this.y) .putInt("z", (int) this.z); - BlockEntityBeacon beacon = (BlockEntityBeacon) BlockEntity.createBlockEntity(BlockEntity.BEACON, this.getLevel().getChunk((int) (this.x) >> 4, (int) (this.z) >> 4), nbt); - if (beacon == null) { - return false; - } + BlockEntity.createBlockEntity(BlockEntity.BEACON, this.getChunk(), nbt); + + return true; } - return blockSuccess; + return false; } @Override @@ -105,4 +88,19 @@ public boolean canBePushed() { public BlockColor getColor() { return BlockColor.DIAMOND_BLOCK_COLOR; } -} + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean breakWhenPushed() { + return true; + } + + @Override + public boolean alwaysDropsOnExplosion() { + return true; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockBed.java b/src/main/java/cn/nukkit/block/BlockBed.java index 49f7a9f5429..213641230e5 100644 --- a/src/main/java/cn/nukkit/block/BlockBed.java +++ b/src/main/java/cn/nukkit/block/BlockBed.java @@ -3,19 +3,27 @@ import cn.nukkit.Player; import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.blockentity.BlockEntityBed; -import cn.nukkit.entity.item.EntityPrimedTNT; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.mob.*; +import cn.nukkit.event.player.PlayerBedEnterEvent; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemBed; -import cn.nukkit.lang.TranslationContainer; +import cn.nukkit.level.Explosion; +import cn.nukkit.level.GameRule; import cn.nukkit.level.Level; +import cn.nukkit.level.particle.DestroyBlockParticle; +import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.math.BlockFace; +import cn.nukkit.math.SimpleAxisAlignedBB; +import cn.nukkit.math.Vector3; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.utils.BlockColor; import cn.nukkit.utils.DyeColor; import cn.nukkit.utils.Faceable; +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntSet; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockBed extends BlockTransparentMeta implements Faceable { @@ -38,11 +46,6 @@ public boolean canBeActivated() { return true; } - @Override - public double getResistance() { - return 1; - } - @Override public double getHardness() { return 0.2; @@ -58,29 +61,23 @@ public double getMaxY() { return this.y + 0.5625; } - @Override - public boolean onActivate(Item item) { - return this.onActivate(item, null); - } + /** + * List of mob network IDs which make players unable to sleep when nearby the bed. + */ + private static final IntSet MOB_IDS = new IntOpenHashSet(new int[]{EntityBlaze.NETWORK_ID, EntityCaveSpider.NETWORK_ID, EntityCreeper.NETWORK_ID, EntityDrowned.NETWORK_ID, EntityElderGuardian.NETWORK_ID, EntityEnderman.NETWORK_ID, EntityEndermite.NETWORK_ID, EntityEvoker.NETWORK_ID, EntityGhast.NETWORK_ID, EntityGuardian.NETWORK_ID, EntityHoglin.NETWORK_ID, EntityHusk.NETWORK_ID, EntityPiglinBrute.NETWORK_ID, EntityPillager.NETWORK_ID, EntityRavager.NETWORK_ID, EntityShulker.NETWORK_ID, EntitySilverfish.NETWORK_ID, EntitySkeleton.NETWORK_ID, EntitySlime.NETWORK_ID, EntitySpider.NETWORK_ID, EntityStray.NETWORK_ID, EntityVex.NETWORK_ID, EntityVindicator.NETWORK_ID, EntityWitch.NETWORK_ID, EntityWither.NETWORK_ID, EntityWitherSkeleton.NETWORK_ID, EntityZoglin.NETWORK_ID, EntityZombie.NETWORK_ID, EntityZombiePigman.NETWORK_ID, EntityZombieVillagerV1.NETWORK_ID, EntityZombieVillager.NETWORK_ID}); @Override public boolean onActivate(Item item, Player player) { - if (this.level.getDimension() == Level.DIMENSION_NETHER || this.level.getDimension() == Level.DIMENSION_THE_END) { - CompoundTag tag = EntityPrimedTNT.getDefaultNBT(this).putShort("Fuse", 0); - new EntityPrimedTNT(this.level.getChunk(this.getFloorX() >> 4, this.getFloorZ() >> 4), tag); - return true; - } - - if (player == null) { - return false; - } - - int time = this.getLevel().getTime() % Level.TIME_FULL; - - boolean isNight = (time >= Level.TIME_NIGHT && time < Level.TIME_SUNRISE); - - if (!isNight && !this.getLevel().isThundering()) { - player.sendMessage(new TranslationContainer("tile.bed.noSleep")); + if (this.level.getDimension() != Level.DIMENSION_OVERWORLD) { + if (this.level.getGameRules().getBoolean(GameRule.RESPAWN_BLOCKS_EXPLODE)) { + if (this.getLevel().setBlock(this, Block.get(BlockID.AIR), true, true)) { + this.level.addParticle(new DestroyBlockParticle(this.add(0.5, 0.5, 0.5), this)); + } + + Explosion explosion = new Explosion(this.add(0.5, 0, 0.5), 5, this); + explosion.explodeA(); + explosion.explodeB(); + } return true; } @@ -93,23 +90,56 @@ public boolean onActivate(Item item, Player player) { if ((this.getDamage() & 0x08) == 0x08) { b = this; } else { - if (blockNorth.getId() == this.getId() && (blockNorth.getDamage() & 0x08) == 0x08) { + if (blockNorth.getId() == BED_BLOCK && (blockNorth.getDamage() & 0x08) == 0x08) { b = blockNorth; - } else if (blockSouth.getId() == this.getId() && (blockSouth.getDamage() & 0x08) == 0x08) { + } else if (blockSouth.getId() == BED_BLOCK && (blockSouth.getDamage() & 0x08) == 0x08) { b = blockSouth; - } else if (blockEast.getId() == this.getId() && (blockEast.getDamage() & 0x08) == 0x08) { + } else if (blockEast.getId() == BED_BLOCK && (blockEast.getDamage() & 0x08) == 0x08) { b = blockEast; - } else if (blockWest.getId() == this.getId() && (blockWest.getDamage() & 0x08) == 0x08) { + } else if (blockWest.getId() == BED_BLOCK && (blockWest.getDamage() & 0x08) == 0x08) { b = blockWest; } else { - player.sendMessage(new TranslationContainer("tile.bed.notValid")); + if (player != null) { + player.sendMessage("§7%tile.bed.notValid", true); + } return true; } } - if (!player.sleepOn(b)) { - player.sendMessage(new TranslationContainer("tile.bed.occupied")); + if (player != null) { + if (player.distanceSquared(this) > 36) { + player.sendMessage("§7%tile.bed.tooFar", true); + return true; + } + + if (!player.isCreative()) { + BlockFace secondPart = this.getBlockFace().getOpposite(); + AxisAlignedBB checkArea = new SimpleAxisAlignedBB(b.x - 8, b.y - 6.5, b.z - 8, b.x + 9, b.y + 5.5, b.z + 9).addCoord(secondPart.getXOffset(), 0, secondPart.getZOffset()); + + for (Entity entity : this.getLevel().getCollidingEntities(checkArea)) { + if (!entity.isClosed() && MOB_IDS.contains(entity.getNetworkId())) { + player.sendMessage("§7%tile.bed.notSafe", true); + return true; + } + } + } + + int time = this.getLevel().getTime() % Level.TIME_FULL; + boolean isNight = time >= Level.TIME_NIGHT && time < Level.TIME_SUNRISE; + if (!isNight && !this.getLevel().isThundering()) { + if (!b.equals(player.getSpawnPosition())) { + PlayerBedEnterEvent ev = new PlayerBedEnterEvent(player, this, true); // TODO: Event for setting player respawn point? + player.getServer().getPluginManager().callEvent(ev); + if (!ev.isCancelled()) { + player.setSpawn(b); + player.sendMessage("§7%tile.bed.respawnSet", true); + } + } + player.sendMessage("§7%tile.bed.noSleep", true); + } else if (!player.sleepOn(b)) { + player.sendMessage("§7%tile.bed.occupied", true); + } } return true; @@ -117,16 +147,15 @@ public boolean onActivate(Item item, Player player) { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - Block down = this.down(); - if (!down.isTransparent()) { - Block next = this.getSide(player.getDirection()); - Block downNext = next.down(); + if (canStayOnFullNonSolid(this.down())) { + Block next = this.getSide(player.getHorizontalFacing()); - if (next.canBeReplaced() && !downNext.isTransparent()) { + if (next.canBeReplaced() && canStayOnFullNonSolid(next.down())) { int meta = player.getDirection().getHorizontalIndex(); - this.getLevel().setBlock(block, Block.get(this.getId(), meta), true, true); - this.getLevel().setBlock(next, Block.get(this.getId(), meta | 0x08), true, true); + this.getLevel().setBlock(block, Block.get(BED_BLOCK, meta), true, true); + + this.getLevel().setBlock(next, Block.get(BED_BLOCK, meta | 0x08), true, true); createBlockEntity(this, item.getDamage()); createBlockEntity(next, item.getDamage()); @@ -137,36 +166,69 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl return false; } + /** + * Internal: Can drop item when broken + */ + public boolean canDropItem = true; + @Override public boolean onBreak(Item item) { - Block blockNorth = this.north(); //Gets the blocks around them + Block blockNorth = this.north(); Block blockSouth = this.south(); Block blockEast = this.east(); Block blockWest = this.west(); - if ((this.getDamage() & 0x08) == 0x08) { //This is the Top part of bed - if (blockNorth.getId() == BED_BLOCK && (blockNorth.getDamage() & 0x08) != 0x08) { //Checks if the block ID&&meta are right - this.getLevel().setBlock(blockNorth, Block.get(BlockID.AIR), true, true); + Block secondPart = null; + if ((this.getDamage() & 0x08) == 0x08) { // Top part of the bed + if (blockNorth.getId() == BED_BLOCK && (blockNorth.getDamage() & 0x08) != 0x08) { // Check if the block ID & meta are right + secondPart = blockNorth; } else if (blockSouth.getId() == BED_BLOCK && (blockSouth.getDamage() & 0x08) != 0x08) { - this.getLevel().setBlock(blockSouth, Block.get(BlockID.AIR), true, true); + secondPart = blockSouth; } else if (blockEast.getId() == BED_BLOCK && (blockEast.getDamage() & 0x08) != 0x08) { - this.getLevel().setBlock(blockEast, Block.get(BlockID.AIR), true, true); + secondPart = blockEast; } else if (blockWest.getId() == BED_BLOCK && (blockWest.getDamage() & 0x08) != 0x08) { - this.getLevel().setBlock(blockWest, Block.get(BlockID.AIR), true, true); + secondPart = blockWest; } - } else { //Bottom Part of Bed - if (blockNorth.getId() == this.getId() && (blockNorth.getDamage() & 0x08) == 0x08) { - this.getLevel().setBlock(blockNorth, Block.get(BlockID.AIR), true, true); - } else if (blockSouth.getId() == this.getId() && (blockSouth.getDamage() & 0x08) == 0x08) { - this.getLevel().setBlock(blockSouth, Block.get(BlockID.AIR), true, true); - } else if (blockEast.getId() == this.getId() && (blockEast.getDamage() & 0x08) == 0x08) { - this.getLevel().setBlock(blockEast, Block.get(BlockID.AIR), true, true); - } else if (blockWest.getId() == this.getId() && (blockWest.getDamage() & 0x08) == 0x08) { - this.getLevel().setBlock(blockWest, Block.get(BlockID.AIR), true, true); + } else { // Bottom part of the bed + if (blockNorth.getId() == BED_BLOCK && (blockNorth.getDamage() & 0x08) == 0x08) { + secondPart = blockNorth; + } else if (blockSouth.getId() == BED_BLOCK && (blockSouth.getDamage() & 0x08) == 0x08) { + secondPart = blockSouth; + } else if (blockEast.getId() == BED_BLOCK && (blockEast.getDamage() & 0x08) == 0x08) { + secondPart = blockEast; + } else if (blockWest.getId() == BED_BLOCK && (blockWest.getDamage() & 0x08) == 0x08) { + secondPart = blockWest; } } - this.getLevel().setBlock(this, Block.get(BlockID.AIR), true, false); // Do not update both parts to prevent duplication bug if there is two fallable blocks top of the bed + if (secondPart != null) { + Item secondPartDrop = (secondPart.getDamage() & 0x08) == 0x08 ? secondPart.toItem() : null; // Get drops before block entity is destroyed to keep the color + if (this.getLevel().setBlock(secondPart, Block.get(BlockID.AIR), true, true)) { + if (secondPartDrop != null && this.canDropItem && this.getLevel().gameRules.getBoolean(GameRule.DO_TILE_DROPS)) { + this.getLevel().dropItem(this.add(0.5, 0.5, 0.5), secondPartDrop); // Drops only from the top part, prevent a dupe + } + } + } + + this.getLevel().setBlock(this, Block.get(BlockID.AIR), true, secondPart == null); // Don't update both parts to prevent duplication bug if there are two fallable blocks on top of the bed + + for (Entity entity : this.level.getNearbyEntities(new SimpleAxisAlignedBB(this, this).grow(2, 1, 2))) { + if (!(entity instanceof Player)) continue; + Player player = (Player) entity; + + if (player.getSleepingPos() == null) continue; + if (!player.getSleepingPos().equals(this) && !player.getSleepingPos().equals(secondPart)) continue; + player.stopSleep(); + } + + if (level.getDimension() == Level.DIMENSION_OVERWORLD) { + Vector3 safeSpawn = null; + for (Player player : level.getServer().getOnlinePlayers().values()) { + if (player.getSpawnPosition() != null && (player.getSpawnPosition().equals(this) || player.getSpawnPosition().equals(secondPart))) { + player.setSpawn(safeSpawn == null ? (safeSpawn = level.getServer().getDefaultLevel().getSafeSpawn()) : safeSpawn); + } + } + } return true; } @@ -175,12 +237,13 @@ private void createBlockEntity(Block pos, int color) { CompoundTag nbt = BlockEntity.getDefaultCompound(pos, BlockEntity.BED); nbt.putByte("color", color); - BlockEntity.createBlockEntity(BlockEntity.BED, pos.getChunk(), nbt); + BlockEntityBed be = (BlockEntityBed) BlockEntity.createBlockEntity(BlockEntity.BED, pos.getChunk(), nbt); + be.spawnToAll(); } @Override public Item toItem() { - return new ItemBed(this.getDyeColor().getWoolData()); + return Item.get(Item.BED, this.getDyeColor().getWoolData()); } @Override @@ -204,4 +267,14 @@ public DyeColor getDyeColor() { public BlockFace getBlockFace() { return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); } + + /*@Override + public boolean breakWhenPushed() { + return true; + }*/ + + @Override + public boolean canBePushed() { + return false; // Temporary dupe patch + } } diff --git a/src/main/java/cn/nukkit/block/BlockBedrock.java b/src/main/java/cn/nukkit/block/BlockBedrock.java index 73e75f6ab2e..bde9f7bf001 100644 --- a/src/main/java/cn/nukkit/block/BlockBedrock.java +++ b/src/main/java/cn/nukkit/block/BlockBedrock.java @@ -3,14 +3,11 @@ import cn.nukkit.item.Item; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class BlockBedrock extends BlockSolid { - public BlockBedrock() { - } - @Override public int getId() { return BEDROCK; diff --git a/src/main/java/cn/nukkit/block/BlockBedrockInvisible.java b/src/main/java/cn/nukkit/block/BlockBedrockInvisible.java index 3f586ca815f..a85caf29b6f 100644 --- a/src/main/java/cn/nukkit/block/BlockBedrockInvisible.java +++ b/src/main/java/cn/nukkit/block/BlockBedrockInvisible.java @@ -1,7 +1,6 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemBlock; import cn.nukkit.utils.BlockColor; /** @@ -9,9 +8,6 @@ */ public class BlockBedrockInvisible extends BlockSolid { - public BlockBedrockInvisible() { - } - @Override public int getId() { return INVISIBLE_BEDROCK; @@ -49,6 +45,11 @@ public boolean canBePushed() { @Override public Item toItem() { - return new ItemBlock(Block.get(BlockID.AIR)); + return Item.get(0); + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.FLOW_INTO_BLOCK; } } diff --git a/src/main/java/cn/nukkit/block/BlockBeeNest.java b/src/main/java/cn/nukkit/block/BlockBeeNest.java new file mode 100644 index 00000000000..a325df1e5e9 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBeeNest.java @@ -0,0 +1,55 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.utils.BlockColor; + +public class BlockBeeNest extends BlockBeehive { + + public BlockBeeNest() { + this(0); + } + + public BlockBeeNest(int meta) { + super(meta); + } + + @Override + public int getId() { + return BEE_NEST; + } + + @Override + public String getName() { + return "Bee Nest"; + } + + @Override + public int getBurnChance() { + return 30; + } + + @Override + public int getBurnAbility() { + return 60; + } + + @Override + public double getHardness() { + return 0.3; + } + + @Override + public double getResistance() { + return 0.3; + } + + @Override + public Item[] getDrops(Item item) { + return new Item[0]; + } + + @Override + public BlockColor getColor() { + return BlockColor.YELLOW_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBeehive.java b/src/main/java/cn/nukkit/block/BlockBeehive.java new file mode 100644 index 00000000000..9864544eb51 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBeehive.java @@ -0,0 +1,77 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.BlockColor; + +public class BlockBeehive extends BlockSolidMeta { + + public BlockBeehive() { + this(0); + } + + public BlockBeehive(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Beehive"; + } + + @Override + public int getId() { + return BEEHIVE; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_AXE; + } + + @Override + public int getBurnChance() { + return 5; + } + + @Override + public int getBurnAbility() { + return 20; + } + + @Override + public double getHardness() { + return 0.6; + } + + @Override + public double getResistance() { + return 0.6; + } + + @Override + public BlockColor getColor() { + return BlockColor.WOOD_BLOCK_COLOR; + } + + @Override + public boolean canSilkTouch() { + return true; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + private static final short[] FACES = {2, 3, 0, 1}; + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + this.setDamage(FACES[player != null ? player.getDirection().getHorizontalIndex() : 0]); + return this.getLevel().setBlock(this, this, true, true); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBeetroot.java b/src/main/java/cn/nukkit/block/BlockBeetroot.java index 155f69f58b0..90ab0f6363f 100644 --- a/src/main/java/cn/nukkit/block/BlockBeetroot.java +++ b/src/main/java/cn/nukkit/block/BlockBeetroot.java @@ -1,7 +1,7 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemSeedsBeetroot; +import cn.nukkit.utils.Utils; /** * Created on 2015/11/22 by xtypr. @@ -28,7 +28,7 @@ public String getName() { @Override public Item toItem() { - return new ItemSeedsBeetroot(); + return Item.get(Item.BEETROOT_SEEDS); } @Override @@ -36,7 +36,7 @@ public Item[] getDrops(Item item) { if (this.getDamage() >= 0x07) { return new Item[]{ Item.get(Item.BEETROOT, 0, 1), - Item.get(Item.BEETROOT_SEEDS, 0, (int) (4d * Math.random())) + Item.get(Item.BEETROOT_SEEDS, 0, Utils.random.nextInt(0, 4)) }; } else { return new Item[]{ diff --git a/src/main/java/cn/nukkit/block/BlockBell.java b/src/main/java/cn/nukkit/block/BlockBell.java new file mode 100644 index 00000000000..9376f1d9783 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBell.java @@ -0,0 +1,405 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.blockentity.BlockEntity; +import cn.nukkit.blockentity.BlockEntityBell; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityItem; +import cn.nukkit.event.block.BellRingEvent; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.level.Level; +import cn.nukkit.level.Position; +import cn.nukkit.math.AxisAlignedBB; +import cn.nukkit.math.BlockFace; +import cn.nukkit.math.SimpleAxisAlignedBB; +import cn.nukkit.math.Vector3; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.network.protocol.LevelSoundEventPacket; +import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.Faceable; + +public class BlockBell extends BlockTransparentMeta implements Faceable { + + public static final int TYPE_ATTACHMENT_STANDING = 0; + public static final int TYPE_ATTACHMENT_HANGING = 1; + public static final int TYPE_ATTACHMENT_SIDE = 2; + public static final int TYPE_ATTACHMENT_MULTIPLE = 3; + + public BlockBell() { + this(0); + } + + public BlockBell(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Bell"; + } + + @Override + public int getId() { + return BELL; + } + + private boolean isConnectedTo(BlockFace connectedFace, int attachmentType, BlockFace blockFace) { + BlockFace.Axis faceAxis = connectedFace.getAxis(); + switch (attachmentType) { + case TYPE_ATTACHMENT_STANDING: + if (faceAxis == BlockFace.Axis.Y) { + return connectedFace == BlockFace.DOWN; + } else { + return blockFace.getAxis() != faceAxis; + } + case TYPE_ATTACHMENT_HANGING: + return connectedFace == BlockFace.UP; + case TYPE_ATTACHMENT_SIDE: + return connectedFace == blockFace.getOpposite(); + case TYPE_ATTACHMENT_MULTIPLE: + return connectedFace == blockFace || connectedFace == blockFace.getOpposite(); + } + return false; + } + + @Override + protected AxisAlignedBB recalculateBoundingBox() { + int attachmentType = getAttachmentType(); + BlockFace blockFace = getBlockFace(); + boolean north = this.isConnectedTo(BlockFace.NORTH, attachmentType, blockFace); + boolean south = this.isConnectedTo(BlockFace.SOUTH, attachmentType, blockFace); + boolean west = this.isConnectedTo(BlockFace.WEST, attachmentType, blockFace); + boolean east = this.isConnectedTo(BlockFace.EAST, attachmentType, blockFace); + boolean up = this.isConnectedTo(BlockFace.UP, attachmentType, blockFace); + boolean down = this.isConnectedTo(BlockFace.DOWN, attachmentType, blockFace); + + double n = north ? 0 : 0.25; + double s = south ? 1 : 0.75; + double w = west ? 0 : 0.25; + double e = east ? 1 : 0.75; + double d = down ? 0 : 0.25; + double u = up ? 1 : 0.75; + + return new SimpleAxisAlignedBB(this.x + w, this.y + d, this.z + n, this.x + e, this.y + u, this.z + s); + } + + @Override + public void onEntityCollide(Entity entity) { + if (entity instanceof EntityItem && entity.getMotion().lengthSquared() > 0.01) { + AxisAlignedBB boundingBox = entity.getBoundingBox(); + AxisAlignedBB blockBoundingBox = this.getCollisionBoundingBox(); + if (boundingBox.intersectsWith(blockBoundingBox)) { + Vector3 entityCenter = new Vector3( + (boundingBox.getMaxX() - boundingBox.getMinX()) / 2, + (boundingBox.getMaxY() - boundingBox.getMinY()) / 2, + (boundingBox.getMaxZ() - boundingBox.getMinZ()) / 2 + ); + + Vector3 blockCenter = new Vector3( + (blockBoundingBox.getMaxX() - blockBoundingBox.getMinX()) / 2, + (blockBoundingBox.getMaxY() - blockBoundingBox.getMinY()) / 2, + (blockBoundingBox.getMaxZ() - blockBoundingBox.getMinZ()) / 2 + ); + Vector3 entityPos = entity.add(entityCenter); + Vector3 blockPos = this.add( + blockBoundingBox.getMinX() - x + blockCenter.x, + blockBoundingBox.getMinY() - y + blockCenter.y, + blockBoundingBox.getMinZ() - z + blockCenter.z + ); + + Vector3 entityVector = entityPos.subtract(blockPos); + entityVector = entityVector.normalize().multiply(0.4); + entityVector.y = Math.max(0.15, entityVector.y); + if (this.ring(entity, BellRingEvent.RingCause.DROPPED_ITEM)) { + entity.setMotion(entityVector); + } + } + } + } + + @Override + public boolean hasEntityCollision() { + return true; + } + + @Override + protected AxisAlignedBB recalculateCollisionBoundingBox() { + return recalculateBoundingBox().expand(0.000001, 0.000001, 0.000001); + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Item item, Player player) { + return this.ring(player, player != null? BellRingEvent.RingCause.HUMAN_INTERACTION : BellRingEvent.RingCause.UNKNOWN); + } + + public boolean ring(Entity causeEntity, BellRingEvent.RingCause cause) { + return this.ring(causeEntity, cause, null); + } + + public boolean ring(Entity causeEntity, BellRingEvent.RingCause cause, BlockFace hitFace) { + BlockEntityBell bell = this.getOrCreateBlockEntity(); + if (bell == null) { + return true; + } + boolean addException = true; + BlockFace blockFace = getBlockFace(); + if (hitFace == null) { + if (causeEntity != null) { + if (causeEntity instanceof EntityItem) { + Position blockMid = this.add(0.5, 0.5, 0.5); + Vector3 vector = causeEntity.subtract(blockMid).normalize(); + int x = vector.x < 0? -1 : vector.x > 0? 1 : 0; + int z = vector.z < 0? -1 : vector.z > 0? 1 : 0; + if (x != 0 && z != 0) { + if (Math.abs(vector.x) < Math.abs(vector.z)) { + x = 0; + } else { + z = 0; + } + } + hitFace = blockFace; + for (BlockFace face : BlockFace.values()) { + if (face.getXOffset() == x && face.getZOffset() == z) { + hitFace = face; + break; + } + } + } else { + hitFace = causeEntity.getDirection(); + } + } else { + hitFace = blockFace; + } + } + switch (this.getAttachmentType()) { + case TYPE_ATTACHMENT_STANDING: + if (hitFace.getAxis() != blockFace.getAxis()) { + return false; + } + break; + case TYPE_ATTACHMENT_MULTIPLE: + if (hitFace.getAxis() == blockFace.getAxis()) { + return false; + } + break; + case TYPE_ATTACHMENT_SIDE: + if (hitFace.getAxis() == blockFace.getAxis()) { + addException = false; + } + break; + } + + BellRingEvent event = new BellRingEvent(this, cause, causeEntity); + this.level.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return false; + } + + bell.setDirection(hitFace.getOpposite().getHorizontalIndex()); + bell.setTicks(0); + bell.setRinging(true); + if (addException && causeEntity instanceof Player) { + bell.spawnExceptions.add(causeEntity.getId()); + } + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_BLOCK_BELL_HIT); + return true; + } + + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + private boolean checkSupport() { + switch (this.getAttachmentType()) { + case TYPE_ATTACHMENT_STANDING: + if (this.checkSupport(this.down(), BlockFace.UP)) { + return true; + } + break; + case TYPE_ATTACHMENT_HANGING: + if (this.checkSupport(this.up(), BlockFace.DOWN)) { + return true; + } + break; + case TYPE_ATTACHMENT_MULTIPLE: + BlockFace blockFace = getBlockFace(); + if (this.checkSupport(this.getSide(blockFace), blockFace.getOpposite()) && + this.checkSupport(this.getSide(blockFace.getOpposite()), blockFace)) { + return true; + } + break; + case TYPE_ATTACHMENT_SIDE: + blockFace = getBlockFace(); + if (this.checkSupport(this.getSide(blockFace.getOpposite()), blockFace)) { + return true; + } + break; + } + + return false; + } + + private boolean checkSupport(Block support, BlockFace attachmentFace) { + if (!support.isTransparent()) { + return true; + } + + if (attachmentFace == BlockFace.DOWN) { + switch (support.getId()) { + case HOPPER_BLOCK: + case IRON_BARS: + return true; + default: + return support instanceof BlockFence; + } + } + + if (support instanceof BlockCauldron) { + return attachmentFace == BlockFace.UP; + } + + if (attachmentFace == BlockFace.UP) { + return Block.canStayOnFullSolid(support); + } + return false; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + if (!checkSupport()) { + this.level.useBreakOn(this); + } + return type; + } else if (type == Level.BLOCK_UPDATE_REDSTONE) { + if (level.isBlockPowered(this)) { + if (!isToggled()) { + setToggled(true); + this.level.setBlock(this, this, true, true); + ring(null, BellRingEvent.RingCause.REDSTONE); + } + } else if (isToggled()) { + setToggled(false); + this.level.setBlock(this, this, true, true); + } + return type; + } + return 0; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (block.canBeReplaced() && block.getId() != AIR && !(block instanceof BlockLiquid)) { + face = BlockFace.UP; + } + switch (face) { + case UP: + this.setAttachmentType(TYPE_ATTACHMENT_STANDING); + this.setBlockFace(player.getDirection().getOpposite()); + break; + case DOWN: + this.setAttachmentType(TYPE_ATTACHMENT_HANGING); + this.setBlockFace(player.getDirection().getOpposite()); + break; + default: + this.setBlockFace(face); + if (this.checkSupport(block.getSide(face), face.getOpposite())) { + this.setAttachmentType(TYPE_ATTACHMENT_MULTIPLE); + } else { + this.setAttachmentType(TYPE_ATTACHMENT_SIDE); + } + } + if (!this.checkSupport()) { + return false; + } + this.getLevel().setBlock(this, this, true, true); + this.createBlockEntity(); + return true; + } + + private BlockEntityBell createBlockEntity() { + CompoundTag nbt = BlockEntity.getDefaultCompound(this, BlockEntity.BELL); + return (BlockEntityBell) BlockEntity.createBlockEntity(BlockEntity.BELL, this.getChunk(), nbt); + } + + private BlockEntityBell getOrCreateBlockEntity() { + BlockEntity blockEntity = this.getLevel().getBlockEntity(this); + if (!(blockEntity instanceof BlockEntityBell)) { + blockEntity = this.createBlockEntity(); + } + return (BlockEntityBell) blockEntity; + } + + @Override + public BlockFace getBlockFace() { + return BlockFace.fromHorizontalIndex(getDamage() & 0b11); + } + + public void setBlockFace(BlockFace face) { + if (face.getHorizontalIndex() == -1) { + return; + } + this.setDamage(this.getDamage() & (DATA_MASK ^ 0b11) | face.getHorizontalIndex()); + } + + public int getAttachmentType() { + return (this.getDamage() & 0b1100) >> 2 & 0b11; + } + + public void setAttachmentType(int attachmentType) { + attachmentType = attachmentType & 0b11; + this.setDamage(getDamage() & (DATA_MASK ^ 0b1100) | (attachmentType << 2)); + } + + public boolean isToggled() { + return (this.getDamage() & 0b010000) == 0b010000; + } + + public void setToggled(boolean toggled) { + this.setDamage(this.getDamage() & (DATA_MASK ^ 0b010000) | (toggled? 0b010000 : 0b000000)); + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public double getHardness() { + return 5; + } + + @Override + public double getResistance() { + return 5; + } + + @Override + public BlockColor getColor() { + return BlockColor.GOLD_BLOCK_COLOR; + } + + @Override + public boolean canBePushed() { + return false; // prevent item loss issue with pistons until a working implementation + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockBirchSignStanding.java b/src/main/java/cn/nukkit/block/BlockBirchSignStanding.java new file mode 100644 index 00000000000..c45b9f2652e --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBirchSignStanding.java @@ -0,0 +1,40 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; + +public class BlockBirchSignStanding extends BlockSignPost { + + public BlockBirchSignStanding() { + this(0); + } + + public BlockBirchSignStanding(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Birch Sign Post"; + } + + @Override + public int getId() { + return BIRCH_STANDING_SIGN; + } + + @Override + public Item toItem() { + return Item.get(ItemID.BIRCH_SIGN); + } + + @Override + protected int getPostId() { + return BIRCH_STANDING_SIGN; + } + + @Override + protected int getWallId() { + return BIRCH_WALL_SIGN; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBirchWallSign.java b/src/main/java/cn/nukkit/block/BlockBirchWallSign.java new file mode 100644 index 00000000000..8fd9e0c35dc --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBirchWallSign.java @@ -0,0 +1,40 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; + +public class BlockBirchWallSign extends BlockWallSign { + + public BlockBirchWallSign() { + this(0); + } + + public BlockBirchWallSign(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Birch Wall Sign"; + } + + @Override + public int getId() { + return BIRCH_WALL_SIGN; + } + + @Override + public Item toItem() { + return Item.get(ItemID.BIRCH_SIGN); + } + + @Override + protected int getPostId() { + return BIRCH_STANDING_SIGN; + } + + @Override + protected int getWallId() { + return BIRCH_WALL_SIGN; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBlackstone.java b/src/main/java/cn/nukkit/block/BlockBlackstone.java new file mode 100644 index 00000000000..ace24d44ab7 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBlackstone.java @@ -0,0 +1,57 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockBlackstone extends BlockSolid { + + public BlockBlackstone() { + } + + @Override + public int getId() { + return BLACKSTONE; + } + + @Override + public String getName() { + return "Blackstone"; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public BlockColor getColor() { + return BlockColor.BLACK_BLOCK_COLOR; + } + + @Override + public double getHardness() { + return 1.5; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public Item[] getDrops(Item item) { + if (item.isPickaxe()) { + return new Item[]{ + toItem() + }; + } else { + return new Item[0]; + } + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBlackstoneGilded.java b/src/main/java/cn/nukkit/block/BlockBlackstoneGilded.java new file mode 100644 index 00000000000..6a7590a6997 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBlackstoneGilded.java @@ -0,0 +1,87 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; +import cn.nukkit.item.ItemTool; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.utils.BlockColor; + +import java.util.concurrent.ThreadLocalRandom; + +public class BlockBlackstoneGilded extends BlockSolid { + + @Override + public int getId() { + return GILDED_BLACKSTONE; + } + + @Override + public String getName() { + return "Gilded Blackstone"; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public Item[] getDrops(Item item) { + if (!item.isPickaxe()) { + return new Item[0]; + } + + int dropOdds; + int fortune = 0; + Enchantment enchantment = item.getEnchantment(Enchantment.ID_FORTUNE_DIGGING); + if (enchantment != null) { + fortune = enchantment.getLevel(); + } + + switch (fortune) { + case 0: + dropOdds = 10; + break; + case 1: + dropOdds = 7; + break; + case 2: + dropOdds = 4; + break; + default: + dropOdds = 1; + } + + ThreadLocalRandom random = ThreadLocalRandom.current(); + if (dropOdds > 1 && random.nextInt(dropOdds) != 0) { + return new Item[] { toItem() }; + } + + return new Item[] { Item.get(ItemID.GOLD_NUGGET, 0, random.nextInt(2, 6)) }; + } + + @Override + public boolean canSilkTouch() { + return true; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public BlockColor getColor() { + return BlockColor.BLACK_BLOCK_COLOR; + } + + @Override + public double getHardness() { + return 1.5; + } + + @Override + public double getResistance() { + return 6; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBlackstonePolished.java b/src/main/java/cn/nukkit/block/BlockBlackstonePolished.java new file mode 100644 index 00000000000..764187eae64 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBlackstonePolished.java @@ -0,0 +1,19 @@ +package cn.nukkit.block; + +public class BlockBlackstonePolished extends BlockBlackstone { + + @Override + public String getName() { + return "Polished Blackstone"; + } + + @Override + public int getId() { + return POLISHED_BLACKSTONE; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBlackstonePolishedChiseled.java b/src/main/java/cn/nukkit/block/BlockBlackstonePolishedChiseled.java new file mode 100644 index 00000000000..c04d8014f10 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBlackstonePolishedChiseled.java @@ -0,0 +1,14 @@ +package cn.nukkit.block; + +public class BlockBlackstonePolishedChiseled extends BlockBlackstonePolished { + + @Override + public int getId() { + return CHISELED_POLISHED_BLACKSTONE; + } + + @Override + public String getName() { + return "Chiseled Polished Blackstone"; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBlackstoneWall.java b/src/main/java/cn/nukkit/block/BlockBlackstoneWall.java new file mode 100644 index 00000000000..d4fd0797f2c --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBlackstoneWall.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockBlackstoneWall extends BlockWall { + + public BlockBlackstoneWall() { + this(0); + } + + public BlockBlackstoneWall(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Blackstone Wall"; + } + + @Override + public int getId() { + return BLACKSTONE_WALL; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBlastFurnace.java b/src/main/java/cn/nukkit/block/BlockBlastFurnace.java new file mode 100644 index 00000000000..3110b37b0e7 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBlastFurnace.java @@ -0,0 +1,27 @@ +package cn.nukkit.block; + +public class BlockBlastFurnace extends BlockBlastFurnaceLit { + + public BlockBlastFurnace() { + this(0); + } + + public BlockBlastFurnace(int meta) { + super(meta); + } + + @Override + public int getLightLevel() { + return 0; + } + + @Override + public String getName() { + return "Blast Furnace"; + } + + @Override + public int getId() { + return BLAST_FURNACE; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBlastFurnaceLit.java b/src/main/java/cn/nukkit/block/BlockBlastFurnaceLit.java new file mode 100644 index 00000000000..56d7373ead6 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBlastFurnaceLit.java @@ -0,0 +1,87 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.blockentity.BlockEntity; +import cn.nukkit.blockentity.BlockEntityBlastFurnace; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.math.BlockFace; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.ListTag; +import cn.nukkit.nbt.tag.StringTag; +import cn.nukkit.nbt.tag.Tag; + +import java.util.Map; + +public class BlockBlastFurnaceLit extends BlockFurnaceBurning { + + public BlockBlastFurnaceLit() { + this(0); + } + + public BlockBlastFurnaceLit(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Lit Blast Furnace"; + } + + @Override + public int getId() { + return LIT_BLAST_FURNACE; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(BLAST_FURNACE)); + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + this.setDamage(Block.FACES2534[player != null ? player.getDirection().getHorizontalIndex() : 0]); + this.getLevel().setBlock(block, this, true, true); + CompoundTag nbt = new CompoundTag() + .putList(new ListTag<>("Items")) + .putString("id", BlockEntity.BLAST_FURNACE) + .putInt("x", (int) this.x) + .putInt("y", (int) this.y) + .putInt("z", (int) this.z); + + if (item.hasCustomName()) { + nbt.putString("CustomName", item.getCustomName()); + } + + if (item.hasCustomBlockData()) { + Map customData = item.getCustomBlockData().getTags(); + for (Map.Entry tag : customData.entrySet()) { + nbt.put(tag.getKey(), tag.getValue()); + } + } + + BlockEntityBlastFurnace furnace = (BlockEntityBlastFurnace) BlockEntity.createBlockEntity(BlockEntity.BLAST_FURNACE, this.getChunk(), nbt); + return furnace != null; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (player != null) { + BlockEntity t = this.getLevel().getBlockEntity(this); + if (!(t instanceof BlockEntityBlastFurnace)) { + return false; + } + + BlockEntityBlastFurnace furnace = (BlockEntityBlastFurnace) t; + if (furnace.namedTag.contains("Lock") && furnace.namedTag.get("Lock") instanceof StringTag) { + if (!furnace.namedTag.getString("Lock").equals(item.getCustomName())) { + return true; + } + } + + player.addWindow(furnace.getInventory()); + } + + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBlueIce.java b/src/main/java/cn/nukkit/block/BlockBlueIce.java new file mode 100644 index 00000000000..01df5f71dcb --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBlueIce.java @@ -0,0 +1,29 @@ +package cn.nukkit.block; + +public class BlockBlueIce extends BlockIcePacked { + + @Override + public String getName() { + return "Blue Ice"; + } + + @Override + public int getId() { + return BLUE_ICE; + } + + @Override + public double getFrictionFactor() { + return 0.989; + } + + @Override + public double getHardness() { + return 2.8; + } + + @Override + public double getResistance() { + return 14; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBone.java b/src/main/java/cn/nukkit/block/BlockBone.java index ae747a445b9..7945abb9fbe 100644 --- a/src/main/java/cn/nukkit/block/BlockBone.java +++ b/src/main/java/cn/nukkit/block/BlockBone.java @@ -11,7 +11,7 @@ /** * @author CreeperFace */ -public class BlockBone extends BlockSolidMeta implements Faceable { +public class BlockBone extends BlockSolid implements Faceable { private static final int[] FACES = { 0, @@ -22,14 +22,6 @@ public class BlockBone extends BlockSolidMeta implements Faceable { 0b0100 }; - public BlockBone() { - this(0); - } - - public BlockBone(int meta) { - super(meta); - } - @Override public int getId() { return BONE_BLOCK; @@ -57,7 +49,7 @@ public int getToolType() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{new ItemBlock(this)}; } diff --git a/src/main/java/cn/nukkit/block/BlockBookshelf.java b/src/main/java/cn/nukkit/block/BlockBookshelf.java index 9b931281d34..dba76c928e1 100644 --- a/src/main/java/cn/nukkit/block/BlockBookshelf.java +++ b/src/main/java/cn/nukkit/block/BlockBookshelf.java @@ -1,22 +1,13 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemBook; import cn.nukkit.item.ItemTool; import cn.nukkit.utils.BlockColor; /** * @author Nukkit Project Team */ -public class BlockBookshelf extends BlockSolidMeta { - - public BlockBookshelf(int meta) { - super(meta); - } - - public BlockBookshelf() { - this(0); - } +public class BlockBookshelf extends BlockSolid { @Override public String getName() { @@ -56,7 +47,7 @@ public int getBurnAbility() { @Override public Item[] getDrops(Item item) { return new Item[]{ - new ItemBook(0, 3) + Item.get(Item.BOOK, 0, 3) }; } diff --git a/src/main/java/cn/nukkit/block/BlockBorder.java b/src/main/java/cn/nukkit/block/BlockBorder.java new file mode 100644 index 00000000000..d866be7c309 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBorder.java @@ -0,0 +1,41 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; + +public class BlockBorder extends BlockTransparent { + + @Override + public int getId() { + return BORDER_BLOCK; + } + + @Override + public double getHardness() { + return -1; + } + + @Override + public double getResistance() { + return 18000000; + } + + @Override + public String getName() { + return "Border"; + } + + @Override + public boolean isBreakable(Item item) { + return false; + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBrewingStand.java b/src/main/java/cn/nukkit/block/BlockBrewingStand.java index b2d48d44645..73473046bfc 100644 --- a/src/main/java/cn/nukkit/block/BlockBrewingStand.java +++ b/src/main/java/cn/nukkit/block/BlockBrewingStand.java @@ -1,11 +1,11 @@ package cn.nukkit.block; + import cn.nukkit.Player; import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.blockentity.BlockEntityBrewingStand; import cn.nukkit.inventory.ContainerInventory; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemBrewingStand; import cn.nukkit.item.ItemTool; import cn.nukkit.math.BlockFace; import cn.nukkit.nbt.tag.CompoundTag; @@ -63,53 +63,39 @@ public int getLightLevel() { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - if (!block.down().isTransparent()) { - getLevel().setBlock(block, this, true, true); - - CompoundTag nbt = new CompoundTag() - .putList(new ListTag<>("Items")) - .putString("id", BlockEntity.BREWING_STAND) - .putInt("x", (int) this.x) - .putInt("y", (int) this.y) - .putInt("z", (int) this.z); - - if (item.hasCustomName()) { - nbt.putString("CustomName", item.getCustomName()); - } + this.getLevel().setBlock(this, this, true, true); - if (item.hasCustomBlockData()) { - Map customData = item.getCustomBlockData().getTags(); - for (Map.Entry tag : customData.entrySet()) { - nbt.put(tag.getKey(), tag.getValue()); - } - } + CompoundTag nbt = new CompoundTag() + .putList(new ListTag<>("Items")) + .putString("id", BlockEntity.BREWING_STAND) + .putInt("x", (int) this.x) + .putInt("y", (int) this.y) + .putInt("z", (int) this.z); - BlockEntityBrewingStand brewing = (BlockEntityBrewingStand) BlockEntity.createBlockEntity(BlockEntity.BREWING_STAND, getLevel().getChunk((int) this.x >> 4, (int) this.z >> 4), nbt); - return brewing != null; + if (item.hasCustomName()) { + nbt.putString("CustomName", item.getCustomName()); } - return false; + + if (item.hasCustomBlockData()) { + Map customData = item.getCustomBlockData().getTags(); + for (Map.Entry tag : customData.entrySet()) { + nbt.put(tag.getKey(), tag.getValue()); + } + } + + BlockEntityBrewingStand brewing = (BlockEntityBrewingStand) BlockEntity.createBlockEntity(BlockEntity.BREWING_STAND, this.getChunk(), nbt); + return brewing != null; } @Override public boolean onActivate(Item item, Player player) { if (player != null) { BlockEntity t = getLevel().getBlockEntity(this); - BlockEntityBrewingStand brewing; - if (t instanceof BlockEntityBrewingStand) { - brewing = (BlockEntityBrewingStand) t; - } else { - CompoundTag nbt = new CompoundTag() - .putList(new ListTag<>("Items")) - .putString("id", BlockEntity.BREWING_STAND) - .putInt("x", (int) this.x) - .putInt("y", (int) this.y) - .putInt("z", (int) this.z); - brewing = (BlockEntityBrewingStand) BlockEntity.createBlockEntity(BlockEntity.BREWING_STAND, this.getLevel().getChunk((int) (this.x) >> 4, (int) (this.z) >> 4), nbt); - if (brewing == null) { - return false; - } + if (!(t instanceof BlockEntityBrewingStand)) { + return false; } + BlockEntityBrewingStand brewing = (BlockEntityBrewingStand) t; if (brewing.namedTag.contains("Lock") && brewing.namedTag.get("Lock") instanceof StringTag) { if (!brewing.namedTag.getString("Lock").equals(item.getCustomName())) { return false; @@ -124,12 +110,12 @@ public boolean onActivate(Item item, Player player) { @Override public Item toItem() { - return new ItemBrewingStand(); + return Item.get(Item.BREWING_STAND); } @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; @@ -193,4 +179,14 @@ public int getComparatorInputOverride() { public boolean canHarvestWithHand() { return false; } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean canBePushed() { + return false; // prevent item loss issue with pistons until a working implementation + } } diff --git a/src/main/java/cn/nukkit/block/BlockBricks.java b/src/main/java/cn/nukkit/block/BlockBricks.java index de1eb072dbd..fadb8d5526f 100644 --- a/src/main/java/cn/nukkit/block/BlockBricks.java +++ b/src/main/java/cn/nukkit/block/BlockBricks.java @@ -9,9 +9,6 @@ */ public class BlockBricks extends BlockSolid { - public BlockBricks() { - } - @Override public String getName() { return "Bricks"; @@ -39,7 +36,7 @@ public int getToolType() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ Item.get(Item.BRICKS_BLOCK, 0, 1) }; @@ -49,12 +46,12 @@ public Item[] getDrops(Item item) { } @Override - public BlockColor getColor() { - return BlockColor.RED_BLOCK_COLOR; + public boolean canHarvestWithHand() { + return false; } @Override - public boolean canHarvestWithHand() { - return false; + public BlockColor getColor() { + return BlockColor.RED_BLOCK_COLOR; } } diff --git a/src/main/java/cn/nukkit/block/BlockBricksBlackstonePolished.java b/src/main/java/cn/nukkit/block/BlockBricksBlackstonePolished.java new file mode 100644 index 00000000000..6672abea2fa --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBricksBlackstonePolished.java @@ -0,0 +1,14 @@ +package cn.nukkit.block; + +public class BlockBricksBlackstonePolished extends BlockBlackstonePolished { + + @Override + public int getId() { + return POLISHED_BLACKSTONE_BRICKS; + } + + @Override + public String getName() { + return "Polished Blackstone Bricks"; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockBricksBlackstonePolishedCracked.java b/src/main/java/cn/nukkit/block/BlockBricksBlackstonePolishedCracked.java new file mode 100644 index 00000000000..aeef4f683d9 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBricksBlackstonePolishedCracked.java @@ -0,0 +1,14 @@ +package cn.nukkit.block; + +public class BlockBricksBlackstonePolishedCracked extends BlockBricksBlackstonePolished { + + @Override + public int getId() { + return CRACKED_POLISHED_BLACKSTONE_BRICKS; + } + + @Override + public String getName() { + return "Cracked Polished Blackstone Bricks"; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBricksDeepslate.java b/src/main/java/cn/nukkit/block/BlockBricksDeepslate.java new file mode 100644 index 00000000000..0400c136f45 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBricksDeepslate.java @@ -0,0 +1,50 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockBricksDeepslate extends BlockSolid { + + public BlockBricksDeepslate() { + } + + @Override + public int getId() { + return DEEPSLATE_BRICKS; + } + + @Override + public String getName() { + return "Deepslate Bricks"; + } + + @Override + public double getHardness() { + return 3.5; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_WOODEN; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBricksDeepslateCracked.java b/src/main/java/cn/nukkit/block/BlockBricksDeepslateCracked.java new file mode 100644 index 00000000000..2fe2a6fc937 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBricksDeepslateCracked.java @@ -0,0 +1,18 @@ +package cn.nukkit.block; + +public class BlockBricksDeepslateCracked extends BlockBricksDeepslate { + + public BlockBricksDeepslateCracked() { + // Does nothing + } + + @Override + public int getId() { + return CRACKED_DEEPSLATE_BRICKS; + } + + @Override + public String getName() { + return "Cracked Deepslate Bricks"; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBricksEndStone.java b/src/main/java/cn/nukkit/block/BlockBricksEndStone.java index 09684d99c3c..abc6095e4ec 100644 --- a/src/main/java/cn/nukkit/block/BlockBricksEndStone.java +++ b/src/main/java/cn/nukkit/block/BlockBricksEndStone.java @@ -6,9 +6,6 @@ public class BlockBricksEndStone extends BlockSolid { - public BlockBricksEndStone() { - } - @Override public String getName() { return "End Stone Bricks"; @@ -36,7 +33,7 @@ public double getResistance() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ Item.get(Item.END_BRICKS, 0, 1) }; diff --git a/src/main/java/cn/nukkit/block/BlockBricksNether.java b/src/main/java/cn/nukkit/block/BlockBricksNether.java index 2dab022be92..ac533f6f13c 100644 --- a/src/main/java/cn/nukkit/block/BlockBricksNether.java +++ b/src/main/java/cn/nukkit/block/BlockBricksNether.java @@ -10,9 +10,6 @@ */ public class BlockBricksNether extends BlockSolid { - public BlockBricksNether() { - } - @Override public String getName() { return "Nether Brick"; @@ -40,7 +37,7 @@ public double getResistance() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ Item.get(Item.NETHER_BRICKS, 0, 1) }; diff --git a/src/main/java/cn/nukkit/block/BlockBricksNetherChiseled.java b/src/main/java/cn/nukkit/block/BlockBricksNetherChiseled.java new file mode 100644 index 00000000000..e9fe3a42f5a --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBricksNetherChiseled.java @@ -0,0 +1,14 @@ +package cn.nukkit.block; + +public class BlockBricksNetherChiseled extends BlockNetherBrick { + + @Override + public int getId() { + return CHISELED_NETHER_BRICKS; + } + + @Override + public String getName() { + return "Chiseled Nether Bricks"; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBricksNetherCracked.java b/src/main/java/cn/nukkit/block/BlockBricksNetherCracked.java new file mode 100644 index 00000000000..b91c793f11a --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBricksNetherCracked.java @@ -0,0 +1,14 @@ +package cn.nukkit.block; + +public class BlockBricksNetherCracked extends BlockNetherBrick { + + @Override + public int getId() { + return CRACKED_NETHER_BRICKS; + } + + @Override + public String getName() { + return "Cracked Nether Bricks"; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBricksRedNether.java b/src/main/java/cn/nukkit/block/BlockBricksRedNether.java index d69d0358039..8ce2ad7cad1 100644 --- a/src/main/java/cn/nukkit/block/BlockBricksRedNether.java +++ b/src/main/java/cn/nukkit/block/BlockBricksRedNether.java @@ -1,14 +1,10 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemTool; import cn.nukkit.utils.BlockColor; public class BlockBricksRedNether extends BlockNetherBrick { - public BlockBricksRedNether() { - } - @Override public String getName() { return "Red Nether Bricks"; @@ -21,7 +17,7 @@ public int getId() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ Item.get(Item.RED_NETHER_BRICK, 0, 1) }; diff --git a/src/main/java/cn/nukkit/block/BlockBricksStone.java b/src/main/java/cn/nukkit/block/BlockBricksStone.java index 358a5729928..1ad784a35eb 100644 --- a/src/main/java/cn/nukkit/block/BlockBricksStone.java +++ b/src/main/java/cn/nukkit/block/BlockBricksStone.java @@ -4,7 +4,7 @@ import cn.nukkit.item.ItemTool; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockBricksStone extends BlockSolidMeta { @@ -13,6 +13,7 @@ public class BlockBricksStone extends BlockSolidMeta { public static final int CRACKED = 2; public static final int CHISELED = 3; + public BlockBricksStone() { this(0); } @@ -36,21 +37,21 @@ public double getResistance() { return 30; } + private static final String[] NAMES = { + "Stone Bricks", + "Mossy Stone Bricks", + "Cracked Stone Bricks", + "Chiseled Stone Bricks" + }; + @Override public String getName() { - String[] names = new String[]{ - "Stone Bricks", - "Mossy Stone Bricks", - "Cracked Stone Bricks", - "Chiseled Stone Bricks" - }; - - return names[this.getDamage() & 0x03]; + return NAMES[this.getDamage() & 0x03]; } @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ Item.get(Item.STONE_BRICKS, this.getDamage() & 0x03, 1) }; diff --git a/src/main/java/cn/nukkit/block/BlockBubbleColumn.java b/src/main/java/cn/nukkit/block/BlockBubbleColumn.java new file mode 100644 index 00000000000..c5c22d59127 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBubbleColumn.java @@ -0,0 +1,180 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.Server; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.EntityCreature; +import cn.nukkit.entity.item.EntityItem; +import cn.nukkit.event.block.BlockFormEvent; +import cn.nukkit.item.Item; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; + +public class BlockBubbleColumn extends BlockTransparentMeta { + + public static final int DIRECTION_UP = 0; + public static final int DIRECTION_DOWN = 1; + + public BlockBubbleColumn() { + this(0); + } + + public BlockBubbleColumn(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Bubble Column"; + } + + @Override + public int getId() { + return BUBBLE_COLUMN; + } + + @Override + public double getResistance() { + return 100; + } + + @Override + public double getHardness() { + return 0; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public boolean canBeReplaced() { + return true; + } + + @Override + public boolean canPassThrough() { + return true; + } + + @Override + public boolean isBreakable(Item item) { + return false; + } + + @Override + public Item toItem() { + return Item.get(0); + } + + @Override + public Item[] getDrops(Item item) { + return new Item[0]; + } + + @Override + public boolean breakWhenPushed() { + return true; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (this.getLevel().setBlock(this, this, true, true)) { + this.getLevel().setBlock(this, Block.LAYER_WATERLOGGED, Block.get(Block.STILL_WATER), true, true); + return true; + } + return false; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.FLOW_INTO_BLOCK; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + Block down = this.down(); + + if (down.getId() == BUBBLE_COLUMN) { + if (down.getDamage() != this.getDamage()) { + this.getLevel().setBlock(this, down, false, true); + } + } else if (down.getId() == SOUL_SAND) { + if (this.getDamage() != DIRECTION_UP) { + this.setDamage(DIRECTION_UP); + this.getLevel().setBlock(this, this, false, true); + } + } else if (down.getId() == MAGMA) { + if (this.getDamage() != DIRECTION_DOWN) { + this.setDamage(DIRECTION_DOWN); + this.getLevel().setBlock(this, this, false, true); + } + } else { + this.getLevel().setBlock(this, Block.get(WATER), false, true); + return type; + } + + Block up = this.up(); + if (up instanceof BlockWater && (up.getDamage() == 0 || up.getDamage() == 8)) { + BlockFormEvent event = new BlockFormEvent(up, Block.get(BUBBLE_COLUMN, this.getDamage())); + Server.getInstance().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + this.getLevel().setBlock(up, event.getNewState(), false, true); + } + } + + return type; + } + + return 0; + } + + @Override + public boolean hasEntityCollision() { + return true; + } + + @Override + public void onEntityCollide(Entity entity) { + if (entity.canBeMovedByCurrents()) { + if (this.level.getBlockIdAt((int) this.x, (int) this.y + 1, (int) this.z) == AIR) { + double motY = entity.motionY; + + if (this.getDamage() == 1) { + motY = Math.max(-0.9, motY - 0.03); + } else { + if ((entity instanceof EntityCreature) && motY < -0.64f) { + motY = -0.16f; + } + motY = Math.min(1.8, motY + 0.1); + } + + if (entity instanceof Player) { + ((Player) entity).setMotionLocally(entity.getMotion().setY(motY)); + } else { + entity.motionY = motY; + } + } else { + double motY = entity.motionY; + + if (this.getDamage() == 1) { + motY = Math.max(-0.3, motY - 0.3); + } else { + motY = Math.min(0.7, motY + 0.06); + } + + if (entity instanceof Player) { + ((Player) entity).setMotionLocally(entity.getMotion().setY(motY)); + } else { + entity.motionY = motY; + } + } + if (entity instanceof EntityItem) { + entity.collisionBlocks = null; + } + } + } +} diff --git a/src/main/java/cn/nukkit/block/BlockBuddingAmethyst.java b/src/main/java/cn/nukkit/block/BlockBuddingAmethyst.java new file mode 100644 index 00000000000..a17b8d7d3d0 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockBuddingAmethyst.java @@ -0,0 +1,96 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.event.block.BlockSpreadEvent; +import cn.nukkit.item.Item; +import cn.nukkit.level.Level; +import cn.nukkit.level.particle.DestroyBlockParticle; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.BlockColor; + +import java.util.concurrent.ThreadLocalRandom; + +public class BlockBuddingAmethyst extends BlockSolid { + + public BlockBuddingAmethyst() { + } + + @Override + public int getId() { + return BUDDING_AMETHYST; + } + + @Override + public double getResistance() { + return 1.5; + } + + @Override + public double getHardness() { + return 1.5; + } + + @Override + public String getName() { + return "Budding Amethyst"; + } + + @Override + public int onUpdate(int type) { + if (type != Level.BLOCK_UPDATE_RANDOM || ThreadLocalRandom.current().nextInt(4) != 0) { + return type; + } + + BlockFace face = BlockFace.values()[ThreadLocalRandom.current().nextInt(BlockFace.values().length)]; + Block block = this.getSide(face); + + BlockAmethystBud targetBlock = null; + if (block.getId() == AIR || (Block.isWater(block.getId()) && block.getDamage() == 8)) { + targetBlock = (BlockAmethystBud) Block.get(SMALL_AMETHYST_BUD); + } else if (block.getId() == SMALL_AMETHYST_BUD && ((BlockAmethystBud) block).getBlockFace() == face) { + targetBlock = (BlockAmethystBud) Block.get(MEDIUM_AMETHYST_BUD); + } else if (block.getId() == MEDIUM_AMETHYST_BUD && ((BlockAmethystBud) block).getBlockFace() == face) { + targetBlock = (BlockAmethystBud) Block.get(LARGE_AMETHYST_BUD); + } else if (block.getId() == LARGE_AMETHYST_BUD && ((BlockAmethystBud) block).getBlockFace() == face) { + targetBlock = (BlockAmethystBud) Block.get(AMETHYST_CLUSTER); + } + + if (targetBlock != null) { + targetBlock.setBlockFace(face); + + BlockSpreadEvent event = new BlockSpreadEvent(block, this, targetBlock); + this.getLevel().getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + this.getLevel().setBlock(block, event.getNewState(), false, true); + } + } + return type; + } + + @Override + public boolean onBreak(Item item, Player player) { + for (BlockFace face : BlockFace.values()) { + Block side = this.getSide(face); + if (side instanceof BlockAmethystBud && ((BlockAmethystBud) side).getBlockFace() == face) { + this.getLevel().setBlock(side, Block.get(BlockID.AIR), true, true); + this.getLevel().addParticle(new DestroyBlockParticle(side.add(0.5), side)); + } + } + return super.onBreak(item, player); + } + + @Override + public boolean breakWhenPushed() { + return true; + } + + @Override + public boolean canSilkTouch() { + return true; + } + + @Override + public BlockColor getColor() { + return BlockColor.PURPLE_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockButton.java b/src/main/java/cn/nukkit/block/BlockButton.java index 7ce86e1beb3..fa08018df5b 100644 --- a/src/main/java/cn/nukkit/block/BlockButton.java +++ b/src/main/java/cn/nukkit/block/BlockButton.java @@ -3,10 +3,9 @@ import cn.nukkit.Player; import cn.nukkit.event.block.BlockRedstoneEvent; import cn.nukkit.item.Item; -import cn.nukkit.level.GlobalBlockPalette; +import cn.nukkit.item.ItemBlock; import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; -import cn.nukkit.math.Vector3; import cn.nukkit.network.protocol.LevelSoundEventPacket; import cn.nukkit.utils.Faceable; @@ -35,12 +34,12 @@ public double getHardness() { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - if (target.isTransparent()) { + this.setDamage(face.getIndex()); + if (!isSupportValid(this.getSide(this.getFacing().getOpposite()))) { return false; } - this.setDamage(face.getIndex()); - this.level.setBlock(block, this, true, true); + this.getLevel().setBlock(this, this, true, true); return true; } @@ -58,19 +57,18 @@ public boolean onActivate(Item item, Player player) { this.level.getServer().getPluginManager().callEvent(new BlockRedstoneEvent(this, 0, 15)); this.setDamage(this.getDamage() ^ 0x08); this.level.setBlock(this, this, true, false); - this.level.addLevelSoundEvent(this.add(0.5, 0.5, 0.5), LevelSoundEventPacket.SOUND_POWER_ON, GlobalBlockPalette.getOrCreateRuntimeId(this.getId(), this.getDamage())); + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_POWER_ON); this.level.scheduleUpdate(this, 30); - Vector3 pos = getLocation(); - level.updateAroundRedstone(pos, null); - level.updateAroundRedstone(pos.getSide(getFacing().getOpposite()), null); + level.updateAroundRedstone(this, null); + level.updateAroundRedstone(getSideVec(getFacing().getOpposite()), null); return true; } @Override public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_NORMAL) { - if (this.getSide(getFacing().getOpposite()).isTransparent()) { + if (!isSupportValid(this.getSide(this.getFacing().getOpposite()))) { this.level.useBreakOn(this, Item.get(Item.WOODEN_PICKAXE)); return Level.BLOCK_UPDATE_NORMAL; } @@ -80,11 +78,10 @@ public int onUpdate(int type) { this.setDamage(this.getDamage() ^ 0x08); this.level.setBlock(this, this, true, false); - this.level.addLevelSoundEvent(this.add(0.5, 0.5, 0.5), LevelSoundEventPacket.SOUND_POWER_OFF, GlobalBlockPalette.getOrCreateRuntimeId(this.getId(), this.getDamage())); + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_POWER_OFF); - Vector3 pos = getLocation(); - level.updateAroundRedstone(pos, null); - level.updateAroundRedstone(pos.getSide(getFacing().getOpposite()), null); + level.updateAroundRedstone(this, null); + level.updateAroundRedstone(getSideVec(getFacing().getOpposite()), null); } return Level.BLOCK_UPDATE_SCHEDULED; @@ -93,6 +90,16 @@ public int onUpdate(int type) { return 0; } + private boolean isSupportValid(Block block) { + if (!block.isTransparent()) { + return true; + } + if (this.getFacing() == BlockFace.UP) { + return Block.canStayOnFullSolid(block); + } + return Block.canConnectToFullSolid(block); + } + public boolean isActivated() { return ((this.getDamage() & 0x08) == 0x08); } @@ -126,11 +133,26 @@ public boolean onBreak(Item item) { @Override public Item toItem() { - return Item.get(this.getId(), 0); + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override public BlockFace getBlockFace() { return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean canBeFlowedInto() { + return false; + } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockButtonAcacia.java b/src/main/java/cn/nukkit/block/BlockButtonAcacia.java new file mode 100644 index 00000000000..e434650f9f8 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockButtonAcacia.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockButtonAcacia extends BlockButtonWooden { + + public BlockButtonAcacia() { + this(0); + } + + public BlockButtonAcacia(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Acacia Button"; + } + + @Override + public int getId() { + return ACACIA_BUTTON; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockButtonBirch.java b/src/main/java/cn/nukkit/block/BlockButtonBirch.java new file mode 100644 index 00000000000..2a80276e790 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockButtonBirch.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockButtonBirch extends BlockButtonWooden { + + public BlockButtonBirch() { + this(0); + } + + public BlockButtonBirch(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Birch Button"; + } + + @Override + public int getId() { + return BIRCH_BUTTON; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockButtonCrimson.java b/src/main/java/cn/nukkit/block/BlockButtonCrimson.java new file mode 100644 index 00000000000..426e22e2b91 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockButtonCrimson.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockButtonCrimson extends BlockButtonWooden { + + public BlockButtonCrimson() { + this(0); + } + + public BlockButtonCrimson(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Crimson Button"; + } + + @Override + public int getId() { + return CRIMSON_BUTTON; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockButtonDarkOak.java b/src/main/java/cn/nukkit/block/BlockButtonDarkOak.java new file mode 100644 index 00000000000..c886ca68b20 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockButtonDarkOak.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockButtonDarkOak extends BlockButtonWooden { + + public BlockButtonDarkOak() { + this(0); + } + + public BlockButtonDarkOak(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Dark Oak Button"; + } + + @Override + public int getId() { + return DARK_OAK_BUTTON; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockButtonJungle.java b/src/main/java/cn/nukkit/block/BlockButtonJungle.java new file mode 100644 index 00000000000..81f68c4e94e --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockButtonJungle.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockButtonJungle extends BlockButtonWooden { + + public BlockButtonJungle() { + this(0); + } + + public BlockButtonJungle(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Jungle Button"; + } + + @Override + public int getId() { + return JUNGLE_BUTTON; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockButtonPolishedBlackstone.java b/src/main/java/cn/nukkit/block/BlockButtonPolishedBlackstone.java new file mode 100644 index 00000000000..53718653044 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockButtonPolishedBlackstone.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockButtonPolishedBlackstone extends BlockButtonStone { + + public BlockButtonPolishedBlackstone() { + this(0); + } + + public BlockButtonPolishedBlackstone(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Polished Blackstone Button"; + } + + @Override + public int getId() { + return POLISHED_BLACKSTONE_BUTTON; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockButtonSpruce.java b/src/main/java/cn/nukkit/block/BlockButtonSpruce.java new file mode 100644 index 00000000000..38c7a7ef929 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockButtonSpruce.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockButtonSpruce extends BlockButtonWooden { + + public BlockButtonSpruce() { + this(0); + } + + public BlockButtonSpruce(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Spruce Button"; + } + + @Override + public int getId() { + return SPRUCE_BUTTON; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockButtonStone.java b/src/main/java/cn/nukkit/block/BlockButtonStone.java index f591330ca4d..1657ad1f477 100644 --- a/src/main/java/cn/nukkit/block/BlockButtonStone.java +++ b/src/main/java/cn/nukkit/block/BlockButtonStone.java @@ -33,7 +33,7 @@ public int getToolType() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ this.toItem() }; diff --git a/src/main/java/cn/nukkit/block/BlockButtonWarped.java b/src/main/java/cn/nukkit/block/BlockButtonWarped.java new file mode 100644 index 00000000000..ddad2f9ee2e --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockButtonWarped.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockButtonWarped extends BlockButtonWooden { + + public BlockButtonWarped() { + this(0); + } + + public BlockButtonWarped(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Warped Button"; + } + + @Override + public int getId() { + return WARPED_BUTTON; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockButtonWooden.java b/src/main/java/cn/nukkit/block/BlockButtonWooden.java index b5d8fb2944a..490fa749034 100644 --- a/src/main/java/cn/nukkit/block/BlockButtonWooden.java +++ b/src/main/java/cn/nukkit/block/BlockButtonWooden.java @@ -22,7 +22,7 @@ public int getId() { @Override public String getName() { - return "Wooden Button"; + return "Oak Button"; } @Override diff --git a/src/main/java/cn/nukkit/block/BlockCactus.java b/src/main/java/cn/nukkit/block/BlockCactus.java index 9cdc6921e43..2c3aca1a550 100644 --- a/src/main/java/cn/nukkit/block/BlockCactus.java +++ b/src/main/java/cn/nukkit/block/BlockCactus.java @@ -8,10 +8,8 @@ import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; import cn.nukkit.item.Item; import cn.nukkit.level.Level; -import cn.nukkit.math.AxisAlignedBB; +import cn.nukkit.level.format.FullChunk; import cn.nukkit.math.BlockFace; -import cn.nukkit.math.SimpleAxisAlignedBB; -import cn.nukkit.math.Vector3; import cn.nukkit.utils.BlockColor; /** @@ -47,16 +45,11 @@ public boolean hasEntityCollision() { return true; } - @Override + /*@Override public double getMinX() { return this.x + 0.0625; } - @Override - public double getMinY() { - return this.y; - } - @Override public double getMinZ() { return this.z + 0.0625; @@ -67,19 +60,18 @@ public double getMaxX() { return this.x + 0.9375; } - @Override - public double getMaxY() { - return this.y + 0.9375; - } - @Override public double getMaxZ() { return this.z + 0.9375; - } + }*/ + + // Hack: Fix entity collisions + // No need for separate collision box + // Y-collisions need another fix anyway @Override - protected AxisAlignedBB recalculateCollisionBoundingBox() { - return new SimpleAxisAlignedBB(this.x, this.y, this.z, this.x + 1, this.y + 1, this.z + 1); + public double getMaxY() { + return this.y + 0.9375; } @Override @@ -104,13 +96,14 @@ public int onUpdate(int type) { } else if (type == Level.BLOCK_UPDATE_RANDOM) { if (down().getId() != CACTUS) { if (this.getDamage() == 0x0F) { + FullChunk chunk = this.level.getChunk((int) x >> 4, (int) z >> 4); for (int y = 1; y < 3; ++y) { - Block b = this.getLevel().getBlock(new Vector3(this.x, this.y + y, this.z)); + Block b = this.getLevel().getBlock(chunk, (int) this.x, (int) this.y + y, (int) this.z, true); if (b.getId() == AIR) { - BlockGrowEvent event = new BlockGrowEvent(b, Block.get(BlockID.CACTUS)); + BlockGrowEvent event = new BlockGrowEvent(b, Block.get(CACTUS)); Server.getInstance().getPluginManager().callEvent(event); if (!event.isCancelled()) { - this.getLevel().setBlock(b, event.getNewState(), true); + this.getLevel().setBlock(b, event.getNewState(), true, true); } break; } @@ -119,7 +112,7 @@ public int onUpdate(int type) { } else { this.setDamage(this.getDamage() + 1); } - this.getLevel().setBlock(this, this); + this.level.setBlock((int) this.x, (int) this.y, (int) this.z, BlockLayer.NORMAL, this, false, true, false); // No need to send this to client } } @@ -135,8 +128,7 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl Block block2 = west(); Block block3 = east(); if (block0.canBeFlowedInto() && block1.canBeFlowedInto() && block2.canBeFlowedInto() && block3.canBeFlowedInto()) { - this.getLevel().setBlock(this, this, true); - + this.getLevel().setBlock(this, this, true, true); return true; } } @@ -152,11 +144,21 @@ public String getName() { public BlockColor getColor() { return BlockColor.FOLIAGE_BLOCK_COLOR; } - + @Override public Item[] getDrops(Item item) { return new Item[]{ - Item.get(Item.CACTUS, 0, 1) + Item.get(Item.CACTUS, 0, 1) }; } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockCake.java b/src/main/java/cn/nukkit/block/BlockCake.java index 58c3bdfaa75..f2a9a56f7cd 100644 --- a/src/main/java/cn/nukkit/block/BlockCake.java +++ b/src/main/java/cn/nukkit/block/BlockCake.java @@ -2,10 +2,10 @@ import cn.nukkit.Player; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemCake; import cn.nukkit.item.food.Food; import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; +import cn.nukkit.network.protocol.LevelSoundEventPacket; import cn.nukkit.utils.BlockColor; /** @@ -43,17 +43,12 @@ public double getHardness() { @Override public double getResistance() { - return 2.5; + return 0.5; } @Override public double getMinX() { - return this.x + (1 + getDamage() * 2) / 16; - } - - @Override - public double getMinY() { - return this.y; + return this.x + ((1 + (getDamage() << 1)) >> 4); } @Override @@ -79,8 +74,7 @@ public double getMaxZ() { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { if (down().getId() != Block.AIR) { - getLevel().setBlock(block, this, true, true); - + this.getLevel().setBlock(this, this, true, true); return true; } return false; @@ -106,12 +100,12 @@ public Item[] getDrops(Item item) { @Override public Item toItem() { - return new ItemCake(); + return Item.get(Item.CAKE); } @Override public boolean onActivate(Item item, Player player) { - if (player != null && (player.getFoodData().getLevel() < player.getFoodData().getMaxLevel() || player.isCreative() || player.getServer().getDifficulty() == 0)) { + if (player != null && player.canEat(false)) { if (getDamage() <= 0x06) setDamage(getDamage() + 1); if (getDamage() >= 0x06) { getLevel().setBlock(this, Block.get(BlockID.AIR), true); @@ -119,6 +113,7 @@ public boolean onActivate(Item item, Player player) { Food.getByRelative(this).eatenBy(player); getLevel().setBlock(this, this, true); } + player.getLevel().addLevelSoundEvent(player, LevelSoundEventPacket.SOUND_BURP); return true; } return false; @@ -130,10 +125,20 @@ public BlockColor getColor() { } public int getComparatorInputOverride() { - return (7 - this.getDamage()) * 2; + return (7 - this.getDamage()) << 1; } public boolean hasComparatorInputOverride() { return true; } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockCalcite.java b/src/main/java/cn/nukkit/block/BlockCalcite.java new file mode 100644 index 00000000000..68866eb270c --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCalcite.java @@ -0,0 +1,46 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; + +public class BlockCalcite extends BlockSolid { + + public BlockCalcite() { + // Does nothing + } + + @Override + public String getName() { + return "Calcite"; + } + + @Override + public int getId() { + return CALCITE; + } + + @Override + public double getHardness() { + return 0.75; + } + + @Override + public double getResistance() { + return 0.75; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + // TODO: + /*@Override + public boolean isLavaResistant() { + return true; + }*/ +} diff --git a/src/main/java/cn/nukkit/block/BlockCampfire.java b/src/main/java/cn/nukkit/block/BlockCampfire.java new file mode 100644 index 00000000000..2e5b9ce443b --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCampfire.java @@ -0,0 +1,261 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.blockentity.BlockEntity; +import cn.nukkit.blockentity.BlockEntityCampfire; +import cn.nukkit.entity.Entity; +import cn.nukkit.event.entity.EntityDamageByBlockEvent; +import cn.nukkit.event.entity.EntityDamageEvent; +import cn.nukkit.inventory.CampfireInventory; +import cn.nukkit.inventory.CampfireRecipe; +import cn.nukkit.inventory.ContainerInventory; +import cn.nukkit.item.*; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.Tag; +import cn.nukkit.network.protocol.LevelSoundEventPacket; +import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.Faceable; + +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; + +public class BlockCampfire extends BlockTransparentMeta implements Faceable { + + public BlockCampfire() { + this(0); + } + + public BlockCampfire(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Campfire"; + } + + @Override + public int getId() { + return CAMPFIRE_BLOCK; + } + + @Override + public int getLightLevel() { + return isExtinguished() ? 0 : 15; + } + + @Override + public double getResistance() { + return 2; + } + + @Override + public double getHardness() { + return 2; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_AXE; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public Item[] getDrops(Item item) { + return new Item[] {Item.get(ItemID.COAL, 0, 1 + ThreadLocalRandom.current().nextInt(1))}; + } + + @Override + public boolean canSilkTouch() { + return true; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (this.down().getId() == CAMPFIRE_BLOCK) { + return false; + } + + this.setDamage(player != null ? player.getDirection().getOpposite().getHorizontalIndex() : 0); + Block layer1 = block.getLevelBlock(BlockLayer.WATERLOGGED); + + boolean defaultLayerCheck = (block instanceof BlockWater && block.getDamage() == 0 || block.getDamage() >= 8) || block instanceof BlockIceFrosted; + boolean layer1Check = (layer1 instanceof BlockWater && layer1.getDamage() == 0 || layer1.getDamage() >= 8) || layer1 instanceof BlockIceFrosted; + if (defaultLayerCheck || layer1Check) { + this.setExtinguished(true); + this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_FIZZ); + this.level.setBlock(this, BlockLayer.WATERLOGGED, defaultLayerCheck ? block : layer1, false, false); + } else { + this.level.setBlock(this, BlockLayer.WATERLOGGED, Block.get(Block.AIR), false, false); + } + + this.getLevel().setBlock(this, this, true, true); + this.createBlockEntity(item); + return true; + } + + private BlockEntityCampfire createBlockEntity(Item item) { + CompoundTag nbt = new CompoundTag() + .putString("id", BlockEntity.CAMPFIRE) + .putInt("x", (int) this.x) + .putInt("y", (int) this.y) + .putInt("z", (int) this.z); + + if (item.hasCustomBlockData()) { + Map customData = item.getCustomBlockData().getTags(); + for (Map.Entry tag : customData.entrySet()) { + nbt.put(tag.getKey(), tag.getValue()); + } + } + + return (BlockEntityCampfire) BlockEntity.createBlockEntity(BlockEntity.CAMPFIRE, this.getChunk(), nbt); + } + + @Override + public boolean hasEntityCollision() { + return true; + } + + @Override + public void onEntityCollide(Entity entity) { + if (!this.isExtinguished() && !entity.isSneaking()) { + entity.attack(new EntityDamageByBlockEvent(this, entity, EntityDamageEvent.DamageCause.FIRE, this instanceof BlockCampfireSoul ? 2 : 1)); + } + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + if (!this.isExtinguished()) { + Block layer1 = this.getLevelBlock(BlockLayer.WATERLOGGED); + if (layer1 instanceof BlockWater || layer1 instanceof BlockIceFrosted) { + this.setExtinguished(true); + this.level.setBlock(this, this, true, true); + this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_FIZZ); + } + } + return type; + } + return 0; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (item.getId() == BlockID.AIR || item.getCount() <= 0) { + return false; + } + + BlockEntity entity = this.level.getBlockEntity(this); + if (!(entity instanceof BlockEntityCampfire)) { + return false; + } + + boolean itemUsed = false; + if (item.isShovel() && !this.isExtinguished()) { + this.setExtinguished(true); + this.level.setBlock(this, this, true, true); + this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_FIZZ); + itemUsed = true; + } else if (item.getId() == ItemID.FLINT_AND_STEEL || item.hasEnchantment(Enchantment.ID_FIRE_ASPECT)) { + item.useOn(this); + this.setExtinguished(false); + this.level.setBlock(this, this, true, true); + entity.scheduleUpdate(); + level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_IGNITE); + itemUsed = true; + } + + BlockEntityCampfire campfire = (BlockEntityCampfire) entity; + Item cloned = item.clone(); + cloned.setCount(1); + CampfireInventory inventory = campfire.getInventory(); + if (inventory.canAddItem(cloned)) { + CampfireRecipe recipe = this.level.getServer().getCraftingManager().matchCampfireRecipe(cloned); + if (recipe != null) { + inventory.addItem(cloned); + item.setCount(item.getCount() - 1); + return true; + } + } + + return itemUsed; + } + + @Override + public double getMaxY() { + return y + 0.5; + } + + @Override + public BlockColor getColor() { + return BlockColor.SPRUCE_BLOCK_COLOR; + } + + public boolean isExtinguished() { + return (this.getDamage() & 0x4) == 0x4; + } + + public void setExtinguished(boolean extinguished) { + this.setDamage((this.getDamage() & 0x3) | (extinguished? 0x4 : 0x0)); + } + + @Override + public BlockFace getBlockFace() { + return BlockFace.fromHorizontalIndex(getDamage() & 0x3); + } + + public void setBlockFace(BlockFace face) { + if (face == BlockFace.UP || face == BlockFace.DOWN) { + return; + } + + this.setDamage((this.getDamage() & 0x4) | face.getHorizontalIndex()); + } + + @Override + public Item toItem() { + return Item.get(ItemID.CAMPFIRE); + } + + public boolean hasComparatorInputOverride() { + return true; + } + + @Override + public int getComparatorInputOverride() { + BlockEntity blockEntity = this.level.getBlockEntity(this); + + if (blockEntity instanceof BlockEntityCampfire) { + return ContainerInventory.calculateRedstone(((BlockEntityCampfire) blockEntity).getInventory()); + } + + return super.getComparatorInputOverride(); + } + + @Override + public boolean breakWhenPushed() { + return true; + } + + @Override + public boolean canBePushed() { + return false; // prevent item loss issue with pistons until a working implementation + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCampfireSoul.java b/src/main/java/cn/nukkit/block/BlockCampfireSoul.java new file mode 100644 index 00000000000..893cd1734b5 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCampfireSoul.java @@ -0,0 +1,41 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemID; + +public class BlockCampfireSoul extends BlockCampfire { + + public BlockCampfireSoul() { + this(0); + } + + public BlockCampfireSoul(int meta) { + super(meta); + } + + @Override + public int getId() { + return SOUL_CAMPFIRE_BLOCK; + } + + @Override + public String getName() { + return "Soul Campfire"; + } + + @Override + public int getLightLevel() { + return isExtinguished()? 0 : 10; + } + + @Override + public Item toItem() { + return Item.get(ItemID.SOUL_CAMPFIRE); + } + + @Override + public Item[] getDrops(Item item) { + return new Item[]{ new ItemBlock(Block.get(Block.SOUL_SOIL, 0), 0) }; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCarpet.java b/src/main/java/cn/nukkit/block/BlockCarpet.java index 3cfa2db4e1d..87cf0709a33 100644 --- a/src/main/java/cn/nukkit/block/BlockCarpet.java +++ b/src/main/java/cn/nukkit/block/BlockCarpet.java @@ -3,7 +3,6 @@ import cn.nukkit.Player; import cn.nukkit.item.Item; import cn.nukkit.level.Level; -import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.math.BlockFace; import cn.nukkit.utils.BlockColor; import cn.nukkit.utils.DyeColor; @@ -13,6 +12,7 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockCarpet extends BlockFlowable { + public BlockCarpet() { this(0); } @@ -30,11 +30,6 @@ public int getId() { return CARPET; } - @Override - public double getHardness() { - return 0.1; - } - @Override public double getResistance() { return 0.5; @@ -47,7 +42,7 @@ public boolean isSolid() { @Override public String getName() { - return DyeColor.getByWoolData(getDamage()) + " Carpet"; + return DyeColor.getByWoolData(getDamage()).getName() + " Carpet"; } @Override @@ -55,11 +50,6 @@ public boolean canPassThrough() { return false; } - @Override - protected AxisAlignedBB recalculateBoundingBox() { - return this; - } - @Override public double getMaxY() { return this.y + 0.0625; @@ -69,7 +59,7 @@ public double getMaxY() { public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { Block down = this.down(); if (down.getId() != Item.AIR) { - this.getLevel().setBlock(block, this, true, true); + this.getLevel().setBlock(this, this, true, true); return true; } return false; @@ -97,4 +87,13 @@ public DyeColor getDyeColor() { return DyeColor.getByWoolData(getDamage()); } + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockCarrot.java b/src/main/java/cn/nukkit/block/BlockCarrot.java index f86a429c4c6..66d00118a05 100644 --- a/src/main/java/cn/nukkit/block/BlockCarrot.java +++ b/src/main/java/cn/nukkit/block/BlockCarrot.java @@ -1,9 +1,7 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemCarrot; - -import java.util.Random; +import cn.nukkit.utils.Utils; /** * @author Nukkit Project Team @@ -32,16 +30,16 @@ public int getId() { public Item[] getDrops(Item item) { if (getDamage() >= 0x07) { return new Item[]{ - new ItemCarrot(0, new Random().nextInt(3) + 1) + Item.get(Item.CARROT, 0, Utils.rand(1, 5)) }; } return new Item[]{ - new ItemCarrot() + Item.get(Item.CARROT) }; } @Override public Item toItem() { - return new ItemCarrot(); + return Item.get(Item.CARROT); } } diff --git a/src/main/java/cn/nukkit/block/BlockCartographyTable.java b/src/main/java/cn/nukkit/block/BlockCartographyTable.java new file mode 100644 index 00000000000..447373c3984 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCartographyTable.java @@ -0,0 +1,42 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockCartographyTable extends BlockSolid { + + @Override + public String getName() { + return "Cartography Table"; + } + + @Override + public int getId() { + return CARTOGRAPHY_TABLE; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_AXE; + } + + @Override + public double getResistance() { + return 12.5; + } + + @Override + public double getHardness() { + return 2.5; + } + + @Override + public BlockColor getColor() { + return BlockColor.WOOD_BLOCK_COLOR; + } + + @Override + public int getBurnChance() { + return 5; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCauldron.java b/src/main/java/cn/nukkit/block/BlockCauldron.java index d9bae0a4acb..9c8130b2453 100644 --- a/src/main/java/cn/nukkit/block/BlockCauldron.java +++ b/src/main/java/cn/nukkit/block/BlockCauldron.java @@ -6,18 +6,32 @@ import cn.nukkit.event.player.PlayerBucketEmptyEvent; import cn.nukkit.event.player.PlayerBucketFillEvent; import cn.nukkit.item.*; +import cn.nukkit.level.Level; +import cn.nukkit.level.Sound; +import cn.nukkit.level.biome.Biome; +import cn.nukkit.level.particle.SmokeParticle; import cn.nukkit.math.BlockFace; +import cn.nukkit.math.MathHelper; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.Tag; import cn.nukkit.network.protocol.LevelEventPacket; +import cn.nukkit.network.protocol.LevelSoundEventPacket; +import cn.nukkit.utils.BlockColor; import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; /** - * author: CreeperFace + * @author CreeperFace * Nukkit Project */ -public class BlockCauldron extends BlockSolidMeta { +public class BlockCauldron extends BlockTransparentMeta { + + /** + * Used to cache biome check for freezing + * 1 = can't freeze, 2 = can freeze + */ + private byte freezing; public BlockCauldron() { super(0); @@ -57,13 +71,22 @@ public boolean canBeActivated() { } public boolean isFull() { - return this.getDamage() == 0x06; + return (this.getDamage() & 0x06) == 0x06; } public boolean isEmpty() { return this.getDamage() == 0x00; } + public int getFillLevel() { + return (getDamage() & 0x6) >> 1; + } + + public void setFillLevel(int fillLevel) { + fillLevel = MathHelper.clamp(fillLevel, 0, 3); + setDamage(fillLevel << 1); + } + @Override public boolean onActivate(Item item, Player player) { BlockEntity be = this.level.getBlockEntity(this); @@ -89,14 +112,13 @@ public boolean onActivate(Item item, Player player) { this.level.getServer().getPluginManager().callEvent(ev); if (!ev.isCancelled()) { replaceBucket(item, player, ev.getItem()); - this.setDamage(0);//empty + this.setFillLevel(0);//empty this.level.setBlock(this, this, true); cauldron.clearCustomColor(); - this.getLevel().addLevelEvent(this.add(0.5, 0.375 + this.getDamage() * 0.125, 0.5), LevelEventPacket.EVENT_CAULDRON_TAKE_WATER); + this.getLevel().addSound(this, Sound.CAULDRON_TAKEWATER); } - } else if (item.getDamage() == 8) {//water bucket - - if (isFull() && !cauldron.isCustomColor() && !cauldron.hasPotion()) { + } else if (item.getDamage() == 8 || item.getDamage() == 10) {//water and lava buckets + if (isFull() && !cauldron.isCustomColor() && !cauldron.hasPotion() && item.getDamage() == 8) { break; } @@ -107,71 +129,142 @@ public boolean onActivate(Item item, Player player) { PlayerBucketEmptyEvent ev = new PlayerBucketEmptyEvent(player, this, null, item, bucket); this.level.getServer().getPluginManager().callEvent(ev); if (!ev.isCancelled()) { - replaceBucket(item, player, ev.getItem()); + if (player.isSurvival() || player.isAdventure()) { + replaceBucket(item, player, ev.getItem()); + } if (cauldron.hasPotion()) {//if has potion - this.setDamage(0);//empty - cauldron.setPotionId(0xffff);//reset potion - cauldron.setSplashPotion(false); - cauldron.clearCustomColor(); - this.level.setBlock(this, this, true); - this.level.addLevelEvent(this.add(0.5, 0.375 + this.getDamage() * 0.125, 0.5), LevelEventPacket.EVENT_SOUND_EXPLODE); - } else { - this.setDamage(6);//fill + clearWithFizz(cauldron); + } else if (item.getDamage() == 8) { //water bucket + this.setFillLevel(3);//fill cauldron.clearCustomColor(); this.level.setBlock(this, this, true); - this.level.addLevelEvent(this.add(0.5, 0.375 + this.getDamage() * 0.125, 0.5), LevelEventPacket.EVENT_SOUND_CAULDRON_FILL_WATER); + this.getLevel().addSound(this, Sound.CAULDRON_FILLWATER); + } else { // lava bucket + if (isEmpty()) { + BlockCauldronLava cauldronLava = new BlockCauldronLava(0xE); + cauldronLava.setFillLevel(3); + this.level.setBlock(this, cauldronLava, true, true); + cauldron.clearCustomColor(); + this.getLevel().addSound(this.add(0.5, 0.5, 0.5), Sound.BUCKET_EMPTY_LAVA); + } else { + clearWithFizz(cauldron); + } } //this.update(); } } break; - case Item.DYE: //TODO + case Item.DYE: + if (isEmpty() || cauldron.hasPotion()) { + break; + } + + if (player.isSurvival() || player.isAdventure()) { + item.count--; + } + + BlockColor color = new ItemDye(item.getDamage()).getDyeColor().getColor(); + if (!cauldron.isCustomColor()) { + cauldron.setCustomColor(color); + } else { + BlockColor current = cauldron.getCustomColor(); + BlockColor mixed = new BlockColor( + current.getRed() + ((color.getRed() - current.getRed()) >> 1), + current.getGreen() + ((color.getGreen() - current.getGreen()) >> 1), + current.getBlue() + ((color.getBlue() - current.getBlue()) >> 1) + ); + cauldron.setCustomColor(mixed); + } + this.level.addSound(this, Sound.CAULDRON_ADDDYE); break; case Item.LEATHER_CAP: case Item.LEATHER_TUNIC: case Item.LEATHER_PANTS: case Item.LEATHER_BOOTS: + case Item.LEATHER_HORSE_ARMOR: + if (isEmpty() || cauldron.hasPotion()) { + break; + } + + CompoundTag compoundTag = item.getNamedTag(); + if (compoundTag == null) compoundTag = new CompoundTag(); + if (cauldron.isCustomColor()) { + compoundTag.putInt("customColor", cauldron.getCustomColor().getRGB()); + } else { + compoundTag.remove("customColor"); + } + item.setCompoundTag(compoundTag); + player.getInventory().setItemInHand(item); + + setFillLevel(getFillLevel() - 1); + this.level.setBlock(this, this, true, true); + this.level.addSound(this, Sound.CAULDRON_DYEARMOR); break; case Item.POTION: + case Item.SPLASH_POTION: + case Item.LINGERING_POTION: + if (!isEmpty() && (cauldron.hasPotion() ? cauldron.getPotionId() != item.getDamage() : item.getDamage() != 0)) { + clearWithFizz(cauldron); + consumePotion(item, player); + break; + } if (isFull()) { break; } - this.setDamage(this.getDamage() + 1); - if (this.getDamage() > 0x06) - this.setDamage(0x06); - - if (item.getCount() == 1) { - player.getInventory().setItemInHand(new ItemBlock(Block.get(BlockID.AIR))); - } else if (item.getCount() > 1) { - item.setCount(item.getCount() - 1); - player.getInventory().setItemInHand(item); - - Item bottle = new ItemGlassBottle(); - if (player.getInventory().canAddItem(bottle)) { - player.getInventory().addItem(bottle); - } else { - player.getLevel().dropItem(player.add(0, 1.3, 0), bottle, player.getDirectionVector().multiply(0.4)); - } + if (item.getDamage() != 0 && isEmpty()) { + cauldron.setPotionId(item.getDamage()); } - - this.level.addLevelEvent(this.add(0.5, 0.375 + this.getDamage() * 0.125, 0.5), LevelEventPacket.EVENT_CAULDRON_FILL_POTION); + cauldron.setPotionType( + item.getId() == Item.POTION ? BlockEntityCauldron.POTION_TYPE_NORMAL : + item.getId() == Item.SPLASH_POTION ? BlockEntityCauldron.POTION_TYPE_SPLASH : + BlockEntityCauldron.POTION_TYPE_LINGERING + ); + cauldron.spawnToAll(); + + setFillLevel(getFillLevel() + 1); + this.level.setBlock(this, this, true); + consumePotion(item, player); + this.getLevel().addSound(this, Sound.CAULDRON_FILLPOTION); break; case Item.GLASS_BOTTLE: if (isEmpty()) { break; } - this.setDamage(this.getDamage() - 1); - if (this.getDamage() < 0x00) - this.setDamage(0x00); + int meta = cauldron.hasPotion() ? cauldron.getPotionId() : 0; + Item potion; + if (meta == 0) { + potion = Item.get(Item.POTION); + } else { + switch (cauldron.getPotionType()) { + case BlockEntityCauldron.POTION_TYPE_SPLASH: + potion = Item.get(Item.SPLASH_POTION, meta); + break; + case BlockEntityCauldron.POTION_TYPE_LINGERING: + potion = Item.get(Item.LINGERING_POTION, meta); + break; + case BlockEntityCauldron.POTION_TYPE_NORMAL: + default: + potion = Item.get(Item.POTION, meta); + break; + } + } + + setFillLevel(getFillLevel() - 1); + if (isEmpty()) { + cauldron.setPotionId(0xffff);//reset potion + cauldron.clearCustomColor(); + } + this.level.setBlock(this, this, true); - if (item.getCount() == 1) { - player.getInventory().setItemInHand(new ItemPotion()); + boolean consumeBottle = player.isSurvival() || player.isAdventure(); + if (consumeBottle && item.getCount() == 1) { + player.getInventory().setItemInHand(potion); } else if (item.getCount() > 1) { - item.setCount(item.getCount() - 1); - player.getInventory().setItemInHand(item); + if (consumeBottle) { + item.count--; + } - Item potion = new ItemPotion(); if (player.getInventory().canAddItem(potion)) { player.getInventory().addItem(potion); } else { @@ -179,7 +272,48 @@ public boolean onActivate(Item item, Player player) { } } - this.level.addLevelEvent(this.add(0.5, 0.375 + this.getDamage() * 0.125, 0.5), LevelEventPacket.EVENT_CAULDRON_TAKE_POTION); + this.getLevel().addSound(this, Sound.CAULDRON_TAKEPOTION); + break; + case Item.ARROW: + if (item.getDamage() > 1 || !cauldron.hasPotion()) { + break; + } + + if (!player.isCreative() && item.getCount() == 1) { + item.setDamage(potion2arrow(cauldron.getPotionId())); + player.getInventory().setItemInHand(item); + } else if (item.getCount() > 1) { + Item newItem = item.clone(); + newItem.setCount(1); + newItem.setDamage(potion2arrow(cauldron.getPotionId())); + + if (!player.isCreative()) { + item.count--; + } + + if (player.getInventory().canAddItem(newItem)) { + player.getInventory().addItem(newItem); + } else { + player.getLevel().dropItem(player.add(0, 1.3, 0), newItem, player.getDirectionVector().multiply(0.4)); + } + } + + setFillLevel(getFillLevel() - 1); + if (isEmpty()) { + cauldron.setPotionId(0xffff); + cauldron.clearCustomColor(); + } + this.level.setBlock(this, this, true); + this.level.addLevelEvent(this.add(0.5, 0.375 + this.getDamage() * 0.125, 0.5), LevelEventPacket.EVENT_CAULDRON_DYE_ARMOR); + case BlockID.SHULKER_BOX: + if (isEmpty() || cauldron.isCustomColor() || cauldron.hasPotion()) { + break; + } + + player.getInventory().setItemInHand(Item.get(Item.UNDYED_SHULKER_BOX).setCompoundTag(item.getCompoundTag())); + setFillLevel(getFillLevel() - 1); + this.level.setBlock(this, this, true); + this.getLevel().addSound(this, Sound.CAULDRON_TAKEPOTION); break; default: return true; @@ -188,7 +322,13 @@ public boolean onActivate(Item item, Player player) { this.level.updateComparatorOutputLevel(this); return true; } - + + private static int potion2arrow(int potion) { + int id = potion & 0xffff; + if (id < 5 || id > 43) return 1; // if it fails don't create game crashing arrows + return id < 43 ? id + 1 : id; + } + protected void replaceBucket(Item oldBucket, Player player, Item newBucket) { if (player.isSurvival() || player.isAdventure()) { if (oldBucket.getCount() == 1) { @@ -203,7 +343,7 @@ protected void replaceBucket(Item oldBucket, Player player, Item newBucket) { } } } - + @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { CompoundTag nbt = new CompoundTag("") @@ -221,26 +361,39 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl } } - BlockEntityCauldron cauldron = (BlockEntityCauldron) BlockEntity.createBlockEntity(BlockEntity.CAULDRON, this.level.getChunk((int) this.x >> 4, (int) this.z >> 4), nbt); - if (cauldron == null) { - return false; - } - this.getLevel().setBlock(block, this, true, true); + BlockEntity.createBlockEntity(BlockEntity.CAULDRON, this.getChunk(), nbt); + + this.getLevel().setBlock(this, this, true, true); return true; } @Override public Item[] getDrops(Item item) { if (item.getTier() >= ItemTool.TIER_WOODEN) { - return new Item[]{new ItemCauldron()}; + return new Item[]{Item.get(Item.CAULDRON)}; } return new Item[0]; } + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_RANDOM && level.isRaining() && !this.isFull()) { + if (freezing < 1) { + freezing = Biome.getBiome(level.getBiomeId((int) this.x, (int) this.z)).isFreezing() ? (byte) 2 : (byte) 1; + } + if (freezing == 1 && ThreadLocalRandom.current().nextInt(20) == 0 && level.canBlockSeeSky(this)) { + this.setFillLevel(this.getFillLevel() + 1); + this.getLevel().setBlock(this, this, true, true); + return Level.BLOCK_UPDATE_RANDOM; + } + } + return super.onUpdate(type); + } + @Override public Item toItem() { - return new ItemCauldron(); + return Item.get(Item.CAULDRON); } public boolean hasComparatorInputOverride() { @@ -248,11 +401,54 @@ public boolean hasComparatorInputOverride() { } public int getComparatorInputOverride() { - return this.getDamage(); + return getFillLevel(); } @Override public boolean canHarvestWithHand() { return false; } + + // Source: PN/#666 + private void consumePotion(Item item, Player player) { + if (player.isSurvival() || player.isAdventure()) { + if (item.getCount() == 1) { + player.getInventory().setItemInHand(new ItemBlock(Block.get(AIR))); + } else if (item.getCount() > 1) { + item.count--; + Item bottle = Item.get(Item.GLASS_BOTTLE); + if (player.getInventory().canAddItem(bottle)) { + player.getInventory().addItem(bottle); + } else { + player.getLevel().dropItem(player.add(0, 1.3, 0), bottle, player.getDirectionVector().multiply(0.4)); + } + } + } + } + + // Source: PN/#666 + public void clearWithFizz(BlockEntityCauldron cauldron) { + this.setFillLevel(0); + cauldron.setPotionId(0xffff); + cauldron.setSplashPotion(false); + cauldron.clearCustomColor(); + this.level.setBlock(this, Block.get(CAULDRON_BLOCK), true); + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_FIZZ); + this.getLevel().addParticle(new SmokeParticle(add(Math.random(), 1.2, Math.random())), null, 8); + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean canBePushed() { + return false; // prevent item loss issue with pistons until a working implementation + } + + @Override + public BlockColor getColor() { + return BlockColor.GRAY_BLOCK_COLOR; + } } diff --git a/src/main/java/cn/nukkit/block/BlockCauldronLava.java b/src/main/java/cn/nukkit/block/BlockCauldronLava.java new file mode 100644 index 00000000000..64e524b638c --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCauldronLava.java @@ -0,0 +1,113 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.Server; +import cn.nukkit.blockentity.BlockEntity; +import cn.nukkit.blockentity.BlockEntityCauldron; +import cn.nukkit.entity.BaseEntity; +import cn.nukkit.entity.Entity; +import cn.nukkit.event.entity.EntityCombustByBlockEvent; +import cn.nukkit.event.entity.EntityDamageByBlockEvent; +import cn.nukkit.event.entity.EntityDamageEvent; +import cn.nukkit.event.player.PlayerBucketFillEvent; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; +import cn.nukkit.level.Sound; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.potion.Effect; + +public class BlockCauldronLava extends BlockCauldron { + + public BlockCauldronLava() { + this(0x8); + } + + public BlockCauldronLava(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Lava Cauldron"; + } + + @Override + public int getId() { + return LAVA_CAULDRON; + } + + @Override + public int getLightLevel() { + return 15; + } + + @Override + public boolean hasEntityCollision() { + return true; + } + + @Override + public void setFillLevel(int fillLevel) { + super.setFillLevel(fillLevel); + setDamage(getDamage() | 0x8); + } + + @Override + public void onEntityCollide(Entity entity) { + if (!entity.fireProof || !entity.isOnFire() || !(entity instanceof BaseEntity)) { // Improve performance + if (!entity.fireProof || !entity.isOnFire()) { + + EntityCombustByBlockEvent ev = new EntityCombustByBlockEvent(this, entity, 8); + Server.getInstance().getPluginManager().callEvent(ev); + if (!ev.isCancelled() && entity.isAlive() && entity.noDamageTicks == 0) { + entity.setOnFire(ev.getDuration()); + } + } + + if (!entity.hasEffect(Effect.FIRE_RESISTANCE)) { + entity.attack(new EntityDamageByBlockEvent(this, entity, EntityDamageEvent.DamageCause.LAVA, 4)); + } + } + } + + @Override + public boolean onActivate(Item item, Player player) { + if (item.getId() == ItemID.BUCKET) { + if (item.getDamage() == 0) { + if (!isFull()) { + return false; + } + + PlayerBucketFillEvent ev = new PlayerBucketFillEvent(player, this, null, item, Item.get(ItemID.BUCKET, 10, 1)); + this.level.getServer().getPluginManager().callEvent(ev); + if (!ev.isCancelled()) { + replaceBucket(item, player, ev.getItem()); + if (!(this.level.getBlockEntity(this) instanceof BlockEntityCauldron)) { + BlockEntity.createBlockEntity(BlockEntity.CAULDRON, this.getChunk(), new CompoundTag("") + .putString("id", BlockEntity.CAULDRON) + .putInt("x", (int) this.x) + .putInt("y", (int) this.y) + .putInt("z", (int) this.z) + .putShort("PotionId", 0xffff) + .putByte("SplashPotion", 0)); + } + this.level.setBlock(this, Block.get(CAULDRON_BLOCK), true); + this.getLevel().addSound(this.add(0.5, 0.5, 0.5), Sound.BUCKET_FILL_LAVA); + } + } + } + + this.level.updateComparatorOutputLevel(this); + return true; + } + + @Override + public boolean isFull() { + return this.getDamage() == 14; + } + + @Override + public int onUpdate(int type) { + return 0; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCaveVines.java b/src/main/java/cn/nukkit/block/BlockCaveVines.java new file mode 100644 index 00000000000..054e55a851a --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCaveVines.java @@ -0,0 +1,243 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.event.block.BlockGrowEvent; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemDye; +import cn.nukkit.item.ItemID; +import cn.nukkit.level.Level; +import cn.nukkit.level.Position; +import cn.nukkit.level.particle.BoneMealParticle; +import cn.nukkit.math.BlockFace; + +import java.util.concurrent.ThreadLocalRandom; + +public class BlockCaveVines extends BlockTransparentMeta { + + private static final float CHANCE_OF_BERRIES_ON_GROWTH = 0.11F * 1.2F; + + public BlockCaveVines() { + this(0); + } + + public BlockCaveVines(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Cave Vines"; + } + + @Override + public int getId() { + return CAVE_VINES; + } + + @Override + public double getHardness() { + return 0; + } + + @Override + public boolean isSolid() { + return false; + } + + @Override + public boolean canPlaceOn(Block floor, Position pos) { + Block up = floor.up(2); + return (up.isSolid() || up instanceof BlockCaveVines) && super.canPlaceOn(floor, pos); + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (!this.canPlaceOn(block.down(), target)) { + return false; + } + + Block support = block.up(); + if (isCaveVine(support)) { + this.setVineAge(Math.min(this.getMaxAge(), ((BlockCaveVines) support).getVineAge() + 1)); + } else { + this.setVineAge(0); + } + return this.getLevel().setBlock(this, this, true, true); + } + + @Override + public int onUpdate(int type) { + switch (type) { + case Level.BLOCK_UPDATE_NORMAL: + Block up = this.up(); + if (!isCaveVine(up) && !up.isSolid()) { + this.getLevel().scheduleUpdate(this, 1); + } + break; + case Level.BLOCK_UPDATE_SCHEDULED: + this.getLevel().useBreakOn(this, null, null, true); + break; + case Level.BLOCK_UPDATE_RANDOM: + if (!this.tryGrowItself()) { + this.tryGrow(); + } + break; + } + return type; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (this.tryPickupBerries()) { + return true; + } + + if (item.getId() != Item.DYE || item.getDamage() != ItemDye.BONE_MEAL) { + return false; + } + + Block bottom = this; + BlockCaveVines plantHead = null; + while (bottom instanceof BlockCaveVines) { + plantHead = (BlockCaveVines) bottom; + bottom = bottom.down(); + } + + if (!plantHead.tryGrow()) { + return false; + } + + this.level.addParticle(new BoneMealParticle(plantHead)); + if (player != null && !player.isCreative()) { + item.count--; + } + return true; + } + + @Override + public boolean canBeActivated() { + return true; + } + + private boolean tryPickupBerries() { + if (!this.hasBerries()) { + return false; + } + + BlockCaveVines blockCaveVines = this.getStateWithoutBerries(this); + this.getLevel().setBlock(this, blockCaveVines, false, true); + + Item item = Item.get(ItemID.GLOW_BERRIES, 0, 1); + this.getLevel().dropItem(this.add(0.5, 0.5, 0.5), item); + return true; + } + + private boolean tryGrow() { + if (this.getVineAge() >= this.getMaxAge()) { + return false; + } + + Block down = this.down(); + if (down.getY() <= this.getLevel().getMinBlockY() || down.getId() != Block.AIR) { + return false; + } + + Block topBlock = this; + while (topBlock instanceof BlockCaveVines) { + if (topBlock.getDamage() < this.getVineAge()) { + break; + } + topBlock = topBlock.up(); + } + + if (topBlock.getDamage() >= this.getMaxAge()) { + return false; + } + + boolean withBerries = ThreadLocalRandom.current().nextFloat() < CHANCE_OF_BERRIES_ON_GROWTH; + BlockCaveVines head = withBerries ? this.getStateWithBerries(down) : this.getStateWithoutBerries(down); + + BlockGrowEvent event = new BlockGrowEvent(this, head); + this.getLevel().getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return false; + } + + this.getLevel().setBlock(down, event.getNewState(), true, true); + + BlockCaveVines support = (BlockCaveVines) Block.get(this.hasBerries() ? CAVE_VINES_BODY_WITH_BERRIES : CAVE_VINES, this.getDamage()); + this.getLevel().setBlock(this, support, true, true); + return true; + } + + private boolean tryGrowItself() { + if (this.hasBerries() || ThreadLocalRandom.current().nextFloat() >= CHANCE_OF_BERRIES_ON_GROWTH) { + return false; + } + + BlockCaveVines blockCaveVines = this.getStateWithBerries(this); + this.getLevel().setBlock(this, blockCaveVines, true, true); + return true; + } + + public BlockCaveVines getStateWithBerries(Position position) { + if (this.getDamage() == 0) { + return (BlockCaveVines) Block.get(CAVE_VINES_HEAD_WITH_BERRIES, 0, position); + } + return (BlockCaveVines) Block.get(CAVE_VINES_HEAD_WITH_BERRIES, this.getDamage(), position); + } + + public BlockCaveVines getStateWithoutBerries(Position position) { + return (BlockCaveVines) Block.get(CAVE_VINES, this.getDamage(), position); + } + + @Override + public Item[] getDrops(Item item) { + if (!this.hasBerries()) { + return new Item[0]; + } + return new Item[]{ Item.get(ItemID.GLOW_BERRIES, 0, 1) }; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId()), 0, 1); + } + + public void setVineAge(int age) { + this.setDamage(age); + } + + public int getVineAge() { + return this.getDamage(); + } + + public int getMaxAge() { + return 25; + } + + public boolean hasBerries() { + return false; + } + + @Override + public boolean canBeClimbed() { + return true; + } + + public static boolean isCaveVine(Block block) { + switch (block.getId()) { + case CAVE_VINES: + case CAVE_VINES_BODY_WITH_BERRIES: + case CAVE_VINES_HEAD_WITH_BERRIES: + return true; + } + return false; + } + + @Override + public boolean canPassThrough() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCaveVinesBerriesBody.java b/src/main/java/cn/nukkit/block/BlockCaveVinesBerriesBody.java new file mode 100644 index 00000000000..f01f70b3bf8 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCaveVinesBerriesBody.java @@ -0,0 +1,34 @@ +package cn.nukkit.block; + +import cn.nukkit.level.Position; + +public class BlockCaveVinesBerriesBody extends BlockCaveVines { + + public BlockCaveVinesBerriesBody() { + this(0); + } + + public BlockCaveVinesBerriesBody(int meta) { + super(meta); + } + + @Override + public int getId() { + return CAVE_VINES_BODY_WITH_BERRIES; + } + + @Override + public BlockCaveVines getStateWithBerries(Position position) { + return (BlockCaveVines) Block.get(CAVE_VINES_HEAD_WITH_BERRIES, this.getDamage(), position); + } + + @Override + public BlockCaveVines getStateWithoutBerries(Position position) { + return (BlockCaveVines) Block.get(CAVE_VINES, this.getDamage(), position); + } + + @Override + public boolean hasBerries() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCaveVinesBerriesHead.java b/src/main/java/cn/nukkit/block/BlockCaveVinesBerriesHead.java new file mode 100644 index 00000000000..8424b9559ee --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCaveVinesBerriesHead.java @@ -0,0 +1,34 @@ +package cn.nukkit.block; + +import cn.nukkit.level.Position; + +public class BlockCaveVinesBerriesHead extends BlockCaveVines { + + public BlockCaveVinesBerriesHead() { + this(0); + } + + public BlockCaveVinesBerriesHead(int meta) { + super(meta); + } + + @Override + public int getId() { + return CAVE_VINES_HEAD_WITH_BERRIES; + } + + @Override + public BlockCaveVines getStateWithBerries(Position position) { + return (BlockCaveVines) Block.get(CAVE_VINES_HEAD_WITH_BERRIES, 0, position); + } + + @Override + public BlockCaveVines getStateWithoutBerries(Position position) { + return (BlockCaveVines) Block.get(CAVE_VINES, 0, position); + } + + @Override + public boolean hasBerries() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockChain.java b/src/main/java/cn/nukkit/block/BlockChain.java new file mode 100644 index 00000000000..d1f01d4798f --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockChain.java @@ -0,0 +1,112 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; +import cn.nukkit.math.BlockFace; + +public class BlockChain extends BlockTransparentMeta { + + public BlockChain() { + this(0); + } + + public BlockChain(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Chain"; + } + + @Override + public int getId() { + return CHAIN_BLOCK; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + this.setPillarAxis(face.getAxis()); + if (super.place(item, block, target, face, fx, fy, fz, player)) { + return true; + } + return false; + } + + public void setPillarAxis(BlockFace.Axis axis) { + switch (axis) { + case Y: + this.setDamage(0); + break; + case X: + this.setDamage(1); + break; + case Z: + this.setDamage(2); + break; + } + } + + public BlockFace.Axis getPillarAxis() { + switch (this.getDamage() % 3) { + case 2: + return BlockFace.Axis.Z; + case 1: + return BlockFace.Axis.X; + case 0: + default: + return BlockFace.Axis.Y; + } + } + + @Override + public double getHardness() { + return 5; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public double getMinX() { + return x + 7 / 16.0; + } + + @Override + public double getMaxX() { + return x + 9 / 16.0; + } + + @Override + public double getMinZ() { + return z + 7 / 16.0; + } + + @Override + public double getMaxZ() { + return z + 9 / 16.0; + } + + @Override + public Item toItem() { + return Item.get(Item.CHAIN); + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockChest.java b/src/main/java/cn/nukkit/block/BlockChest.java index e6620669812..f4b3daec93e 100644 --- a/src/main/java/cn/nukkit/block/BlockChest.java +++ b/src/main/java/cn/nukkit/block/BlockChest.java @@ -18,7 +18,7 @@ import java.util.Map; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class BlockChest extends BlockTransparentMeta implements Faceable { @@ -61,42 +61,10 @@ public int getToolType() { return ItemTool.TYPE_AXE; } - @Override - public double getMinX() { - return this.x + 0.0625; - } - - @Override - public double getMinY() { - return this.y; - } - - @Override - public double getMinZ() { - return this.z + 0.0625; - } - - @Override - public double getMaxX() { - return this.x + 0.9375; - } - - @Override - public double getMaxY() { - return this.y + 0.9475; - } - - @Override - public double getMaxZ() { - return this.z + 0.9375; - } - - @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { BlockEntityChest chest = null; - int[] faces = {2, 5, 3, 4}; - this.setDamage(faces[player != null ? player.getDirection().getHorizontalIndex() : 0]); + this.setDamage(Block.FACES2534[player != null ? player.getDirection().getHorizontalIndex() : 0]); for (int side = 2; side <= 5; ++side) { if ((this.getDamage() == 4 || this.getDamage() == 5) && (side == 4 || side == 5)) { @@ -114,7 +82,8 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl } } - this.getLevel().setBlock(block, this, true, true); + this.getLevel().setBlock(this, this, true, true); + CompoundTag nbt = new CompoundTag("") .putList(new ListTag<>("Items")) .putString("id", BlockEntity.CHEST) @@ -133,11 +102,7 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl } } - BlockEntityChest blockEntity = (BlockEntityChest) BlockEntity.createBlockEntity(BlockEntity.CHEST, this.getLevel().getChunk((int) (this.x) >> 4, (int) (this.z) >> 4), nbt); - - if (blockEntity == null) { - return false; - } + BlockEntityChest blockEntity = (BlockEntityChest) BlockEntity.createBlockEntity(BlockEntity.CHEST, this.getChunk(), nbt); if (chest != null) { chest.pairWith(blockEntity); @@ -161,28 +126,19 @@ public boolean onBreak(Item item) { @Override public boolean onActivate(Item item, Player player) { if (player != null) { - Block top = up(); - if (!top.isTransparent()) { - return true; + Block top = this.up(); + if (!(top instanceof BlockStairs)) { // Stairs don't block chest on vanilla + if (!top.isTransparent()) { + return true; + } } BlockEntity t = this.getLevel().getBlockEntity(this); - BlockEntityChest chest; - if (t instanceof BlockEntityChest) { - chest = (BlockEntityChest) t; - } else { - CompoundTag nbt = new CompoundTag("") - .putList(new ListTag<>("Items")) - .putString("id", BlockEntity.CHEST) - .putInt("x", (int) this.x) - .putInt("y", (int) this.y) - .putInt("z", (int) this.z); - chest = (BlockEntityChest) BlockEntity.createBlockEntity(BlockEntity.CHEST, this.getLevel().getChunk((int) (this.x) >> 4, (int) (this.z) >> 4), nbt); - if (chest == null) { - return false; - } + if (!(t instanceof BlockEntityChest)) { + return false; } + BlockEntityChest chest = (BlockEntityChest) t; if (chest.namedTag.contains("Lock") && chest.namedTag.get("Lock") instanceof StringTag) { if (!chest.namedTag.getString("Lock").equals(item.getCustomName())) { return true; @@ -216,11 +172,21 @@ public int getComparatorInputOverride() { @Override public Item toItem() { - return new ItemBlock(this, 0); + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override public BlockFace getBlockFace() { return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); } + + @Override + public boolean canBePushed() { + return false; // prevent item loss issue with pistons until a working implementation + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } } diff --git a/src/main/java/cn/nukkit/block/BlockChorusFlower.java b/src/main/java/cn/nukkit/block/BlockChorusFlower.java index 46ad4e2a2c9..68308fd6b19 100644 --- a/src/main/java/cn/nukkit/block/BlockChorusFlower.java +++ b/src/main/java/cn/nukkit/block/BlockChorusFlower.java @@ -1,11 +1,30 @@ package cn.nukkit.block; +import cn.nukkit.Player; +import cn.nukkit.Server; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.projectile.EntityArrow; +import cn.nukkit.entity.projectile.EntitySnowball; +import cn.nukkit.event.block.BlockGrowEvent; import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemTool; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; +import cn.nukkit.network.protocol.LevelSoundEventPacket; +import cn.nukkit.utils.BlockColor; -public class BlockChorusFlower extends BlockTransparent { +import java.util.concurrent.ThreadLocalRandom; +public class BlockChorusFlower extends BlockTransparentMeta { + + // Version 7a3d8a5 public BlockChorusFlower() { + super(0); + } + + public BlockChorusFlower(int meta) { + super(meta); } @Override @@ -25,16 +44,206 @@ public double getHardness() { @Override public double getResistance() { - return 2; + return 0.4; } @Override public int getToolType() { - return ItemTool.TYPE_NONE; + return ItemTool.TYPE_AXE; + } + + private boolean isPositionValid() { + // Chorus flowers must be above end stone or chorus plant, or be above air and horizontally adjacent to exactly one chorus plant. + // If these conditions are not met, the block breaks without dropping anything. + Block down = down(); + if (down.getId() == CHORUS_PLANT || down.getId() == END_STONE) { + return true; + } + if (down.getId() != AIR) { + return false; + } + boolean foundPlant = false; + for (BlockFace face : BlockFace.Plane.HORIZONTAL) { + Block side = getSide(face); + if (side.getId() == CHORUS_PLANT) { + if (foundPlant) { + return false; + } + foundPlant = true; + } + } + + return foundPlant; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + if (!isPositionValid()) { + this.getLevel().scheduleUpdate(this, 1); + return type; + } + } else if (type == Level.BLOCK_UPDATE_SCHEDULED) { + this.getLevel().useBreakOn(this, null, null, true); + return type; + } else if (type == Level.BLOCK_UPDATE_RANDOM) { + // Check limit + Block up; + if (this.y < level.getMaxBlockY() && (up = this.up()).getId() == AIR) { + if (!isFullyAged()) { + boolean growUp = false; // Grow upward? + boolean ground = false; // Is on the ground directly? + Block down = this.down(); + if (down.getId() == AIR || down.getId() == END_STONE) { + growUp = true; + } else if (down.getId() == CHORUS_PLANT) { + int height = 1; + for (int y = 2; y < 6; y++) { + Block downY = this.down(y); + if (downY.getId() == CHORUS_PLANT) { + height++; + } else { + if (downY.getId() == END_STONE) { + ground = true; + } + break; + } + } + + if (height < 2 || height <= ThreadLocalRandom.current().nextInt(ground ? 5 : 4)) { + growUp = true; + } + } + + // Grow Upward + if (growUp && up.up().getId() == AIR && isHorizontalAir(up)) { + BlockChorusFlower block = (BlockChorusFlower) this.clone(); + block.y = this.y + 1; + BlockGrowEvent ev = new BlockGrowEvent(this, block); + Server.getInstance().getPluginManager().callEvent(ev); + + if (!ev.isCancelled()) { + this.getLevel().setBlock(this, Block.get(CHORUS_PLANT)); + this.getLevel().setBlock(block, ev.getNewState()); + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_CHORUSGROW); + } else { + return Level.BLOCK_UPDATE_RANDOM; + } + // Grow Horizontally + } else if (!isFullyAged()) { + for (int i = 0; i < ThreadLocalRandom.current().nextInt(ground ? 5 : 4); i++) { + BlockFace face = BlockFace.Plane.HORIZONTAL.random(); + Block check = this.getSide(face); + if (check.getId() == AIR && check.down().getId() == AIR && isHorizontalAirExcept(check, face.getOpposite())) { + BlockChorusFlower block = (BlockChorusFlower) this.clone(); + block.x = check.x; + block.y = check.y; + block.z = check.z; + block.setAge(getAge() + 1); + BlockGrowEvent ev = new BlockGrowEvent(this, block); + Server.getInstance().getPluginManager().callEvent(ev); + + if (!ev.isCancelled()) { + this.getLevel().setBlock(this, Block.get(CHORUS_PLANT)); + this.getLevel().setBlock(block, ev.getNewState()); + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_CHORUSGROW); + } else { + return Level.BLOCK_UPDATE_RANDOM; + } + } + } + // Death + } else { + BlockChorusFlower block = (BlockChorusFlower) this.clone(); + block.setAge(getMaxAge()); + BlockGrowEvent ev = new BlockGrowEvent(this, block); + Server.getInstance().getPluginManager().callEvent(ev); + + if (!ev.isCancelled()) { + this.getLevel().setBlock(block, ev.getNewState()); + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_CHORUSDEATH); + } else { + return Level.BLOCK_UPDATE_RANDOM; + } + } + } + } else { + return Level.BLOCK_UPDATE_RANDOM; + } + } + + return 0; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (!isPositionValid()) { + return false; + } + return super.place(item, block, target, face, fx, fy, fz, player); } @Override public Item[] getDrops(Item item) { return new Item[]{this.toItem()}; } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public void onEntityCollide(Entity entity) { + if (entity instanceof EntityArrow || entity instanceof EntitySnowball) { + entity.close(); + this.getLevel().useBreakOn(this); + } + } + + public int getMaxAge() { + return 5; + } + + public int getAge() { + return getDamage(); + } + + public void setAge(int age) { + this.setDamage(age); + } + + public boolean isFullyAged() { + return getAge() >= getMaxAge(); + } + + private boolean isHorizontalAir(Block block) { + for (BlockFace face : BlockFace.Plane.HORIZONTAL) { + if (block.getSide(face).getId() != AIR) { + return false; + } + } + return true; + } + + private boolean isHorizontalAirExcept(Block block, BlockFace except) { + for (BlockFace face : BlockFace.Plane.HORIZONTAL) { + if (face != except) { + if (block.getSide(face).getId() != AIR) { + return false; + } + } + } + return true; + } + + @Override + public boolean breakWhenPushed() { + return true; + } + + @Override + public BlockColor getColor() { + return BlockColor.PURPLE_BLOCK_COLOR; + } } diff --git a/src/main/java/cn/nukkit/block/BlockChorusPlant.java b/src/main/java/cn/nukkit/block/BlockChorusPlant.java index f4363f5ecf3..9424205aeaf 100644 --- a/src/main/java/cn/nukkit/block/BlockChorusPlant.java +++ b/src/main/java/cn/nukkit/block/BlockChorusPlant.java @@ -1,17 +1,16 @@ package cn.nukkit.block; +import cn.nukkit.Player; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemID; import cn.nukkit.item.ItemTool; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; import cn.nukkit.utils.BlockColor; - -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; public class BlockChorusPlant extends BlockTransparent { - public BlockChorusPlant() { - } - @Override public int getId() { return CHORUS_PLANT; @@ -29,21 +28,76 @@ public double getHardness() { @Override public double getResistance() { - return 2; + return 0.4; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (!isSupportValid()) { + return false; + } + return super.place(item, block, target, face, fx, fy, fz, player); } @Override public int getToolType() { - return ItemTool.TYPE_NONE; + return ItemTool.TYPE_AXE; + } + + private boolean isSupportValid() { + // Must be on end stone or chorus plant, or be above air and horizontally adjacent to exactly one chorus plant, otherwise breaks without dropping anything + int down = down().getId(); + if (down == CHORUS_PLANT || down == END_STONE) { + return true; + } + + if (down != AIR) { + return false; + } + + boolean plantFound = false; + for (BlockFace face : BlockFace.Plane.HORIZONTAL) { + if (getSide(face).getId() == CHORUS_PLANT) { + if (plantFound) { + return false; + } + plantFound = true; + } + } + + return plantFound; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + if (!isSupportValid()) { + this.getLevel().scheduleUpdate(this, 1); + return type; + } + } else if (type == Level.BLOCK_UPDATE_SCHEDULED) { + this.getLevel().useBreakOn(this, null, null, true); + return type; + } + + return 0; } @Override public Item[] getDrops(Item item) { - return ThreadLocalRandom.current().nextBoolean() ? new Item[]{Item.get(ItemID.CHORUS_FRUIT, 0, 1)} : new Item[0]; + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; + } + return Utils.rand() ? new Item[]{Item.get(Item.CHORUS_FRUIT, 0, 1)} : new Item[0]; } @Override public BlockColor getColor() { return BlockColor.PURPLE_BLOCK_COLOR; } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockClay.java b/src/main/java/cn/nukkit/block/BlockClay.java index b2cdee1d549..e0661d910cb 100644 --- a/src/main/java/cn/nukkit/block/BlockClay.java +++ b/src/main/java/cn/nukkit/block/BlockClay.java @@ -1,8 +1,8 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemClay; import cn.nukkit.item.ItemTool; +import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.utils.BlockColor; /** @@ -10,9 +10,6 @@ */ public class BlockClay extends BlockSolid { - public BlockClay() { - } - @Override public double getHardness() { return 0.6; @@ -40,8 +37,11 @@ public String getName() { @Override public Item[] getDrops(Item item) { + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; + } return new Item[]{ - new ItemClay(0, 4) + Item.get(Item.CLAY, 0, 4) }; } diff --git a/src/main/java/cn/nukkit/block/BlockCoal.java b/src/main/java/cn/nukkit/block/BlockCoal.java index 48fc76c6b6b..9df6085b51c 100644 --- a/src/main/java/cn/nukkit/block/BlockCoal.java +++ b/src/main/java/cn/nukkit/block/BlockCoal.java @@ -9,8 +9,6 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockCoal extends BlockSolid { - public BlockCoal() { - } @Override public int getId() { @@ -49,7 +47,7 @@ public String getName() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; diff --git a/src/main/java/cn/nukkit/block/BlockCobblestone.java b/src/main/java/cn/nukkit/block/BlockCobblestone.java index 223f38def5b..bdf270cb198 100644 --- a/src/main/java/cn/nukkit/block/BlockCobblestone.java +++ b/src/main/java/cn/nukkit/block/BlockCobblestone.java @@ -4,14 +4,11 @@ import cn.nukkit.item.ItemTool; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class BlockCobblestone extends BlockSolid { - public BlockCobblestone() { - } - @Override public int getId() { return COBBLESTONE; @@ -39,7 +36,7 @@ public String getName() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; diff --git a/src/main/java/cn/nukkit/block/BlockCobweb.java b/src/main/java/cn/nukkit/block/BlockCobweb.java index 16ca8a689d8..cca7d8d655c 100644 --- a/src/main/java/cn/nukkit/block/BlockCobweb.java +++ b/src/main/java/cn/nukkit/block/BlockCobweb.java @@ -2,8 +2,8 @@ import cn.nukkit.entity.Entity; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemString; import cn.nukkit.item.ItemTool; +import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.utils.BlockColor; /** @@ -11,6 +11,7 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockCobweb extends BlockFlowable { + public BlockCobweb() { this(0); } @@ -44,6 +45,11 @@ public int getToolType() { return ItemTool.TYPE_SWORD; } + @Override + public boolean hasEntityCollision() { + return true; + } + @Override public void onEntityCollide(Entity entity) { entity.resetFallDistance(); @@ -57,7 +63,7 @@ public Item[] getDrops(Item item) { }; } else if (item.isSword()) { return new Item[]{ - new ItemString() + Item.get(Item.STRING) }; } else { return new Item[0]; @@ -73,4 +79,19 @@ public BlockColor getColor() { public boolean canHarvestWithHand() { return false; } + + @Override + protected AxisAlignedBB recalculateBoundingBox() { + return this; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockCocoa.java b/src/main/java/cn/nukkit/block/BlockCocoa.java index 66faef60934..19d098d522e 100644 --- a/src/main/java/cn/nukkit/block/BlockCocoa.java +++ b/src/main/java/cn/nukkit/block/BlockCocoa.java @@ -13,19 +13,30 @@ import cn.nukkit.math.SimpleAxisAlignedBB; import cn.nukkit.utils.DyeColor; import cn.nukkit.utils.Faceable; - -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; /** * Created by CreeperFace on 27. 10. 2016. */ public class BlockCocoa extends BlockTransparentMeta implements Faceable { - protected static final AxisAlignedBB[] EAST = new SimpleAxisAlignedBB[]{new SimpleAxisAlignedBB(0.6875D, 0.4375D, 0.375D, 0.9375D, 0.75D, 0.625D), new SimpleAxisAlignedBB(0.5625D, 0.3125D, 0.3125D, 0.9375D, 0.75D, 0.6875D), new SimpleAxisAlignedBB(0.5625D, 0.3125D, 0.3125D, 0.9375D, 0.75D, 0.6875D)}; - protected static final AxisAlignedBB[] WEST = new SimpleAxisAlignedBB[]{new SimpleAxisAlignedBB(0.0625D, 0.4375D, 0.375D, 0.3125D, 0.75D, 0.625D), new SimpleAxisAlignedBB(0.0625D, 0.3125D, 0.3125D, 0.4375D, 0.75D, 0.6875D), new SimpleAxisAlignedBB(0.0625D, 0.3125D, 0.3125D, 0.4375D, 0.75D, 0.6875D)}; - protected static final AxisAlignedBB[] NORTH = new SimpleAxisAlignedBB[]{new SimpleAxisAlignedBB(0.375D, 0.4375D, 0.0625D, 0.625D, 0.75D, 0.3125D), new SimpleAxisAlignedBB(0.3125D, 0.3125D, 0.0625D, 0.6875D, 0.75D, 0.4375D), new SimpleAxisAlignedBB(0.3125D, 0.3125D, 0.0625D, 0.6875D, 0.75D, 0.4375D)}; - protected static final AxisAlignedBB[] SOUTH = new SimpleAxisAlignedBB[]{new SimpleAxisAlignedBB(0.375D, 0.4375D, 0.6875D, 0.625D, 0.75D, 0.9375D), new SimpleAxisAlignedBB(0.3125D, 0.3125D, 0.5625D, 0.6875D, 0.75D, 0.9375D), new SimpleAxisAlignedBB(0.3125D, 0.3125D, 0.5625D, 0.6875D, 0.75D, 0.9375D)}; - protected static final AxisAlignedBB[] ALL = new AxisAlignedBB[12]; + protected static final AxisAlignedBB[] EAST = {new SimpleAxisAlignedBB(0.6875D, 0.4375D, 0.375D, 0.9375D, 0.75D, 0.625D), new SimpleAxisAlignedBB(0.5625D, 0.3125D, 0.3125D, 0.9375D, 0.75D, 0.6875D), new SimpleAxisAlignedBB(0.5625D, 0.3125D, 0.3125D, 0.9375D, 0.75D, 0.6875D)}; + protected static final AxisAlignedBB[] WEST = {new SimpleAxisAlignedBB(0.0625D, 0.4375D, 0.375D, 0.3125D, 0.75D, 0.625D), new SimpleAxisAlignedBB(0.0625D, 0.3125D, 0.3125D, 0.4375D, 0.75D, 0.6875D), new SimpleAxisAlignedBB(0.0625D, 0.3125D, 0.3125D, 0.4375D, 0.75D, 0.6875D)}; + protected static final AxisAlignedBB[] NORTH = {new SimpleAxisAlignedBB(0.375D, 0.4375D, 0.0625D, 0.625D, 0.75D, 0.3125D), new SimpleAxisAlignedBB(0.3125D, 0.3125D, 0.0625D, 0.6875D, 0.75D, 0.4375D), new SimpleAxisAlignedBB(0.3125D, 0.3125D, 0.0625D, 0.6875D, 0.75D, 0.4375D)}; + protected static final AxisAlignedBB[] SOUTH = {new SimpleAxisAlignedBB(0.375D, 0.4375D, 0.6875D, 0.625D, 0.75D, 0.9375D), new SimpleAxisAlignedBB(0.3125D, 0.3125D, 0.5625D, 0.6875D, 0.75D, 0.9375D), new SimpleAxisAlignedBB(0.3125D, 0.3125D, 0.5625D, 0.6875D, 0.75D, 0.9375D)}; + + private static final short[] FACES = { + 0, + 0, + 0, + 2, + 3, + 1, + }; + + private static final short[] FACES_2 = { + 3, 4, 2, 5, 3, 4, 2, 5, 3, 4, 2, 5 + }; public BlockCocoa() { this(0); @@ -46,52 +57,15 @@ public String getName() { } @Override - public void setDamage(int meta) { - super.setDamage(meta); - } - - - @Override - public double getMinX() { - return this.x + getRelativeBoundingBox().getMinX(); - } - - @Override - public double getMaxX() { - return this.x + getRelativeBoundingBox().getMaxX(); - } - - @Override - public double getMinY() { - return this.y + getRelativeBoundingBox().getMinY(); - } - - @Override - public double getMaxY() { - return this.y + getRelativeBoundingBox().getMaxY(); - } - - @Override - public double getMinZ() { - return this.z + getRelativeBoundingBox().getMinZ(); - } - - @Override - public double getMaxZ() { - return this.z + getRelativeBoundingBox().getMaxZ(); - } + protected AxisAlignedBB recalculateBoundingBox() { + AxisAlignedBB[] bbs; - private AxisAlignedBB getRelativeBoundingBox() { int damage = this.getDamage(); if (damage > 11) { - this.setDamage(damage = 11); + damage = 11; } - AxisAlignedBB boundingBox = ALL[damage]; - if (boundingBox != null) return boundingBox; - - AxisAlignedBB[] bbs; - switch (getDamage()) { + switch (damage) { case 1: case 5: case 9: @@ -112,23 +86,14 @@ private AxisAlignedBB getRelativeBoundingBox() { break; } - return ALL[damage] = bbs[this.getDamage() >> 2]; + return bbs[(damage >> 2)].getOffsetBoundingBox(x, y, z); } @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { if (target.getId() == Block.WOOD && (target.getDamage() & 0x03) == BlockWood.JUNGLE) { if (face != BlockFace.DOWN && face != BlockFace.UP) { - int[] faces = new int[]{ - 0, - 0, - 0, - 2, - 3, - 1, - }; - - this.setDamage(faces[face.getIndex()]); + this.setDamage(FACES[face.getIndex()]); this.level.setBlock(block, this, true, true); return true; } @@ -139,19 +104,15 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl @Override public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_NORMAL) { - int[] faces = new int[]{ - 3, 4, 2, 5, 3, 4, 2, 5, 3, 4, 2, 5 - }; - - Block side = this.getSide(BlockFace.fromIndex(faces[this.getDamage()])); + Block side = this.getSide(BlockFace.fromIndex(FACES_2[this.getDamage()])); - if (side.getId() != Block.WOOD && side.getDamage() != BlockWood.JUNGLE) { + if (side.getId() != Block.WOOD && (side.getDamage() & 0x03) != BlockWood.JUNGLE) { this.getLevel().useBreakOn(this); return Level.BLOCK_UPDATE_NORMAL; } } else if (type == Level.BLOCK_UPDATE_RANDOM) { - if (ThreadLocalRandom.current().nextInt(2) == 1) { - if (this.getDamage() / 4 < 2) { + if (Utils.random.nextInt(2) == 1) { + if (this.getDamage() >> 2 < 2) { BlockCocoa block = (BlockCocoa) this.clone(); block.setDamage(block.getDamage() + 4); BlockGrowEvent ev = new BlockGrowEvent(this, block); @@ -178,9 +139,9 @@ public boolean canBeActivated() { @Override public boolean onActivate(Item item, Player player) { - if (item.getId() == Item.DYE && item.getDamage() == 0x0f) { + if (item.getId() == Item.DYE && item.getDamage() == ItemDye.BONE_MEAL) { Block block = this.clone(); - if (this.getDamage() / 4 < 2) { + if (this.getDamage() >> 2 < 2) { block.setDamage(block.getDamage() + 4); BlockGrowEvent ev = new BlockGrowEvent(this, block); Server.getInstance().getPluginManager().callEvent(ev); @@ -188,10 +149,11 @@ public boolean onActivate(Item item, Player player) { if (ev.isCancelled()) { return false; } + this.getLevel().setBlock(this, ev.getNewState(), true, true); this.level.addParticle(new BoneMealParticle(this)); - if (player != null && (player.gamemode & 0x01) == 0) { + if (player != null && !player.isCreative()) { item.count--; } } @@ -219,24 +181,39 @@ public int getToolType() { @Override public Item toItem() { - return new ItemDye(DyeColor.BROWN.getDyeData()); + return Item.get(Item.DYE, DyeColor.BROWN.getDyeData()); } @Override public Item[] getDrops(Item item) { if (this.getDamage() >= 8) { return new Item[]{ - new ItemDye(3, 3) + Item.get(Item.DYE, 3, Utils.rand(2, 3)) }; } else { return new Item[]{ - new ItemDye(3, 1) + Item.get(Item.DYE, 3, 1) }; } } @Override public BlockFace getBlockFace() { - return BlockFace.fromHorizontalIndex(this.getDamage() & 0x07); + return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.FLOW_INTO_BLOCK; + } + + @Override + public boolean canBeFlowedInto() { + return false; + } + + @Override + public boolean breakWhenPushed() { + return true; } } diff --git a/src/main/java/cn/nukkit/block/BlockCommandBlock.java b/src/main/java/cn/nukkit/block/BlockCommandBlock.java new file mode 100644 index 00000000000..4f727d3d0b5 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCommandBlock.java @@ -0,0 +1,41 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; + +public class BlockCommandBlock extends BlockSolid { + + @Override + public int getId() { + return COMMAND_BLOCK; + } + + @Override + public double getHardness() { + return -1; + } + + @Override + public double getResistance() { + return 18000000; + } + + @Override + public String getName() { + return "Command Block"; + } + + @Override + public boolean isBreakable(Item item) { + return false; + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCommandBlockChain.java b/src/main/java/cn/nukkit/block/BlockCommandBlockChain.java new file mode 100644 index 00000000000..5f11fc8c5f9 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCommandBlockChain.java @@ -0,0 +1,41 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; + +public class BlockCommandBlockChain extends BlockSolid { + + @Override + public int getId() { + return CHAIN_COMMAND_BLOCK; + } + + @Override + public double getHardness() { + return -1; + } + + @Override + public double getResistance() { + return 18000000; + } + + @Override + public String getName() { + return "Chain Command Block"; + } + + @Override + public boolean isBreakable(Item item) { + return false; + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCommandBlockRepeating.java b/src/main/java/cn/nukkit/block/BlockCommandBlockRepeating.java new file mode 100644 index 00000000000..179badce4ac --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCommandBlockRepeating.java @@ -0,0 +1,41 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; + +public class BlockCommandBlockRepeating extends BlockSolid { + + @Override + public int getId() { + return REPEATING_COMMAND_BLOCK; + } + + @Override + public double getHardness() { + return -1; + } + + @Override + public double getResistance() { + return 18000000; + } + + @Override + public String getName() { + return "Repeating Command Block"; + } + + @Override + public boolean isBreakable(Item item) { + return false; + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockComposter.java b/src/main/java/cn/nukkit/block/BlockComposter.java new file mode 100644 index 00000000000..36e1febeee1 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockComposter.java @@ -0,0 +1,210 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.event.block.ComposterEmptyEvent; +import cn.nukkit.event.block.ComposterFillEvent; +import cn.nukkit.item.*; +import cn.nukkit.level.Sound; +import cn.nukkit.utils.DyeColor; +import cn.nukkit.utils.Utils; +import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; + +public class BlockComposter extends BlockTransparentMeta implements ItemID { + + private static final Int2IntOpenHashMap ITEMS = new Int2IntOpenHashMap(); + + static { + registerItems(30, KELP, BEETROOT_SEEDS, DRIED_KELP, MELON_SEEDS, PUMPKIN_SEEDS, SWEET_BERRIES, WHEAT_SEEDS); + registerItems(50, MELON_SLICE, SUGAR_CANE); + registerItems(65, APPLE, BEETROOT, CARROT, COCOA, POTATO, WHEAT); + registerItems(85, BAKED_POTATOES, BREAD, COOKIE); + registerItems(100, CAKE, PUMPKIN_PIE); + registerBlocks(30, BLOCK_KELP, LEAVES, LEAVES2, SAPLINGS, SEAGRASS, SWEET_BERRY_BUSH); + registerBlocks(50, GRASS, CACTUS, DRIED_KELP_BLOCK, VINES, NETHER_SPROUTS_BLOCK); + registerBlocks(65, DANDELION, RED_FLOWER, DOUBLE_PLANT, WITHER_ROSE, LILY_PAD, MELON_BLOCK, PUMPKIN, CARVED_PUMPKIN, SEA_PICKLE, BROWN_MUSHROOM, RED_MUSHROOM, SHROOMLIGHT, CRIMSON_FUNGUS, WARPED_FUNGUS, MUSHROOM_STEW); + registerBlocks(85, HAY_BALE, BROWN_MUSHROOM_BLOCK, RED_MUSHROOM_BLOCK, BLOCK_NETHER_WART_BLOCK, WARPED_WART_BLOCK); + registerBlocks(100, CAKE_BLOCK); + registerBlock(50, TALL_GRASS, 0); + registerBlock(50, TALL_GRASS, 1); + registerBlock(65, TALL_GRASS, 2); + registerBlock(65, TALL_GRASS, 3); + } + + public BlockComposter() { + this(0); + } + + public BlockComposter(int meta) { + super(meta); + } + + @Override + public int getId() { + return COMPOSTER; + } + + @Override + public String getName() { + return "Composter"; + } + + @Override + public double getHardness() { + return 0.6; + } + + @Override + public double getResistance() { + return 0.6; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_AXE; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public boolean hasComparatorInputOverride() { + return true; + } + + @Override + public int getComparatorInputOverride() { + return getDamage(); + } + + public boolean incrementLevel() { + int fillLevel = getDamage() + 1; + setDamage(fillLevel); + this.level.setBlock(this, this, true, true); + return fillLevel == 8; + } + + public boolean isFull() { + return getDamage() == 8; + } + + public boolean isEmpty() { + return getDamage() == 0; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (item.getCount() <= 0 || item.getId() == Item.AIR) { + return false; + } + + if (isFull()) { + empty(item, player); + return true; + } + + int chance = getChance(item); + if (chance <= 0) { + return false; + } + + boolean success = Utils.random.nextInt(100) < chance; + ComposterFillEvent event = new ComposterFillEvent(this, player, item, chance, success); + this.level.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return true; + } + + if (player != null && !player.isCreative()) { + item.setCount(item.getCount() - 1); + } + + if (event.isSuccess()) { + if (incrementLevel()) { + level.addSound(this.add(0.5, 0.5, 0.5), Sound.BLOCK_COMPOSTER_READY); + } else { + level.addSound(this.add(0.5, 0.5, 0.5), Sound.BLOCK_COMPOSTER_FILL_SUCCESS); + } + } else { + level.addSound(this.add(0.5, 0.5, 0.5), Sound.BLOCK_COMPOSTER_FILL); + } + + return true; + } + + public Item empty() { + return empty(null, null); + } + + public Item empty(Player player) { + return this.empty(null, player); + } + + public Item empty(Item item, Player player) { + if (isEmpty()) { + return null; + } + ComposterEmptyEvent event = new ComposterEmptyEvent(this, player, item, new ItemDye(DyeColor.WHITE), 0); + this.level.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + this.setDamage(event.getNewLevel()); + this.level.setBlock(this, this, true, true); + if (item != null) { + this.level.dropItem(add(0.5, 0.85, 0.5), event.getDrop()); + } + this.level.addSound(add(0.5 , 0.5, 0.5), Sound.BLOCK_COMPOSTER_EMPTY); + return event.getDrop(); + } + return null; + } + + public static void registerItem(int chance, int itemId) { + registerItem(chance, itemId, 0); + } + + public static void registerItem(int chance, int itemId, int meta) { + ITEMS.put(itemId << 6 | meta & 0x3F, chance); + } + + public static void registerItems(int chance, int... itemIds) { + for (int itemId : itemIds) { + registerItem(chance, itemId, 0); + } + } + + public static void registerBlocks(int chance, int... blockIds) { + for (int blockId : blockIds) { + registerBlock(chance, blockId, 0); + } + } + + public static void registerBlock(int chance, int blockId) { + registerBlock(chance, blockId, 0); + } + + public static void registerBlock(int chance, int blockId, int meta) { + if (blockId > 255) { + blockId = 255 - blockId; + } + registerItem(chance, blockId, meta); + } + + public static void register(int chance, Item item) { + registerItem(chance, item.getId(), item.getDamage()); + } + + public static int getChance(Item item) { + int chance = ITEMS.get(item.getId() << 6 | item.getDamage()); + if (chance == 0) { + chance = ITEMS.get(item.getId() << 6); + } + return chance; + } + + @Override + public boolean canBeActivated() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockConcrete.java b/src/main/java/cn/nukkit/block/BlockConcrete.java index 115f543014e..3597f2981c9 100644 --- a/src/main/java/cn/nukkit/block/BlockConcrete.java +++ b/src/main/java/cn/nukkit/block/BlockConcrete.java @@ -35,7 +35,7 @@ public double getHardness() { @Override public String getName() { - return "Concrete"; + return getDyeColor().getName() + " Concrete"; } @Override diff --git a/src/main/java/cn/nukkit/block/BlockConcretePowder.java b/src/main/java/cn/nukkit/block/BlockConcretePowder.java index 20811ae3608..6e43d09f0b2 100644 --- a/src/main/java/cn/nukkit/block/BlockConcretePowder.java +++ b/src/main/java/cn/nukkit/block/BlockConcretePowder.java @@ -11,30 +11,19 @@ /** * Created by CreeperFace on 2.6.2017. */ -public class BlockConcretePowder extends BlockFallable { - private int meta; +public class BlockConcretePowder extends BlockFallableMeta { public BlockConcretePowder() { - this(0); + super(0); } public BlockConcretePowder(int meta) { - this.meta = meta; + super(meta); } @Override public int getFullId() { - return (getId() << 4) + getDamage(); - } - - @Override - public final int getDamage() { - return this.meta; - } - - @Override - public final void setDamage(int meta) { - this.meta = meta; + return (CONCRETE_POWDER << Block.DATA_BITS) + getDamage(); } @Override @@ -44,7 +33,7 @@ public int getId() { @Override public String getName() { - return "Concrete Powder"; + return getDyeColor().getName() + " Concrete Powder"; } @Override @@ -70,7 +59,7 @@ public int onUpdate(int type) { for (int side = 1; side <= 5; side++) { Block block = this.getSide(BlockFace.fromIndex(side)); if (block.getId() == Block.WATER || block.getId() == Block.STILL_WATER) { - this.level.setBlock(this, Block.get(Block.CONCRETE, this.meta), true, true); + this.level.setBlock(this, Block.get(Block.CONCRETE, this.getDamage()), true, true); } } @@ -104,4 +93,8 @@ public boolean place(Item item, Block b, Block target, BlockFace face, double fx public BlockColor getColor() { return DyeColor.getByWoolData(getDamage()).getColor(); } + + public DyeColor getDyeColor() { + return DyeColor.getByWoolData(getDamage()); + } } diff --git a/src/main/java/cn/nukkit/block/BlockConduit.java b/src/main/java/cn/nukkit/block/BlockConduit.java new file mode 100644 index 00000000000..41c3c4c7ce5 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockConduit.java @@ -0,0 +1,59 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; + +public class BlockConduit extends BlockSolidMeta { + + public BlockConduit() { + this(0); + } + + public BlockConduit(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Conduit"; + } + + @Override + public int getId() { + return CONDUIT; + } + + @Override + public double getResistance() { + return 3; + } + + @Override + public double getHardness() { + return 3; + } + + @Override + public int getLightLevel() { + return 15; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.FLOW_INTO_BLOCK; + } + + @Override + public boolean alwaysDropsOnExplosion() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCopper.java b/src/main/java/cn/nukkit/block/BlockCopper.java new file mode 100644 index 00000000000..ef174b80ad8 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCopper.java @@ -0,0 +1,31 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.utils.BlockColor; + +public class BlockCopper extends BlockCopperBase { + + public BlockCopper() { + // Does nothing + } + + @Override + public String getName() { + return "Block of Copper"; + } + + @Override + public int getId() { + return COPPER_BLOCK; + } + + @Override + public BlockColor getColor() { + return BlockColor.ORANGE_BLOCK_COLOR; + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.UNAFFECTED; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCopperBase.java b/src/main/java/cn/nukkit/block/BlockCopperBase.java new file mode 100644 index 00000000000..1e28a64571a --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCopperBase.java @@ -0,0 +1,98 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; + +public abstract class BlockCopperBase extends BlockSolid implements Oxidizable, Waxable { + + public BlockCopperBase() { + // Does nothing + } + + @Override + public double getHardness() { + return 3; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_STONE; + } + + @Override + public boolean onActivate(Item item, Player player) { + return Waxable.super.onActivate(item, player) + || Oxidizable.super.onActivate(item, player); + } + + @Override + public int onUpdate(int type) { + return Oxidizable.super.onUpdate(type); + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public Block getStateWithOxidizationLevel(OxidizationLevel oxidizationLevel) { + return Block.get(this.getCopperId(this.isWaxed(), oxidizationLevel), this.getDamage()); + } + + @Override + public boolean setOxidizationLevel(OxidizationLevel oxidizationLevel) { + if (this.getOxidizationLevel().equals(oxidizationLevel)) { + return true; + } + return this.level.setBlock(this, Block.get(this.getCopperId(this.isWaxed(), oxidizationLevel))); + } + + @Override + public boolean setWaxed(boolean waxed) { + if (this.isWaxed() == waxed) { + return true; + } + return this.level.setBlock(this, Block.get(getCopperId(waxed, getOxidizationLevel()))); + } + + @Override + public boolean isWaxed() { + return false; + } + + protected int getCopperId(boolean waxed, OxidizationLevel oxidizationLevel) { + if (oxidizationLevel == null) { + return this.getId(); + } + switch (oxidizationLevel) { + case UNAFFECTED: + return waxed ? WAXED_COPPER : COPPER_BLOCK; + case EXPOSED: + return waxed ? WAXED_EXPOSED_COPPER : EXPOSED_COPPER; + case WEATHERED: + return waxed ? WAXED_WEATHERED_COPPER : WEATHERED_COPPER; + case OXIDIZED: + return waxed ? WAXED_OXIDIZED_COPPER : OXIDIZED_COPPER; + default: + return this.getId(); + } + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCopperCut.java b/src/main/java/cn/nukkit/block/BlockCopperCut.java new file mode 100644 index 00000000000..8dbcb53b40b --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCopperCut.java @@ -0,0 +1,51 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.utils.BlockColor; + +public class BlockCopperCut extends BlockCopperBase { + + public BlockCopperCut() { + // Does nothing + } + + @Override + public String getName() { + return "Cut Copper"; + } + + @Override + public int getId() { + return CUT_COPPER; + } + + @Override + public BlockColor getColor() { + return BlockColor.ORANGE_BLOCK_COLOR; + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.UNAFFECTED; + } + + @Override + protected int getCopperId(boolean waxed, OxidizationLevel oxidizationLevel) { + if (oxidizationLevel == null) { + return this.getId(); + } + + switch (oxidizationLevel) { + case UNAFFECTED: + return waxed ? WAXED_CUT_COPPER : CUT_COPPER; + case EXPOSED: + return waxed ? WAXED_EXPOSED_CUT_COPPER : EXPOSED_CUT_COPPER; + case WEATHERED: + return waxed ? WAXED_WEATHERED_CUT_COPPER : WEATHERED_CUT_COPPER; + case OXIDIZED: + return waxed ? WAXED_OXIDIZED_CUT_COPPER : OXIDIZED_CUT_COPPER; + default: + return this.getId(); + } + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockCopperCutExposed.java b/src/main/java/cn/nukkit/block/BlockCopperCutExposed.java new file mode 100644 index 00000000000..b77eefd1b45 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCopperCutExposed.java @@ -0,0 +1,31 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.utils.BlockColor; + +public class BlockCopperCutExposed extends BlockCopperCut { + + public BlockCopperCutExposed() { + // Does nothing + } + + @Override + public String getName() { + return "Exposed Cut Copper"; + } + + @Override + public int getId() { + return EXPOSED_CUT_COPPER; + } + + @Override + public BlockColor getColor() { + return BlockColor.LIGHT_GRAY_TERRACOTA_BLOCK_COLOR; + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.EXPOSED; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCopperCutExposedWaxed.java b/src/main/java/cn/nukkit/block/BlockCopperCutExposedWaxed.java new file mode 100644 index 00000000000..a36ab3d4bde --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCopperCutExposedWaxed.java @@ -0,0 +1,23 @@ +package cn.nukkit.block; + +public class BlockCopperCutExposedWaxed extends BlockCopperCutExposed { + + public BlockCopperCutExposedWaxed() { + // Does nothing + } + + @Override + public String getName() { + return "Waxed Exposed Cut Copper"; + } + + @Override + public int getId() { + return WAXED_EXPOSED_CUT_COPPER; + } + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCopperCutOxidized.java b/src/main/java/cn/nukkit/block/BlockCopperCutOxidized.java new file mode 100644 index 00000000000..790a6435c11 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCopperCutOxidized.java @@ -0,0 +1,31 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.utils.BlockColor; + +public class BlockCopperCutOxidized extends BlockCopperCut { + + public BlockCopperCutOxidized() { + // Does nothing + } + + @Override + public String getName() { + return "Oxidized Cut Copper"; + } + + @Override + public int getId() { + return OXIDIZED_CUT_COPPER; + } + + @Override + public BlockColor getColor() { + return BlockColor.WARPED_NYLIUM_BLOCK_COLOR; + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.OXIDIZED; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCopperCutOxidizedWaxed.java b/src/main/java/cn/nukkit/block/BlockCopperCutOxidizedWaxed.java new file mode 100644 index 00000000000..13a29499f6c --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCopperCutOxidizedWaxed.java @@ -0,0 +1,23 @@ +package cn.nukkit.block; + +public class BlockCopperCutOxidizedWaxed extends BlockCopperCutOxidized { + + public BlockCopperCutOxidizedWaxed() { + // Does nothing + } + + @Override + public String getName() { + return "Waxed Oxidized Cut Copper"; + } + + @Override + public int getId() { + return WAXED_OXIDIZED_CUT_COPPER; + } + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCopperCutWaxed.java b/src/main/java/cn/nukkit/block/BlockCopperCutWaxed.java new file mode 100644 index 00000000000..52c8b0d2348 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCopperCutWaxed.java @@ -0,0 +1,23 @@ +package cn.nukkit.block; + +public class BlockCopperCutWaxed extends BlockCopperCut { + + public BlockCopperCutWaxed() { + // Does nothing + } + + @Override + public String getName() { + return "Waxed Cut Copper"; + } + + @Override + public int getId() { + return WAXED_CUT_COPPER; + } + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCopperCutWeathered.java b/src/main/java/cn/nukkit/block/BlockCopperCutWeathered.java new file mode 100644 index 00000000000..e8885c59d12 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCopperCutWeathered.java @@ -0,0 +1,31 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.utils.BlockColor; + +public class BlockCopperCutWeathered extends BlockCopperCut { + + public BlockCopperCutWeathered() { + // Does nothing + } + + @Override + public String getName() { + return "Weathered Cut Copper"; + } + + @Override + public int getId() { + return WEATHERED_CUT_COPPER; + } + + @Override + public BlockColor getColor() { + return BlockColor.WARPED_STEM_BLOCK_COLOR; + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.WEATHERED; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCopperCutWeatheredWaxed.java b/src/main/java/cn/nukkit/block/BlockCopperCutWeatheredWaxed.java new file mode 100644 index 00000000000..0ffd40655b5 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCopperCutWeatheredWaxed.java @@ -0,0 +1,23 @@ +package cn.nukkit.block; + +public class BlockCopperCutWeatheredWaxed extends BlockCopperCutWeathered { + + public BlockCopperCutWeatheredWaxed() { + // Does nothing + } + + @Override + public String getName() { + return "Waxed Weathered Cut Copper"; + } + + @Override + public int getId() { + return WAXED_WEATHERED_CUT_COPPER; + } + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCopperExposed.java b/src/main/java/cn/nukkit/block/BlockCopperExposed.java new file mode 100644 index 00000000000..4a6568800b2 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCopperExposed.java @@ -0,0 +1,31 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.utils.BlockColor; + +public class BlockCopperExposed extends BlockCopper { + + public BlockCopperExposed() { + // Does nothing + } + + @Override + public String getName() { + return "Exposed Copper"; + } + + @Override + public int getId() { + return EXPOSED_COPPER; + } + + @Override + public BlockColor getColor() { + return BlockColor.LIGHT_GRAY_TERRACOTA_BLOCK_COLOR; + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.EXPOSED; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCopperExposedWaxed.java b/src/main/java/cn/nukkit/block/BlockCopperExposedWaxed.java new file mode 100644 index 00000000000..7b24a095109 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCopperExposedWaxed.java @@ -0,0 +1,23 @@ +package cn.nukkit.block; + +public class BlockCopperExposedWaxed extends BlockCopperExposed { + + public BlockCopperExposedWaxed( ) { + // Does nothing + } + + @Override + public String getName() { + return "Waxed Exposed Copper"; + } + + @Override + public int getId() { + return WAXED_EXPOSED_COPPER; + } + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCopperOxidized.java b/src/main/java/cn/nukkit/block/BlockCopperOxidized.java new file mode 100644 index 00000000000..2df9499a8a3 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCopperOxidized.java @@ -0,0 +1,31 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.utils.BlockColor; + +public class BlockCopperOxidized extends BlockCopper { + + public BlockCopperOxidized() { + // Does nothing + } + + @Override + public String getName() { + return "Oxidized Copper"; + } + + @Override + public int getId() { + return OXIDIZED_COPPER; + } + + @Override + public BlockColor getColor() { + return BlockColor.WARPED_NYLIUM_BLOCK_COLOR; + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.OXIDIZED; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCopperOxidizedWaxed.java b/src/main/java/cn/nukkit/block/BlockCopperOxidizedWaxed.java new file mode 100644 index 00000000000..35bf2facce3 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCopperOxidizedWaxed.java @@ -0,0 +1,23 @@ +package cn.nukkit.block; + +public class BlockCopperOxidizedWaxed extends BlockCopperOxidized { + + public BlockCopperOxidizedWaxed() { + // Does nothing + } + + @Override + public String getName() { + return "Waxed Oxidized Copper"; + } + + @Override + public int getId() { + return WAXED_OXIDIZED_COPPER; + } + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCopperWaxed.java b/src/main/java/cn/nukkit/block/BlockCopperWaxed.java new file mode 100644 index 00000000000..b28423eddf1 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCopperWaxed.java @@ -0,0 +1,23 @@ +package cn.nukkit.block; + +public class BlockCopperWaxed extends BlockCopper { + + public BlockCopperWaxed() { + // Does nothing + } + + @Override + public String getName() { + return "Waxed Block of Copper"; + } + + @Override + public int getId() { + return WAXED_COPPER; + } + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCopperWeathered.java b/src/main/java/cn/nukkit/block/BlockCopperWeathered.java new file mode 100644 index 00000000000..05a62e1e7a1 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCopperWeathered.java @@ -0,0 +1,31 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.utils.BlockColor; + +public class BlockCopperWeathered extends BlockCopper { + + public BlockCopperWeathered() { + // Does nothing + } + + @Override + public String getName() { + return "Weathered Copper"; + } + + @Override + public int getId() { + return WEATHERED_COPPER; + } + + @Override + public BlockColor getColor() { + return BlockColor.WARPED_STEM_BLOCK_COLOR; + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.WEATHERED; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCopperWeatheredWaxed.java b/src/main/java/cn/nukkit/block/BlockCopperWeatheredWaxed.java new file mode 100644 index 00000000000..dc381145457 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCopperWeatheredWaxed.java @@ -0,0 +1,23 @@ +package cn.nukkit.block; + +public class BlockCopperWeatheredWaxed extends BlockCopperWeathered { + + public BlockCopperWeatheredWaxed() { + // Does nothing + } + + @Override + public String getName() { + return "Waxed Weathered Copper"; + } + + @Override + public int getId() { + return WAXED_WEATHERED_COPPER; + } + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCoral.java b/src/main/java/cn/nukkit/block/BlockCoral.java new file mode 100644 index 00000000000..73139c9c87a --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCoral.java @@ -0,0 +1,114 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; + +public class BlockCoral extends BlockTransparentMeta { + + public static final int TYPE_TUBE = 0; + public static final int TYPE_BRAIN = 1; + public static final int TYPE_BUBBLE = 2; + public static final int TYPE_FIRE = 3; + public static final int TYPE_HORN = 4; + + private static final String[] NAMES = { + "Tube Coral", + "Brain Coral", + "Bubble Coral", + "Fire Coral", + "Horn Coral", + "", + "", + "", + "Dead Tube Coral", + "Dead Brain Coral", + "Dead Bubble Coral", + "Dead Fire Coral", + "Dead Horn Coral" + }; + + public BlockCoral() { + this(0); + } + + public BlockCoral(int meta) { + super(meta); + } + + @Override + public String getName() { + int variant = this.getDamage(); + if (variant >= NAMES.length) { + return NAMES[0]; + } + return NAMES[variant]; + } + + @Override + public int getId() { + return CORAL; + } + + public double getHardness() { + return 0; + } + + public double getResistance() { + return 0; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.FLOW_INTO_BLOCK; + } + + @Override + public boolean canSilkTouch() { + return true; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + if (this.down().isTransparent()) { + this.getLevel().useBreakOn(this); + return Level.BLOCK_UPDATE_NORMAL; + } + } + return 0; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (this.down().isTransparent()) { + return false; + } + if (this.getDamage() < 8 && !(block instanceof BlockWater || block.level.isBlockWaterloggedAt(block.getChunk(), (int) block.x, (int) block.y, (int) block.z))) { + this.setDamage(8 + this.getDamage()); // Dead + } + if (this.getLevel().setBlock(this, this, true, true)) { + if (block instanceof BlockWater) { + this.getLevel().setBlock((int) this.x, (int) this.y, (int) this.z, Block.LAYER_WATERLOGGED, Block.get(Block.STILL_WATER), true, true); + } + return true; + } + return false; + } + + @Override + public Item[] getDrops(Item item) { + if (item.getEnchantment(Enchantment.ID_SILK_TOUCH) != null) { + return super.getDrops(item); + } else { + return new Item[0]; + } + } + + @Override + public boolean canPassThrough() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCoralBlock.java b/src/main/java/cn/nukkit/block/BlockCoralBlock.java new file mode 100644 index 00000000000..71fdbc8ea82 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCoralBlock.java @@ -0,0 +1,124 @@ +package cn.nukkit.block; + +import cn.nukkit.event.block.BlockFadeEvent; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; + +import java.util.concurrent.ThreadLocalRandom; + +public class BlockCoralBlock extends BlockSolidMeta { + + private static final String[] NAMES = { + "Tube Coral Block", + "Brain Coral Block", + "Bubble Coral Block", + "Fire Coral Block", + "Horn Coral Block", + }; + + public BlockCoralBlock() { + this(0); + } + + public BlockCoralBlock(int meta) { + super(meta); + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + if (!this.isDead()) { + this.getLevel().scheduleUpdate(this, 60 + ThreadLocalRandom.current().nextInt(40)); + } + return type; + } + + if (type != Level.BLOCK_UPDATE_SCHEDULED) { + return 0; + } + + if (this.isDead()) { + return type; + } + + for (BlockFace face : BlockFace.values()) { + if (this.getSide(BlockLayer.NORMAL, face) instanceof BlockWater || this.getSide(BlockLayer.WATERLOGGED, face) instanceof BlockWater + || this.getSide(BlockLayer.NORMAL, face) instanceof BlockIceFrosted || this.getSide(BlockLayer.WATERLOGGED, face) instanceof BlockIceFrosted) { + return type; + } + } + + BlockFadeEvent event = new BlockFadeEvent(this, Block.get(CORAL_BLOCK, this.getDamage() | 0x8)); + level.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + this.setDead(true); + this.getLevel().setBlock(this, event.getNewState(), true, true); + } + return type; + } + + public double getHardness() { + return 1.5; + } + + public double getResistance() { + return 6; + } + + @Override + public String getName() { + int variant = this.getDamage() & 0x7; + String name; + if (variant >= NAMES.length) { + name = NAMES[0]; + } else { + name = NAMES[variant]; + } + return this.isDead() ? "Dead " + name : name; + } + + @Override + public int getId() { + return CORAL_BLOCK; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public Item[] getDrops(Item item) { + if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.getEnchantment(Enchantment.ID_SILK_TOUCH) != null) { + return new Item[]{this.toItem() }; + } else { + return new Item[]{ new ItemBlock(this.clone(), this.getDamage() | 0x8) }; + } + } else { + return new Item[0]; + } + } + + public boolean isDead() { + return (this.getDamage() & 0x8) == 0x8; + } + + public void setDead(boolean dead) { + if (dead) { + this.setDamage(this.getDamage() | 0x8); + } else { + this.setDamage(this.getDamage() ^ 0x8); + } + } + +} diff --git a/src/main/java/cn/nukkit/block/BlockCoralFan.java b/src/main/java/cn/nukkit/block/BlockCoralFan.java new file mode 100644 index 00000000000..2ba5330c0a2 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCoralFan.java @@ -0,0 +1,195 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.event.block.BlockFadeEvent; +import cn.nukkit.item.Item; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.Faceable; + +import java.util.concurrent.ThreadLocalRandom; + +public class BlockCoralFan extends BlockCoral implements Faceable { + + private static final String[] NAMES = { + "Tube Coral Fan", + "Brain Coral Fan", + "Bubble Coral Fan", + "Fire Coral Fan", + "Horn Coral Fan" + }; + + public BlockCoralFan() { + this(0); + } + + public BlockCoralFan(int meta) { + super(meta); + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + Block side = this.getSide(this.getRootsFace()); + if (!side.isSolid() || side.getId() == MAGMA || side.getId() == SOUL_SAND) { + this.getLevel().useBreakOn(this); + } else { + this.getLevel().scheduleUpdate(this, 60 + ThreadLocalRandom.current().nextInt(40)); + } + return type; + } else if (type == Level.BLOCK_UPDATE_SCHEDULED) { + Block side = this.getSide(this.getRootsFace()); + if (side.getId() == ICE) { + this.getLevel().useBreakOn(this); + return type; + } + + if (!this.isDead() && !(this.getLevelBlock(BlockLayer.WATERLOGGED) instanceof BlockWater) && !(this.getLevelBlock(BlockLayer.WATERLOGGED) instanceof BlockIceFrosted)) { + BlockFadeEvent event = new BlockFadeEvent(this, Block.get(CORAL_FAN_DEAD, this.getDamage())); + level.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + this.getLevel().setBlock(this, event.getNewState(), true, true); + } + } + return type; + } else if (type == Level.BLOCK_UPDATE_RANDOM) { + if ((this.getDamage() & 0x8) == 0) { + this.setDamage(this.getDamage() | 0x8); + } else { + this.setDamage(this.getDamage() ^ 0x8); + } + this.getLevel().setBlock(this, this, true, true); + return type; + } + return 0; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (face == BlockFace.DOWN) { + return false; + } + + Block layer1 = block.getLevelBlock(BlockLayer.WATERLOGGED); + boolean hasWater = layer1 instanceof BlockWater; + if (layer1.getId() != Block.AIR && (!hasWater || layer1.getDamage() != 0 && layer1.getDamage() != 8)) { + return false; + } + + if (hasWater && layer1.getDamage() == 8) { + this.getLevel().setBlock(this, BlockLayer.WATERLOGGED, Block.get(WATER), true, false); + } + + if (!target.isSolid() || target.getId() == MAGMA || target.getId() == SOUL_SAND) { + return false; + } + + if (face == BlockFace.UP) { + double rotation = player.yaw % 360; + if (rotation < 0) { + rotation += 360.0; + } + int axisBit = rotation >= 0 && rotation < 12 || (342 <= rotation && rotation < 360)? 0x0 : 0x8; + this.setDamage(this.getDamage() & 0x7 | axisBit); + this.getLevel().setBlock(this, BlockLayer.NORMAL, hasWater ? new BlockCoralFan(this.getDamage()) : new BlockCoralFanDead(this.getDamage()), true, true); + } else { + int type = this.getType(); + int typeBit = type % 2; + int deadBit = this.isDead()? 0x1 : 0; + int faceBit; + switch (face) { + case WEST: + faceBit = 0; + break; + case EAST: + faceBit = 1; + break; + case NORTH: + faceBit = 2; + break; + default: + case SOUTH: + faceBit = 3; + break; + } + int deadData = faceBit << 2 | deadBit << 1 | typeBit; + int deadBlockId; + switch (type) { + default: + case BlockCoral.TYPE_TUBE: + case BlockCoral.TYPE_BRAIN: + deadBlockId = CORAL_FAN_HANG; + break; + case BlockCoral.TYPE_BUBBLE: + case BlockCoral.TYPE_FIRE: + deadBlockId = CORAL_FAN_HANG2; + break; + case BlockCoral.TYPE_HORN: + deadBlockId = CORAL_FAN_HANG3; + break; + } + this.getLevel().setBlock(this, BlockLayer.NORMAL, Block.get(deadBlockId, deadData), true, true); + } + return true; + } + + + @Override + public String getName() { + int variant = this.getType(); + String name; + if (variant >= NAMES.length) { + name = NAMES[0]; + } else { + name = NAMES[variant]; + } + return name; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.FLOW_INTO_BLOCK; + } + + @Override + public int getId() { + return CORAL_FAN; + } + + @Override + public boolean canSilkTouch() { + return true; + } + + @Override + public Item toItem() { + return Item.get(this.getItemId(), this.getDamage() ^ 0x8); + } + + @Override + public Item[] getDrops(Item item) { + if (item.getEnchantment(Enchantment.ID_SILK_TOUCH) != null) { + return super.getDrops(item); + } else { + return new Item[0]; + } + } + + public boolean isDead() { + return false; + } + + public int getType() { + return this.getDamage() & 0x7; + } + + @Override + public BlockFace getBlockFace() { + return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); + } + + public BlockFace getRootsFace() { + return BlockFace.DOWN; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCoralFanDead.java b/src/main/java/cn/nukkit/block/BlockCoralFanDead.java new file mode 100644 index 00000000000..1bffaded712 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCoralFanDead.java @@ -0,0 +1,48 @@ +package cn.nukkit.block; + +import cn.nukkit.level.Level; +import cn.nukkit.utils.BlockColor; + +public class BlockCoralFanDead extends BlockCoralFan { + + public BlockCoralFanDead() { + this(0); + } + + public BlockCoralFanDead(int meta) { + super(meta); + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + if (!this.getSide(this.getRootsFace()).isSolid()) { + this.getLevel().useBreakOn(this); + } + return type; + } else if (type == Level.BLOCK_UPDATE_RANDOM) { + return super.onUpdate(type); + } + return 0; + } + + @Override + public String getName() { + return "Dead " + super.getName(); + } + + @Override + public BlockColor getColor() { + return BlockColor.GRAY_BLOCK_COLOR; + } + + @Override + public int getId() { + return CORAL_FAN_DEAD; + } + + @Override + public boolean isDead() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCoralFanHang.java b/src/main/java/cn/nukkit/block/BlockCoralFanHang.java new file mode 100644 index 00000000000..394218ff3d9 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCoralFanHang.java @@ -0,0 +1,83 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; + +public class BlockCoralFanHang extends BlockCoralFan { + + public BlockCoralFanHang() { + this(0); + } + + public BlockCoralFanHang(int meta) { + super(meta); + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_RANDOM) { + return type; + } else { + return super.onUpdate(type); + } + } + + @Override + public int getType() { + if ((this.getDamage() & 0b1) == 0) { + return BlockCoral.TYPE_TUBE; + } else { + return BlockCoral.TYPE_BRAIN; + } + } + + @Override + public BlockFace getBlockFace() { + int face = this.getDamage() >> 2 & 0x3; + switch (face) { + case 0: + return BlockFace.WEST; + case 1: + return BlockFace.EAST; + case 2: + return BlockFace.NORTH; + default: + case 3: + return BlockFace.SOUTH; + } + } + + + @Override + public String getName() { + String name = super.getName(); + name = name.substring(0, name.length() - 4); + if (isDead()) { + return "Dead " + name + " Wall Fan"; + } else { + return name + " Wall Fan"; + } + } + + @Override + public boolean isDead() { + return (this.getDamage() & 0b10) == 0b10; + } + + @Override + public BlockFace getRootsFace() { + return this.getBlockFace().getOpposite(); + } + + @Override + public int getId() { + return CORAL_FAN_HANG; + } + + @Override + public Item toItem() { + return new ItemBlock(this.isDead()? new BlockCoralFanDead() : new BlockCoralFan(), this.getType()); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCoralFanHang2.java b/src/main/java/cn/nukkit/block/BlockCoralFanHang2.java new file mode 100644 index 00000000000..3dfeb9fa72c --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCoralFanHang2.java @@ -0,0 +1,26 @@ +package cn.nukkit.block; + +public class BlockCoralFanHang2 extends BlockCoralFanHang { + + public BlockCoralFanHang2() { + this(0); + } + + public BlockCoralFanHang2(int meta) { + super(meta); + } + + @Override + public int getId() { + return CORAL_FAN_HANG2; + } + + @Override + public int getType() { + if ((this.getDamage() & 0b1) == 0) { + return BlockCoral.TYPE_BUBBLE; + } else { + return BlockCoral.TYPE_FIRE; + } + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCoralFanHang3.java b/src/main/java/cn/nukkit/block/BlockCoralFanHang3.java new file mode 100644 index 00000000000..434341e0783 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCoralFanHang3.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockCoralFanHang3 extends BlockCoralFanHang { + + public BlockCoralFanHang3() { + this(0); + } + + public BlockCoralFanHang3(int meta) { + super(meta); + } + + @Override + public int getId() { + return CORAL_FAN_HANG3; + } + + @Override + public int getType() { + return BlockCoral.TYPE_HORN; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCraftingTable.java b/src/main/java/cn/nukkit/block/BlockCraftingTable.java index aa5a9039dde..a5e4e0fb5cd 100644 --- a/src/main/java/cn/nukkit/block/BlockCraftingTable.java +++ b/src/main/java/cn/nukkit/block/BlockCraftingTable.java @@ -1,6 +1,7 @@ package cn.nukkit.block; import cn.nukkit.Player; +import cn.nukkit.event.player.CraftingTableOpenEvent; import cn.nukkit.item.Item; import cn.nukkit.item.ItemTool; import cn.nukkit.network.protocol.ContainerOpenPacket; @@ -11,8 +12,6 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockCraftingTable extends BlockSolid { - public BlockCraftingTable() { - } @Override public String getName() { @@ -47,16 +46,25 @@ public int getToolType() { @Override public boolean onActivate(Item item, Player player) { if (player != null) { - player.craftingType = Player.CRAFTING_BIG; - player.setCraftingGrid(player.getUIInventory().getBigCraftingGrid()); - ContainerOpenPacket pk = new ContainerOpenPacket(); - pk.windowId = -1; - pk.type = 1; - pk.x = (int) x; - pk.y = (int) y; - pk.z = (int) z; - pk.entityId = player.getId(); - player.dataPacket(pk); + CraftingTableOpenEvent ev = new CraftingTableOpenEvent(player, this); + player.getServer().getPluginManager().callEvent(ev); + if (!ev.isCancelled()) { + if (player.craftingType == Player.CRAFTING_BIG) { + player.getServer().getLogger().debug(player.getName() + " tried to activate crafting table but craftingType is already CRAFTING_BIG"); + return true; + } + player.craftingType = Player.CRAFTING_BIG; + player.setCraftingGrid(player.getUIInventory().getBigCraftingGrid()); + + ContainerOpenPacket pk = new ContainerOpenPacket(); + pk.windowId = -1; + pk.type = 1; + pk.x = (int) x; + pk.y = (int) y; + pk.z = (int) z; + pk.entityId = player.getId(); + player.dataPacket(pk); + } } return true; } @@ -65,4 +73,9 @@ public boolean onActivate(Item item, Player player) { public BlockColor getColor() { return BlockColor.WOOD_BLOCK_COLOR; } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } } diff --git a/src/main/java/cn/nukkit/block/BlockCrimsonDoor.java b/src/main/java/cn/nukkit/block/BlockCrimsonDoor.java new file mode 100644 index 00000000000..55e14d4c778 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCrimsonDoor.java @@ -0,0 +1,29 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; + +public class BlockCrimsonDoor extends BlockDoor { + + public BlockCrimsonDoor() { + this(0); + } + + public BlockCrimsonDoor(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Crimson Door"; + } + + @Override + public int getId() { + return CRIMSON_DOOR_BLOCK; + } + + @Override + public Item toItem() { + return Item.get(Item.CRIMSON_DOOR); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCrimsonFungus.java b/src/main/java/cn/nukkit/block/BlockCrimsonFungus.java new file mode 100644 index 00000000000..cecfac16215 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCrimsonFungus.java @@ -0,0 +1,97 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.level.Level; +import cn.nukkit.level.generator.object.tree.ObjectCrimsonTree; +import cn.nukkit.level.particle.BoneMealParticle; +import cn.nukkit.level.Position; +import cn.nukkit.utils.BlockColor; +import cn.nukkit.math.NukkitRandom; +import cn.nukkit.math.Vector3; +import cn.nukkit.utils.DyeColor; + +import java.util.concurrent.ThreadLocalRandom; + +public class BlockCrimsonFungus extends BlockFungus { + + public BlockCrimsonFungus() { + // Does nothing + } + + @Override + public int getId() { + return CRIMSON_FUNGUS; + } + + @Override + public String getName() { + return "Crimson Fungus"; + } + + @Override + protected boolean canGrowOn(Block support) { + return support.getId() == CRIMSON_NYLIUM; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + if (this.down().isTransparent()) { + this.getLevel().useBreakOn(this); + return Level.BLOCK_UPDATE_NORMAL; + } + } + return 0; + } + + @Override + public boolean grow(Player cause) { + // TODO: + return false; + } + + @Override + public BlockColor getColor() { + return BlockColor.NETHERRACK_BLOCK_COLOR; + } + + public boolean canPlaceOn(Block floor, Position pos) { + switch (floor.getId()) { + case BlockID.GRASS: + case BlockID.DIRT: + case BlockID.PODZOL: + case BlockID.FARMLAND: + case BlockID.CRIMSON_NYLIUM: + case BlockID.WARPED_NYLIUM: + case BlockID.MYCELIUM: + case BlockID.SOUL_SOIL: + return true; + default: + return false; + } + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (item.getId() == Item.DYE && item.getDamage() == DyeColor.WHITE.getDyeData()) { + if (player != null && (player.gamemode & 0x01) == 0) { + item.count--; + } + + if (ThreadLocalRandom.current().nextFloat() < 0.4 && this.level.getBlockIdAt((int) this.x, (int) this.y - 1, (int) this.z) == CRIMSON_NYLIUM) { + new ObjectCrimsonTree().placeObject(this.level, (int) this.x, (int) this.y, (int) this.z, new NukkitRandom()); + this.level.setBlock(new Vector3((int) this.x, (int) this.y - 1, (int) this.z), Block.get(NETHERRACK), false, true); + } + + this.level.addParticle(new BoneMealParticle(this)); + return true; + } + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCrimsonNylium.java b/src/main/java/cn/nukkit/block/BlockCrimsonNylium.java new file mode 100644 index 00000000000..d9a92cd64f6 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCrimsonNylium.java @@ -0,0 +1,25 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockCrimsonNylium extends BlockNylium { + + public BlockCrimsonNylium() { + // Does nothing + } + + @Override + public String getName() { + return "Crimson Nylium"; + } + + @Override + public int getId() { + return CRIMSON_NYLIUM; + } + + @Override + public BlockColor getColor() { + return BlockColor.CRIMSON_NYLIUM_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCrimsonPlanks.java b/src/main/java/cn/nukkit/block/BlockCrimsonPlanks.java new file mode 100644 index 00000000000..29fedb8ca1d --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCrimsonPlanks.java @@ -0,0 +1,45 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockCrimsonPlanks extends BlockSolid { + + public BlockCrimsonPlanks() { + this(0); + } + + public BlockCrimsonPlanks(int meta) { + // super(meta); + } + + @Override + public String getName() { + return "Crimson Planks"; + } + + @Override + public int getId() { + return CRIMSON_PLANKS; + } + + @Override + public int getBurnChance() { + return 0; + } + + @Override + public int getBurnAbility() { + return 0; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_AXE; + } + + @Override + public BlockColor getColor() { + return BlockColor.CRIMSON_STEM_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCrimsonRoots.java b/src/main/java/cn/nukkit/block/BlockCrimsonRoots.java new file mode 100644 index 00000000000..b583589db2f --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCrimsonRoots.java @@ -0,0 +1,39 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockCrimsonRoots extends BlockRoots { + + public BlockCrimsonRoots() { + this(0); + } + + public BlockCrimsonRoots(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Crimson Roots"; + } + + @Override + public int getId() { + return CRIMSON_ROOTS; + } + + @Override + public BlockColor getColor() { + return BlockColor.NETHERRACK_BLOCK_COLOR; + } + + @Override + public boolean canBeReplaced() { + return true; + } + + @Override + public boolean breakWhenPushed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCrimsonSign.java b/src/main/java/cn/nukkit/block/BlockCrimsonSign.java new file mode 100644 index 00000000000..5276bbd4e1a --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCrimsonSign.java @@ -0,0 +1,40 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; + +public class BlockCrimsonSign extends BlockSignPost { + + public BlockCrimsonSign() { + this(0); + } + + public BlockCrimsonSign(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Crimson Sign"; + } + + @Override + public int getId() { + return CRIMSON_STANDING_SIGN; + } + + @Override + public Item toItem() { + return Item.get(ItemID.CRIMSON_SIGN); + } + + @Override + protected int getPostId() { + return CRIMSON_STANDING_SIGN; + } + + @Override + protected int getWallId() { + return CRIMSON_WALL_SIGN; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCrimsonStairs.java b/src/main/java/cn/nukkit/block/BlockCrimsonStairs.java new file mode 100644 index 00000000000..2080606f77b --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCrimsonStairs.java @@ -0,0 +1,39 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockCrimsonStairs extends BlockStairsWood { + + public BlockCrimsonStairs() { + this(0); + } + + public BlockCrimsonStairs(int meta) { + super(meta); + } + + @Override + public int getId() { + return CRIMSON_STAIRS; + } + + @Override + public String getName() { + return "Crimson Stairs"; + } + + @Override + public BlockColor getColor() { + return BlockColor.NETHERRACK_BLOCK_COLOR; + } + + @Override + public int getBurnChance() { + return 0; + } + + @Override + public int getBurnAbility() { + return 0; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockCrimsonStem.java b/src/main/java/cn/nukkit/block/BlockCrimsonStem.java new file mode 100644 index 00000000000..067f8fd6cf8 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCrimsonStem.java @@ -0,0 +1,51 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.utils.BlockColor; + +public class BlockCrimsonStem extends BlockStem { + + public BlockCrimsonStem() { + this(0); + } + + public BlockCrimsonStem(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Crimson Stem"; + } + + @Override + public int getId() { + return CRIMSON_STEM; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public int getStrippedId() { + return STRIPPED_CRIMSON_STEM; + } + + @Override + public BlockColor getColor() { + return BlockColor.CRIMSON_STEM_BLOCK_COLOR; + } + + @Override + public int getBurnChance() { + return 0; + } + + @Override + public int getBurnAbility() { + return 0; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockCrimsonTrapdoor.java b/src/main/java/cn/nukkit/block/BlockCrimsonTrapdoor.java new file mode 100644 index 00000000000..e58c80ca0f4 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCrimsonTrapdoor.java @@ -0,0 +1,30 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; + +public class BlockCrimsonTrapdoor extends BlockTrapdoor { + + public BlockCrimsonTrapdoor() { + this(0); + } + + public BlockCrimsonTrapdoor(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Crimson Trapdoor"; + } + + @Override + public int getId() { + return CRIMSON_TRAPDOOR; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCrimsonWallSign.java b/src/main/java/cn/nukkit/block/BlockCrimsonWallSign.java new file mode 100644 index 00000000000..757663c0778 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockCrimsonWallSign.java @@ -0,0 +1,29 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; + +public class BlockCrimsonWallSign extends BlockWallSign { + + public BlockCrimsonWallSign() { + this(0); + } + + public BlockCrimsonWallSign(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Crimson WallSign"; + } + + @Override + public int getId() { + return CRIMSON_WALL_SIGN; + } + + @Override + public Item toItem() { + return Item.get(Item.CRIMSON_SIGN); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockCrops.java b/src/main/java/cn/nukkit/block/BlockCrops.java index f02c05df693..028aaca5d27 100644 --- a/src/main/java/cn/nukkit/block/BlockCrops.java +++ b/src/main/java/cn/nukkit/block/BlockCrops.java @@ -4,15 +4,15 @@ import cn.nukkit.Server; import cn.nukkit.event.block.BlockGrowEvent; import cn.nukkit.item.Item; +import cn.nukkit.item.ItemDye; import cn.nukkit.level.Level; import cn.nukkit.level.particle.BoneMealParticle; import cn.nukkit.math.BlockFace; import cn.nukkit.utils.BlockColor; - -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class BlockCrops extends BlockFlowable { @@ -26,7 +26,6 @@ public boolean canBeActivated() { return true; } - @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { if (block.down().getId() == FARMLAND) { @@ -38,11 +37,10 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl @Override public boolean onActivate(Item item, Player player) { - //Bone meal - if (item.getId() == Item.DYE && item.getDamage() == 0x0f) { + if (item.getId() == Item.DYE && item.getDamage() == ItemDye.BONE_MEAL) { if (this.getDamage() < 7) { BlockCrops block = (BlockCrops) this.clone(); - block.setDamage(block.getDamage() + ThreadLocalRandom.current().nextInt(3) + 2); + block.setDamage(block.getDamage() + Utils.random.nextInt(3) + 2); if (block.getDamage() > 7) { block.setDamage(7); } @@ -54,9 +52,10 @@ public boolean onActivate(Item item, Player player) { } this.getLevel().setBlock(this, ev.getNewState(), false, true); + this.level.addParticle(new BoneMealParticle(this)); - if (player != null && (player.gamemode & 0x01) == 0) { + if (player != null && !player.isCreative()) { item.count--; } } @@ -75,7 +74,7 @@ public int onUpdate(int type) { return Level.BLOCK_UPDATE_NORMAL; } } else if (type == Level.BLOCK_UPDATE_RANDOM) { - if (ThreadLocalRandom.current().nextInt(2) == 1) { + if (Utils.random.nextInt(2) == 1) { if (this.getDamage() < 0x07) { BlockCrops block = (BlockCrops) this.clone(); block.setDamage(block.getDamage() + 1); diff --git a/src/main/java/cn/nukkit/block/BlockDandelion.java b/src/main/java/cn/nukkit/block/BlockDandelion.java index acfe445c8ab..965f7ff4d01 100644 --- a/src/main/java/cn/nukkit/block/BlockDandelion.java +++ b/src/main/java/cn/nukkit/block/BlockDandelion.java @@ -5,6 +5,7 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockDandelion extends BlockFlower { + public BlockDandelion() { this(0); } diff --git a/src/main/java/cn/nukkit/block/BlockDarkOakSignStanding.java b/src/main/java/cn/nukkit/block/BlockDarkOakSignStanding.java new file mode 100644 index 00000000000..255056a8490 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDarkOakSignStanding.java @@ -0,0 +1,40 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; + +public class BlockDarkOakSignStanding extends BlockSignPost { + + public BlockDarkOakSignStanding() { + this(0); + } + + public BlockDarkOakSignStanding(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Dark Oak Sign Post"; + } + + @Override + public int getId() { + return DARK_OAK_STANDING_SIGN; + } + + @Override + public Item toItem() { + return Item.get(ItemID.DARKOAK_SIGN); + } + + @Override + protected int getPostId() { + return DARK_OAK_STANDING_SIGN; + } + + @Override + protected int getWallId() { + return DARK_OAK_WALL_SIGN; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDarkOakWallSign.java b/src/main/java/cn/nukkit/block/BlockDarkOakWallSign.java new file mode 100644 index 00000000000..3a28af6e740 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDarkOakWallSign.java @@ -0,0 +1,40 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; + +public class BlockDarkOakWallSign extends BlockWallSign { + + public BlockDarkOakWallSign() { + this(0); + } + + public BlockDarkOakWallSign(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Dark Oak Wall Sign"; + } + + @Override + public int getId() { + return DARK_OAK_WALL_SIGN; + } + + @Override + public Item toItem() { + return Item.get(ItemID.DARKOAK_SIGN); + } + + @Override + protected int getPostId() { + return DARK_OAK_STANDING_SIGN; + } + + @Override + protected int getWallId() { + return DARK_OAK_WALL_SIGN; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDaylightDetector.java b/src/main/java/cn/nukkit/block/BlockDaylightDetector.java index 8e196e50c94..a327f55ec0f 100644 --- a/src/main/java/cn/nukkit/block/BlockDaylightDetector.java +++ b/src/main/java/cn/nukkit/block/BlockDaylightDetector.java @@ -1,7 +1,10 @@ package cn.nukkit.block; +import cn.nukkit.Player; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; import cn.nukkit.utils.BlockColor; /** @@ -10,9 +13,6 @@ */ public class BlockDaylightDetector extends BlockTransparent { - public BlockDaylightDetector() { - } - @Override public int getId() { return DAYLIGHT_DETECTOR; @@ -33,9 +33,36 @@ public BlockColor getColor() { return BlockColor.WOOD_BLOCK_COLOR; } + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Item item, Player player) { + this.getLevel().setBlock(this, Block.get(DAYLIGHT_DETECTOR_INVERTED)); + return true; + } + @Override public Item toItem() { - return new ItemBlock(this, 0); + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public boolean isPowerSource() { + return true; + } + + @Override + public int getWeakPower(BlockFace face) { + int time = level.getTime() % Level.TIME_FULL; + return time < 13184 || time > 22800 ? 15 : 0; + } + + @Override + public boolean canBePushed() { + return false; } @Override @@ -48,11 +75,30 @@ public double getMaxY() { return this.y + 0.625; } - //This function is a suggestion that can be renamed or deleted - protected boolean invertDetect() { - return false; + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL || type == Level.BLOCK_UPDATE_SCHEDULED) { + if (type == Level.BLOCK_UPDATE_SCHEDULED) { + this.level.updateAroundRedstone(this, null); + } + this.level.scheduleUpdate(this, 40); + } + return 0; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; } - //todo redstone + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (this.getLevel().setBlock(this, this, true, true)) { + this.level.scheduleUpdate(this, 40); + + return true; + } + return false; + } } diff --git a/src/main/java/cn/nukkit/block/BlockDaylightDetectorInverted.java b/src/main/java/cn/nukkit/block/BlockDaylightDetectorInverted.java index 3d0307915b6..3169f1d88cf 100644 --- a/src/main/java/cn/nukkit/block/BlockDaylightDetectorInverted.java +++ b/src/main/java/cn/nukkit/block/BlockDaylightDetectorInverted.java @@ -1,7 +1,10 @@ package cn.nukkit.block; +import cn.nukkit.Player; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; /** * Created on 2015/11/22 by CreeperFace. @@ -9,9 +12,6 @@ */ public class BlockDaylightDetectorInverted extends BlockDaylightDetector { - public BlockDaylightDetectorInverted() { - } - @Override public int getId() { return DAYLIGHT_DETECTOR_INVERTED; @@ -22,13 +22,25 @@ public String getName() { return "Daylight Detector Inverted"; } + @Override + public boolean onActivate(Item item, Player player) { + this.getLevel().setBlock(this, Block.get(DAYLIGHT_DETECTOR)); + return true; + } + @Override public Item toItem() { - return new ItemBlock(Block.get(BlockID.DAYLIGHT_DETECTOR), 0); + return new ItemBlock(Block.get(DAYLIGHT_DETECTOR), 0); } - protected boolean invertDetect() { + @Override + public boolean isPowerSource() { return true; } + @Override + public int getWeakPower(BlockFace face) { + int time = level.getTime() % Level.TIME_FULL; + return time < 13184 || time > 22800 ? 0 : 15; + } } diff --git a/src/main/java/cn/nukkit/block/BlockDeadBush.java b/src/main/java/cn/nukkit/block/BlockDeadBush.java index 23b4c9e2296..66d06ac0108 100644 --- a/src/main/java/cn/nukkit/block/BlockDeadBush.java +++ b/src/main/java/cn/nukkit/block/BlockDeadBush.java @@ -2,24 +2,22 @@ import cn.nukkit.Player; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemStick; import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; import cn.nukkit.utils.BlockColor; - -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; /** * Created on 2015/12/2 by xtypr. * Package cn.nukkit.block in project Nukkit . */ public class BlockDeadBush extends BlockFlowable { + public BlockDeadBush() { this(0); } public BlockDeadBush(int meta) { - // Dead bushes can't have meta. Also stops the server from throwing an exception with the block palette. super(0); } @@ -42,7 +40,7 @@ public boolean canBeReplaced() { public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { Block down = this.down(); int id = down.getId(); - if (id == SAND || id == TERRACOTTA || id == STAINED_TERRACOTTA || id == DIRT || id == PODZOL || id == MYCELIUM || id == GRASS) { + if (id == SAND || id == TERRACOTTA || id == STAINED_TERRACOTTA || id == DIRT || id == PODZOL || id == MYCELIUM || id == GRASS || id == MOSS_BLOCK) { this.getLevel().setBlock(block, this, true, true); return true; } @@ -70,7 +68,7 @@ public Item[] getDrops(Item item) { }; } else { return new Item[]{ - new ItemStick(0, ThreadLocalRandom.current().nextInt(3)) + Item.get(Item.STICK, 0, Utils.random.nextInt(3)) }; } } @@ -78,4 +76,14 @@ public Item[] getDrops(Item item) { public BlockColor getColor() { return BlockColor.FOLIAGE_BLOCK_COLOR; } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockDeepslate.java b/src/main/java/cn/nukkit/block/BlockDeepslate.java new file mode 100644 index 00000000000..803cf8bc4a2 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDeepslate.java @@ -0,0 +1,106 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.BlockColor; + +public class BlockDeepslate extends BlockSolidMeta { + + public BlockDeepslate() { + this(0); + } + + public BlockDeepslate(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Deepslate"; + } + + @Override + public int getId() { + return DEEPSLATE; + } + + @Override + public double getHardness() { + return 3; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + this.setPillarAxis(face.getAxis()); + this.getLevel().setBlock(block, this, true, true); + return true; + } + + public void setPillarAxis(BlockFace.Axis axis) { + switch (axis) { + case Y: + this.setDamage(0); + break; + case X: + this.setDamage(1); + break; + case Z: + this.setDamage(2); + break; + } + } + + public BlockFace.Axis getPillarAxis() { + switch (this.getDamage() % 3) { + case 2: + return BlockFace.Axis.Z; + case 1: + return BlockFace.Axis.X; + case 0: + default: + return BlockFace.Axis.Y; + } + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(DEEPSLATE), 0); + } + + @Override + public Item[] getDrops(Item item) { + if (!this.canHarvest(item)) { + return new Item[0]; + } + + return new Item[]{new ItemBlock(Block.get(COBBLED_DEEPSLATE), 0)}; + } + + @Override + public boolean canSilkTouch() { + return true; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDeepslateChiseled.java b/src/main/java/cn/nukkit/block/BlockDeepslateChiseled.java new file mode 100644 index 00000000000..ec1bc34b5cf --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDeepslateChiseled.java @@ -0,0 +1,17 @@ +package cn.nukkit.block; + +public class BlockDeepslateChiseled extends BlockDeepslateCobbled { + + public BlockDeepslateChiseled() { + } + + @Override + public int getId() { + return CHISELED_DEEPSLATE; + } + + @Override + public String getName() { + return "Chiseled Deepslate"; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDeepslateCobbled.java b/src/main/java/cn/nukkit/block/BlockDeepslateCobbled.java new file mode 100644 index 00000000000..3c7dfaf4dfd --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDeepslateCobbled.java @@ -0,0 +1,40 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; + +public class BlockDeepslateCobbled extends BlockSolid { + + public BlockDeepslateCobbled() { + } + + @Override + public String getName() { + return "Cobbled Deepslate"; + } + + @Override + public int getId() { + return COBBLED_DEEPSLATE; + } + + @Override + public double getHardness() { + return 3.5; + } + + @Override + public double getResistance() { + return 6.0; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDeepslatePolished.java b/src/main/java/cn/nukkit/block/BlockDeepslatePolished.java new file mode 100644 index 00000000000..76ed536817c --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDeepslatePolished.java @@ -0,0 +1,18 @@ +package cn.nukkit.block; + +public class BlockDeepslatePolished extends BlockDeepslateCobbled { + + public BlockDeepslatePolished() { + // Does nothing + } + + @Override + public String getName() { + return "Polished Deepslate"; + } + + @Override + public int getId() { + return POLISHED_DEEPSLATE; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDeny.java b/src/main/java/cn/nukkit/block/BlockDeny.java new file mode 100644 index 00000000000..26c60adca9b --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDeny.java @@ -0,0 +1,41 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; + +public class BlockDeny extends BlockSolid { + + @Override + public int getId() { + return DENY; + } + + @Override + public double getHardness() { + return -1; + } + + @Override + public double getResistance() { + return 18000000; + } + + @Override + public String getName() { + return "Deny"; + } + + @Override + public boolean isBreakable(Item item) { + return false; + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDiamond.java b/src/main/java/cn/nukkit/block/BlockDiamond.java index 53073452789..61f95a42c96 100644 --- a/src/main/java/cn/nukkit/block/BlockDiamond.java +++ b/src/main/java/cn/nukkit/block/BlockDiamond.java @@ -9,9 +9,6 @@ */ public class BlockDiamond extends BlockSolid { - public BlockDiamond() { - } - @Override public double getHardness() { return 5; @@ -34,7 +31,7 @@ public int getId() { @Override public String getName() { - return "Diamond Block"; + return "Block of Diamond"; } @Override diff --git a/src/main/java/cn/nukkit/block/BlockDirt.java b/src/main/java/cn/nukkit/block/BlockDirt.java index dd87fb80c7e..54dba736218 100644 --- a/src/main/java/cn/nukkit/block/BlockDirt.java +++ b/src/main/java/cn/nukkit/block/BlockDirt.java @@ -1,13 +1,14 @@ package cn.nukkit.block; import cn.nukkit.Player; -import cn.nukkit.item.Item; -import cn.nukkit.item.ItemBlock; -import cn.nukkit.item.ItemTool; +import cn.nukkit.item.*; +import cn.nukkit.level.Sound; +import cn.nukkit.level.generator.object.ObjectTallGrass; +import cn.nukkit.level.particle.BoneMealParticle; import cn.nukkit.utils.BlockColor; /** - * author: MagicDroidX + * @author MagicDroidX * AMAZING COARSE DIRT added by kvetinac97 * Nukkit Project */ @@ -17,7 +18,7 @@ public BlockDirt() { this(0); } - public BlockDirt(int meta){ + public BlockDirt(int meta) { super(meta); } @@ -54,17 +55,47 @@ public String getName() { @Override public boolean onActivate(Item item, Player player) { if (item.isHoe()) { - if (this.up() instanceof BlockAir) { + Block up = this.up(); + if (up instanceof BlockAir || up instanceof BlockFlowable) { item.useOn(this); this.getLevel().setBlock(this, this.getDamage() == 0 ? get(FARMLAND) : get(DIRT), true); + if (player != null) { + player.getLevel().addSound(player, Sound.STEP_GRASS); + } return true; } } else if (item.isShovel()) { - if (this.up() instanceof BlockAir) { + Block up = this.up(); + if (up instanceof BlockAir || up instanceof BlockFlowable) { item.useOn(this); - this.getLevel().setBlock(this, get(GRASS_PATH)); + this.getLevel().setBlock(this, Block.get(GRASS_PATH)); + if (player != null) { + player.getLevel().addSound(player, Sound.STEP_GRASS); + } return true; } + } else if (player != null && item.getId() == Item.DYE && item.getDamage() == ItemDye.BONE_MEAL) { + Block up = this.up(); + if (up instanceof BlockWater) { + if (!player.isCreative()) { + item.count--; + } + this.level.addParticle(new BoneMealParticle(this)); + if (up.up() instanceof BlockWater) { + ObjectTallGrass.growSeagrass(this.getLevel(), this); + } + return true; + } + } else if (player != null && item.getId() == Item.POTION && item.getDamage() == ItemPotion.NO_EFFECTS) { + item.count--; + Item emptyBottle = Item.get(Item.GLASS_BOTTLE); + if (player.getInventory().canAddItem(emptyBottle)) { + player.getInventory().addItem(emptyBottle); + } else { + player.getLevel().dropItem(player.add(0, 1.3, 0), emptyBottle, player.getDirectionVector().multiply(0.4)); + } + this.getLevel().setBlock(this, get(MUD), true); + return true; } return false; @@ -72,7 +103,8 @@ public boolean onActivate(Item item, Player player) { @Override public Item[] getDrops(Item item) { - return new Item[]{new ItemBlock(Block.get(BlockID.DIRT))}; + int damage = this.getDamage() & 0x01; + return new Item[]{new ItemBlock(Block.get(BlockID.DIRT, damage), damage)}; } @Override diff --git a/src/main/java/cn/nukkit/block/BlockDirtRooted.java b/src/main/java/cn/nukkit/block/BlockDirtRooted.java new file mode 100644 index 00000000000..4a888b24c70 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDirtRooted.java @@ -0,0 +1,81 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.event.block.BlockGrowEvent; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemDye; +import cn.nukkit.level.Sound; +import cn.nukkit.level.particle.BoneMealParticle; + +public class BlockDirtRooted extends BlockDirt { + + public BlockDirtRooted() { + this(0); + } + + public BlockDirtRooted(int meta) { + super(0); // no different states + } + + @Override + public int getId() { + return ROOTED_DIRT; + } + + @Override + public String getName() { + return "Rooted Dirt"; + } + + @Override + public boolean onActivate(Item item, Player player) { + Block up = this.up(); + if (item.isShovel() && (up instanceof BlockAir || up instanceof BlockFlowable)) { + item.useOn(this); + this.getLevel().setBlock(this, Block.get(GRASS_PATH)); + if (player != null) { + player.getLevel().addSound(player, Sound.STEP_GRASS); + } + return true; + } + + if (item.isHoe() && (up instanceof BlockAir || up instanceof BlockFlowable)) { + item.useOn(this); + this.getLevel().setBlock(this, Block.get(DIRT)); + if (player != null) { + player.getLevel().addSound(player, Sound.STEP_GRASS); + } + this.getLevel().dropItem(this.add(0.5, 0.8, 0.5), new ItemBlock(Block.get(HANGING_ROOTS), 0)); + return true; + } + + if (item.getId() != Item.DYE || item.getDamage() != ItemDye.BONE_MEAL) { + return false; + } + + Block down = this.down(); + BlockGrowEvent event = new BlockGrowEvent(down, Block.get(BlockID.HANGING_ROOTS, 0, down)); + this.getLevel().getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return false; + } + + if (down.getId() == AIR || down.canBeReplaced()) { + this.getLevel().setBlock(down, Block.get(HANGING_ROOTS)); + this.level.addParticle(new BoneMealParticle(down)); + return true; + } + return false; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId()), 0, 1); + } + + @Override + public Item[] getDrops(Item item) { + return new Item[]{ this.toItem() }; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDispenser.java b/src/main/java/cn/nukkit/block/BlockDispenser.java index 3bd7bbd75f5..0976b60b37b 100644 --- a/src/main/java/cn/nukkit/block/BlockDispenser.java +++ b/src/main/java/cn/nukkit/block/BlockDispenser.java @@ -1,10 +1,23 @@ package cn.nukkit.block; +import cn.nukkit.Player; +import cn.nukkit.blockentity.BlockEntity; +import cn.nukkit.blockentity.BlockEntityDispenser; +import cn.nukkit.dispenser.DispenseBehavior; +import cn.nukkit.dispenser.DispenseBehaviorRegister; +import cn.nukkit.inventory.ContainerInventory; +import cn.nukkit.inventory.Inventory; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; +import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; import cn.nukkit.math.Vector3; +import cn.nukkit.nbt.tag.StringTag; +import cn.nukkit.network.protocol.LevelSoundEventPacket; import cn.nukkit.utils.Faceable; +import cn.nukkit.utils.Utils; + +import java.util.Map.Entry; /** * Created by CreeperFace on 15.4.2017. @@ -36,22 +49,18 @@ public int getId() { @Override public Item toItem() { - return new ItemBlock(this, 0); + return new ItemBlock(Block.get(Block.DISPENSER)); } @Override public int getComparatorInputOverride() { - /*BlockEntity blockEntity = this.level.getBlockEntity(this); - - if(blockEntity instanceof BlockEntityDispenser) { - //return ContainerInventory.calculateRedstone(((BlockEntityDispenser) blockEntity).getInventory()); TODO: dispenser - }*/ + BlockEntity blockEntity = this.level.getBlockEntity(this); - return super.getComparatorInputOverride(); - } + if (blockEntity instanceof BlockEntityDispenser) { + return ContainerInventory.calculateRedstone(((BlockEntityDispenser) blockEntity).getInventory()); + } - public BlockFace getFacing() { - return BlockFace.fromIndex(this.getDamage() & 7); + return 0; } public boolean isTriggered() { @@ -60,7 +69,7 @@ public boolean isTriggered() { public void setTriggered(boolean value) { int i = 0; - i |= getFacing().getIndex(); + i |= getBlockFace().getIndex(); if (value) { i |= 8; @@ -70,20 +79,136 @@ public void setTriggered(boolean value) { } @Override - public boolean canHarvestWithHand() { - return false; + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (player == null) { + return false; + } + + BlockEntity blockEntity = this.level.getBlockEntity(this); + + if (!(blockEntity instanceof BlockEntityDispenser)) { + return false; + } + + if (blockEntity.namedTag.contains("Lock") && blockEntity.namedTag.get("Lock") instanceof StringTag) { + if (!blockEntity.namedTag.getString("Lock").equals(item.getCustomName())) { + return true; + } + } + + player.addWindow(((BlockEntityDispenser) blockEntity).getInventory()); + return true; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (player != null) { + if (Math.abs(player.x - this.x) < 2 && Math.abs(player.z - this.z) < 2) { + double y = player.y + player.getEyeHeight(); + + if (y - this.y > 2) { + this.setDamage(BlockFace.UP.getIndex()); + } else if (this.y - y > 0) { + this.setDamage(BlockFace.DOWN.getIndex()); + } else { + this.setDamage(player.getHorizontalFacing().getOpposite().getIndex()); + } + } else { + this.setDamage(player.getHorizontalFacing().getOpposite().getIndex()); + } + } + + this.getLevel().setBlock(block, this, true); + + BlockEntity.createBlockEntity(BlockEntity.DISPENSER, this.getChunk(), BlockEntity.getDefaultCompound(this, BlockEntity.DISPENSER)); + return true; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_SCHEDULED) { + this.setTriggered(false); + this.level.setBlock((int) this.x, (int) this.y, (int) this.z, BlockLayer.NORMAL, this, false, false, false); // No need to send this to client + dispense(); + return type; + } else if (type == Level.BLOCK_UPDATE_REDSTONE) { + if (!isTriggered() && (level.isBlockPowered(this) || level.isBlockPowered(this.getSideVec(BlockFace.UP)))) { + this.setTriggered(true); + this.level.setBlock((int) this.x, (int) this.y, (int) this.z, BlockLayer.NORMAL, this, false, false, false); // No need to send this to client + level.scheduleUpdate(this, this, 4); + } + + return type; + } + + return 0; + } + + public void dispense() { + BlockEntity blockEntity = this.level.getBlockEntity(this); + + if (!(blockEntity instanceof BlockEntityDispenser)) { + return; + } + + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_BLOCK_CLICK); + + int r = 1; + int slot = -1; + Item target = null; + + Inventory inv = ((BlockEntityDispenser) blockEntity).getInventory(); + for (Entry entry : inv.getContents().entrySet()) { + Item item = entry.getValue(); + + if (!item.isNull() && Utils.random.nextInt(r++) == 0) { + target = item; + slot = entry.getKey(); + } + } + + if (target == null) { + return; + } + target = target.clone(); + + DispenseBehavior behavior = DispenseBehaviorRegister.getBehavior(target.getId()); + Item result = behavior.dispense(this, getBlockFace(), target); + + if (result == null) { + target.count--; + inv.setItem(slot, target); + } else if (!result.equals(target)) { + inv.setItem(slot, result); + } } public Vector3 getDispensePosition() { - BlockFace facing = getFacing(); - double x = this.getX() + 0.7 * facing.getXOffset(); - double y = this.getY() + 0.7 * facing.getYOffset(); - double z = this.getZ() + 0.7 * facing.getZOffset(); - return new Vector3(x, y, z); + BlockFace facing = getBlockFace(); + return this.add( + 0.5 + 0.7 * facing.getXOffset(), + 0.5 + 0.7 * facing.getYOffset(), + 0.5 + 0.7 * facing.getZOffset() + ); } @Override public BlockFace getBlockFace() { - return BlockFace.fromHorizontalIndex(this.getDamage() & 0x07); + return BlockFace.fromIndex(this.getDamage() & 0x07); + } + + @Override + public double getHardness() { + return 3.5; + } + + @Override + public boolean canBePushed() { + return false; // prevent item loss issue with pistons until a working implementation } } diff --git a/src/main/java/cn/nukkit/block/BlockDoor.java b/src/main/java/cn/nukkit/block/BlockDoor.java index 53995465ecb..b55eab93cbd 100644 --- a/src/main/java/cn/nukkit/block/BlockDoor.java +++ b/src/main/java/cn/nukkit/block/BlockDoor.java @@ -5,22 +5,24 @@ import cn.nukkit.event.block.DoorToggleEvent; import cn.nukkit.item.Item; import cn.nukkit.level.Level; +import cn.nukkit.level.Sound; import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.math.BlockFace; import cn.nukkit.math.SimpleAxisAlignedBB; -import cn.nukkit.network.protocol.LevelEventPacket; import cn.nukkit.utils.Faceable; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class BlockDoor extends BlockTransparentMeta implements Faceable { - public static int DOOR_OPEN_BIT = 0x04; - public static int DOOR_TOP_BIT = 0x08; - public static int DOOR_HINGE_BIT = 0x01; - public static int DOOR_POWERED_BIT = 0x02; + public static final int DOOR_OPEN_BIT = 0x04; + public static final int DOOR_TOP_BIT = 0x08; + public static final int DOOR_HINGE_BIT = 0x01; + public static final int DOOR_POWERED_BIT = 0x02; + + private static final int[] FACES = {1, 2, 3, 0}; protected BlockDoor(int meta) { super(meta); @@ -36,21 +38,27 @@ public boolean isSolid() { return false; } - public int getFullDamage() { - int meta; - + private int getFullDamage() { + int up; + int down; if (isTop()) { - meta = this.down().getDamage(); + down = this.down().getDamage(); + up = this.getDamage(); } else { - meta = this.getDamage(); + down = this.getDamage(); + up = this.up().getDamage(); } - return (this.getId() << 5 ) + (meta & 0x07 | (isTop() ? 0x08 : 0) | (isRightHinged() ? 0x10 :0)); + + boolean isRight = (up & DOOR_HINGE_BIT) > 0; + + return down & 0x07 | (isTop() ? 0x08 : 0) | (isRight ? 0x10 : 0); } @Override protected AxisAlignedBB recalculateBoundingBox() { double f = 0.1875; + int damage = this.getFullDamage(); AxisAlignedBB bb = new SimpleAxisAlignedBB( this.x, @@ -61,9 +69,9 @@ protected AxisAlignedBB recalculateBoundingBox() { this.z + 1 ); - int j = isTop() ? (this.down().getDamage() & 0x03) : getDamage() & 0x03; - boolean isOpen = isOpen(); - boolean isRight = isRightHinged(); + int j = damage & 0x03; + boolean isOpen = ((damage & 0x04) > 0); + boolean isRight = ((damage & 0x10) > 0); if (j == 0) { if (isOpen) { @@ -210,7 +218,8 @@ public int onUpdate(int type) { } if (type == Level.BLOCK_UPDATE_REDSTONE) { - if ((!isOpen() && this.level.isBlockPowered(this.getLocation())) || (isOpen() && !this.level.isBlockPowered(this.getLocation()))) { + boolean powered = this.level.isBlockPowered(this); + if ((!isOpen() && powered) || (isOpen() && !powered)) { this.level.getServer().getPluginManager().callEvent(new BlockRedstoneEvent(this, isOpen() ? 15 : 0, isOpen() ? 0 : 15)); this.toggle(null); @@ -222,15 +231,14 @@ public int onUpdate(int type) { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - if (this.y > 254) return false; + if (this.y > target.getLevel().getMaxBlockY() - 1) return false; if (face == BlockFace.UP) { Block blockUp = this.up(); - Block blockDown = this.down(); - if (!blockUp.canBeReplaced() || blockDown.isTransparent()) { + if (!blockUp.canBeReplaced() || !canStayOnFullNonSolid(this.down())) { return false; } - int[] faces = {1, 2, 3, 0}; - int direction = faces[player != null ? player.getDirection().getHorizontalIndex() : 0]; + + int direction = FACES[player != null ? player.getDirection().getHorizontalIndex() : 0]; Block left = this.getSide(player.getDirection().rotateYCCW()); Block right = this.getSide(player.getDirection().rotateY()); @@ -240,15 +248,12 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl } this.setDamage(direction); - this.getLevel().setBlock(block, this, true, false); //Bottom - this.getLevel().setBlock(blockUp, Block.get(this.getId(), metaUp), true, true); //Top - if (!this.isOpen() && this.level.isBlockPowered(this.getLocation())) { - this.toggle(null); - metaUp |= DOOR_POWERED_BIT; - this.getLevel().setBlockDataAt(blockUp.getFloorX(), blockUp.getFloorY(), blockUp.getFloorZ(), metaUp); - } + //Bottom + this.getLevel().setBlock(this, this, true, true); + //Top + this.getLevel().setBlock(blockUp, Block.get(this.getId(), metaUp), true); return true; } @@ -273,19 +278,9 @@ public boolean onBreak(Item item) { return true; } - @Override - public boolean onActivate(Item item) { - return this.onActivate(item, null); - } - @Override public boolean onActivate(Item item, Player player) { - if (!this.toggle(player)) { - return false; - } - - this.getLevel().addLevelEvent(this.add(0.5, 0.5, 0.5), LevelEventPacket.EVENT_SOUND_DOOR); - return true; + return this.toggle(player); } public boolean toggle(Player player) { @@ -297,19 +292,37 @@ public boolean toggle(Player player) { } Block down; - if (isTop()) { + Block up; + if (isTop(this.getDamage())) { down = this.down(); + up = this; } else { down = this; + up = this.up(); } - if (down.up().getId() != down.getId()) { + + if (up.getId() != down.getId()) { return false; } - down.setDamage(down.getDamage() ^ DOOR_OPEN_BIT); - getLevel().setBlock(down, down, true, true); + + int data = down.getDamage() ^ 0x04; + this.level.setBlockDataAt(down.getFloorX(), down.getFloorY(), down.getFloorZ(), data); + if (this.isOpenAfter(data)) { + this.level.addSound(this, Sound.RANDOM_DOOR_OPEN); + } else { + this.level.addSound(this, Sound.RANDOM_DOOR_CLOSE); + } return true; } + private boolean isOpenAfter(int data) { + if (isTop(data)) { + return (this.down().getDamage() & DOOR_OPEN_BIT) > 0; + } else { + return (data & DOOR_OPEN_BIT) > 0; + } + } + public boolean isOpen() { if (isTop(this.getDamage())) { return (this.down().getDamage() & DOOR_OPEN_BIT) > 0; @@ -317,6 +330,7 @@ public boolean isOpen() { return (this.getDamage() & DOOR_OPEN_BIT) > 0; } } + public boolean isTop() { return isTop(this.getDamage()); } @@ -334,6 +348,16 @@ public boolean isRightHinged() { @Override public BlockFace getBlockFace() { - return BlockFace.fromHorizontalIndex(this.getDamage() & 0x07); + return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean breakWhenPushed() { + return true; } } diff --git a/src/main/java/cn/nukkit/block/BlockDoorAcacia.java b/src/main/java/cn/nukkit/block/BlockDoorAcacia.java index 0ca8279bbf0..46503b1c544 100644 --- a/src/main/java/cn/nukkit/block/BlockDoorAcacia.java +++ b/src/main/java/cn/nukkit/block/BlockDoorAcacia.java @@ -1,7 +1,6 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemDoorAcacia; import cn.nukkit.utils.BlockColor; public class BlockDoorAcacia extends BlockDoorWood { @@ -26,7 +25,7 @@ public int getId() { @Override public Item toItem() { - return new ItemDoorAcacia(); + return Item.get(Item.ACACIA_DOOR); } @Override diff --git a/src/main/java/cn/nukkit/block/BlockDoorBirch.java b/src/main/java/cn/nukkit/block/BlockDoorBirch.java index 6556596f898..66cf813df2a 100644 --- a/src/main/java/cn/nukkit/block/BlockDoorBirch.java +++ b/src/main/java/cn/nukkit/block/BlockDoorBirch.java @@ -1,7 +1,6 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemDoorBirch; import cn.nukkit.utils.BlockColor; public class BlockDoorBirch extends BlockDoorWood { @@ -26,7 +25,7 @@ public int getId() { @Override public Item toItem() { - return new ItemDoorBirch(); + return Item.get(Item.BIRCH_DOOR); } @Override diff --git a/src/main/java/cn/nukkit/block/BlockDoorDarkOak.java b/src/main/java/cn/nukkit/block/BlockDoorDarkOak.java index 4da32f31c85..38c90229867 100644 --- a/src/main/java/cn/nukkit/block/BlockDoorDarkOak.java +++ b/src/main/java/cn/nukkit/block/BlockDoorDarkOak.java @@ -1,7 +1,6 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemDoorDarkOak; import cn.nukkit.utils.BlockColor; public class BlockDoorDarkOak extends BlockDoorWood { @@ -26,7 +25,7 @@ public int getId() { @Override public Item toItem() { - return new ItemDoorDarkOak(); + return Item.get(Item.DARK_OAK_DOOR); } @Override diff --git a/src/main/java/cn/nukkit/block/BlockDoorIron.java b/src/main/java/cn/nukkit/block/BlockDoorIron.java index 74df6c75bd8..2a7a572c6b7 100644 --- a/src/main/java/cn/nukkit/block/BlockDoorIron.java +++ b/src/main/java/cn/nukkit/block/BlockDoorIron.java @@ -2,12 +2,11 @@ import cn.nukkit.Player; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemDoorIron; import cn.nukkit.item.ItemTool; import cn.nukkit.utils.BlockColor; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockDoorIron extends BlockDoor { @@ -30,11 +29,6 @@ public int getId() { return IRON_DOOR_BLOCK; } - @Override - public boolean canBeActivated() { - return true; - } - @Override public double getHardness() { return 5; @@ -52,7 +46,7 @@ public int getToolType() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; @@ -63,7 +57,7 @@ public Item[] getDrops(Item item) { @Override public Item toItem() { - return new ItemDoorIron(); + return Item.get(Item.IRON_DOOR); } @Override diff --git a/src/main/java/cn/nukkit/block/BlockDoorJungle.java b/src/main/java/cn/nukkit/block/BlockDoorJungle.java index 5f6cb1fed5a..2af2d291a69 100644 --- a/src/main/java/cn/nukkit/block/BlockDoorJungle.java +++ b/src/main/java/cn/nukkit/block/BlockDoorJungle.java @@ -1,7 +1,6 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemDoorJungle; import cn.nukkit.utils.BlockColor; public class BlockDoorJungle extends BlockDoorWood { @@ -26,7 +25,7 @@ public int getId() { @Override public Item toItem() { - return new ItemDoorJungle(); + return Item.get(Item.JUNGLE_DOOR); } @Override diff --git a/src/main/java/cn/nukkit/block/BlockDoorSpruce.java b/src/main/java/cn/nukkit/block/BlockDoorSpruce.java index 1f9accf6ebe..05b3f0f66a1 100644 --- a/src/main/java/cn/nukkit/block/BlockDoorSpruce.java +++ b/src/main/java/cn/nukkit/block/BlockDoorSpruce.java @@ -1,7 +1,6 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemDoorSpruce; import cn.nukkit.utils.BlockColor; public class BlockDoorSpruce extends BlockDoorWood { @@ -26,7 +25,7 @@ public int getId() { @Override public Item toItem() { - return new ItemDoorSpruce(); + return Item.get(Item.SPRUCE_DOOR); } @Override diff --git a/src/main/java/cn/nukkit/block/BlockDoorWood.java b/src/main/java/cn/nukkit/block/BlockDoorWood.java index ad34c77d4d7..27a79562fa8 100644 --- a/src/main/java/cn/nukkit/block/BlockDoorWood.java +++ b/src/main/java/cn/nukkit/block/BlockDoorWood.java @@ -1,12 +1,11 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemDoorWood; import cn.nukkit.item.ItemTool; import cn.nukkit.utils.BlockColor; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockDoorWood extends BlockDoor { @@ -46,7 +45,7 @@ public int getToolType() { @Override public Item toItem() { - return new ItemDoorWood(); + return Item.get(Item.WOODEN_DOOR); } @Override diff --git a/src/main/java/cn/nukkit/block/BlockDoubleMudBrickSlab.java b/src/main/java/cn/nukkit/block/BlockDoubleMudBrickSlab.java new file mode 100644 index 00000000000..ff60c220548 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleMudBrickSlab.java @@ -0,0 +1,31 @@ +package cn.nukkit.block; + +public class BlockDoubleMudBrickSlab extends BlockDoubleSlabBase { + + public BlockDoubleMudBrickSlab() { + this(0); + } + + public BlockDoubleMudBrickSlab(int meta) { + super(meta); + } + + @Override + public int getId() { + return MUD_BRICK_DOUBLE_SLAB; + } + + @Override + public String getSlabName() { + return "Double Mud Brick Slab"; + } + @Override + public int getSingleSlabId() { + return MUD_BRICK_SLAB; + } + + @Override + public int getItemDamage() { + return 0; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoublePlant.java b/src/main/java/cn/nukkit/block/BlockDoublePlant.java index a5686af96d8..9d0ce3ace01 100644 --- a/src/main/java/cn/nukkit/block/BlockDoublePlant.java +++ b/src/main/java/cn/nukkit/block/BlockDoublePlant.java @@ -2,19 +2,20 @@ import cn.nukkit.Player; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemSeedsWheat; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemDye; import cn.nukkit.level.Level; import cn.nukkit.level.particle.BoneMealParticle; import cn.nukkit.math.BlockFace; import cn.nukkit.utils.BlockColor; - -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; /** * Created on 2015/11/23 by xtypr. * Package cn.nukkit.block in project Nukkit . */ public class BlockDoublePlant extends BlockFlowable { + public static final int SUNFLOWER = 0; public static final int LILAC = 1; public static final int TALL_GRASS = 2; @@ -23,7 +24,7 @@ public class BlockDoublePlant extends BlockFlowable { public static final int PEONY = 5; public static final int TOP_HALF_BITMASK = 0x8; - private static final String[] NAMES = new String[]{ + private static final String[] NAMES = { "Sunflower", "Lilac", "Double Tallgrass", @@ -47,7 +48,8 @@ public int getId() { @Override public boolean canBeReplaced() { - return this.getDamage() == TALL_GRASS || this.getDamage() == LARGE_FERN; + int damage = this.getDamage() & 0x7; + return damage == TALL_GRASS || damage == LARGE_FERN; } @Override @@ -82,9 +84,10 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl Block up = up(); int id = down.getId(); - if (up.getId() == AIR && (id == GRASS || id == DIRT || id == PODZOL || id == FARMLAND || id == MYCELIUM)) { - this.getLevel().setBlock(block, this, true, false); // If we update the bottom half, it will drop the item because there isn't a flower block above - this.getLevel().setBlock(up, Block.get(BlockID.DOUBLE_PLANT, getDamage() ^ TOP_HALF_BITMASK), true, true); + if (up.getId() == AIR && (id == GRASS || id == DIRT || id == PODZOL || id == FARMLAND || id == MYCELIUM || id == MOSS_BLOCK)) { + // Place top half first in order to call block updates on bottom part, but do not update to prevent breaking. + this.getLevel().setBlock(up, Block.get(DOUBLE_PLANT, getDamage() ^ TOP_HALF_BITMASK), true, false); + this.getLevel().setBlock(block, this, true, true); return true; } @@ -93,10 +96,11 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl @Override public boolean onBreak(Item item) { - Block down = down(); - if ((this.getDamage() & TOP_HALF_BITMASK) == TOP_HALF_BITMASK) { // Top half - this.getLevel().useBreakOn(down); + Block down = down(); + if (down instanceof BlockDoublePlant) { + this.getLevel().useBreakOn(down); + } } else { this.getLevel().setBlock(this, Block.get(BlockID.AIR), true, true); } @@ -107,27 +111,27 @@ public boolean onBreak(Item item) { @Override public Item[] getDrops(Item item) { if ((this.getDamage() & TOP_HALF_BITMASK) != TOP_HALF_BITMASK) { - switch (this.getDamage() & 0x07) { + int type = this.getDamage() & 0x07; + switch (type) { case TALL_GRASS: case LARGE_FERN: - boolean dropSeeds = ThreadLocalRandom.current().nextInt(10) == 0; + boolean dropSeeds = Utils.random.nextInt(10) == 0; if (item.isShears()) { - //todo enchantment if (dropSeeds) { return new Item[]{ - new ItemSeedsWheat(0, 1), - toItem() + Item.get(Item.WHEAT_SEEDS), + Item.get(Item.TALL_GRASS, type == LARGE_FERN ? 2 : 1, 2) }; } else { return new Item[]{ - toItem() + Item.get(Item.TALL_GRASS, type == LARGE_FERN ? 2 : 1, 2) }; } } if (dropSeeds) { return new Item[]{ - new ItemSeedsWheat() + Item.get(Item.WHEAT_SEEDS) }; } else { return new Item[0]; @@ -152,22 +156,23 @@ public boolean canBeActivated() { @Override public boolean onActivate(Item item, Player player) { - if (item.getId() == Item.DYE && item.getDamage() == 0x0f) { //Bone meal - switch (this.getDamage() & 0x07) { - case SUNFLOWER: - case LILAC: - case ROSE_BUSH: - case PEONY: - if (player != null && (player.gamemode & 0x01) == 0) { - item.count--; - } - this.level.addParticle(new BoneMealParticle(this)); - this.level.dropItem(this, this.toItem()); - } + if (item.getId() == Item.DYE && item.getDamage() == ItemDye.BONE_MEAL) { + int type = this.getDamage() & 0x07; + if (type == SUNFLOWER || type == LILAC || type == ROSE_BUSH || type == PEONY) { // Flower + if (player != null && !player.isCreative()) { + item.count--; + } + this.level.addParticle(new BoneMealParticle(this)); + this.level.dropItem(this, this.toItem()); + } return true; } return false; } + + public Item toItem() { + return new ItemBlock(this, this.getDamage() & 0x07, 1); + } } diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlab.java b/src/main/java/cn/nukkit/block/BlockDoubleSlab.java index c23819a90cc..4cb9f38000e 100644 --- a/src/main/java/cn/nukkit/block/BlockDoubleSlab.java +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlab.java @@ -1,14 +1,11 @@ package cn.nukkit.block; -import cn.nukkit.item.Item; -import cn.nukkit.item.ItemTool; -import cn.nukkit.utils.BlockColor; - /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ -public class BlockDoubleSlab extends BlockSolidMeta { +public class BlockDoubleSlab extends BlockDoubleSlabStone { + public static final int STONE = 0; public static final int SANDSTONE = 1; public static final int WOODEN = 2; @@ -25,67 +22,4 @@ public BlockDoubleSlab() { public BlockDoubleSlab(int meta) { super(meta); } - - @Override - public int getId() { - return DOUBLE_SLAB; - } - - //todo hardness and residence - - @Override - public double getHardness() { - return 2; - } - - @Override - public int getToolType() { - return ItemTool.TYPE_PICKAXE; - } - - @Override - public String getName() { - String[] names = new String[]{ - "Stone", - "Sandstone", - "Wooden", - "Cobblestone", - "Brick", - "Stone Brick", - "Quartz", - "Nether Brick" - }; - return "Double " + names[this.getDamage() & 0x07] + " Slab"; - } - - @Override - public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { - return new Item[]{ - Item.get(Item.SLAB, this.getDamage() & 0x07, 2) - }; - } else { - return new Item[0]; - } - } - - @Override - public BlockColor getColor() { - switch (this.getDamage() & 0x07) { - case BlockDoubleSlab.WOODEN: - return BlockColor.WOOD_BLOCK_COLOR; - default: - case BlockDoubleSlab.COBBLESTONE: - case BlockDoubleSlab.BRICK: - case BlockDoubleSlab.STONE_BRICK: - case BlockDoubleSlab.STONE: - return BlockColor.STONE_BLOCK_COLOR; - case BlockDoubleSlab.SANDSTONE: - return BlockColor.SAND_BLOCK_COLOR; - case BlockDoubleSlab.QUARTZ: - return BlockColor.QUARTZ_BLOCK_COLOR; - case BlockDoubleSlab.NETHER_BRICK: - return BlockColor.NETHERRACK_BLOCK_COLOR; - } - } } diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabBase.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabBase.java new file mode 100644 index 00000000000..92f341b7832 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabBase.java @@ -0,0 +1,46 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; + +public abstract class BlockDoubleSlabBase extends BlockSolidMeta { + + public BlockDoubleSlabBase() { + this(0); + } + + public BlockDoubleSlabBase(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Double " + this.getSlabName() + " Slab"; + } + + public abstract String getSlabName(); + + public abstract int getSingleSlabId(); + + public abstract int getItemDamage(); + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getSingleSlabId(), this.getItemDamage()), this.getItemDamage(), 1); + } + + protected boolean isCorrectTool(Item item) { + return canHarvestWithHand() || canHarvest(item); + } + + @Override + public Item[] getDrops(Item item) { + if (isCorrectTool(item)) { + Item slab = toItem(); + slab.setCount(2); + return new Item[]{ slab }; + } else { + return new Item[0]; + } + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabBlackstone.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabBlackstone.java new file mode 100644 index 00000000000..b0a74134e98 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabBlackstone.java @@ -0,0 +1,60 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockDoubleSlabBlackstone extends BlockDoubleSlabBase { + + public BlockDoubleSlabBlackstone() { + this(0); + } + + protected BlockDoubleSlabBlackstone(int meta) { + super(meta); + } + + @Override + public String getSlabName() { + return "Double Blackstone Slab"; + } + + @Override + public int getId() { + return BLACKSTONE_DOUBLE_SLAB; + } + + @Override + public int getItemDamage() { + return 0; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public double getHardness() { + return 2; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public int getSingleSlabId() { + return BLACKSTONE_SLAB; + } + + @Override + public BlockColor getColor() { + return BlockColor.BLACK_BLOCK_COLOR; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabBlackstonePolished.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabBlackstonePolished.java new file mode 100644 index 00000000000..cc9da667057 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabBlackstonePolished.java @@ -0,0 +1,60 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockDoubleSlabBlackstonePolished extends BlockDoubleSlabBase { + + public BlockDoubleSlabBlackstonePolished() { + this(0); + } + + public BlockDoubleSlabBlackstonePolished(int meta) { + super(meta); + } + + @Override + public int getId() { + return POLISHED_BLACKSTONE_DOUBLE_SLAB; + } + + @Override + public int getSingleSlabId() { + return POLISHED_BLACKSTONE_SLAB; + } + + @Override + public int getItemDamage() { + return 0; + } + + @Override + public String getSlabName() { + return "Polished Blackstone"; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public double getHardness() { + return 2; + } + + @Override + public double getResistance() { + return 6.0; + } + + @Override + public BlockColor getColor() { + return BlockColor.BLACK_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabBrickBlackstonePolished.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabBrickBlackstonePolished.java new file mode 100644 index 00000000000..689d81e3813 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabBrickBlackstonePolished.java @@ -0,0 +1,32 @@ +package cn.nukkit.block; + +public class BlockDoubleSlabBrickBlackstonePolished extends BlockDoubleSlabBlackstonePolished { + + public BlockDoubleSlabBrickBlackstonePolished() { + this(0); + } + + public BlockDoubleSlabBrickBlackstonePolished(int meta) { + super(meta); + } + + @Override + public int getId() { + return POLISHED_BLACKSTONE_BRICK_DOUBLE_SLAB; + } + + @Override + public int getSingleSlabId() { + return POLISHED_BLACKSTONE_BRICK_SLAB; + } + + @Override + public String getSlabName() { + return "Polished Blackstone Brick"; + } + + @Override + public double getHardness() { + return 2; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabBrickDeepslate.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabBrickDeepslate.java new file mode 100644 index 00000000000..1ef60c38691 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabBrickDeepslate.java @@ -0,0 +1,65 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockDoubleSlabBrickDeepslate extends BlockDoubleSlabBase { + + public BlockDoubleSlabBrickDeepslate() { + this(0); + } + + protected BlockDoubleSlabBrickDeepslate(int meta) { + super(meta); + } + + @Override + public int getId() { + return DEEPSLATE_BRICK_DOUBLE_SLAB; + } + + @Override + public int getSingleSlabId() { + return DEEPSLATE_BRICK_SLAB; + } + + @Override + public int getItemDamage() { + return 0; + } + + @Override + public String getSlabName() { + return "Double Deepslate Brick Slab"; + } + + @Override + public double getHardness() { + return 3.5; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_WOODEN; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperBase.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperBase.java new file mode 100644 index 00000000000..a5489b9b554 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperBase.java @@ -0,0 +1,88 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public abstract class BlockDoubleSlabCopperBase extends BlockDoubleSlabBase implements Waxable, Oxidizable { + + public BlockDoubleSlabCopperBase(int meta) { + super(meta); + } + + @Override + public double getHardness() { + return 3; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_STONE; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public boolean onActivate(Item item, Player player) { + return Waxable.super.onActivate(item, player) + || Oxidizable.super.onActivate(item, player); + } + + @Override + public int onUpdate(int type) { + return Oxidizable.super.onUpdate(type); + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public BlockColor getColor() { + return BlockColor.ORANGE_BLOCK_COLOR; + } + + @Override + public Block getStateWithOxidizationLevel(OxidizationLevel oxidizationLevel) { + return Block.get(this.getCopperId(this.isWaxed(), oxidizationLevel), this.getDamage()); + } + + @Override + public boolean setOxidizationLevel(OxidizationLevel oxidizationLevel) { + if (this.getOxidizationLevel().equals(oxidizationLevel)) { + return true; + } + return this.level.setBlock(this, Block.get(this.getCopperId(this.isWaxed(), oxidizationLevel))); + } + + @Override + public boolean setWaxed(boolean waxed) { + if (this.isWaxed() == waxed) { + return true; + } + return this.level.setBlock(this, Block.get(getCopperId(waxed, getOxidizationLevel()))); + } + + @Override + public boolean isWaxed() { + return false; + } + + protected abstract int getCopperId(boolean waxed, OxidizationLevel oxidizationLevel); +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCut.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCut.java new file mode 100644 index 00000000000..6982605b262 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCut.java @@ -0,0 +1,68 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; + +public class BlockDoubleSlabCopperCut extends BlockDoubleSlabCopperBase { + + public BlockDoubleSlabCopperCut() { + this(0); + } + + public BlockDoubleSlabCopperCut(int meta) { + super(meta); + } + + @Override + public int getId() { + return DOUBLE_CUT_COPPER_SLAB; + } + + @Override + public String getSlabName() { + String name = ""; + if (this.isWaxed()) { + name += "Waxed "; + } + + OxidizationLevel oxidizationLevel = this.getOxidizationLevel(); + if (oxidizationLevel != OxidizationLevel.UNAFFECTED) { + String oxidationName = oxidizationLevel.name(); + name += oxidationName.charAt(0) + oxidationName.substring(1).toLowerCase(); + } + return name + " Cut Copper"; + } + + @Override + public int getSingleSlabId() { + return CUT_COPPER_SLAB; + } + + @Override + public int getItemDamage() { + return 0; + } + + @Override + protected int getCopperId(boolean waxed, OxidizationLevel oxidizationLevel) { + if (oxidizationLevel == null) { + return getId(); + } + switch (oxidizationLevel) { + case UNAFFECTED: + return waxed? WAXED_DOUBLE_CUT_COPPER_SLAB : DOUBLE_CUT_COPPER_SLAB; + case EXPOSED: + return waxed? WAXED_EXPOSED_DOUBLE_CUT_COPPER_SLAB : EXPOSED_DOUBLE_CUT_COPPER_SLAB; + case WEATHERED: + return waxed? WAXED_WEATHERED_DOUBLE_CUT_COPPER_SLAB : WEATHERED_DOUBLE_CUT_COPPER_SLAB; + case OXIDIZED: + return waxed? WAXED_OXIDIZED_DOUBLE_CUT_COPPER_SLAB : OXIDIZED_DOUBLE_CUT_COPPER_SLAB; + default: + return getId(); + } + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.UNAFFECTED; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutExposed.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutExposed.java new file mode 100644 index 00000000000..85cec004911 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutExposed.java @@ -0,0 +1,35 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.utils.BlockColor; + +public class BlockDoubleSlabCopperCutExposed extends BlockDoubleSlabCopperCut { + + public BlockDoubleSlabCopperCutExposed() { + this(0); + } + + public BlockDoubleSlabCopperCutExposed(int meta) { + super(meta); + } + + @Override + public int getSingleSlabId() { + return EXPOSED_CUT_COPPER_SLAB; + } + + @Override + public int getId() { + return EXPOSED_DOUBLE_CUT_COPPER_SLAB; + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.EXPOSED; + } + + @Override + public BlockColor getColor() { + return BlockColor.LIGHT_GRAY_TERRACOTA_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutExposedWaxed.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutExposedWaxed.java new file mode 100644 index 00000000000..52f8b6ee48c --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutExposedWaxed.java @@ -0,0 +1,27 @@ +package cn.nukkit.block; + +public class BlockDoubleSlabCopperCutExposedWaxed extends BlockDoubleSlabCopperCutExposed { + + public BlockDoubleSlabCopperCutExposedWaxed() { + this(0); + } + + public BlockDoubleSlabCopperCutExposedWaxed(int meta) { + super(meta); + } + + @Override + public int getSingleSlabId() { + return WAXED_EXPOSED_CUT_COPPER_SLAB; + } + + @Override + public int getId() { + return WAXED_EXPOSED_DOUBLE_CUT_COPPER_SLAB; + } + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutOxidized.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutOxidized.java new file mode 100644 index 00000000000..aa69ae2dcab --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutOxidized.java @@ -0,0 +1,35 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.utils.BlockColor; + +public class BlockDoubleSlabCopperCutOxidized extends BlockDoubleSlabCopperCut { + + public BlockDoubleSlabCopperCutOxidized() { + this(0); + } + + public BlockDoubleSlabCopperCutOxidized(int meta) { + super(meta); + } + + @Override + public int getSingleSlabId() { + return OXIDIZED_CUT_COPPER_SLAB; + } + + @Override + public int getId() { + return OXIDIZED_DOUBLE_CUT_COPPER_SLAB; + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.OXIDIZED; + } + + @Override + public BlockColor getColor() { + return BlockColor.WARPED_NYLIUM_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutOxidizedWaxed.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutOxidizedWaxed.java new file mode 100644 index 00000000000..feb03bff0ad --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutOxidizedWaxed.java @@ -0,0 +1,27 @@ +package cn.nukkit.block; + +public class BlockDoubleSlabCopperCutOxidizedWaxed extends BlockDoubleSlabCopperCutOxidized { + + public BlockDoubleSlabCopperCutOxidizedWaxed() { + this(0); + } + + public BlockDoubleSlabCopperCutOxidizedWaxed(int meta) { + super(meta); + } + + @Override + public int getSingleSlabId() { + return WAXED_OXIDIZED_CUT_COPPER_SLAB; + } + + @Override + public int getId() { + return WAXED_OXIDIZED_DOUBLE_CUT_COPPER_SLAB; + } + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutWaxed.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutWaxed.java new file mode 100644 index 00000000000..233a09a151c --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutWaxed.java @@ -0,0 +1,27 @@ +package cn.nukkit.block; + +public class BlockDoubleSlabCopperCutWaxed extends BlockDoubleSlabCopperCut { + + public BlockDoubleSlabCopperCutWaxed() { + this(0); + } + + public BlockDoubleSlabCopperCutWaxed(int meta) { + super(meta); + } + + @Override + public int getSingleSlabId() { + return WAXED_CUT_COPPER_SLAB; + } + + @Override + public int getId() { + return WAXED_DOUBLE_CUT_COPPER_SLAB; + } + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutWeathered.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutWeathered.java new file mode 100644 index 00000000000..ba6ea011121 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutWeathered.java @@ -0,0 +1,35 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.utils.BlockColor; + +public class BlockDoubleSlabCopperCutWeathered extends BlockDoubleSlabCopperCut { + + public BlockDoubleSlabCopperCutWeathered() { + this(0); + } + + public BlockDoubleSlabCopperCutWeathered(int meta) { + super(meta); + } + + @Override + public int getSingleSlabId() { + return WEATHERED_CUT_COPPER_SLAB; + } + + @Override + public int getId() { + return WEATHERED_DOUBLE_CUT_COPPER_SLAB; + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.WEATHERED; + } + + @Override + public BlockColor getColor() { + return BlockColor.WARPED_STEM_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutWeatheredWaxed.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutWeatheredWaxed.java new file mode 100644 index 00000000000..e5d05579f49 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabCopperCutWeatheredWaxed.java @@ -0,0 +1,27 @@ +package cn.nukkit.block; + +public class BlockDoubleSlabCopperCutWeatheredWaxed extends BlockDoubleSlabCopperCutWeathered { + + public BlockDoubleSlabCopperCutWeatheredWaxed() { + this(0); + } + + public BlockDoubleSlabCopperCutWeatheredWaxed(int meta) { + super(meta); + } + + @Override + public int getSingleSlabId() { + return WAXED_WEATHERED_CUT_COPPER_SLAB; + } + + @Override + public int getId() { + return WAXED_WEATHERED_DOUBLE_CUT_COPPER_SLAB; + } + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabCrimson.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabCrimson.java new file mode 100644 index 00000000000..34673b88eff --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabCrimson.java @@ -0,0 +1,65 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockDoubleSlabCrimson extends BlockDoubleSlabBase { + + public BlockDoubleSlabCrimson() { + super(0); + } + + public BlockDoubleSlabCrimson(int meta) { + super(meta); + } + + @Override + public int getId() { + return CRIMSON_DOUBLE_SLAB; + } + + @Override + public String getSlabName() { + return "Crimson"; + } + + @Override + public int getSingleSlabId() { + return CRIMSON_SLAB; + } + + @Override + public int getItemDamage() { + return 0; + } + + @Override + public double getHardness() { + return 2; + } + + @Override + public double getResistance() { + return 3; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_AXE; + } + + @Override + public BlockColor getColor() { + return BlockColor.NETHERRACK_BLOCK_COLOR; + } + + @Override + public int getBurnChance() { + return 0; + } + + @Override + public int getBurnAbility() { + return 0; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabDeepslateCobbled.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabDeepslateCobbled.java new file mode 100644 index 00000000000..7c420775846 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabDeepslateCobbled.java @@ -0,0 +1,32 @@ +package cn.nukkit.block; + +public class BlockDoubleSlabDeepslateCobbled extends BlockDoubleSlabBase { + + public BlockDoubleSlabDeepslateCobbled() { + this(0); + } + + public BlockDoubleSlabDeepslateCobbled(int meta) { + super(meta); + } + + @Override + public int getId() { + return COBBLED_DEEPSLATE_DOUBLE_SLAB; + } + + @Override + public String getSlabName() { + return "Cobbled Deepslate"; + } + + @Override + public int getSingleSlabId() { + return COBBLED_DEEPSLATE_SLAB; + } + + @Override + public int getItemDamage() { + return 0; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabDeepslatePolished.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabDeepslatePolished.java new file mode 100644 index 00000000000..09eb2fc4387 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabDeepslatePolished.java @@ -0,0 +1,65 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockDoubleSlabDeepslatePolished extends BlockDoubleSlabBase { + + public BlockDoubleSlabDeepslatePolished() { + this(0); + } + + public BlockDoubleSlabDeepslatePolished(int meta) { + super(meta); + } + + @Override + public int getId() { + return POLISHED_DEEPSLATE_DOUBLE_SLAB; + } + + @Override + public int getSingleSlabId() { + return POLISHED_DEEPSLATE_SLAB; + } + + @Override + public int getItemDamage() { + return 0; + } + + @Override + public String getSlabName() { + return "Double Polished Deepslate Slab"; + } + + @Override + public double getHardness() { + return 3.5; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_WOODEN; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabRedSandstone.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabRedSandstone.java index 176c645a37e..efe46e3484e 100644 --- a/src/main/java/cn/nukkit/block/BlockDoubleSlabRedSandstone.java +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabRedSandstone.java @@ -1,14 +1,23 @@ package cn.nukkit.block; -import cn.nukkit.item.Item; -import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemTool; import cn.nukkit.utils.BlockColor; /** * Created by CreeperFace on 26. 11. 2016. */ -public class BlockDoubleSlabRedSandstone extends BlockSolidMeta { +public class BlockDoubleSlabRedSandstone extends BlockDoubleSlabBase { + + private static final String[] NAMES = { + "Red Sandstone", + "Purpur", + "", + "", + "", + "", + "", + "" + }; public BlockDoubleSlabRedSandstone() { this(0); @@ -23,6 +32,11 @@ public int getId() { return DOUBLE_RED_SANDSTONE_SLAB; } + @Override + public int getSingleSlabId() { + return RED_SANDSTONE_SLAB; + } + @Override public double getResistance() { return 30; @@ -39,35 +53,13 @@ public int getToolType() { } @Override - public String getName() { - String[] names = new String[]{ - "Red Sandstone", - "Purpur", - "", - "", - "", - "", - "", - "" - }; - - return "Double " + names[this.getDamage() & 0x07] + " Slab"; + public String getSlabName() { + return NAMES[this.getDamage() & 0x07]; } @Override - public Item toItem() { - return new ItemBlock(Block.get(BlockID.RED_SANDSTONE_SLAB), this.getDamage() & 0x07); - } - - @Override - public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { - return new Item[]{ - Item.get(Item.RED_SANDSTONE_SLAB, this.getDamage() & 0x07, 2) - }; - } else { - return new Item[0]; - } + public int getItemDamage() { + return this.getDamage() & 0x07; } @Override @@ -86,4 +78,4 @@ public BlockColor getColor() { return BlockColor.STONE_BLOCK_COLOR; } } -} \ No newline at end of file +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabStone.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabStone.java index 6828f735a1e..e56c023ee02 100644 --- a/src/main/java/cn/nukkit/block/BlockDoubleSlabStone.java +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabStone.java @@ -1,15 +1,14 @@ package cn.nukkit.block; -import cn.nukkit.item.Item; -import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemTool; import cn.nukkit.utils.BlockColor; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ -public class BlockDoubleSlabStone extends BlockSolidMeta { +public class BlockDoubleSlabStone extends BlockDoubleSlabBase { + public static final int STONE = 0; public static final int SANDSTONE = 1; public static final int WOODEN = 2; @@ -19,6 +18,17 @@ public class BlockDoubleSlabStone extends BlockSolidMeta { public static final int QUARTZ = 6; public static final int NETHER_BRICK = 7; + private static final String[] NAMES = { + "Stone", + "Sandstone", + "Oak", + "Cobblestone", + "Brick", + "Stone Brick", + "Quartz", + "Nether Brick" + }; + public BlockDoubleSlabStone() { this(0); } @@ -32,6 +42,11 @@ public int getId() { return DOUBLE_SLAB; } + @Override + public int getSingleSlabId() { + return STONE_SLAB; + } + @Override public double getResistance() { return getToolType() > ItemTool.TIER_WOODEN ? 30 : 15; @@ -48,45 +63,24 @@ public int getToolType() { } @Override - public String getName() { - String[] names = new String[]{ - "Stone", - "Sandstone", - "Wooden", - "Cobblestone", - "Brick", - "Stone Brick", - "Quartz", - "Nether Brick" - }; - return "Double " + names[this.getDamage() & 0x07] + " Slab"; + public String getSlabName() { + return NAMES[this.getDamage() & 0x07]; } @Override - public Item toItem() { - return new ItemBlock(Block.get(BlockID.STONE_SLAB), this.getDamage() & 0x07); - } - - @Override - public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { - return new Item[]{ - Item.get(Item.SLAB, this.getDamage() & 0x07, 2) - }; - } else { - return new Item[0]; - } + public int getItemDamage() { + return this.getDamage() & 0x07; } @Override public BlockColor getColor() { switch (this.getDamage() & 0x07) { default: - case BlockDoubleSlabStone.STONE: - case BlockDoubleSlabStone.COBBLESTONE: - case BlockDoubleSlabStone.BRICK: - case BlockDoubleSlabStone.STONE_BRICK: - return BlockColor.STONE_BLOCK_COLOR; + case BlockDoubleSlabStone.STONE: + case BlockDoubleSlabStone.COBBLESTONE: + case BlockDoubleSlabStone.BRICK: + case BlockDoubleSlabStone.STONE_BRICK: + return BlockColor.STONE_BLOCK_COLOR; case BlockDoubleSlabStone.SANDSTONE: return BlockColor.SAND_BLOCK_COLOR; case BlockDoubleSlabStone.WOODEN: @@ -102,4 +96,4 @@ public BlockColor getColor() { public boolean canHarvestWithHand() { return false; } -} \ No newline at end of file +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabStone3.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabStone3.java new file mode 100644 index 00000000000..b6e21925724 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabStone3.java @@ -0,0 +1,79 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockDoubleSlabStone3 extends BlockDoubleSlabBase { + + public static final int END_STONE_BRICKS = 0; + public static final int SMOOTH_RED_SANDSTONE = 1; + public static final int POLISHED_ANDESITE = 2; + public static final int ANDESITE = 3; + public static final int DIORITE = 4; + public static final int POLISHED_DIORITE = 5; + public static final int GRANITE = 6; + public static final int POLISHED_GRANITE = 7; + + private static final String[] NAMES = { + "End Stone Brick", + "Smooth Red Sandstone", + "Polished Andesite", + "Andesite", + "Diorite", + "Polished Diorite", + "Granite", + "Polisehd Granite" + }; + + public BlockDoubleSlabStone3() { + this(0); + } + + public BlockDoubleSlabStone3(int meta) { + super(meta); + } + + @Override + public String getSlabName() { + return NAMES[this.getDamage() & 0x07]; + } + + @Override + public int getId() { + return DOUBLE_STONE_SLAB3; + } + + @Override + public int getSingleSlabId() { + return STONE_SLAB3; + } + + @Override + public int getItemDamage() { + return this.getDamage() & 0x07; + } + + @Override + public BlockColor getColor() { + switch (this.getDamage() & 0x07) { + case END_STONE_BRICKS: + return BlockColor.SAND_BLOCK_COLOR; + case SMOOTH_RED_SANDSTONE: + return BlockColor.ORANGE_BLOCK_COLOR; + default: + case POLISHED_ANDESITE: + case ANDESITE: + return BlockColor.STONE_BLOCK_COLOR; + case DIORITE: + case POLISHED_DIORITE: + return BlockColor.QUARTZ_BLOCK_COLOR; + case GRANITE: + case POLISHED_GRANITE: + return BlockColor.DIRT_BLOCK_COLOR; + } + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabStone4.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabStone4.java new file mode 100644 index 00000000000..c85a71c5015 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabStone4.java @@ -0,0 +1,89 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockDoubleSlabStone4 extends BlockDoubleSlabBase { + + private static final String[] NAMES = { + "Mossy Stone Brick", + "Smooth Quartz", + "Stone", + "Cut Sandstone", + "Cut Red Sandstone", + }; + + public static final int MOSSY_STONE_BRICKS = 0; + public static final int SMOOTH_QUARTZ = 1; + public static final int STONE = 2; + public static final int CUT_SANDSTONE = 3; + public static final int CUT_RED_SANDSTONE = 4; + + public BlockDoubleSlabStone4() { + this(0); + } + + public BlockDoubleSlabStone4(int meta) { + super(meta); + } + + @Override + public int getId() { + return DOUBLE_STONE_SLAB4; + } + + @Override + public int getSingleSlabId() { + return STONE_SLAB4; + } + + @Override + public double getResistance() { + return this.getToolType() > ItemTool.TIER_WOODEN ? 30 : 15; + } + + @Override + public double getHardness() { + return 2; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public String getSlabName() { + int variant = this.getDamage() & 0x07; + if (variant >= NAMES.length) { + return NAMES[0]; + } + return NAMES[variant]; + } + + @Override + public int getItemDamage() { + return this.getDamage() & 0x07; + } + + @Override + public BlockColor getColor() { + switch (this.getDamage() & 0x07) { + default: + case MOSSY_STONE_BRICKS: + case STONE: + return BlockColor.STONE_BLOCK_COLOR; + case SMOOTH_QUARTZ: + return BlockColor.QUARTZ_BLOCK_COLOR; + case CUT_SANDSTONE: + return BlockColor.SAND_BLOCK_COLOR; + case CUT_RED_SANDSTONE: + return BlockColor.ORANGE_BLOCK_COLOR; + } + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabTileDeepslate.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabTileDeepslate.java new file mode 100644 index 00000000000..4ae1646a3eb --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabTileDeepslate.java @@ -0,0 +1,65 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockDoubleSlabTileDeepslate extends BlockDoubleSlabBase { + + public BlockDoubleSlabTileDeepslate() { + this(0); + } + + protected BlockDoubleSlabTileDeepslate(int meta) { + super(meta); + } + + @Override + public int getId() { + return DEEPSLATE_TILE_DOUBLE_SLAB; + } + + @Override + public int getSingleSlabId() { + return DEEPSLATE_TILE_SLAB; + } + + @Override + public int getItemDamage() { + return 0; + } + + @Override + public String getSlabName() { + return "Double Deepslate Tile Slab"; + } + + @Override + public double getHardness() { + return 3.5; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_WOODEN; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabWarped.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabWarped.java new file mode 100644 index 00000000000..fea73e3c109 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabWarped.java @@ -0,0 +1,65 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockDoubleSlabWarped extends BlockDoubleSlabBase { + + public BlockDoubleSlabWarped() { + super(0); + } + + public BlockDoubleSlabWarped(int meta) { + super(meta); + } + + @Override + public int getId() { + return WARPED_DOUBLE_SLAB; + } + + @Override + public String getSlabName() { + return "Warped"; + } + + @Override + public int getSingleSlabId() { + return WARPED_SLAB; + } + + @Override + public int getItemDamage() { + return 0; + } + + @Override + public double getHardness() { + return 2; + } + + @Override + public double getResistance() { + return 3; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_AXE; + } + + @Override + public BlockColor getColor() { + return BlockColor.CYAN_BLOCK_COLOR; + } + + @Override + public int getBurnChance() { + return 0; + } + + @Override + public int getBurnAbility() { + return 0; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDoubleSlabWood.java b/src/main/java/cn/nukkit/block/BlockDoubleSlabWood.java index ab83b36c568..7bf20a7a6a3 100644 --- a/src/main/java/cn/nukkit/block/BlockDoubleSlabWood.java +++ b/src/main/java/cn/nukkit/block/BlockDoubleSlabWood.java @@ -1,7 +1,5 @@ package cn.nukkit.block; -import cn.nukkit.item.Item; -import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemTool; import cn.nukkit.utils.BlockColor; @@ -9,7 +7,18 @@ * Created on 2015/12/2 by xtypr. * Package cn.nukkit.block in project Nukkit . */ -public class BlockDoubleSlabWood extends BlockSolidMeta { +public class BlockDoubleSlabWood extends BlockDoubleSlabBase { + + private static final String[] NAMES = { + "Oak", + "Spruce", + "Birch", + "Jungle", + "Acacia", + "Dark Oak", + "", + "" + }; public BlockDoubleSlabWood() { this(0); @@ -24,6 +33,11 @@ public int getId() { return DOUBLE_WOOD_SLAB; } + @Override + public int getSingleSlabId() { + return WOOD_SLAB; + } + @Override public double getHardness() { return 2; @@ -40,37 +54,21 @@ public int getToolType() { } @Override - public String getName() { - String[] names = new String[]{ - "Oak", - "Spruce", - "Birch", - "Jungle", - "Acacia", - "Dark Oak", - "", - "" - }; - return "Double " + names[this.getDamage() & 0x07] + " Slab"; + public String getSlabName() { + return NAMES[this.getDamage() & 0x07]; } @Override - public Item toItem() { - return new ItemBlock(Block.get(BlockID.WOODEN_SLAB), this.getDamage() & 0x07); - } - - public Item[] getDrops(Item item) { - return new Item[]{ - Item.get(Item.WOOD_SLAB, this.getDamage() & 0x07, 2) - }; + public int getItemDamage() { + return this.getDamage() & 0x07; } @Override public BlockColor getColor() { - switch(this.getDamage() & 0x07){ + switch (this.getDamage() & 0x07) { default: - case 0: //OAK - return BlockColor.WOOD_BLOCK_COLOR; + case 0: //OAK + return BlockColor.WOOD_BLOCK_COLOR; case 1: //SPRUCE return BlockColor.SPRUCE_BLOCK_COLOR; case 2: //BIRCH diff --git a/src/main/java/cn/nukkit/block/BlockDragonEgg.java b/src/main/java/cn/nukkit/block/BlockDragonEgg.java index 8e02b46d3b6..dc6465562c6 100644 --- a/src/main/java/cn/nukkit/block/BlockDragonEgg.java +++ b/src/main/java/cn/nukkit/block/BlockDragonEgg.java @@ -4,14 +4,10 @@ import cn.nukkit.level.Level; import cn.nukkit.network.protocol.LevelEventPacket; import cn.nukkit.utils.BlockColor; - -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; public class BlockDragonEgg extends BlockFallable { - public BlockDragonEgg() { - } - @Override public String getName() { return "Dragon Egg"; @@ -29,7 +25,7 @@ public double getHardness() { @Override public double getResistance() { - return 45; + return 9; } @Override @@ -39,7 +35,7 @@ public int getLightLevel() { @Override public BlockColor getColor() { - return BlockColor.OBSIDIAN_BLOCK_COLOR; + return BlockColor.BLACK_BLOCK_COLOR; } @Override @@ -56,15 +52,13 @@ public int onUpdate(int type) { } public void teleport() { - ThreadLocalRandom random = ThreadLocalRandom.current(); for (int i = 0; i < 1000; ++i) { - Block to = this.getLevel().getBlock(this.add(random.nextInt(-16, 16), random.nextInt(-16, 16), random.nextInt(-16, 16))); + Block to = this.getLevel().getBlock(this.add(Utils.random.nextInt(-16, 16), Utils.random.nextInt(-16, 16), Utils.random.nextInt(-16, 16))); if (to.getId() == AIR) { BlockFromToEvent event = new BlockFromToEvent(this, to); this.level.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) return; to = event.getTo(); - int diffX = this.getFloorX() - to.getFloorX(); int diffY = this.getFloorY() - to.getFloorY(); int diffZ = this.getFloorZ() - to.getFloorZ(); @@ -74,11 +68,26 @@ public void teleport() { pk.x = this.getFloorX(); pk.y = this.getFloorY(); pk.z = this.getFloorZ(); - this.getLevel().addChunkPacket(this.getFloorX() >> 4, this.getFloorZ() >> 4, pk); + this.getLevel().addChunkPacket(this.getChunkX(), this.getChunkZ(), pk); this.getLevel().setBlock(this, get(AIR), true); this.getLevel().setBlock(to, this, true); return; } } } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean breakWhenPushed() { + return true; + } + + @Override + public boolean alwaysDropsOnExplosion() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockDriedKelpBlock.java b/src/main/java/cn/nukkit/block/BlockDriedKelpBlock.java new file mode 100644 index 00000000000..eb26d53c09b --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDriedKelpBlock.java @@ -0,0 +1,40 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockDriedKelpBlock extends Block { + + @Override + public String getName() { + return "Dried Kelp Block"; + } + + @Override + public int getId() { + return DRIED_KELP_BLOCK; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_HOE; + } + + public double getHardness() { + return 0.5; + } + + public double getResistance() { + return 2.5; + } + + @Override + public int getBurnAbility() { + return 30; + } + + @Override + public BlockColor getColor() { + return BlockColor.GREEN_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDripleafBig.java b/src/main/java/cn/nukkit/block/BlockDripleafBig.java new file mode 100644 index 00000000000..b92d735f3a7 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDripleafBig.java @@ -0,0 +1,287 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.block.properties.BlockPropertiesHelper; +import cn.nukkit.block.properties.DripleafTilt; +import cn.nukkit.block.properties.VanillaProperties; +import cn.nukkit.block.custom.properties.BlockProperties; +import cn.nukkit.block.custom.properties.BlockProperty; +import cn.nukkit.block.custom.properties.BooleanBlockProperty; +import cn.nukkit.block.custom.properties.EnumBlockProperty; +import cn.nukkit.entity.Entity; +import cn.nukkit.event.Event; +import cn.nukkit.event.block.BlockGrowEvent; +import cn.nukkit.event.player.PlayerInteractEvent; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemDye; +import cn.nukkit.level.Level; +import cn.nukkit.level.Position; +import cn.nukkit.level.Sound; +import cn.nukkit.level.particle.BoneMealParticle; +import cn.nukkit.level.particle.DestroyBlockParticle; +import cn.nukkit.math.AxisAlignedBB; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.Faceable; + +public class BlockDripleafBig extends BlockSolidMeta implements BlockPropertiesHelper, Faceable { + + public static final BlockProperty TILT_PROPERTY = new EnumBlockProperty<>("big_dripleaf_tilt", false, DripleafTilt.class); + public static final BlockProperty HEAD_PROPERTY = new BooleanBlockProperty("big_dripleaf_head", false); + + private static final BlockProperties PROPERTIES = new BlockProperties(TILT_PROPERTY, HEAD_PROPERTY, VanillaProperties.DIRECTION); + + public BlockDripleafBig() { + this(0); + } + + public BlockDripleafBig(int meta) { + super(meta); + } + + @Override + public BlockProperties getBlockProperties() { + return PROPERTIES; + } + + @Override + public boolean canPlaceOn(Block floor, Position pos) { + switch (floor.getId()) { + case CLAY_BLOCK: + case DIRT: + case FARMLAND: + case GRASS: + case MOSS_BLOCK: + case MYCELIUM: + case BIG_DRIPLEAF: + case WATER: + case STILL_WATER: + return super.canPlaceOn(floor, pos); + } + + if (floor.getLayer() == LAYER_WATERLOGGED && floor.getId() == AIR) { + return super.canPlaceOn(floor, pos); + } + return false; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + Block down = block.down(); + if (!this.canPlaceOn(down, target)) { + return false; + } + + if (down.getId() == BIG_DRIPLEAF) { + BlockDripleafBig floor = (BlockDripleafBig) down; + floor.setHasHead(false); + this.getLevel().setBlock(floor, floor, true, true); + this.setDirection(floor.getDirection()); + } else { + this.setDirection(player.getDirection().getOpposite()); + } + + this.setTilt(DripleafTilt.NONE); + this.setHasHead(true); + return this.getLevel().setBlock(this, this, true, true); + } + + @Override + public boolean onBreak(Item item, Player player) { + Block down = this.down(); + while (down instanceof BlockDripleafBig) { + this.getLevel().setBlock(down, Block.get(BlockID.AIR), true, true); + this.getLevel().addParticle(new DestroyBlockParticle(down.add(0.5), down)); + down = down.down(); + } + + Block up = this.up(); + while (up instanceof BlockDripleafBig) { + this.getLevel().setBlock(up, Block.get(BlockID.AIR), true, true); + this.getLevel().addParticle(new DestroyBlockParticle(up.add(0.5), up)); + up = up.up(); + } + + return super.onBreak(item, player); + } + + @Override + public void onEntityCollide(Entity entity) { + if (!(entity instanceof Player) || !this.hasHead() || this.getTilt() != DripleafTilt.NONE) { + return; + } + + Event event = new PlayerInteractEvent((Player) entity, null, this, null, PlayerInteractEvent.Action.PHYSICAL); + this.getLevel().getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return; + } + + this.setTiltAndScheduleTick(DripleafTilt.UNSTABLE, false); + } + + @Override + public int onUpdate(int type) { + if (type != Level.BLOCK_UPDATE_SCHEDULED) { + return super.onUpdate(type); + } + + DripleafTilt tilt = this.getTilt(); + if (tilt == DripleafTilt.UNSTABLE) { + this.setTiltAndScheduleTick(DripleafTilt.PARTIAL_TILT, true); + } else if (tilt == DripleafTilt.PARTIAL_TILT) { + this.setTiltAndScheduleTick(DripleafTilt.FULL_TILT, true); + } else if (tilt == DripleafTilt.FULL_TILT) { + this.resetTilt(); + } + return 0; + } + + private void setTiltAndScheduleTick(DripleafTilt tilt, boolean sound) { + this.setTilt(tilt); + this.getLevel().setBlock(this, this, true, true); + + if (sound) { + this.getLevel().addSound(this, Sound.TILT_DOWN_BIG_DRIPLEAF); + } + + int delay = tilt.getNetxStateDelay(); + if (delay != -1) { + this.getLevel().scheduleUpdate(this, delay); + } + } + + private void resetTilt() { + this.setTilt(DripleafTilt.NONE); + this.getLevel().setBlock(this, this, true, true); + this.getLevel().addSound(this, Sound.TILT_UP_BIG_DRIPLEAF); + } + + @Override + public boolean onActivate(Item item, Player player) { + if (item.getId() != Item.DYE || item.getDamage() != ItemDye.BONE_MEAL) { + return false; + } + + BlockGrowEvent event = new BlockGrowEvent(this, Block.get(BlockID.BIG_DRIPLEAF, 0, this)); + this.getLevel().getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return false; + } + + Block up = this; + BlockDripleafBig highestPart = null; + while (up instanceof BlockDripleafBig) { + highestPart = (BlockDripleafBig) up; + up = up.up(); + } + + if (highestPart == null) { + return false; + } + + highestPart.setHasHead(false); + this.getLevel().setBlock(highestPart, highestPart, false, true); + + BlockDripleafBig block = (BlockDripleafBig) this.clone(); + block.setHasHead(true); + + this.getLevel().setBlock(highestPart.up(), block, false, true); + + this.level.addParticle(new BoneMealParticle(this)); + + if (player != null && !player.isCreative()) { + item.count--; + } + return true; + } + + @Override + protected AxisAlignedBB recalculateBoundingBox() { + return super.recalculateBoundingBox(); // TODO: + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId()), 0, 1); + } + + @Override + public String getName() { + return "Big Dripleaf"; + } + + @Override + public int getId() { + return BIG_DRIPLEAF; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.FLOW_INTO_BLOCK; + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public double getResistance() { + return 0.1; + } + + @Override + public double getHardness() { + return 0.1; + } + + public void setTilt(DripleafTilt tilt) { + this.setPropertyValue(TILT_PROPERTY, tilt); + } + + public DripleafTilt getTilt() { + return this.getPropertyValue(TILT_PROPERTY); + } + + public void setHasHead(boolean value) { + this.setBooleanValue(HEAD_PROPERTY, value); + } + + public boolean hasHead() { + return this.getBooleanValue(HEAD_PROPERTY); + } + + public void setDirection(BlockFace blockFace) { + this.setPropertyValue(VanillaProperties.DIRECTION, blockFace); + } + + public BlockFace getDirection() { + return this.getPropertyValue(VanillaProperties.DIRECTION); + } + + @Override + public BlockFace getBlockFace() { + return this.getDirection(); + } + + @Override + public boolean breakWhenPushed() { + return true; + } + + @Override + public boolean isTransparent() { + return !this.hasHead() || !this.getTilt().isStable(); + } + + @Override + public boolean isSolid() { + return this.hasHead() && this.getTilt().isStable(); + } + + @Override + public boolean canPassThrough() { + return !this.hasHead() || !this.getTilt().isStable(); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDripleafSmall.java b/src/main/java/cn/nukkit/block/BlockDripleafSmall.java new file mode 100644 index 00000000000..e80932bdfef --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDripleafSmall.java @@ -0,0 +1,197 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.block.properties.BlockPropertiesHelper; +import cn.nukkit.block.properties.VanillaProperties; +import cn.nukkit.block.custom.properties.BlockProperties; +import cn.nukkit.event.block.BlockGrowEvent; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemDye; +import cn.nukkit.level.Position; +import cn.nukkit.level.particle.BoneMealParticle; +import cn.nukkit.level.particle.DestroyBlockParticle; +import cn.nukkit.math.AxisAlignedBB; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.Faceable; + +public class BlockDripleafSmall extends BlockFlowable implements BlockPropertiesHelper, Faceable { + + private static final BlockProperties PROPERTIES = new BlockProperties(VanillaProperties.UPPER_BLOCK, VanillaProperties.DIRECTION); + + public BlockDripleafSmall() { + this(0); + } + + public BlockDripleafSmall(int meta) { + super(meta); + } + + @Override + public BlockProperties getBlockProperties() { + return PROPERTIES; + } + + @Override + public boolean canPlaceOn(Block floor, Position pos) { + switch (floor.getId()) { + case CLAY_BLOCK: + case DIRT: + case FARMLAND: + case GRASS: + case MOSS_BLOCK: + case MYCELIUM: + case SMALL_DRIPLEAF: + case WATER: + case STILL_WATER: + return super.canPlaceOn(floor, pos); + } + + if (floor.getLayer() == LAYER_WATERLOGGED && floor.getId() == AIR) { + return super.canPlaceOn(floor, pos); + } + return false; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + Block down = block.down(); + if (!this.canPlaceOn(down, target)) { + return false; + } + + if (down.getId() == SMALL_DRIPLEAF) { + BlockDripleafSmall floor = (BlockDripleafSmall) down; + floor.setHasHead(false); + this.getLevel().setBlock(floor, floor, true, true); + this.setDirection(floor.getDirection()); + } else { + this.setDirection(player.getDirection().getOpposite()); + } + + this.setHasHead(true); + return this.getLevel().setBlock(this, this, true, true); + } + + @Override + public boolean onBreak(Item item, Player player) { + Block down = this.down(); + while (down instanceof BlockDripleafSmall) { + this.getLevel().setBlock(down, Block.get(BlockID.AIR), true, true); + this.getLevel().addParticle(new DestroyBlockParticle(down.add(0.5), down)); + down = down.down(); + } + + Block up = this.up(); + while (up instanceof BlockDripleafSmall) { + this.getLevel().setBlock(up, Block.get(BlockID.AIR), true, true); + this.getLevel().addParticle(new DestroyBlockParticle(up.add(0.5), up)); + up = up.up(); + } + + return super.onBreak(item, player); + } + + @Override + public boolean onActivate(Item item, Player player) { + if (item.getId() != Item.DYE || item.getDamage() != ItemDye.BONE_MEAL) { + return false; + } + + BlockGrowEvent event = new BlockGrowEvent(this, Block.get(BlockID.BIG_DRIPLEAF, 0, this)); + this.getLevel().getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return false; + } + + Block down = this.down(); + while (down instanceof BlockDripleafSmall) { + BlockDripleafBig block = (BlockDripleafBig) Block.get(BlockID.BIG_DRIPLEAF); + block.setDirection(this.getDirection()); + this.getLevel().setBlock(down, block, false, true); + down = down.down(); + } + + Block up = this; + while (up instanceof BlockDripleafSmall) { + BlockDripleafBig block = (BlockDripleafBig) Block.get(BlockID.BIG_DRIPLEAF); + block.setDirection(this.getDirection()); + this.getLevel().setBlock(up, block, false, true); + up = up.up(); + } + + Block highestPart = this.getLevel().getBlock(up.down()); + if (highestPart instanceof BlockDripleafBig) { + ((BlockDripleafBig) highestPart).setHasHead(true); + this.getLevel().setBlock(highestPart, highestPart, false, true); + } + + this.level.addParticle(new BoneMealParticle(this)); + + if (player != null && !player.isCreative()) { + item.count--; + } + return true; + } + + @Override + protected AxisAlignedBB recalculateBoundingBox() { + return null; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId()), 0, 1); + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public String getName() { + return "Small Dripleaf"; + } + + @Override + public int getId() { + return SMALL_DRIPLEAF; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.FLOW_INTO_BLOCK; + } + + public void setHasHead(boolean value) { + this.setBooleanValue(VanillaProperties.UPPER_BLOCK, value); + } + + public boolean hasHead() { + return this.getBooleanValue(VanillaProperties.UPPER_BLOCK); + } + + public void setDirection(BlockFace blockFace) { + this.setPropertyValue(VanillaProperties.DIRECTION, blockFace); + } + + public BlockFace getDirection() { + return this.getPropertyValue(VanillaProperties.DIRECTION); + } + + @Override + public BlockFace getBlockFace() { + return this.getDirection(); + } + + @Override + public boolean canBeFlowedInto() { + return false; + } + + @Override + public boolean canPassThrough() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockDripstone.java b/src/main/java/cn/nukkit/block/BlockDripstone.java new file mode 100644 index 00000000000..4a5be4bde27 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDripstone.java @@ -0,0 +1,46 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; + +public class BlockDripstone extends BlockSolid { + + public BlockDripstone() { + // Does nothing + } + + @Override + public String getName() { + return "Dripstone Block"; + } + + @Override + public int getId() { + return DRIPSTONE_BLOCK; + } + + @Override + public double getHardness() { + return 1.5; + } + + @Override + public double getResistance() { + return 1; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + // TODO: + /*@Override + public boolean isLavaResistant() { + return true; + }*/ +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockDropper.java b/src/main/java/cn/nukkit/block/BlockDropper.java new file mode 100644 index 00000000000..07efd6f5e2b --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockDropper.java @@ -0,0 +1,242 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.blockentity.BlockEntity; +import cn.nukkit.blockentity.BlockEntityDropper; +import cn.nukkit.inventory.ContainerInventory; +import cn.nukkit.inventory.Inventory; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; +import cn.nukkit.math.Vector3; +import cn.nukkit.nbt.tag.StringTag; +import cn.nukkit.network.protocol.LevelSoundEventPacket; +import cn.nukkit.utils.Faceable; +import cn.nukkit.utils.Utils; + +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; + +public class BlockDropper extends BlockSolidMeta implements Faceable { + + public BlockDropper() { + this(0); + } + + public BlockDropper(int meta) { + super(meta); + } + + @Override + public int getId() { + return DROPPER; + } + + @Override + public String getName() { + return "Dropper"; + } + + @Override + public double getHardness() { + return 3.5; + } + + @Override + public double getResistance() { + return 17.5; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (player != null) { + if (Math.abs(player.x - this.x) < 2 && Math.abs(player.z - this.z) < 2) { + double y = player.y + player.getEyeHeight(); + + if (y - this.y > 2) { + this.setDamage(BlockFace.UP.getIndex()); + } else if (this.y - y > 0) { + this.setDamage(BlockFace.DOWN.getIndex()); + } else { + this.setDamage(player.getHorizontalFacing().getOpposite().getIndex()); + } + } else { + this.setDamage(player.getHorizontalFacing().getOpposite().getIndex()); + } + } + + this.getLevel().setBlock(block, this, true); + + BlockEntity.createBlockEntity(BlockEntity.DROPPER, this.getChunk(), BlockEntity.getDefaultCompound(this, BlockEntity.DROPPER)); + return true; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (player == null) { + return false; + } + + BlockEntity blockEntity = this.level.getBlockEntity(this); + + if (!(blockEntity instanceof BlockEntityDropper)) { + return false; + } + + if (blockEntity.namedTag.contains("Lock") && blockEntity.namedTag.get("Lock") instanceof StringTag) { + if (!blockEntity.namedTag.getString("Lock").equals(item.getCustomName())) { + return true; + } + } + + player.addWindow(((BlockEntityDropper) blockEntity).getInventory()); + return true; + } + + @Override + public BlockFace getBlockFace() { + return BlockFace.fromIndex(this.getDamage() & 0x7); + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(Block.DROPPER)); + } + + public Vector3 getDispensePosition() { + BlockFace facing = getBlockFace(); + return this.add( + 0.5 + 0.7 * facing.getXOffset(), + 0.5 + 0.7 * facing.getYOffset(), + 0.5 + 0.7 * facing.getZOffset() + ); + } + + public void dispense() { + BlockEntity blockEntity = this.level.getBlockEntity(this); + + if (!(blockEntity instanceof BlockEntityDropper)) { + return; + } + + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_BLOCK_CLICK); + + int r = 1; + int slot = -1; + Item target = null; + + Inventory inv = ((BlockEntityDropper) blockEntity).getInventory(); + for (Map.Entry entry : inv.getContents().entrySet()) { + Item item = entry.getValue(); + + if (!item.isNull() && Utils.random.nextInt(r++) == 0) { + target = item; + slot = entry.getKey(); + } + } + + if (target != null) { + target = target.clone(); + drop(target); + + target.count--; + inv.setItem(slot, target); + } + } + + public void drop(Item item) { + BlockFace face = this.getBlockFace(); + Vector3 dispensePos = this.getDispensePosition(); + + if (face.getAxis() == BlockFace.Axis.Y) { + dispensePos.y -= 0.125; + } else { + dispensePos.y -= 0.15625; + } + + ThreadLocalRandom rand = ThreadLocalRandom.current(); + Vector3 motion = new Vector3(); + + double offset = rand.nextDouble() * 0.1 + 0.2; + + motion.x = face.getXOffset() * offset; + motion.y = 0.1; + motion.z = face.getZOffset() * offset; + + motion.x += rand.nextGaussian() * 0.007499999832361937 * 6; + motion.y += rand.nextGaussian() * 0.007499999832361937 * 6; + motion.z += rand.nextGaussian() * 0.007499999832361937 * 6; + + Item i = item.clone(); + i.setCount(1); + this.level.dropItem(dispensePos, i, motion); + } + + @Override + public boolean hasComparatorInputOverride() { + return true; + } + + @Override + public int getComparatorInputOverride() { + BlockEntity blockEntity = this.level.getBlockEntity(this); + + if (blockEntity instanceof BlockEntityDropper) { + return ContainerInventory.calculateRedstone(((BlockEntityDropper) blockEntity).getInventory()); + } + + return 0; + } + + public boolean isTriggered() { + return (this.getDamage() & 8) > 0; + } + + public void setTriggered(boolean value) { + int i = 0; + i |= getBlockFace().getIndex(); + + if (value) { + i |= 8; + } + + this.setDamage(i); + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_SCHEDULED) { + this.setTriggered(false); + this.level.setBlock((int) this.x, (int) this.y, (int) this.z, BlockLayer.NORMAL, this, false, false, false); // No need to send this to client + dispense(); + return type; + } else if (type == Level.BLOCK_UPDATE_REDSTONE) { + if (!isTriggered() && (level.isBlockPowered(this) || level.isBlockPowered(this.getSideVec(BlockFace.UP)))) { + this.setTriggered(true); + this.level.setBlock((int) this.x, (int) this.y, (int) this.z, BlockLayer.NORMAL, this, false, false, false); // No need to send this to client + level.scheduleUpdate(this, this, 4); + } + + return type; + } + + return 0; + } + + @Override + public boolean canBePushed() { + return false; // prevent item loss issue with pistons until a working implementation + } +} diff --git a/src/main/java/cn/nukkit/block/BlockEmerald.java b/src/main/java/cn/nukkit/block/BlockEmerald.java index 92e949c544a..e31af8631e1 100644 --- a/src/main/java/cn/nukkit/block/BlockEmerald.java +++ b/src/main/java/cn/nukkit/block/BlockEmerald.java @@ -10,12 +10,9 @@ */ public class BlockEmerald extends BlockSolid { - public BlockEmerald() { - } - @Override public String getName() { - return "Emerald Block"; + return "Block of Emerald"; } @Override @@ -40,7 +37,7 @@ public int getToolType() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; diff --git a/src/main/java/cn/nukkit/block/BlockEnchantingTable.java b/src/main/java/cn/nukkit/block/BlockEnchantingTable.java index e8c61f58fd3..4de0edde00e 100644 --- a/src/main/java/cn/nukkit/block/BlockEnchantingTable.java +++ b/src/main/java/cn/nukkit/block/BlockEnchantingTable.java @@ -8,7 +8,6 @@ import cn.nukkit.item.ItemTool; import cn.nukkit.math.BlockFace; import cn.nukkit.nbt.tag.CompoundTag; -import cn.nukkit.nbt.tag.ListTag; import cn.nukkit.nbt.tag.StringTag; import cn.nukkit.nbt.tag.Tag; import cn.nukkit.utils.BlockColor; @@ -20,8 +19,6 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockEnchantingTable extends BlockTransparent { - public BlockEnchantingTable() { - } @Override public int getId() { @@ -60,7 +57,7 @@ public boolean canBeActivated() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; @@ -71,7 +68,7 @@ public Item[] getDrops(Item item) { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - this.getLevel().setBlock(block, this, true, true); + this.getLevel().setBlock(this, this, true, true); CompoundTag nbt = new CompoundTag() .putString("id", BlockEntity.ENCHANT_TABLE) @@ -90,37 +87,27 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl } } - BlockEntityEnchantTable enchantTable = (BlockEntityEnchantTable) BlockEntity.createBlockEntity(BlockEntity.ENCHANT_TABLE, getLevel().getChunk((int) this.x >> 4, (int) this.z >> 4), nbt); - return enchantTable != null; + BlockEntity.createBlockEntity(BlockEntity.ENCHANT_TABLE, this.getChunk(), nbt); + + return true; } @Override public boolean onActivate(Item item, Player player) { if (player != null) { BlockEntity t = this.getLevel().getBlockEntity(this); - BlockEntityEnchantTable enchantTable; - if (t instanceof BlockEntityEnchantTable) { - enchantTable = (BlockEntityEnchantTable) t; - } else { - CompoundTag nbt = new CompoundTag() - .putList(new ListTag<>("Items")) - .putString("id", BlockEntity.ENCHANT_TABLE) - .putInt("x", (int) this.x) - .putInt("y", (int) this.y) - .putInt("z", (int) this.z); - enchantTable = (BlockEntityEnchantTable) BlockEntity.createBlockEntity(BlockEntity.ENCHANT_TABLE, this.getLevel().getChunk((int) (this.x) >> 4, (int) (this.z) >> 4), nbt); - if (enchantTable == null) { - return false; - } + if (!(t instanceof BlockEntityEnchantTable)) { + return false; } + BlockEntityEnchantTable enchantTable = (BlockEntityEnchantTable) t; if (enchantTable.namedTag.contains("Lock") && enchantTable.namedTag.get("Lock") instanceof StringTag) { if (!enchantTable.namedTag.getString("Lock").equals(item.getCustomName())) { return true; } } - player.addWindow(new EnchantInventory(player.getUIInventory(), this.getLocation()), Player.ENCHANT_WINDOW_ID); + player.addWindow(new EnchantInventory(player.getUIInventory(), this), Player.ENCHANT_WINDOW_ID); } return true; @@ -135,4 +122,9 @@ public boolean canHarvestWithHand() { public BlockColor getColor() { return BlockColor.RED_BLOCK_COLOR; } + + @Override + public boolean canBePushed() { + return false; + } } diff --git a/src/main/java/cn/nukkit/block/BlockEndGateway.java b/src/main/java/cn/nukkit/block/BlockEndGateway.java index 826d95eaa9d..dfe2f026a64 100644 --- a/src/main/java/cn/nukkit/block/BlockEndGateway.java +++ b/src/main/java/cn/nukkit/block/BlockEndGateway.java @@ -9,9 +9,6 @@ */ public class BlockEndGateway extends BlockSolid { - public BlockEndGateway() { - } - @Override public String getName() { return "End Gateway"; @@ -62,4 +59,13 @@ public Item toItem() { return new ItemBlock(Block.get(BlockID.AIR)); } + @Override + public boolean canBePushed() { + return false; + } + + @Override + public boolean isSolid() { + return false; + } } diff --git a/src/main/java/cn/nukkit/block/BlockEndPortal.java b/src/main/java/cn/nukkit/block/BlockEndPortal.java index 8d2cf1ac1ee..e2ae2683e1e 100644 --- a/src/main/java/cn/nukkit/block/BlockEndPortal.java +++ b/src/main/java/cn/nukkit/block/BlockEndPortal.java @@ -2,6 +2,7 @@ import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; +import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.utils.BlockColor; public class BlockEndPortal extends BlockFlowable { @@ -24,11 +25,6 @@ public int getId() { return END_PORTAL; } - @Override - public boolean canPassThrough() { - return true; - } - @Override public boolean isBreakable(Item item) { return false; @@ -74,6 +70,11 @@ public boolean canBeFlowedInto() { return false; } + @Override + protected AxisAlignedBB recalculateBoundingBox() { + return this; + } + @Override public Item toItem() { return new ItemBlock(Block.get(BlockID.AIR)); diff --git a/src/main/java/cn/nukkit/block/BlockEndPortalFrame.java b/src/main/java/cn/nukkit/block/BlockEndPortalFrame.java index a8e45f5c75f..f6070d46b0d 100644 --- a/src/main/java/cn/nukkit/block/BlockEndPortalFrame.java +++ b/src/main/java/cn/nukkit/block/BlockEndPortalFrame.java @@ -4,14 +4,10 @@ import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.math.BlockFace; -import cn.nukkit.math.Vector3; import cn.nukkit.network.protocol.LevelSoundEventPacket; import cn.nukkit.utils.BlockColor; import cn.nukkit.utils.Faceable; -import java.util.ArrayList; -import java.util.List; - /** * Created by Pub4Game on 26.12.2015. */ @@ -82,91 +78,27 @@ public boolean canBeActivated() { @Override public boolean onActivate(Item item, Player player) { - if((this.getDamage() & 0x04) == 0 && player != null && item.getId() == Item.ENDER_EYE) { + if ((this.getDamage() & 0x04) == 0 && player != null && item.getId() == Item.ENDER_EYE && !player.sneakToBlockInteract()) { this.setDamage(this.getDamage() + 4); - this.getLevel().setBlock(this, this, true, true); + this.getLevel().setBlock(this, this, true, false); this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_BLOCK_END_PORTAL_FRAME_FILL); - this.createPortal(); - return true; - } - return false; - } - - public void createPortal() { - Vector3 centerSpot = this.searchCenter(new ArrayList<>()); - if(centerSpot != null) { - for(int x = -2; x <= 2; x++) { - for(int z = -2; z <= 2; z++) { - if((x == -2 || x == 2) && (z == -2 || z == 2)) - continue; - if(x == -2 || x == 2 || z == -2 || z == 2) { - if(!this.checkFrame(this.getLevel().getBlock(centerSpot.add(x, 0, z)), x, z)) { - return; + for (int i = 0; i < 4; i++) { + for (int j = -1; j <= 1; j++) { + Block t = this.getSide(BlockFace.fromHorizontalIndex(i), 2).getSide(BlockFace.fromHorizontalIndex((i + 1) % 4), j); + if (isCompletedPortal(t)) { + for (int k = -1; k <= 1; k++) { + for (int l = -1; l <= 1; l++) { + this.getLevel().setBlock(t.add(k, 0, l), Block.get(Block.END_PORTAL), true); + } } + this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_BLOCK_END_PORTAL_SPAWN); + return true; } } } - - for(int x = -1; x <= 1; x++) { - for(int z = -1; z <= 1; z++) { - Vector3 vector3 = centerSpot.add(x, 0, z); - if(this.getLevel().getBlock(vector3).getId() != Block.AIR) { - this.getLevel().useBreakOn(vector3); - } - this.getLevel().setBlock(vector3, Block.get(Block.END_PORTAL)); - } - } - } - } - - private Vector3 searchCenter(List visited) { - for(int x = -2; x <= 2; x++) { - if(x == 0) - continue; - Block block = this.getLevel().getBlock(this.add(x, 0, 0)); - Block iBlock = this.getLevel().getBlock(this.add(x * 2, 0, 0)); - if(this.checkFrame(block) && !visited.contains(block)) { - visited.add(block); - if((x == -1 || x == 1) && this.checkFrame(iBlock)) - return ((BlockEndPortalFrame) block).searchCenter(visited); - for(int z = -4; z <= 4; z++) { - if(z == 0) - continue; - block = this.getLevel().getBlock(this.add(x, 0, z)); - if(this.checkFrame(block)) { - return this.add(x / 2, 0, z / 2); - } - } - } - } - for(int z = -2; z <= 2; z++) { - if(z == 0) - continue; - Block block = this.getLevel().getBlock(this.add(0, 0, z)); - Block iBlock = this.getLevel().getBlock(this.add(0, 0, z * 2)); - if(this.checkFrame(block) && !visited.contains(block)) { - visited.add(block); - if((z == -1 || z == 1) && this.checkFrame(iBlock)) - return ((BlockEndPortalFrame) block).searchCenter(visited); - for(int x = -4; x <= 4; x++) { - if(x == 0) - continue; - block = this.getLevel().getBlock(this.add(x, 0, z)); - if(this.checkFrame(block)) { - return this.add(x / 2, 0, z / 2); - } - } - } + return true; } - return null; - } - - private boolean checkFrame(Block block) { - return block.getId() == this.getId() && (block.getDamage() & 4) == 4; - } - - private boolean checkFrame(Block block, int x, int z) { - return block.getId() == this.getId() && (block.getDamage() - 4) == (x == -2 ? 3 : x == 2 ? 1 : z == -2 ? 0 : z == 2 ? 2 : -1); + return false; } @Override @@ -176,18 +108,31 @@ public boolean canHarvestWithHand() { @Override public Item toItem() { - return new ItemBlock(this, 0); + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override public BlockFace getBlockFace() { - return BlockFace.fromHorizontalIndex(this.getDamage() & 0x07); + return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); } @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { this.setDamage(FACES[player != null ? player.getDirection().getHorizontalIndex() : 0]); - this.getLevel().setBlock(block, this, true); + + this.getLevel().setBlock(this, this, true, true); + return true; + } + + private static boolean isCompletedPortal(Block center) { + for (int i = 0; i < 4; i++) { + for (int j = -1; j <= 1; j++) { + Block block = center.getSide(BlockFace.fromHorizontalIndex(i), 2).getSide(BlockFace.fromHorizontalIndex((i + 1) % 4), j); + if (block.getId() != Block.END_PORTAL_FRAME || (block.getDamage() & 0x4) == 0) { + return false; + } + } + } return true; } @@ -195,4 +140,9 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl public BlockColor getColor() { return BlockColor.GREEN_BLOCK_COLOR; } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } } diff --git a/src/main/java/cn/nukkit/block/BlockEndRod.java b/src/main/java/cn/nukkit/block/BlockEndRod.java index 2c4da5a0106..801388d6eb6 100644 --- a/src/main/java/cn/nukkit/block/BlockEndRod.java +++ b/src/main/java/cn/nukkit/block/BlockEndRod.java @@ -8,12 +8,14 @@ import cn.nukkit.utils.Faceable; /** - * http://minecraft.gamepedia.com/End_Rod + * ... * * @author PikyCZ */ public class BlockEndRod extends BlockTransparentMeta implements Faceable { + private static final int[] FACES = {0, 1, 3, 2, 5, 4}; + public BlockEndRod() { this(0); } @@ -47,11 +49,6 @@ public int getLightLevel() { return 14; } - @Override - public boolean canBePushed() { - return true; - } - @Override public int getToolType() { return ItemTool.TYPE_PICKAXE; @@ -79,8 +76,7 @@ public double getMaxZ() { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - int[] faces = {0, 1, 3, 2, 5, 4}; - this.setDamage(faces[player != null ? face.getIndex() : 0]); + this.setDamage(FACES[player != null ? face.getIndex() : 0]); this.getLevel().setBlock(block, this, true, true); return true; @@ -88,12 +84,21 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl @Override public Item toItem() { - return new ItemBlock(this, 0); + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override public BlockFace getBlockFace() { - return BlockFace.fromHorizontalIndex(this.getDamage() & 0x07); + return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); } + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.FLOW_INTO_BLOCK; + } + + @Override + public boolean canBeFlowedInto() { + return false; + } } diff --git a/src/main/java/cn/nukkit/block/BlockEndStone.java b/src/main/java/cn/nukkit/block/BlockEndStone.java index 1695fa12b8a..1956362e918 100644 --- a/src/main/java/cn/nukkit/block/BlockEndStone.java +++ b/src/main/java/cn/nukkit/block/BlockEndStone.java @@ -10,9 +10,6 @@ */ public class BlockEndStone extends BlockSolid { - public BlockEndStone() { - } - @Override public String getName() { return "End Stone"; @@ -40,7 +37,7 @@ public int getToolType() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; diff --git a/src/main/java/cn/nukkit/block/BlockEnderChest.java b/src/main/java/cn/nukkit/block/BlockEnderChest.java index 0cac7913762..01b74651572 100644 --- a/src/main/java/cn/nukkit/block/BlockEnderChest.java +++ b/src/main/java/cn/nukkit/block/BlockEnderChest.java @@ -6,6 +6,7 @@ import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemTool; +import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.math.BlockFace; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.StringTag; @@ -19,7 +20,7 @@ public class BlockEnderChest extends BlockTransparentMeta implements Faceable { - private Set viewers = new HashSet<>(); + private final Set viewers = new HashSet<>(); public BlockEnderChest() { this(0); @@ -64,37 +65,12 @@ public int getToolType() { return ItemTool.TYPE_PICKAXE; } - @Override - public double getMinX() { - return this.x + 0.0625; - } - - @Override - public double getMinZ() { - return this.z + 0.0625; - } - - @Override - public double getMaxX() { - return this.x + 0.9375; - } - - @Override - public double getMaxY() { - return this.y + 0.9475; - } - - @Override - public double getMaxZ() { - return this.z + 0.9375; - } - @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - int[] faces = {2, 5, 3, 4}; - this.setDamage(faces[player != null ? player.getDirection().getHorizontalIndex() : 0]); + this.setDamage(Block.FACES2534[player != null ? player.getDirection().getHorizontalIndex() : 0]); + + this.getLevel().setBlock(this, this, true, true); - this.getLevel().setBlock(block, this, true, true); CompoundTag nbt = new CompoundTag("") .putString("id", BlockEntity.ENDER_CHEST) .putInt("x", (int) this.x) @@ -112,8 +88,8 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl } } - BlockEntityEnderChest ender = (BlockEntityEnderChest) BlockEntity.createBlockEntity(BlockEntity.ENDER_CHEST, this.getLevel().getChunk((int) this.x >> 4, (int) this.z >> 4), nbt); - return ender != null; + BlockEntity.createBlockEntity(BlockEntity.ENDER_CHEST, this.getChunk(), nbt); + return true; } @Override @@ -125,21 +101,11 @@ public boolean onActivate(Item item, Player player) { } BlockEntity t = this.getLevel().getBlockEntity(this); - BlockEntityEnderChest chest; - if (t instanceof BlockEntityEnderChest) { - chest = (BlockEntityEnderChest) t; - } else { - CompoundTag nbt = new CompoundTag("") - .putString("id", BlockEntity.ENDER_CHEST) - .putInt("x", (int) this.x) - .putInt("y", (int) this.y) - .putInt("z", (int) this.z); - chest = (BlockEntityEnderChest) BlockEntity.createBlockEntity(BlockEntity.ENDER_CHEST, this.getLevel().getChunk((int) this.x >> 4, (int) this.z >> 4), nbt); - if (chest == null) { - return false; - } + if (!(t instanceof BlockEntityEnderChest)) { + return false; } + BlockEntityEnderChest chest = (BlockEntityEnderChest) t; if (chest.namedTag.contains("Lock") && chest.namedTag.get("Lock") instanceof StringTag) { if (!chest.namedTag.getString("Lock").equals(item.getCustomName())) { return true; @@ -155,7 +121,10 @@ public boolean onActivate(Item item, Player player) { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; + } return new Item[]{ Item.get(Item.OBSIDIAN, 0, 8) }; @@ -190,11 +159,16 @@ public boolean canSilkTouch() { @Override public Item toItem() { - return new ItemBlock(this, 0); + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override public BlockFace getBlockFace() { - return BlockFace.fromHorizontalIndex(this.getDamage() & 0x07); + return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; } } diff --git a/src/main/java/cn/nukkit/block/BlockFallable.java b/src/main/java/cn/nukkit/block/BlockFallable.java index 04740226643..9cb3ce6a0ff 100644 --- a/src/main/java/cn/nukkit/block/BlockFallable.java +++ b/src/main/java/cn/nukkit/block/BlockFallable.java @@ -9,9 +9,8 @@ import cn.nukkit.nbt.tag.FloatTag; import cn.nukkit.nbt.tag.ListTag; - /** - * author: rcsuperman + * @author rcsuperman * Nukkit Project */ public abstract class BlockFallable extends BlockSolid { @@ -28,7 +27,6 @@ public int onUpdate(int type) { if (event.isCancelled()) { return type; } - this.level.setBlock(this, Block.get(Block.AIR), true, true); CompoundTag nbt = new CompoundTag() .putList(new ListTag("Pos") @@ -46,11 +44,7 @@ public int onUpdate(int type) { .putInt("TileID", this.getId()) .putByte("Data", this.getDamage()); - EntityFallingBlock fall = (EntityFallingBlock) Entity.createEntity("FallingSand", this.getLevel().getChunk((int) this.x >> 4, (int) this.z >> 4), nbt); - - if (fall != null) { - fall.spawnToAll(); - } + Entity.createEntity(EntityFallingBlock.NETWORK_ID, this.getLevel().getChunk((int) this.x >> 4, (int) this.z >> 4), nbt).spawnToAll(); } } return type; diff --git a/src/main/java/cn/nukkit/block/BlockFallableMeta.java b/src/main/java/cn/nukkit/block/BlockFallableMeta.java new file mode 100644 index 00000000000..ff2c538eda9 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockFallableMeta.java @@ -0,0 +1,53 @@ +package cn.nukkit.block; + +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityFallingBlock; +import cn.nukkit.event.block.BlockFallEvent; +import cn.nukkit.level.Level; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.DoubleTag; +import cn.nukkit.nbt.tag.FloatTag; +import cn.nukkit.nbt.tag.ListTag; + +/** + * @author rcsuperman + * Nukkit Project + */ +public abstract class BlockFallableMeta extends BlockSolidMeta { + + protected BlockFallableMeta(int meta) { + super(meta); + } + + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + Block down = this.down(); + if (down.getId() == AIR || down instanceof BlockLiquid || down instanceof BlockFire) { + BlockFallEvent event = new BlockFallEvent(this); + this.level.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return type; + } + this.level.setBlock(this, Block.get(Block.AIR), true, true); + CompoundTag nbt = new CompoundTag() + .putList(new ListTag("Pos") + .add(new DoubleTag("", this.x + 0.5)) + .add(new DoubleTag("", this.y)) + .add(new DoubleTag("", this.z + 0.5))) + .putList(new ListTag("Motion") + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0))) + + .putList(new ListTag("Rotation") + .add(new FloatTag("", 0)) + .add(new FloatTag("", 0))) + .putInt("TileID", this.getId()) + .putByte("Data", this.getDamage()); + + Entity.createEntity(EntityFallingBlock.NETWORK_ID, this.getLevel().getChunk((int) this.x >> 4, (int) this.z >> 4), nbt).spawnToAll(); + } + } + return type; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockFarmland.java b/src/main/java/cn/nukkit/block/BlockFarmland.java index 7301b15da03..282365f18a9 100644 --- a/src/main/java/cn/nukkit/block/BlockFarmland.java +++ b/src/main/java/cn/nukkit/block/BlockFarmland.java @@ -4,7 +4,7 @@ import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemTool; import cn.nukkit.level.Level; -import cn.nukkit.math.Vector3; +import cn.nukkit.level.format.FullChunk; import cn.nukkit.utils.BlockColor; /** @@ -48,25 +48,21 @@ public int getToolType() { @Override public double getMaxY() { - return this.y + 1; + return this.y + 0.9375; } @Override public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_RANDOM) { - Vector3 v = new Vector3(); + Block up = this.up(); - if (this.level.getBlock(v.setComponents(x, this.y + 1, z)) instanceof BlockCrops) { - return 0; - } - - if (this.level.getBlock(v.setComponents(x, this.y + 1, z)).isSolid()) { + if (up.isSolid()) { this.level.setBlock(this, Block.get(BlockID.DIRT), false, true); - return Level.BLOCK_UPDATE_RANDOM; } boolean found = false; + boolean unloadedChunk = false; if (this.level.isRaining()) { found = true; @@ -78,10 +74,14 @@ public int onUpdate(int type) { continue; } - v.setComponents(x, y, z); - int block = this.level.getBlockIdAt(v.getFloorX(), v.getFloorY(), v.getFloorZ()); + FullChunk chunk = this.level.getChunkIfLoaded(x >> 4, z >> 4); + if (chunk == null) { + unloadedChunk = true; + continue; + } - if (block == WATER || block == STILL_WATER) { + int block = this.level.getBlockIdAt(chunk, x, y, z); + if (Block.isWater(block) || block == FROSTED_ICE || this.level.isBlockWaterloggedAt(chunk, x, y, z)) { found = true; break; } @@ -90,23 +90,32 @@ public int onUpdate(int type) { } } - Block block = this.level.getBlock(v.setComponents(x, y - 1, z)); - if (found || block instanceof BlockWater) { + if (!found && unloadedChunk) { + return 0; + } + + Block block; + if (found || (block = this.down()) instanceof BlockWater || block instanceof BlockIceFrosted) { if (this.getDamage() < 7) { this.setDamage(7); - this.level.setBlock(this, this, false, false); + this.level.setBlock(this, this, false, true); } return Level.BLOCK_UPDATE_RANDOM; } if (this.getDamage() > 0) { this.setDamage(this.getDamage() - 1); - this.level.setBlock(this, this, false, false); - } else { + this.level.setBlock(this, this, false, true); + } else if (!(up instanceof BlockCrops)) { this.level.setBlock(this, Block.get(Block.DIRT), false, true); } return Level.BLOCK_UPDATE_RANDOM; + } else if (type == Level.BLOCK_UPDATE_NORMAL) { + if (this.up().isSolid()) { + this.level.setBlock(this, Block.get(DIRT), false, true); + return Level.BLOCK_UPDATE_NORMAL; + } } return 0; diff --git a/src/main/java/cn/nukkit/block/BlockFence.java b/src/main/java/cn/nukkit/block/BlockFence.java index 3c6356511de..98f6d05c201 100644 --- a/src/main/java/cn/nukkit/block/BlockFence.java +++ b/src/main/java/cn/nukkit/block/BlockFence.java @@ -48,22 +48,22 @@ public int getToolType() { return ItemTool.TYPE_AXE; } + private static final String[] NAMES = { + "Oak Fence", + "Spruce Fence", + "Birch Fence", + "Jungle Fence", + "Acacia Fence", + "Dark Oak Fence", + "", + "" + }; + @Override public String getName() { - String[] names = new String[]{ - "Oak Fence", - "Spruce Fence", - "Birch Fence", - "Jungle Fence", - "Acacia Fence", - "Dark Oak Fence", - "", - "" - }; - return names[this.getDamage() & 0x07]; + return NAMES[this.getDamage() & 0x07]; } - @Override protected AxisAlignedBB recalculateBoundingBox() { boolean north = this.canConnect(this.north()); boolean south = this.canConnect(this.south()); @@ -99,19 +99,19 @@ public boolean canConnect(Block block) { @Override public BlockColor getColor() { - switch(this.getDamage() & 0x07){ + switch (this.getDamage() & 0x07) { default: - case BlockFence.FENCE_OAK: //OAK + case FENCE_OAK: //OAK return BlockColor.WOOD_BLOCK_COLOR; - case BlockFence.FENCE_SPRUCE: //SPRUCE + case FENCE_SPRUCE: //SPRUCE return BlockColor.SPRUCE_BLOCK_COLOR; - case BlockFence.FENCE_BIRCH: //BIRCH + case FENCE_BIRCH: //BIRCH return BlockColor.SAND_BLOCK_COLOR; - case BlockFence.FENCE_JUNGLE: //JUNGLE + case FENCE_JUNGLE: //JUNGLE return BlockColor.DIRT_BLOCK_COLOR; - case BlockFence.FENCE_ACACIA: //ACACIA + case FENCE_ACACIA: //ACACIA return BlockColor.ORANGE_BLOCK_COLOR; - case BlockFence.FENCE_DARK_OAK: //DARK OAK + case FENCE_DARK_OAK: //DARK OAK return BlockColor.BROWN_BLOCK_COLOR; } } @@ -120,4 +120,9 @@ public BlockColor getColor() { public Item toItem() { return new ItemBlock(this, this.getDamage()); } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } } diff --git a/src/main/java/cn/nukkit/block/BlockFenceCrimson.java b/src/main/java/cn/nukkit/block/BlockFenceCrimson.java new file mode 100644 index 00000000000..055c65ebfdf --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockFenceCrimson.java @@ -0,0 +1,40 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; + +public class BlockFenceCrimson extends BlockFence { + + public BlockFenceCrimson() { + this(0); + } + + public BlockFenceCrimson(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Crimson Fence"; + } + + @Override + public int getId() { + return CRIMSON_FENCE; + } + + @Override + public int getBurnChance() { + return 0; + } + + @Override + public int getBurnAbility() { + return 0; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockFenceGate.java b/src/main/java/cn/nukkit/block/BlockFenceGate.java index 15c18e7b44a..a776602fd42 100644 --- a/src/main/java/cn/nukkit/block/BlockFenceGate.java +++ b/src/main/java/cn/nukkit/block/BlockFenceGate.java @@ -5,8 +5,8 @@ import cn.nukkit.item.Item; import cn.nukkit.item.ItemTool; import cn.nukkit.level.Level; +import cn.nukkit.level.Sound; import cn.nukkit.math.BlockFace; -import cn.nukkit.network.protocol.LevelEventPacket; import cn.nukkit.utils.BlockColor; import cn.nukkit.utils.Faceable; @@ -104,8 +104,8 @@ public double getMaxZ() { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { this.setDamage(player != null ? player.getDirection().getHorizontalIndex() : 0); - this.getLevel().setBlock(block, this, true, true); + this.getLevel().setBlock(this, this, true, true); return true; } @@ -119,7 +119,12 @@ public boolean onActivate(Item item, Player player) { return false; } - this.getLevel().addLevelEvent(this.add(0.5, 0.5, 0.5), LevelEventPacket.EVENT_SOUND_DOOR); + this.getLevel().setBlock(this, this, true); + if (this.isOpen()) { + this.level.addSound(this, Sound.RANDOM_DOOR_OPEN); + } else { + this.level.addSound(this, Sound.RANDOM_DOOR_CLOSE); + } return true; } @@ -174,7 +179,12 @@ public boolean toggle(Player player) { } this.setDamage(direction | ((~this.getDamage()) & 0x04)); - this.level.setBlock(this, this, false, false); + this.level.setBlock(this, this, true, false); + if (this.isOpen()) { + this.level.addSound(this, Sound.RANDOM_DOOR_OPEN); + } else { + this.level.addSound(this, Sound.RANDOM_DOOR_CLOSE); + } return true; } @@ -185,7 +195,8 @@ public boolean isOpen() { @Override public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_REDSTONE) { - if ((!isOpen() && this.level.isBlockPowered(this.getLocation())) || (isOpen() && !this.level.isBlockPowered(this.getLocation()))) { + boolean powered = this.level.isBlockPowered(this); + if ((!isOpen() && powered) || (isOpen() && !powered)) { this.toggle(null); return type; } @@ -193,7 +204,7 @@ public int onUpdate(int type) { return 0; } - + @Override public Item toItem() { return Item.get(Item.FENCE_GATE, 0, 1); @@ -201,6 +212,16 @@ public Item toItem() { @Override public BlockFace getBlockFace() { - return BlockFace.fromHorizontalIndex(this.getDamage() & 0x07); + return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); + } + + @Override + public boolean canPassThrough() { + return this.isOpen(); + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; } -} \ No newline at end of file +} diff --git a/src/main/java/cn/nukkit/block/BlockFenceGateAcacia.java b/src/main/java/cn/nukkit/block/BlockFenceGateAcacia.java index db80aa78a0f..69663971f3b 100644 --- a/src/main/java/cn/nukkit/block/BlockFenceGateAcacia.java +++ b/src/main/java/cn/nukkit/block/BlockFenceGateAcacia.java @@ -8,6 +8,7 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockFenceGateAcacia extends BlockFenceGate { + public BlockFenceGateAcacia() { this(0); } @@ -25,7 +26,7 @@ public int getId() { public String getName() { return "Acacia Fence Gate"; } - + @Override public Item toItem() { return Item.get(Item.FENCE_GATE_ACACIA, 0, 1); diff --git a/src/main/java/cn/nukkit/block/BlockFenceGateBirch.java b/src/main/java/cn/nukkit/block/BlockFenceGateBirch.java index 9b0723112bf..97654be29f5 100644 --- a/src/main/java/cn/nukkit/block/BlockFenceGateBirch.java +++ b/src/main/java/cn/nukkit/block/BlockFenceGateBirch.java @@ -8,6 +8,7 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockFenceGateBirch extends BlockFenceGate { + public BlockFenceGateBirch() { this(0); } @@ -25,7 +26,7 @@ public int getId() { public String getName() { return "Birch Fence Gate"; } - + @Override public Item toItem() { return Item.get(Item.FENCE_GATE_BIRCH, 0, 1); diff --git a/src/main/java/cn/nukkit/block/BlockFenceGateCrimson.java b/src/main/java/cn/nukkit/block/BlockFenceGateCrimson.java new file mode 100644 index 00000000000..e0c76702ebf --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockFenceGateCrimson.java @@ -0,0 +1,30 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; + +public class BlockFenceGateCrimson extends BlockFenceGate { + + public BlockFenceGateCrimson() { + this(0); + } + + public BlockFenceGateCrimson(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Crimson Fence Gate"; + } + + @Override + public int getId() { + return CRIMSON_FENCE_GATE; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockFenceGateDarkOak.java b/src/main/java/cn/nukkit/block/BlockFenceGateDarkOak.java index 9f03cf39859..04ca651b283 100644 --- a/src/main/java/cn/nukkit/block/BlockFenceGateDarkOak.java +++ b/src/main/java/cn/nukkit/block/BlockFenceGateDarkOak.java @@ -8,6 +8,7 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockFenceGateDarkOak extends BlockFenceGate { + public BlockFenceGateDarkOak() { this(0); } @@ -25,7 +26,7 @@ public int getId() { public String getName() { return "Dark Oak Fence Gate"; } - + @Override public Item toItem() { return Item.get(Item.FENCE_GATE_DARK_OAK, 0, 1); diff --git a/src/main/java/cn/nukkit/block/BlockFenceGateJungle.java b/src/main/java/cn/nukkit/block/BlockFenceGateJungle.java index fe8c23fa047..eb5e176489d 100644 --- a/src/main/java/cn/nukkit/block/BlockFenceGateJungle.java +++ b/src/main/java/cn/nukkit/block/BlockFenceGateJungle.java @@ -8,6 +8,7 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockFenceGateJungle extends BlockFenceGate { + public BlockFenceGateJungle() { this(0); } @@ -25,7 +26,7 @@ public int getId() { public String getName() { return "Jungle Fence Gate"; } - + @Override public Item toItem() { return Item.get(Item.FENCE_GATE_JUNGLE, 0, 1); diff --git a/src/main/java/cn/nukkit/block/BlockFenceGateSpruce.java b/src/main/java/cn/nukkit/block/BlockFenceGateSpruce.java index d9809efd834..8b38f74dfd1 100644 --- a/src/main/java/cn/nukkit/block/BlockFenceGateSpruce.java +++ b/src/main/java/cn/nukkit/block/BlockFenceGateSpruce.java @@ -8,6 +8,7 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockFenceGateSpruce extends BlockFenceGate { + public BlockFenceGateSpruce() { this(0); } @@ -25,7 +26,7 @@ public int getId() { public String getName() { return "Spruce Fence Gate"; } - + @Override public Item toItem() { return Item.get(Item.FENCE_GATE_SPRUCE,0, 1); diff --git a/src/main/java/cn/nukkit/block/BlockFenceGateWarped.java b/src/main/java/cn/nukkit/block/BlockFenceGateWarped.java new file mode 100644 index 00000000000..e916d49396d --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockFenceGateWarped.java @@ -0,0 +1,30 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; + +public class BlockFenceGateWarped extends BlockFenceGate { + + public BlockFenceGateWarped() { + this(0); + } + + public BlockFenceGateWarped(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Warped Fence Gate"; + } + + @Override + public int getId() { + return WARPED_FENCE_GATE; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockFenceNetherBrick.java b/src/main/java/cn/nukkit/block/BlockFenceNetherBrick.java index f8ca8847192..baa16ba4c74 100644 --- a/src/main/java/cn/nukkit/block/BlockFenceNetherBrick.java +++ b/src/main/java/cn/nukkit/block/BlockFenceNetherBrick.java @@ -33,11 +33,6 @@ public int getId() { return NETHER_BRICK_FENCE; } - @Override - public double getHardness() { - return 2; - } - @Override public double getResistance() { return 10; @@ -45,7 +40,7 @@ public double getResistance() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; diff --git a/src/main/java/cn/nukkit/block/BlockFenceWarped.java b/src/main/java/cn/nukkit/block/BlockFenceWarped.java new file mode 100644 index 00000000000..5e9a3841594 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockFenceWarped.java @@ -0,0 +1,40 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; + +public class BlockFenceWarped extends BlockFence { + + public BlockFenceWarped() { + this(0); + } + + public BlockFenceWarped(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Warped Fence"; + } + + @Override + public int getId() { + return WARPED_FENCE; + } + + @Override + public int getBurnChance() { + return 0; + } + + @Override + public int getBurnAbility() { + return 0; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockFire.java b/src/main/java/cn/nukkit/block/BlockFire.java index 4d1eeb3458f..6d9b7bd3505 100644 --- a/src/main/java/cn/nukkit/block/BlockFire.java +++ b/src/main/java/cn/nukkit/block/BlockFire.java @@ -1,7 +1,9 @@ package cn.nukkit.block; import cn.nukkit.Server; +import cn.nukkit.entity.BaseEntity; import cn.nukkit.entity.Entity; +import cn.nukkit.entity.EntityLiving; import cn.nukkit.entity.item.EntityPotion; import cn.nukkit.entity.projectile.EntityArrow; import cn.nukkit.event.block.BlockBurnEvent; @@ -16,16 +18,13 @@ import cn.nukkit.level.Level; import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.math.BlockFace; -import cn.nukkit.math.Vector3; import cn.nukkit.potion.Effect; import cn.nukkit.potion.Potion; import cn.nukkit.utils.BlockColor; - -import java.util.Random; -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockFire extends BlockFlowable { @@ -81,17 +80,24 @@ public void onEntityCollide(Entity entity) { } } - if (!entity.hasEffect(Effect.FIRE_RESISTANCE)) { - entity.attack(new EntityDamageByBlockEvent(this, entity, DamageCause.FIRE, 1)); - } + if (!entity.fireProof || !entity.isOnFire() || !(entity instanceof BaseEntity)) { // Improve performance - EntityCombustByBlockEvent ev = new EntityCombustByBlockEvent(this, entity, 8); - if (entity instanceof EntityArrow) { - ev.setCancelled(); - } - Server.getInstance().getPluginManager().callEvent(ev); - if (!ev.isCancelled() && entity.isAlive() && entity.noDamageTicks == 0) { - entity.setOnFire(ev.getDuration()); + if (!(entity instanceof EntityLiving) || (!entity.hasEffect(Effect.FIRE_RESISTANCE) && this.level.getGameRules().getBoolean(GameRule.FIRE_DAMAGE))) { + entity.attack(new EntityDamageByBlockEvent(this, entity, DamageCause.FIRE, 1)); + } + + if (!entity.fireProof || !entity.isOnFire()) { + EntityCombustByBlockEvent ev = new EntityCombustByBlockEvent(this, entity, 8); + if (entity instanceof EntityArrow) { + ev.setCancelled(); + } + + Server.getInstance().getPluginManager().callEvent(ev); + + if (!ev.isCancelled() && entity.isAlive() && entity.noDamageTicks == 0) { + entity.setOnFire(ev.getDuration()); + } + } } } @@ -104,28 +110,15 @@ public Item[] getDrops(Item item) { public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_NORMAL || type == Level.BLOCK_UPDATE_RANDOM) { if (!this.isBlockTopFacingSurfaceSolid(this.down()) && !this.canNeighborBurn()) { - BlockFadeEvent event = new BlockFadeEvent(this, get(AIR)); - level.getServer().getPluginManager().callEvent(event); - if (!event.isCancelled()) { - level.setBlock(this, event.getNewState(), true); - } + this.getLevel().setBlock(this, Block.get(BlockID.AIR), true); + } else if (this.level.gameRules.getBoolean(GameRule.DO_FIRE_TICK) && !level.isUpdateScheduled(this, this)) { + level.scheduleUpdate(this, tickRate()); } return Level.BLOCK_UPDATE_NORMAL; } else if (type == Level.BLOCK_UPDATE_SCHEDULED && this.level.gameRules.getBoolean(GameRule.DO_FIRE_TICK)) { - boolean forever = this.down().getId() == Block.NETHERRACK || this.down().getId() == Block.MAGMA; - - ThreadLocalRandom random = ThreadLocalRandom.current(); - - //TODO: END - - if (!this.isBlockTopFacingSurfaceSolid(this.down()) && !this.canNeighborBurn()) { - BlockFadeEvent event = new BlockFadeEvent(this, get(AIR)); - level.getServer().getPluginManager().callEvent(event); - if (!event.isCancelled()) { - level.setBlock(this, event.getNewState(), true); - } - } + Block down = this.down(); + boolean forever = this.getId() == SOUL_FIRE || down.getId() == NETHERRACK || down.getId() == MAGMA || (down.getId() == BEDROCK && level.getDimension() == Level.DIMENSION_THE_END); if (!forever && this.getLevel().isRaining() && (this.getLevel().canBlockSeeSky(this) || @@ -134,80 +127,75 @@ public int onUpdate(int type) { this.getLevel().canBlockSeeSky(this.south()) || this.getLevel().canBlockSeeSky(this.north())) ) { - BlockFadeEvent event = new BlockFadeEvent(this, get(AIR)); - level.getServer().getPluginManager().callEvent(event); - if (!event.isCancelled()) { - level.setBlock(this, event.getNewState(), true); + + this.getLevel().setBlock(this, Block.get(BlockID.AIR), true); + } + + if (!this.isBlockTopFacingSurfaceSolid(down) && !this.canNeighborBurn()) { + this.getLevel().setBlock(this, Block.get(BlockID.AIR), true); + return 0; + } + + int meta = this.getDamage(); + + if (meta < 15) { + int newMeta = meta + Utils.random.nextInt(3); + if (newMeta > 15) newMeta = 15; + this.setDamage(newMeta); + this.getLevel().setBlock((int) this.x, (int) this.y, (int) this.z, BlockLayer.NORMAL, this, false, true, false); // No need to send this to client + } + + this.getLevel().scheduleUpdate(this, this.tickRate() + Utils.random.nextInt(10)); + + if (!forever && !this.canNeighborBurn()) { + if (!this.isBlockTopFacingSurfaceSolid(this.down()) || meta > 3) { + this.getLevel().setBlock(this, Block.get(BlockID.AIR), true); } + } else if (!forever && !(this.down().getBurnAbility() > 0) && meta == 15 && Utils.random.nextInt(4) == 0) { + this.getLevel().setBlock(this, Block.get(BlockID.AIR), true); } else { - int meta = this.getDamage(); + int o = 0; - if (meta < 15) { - int newMeta = meta + random.nextInt(3); - this.setDamage(Math.min(newMeta, 15)); - this.getLevel().setBlock(this, this, true); - } + //TODO: decrease the o if the rainfall values are high - this.getLevel().scheduleUpdate(this, this.tickRate() + random.nextInt(10)); + this.tryToCatchBlockOnFire(this.east(), 300 + o, meta); + this.tryToCatchBlockOnFire(this.west(), 300 + o, meta); + this.tryToCatchBlockOnFire(this.down(), 250 + o, meta); + this.tryToCatchBlockOnFire(this.up(), 250 + o, meta); + this.tryToCatchBlockOnFire(this.south(), 300 + o, meta); + this.tryToCatchBlockOnFire(this.north(), 300 + o, meta); - if (!forever && !this.canNeighborBurn()) { - if (!this.isBlockTopFacingSurfaceSolid(this.down()) || meta > 3) { - BlockFadeEvent event = new BlockFadeEvent(this, get(AIR)); - level.getServer().getPluginManager().callEvent(event); - if (!event.isCancelled()) { - level.setBlock(this, event.getNewState(), true); - } - } - } else if (!forever && !(this.down().getBurnAbility() > 0) && meta == 15 && random.nextInt(4) == 0) { - BlockFadeEvent event = new BlockFadeEvent(this, get(AIR)); - level.getServer().getPluginManager().callEvent(event); - if (!event.isCancelled()) { - level.setBlock(this, event.getNewState(), true); - } - } else { - int o = 0; - - //TODO: decrease the o if the rainfall values are high - - this.tryToCatchBlockOnFire(this.east(), 300 + o, meta); - this.tryToCatchBlockOnFire(this.west(), 300 + o, meta); - this.tryToCatchBlockOnFire(this.down(), 250 + o, meta); - this.tryToCatchBlockOnFire(this.up(), 250 + o, meta); - this.tryToCatchBlockOnFire(this.south(), 300 + o, meta); - this.tryToCatchBlockOnFire(this.north(), 300 + o, meta); - - for (int x = (int) (this.x - 1); x <= (int) (this.x + 1); ++x) { - for (int z = (int) (this.z - 1); z <= (int) (this.z + 1); ++z) { - for (int y = (int) (this.y - 1); y <= (int) (this.y + 4); ++y) { - if (x != (int) this.x || y != (int) this.y || z != (int) this.z) { - int k = 100; - - if (y > this.y + 1) { - k += (y - (this.y + 1)) * 100; - } + for (int x = (int) (this.x - 1); x <= (int) (this.x + 1); ++x) { + for (int z = (int) (this.z - 1); z <= (int) (this.z + 1); ++z) { + for (int y = (int) (this.y - 1); y <= (int) (this.y + 4); ++y) { + if (x != (int) this.x || y != (int) this.y || z != (int) this.z) { + int k = 100; + + if (y > this.y + 1) { + k += (y - (this.y + 1)) * 100; + } - Block block = this.getLevel().getBlock(new Vector3(x, y, z)); - int chance = this.getChanceOfNeighborsEncouragingFire(block); + Block block = this.getLevel().getBlock(x, y, z); + int chance = getChanceOfNeighborsEncouragingFire(block); - if (chance > 0) { - int t = (chance + 40 + this.getLevel().getServer().getDifficulty() * 7) / (meta + 30); + if (chance > 0) { + int t = (chance + 40 + this.getLevel().getServer().getDifficulty() * 7) / (meta + 30); - //TODO: decrease the t if the rainfall values are high + //TODO: decrease the t if the rainfall values are high - if (t > 0 && random.nextInt(k) <= t) { - int damage = meta + random.nextInt(5) / 4; + if (t > 0 && Utils.random.nextInt(k) <= t) { + int damage = meta + (Utils.random.nextInt(5) >> 2); - if (damage > 15) { - damage = 15; - } + if (damage > 15) { + damage = 15; + } - BlockIgniteEvent e = new BlockIgniteEvent(block, this, null, BlockIgniteEvent.BlockIgniteCause.SPREAD); - this.level.getServer().getPluginManager().callEvent(e); + BlockIgniteEvent e = new BlockIgniteEvent(block, this, null, BlockIgniteEvent.BlockIgniteCause.SPREAD); + this.level.getServer().getPluginManager().callEvent(e); - if (!e.isCancelled()) { - this.getLevel().setBlock(block, Block.get(BlockID.FIRE, damage), true); - this.getLevel().scheduleUpdate(block, this.tickRate()); - } + if (!e.isCancelled()) { + this.getLevel().setBlock(block, Block.get(FIRE, damage), true); + this.getLevel().scheduleUpdate(block, this.tickRate()); } } } @@ -222,14 +210,10 @@ public int onUpdate(int type) { } private void tryToCatchBlockOnFire(Block block, int bound, int damage) { - int burnAbility = block.getBurnAbility(); - - Random random = ThreadLocalRandom.current(); - - if (random.nextInt(bound) < burnAbility) { + if (Utils.random.nextInt(bound) < block.getBurnAbility()) { - if (random.nextInt(damage + 10) < 5) { - int meta = damage + random.nextInt(5) / 4; + if (Utils.random.nextInt(damage + 10) < 5) { + int meta = damage + (Utils.random.nextInt(5) >> 2); if (meta > 15) { meta = 15; @@ -239,7 +223,7 @@ private void tryToCatchBlockOnFire(Block block, int bound, int damage) { this.level.getServer().getPluginManager().callEvent(e); if (!e.isCancelled()) { - this.getLevel().setBlock(block, Block.get(BlockID.FIRE, meta), true); + this.getLevel().setBlock(block, Block.get(FIRE, meta), true); this.getLevel().scheduleUpdate(block, this.tickRate()); } } else { @@ -257,7 +241,7 @@ private void tryToCatchBlockOnFire(Block block, int bound, int damage) { } } - private int getChanceOfNeighborsEncouragingFire(Block block) { + private static int getChanceOfNeighborsEncouragingFire(Block block) { if (block.getId() != AIR) { return 0; } else { @@ -284,23 +268,31 @@ public boolean canNeighborBurn() { public boolean isBlockTopFacingSurfaceSolid(Block block) { if (block != null) { - if (block.isSolid()) { + if (block instanceof BlockStairs && (block.getDamage() & 4) == 4) { return true; - } else { - if (block instanceof BlockStairs && - (block.getDamage() & 4) == 4) { - - return true; - } else if (block instanceof BlockSlab && - (block.getDamage() & 8) == 8) { - - return true; - } else if (block instanceof BlockSnowLayer && - (block.getDamage() & 7) == 7) { - - return true; - } - } + } else if (block instanceof BlockSlab && (this.getDamage() & 0x08) > 0) { + return true; + } else if (block instanceof BlockSnowLayer && (block.getDamage() & 7) == 7) { + return true; + } else if (block instanceof BlockGlass) { + return false; + } else if (block instanceof BlockHopper || block instanceof BlockBeacon) { + return false; + } else if (block instanceof BlockShulkerBox || block instanceof BlockChest || block instanceof BlockEnderChest) { + return false; + } else if (block instanceof BlockAnvil || block instanceof BlockEnchantingTable || block instanceof BlockBrewingStand) { + return false; + } else if (block instanceof BlockCampfire) { + return false; + } else if (block instanceof BlockCactus) { + return false; + } else if (block instanceof BlockDaylightDetector) { + return false; + } else if (block instanceof BlockIce) { + return false; + } else if (block instanceof BlockCake) { + return false; + } else return block.isSolid(); } return false; @@ -313,7 +305,7 @@ public int tickRate() { @Override public BlockColor getColor() { - return BlockColor.LAVA_BLOCK_COLOR; + return BlockColor.AIR_BLOCK_COLOR; } @Override @@ -325,4 +317,9 @@ protected AxisAlignedBB recalculateCollisionBoundingBox() { public Item toItem() { return new ItemBlock(Block.get(BlockID.AIR)); } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockFletchingTable.java b/src/main/java/cn/nukkit/block/BlockFletchingTable.java new file mode 100644 index 00000000000..cf57ce7b062 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockFletchingTable.java @@ -0,0 +1,42 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockFletchingTable extends BlockSolid { + + @Override + public String getName() { + return "Fletching Table"; + } + + @Override + public int getId() { + return FLETCHING_TABLE; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_AXE; + } + + @Override + public double getResistance() { + return 12.5; + } + + @Override + public double getHardness() { + return 2.5; + } + + @Override + public BlockColor getColor() { + return BlockColor.WOOD_BLOCK_COLOR; + } + + @Override + public int getBurnChance() { + return 5; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockFlowable.java b/src/main/java/cn/nukkit/block/BlockFlowable.java index a0f2d7dd5b8..0dbc59e6d8f 100644 --- a/src/main/java/cn/nukkit/block/BlockFlowable.java +++ b/src/main/java/cn/nukkit/block/BlockFlowable.java @@ -3,7 +3,7 @@ import cn.nukkit.math.AxisAlignedBB; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class BlockFlowable extends BlockTransparentMeta { @@ -41,4 +41,9 @@ public boolean isSolid() { protected AxisAlignedBB recalculateBoundingBox() { return null; } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockFlower.java b/src/main/java/cn/nukkit/block/BlockFlower.java index 9f5e60536bc..96ff0b6861f 100644 --- a/src/main/java/cn/nukkit/block/BlockFlower.java +++ b/src/main/java/cn/nukkit/block/BlockFlower.java @@ -2,19 +2,20 @@ import cn.nukkit.Player; import cn.nukkit.item.Item; +import cn.nukkit.item.ItemDye; import cn.nukkit.level.Level; import cn.nukkit.level.particle.BoneMealParticle; import cn.nukkit.math.BlockFace; import cn.nukkit.math.Vector3; import cn.nukkit.utils.BlockColor; - -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; /** * Created on 2015/11/23 by xtypr. * Package cn.nukkit.block in project Nukkit . */ public class BlockFlower extends BlockFlowable { + public static final int TYPE_POPPY = 0; public static final int TYPE_BLUE_ORCHID = 1; public static final int TYPE_ALLIUM = 2; @@ -27,6 +28,25 @@ public class BlockFlower extends BlockFlowable { public static final int TYPE_CORNFLOWER = 9; public static final int TYPE_LILY_OF_THE_VALLEY = 10; + private static final String[] NAMES = { + "Poppy", + "Blue Orchid", + "Allium", + "Azure Bluet", + "Red Tulip", + "Orange Tulip", + "White Tulip", + "Pink Tulip", + "Oxeye Daisy", + "Cornflower", + "Lily of the Valley", + "Unknown", + "Unknown", + "Unknown", + "Unknown", + "Unknown" + }; + public BlockFlower() { this(0); } @@ -42,34 +62,15 @@ public int getId() { @Override public String getName() { - String[] names = new String[]{ - "Poppy", - "Blue Orchid", - "Allium", - "Azure Bluet", - "Red Tulip", - "Orange Tulip", - "White Tulip", - "Pink Tulip", - "Oxeye Daisy", - "Cornflower", - "Lily of the Valley", - "Unknown", - "Unknown", - "Unknown", - "Unknown", - "Unknown" - }; - return names[this.getDamage() & 0x0f]; + return NAMES[this.getDamage() & 0x0f]; } @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { Block down = this.down(); int id = down.getId(); - if (id == Block.GRASS || id == Block.DIRT || id == Block.FARMLAND || id == Block.PODZOL || id == MYCELIUM) { + if (id == Block.GRASS || id == Block.DIRT || id == Block.FARMLAND || id == Block.PODZOL || id == MYCELIUM || id == MOSS_BLOCK) { this.getLevel().setBlock(block, this, true); - return true; } return false; @@ -100,8 +101,8 @@ public boolean canBeActivated() { @Override public boolean onActivate(Item item, Player player) { - if (item.getId() == Item.DYE && item.getDamage() == 0x0f) { //Bone meal - if (player != null && (player.gamemode & 0x01) == 0) { + if (item.getId() == Item.DYE && item.getDamage() == ItemDye.BONE_MEAL) { + if (player != null && !player.isCreative()) { item.count--; } @@ -109,15 +110,15 @@ public boolean onActivate(Item item, Player player) { for (int i = 0; i < 8; i++) { Vector3 vec = this.add( - ThreadLocalRandom.current().nextInt(-3, 4), - ThreadLocalRandom.current().nextInt(-1, 2), - ThreadLocalRandom.current().nextInt(-3, 4)); + Utils.random.nextInt(-3, 4), + Utils.random.nextInt(-1, 2), + Utils.random.nextInt(-3, 4)); - if (level.getBlock(vec).getId() == AIR && level.getBlock(vec.down()).getId() == GRASS && vec.getY() >= 0 && vec.getY() < 256) { - if (ThreadLocalRandom.current().nextInt(10) == 0) { + if (vec.getY() >= level.getMinBlockY() && vec.getY() <= level.getMaxBlockY() && level.getBlock(vec).getId() == AIR && level.getBlock(vec.down()).getId() == GRASS) { + if ((this.getDamage() == POPPY || this.getDamage() == DANDELION) && Utils.random.nextInt(10) == 0) { this.level.setBlock(vec, this.getUncommonFlower(), true); } else { - this.level.setBlock(vec, get(this.getId()), true); + this.level.setBlock(vec, get(this.getId(), this.getDamage()), true); } } } @@ -131,4 +132,9 @@ public boolean onActivate(Item item, Player player) { protected Block getUncommonFlower() { return get(DANDELION); } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockFlowerPot.java b/src/main/java/cn/nukkit/block/BlockFlowerPot.java index 1661b090f60..efafd50c07d 100644 --- a/src/main/java/cn/nukkit/block/BlockFlowerPot.java +++ b/src/main/java/cn/nukkit/block/BlockFlowerPot.java @@ -4,7 +4,8 @@ import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.blockentity.BlockEntityFlowerPot; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemFlowerPot; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.level.Level; import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.math.BlockFace; import cn.nukkit.nbt.tag.CompoundTag; @@ -23,8 +24,8 @@ public BlockFlowerPot(int meta) { super(meta); } - protected static boolean canPlaceIntoFlowerPot(int id) { - switch (id) { + private static boolean canPlaceIntoFlowerPot(Item item) { + switch (item.getId()) { case SAPLING: case DEAD_BUSH: case DANDELION: @@ -33,6 +34,35 @@ protected static boolean canPlaceIntoFlowerPot(int id) { case BROWN_MUSHROOM: case CACTUS: return true; + case TALL_GRASS: + if (item.getDamage() == 2 || item.getDamage() == 3) { + return true; + } + default: + return false; + } + } + + private static boolean canPlaceIntoFlowerPot(Block block) { + if (block == null) { + return false; + } + switch (block.getId()) { + case SAPLING: + case DEAD_BUSH: + case DANDELION: + case ROSE: + case RED_MUSHROOM: + case BROWN_MUSHROOM: + case CACTUS: + case BAMBOO: + case CRIMSON_FUNGUS: + case WARPED_FUNGUS: + case CRIMSON_ROOTS: + case WARPED_ROOTS: + case WITHER_ROSE: + case MANGROVE_PROPAGULE: + return true; default: return false; } @@ -48,19 +78,24 @@ public int getId() { return FLOWER_POT_BLOCK; } - @Override - public double getHardness() { - return 0; + private static boolean isSupportValid(Block block) { + return block.isSolid() || block.isNarrowSurface() || Block.canStayOnFullSolid(block); } @Override - public double getResistance() { + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + if (!isSupportValid(down())) { + level.useBreakOn(this); + return type; + } + } return 0; } @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - if (face != BlockFace.UP) return false; + if (!isSupportValid(down())) return false; CompoundTag nbt = new CompoundTag() .putString("id", BlockEntity.FLOWER_POT) .putInt("x", (int) this.x) @@ -73,10 +108,9 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl nbt.put(aTag.getName(), aTag); } } - BlockEntityFlowerPot flowerPot = (BlockEntityFlowerPot) BlockEntity.createBlockEntity(BlockEntity.FLOWER_POT, getLevel().getChunk((int) block.x >> 4, (int) block.z >> 4), nbt); - if (flowerPot == null) return false; + BlockEntity.createBlockEntity(BlockEntity.FLOWER_POT, this.getChunk(), nbt); - this.getLevel().setBlock(block, this, true, true); + this.getLevel().setBlock(this, this, true, true); return true; } @@ -85,26 +119,27 @@ public boolean canBeActivated() { return true; } - @Override - public boolean onActivate(Item item) { - return this.onActivate(item, null); - } - @Override public boolean onActivate(Item item, Player player) { BlockEntity blockEntity = getLevel().getBlockEntity(this); if (!(blockEntity instanceof BlockEntityFlowerPot)) return false; - - if (blockEntity.namedTag.getShort("item") != AIR || blockEntity.namedTag.getInt("mData") != AIR) { - if (!canPlaceIntoFlowerPot(item.getId())) { + if (blockEntity.namedTag.getShort("item") != AIR) { + if (!canPlaceIntoFlowerPot(item) && !canPlaceIntoFlowerPot(item.getBlockUnsafe())) { int id = blockEntity.namedTag.getShort("item"); - if (id == AIR) id = blockEntity.namedTag.getInt("mData"); - for (Item drop : player.getInventory().addItem(Item.get(id, blockEntity.namedTag.getInt("data")))) { - player.dropItem(drop); + if (id > 255) { + for (Item drop : player.getInventory().addItem(new ItemBlock(Block.get(id)))) { + player.dropItem(drop); + } + } else { + for (Item drop : player.getInventory().addItem(Item.get(id, blockEntity.namedTag.getInt("data")))) { + player.dropItem(drop); + } } blockEntity.namedTag.putShort("item", AIR); blockEntity.namedTag.putInt("data", 0); + blockEntity.setDirty(); + this.setDamage(0); this.level.setBlock(this, this, true); ((BlockEntityFlowerPot) blockEntity).spawnToAll(); @@ -112,30 +147,26 @@ public boolean onActivate(Item item, Player player) { } return false; } - int itemID; - int itemMeta; - if (!canPlaceIntoFlowerPot(item.getId())) { + if (!canPlaceIntoFlowerPot(item)) { Block block = item.getBlockUnsafe(); - if (block == null || !canPlaceIntoFlowerPot(block.getId())) { + if (!canPlaceIntoFlowerPot(block)) { return true; } itemID = block.getId(); - itemMeta = item.getDamage(); } else { itemID = item.getId(); - itemMeta = item.getDamage(); } blockEntity.namedTag.putShort("item", itemID); - blockEntity.namedTag.putInt("data", itemMeta); + blockEntity.namedTag.putInt("data", item.getDamage()); + blockEntity.setDirty(); this.setDamage(1); this.getLevel().setBlock(this, this, true); ((BlockEntityFlowerPot) blockEntity).spawnToAll(); - if (player.isSurvival()) { - item.setCount(item.getCount() - 1); - player.getInventory().setItemInHand(item.getCount() > 0 ? item : Item.get(Item.AIR)); + if (!player.isCreative()) { + item.count--; } return true; } @@ -153,13 +184,20 @@ public Item[] getDrops(Item item) { } if (dropInside) { - return new Item[]{ - new ItemFlowerPot(), - Item.get(insideID, insideMeta, 1) - }; + if (insideID > 255) { + return new Item[]{ + Item.get(Item.FLOWER_POT), + new ItemBlock(Block.get(insideID)) + }; + } else { + return new Item[]{ + Item.get(Item.FLOWER_POT), + Item.get(insideID, insideMeta, 1) + }; + } } else { return new Item[]{ - new ItemFlowerPot() + Item.get(Item.FLOWER_POT) }; } } @@ -201,6 +239,21 @@ public boolean canPassThrough() { @Override public Item toItem() { - return new ItemFlowerPot(); + return Item.get(Item.FLOWER_POT); + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean breakWhenPushed() { + return true; + } + + @Override + public boolean canBePushed() { + return false; // prevent item loss issue with pistons until a working implementation } } diff --git a/src/main/java/cn/nukkit/block/BlockFroglight.java b/src/main/java/cn/nukkit/block/BlockFroglight.java new file mode 100644 index 00000000000..86a103bb176 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockFroglight.java @@ -0,0 +1,37 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.utils.BlockColor; + +public abstract class BlockFroglight extends BlockSolidMeta { + + protected BlockFroglight(int meta) { + super(meta); + } + + @Override + public double getResistance() { + return 0.3; + } + + @Override + public double getHardness() { + return 0.3; + } + + @Override + public int getLightLevel() { + return 15; + } + + @Override + public BlockColor getColor() { + return BlockColor.WHITE_BLOCK_COLOR; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockFroglightOchre.java b/src/main/java/cn/nukkit/block/BlockFroglightOchre.java new file mode 100644 index 00000000000..11e80055764 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockFroglightOchre.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockFroglightOchre extends BlockFroglight { + + public BlockFroglightOchre() { + this(0); + } + + public BlockFroglightOchre(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Ochre Froglight"; + } + + @Override + public int getId() { + return OCHRE_FROGLIGHT; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockFroglightPearlescent.java b/src/main/java/cn/nukkit/block/BlockFroglightPearlescent.java new file mode 100644 index 00000000000..b1163833fbd --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockFroglightPearlescent.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockFroglightPearlescent extends BlockFroglight { + + public BlockFroglightPearlescent() { + this(0); + } + + public BlockFroglightPearlescent(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Pearlescent Froglight"; + } + + @Override + public int getId() { + return PEARLESCENT_FROGLIGHT; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockFroglightVerdant.java b/src/main/java/cn/nukkit/block/BlockFroglightVerdant.java new file mode 100644 index 00000000000..59992bf73c6 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockFroglightVerdant.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockFroglightVerdant extends BlockFroglight { + + public BlockFroglightVerdant() { + this(0); + } + + public BlockFroglightVerdant(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Verdant Froglight"; + } + + @Override + public int getId() { + return VERDANT_FROGLIGHT; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockFrogspawn.java b/src/main/java/cn/nukkit/block/BlockFrogspawn.java new file mode 100644 index 00000000000..4f012abbec1 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockFrogspawn.java @@ -0,0 +1,45 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.math.BlockFace; + +public class BlockFrogspawn extends BlockFlowable { + + public BlockFrogspawn() { + this(0); + } + + public BlockFrogspawn(int meta) { + super(0); + } + + @Override + public int getId() { + return FROG_SPAWN; + } + + @Override + public String getName() { + return "Frogspawn"; + } + + @Override + public Item[] getDrops(Item item) { + return new Item[0]; + } + + @Override + public int getDropExp() { + return 1; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + Block up; + if (!(block instanceof BlockWater) || !((up = block.up()) instanceof BlockAir)) { + return false; + } + return this.getLevel().setBlock(up, this, true, true); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockFungus.java b/src/main/java/cn/nukkit/block/BlockFungus.java new file mode 100644 index 00000000000..deaa054567a --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockFungus.java @@ -0,0 +1,89 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemDye; +import cn.nukkit.item.ItemID; +import cn.nukkit.level.Level; +import cn.nukkit.level.particle.BoneMealParticle; +import cn.nukkit.math.BlockFace; + +import java.util.concurrent.ThreadLocalRandom; + +public abstract class BlockFungus extends BlockFlowable { + + protected BlockFungus() { + super(0); + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (!isValidSupport(this.down())) { + return false; + } + return super.place(item, block, target, face, fx, fy, fz, player); + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL && !isValidSupport(down())) { + this.level.useBreakOn(this); + return type; + } + return 0; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (item.isNull()) { + return false; + } + + if (!(item.getId() == ItemID.DYE && item.getDamage() == ItemDye.BONE_MEAL)) { + return false; + } + + this.level.addParticle(new BoneMealParticle(this)); + if (player != null && !player.isCreative()) { + item.count--; + } + + Block down = this.down(); + if (!this.isValidSupport(down)) { + this.level.useBreakOn(this); + return true; + } + + if (!this.canGrowOn(down) || ThreadLocalRandom.current().nextFloat() >= 0.4) { + return true; + } + + this.grow(player); + return true; + } + + protected abstract boolean canGrowOn(Block support); + + protected boolean isValidSupport(Block support) { + switch (support.getId()) { + case GRASS: + case DIRT: + case PODZOL: + case FARMLAND: + case CRIMSON_NYLIUM: + case WARPED_NYLIUM: + case SOUL_SOIL: + case MYCELIUM: + return true; + default: + return false; + } + } + + @Override + public boolean canBeActivated() { + return true; + } + + public abstract boolean grow(Player cause); +} diff --git a/src/main/java/cn/nukkit/block/BlockFurnace.java b/src/main/java/cn/nukkit/block/BlockFurnace.java index 37851c63e3c..ac7ba3988c8 100644 --- a/src/main/java/cn/nukkit/block/BlockFurnace.java +++ b/src/main/java/cn/nukkit/block/BlockFurnace.java @@ -1,10 +1,13 @@ package cn.nukkit.block; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.Faceable; + /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ -public class BlockFurnace extends BlockFurnaceBurning { +public class BlockFurnace extends BlockFurnaceBurning implements Faceable { public BlockFurnace() { this(0); @@ -30,7 +33,7 @@ public int getLightLevel() { } @Override - public boolean canHarvestWithHand() { - return false; + public BlockFace getBlockFace() { + return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); } } \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockFurnaceBurning.java b/src/main/java/cn/nukkit/block/BlockFurnaceBurning.java index 2ef0ca35b9a..0cecc9f2ce8 100644 --- a/src/main/java/cn/nukkit/block/BlockFurnaceBurning.java +++ b/src/main/java/cn/nukkit/block/BlockFurnaceBurning.java @@ -12,15 +12,14 @@ import cn.nukkit.nbt.tag.ListTag; import cn.nukkit.nbt.tag.StringTag; import cn.nukkit.nbt.tag.Tag; -import cn.nukkit.utils.Faceable; import java.util.Map; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ -public class BlockFurnaceBurning extends BlockSolidMeta implements Faceable { +public class BlockFurnaceBurning extends BlockSolidMeta { public BlockFurnaceBurning() { this(0); @@ -67,8 +66,7 @@ public int getLightLevel() { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - int[] faces = {2, 5, 3, 4}; - this.setDamage(faces[player != null ? player.getDirection().getHorizontalIndex() : 0]); + this.setDamage(Block.FACES2534[player != null ? player.getDirection().getHorizontalIndex() : 0]); this.getLevel().setBlock(block, this, true, true); CompoundTag nbt = new CompoundTag() .putList(new ListTag<>("Items")) @@ -88,8 +86,8 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl } } - BlockEntityFurnace furnace = (BlockEntityFurnace) BlockEntity.createBlockEntity(BlockEntity.FURNACE, this.getLevel().getChunk((int) (this.x) >> 4, (int) (this.z) >> 4), nbt); - return furnace != null; + BlockEntity.createBlockEntity(BlockEntity.FURNACE, this.getChunk(), nbt); + return true; } @Override @@ -102,22 +100,11 @@ public boolean onBreak(Item item) { public boolean onActivate(Item item, Player player) { if (player != null) { BlockEntity t = this.getLevel().getBlockEntity(this); - BlockEntityFurnace furnace; - if (t instanceof BlockEntityFurnace) { - furnace = (BlockEntityFurnace) t; - } else { - CompoundTag nbt = new CompoundTag() - .putList(new ListTag<>("Items")) - .putString("id", BlockEntity.FURNACE) - .putInt("x", (int) this.x) - .putInt("y", (int) this.y) - .putInt("z", (int) this.z); - furnace = (BlockEntityFurnace) BlockEntity.createBlockEntity(BlockEntity.FURNACE, this.getLevel().getChunk((int) (this.x) >> 4, (int) (this.z) >> 4), nbt); - if (furnace == null) { - return false; - } + if (!(t instanceof BlockEntityFurnace)) { + return false; } + BlockEntityFurnace furnace = (BlockEntityFurnace) t; if (furnace.namedTag.contains("Lock") && furnace.namedTag.get("Lock") instanceof StringTag) { if (!furnace.namedTag.getString("Lock").equals(item.getCustomName())) { return true; @@ -132,12 +119,12 @@ public boolean onActivate(Item item, Player player) { @Override public Item toItem() { - return new ItemBlock(Block.get(BlockID.FURNACE)); + return new ItemBlock(Block.get(FURNACE)); } @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ this.toItem() }; @@ -167,7 +154,7 @@ public boolean canHarvestWithHand() { } @Override - public BlockFace getBlockFace() { - return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); + public boolean canBePushed() { + return false; // prevent item loss issue with pistons until a working implementation } } diff --git a/src/main/java/cn/nukkit/block/BlockGlass.java b/src/main/java/cn/nukkit/block/BlockGlass.java index 219e4df9dcd..c754c9c8168 100644 --- a/src/main/java/cn/nukkit/block/BlockGlass.java +++ b/src/main/java/cn/nukkit/block/BlockGlass.java @@ -4,14 +4,11 @@ import cn.nukkit.utils.BlockColor; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class BlockGlass extends BlockTransparent { - public BlockGlass() { - } - @Override public int getId() { return GLASS; diff --git a/src/main/java/cn/nukkit/block/BlockGlassPane.java b/src/main/java/cn/nukkit/block/BlockGlassPane.java index 3f04d2bee2b..e418f961fa4 100644 --- a/src/main/java/cn/nukkit/block/BlockGlassPane.java +++ b/src/main/java/cn/nukkit/block/BlockGlassPane.java @@ -9,9 +9,6 @@ */ public class BlockGlassPane extends BlockThin { - public BlockGlassPane() { - } - @Override public String getName() { return "Glass Pane"; @@ -46,4 +43,9 @@ public BlockColor getColor() { public boolean canSilkTouch() { return true; } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } } diff --git a/src/main/java/cn/nukkit/block/BlockGlassPaneStained.java b/src/main/java/cn/nukkit/block/BlockGlassPaneStained.java index 2c37ea9367b..85247cb6b85 100644 --- a/src/main/java/cn/nukkit/block/BlockGlassPaneStained.java +++ b/src/main/java/cn/nukkit/block/BlockGlassPaneStained.java @@ -20,7 +20,7 @@ public BlockGlassPaneStained(int meta) { @Override public int getFullId() { - return (getId() << 4) + getDamage(); + return (STAINED_GLASS_PANE << Block.DATA_BITS) + meta; } @Override @@ -30,7 +30,7 @@ public int getId() { @Override public String getName() { - return getDyeColor().getName() + " stained glass pane"; + return getDyeColor().getName() + " Stained Glass Pane"; } @Override @@ -39,7 +39,7 @@ public BlockColor getColor() { } public DyeColor getDyeColor() { - return DyeColor.getByWoolData(getDamage()); + return DyeColor.getByWoolData(meta); } @Override @@ -51,9 +51,4 @@ public final int getDamage() { public final void setDamage(int meta) { this.meta = meta; } - - @Override - public boolean canSilkTouch() { - return true; - } } diff --git a/src/main/java/cn/nukkit/block/BlockGlassStained.java b/src/main/java/cn/nukkit/block/BlockGlassStained.java index d27e300b820..7f746b4365a 100644 --- a/src/main/java/cn/nukkit/block/BlockGlassStained.java +++ b/src/main/java/cn/nukkit/block/BlockGlassStained.java @@ -20,7 +20,7 @@ public BlockGlassStained(int meta) { @Override public int getFullId() { - return (getId() << 4) + getDamage(); + return (this.getId() << Block.DATA_BITS) + this.getDamage(); } @Override @@ -35,11 +35,11 @@ public String getName() { @Override public BlockColor getColor() { - return DyeColor.getByWoolData(getDamage()).getColor(); + return DyeColor.getByWoolData(meta).getColor(); } public DyeColor getDyeColor() { - return DyeColor.getByWoolData(getDamage()); + return DyeColor.getByWoolData(meta); } @Override @@ -51,9 +51,4 @@ public final int getDamage() { public final void setDamage(int meta) { this.meta = meta; } - - @Override - public boolean canSilkTouch() { - return true; - } } diff --git a/src/main/java/cn/nukkit/block/BlockGlassTinted.java b/src/main/java/cn/nukkit/block/BlockGlassTinted.java new file mode 100644 index 00000000000..b4bf8595d0d --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockGlassTinted.java @@ -0,0 +1,30 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; + +public class BlockGlassTinted extends BlockGlass { + + public BlockGlassTinted() { + // Does nothing + } + + @Override + public String getName() { + return "Tinted Glass"; + } + + @Override + public int getId() { + return TINTED_GLASS; + } + + @Override + public Item[] getDrops(Item item) { + return new Item[] { this.toItem() }; + } + + @Override + public boolean canSilkTouch() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockGlowLichen.java b/src/main/java/cn/nukkit/block/BlockGlowLichen.java new file mode 100644 index 00000000000..495bec2ab82 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockGlowLichen.java @@ -0,0 +1,204 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.block.properties.BlockPropertiesHelper; +import cn.nukkit.block.custom.properties.BlockProperties; +import cn.nukkit.block.custom.properties.BooleanBlockProperty; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.level.Level; +import cn.nukkit.math.AxisAlignedBB; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.BlockColor; + +import java.util.EnumSet; +import java.util.Set; + +public class BlockGlowLichen extends BlockTransparentMeta implements BlockPropertiesHelper { + + // Currently multi_face_direction_bits: 0x01 - down, 0x02 - up, 0x04 - north, 0x08 - south, 0x10 - west, 0x20 - east + private static final BooleanBlockProperty CONNECTION_DOWN = new BooleanBlockProperty("connection_down", false); + private static final BooleanBlockProperty CONNECTION_UP = new BooleanBlockProperty("connection_up", false); + private static final BooleanBlockProperty CONNECTION_NORTH = new BooleanBlockProperty("connection_north", false); + private static final BooleanBlockProperty CONNECTION_SOUTH = new BooleanBlockProperty("connection_south", false); + private static final BooleanBlockProperty CONNECTION_WEST = new BooleanBlockProperty("connection_west", false); + private static final BooleanBlockProperty CONNECTION_EAST = new BooleanBlockProperty("connection_east", false); + + private static final BlockProperties PROPERTIES = new BlockProperties(CONNECTION_DOWN, CONNECTION_UP, CONNECTION_NORTH, CONNECTION_SOUTH, CONNECTION_WEST, CONNECTION_EAST); + + public BlockGlowLichen() { + this(0); + } + + public BlockGlowLichen(int meta) { + super(meta); + } + + @Override + public int getId() { + return GLOW_LICHEN; + } + + @Override + public String getName() { + return "Glow Lichen"; + } + + @Override + public BlockProperties getBlockProperties() { + return PROPERTIES; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (!this.canPlaceOn(block.down(), target) || !target.isSolid()) { + return false; + } + + if (block.getId() == GLOW_LICHEN) { + this.setDamage(block.getDamage()); + } else { + this.setDamage(0); + } + + this.setBlockFace(face.getOpposite(), true); + this.getLevel().setBlock(this, this, false, true); + return true; + } + + @Override + public Item[] getDrops(Item item) { + if (item.isShears()) { + return new Item[] { this.toItem() }; + } + return new Item[0]; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_SCHEDULED) { + this.getLevel().useBreakOn(this, null, null, true); + } else if (type != Level.BLOCK_UPDATE_NORMAL) { + return type; + } + + boolean update = false; + boolean support = false; + + Set faces = this.getSupportedFaces(); + for (BlockFace face : faces) { + Block block = this.getLevel().getBlock(this.getSide(face)); + if (block.isSolid()) { + support = true; + } else { + update = true; + this.setBlockFace(face, false); + } + } + + if (!support) { + this.getLevel().scheduleUpdate(this, 1); + } else if (update) { + this.getLevel().setBlock(this, this, false, true); + } + return type; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId()), 0, 1); + } + + @Override + public double getHardness() { + return 0.2; + } + + @Override + public int getLightLevel() { + return 7; + } + + @Override + public boolean canPassThrough() { + return true; + } + + @Override + public boolean canBeReplaced() { + return true; + } + + @Override + public boolean isSolid() { + return false; + } + + @Override + protected AxisAlignedBB recalculateBoundingBox() { + return null; + } + + @Override + public BlockColor getColor() { + return BlockColor.GRAY_BLOCK_COLOR; + } + + public void setBlockFace(BlockFace face, boolean value) { + switch (face) { + case UP: + this.setBooleanValue(CONNECTION_UP, value); + break; + case DOWN: + this.setBooleanValue(CONNECTION_DOWN, value); + break; + case NORTH: + this.setBooleanValue(CONNECTION_NORTH, value); + break; + case SOUTH: + this.setBooleanValue(CONNECTION_SOUTH, value); + break; + case WEST: + this.setBooleanValue(CONNECTION_WEST, value); + break; + case EAST: + this.setBooleanValue(CONNECTION_EAST, value); + break; + + } + } + + public boolean hasBlockFace(BlockFace face) { + switch (face) { + case UP: + return this.getBooleanValue(CONNECTION_UP); + case DOWN: + return this.getBooleanValue(CONNECTION_DOWN); + case NORTH: + return this.getBooleanValue(CONNECTION_NORTH); + case SOUTH: + return this.getBooleanValue(CONNECTION_SOUTH); + case WEST: + return this.getBooleanValue(CONNECTION_WEST); + case EAST: + return this.getBooleanValue(CONNECTION_EAST); + + } + return false; + } + + public Set getSupportedFaces() { + EnumSet faces = EnumSet.noneOf(BlockFace.class); + for (BlockFace face : BlockFace.values()) { + if (this.hasBlockFace(face)) { + faces.add(face); + } + } + return faces; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockGlowstone.java b/src/main/java/cn/nukkit/block/BlockGlowstone.java index 77e95fdd708..99eebf56fed 100644 --- a/src/main/java/cn/nukkit/block/BlockGlowstone.java +++ b/src/main/java/cn/nukkit/block/BlockGlowstone.java @@ -1,20 +1,16 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemGlowstoneDust; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.math.MathHelper; import cn.nukkit.utils.BlockColor; - -import java.util.Random; +import cn.nukkit.utils.Utils; /** * Created on 2015/12/6 by xtypr. * Package cn.nukkit.block in project Nukkit . */ public class BlockGlowstone extends BlockTransparent { - public BlockGlowstone() { - } @Override public String getName() { @@ -43,16 +39,19 @@ public int getLightLevel() { @Override public Item[] getDrops(Item item) { - Random random = new Random(); - int count = 2 + random.nextInt(3); + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; + } + + int count = 2 + Utils.random.nextInt(3); Enchantment fortune = item.getEnchantment(Enchantment.ID_FORTUNE_DIGGING); if (fortune != null && fortune.getLevel() >= 1) { - count += random.nextInt(fortune.getLevel() + 1); + count += Utils.random.nextInt(fortune.getLevel() + 1); } return new Item[]{ - new ItemGlowstoneDust(0, MathHelper.clamp(count, 1, 4)) + Item.get(Item.GLOWSTONE_DUST, 0, MathHelper.clamp(count, 1, 4)) }; } diff --git a/src/main/java/cn/nukkit/block/BlockGold.java b/src/main/java/cn/nukkit/block/BlockGold.java index 35b92555d88..7124c8445f2 100644 --- a/src/main/java/cn/nukkit/block/BlockGold.java +++ b/src/main/java/cn/nukkit/block/BlockGold.java @@ -5,15 +5,11 @@ import cn.nukkit.utils.BlockColor; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class BlockGold extends BlockSolid { - - public BlockGold() { - } - @Override public int getId() { return GOLD_BLOCK; @@ -21,7 +17,7 @@ public int getId() { @Override public String getName() { - return "Gold Block"; + return "Block of Gold"; } @Override diff --git a/src/main/java/cn/nukkit/block/BlockGrass.java b/src/main/java/cn/nukkit/block/BlockGrass.java index 3da4fe6faa7..65c0e26ebb7 100644 --- a/src/main/java/cn/nukkit/block/BlockGrass.java +++ b/src/main/java/cn/nukkit/block/BlockGrass.java @@ -4,14 +4,18 @@ import cn.nukkit.Server; import cn.nukkit.event.block.BlockSpreadEvent; import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemDye; +import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.level.Level; +import cn.nukkit.level.Sound; import cn.nukkit.level.generator.object.ObjectTallGrass; import cn.nukkit.level.particle.BoneMealParticle; -import cn.nukkit.math.NukkitRandom; import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.Utils; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class BlockGrass extends BlockDirt { @@ -21,7 +25,6 @@ public BlockGrass() { } public BlockGrass(int meta) { - // Grass can't have meta. super(0); } @@ -47,8 +50,8 @@ public String getName() { @Override public boolean onActivate(Item item, Player player) { - if (item.getId() == Item.DYE && item.getDamage() == 0x0F) { - ObjectTallGrass.growGrass(this.getLevel(), this, new NukkitRandom()); + if (item.getId() == Item.DYE && item.getDamage() == ItemDye.BONE_MEAL) { + ObjectTallGrass.growGrass(this.getLevel(), this); this.level.addParticle(new BoneMealParticle(this)); if (player != null) { if (!player.isCreative()) { @@ -61,6 +64,9 @@ public boolean onActivate(Item item, Player player) { if (up instanceof BlockAir || up instanceof BlockFlowable) { item.useOn(this); this.getLevel().setBlock(this, Block.get(FARMLAND)); + if (player != null) { + player.getLevel().addSound(player, Sound.STEP_GRASS); + } return true; } } else if (item.isShovel()) { @@ -68,6 +74,9 @@ public boolean onActivate(Item item, Player player) { if (up instanceof BlockAir || up instanceof BlockFlowable) { item.useOn(this); this.getLevel().setBlock(this, Block.get(GRASS_PATH)); + if (player != null) { + player.getLevel().addSound(player, Sound.STEP_GRASS); + } return true; } } @@ -79,6 +88,10 @@ public boolean onActivate(Item item, Player player) { public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_RANDOM) { Block up = this.up(); + if (up instanceof BlockUnknown) { + return 0; + } + if ((up.isSolid() && !up.isTransparent()) || up instanceof BlockLiquid) { BlockSpreadEvent ev = new BlockSpreadEvent(this, this, Block.get(BlockID.DIRT)); Server.getInstance().getPluginManager().callEvent(ev); @@ -88,10 +101,9 @@ public int onUpdate(int type) { return 0; } - NukkitRandom random = new NukkitRandom(); - int xx = random.nextRange((int) x - 1, (int) x + 1); - int yy = random.nextRange((int) y - 2, (int) y + 2); - int zz = random.nextRange((int) z - 1, (int) z + 1); + int xx = Utils.rand((int) x - 1, (int) x + 1); + int yy = Utils.rand((int) y - 2, (int) y + 2); + int zz = Utils.rand((int) z - 1, (int) z + 1); Block block = this.getLevel().getBlock(xx, yy, zz); if (block.getId() == Block.DIRT && block.getDamage() == 0) { up = block.up(); @@ -119,11 +131,18 @@ public boolean canSilkTouch() { @Override public int getFullId() { - return this.getId() << 4; + return this.getId() << Block.DATA_BITS; } @Override public void setDamage(int meta) { + } + @Override + public Item[] getDrops(Item item) { + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; + } + return new Item[]{new ItemBlock(Block.get(BlockID.DIRT))}; } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockGrassPath.java b/src/main/java/cn/nukkit/block/BlockGrassPath.java index e8bde73f525..8409c798abb 100644 --- a/src/main/java/cn/nukkit/block/BlockGrassPath.java +++ b/src/main/java/cn/nukkit/block/BlockGrassPath.java @@ -2,7 +2,7 @@ import cn.nukkit.Player; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemTool; +import cn.nukkit.level.Sound; import cn.nukkit.utils.BlockColor; /** @@ -11,9 +11,6 @@ */ public class BlockGrassPath extends BlockGrass { - public BlockGrassPath() { - } - @Override public int getId() { return GRASS_PATH; @@ -24,29 +21,11 @@ public String getName() { return "Grass Path"; } - @Override - public int getToolType() { - return ItemTool.TYPE_SHOVEL; - } - - @Override - public double getMaxY() { - return this.y + 1; - } - @Override public double getResistance() { return 3.25; } - @Override - public BlockColor getColor() { return BlockColor.DIRT_BLOCK_COLOR; } - - @Override - public boolean canSilkTouch() { - return true; - } - @Override public int onUpdate(int type) { return 0; @@ -55,11 +34,27 @@ public int onUpdate(int type) { @Override public boolean onActivate(Item item, Player player) { if (item.isHoe()) { - item.useOn(this); - this.getLevel().setBlock(this, get(FARMLAND), true); - return true; + Block up = this.up(); + if (up instanceof BlockAir || up instanceof BlockFlowable) { + item.useOn(this); + this.getLevel().setBlock(this, get(FARMLAND), true); + if (player != null) { + player.getLevel().addSound(player, Sound.STEP_GRASS); + } + return true; + } } return false; } + + @Override + public BlockColor getColor() { + return BlockColor.DIRT_BLOCK_COLOR; + } + + @Override + public double getMaxY() { + return this.y + 0.9375; + } } diff --git a/src/main/java/cn/nukkit/block/BlockGravel.java b/src/main/java/cn/nukkit/block/BlockGravel.java index d298404c7d2..df8fab2ce86 100644 --- a/src/main/java/cn/nukkit/block/BlockGravel.java +++ b/src/main/java/cn/nukkit/block/BlockGravel.java @@ -1,21 +1,21 @@ package cn.nukkit.block; +import cn.nukkit.Player; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemFlint; +import cn.nukkit.item.ItemDye; import cn.nukkit.item.ItemTool; - -import java.util.Random; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.level.generator.object.ObjectTallGrass; +import cn.nukkit.level.particle.BoneMealParticle; +import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.Utils; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockGravel extends BlockFallable { - - public BlockGravel() { - } - @Override public int getId() { return GRAVEL; @@ -43,9 +43,9 @@ public String getName() { @Override public Item[] getDrops(Item item) { - if (new Random().nextInt(9) == 0) { + if (Utils.random.nextInt(9) == 0 && !item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { return new Item[]{ - new ItemFlint() + Item.get(Item.FLINT) }; } else { return new Item[]{ @@ -53,9 +53,38 @@ public Item[] getDrops(Item item) { }; } } - + + @Override + public BlockColor getColor() { + return BlockColor.GRAY_BLOCK_COLOR; + } + @Override public boolean canSilkTouch() { return true; } + + @Override + public boolean onActivate(Item item, Player player) { + if (player != null && item.getId() == Item.DYE && item.getDamage() == ItemDye.BONE_MEAL) { + Block up = this.up(); + if (up instanceof BlockWater) { + if (!player.isCreative()) { + item.count--; + } + this.level.addParticle(new BoneMealParticle(this)); + if (up.getDamage() == 0 && up.up() instanceof BlockWater) { + ObjectTallGrass.growSeagrass(this.getLevel(), this); + } + return true; + } + } + + return false; + } + + @Override + public boolean canBeActivated() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockGrindstone.java b/src/main/java/cn/nukkit/block/BlockGrindstone.java new file mode 100644 index 00000000000..e96c1e03870 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockGrindstone.java @@ -0,0 +1,135 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.Faceable; + +public class BlockGrindstone extends BlockTransparentMeta implements Faceable { + + public static final int TYPE_ATTACHMENT_STANDING = 0; + public static final int TYPE_ATTACHMENT_HANGING = 1; + public static final int TYPE_ATTACHMENT_SIDE = 2; + public static final int TYPE_ATTACHMENT_MULTIPLE = 3; + + public BlockGrindstone() { + this(0); + } + + public BlockGrindstone(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Grindstone"; + } + + @Override + public int getId() { + return GRINDSTONE; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public BlockColor getColor() { + return BlockColor.IRON_BLOCK_COLOR; + } + + @Override + public double getHardness() { + return 2; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public BlockFace getBlockFace() { + return BlockFace.fromHorizontalIndex(getDamage() & 0b11); + } + + public void setBlockFace(BlockFace face) { + if (face.getHorizontalIndex() == -1) { + return; + } + setDamage(getDamage() & (DATA_MASK ^ 0b11) | face.getHorizontalIndex()); + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(GRINDSTONE)); + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (block.getId() != AIR && block.canBeReplaced()) { + face = BlockFace.UP; + } + + switch (face) { + case UP: + this.setAttachmentType(TYPE_ATTACHMENT_STANDING); + this.setBlockFace(player.getDirection().getOpposite()); + break; + case DOWN: + this.setAttachmentType(TYPE_ATTACHMENT_HANGING); + this.setBlockFace(player.getDirection().getOpposite()); + break; + default: + this.setBlockFace(face); + this.setAttachmentType(TYPE_ATTACHMENT_SIDE); + } + + if (!this.checkSupport()) { + return false; + } + + return super.place(item, block, target, face, fx, fy, fz, player); + } + + public int getAttachmentType() { + return (getDamage() & 0b1100) >> 2 & 0b11; + } + + public void setAttachmentType(int attachmentType) { + attachmentType = attachmentType & 0b11; + setDamage(getDamage() & (DATA_MASK ^ 0b1100) | (attachmentType << 2)); + } + + private boolean checkSupport() { + switch (this.getAttachmentType()) { + case TYPE_ATTACHMENT_STANDING: + if (down().getId() != AIR) { + return true; + } + break; + case TYPE_ATTACHMENT_HANGING: + if (up().getId() != AIR) { + return true; + } + break; + case TYPE_ATTACHMENT_SIDE: + BlockFace blockFace = getBlockFace(); + if (getSide(blockFace.getOpposite()).getId() != AIR) { + return true; + } + break; + } + + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockHayBale.java b/src/main/java/cn/nukkit/block/BlockHayBale.java index 7bef3ed7b47..726e4a067c1 100644 --- a/src/main/java/cn/nukkit/block/BlockHayBale.java +++ b/src/main/java/cn/nukkit/block/BlockHayBale.java @@ -12,6 +12,16 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockHayBale extends BlockSolidMeta implements Faceable { + + private static final short[] FACES = { + 0, + 0, + 0b1000, + 0b1000, + 0b0100, + 0b0100, + }; + public BlockHayBale() { this(0); } @@ -40,11 +50,6 @@ public double getResistance() { return 2.5; } - @Override - public int getToolType() { - return ItemTool.TYPE_HOE; - } - @Override public int getBurnChance() { return 60; @@ -55,17 +60,14 @@ public int getBurnAbility() { return 20; } + @Override + public int getToolType() { + return ItemTool.TYPE_HOE; + } + @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - int[] faces = new int[]{ - 0, - 0, - 0b1000, - 0b1000, - 0b0100, - 0b0100, - }; - this.setDamage((this.getDamage() & 0x03) | faces[face.getIndex()]); + this.setDamage((this.getDamage() & 0x03) | FACES[face.getIndex()]); this.getLevel().setBlock(block, this, true, true); return true; @@ -78,7 +80,7 @@ public BlockColor getColor() { @Override public BlockFace getBlockFace() { - return BlockFace.fromHorizontalIndex(this.getDamage() & 0x07); + return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); } @Override diff --git a/src/main/java/cn/nukkit/block/BlockHoneyBlock.java b/src/main/java/cn/nukkit/block/BlockHoneyBlock.java new file mode 100644 index 00000000000..2e6058b30c0 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockHoneyBlock.java @@ -0,0 +1,56 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.entity.Entity; +import cn.nukkit.math.Vector3; + +public class BlockHoneyBlock extends BlockSolid { + + @Override + public String getName() { + return "Honey Block"; + } + + @Override + public int getId() { + return HONEY_BLOCK; + } + + @Override + public double getHardness() { + return 0; + } + + @Override + public double getResistance() { + return 0; + } + + @Override + public boolean hasEntityCollision() { + return true; + } + + @Override + public void onEntityCollide(Entity entity) { + if (!entity.onGround && entity.motionY <= 0.08 && !(entity instanceof Player)) { + double ex = Math.abs(x + 0.5D - entity.x); + double ez = Math.abs(z + 0.5D - entity.z); + double width = 0.4375D + (double)(entity.getWidth() / 2.0F); + if (ex + 1.0E-3D > width || ez + 1.0E-3D > width) { + Vector3 motion = entity.getMotion(); + motion.y = -0.05; + if (entity.motionY < -0.13) { + double m = -0.05 / entity.motionY; + motion.x *= m; + motion.z *= m; + } + + if (!entity.getMotion().equals(motion)) { + entity.setMotion(motion); + } + entity.resetFallDistance(); + } + } + } +} diff --git a/src/main/java/cn/nukkit/block/BlockHoneycombBlock.java b/src/main/java/cn/nukkit/block/BlockHoneycombBlock.java new file mode 100644 index 00000000000..7c477911b66 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockHoneycombBlock.java @@ -0,0 +1,37 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockHoneycombBlock extends BlockSolid { + + @Override + public String getName() { + return "Honeycomb Block"; + } + + @Override + public int getId() { + return HONEYCOMB_BLOCK; + } + + @Override + public BlockColor getColor() { + return BlockColor.ORANGE_BLOCK_COLOR; + } + + @Override + public double getHardness() { + return 0.6; + } + + @Override + public double getResistance() { + return 3; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_NONE; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockHopper.java b/src/main/java/cn/nukkit/block/BlockHopper.java index dc58c00cf10..e868251bc46 100644 --- a/src/main/java/cn/nukkit/block/BlockHopper.java +++ b/src/main/java/cn/nukkit/block/BlockHopper.java @@ -5,7 +5,6 @@ import cn.nukkit.blockentity.BlockEntityHopper; import cn.nukkit.inventory.ContainerInventory; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemHopper; import cn.nukkit.item.ItemTool; import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; @@ -56,13 +55,13 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl this.setDamage(facing.getIndex()); - boolean powered = this.level.isBlockPowered(this.getLocation()); + boolean powered = this.level.isBlockPowered(this); if (powered == this.isEnabled()) { this.setEnabled(!powered); } - this.level.setBlock(this, this); + this.getLevel().setBlock(this, this, true, true); CompoundTag nbt = new CompoundTag() .putList(new ListTag<>("Items")) @@ -71,8 +70,8 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl .putInt("y", (int) this.y) .putInt("z", (int) this.z); - BlockEntityHopper hopper = (BlockEntityHopper) BlockEntity.createBlockEntity(BlockEntity.HOPPER, this.level.getChunk(this.getFloorX() >> 4, this.getFloorZ() >> 4), nbt); - return hopper != null; + BlockEntity.createBlockEntity(BlockEntity.HOPPER, this.getChunk(), nbt); + return true; } @Override @@ -80,7 +79,8 @@ public boolean onActivate(Item item, Player player) { BlockEntity blockEntity = this.level.getBlockEntity(this); if (blockEntity instanceof BlockEntityHopper) { - return player.addWindow(((BlockEntityHopper) blockEntity).getInventory()) != -1; + player.addWindow(((BlockEntityHopper) blockEntity).getInventory()); + return true; } return false; @@ -123,11 +123,11 @@ public void setEnabled(boolean enabled) { @Override public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_NORMAL) { - boolean powered = this.level.isBlockPowered(this.getLocation()); + boolean powered = this.level.isBlockPowered(this); if (powered == this.isEnabled()) { this.setEnabled(!powered); - this.level.setBlock(this, this, true, false); + this.level.setBlock((int) this.x, (int) this.y, (int) this.z, BlockLayer.NORMAL, this, false, false, false); // No need to send this to client } return type; @@ -152,7 +152,7 @@ public Item[] getDrops(Item item) { @Override public Item toItem() { - return new ItemHopper(); + return Item.get(Item.HOPPER); } @Override @@ -162,6 +162,16 @@ public boolean canHarvestWithHand() { @Override public BlockFace getBlockFace() { - return BlockFace.fromHorizontalIndex(this.getDamage() & 0x07); + return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean canBePushed() { + return false; // prevent item loss issue with pistons until a working implementation } } diff --git a/src/main/java/cn/nukkit/block/BlockHugeMushroomBrown.java b/src/main/java/cn/nukkit/block/BlockHugeMushroomBrown.java index 3ee1bb5d380..8d0473eb9be 100644 --- a/src/main/java/cn/nukkit/block/BlockHugeMushroomBrown.java +++ b/src/main/java/cn/nukkit/block/BlockHugeMushroomBrown.java @@ -3,8 +3,10 @@ import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemTool; -import cn.nukkit.math.NukkitRandom; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.level.generator.object.mushroom.BigMushroom; import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.Utils; /** * Created by Pub4Game on 28.01.2016. @@ -39,20 +41,12 @@ public double getHardness() { return 0.2; } - @Override - public double getResistance() { - return 1; - } - @Override public Item[] getDrops(Item item) { - if (new NukkitRandom().nextRange(1, 20) == 0) { - return new Item[]{ - new ItemBlock(Block.get(BlockID.BROWN_MUSHROOM)) - }; - } else { - return new Item[0]; + if (item != null && item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; } + return new Item[]{new ItemBlock(Block.get(BROWN_MUSHROOM), 0, Utils.rand() ? Utils.rand(0, 2) : 0)}; } @Override @@ -61,5 +55,13 @@ public boolean canSilkTouch() { } @Override - public BlockColor getColor() { return BlockColor.DIRT_BLOCK_COLOR; } + public BlockColor getColor() { + return BlockColor.WOOD_BLOCK_COLOR; + } + + @Override + public Item toItem() { + int type = this.getDamage() == BigMushroom.STEM ? BigMushroom.ALL_STEM : BigMushroom.ALL_OUTSIDE; + return new ItemBlock(Block.get(this.getId(), type), type); + } } diff --git a/src/main/java/cn/nukkit/block/BlockHugeMushroomRed.java b/src/main/java/cn/nukkit/block/BlockHugeMushroomRed.java index 4b24523a5ad..5fc79d09b4f 100644 --- a/src/main/java/cn/nukkit/block/BlockHugeMushroomRed.java +++ b/src/main/java/cn/nukkit/block/BlockHugeMushroomRed.java @@ -3,8 +3,10 @@ import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemTool; -import cn.nukkit.math.NukkitRandom; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.level.generator.object.mushroom.BigMushroom; import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.Utils; /** * Created by Pub4Game on 28.01.2016. @@ -39,20 +41,12 @@ public double getHardness() { return 0.2; } - @Override - public double getResistance() { - return 1; - } - @Override public Item[] getDrops(Item item) { - if (new NukkitRandom().nextRange(1, 20) == 0) { - return new Item[]{ - new ItemBlock(Block.get(BlockID.RED_MUSHROOM)) - }; - } else { - return new Item[0]; + if (item != null && item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; } + return new Item[]{new ItemBlock(Block.get(RED_MUSHROOM), 0, Utils.rand() ? Utils.rand(0, 2) : 0)}; } @Override @@ -64,4 +58,10 @@ public boolean canSilkTouch() { public BlockColor getColor() { return BlockColor.RED_BLOCK_COLOR; } + + @Override + public Item toItem() { + int type = this.getDamage() == BigMushroom.STEM ? BigMushroom.ALL_STEM : BigMushroom.ALL_OUTSIDE; + return new ItemBlock(Block.get(this.getId(), type), type); + } } diff --git a/src/main/java/cn/nukkit/block/BlockHyphaeCrimson.java b/src/main/java/cn/nukkit/block/BlockHyphaeCrimson.java new file mode 100644 index 00000000000..bff5138dd04 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockHyphaeCrimson.java @@ -0,0 +1,44 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockHyphaeCrimson extends BlockStem { + + public BlockHyphaeCrimson() { + this(0); + } + + public BlockHyphaeCrimson(int meta) { + super(meta); + } + + @Override + public int getId() { + return CRIMSON_HYPHAE; + } + + @Override + public int getStrippedId() { + return STRIPPED_CRIMSON_HYPHAE; + } + + @Override + public String getName() { + return "Crimson Hyphae"; + } + + @Override + public double getHardness() { + return 0.3; // 2 + } + + @Override + public double getResistance() { + return 2; + } + + @Override + public BlockColor getColor() { + return BlockColor.WARPED_HYPHAE_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockHyphaeStrippedCrimson.java b/src/main/java/cn/nukkit/block/BlockHyphaeStrippedCrimson.java new file mode 100644 index 00000000000..0bc86caba82 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockHyphaeStrippedCrimson.java @@ -0,0 +1,34 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockHyphaeStrippedCrimson extends BlockStemStripped { + + public BlockHyphaeStrippedCrimson() { + this(0); + } + + public BlockHyphaeStrippedCrimson(int meta) { + super(meta); + } + + @Override + public int getId() { + return STRIPPED_CRIMSON_HYPHAE; + } + + @Override + public String getName() { + return "Crimson Stripped Hyphae"; + } + + @Override + public double getHardness() { + return 0.3; // 2 + } + + @Override + public BlockColor getColor() { + return BlockColor.CRIMSON_HYPHAE_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockHyphaeStrippedWarped.java b/src/main/java/cn/nukkit/block/BlockHyphaeStrippedWarped.java new file mode 100644 index 00000000000..83d16c54bc3 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockHyphaeStrippedWarped.java @@ -0,0 +1,34 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockHyphaeStrippedWarped extends BlockStemStripped { + + public BlockHyphaeStrippedWarped() { + this(0); + } + + public BlockHyphaeStrippedWarped(int meta) { + super(meta); + } + + @Override + public int getId() { + return STRIPPED_WARPED_HYPHAE; + } + + @Override + public String getName() { + return "Warped Stripped Hyphae"; + } + + @Override + public double getHardness() { + return 0.3; // 2 + } + + @Override + public BlockColor getColor() { + return BlockColor.WARPED_HYPHAE_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockHyphaeWarped.java b/src/main/java/cn/nukkit/block/BlockHyphaeWarped.java new file mode 100644 index 00000000000..e10bde7a5f6 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockHyphaeWarped.java @@ -0,0 +1,43 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockHyphaeWarped extends BlockStem { + + public BlockHyphaeWarped() { + this(0); + } + + public BlockHyphaeWarped(int meta) { + super(meta); + } + + @Override + public int getId() { + return WARPED_HYPHAE; + } + + @Override + public int getStrippedId() { + return STRIPPED_WARPED_HYPHAE; + } + + @Override + public String getName() { + return "Warped Hyphae"; + } + + @Override + public BlockColor getColor() { + return BlockColor.WARPED_HYPHAE_BLOCK_COLOR; + } + + public double getHardness() { + return 2; + } + + @Override + public double getResistance() { + return 2; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockID.java b/src/main/java/cn/nukkit/block/BlockID.java index 2bc85eaa001..4c09f98a76c 100644 --- a/src/main/java/cn/nukkit/block/BlockID.java +++ b/src/main/java/cn/nukkit/block/BlockID.java @@ -1,10 +1,15 @@ package cn.nukkit.block; +/** + * List of block IDs + */ public interface BlockID { + int AIR = 0; int STONE = 1; int GRASS = 2; - int GRASS_BLOCK = 2; + @SuppressWarnings("unused") + int GRASS_BLOCK = GRASS; int DIRT = 3; int COBBLESTONE = 4; int COBBLE = 4; @@ -49,6 +54,7 @@ public interface BlockID { int PISTON = 33; int PISTON_HEAD = 34; int WOOL = 35; + int WHITE_WOOL = 35; int DANDELION = 37; int POPPY = 38; int ROSE = 38; @@ -102,7 +108,6 @@ public interface BlockID { int STONE_PRESSURE_PLATE = 70; int IRON_DOOR_BLOCK = 71; int WOODEN_PRESSURE_PLATE = 72; - int REDSTONE_ORE = 73; int GLOWING_REDSTONE_ORE = 74; int LIT_REDSTONE_ORE = 74; @@ -171,7 +176,6 @@ public interface BlockID { int DRAGON_EGG = 122; int REDSTONE_LAMP = 123; int LIT_REDSTONE_LAMP = 124; - //Note: dropper CAN NOT BE HARVESTED WITH HAND -- canHarvestWithHand method should be overridden FALSE. int DROPPER = 125; int ACTIVATOR_RAIL = 126; int COCOA = 127; @@ -232,7 +236,7 @@ public interface BlockID { int DARK_OAK_WOODEN_STAIRS = 164; int SLIME_BLOCK = 165; int SLIME = 165; - int GLOW_STICK = 166; + //int GLOW_STICK = 166; int IRON_TRAPDOOR = 167; int PRISMARINE = 168; int SEA_LANTERN = 169; @@ -258,6 +262,9 @@ public interface BlockID { int FENCE_GATE_ACACIA = 187; int REPEATING_COMMAND_BLOCK = 188; int CHAIN_COMMAND_BLOCK = 189; + //int HARD_GLASS_PANE = 190; + //int HARD_STAINED_GLASS_PANE = 191; + //int CHEMICAL_HEAT = 192; int SPRUCE_DOOR_BLOCK = 193; int BIRCH_DOOR_BLOCK = 194; int JUNGLE_DOOR_BLOCK = 195; @@ -267,11 +274,11 @@ public interface BlockID { int ITEM_FRAME_BLOCK = 199; int CHORUS_FLOWER = 200; int PURPUR_BLOCK = 201; - + //int COLORED_TORCH_RG = 202; int PURPUR_STAIRS = 203; + //int COLORED_TORCH_BP = 204; int UNDYED_SHULKER_BOX = 205; int END_BRICKS = 206; - //Note: frosted ice CAN NOT BE HARVESTED WITH HAND -- canHarvestWithHand method should be overridden FALSE. int FROSTED_ICE = 207; int ICE_FROSTED = 207; int END_ROD = 208; @@ -283,7 +290,7 @@ public interface BlockID { int BLOCK_NETHER_WART_BLOCK = 214; int RED_NETHER_BRICK = 215; int BONE_BLOCK = 216; - + // int SHULKER_BOX = 218; int PURPLE_GLAZED_TERRACOTTA = 219; int WHITE_GLAZED_TERRACOTTA = 220; @@ -296,6 +303,7 @@ public interface BlockID { int GRAY_GLAZED_TERRACOTTA = 227; int SILVER_GLAZED_TERRACOTTA = 228; int CYAN_GLAZED_TERRACOTTA = 229; + // 230 Chalkboard in Education Edition int BLUE_GLAZED_TERRACOTTA = 231; int BROWN_GLAZED_TERRACOTTA = 232; int GREEN_GLAZED_TERRACOTTA = 233; @@ -303,20 +311,511 @@ public interface BlockID { int BLACK_GLAZED_TERRACOTTA = 235; int CONCRETE = 236; int CONCRETE_POWDER = 237; - int CONCRETEPOWDER = 237; - + //int CHEMISTRY_TABLE = 238; + //int UNDERWATER_TORCH = 239; int CHORUS_PLANT = 240; int STAINED_GLASS = 241; + int CAMERA_BLOCK = 242; int PODZOL = 243; int BEETROOT_BLOCK = 244; int STONECUTTER = 245; int GLOWING_OBSIDIAN = 246; - int NETHER_REACTOR = 247; //Should not be removed + int NETHER_REACTOR = 247; int INFO_UPDATE = 248; int INFO_UPDATE2 = 249; - int PISTON_EXTENSION = 250; - + int MOVING_BLOCK = 250; int OBSERVER = 251; int STRUCTURE_BLOCK = 252; + //int HARD_GLASS = 253; + //int HARD_STAINED_GLASS = 254; + int RESERVED6 = 255; + // + int PRISMARINE_STAIRS = 257; + int DARK_PRISMARINE_STAIRS = 258; + int PRISMARINE_BRICKS_STAIRS = 259; + int STRIPPED_SPRUCE_LOG = 260; + int STRIPPED_BIRCH_LOG = 261; + int STRIPPED_JUNGLE_LOG = 262; + int STRIPPED_ACACIA_LOG = 263; + int STRIPPED_DARK_OAK_LOG = 264; + int STRIPPED_OAK_LOG = 265; + int BLUE_ICE = 266; + // + int SEAGRASS = 385; + int CORAL = 386; + int CORAL_BLOCK = 387; + int CORAL_FAN = 388; + int CORAL_FAN_DEAD = 389; + int CORAL_FAN_HANG = 390; + int CORAL_FAN_HANG2 = 391; + int CORAL_FAN_HANG3 = 392; + int BLOCK_KELP = 393; + int DRIED_KELP_BLOCK = 394; + int ACACIA_BUTTON = 395; + int BIRCH_BUTTON = 396; + int DARK_OAK_BUTTON = 397; + int JUNGLE_BUTTON = 398; + int SPRUCE_BUTTON = 399; + int ACACIA_TRAPDOOR = 400; + int BIRCH_TRAPDOOR = 401; + int DARK_OAK_TRAPDOOR = 402; + int JUNGLE_TRAPDOOR = 403; + int SPRUCE_TRAPDOOR = 404; + int ACACIA_PRESSURE_PLATE = 405; + int BIRCH_PRESSURE_PLATE = 406; + int DARK_OAK_PRESSURE_PLATE = 407; + int JUNGLE_PRESSURE_PLATE = 408; + int SPRUCE_PRESSURE_PLATE = 409; + int CARVED_PUMPKIN = 410; + int SEA_PICKLE = 411; + int CONDUIT = 412; + // + int TURTLE_EGG = 414; + int BUBBLE_COLUMN = 415; + int BARRIER = 416; + int STONE_SLAB3 = 417; + int BAMBOO = 418; + int BAMBOO_SAPLING = 419; + int SCAFFOLDING = 420; + int STONE_SLAB4 = 421; + int DOUBLE_STONE_SLAB3 = 422; + int DOUBLE_STONE_SLAB4 = 423; + int GRANITE_STAIRS = 424; + int DIORITE_STAIRS = 425; + int ANDESITE_STAIRS = 426; + int POLISHED_GRANITE_STAIRS = 427; + int POLISHED_DIORITE_STAIRS = 428; + int POLISHED_ANDESITE_STAIRS = 429; + int MOSSY_STONE_BRICK_STAIRS = 430; + int SMOOTH_RED_SANDSTONE_STAIRS = 431; + int SMOOTH_SANDSTONE_STAIRS = 432; + int END_BRICK_STAIRS = 433; + int MOSSY_COBBLESTONE_STAIRS = 434; + int NORMAL_STONE_STAIRS = 435; + int SPRUCE_STANDING_SIGN = 436; + int SPRUCE_WALL_SIGN = 437; + int SMOOTH_STONE = 438; + int RED_NETHER_BRICK_STAIRS = 439; + int SMOOTH_QUARTZ_STAIRS = 440; + int BIRCH_STANDING_SIGN = 441; + int BIRCH_WALL_SIGN = 442; + int JUNGLE_STANDING_SIGN = 443; + int JUNGLE_WALL_SIGN = 444; + int ACACIA_STANDING_SIGN = 445; + int ACACIA_WALL_SIGN = 446; + int DARK_OAK_STANDING_SIGN = 447; + int DARK_OAK_WALL_SIGN = 448; + int LECTERN = 449; + int GRINDSTONE = 450; + int BLAST_FURNACE = 451; + int STONECUTTER_BLOCK = 452; + int SMOKER = 453; + int LIT_SMOKER = 454; + int CARTOGRAPHY_TABLE = 455; + int FLETCHING_TABLE = 456; + int SMITHING_TABLE = 457; + int BARREL = 458; + int LOOM = 459; + // + int BELL = 461; + int SWEET_BERRY_BUSH = 462; + int LANTERN = 463; + int CAMPFIRE_BLOCK = 464; + int LAVA_CAULDRON = 465; + int JIGSAW = 466; + int WOOD_BARK = 467; + int COMPOSTER = 468; + int LIT_BLAST_FURNACE = 469; + int LIGHT_BLOCK = 470; + int WITHER_ROSE = 471; + int PISTON_HEAD_STICKY = 472; + int BEE_NEST = 473; + int BEEHIVE = 474; + int HONEY_BLOCK = 475; + int HONEYCOMB_BLOCK = 476; + int LODESTONE = 477; + int CRIMSON_ROOTS = 478; + int WARPED_ROOTS = 479; + int CRIMSON_STEM = 480; + int WARPED_STEM = 481; + int WARPED_WART_BLOCK = 482; + int CRIMSON_FUNGUS = 483; + int WARPED_FUNGUS = 484; + int SHROOMLIGHT = 485; + int WEEPING_VINES = 486; + int CRIMSON_NYLIUM = 487; + int WARPED_NYLIUM = 488; + int BASALT = 489; + int POLISHED_BASALT = 490; + int SOUL_SOIL = 491; + int SOUL_FIRE = 492; + int NETHER_SPROUTS_BLOCK = 493; + int TARGET = 494; + int STRIPPED_CRIMSON_STEM = 495; + int STRIPPED_WARPED_STEM = 496; + int CRIMSON_PLANKS = 497; + int WARPED_PLANKS = 498; + int CRIMSON_DOOR_BLOCK = 499; + int WARPED_DOOR_BLOCK = 500; + int CRIMSON_TRAPDOOR = 501; + int WARPED_TRAPDOOR = 502; + // + int CRIMSON_STANDING_SIGN = 505; + int WARPED_STANDING_SIGN = 506; + int CRIMSON_WALL_SIGN = 507; + int WARPED_WALL_SIGN = 508; + int CRIMSON_STAIRS = 509; + int WARPED_STAIRS = 510; + int CRIMSON_FENCE = 511; + int WARPED_FENCE = 512; + int CRIMSON_FENCE_GATE = 513; + int WARPED_FENCE_GATE = 514; + int CRIMSON_BUTTON = 515; + int WARPED_BUTTON = 516; + int CRIMSON_PRESSURE_PLATE = 517; + int WARPED_PRESSURE_PLATE = 518; + int CRIMSON_SLAB = 519; + int WARPED_SLAB = 520; + int CRIMSON_DOUBLE_SLAB = 521; + int WARPED_DOUBLE_SLAB = 522; + int SOUL_TORCH = 523; + int SOUL_LANTERN = 524; + int NETHERITE_BLOCK = 525; + int ANCIENT_DEBRIS = 526; + int RESPAWN_ANCHOR = 527; + int BLACKSTONE = 528; + int POLISHED_BLACKSTONE_BRICKS = 529; + int POLISHED_BLACKSTONE_BRICK_STAIRS = 530; + int BLACKSTONE_STAIRS = 531; + int BLACKSTONE_WALL = 532; + int POLISHED_BLACKSTONE_BRICK_WALL = 533; + int CHISELED_POLISHED_BLACKSTONE = 534; + int CRACKED_POLISHED_BLACKSTONE_BRICKS = 535; + int GILDED_BLACKSTONE = 536; + int BLACKSTONE_SLAB = 537; + int BLACKSTONE_DOUBLE_SLAB = 538; + int POLISHED_BLACKSTONE_BRICK_SLAB = 539; + int POLISHED_BLACKSTONE_BRICK_DOUBLE_SLAB = 540; + int CHAIN_BLOCK = 541; + int TWISTING_VINES = 542; + int NETHER_GOLD_ORE = 543; + int CRYING_OBSIDIAN = 544; + int SOUL_CAMPFIRE_BLOCK = 545; + int POLISHED_BLACKSTONE = 546; + int POLISHED_BLACKSTONE_STAIRS = 547; + int POLISHED_BLACKSTONE_SLAB = 548; + int POLISHED_BLACKSTONE_DOUBLE_SLAB = 549; + int POLISHED_BLACKSTONE_PRESSURE_PLATE = 550; + int POLISHED_BLACKSTONE_BUTTON = 551; + int POLISHED_BLACKSTONE_WALL = 552; + int WARPED_HYPHAE = 553; + int CRIMSON_HYPHAE = 554; + int STRIPPED_CRIMSON_HYPHAE = 555; + int STRIPPED_WARPED_HYPHAE = 556; + int CHISELED_NETHER_BRICKS = 557; + int CRACKED_NETHER_BRICKS = 558; + int QUARTZ_BRICKS = 559; + // + int POWDER_SNOW = 561; + int SCULK_SENSOR = 562; + int POINTED_DRIPSTONE = 563; + // + int COPPER_ORE = 566; + int LIGHTNING_ROD = 567; + int CRAFTER = 568; + int VAULT = 569; + int TRIAL_SPAWNER = 570; + int HEAVY_CORE = 571; + int DRIPSTONE_BLOCK = 572; + int ROOTED_DIRT = 573; + int HANGING_ROOTS = 574; + int MOSS_BLOCK = 575; + int SPORE_BLOSSOM = 576; + int CAVE_VINES = 577; + int BIG_DRIPLEAF = 578; + int AZALEA_LEAVES = 579; + int AZALEA_LEAVES_FLOWERED = 580; + int CALCITE = 581; + int AMETHYST_BLOCK = 582; + int BUDDING_AMETHYST = 583; + int AMETHYST_CLUSTER = 584; + int LARGE_AMETHYST_BUD = 585; + int MEDIUM_AMETHYST_BUD = 586; + int SMALL_AMETHYST_BUD = 587; + int TUFF = 588; + int TINTED_GLASS = 589; + int MOSS_CARPET = 590; + int SMALL_DRIPLEAF = 591; + int AZALEA = 592; + int FLOWERING_AZALEA = 593; + int GLOW_FRAME = 594; + int COPPER_BLOCK = 595; + int EXPOSED_COPPER = 596; + int WEATHERED_COPPER = 597; + int OXIDIZED_COPPER = 598; + int WAXED_COPPER = 599; + int WAXED_EXPOSED_COPPER = 600; + int WAXED_WEATHERED_COPPER = 601; + int CUT_COPPER = 602; + int EXPOSED_CUT_COPPER = 603; + int WEATHERED_CUT_COPPER = 604; + int OXIDIZED_CUT_COPPER = 605; + int WAXED_CUT_COPPER = 606; + int WAXED_EXPOSED_CUT_COPPER = 607; + int WAXED_WEATHERED_CUT_COPPER = 608; + int CUT_COPPER_STAIRS = 609; + int EXPOSED_CUT_COPPER_STAIRS = 610; + int WEATHERED_CUT_COPPER_STAIRS = 611; + int OXIDIZED_CUT_COPPER_STAIRS = 612; + int WAXED_CUT_COPPER_STAIRS = 613; + int WAXED_EXPOSED_CUT_COPPER_STAIRS = 614; + int WAXED_WEATHERED_CUT_COPPER_STAIRS = 615; + int CUT_COPPER_SLAB = 616; + int EXPOSED_CUT_COPPER_SLAB = 617; + int WEATHERED_CUT_COPPER_SLAB = 618; + int OXIDIZED_CUT_COPPER_SLAB = 619; + int WAXED_CUT_COPPER_SLAB = 620; + int WAXED_EXPOSED_CUT_COPPER_SLAB = 621; + int WAXED_WEATHERED_CUT_COPPER_SLAB = 622; + int DOUBLE_CUT_COPPER_SLAB = 623; + int EXPOSED_DOUBLE_CUT_COPPER_SLAB = 624; + int WEATHERED_DOUBLE_CUT_COPPER_SLAB = 625; + int OXIDIZED_DOUBLE_CUT_COPPER_SLAB = 626; + int WAXED_DOUBLE_CUT_COPPER_SLAB = 627; + int WAXED_EXPOSED_DOUBLE_CUT_COPPER_SLAB = 628; + int WAXED_WEATHERED_DOUBLE_CUT_COPPER_SLAB = 629; + int CAVE_VINES_BODY_WITH_BERRIES = 630; + int CAVE_VINES_HEAD_WITH_BERRIES = 631; + int SMOOTH_BASALT = 632; + int DEEPSLATE = 633; + int COBBLED_DEEPSLATE = 634; + int COBBLED_DEEPSLATE_SLAB = 635; + int COBBLED_DEEPSLATE_STAIRS = 636; + int COBBLED_DEEPSLATE_WALL = 637; + int POLISHED_DEEPSLATE = 638; + int POLISHED_DEEPSLATE_SLAB = 639; + int POLISHED_DEEPSLATE_STAIRS = 640; + int POLISHED_DEEPSLATE_WALL = 641; + int DEEPSLATE_TILES = 642; + int DEEPSLATE_TILE_SLAB = 643; + int DEEPSLATE_TILE_STAIRS = 644; + int DEEPSLATE_TILE_WALL = 645; + int DEEPSLATE_BRICKS = 646; + int DEEPSLATE_BRICK_SLAB = 647; + int DEEPSLATE_BRICK_STAIRS = 648; + int DEEPSLATE_BRICK_WALL = 649; + int CHISELED_DEEPSLATE = 650; + int COBBLED_DEEPSLATE_DOUBLE_SLAB = 651; + int POLISHED_DEEPSLATE_DOUBLE_SLAB = 652; + int DEEPSLATE_TILE_DOUBLE_SLAB = 653; + int DEEPSLATE_BRICK_DOUBLE_SLAB = 654; + int DEEPSLATE_LAPIS_ORE = 655; + int DEEPSLATE_IRON_ORE = 656; + int DEEPSLATE_GOLD_ORE = 657; + int DEEPSLATE_REDSTONE_ORE = 658; + int LIT_DEEPSLATE_REDSTONE_ORE = 659; + int DEEPSLATE_DIAMOND_ORE = 660; + int DEEPSLATE_COAL_ORE = 661; + int DEEPSLATE_EMERALD_ORE = 662; + int DEEPSLATE_COPPER_ORE = 663; + int CRACKED_DEEPSLATE_TILES = 664; + int CRACKED_DEEPSLATE_BRICKS = 665; + int GLOW_LICHEN = 666; + int CANDLE = 667; + int WHITE_CANDLE = 668; + int ORANGE_CANDLE = 669; + int MAGENTA_CANDLE = 670; + int LIGHT_BLUE_CANDLE = 671; + int YELLOW_CANDLE = 672; + int LIME_CANDLE = 673; + int PINK_CANDLE = 674; + int GRAY_CANDLE = 675; + int LIGHT_GRAY_CANDLE = 676; + int CYAN_CANDLE = 677; + int PURPLE_CANDLE = 678; + int BLUE_CANDLE = 679; + int BROWN_CANDLE = 680; + int GREEN_CANDLE = 681; + int RED_CANDLE = 682; + int BLACK_CANDLE = 683; + int CANDLE_CAKE = 684; + int WHITE_CANDLE_CAKE = 685; + int ORANGE_CANDLE_CAKE = 686; + int MAGENTA_CANDLE_CAKE = 687; + int LIGHT_BLUE_CANDLE_CAKE = 688; + int YELLOW_CANDLE_CAKE = 689; + int LIME_CANDLE_CAKE = 690; + int PINK_CANDLE_CAKE = 691; + int GRAY_CANDLE_CAKE = 692; + int LIGHT_GRAY_CANDLE_CAKE = 693; + int CYAN_CANDLE_CAKE = 694; + int PURPLE_CANDLE_CAKE = 695; + int BLUE_CANDLE_CAKE = 696; + int BROWN_CANDLE_CAKE = 697; + int GREEN_CANDLE_CAKE = 698; + int RED_CANDLE_CAKE = 699; + int BLACK_CANDLE_CAKE = 700; + int WAXED_OXIDIZED_COPPER = 701; + int WAXED_OXIDIZED_CUT_COPPER = 702; + int WAXED_OXIDIZED_CUT_COPPER_STAIRS = 703; + int WAXED_OXIDIZED_CUT_COPPER_SLAB = 704; + int WAXED_OXIDIZED_DOUBLE_CUT_COPPER_SLAB = 705; + int RAW_IRON_BLOCK = 706; + int RAW_COPPER_BLOCK = 707; + int RAW_GOLD_BLOCK = 708; + int INFESTED_DEEPSLATE = 709; + // + int SCULK = 713; + int SCULK_VEIN = 714; + int SCULK_CATALYST = 715; + int SCULK_SHRIEKER = 716; + // + int REINFORCED_DEEPSLATE = 721; + // + int FROG_SPAWN = 723; + int PEARLESCENT_FROGLIGHT = 724; + int VERDANT_FROGLIGHT = 725; + int OCHRE_FROGLIGHT = 726; + int MANGROVE_LEAVES = 727; + int MUD = 728; + int MANGROVE_PROPAGULE = 729; + int MUD_BRICKS = 730; + int PACKED_MUD = 732; + int MUD_BRICK_SLAB = 733; + int MUD_BRICK_DOUBLE_SLAB = 734; + int MUD_BRICK_STAIRS = 735; + int MUD_BRICK_WALL = 736; + int MANGROVE_ROOTS = 737; + int MUDDY_MANGROVE_ROOTS = 738; + int MANGROVE_LOG = 739; + int STRIPPED_MANGROVE_LOG = 740; + int MANGROVE_PLANKS = 741; + int MANGROVE_BUTTON = 742; + int MANGROVE_STAIRS = 743; + int MANGROVE_SLAB = 744; + int MANGROVE_PRESSURE_PLATE = 745; + int MANGROVE_FENCE = 746; + int MANGROVE_FENCE_GATE = 747; + int MANGROVE_DOOR = 748; + int MANGROVE_STANDING_SIGN = 749; + int MANGROVE_WALL_SIGN = 750; + int MANGROVE_TRAPDOOR = 751; + int MANGROVE_WOOD = 752; + int STRIPPED_MANGROVE_WOOD = 753; + int MANGROVE_DOUBLE_SLAB = 754; + int OAK_HANGING_SIGN = 755; + int SPRUCE_HANGING_SIGN = 756; + int BIRCH_HANGING_SIGN = 757; + int JUNGLE_HANGING_SIGN = 758; + int ACACIA_HANGING_SIGN = 759; + int DARK_OAK_HANGING_SIGN = 760; + int CRIMSON_HANGING_SIGN = 761; + int WARPED_HANGING_SIGN = 762; + int MANGROVE_HANGING_SIGN = 763; + int BAMBOO_MOSAIC = 764; + int BAMBOO_PLANKS = 765; + int BAMBOO_BUTTON = 766; + int BAMBOO_STAIRS = 767; + int BAMBOO_SLAB = 768; + int BAMBOO_PRESSURE_PLATE = 769; + int BAMBOO_FENCE = 770; + int BAMBOO_FENCE_GATE = 771; + int BAMBOO_DOOR = 772; + int BAMBOO_STANDING_SIGN = 773; + int BAMBOO_WALL_SIGN = 774; + int BAMBOO_TRAPDOOR = 775; + int BAMBOO_DOUBLE_SLAB = 776; + int BAMBOO_HANGING_SIGN = 777; + int BAMBOO_MOSAIC_STAIRS = 778; + int BAMBOO_MOSAIC_SLAB = 779; + int BAMBOO_MOSAIC_DOUBLE_SLAB = 780; + int CHISELED_BOOKSHELF = 781; + int BAMBOO_BLOCK = 782; + int STRIPPED_BAMBOO_BLOCK = 783; + int SUSPICIOUS_SAND = 784; + int CHERRY_BUTTON = 785; + int CHERRY_DOOR = 786; + int CHERRY_FENCE = 787; + int CHERRY_FENCE_GATE = 788; + int CHERRY_HANGING_SIGN = 789; + int STRIPPED_CHERRY_LOG = 790; + int CHERRY_LOG = 791; + int CHERRY_PLANKS = 792; + int CHERRY_PRESSURE_PLATE = 793; + int CHERRY_SLAB = 794; + int CHERRY_DOUBLE_SLAB = 795; + int CHERRY_STAIRS = 796; + int CHERRY_STANDING_SIGN = 797; + int CHERRY_TRAPDOOR = 798; + int CHERRY_WALL_SIGN = 799; + int STRIPPED_CHERRY_WOOD = 800; + int CHERRY_WOOD = 801; + int CHERRY_SAPLING = 802; + int CHERRY_LEAVES = 803; + int PINK_PETALS = 804; + int DECORATED_POT = 806; + int TORCHFLOWER_CROP = 822; + int TORCHFLOWER = 823; + int SUSPICIOUS_GRAVEL = 828; + int PITCHER_CROP = 829; + int CALIBRATED_SCULK_SENSOR = 835; + int SNIFFER_EGG = 851; + int PITCHER_PLANT = 867; + int TUFF_SLAB = 999; + int TUFF_DOUBLE_SLAB = 1000; + int TUFF_STAIRS = 1001; + int TUFF_WALL = 1002; + int POLISHED_TUFF = 1003; + int POLISHED_TUFF_SLAB = 1004; + int POLISHED_TUFF_DOUBLE_SLAB = 1005; + int POLISHED_TUFF_STAIRS = 1006; + int POLISHED_TUFF_WALL = 1007; + int CHISELED_TUFF = 1008; + int TUFF_BRICKS = 1009; + int TUFF_BRICK_SLAB = 1010; + int TUFF_BRICK_DOUBLE_SLAB = 1011; + int TUFF_BRICK_STAIRS = 1012; + int TUFF_BRICK_WALL = 1013; + int CHISELED_TUFF_BRICKS = 1014; + int CHISELED_COPPER = 1015; + int EXPOSED_CHISELED_COPPER = 1016; + int WEATHERED_CHISELED_COPPER = 1017; + int OXIDIZED_CHISELED_COPPER = 1018; + int WAXED_CHISELED_COPPER = 1019; + int WAXED_EXPOSED_CHISELED_COPPER = 1020; + int WAXED_OXIDIZED_CHISELED_COPPER = 1021; + int WAXED_WEATHERED_CHISELED_COPPER = 1022; + int COPPER_GRATE = 1023; + int EXPOSED_COPPER_GRATE = 1024; + int WEATHERED_COPPER_GRATE = 1025; + int OXIDIZED_COPPER_GRATE = 1026; + int WAXED_COPPER_GRATE = 1027; + int WAXED_EXPOSED_COPPER_GRATE = 1028; + int WAXED_WEATHERED_COPPER_GRATE = 1029; + int WAXED_OXIDIZED_COPPER_GRATE = 1030; + int COPPER_BULB = 1031; + int EXPOSED_COPPER_BULB = 1032; + int WEATHERED_COPPER_BULB = 1033; + int OXIDIZED_COPPER_BULB = 1034; + int WAXED_COPPER_BULB = 1035; + int WAXED_EXPOSED_COPPER_BULB = 1036; + int WAXED_WEATHERED_COPPER_BULB = 1037; + int WAXED_OXIDIZED_COPPER_BULB = 1038; + int COPPER_DOOR = 1039; + int EXPOSED_COPPER_DOOR = 1040; + int WEATHERED_COPPER_DOOR = 1041; + int OXIDIZED_COPPER_DOOR = 1042; + int WAXED_COPPER_DOOR = 1043; + int WAXED_EXPOSED_COPPER_DOOR = 1044; + int WAXED_WEATHERED_COPPER_DOOR = 1045; + int WAXED_OXIDIZED_COPPER_DOOR = 1046; + int COPPER_TRAPDOOR = 1047; + int EXPOSED_COPPER_TRAPDOOR = 1048; + int WEATHERED_COPPER_TRAPDOOR = 1049; + int OXIDIZED_COPPER_TRAPDOOR = 1050; + int WAXED_COPPER_TRAPDOOR = 1051; + int WAXED_EXPOSED_COPPER_TRAPDOOR = 1052; + int WAXED_WEATHERED_COPPER_TRAPDOOR = 1053; + int WAXED_OXIDIZED_COPPER_TRAPDOOR = 1054; } diff --git a/src/main/java/cn/nukkit/block/BlockIce.java b/src/main/java/cn/nukkit/block/BlockIce.java index fe039468082..3bf6a2672d2 100644 --- a/src/main/java/cn/nukkit/block/BlockIce.java +++ b/src/main/java/cn/nukkit/block/BlockIce.java @@ -8,14 +8,11 @@ import cn.nukkit.utils.BlockColor; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockIce extends BlockTransparent { - public BlockIce() { - } - @Override public int getId() { return ICE; @@ -28,7 +25,7 @@ public String getName() { @Override public double getResistance() { - return 2.5; + return 0.5; } @Override @@ -48,11 +45,10 @@ public int getToolType() { @Override public boolean onBreak(Item item) { - if (this.getLevel().getDimension() != Level.DIMENSION_NETHER) { - return this.getLevel().setBlock(this, Block.get(BlockID.WATER), true); - } else { + if (this.getLevel().getDimension() == Level.DIMENSION_NETHER || item.hasEnchantment(Enchantment.ID_SILK_TOUCH) || down().getId() == BlockID.AIR) { return super.onBreak(item); } + return this.getLevel().setBlock(this, Block.get(BlockID.WATER), true); } @Override @@ -82,7 +78,7 @@ public Item[] getDrops(Item item) { public BlockColor getColor() { return BlockColor.ICE_BLOCK_COLOR; } - + @Override public boolean canSilkTouch() { return true; diff --git a/src/main/java/cn/nukkit/block/BlockIceFrosted.java b/src/main/java/cn/nukkit/block/BlockIceFrosted.java new file mode 100644 index 00000000000..45007fd067e --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockIceFrosted.java @@ -0,0 +1,125 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.Utils; + +public class BlockIceFrosted extends BlockTransparentMeta { + + public BlockIceFrosted() { + this(0); + } + + public BlockIceFrosted(int meta) { + super(meta); + } + + @Override + public int getId() { + return ICE_FROSTED; + } + + @Override + public String getName() { + return "Frosted Ice"; + } + + @Override + public double getResistance() { + return 0.5; + } + + @Override + public double getHardness() { + return 0.5; + } + + @Override + public double getFrictionFactor() { + return 0.98; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + boolean success = super.place(item, block, target, face, fx, fy, fz, player); + if (success) { + level.scheduleUpdate(this, Utils.random.nextInt(20, 40)); + } + return success; + } + + @Override + public boolean onBreak(Item item) { + level.setBlock(this, get(WATER), true); + return true; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_SCHEDULED) { + int time = level.getTime() % Level.TIME_FULL; + if (((time < 13184 || time > 22800) || this.getLevel().getBlockLightAt((int) this.x, (int) this.y, (int) this.z) >= 12) && (Utils.random.nextInt(3) == 0 || countNeighbors() < 4)) { + slightlyMelt(true); + } else { + level.scheduleUpdate(this, Utils.random.nextInt(20, 40)); + } + } else if (type == Level.BLOCK_UPDATE_NORMAL) { + if (countNeighbors() < 2) { + level.setBlock(this, get(WATER), true); + } + } else if (type == Level.BLOCK_UPDATE_RANDOM) { + int time = level.getTime() % Level.TIME_FULL; + if (((time < 13184 || time > 22800) || this.getLevel().getBlockLightAt((int) this.x, (int) this.y, (int) this.z) >= 12) && (Utils.random.nextInt(3) == 0 || countNeighbors() < 4)) { + slightlyMelt(true); + } + } + return super.onUpdate(type); + } + + @Override + public Item toItem() { + return Item.get(AIR); + } + + @Override + public BlockColor getColor() { + return BlockColor.ICE_BLOCK_COLOR; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + protected void slightlyMelt(boolean isSource) { + int age = getDamage(); + if (age < 3) { + setDamage(age + 1); + level.setBlock(this, this, true); + level.scheduleUpdate(level.getBlock(this), Utils.random.nextInt(20, 40)); + } else { + level.setBlock(this, get(WATER), true); + if (isSource) { + for (BlockFace face : BlockFace.values()) { + Block block = getSide(face); + if (block instanceof BlockIceFrosted) { + ((BlockIceFrosted) block).slightlyMelt(false); + } + } + } + } + } + + private int countNeighbors() { + int neighbors = 0; + for (BlockFace face : BlockFace.values()) { + if (getSide(face).getId() == ICE_FROSTED && ++neighbors >= 4) { + return neighbors; + } + } + return neighbors; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockIcePacked.java b/src/main/java/cn/nukkit/block/BlockIcePacked.java index ae8f9ec26c0..0cb32b1ca62 100644 --- a/src/main/java/cn/nukkit/block/BlockIcePacked.java +++ b/src/main/java/cn/nukkit/block/BlockIcePacked.java @@ -1,17 +1,14 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemTool; +import cn.nukkit.item.enchantment.Enchantment; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockIcePacked extends BlockIce { - public BlockIcePacked() { - } - @Override public int getId() { return PACKED_ICE; @@ -23,29 +20,33 @@ public String getName() { } @Override - public int getToolType() { - return ItemTool.TYPE_PICKAXE; + public double getHardness() { + return 0.5; } @Override - public int onUpdate(int type) { - return 0; //not being melted + public boolean onBreak(Item item) { + return this.getLevel().setBlock(this, Block.get(BlockID.AIR), true); } @Override - public boolean canHarvestWithHand() { - return false; + public Item[] getDrops(Item item) { + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{ + this.toItem() + }; + } + return new Item[0]; } - + @Override - public boolean onBreak(Item item) { - this.getLevel().setBlock(this, Block.get(BlockID.AIR), true); //no water - return true; + public int onUpdate(int type) { + return 0; } @Override - public boolean canSilkTouch() { - return true; + public boolean canHarvestWithHand() { + return false; } @Override diff --git a/src/main/java/cn/nukkit/block/BlockInfestedDeepslate.java b/src/main/java/cn/nukkit/block/BlockInfestedDeepslate.java new file mode 100644 index 00000000000..d17518da376 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockInfestedDeepslate.java @@ -0,0 +1,44 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; + +public class BlockInfestedDeepslate extends BlockDeepslate { + + public BlockInfestedDeepslate() { + this(0); + } + + public BlockInfestedDeepslate(int meta) { + super(meta); + } + + @Override + public int getId() { + return INFESTED_DEEPSLATE; + } + + @Override + public String getName() { + return "Infested Deepslate"; + } + + @Override + public double getHardness() { + return 0; + } + + @Override + public double getResistance() { + return 0.75; + } + + @Override + public Item[] getDrops(Item item) { + return new Item[0]; + } + + @Override + public boolean canSilkTouch() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockInfoUpdate.java b/src/main/java/cn/nukkit/block/BlockInfoUpdate.java new file mode 100644 index 00000000000..163608548ed --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockInfoUpdate.java @@ -0,0 +1,26 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; + +public class BlockInfoUpdate extends BlockSolid { + + @Override + public int getId() { + return INFO_UPDATE; + } + + @Override + public String getName() { + return "Update Game Block"; + } + + @Override + public double getHardness() { + return 0.1; + } + + @Override + public Item[] getDrops(Item item) { + return new Item[0]; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockInfoUpdate2.java b/src/main/java/cn/nukkit/block/BlockInfoUpdate2.java new file mode 100644 index 00000000000..ba62efccc76 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockInfoUpdate2.java @@ -0,0 +1,21 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; + +public class BlockInfoUpdate2 extends BlockSolid { + + @Override + public int getId() { + return INFO_UPDATE2; + } + + @Override + public String getName() { + return "Update Game Block"; + } + + @Override + public Item[] getDrops(Item item) { + return new Item[0]; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockIron.java b/src/main/java/cn/nukkit/block/BlockIron.java index ff825a00591..e59d64f4c33 100644 --- a/src/main/java/cn/nukkit/block/BlockIron.java +++ b/src/main/java/cn/nukkit/block/BlockIron.java @@ -5,15 +5,11 @@ import cn.nukkit.utils.BlockColor; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class BlockIron extends BlockSolid { - - public BlockIron() { - } - @Override public int getId() { return IRON_BLOCK; @@ -21,7 +17,7 @@ public int getId() { @Override public String getName() { - return "Iron Block"; + return "Block of Iron"; } @Override diff --git a/src/main/java/cn/nukkit/block/BlockIronBars.java b/src/main/java/cn/nukkit/block/BlockIronBars.java index 9f80a1d1ca5..a91c61d8216 100644 --- a/src/main/java/cn/nukkit/block/BlockIronBars.java +++ b/src/main/java/cn/nukkit/block/BlockIronBars.java @@ -11,9 +11,6 @@ */ public class BlockIronBars extends BlockThin { - public BlockIronBars() { - } - @Override public String getName() { return "Iron Bars"; @@ -41,12 +38,12 @@ public int getToolType() { @Override public Item toItem() { - return new ItemBlock(this, 0); + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ this.toItem() }; @@ -64,4 +61,9 @@ public BlockColor getColor() { public boolean canHarvestWithHand() { return false; } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } } diff --git a/src/main/java/cn/nukkit/block/BlockItemFrame.java b/src/main/java/cn/nukkit/block/BlockItemFrame.java index 02bcabf585f..785c4c98481 100644 --- a/src/main/java/cn/nukkit/block/BlockItemFrame.java +++ b/src/main/java/cn/nukkit/block/BlockItemFrame.java @@ -4,7 +4,6 @@ import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.blockentity.BlockEntityItemFrame; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemItemFrame; import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; import cn.nukkit.nbt.tag.CompoundTag; @@ -12,16 +11,12 @@ import cn.nukkit.network.protocol.LevelEventPacket; import cn.nukkit.utils.Faceable; -import java.util.concurrent.ThreadLocalRandom; - /** * Created by Pub4Game on 03.07.2016. */ public class BlockItemFrame extends BlockTransparentMeta implements Faceable { - private final static int[] FACING = new int[]{4, 5, 3, 2, 1, 0}; // TODO when 1.13 support arrives, add UP/DOWN facings - private final static int FACING_BITMASK = 0b0111; - private final static int MAP_BIT = 0b1000; + protected final static int[] FACING = {8, 9, 3, 2, 1, 0}; public BlockItemFrame() { this(0); @@ -61,15 +56,21 @@ public boolean canBeActivated() { @Override public boolean onActivate(Item item, Player player) { BlockEntity blockEntity = this.getLevel().getBlockEntity(this); + if (!(blockEntity instanceof BlockEntityItemFrame)) { + return false; + } + BlockEntityItemFrame itemFrame = (BlockEntityItemFrame) blockEntity; + if (itemFrame.getItem() == null) { + return true; + } if (itemFrame.getItem().getId() == Item.AIR) { - Item itemOnFrame = item.clone(); - if (player != null && player.isSurvival()) { - itemOnFrame.setCount(itemOnFrame.getCount() - 1); - player.getInventory().setItemInHand(itemOnFrame); + Item itemToFrame = item.clone(); + if (player != null && !player.isCreative()) { + item.count--; } - itemOnFrame.setCount(1); - itemFrame.setItem(itemOnFrame); + itemToFrame.setCount(1); + itemFrame.setItem(itemToFrame); this.getLevel().addLevelEvent(this, LevelEventPacket.EVENT_SOUND_ITEM_FRAME_ITEM_ADDED); } else { itemFrame.setItemRotation((itemFrame.getItemRotation() + 1) % 8); @@ -80,9 +81,11 @@ public boolean onActivate(Item item, Player player) { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - if (face.getIndex() > 1 && target.isSolid() && (!block.isSolid() || block.canBeReplaced())) { + if (target.isSolid() && (!block.isSolid() || block.canBeReplaced())) { this.setDamage(FACING[face.getIndex()]); - this.getLevel().setBlock(block, this, true, true); + + this.getLevel().setBlock(this, this, true, true); + CompoundTag nbt = new CompoundTag() .putString("id", BlockEntity.ITEM_FRAME) .putInt("x", (int) block.x) @@ -95,10 +98,8 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl nbt.put(aTag.getName(), aTag); } } - BlockEntityItemFrame frame = (BlockEntityItemFrame) BlockEntity.createBlockEntity(BlockEntity.ITEM_FRAME, this.getLevel().getChunk((int) this.x >> 4, (int) this.z >> 4), nbt); - if (frame == null) { - return false; - } + BlockEntity.createBlockEntity(BlockEntity.ITEM_FRAME, this.getChunk(), nbt); + this.getLevel().addLevelEvent(this, LevelEventPacket.EVENT_SOUND_ITEM_FRAME_PLACED); return true; } return false; @@ -111,24 +112,9 @@ public boolean onBreak(Item item) { return true; } - @Override - public Item[] getDrops(Item item) { - BlockEntity blockEntity = this.getLevel().getBlockEntity(this); - BlockEntityItemFrame itemFrame = (BlockEntityItemFrame) blockEntity; - if (itemFrame != null && ThreadLocalRandom.current().nextFloat() <= itemFrame.getItemDropChance()) { - return new Item[]{ - toItem(), itemFrame.getItem().clone() - }; - } else { - return new Item[]{ - toItem() - }; - } - } - @Override public Item toItem() { - return new ItemItemFrame(); + return Item.get(Item.ITEM_FRAME); } @Override @@ -153,18 +139,26 @@ public int getComparatorInputOverride() { } public BlockFace getFacing() { - switch (this.getDamage() & FACING_BITMASK) { + switch (this.getDamage()) { case 0: + case 4: return BlockFace.WEST; case 1: + case 5: return BlockFace.EAST; case 2: + case 6: return BlockFace.NORTH; case 3: + case 7: return BlockFace.SOUTH; + case 8: + return BlockFace.UP; + case 9: + return BlockFace.DOWN; } - return null; + return BlockFace.UP; } @Override @@ -172,13 +166,28 @@ public double getHardness() { return 0.25; } + @Override + public boolean isSolid() { + return false; + } + + @Override + public boolean breakWhenPushed() { + return true; + } + @Override public BlockFace getBlockFace() { return this.getFacing().getOpposite(); } @Override - public boolean isSolid() { - return false; + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean canBePushed() { + return false; // prevent item loss issue with pistons until a working implementation } } diff --git a/src/main/java/cn/nukkit/block/BlockItemFrameGlow.java b/src/main/java/cn/nukkit/block/BlockItemFrameGlow.java new file mode 100644 index 00000000000..f3d290ffc19 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockItemFrameGlow.java @@ -0,0 +1,62 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.blockentity.BlockEntity; +import cn.nukkit.item.Item; +import cn.nukkit.math.BlockFace; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.Tag; +import cn.nukkit.network.protocol.LevelEventPacket; + +public class BlockItemFrameGlow extends BlockItemFrame { + + public BlockItemFrameGlow() { + this(0); + } + + public BlockItemFrameGlow(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Glow Item Frame"; + } + + @Override + public int getId() { + return GLOW_FRAME; + } + + @Override + public Item toItem() { + return Item.get(Item.GLOW_ITEM_FRAME); + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (target.isSolid() && (!block.isSolid() || block.canBeReplaced())) { + this.setDamage(FACING[face.getIndex()]); + + this.getLevel().setBlock(this, this, true, true); + + CompoundTag nbt = new CompoundTag() + .putString("id", BlockEntity.GLOW_ITEM_FRAME) + .putInt("x", (int) block.x) + .putInt("y", (int) block.y) + .putInt("z", (int) block.z) + .putByte("ItemRotation", 0) + .putFloat("ItemDropChance", 1.0f); + if (item.hasCustomBlockData()) { + for (Tag aTag : item.getCustomBlockData().getAllTags()) { + nbt.put(aTag.getName(), aTag); + } + } + BlockEntity.createBlockEntity(BlockEntity.GLOW_ITEM_FRAME, this.getChunk(), nbt); + this.getLevel().addLevelEvent(this, LevelEventPacket.EVENT_SOUND_ITEM_FRAME_PLACED); + return true; + } + return false; + } +} + diff --git a/src/main/java/cn/nukkit/block/BlockJigsaw.java b/src/main/java/cn/nukkit/block/BlockJigsaw.java new file mode 100644 index 00000000000..df68ee485bb --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockJigsaw.java @@ -0,0 +1,79 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.Faceable; + +public class BlockJigsaw extends BlockSolidMeta implements Faceable { + + public BlockJigsaw() { + this(0); + } + + public BlockJigsaw(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Jigsaw"; + } + + @Override + public int getId() { + return JIGSAW; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public double getResistance() { + return 18000000; + } + + @Override + public double getHardness() { + return -1; + } + + @Override + public boolean isBreakable(Item item) { + return false; + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + public BlockFace getBlockFace() { + return BlockFace.fromIndex(getDamage()); + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (Math.abs(player.x - this.x) < 2 && Math.abs(player.z - this.z) < 2) { + double y = player.y + player.getEyeHeight(); + if (y - this.y > 2) { + this.setDamage(BlockFace.UP.getIndex()); + } else if (this.y - y > 0) { + this.setDamage(BlockFace.DOWN.getIndex()); + } else { + this.setDamage(player.getHorizontalFacing().getOpposite().getIndex()); + } + } else { + this.setDamage(player.getHorizontalFacing().getOpposite().getIndex()); + } + return super.place(item, block, target, face, fx, fy, fz, player); + } + + @Override + public Item[] getDrops(Item item) { + return new Item[0]; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockJukebox.java b/src/main/java/cn/nukkit/block/BlockJukebox.java index c0efcac6220..9fadda9c14c 100644 --- a/src/main/java/cn/nukkit/block/BlockJukebox.java +++ b/src/main/java/cn/nukkit/block/BlockJukebox.java @@ -6,9 +6,11 @@ import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemRecord; +import cn.nukkit.item.ItemTool; import cn.nukkit.math.BlockFace; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.ListTag; +import cn.nukkit.network.protocol.TextPacket; import cn.nukkit.utils.BlockColor; /** @@ -16,9 +18,6 @@ */ public class BlockJukebox extends BlockSolid { - public BlockJukebox() { - } - @Override public String getName() { return "Jukebox"; @@ -29,6 +28,21 @@ public int getId() { return JUKEBOX; } + @Override + public double getHardness() { + return 2; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_AXE; + } + @Override public boolean canBeActivated() { return true; @@ -36,14 +50,14 @@ public boolean canBeActivated() { @Override public Item toItem() { - return new ItemBlock(this, 0); + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override public boolean onActivate(Item item, Player player) { BlockEntity blockEntity = this.getLevel().getBlockEntity(this); if (!(blockEntity instanceof BlockEntityJukebox)) { - blockEntity = this.createBlockEntity(); + return false; } BlockEntityJukebox jukebox = (BlockEntityJukebox) blockEntity; @@ -52,7 +66,18 @@ public boolean onActivate(Item item, Player player) { } else if (item instanceof ItemRecord) { jukebox.setRecordItem(item); jukebox.play(); - player.getInventory().decreaseCount(player.getInventory().getHeldItemIndex()); + + if (player != null) { + TextPacket pk = new TextPacket(); + pk.type = TextPacket.TYPE_JUKEBOX_POPUP; + pk.message = "%record.nowPlaying"; + pk.parameters = new String[]{((ItemRecord) item).getDiscName()}; + pk.isLocalized = true; + player.dataPacket(pk); + + item.count--; + return true; + } } return false; @@ -61,26 +86,27 @@ public boolean onActivate(Item item, Player player) { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { if (super.place(item, block, target, face, fx, fy, fz, player)) { - createBlockEntity(); + CompoundTag nbt = new CompoundTag() + .putList(new ListTag<>("Items")) + .putString("id", BlockEntity.JUKEBOX) + .putInt("x", getFloorX()) + .putInt("y", getFloorY()) + .putInt("z", getFloorZ()); + + BlockEntity.createBlockEntity(BlockEntity.JUKEBOX, this.getChunk(), nbt); return true; } return false; } - private BlockEntity createBlockEntity() { - CompoundTag nbt = new CompoundTag() - .putList(new ListTag<>("Items")) - .putString("id", BlockEntity.JUKEBOX) - .putInt("x", getFloorX()) - .putInt("y", getFloorY()) - .putInt("z", getFloorZ()); - - return BlockEntity.createBlockEntity(BlockEntity.JUKEBOX, this.level.getChunk(getFloorX() >> 4, getFloorZ() >> 4), nbt); + @Override + public BlockColor getColor() { + return BlockColor.WOOD_BLOCK_COLOR; } @Override - public BlockColor getColor() { - return BlockColor.DIRT_BLOCK_COLOR; + public boolean canBePushed() { + return false; } } diff --git a/src/main/java/cn/nukkit/block/BlockJungleSignStanding.java b/src/main/java/cn/nukkit/block/BlockJungleSignStanding.java new file mode 100644 index 00000000000..e9d9b5d4a5e --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockJungleSignStanding.java @@ -0,0 +1,40 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; + +public class BlockJungleSignStanding extends BlockSignPost { + + public BlockJungleSignStanding() { + this(0); + } + + public BlockJungleSignStanding(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Jungle Sign Post"; + } + + @Override + public int getId() { + return JUNGLE_STANDING_SIGN; + } + + @Override + public Item toItem() { + return Item.get(ItemID.JUNGLE_SIGN); + } + + @Override + protected int getPostId() { + return JUNGLE_STANDING_SIGN; + } + + @Override + protected int getWallId() { + return JUNGLE_WALL_SIGN; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockJungleWallSign.java b/src/main/java/cn/nukkit/block/BlockJungleWallSign.java new file mode 100644 index 00000000000..9b21a0912fb --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockJungleWallSign.java @@ -0,0 +1,40 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; + +public class BlockJungleWallSign extends BlockWallSign { + + public BlockJungleWallSign() { + this(0); + } + + public BlockJungleWallSign(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Jungle Wall Sign"; + } + + @Override + public int getId() { + return JUNGLE_WALL_SIGN; + } + + @Override + public Item toItem() { + return Item.get(ItemID.JUNGLE_SIGN); + } + + @Override + protected int getPostId() { + return JUNGLE_STANDING_SIGN; + } + + @Override + protected int getWallId() { + return JUNGLE_WALL_SIGN; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockKelp.java b/src/main/java/cn/nukkit/block/BlockKelp.java new file mode 100644 index 00000000000..13411b8a321 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockKelp.java @@ -0,0 +1,254 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.Server; +import cn.nukkit.event.block.BlockGrowEvent; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemDye; +import cn.nukkit.item.ItemID; +import cn.nukkit.level.Level; +import cn.nukkit.level.format.anvil.Anvil; +import cn.nukkit.level.particle.BoneMealParticle; +import cn.nukkit.math.AxisAlignedBB; +import cn.nukkit.math.BlockFace; +import cn.nukkit.math.MathHelper; +import cn.nukkit.utils.Utils; + +import java.util.concurrent.ThreadLocalRandom; + +public class BlockKelp extends BlockFlowable { + + public BlockKelp() { + this(0); + } + + public BlockKelp(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Kelp"; + } + + @Override + public int getId() { + return BLOCK_KELP; + } + + public double getHardness() { + return 0; + } + + public double getResistance() { + return 0; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.FLOW_INTO_BLOCK; + } + + @Override + public boolean canBeFlowedInto() { + return level == null || !(level.getProvider() instanceof Anvil); + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (level != null && level.getProvider() instanceof Anvil) { + Block down; + if (!((block instanceof BlockWater && (block.getDamage() == 0 || block.getDamage() >= 8)) || block instanceof BlockBubbleColumn) || ((down = this.down()).getId() != this.getId() && down.isTransparent())) { + return false; + } + // 15 is the highest supported meta value + // Meta 0 does not grow to not overgrow previously generated kelp + this.setDamage(Utils.rand(1, 15)); + return this.getLevel().setBlock(this, this, true, true); + } + + + Block down = this.down(); + Block layer1Block = block.getLevelBlock(BlockLayer.WATERLOGGED); + int waterDamage; + if ((down.getId() == BLOCK_KELP || down.isSolid()) && down.getId() != MAGMA && down.getId() != ICE && down.getId() != SOUL_SAND && + (layer1Block instanceof BlockWater && ((waterDamage = (block.getDamage())) == 0 || waterDamage == 8)) + ) { + if (waterDamage == 8) { + this.getLevel().setBlock(this, BlockLayer.WATERLOGGED, Block.get(WATER), true, false); + } + + if (down.getId() == BLOCK_KELP && down.getDamage() != 24) { + down.setDamage(24); + this.getLevel().setBlock(down, down, true, true); + } + + // Placing it by hand gives it a random age value between 0 and 24 + // Meta 0 does not grow to not overgrow previously generated kelp + this.setDamage(Utils.rand(1, 24)); + this.getLevel().setBlock(this, this, true, true); + return true; + } + return false; + } + + @Override + public int onUpdate(int type) { + if (level != null && level.getProvider() instanceof Anvil) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + Block down = this.down(); + if (down.getId() != this.getId() && down.isTransparent()) { + this.getLevel().useBreakOn(this); + } + } else if (type == Level.BLOCK_UPDATE_RANDOM) { + // Ignore meta value 0 to not overgrow previously generated kelp + if (this.getDamage() > 0 && ThreadLocalRandom.current().nextInt(100) < 14) { // 14% chance to grow + if (this.getDamage() < 15) { + Block up = up(); + if (up instanceof BlockWater && up.getDamage() == 0) { + Block grown = Block.get(BLOCK_KELP, this.getDamage() + 1); + BlockGrowEvent ev = new BlockGrowEvent(this, grown); + Server.getInstance().getPluginManager().callEvent(ev); + if (!ev.isCancelled()) { + this.level.setBlock((int) this.x, (int) this.y, (int) this.z, BlockLayer.NORMAL, this, false, false, false); // No need to send this to client + this.getLevel().setBlock(up, ev.getNewState(), true, true); + } + } + } + } + } + return type; + } + + + if (type == Level.BLOCK_UPDATE_NORMAL) { + Block blockLayer1 = this.getLevelBlock(BlockLayer.WATERLOGGED); + int waterDamage = 0; + if (!(blockLayer1 instanceof BlockIceFrosted) && + (!(blockLayer1 instanceof BlockWater) || ((waterDamage = blockLayer1.getDamage()) != 0 && waterDamage != 8))) { + this.getLevel().useBreakOn(this); + return type; + } + + Block down = this.down(); + if ((!down.isSolid() && down.getId() != BLOCK_KELP) || down.getId() == MAGMA || down.getId() == ICE || down.getId() == SOUL_SAND) { + this.getLevel().useBreakOn(this); + return type; + } + + if (waterDamage == 8) { + this.getLevel().setBlock(this, BlockLayer.WATERLOGGED, Block.get(WATER), true, false); + } + return type; + } else if (type == Level.BLOCK_UPDATE_RANDOM) { + // Ignore meta value 0 to not overgrow previously generated + if (this.getDamage() > 0 && ThreadLocalRandom.current().nextInt(100) < 14) { // 14% chance to grow + this.grow(); + } + return type; + } + return super.onUpdate(type); + } + + public boolean grow() { + int age = MathHelper.clamp(this.getDamage(), 0, 25); + if (age < 25) { + Block up = this.up(); + if (up instanceof BlockWater && (up.getDamage() == 0 || up.getDamage() == 8)) { + Block grown = Block.get(BLOCK_KELP, age + 1); + BlockGrowEvent ev = new BlockGrowEvent(this, grown); + this.level.getServer().getPluginManager().callEvent(ev); + + if (!ev.isCancelled()) { + this.setDamage(25); + this.level.setBlock((int) this.x, (int) this.y, (int) this.z, BlockLayer.NORMAL, this, false, false, false); // No need to send this to client + + this.getLevel().setBlock(up, BlockLayer.WATERLOGGED, Block.get(WATER), true, false); + this.getLevel().setBlock(up, BlockLayer.NORMAL, ev.getNewState(), true, true); + return true; + } + } + } + return false; + } + + @Override + public boolean onBreak(Item item) { + if (level != null && level.getProvider() instanceof Anvil) { + return super.onBreak(item); + } + + + Block down = this.down(); + if (down.getId() == BLOCK_KELP) { + this.getLevel().setBlock(down, Block.get(BLOCK_KELP, ThreadLocalRandom.current().nextInt(25)), true, true); + } + this.getLevel().setBlock(this, Block.get(AIR), true, true); + return true; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (level != null && level.getProvider() instanceof Anvil) { + if (item.getId() == ItemID.DYE && item.getDamage() == ItemDye.BONE_MEAL) { + if (this.grow()) { + if (player != null && !player.isCreative()) { + item.count--; + } + level.addParticle(new BoneMealParticle(this)); + } + return true; + } + return super.onActivate(item, player); + } + + + if (item.getId() != Item.DYE || item.getDamage() != ItemDye.BONE_MEAL) { + return false; + } + int x = (int) this.x; + int z = (int) this.z; + + for (int y = (int) this.y + 1; y < 255; y++) { + int blockIdAbove = this.getLevel().getBlockIdAt(x, y, z); + if (blockIdAbove == BLOCK_KELP) continue; + if (!Block.isWater(blockIdAbove)) { + return false; + } + + int waterData = this.getLevel().getBlockDataAt(x, y, z); + if (waterData == 0 || waterData == 8) { + BlockKelp highestKelp = (BlockKelp) this.getLevel().getBlock(x, y - 1, z); + if (highestKelp.grow()) { + this.level.addParticle(new BoneMealParticle(this)); + + if (player != null && (player.gamemode & 0x01) == 0) { + item.count--; + } + } + } + return true; + } + return false; + } + + @Override + public Item toItem() { + return Item.get(Item.KELP, 0, 1); + } + + @Override + public AxisAlignedBB getBoundingBox() { + return null; + } + + @Override + public boolean breakWhenPushed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockLadder.java b/src/main/java/cn/nukkit/block/BlockLadder.java index 014ac90b437..0862d813a48 100644 --- a/src/main/java/cn/nukkit/block/BlockLadder.java +++ b/src/main/java/cn/nukkit/block/BlockLadder.java @@ -1,10 +1,10 @@ package cn.nukkit.block; import cn.nukkit.Player; +import cn.nukkit.entity.Entity; import cn.nukkit.item.Item; import cn.nukkit.item.ItemTool; import cn.nukkit.level.Level; -import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.math.BlockFace; import cn.nukkit.utils.BlockColor; import cn.nukkit.utils.Faceable; @@ -15,13 +15,23 @@ */ public class BlockLadder extends BlockTransparentMeta implements Faceable { + private static final int[] FACES = { + 0, //never use + 1, //never use + 3, + 2, + 5, + 4 + }; + public BlockLadder() { this(0); } public BlockLadder(int meta) { super(meta); - calculateOffsets(); + + this.calculateOffsets(); } @Override @@ -94,19 +104,13 @@ private void calculateOffsets() { break; default: this.offMinX = 0; - this.offMinZ = 1 ; + this.offMinZ = 1; this.offMaxX = 1; this.offMaxZ = 1; break; } } - @Override - public void setDamage(int meta) { - super.setDamage(meta); - calculateOffsets(); - } - @Override public double getMinX() { return this.x + offMinX; @@ -127,17 +131,12 @@ public double getMaxZ() { return this.z + offMaxZ; } - @Override - protected AxisAlignedBB recalculateCollisionBoundingBox() { - return super.recalculateBoundingBox(); - } - @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { if (!target.isTransparent()) { if (face.getIndex() >= 2 && face.getIndex() <= 5) { this.setDamage(face.getIndex()); - this.getLevel().setBlock(block, this, true, true); + this.getLevel().setBlock(this, this, true, true); return true; } } @@ -147,15 +146,7 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl @Override public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_NORMAL) { - int[] faces = { - 0, //never use - 1, //never use - 3, - 2, - 5, - 4 - }; - if (!this.getSide(BlockFace.fromIndex(faces[this.getDamage()])).isSolid()) { + if (!this.getSide(BlockFace.fromIndex(FACES[this.getDamage()])).isSolid()) { this.getLevel().useBreakOn(this); return Level.BLOCK_UPDATE_NORMAL; } @@ -172,16 +163,31 @@ public int getToolType() { public BlockColor getColor() { return BlockColor.AIR_BLOCK_COLOR; } - + @Override public Item[] getDrops(Item item) { return new Item[]{ - Item.get(Item.LADDER, 0, 1) + Item.get(Item.LADDER) }; } @Override public BlockFace getBlockFace() { - return BlockFace.fromHorizontalIndex(this.getDamage() & 0x07); + return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); + } + + @Override + public void onEntityCollide(Entity entity) { + entity.resetFallDistance(); + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean breakWhenPushed() { + return true; } } diff --git a/src/main/java/cn/nukkit/block/BlockLantern.java b/src/main/java/cn/nukkit/block/BlockLantern.java new file mode 100644 index 00000000000..6f7658f9757 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockLantern.java @@ -0,0 +1,163 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.level.Level; +import cn.nukkit.math.AxisAlignedBB; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.BlockColor; + +public class BlockLantern extends BlockFlowable { + + public BlockLantern() { + this(0); + } + + public BlockLantern(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Lantern"; + } + + @Override + public int getId() { + return LANTERN; + } + + @Override + public int getLightLevel() { + return 15; + } + + @Override + public double getResistance() { + return 3.5; + } + + @Override + public double getHardness() { + return 3.5; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public boolean canPassThrough() { + return false; + } + + @Override + public BlockColor getColor() { + return BlockColor.IRON_BLOCK_COLOR; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(LANTERN)); + } + + @Override + protected AxisAlignedBB recalculateBoundingBox() { + return this; + } + + @Override + public double getMinX() { + return this.x + 0.3125; + } + + @Override + public double getMinZ() { + return this.z + 0.3125; + } + + @Override + public double getMaxX() { + return this.x + 0.6875; + } + + @Override + public double getMaxY() { + return this.y + 0.5; + } + + @Override + public double getMaxZ() { + return this.z + 0.6875; + } + + private boolean isBlockAboveValid() { + Block support = this.up(); + switch (support.getId()) { + case IRON_BARS: + case HOPPER_BLOCK: + case CHAIN_BLOCK: + return true; + default: + if (support instanceof BlockFence || support instanceof BlockGlass || support instanceof BlockGlassPane) { + return true; + } + if (support instanceof BlockTrapdoor) { + return !((BlockTrapdoor) support).isTop() && !((BlockTrapdoor) support).isOpen(); + } + if (support instanceof BlockSlab && (support.getDamage() & 0x08) == 0x00) { + return true; + } + if (support instanceof BlockStairs && (support.getDamage() & 0x04) == 0x00) { + return true; + } + return !support.isTransparent() && support.isSolid() && !support.isPowerSource(); + } + } + + private boolean isBlockUnderValid() { + Block down = this.down(); + return !down.isTransparent() || down.isNarrowSurface() || Block.canStayOnFullSolid(down); + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + boolean isUnderValid = this.isBlockUnderValid(); + boolean hanging = face != BlockFace.UP && this.isBlockAboveValid() && (!isUnderValid || face == BlockFace.DOWN); + if (!isUnderValid && !hanging) { + return false; + } + + if (hanging) { + this.setDamage(1); + } else { + this.setDamage(0); + } + + this.getLevel().setBlock(this, this, true, true); + return true; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + if (this.getDamage() == 0) { + if (!this.isBlockUnderValid()) { + level.useBreakOn(this, null, null, true); + } + } else if (!this.isBlockAboveValid()) { + level.useBreakOn(this, null, null, true); + } + return type; + } + return 0; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockLapis.java b/src/main/java/cn/nukkit/block/BlockLapis.java index a8c0166fdac..a7d24808f66 100644 --- a/src/main/java/cn/nukkit/block/BlockLapis.java +++ b/src/main/java/cn/nukkit/block/BlockLapis.java @@ -5,15 +5,11 @@ import cn.nukkit.utils.BlockColor; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class BlockLapis extends BlockSolid { - - public BlockLapis() { - } - @Override public int getId() { return LAPIS_BLOCK; @@ -59,5 +55,4 @@ public BlockColor getColor() { public boolean canHarvestWithHand() { return false; } - } diff --git a/src/main/java/cn/nukkit/block/BlockLava.java b/src/main/java/cn/nukkit/block/BlockLava.java index fc90be4c510..c495bdc9cbc 100644 --- a/src/main/java/cn/nukkit/block/BlockLava.java +++ b/src/main/java/cn/nukkit/block/BlockLava.java @@ -2,6 +2,7 @@ import cn.nukkit.Player; import cn.nukkit.Server; +import cn.nukkit.entity.BaseEntity; import cn.nukkit.entity.Entity; import cn.nukkit.entity.item.EntityPrimedTNT; import cn.nukkit.event.block.BlockIgniteEvent; @@ -15,12 +16,10 @@ import cn.nukkit.math.Vector3; import cn.nukkit.potion.Effect; import cn.nukkit.utils.BlockColor; - -import java.util.Random; -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockLava extends BlockLiquid { @@ -52,17 +51,22 @@ public String getName() { public void onEntityCollide(Entity entity) { entity.highestPosition -= (entity.highestPosition - entity.y) * 0.5; - EntityCombustByBlockEvent ev = new EntityCombustByBlockEvent(this, entity, 8); - Server.getInstance().getPluginManager().callEvent(ev); - if (!ev.isCancelled() - // Making sure the entity is actually alive and not invulnerable. - && entity.isAlive() - && entity.noDamageTicks == 0) { - entity.setOnFire(ev.getDuration()); - } + if (!entity.fireProof || !entity.isOnFire() || !(entity instanceof BaseEntity)) { // Improve performance + if (!entity.fireProof || !entity.isOnFire()) { + + EntityCombustByBlockEvent ev = new EntityCombustByBlockEvent(this, entity, 8); + Server.getInstance().getPluginManager().callEvent(ev); + if (!ev.isCancelled() + // Making sure the entity is actually alive and not invulnerable + && entity.isAlive() + && entity.noDamageTicks == 0) { + entity.setOnFire(ev.getDuration()); + } + } - if (!entity.hasEffect(Effect.FIRE_RESISTANCE)) { - entity.attack(new EntityDamageByBlockEvent(this, entity, DamageCause.LAVA, 4)); + if (!entity.hasEffect(Effect.FIRE_RESISTANCE)) { + entity.attack(new EntityDamageByBlockEvent(this, entity, DamageCause.LAVA, 4)); + } } super.onEntityCollide(entity); @@ -81,13 +85,11 @@ public int onUpdate(int type) { int result = super.onUpdate(type); if (type == Level.BLOCK_UPDATE_RANDOM && this.level.gameRules.getBoolean(GameRule.DO_FIRE_TICK)) { - Random random = ThreadLocalRandom.current(); - - int i = random.nextInt(3); + int i = Utils.random.nextInt(3); if (i > 0) { for (int k = 0; k < i; ++k) { - Vector3 v = this.add(random.nextInt(3) - 1, 1, random.nextInt(3) - 1); + Vector3 v = this.add(Utils.random.nextInt(3) - 1, 1, Utils.random.nextInt(3) - 1); Block block = this.getLevel().getBlock(v); if (block.getId() == AIR) { @@ -110,7 +112,7 @@ public int onUpdate(int type) { } } else { for (int k = 0; k < 3; ++k) { - Vector3 v = this.add(random.nextInt(3) - 1, 0, random.nextInt(3) - 1); + Vector3 v = this.add(Utils.random.nextInt(3) - 1, 0, Utils.random.nextInt(3) - 1); Block block = this.getLevel().getBlock(v); if (block.up().getId() == AIR && block.getBurnChance() > 0) { @@ -147,9 +149,9 @@ public BlockColor getColor() { @Override public BlockLiquid getBlock(int meta) { - return (BlockLiquid) Block.get(BlockID.LAVA, meta); + return (BlockLiquid) Block.get(LAVA, meta); } - + @Override public int tickRate() { if (this.level.getDimension() == Level.DIMENSION_NETHER) { @@ -167,29 +169,35 @@ public int getFlowDecayPerBlock() { } @Override - protected void checkForHarden(){ + protected void checkForHarden() { Block colliding = null; - for(int side = 1; side < 6; ++side){ //don't check downwards side + for (int side = 1; side < 6; ++side) { //don't check downwards side Block blockSide = this.getSide(BlockFace.fromIndex(side)); - if(blockSide instanceof BlockWater){ + if (blockSide instanceof BlockWater || blockSide.getLevelBlock(BlockLayer.WATERLOGGED) instanceof BlockWater) { colliding = blockSide; break; } + if (blockSide instanceof BlockBlueIce) { + if (down() instanceof BlockSoulSoil) { + liquidCollide(this, Block.get(BlockID.BASALT)); + return; + } + } } - if(colliding != null){ - if(this.getDamage() == 0){ - this.liquidCollide(colliding, Block.get(BlockID.OBSIDIAN)); - }else if(this.getDamage() <= 4){ - this.liquidCollide(colliding, Block.get(BlockID.COBBLESTONE)); + if (colliding != null) { + if (this.getDamage() == 0) { + this.liquidCollide(colliding, Block.get(OBSIDIAN)); + } else if (this.getDamage() <= 4) { + this.liquidCollide(colliding, Block.get(COBBLESTONE)); } } } @Override - protected void flowIntoBlock(Block block, int newFlowDecay){ - if(block instanceof BlockWater){ - ((BlockLiquid) block).liquidCollide(this, Block.get(BlockID.STONE)); - }else{ + protected void flowIntoBlock(Block block, int newFlowDecay) { + if (block instanceof BlockWater) { + ((BlockLiquid) block).liquidCollide(this, Block.get(STONE)); + } else { super.flowIntoBlock(block, newFlowDecay); } } @@ -200,4 +208,53 @@ public void addVelocityToEntity(Entity entity, Vector3 vector) { super.addVelocityToEntity(entity, vector); } } + + @Override + protected boolean[] getOptimalFlowDirections() { + int[] flowCost = { + 1000, + 1000, + 1000, + 1000 + }; + int maxCost = 4 / this.getFlowDecayPerBlock(); + for (int j = 0; j < 4; ++j) { + int x = (int) this.x; + int y = (int) this.y; + int z = (int) this.z; + if (j == 0) { + --x; + } else if (j == 1) { + ++x; + } else if (j == 2) { + --z; + } else { + ++z; + } + Block block = this.level.getBlock(x, y, z); + if (!this.canFlowInto(block)) { + this.flowCostVisited.put(Level.blockHash(x, y, z, this.level.getDimensionData()), BLOCKED); + } else if (this.level.getBlock(x, y - 1, z).canBeFlowedInto()) { + this.flowCostVisited.put(Level.blockHash(x, y, z, this.level.getDimensionData()), CAN_FLOW_DOWN); + flowCost[j] = maxCost = 0; + } else if (maxCost > 0) { + this.flowCostVisited.put(Level.blockHash(x, y, z, this.level.getDimensionData()), CAN_FLOW); + flowCost[j] = this.calculateFlowCost(x, y, z, 1, maxCost, j ^ 0x01, j ^ 0x01); + maxCost = Math.min(maxCost, flowCost[j]); + } + } + this.flowCostVisited.clear(); + double minCost = Double.MAX_VALUE; + for (int i = 0; i < 4; i++) { + double d = flowCost[i]; + if (d < minCost) { + minCost = d; + } + } + boolean[] isOptimalFlowDirection = new boolean[4]; + for (int i = 0; i < 4; ++i) { + isOptimalFlowDirection[i] = (flowCost[i] == minCost); + } + return isOptimalFlowDirection; + } } diff --git a/src/main/java/cn/nukkit/block/BlockLavaStill.java b/src/main/java/cn/nukkit/block/BlockLavaStill.java index c587211d137..6c29fb16c5a 100644 --- a/src/main/java/cn/nukkit/block/BlockLavaStill.java +++ b/src/main/java/cn/nukkit/block/BlockLavaStill.java @@ -1,9 +1,7 @@ package cn.nukkit.block; -import cn.nukkit.level.Level; - /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class BlockLavaStill extends BlockLava { @@ -28,14 +26,6 @@ public String getName() { @Override public BlockLiquid getBlock(int meta) { - return (BlockLiquid) Block.get(BlockID.STILL_LAVA, meta); - } - - @Override - public int onUpdate(int type) { - if (type != Level.BLOCK_UPDATE_SCHEDULED) { - return super.onUpdate(type); - } - return 0; + return (BlockLiquid) Block.get(STILL_LAVA, meta); } } diff --git a/src/main/java/cn/nukkit/block/BlockLayer.java b/src/main/java/cn/nukkit/block/BlockLayer.java new file mode 100644 index 00000000000..8f17f52fb85 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockLayer.java @@ -0,0 +1,6 @@ +package cn.nukkit.block; + +public enum BlockLayer { + NORMAL, + WATERLOGGED +} diff --git a/src/main/java/cn/nukkit/block/BlockLeaves.java b/src/main/java/cn/nukkit/block/BlockLeaves.java index 2185fc3f95a..69b962b1cf3 100644 --- a/src/main/java/cn/nukkit/block/BlockLeaves.java +++ b/src/main/java/cn/nukkit/block/BlockLeaves.java @@ -6,20 +6,21 @@ import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemTool; +import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; import cn.nukkit.utils.BlockColor; import cn.nukkit.utils.Hash; +import cn.nukkit.utils.Utils; import it.unimi.dsi.fastutil.longs.LongArraySet; import it.unimi.dsi.fastutil.longs.LongSet; -import java.util.concurrent.ThreadLocalRandom; - /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class BlockLeaves extends BlockTransparentMeta { + public static final int OAK = 0; public static final int SPRUCE = 1; public static final int BIRCH = 2; @@ -48,15 +49,16 @@ public int getToolType() { return ItemTool.TYPE_HOE; } + private static final String[] NAMES = { + "Oak Leaves", + "Spruce Leaves", + "Birch Leaves", + "Jungle Leaves" + }; + @Override public String getName() { - String[] names = new String[]{ - "Oak Leaves", - "Spruce Leaves", - "Birch Leaves", - "Jungle Leaves" - }; - return names[this.getDamage() & 0x03]; + return NAMES[this.getDamage() & 0x03]; } @Override @@ -71,8 +73,8 @@ public int getBurnAbility() { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - this.setPersistent(true); - this.getLevel().setBlock(this, this, true); + setPersistent(true); + this.getLevel().setBlock(this, this, true, true); return true; } @@ -88,17 +90,20 @@ public Item[] getDrops(Item item) { toItem() }; } else { - if (this.canDropApple() && ThreadLocalRandom.current().nextInt(200) == 0) { + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; + } + if (this.canDropApple() && Utils.random.nextInt(200) == 0) { return new Item[]{ Item.get(Item.APPLE) }; } - if (ThreadLocalRandom.current().nextInt(20) == 0) { - if (ThreadLocalRandom.current().nextBoolean()) { + if (Utils.random.nextInt(20) == 0) { + if (Utils.rand()) { return new Item[]{ - Item.get(Item.STICK, 0, ThreadLocalRandom.current().nextInt(1, 2)) + Item.get(Item.STICK, 0, Utils.random.nextInt(1, 2)) }; - } else if ((this.getDamage() & 0x03) != JUNGLE || ThreadLocalRandom.current().nextInt(20) == 0) { + } else if ((this.getDamage() & 0x03) != JUNGLE || Utils.random.nextInt(20) == 0) { return new Item[]{ this.getSapling() }; @@ -112,16 +117,15 @@ public Item[] getDrops(Item item) { public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_RANDOM && !isPersistent() && !isCheckDecay()) { setCheckDecay(true); - getLevel().setBlock(this, this, false, false); + getLevel().setBlock((int) this.x, (int) this.y, (int) this.z, BlockLayer.NORMAL, this, false, false, false); // No need to send this to client } else if (type == Level.BLOCK_UPDATE_RANDOM && isCheckDecay() && !isPersistent()) { - setDamage(getDamage() & 0x03); - int check = 0; + this.setOnDecayDamage(); LeavesDecayEvent ev = new LeavesDecayEvent(this); Server.getInstance().getPluginManager().callEvent(ev); - if (ev.isCancelled() || findLog(this, new LongArraySet(), 0, check)) { - getLevel().setBlock(this, this, false, false); + if (ev.isCancelled() || findLog(this, new LongArraySet())) { + getLevel().setBlock((int) this.x, (int) this.y, (int) this.z, BlockLayer.NORMAL, this, false, false, false); // No need to send this to client } else { getLevel().useBreakOn(this); return Level.BLOCK_UPDATE_NORMAL; @@ -130,16 +134,20 @@ public int onUpdate(int type) { return 0; } - private Boolean findLog(Block pos, LongSet visited, Integer distance, Integer check) { - return findLog(pos, visited, distance, check, null); + protected void setOnDecayDamage() { + setDamage(getDamage() & 0x03); } - private Boolean findLog(Block pos, LongSet visited, Integer distance, Integer check, BlockFace fromSide) { + private boolean findLog(Block pos, LongSet visited) { + return findLog(pos, visited, 0, 0, null); + } + + private boolean findLog(Block pos, LongSet visited, Integer distance, Integer check, BlockFace fromSide) { ++check; long index = Hash.hashBlock((int) pos.x, (int) pos.y, (int) pos.z); if (visited.contains(index)) return false; if (pos.getId() == WOOD || pos.getId() == WOOD2) return true; - if ((pos.getId() == LEAVES || pos.getId() == LEAVES2) && distance <= 4) { + if ((pos.getId() == LEAVES || pos.getId() == LEAVES2) && distance < 6) { visited.add(index); int down = pos.down().getId(); if (down == WOOD || down == WOOD2) { @@ -198,7 +206,7 @@ public void setCheckDecay(boolean checkDecay) { if (checkDecay) { this.setDamage(this.getDamage() | 0x08); } else { - this.setDamage(this.getDamage() & ~0x08); + this.setDamage(this.getDamage() & -9); } } @@ -210,7 +218,7 @@ public void setPersistent(boolean persistent) { if (persistent) { this.setDamage(this.getDamage() | 0x04); } else { - this.setDamage(this.getDamage() & ~0x04); + this.setDamage(this.getDamage() & -5); } } @@ -231,4 +239,14 @@ protected boolean canDropApple() { protected Item getSapling() { return Item.get(BlockID.SAPLING, this.getDamage() & 0x03); } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockLeaves2.java b/src/main/java/cn/nukkit/block/BlockLeaves2.java index 4d95cea3578..543773a855d 100644 --- a/src/main/java/cn/nukkit/block/BlockLeaves2.java +++ b/src/main/java/cn/nukkit/block/BlockLeaves2.java @@ -4,12 +4,18 @@ /** * Created on 2015/12/1 by xtypr. - * Package cn.nukkit.block in project Nukkit . + * Package cn.nukkit.block in project Nukkit. */ public class BlockLeaves2 extends BlockLeaves { + public static final int ACACIA = 0; public static final int DARK_OAK = 1; + private static final String[] NAMES = { + "Acacia Leaves", + "Dark Oak Leaves" + }; + public BlockLeaves2() { this(0); } @@ -19,11 +25,7 @@ public BlockLeaves2(int meta) { } public String getName() { - String[] names = new String[]{ - "Acacia Leaves", - "Dark Oak Leaves" - }; - return names[this.getDamage() & 0x01]; + return NAMES[this.getDamage() & 0x01]; } @Override @@ -33,7 +35,7 @@ public int getId() { @Override protected boolean canDropApple() { - return (this.getDamage() & 0x01) != 0; + return (this.getDamage() & 0x01) == DARK_OAK; } @Override diff --git a/src/main/java/cn/nukkit/block/BlockLeavesMangrove.java b/src/main/java/cn/nukkit/block/BlockLeavesMangrove.java new file mode 100644 index 00000000000..c053a9b1672 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockLeavesMangrove.java @@ -0,0 +1,69 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.math.BlockFace; + +public class BlockLeavesMangrove extends BlockLeaves { + + public BlockLeavesMangrove() { + this(0); + } + + public BlockLeavesMangrove(int meta) { + super(meta); + } + + @Override + public int getId() { + return MANGROVE_LEAVES; + } + + @Override + public String getName() { + return "Mangrove Leaves"; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + this.setPersistent(true); + return super.place(item, block, target, face, fx, fy, fz, player); + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + protected void setOnDecayDamage() { + this.setCheckDecay(false); + } + + @Override + protected boolean canDropApple() { + return false; + } + + @Override + public boolean isPersistent() { + return (this.getDamage() & 2) >>> 1 == 1; + } + + @Override + public void setPersistent(boolean persistent) { + int value = (persistent ? 1 : 0) << 1; + this.setDamage(this.getDamage() & ~1 | (value & 2)); + } + + @Override + public boolean isCheckDecay() { + return (this.getDamage() & 1) == 1; + } + + @Override + public void setCheckDecay(boolean updateBit) { + this.setDamage(this.getDamage() & ~1 | ((updateBit ? 1 : 0) & 1)); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockLectern.java b/src/main/java/cn/nukkit/block/BlockLectern.java new file mode 100644 index 00000000000..a5c6e1f8246 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockLectern.java @@ -0,0 +1,170 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.blockentity.BlockEntity; +import cn.nukkit.blockentity.BlockEntityLectern; +import cn.nukkit.inventory.InventoryType; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; +import cn.nukkit.item.ItemTool; +import cn.nukkit.math.BlockFace; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.network.protocol.ContainerOpenPacket; +import cn.nukkit.network.protocol.LevelSoundEventPacket; +import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.Faceable; + +public class BlockLectern extends BlockTransparentMeta implements Faceable { + + public BlockLectern() { + this(0); + } + + public BlockLectern(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Lectern"; + } + + @Override + public int getId() { + return LECTERN; + } + + @Override + public BlockColor getColor() { + return BlockColor.WOOD_BLOCK_COLOR; + } + + public int getToolType() { + return ItemTool.TYPE_AXE; + } + + public double getHardness() { + return 2.5; + } + + public double getResistance() { + return 2.5; + } + + @Override + public int getBurnChance() { + return 30; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + int horizontalIndex = (player != null ? player.getDirection().getOpposite() : BlockFace.SOUTH).getHorizontalIndex(); + if (horizontalIndex >= 0) { + this.setDamage(getDamage() & (15 ^ 0b11) | (horizontalIndex & 0b11)); + } + CompoundTag nbt = new CompoundTag() + .putString("id", BlockEntity.LECTERN) + .putInt("x", (int) this.x) + .putInt("y", (int) this.y) + .putInt("z", (int) this.z); + BlockEntityLectern lectern = (BlockEntityLectern) BlockEntity.createBlockEntity(BlockEntity.LECTERN, this.getChunk(), nbt); + if (lectern == null) { + return false; + } + this.getLevel().setBlock(this, this, true, true); + return true; + } + + @Override + public BlockFace getBlockFace() { + return BlockFace.fromHorizontalIndex(getDamage() & 0b11); + } + + public boolean dropBook() { + BlockEntity blockEntity = this.getLevel().getBlockEntity(this); + if (blockEntity instanceof BlockEntityLectern) { + BlockEntityLectern lectern = (BlockEntityLectern) blockEntity; + Item book = lectern.getBook(); + if (book.getId() != BlockID.AIR) { + lectern.setBook(Item.get(BlockID.AIR)); + lectern.spawnToAll(); + this.level.dropItem(lectern.add(0.5f, 1, 0.5f), book); + return true; + } + } + return false; + } + + @Override + public boolean isPowerSource() { + return true; + } + + public boolean isActivated() { + return (this.getDamage() & 0x04) == 0x04; + } + + public void setActivated(boolean activated) { + if (activated) { + setDamage(getDamage() | 0x04); + } else { + setDamage(getDamage() ^ 0x04); + } + } + + @Override + public int getWeakPower(BlockFace face) { + return isActivated() ? 15 : 0; + } + + @Override + public int getStrongPower(BlockFace side) { + return 0; + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (player != null) { + BlockEntity t = this.getLevel().getBlockEntity(this); + if (!(t instanceof BlockEntityLectern)) { + return false; + } + + BlockEntityLectern lectern = (BlockEntityLectern) t;; + Item currentBook = lectern.getBook(); + if (currentBook.getId() == BlockID.AIR) { + if (item.getId() == ItemID.WRITTEN_BOOK || item.getId() == ItemID.BOOK_AND_QUILL) { + Item newBook = item.clone(); + if (!player.isCreative()) { + item.count--; + } + newBook.setCount(1); + lectern.setBook(newBook); + lectern.spawnToAll(); + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_ITEM_BOOK_PUT); + } + } else { + ContainerOpenPacket pk = new ContainerOpenPacket(); + pk.windowId = -1; + pk.type = InventoryType.LECTERN.getNetworkType(); + pk.x = (int) x; + pk.y = (int) y; + pk.z = (int) z; + pk.entityId = player.getId(); + player.dataPacket(pk); + } + } + + return true; + } + + @Override + public boolean canBePushed() { + return false; // prevent item loss issue with pistons until a working implementation + } +} diff --git a/src/main/java/cn/nukkit/block/BlockLever.java b/src/main/java/cn/nukkit/block/BlockLever.java index 98903e236de..b0b66f9efb8 100644 --- a/src/main/java/cn/nukkit/block/BlockLever.java +++ b/src/main/java/cn/nukkit/block/BlockLever.java @@ -6,7 +6,7 @@ import cn.nukkit.item.ItemBlock; import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; -import cn.nukkit.network.protocol.LevelEventPacket; +import cn.nukkit.network.protocol.LevelSoundEventPacket; import cn.nukkit.utils.BlockColor; import cn.nukkit.utils.Faceable; @@ -50,7 +50,7 @@ public double getResistance() { @Override public Item toItem() { - return new ItemBlock(this, 0); + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override @@ -68,12 +68,16 @@ public boolean onActivate(Item item, Player player) { this.setDamage(this.getDamage() ^ 0x08); this.getLevel().setBlock(this, this, false, true); - this.getLevel().addLevelEvent(this.add(0.5, 0.5, 0.5), LevelEventPacket.EVENT_SOUND_BUTTON_CLICK, this.isPowerOn() ? 600 : 500); + if (this.isPowerOn()) { + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_POWER_ON); + } else { + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_POWER_OFF); + } LeverOrientation orientation = LeverOrientation.byMetadata(this.isPowerOn() ? this.getDamage() ^ 0x08 : this.getDamage()); BlockFace face = orientation.getFacing(); - //this.level.updateAroundRedstone(this, null); - this.level.updateAroundRedstone(this.getLocation().getSide(face.getOpposite()), isPowerOn() ? face : null); + level.updateAroundRedstone(this, null); + this.level.updateAroundRedstone(this.getSideVec(face.getOpposite()), isPowerOn() ? face : null); return true; } @@ -82,7 +86,7 @@ public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_NORMAL) { int face = this.isPowerOn() ? this.getDamage() ^ 0x08 : this.getDamage(); BlockFace faces = LeverOrientation.byMetadata(face).getFacing().getOpposite(); - if (!this.getSide(faces).isSolid()) { + if (!isSupportValid(this.getSide(faces))) { this.level.useBreakOn(this); } } @@ -91,12 +95,12 @@ public int onUpdate(int type) { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - if (target.isNormalBlock()) { - this.setDamage(LeverOrientation.forFacings(face, player.getHorizontalFacing()).getMetadata()); - this.getLevel().setBlock(block, this, true, true); - return true; + LeverOrientation faces = LeverOrientation.forFacings(face, player.getHorizontalFacing()); + this.setDamage(faces.getMetadata()); + if (!isSupportValid(this.getSide(faces.facing.getOpposite()))) { + return false; } - return false; + return this.getLevel().setBlock(block, this, true, true); } @Override @@ -104,19 +108,33 @@ public boolean onBreak(Item item) { this.getLevel().setBlock(this, Block.get(BlockID.AIR), true, true); if (isPowerOn()) { - BlockFace face = LeverOrientation.byMetadata(this.isPowerOn() ? this.getDamage() ^ 0x08 : this.getDamage()).getFacing(); - this.level.updateAround(this.getLocation().getSide(face.getOpposite())); + BlockFace face = LeverOrientation.byMetadata(this.getDamage() ^ 0x08).getFacing(); + this.level.updateAround(this.getSideVec(face.getOpposite())); } return true; } + private boolean isSupportValid(Block block) { + if (!block.isTransparent()) { + return true; + } + if (BlockFace.fromIndex(isPowerOn() ? getDamage() ^ 0x08 : getDamage()) == BlockFace.DOWN) { + return Block.canStayOnFullSolid(block); + } + return Block.canConnectToFullSolid(block); + } + @Override public int getWeakPower(BlockFace side) { return isPowerOn() ? 15 : 0; } public int getStrongPower(BlockFace side) { - return !isPowerOn() ? 0 : LeverOrientation.byMetadata(this.isPowerOn() ? this.getDamage() ^ 0x08 : this.getDamage()).getFacing() == side ? 15 : 0; + if (!isPowerOn()) { + return 0; + } else { + return LeverOrientation.byMetadata(this.getDamage() ^ 0x08).getFacing() == side ? 15 : 0; + } } @Override @@ -214,18 +232,33 @@ public String getName() { static { for (LeverOrientation face : values()) { - META_LOOKUP[face.getMetadata()] = face; + META_LOOKUP[face.meta] = face; } } } @Override public BlockFace getBlockFace() { - return BlockFace.fromHorizontalIndex(this.getDamage() & 0x07); + return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); } @Override public BlockColor getColor() { return BlockColor.AIR_BLOCK_COLOR; } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.FLOW_INTO_BLOCK; + } + + @Override + public boolean canBeFlowedInto() { + return false; + } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockLightBlock.java b/src/main/java/cn/nukkit/block/BlockLightBlock.java new file mode 100644 index 00000000000..062911bccdc --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockLightBlock.java @@ -0,0 +1,75 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.math.AxisAlignedBB; + +public class BlockLightBlock extends BlockTransparentMeta { + + public BlockLightBlock() { + this(0); + } + + public BlockLightBlock(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Light Block"; + } + + @Override + public int getId() { + return LIGHT_BLOCK; + } + + @Override + public int getLightLevel() { + return getDamage() & 0xF; + } + + @Override + public AxisAlignedBB getBoundingBox() { + return null; + } + + @Override + public boolean canBeFlowedInto() { + return true; + } + + @Override + public boolean canBeReplaced() { + return true; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public double getHardness() { + return 0; + } + + @Override + public double getResistance() { + return 3600000.8; + } + + @Override + public boolean canPassThrough() { + return true; + } + + @Override + public Item toItem() { + return Item.get(Item.AIR); + } + + @Override + public boolean canBePushed() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockLightningRod.java b/src/main/java/cn/nukkit/block/BlockLightningRod.java new file mode 100644 index 00000000000..c3d885efe68 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockLightningRod.java @@ -0,0 +1,87 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; +import cn.nukkit.math.BlockFace; + +public class BlockLightningRod extends BlockTransparentMeta { + + private static final int[] FACES = {0, 1, 2, 3, 4, 5}; + + public BlockLightningRod() { + this(0); + } + + public BlockLightningRod(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Lightning Rod"; + } + + @Override + public int getId() { + return LIGHTNING_ROD; + } + + @Override + public double getHardness() { + return 3; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public double getMinX() { + return this.x + 0.4; + } + + @Override + public double getMinZ() { + return this.z + 0.4; + } + + @Override + public double getMaxX() { + return this.x + 0.6; + } + + @Override + public double getMaxZ() { + return this.z + 0.6; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + this.setDamage(FACES[player != null ? face.getIndex() : 0]); + this.getLevel().setBlock(this, this, true, true); + return true; + } + + @Override + public Item[] getDrops(Item item) { + if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_STONE) { + return new Item[]{ + toItem() + }; + } else { + return new Item[0]; + } + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockLiquid.java b/src/main/java/cn/nukkit/block/BlockLiquid.java index 688be7cf069..da9dfa3306d 100644 --- a/src/main/java/cn/nukkit/block/BlockLiquid.java +++ b/src/main/java/cn/nukkit/block/BlockLiquid.java @@ -6,29 +6,25 @@ import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.level.Level; -import cn.nukkit.level.particle.SmokeParticle; +import cn.nukkit.level.format.FullChunk; import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.math.Vector3; -import cn.nukkit.network.protocol.LevelEventPacket; import cn.nukkit.network.protocol.LevelSoundEventPacket; import it.unimi.dsi.fastutil.longs.Long2ByteMap; import it.unimi.dsi.fastutil.longs.Long2ByteOpenHashMap; -import java.util.Random; -import java.util.concurrent.ThreadLocalRandom; - /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class BlockLiquid extends BlockTransparentMeta { - private final byte CAN_FLOW_DOWN = 1; - private final byte CAN_FLOW = 0; - private final byte BLOCKED = -1; + protected static final byte CAN_FLOW_DOWN = 1; + protected static final byte CAN_FLOW = 0; + protected static final byte BLOCKED = -1; public int adjacentSources = 0; protected Vector3 flowVector = null; - private Long2ByteMap flowCostVisited = new Long2ByteOpenHashMap(); + protected Long2ByteMap flowCostVisited = new Long2ByteOpenHashMap(); protected BlockLiquid(int meta) { super(meta); @@ -39,10 +35,12 @@ public boolean canBeFlowedInto() { return true; } + @Override protected AxisAlignedBB recalculateBoundingBox() { return null; } + @Override public Item[] getDrops(Item item) { return new Item[0]; } @@ -77,6 +75,11 @@ public AxisAlignedBB getBoundingBox() { return null; } + @Override + public boolean breakWhenPushed() { + return true; + } + @Override public double getMaxY() { return this.y + 1 - getFluidHeightPercent(); @@ -98,14 +101,22 @@ public float getFluidHeightPercent() { protected int getFlowDecay(Block block) { if (block.getId() != this.getId()) { - return -1; + Block layer1 = block.getLevelBlock(BlockLayer.WATERLOGGED); + if (layer1.getId() != this.getId()) { + return -1; + } else { + return layer1.getDamage(); + } } return block.getDamage(); } protected int getEffectiveFlowDecay(Block block) { if (block.getId() != this.getId()) { - return -1; + block = block.getLevelBlock(BlockLayer.WATERLOGGED); + if (block.getId() != this.getId()) { + return -1; + } } int decay = block.getDamage(); if (decay >= 8) { @@ -142,13 +153,14 @@ public Vector3 getFlowVector() { default: z++; } - Block sideBlock = this.level.getBlock(x, y, z); + FullChunk chunk = this.level.getChunk(x >> 4, z >> 4); + Block sideBlock = this.level.getBlock(chunk, x, y, z, true); int blockDecay = this.getEffectiveFlowDecay(sideBlock); if (blockDecay < 0) { if (!sideBlock.canBeFlowedInto()) { continue; } - blockDecay = this.getEffectiveFlowDecay(this.level.getBlock(x, y - 1, z)); + blockDecay = this.getEffectiveFlowDecay(this.level.getBlock(chunk, x, y - 1, z, true)); if (blockDecay >= 0) { int realDecay = blockDecay - (decay - 8); vector.x += (sideBlock.x - this.x) * realDecay; @@ -163,15 +175,17 @@ public Vector3 getFlowVector() { } } if (this.getDamage() >= 8) { - if (!this.canFlowInto(this.level.getBlock((int) this.x, (int) this.y, (int) this.z - 1)) || - !this.canFlowInto(this.level.getBlock((int) this.x, (int) this.y, (int) this.z + 1)) || - !this.canFlowInto(this.level.getBlock((int) this.x - 1, (int) this.y, (int) this.z)) || - !this.canFlowInto(this.level.getBlock((int) this.x + 1, (int) this.y, (int) this.z)) || - !this.canFlowInto(this.level.getBlock((int) this.x, (int) this.y + 1, (int) this.z - 1)) || - !this.canFlowInto(this.level.getBlock((int) this.x, (int) this.y + 1, (int) this.z + 1)) || - !this.canFlowInto(this.level.getBlock((int) this.x - 1, (int) this.y + 1, (int) this.z)) || - !this.canFlowInto(this.level.getBlock((int) this.x + 1, (int) this.y + 1, (int) this.z))) { - vector = vector.normalize().add(0, -6, 0); + FullChunk guessChunk = getChunk(); + if (!this.canFlowInto(this.level.getBlock(guessChunk, (int) this.x, (int) this.y, (int) this.z - 1, true)) || + !this.canFlowInto(this.level.getBlock(guessChunk, (int) this.x, (int) this.y, (int) this.z + 1, true)) || + !this.canFlowInto(this.level.getBlock(guessChunk, (int) this.x - 1, (int) this.y, (int) this.z, true)) || + !this.canFlowInto(this.level.getBlock(guessChunk, (int) this.x + 1, (int) this.y, (int) this.z, true)) || + !this.canFlowInto(this.level.getBlock(guessChunk, (int) this.x, (int) this.y + 1, (int) this.z - 1, true)) || + !this.canFlowInto(this.level.getBlock(guessChunk, (int) this.x, (int) this.y + 1, (int) this.z + 1, true)) || + !this.canFlowInto(this.level.getBlock(guessChunk, (int) this.x - 1, (int) this.y + 1, (int) this.z, true)) || + !this.canFlowInto(this.level.getBlock(guessChunk, (int) this.x + 1, (int) this.y + 1, (int) this.z, true))) { + vector = vector.normalize(); + vector.y -= 6; } } return this.flowVector = vector.normalize(); @@ -195,32 +209,47 @@ public int getFlowDecayPerBlock() { public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_NORMAL) { this.checkForHarden(); + if (this.usesWaterLogging() && this.getLayer().ordinal() > LAYER_NORMAL.ordinal()) { + Block layer0 = this.level.getBlock(this, LAYER_NORMAL, true); + if (layer0.getId() == Block.AIR) { + this.level.setBlock(this, LAYER_WATERLOGGED, Block.get(Block.AIR), false, false); + this.level.setBlock(this, LAYER_NORMAL, this, false, false); + } else if (layer0.getWaterloggingType() == WaterloggingType.NO_WATERLOGGING || ((layer0.getWaterloggingType() == WaterloggingType.WHEN_PLACED_IN_WATER) && (this.getDamage() > 0))) { + this.level.setBlock(this, LAYER_WATERLOGGED, Block.get(Block.AIR), true, true); + } + } this.level.scheduleUpdate(this, this.tickRate()); return 0; } else if (type == Level.BLOCK_UPDATE_SCHEDULED) { int decay = this.getFlowDecay(this); int multiplier = this.getFlowDecayPerBlock(); + FullChunk guessChunk = getChunk(); if (decay > 0) { int smallestFlowDecay = -100; this.adjacentSources = 0; - smallestFlowDecay = this.getSmallestFlowDecay(this.level.getBlock((int) this.x, (int) this.y, (int) this.z - 1), smallestFlowDecay); - smallestFlowDecay = this.getSmallestFlowDecay(this.level.getBlock((int) this.x, (int) this.y, (int) this.z + 1), smallestFlowDecay); - smallestFlowDecay = this.getSmallestFlowDecay(this.level.getBlock((int) this.x - 1, (int) this.y, (int) this.z), smallestFlowDecay); - smallestFlowDecay = this.getSmallestFlowDecay(this.level.getBlock((int) this.x + 1, (int) this.y, (int) this.z), smallestFlowDecay); + smallestFlowDecay = this.getSmallestFlowDecay(this.level.getBlock(guessChunk, (int) this.x, (int) this.y, (int) this.z - 1, true), smallestFlowDecay); + smallestFlowDecay = this.getSmallestFlowDecay(this.level.getBlock(guessChunk, (int) this.x, (int) this.y, (int) this.z + 1, true), smallestFlowDecay); + smallestFlowDecay = this.getSmallestFlowDecay(this.level.getBlock(guessChunk, (int) this.x - 1, (int) this.y, (int) this.z, true), smallestFlowDecay); + smallestFlowDecay = this.getSmallestFlowDecay(this.level.getBlock(guessChunk, (int) this.x + 1, (int) this.y, (int) this.z, true), smallestFlowDecay); int newDecay = smallestFlowDecay + multiplier; if (newDecay >= 8 || smallestFlowDecay < 0) { newDecay = -1; } - int topFlowDecay = this.getFlowDecay(this.level.getBlock((int) this.x, (int) this.y + 1, (int) this.z)); + int topFlowDecay = this.getFlowDecay(this.level.getBlock(guessChunk, (int) this.x, (int) this.y + 1, (int) this.z, true)); if (topFlowDecay >= 0) { newDecay = topFlowDecay | 0x08; } if (this.adjacentSources >= 2 && this instanceof BlockWater) { - Block bottomBlock = this.level.getBlock((int) this.x, (int) this.y - 1, (int) this.z); + Block bottomBlock = this.level.getBlock(guessChunk, (int) this.x, (int) this.y - 1, (int) this.z, true); if (bottomBlock.isSolid()) { newDecay = 0; } else if (bottomBlock instanceof BlockWater && bottomBlock.getDamage() == 0) { newDecay = 0; + } else { + bottomBlock = bottomBlock.getLevelBlock(BlockLayer.WATERLOGGED); + if (bottomBlock instanceof BlockWater && bottomBlock.getDamage() == 0) { + newDecay = 0; + } } } if (newDecay != decay) { @@ -235,7 +264,7 @@ public int onUpdate(int type) { BlockFromToEvent event = new BlockFromToEvent(this, to); level.getServer().getPluginManager().callEvent(event); if (!event.isCancelled()) { - this.level.setBlock(this, event.getTo(), true, true); + this.level.setBlock(this, this.getLayer(), event.getTo(), true, true); if (!decayed) { this.level.scheduleUpdate(this, this.tickRate()); } @@ -243,9 +272,9 @@ public int onUpdate(int type) { } } if (decay >= 0) { - Block bottomBlock = this.level.getBlock((int) this.x, (int) this.y - 1, (int) this.z); + Block bottomBlock = this.level.getBlock(guessChunk, (int) this.x, (int) this.y - 1, (int) this.z, true); this.flowIntoBlock(bottomBlock, decay | 0x08); - if (decay == 0 || !bottomBlock.canBeFlowedInto()) { + if (decay == 0 || !(this.usesWaterLogging()? bottomBlock.canWaterloggingFlowInto(): bottomBlock.canBeFlowedInto())) { int adjacentDecay; if (decay >= 8) { adjacentDecay = 1; @@ -255,16 +284,16 @@ public int onUpdate(int type) { if (adjacentDecay < 8) { boolean[] flags = this.getOptimalFlowDirections(); if (flags[0]) { - this.flowIntoBlock(this.level.getBlock((int) this.x - 1, (int) this.y, (int) this.z), adjacentDecay); + this.flowIntoBlock(this.level.getBlock(guessChunk, (int) this.x - 1, (int) this.y, (int) this.z, true), adjacentDecay); } if (flags[1]) { - this.flowIntoBlock(this.level.getBlock((int) this.x + 1, (int) this.y, (int) this.z), adjacentDecay); + this.flowIntoBlock(this.level.getBlock(guessChunk, (int) this.x + 1, (int) this.y, (int) this.z, true), adjacentDecay); } if (flags[2]) { - this.flowIntoBlock(this.level.getBlock((int) this.x, (int) this.y, (int) this.z - 1), adjacentDecay); + this.flowIntoBlock(this.level.getBlock(guessChunk, (int) this.x, (int) this.y, (int) this.z - 1, true), adjacentDecay); } if (flags[3]) { - this.flowIntoBlock(this.level.getBlock((int) this.x, (int) this.y, (int) this.z + 1), adjacentDecay); + this.flowIntoBlock(this.level.getBlock(guessChunk, (int) this.x, (int) this.y, (int) this.z + 1, true), adjacentDecay); } } } @@ -275,27 +304,37 @@ public int onUpdate(int type) { } protected void flowIntoBlock(Block block, int newFlowDecay) { - if (this.canFlowInto(block) && !(block instanceof BlockLiquid)) { + if (!(block instanceof BlockLiquid) && this.canFlowInto(block)) { + if (this.usesWaterLogging()) { + Block waterlogged = block.getLevelBlock(LAYER_WATERLOGGED); + if (waterlogged instanceof BlockLiquid) { + return; + } + + if (block.getWaterloggingType() == WaterloggingType.FLOW_INTO_BLOCK) { + block = waterlogged; + } + } + LiquidFlowEvent event = new LiquidFlowEvent(block, this, newFlowDecay); level.getServer().getPluginManager().callEvent(event); if (!event.isCancelled()) { - if (block.getId() > 0) { + if (block.getLayer() == BlockLayer.NORMAL && block.getId() != 0) { this.level.useBreakOn(block, block.getId() == COBWEB ? Item.get(Item.WOODEN_SWORD) : null); } - this.level.setBlock(block, getBlock(newFlowDecay), true, true); + this.level.setBlock(block, block.getLayer(), getBlock(newFlowDecay), true, true); this.level.scheduleUpdate(block, this.tickRate()); } } } - private int calculateFlowCost(int blockX, int blockY, int blockZ, int accumulatedCost, int maxCost, int originOpposite, int lastOpposite) { + protected int calculateFlowCost(int blockX, int blockY, int blockZ, int accumulatedCost, int maxCost, int originOpposite, int lastOpposite) { int cost = 1000; for (int j = 0; j < 4; ++j) { if (j == originOpposite || j == lastOpposite) { continue; } int x = blockX; - int y = blockY; int z = blockZ; if (j == 0) { --x; @@ -306,18 +345,26 @@ private int calculateFlowCost(int blockX, int blockY, int blockZ, int accumulate } else if (j == 3) { ++z; } - long hash = Level.blockHash(x, y, z); - if (!this.flowCostVisited.containsKey(hash)) { - Block blockSide = this.level.getBlock(x, y, z); + long hash = Level.blockHash(x, blockY, z, this.level.getDimensionData()); + byte status; + if (this.flowCostVisited.containsKey(hash)) { + status = this.flowCostVisited.get(hash); + } else { + FullChunk chunk = this.level.getChunk(x >> 4, z >> 4); + Block blockSide = this.level.getBlock(chunk, x, blockY, z, true); if (!this.canFlowInto(blockSide)) { this.flowCostVisited.put(hash, BLOCKED); - } else if (this.level.getBlock(x, y - 1, z).canBeFlowedInto()) { + status = BLOCKED; + } else if (usesWaterLogging()? + this.level.getBlock(x, blockY - 1, z).canWaterloggingFlowInto() : + this.level.getBlock(chunk, x, blockY - 1, z, true).canBeFlowedInto()) { this.flowCostVisited.put(hash, CAN_FLOW_DOWN); + status = CAN_FLOW_DOWN; } else { this.flowCostVisited.put(hash, CAN_FLOW); + status = CAN_FLOW; } } - byte status = this.flowCostVisited.get(hash); if (status == BLOCKED) { continue; } else if (status == CAN_FLOW_DOWN) { @@ -326,7 +373,7 @@ private int calculateFlowCost(int blockX, int blockY, int blockZ, int accumulate if (accumulatedCost >= maxCost) { continue; } - int realCost = this.calculateFlowCost(x, y, z, accumulatedCost + 1, maxCost, originOpposite, j ^ 0x01); + int realCost = this.calculateFlowCost(x, blockY, z, accumulatedCost + 1, maxCost, originOpposite, j ^ 0x01); if (realCost < cost) { cost = realCost; } @@ -344,8 +391,8 @@ public double getResistance() { return 500; } - private boolean[] getOptimalFlowDirections() { - int[] flowCost = new int[]{ + protected boolean[] getOptimalFlowDirections() { + int[] flowCost = { 1000, 1000, 1000, @@ -365,14 +412,17 @@ private boolean[] getOptimalFlowDirections() { } else { ++z; } - Block block = this.level.getBlock(x, y, z); + FullChunk chunk = this.level.getChunk(x >> 4, z >> 4); + Block block = this.level.getBlock(chunk, x, y, z, true); if (!this.canFlowInto(block)) { - this.flowCostVisited.put(Level.blockHash(x, y, z), BLOCKED); - } else if (this.level.getBlock(x, y - 1, z).canBeFlowedInto()) { - this.flowCostVisited.put(Level.blockHash(x, y, z), CAN_FLOW_DOWN); + this.flowCostVisited.put(Level.blockHash(x, y, z, this.level.getDimensionData()), BLOCKED); + } else if (usesWaterLogging()? + this.level.getBlock(x, y - 1, z).canWaterloggingFlowInto(): + this.level.getBlock(chunk, x, y - 1, z, true).canBeFlowedInto()) { + this.flowCostVisited.put(Level.blockHash(x, y, z, this.level.getDimensionData()), CAN_FLOW_DOWN); flowCost[j] = maxCost = 0; } else if (maxCost > 0) { - this.flowCostVisited.put(Level.blockHash(x, y, z), CAN_FLOW); + this.flowCostVisited.put(Level.blockHash(x, y, z, this.level.getDimensionData()), CAN_FLOW); flowCost[j] = this.calculateFlowCost(x, y, z, 1, maxCost, j ^ 0x01, j ^ 0x01); maxCost = Math.min(maxCost, flowCost[j]); } @@ -407,15 +457,6 @@ private int getSmallestFlowDecay(Block block, int decay) { protected void checkForHarden() { } - protected void triggerLavaMixEffects(Vector3 pos) { - Random random = ThreadLocalRandom.current(); - this.getLevel().addLevelEvent(pos.add(0.5, 0.5, 0.5), LevelEventPacket.EVENT_SOUND_FIZZ, (int) ((random.nextFloat() - random.nextFloat()) * 800) + 2600); - - for (int i = 0; i < 8; ++i) { - this.getLevel().addParticle(new SmokeParticle(pos.add(Math.random(), 1.2, Math.random()))); - } - } - public abstract BlockLiquid getBlock(int meta); @Override @@ -435,11 +476,18 @@ protected boolean liquidCollide(Block cause, Block result) { return false; } this.level.setBlock(this, event.getTo(), true, true); + this.level.setBlock(this, Block.LAYER_WATERLOGGED, Block.get(Block.AIR), true, true); this.getLevel().addLevelSoundEvent(this.add(0.5, 0.5, 0.5), LevelSoundEventPacket.SOUND_FIZZ); return true; } protected boolean canFlowInto(Block block) { + if (this.usesWaterLogging()) { + if (block.canWaterloggingFlowInto()) { + Block blockLayer1 = block.getLevelBlock(BlockLayer.WATERLOGGED); + return !(block instanceof BlockLiquid && block.getDamage() == 0) && !(blockLayer1 instanceof BlockLiquid && blockLayer1.getDamage() == 0); + } + } return block.canBeFlowedInto() && !(block instanceof BlockLiquid && block.getDamage() == 0); } @@ -447,4 +495,8 @@ protected boolean canFlowInto(Block block) { public Item toItem() { return new ItemBlock(Block.get(BlockID.AIR)); } -} + + public boolean usesWaterLogging() { + return false; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockLodestone.java b/src/main/java/cn/nukkit/block/BlockLodestone.java new file mode 100644 index 00000000000..cd54861b331 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockLodestone.java @@ -0,0 +1,36 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; + +public class BlockLodestone extends BlockSolid { + + @Override + public String getName() { + return "Lodestone"; + } + + @Override + public int getId() { + return LODESTONE; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public double getHardness() { + return 3.5; + } + + @Override + public double getResistance() { + return 3.5; + } + + @Override + public boolean canBePushed() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockLoom.java b/src/main/java/cn/nukkit/block/BlockLoom.java new file mode 100644 index 00000000000..f01e16f3d30 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockLoom.java @@ -0,0 +1,76 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.inventory.LoomInventory; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.BlockColor; + +public class BlockLoom extends BlockSolidMeta { + + public BlockLoom() { + this(0); + } + + public BlockLoom(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Loom"; + } + + @Override + public int getId() { + return LOOM; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_AXE; + } + + @Override + public double getResistance() { + return 12.5; + } + + @Override + public double getHardness() { + return 2.5; + } + + @Override + public BlockColor getColor() { + return BlockColor.WOOD_BLOCK_COLOR; + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (player != null) { + player.addWindow(new LoomInventory(player.getUIInventory(), this), Player.LOOM_WINDOW_ID); + } + return true; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + private static final short[] FACES = {2, 3, 0, 1}; + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + this.setDamage(FACES[player != null ? player.getDirection().getHorizontalIndex() : 0]); + return this.getLevel().setBlock(this, this, true, true); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockMagma.java b/src/main/java/cn/nukkit/block/BlockMagma.java index 9ba436318ea..286b61f07a7 100644 --- a/src/main/java/cn/nukkit/block/BlockMagma.java +++ b/src/main/java/cn/nukkit/block/BlockMagma.java @@ -1,21 +1,22 @@ package cn.nukkit.block; import cn.nukkit.Player; +import cn.nukkit.Server; import cn.nukkit.entity.Entity; +import cn.nukkit.event.block.BlockFormEvent; import cn.nukkit.event.entity.EntityDamageByBlockEvent; import cn.nukkit.event.entity.EntityDamageEvent; +import cn.nukkit.inventory.PlayerInventory; import cn.nukkit.item.Item; import cn.nukkit.item.ItemTool; +import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.level.GameRule; +import cn.nukkit.level.Level; import cn.nukkit.potion.Effect; import cn.nukkit.utils.BlockColor; public class BlockMagma extends BlockSolid { - public BlockMagma(){ - - } - @Override public int getId() { return MAGMA; @@ -38,7 +39,7 @@ public double getHardness() { @Override public double getResistance() { - return 30; + return 0.5; } @Override @@ -48,7 +49,7 @@ public int getLightLevel() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; @@ -59,14 +60,18 @@ public Item[] getDrops(Item item) { @Override public void onEntityCollide(Entity entity) { - if (!entity.hasEffect(Effect.FIRE_RESISTANCE)) { + if (entity.y >= this.y + 1 && !entity.hasEffect(Effect.FIRE_RESISTANCE)) { if (entity instanceof Player) { Player p = (Player) entity; - if (!p.isCreative() && !p.isSpectator() && !p.isSneaking() && p.level.gameRules.getBoolean(GameRule.FIRE_DAMAGE)) { - entity.attack(new EntityDamageByBlockEvent(this, entity, EntityDamageEvent.DamageCause.LAVA, 1)); + PlayerInventory inv = p.getInventory(); + if (inv == null || inv.getBootsFast().hasEnchantment(Enchantment.ID_FROST_WALKER) || !entity.level.gameRules.getBoolean(GameRule.FIRE_DAMAGE)) { + return; + } + if (!p.isCreative() && !p.isSpectator() && !p.isSneaking()) { + entity.attack(new EntityDamageByBlockEvent(this, entity, EntityDamageEvent.DamageCause.MAGMA, 1)); } } else { - entity.attack(new EntityDamageByBlockEvent(this, entity, EntityDamageEvent.DamageCause.LAVA, 1)); + entity.attack(new EntityDamageByBlockEvent(this, entity, EntityDamageEvent.DamageCause.MAGMA, 1)); } } } @@ -80,5 +85,26 @@ public BlockColor getColor() { public boolean canHarvestWithHand() { return false; } + + @Override + public boolean hasEntityCollision() { + return true; + } + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + Block up = this.up(); + if (up instanceof BlockWater && (up.getDamage() == 0 || up.getDamage() == 8)) { + BlockFormEvent event = new BlockFormEvent(up, Block.get(BUBBLE_COLUMN, BlockBubbleColumn.DIRECTION_DOWN)); + Server.getInstance().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + this.getLevel().setBlock(up, event.getNewState(), false, true); + } + } + } + + return 0; + } } diff --git a/src/main/java/cn/nukkit/block/BlockMangrovePropagule.java b/src/main/java/cn/nukkit/block/BlockMangrovePropagule.java new file mode 100644 index 00000000000..444ff0b5b5b --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockMangrovePropagule.java @@ -0,0 +1,45 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; + +public class BlockMangrovePropagule extends BlockSapling { + + public BlockMangrovePropagule() { + this(0); + } + + public BlockMangrovePropagule(int meta) { + super(meta); + } + + @Override + public int getId() { + return MANGROVE_PROPAGULE; + } + + @Override + public String getName() { + return "Mangrove Propagule"; + } + + @Override + public Item[] getDrops(Item item) { + return new Item[0]; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public boolean canBeFlowedInto() { + return false; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.FLOW_INTO_BLOCK; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockMangroveRoots.java b/src/main/java/cn/nukkit/block/BlockMangroveRoots.java new file mode 100644 index 00000000000..dab9e321ab8 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockMangroveRoots.java @@ -0,0 +1,46 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; + +public class BlockMangroveRoots extends BlockTransparent { + + @Override + public String getName() { + return "Mangrove Roots"; + } + + @Override + public int getId() { + return MANGROVE_ROOTS; + } + + @Override + public double getHardness() { + return 0.7; + } + + @Override + public double getResistance() { + return 0.7; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_AXE; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public int getBurnChance() { + return 30; + } + + @Override + public int getBurnAbility() { + return 60; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockMangroveRootsMuddy.java b/src/main/java/cn/nukkit/block/BlockMangroveRootsMuddy.java new file mode 100644 index 00000000000..1e36ffbdf1e --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockMangroveRootsMuddy.java @@ -0,0 +1,38 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; + +public class BlockMangroveRootsMuddy extends BlockMangroveRoots { + + @Override + public String getName() { + return "Muddy Mangrove Roots"; + } + + @Override + public int getId() { + return MUDDY_MANGROVE_ROOTS; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_SHOVEL; + } + + @Override + public int getBurnChance() { + return 0; + } + + @Override + public int getBurnAbility() { + return 0; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockMelon.java b/src/main/java/cn/nukkit/block/BlockMelon.java index 6bad17f49ae..3e99161d1e1 100644 --- a/src/main/java/cn/nukkit/block/BlockMelon.java +++ b/src/main/java/cn/nukkit/block/BlockMelon.java @@ -1,12 +1,10 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemMelon; import cn.nukkit.item.ItemTool; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.utils.BlockColor; - -import java.util.Random; +import cn.nukkit.utils.Utils; /** * Created on 2015/12/11 by Pub4Game. @@ -15,9 +13,6 @@ public class BlockMelon extends BlockSolid { - public BlockMelon() { - } - @Override public int getId() { return MELON_BLOCK; @@ -38,16 +33,19 @@ public double getResistance() { @Override public Item[] getDrops(Item item) { - Random random = new Random(); - int count = 3 + random.nextInt(5); + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; + } + + int count = 3 + Utils.random.nextInt(5); Enchantment fortune = item.getEnchantment(Enchantment.ID_FORTUNE_DIGGING); if (fortune != null && fortune.getLevel() >= 1) { - count += random.nextInt(fortune.getLevel() + 1); + count += Utils.random.nextInt(fortune.getLevel() + 1); } return new Item[]{ - new ItemMelon(0, Math.min(9, count)) + Item.get(Item.MELON, 0, Math.min(9, count)) }; } @@ -60,9 +58,14 @@ public int getToolType() { public BlockColor getColor() { return BlockColor.LIME_BLOCK_COLOR; } - + @Override public boolean canSilkTouch() { return true; } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockMeta.java b/src/main/java/cn/nukkit/block/BlockMeta.java index 6ffb2087e38..7fc627bcc51 100644 --- a/src/main/java/cn/nukkit/block/BlockMeta.java +++ b/src/main/java/cn/nukkit/block/BlockMeta.java @@ -1,6 +1,7 @@ package cn.nukkit.block; public abstract class BlockMeta extends Block { + private int meta; protected BlockMeta(int meta) { @@ -9,7 +10,7 @@ protected BlockMeta(int meta) { @Override public int getFullId() { - return (getId() << 4) + getDamage(); + return (getId() << DATA_BITS) + getDamage(); } @Override @@ -21,5 +22,4 @@ public final int getDamage() { public void setDamage(int meta) { this.meta = meta; } - -} \ No newline at end of file +} diff --git a/src/main/java/cn/nukkit/block/BlockMobSpawner.java b/src/main/java/cn/nukkit/block/BlockMobSpawner.java index 766b662146b..dca8ea8089e 100644 --- a/src/main/java/cn/nukkit/block/BlockMobSpawner.java +++ b/src/main/java/cn/nukkit/block/BlockMobSpawner.java @@ -1,16 +1,17 @@ package cn.nukkit.block; +import cn.nukkit.Player; +import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.item.Item; import cn.nukkit.item.ItemTool; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.Utils; /** * Created by Pub4Game on 27.12.2015. */ public class BlockMobSpawner extends BlockSolid { - public BlockMobSpawner() { - } - @Override public String getName() { return "Monster Spawner"; @@ -37,8 +38,13 @@ public double getResistance() { } @Override - public Item[] getDrops(Item item) { - return new Item[0]; + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (super.place(item, block, target, face, fx, fy, fz, player)) { + BlockEntity.createBlockEntity(BlockEntity.MOB_SPAWNER, this.getChunk(), BlockEntity.getDefaultCompound(this, BlockEntity.MOB_SPAWNER)); + + return true; + } + return false; } @Override @@ -51,4 +57,28 @@ public boolean canHarvestWithHand() { return false; } + @Override + public Item[] getDrops(Item item) { + return new Item[0]; + } + + @Override + public int getLightLevel() { + return 3; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean breakWhenPushed() { + return true; + } + + @Override + public int getDropExp() { + return Utils.rand(15, 43); + } } diff --git a/src/main/java/cn/nukkit/block/BlockMonsterEgg.java b/src/main/java/cn/nukkit/block/BlockMonsterEgg.java index 129c35d09c2..adf172b52e4 100644 --- a/src/main/java/cn/nukkit/block/BlockMonsterEgg.java +++ b/src/main/java/cn/nukkit/block/BlockMonsterEgg.java @@ -3,6 +3,7 @@ import cn.nukkit.item.Item; public class BlockMonsterEgg extends BlockSolidMeta { + public static final int STONE = 0; public static final int COBBLESTONE = 1; public static final int STONE_BRICK = 2; @@ -10,7 +11,7 @@ public class BlockMonsterEgg extends BlockSolidMeta { public static final int CRACKED_BRICK = 4; public static final int CHISELED_BRICK = 5; - private static final String[] NAMES = new String[]{ + private static final String[] NAMES = { "Stone", "Cobblestone", "Stone Brick", @@ -34,12 +35,12 @@ public int getId() { @Override public double getHardness() { - return 0.75; + return 1; } @Override public double getResistance() { - return 3.75; + return 0.75; } @Override diff --git a/src/main/java/cn/nukkit/block/BlockMoss.java b/src/main/java/cn/nukkit/block/BlockMoss.java new file mode 100644 index 00000000000..82593686f9f --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockMoss.java @@ -0,0 +1,118 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemDye; +import cn.nukkit.item.ItemTool; +import cn.nukkit.level.particle.BoneMealParticle; +import cn.nukkit.utils.BlockColor; + +import java.util.concurrent.ThreadLocalRandom; + +public class BlockMoss extends BlockDirt { + + public BlockMoss() { + } + + public BlockMoss(int meta) { + super(0); + } + + @Override + public int getId() { + return MOSS_BLOCK; + } + + @Override + public String getName() { + return "Moss Block"; + } + + @Override + public double getHardness() { + return 0.1; + } + + @Override + public double getResistance() { + return 2.5; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (item.getId() != Item.DYE || item.getDamage() != ItemDye.BONE_MEAL || this.up().getId() != AIR) { + return false; + } + + int random = ThreadLocalRandom.current().nextInt(13); + Block block; + Block block2 = null; + if (random < 5) { + block = Block.get(TALL_GRASS); + } else if (random < 8) { + block = Block.get(MOSS_CARPET); + } else if (random < 9) { + if (this.up(2).getId() != AIR) { + return false; + } + + block = Block.get(DOUBLE_PLANT, BlockDoublePlant.TALL_GRASS); + block2 = Block.get(DOUBLE_PLANT, BlockDoublePlant.TALL_GRASS ^ BlockDoublePlant.TOP_HALF_BITMASK); + } else if (random < 11) { + block = Block.get(AZALEA); + } else { + block = Block.get(FLOWERING_AZALEA); + } + + this.getLevel().setBlock(this.up(), block, false, true); + if (block2 != null) { + this.getLevel().setBlock(this.up(2), block2, false, true); + } + + this.level.addParticle(new BoneMealParticle(this)); + + if (player != null && !player.isCreative()) { + item.count--; + } + return true; + } + + @Override + public BlockColor getColor() { + return BlockColor.GREEN_BLOCK_COLOR; + } + + @Override + public boolean canSilkTouch() { + return true; + } + + @Override + public int getFullId() { + return this.getId() << Block.DATA_BITS; + } + + @Override + public void setDamage(int meta) { + // Noop + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId()), 0, 1); + } + + @Override + public Item[] getDrops(Item item) { + if (this.canHarvestWithHand() || this.canHarvest(item)) { + return new Item[]{this.toItem()}; + } + return new Item[0]; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_HOE; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockMossCarpet.java b/src/main/java/cn/nukkit/block/BlockMossCarpet.java new file mode 100644 index 00000000000..a482fc38db8 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockMossCarpet.java @@ -0,0 +1,90 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.DyeColor; + +public class BlockMossCarpet extends BlockTransparent { + + public BlockMossCarpet() { + } + + @Override + public int getId() { + return MOSS_CARPET; + } + + @Override + public String getName() { + return "Moss Carpet"; + } + + @Override + public boolean canBeFlowedInto() { + return true; + } + + @Override + public double getHardness() { + return 0.1; + } + + @Override + public double getResistance() { + return 0.5; + } + + @Override + public boolean isSolid() { + return true; + } + + @Override + public boolean canPassThrough() { + return false; + } + + @Override + public double getMaxY() { + return this.y + 0.0625; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + Block down = this.down(); + if (down.getId() != Item.AIR) { + this.getLevel().setBlock(block, this, true, true); + return true; + } + return false; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + if (!this.down().isSolid()) { + this.getLevel().useBreakOn(this); + return Level.BLOCK_UPDATE_NORMAL; + } + } + return 0; + } + + @Override + public BlockColor getColor() { + return DyeColor.GREEN.getColor(); + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean breakWhenPushed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockMossStone.java b/src/main/java/cn/nukkit/block/BlockMossStone.java index 9c4a6e9cf72..cf1a65533d3 100644 --- a/src/main/java/cn/nukkit/block/BlockMossStone.java +++ b/src/main/java/cn/nukkit/block/BlockMossStone.java @@ -9,9 +9,6 @@ */ public class BlockMossStone extends BlockSolid { - public BlockMossStone() { - } - @Override public String getName() { return "Mossy Cobblestone"; @@ -39,7 +36,7 @@ public int getToolType() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; diff --git a/src/main/java/cn/nukkit/block/BlockMud.java b/src/main/java/cn/nukkit/block/BlockMud.java new file mode 100644 index 00000000000..8ce0ce5b773 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockMud.java @@ -0,0 +1,39 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; + +public class BlockMud extends BlockSolid { + + public BlockMud() { + } + + @Override + public String getName() { + return "Mud"; + } + + @Override + public int getId() { + return MUD; + } + + @Override + public double getHardness() { + return 0.5; + } + + @Override + public double getResistance() { + return 0.5; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_SHOVEL; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_WOODEN; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockMudBrick.java b/src/main/java/cn/nukkit/block/BlockMudBrick.java new file mode 100644 index 00000000000..4ea3fb4322f --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockMudBrick.java @@ -0,0 +1,27 @@ +package cn.nukkit.block; + +public class BlockMudBrick extends BlockSolid { + + public BlockMudBrick() { + } + + @Override + public String getName() { + return "Mud Brick"; + } + + @Override + public int getId() { + return MUD_BRICKS; + } + + @Override + public double getHardness() { + return 1.5; + } + + @Override + public double getResistance() { + return 3; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockMudBrickSlab.java b/src/main/java/cn/nukkit/block/BlockMudBrickSlab.java new file mode 100644 index 00000000000..450db319183 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockMudBrickSlab.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockMudBrickSlab extends BlockSlab { + + public BlockMudBrickSlab() { + this(0); + } + + public BlockMudBrickSlab(int meta) { + super(meta, MUD_BRICK_DOUBLE_SLAB); + } + + @Override + public int getId() { + return MUD_BRICK_SLAB; + } + + @Override + public String getSlabName() { + return "Mud Brick Slab"; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockMudBrickStairs.java b/src/main/java/cn/nukkit/block/BlockMudBrickStairs.java new file mode 100644 index 00000000000..99e5bee899a --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockMudBrickStairs.java @@ -0,0 +1,32 @@ +package cn.nukkit.block; + +public class BlockMudBrickStairs extends BlockStairs { + + public BlockMudBrickStairs() { + this(0); + } + + public BlockMudBrickStairs(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Mud Brick Stair"; + } + + @Override + public int getId() { + return MUD_BRICK_STAIRS; + } + + @Override + public double getHardness() { + return 1.5; + } + + @Override + public double getResistance() { + return 3; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockMudBrickWall.java b/src/main/java/cn/nukkit/block/BlockMudBrickWall.java new file mode 100644 index 00000000000..1924a95f277 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockMudBrickWall.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockMudBrickWall extends BlockWall { + + public BlockMudBrickWall() { + this(0); + } + + public BlockMudBrickWall(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Mud Brick Wall"; + } + + @Override + public int getId() { + return MUD_BRICK_WALL; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockMushroom.java b/src/main/java/cn/nukkit/block/BlockMushroom.java index 350229a9eef..5ff2af6a8e0 100644 --- a/src/main/java/cn/nukkit/block/BlockMushroom.java +++ b/src/main/java/cn/nukkit/block/BlockMushroom.java @@ -1,10 +1,9 @@ package cn.nukkit.block; import cn.nukkit.Player; -import cn.nukkit.event.level.StructureGrowEvent; import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; import cn.nukkit.level.Level; -import cn.nukkit.level.ListChunkManager; import cn.nukkit.level.generator.object.mushroom.BigMushroom; import cn.nukkit.level.particle.BoneMealParticle; import cn.nukkit.math.BlockFace; @@ -38,6 +37,10 @@ public int onUpdate(int type) { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (block instanceof BlockWater || block.level.isBlockWaterloggedAt(block.getChunk(), (int) block.x, (int) block.y, (int) block.z)) { + return false; + } + if (canStay()) { getLevel().setBlock(block, this, true, true); return true; @@ -53,7 +56,7 @@ public boolean canBeActivated() { @Override public boolean onActivate(Item item, Player player) { if (item.getId() == Item.DYE && item.getDamage() == DyeColor.WHITE.getDyeData()) { - if (player != null && (player.gamemode & 0x01) == 0) { + if (player != null && !player.isCreative()) { item.count--; } @@ -72,16 +75,7 @@ public boolean grow() { BigMushroom generator = new BigMushroom(getType()); - ListChunkManager chunkManager = new ListChunkManager(this.level); - if (generator.generate(chunkManager, new NukkitRandom(), this)) { - StructureGrowEvent ev = new StructureGrowEvent(this, chunkManager.getBlocks()); - this.level.getServer().getPluginManager().callEvent(ev); - if (ev.isCancelled()) { - return false; - } - for(Block block : ev.getBlockList()) { - this.level.setBlockAt(block.getFloorX(), block.getFloorY(), block.getFloorZ(), block.getId(), block.getDamage()); - } + if (generator.generate(this.level, new NukkitRandom(), this)) { return true; } else { this.level.setBlock(this, this, true, false); @@ -91,7 +85,7 @@ public boolean grow() { public boolean canStay() { Block block = this.down(); - return block.getId() == MYCELIUM || block.getId() == PODZOL || (!block.isTransparent() && this.level.getFullLight(this) < 13); + return block.getId() == MYCELIUM || block.getId() == PODZOL || (!block.isTransparent() && this.level.getBlockLightAt((int) this.x, (int) this.y, (int) this.z) < 13); // TODO: sky/full light } @Override @@ -105,4 +99,14 @@ public boolean canSilkTouch() { } protected abstract int getType(); + + @Override + public boolean breakWhenPushed() { + return true; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } } diff --git a/src/main/java/cn/nukkit/block/BlockMushroomBrown.java b/src/main/java/cn/nukkit/block/BlockMushroomBrown.java index 5655ea13196..8ce4f00e33a 100644 --- a/src/main/java/cn/nukkit/block/BlockMushroomBrown.java +++ b/src/main/java/cn/nukkit/block/BlockMushroomBrown.java @@ -32,4 +32,4 @@ public int getLightLevel() { protected int getType() { return 0; } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockMushroomRed.java b/src/main/java/cn/nukkit/block/BlockMushroomRed.java index ce82f01a9c2..9f27cc06ca4 100644 --- a/src/main/java/cn/nukkit/block/BlockMushroomRed.java +++ b/src/main/java/cn/nukkit/block/BlockMushroomRed.java @@ -27,4 +27,4 @@ public int getId() { protected int getType() { return 1; } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockMycelium.java b/src/main/java/cn/nukkit/block/BlockMycelium.java index 358d6677130..150d3546951 100644 --- a/src/main/java/cn/nukkit/block/BlockMycelium.java +++ b/src/main/java/cn/nukkit/block/BlockMycelium.java @@ -1,23 +1,21 @@ package cn.nukkit.block; +import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.event.block.BlockSpreadEvent; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemTool; import cn.nukkit.level.Level; -import cn.nukkit.math.NukkitRandom; -import cn.nukkit.math.Vector3; +import cn.nukkit.level.Sound; import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.Utils; /** * Created by Pub4Game on 03.01.2016. */ public class BlockMycelium extends BlockSolid { - public BlockMycelium() { - } - @Override public String getName() { return "Mycelium"; @@ -53,15 +51,13 @@ public Item[] getDrops(Item item) { @Override public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_RANDOM) { - //TODO: light levels - NukkitRandom random = new NukkitRandom(); - x = random.nextRange((int) x - 1, (int) x + 1); - y = random.nextRange((int) y - 1, (int) y + 1); - z = random.nextRange((int) z - 1, (int) z + 1); - Block block = this.getLevel().getBlock(new Vector3(x, y, z)); + int xx = Utils.rand((int) x - 1, (int) x + 1); + int yy = Utils.rand((int) y - 1, (int) y + 1); + int zz = Utils.rand((int) z - 1, (int) z + 1); + Block block = this.getLevel().getBlock(xx, yy, zz); if (block.getId() == Block.DIRT && block.getDamage() == 0) { - if (block.up().isTransparent()) { - BlockSpreadEvent ev = new BlockSpreadEvent(block, this, Block.get(BlockID.MYCELIUM)); + if (block.up() instanceof BlockAir) { + BlockSpreadEvent ev = new BlockSpreadEvent(block, this, Block.get(MYCELIUM)); Server.getInstance().getPluginManager().callEvent(ev); if (!ev.isCancelled()) { this.getLevel().setBlock(block, ev.getNewState()); @@ -76,9 +72,30 @@ public int onUpdate(int type) { public BlockColor getColor() { return BlockColor.PURPLE_BLOCK_COLOR; } - + @Override public boolean canSilkTouch() { return true; } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (item.isShovel()) { + Block up = this.up(); + if (up instanceof BlockAir || up instanceof BlockFlowable) { + item.useOn(this); + this.getLevel().setBlock(this, Block.get(GRASS_PATH)); + if (player != null) { + player.getLevel().addSound(player, Sound.STEP_GRASS); + } + return true; + } + } + return false; + } } diff --git a/src/main/java/cn/nukkit/block/BlockNetherBrick.java b/src/main/java/cn/nukkit/block/BlockNetherBrick.java index ff28430572c..06e3bb942c0 100644 --- a/src/main/java/cn/nukkit/block/BlockNetherBrick.java +++ b/src/main/java/cn/nukkit/block/BlockNetherBrick.java @@ -10,9 +10,6 @@ */ public class BlockNetherBrick extends BlockSolid { - public BlockNetherBrick() { - } - @Override public String getName() { return "Nether Bricks"; @@ -40,7 +37,7 @@ public double getResistance() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; diff --git a/src/main/java/cn/nukkit/block/BlockNetherPortal.java b/src/main/java/cn/nukkit/block/BlockNetherPortal.java index b48c0ee8c7b..fbdf3af76c6 100644 --- a/src/main/java/cn/nukkit/block/BlockNetherPortal.java +++ b/src/main/java/cn/nukkit/block/BlockNetherPortal.java @@ -1,11 +1,16 @@ package cn.nukkit.block; +import cn.nukkit.Server; +import cn.nukkit.event.level.NetherPortalSpawnEvent; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.level.Level; import cn.nukkit.level.Position; +import cn.nukkit.level.format.FullChunk; import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.math.BlockFace; +import cn.nukkit.math.BlockFace.Axis; +import cn.nukkit.math.Vector3; import cn.nukkit.utils.BlockColor; import cn.nukkit.utils.Faceable; @@ -34,16 +39,6 @@ public int getId() { return NETHER_PORTAL; } - @Override - public boolean canBeFlowedInto() { - return false; - } - - @Override - public boolean canPassThrough() { - return true; - } - @Override public boolean isBreakable(Item item) { return false; @@ -64,15 +59,18 @@ public Item toItem() { return new ItemBlock(Block.get(BlockID.AIR)); } + @Override + public boolean canBeFlowedInto() { + return false; + } + @Override public boolean onBreak(Item item) { boolean result = super.onBreak(item); for (BlockFace face : BlockFace.values()) { Block b = this.getSide(face); - if (b != null) { - if (b instanceof BlockNetherPortal) { - result &= b.onBreak(item); - } + if (b instanceof BlockNetherPortal) { + result &= b.onBreak(item); } } return result; @@ -98,17 +96,234 @@ public boolean canHarvestWithHand() { return false; } + public static boolean trySpawnPortal(Level level, Vector3 pos) { + return trySpawnPortal(level, pos, false); + } + @Override protected AxisAlignedBB recalculateBoundingBox() { return this; } - public static void spawnPortal(Position pos) { + public static boolean trySpawnPortal(Level level, Vector3 pos, boolean force) { + PortalBuilder builder = new PortalBuilder(level, pos, Axis.X, force); + + if (builder.isValid() && builder.portalBlockCount == 0) { + builder.placePortalBlocks(); + return true; + } else { + builder = new PortalBuilder(level, pos, Axis.Z, force); + + if (builder.isValid() && builder.portalBlockCount == 0) { + builder.placePortalBlocks(); + return true; + } else { + return false; + } + } + } + + public static class PortalBuilder { + + private final Level level; + private final Axis axis; + private final BlockFace rightDir; + private final BlockFace leftDir; + private int portalBlockCount; + private Vector3 bottomLeft; + private int height; + private int width; + + private final boolean force; + + public PortalBuilder(Level level, Vector3 pos, Axis axis, boolean force) { + this.level = level; + this.axis = axis; + this.force = force; + + if (axis == Axis.X) { + this.leftDir = BlockFace.EAST; + this.rightDir = BlockFace.WEST; + } else { + this.leftDir = BlockFace.NORTH; + this.rightDir = BlockFace.SOUTH; + } + + + for (Vector3 blockpos = pos; pos.getY() > blockpos.getY() - 21 && pos.getY() > level.getMinBlockY() && this.isEmptyBlock(getBlockId(pos.getSideVec(BlockFace.DOWN))); pos = pos.getSideVec(BlockFace.DOWN)) { + } + + int i = this.getDistanceUntilEdge(pos, this.leftDir) - 1; + + if (i >= 0) { + this.bottomLeft = pos.getSideVec(this.leftDir, i); + this.width = this.getDistanceUntilEdge(this.bottomLeft, this.rightDir); + + if (this.width < 2 || this.width > 21) { + this.bottomLeft = null; + this.width = 0; + } + } + + if (this.bottomLeft != null) { + this.height = this.calculatePortalHeight(); + } + } + + protected int getDistanceUntilEdge(Vector3 pos, BlockFace dir) { + int i; + + for (i = 0; i < 22; ++i) { + Vector3 v = pos.getSideVec(dir, i); + + if (!this.isEmptyBlock(getBlockId(v)) || getBlockId(v.getSideVec(BlockFace.DOWN)) != OBSIDIAN) { + break; + } + } + + return getBlockId(pos.getSideVec(dir, i)) == OBSIDIAN ? i : 0; + } + + public int getHeight() { + return this.height; + } + + public int getWidth() { + return this.width; + } + + protected int calculatePortalHeight() { + + loop: + for (this.height = 0; this.height < 21; ++this.height) { + for (int i = 0; i < this.width; ++i) { + Vector3 blockpos = this.bottomLeft.getSideVec(this.rightDir, i).up(this.height); + int block = getBlockId(blockpos); + + if (!this.isEmptyBlock(block)) { + break loop; + } + + if (block == NETHER_PORTAL) { + ++this.portalBlockCount; + } + + if (i == 0) { + block = getBlockId(blockpos.getSideVec(this.leftDir)); + + if (block != OBSIDIAN) { + break loop; + } + } else if (i == this.width - 1) { + block = getBlockId(blockpos.getSideVec(this.rightDir)); + + if (block != OBSIDIAN) { + break loop; + } + } + } + } + + for (int i = 0; i < this.width; ++i) { + if (getBlockId(this.bottomLeft.getSideVec(this.rightDir, i).up(this.height)) != OBSIDIAN) { + this.height = 0; + break; + } + } + + if (this.height <= 21 && this.height >= 3) { + return this.height; + } else { + this.bottomLeft = null; + this.width = 0; + this.height = 0; + return 0; + } + } + + private int getBlockId(Vector3 pos) { + return this.level.getBlockIdAt(pos.getFloorX(), pos.getFloorY(), pos.getFloorZ()); + } + + protected boolean isEmptyBlock(int id) { + return force || id == AIR || id == FIRE || id == NETHER_PORTAL; + } + + public boolean isValid() { + return this.bottomLeft != null && this.width >= 2 && this.width <= 21 && this.height >= 3 && this.height <= 21; + } + + public void placePortalBlocks() { + for (int i = 0; i < this.width; ++i) { + Vector3 blockpos = this.bottomLeft.getSideVec(this.rightDir, i); + + for (int j = 0; j < this.height; ++j) { + this.level.setBlock(blockpos.up(j), Block.get(NETHER_PORTAL, this.axis == Axis.X ? 1 : this.axis == Axis.Z ? 2 : 0)); + } + } + } + } + + public static Position getSafePortal(Position portal) { + Level level = portal.getLevel(); + FullChunk chunk = portal.getChunk(); + Vector3 down = portal.getSideVec(BlockFace.DOWN); + + while (level.getBlockIdAt(chunk, down.getFloorX(), down.getFloorY(), down.getFloorZ()) == NETHER_PORTAL) { + down = down.getSideVec(BlockFace.DOWN); + } + + return Position.fromObject(down.up(), portal.getLevel()); + } + + public static Position findNearestPortal(Position pos) { + Level level = pos.getLevel(); + Position found = null; + int maxY = level.getMaxBlockY(); + + for (int xx = -16; xx <= 16; xx++) { + for (int zz = -16; zz <= 16; zz++) { + for (int y = 0; y < maxY; y++) { + int x = pos.getFloorX() + xx, z = pos.getFloorZ() + zz; + if (level.getBlockIdAt(x, y, z) == NETHER_PORTAL) { + found = new Position(x, y, z, level); + break; + } + } + } + } + + if (found == null) { + return null; + } + Vector3 up = found.up(); + int x = up.getFloorX(), y = up.getFloorY(), z = up.getFloorZ(); + int id = level.getBlockIdAt(x, y, z); + if (id != AIR && id != OBSIDIAN && id != NETHER_PORTAL) { + for (int xx = -1; xx < 4; xx++) { + for (int yy = 1; yy < 4; yy++) { + for (int zz = -1; zz < 3; zz++) { + level.setBlockAt(x + xx, y + yy, z + zz, AIR); + } + } + } + } + return found; + } + + public static void spawnPortal(Position pos) { + NetherPortalSpawnEvent ev = new NetherPortalSpawnEvent(pos); + Server.getInstance().getPluginManager().callEvent(ev); + + if (ev.isCancelled()) { + return; + } + Level lvl = pos.level; int x = pos.getFloorX(), y = pos.getFloorY(), z = pos.getFloorZ(); for (int xx = -1; xx < 4; xx++) { - for (int yy = 1; yy < 4; yy++) { + for (int yy = 1; yy < 4; yy++) { for (int zz = -1; zz < 3; zz++) { lvl.setBlockAt(x + xx, y + yy, z + zz, AIR); } @@ -156,6 +371,6 @@ public static void spawnPortal(Position pos) { @Override public BlockFace getBlockFace() { - return BlockFace.fromHorizontalIndex(this.getDamage() & 0x07); + return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); } } diff --git a/src/main/java/cn/nukkit/block/BlockNetherReactor.java b/src/main/java/cn/nukkit/block/BlockNetherReactor.java new file mode 100644 index 00000000000..30bb6702f01 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockNetherReactor.java @@ -0,0 +1,44 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; + +public class BlockNetherReactor extends BlockSolid { + + @Override + public int getId() { + return NETHER_REACTOR; + } + + @Override + public String getName() { + return "Nether Reactor Core"; + } + + @Override + public double getHardness() { + return 3; + } + + @Override + public double getResistance() { + return 15; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public Item[] getDrops(Item item) { + if (item.isPickaxe()) { + return new Item[]{Item.get(Item.DIAMOND, 0, 3), Item.get(Item.IRON_INGOT, 0, 6)}; + } else return new Item[0]; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockNetherSprouts.java b/src/main/java/cn/nukkit/block/BlockNetherSprouts.java new file mode 100644 index 00000000000..b695f1cd9db --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockNetherSprouts.java @@ -0,0 +1,54 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockNetherSprouts extends BlockRoots { + + public BlockNetherSprouts() { + this(0); + } + + public BlockNetherSprouts(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Nether Sprouts"; + } + + @Override + public int getId() { + return NETHER_SPROUTS_BLOCK; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_SHEARS; + } + + @Override + public Item toItem() { + return Item.get(Item.NETHER_SPROUTS); + } + + @Override + public BlockColor getColor() { + return BlockColor.CYAN_BLOCK_COLOR; + } + + @Override + public Item[] getDrops(Item item) { + if (item.isShears()) { + return new Item[]{ toItem() }; + } + return new Item[0]; + } + + @Override + public boolean canBeReplaced() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockNetherWart.java b/src/main/java/cn/nukkit/block/BlockNetherWart.java index f286e4f96b1..502cd7baad2 100644 --- a/src/main/java/cn/nukkit/block/BlockNetherWart.java +++ b/src/main/java/cn/nukkit/block/BlockNetherWart.java @@ -4,12 +4,10 @@ import cn.nukkit.Server; import cn.nukkit.event.block.BlockGrowEvent; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemNetherWart; import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; import cn.nukkit.utils.BlockColor; - -import java.util.Random; +import cn.nukkit.utils.Utils; /** * Created by Leonidius20 on 22.03.17. @@ -42,9 +40,9 @@ public int onUpdate(int type) { return Level.BLOCK_UPDATE_NORMAL; } } else if (type == Level.BLOCK_UPDATE_RANDOM) { - if (new Random().nextInt(10) == 1) { + if (Utils.random.nextInt(10) == 1) { if (this.getDamage() < 0x03) { - BlockNetherWart block = (BlockNetherWart) this.clone(); + Block block = this.clone(); block.setDamage(block.getDamage() + 1); BlockGrowEvent ev = new BlockGrowEvent(this, block); Server.getInstance().getPluginManager().callEvent(ev); @@ -65,7 +63,7 @@ public int onUpdate(int type) { @Override public BlockColor getColor() { - return BlockColor.RED_BLOCK_COLOR; + return BlockColor.FOLIAGE_BLOCK_COLOR; } @Override @@ -82,19 +80,22 @@ public int getId() { public Item[] getDrops(Item item) { if (this.getDamage() == 0x03) { return new Item[]{ - new ItemNetherWart(0, 2 + (int) (Math.random() * ((4 - 2) + 1))) + Item.get(Item.NETHER_WART, 0, 2 + (int) (Math.random() * (3))) }; } else { return new Item[]{ - new ItemNetherWart() + Item.get(Item.NETHER_WART) }; } } @Override public Item toItem() { - return new ItemNetherWart(); + return Item.get(Item.NETHER_WART); } -} - + @Override + public boolean breakWhenPushed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockNetherWartBlock.java b/src/main/java/cn/nukkit/block/BlockNetherWartBlock.java index 0edaf1cb54b..d20ed238ea0 100644 --- a/src/main/java/cn/nukkit/block/BlockNetherWartBlock.java +++ b/src/main/java/cn/nukkit/block/BlockNetherWartBlock.java @@ -1,13 +1,11 @@ package cn.nukkit.block; import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; import cn.nukkit.utils.BlockColor; public class BlockNetherWartBlock extends BlockSolid { - public BlockNetherWartBlock() { - } - @Override public String getName() { return "Nether Wart Block"; @@ -20,7 +18,7 @@ public int getId() { @Override public double getResistance() { - return 5; + return 1; } @Override @@ -39,4 +37,9 @@ public Item[] getDrops(Item item) { public BlockColor getColor() { return BlockColor.RED_BLOCK_COLOR; } + + @Override + public int getToolType() { + return ItemTool.TYPE_HOE; + } } diff --git a/src/main/java/cn/nukkit/block/BlockNetheriteBlock.java b/src/main/java/cn/nukkit/block/BlockNetheriteBlock.java new file mode 100644 index 00000000000..7c68f12c7c8 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockNetheriteBlock.java @@ -0,0 +1,45 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockNetheriteBlock extends BlockSolid { + + public BlockNetheriteBlock() { + } + + @Override + public int getId() { + return NETHERITE_BLOCK; + } + + @Override + public String getName() { + return "Netherite Block"; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public double getHardness() { + return 35; + } + + @Override + public double getResistance() { + return 6000; + } + + @Override + public BlockColor getColor() { + return BlockColor.BLACK_BLOCK_COLOR; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockNetherrack.java b/src/main/java/cn/nukkit/block/BlockNetherrack.java index 8417aaa474e..2043e7dd363 100644 --- a/src/main/java/cn/nukkit/block/BlockNetherrack.java +++ b/src/main/java/cn/nukkit/block/BlockNetherrack.java @@ -10,9 +10,6 @@ */ public class BlockNetherrack extends BlockSolid { - public BlockNetherrack() { - } - @Override public int getId() { return NETHERRACK; @@ -40,7 +37,7 @@ public String getName() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; @@ -58,5 +55,4 @@ public BlockColor getColor() { public boolean canHarvestWithHand() { return false; } - } diff --git a/src/main/java/cn/nukkit/block/BlockNoteblock.java b/src/main/java/cn/nukkit/block/BlockNoteblock.java index 66c304992c6..848a42d920f 100644 --- a/src/main/java/cn/nukkit/block/BlockNoteblock.java +++ b/src/main/java/cn/nukkit/block/BlockNoteblock.java @@ -18,10 +18,6 @@ */ public class BlockNoteblock extends BlockSolid { - public BlockNoteblock() { - - } - @Override public String getName() { return "Note Block"; @@ -55,7 +51,8 @@ public boolean canBeActivated() { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { this.getLevel().setBlock(block, this, true); - return this.createBlockEntity() != null; + BlockEntity.createBlockEntity(BlockEntity.MUSIC, this.getChunk(), BlockEntity.getDefaultCompound(this, BlockEntity.MUSIC)); + return true; } public int getStrength() { @@ -203,6 +200,7 @@ public Instrument getInstrument() { case CONCRETE: case STONECUTTER: case OBSERVER: + case RESPAWN_ANCHOR: return Instrument.BASS_DRUM; default: return Instrument.PIANO; @@ -210,7 +208,9 @@ public Instrument getInstrument() { } public void emitSound() { - if (this.up().getId() != AIR) return; + if (this.level.getBlockIdAt((int) this.x, (int) this.y + 1, (int) this.z) != AIR) { + return; + } Instrument instrument = this.getInstrument(); @@ -222,11 +222,12 @@ public void emitSound() { pk.z = this.getFloorZ(); pk.case1 = instrument.ordinal(); pk.case2 = this.getStrength(); - this.getLevel().addChunkPacket(this.getFloorX() >> 4, this.getFloorZ() >> 4, pk); + this.getLevel().addChunkPacket(this.getChunkX(), this.getChunkZ(), pk); } @Override public boolean onActivate(Item item, Player player) { + if (player.sneakToBlockInteract()) return false; this.increaseStrength(); this.emitSound(); return true; @@ -258,11 +259,6 @@ private BlockEntityMusic getBlockEntity() { return null; } - private BlockEntityMusic createBlockEntity() { - return (BlockEntityMusic) BlockEntity.createBlockEntity(BlockEntity.MUSIC, this.getLevel().getChunk(this.getFloorX() >> 4, this.getFloorZ() >> 4), - BlockEntity.getDefaultCompound(this, BlockEntity.MUSIC)); - } - public enum Instrument { PIANO(Sound.NOTE_HARP), BASS_DRUM(Sound.NOTE_BD), @@ -296,4 +292,9 @@ public Sound getSound() { public BlockColor getColor() { return BlockColor.WOOD_BLOCK_COLOR; } -} + + @Override + public boolean canBePushed() { + return false; // prevent item loss issue with pistons until a working implementation + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockNylium.java b/src/main/java/cn/nukkit/block/BlockNylium.java new file mode 100644 index 00000000000..f58cdd2bd38 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockNylium.java @@ -0,0 +1,59 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; +import cn.nukkit.level.Level; + +public abstract class BlockNylium extends BlockSolid { + + public BlockNylium() { + // Does nothing + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_RANDOM && !up().isTransparent()) { + level.setBlock(this, Block.get(NETHERRACK), false); + return type; + } + return 0; + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public double getResistance() { + return 0.4; + } + + @Override + public double getHardness() { + return 0.4; + } + + @Override + public Item[] getDrops(Item item) { + if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + return new Item[]{ Item.get(NETHERRACK) }; + } + return new Item[0]; + } + + @Override + public boolean canSilkTouch() { + return true; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockObserver.java b/src/main/java/cn/nukkit/block/BlockObserver.java index f2d1855b4bc..3841dbf966e 100644 --- a/src/main/java/cn/nukkit/block/BlockObserver.java +++ b/src/main/java/cn/nukkit/block/BlockObserver.java @@ -1,16 +1,22 @@ package cn.nukkit.block; import cn.nukkit.Player; +import cn.nukkit.event.redstone.RedstoneUpdateEvent; import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemTool; +import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; +import cn.nukkit.math.Vector3; import cn.nukkit.utils.Faceable; -/** - * Created by Leonidius20 on 18.08.18. - */ public class BlockObserver extends BlockSolidMeta implements Faceable { + /** + * Where the block update happens. Used to check whether this observer should detect it. + */ + private Vector3 updatePos; + public BlockObserver() { this(0); } @@ -19,21 +25,53 @@ public BlockObserver(int meta) { super(meta); } + @Override + public int getId() { + return OBSERVER; + } + @Override public String getName() { return "Observer"; } @Override - public int getId() { - return OBSERVER; + public double getHardness() { + return 3.5; + } + + @Override + public double getResistance() { + return 17.5; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public Item[] getDrops(Item item) { + if (item.isPickaxe()) { + return new Item[]{ + Item.get(Item.OBSERVER, 0, 1) + }; + } else { + return new Item[0]; + } + } + + @Override + public boolean canHarvestWithHand() { + return false; } @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { if (player != null) { - if (Math.abs(player.getFloorX() - this.x) <= 1 && Math.abs(player.getFloorZ() - this.z) <= 1) { + if (Math.abs(player.x - this.x) < 2 && Math.abs(player.z - this.z) < 2) { double y = player.y + player.getEyeHeight(); + if (y - this.y > 2) { this.setDamage(BlockFace.DOWN.getIndex()); } else if (this.y - y > 0) { @@ -44,36 +82,73 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl } else { this.setDamage(player.getHorizontalFacing().getIndex()); } - } else { - this.setDamage(0); } - this.getLevel().setBlock(block, this, true, true); - return true; + + return this.getLevel().setBlock(this, this, true, true); } @Override - public boolean canHarvestWithHand() { - return false; + public BlockFace getBlockFace() { + return BlockFace.fromIndex(this.getDamage() & 0x07); } @Override - public int getToolType() { - return ItemTool.TYPE_PICKAXE; + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL && this.getSideVec(this.getBlockFace()).equals(this.updatePos) && !this.isPowered()) { + RedstoneUpdateEvent ev = new RedstoneUpdateEvent(this); + this.level.getServer().getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + return 0; + } + this.setPowered(true); + this.level.setBlock(this, this, false, false); + this.level.updateAroundRedstone(this, this.getBlockFace()); + level.scheduleUpdate(this, 4); + return Level.BLOCK_UPDATE_NORMAL; + } else if (type == Level.BLOCK_UPDATE_SCHEDULED && this.isPowered()) { + RedstoneUpdateEvent ev = new RedstoneUpdateEvent(this); + this.level.getServer().getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + return 0; + } + this.setPowered(false); + this.level.setBlock(this, this, false, false); + this.level.updateAroundRedstone(this, this.getBlockFace()); + } + return type; } @Override - public double getHardness() { - return 3.5; + public Item toItem() { + return new ItemBlock(Block.get(Block.OBSERVER)); } @Override - public double getResistance() { - return 17.5; + public boolean isPowerSource() { + return true; } @Override - public BlockFace getBlockFace() { - return BlockFace.fromHorizontalIndex(this.getDamage() & 0x07); + public int getStrongPower(BlockFace side) { + return this.isPowered() && side == this.getBlockFace() ? 15 : 0; + } + + @Override + public int getWeakPower(BlockFace face) { + return this.getStrongPower(face); + } + + public boolean isPowered() { + return (this.getDamage() & 0x8) == 0x8; } + public void setPowered(boolean powered) { + this.setDamage((this.getDamage() & 0x7) | (powered ? 0x8 : 0x0)); + } + + @Override + public Block setUpdatePos(Vector3 pos) { + this.updatePos = pos; + return this; + } } diff --git a/src/main/java/cn/nukkit/block/BlockObsidian.java b/src/main/java/cn/nukkit/block/BlockObsidian.java index 7ac74925ae3..cca7e15cff0 100644 --- a/src/main/java/cn/nukkit/block/BlockObsidian.java +++ b/src/main/java/cn/nukkit/block/BlockObsidian.java @@ -10,9 +10,6 @@ */ public class BlockObsidian extends BlockSolid { - public BlockObsidian() { - } - @Override public String getName() { return "Obsidian"; @@ -30,7 +27,7 @@ public int getToolType() { @Override public double getHardness() { - return 35; //50 in PC + return 35; } @Override @@ -52,7 +49,7 @@ public Item[] getDrops(Item item) { @Override public boolean onBreak(Item item) { //destroy the nether portal - Block[] nearby = new Block[]{ + Block[] nearby = { this.up(), this.down(), this.north(), south(), this.west(), this.east(), diff --git a/src/main/java/cn/nukkit/block/BlockObsidianCrying.java b/src/main/java/cn/nukkit/block/BlockObsidianCrying.java new file mode 100644 index 00000000000..84fd9177d13 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockObsidianCrying.java @@ -0,0 +1,63 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockObsidianCrying extends BlockSolid { + + @Override + public int getId() { + return CRYING_OBSIDIAN; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public String getName() { + return "Crying Obsidian"; + } + + @Override + public double getHardness() { + return 35; + } + + @Override + public double getResistance() { + return 1200; + } + @Override + public Item[] getDrops(Item item) { + if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_DIAMOND) { + return new Item[]{ + toItem() + }; + } else { + return new Item[0]; + } + } + + @Override + public int getLightLevel() { + return 10; + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public BlockColor getColor() { + return BlockColor.OBSIDIAN_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockObsidianGlowing.java b/src/main/java/cn/nukkit/block/BlockObsidianGlowing.java index 8b57354b0e5..2797560fd03 100644 --- a/src/main/java/cn/nukkit/block/BlockObsidianGlowing.java +++ b/src/main/java/cn/nukkit/block/BlockObsidianGlowing.java @@ -3,6 +3,7 @@ import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; /** * Created on 2015/11/22 by xtypr. @@ -10,47 +11,49 @@ */ public class BlockObsidianGlowing extends BlockSolid { - public BlockObsidianGlowing() { - } - @Override public int getId() { return GLOWING_OBSIDIAN; } @Override - public int getToolType() { - return ItemTool.TYPE_PICKAXE; + public String getName() { + return "Glowing Obsidian"; } @Override - public String getName() { - return "Glowing Obsidian"; + public int getLightLevel() { + return 12; } @Override - public double getHardness() { - return 50; + public Item toItem() { + return new ItemBlock(Block.get(GLOWING_OBSIDIAN)); } @Override - public double getResistance() { - return 6000; + public boolean onBreak(Item item) { + return this.getLevel().setBlock(this, Block.get(BlockID.AIR), true, true); } @Override - public int getLightLevel() { - return 12; + public int getToolType() { + return ItemTool.TYPE_PICKAXE; } @Override - public Item toItem() { - return new ItemBlock(Block.get(BlockID.OBSIDIAN)); + public double getHardness() { + return 12; //? + } + + @Override + public double getResistance() { + return 6000; } @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() > ItemTool.DIAMOND_PICKAXE) { + if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_DIAMOND) { return new Item[]{ toItem() }; @@ -59,6 +62,11 @@ public Item[] getDrops(Item item) { } } + @Override + public BlockColor getColor() { + return BlockColor.OBSIDIAN_BLOCK_COLOR; + } + @Override public boolean canBePushed() { return false; diff --git a/src/main/java/cn/nukkit/block/BlockOre.java b/src/main/java/cn/nukkit/block/BlockOre.java new file mode 100644 index 00000000000..ea25e4fc42e --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockOre.java @@ -0,0 +1,82 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.math.NukkitMath; + +import java.util.concurrent.ThreadLocalRandom; + +public abstract class BlockOre extends BlockSolid { + + public BlockOre() { + } + + @Override + public Item[] getDrops(Item item) { + if (!this.canHarvest(item) || item.getTier() < this.getToolTier()) { + return new Item[0]; + } + + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; + } + + int rawMaterial = this.getRawMaterial(); + if (rawMaterial == BlockID.AIR) { + return super.getDrops(item); + } + + float multiplier = this.getDropMultiplier(); + int amount = (int) multiplier; + if (amount > 1) { + amount = 1 + ThreadLocalRandom.current().nextInt(amount); + } + int fortuneLevel = NukkitMath.clamp(item.getEnchantmentLevel(Enchantment.ID_FORTUNE_DIGGING), 0, 3); + if (fortuneLevel > 0) { + int increase = ThreadLocalRandom.current().nextInt((int)(multiplier * fortuneLevel) + 1); + amount += increase; + } + return new Item[]{ Item.get(rawMaterial, this.getRawMaterialMeta(), amount) }; + } + + protected abstract int getRawMaterial(); + + protected int getRawMaterialMeta() { + return 0; + } + + protected float getDropMultiplier() { + return 1; + } + + @Override + public boolean canSilkTouch() { + return true; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_STONE; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public double getHardness() { + return 3; + } + + @Override + public double getResistance() { + return 3; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockOreCoal.java b/src/main/java/cn/nukkit/block/BlockOreCoal.java index e7ea88dd02d..1f7216f1707 100644 --- a/src/main/java/cn/nukkit/block/BlockOreCoal.java +++ b/src/main/java/cn/nukkit/block/BlockOreCoal.java @@ -1,23 +1,16 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemCoal; import cn.nukkit.item.ItemTool; import cn.nukkit.item.enchantment.Enchantment; -import cn.nukkit.math.NukkitRandom; -import cn.nukkit.utils.BlockColor; - -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockOreCoal extends BlockSolid { - public BlockOreCoal() { - } - @Override public int getId() { return COAL_ORE; @@ -30,7 +23,7 @@ public double getHardness() { @Override public double getResistance() { - return 15; + return 3; } @Override @@ -45,11 +38,15 @@ public String getName() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; + } + int count = 1; Enchantment fortune = item.getEnchantment(Enchantment.ID_FORTUNE_DIGGING); if (fortune != null && fortune.getLevel() >= 1) { - int i = ThreadLocalRandom.current().nextInt(fortune.getLevel() + 2) - 1; + int i = Utils.random.nextInt(fortune.getLevel() + 2) - 1; if (i < 0) { i = 0; @@ -59,7 +56,7 @@ public Item[] getDrops(Item item) { } return new Item[]{ - new ItemCoal(0, count) + Item.get(Item.COAL, 0, count) }; } else { return new Item[0]; @@ -68,21 +65,16 @@ public Item[] getDrops(Item item) { @Override public int getDropExp() { - return new NukkitRandom().nextRange(0, 2); + return Utils.rand(0, 2); } @Override public boolean canHarvestWithHand() { return false; } - + @Override public boolean canSilkTouch() { return true; } - - @Override - public BlockColor getColor() { - return BlockColor.BLACK_BLOCK_COLOR; - } } diff --git a/src/main/java/cn/nukkit/block/BlockOreCoalDeepslate.java b/src/main/java/cn/nukkit/block/BlockOreCoalDeepslate.java new file mode 100644 index 00000000000..0d71042547a --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockOreCoalDeepslate.java @@ -0,0 +1,41 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemID; +import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.Utils; + +public class BlockOreCoalDeepslate extends BlockOre { + + public BlockOreCoalDeepslate() { + } + + @Override + protected int getRawMaterial() { + return ItemID.COAL; + } + + @Override + public int getId() { + return DEEPSLATE_COAL_ORE; + } + + @Override + public double getHardness() { + return 4.5; + } + + @Override + public String getName() { + return "Deepslate Coal Ore"; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } + + @Override + public int getDropExp() { + return Utils.rand(0, 2); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockOreCopper.java b/src/main/java/cn/nukkit/block/BlockOreCopper.java new file mode 100644 index 00000000000..c538a855257 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockOreCopper.java @@ -0,0 +1,36 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemID; +import cn.nukkit.utils.Utils; + +public class BlockOreCopper extends BlockOre { + + public BlockOreCopper() { + // Does nothing + } + + @Override + public String getName() { + return "Copper Ore"; + } + + @Override + public int getId() { + return COPPER_ORE; + } + + @Override + protected int getRawMaterial() { + return ItemID.RAW_COPPER; + } + + @Override + protected float getDropMultiplier() { + return 3; + } + + @Override + public int getDropExp() { + return Utils.rand(0, 2); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockOreCopperDeepslate.java b/src/main/java/cn/nukkit/block/BlockOreCopperDeepslate.java new file mode 100644 index 00000000000..2da6a62e90a --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockOreCopperDeepslate.java @@ -0,0 +1,30 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockOreCopperDeepslate extends BlockOreCopper { + + public BlockOreCopperDeepslate() { + // Does nothing + } + + @Override + public String getName() { + return "Deepslate Copper Ore"; + } + + @Override + public int getId() { + return DEEPSLATE_COPPER_ORE; + } + + @Override + public double getHardness() { + return 4.5; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockOreDiamond.java b/src/main/java/cn/nukkit/block/BlockOreDiamond.java index d284ad98a6a..6d0d75d97cf 100644 --- a/src/main/java/cn/nukkit/block/BlockOreDiamond.java +++ b/src/main/java/cn/nukkit/block/BlockOreDiamond.java @@ -1,23 +1,16 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemDiamond; import cn.nukkit.item.ItemTool; import cn.nukkit.item.enchantment.Enchantment; -import cn.nukkit.math.NukkitRandom; - -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockOreDiamond extends BlockSolid { - - public BlockOreDiamond() { - } - @Override public int getId() { return DIAMOND_ORE; @@ -30,7 +23,7 @@ public double getHardness() { @Override public double getResistance() { - return 15; + return 3; } @Override @@ -46,10 +39,14 @@ public String getName() { @Override public Item[] getDrops(Item item) { if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_IRON) { + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; + } + int count = 1; Enchantment fortune = item.getEnchantment(Enchantment.ID_FORTUNE_DIGGING); if (fortune != null && fortune.getLevel() >= 1) { - int i = ThreadLocalRandom.current().nextInt(fortune.getLevel() + 2) - 1; + int i = Utils.random.nextInt(fortune.getLevel() + 2) - 1; if (i < 0) { i = 0; @@ -59,7 +56,7 @@ public Item[] getDrops(Item item) { } return new Item[]{ - new ItemDiamond(0, count) + Item.get(Item.DIAMOND, 0, count) }; } else { return new Item[0]; @@ -68,14 +65,14 @@ public Item[] getDrops(Item item) { @Override public int getDropExp() { - return new NukkitRandom().nextRange(3, 7); + return Utils.rand(3, 7); } @Override public boolean canHarvestWithHand() { return false; } - + @Override public boolean canSilkTouch() { return true; diff --git a/src/main/java/cn/nukkit/block/BlockOreDiamondDeepslate.java b/src/main/java/cn/nukkit/block/BlockOreDiamondDeepslate.java new file mode 100644 index 00000000000..c14504c25ab --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockOreDiamondDeepslate.java @@ -0,0 +1,47 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemID; +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.Utils; + +public class BlockOreDiamondDeepslate extends BlockOre { + + public BlockOreDiamondDeepslate() { + } + + @Override + protected int getRawMaterial() { + return ItemID.DIAMOND; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_IRON; + } + + @Override + public int getId() { + return DEEPSLATE_DIAMOND_ORE; + } + + @Override + public double getHardness() { + return 4.5; + } + + @Override + public String getName() { + return "Deepslate Diamond Ore"; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } + + @Override + public int getDropExp() { + return Utils.rand(3, 7); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockOreEmerald.java b/src/main/java/cn/nukkit/block/BlockOreEmerald.java index 65c8d0e34f1..c9f1d3d3426 100644 --- a/src/main/java/cn/nukkit/block/BlockOreEmerald.java +++ b/src/main/java/cn/nukkit/block/BlockOreEmerald.java @@ -1,12 +1,9 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemEmerald; import cn.nukkit.item.ItemTool; import cn.nukkit.item.enchantment.Enchantment; -import cn.nukkit.math.NukkitRandom; - -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; /** * Created on 2015/12/1 by xtypr. @@ -14,9 +11,6 @@ */ public class BlockOreEmerald extends BlockSolid { - public BlockOreEmerald() { - } - @Override public String getName() { return "Emerald Ore"; @@ -39,16 +33,20 @@ public double getHardness() { @Override public double getResistance() { - return 15; + return 3; } @Override public Item[] getDrops(Item item) { if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_IRON) { + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; + } + int count = 1; Enchantment fortune = item.getEnchantment(Enchantment.ID_FORTUNE_DIGGING); if (fortune != null && fortune.getLevel() >= 1) { - int i = ThreadLocalRandom.current().nextInt(fortune.getLevel() + 2) - 1; + int i = Utils.random.nextInt(fortune.getLevel() + 2) - 1; if (i < 0) { i = 0; @@ -58,7 +56,7 @@ public Item[] getDrops(Item item) { } return new Item[]{ - new ItemEmerald(0, count) + Item.get(Item.EMERALD, 0, count) }; } else { return new Item[0]; @@ -67,14 +65,14 @@ public Item[] getDrops(Item item) { @Override public int getDropExp() { - return new NukkitRandom().nextRange(3, 7); + return Utils.rand(3, 7); } @Override public boolean canHarvestWithHand() { return false; } - + @Override public boolean canSilkTouch() { return true; diff --git a/src/main/java/cn/nukkit/block/BlockOreEmeraldDeepslate.java b/src/main/java/cn/nukkit/block/BlockOreEmeraldDeepslate.java new file mode 100644 index 00000000000..aa374976d5f --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockOreEmeraldDeepslate.java @@ -0,0 +1,47 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemID; +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.Utils; + +public class BlockOreEmeraldDeepslate extends BlockOre { + + public BlockOreEmeraldDeepslate() { + } + + @Override + protected int getRawMaterial() { + return ItemID.EMERALD; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_IRON; + } + + @Override + public int getId() { + return DEEPSLATE_EMERALD_ORE; + } + + @Override + public double getHardness() { + return 4.5; + } + + @Override + public String getName() { + return "Deepslate Emerald Ore"; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } + + @Override + public int getDropExp() { + return Utils.rand(3, 7); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockOreGold.java b/src/main/java/cn/nukkit/block/BlockOreGold.java index fb80d03b712..e74bda7bc3c 100644 --- a/src/main/java/cn/nukkit/block/BlockOreGold.java +++ b/src/main/java/cn/nukkit/block/BlockOreGold.java @@ -1,16 +1,12 @@ package cn.nukkit.block; -import cn.nukkit.item.Item; -import cn.nukkit.item.ItemTool; +import cn.nukkit.item.ItemID; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ -public class BlockOreGold extends BlockSolid { - - public BlockOreGold() { - } +public class BlockOreGold extends BlockOre { @Override public int getId() { @@ -18,38 +14,12 @@ public int getId() { } @Override - public double getHardness() { - return 3; - } - - @Override - public double getResistance() { - return 15; - } - - @Override - public int getToolType() { - return ItemTool.TYPE_PICKAXE; + protected int getRawMaterial() { + return ItemID.RAW_GOLD; } @Override public String getName() { return "Gold Ore"; } - - @Override - public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_IRON) { - return new Item[]{ - Item.get(GOLD_ORE) - }; - } else { - return new Item[0]; - } - } - - @Override - public boolean canHarvestWithHand() { - return false; - } } diff --git a/src/main/java/cn/nukkit/block/BlockOreGoldDeepslate.java b/src/main/java/cn/nukkit/block/BlockOreGoldDeepslate.java new file mode 100644 index 00000000000..ca85c573b5c --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockOreGoldDeepslate.java @@ -0,0 +1,41 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemID; +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockOreGoldDeepslate extends BlockOre { + + public BlockOreGoldDeepslate() { + } + + @Override + protected int getRawMaterial() { + return ItemID.RAW_GOLD; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_IRON; + } + + @Override + public int getId() { + return DEEPSLATE_GOLD_ORE; + } + + @Override + public double getHardness() { + return 4.5; + } + + @Override + public String getName() { + return "Deepslate Gold Ore"; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockOreGoldNether.java b/src/main/java/cn/nukkit/block/BlockOreGoldNether.java new file mode 100644 index 00000000000..d6df72b9ed8 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockOreGoldNether.java @@ -0,0 +1,90 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.utils.BlockColor; + +import java.util.concurrent.ThreadLocalRandom; + +public class BlockOreGoldNether extends BlockSolid { + + @Override + public int getId() { + return NETHER_GOLD_ORE; + } + + @Override + public double getHardness() { + return 3; + } + + @Override + public double getResistance() { + return 3; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public String getName() { + return "Nether Gold Ore"; + } + + @Override + public Item[] getDrops(Item item) { + if (!item.isPickaxe()) { + return new Item[0]; + } + + Enchantment enchantment = item.getEnchantment(Enchantment.ID_FORTUNE_DIGGING); + int fortune = 0; + if (enchantment != null) { + fortune = enchantment.getLevel(); + } + + ThreadLocalRandom random = ThreadLocalRandom.current(); + int count = random.nextInt(2, 7); + switch (fortune) { + case 0: + // Does nothing + break; + case 1: + if (random.nextInt(0, 2) == 0) { + count *= 2; + } + break; + case 2: + if (random.nextInt(0, 1) == 0) { + count *= random.nextInt(2, 3); + } + break; + default: + case 3: + if (random.nextInt(0, 4) < 3) { + count *= random.nextInt(2, 4); + } + break; + } + + return new Item[]{ Item.get(Item.GOLD_NUGGET, 0, count) }; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public boolean canSilkTouch() { + return true; + } + + @Override + public BlockColor getColor() { + return BlockColor.NETHERRACK_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockOreIron.java b/src/main/java/cn/nukkit/block/BlockOreIron.java index 27fcc2c5284..93e783aec64 100644 --- a/src/main/java/cn/nukkit/block/BlockOreIron.java +++ b/src/main/java/cn/nukkit/block/BlockOreIron.java @@ -1,17 +1,12 @@ package cn.nukkit.block; -import cn.nukkit.item.Item; -import cn.nukkit.item.ItemTool; +import cn.nukkit.item.ItemID; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ -public class BlockOreIron extends BlockSolid { - - - public BlockOreIron() { - } +public class BlockOreIron extends BlockOre { @Override public int getId() { @@ -19,38 +14,12 @@ public int getId() { } @Override - public double getHardness() { - return 3; - } - - @Override - public double getResistance() { - return 5; - } - - @Override - public int getToolType() { - return ItemTool.TYPE_PICKAXE; + protected int getRawMaterial() { + return ItemID.RAW_IRON; } @Override public String getName() { return "Iron Ore"; } - - @Override - public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_STONE) { - return new Item[]{ - Item.get(IRON_ORE) - }; - } else { - return new Item[0]; - } - } - - @Override - public boolean canHarvestWithHand() { - return false; - } } diff --git a/src/main/java/cn/nukkit/block/BlockOreIronDeepslate.java b/src/main/java/cn/nukkit/block/BlockOreIronDeepslate.java new file mode 100644 index 00000000000..459b66be921 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockOreIronDeepslate.java @@ -0,0 +1,35 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemID; +import cn.nukkit.utils.BlockColor; + +public class BlockOreIronDeepslate extends BlockOre { + + public BlockOreIronDeepslate() { + } + + @Override + protected int getRawMaterial() { + return ItemID.RAW_IRON; + } + + @Override + public int getId() { + return DEEPSLATE_IRON_ORE; + } + + @Override + public double getHardness() { + return 4.5; + } + + @Override + public String getName() { + return "Deepslate Iron Ore"; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockOreLapis.java b/src/main/java/cn/nukkit/block/BlockOreLapis.java index 3e4207985a2..1883976ea20 100644 --- a/src/main/java/cn/nukkit/block/BlockOreLapis.java +++ b/src/main/java/cn/nukkit/block/BlockOreLapis.java @@ -1,24 +1,16 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemDye; import cn.nukkit.item.ItemTool; import cn.nukkit.item.enchantment.Enchantment; -import cn.nukkit.math.NukkitRandom; - -import java.util.Random; -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockOreLapis extends BlockSolid { - - public BlockOreLapis() { - } - @Override public int getId() { return LAPIS_ORE; @@ -31,7 +23,7 @@ public double getHardness() { @Override public double getResistance() { - return 5; + return 3; } @Override @@ -47,20 +39,24 @@ public String getName() { @Override public Item[] getDrops(Item item) { if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_STONE) { - int count = 4 + ThreadLocalRandom.current().nextInt(5); + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; + } + + int count = 4 + Utils.random.nextInt(6); Enchantment fortune = item.getEnchantment(Enchantment.ID_FORTUNE_DIGGING); if (fortune != null && fortune.getLevel() >= 1) { - int i = ThreadLocalRandom.current().nextInt(fortune.getLevel() + 2) - 1; + int i = Utils.random.nextInt(fortune.getLevel() + 2) - 1; if (i < 0) { i = 0; } - count *= (i + 1); + count = count + i; } return new Item[]{ - new ItemDye(4, new Random().nextInt(4) + 4) + Item.get(Item.DYE, 4, count) }; } else { return new Item[0]; @@ -69,14 +65,14 @@ public Item[] getDrops(Item item) { @Override public int getDropExp() { - return new NukkitRandom().nextRange(2, 5); + return Utils.rand(2, 5); } @Override public boolean canHarvestWithHand() { return false; } - + @Override public boolean canSilkTouch() { return true; diff --git a/src/main/java/cn/nukkit/block/BlockOreLapisDeepslate.java b/src/main/java/cn/nukkit/block/BlockOreLapisDeepslate.java new file mode 100644 index 00000000000..8745d203e54 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockOreLapisDeepslate.java @@ -0,0 +1,41 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemDye; +import cn.nukkit.item.ItemID; +import cn.nukkit.utils.BlockColor; + +public class BlockOreLapisDeepslate extends BlockOre { + + public BlockOreLapisDeepslate() { + } + + @Override + protected int getRawMaterial() { + return ItemID.DYE; + } + + @Override + protected int getRawMaterialMeta() { + return ItemDye.LAPIS_LAZULI; + } + + @Override + public int getId() { + return DEEPSLATE_LAPIS_ORE; + } + + @Override + public double getHardness() { + return 4.5; + } + + @Override + public String getName() { + return "Deepslate Lapis Lazuli Ore"; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockOreQuartz.java b/src/main/java/cn/nukkit/block/BlockOreQuartz.java index 3b3556971ad..ba52256307c 100644 --- a/src/main/java/cn/nukkit/block/BlockOreQuartz.java +++ b/src/main/java/cn/nukkit/block/BlockOreQuartz.java @@ -1,12 +1,9 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemQuartz; import cn.nukkit.item.ItemTool; import cn.nukkit.item.enchantment.Enchantment; -import cn.nukkit.math.NukkitRandom; - -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; /** * Created on 2015/12/26 by xtypr. @@ -14,9 +11,6 @@ */ public class BlockOreQuartz extends BlockSolid { - public BlockOreQuartz() { - } - @Override public String getName() { return "Quartz Ore"; @@ -34,7 +28,7 @@ public double getHardness() { @Override public double getResistance() { - return 5; + return 3; } @Override @@ -44,11 +38,15 @@ public int getToolType() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; + } + int count = 1; Enchantment fortune = item.getEnchantment(Enchantment.ID_FORTUNE_DIGGING); if (fortune != null && fortune.getLevel() >= 1) { - int i = ThreadLocalRandom.current().nextInt(fortune.getLevel() + 2) - 1; + int i = Utils.random.nextInt(fortune.getLevel() + 2) - 1; if (i < 0) { i = 0; @@ -58,7 +56,7 @@ public Item[] getDrops(Item item) { } return new Item[]{ - new ItemQuartz(0, count) + Item.get(Item.QUARTZ, 0, count) }; } else { return new Item[0]; @@ -67,7 +65,7 @@ public Item[] getDrops(Item item) { @Override public int getDropExp() { - return new NukkitRandom().nextRange(1, 5); + return Utils.rand(1, 5); } @Override diff --git a/src/main/java/cn/nukkit/block/BlockOreRedstone.java b/src/main/java/cn/nukkit/block/BlockOreRedstone.java index 0ce78d76c5c..a96f0cc371c 100644 --- a/src/main/java/cn/nukkit/block/BlockOreRedstone.java +++ b/src/main/java/cn/nukkit/block/BlockOreRedstone.java @@ -1,23 +1,17 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemRedstone; import cn.nukkit.item.ItemTool; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.level.Level; -import cn.nukkit.math.NukkitRandom; - -import java.util.Random; +import cn.nukkit.utils.Utils; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockOreRedstone extends BlockSolid { - public BlockOreRedstone() { - } - @Override public int getId() { return REDSTONE_ORE; @@ -30,7 +24,7 @@ public double getHardness() { @Override public double getResistance() { - return 15; + return 3; } @Override @@ -46,15 +40,19 @@ public String getName() { @Override public Item[] getDrops(Item item) { if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_IRON) { - int count = new Random().nextInt(2) + 4; + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; + } + + int count = Utils.random.nextInt(2) + 4; Enchantment fortune = item.getEnchantment(Enchantment.ID_FORTUNE_DIGGING); if (fortune != null && fortune.getLevel() >= 1) { - count += new Random().nextInt(fortune.getLevel() + 1); + count += Utils.random.nextInt(fortune.getLevel() + 1); } return new Item[]{ - new ItemRedstone(0, count) + Item.get(Item.REDSTONE_DUST, 0, count) }; } else { return new Item[0]; @@ -63,8 +61,9 @@ public Item[] getDrops(Item item) { @Override public int onUpdate(int type) { - if (type == Level.BLOCK_UPDATE_TOUCH) { //type == Level.BLOCK_UPDATE_NORMAL || - this.getLevel().setBlock(this, Block.get(BlockID.GLOWING_REDSTONE_ORE), false, false); + if (type == Level.BLOCK_UPDATE_TOUCH) { + this.getLevel().setBlock(this, Block.get(GLOWING_REDSTONE_ORE), false, false); + this.getLevel().scheduleUpdate(this, 600); return Level.BLOCK_UPDATE_WEAK; } @@ -74,7 +73,7 @@ public int onUpdate(int type) { @Override public int getDropExp() { - return new NukkitRandom().nextRange(1, 5); + return Utils.rand(1, 5); } @Override diff --git a/src/main/java/cn/nukkit/block/BlockOreRedstoneDeepslate.java b/src/main/java/cn/nukkit/block/BlockOreRedstoneDeepslate.java new file mode 100644 index 00000000000..d4b86824ed3 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockOreRedstoneDeepslate.java @@ -0,0 +1,53 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemID; +import cn.nukkit.item.ItemTool; +import cn.nukkit.level.Level; +import cn.nukkit.utils.BlockColor; + +public class BlockOreRedstoneDeepslate extends BlockOre { + + public BlockOreRedstoneDeepslate() { + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_TOUCH) { + this.getLevel().setBlock(this, Block.get(LIT_DEEPSLATE_REDSTONE_ORE), false, false); + this.getLevel().scheduleUpdate(this, 600); + + return Level.BLOCK_UPDATE_WEAK; + } + return 0; + } + + @Override + protected int getRawMaterial() { + return ItemID.REDSTONE_DUST; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_IRON; + } + + @Override + public int getId() { + return DEEPSLATE_REDSTONE_ORE; + } + + @Override + public double getHardness() { + return 4.5; + } + + @Override + public String getName() { + return "Deepslate Redstone Ore"; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockOreRedstoneDeepslateGlowing.java b/src/main/java/cn/nukkit/block/BlockOreRedstoneDeepslateGlowing.java new file mode 100644 index 00000000000..2b55f735f6d --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockOreRedstoneDeepslateGlowing.java @@ -0,0 +1,47 @@ +package cn.nukkit.block; + +import cn.nukkit.event.block.BlockFadeEvent; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.level.Level; + +public class BlockOreRedstoneDeepslateGlowing extends BlockOreRedstoneDeepslate { + + public BlockOreRedstoneDeepslateGlowing() { + } + + @Override + public int getId() { + return LIT_DEEPSLATE_REDSTONE_ORE; + } + + @Override + public String getName() { + return "Glowing Deepslate Redstone Ore"; + } + + @Override + public int getLightLevel() { + return 9; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(REDSTONE_ORE)); + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_SCHEDULED || type == Level.BLOCK_UPDATE_RANDOM) { + BlockFadeEvent event = new BlockFadeEvent(this, Block.get(DEEPSLATE_REDSTONE_ORE)); + level.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + level.setBlock(this, event.getNewState(), false, false); + } + + return Level.BLOCK_UPDATE_WEAK; + } + + return 0; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockOreRedstoneGlowing.java b/src/main/java/cn/nukkit/block/BlockOreRedstoneGlowing.java index dd607c696d4..d737a298ba2 100644 --- a/src/main/java/cn/nukkit/block/BlockOreRedstoneGlowing.java +++ b/src/main/java/cn/nukkit/block/BlockOreRedstoneGlowing.java @@ -5,17 +5,12 @@ import cn.nukkit.item.ItemBlock; import cn.nukkit.level.Level; -//和pm源码有点出入,这里参考了wiki - /** * Created on 2015/12/6 by xtypr. * Package cn.nukkit.block in project Nukkit . */ public class BlockOreRedstoneGlowing extends BlockOreRedstone { - public BlockOreRedstoneGlowing() { - } - @Override public String getName() { return "Glowing Redstone Ore"; @@ -33,7 +28,7 @@ public int getLightLevel() { @Override public Item toItem() { - return new ItemBlock(Block.get(BlockID.REDSTONE_ORE)); + return new ItemBlock(Block.get(REDSTONE_ORE)); } @Override @@ -50,14 +45,4 @@ public int onUpdate(int type) { return 0; } - - @Override - public boolean canHarvestWithHand() { - return false; - } - - @Override - public boolean canSilkTouch() { - return true; - } } diff --git a/src/main/java/cn/nukkit/block/BlockPackedMud.java b/src/main/java/cn/nukkit/block/BlockPackedMud.java new file mode 100644 index 00000000000..08233302453 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockPackedMud.java @@ -0,0 +1,27 @@ +package cn.nukkit.block; + +public class BlockPackedMud extends BlockSolid { + + public BlockPackedMud() { + } + + @Override + public String getName() { + return "Packed Mud"; + } + + @Override + public int getId() { + return PACKED_MUD; + } + + @Override + public double getHardness() { + return 1; + } + + @Override + public double getResistance() { + return 3; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockPiston.java b/src/main/java/cn/nukkit/block/BlockPiston.java index 6bf3cff2f36..5c0c7dce6f8 100644 --- a/src/main/java/cn/nukkit/block/BlockPiston.java +++ b/src/main/java/cn/nukkit/block/BlockPiston.java @@ -18,6 +18,11 @@ public int getId() { return PISTON; } + @Override + public int getPistonHeadBlockId() { + return PISTON_HEAD; + } + @Override public String getName() { return "Piston"; diff --git a/src/main/java/cn/nukkit/block/BlockPistonBase.java b/src/main/java/cn/nukkit/block/BlockPistonBase.java index 19c8a24b4ff..66ea91af066 100644 --- a/src/main/java/cn/nukkit/block/BlockPistonBase.java +++ b/src/main/java/cn/nukkit/block/BlockPistonBase.java @@ -4,6 +4,8 @@ import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.blockentity.BlockEntityPistonArm; import cn.nukkit.event.block.BlockPistonChangeEvent; +import cn.nukkit.event.block.BlockPistonEvent; +import cn.nukkit.event.redstone.RedstoneUpdateEvent; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.level.Level; @@ -31,21 +33,22 @@ public BlockPistonBase(int meta) { super(meta); } + public abstract int getPistonHeadBlockId(); + @Override public double getResistance() { - return 2.5; + return 1.5; } @Override public double getHardness() { - return 0.5; + return 1.5; } @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - if (Math.abs(player.x - this.x) < 2 && Math.abs(player.z - this.z) < 2) { + if (Math.abs(player.getFloorX() - this.x) < 2 && Math.abs(player.getFloorZ() - this.z) < 2) { double y = player.y + player.getEyeHeight(); - if (y - this.y > 2) { this.setDamage(BlockFace.UP.getIndex()); } else if (this.y - y > 0) { @@ -56,7 +59,7 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl } else { this.setDamage(player.getHorizontalFacing().getIndex()); } - this.level.setBlock(block, this, true, false); + this.getLevel().setBlock(this, this, true, false); CompoundTag nbt = new CompoundTag("") .putString("id", BlockEntity.PISTON_ARM) @@ -65,10 +68,11 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl .putInt("z", (int) this.z) .putBoolean("Sticky", this.sticky); - BlockEntityPistonArm be = (BlockEntityPistonArm) BlockEntity.createBlockEntity(BlockEntity.PISTON_ARM, this.level.getChunk((int) this.x >> 4, (int) this.z >> 4), nbt); + BlockEntityPistonArm be = (BlockEntityPistonArm) BlockEntity.createBlockEntity(BlockEntity.PISTON_ARM, this.getChunk(), nbt); + be.sticky = this.sticky; + be.spawnToAll(); - if (be == null) return false; - //this.checkState(); + this.checkState(); return true; } @@ -77,8 +81,7 @@ public boolean onBreak(Item item) { this.level.setBlock(this, Block.get(BlockID.AIR), true, true); Block block = this.getSide(getFacing()); - - if (block instanceof BlockPistonHead && ((BlockPistonHead) block).getFacing() == this.getFacing()) { + if (block instanceof BlockPistonHead && ((BlockPistonHead) block).getBlockFace() == this.getFacing()) { block.onBreak(item); } return true; @@ -87,7 +90,7 @@ public boolean onBreak(Item item) { public boolean isExtended() { BlockFace face = getFacing(); Block block = getSide(face); - return block instanceof BlockPistonHead && ((BlockPistonHead) block).getFacing() == face; + return block instanceof BlockPistonHead && ((BlockPistonHead) block).getBlockFace() == face; } @Override @@ -95,19 +98,14 @@ public int onUpdate(int type) { if (type != 6 && type != 1) { return 0; } else { - BlockEntity blockEntity = this.level.getBlockEntity(this); - if (blockEntity instanceof BlockEntityPistonArm) { - BlockEntityPistonArm arm = (BlockEntityPistonArm) blockEntity; - boolean powered = this.isPowered(); - if (arm.powered != powered) { - this.level.getServer().getPluginManager().callEvent(new BlockPistonChangeEvent(this, powered ? 0 : 15, powered ? 15 : 0)); - arm.powered = !arm.powered; - if (arm.chunk != null) { - arm.chunk.setChanged(); - } + if (type == Level.BLOCK_UPDATE_REDSTONE) { + RedstoneUpdateEvent ev = new RedstoneUpdateEvent(this); + getLevel().getServer().getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + return 0; } } - + this.checkState(); return type; } } @@ -115,31 +113,36 @@ public int onUpdate(int type) { private void checkState() { BlockFace facing = getFacing(); boolean isPowered = this.isPowered(); + boolean extended = isExtended(); - if (isPowered && !isExtended()) { - if ((new BlocksCalculator(this.level, this, facing, true)).canMove()) { - if (!this.doMove(true)) { + if (isPowered && !extended) { + BlocksCalculator calculator = new BlocksCalculator(this, facing, true); + if (calculator.canMove()) { + if (!this.doMove(true, calculator)) { return; } - + this.updateBlockEntity(true); this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_PISTON_OUT); - } else { } - } else if (!isPowered && isExtended()) { - //this.level.setBlock() TODO: set piston extension? + return; + } + if (!isPowered && extended) { if (this.sticky) { - Vector3 pos = this.add(facing.getXOffset() * 2, facing.getYOffset() * 2, facing.getZOffset() * 2); + Vector3 pos = this.add(facing.getXOffset() << 1, facing.getYOffset() << 1, facing.getZOffset() << 1); Block block = this.level.getBlock(pos); if (block.getId() == AIR) { - this.level.setBlock(this.getLocation().getSide(facing), Block.get(BlockID.AIR), true, true); + this.level.setBlock(this.getSideVec(facing), Block.get(BlockID.AIR), true, true); } - if (canPush(block, facing.getOpposite(), false) && (!(block instanceof BlockFlowable) || block.getId() == PISTON || block.getId() == STICKY_PISTON)) { - this.doMove(false); + if (canPush(block, facing.getOpposite(), false) && (!(block instanceof BlockFlowable || block.breakWhenPushed()) || block.getId() == PISTON || block.getId() == STICKY_PISTON)) { + if (this.doMove(false, null)) { + this.updateBlockEntity(false); + } } } else { - this.level.setBlock(getLocation().getSide(facing), Block.get(BlockID.AIR), true, false); + this.updateBlockEntity(false); + this.level.setBlock(getSideVec(facing), Block.get(BlockID.AIR), true, true); } this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_PISTON_IN); @@ -147,14 +150,21 @@ private void checkState() { } public BlockFace getFacing() { - return BlockFace.fromIndex(this.getDamage()).getOpposite(); + BlockFace face = BlockFace.fromIndex(this.getDamage()).getOpposite(); + if (face == BlockFace.UP) return BlockFace.DOWN; + if (face == BlockFace.DOWN) return BlockFace.UP; + return face; } private boolean isPowered() { BlockFace face = getFacing(); + // Revert to opposite + if (face == BlockFace.UP) face = BlockFace.DOWN; + if (face == BlockFace.DOWN) face = BlockFace.UP; + for (BlockFace side : BlockFace.values()) { - if (side != face && this.level.isSidePowered(this.getLocation().getSide(side), side)) { + if (side != face && this.level.isSidePowered(this.getSideVec(side), side)) { return true; } } @@ -162,10 +172,10 @@ private boolean isPowered() { if (this.level.isSidePowered(this, BlockFace.DOWN)) { return true; } else { - Vector3 pos = this.getLocation().up(); + Vector3 pos = this.getSideVec(BlockFace.UP); for (BlockFace side : BlockFace.values()) { - if (side != BlockFace.DOWN && this.level.isSidePowered(pos.getSide(side), side)) { + if (side != BlockFace.DOWN && this.level.isSidePowered(pos.getSideVec(side), side)) { return true; } } @@ -174,23 +184,54 @@ private boolean isPowered() { } } - private boolean doMove(boolean extending) { - Vector3 pos = this.getLocation(); + private void updateBlockEntity(boolean extending) { + BlockEntity blockEntity = this.level.getBlockEntity(this); + if (blockEntity instanceof BlockEntityPistonArm) { + BlockEntityPistonArm arm = (BlockEntityPistonArm) blockEntity; + if (arm.isExtended() != extending) { + this.level.getServer().getPluginManager().callEvent(new BlockPistonChangeEvent(this, extending ? 0 : 15, extending ? 15 : 0)); + arm.setExtended(extending); + arm.broadcastMove(); + if (arm.chunk != null) { + arm.chunk.setChanged(); + } + } + } + } + + private boolean doMove(boolean extending, BlocksCalculator calculator) { BlockFace direction = getFacing(); if (!extending) { - this.level.setBlock(pos.getSide(direction), Block.get(BlockID.AIR), true, false); + this.level.setBlock(this.getSideVec(direction), Block.get(BlockID.AIR), true, false); + } + if (calculator == null) { + calculator = new BlocksCalculator(this, direction, extending); } - BlocksCalculator calculator = new BlocksCalculator(this.level, this, direction, extending); + if (calculator.canMove()) { + BlockPistonEvent event = new BlockPistonEvent(this, direction, calculator.getBlocksToMove(), calculator.getBlocksToDestroy(), extending); + this.level.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return false; + } - if (!calculator.canMove()) { - return false; - } else { List blocks = calculator.getBlocksToMove(); + if (!extending && blocks.isEmpty()) { + this.level.setBlock(this.getSideVec(direction), Block.get(BlockID.AIR), false, true); + return true; + } - List newBlocks = new ArrayList<>(blocks); + Block pistonHead = null; + if (extending) { + pistonHead = this.getSide(direction); + if (!pistonHead.canBePushed()) { + return false; // TODO: figure out why this happens + } + } + List newBlocks = new ArrayList<>(blocks); List destroyBlocks = calculator.getBlocksToDestroy(); BlockFace side = extending ? direction : direction.getOpposite(); @@ -201,43 +242,35 @@ private boolean doMove(boolean extending) { for (int i = blocks.size() - 1; i >= 0; --i) { Block block = blocks.get(i); - this.level.setBlock(block, Block.get(BlockID.AIR)); - Vector3 newPos = block.getLocation().getSide(side); + this.level.setBlock(block, Block.get(BlockID.AIR), true, false); + Vector3 newPos = block.getSideVec(side); - //TODO: change this to block entity - this.level.setBlock(newPos, newBlocks.get(i)); + // TODO: Change this to block entity + this.level.setBlock(newPos, newBlocks.get(i), true, false); } - Vector3 pistonHead = pos.getSide(direction); - - if (extending) { - //extension block entity - - this.level.setBlock(pistonHead, Block.get(BlockID.PISTON_HEAD, this.getDamage())); + if (pistonHead != null) { + this.level.setBlock(pistonHead, Block.get(this.getPistonHeadBlockId(), this.getDamage()), true, false); } - return true; + } else { + return false; } } public static boolean canPush(Block block, BlockFace face, boolean destroyBlocks) { - if (block.canBePushed() && block.getY() >= 0 && (face != BlockFace.DOWN || block.getY() != 0) && - block.getY() <= 255 && (face != BlockFace.UP || block.getY() != 255)) { + if (block.canBePushed() && block.getY() >= block.getLevel().getMinBlockY() && (face != BlockFace.DOWN || block.getY() != block.getLevel().getMinBlockY()) && block.getY() <= block.getLevel().getMaxBlockY() && (face != BlockFace.UP || block.getY() != block.getLevel().getMaxBlockY())) { if (!(block instanceof BlockPistonBase)) { - - if (block instanceof BlockFlowable) { + if ((block instanceof BlockFlowable && !(block instanceof BlockEndPortal || block instanceof BlockNetherPortal)) || block.breakWhenPushed()) { return destroyBlocks; } } else return !((BlockPistonBase) block).isExtended(); return true; } return false; - } public static class BlocksCalculator { - - private final Level level; private final Vector3 pistonPos; private final Block blockToMove; private final BlockFace moveDirection; @@ -245,8 +278,9 @@ public static class BlocksCalculator { private final List toMove = new ArrayList<>(); private final List toDestroy = new ArrayList<>(); - public BlocksCalculator(Level level, Block pos, BlockFace facing, boolean extending) { - this.level = level; + protected Boolean canMove; + + public BlocksCalculator(Block pos, BlockFace facing, boolean extending) { this.pistonPos = pos.getLocation(); if (extending) { @@ -259,13 +293,25 @@ public BlocksCalculator(Level level, Block pos, BlockFace facing, boolean extend } public boolean canMove() { + return this.canMove == null ? this.canMove = this.eval() : this.canMove; + } + + private boolean eval() { this.toMove.clear(); this.toDestroy.clear(); - Block block = this.blockToMove; - if (!canPush(block, this.moveDirection, false)) { - if (block instanceof BlockFlowable) { - this.toDestroy.add(this.blockToMove); + if (!canPush(this.blockToMove, this.moveDirection, false)) { + if ((this.blockToMove instanceof BlockFlowable && !(this.blockToMove instanceof BlockEndPortal || this.blockToMove instanceof BlockNetherPortal)) || this.blockToMove.breakWhenPushed()) { + boolean exists = false; + for (Block b : this.toDestroy) { + if (b.x == this.blockToMove.x && b.y == this.blockToMove.y && b.z == this.blockToMove.z) { + exists = true; + break; + } + } + if (!exists) { + this.toDestroy.add(this.blockToMove); + } return true; } else { return false; @@ -273,18 +319,20 @@ public boolean canMove() { } else if (!this.addBlockLine(this.blockToMove)) { return false; } else { - for (Block b : this.toMove) { - if (b.getId() == SLIME_BLOCK && !this.addBranchingBlocks(b)) { - return false; + /*if (false) { //todo? + for (Block b : this.toMove) { + if (b.getId() == SLIME_BLOCK && !this.addBranchingBlocks(b)) { + return false; + } } - } + }*/ return true; } } private boolean addBlockLine(Block origin) { - Block block = origin.clone(); + Block block = origin/*.clone()*/; if (block.getId() == AIR) { return true; @@ -300,7 +348,7 @@ private boolean addBlockLine(Block origin) { if (count + this.toMove.size() > 12) { return false; } else { - while (block.getId() == SLIME_BLOCK) { + /*while (false && block.getId() == SLIME_BLOCK) { block = origin.getSide(this.moveDirection.getOpposite(), count); if (block.getId() == AIR || !canPush(block, this.moveDirection, false) || block.equals(this.pistonPos)) { @@ -312,12 +360,16 @@ private boolean addBlockLine(Block origin) { if (count + this.toMove.size() > 12) { return false; } - } + }*/ int blockCount = 0; for (int step = count - 1; step >= 0; --step) { - this.toMove.add(block.getSide(this.moveDirection.getOpposite(), step)); + Block aBlock = block.getSide(this.moveDirection.getOpposite(), step); + if (aBlock.breakWhenPushed()) { + return true; // shouldn't be possible? + } + this.toMove.add(aBlock); ++blockCount; } @@ -333,9 +385,9 @@ private boolean addBlockLine(Block origin) { for (int l = 0; l <= index + blockCount; ++l) { Block b = this.toMove.get(l); - if (b.getId() == SLIME_BLOCK && !this.addBranchingBlocks(b)) { + /*if (false && b.getId() == SLIME_BLOCK && !this.addBranchingBlocks(b)) { return false; - } + }*/ } return true; @@ -349,8 +401,17 @@ private boolean addBlockLine(Block origin) { return false; } - if (nextBlock instanceof BlockFlowable) { - this.toDestroy.add(nextBlock); + if ((nextBlock instanceof BlockFlowable && !(nextBlock instanceof BlockEndPortal || nextBlock instanceof BlockNetherPortal)) || nextBlock.breakWhenPushed()) { + boolean exists = false; + for (Block b : this.toDestroy) { + if (b.x == nextBlock.x && b.y == nextBlock.y && b.z == nextBlock.z) { + exists = true; + break; + } + } + if (!exists) { + this.toDestroy.add(nextBlock); + } return true; } @@ -376,7 +437,7 @@ private void reorderListAtCollision(int count, int index) { this.toMove.addAll(list2); } - private boolean addBranchingBlocks(Block block) { + /*private boolean addBranchingBlocks(Block block) { for (BlockFace face : BlockFace.values()) { if (face.getAxis() != this.moveDirection.getAxis() && !this.addBlockLine(block.getSide(face))) { return false; @@ -384,7 +445,7 @@ private boolean addBranchingBlocks(Block block) { } return true; - } + }*/ public List getBlocksToMove() { return this.toMove; @@ -397,7 +458,7 @@ public List getBlocksToDestroy() { @Override public Item toItem() { - return new ItemBlock(this, 0); + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override diff --git a/src/main/java/cn/nukkit/block/BlockPistonExtension.java b/src/main/java/cn/nukkit/block/BlockPistonExtension.java new file mode 100644 index 00000000000..92df04df905 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockPistonExtension.java @@ -0,0 +1,36 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; + +public class BlockPistonExtension extends BlockTransparent { + + @Override + public int getId() { + return PISTON_EXTENSION; + } + + @Override + public String getName() { + return "Piston Extension"; + } + + @Override + public double getHardness() { + return 0.1; + } + + @Override + public double getResistance() { + return 0.1; + } + + @Override + public Item[] getDrops(Item item) { + return new Item[0]; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockPistonHead.java b/src/main/java/cn/nukkit/block/BlockPistonHead.java index fb99b423307..f58b42c3bff 100644 --- a/src/main/java/cn/nukkit/block/BlockPistonHead.java +++ b/src/main/java/cn/nukkit/block/BlockPistonHead.java @@ -3,11 +3,12 @@ import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.Faceable; /** * @author CreeperFace */ -public class BlockPistonHead extends BlockTransparentMeta { +public class BlockPistonHead extends BlockTransparentMeta implements Faceable { public BlockPistonHead() { this(0); @@ -29,12 +30,12 @@ public String getName() { @Override public double getResistance() { - return 2.5; + return 1.5; } @Override public double getHardness() { - return 0.5; + return 1.5; } @Override @@ -45,16 +46,19 @@ public Item[] getDrops(Item item) { @Override public boolean onBreak(Item item) { this.level.setBlock(this, Block.get(BlockID.AIR), true, true); - Block piston = getSide(getFacing().getOpposite()); - - if (piston instanceof BlockPistonBase && ((BlockPistonBase) piston).getFacing() == this.getFacing()) { + Block piston = getSide(getBlockFace().getOpposite()); + if (piston instanceof BlockPistonBase && ((BlockPistonBase) piston).getFacing() == this.getBlockFace()) { piston.onBreak(item); } return true; } - public BlockFace getFacing() { - return BlockFace.fromIndex(this.getDamage()).getOpposite(); + @Override + public BlockFace getBlockFace() { + BlockFace face = BlockFace.fromIndex(this.getDamage()).getOpposite(); + if (face == BlockFace.UP) return BlockFace.DOWN; + if (face == BlockFace.DOWN) return BlockFace.UP; + return face; } @Override diff --git a/src/main/java/cn/nukkit/block/BlockPistonHeadSticky.java b/src/main/java/cn/nukkit/block/BlockPistonHeadSticky.java new file mode 100644 index 00000000000..ad895ed5090 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockPistonHeadSticky.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockPistonHeadSticky extends BlockPistonHead { + + public BlockPistonHeadSticky() { + this(0); + } + + public BlockPistonHeadSticky(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Sticky Piston Head"; + } + + @Override + public int getId() { + return PISTON_HEAD_STICKY; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockPistonSticky.java b/src/main/java/cn/nukkit/block/BlockPistonSticky.java index 4962b5c6db3..de68535b58c 100644 --- a/src/main/java/cn/nukkit/block/BlockPistonSticky.java +++ b/src/main/java/cn/nukkit/block/BlockPistonSticky.java @@ -19,6 +19,11 @@ public int getId() { return STICKY_PISTON; } + @Override + public int getPistonHeadBlockId() { + return PISTON_HEAD_STICKY; + } + @Override public String getName() { return "Sticky Piston"; diff --git a/src/main/java/cn/nukkit/block/BlockPlanks.java b/src/main/java/cn/nukkit/block/BlockPlanks.java index 409ae264815..71984c11667 100644 --- a/src/main/java/cn/nukkit/block/BlockPlanks.java +++ b/src/main/java/cn/nukkit/block/BlockPlanks.java @@ -4,10 +4,11 @@ import cn.nukkit.utils.BlockColor; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockPlanks extends BlockSolidMeta { + public static final int OAK = 0; public static final int SPRUCE = 1; public static final int BIRCH = 2; @@ -15,7 +16,6 @@ public class BlockPlanks extends BlockSolidMeta { public static final int ACACIA = 4; public static final int DARK_OAK = 5; - public BlockPlanks() { this(0); } @@ -49,18 +49,18 @@ public int getBurnAbility() { return 20; } + private static final String[] NAMES = { + "Oak Planks", + "Spruce Planks", + "Birch Planks", + "Jungle Planks", + "Acacia Planks", + "Dark Oak Planks", + }; + @Override public String getName() { - String[] names = new String[]{ - "Oak Wood Planks", - "Spruce Wood Planks", - "Birch Wood Planks", - "Jungle Wood Planks", - "Acacia Wood Planks", - "Dark Oak Wood Planks", - }; - - return this.getDamage() < 0 ? "Unknown" : names[this.getDamage() % 6]; + return NAMES[this.getDamage() & 0x07]; } @Override @@ -70,7 +70,7 @@ public int getToolType() { @Override public BlockColor getColor() { - switch(getDamage() & 0x07){ + switch (getDamage() & 0x07) { default: case OAK: return BlockColor.WOOD_BLOCK_COLOR; diff --git a/src/main/java/cn/nukkit/block/BlockPodzol.java b/src/main/java/cn/nukkit/block/BlockPodzol.java index b2cff7609f7..512caff6f5e 100644 --- a/src/main/java/cn/nukkit/block/BlockPodzol.java +++ b/src/main/java/cn/nukkit/block/BlockPodzol.java @@ -2,7 +2,7 @@ import cn.nukkit.Player; import cn.nukkit.item.Item; -import cn.nukkit.utils.BlockColor; +import cn.nukkit.level.Sound; /** * Created on 2015/11/22 by xtypr. @@ -15,7 +15,6 @@ public BlockPodzol() { } public BlockPodzol(int meta) { - // Podzol can't have meta. super(0); } @@ -34,28 +33,28 @@ public boolean canSilkTouch() { return true; } - @Override - public boolean canBeActivated() { - return false; - } - @Override public boolean onActivate(Item item, Player player) { + if (item.isShovel()) { + Block up = this.up(); + if (up instanceof BlockAir || up instanceof BlockFlowable) { + item.useOn(this); + this.getLevel().setBlock(this, Block.get(GRASS_PATH)); + if (player != null) { + player.getLevel().addSound(player, Sound.STEP_GRASS); + } + return true; + } + } return false; } @Override public int getFullId() { - return this.getId() << 4; + return getId() << DATA_BITS; } @Override public void setDamage(int meta) { - - } - - @Override - public BlockColor getColor() { - return BlockColor.SPRUCE_BLOCK_COLOR; } } diff --git a/src/main/java/cn/nukkit/block/BlockPointedDripstone.java b/src/main/java/cn/nukkit/block/BlockPointedDripstone.java new file mode 100644 index 00000000000..1dba4d7c260 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockPointedDripstone.java @@ -0,0 +1,287 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.block.properties.BlockPropertiesHelper; +import cn.nukkit.block.properties.DripstoneThickness; +import cn.nukkit.block.custom.properties.BlockProperties; +import cn.nukkit.block.custom.properties.BooleanBlockProperty; +import cn.nukkit.block.custom.properties.EnumBlockProperty; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityFallingBlock; +import cn.nukkit.event.block.BlockFallEvent; +import cn.nukkit.event.block.BlockGrowEvent; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.level.Level; +import cn.nukkit.level.Location; +import cn.nukkit.level.Position; +import cn.nukkit.level.particle.DestroyBlockParticle; +import cn.nukkit.math.BlockFace; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.DoubleTag; +import cn.nukkit.nbt.tag.FloatTag; +import cn.nukkit.nbt.tag.ListTag; +import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.Faceable; +import it.unimi.dsi.fastutil.ints.IntObjectPair; + +import java.util.concurrent.ThreadLocalRandom; +import java.util.function.Consumer; + +public class BlockPointedDripstone extends BlockSolidMeta implements BlockPropertiesHelper, Faceable { + + private static final float GROWTH_PROBABILITY = 0.011377778F; + private static final int MAX_HEIGHT = 7; + + private static final EnumBlockProperty THICKNESS = new EnumBlockProperty<>("dripstone_thickness", false, DripstoneThickness.class); + private static final BooleanBlockProperty HANGING = new BooleanBlockProperty("hanging", false); + private static final BlockProperties PROPERTIES = new BlockProperties(HANGING, THICKNESS); + + public BlockPointedDripstone() { + this(0); + } + + public BlockPointedDripstone(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Pointed Dripstone"; + } + + @Override + public int getId() { + return POINTED_DRIPSTONE; + } + + @Override + public BlockProperties getBlockProperties() { + return PROPERTIES; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (!this.canPlaceOn(block.down(), target)) { + return false; + } + + Block up = this.up(); + Block down = this.down(); + + boolean hanging = false; + if (face == BlockFace.UP || face == BlockFace.DOWN) { + if ((face == BlockFace.UP && !down.isSolid()) || (face == BlockFace.DOWN && !up.isSolid())) { + return false; + } + hanging = face == BlockFace.DOWN; + } else if (up.isSolid()) { + hanging = true; + } else if (!down.isSolid()) { + return false; + } + + + Block tip = null; + if (up instanceof BlockPointedDripstone && hanging) { + tip = up; + } else if (down instanceof BlockPointedDripstone) { + tip = down; + } + + if (tip != null) { + IntObjectPair pair = this.getDripstoneHeightFromTip(tip, hanging); + int height = pair.keyInt(); + if (height == 0 || height == MAX_HEIGHT) { + return false; + } + Location location = pair.right().getLocation(); + this.growPointedDripstone(location, hanging, height); + } else { + this.setHanging(hanging); + this.setThickness(DripstoneThickness.TIP); + this.getLevel().setBlock(this, this, true, true); + } + return true; + } + + @Override + public boolean onBreak(Item item, Player player) { + boolean hanging = this.isHanging(); + + Block newTip = hanging ? this.up() : this.down(); + if (newTip instanceof BlockPointedDripstone) { + ((BlockPointedDripstone) newTip).setThickness(DripstoneThickness.TIP); + this.getLevel().setBlock(newTip, newTip); + } + + DripstoneThickness thickness = this.getThickness(); + if (thickness == DripstoneThickness.TIP || thickness == DripstoneThickness.MERGE) { + return super.onBreak(item, player); + } + + Block block = this; + while (block instanceof BlockPointedDripstone) { + BlockPointedDripstone dripstone = (BlockPointedDripstone) block; + if (this != dripstone) { + this.getLevel().addParticle(new DestroyBlockParticle(block.add(0.5), block)); + if (hanging) { + this.spawnFallingBlock(dripstone); + } else { + this.getLevel().dropItem(block.add(0.5, 0.5, 0.5), block.toItem()); + } + } + this.getLevel().setBlock(block, Block.get(BlockID.AIR), false, true); + block = hanging ? block.down() : block.up(); + } + return true; + } + + @Override + public int onUpdate(int type) { + if (type != Level.BLOCK_UPDATE_RANDOM) { + return 0; + } + + if (ThreadLocalRandom.current().nextFloat() >= GROWTH_PROBABILITY || !this.isHanging() || this.up().getId() == POINTED_DRIPSTONE) { + return 0; + } + + int height; + if (this.canGrow() && (height = this.getDripstoneHeightFromBase(this, true)) < MAX_HEIGHT) { + BlockGrowEvent event = new BlockGrowEvent(this, Block.get(BlockID.POINTED_DRIPSTONE)); + this.getLevel().getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return 0; + } + this.growPointedDripstone(this.getLocation(), true, height); + } + + // TODO: grow from ground too + return 0; + } + + private void growPointedDripstone(Position position, boolean hanging, int height) { + this.buildBaseToTipColumn(height + 1, false, thickness -> { + BlockPointedDripstone dripstone = (BlockPointedDripstone) Block.get(POINTED_DRIPSTONE); + dripstone.setHanging(hanging); + dripstone.setThickness(thickness); + this.getLevel().setBlock(position, dripstone); + position.setY(hanging ? position.getY() - 1 : position.getY() + 1); + }); + } + + private IntObjectPair getDripstoneHeightFromTip(Block block, boolean hanging) { + int height = 0; + BlockPointedDripstone dripstone = null; + while (block instanceof BlockPointedDripstone) { + height++; + dripstone = (BlockPointedDripstone) block; + block = hanging ? block.up() : block.down(); + } + return IntObjectPair.of(height, dripstone); + } + + private int getDripstoneHeightFromBase(Block block, boolean hanging) { + int height = 0; + while (block instanceof BlockPointedDripstone) { + height++; + block = hanging ? block.down() : block.up(); + } + return height; + } + + private void buildBaseToTipColumn(int height, boolean merge, Consumer callback) { + if (height >= 3) { + callback.accept(DripstoneThickness.BASE); + for(int i = 0; i < height - 3; ++i) { + callback.accept(DripstoneThickness.MIDDLE); + } + } + + if (height >= 2) { + callback.accept(DripstoneThickness.FRUSTUM); + } + + if (height >= 1) { + callback.accept(merge ? DripstoneThickness.MERGE : DripstoneThickness.TIP); + } + } + + private boolean canGrow() { + // TODO: grow from ground too + return this.down().getId() == AIR && this.up().getId() == DRIPSTONE_BLOCK && Block.isWater(this.up(2).getId()); + } + + private void spawnFallingBlock(BlockPointedDripstone block) { + BlockFallEvent event = new BlockFallEvent(block); + this.level.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return; + } + + CompoundTag nbt = new CompoundTag() + .putList(new ListTag("Pos") + .add(new DoubleTag("", this.x + 0.5)) + .add(new DoubleTag("", this.y)) + .add(new DoubleTag("", this.z + 0.5))) + .putList(new ListTag("Motion") + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0))) + + .putList(new ListTag("Rotation") + .add(new FloatTag("", 0)) + .add(new FloatTag("", 0))) + .putInt("TileID", this.getId()) + .putByte("Data", this.getDamage()); + + Entity.createEntity(EntityFallingBlock.NETWORK_ID, this.getLevel().getChunk((int) this.x >> 4, (int) this.z >> 4), nbt).spawnToAll(); + } + + @Override + public double getHardness() { + return 1.5; + } + + @Override + public double getResistance() { + return 3; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId()), 0, 1); + } + + @Override + public BlockColor getColor() { + return BlockColor.BROWN_TERRACOTA_BLOCK_COLOR; + } + + @Override + public BlockFace getBlockFace() { + return this.getBooleanValue(HANGING) ? BlockFace.DOWN : BlockFace.UP; + } + + public boolean isHanging() { + return this.getBooleanValue(HANGING); + } + + public void setHanging(boolean hanging) { + this.setBooleanValue(HANGING, hanging); + } + + public DripstoneThickness getThickness() { + return this.getPropertyValue(THICKNESS); + } + + public void setThickness(DripstoneThickness value) { + this.setPropertyValue(THICKNESS, value); + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockPolishedBasalt.java b/src/main/java/cn/nukkit/block/BlockPolishedBasalt.java new file mode 100644 index 00000000000..ae426211685 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockPolishedBasalt.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockPolishedBasalt extends BlockBasalt { + + public BlockPolishedBasalt() { + this(0); + } + + public BlockPolishedBasalt(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Polished Basalt"; + } + + @Override + public int getId() { + return BlockID.POLISHED_BASALT; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockPolishedBlackstoneBrickWall.java b/src/main/java/cn/nukkit/block/BlockPolishedBlackstoneBrickWall.java new file mode 100644 index 00000000000..a5992ee797c --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockPolishedBlackstoneBrickWall.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockPolishedBlackstoneBrickWall extends BlockWall { + + public BlockPolishedBlackstoneBrickWall() { + this(0); + } + + public BlockPolishedBlackstoneBrickWall(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Polished Blackstone Brick Wall"; + } + + @Override + public int getId() { + return POLISHED_BLACKSTONE_BRICK_WALL; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockPolishedBlackstoneWall.java b/src/main/java/cn/nukkit/block/BlockPolishedBlackstoneWall.java new file mode 100644 index 00000000000..e61677a44e9 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockPolishedBlackstoneWall.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockPolishedBlackstoneWall extends BlockWall { + + public BlockPolishedBlackstoneWall() { + this(0); + } + + public BlockPolishedBlackstoneWall(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Polished Blackstone Wall"; + } + + @Override + public int getId() { + return POLISHED_BLACKSTONE_WALL; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockPotato.java b/src/main/java/cn/nukkit/block/BlockPotato.java index 3d93d11d59f..65527080f70 100644 --- a/src/main/java/cn/nukkit/block/BlockPotato.java +++ b/src/main/java/cn/nukkit/block/BlockPotato.java @@ -1,9 +1,7 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemPotato; - -import java.util.Random; +import cn.nukkit.utils.Utils; /** * Created by Pub4Game on 15.01.2016. @@ -30,18 +28,25 @@ public int getId() { @Override public Item toItem() { - return new ItemPotato(); + return Item.get(Item.POTATO); } @Override public Item[] getDrops(Item item) { if (getDamage() >= 0x07) { - return new Item[]{ - new ItemPotato(0, new Random().nextInt(3) + 1) - }; + if (Utils.random.nextInt(100) < 2) { + return new Item[]{ + Item.get(Item.POTATO, 0, Utils.random.nextInt(3) + 2), + Item.get(Item.POISONOUS_POTATO, 0, 1) + }; + } else { + return new Item[]{ + Item.get(Item.POTATO, 0, Utils.random.nextInt(3) + 2) + }; + } } else { return new Item[]{ - new ItemPotato() + Item.get(Item.POTATO) }; } } diff --git a/src/main/java/cn/nukkit/block/BlockPowderSnow.java b/src/main/java/cn/nukkit/block/BlockPowderSnow.java new file mode 100644 index 00000000000..0b8c71fcbfe --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockPowderSnow.java @@ -0,0 +1,46 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.utils.BlockColor; + +public class BlockPowderSnow extends BlockTransparent { + + public BlockPowderSnow() { + super(); + } + + @Override + public String getName() { + return "Powder Snow"; + } + + @Override + public int getId() { + return POWDER_SNOW; + } + + @Override + public double getHardness() { + return 0.25; + } + + @Override + public double getResistance() { + return 0.25; + } + + @Override + public Item[] getDrops(Item item) { + return new Item[0]; + } + + @Override + public BlockColor getColor() { + return BlockColor.SNOW_BLOCK_COLOR; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockPressurePlateAcacia.java b/src/main/java/cn/nukkit/block/BlockPressurePlateAcacia.java new file mode 100644 index 00000000000..1543cafd353 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockPressurePlateAcacia.java @@ -0,0 +1,29 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockPressurePlateAcacia extends BlockPressurePlateWood { + + public BlockPressurePlateAcacia() { + this(0); + } + + public BlockPressurePlateAcacia(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Acacia Pressure Plate"; + } + + @Override + public int getId() { + return ACACIA_PRESSURE_PLATE; + } + + @Override + public BlockColor getColor() { + return BlockColor.ORANGE_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockPressurePlateBase.java b/src/main/java/cn/nukkit/block/BlockPressurePlateBase.java index 5bcc098a27c..182dc990659 100644 --- a/src/main/java/cn/nukkit/block/BlockPressurePlateBase.java +++ b/src/main/java/cn/nukkit/block/BlockPressurePlateBase.java @@ -9,7 +9,6 @@ import cn.nukkit.event.player.PlayerInteractEvent.Action; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; -import cn.nukkit.level.GlobalBlockPalette; import cn.nukkit.level.Level; import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.math.BlockFace; @@ -33,11 +32,6 @@ protected BlockPressurePlateBase(int meta) { super(meta); } - @Override - public boolean canPassThrough() { - return true; - } - @Override public boolean canHarvestWithHand() { return false; @@ -53,11 +47,6 @@ public double getMinZ() { return this.z + 0.625; } - @Override - public double getMinY() { - return this.y + 0; - } - @Override public double getMaxX() { return this.x + 0.9375; @@ -70,7 +59,7 @@ public double getMaxZ() { @Override public double getMaxY() { - return isActivated() ? this.y + 0.03125 : this.y + 0.0625; + return this.isActivated() ? this.y + 0.03125 : this.y + 0.0625; } @Override @@ -85,8 +74,7 @@ public boolean isActivated() { @Override public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_NORMAL) { - Block down = this.down(); - if (down.isTransparent() && !(down instanceof BlockFence)) { + if (!isSupportValid(this.down())) { this.level.useBreakOn(this, Item.get(Item.WOODEN_PICKAXE)); } } else if (type == Level.BLOCK_UPDATE_SCHEDULED) { @@ -102,15 +90,18 @@ public int onUpdate(int type) { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - Block down = block.down(); - if (down.isTransparent() && !(down instanceof BlockFence)) { + if (!isSupportValid(this.down())) { return false; } - this.level.setBlock(block, this, true, true); + this.getLevel().setBlock(this, this, true, true); return true; } + private static boolean isSupportValid(Block block) { + return !block.isTransparent() || block.isNarrowSurface() || Block.canStayOnFullSolid(block); + } + @Override protected AxisAlignedBB recalculateCollisionBoundingBox() { return new SimpleAxisAlignedBB(this.x + 0.125, this.y, this.z + 0.125, this.x + 0.875, this.y + 0.25, this.z + 0.875D); @@ -147,7 +138,7 @@ protected void updateState(int oldStrength) { this.level.setBlock(this, this, false, false); this.level.updateAroundRedstone(this, null); - this.level.updateAroundRedstone(this.getLocation().down(), null); + this.level.updateAroundRedstone(this.getSideVec(BlockFace.DOWN), null); if (!isPowered && wasPowered) { this.playOffSound(); @@ -169,7 +160,7 @@ public boolean onBreak(Item item) { if (this.getRedstonePower() > 0) { this.level.updateAroundRedstone(this, null); - this.level.updateAroundRedstone(this.getLocation().down(), null); + this.level.updateAroundRedstone(this.getSideVec(BlockFace.DOWN), null); } return true; @@ -194,17 +185,22 @@ public void setRedstonePower(int power) { } protected void playOnSound() { - this.level.addLevelSoundEvent(this.add(0.5, 0.1, 0.5), LevelSoundEventPacket.SOUND_POWER_ON, GlobalBlockPalette.getOrCreateRuntimeId(this.getId(), this.getDamage())); + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_POWER_ON); } protected void playOffSound() { - this.level.addLevelSoundEvent(this.add(0.5, 0.1, 0.5), LevelSoundEventPacket.SOUND_POWER_OFF, GlobalBlockPalette.getOrCreateRuntimeId(this.getId(), this.getDamage())); + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_POWER_OFF); } protected abstract int computeRedstoneStrength(); @Override public Item toItem() { - return new ItemBlock(this, 0, 1); + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public boolean breakWhenPushed() { + return true; } } diff --git a/src/main/java/cn/nukkit/block/BlockPressurePlateBirch.java b/src/main/java/cn/nukkit/block/BlockPressurePlateBirch.java new file mode 100644 index 00000000000..a17fda05033 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockPressurePlateBirch.java @@ -0,0 +1,29 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockPressurePlateBirch extends BlockPressurePlateWood { + + public BlockPressurePlateBirch() { + this(0); + } + + public BlockPressurePlateBirch(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Birch Pressure Plate"; + } + + @Override + public int getId() { + return BIRCH_PRESSURE_PLATE; + } + + @Override + public BlockColor getColor() { + return BlockColor.SAND_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockPressurePlateCrimson.java b/src/main/java/cn/nukkit/block/BlockPressurePlateCrimson.java new file mode 100644 index 00000000000..e8014b9d19b --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockPressurePlateCrimson.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockPressurePlateCrimson extends BlockPressurePlateWood { + + public BlockPressurePlateCrimson() { + this(0); + } + + public BlockPressurePlateCrimson(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Crimson Pressure Plate"; + } + + @Override + public int getId() { + return CRIMSON_PRESSURE_PLATE; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockPressurePlateDarkOak.java b/src/main/java/cn/nukkit/block/BlockPressurePlateDarkOak.java new file mode 100644 index 00000000000..0e5d6e89906 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockPressurePlateDarkOak.java @@ -0,0 +1,29 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockPressurePlateDarkOak extends BlockPressurePlateWood { + + public BlockPressurePlateDarkOak() { + this(0); + } + + public BlockPressurePlateDarkOak(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Dark Oak Pressure Plate"; + } + + @Override + public int getId() { + return DARK_OAK_PRESSURE_PLATE; + } + + @Override + public BlockColor getColor() { + return BlockColor.BROWN_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockPressurePlateJungle.java b/src/main/java/cn/nukkit/block/BlockPressurePlateJungle.java new file mode 100644 index 00000000000..e2ab97d937a --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockPressurePlateJungle.java @@ -0,0 +1,29 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockPressurePlateJungle extends BlockPressurePlateWood { + + public BlockPressurePlateJungle() { + this(0); + } + + public BlockPressurePlateJungle(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Jungle Pressure Plate"; + } + + @Override + public int getId() { + return JUNGLE_PRESSURE_PLATE; + } + + @Override + public BlockColor getColor() { + return BlockColor.DIRT_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockPressurePlatePolishedBlackstone.java b/src/main/java/cn/nukkit/block/BlockPressurePlatePolishedBlackstone.java new file mode 100644 index 00000000000..d63ff6c0e6b --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockPressurePlatePolishedBlackstone.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockPressurePlatePolishedBlackstone extends BlockPressurePlateStone { + + public BlockPressurePlatePolishedBlackstone() { + this(0); + } + + public BlockPressurePlatePolishedBlackstone(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Polished Blackstone Pressure Plate"; + } + + @Override + public int getId() { + return POLISHED_BLACKSTONE_PRESSURE_PLATE; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockPressurePlateSpruce.java b/src/main/java/cn/nukkit/block/BlockPressurePlateSpruce.java new file mode 100644 index 00000000000..fe84bd1e102 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockPressurePlateSpruce.java @@ -0,0 +1,29 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockPressurePlateSpruce extends BlockPressurePlateWood { + + public BlockPressurePlateSpruce() { + this(0); + } + + public BlockPressurePlateSpruce(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Spruce Pressure Plate"; + } + + @Override + public int getId() { + return SPRUCE_PRESSURE_PLATE; + } + + @Override + public BlockColor getColor() { + return BlockColor.SPRUCE_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockPressurePlateStone.java b/src/main/java/cn/nukkit/block/BlockPressurePlateStone.java index 2abf30e05d7..e18fa96f049 100644 --- a/src/main/java/cn/nukkit/block/BlockPressurePlateStone.java +++ b/src/main/java/cn/nukkit/block/BlockPressurePlateStone.java @@ -49,7 +49,7 @@ public int getToolType() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; diff --git a/src/main/java/cn/nukkit/block/BlockPressurePlateWarped.java b/src/main/java/cn/nukkit/block/BlockPressurePlateWarped.java new file mode 100644 index 00000000000..8523e4870e7 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockPressurePlateWarped.java @@ -0,0 +1,23 @@ +package cn.nukkit.block; + +public class BlockPressurePlateWarped extends BlockPressurePlateWood { + + public BlockPressurePlateWarped() { + this(0); + } + + public BlockPressurePlateWarped(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Warped Pressure Plate"; + } + + @Override + public int getId() { + return WARPED_PRESSURE_PLATE; + } +} + diff --git a/src/main/java/cn/nukkit/block/BlockPressurePlateWood.java b/src/main/java/cn/nukkit/block/BlockPressurePlateWood.java index 7588c91f9a9..a792424dcb5 100644 --- a/src/main/java/cn/nukkit/block/BlockPressurePlateWood.java +++ b/src/main/java/cn/nukkit/block/BlockPressurePlateWood.java @@ -23,7 +23,7 @@ public BlockPressurePlateWood() { @Override public String getName() { - return "Wooden Pressure Plate"; + return "Oak Pressure Plate"; } @Override @@ -38,12 +38,12 @@ public int getToolType() { @Override public double getHardness() { - return 0.5D; + return 0.1D; } @Override public double getResistance() { - return 2.5D; + return 0.5D; } @Override diff --git a/src/main/java/cn/nukkit/block/BlockPrismarine.java b/src/main/java/cn/nukkit/block/BlockPrismarine.java index 6073aeffa0c..73bbcb0b4d4 100644 --- a/src/main/java/cn/nukkit/block/BlockPrismarine.java +++ b/src/main/java/cn/nukkit/block/BlockPrismarine.java @@ -11,10 +11,10 @@ public class BlockPrismarine extends BlockSolidMeta { public static final int DARK = 1; public static final int BRICKS = 2; - private static final String[] NAMES = new String[]{ + private static final String[] NAMES = { "Prismarine", - "Dark prismarine", - "Prismarine bricks" + "Dark Prismarine", + "Prismarine Bricks" }; public BlockPrismarine() { @@ -52,7 +52,7 @@ public String getName() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; @@ -68,11 +68,11 @@ public boolean canHarvestWithHand() { @Override public BlockColor getColor() { - switch(getDamage() & 0x07){ + switch (getDamage() & 0x07) { case NORMAL: return BlockColor.CYAN_BLOCK_COLOR; - case DARK: case BRICKS: + case DARK: return BlockColor.DIAMOND_BLOCK_COLOR; default: return BlockColor.STONE_BLOCK_COLOR; diff --git a/src/main/java/cn/nukkit/block/BlockPumpkin.java b/src/main/java/cn/nukkit/block/BlockPumpkin.java index 82aabab6b0b..478900662d4 100644 --- a/src/main/java/cn/nukkit/block/BlockPumpkin.java +++ b/src/main/java/cn/nukkit/block/BlockPumpkin.java @@ -3,6 +3,7 @@ import cn.nukkit.Player; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemID; import cn.nukkit.item.ItemTool; import cn.nukkit.math.BlockFace; import cn.nukkit.utils.BlockColor; @@ -13,6 +14,7 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockPumpkin extends BlockSolidMeta implements Faceable { + public BlockPumpkin() { this(0); } @@ -48,12 +50,12 @@ public int getToolType() { @Override public Item toItem() { - return new ItemBlock(this, 0); + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - this.setDamage(player != null ? player.getDirection().getOpposite().getHorizontalIndex() : 0); + this.setBlockFace(player != null ? player.getDirection().getOpposite() : BlockFace.SOUTH); this.getLevel().setBlock(block, this, true, true); return true; } @@ -64,12 +66,36 @@ public BlockColor getColor() { } @Override - public boolean canBePushed() { - return false; + public BlockFace getBlockFace() { + return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); } @Override - public BlockFace getBlockFace() { - return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); + public boolean breakWhenPushed() { + return true; + } + + @Override + public boolean canBeActivated() { + return true; + } + + + @Override + public boolean onActivate(Item item, Player player) { + if (!item.isShears()) { + return false; + } + + BlockPumpkinCarved carvedPumpkin = new BlockPumpkinCarved(); + carvedPumpkin.setBlockFace(this.getBlockFace()); + item.useOn(this); + this.level.setBlock(this, carvedPumpkin, true, true); + this.getLevel().dropItem(add(0.5, 0.5, 0.5), Item.get(ItemID.PUMPKIN_SEEDS)); + this.getLevel().dropItem(add(0.5, 0.5, 0.5), Item.get(Item.PUMPKIN_SEEDS));return true; + } + + public void setBlockFace(BlockFace blockFace) { + this.setDamage(blockFace.getHorizontalIndex()); } } diff --git a/src/main/java/cn/nukkit/block/BlockPumpkinCarved.java b/src/main/java/cn/nukkit/block/BlockPumpkinCarved.java new file mode 100644 index 00000000000..1a5786f4cac --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockPumpkinCarved.java @@ -0,0 +1,26 @@ +package cn.nukkit.block; + +public class BlockPumpkinCarved extends BlockPumpkin { + + public BlockPumpkinCarved() { + } + + public BlockPumpkinCarved(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Carved Pumpkin"; + } + + @Override + public int getId() { + return CARVED_PUMPKIN; + } + + @Override + public boolean canBeActivated() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockPumpkinLit.java b/src/main/java/cn/nukkit/block/BlockPumpkinLit.java index 0f55f876885..8cad971779f 100644 --- a/src/main/java/cn/nukkit/block/BlockPumpkinLit.java +++ b/src/main/java/cn/nukkit/block/BlockPumpkinLit.java @@ -5,6 +5,7 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockPumpkinLit extends BlockPumpkin { + public BlockPumpkinLit() { this(0); } @@ -28,4 +29,8 @@ public int getLightLevel() { return 15; } + @Override + public boolean canBeActivated() { + return false; + } } diff --git a/src/main/java/cn/nukkit/block/BlockPurpur.java b/src/main/java/cn/nukkit/block/BlockPurpur.java index 3f611508142..782b5b24a93 100644 --- a/src/main/java/cn/nukkit/block/BlockPurpur.java +++ b/src/main/java/cn/nukkit/block/BlockPurpur.java @@ -12,24 +12,33 @@ public class BlockPurpur extends BlockSolidMeta { public static final int PURPUR_NORMAL = 0; public static final int PURPUR_PILLAR = 2; + private static final short[] FACES = { + 0, + 0, + 0b1000, + 0b1000, + 0b0100, + 0b0100 + }; + public BlockPurpur() { - this(0); + this(PURPUR_NORMAL); } public BlockPurpur(int meta) { super(meta); } + private static final String[] NAMES = { + "Purpur Block", + "", + "Purpur Pillar", + "" + }; + @Override public String getName() { - String[] names = new String[]{ - "Purpur Block", - "", - "Purpur Pillar", - "" - }; - - return names[this.getDamage() & 0x03]; + return NAMES[this.getDamage() & 0x03]; } @Override @@ -55,16 +64,7 @@ public int getToolType() { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { if (this.getDamage() != PURPUR_NORMAL) { - short[] faces = new short[]{ - 0, - 0, - 0b1000, - 0b1000, - 0b0100, - 0b0100 - }; - - this.setDamage(((this.getDamage() & 0x03) | faces[face.getIndex()])); + this.setDamage(((this.getDamage() & 0x03) | FACES[face.getIndex()])); } this.getLevel().setBlock(block, this, true, true); @@ -73,7 +73,7 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; @@ -84,7 +84,7 @@ public Item[] getDrops(Item item) { @Override public Item toItem() { - return new ItemBlock(Block.get(BlockID.PURPUR_BLOCK), this.getDamage() & 0x03, 1); + return new ItemBlock(Block.get(Block.PURPUR_BLOCK), this.getDamage() & 0x03, 1); } @Override diff --git a/src/main/java/cn/nukkit/block/BlockQuartz.java b/src/main/java/cn/nukkit/block/BlockQuartz.java index 2bacdbc1ff8..37d0eb608fe 100644 --- a/src/main/java/cn/nukkit/block/BlockQuartz.java +++ b/src/main/java/cn/nukkit/block/BlockQuartz.java @@ -8,7 +8,7 @@ import cn.nukkit.utils.BlockColor; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockQuartz extends BlockSolidMeta { @@ -16,8 +16,16 @@ public class BlockQuartz extends BlockSolidMeta { public static final int QUARTZ_NORMAL = 0; public static final int QUARTZ_CHISELED = 1; public static final int QUARTZ_PILLAR = 2; - public static final int QUARTZ_PILLAR2 = 3; + public static final int QUARTZ_SMOOTH = 3; + private static final short[] FACES = { + 0, + 0, + 0b1000, + 0b1000, + 0b0100, + 0b0100 + }; public BlockQuartz() { this(0); @@ -42,31 +50,22 @@ public double getResistance() { return 4; } + private static final String[] NAMES = { + "Block of Quartz", + "Chiseled Quartz Block", + "Quartz Pillar Block", + "Smooth Quartz Block" + }; + @Override public String getName() { - String[] names = new String[]{ - "Quartz Block", - "Chiseled Quartz Block", - "Quartz Pillar", - "Quartz Pillar" - }; - - return names[this.getDamage() & 0x03]; + return NAMES[this.getDamage() & 0x03]; } @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { if (this.getDamage() != QUARTZ_NORMAL) { - short[] faces = new short[]{ - 0, - 0, - 0b1000, - 0b1000, - 0b0100, - 0b0100 - }; - - this.setDamage(((this.getDamage() & 0x03) | faces[face.getIndex()])); + this.setDamage(((this.getDamage() & 0x03) | FACES[face.getIndex()])); } this.getLevel().setBlock(block, this, true, true); @@ -75,7 +74,7 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; @@ -86,7 +85,7 @@ public Item[] getDrops(Item item) { @Override public Item toItem() { - return new ItemBlock(Block.get(BlockID.QUARTZ_BLOCK), this.getDamage() & 0x03, 1); + return new ItemBlock(this, this.getDamage() & 0x03, 1); } @Override diff --git a/src/main/java/cn/nukkit/block/BlockQuartzBricks.java b/src/main/java/cn/nukkit/block/BlockQuartzBricks.java new file mode 100644 index 00000000000..93983ec9c83 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockQuartzBricks.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockQuartzBricks extends BlockQuartz { + + public BlockQuartzBricks() { + this(0); + } + + public BlockQuartzBricks(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Quartz Bricks"; + } + + @Override + public int getId() { + return QUARTZ_BRICKS; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockRail.java b/src/main/java/cn/nukkit/block/BlockRail.java index e7f348763ce..8cc7a77c437 100644 --- a/src/main/java/cn/nukkit/block/BlockRail.java +++ b/src/main/java/cn/nukkit/block/BlockRail.java @@ -58,11 +58,6 @@ public double getResistance() { return 3.5; } - @Override - public boolean canPassThrough() { - return true; - } - @Override public int getToolType() { return ItemTool.TYPE_PICKAXE; @@ -72,23 +67,73 @@ public int getToolType() { public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_NORMAL) { Optional ascendingDirection = this.getOrientation().ascendingDirection(); - Block down = this.down(); - if ((down.isTransparent() && down.getId() != HOPPER_BLOCK) || (ascendingDirection.isPresent() && this.getSide(ascendingDirection.get()).isTransparent())) { + if (!canStayOnFullSolid(this.down()) || (ascendingDirection.isPresent() && this.getSide(ascendingDirection.get()).isTransparent())) { this.getLevel().useBreakOn(this); return Level.BLOCK_UPDATE_NORMAL; } + } else if (type == Level.BLOCK_UPDATE_REDSTONE) { + if (this instanceof BlockRailPowered || this instanceof BlockRailDetector || this instanceof BlockRailActivator) { + return 0; + } + boolean power = level.isBlockPowered(this); + Map railsAround = this.checkRailsAround(Arrays.asList(SOUTH, EAST, WEST, NORTH)); + int railsAmount = railsAround.size(); + if (railsAmount <= 2) { + return 0; + } + List rails = new ArrayList<>(railsAround.keySet()); + List faces = new ArrayList<>(railsAround.values()); + if (railsAmount == 4) { + if (this.isAbstract()) { + if (power) { + this.setDamage(this.connect(rails.get(faces.indexOf(NORTH)), NORTH, rails.get(faces.indexOf(WEST)), WEST).metadata()); + } else { + this.setDamage(this.connect(rails.get(faces.indexOf(SOUTH)), SOUTH, rails.get(faces.indexOf(EAST)), EAST).metadata()); + } + } else { + this.setDamage(this.connect(rails.get(faces.indexOf(EAST)), EAST, rails.get(faces.indexOf(WEST)), WEST).metadata()); + } + } else if (!railsAround.isEmpty()) { + if (this.isAbstract()) { + List cd; + if (power) { + cd = Stream.of(CURVED_NORTH_WEST, CURVED_SOUTH_WEST, CURVED_NORTH_EAST) + .filter(o -> faces.containsAll(o.connectingDirections())) + .findFirst().get().connectingDirections(); + } else { + cd = Stream.of(CURVED_SOUTH_EAST, CURVED_NORTH_EAST, CURVED_SOUTH_WEST) + .filter(o -> faces.containsAll(o.connectingDirections())) + .findFirst().get().connectingDirections(); + } + BlockFace f1 = cd.get(0); + BlockFace f2 = cd.get(1); + this.setDamage(this.connect(rails.get(faces.indexOf(f1)), f1, rails.get(faces.indexOf(f2)), f2).metadata()); + } else { + BlockFace face = faces.stream().min((f1, f2) -> (f1.getIndex() < f2.getIndex()) ? 1 : ((x == y) ? 0 : -1)).get(); + BlockFace opposite = face.getOpposite(); + if (faces.contains(opposite)) { + this.setDamage(this.connect(rails.get(faces.indexOf(face)), face, rails.get(faces.indexOf(opposite)), opposite).metadata()); + } else { + this.setDamage(this.connect(rails.get(faces.indexOf(face)), face).metadata()); + } + } + } + this.level.setBlock(this, this, true, true); + if (!isAbstract()) { + level.scheduleUpdate(this, this, 0); + } } return 0; } @Override - public double getMaxY() { - return this.y + 0.125; + public AxisAlignedBB recalculateBoundingBox() { + return this; } @Override - public AxisAlignedBB recalculateBoundingBox() { - return this; + public double getMaxY() { + return this.y + 0.125; } @Override @@ -99,8 +144,7 @@ public BlockColor getColor() { //Information from http://minecraft.gamepedia.com/Rail @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - Block down = this.down(); - if (down == null || (down.isTransparent() && down.getId() != HOPPER_BLOCK)) { + if (!canStayOnFullSolid(this.down())) { return false; } Map railsAround = this.checkRailsAroundAffected(); @@ -139,7 +183,7 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl } } } - this.level.setBlock(this, this, true, true); + this.getLevel().setBlock(this, this, true, true); if (!isAbstract()) { level.scheduleUpdate(this, this, 0); } @@ -259,18 +303,28 @@ public void setActive(boolean active) { @Override public Item toItem() { - return new ItemBlock(this, 0); + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override public Item[] getDrops(Item item) { return new Item[]{ - Item.get(Item.RAIL, 0, 1) + Item.get(Item.RAIL) }; } @Override public BlockFace getBlockFace() { - return BlockFace.fromHorizontalIndex(this.getDamage() & 0x07); + return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); + } + + @Override + public boolean canBeFlowedInto() { + return false; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; } } diff --git a/src/main/java/cn/nukkit/block/BlockRailActivator.java b/src/main/java/cn/nukkit/block/BlockRailActivator.java index c48fa6a4d4a..fb96d19a355 100644 --- a/src/main/java/cn/nukkit/block/BlockRailActivator.java +++ b/src/main/java/cn/nukkit/block/BlockRailActivator.java @@ -1,7 +1,9 @@ package cn.nukkit.block; import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; import cn.nukkit.math.Vector3; import cn.nukkit.utils.Rail; @@ -36,21 +38,15 @@ public int onUpdate(int type) { return 0; // Already broken } - boolean wasPowered = isActive(); - boolean isPowered = level.isBlockPowered(this.getLocation()) + boolean isPowered = level.isBlockPowered(this) || checkSurrounding(this, true, 0) || checkSurrounding(this, false, 0); - boolean hasUpdate = false; - if (wasPowered != isPowered) { + if (isActive() != isPowered) { setActive(isPowered); - hasUpdate = true; - } - - if (hasUpdate) { - level.updateAround(down()); + level.updateAround(getSideVec(BlockFace.DOWN)); if (getOrientation().isAscending()) { - level.updateAround(up()); + level.updateAround(getSideVec(BlockFace.UP)); } } return type; @@ -75,7 +71,7 @@ protected boolean checkSurrounding(Vector3 pos, boolean relative, int power) { int dz = pos.getFloorZ(); BlockRail block; - Block block2 = level.getBlock(new Vector3(dx, dy, dz)); + Block block2 = level.getBlock(dx, dy, dz); if (Rail.isRailBlock(block2)) { block = (BlockRail) block2; @@ -145,12 +141,12 @@ protected boolean checkSurrounding(Vector3 pos, boolean relative, int power) { return false; } - return canPowered(new Vector3(dx, dy, dz), base, power, relative) - || onStraight && canPowered(new Vector3(dx, dy - 1, dz), base, power, relative); + return canPowered(dx, dy, dz, base, power, relative) + || onStraight && canPowered(dx, dy - 1, dz, base, power, relative); } - protected boolean canPowered(Vector3 pos, Rail.Orientation state, int power, boolean relative) { - Block block = level.getBlock(pos); + protected boolean canPowered(int x, int y, int z, Rail.Orientation state, int power, boolean relative) { + Block block = level.getBlock(x, y, z); if (!(block instanceof BlockRailActivator)) { return false; @@ -166,18 +162,23 @@ protected boolean canPowered(Vector3 pos, Rail.Orientation state, int power, boo || base != Rail.Orientation.STRAIGHT_EAST_WEST && base != Rail.Orientation.ASCENDING_EAST && base != Rail.Orientation.ASCENDING_WEST) - && (level.isBlockPowered(pos) || checkSurrounding(pos, relative, power + 1)); + && (level.isBlockPowered(block) || checkSurrounding(block, relative, power + 1)); + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override public Item[] getDrops(Item item) { return new Item[]{ - Item.get(Item.ACTIVATOR_RAIL, 0, 1) + toItem() }; } @Override public double getHardness() { - return 0.5; + return 0.5; // 0.7 } } diff --git a/src/main/java/cn/nukkit/block/BlockRailDetector.java b/src/main/java/cn/nukkit/block/BlockRailDetector.java index 28f83f07b81..f28c6cd6555 100644 --- a/src/main/java/cn/nukkit/block/BlockRailDetector.java +++ b/src/main/java/cn/nukkit/block/BlockRailDetector.java @@ -3,6 +3,7 @@ import cn.nukkit.entity.Entity; import cn.nukkit.entity.item.EntityMinecartAbstract; import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; import cn.nukkit.math.SimpleAxisAlignedBB; @@ -48,7 +49,7 @@ public int getWeakPower(BlockFace side) { @Override public int getStrongPower(BlockFace side) { - return isActive() ? 0 : (side == BlockFace.UP ? 15 : 0); + return !isActive() ? 0 : (side == BlockFace.UP ? 15 : 0); } @Override @@ -60,6 +61,11 @@ public int onUpdate(int type) { return super.onUpdate(type); } + @Override + public boolean hasEntityCollision() { + return true; + } + @Override public void onEntityCollide(Entity entity) { updateState(); @@ -68,13 +74,14 @@ public void onEntityCollide(Entity entity) { protected void updateState() { boolean wasPowered = isActive(); boolean isPowered = false; + boolean changed = false; - for (Entity entity : level.getNearbyEntities(new SimpleAxisAlignedBB( + for (Entity entity : level.getCollidingEntities(new SimpleAxisAlignedBB( getFloorX() + 0.125D, getFloorY(), getFloorZ() + 0.125D, getFloorX() + 0.875D, - getFloorY() + 0.525D, + getFloorY() + 0.750D, getFloorZ() + 0.875D))) { if (entity instanceof EntityMinecartAbstract) { isPowered = true; @@ -85,22 +92,31 @@ protected void updateState() { if (isPowered && !wasPowered) { setActive(true); level.scheduleUpdate(this, this, 0); - level.scheduleUpdate(this, this.down(), 0); + level.scheduleUpdate(this, this.getSideVec(BlockFace.DOWN), 0); + changed = true; } if (!isPowered && wasPowered) { setActive(false); level.scheduleUpdate(this, this, 0); - level.scheduleUpdate(this, this.down(), 0); + level.scheduleUpdate(this, this.getSideVec(BlockFace.DOWN), 0); + changed = true; } - level.updateComparatorOutputLevel(this); + if (changed) { + level.updateComparatorOutputLevel(this); + } + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override public Item[] getDrops(Item item) { return new Item[]{ - Item.get(Item.DETECTOR_RAIL, 0, 1) + toItem() }; } } diff --git a/src/main/java/cn/nukkit/block/BlockRailPowered.java b/src/main/java/cn/nukkit/block/BlockRailPowered.java index 83a88072314..4533505baaa 100644 --- a/src/main/java/cn/nukkit/block/BlockRailPowered.java +++ b/src/main/java/cn/nukkit/block/BlockRailPowered.java @@ -1,7 +1,9 @@ package cn.nukkit.block; import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; import cn.nukkit.math.Vector3; import cn.nukkit.utils.Rail; @@ -36,25 +38,20 @@ public String getName() { @Override public int onUpdate(int type) { - // Warning: I din't recommended this on slow networks server or slow client - // Network below 86Kb/s. This will became unresponsive to clients - // When updating the block state. Espicially on the world with many rails. - // Trust me, I tested this on my server. if (type == Level.BLOCK_UPDATE_NORMAL || type == Level.BLOCK_UPDATE_REDSTONE || type == Level.BLOCK_UPDATE_SCHEDULED) { if (super.onUpdate(type) == Level.BLOCK_UPDATE_NORMAL) { return 0; // Already broken } - boolean wasPowered = isActive(); - boolean isPowered = level.isBlockPowered(this.getLocation()) + + boolean isPowered = level.isBlockPowered(this) || checkSurrounding(this, true, 0) || checkSurrounding(this, false, 0); - // Avoid Block minstake - if (wasPowered != isPowered) { + if (isActive() != isPowered) { setActive(isPowered); - level.updateAround(down()); + level.updateAround(this.getSideVec(BlockFace.DOWN)); if (getOrientation().isAscending()) { - level.updateAround(up()); + level.updateAround(this.getSideVec(BlockFace.UP)); } } return type; @@ -81,7 +78,7 @@ protected boolean checkSurrounding(Vector3 pos, boolean relative, int power) { int dz = pos.getFloorZ(); // First: get the base block BlockRail block; - Block block2 = level.getBlock(new Vector3(dx, dy, dz)); + Block block2 = level.getBlock(dx, dy, dz); // Second: check if the rail is Powered rail if (Rail.isRailBlock(block2)) { @@ -155,12 +152,12 @@ protected boolean checkSurrounding(Vector3 pos, boolean relative, int power) { return false; } // Next check the if rail is on power state - return canPowered(new Vector3(dx, dy, dz), base, power, relative) - || onStraight && canPowered(new Vector3(dx, dy - 1, dz), base, power, relative); + return canPowered(dx, dy, dz, base, power, relative) + || onStraight && canPowered(dx, dy - 1, dz, base, power, relative); } - protected boolean canPowered(Vector3 pos, Rail.Orientation state, int power, boolean relative) { - Block block = level.getBlock(pos); + protected boolean canPowered(int x, int y, int z, Rail.Orientation state, int power, boolean relative) { + Block block = level.getBlock(x, y, z); // What! My block is air??!! Impossible! XD if (!(block instanceof BlockRailPowered)) { return false; @@ -179,13 +176,18 @@ protected boolean canPowered(Vector3 pos, Rail.Orientation state, int power, boo || base != Rail.Orientation.STRAIGHT_EAST_WEST && base != Rail.Orientation.ASCENDING_EAST && base != Rail.Orientation.ASCENDING_WEST) - && (level.isBlockPowered(pos) || checkSurrounding(pos, relative, power + 1)); + && (level.isBlockPowered(block) || checkSurrounding(block, relative, power + 1)); + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override public Item[] getDrops(Item item) { return new Item[]{ - Item.get(Item.POWERED_RAIL, 0, 1) + toItem() }; } } diff --git a/src/main/java/cn/nukkit/block/BlockRawCopper.java b/src/main/java/cn/nukkit/block/BlockRawCopper.java new file mode 100644 index 00000000000..d2c7cd86d7c --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockRawCopper.java @@ -0,0 +1,17 @@ +package cn.nukkit.block; + +public class BlockRawCopper extends BlockRawOreVariant { + + public BlockRawCopper() { + } + + @Override + public String getName() { + return "Block of Raw Copper"; + } + + @Override + public int getId() { + return RAW_COPPER_BLOCK; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockRawGold.java b/src/main/java/cn/nukkit/block/BlockRawGold.java new file mode 100644 index 00000000000..b907481662d --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockRawGold.java @@ -0,0 +1,24 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; + +public class BlockRawGold extends BlockRawOreVariant { + + public BlockRawGold() { + } + + @Override + public String getName() { + return "Block of Raw Gold"; + } + + @Override + public int getId() { + return RAW_GOLD_BLOCK; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_IRON; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockRawIron.java b/src/main/java/cn/nukkit/block/BlockRawIron.java new file mode 100644 index 00000000000..2a94a5e2fed --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockRawIron.java @@ -0,0 +1,17 @@ +package cn.nukkit.block; + +public class BlockRawIron extends BlockRawOreVariant { + + public BlockRawIron() { + } + + @Override + public String getName() { + return "Block of Raw Iron"; + } + + @Override + public int getId() { + return RAW_IRON_BLOCK; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockRawOreVariant.java b/src/main/java/cn/nukkit/block/BlockRawOreVariant.java new file mode 100644 index 00000000000..369d62ff264 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockRawOreVariant.java @@ -0,0 +1,50 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; + +public abstract class BlockRawOreVariant extends BlockSolid { + + public BlockRawOreVariant() { + } + + @Override + public double getHardness() { + return 5; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public Item[] getDrops(Item item) { + if (item.getTier() < this.getToolTier()) { + return new Item[0]; + } + return super.getDrops(item); + } + + @Override + public int getToolTier() { + return ItemTool.TIER_STONE; + } + + // TODO: + /*@Override + public boolean isLavaResistant() { + return true; + }*/ + +} diff --git a/src/main/java/cn/nukkit/block/BlockRedSandstone.java b/src/main/java/cn/nukkit/block/BlockRedSandstone.java index 4439e716df8..152ade0d0d1 100644 --- a/src/main/java/cn/nukkit/block/BlockRedSandstone.java +++ b/src/main/java/cn/nukkit/block/BlockRedSandstone.java @@ -2,7 +2,6 @@ import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; -import cn.nukkit.item.ItemTool; import cn.nukkit.utils.BlockColor; /** @@ -23,21 +22,21 @@ public int getId() { return RED_SANDSTONE; } + private static final String[] NAMES = { + "Red Sandstone", + "Chiseled Red Sandstone", + "Cut Red Sandstone", + "Smooth Red Sandstone" + }; + @Override public String getName() { - String[] names = new String[]{ - "Red Sandstone", - "Chiseled Red Sandstone", - "Smooth Red Sandstone", - "" - }; - - return names[this.getDamage() & 0x03]; + return NAMES[this.getDamage() & 0x03]; } @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; @@ -51,11 +50,6 @@ public Item toItem() { return new ItemBlock(this, this.getDamage() & 0x03); } - @Override - public boolean canHarvestWithHand() { - return false; - } - @Override public BlockColor getColor() { return BlockColor.ORANGE_BLOCK_COLOR; diff --git a/src/main/java/cn/nukkit/block/BlockRedstone.java b/src/main/java/cn/nukkit/block/BlockRedstone.java index 19f8d33e01c..e44ec885d5f 100644 --- a/src/main/java/cn/nukkit/block/BlockRedstone.java +++ b/src/main/java/cn/nukkit/block/BlockRedstone.java @@ -1,5 +1,6 @@ package cn.nukkit.block; +import cn.nukkit.Player; import cn.nukkit.item.Item; import cn.nukkit.item.ItemTool; import cn.nukkit.math.BlockFace; @@ -9,15 +10,7 @@ * Created on 2015/12/11 by Pub4Game. * Package cn.nukkit.block in project Nukkit . */ -public class BlockRedstone extends BlockSolidMeta { - - public BlockRedstone() { - this(0); - } - - public BlockRedstone(int meta) { - super(0); - } +public class BlockRedstone extends BlockSolid { @Override public int getId() { @@ -41,14 +34,30 @@ public int getToolType() { @Override public String getName() { - return "Redstone Block"; + return "Block of Redstone"; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (!super.place(item, block, target, face, fx, fy, fz, player)) { + return false; + } + this.level.updateAroundRedstone(this, null); + return true; } - //TODO: redstone + @Override + public boolean onBreak(Item item) { + if (!super.onBreak(item)) { + return false; + } + this.level.updateAroundRedstone(this, null); + return true; + } @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; @@ -76,4 +85,9 @@ public int getWeakPower(BlockFace face) { public boolean canHarvestWithHand() { return false; } -} \ No newline at end of file + + @Override + public boolean canBePushed() { + return false; // TODO: remove when crash issue fixed + } +} diff --git a/src/main/java/cn/nukkit/block/BlockRedstoneComparator.java b/src/main/java/cn/nukkit/block/BlockRedstoneComparator.java index 11d5711c0cd..05229a25ab5 100644 --- a/src/main/java/cn/nukkit/block/BlockRedstoneComparator.java +++ b/src/main/java/cn/nukkit/block/BlockRedstoneComparator.java @@ -4,12 +4,11 @@ import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.blockentity.BlockEntityComparator; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemRedstoneComparator; import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.ListTag; -import cn.nukkit.network.protocol.LevelEventPacket; +import cn.nukkit.network.protocol.LevelSoundEventPacket; import cn.nukkit.utils.BlockColor; /** @@ -41,12 +40,12 @@ public Mode getMode() { @Override protected BlockRedstoneComparator getUnpowered() { - return (BlockRedstoneComparator) Block.get(BlockID.UNPOWERED_COMPARATOR, this.getDamage()); + return (BlockRedstoneComparator) Block.get(UNPOWERED_COMPARATOR, this.getDamage()); } @Override protected BlockRedstoneComparator getPowered() { - return (BlockRedstoneComparator) Block.get(BlockID.POWERED_COMPARATOR, this.getDamage()); + return (BlockRedstoneComparator) Block.get(POWERED_COMPARATOR, this.getDamage()); } @Override @@ -64,13 +63,12 @@ public void updateState() { int power = blockEntity instanceof BlockEntityComparator ? ((BlockEntityComparator) blockEntity).getOutputSignal() : 0; if (output != power || this.isPowered() != this.shouldBePowered()) { - /*if(isFacingTowardsRepeater()) { + /*if (isFacingTowardsRepeater()) { this.level.scheduleUpdate(this, this, 2, -1); } else { this.level.scheduleUpdate(this, this, 2, 0); }*/ - //System.out.println("schedule update 0"); this.level.scheduleUpdate(this, this, 2); } } @@ -119,9 +117,12 @@ public boolean onActivate(Item item, Player player) { this.setDamage(this.getDamage() + 4); } - this.level.addLevelEvent(this.add(0.5, 0.5, 0.5), LevelEventPacket.EVENT_SOUND_BUTTON_CLICK, this.getMode() == Mode.SUBTRACT ? 500 : 550); + if (this.getMode() == Mode.SUBTRACT) { + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_POWER_ON); + } else { + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_POWER_OFF); + } this.level.setBlock(this, this, true, false); - //bug? this.onChange(); return true; @@ -158,7 +159,10 @@ private void onChange() { this.level.setBlock(this, getPowered(), true, false); } - this.level.updateAroundRedstone(this, null); + this.level.updateAroundRedstone(this, null); //TODO: remove + //Block side = this.getSide(getFacing().getOpposite()); + //side.onUpdate(Level.BLOCK_UPDATE_REDSTONE); + //this.level.updateAroundRedstone(side, null); } } @@ -171,10 +175,8 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl .putInt("x", (int) this.x) .putInt("y", (int) this.y) .putInt("z", (int) this.z); - BlockEntityComparator comparator = (BlockEntityComparator) BlockEntity.createBlockEntity(BlockEntity.COMPARATOR, this.level.getChunk((int) this.x >> 4, (int) this.z >> 4), nbt); - if (comparator == null) { - return false; - } + BlockEntity.createBlockEntity(BlockEntity.COMPARATOR, this.getChunk(), nbt); + onUpdate(Level.BLOCK_UPDATE_REDSTONE); return true; } @@ -189,7 +191,7 @@ public boolean isPowered() { @Override public Item toItem() { - return new ItemRedstoneComparator(); + return Item.get(Item.COMPARATOR); } public enum Mode { @@ -201,4 +203,9 @@ public enum Mode { public BlockColor getColor() { return BlockColor.AIR_BLOCK_COLOR; } + + @Override + public boolean canBePushed() { + return false; // prevent item loss issue with pistons until a working implementation + } } diff --git a/src/main/java/cn/nukkit/block/BlockRedstoneDiode.java b/src/main/java/cn/nukkit/block/BlockRedstoneDiode.java index 668d3853bfb..9dd0ed9faa8 100644 --- a/src/main/java/cn/nukkit/block/BlockRedstoneDiode.java +++ b/src/main/java/cn/nukkit/block/BlockRedstoneDiode.java @@ -26,18 +26,18 @@ public BlockRedstoneDiode(int meta) { @Override public boolean onBreak(Item item) { - Vector3 pos = getLocation(); this.level.setBlock(this, Block.get(BlockID.AIR), true, true); for (BlockFace face : BlockFace.values()) { - this.level.updateAroundRedstone(pos.getSide(face), null); + this.level.updateAroundRedstone(this.getSideVec(face), null); } + return true; } @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - if (block.getSide(BlockFace.DOWN).isTransparent()) { + if (!canStayOnFullSolid(this.down())) { return false; } @@ -54,19 +54,17 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_SCHEDULED) { if (!this.isLocked()) { - Vector3 pos = getLocation(); boolean shouldBePowered = this.shouldBePowered(); if (this.isPowered && !shouldBePowered) { - this.level.setBlock(pos, this.getUnpowered(), true, true); + this.level.setBlock(this, this.getUnpowered(), true, true); - this.level.updateAroundRedstone(this.getLocation().getSide(getFacing().getOpposite()), null); + this.level.updateAroundRedstone(this.getSideVec(getFacing().getOpposite()), null); } else if (!this.isPowered) { - this.level.setBlock(pos, this.getPowered(), true, true); - this.level.updateAroundRedstone(this.getLocation().getSide(getFacing().getOpposite()), null); + this.level.setBlock(this, this.getPowered(), true, true); + this.level.updateAroundRedstone(this.getSideVec(getFacing().getOpposite()), null); if (!shouldBePowered) { -// System.out.println("schedule update 2"); level.scheduleUpdate(getPowered(), this, this.getDelay()); } } @@ -78,13 +76,12 @@ public int onUpdate(int type) { if (ev.isCancelled()) { return 0; } - if (type == Level.BLOCK_UPDATE_NORMAL && this.getSide(BlockFace.DOWN).isTransparent()) { + if (type == Level.BLOCK_UPDATE_NORMAL && !canStayOnFullSolid(this.down())) { this.level.useBreakOn(this); - return Level.BLOCK_UPDATE_NORMAL; } else { this.updateState(); - return Level.BLOCK_UPDATE_NORMAL; } + return Level.BLOCK_UPDATE_NORMAL; } return 0; } @@ -113,7 +110,7 @@ public boolean isLocked() { protected int calculateInputStrength() { BlockFace face = getFacing(); - Vector3 pos = this.getLocation().getSide(face); + Vector3 pos = this.getSideVec(face); int power = this.level.getRedstonePower(pos, face); if (power >= 15) { @@ -125,12 +122,10 @@ protected int calculateInputStrength() { } protected int getPowerOnSides() { - Vector3 pos = getLocation(); - BlockFace face = getFacing(); BlockFace face1 = face.rotateY(); BlockFace face2 = face.rotateYCCW(); - return Math.max(this.getPowerOnSide(pos.getSide(face1), face1), this.getPowerOnSide(pos.getSide(face2), face2)); + return Math.max(this.getPowerOnSide(this.getSideVec(face1), face1), this.getPowerOnSide(this.getSideVec(face2), face2)); } protected int getPowerOnSide(Vector3 pos, BlockFace side) { @@ -202,11 +197,26 @@ public boolean isFacingTowardsRepeater() { @Override public BlockFace getBlockFace() { - return BlockFace.fromHorizontalIndex(this.getDamage() & 0x07); + return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); } @Override public BlockColor getColor() { return BlockColor.AIR_BLOCK_COLOR; } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.FLOW_INTO_BLOCK; + } + + @Override + public boolean canBeFlowedInto() { + return false; + } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockRedstoneLamp.java b/src/main/java/cn/nukkit/block/BlockRedstoneLamp.java index d812b27b55a..b26d471f725 100644 --- a/src/main/java/cn/nukkit/block/BlockRedstoneLamp.java +++ b/src/main/java/cn/nukkit/block/BlockRedstoneLamp.java @@ -14,9 +14,6 @@ */ public class BlockRedstoneLamp extends BlockSolid { - public BlockRedstoneLamp() { - } - @Override public String getName() { return "Redstone Lamp"; @@ -44,8 +41,8 @@ public int getToolType() { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - if (this.level.isBlockPowered(this.getLocation())) { - this.level.setBlock(this, Block.get(BlockID.LIT_REDSTONE_LAMP), false, true); + if (this.level.isBlockPowered(this)) { + this.level.setBlock(this, Block.get(LIT_REDSTONE_LAMP), false, true); } else { this.level.setBlock(this, this, false, true); } @@ -61,8 +58,8 @@ public int onUpdate(int type) { if (ev.isCancelled()) { return 0; } - if (this.level.isBlockPowered(this.getLocation())) { - this.level.setBlock(this, Block.get(BlockID.LIT_REDSTONE_LAMP), false, false); + if (this.level.isBlockPowered(this)) { + this.level.setBlock(this, Block.get(LIT_REDSTONE_LAMP), false, false); return 1; } } @@ -73,7 +70,7 @@ public int onUpdate(int type) { @Override public Item[] getDrops(Item item) { return new Item[]{ - new ItemBlock(Block.get(BlockID.REDSTONE_LAMP)) + new ItemBlock(Block.get(REDSTONE_LAMP)) }; } diff --git a/src/main/java/cn/nukkit/block/BlockRedstoneLampLit.java b/src/main/java/cn/nukkit/block/BlockRedstoneLampLit.java index 876e847bb82..7d547700129 100644 --- a/src/main/java/cn/nukkit/block/BlockRedstoneLampLit.java +++ b/src/main/java/cn/nukkit/block/BlockRedstoneLampLit.java @@ -10,9 +10,6 @@ */ public class BlockRedstoneLampLit extends BlockRedstoneLamp { - public BlockRedstoneLampLit() { - } - @Override public String getName() { return "Lit Redstone Lamp"; @@ -30,13 +27,12 @@ public int getLightLevel() { @Override public Item toItem() { - return new ItemBlock(Block.get(BlockID.REDSTONE_LAMP)); + return new ItemBlock(Block.get(REDSTONE_LAMP)); } @Override public int onUpdate(int type) { - if ((type == Level.BLOCK_UPDATE_NORMAL || type == Level.BLOCK_UPDATE_REDSTONE) && !this.level.isBlockPowered(this.getLocation())) { - // Redstone event + if ((type == Level.BLOCK_UPDATE_NORMAL || type == Level.BLOCK_UPDATE_REDSTONE) && !this.level.isBlockPowered(this)) { RedstoneUpdateEvent ev = new RedstoneUpdateEvent(this); getLevel().getServer().getPluginManager().callEvent(ev); if (ev.isCancelled()) { @@ -46,8 +42,8 @@ public int onUpdate(int type) { return 1; } - if (type == Level.BLOCK_UPDATE_SCHEDULED && !this.level.isBlockPowered(this.getLocation())) { - this.level.setBlock(this, Block.get(BlockID.REDSTONE_LAMP), false, false); + if (type == Level.BLOCK_UPDATE_SCHEDULED && !this.level.isBlockPowered(this)) { + this.level.setBlock(this, Block.get(REDSTONE_LAMP), false, false); } return 0; } diff --git a/src/main/java/cn/nukkit/block/BlockRedstoneRepeaterPowered.java b/src/main/java/cn/nukkit/block/BlockRedstoneRepeaterPowered.java index 18bac5eccde..c02a7ecca2a 100644 --- a/src/main/java/cn/nukkit/block/BlockRedstoneRepeaterPowered.java +++ b/src/main/java/cn/nukkit/block/BlockRedstoneRepeaterPowered.java @@ -2,7 +2,6 @@ import cn.nukkit.Player; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemRedstoneRepeater; import cn.nukkit.math.BlockFace; /** @@ -41,12 +40,12 @@ protected boolean isAlternateInput(Block block) { @Override public Item toItem() { - return new ItemRedstoneRepeater(); + return Item.get(Item.REPEATER); } @Override protected int getDelay() { - return (1 + (getDamage() >> 2)) * 2; + return (1 + (getDamage() >> 2)) << 1; } @Override @@ -56,7 +55,7 @@ protected Block getPowered() { @Override protected Block getUnpowered() { - return Block.get(BlockID.UNPOWERED_REPEATER, this.getDamage()); + return Block.get(UNPOWERED_REPEATER, this.getDamage()); } @Override diff --git a/src/main/java/cn/nukkit/block/BlockRedstoneRepeaterUnpowered.java b/src/main/java/cn/nukkit/block/BlockRedstoneRepeaterUnpowered.java index 47e376018c1..81950f605f1 100644 --- a/src/main/java/cn/nukkit/block/BlockRedstoneRepeaterUnpowered.java +++ b/src/main/java/cn/nukkit/block/BlockRedstoneRepeaterUnpowered.java @@ -2,7 +2,6 @@ import cn.nukkit.Player; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemRedstoneRepeater; import cn.nukkit.math.BlockFace; /** @@ -50,17 +49,17 @@ protected boolean isAlternateInput(Block block) { @Override public Item toItem() { - return new ItemRedstoneRepeater(); + return Item.get(Item.REPEATER); } @Override protected int getDelay() { - return (1 + (getDamage() >> 2)) * 2; + return (1 + (getDamage() >> 2)) << 1; } @Override protected Block getPowered() { - return Block.get(BlockID.POWERED_REPEATER, this.getDamage()); + return Block.get(POWERED_REPEATER, this.getDamage()); } @Override @@ -72,4 +71,4 @@ protected Block getUnpowered() { public boolean isLocked() { return this.getPowerOnSides() > 0; } -} \ No newline at end of file +} diff --git a/src/main/java/cn/nukkit/block/BlockRedstoneTorch.java b/src/main/java/cn/nukkit/block/BlockRedstoneTorch.java index 4619dd35f48..e832da6faa7 100644 --- a/src/main/java/cn/nukkit/block/BlockRedstoneTorch.java +++ b/src/main/java/cn/nukkit/block/BlockRedstoneTorch.java @@ -5,14 +5,14 @@ import cn.nukkit.item.Item; import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; -import cn.nukkit.math.Vector3; import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.Faceable; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ -public class BlockRedstoneTorch extends BlockTorch { +public class BlockRedstoneTorch extends BlockTorch implements Faceable { public BlockRedstoneTorch() { this(0); @@ -43,19 +43,6 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl return false; } -// if (!checkState()) { -// BlockFace facing = getFacing().getOpposite(); -// Vector3 pos = getLocation(); -// -// for (BlockFace side : BlockFace.values()) { -// if (facing == side) { -// continue; -// } -// -// this.level.updateAround(pos.getSide(side)); -// } -// } - checkState(); return true; @@ -75,8 +62,6 @@ public int getStrongPower(BlockFace side) { public boolean onBreak(Item item) { super.onBreak(item); - Vector3 pos = getLocation(); - BlockFace face = getBlockFace().getOpposite(); for (BlockFace side : BlockFace.values()) { @@ -84,7 +69,7 @@ public boolean onBreak(Item item) { continue; } - this.level.updateAroundRedstone(pos.getSide(side), null); + this.level.updateAroundRedstone(this.getSideVec(side), null); } return true; } @@ -114,16 +99,15 @@ public int onUpdate(int type) { protected boolean checkState() { if (isPoweredFromSide()) { BlockFace face = getBlockFace().getOpposite(); - Vector3 pos = getLocation(); - this.level.setBlock(pos, Block.get(BlockID.UNLIT_REDSTONE_TORCH, getDamage()), false, true); + this.level.setBlock(this, Block.get(UNLIT_REDSTONE_TORCH, getDamage()), false, true); for (BlockFace side : BlockFace.values()) { if (side == face) { continue; } - this.level.updateAroundRedstone(pos.getSide(side), null); + this.level.updateAroundRedstone(this.getSideVec(side), null); } return true; @@ -134,10 +118,9 @@ protected boolean checkState() { protected boolean isPoweredFromSide() { BlockFace face = getBlockFace().getOpposite(); - return this.level.isSidePowered(this.getLocation().getSide(face), face); + return this.level.isSidePowered(this.getSideVec(face), face); } - - @Override + @Override public int tickRate() { return 2; } @@ -151,4 +134,4 @@ public boolean isPowerSource() { public BlockColor getColor() { return BlockColor.AIR_BLOCK_COLOR; } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockRedstoneTorchUnlit.java b/src/main/java/cn/nukkit/block/BlockRedstoneTorchUnlit.java index eb0c46d6de4..64231974802 100644 --- a/src/main/java/cn/nukkit/block/BlockRedstoneTorchUnlit.java +++ b/src/main/java/cn/nukkit/block/BlockRedstoneTorchUnlit.java @@ -5,7 +5,6 @@ import cn.nukkit.item.ItemBlock; import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; -import cn.nukkit.math.Vector3; /** * Created by CreeperFace on 10.4.2017. @@ -35,19 +34,9 @@ public int getLightLevel() { return 0; } - @Override - public int getWeakPower(BlockFace side) { - return 0; - } - - @Override - public int getStrongPower(BlockFace side) { - return 0; - } - @Override public Item toItem() { - return new ItemBlock(Block.get(BlockID.REDSTONE_TORCH)); + return new ItemBlock(Block.get(REDSTONE_TORCH)); } @Override @@ -73,17 +62,16 @@ public int onUpdate(int type) { protected boolean checkState() { BlockFace face = getBlockFace().getOpposite(); - Vector3 pos = getLocation(); - if (!this.level.isSidePowered(pos.getSide(face), face)) { - this.level.setBlock(pos, Block.get(BlockID.REDSTONE_TORCH, getDamage()), false, true); + if (!this.level.isSidePowered(this.getSideVec(face), face)) { + this.level.setBlock(this, Block.get(REDSTONE_TORCH, getDamage()), false, true); for (BlockFace side : BlockFace.values()) { if (side == face) { continue; } - this.level.updateAroundRedstone(pos.getSide(side), null); + this.level.updateAroundRedstone(this.getSideVec(side), null); } return true; } @@ -95,4 +83,4 @@ protected boolean checkState() { public int tickRate() { return 2; } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockRedstoneWire.java b/src/main/java/cn/nukkit/block/BlockRedstoneWire.java index 06f26de3e5f..ec2f96e0cd7 100644 --- a/src/main/java/cn/nukkit/block/BlockRedstoneWire.java +++ b/src/main/java/cn/nukkit/block/BlockRedstoneWire.java @@ -4,7 +4,6 @@ import cn.nukkit.event.block.BlockRedstoneEvent; import cn.nukkit.event.redstone.RedstoneUpdateEvent; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemRedstone; import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; import cn.nukkit.math.BlockFace.Plane; @@ -14,7 +13,7 @@ import java.util.EnumSet; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class BlockRedstoneWire extends BlockFlowable { @@ -41,51 +40,48 @@ public int getId() { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - if (!canBePlacedOn(block.down())) { + if (block instanceof BlockWater || block.level.isBlockWaterloggedAt(block.getChunk(), (int) block.x, (int) block.y, (int) block.z)) { + return false; + } + + if (!canStayOnFullSolid(block.down())) { return false; } this.getLevel().setBlock(block, this, true, false); - this.updateSurroundingRedstone(true); - Vector3 pos = getLocation(); + this.calculateCurrentChanges(true); for (BlockFace blockFace : Plane.VERTICAL) { - this.level.updateAroundRedstone(pos.getSide(blockFace), blockFace.getOpposite()); + this.level.updateAroundRedstone(this.getSideVec(blockFace), blockFace.getOpposite()); } for (BlockFace blockFace : Plane.VERTICAL) { - this.updateAround(pos.getSide(blockFace), blockFace.getOpposite()); + this.updateAround(this.getSideVec(blockFace), blockFace.getOpposite()); } for (BlockFace blockFace : Plane.HORIZONTAL) { - Vector3 v = pos.getSide(blockFace); + Vector3 v = this.getSideVec(blockFace); if (this.level.getBlock(v).isNormalBlock()) { - this.updateAround(v.up(), BlockFace.DOWN); + this.updateAround(v.getSideVec(BlockFace.UP), BlockFace.DOWN); } else { - this.updateAround(v.down(), BlockFace.UP); + this.updateAround(v.getSideVec(BlockFace.DOWN), BlockFace.UP); } } return true; } private void updateAround(Vector3 pos, BlockFace face) { - if (this.level.getBlock(pos).getId() == Block.REDSTONE_WIRE) { + if (this.level.getBlockIdAt((int) pos.x, (int) pos.y, (int) pos.z) == Block.REDSTONE_WIRE) { this.level.updateAroundRedstone(pos, face); for (BlockFace side : BlockFace.values()) { - this.level.updateAroundRedstone(pos.getSide(side), side.getOpposite()); + this.level.updateAroundRedstone(pos.getSideVec(side), side.getOpposite()); } } } - private void updateSurroundingRedstone(boolean force) { - this.calculateCurrentChanges(force); - } - private void calculateCurrentChanges(boolean force) { - Vector3 pos = this.getLocation(); - int meta = this.getDamage(); int maxStrength = meta; this.canProvidePower = false; @@ -100,7 +96,7 @@ private void calculateCurrentChanges(boolean force) { int strength = 0; for (BlockFace face : Plane.HORIZONTAL) { - Vector3 v = pos.getSide(face); + Vector3 v = this.getSideVec(face); if (v.getX() == this.getX() && v.getZ() == this.getZ()) { continue; @@ -111,10 +107,10 @@ private void calculateCurrentChanges(boolean force) { boolean vNormal = this.level.getBlock(v).isNormalBlock(); - if (vNormal && !this.level.getBlock(pos.up()).isNormalBlock()) { - strength = this.getMaxCurrentStrength(v.up(), strength); + if (vNormal && !this.level.getBlock(this.getSideVec(BlockFace.UP)).isNormalBlock()) { + strength = this.getMaxCurrentStrength(v.getSideVec(BlockFace.UP), strength); } else if (!vNormal) { - strength = this.getMaxCurrentStrength(v.down(), strength); + strength = this.getMaxCurrentStrength(v.getSideVec(BlockFace.DOWN), strength); } } @@ -140,17 +136,17 @@ private void calculateCurrentChanges(boolean force) { this.level.updateAroundRedstone(this, null); for (BlockFace face : BlockFace.values()) { - this.level.updateAroundRedstone(pos.getSide(face), face.getOpposite()); + this.level.updateAroundRedstone(this.getSideVec(face), face.getOpposite()); } } else if (force) { for (BlockFace face : BlockFace.values()) { - this.level.updateAroundRedstone(pos.getSide(face), face.getOpposite()); + this.level.updateAroundRedstone(this.getSideVec(face), face.getOpposite()); } } } private int getMaxCurrentStrength(Vector3 pos, int maxStrength) { - if (this.level.getBlockIdAt(pos.getFloorX(), pos.getFloorY(), pos.getFloorZ()) != this.getId()) { + if (this.level.getBlockIdAt(pos.getFloorX(), pos.getFloorY(), pos.getFloorZ()) != REDSTONE_WIRE) { return maxStrength; } else { int strength = this.level.getBlockDataAt(pos.getFloorX(), pos.getFloorY(), pos.getFloorZ()); @@ -162,20 +158,19 @@ private int getMaxCurrentStrength(Vector3 pos, int maxStrength) { public boolean onBreak(Item item) { this.getLevel().setBlock(this, Block.get(BlockID.AIR), true, true); - Vector3 pos = getLocation(); + this.level.updateAroundRedstone(this, null); - this.level.updateAroundRedstone(pos, null); for (BlockFace blockFace : BlockFace.values()) { - this.level.updateAroundRedstone(pos.getSide(blockFace), null); + this.level.updateAroundRedstone(this.getSideVec(blockFace), null); } for (BlockFace blockFace : Plane.HORIZONTAL) { - Vector3 v = pos.getSide(blockFace); + Vector3 v = this.getSideVec(blockFace); if (this.level.getBlock(v).isNormalBlock()) { - this.updateAround(v.up(), BlockFace.DOWN); + this.updateAround(v.getSideVec(BlockFace.UP), BlockFace.DOWN); } else { - this.updateAround(v.down(), BlockFace.UP); + this.updateAround(v.getSideVec(BlockFace.DOWN), BlockFace.UP); } } return true; @@ -183,7 +178,7 @@ public boolean onBreak(Item item) { @Override public Item toItem() { - return new ItemRedstone(); + return Item.get(Item.REDSTONE_DUST); } @Override @@ -196,6 +191,12 @@ public int onUpdate(int type) { if (type != Level.BLOCK_UPDATE_NORMAL && type != Level.BLOCK_UPDATE_REDSTONE) { return 0; } + + if (type == Level.BLOCK_UPDATE_NORMAL && !canStayOnFullSolid(this.down())) { + this.getLevel().useBreakOn(this); + return Level.BLOCK_UPDATE_NORMAL; + } + // Redstone event RedstoneUpdateEvent ev = new RedstoneUpdateEvent(this); getLevel().getServer().getPluginManager().callEvent(ev); @@ -203,22 +204,18 @@ public int onUpdate(int type) { return 0; } - if (type == Level.BLOCK_UPDATE_NORMAL && !this.canBePlacedOn(this.down())) { - this.getLevel().useBreakOn(this); - return Level.BLOCK_UPDATE_NORMAL; + // Make sure the block still exists to prevent item duplication + if (this.level.getBlockIdAt((int) this.x, (int) this.y, (int) this.z) != this.getId()) { + return 0; } - this.updateSurroundingRedstone(false); + this.calculateCurrentChanges(false); - return Level.BLOCK_UPDATE_NORMAL; + return Level.BLOCK_UPDATE_REDSTONE; } public boolean canBePlacedOn(Vector3 v) { - return this.canBePlacedOn(this.level.getBlock(v)); - } - - private boolean canBePlacedOn(Block b) { - return (b.isSolid() && !b.isTransparent() && b.getId() != GLOWSTONE) || b.getId() == HOPPER_BLOCK; + return canStayOnFullSolid(this.level.getBlock(v)); } public int getStrongPower(BlockFace side) { @@ -256,16 +253,10 @@ public int getWeakPower(BlockFace side) { } private boolean isPowerSourceAt(BlockFace side) { - Vector3 pos = getLocation(); - Vector3 v = pos.getSide(side); - Block block = this.level.getBlock(v); - boolean flag = block.isNormalBlock(); - boolean flag1 = this.level.getBlock(pos.up()).isNormalBlock(); - return !flag1 && flag && canConnectUpwardsTo(this.level, v.up()) || (canConnectTo(block, side) || !flag && canConnectUpwardsTo(this.level, block.down())); - } - - protected static boolean canConnectUpwardsTo(Level level, Vector3 pos) { - return canConnectUpwardsTo(level.getBlock(pos)); + Block sideBlock = this.getSide(side); + boolean sideBlockIsNormal = sideBlock.isNormalBlock(); + return (sideBlockIsNormal && !this.up().isNormalBlock() && canConnectUpwardsTo(sideBlock.up())) || + (canConnectTo(sideBlock, side) || (!sideBlockIsNormal && canConnectUpwardsTo(sideBlock.down()))); } protected static boolean canConnectUpwardsTo(Block block) { @@ -290,10 +281,9 @@ public boolean isPowerSource() { private int getIndirectPower() { int power = 0; - Vector3 pos = getLocation(); for (BlockFace face : BlockFace.values()) { - int blockPower = this.getIndirectPower(pos.getSide(face), face); + int blockPower = this.getIndirectPower(this.getSideVec(face), face); if (blockPower >= 15) { return 15; @@ -312,7 +302,7 @@ private int getIndirectPower(Vector3 pos, BlockFace face) { if (block.getId() == Block.REDSTONE_WIRE) { return 0; } - return block.isNormalBlock() ? getStrongPower(pos.getSide(face), face) : block.getWeakPower(face); + return block.isNormalBlock() ? getStrongPower(pos.getSideVec(face), face) : block.getWeakPower(face); } private int getStrongPower(Vector3 pos, BlockFace direction) { @@ -324,4 +314,9 @@ private int getStrongPower(Vector3 pos, BlockFace direction) { return block.getStrongPower(direction); } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockReinforcedDeeplsate.java b/src/main/java/cn/nukkit/block/BlockReinforcedDeeplsate.java new file mode 100644 index 00000000000..d8d52b2fd5e --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockReinforcedDeeplsate.java @@ -0,0 +1,42 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.utils.BlockColor; + +public class BlockReinforcedDeeplsate extends BlockSolid { + + @Override + public int getId() { + return REINFORCED_DEEPSLATE; + } + + @Override + public String getName() { + return "Reinforced Deeplsate"; + } + + @Override + public double getHardness() { + return 55; + } + + @Override + public double getResistance() { + return 1200; + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } + + @Override + public Item[] getDrops(Item item) { + return new Item[0]; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockRespawnAnchor.java b/src/main/java/cn/nukkit/block/BlockRespawnAnchor.java new file mode 100644 index 00000000000..430bedc6a76 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockRespawnAnchor.java @@ -0,0 +1,151 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.level.Explosion; +import cn.nukkit.level.GameRule; +import cn.nukkit.level.Level; +import cn.nukkit.math.Vector3; +import cn.nukkit.network.protocol.LevelSoundEventPacket; + +public class BlockRespawnAnchor extends BlockSolidMeta { + + public BlockRespawnAnchor() { + this(0); + } + + public BlockRespawnAnchor(int meta) { + super(meta); + } + + @Override + public int getId() { + return RESPAWN_ANCHOR; + } + + @Override + public double getHardness() { + return 50; + } + + @Override + public double getResistance() { + return 1200; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public Item[] getDrops(Item item) { + if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_DIAMOND) { + return new Item[]{ + toItem() + }; + } else { + return new Item[0]; + } + } + + @Override + public int getLightLevel() { + switch (this.getDamage()) { + case 0: + return 0; + case 1: + return 3; + case 2: + return 7; + default: + return 15; + } + } + + @Override + public String getName() { + return "Respawn Anchor"; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Item item, Player player) { + int chargeLevel = this.getDamage(); + + if (item.getId() == GLOWSTONE && chargeLevel < 4) { + if (player != null && !player.isCreative()) { + item.count--; + } + + this.setDamage(chargeLevel + 1); + this.getLevel().setBlock(this, this, true); + this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_RESPAWN_ANCHOR_CHARGE); + return true; + } + + if (chargeLevel > 0 && this.level.getDimension() != Level.DIMENSION_NETHER) { + if (this.level.getGameRules().getBoolean(GameRule.RESPAWN_BLOCKS_EXPLODE)) { + this.getLevel().setBlock(this, Block.get(BlockID.AIR), true, true); + + Explosion explosion = new Explosion(this.add(0.5, 0, 0.5), 5, this); + explosion.explodeA(); + explosion.explodeB(); + } + return true; + } + + if (player != null && chargeLevel > 0 && this.level.getDimension() == Level.DIMENSION_NETHER) { + if (player.distanceSquared(this) > 36) { + return false; + } + + if (!this.equals(player.getSpawnPosition())) { + player.setSpawn(this); + + player.sendMessage("§7%tile.respawn_anchor.respawnSet", true); + + this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_RESPAWN_ANCHOR_SET_SPAWN); + } + } + + return item.getId() == GLOWSTONE; + } + + @Override + public boolean onBreak(Item item) { + boolean r = super.onBreak(item); + if (r) { + if (level.getDimension() == Level.DIMENSION_NETHER) { + Vector3 safeSpawn = null; + for (Player player : level.getServer().getOnlinePlayers().values()) { + if (this.equals(player.getSpawnPosition())) { + player.setSpawn(safeSpawn == null ? (safeSpawn = level.getServer().getDefaultLevel().getSafeSpawn()) : safeSpawn); + } + } + } + } + return r; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockRoots.java b/src/main/java/cn/nukkit/block/BlockRoots.java new file mode 100644 index 00000000000..e929d59b999 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockRoots.java @@ -0,0 +1,53 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; + +public abstract class BlockRoots extends BlockFlowable { + + protected BlockRoots() { + super(0); + } + + protected BlockRoots(int meta) { + super(meta); + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL && !isSupportValid()) { + level.useBreakOn(this); + return type; + } + return 0; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + return this.isSupportValid() && super.place(item, block, target, face, fx, fy, fz, player); + } + + protected boolean isSupportValid() { + switch (this.down().getId()) { + case BlockID.GRASS: + case BlockID.DIRT: + case BlockID.PODZOL: + case BlockID.FARMLAND: + case BlockID.CRIMSON_NYLIUM: + case BlockID.WARPED_NYLIUM: + case BlockID.MYCELIUM: + case BlockID.SOUL_SOIL: + case BlockID.ROOTED_DIRT: + return true; + default: + return false; + } + } + + @Override + public int getBurnChance() { + return 5; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockRootsHanging.java b/src/main/java/cn/nukkit/block/BlockRootsHanging.java new file mode 100644 index 00000000000..2eff0d9b432 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockRootsHanging.java @@ -0,0 +1,28 @@ +package cn.nukkit.block; + +public class BlockRootsHanging extends BlockRoots { + + public BlockRootsHanging() { + this(0); + } + + public BlockRootsHanging(int meta) { + super(0); // hanging roots have no variants + } + + @Override + protected boolean isSupportValid() { + Block up = this.up(); + return up.isSolid() && !up.isTransparent(); + } + + @Override + public String getName() { + return "Hanging Roots"; + } + + @Override + public int getId() { + return HANGING_ROOTS; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSand.java b/src/main/java/cn/nukkit/block/BlockSand.java index 45791d253c9..574675c2a17 100644 --- a/src/main/java/cn/nukkit/block/BlockSand.java +++ b/src/main/java/cn/nukkit/block/BlockSand.java @@ -1,40 +1,28 @@ package cn.nukkit.block; +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemDye; import cn.nukkit.item.ItemTool; +import cn.nukkit.level.generator.object.ObjectTallGrass; +import cn.nukkit.level.particle.BoneMealParticle; import cn.nukkit.utils.BlockColor; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ -public class BlockSand extends BlockFallable { +public class BlockSand extends BlockFallableMeta { public static final int DEFAULT = 0; public static final int RED = 1; - private int meta; - public BlockSand() { this(0); } public BlockSand(int meta) { - this.meta = meta; - } - - @Override - public int getFullId() { - return (getId() << 4) + getDamage(); - } - - @Override - public final int getDamage() { - return this.meta; - } - - @Override - public final void setDamage(int meta) { - this.meta = meta; + super(meta); } @Override @@ -74,4 +62,28 @@ public BlockColor getColor() { return BlockColor.SAND_BLOCK_COLOR; } + + @Override + public boolean onActivate(Item item, Player player) { + if (player != null && item.getId() == Item.DYE && item.getDamage() == ItemDye.BONE_MEAL) { + Block up = this.up(); + if (up instanceof BlockWater) { + if (!player.isCreative()) { + item.count--; + } + this.level.addParticle(new BoneMealParticle(this)); + if (up.getDamage() == 0 && up.up() instanceof BlockWater) { + ObjectTallGrass.growSeagrass(this.getLevel(), this); + } + return true; + } + } + + return false; + } + + @Override + public boolean canBeActivated() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockSandstone.java b/src/main/java/cn/nukkit/block/BlockSandstone.java index 2fef1655c9e..6c3b4f67ebc 100644 --- a/src/main/java/cn/nukkit/block/BlockSandstone.java +++ b/src/main/java/cn/nukkit/block/BlockSandstone.java @@ -6,13 +6,15 @@ import cn.nukkit.utils.BlockColor; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockSandstone extends BlockSolidMeta { + public static final int NORMAL = 0; public static final int CHISELED = 1; - public static final int SMOOTH = 2; + public static final int CUT = 2; + public static final int SMOOTH = 3; public BlockSandstone() { this(0); @@ -29,29 +31,29 @@ public int getId() { @Override public double getHardness() { - return 0.8; + return 2; } @Override public double getResistance() { - return 4; + return 6; } + private static final String[] NAMES = { + "Sandstone", + "Chiseled Sandstone", + "Cut Sandstone", + "Smooth Sandstone" + }; + @Override public String getName() { - String[] names = new String[]{ - "Sandstone", - "Chiseled Sandstone", - "Smooth Sandstone", - "" - }; - - return names[this.getDamage() & 0x03]; + return NAMES[this.getDamage() & 0x03]; } @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; diff --git a/src/main/java/cn/nukkit/block/BlockSapling.java b/src/main/java/cn/nukkit/block/BlockSapling.java index a010867cb0e..0bd6f6da2c4 100644 --- a/src/main/java/cn/nukkit/block/BlockSapling.java +++ b/src/main/java/cn/nukkit/block/BlockSapling.java @@ -3,6 +3,8 @@ import cn.nukkit.Player; import cn.nukkit.event.level.StructureGrowEvent; import cn.nukkit.item.Item; +import cn.nukkit.item.ItemDye; +import cn.nukkit.level.ChunkManager; import cn.nukkit.level.Level; import cn.nukkit.level.ListChunkManager; import cn.nukkit.level.generator.object.BasicGenerator; @@ -13,27 +15,23 @@ import cn.nukkit.math.Vector2; import cn.nukkit.math.Vector3; import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.Utils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; import java.util.concurrent.ThreadLocalRandom; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class BlockSapling extends BlockFlowable { + public static final int OAK = 0; public static final int SPRUCE = 1; public static final int BIRCH = 2; - /** - * placeholder - */ - public static final int BIRCH_TALL = 8 | BIRCH; public static final int JUNGLE = 3; public static final int ACACIA = 4; public static final int DARK_OAK = 5; + public static final int BIRCH_TALL = 10; public BlockSapling() { this(0); @@ -48,26 +46,32 @@ public int getId() { return SAPLING; } + private static final String[] NAMES = { + "Oak Sapling", + "Spruce Sapling", + "Birch Sapling", + "Jungle Sapling", + "Acacia Sapling", + "Dark Oak Sapling", + "", + "" + }; + @Override public String getName() { - String[] names = new String[]{ - "Oak Sapling", - "Spruce Sapling", - "Birch Sapling", - "Jungle Sapling", - "Acacia Sapling", - "Dark Oak Sapling", - "", - "" - }; - return names[this.getDamage() & 0x07]; + return NAMES[this.getDamage() & 0x07]; } @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (!(this instanceof BlockMangrovePropagule) && + (block instanceof BlockWater || block.level.isBlockWaterloggedAt(block.getChunk(), (int) block.x, (int) block.y, (int) block.z))) { + return false; + } + Block down = this.down(); int id = down.getId(); - if (id == Block.GRASS || id == Block.DIRT || id == Block.FARMLAND || id == Block.PODZOL || id == MYCELIUM) { + if (id == Block.GRASS || id == Block.DIRT || id == Block.FARMLAND || id == Block.PODZOL || id == MYCELIUM || id == MOSS_BLOCK || id == MUD) { this.getLevel().setBlock(block, this, true, true); return true; } @@ -81,8 +85,8 @@ public boolean canBeActivated() { } public boolean onActivate(Item item, Player player) { - if (item.getId() == Item.DYE && item.getDamage() == 0x0F) { //BoneMeal - if (player != null && (player.gamemode & 0x01) == 0) { + if (item.getId() == Item.DYE && item.getDamage() == ItemDye.BONE_MEAL) { + if (player != null && !player.isCreative()) { item.count--; } @@ -91,42 +95,19 @@ public boolean onActivate(Item item, Player player) { return true; } - this.grow(); - - return true; + return growTreeHere(); } return false; } - public int onUpdate(int type) { - if (type == Level.BLOCK_UPDATE_NORMAL) { - if (this.down().isTransparent()) { - this.getLevel().useBreakOn(this); - return Level.BLOCK_UPDATE_NORMAL; - } - } else if (type == Level.BLOCK_UPDATE_RANDOM) { //Growth - if (ThreadLocalRandom.current().nextInt(1, 8) == 1) { - if ((this.getDamage() & 0x08) == 0x08) { - this.grow(); - } else { - this.setDamage(this.getDamage() | 0x08); - this.getLevel().setBlock(this, this, true); - return Level.BLOCK_UPDATE_RANDOM; - } - } else { - return Level.BLOCK_UPDATE_RANDOM; - } - } - return Level.BLOCK_UPDATE_NORMAL; - } - - private void grow() { + private boolean growTreeHere() { BasicGenerator generator = null; boolean bigTree = false; - Vector3 vector3 = new Vector3(); + Vector3 vector3 = new Vector3(this.x, this.y - 1, this.z); - switch (this.getDamage() & 0x07) { + int woodType = this.getDamage() & 0x7; + switch (woodType) { case JUNGLE: Vector2 vector2; if ((vector2 = this.findSaplings(JUNGLE)) != null) { @@ -137,12 +118,12 @@ private void grow() { if (!bigTree) { generator = new NewJungleTree(4, 7); - vector3 = this.add(0,0,0); + vector3 = this.add(0, 0, 0); } break; case ACACIA: generator = new ObjectSavannaTree(); - vector3 = this.add(0,0,0); + vector3 = this.add(0, 0, 0); break; case DARK_OAK: if ((vector2 = this.findSaplings(DARK_OAK)) != null) { @@ -152,37 +133,58 @@ private void grow() { } if (!bigTree) { - return; + return false; } break; - //TODO: big spruce + case SPRUCE: + if ((vector2 = this.findSaplings(SPRUCE)) != null) { + vector3 = this.add(vector2.getFloorX(), 0, vector2.getFloorY()); + generator = new HugeTreesGenerator(0, 0, null, null) { + @Override + public boolean generate(ChunkManager level, NukkitRandom rand, Vector3 position) { + ObjectBigSpruceTree object = new ObjectBigSpruceTree(0.25f, 4); + if (!this.ensureGrowable(level, position, object.getTreeHeight())) { + return false; + } + object.placeObject(level, position.getFloorX(), position.getFloorY(), position.getFloorZ(), rand); + return true; + } + }; + bigTree = true; + } + + if (bigTree) { + break; + } default: ListChunkManager chunkManager = new ListChunkManager(this.level); - ObjectTree.growTree(chunkManager, this.getFloorX(), this.getFloorY(), this.getFloorZ(), new NukkitRandom(), this.getDamage() & 0x07); + ObjectTree.growTree(chunkManager, this.getFloorX(), this.getFloorY(), this.getFloorZ(), new NukkitRandom(), woodType); StructureGrowEvent ev = new StructureGrowEvent(this, chunkManager.getBlocks()); this.level.getServer().getPluginManager().callEvent(ev); if (ev.isCancelled()) { - return; + return false; } - for(Block block : ev.getBlockList()) { - this.level.setBlockAt(block.getFloorX(), block.getFloorY(), block.getFloorZ(), block.getId(), block.getDamage()); + + for (Block block : ev.getBlockList()) { + this.level.setBlock(block, block); } - return; + return true; } if (bigTree) { - this.level.setBlock(vector3, get(AIR), true, false); - this.level.setBlock(vector3.add(1, 0, 0), get(AIR), true, false); - this.level.setBlock(vector3.add(0, 0, 1), get(AIR), true, false); - this.level.setBlock(vector3.add(1, 0, 1), get(AIR), true, false); + this.level.setBlock(vector3, Block.get(AIR), true, false); + this.level.setBlock(vector3.add(1, 0, 0), Block.get(AIR), true, false); + this.level.setBlock(vector3.add(0, 0, 1), Block.get(AIR), true, false); + this.level.setBlock(vector3.add(1, 0, 1), Block.get(AIR), true, false); } else { - this.level.setBlock(this, get(AIR), true, false); + this.level.setBlock(this, Block.get(AIR), true, false); } ListChunkManager chunkManager = new ListChunkManager(this.level); boolean success = generator.generate(chunkManager, new NukkitRandom(), vector3); StructureGrowEvent ev = new StructureGrowEvent(this, chunkManager.getBlocks()); this.level.getServer().getPluginManager().callEvent(ev); + if (ev.isCancelled() || !success) { if (bigTree) { this.level.setBlock(vector3, this, true, false); @@ -192,38 +194,35 @@ private void grow() { } else { this.level.setBlock(this, this, true, false); } - return; + return false; } - for(Block block : ev.getBlockList()) { - this.level.setBlockAt(block.getFloorX(), block.getFloorY(), block.getFloorZ(), block.getId(), block.getDamage()); + + for (Block block : ev.getBlockList()) { + this.level.setBlock(block, block); } + return true; } - private Vector2 findSaplings(int type) { - List> validVectorsList = new ArrayList<>(); - validVectorsList.add(Arrays.asList(new Vector2(0, 0), new Vector2(1, 0), new Vector2(0, 1), new Vector2(1, 1))); - validVectorsList.add(Arrays.asList(new Vector2(0, 0), new Vector2(-1, 0), new Vector2(0, -1), new Vector2(-1, -1))); - validVectorsList.add(Arrays.asList(new Vector2(0, 0), new Vector2(1, 0), new Vector2(0, -1), new Vector2(1, -1))); - validVectorsList.add(Arrays.asList(new Vector2(0, 0), new Vector2(-1, 0), new Vector2(0, 1), new Vector2(-1, 1))); - for(List validVectors : validVectorsList) { - boolean correct = true; - for(Vector2 vector2 : validVectors) { - if(!this.isSameType(this.add(vector2.x, 0, vector2.y), type)) - correct = false; + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + if (this.down().isTransparent()) { + this.getLevel().useBreakOn(this); + return Level.BLOCK_UPDATE_NORMAL; } - if(correct) { - int lowestX = 0; - int lowestZ = 0; - for(Vector2 vector2 : validVectors) { - if(vector2.getFloorX() < lowestX) - lowestX = vector2.getFloorX(); - if(vector2.getFloorY() < lowestZ) - lowestZ = vector2.getFloorY(); + } else if (type == Level.BLOCK_UPDATE_RANDOM) { //Growth + if (Utils.rand(1, 7) == 1) { + if ((this.getDamage() & 0x08) == 0x08) { + growTreeHere(); + } else { + this.setDamage(this.getDamage() | 0x08); + this.getLevel().setBlock(this, this, true); + return Level.BLOCK_UPDATE_RANDOM; } - return new Vector2(lowestX, lowestZ); + } else { + return Level.BLOCK_UPDATE_RANDOM; } } - return null; + return 1; } public boolean isSameType(Vector3 pos, int type) { @@ -240,4 +239,45 @@ public Item toItem() { public BlockColor getColor() { return BlockColor.FOLIAGE_BLOCK_COLOR; } + + @Override + public boolean breakWhenPushed() { + return true; + } + + private static final Vector2[][] VALID_SAPLINGS = new Vector2[4][4]; + static { + VALID_SAPLINGS[0] = new Vector2[]{new Vector2(0, 0), new Vector2(1, 0), new Vector2(0, 1), new Vector2(1, 1)}; + VALID_SAPLINGS[1] = new Vector2[]{new Vector2(0, 0), new Vector2(-1, 0), new Vector2(0, -1), new Vector2(-1, -1)}; + VALID_SAPLINGS[2] = new Vector2[]{new Vector2(0, 0), new Vector2(1, 0), new Vector2(0, -1), new Vector2(1, -1)}; + VALID_SAPLINGS[3] = new Vector2[]{new Vector2(0, 0), new Vector2(-1, 0), new Vector2(0, 1), new Vector2(-1, 1)}; + } + + private Vector2 findSaplings(int type) { + for (Vector2[] validVectors : VALID_SAPLINGS) { + boolean found = true; + + for (Vector2 vector2 : validVectors) { + if (!this.isSameType(this.add(vector2.x, 0, vector2.y), type)) { + found = false; + } + } + + if (found) { + int lowestX = 0; + int lowestZ = 0; + for (Vector2 vector2 : validVectors) { + if (vector2.getFloorX() < lowestX) { + lowestX = vector2.getFloorX(); + } + if (vector2.getFloorY() < lowestZ) { + lowestZ = vector2.getFloorY(); + } + } + return new Vector2(lowestX, lowestZ); + } + } + + return null; + } } diff --git a/src/main/java/cn/nukkit/block/BlockScaffolding.java b/src/main/java/cn/nukkit/block/BlockScaffolding.java new file mode 100644 index 00000000000..b105894b73e --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockScaffolding.java @@ -0,0 +1,256 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.entity.Entity; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.BlockColor; + +public class BlockScaffolding extends BlockFallableMeta { + + public BlockScaffolding() { + this(0); + } + + public BlockScaffolding(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Scaffolding"; + } + + @Override + public int getId() { + return SCAFFOLDING; + } + + public int getStability() { + return this.getDamage() & 0x7; + } + + public void setStability(int stability) { + this.setDamage(stability & 0x7 | (this.getDamage() & 0x8)); + } + + public boolean getStabilityCheck() { + return (this.getDamage() & 0x8) > 0; + } + + public void setStabilityCheck(boolean check) { + if (check) { + this.setDamage(getDamage() | 0x8); + } else { + this.setDamage(getDamage() & 0x7); + } + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(SCAFFOLDING)); + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (block instanceof BlockLava) { + return false; + } + + Block down = this.down(); + if (target.getId() != SCAFFOLDING && down.getId() != SCAFFOLDING && down.getId() != AIR && !down.isSolid()) { + boolean scaffoldOnSide = false; + for (int i = 0; i < 4; i++) { + BlockFace sideFace = BlockFace.fromHorizontalIndex(i); + if (sideFace != face) { + Block side = this.getSide(sideFace); + if (side.getId() == SCAFFOLDING) { + scaffoldOnSide = true; + break; + } + } + } + + if (!scaffoldOnSide) { + return false; + } + } + + this.setDamage(0x8); + this.getLevel().setBlock(this, this, true, true); + return true; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + Block down = this.down(); + if (down.isSolid()) { + if (this.getDamage() != 0) { + this.setDamage(0); + this.getLevel().setBlock(this, this, true, true); + } + return type; + } + + int stability = 7; + for (BlockFace face : BlockFace.values()) { + if (face == BlockFace.UP) { + continue; + } + + Block otherBlock = this.getSide(face); + if (otherBlock.getId() == SCAFFOLDING) { + BlockScaffolding other = (BlockScaffolding) otherBlock; + int otherStability = other.getStability(); + if (otherStability < stability) { + if (face == BlockFace.DOWN) { + stability = otherStability; + } else { + stability = otherStability + 1; + } + } + } + } + + if (stability >= 7) { + if (this.getStabilityCheck()) { + super.onUpdate(type); + } else { + this.getLevel().scheduleUpdate(this, 0); + } + return type; + } + + this.setStabilityCheck(false); + this.setStability(stability); + this.getLevel().setBlock(this, this, true, true); + return type; + } else if (type == Level.BLOCK_UPDATE_SCHEDULED) { + this.getLevel().useBreakOn(this); + return type; + } + + return 0; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public double getHardness() { + return 0; + } + + @Override + public double getResistance() { + return 0; + } + + @Override + public int getBurnChance() { + return 60; + } + + @Override + public int getBurnAbility() { + return 60; + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean canBeClimbed() { + return true; + } + + @Override + public boolean canBeFlowedInto() { + return false; + } + + @Override + public void onEntityCollide(Entity entity) { + entity.resetFallDistance(); + } + + @Override + public boolean hasEntityCollision() { + return true; + } + + @Override + public double getMinY() { + return this.y + 0.875; + } + + @Override + public boolean canPassThrough() { + return false; + } + + @Override + public boolean isTransparent() { + return true; + } + + @Override + public BlockColor getColor() { + return BlockColor.TRANSPARENT_BLOCK_COLOR; + } + + @Override + public boolean isSolid() { + return false; + } + + @Override + public boolean breakWhenPushed() { + return true; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (item.getBlockUnsafe() instanceof BlockScaffolding) { + int top = (int) y; + + for (int i = 1; i <= 16; i++) { + int id = this.level.getBlockIdAt(this.getFloorX(), this.getFloorY() - i, this.getFloorZ()); + if (id != SCAFFOLDING) { + break; + } + } + + for (int i = 1; i <= 16; i++) { + int id = this.level.getBlockIdAt(this.getFloorX(), this.getFloorY() + i, this.getFloorZ()); + if (id == SCAFFOLDING) { + top++; + } else { + break; + } + } + + boolean success = false; + + Block block = this.up(top - (int) y + 1); + if (block.getId() == BlockID.AIR) { + success = this.level.setBlock(block, Block.get(SCAFFOLDING)); + } + + if (success) { + if (player != null && !player.isCreative()) { + item.count--; + } + } + return true; + } + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSculk.java b/src/main/java/cn/nukkit/block/BlockSculk.java new file mode 100644 index 00000000000..bb4ac659f42 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSculk.java @@ -0,0 +1,64 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.utils.BlockColor; + +public class BlockSculk extends BlockSolid { + + @Override + public int getId() { + return SCULK; + } + + @Override + public String getName() { + return "Sculk"; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_HOE; + } + + @Override + public double getHardness() { + return 1.5; + } + + @Override + public double getResistance() { + return 1.5; + } + + @Override + public int getLightLevel() { + return 1; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public BlockColor getColor() { + return BlockColor.BLACK_BLOCK_COLOR; + } + + @Override + public Item[] getDrops(Item item) { + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{ + this.toItem() + }; + } + return new Item[0]; + } + + @Override + public int getDropExp() { + return 1; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSculkCatalyst.java b/src/main/java/cn/nukkit/block/BlockSculkCatalyst.java new file mode 100644 index 00000000000..d87a5ecb077 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSculkCatalyst.java @@ -0,0 +1,69 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.utils.BlockColor; + +public class BlockSculkCatalyst extends BlockSolid { + + @Override + public int getId() { + return SCULK_CATALYST; + } + + @Override + public String getName() { + return "Sculk Catalyst"; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_HOE; + } + + @Override + public double getHardness() { + return 3; + } + + @Override + public double getResistance() { + return 3; + } + + @Override + public int getLightLevel() { + return 6; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + public BlockColor getColor() { + return BlockColor.BLACK_BLOCK_COLOR; + } + + @Override + public Item[] getDrops(Item item) { + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{ + this.toItem() + }; + } + return new Item[0]; + } + + @Override + public int getDropExp() { + return 5; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSculkSensor.java b/src/main/java/cn/nukkit/block/BlockSculkSensor.java new file mode 100644 index 00000000000..5936625c55f --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSculkSensor.java @@ -0,0 +1,74 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.utils.BlockColor; + +public class BlockSculkSensor extends BlockTransparent { + + @Override + public int getId() { + return SCULK_SENSOR; + } + + @Override + public String getName() { + return "Sculk Sensor"; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_HOE; + } + + @Override + public double getHardness() { + return 1.5; + } + + @Override + public double getResistance() { + return 1.5; + } + + @Override + public int getLightLevel() { + return 1; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + public BlockColor getColor() { + return BlockColor.BLACK_BLOCK_COLOR; + } + + @Override + public Item[] getDrops(Item item) { + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{ + this.toItem() + }; + } + return new Item[0]; + } + + @Override + public int getDropExp() { + return 5; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSculkShrieker.java b/src/main/java/cn/nukkit/block/BlockSculkShrieker.java new file mode 100644 index 00000000000..4790bcfd206 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSculkShrieker.java @@ -0,0 +1,69 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.utils.BlockColor; + +public class BlockSculkShrieker extends BlockTransparent { + + @Override + public int getId() { + return SCULK_SHRIEKER; + } + + @Override + public String getName() { + return "Sculk Shrieker"; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_HOE; + } + + @Override + public double getHardness() { + return 3; + } + + @Override + public double getResistance() { + return 3; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + public BlockColor getColor() { + return BlockColor.BLACK_BLOCK_COLOR; + } + + @Override + public Item[] getDrops(Item item) { + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{ + this.toItem() + }; + } + return new Item[0]; + } + + @Override + public int getDropExp() { + return 5; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSculkVein.java b/src/main/java/cn/nukkit/block/BlockSculkVein.java new file mode 100644 index 00000000000..4487d0a858c --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSculkVein.java @@ -0,0 +1,77 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.item.enchantment.Enchantment; + +public class BlockSculkVein extends BlockTransparentMeta { + + public BlockSculkVein() { + this(0); + } + + public BlockSculkVein(int meta) { + super(meta); + } + + @Override + public int getId() { + return SCULK_VEIN; + } + + @Override + public String getName() { + return "Sculk Vein"; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_HOE; + } + + @Override + public double getHardness() { + return 0.2; + } + + @Override + public double getResistance() { + return 0.2; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public Item[] getDrops(Item item) { + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{ + this.toItem() + }; + } + return new Item[0]; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean canPassThrough() { + return true; + } + + @Override + public boolean isSolid() { + return false; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSeaLantern.java b/src/main/java/cn/nukkit/block/BlockSeaLantern.java index b1854ccac17..463f7ad8141 100644 --- a/src/main/java/cn/nukkit/block/BlockSeaLantern.java +++ b/src/main/java/cn/nukkit/block/BlockSeaLantern.java @@ -1,15 +1,11 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemPrismarineCrystals; +import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.utils.BlockColor; - -import java.util.concurrent.ThreadLocalRandom; - +import cn.nukkit.utils.Utils; public class BlockSeaLantern extends BlockTransparent { - public BlockSeaLantern() { - } @Override public String getName() { @@ -38,8 +34,11 @@ public int getLightLevel() { @Override public Item[] getDrops(Item item) { + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; + } return new Item[]{ - new ItemPrismarineCrystals(0, ThreadLocalRandom.current().nextInt(2, 4)) + Item.get(Item.PRISMARINE_CRYSTALS, 0, Utils.random.nextInt(2, 4)) }; } @@ -47,7 +46,7 @@ public Item[] getDrops(Item item) { public BlockColor getColor() { return BlockColor.QUARTZ_BLOCK_COLOR; } - + @Override public boolean canSilkTouch() { return true; diff --git a/src/main/java/cn/nukkit/block/BlockSeaPickle.java b/src/main/java/cn/nukkit/block/BlockSeaPickle.java new file mode 100644 index 00000000000..16dc90bbf00 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSeaPickle.java @@ -0,0 +1,187 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.event.block.BlockFadeEvent; +import cn.nukkit.event.block.BlockGrowEvent; +import cn.nukkit.event.block.BlockSpreadEvent; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemDye; +import cn.nukkit.level.Level; +import cn.nukkit.level.particle.BoneMealParticle; +import cn.nukkit.math.BlockFace; +import cn.nukkit.math.SimpleAxisAlignedBB; + +import java.util.concurrent.ThreadLocalRandom; + +public class BlockSeaPickle extends BlockTransparentMeta { + + public BlockSeaPickle() { + this(0); + } + + public BlockSeaPickle(int meta) { + super(meta); + } + + @Override + public int getId() { + return SEA_PICKLE; + } + + public double getHardness() { + return 0; + } + + public double getResistance() { + return 0; + } + + @Override + public String getName() { + return "Sea Pickle"; + } + + public boolean isDead() { + return (getDamage() & 0x4) == 0x4; + } + + public void setDead(boolean dead) { + if (dead) { + this.setDamage(getDamage() | 0x4); + } else { + this.setDamage(getDamage() ^ 0x4); + } + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + Block down = this.down(); + if (!down.isSolid() || down.getId() == MAGMA) { + this.getLevel().useBreakOn(this); + return type; + } + + Block layer1 = getLevelBlock(Block.LAYER_WATERLOGGED); + if (layer1 instanceof BlockWater) { + if (this.isDead() || layer1.getDamage() == 0 && layer1.getDamage() == 8) { + this.getLevel().useBreakOn(this); + return type; + } + } else if (!this.isDead()) { + BlockFadeEvent event = new BlockFadeEvent(this, Block.get(SEA_PICKLE, this.getDamage() ^ 0x4)); + level.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + this.getLevel().setBlock(this, event.getNewState(), true, true); + } + } + + return type; + } + return 0; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (target.getId() == SEA_PICKLE && (target.getDamage() & 0b11) < 3) { + target.setDamage(target.getDamage() + 1); + this.getLevel().setBlock(target, target, true, true); + return true; + } + if (!this.down().isTransparent()) { + Block layer1 = block.getLevelBlock(BlockLayer.WATERLOGGED); + if (layer1 instanceof BlockWater) { + if (layer1.getDamage() != 0 && layer1.getDamage() != 8) { + return false; + } + + if (layer1.getDamage() == 8) { + this.getLevel().setBlock(block, BlockLayer.WATERLOGGED, Block.get(WATER), true, false); + } + } else { + this.setDead(true); + } + this.getLevel().setBlock(block, this, true, true); + return true; + } + return false; + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (item.getId() != Item.DYE || item.getDamage() != ItemDye.BONE_MEAL) { + return super.onActivate(item, player); + } + + BlockSeaPickle block = (BlockSeaPickle) this.clone(); + if (!block.isDead()) { + block.setDamage(3); + } + + BlockGrowEvent blockGrowEvent = new BlockGrowEvent(this, block); + this.level.getServer().getPluginManager().callEvent(blockGrowEvent); + + if (blockGrowEvent.isCancelled()) { + return false; + } + + this.getLevel().setBlock(this, blockGrowEvent.getNewState(), false, true); + this.level.addParticle(new BoneMealParticle(this)); + + if (player != null && !player.isCreative()) { + item.count--; + } + + ThreadLocalRandom random = ThreadLocalRandom.current(); + Block[] blocksAround = this.getLevel().getCollisionBlocks(new SimpleAxisAlignedBB(x - 2, y - 2, z - 2, x + 3, y, z + 3)); + for (Block blockNearby : blocksAround) { + if (blockNearby.getId() == CORAL_BLOCK) { + Block up = blockNearby.up(); + if (up instanceof BlockWater && (up.getDamage() == 0 || up.getDamage() == 8) && random.nextInt(6) == 0) { + BlockSpreadEvent blockSpreadEvent = new BlockSpreadEvent(up, this, Block.get(SEA_PICKLE, random.nextInt(3))); + if (!blockSpreadEvent.isCancelled()) { + this.getLevel().setBlock(up, BlockLayer.WATERLOGGED, Block.get(WATER), true, false); + this.getLevel().setBlock(up, blockSpreadEvent.getNewState(), true, true); + } + } + } + } + return true; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + + @Override + public Item toItem() { + return new ItemBlock(Block.get(SEA_PICKLE), 0); + } + + @Override + public Item[] getDrops(Item item) { + return new Item[]{new ItemBlock(Block.get(SEA_PICKLE), 0, (this.getDamage() & 0x3) + 1)}; + } + + @Override + public int getLightLevel() { + if (this.isDead()) { + return 0; + } else { + return (this.getDamage() + 1) * 3; + } + } + + @Override + public boolean breakWhenPushed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSeagrass.java b/src/main/java/cn/nukkit/block/BlockSeagrass.java new file mode 100644 index 00000000000..ed7781fc642 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSeagrass.java @@ -0,0 +1,178 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.*; +import cn.nukkit.level.Level; +import cn.nukkit.level.format.anvil.Anvil; +import cn.nukkit.level.particle.BoneMealParticle; +import cn.nukkit.math.BlockFace; +import cn.nukkit.math.Vector3; +import cn.nukkit.utils.BlockColor; + +public class BlockSeagrass extends BlockFlowable { + + public BlockSeagrass() { + this(0); + } + + public BlockSeagrass(int meta) { + super(meta % 3); + } + + @Override + public String getName() { + return "Seagrass"; + } + + @Override + public int getId() { + return SEAGRASS; + } + + public int getToolType() { + return ItemTool.SHEARS; + } + + public double getHardness() { + return 0; + } + + public double getResistance() { + return 0; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (level != null && level.getProvider() instanceof Anvil) { + if (!(block instanceof BlockWater && block.getDamage() == 0) || this.down().isTransparent()) { + return false; + } + return this.getLevel().setBlock(this, this, true, true); + } + + + Block down = this.down(); + Block layer1Block = block.getLevelBlock(BlockLayer.WATERLOGGED); + int waterDamage; + if (down.isSolid() && down.getId() != MAGMA && down.getId() != SOUL_SAND && + (layer1Block instanceof BlockWater && ((waterDamage = (block.getDamage())) == 0 || waterDamage == 8)) + ) { + if (waterDamage == 8) { + this.getLevel().setBlock((int) this.x, (int) this.y, (int) this.z, Block.LAYER_WATERLOGGED, Block.get(Block.STILL_WATER), true, true); + } + this.getLevel().setBlock(this, BlockLayer.NORMAL, this, true, true); + return true; + } + return false; + } + + @Override + public int onUpdate(int type) { + if (level != null && level.getProvider() instanceof Anvil) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + Block down = this.down(); + if (down.isTransparent() && down.getId() != SEAGRASS) { + this.getLevel().useBreakOn(this); + } + } + return type; + } + + + if (type == Level.BLOCK_UPDATE_NORMAL) { + Block blockLayer1 = this.getLevelBlock(BlockLayer.WATERLOGGED); + int damage; + if (!(blockLayer1 instanceof BlockIceFrosted) + && (!(blockLayer1 instanceof BlockWater) || ((damage = blockLayer1.getDamage()) != 0 && damage != 8))) { + this.getLevel().useBreakOn(this); + return Level.BLOCK_UPDATE_NORMAL; + } + + Block down = this.down(); + damage = this.getDamage(); + if (damage == 0 || damage == 2) { + if (!down.isSolid() || down.getId() == MAGMA || down.getId() == SOUL_SAND) { + this.getLevel().useBreakOn(this); + return Level.BLOCK_UPDATE_NORMAL; + } + + if (damage == 2) { + Block up = up(); + if (up.getId() != getId() || up.getDamage() != 1) { + this.getLevel().useBreakOn(this); + } + } + } else if (down.getId() != getId() || down.getDamage() != 2) { + this.getLevel().useBreakOn(this); + } + + return Level.BLOCK_UPDATE_NORMAL; + } + + return 0; + } + + @Override + public Item[] getDrops(Item item) { + if (item.isShears()) { + return new Item[] { toItem() }; + } else { + return new Item[0]; + } + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(SEAGRASS), 0, 1); + } + + @Override + public void setDamage(int meta) { + super.setDamage(meta % 3); + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.FLOW_INTO_BLOCK; + } + + @Override + public boolean canBeFlowedInto() { + return level == null || !(level.getProvider() instanceof Anvil); + } + + @Override + public BlockColor getColor() { + return BlockColor.WATER_BLOCK_COLOR; + } + + @Override + public boolean canBeReplaced() { + return true; + } + + + @Override + public boolean canBeActivated() { + return this.getDamage() == 0; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (this.getDamage() == 0 && item.getId() == ItemID.DYE && item.getDamage() == ItemDye.BONE_MEAL && up() instanceof BlockWater) { + Vector3 up = this.getSideVec(BlockFace.UP); + if (this.level.setBlock(up, Block.get(SEAGRASS, 1), true, true)) { + this.level.setBlock(this, Block.get(SEAGRASS, 2), true, true); + } + + if (player != null && !player.isCreative()) { + item.count--; + } + + this.level.addParticle(new BoneMealParticle(this)); + + return true; + } + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockShroomlight.java b/src/main/java/cn/nukkit/block/BlockShroomlight.java new file mode 100644 index 00000000000..6934a70a81a --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockShroomlight.java @@ -0,0 +1,46 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockShroomlight extends BlockSolid { + + public BlockShroomlight() { + // Does nothing + } + + @Override + public int getId() { + return SHROOMLIGHT; + } + + @Override + public String getName() { + return "Shroomlight"; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_HOE; + } + + @Override + public double getResistance() { + return 1; + } + + @Override + public double getHardness() { + return 1; + } + + @Override + public int getLightLevel() { + return 15; + } + + @Override + public BlockColor getColor() { + return BlockColor.ORANGE_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockShulkerBox.java b/src/main/java/cn/nukkit/block/BlockShulkerBox.java index 046cda38896..d7d150ec66c 100644 --- a/src/main/java/cn/nukkit/block/BlockShulkerBox.java +++ b/src/main/java/cn/nukkit/block/BlockShulkerBox.java @@ -1,22 +1,32 @@ package cn.nukkit.block; +import cn.nukkit.Player; +import cn.nukkit.blockentity.BlockEntity; +import cn.nukkit.blockentity.BlockEntityShulkerBox; +import cn.nukkit.inventory.BaseInventory; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.math.BlockFace; +import cn.nukkit.nbt.NBTIO; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.ListTag; import cn.nukkit.utils.BlockColor; import cn.nukkit.utils.DyeColor; -/** - * Created by PetteriM1 - */ -public class BlockShulkerBox extends BlockUndyedShulkerBox { - - private int meta; +public class BlockShulkerBox extends BlockTransparentMeta { public BlockShulkerBox() { this(0); } public BlockShulkerBox(int meta) { - super(); - this.meta = meta; + super(meta); + } + + @Override + public boolean canBeActivated() { + return true; } @Override @@ -29,6 +39,108 @@ public String getName() { return this.getDyeColor().getName() + " Shulker Box"; } + @Override + public double getHardness() { + return 0.6; + } + + @Override + public double getResistance() { + return 2; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public Item toItem() { + ItemBlock item = new ItemBlock(this, this.getDamage(), 1); + + BlockEntity be = this.getLevel().getBlockEntity(this); + + if (be instanceof BlockEntityShulkerBox) { + BlockEntityShulkerBox t = (BlockEntityShulkerBox) be; + + BaseInventory i = t.getInventory(); + + if (!i.slots.isEmpty()) { + + CompoundTag nbt = item.getNamedTag(); + if (nbt == null) + nbt = new CompoundTag(""); + + ListTag items = new ListTag<>(); + + for (int it = 0; it < i.getSize(); it++) { + if (i.getItem(it).getId() != Item.AIR) { + CompoundTag d = NBTIO.putItemHelper(i.getItem(it), it); + items.add(d); + } + } + + nbt.put("Items", items); + + item.setCompoundTag(nbt); + } + + if (t.hasName()) { + item.setCustomName(t.getName()); + } + } + + return item; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + this.getLevel().setBlock(this, this, true, true); + + CompoundTag nbt = BlockEntity.getDefaultCompound(this, BlockEntity.SHULKER_BOX) + .putByte("facing", face.getIndex()); + + if (item.hasCustomName()) { + nbt.putString("CustomName", item.getCustomName()); + } + + CompoundTag t = item.getNamedTag(); + + if (t != null) { + if (t.contains("Items")) { + nbt.putList(t.getList("Items")); + } + } + + BlockEntity.createBlockEntity(BlockEntity.SHULKER_BOX, this.getChunk(), nbt); + return true; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (player != null) { + BlockEntity t = this.getLevel().getBlockEntity(this); + if (!(t instanceof BlockEntityShulkerBox)) { + return false; + } + + BlockEntityShulkerBox box = (BlockEntityShulkerBox) t; + Block block = this.getSide(BlockFace.fromIndex(box.namedTag.getByte("facing"))); + if (!(block instanceof BlockAir) && !(block instanceof BlockLiquid) && !(block instanceof BlockFlowable)) { + return true; + } + + player.addWindow(box.getInventory()); + } + + return true; + } + @Override public BlockColor getColor() { return this.getDyeColor().getColor(); @@ -39,17 +151,17 @@ public DyeColor getDyeColor() { } @Override - public int getFullId() { - return (this.getId() << 4) + this.getDamage(); + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; } @Override - public final int getDamage() { - return this.meta; + public boolean breakWhenPushed() { + return true; } @Override - public void setDamage(int meta) { - this.meta = meta; + public boolean alwaysDropsOnExplosion() { + return true; } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockSignPost.java b/src/main/java/cn/nukkit/block/BlockSignPost.java index 496cb06b285..e0641e011e9 100644 --- a/src/main/java/cn/nukkit/block/BlockSignPost.java +++ b/src/main/java/cn/nukkit/block/BlockSignPost.java @@ -7,7 +7,6 @@ import cn.nukkit.event.block.SignGlowEvent; import cn.nukkit.item.Item; import cn.nukkit.item.ItemDye; -import cn.nukkit.item.ItemSign; import cn.nukkit.item.ItemTool; import cn.nukkit.level.Level; import cn.nukkit.math.AxisAlignedBB; @@ -63,6 +62,14 @@ public AxisAlignedBB getBoundingBox() { return null; } + protected int getPostId() { + return SIGN_POST; + } + + protected int getWallId() { + return WALL_SIGN; + } + @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { if (face != BlockFace.DOWN) { @@ -78,10 +85,13 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl if (face == BlockFace.UP) { setDamage((int) Math.floor(((player.yaw + 180) * 16 / 360) + 0.5) & 0x0f); - getLevel().setBlock(block, Block.get(BlockID.SIGN_POST, getDamage()), true); + getLevel().setBlock(block, Block.get(getPostId(), getDamage()), true); + } else if (target.canBeReplaced()) { + setDamage((int) Math.floor(((player.yaw + 180) * 16 / 360) + 0.5) & 0x0f); + getLevel().setBlock(target, Block.get(getPostId(), getDamage()), true); } else { setDamage(face.getIndex()); - getLevel().setBlock(block, Block.get(BlockID.WALL_SIGN, getDamage()), true); + getLevel().setBlock(block, Block.get(getWallId(), getDamage()), true); } if (player != null) { @@ -94,7 +104,7 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl } } - BlockEntitySign sign = (BlockEntitySign) BlockEntity.createBlockEntity(BlockEntity.SIGN, getLevel().getChunk((int) block.x >> 4, (int) block.z >> 4), nbt); + BlockEntity.createBlockEntity(BlockEntity.SIGN, this.getChunk(), nbt); if (player != null) { OpenSignPacket pk = new OpenSignPacket(); @@ -102,8 +112,7 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl pk.frontSide = true; player.dataPacket(pk); } - - return sign != null; + return true; } return false; @@ -124,7 +133,7 @@ public int onUpdate(int type) { @Override public Item toItem() { - return new ItemSign(); + return Item.get(Item.SIGN); } @Override @@ -150,7 +159,7 @@ public boolean canBeActivated() { @Override public boolean onActivate(Item item, Player player) { if (item.getId() == Item.DYE) { - BlockEntity blockEntity = this.level.getBlockEntity(this); + BlockEntity blockEntity = this.level.getBlockEntityIfLoaded(player == null ? null : player.chunk, this); if (!(blockEntity instanceof BlockEntitySign)) { return false; } @@ -169,9 +178,9 @@ public boolean onActivate(Item item, Player player) { SignGlowEvent event = new SignGlowEvent(this, player, glow); this.level.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { - if (player != null) { + /*if (player != null) { sign.spawnTo(player); - } + }*/ return false; } @@ -189,9 +198,9 @@ public boolean onActivate(Item item, Player player) { BlockColor color = DyeColor.getByDyeData(meta).getSignColor(); if (color.equals(sign.getColor())) { - if (player != null) { + /*if (player != null) { sign.spawnTo(player); - } + }*/ return false; } @@ -217,4 +226,9 @@ public boolean onActivate(Item item, Player player) { } return false; } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockSkull.java b/src/main/java/cn/nukkit/block/BlockSkull.java index c11158ee98b..9672c1bab7e 100644 --- a/src/main/java/cn/nukkit/block/BlockSkull.java +++ b/src/main/java/cn/nukkit/block/BlockSkull.java @@ -15,7 +15,7 @@ import cn.nukkit.utils.Faceable; /** - * author: Justin + * @author Justin */ public class BlockSkull extends BlockTransparentMeta implements Faceable { @@ -73,7 +73,7 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl default: return false; } - this.getLevel().setBlock(block, this, true, true); + this.getLevel().setBlock(this, this, true, true); CompoundTag nbt = new CompoundTag() .putString("id", BlockEntity.SKULL) @@ -90,9 +90,6 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl BlockEntitySkull blockEntity = (BlockEntitySkull) BlockEntity.createBlockEntity(BlockEntity.SKULL, this.getChunk(), nbt); blockEntity.spawnToAll(); - - // TODO: 2016/2/3 SPAWN WITHER - return true; } @@ -123,7 +120,6 @@ public int getToolType() { public BlockColor getColor() { return BlockColor.AIR_BLOCK_COLOR; } - @Override public BlockFace getBlockFace() { return BlockFace.fromIndex(this.getDamage() & 0x7); @@ -144,4 +140,24 @@ protected AxisAlignedBB recalculateBoundingBox() { } return bb; } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean canBeFlowedInto() { + return true; + } + + @Override + public boolean breakWhenPushed() { + return true; + } + + @Override + public boolean alwaysDropsOnExplosion() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockSlab.java b/src/main/java/cn/nukkit/block/BlockSlab.java index 64cfe2f1a9d..dad661f8fce 100644 --- a/src/main/java/cn/nukkit/block/BlockSlab.java +++ b/src/main/java/cn/nukkit/block/BlockSlab.java @@ -2,11 +2,14 @@ import cn.nukkit.Player; import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemTool; +import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.math.BlockFace; +import cn.nukkit.math.SimpleAxisAlignedBB; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class BlockSlab extends BlockTransparentMeta { @@ -19,18 +22,40 @@ public BlockSlab(int meta, int doubleSlab) { } @Override - public double getMinY() { - return ((this.getDamage() & 0x08) > 0) ? this.y + 0.5 : this.y; + protected AxisAlignedBB recalculateBoundingBox() { + if (this.hasTopBit()) { + return new SimpleAxisAlignedBB( + this.x, + this.y + 0.5, + this.z, + this.x + 1, + this.y + 1, + this.z + 1 + ); + } else { + return new SimpleAxisAlignedBB( + this.x, + this.y, + this.z, + this.x + 1, + this.y + 0.5, + this.z + 1 + ); + } + } + + public String getSlabName() { + return ""; } @Override - public double getMaxY() { - return ((this.getDamage() & 0x08) > 0) ? this.y + 1 : this.y + 0.5; + public String getName() { + return (this.hasTopBit()? "Upper " : "") + this.getSlabName() + " Slab"; } @Override public double getHardness() { - return 2; + return 3; } @Override @@ -42,30 +67,30 @@ public double getResistance() { public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { this.setDamage(this.getDamage() & 0x07); if (face == BlockFace.DOWN) { - if (target instanceof BlockSlab && (target.getDamage() & 0x08) == 0x08 && (target.getDamage() & 0x07) == (this.getDamage() & 0x07)) { + if (target instanceof BlockSlab && ((BlockSlab) target).doubleSlab == this.doubleSlab && ((BlockSlab) target).hasTopBit() && (target.getDamage() & 0x07) == (this.getDamage() & 0x07)) { this.getLevel().setBlock(target, Block.get(doubleSlab, this.getDamage()), true); return true; - } else if (block instanceof BlockSlab && (block.getDamage() & 0x07) == (this.getDamage() & 0x07)) { + } else if (block instanceof BlockSlab && ((BlockSlab) block).doubleSlab == this.doubleSlab && (block.getDamage() & 0x07) == (this.getDamage() & 0x07)) { this.getLevel().setBlock(block, Block.get(doubleSlab, this.getDamage()), true); return true; } else { - this.setDamage(this.getDamage() | 0x08); + this.setTopBit(true); } } else if (face == BlockFace.UP) { - if (target instanceof BlockSlab && (target.getDamage() & 0x08) == 0 && (target.getDamage() & 0x07) == (this.getDamage() & 0x07)) { + if (target instanceof BlockSlab && ((BlockSlab) target).doubleSlab == this.doubleSlab && !((BlockSlab) target).hasTopBit() && (target.getDamage() & 0x07) == (this.getDamage() & 0x07)) { this.getLevel().setBlock(target, Block.get(doubleSlab, this.getDamage()), true); return true; - } else if (block instanceof BlockSlab && (block.getDamage() & 0x07) == (this.getDamage() & 0x07)) { + } else if (block instanceof BlockSlab && ((BlockSlab) block).doubleSlab == this.doubleSlab && (block.getDamage() & 0x07) == (this.getDamage() & 0x07)) { this.getLevel().setBlock(block, Block.get(doubleSlab, this.getDamage()), true); return true; } //TODO: check for collision } else { - if (block instanceof BlockSlab) { + if (block instanceof BlockSlab && ((BlockSlab) block).doubleSlab == this.doubleSlab) { if ((block.getDamage() & 0x07) == (this.getDamage() & 0x07)) { this.getLevel().setBlock(block, Block.get(doubleSlab, this.getDamage()), true); @@ -75,16 +100,39 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl return false; } else { if (fy > 0.5) { - this.setDamage(this.getDamage() | 0x08); + this.setTopBit(true); } } } - if (block instanceof BlockSlab && (target.getDamage() & 0x07) != (this.getDamage() & 0x07)) { + if (block instanceof BlockSlab && ((BlockSlab) block).doubleSlab == this.doubleSlab && (target.getDamage() & 0x07) != (this.getDamage() & 0x07)) { return false; } - this.getLevel().setBlock(block, this, true, true); + this.getLevel().setBlock(this, this, true, true); return true; } -} \ No newline at end of file + + public boolean hasTopBit() { + return (this.getDamage() & 0x08) > 0; + } + + public void setTopBit(boolean topBit) { + if (topBit) { + this.setDamage(this.getDamage() | 0x08); + } else { + this.setDamage(this.getDamage() & 0x07); + } + } + + @Override + public Item toItem() { + int damage = this.getDamage() & 0x07; + return new ItemBlock(Block.get(this.getId(), damage), damage); + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabBlackstone.java b/src/main/java/cn/nukkit/block/BlockSlabBlackstone.java new file mode 100644 index 00000000000..ab512d630b6 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabBlackstone.java @@ -0,0 +1,70 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockSlabBlackstone extends BlockSlab { + + public BlockSlabBlackstone() { + this(0); + } + + public BlockSlabBlackstone(int meta) { + super(meta, BLACKSTONE_DOUBLE_SLAB); + } + + @Override + public int getId() { + return BLACKSTONE_SLAB; + } + + @Override + public boolean hasTopBit() { + return (this.getDamage() & 0x01) == 1; + } + + @Override + public void setTopBit(boolean topBit) { + this.setDamage(topBit ? 1 : 0); + } + + @Override + public String getName() { + return "Blackstone Slab"; + } + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public Item[] getDrops(Item item) { + if (item.isPickaxe()) { + return new Item[]{this.toItem()}; + } else { + return new Item[0]; + } + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public BlockColor getColor() { + return BlockColor.BLACK_BLOCK_COLOR; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabBlackstonePolished.java b/src/main/java/cn/nukkit/block/BlockSlabBlackstonePolished.java new file mode 100644 index 00000000000..260b884ecdb --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabBlackstonePolished.java @@ -0,0 +1,74 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockSlabBlackstonePolished extends BlockSlab { + + public BlockSlabBlackstonePolished() { + this(0); + } + + public BlockSlabBlackstonePolished(int meta) { + super(meta, POLISHED_BLACKSTONE_DOUBLE_SLAB); + } + + protected BlockSlabBlackstonePolished(int meta, int doubleSlab) { + super(meta, doubleSlab); + } + + @Override + public int getId() { + return POLISHED_BLACKSTONE_SLAB; + } + + @Override + public boolean hasTopBit() { + return (this.getDamage() & 0x01) == 1; + } + + @Override + public void setTopBit(boolean topBit) { + this.setDamage(topBit ? 1 : 0); + } + + @Override + public String getSlabName() { + return "Polished Blackstone"; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public Item[] getDrops(Item item) { + if (item.isPickaxe()) { + return new Item[]{ this.toItem() }; + } + return new Item[0]; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public double getResistance() { + return 6.0; + } + + @Override + public BlockColor getColor() { + return BlockColor.BLACK_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabBrickBlackstonePolished.java b/src/main/java/cn/nukkit/block/BlockSlabBrickBlackstonePolished.java new file mode 100644 index 00000000000..8cd18484070 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabBrickBlackstonePolished.java @@ -0,0 +1,27 @@ +package cn.nukkit.block; + +public class BlockSlabBrickBlackstonePolished extends BlockSlabBlackstonePolished { + + public BlockSlabBrickBlackstonePolished() { + this(0); + } + + public BlockSlabBrickBlackstonePolished(int meta) { + super(meta, POLISHED_BLACKSTONE_BRICK_DOUBLE_SLAB); + } + + protected BlockSlabBrickBlackstonePolished(int meta, int doubleSlab) { + super(meta, doubleSlab); + } + + @Override + public int getId() { + return POLISHED_BLACKSTONE_BRICK_SLAB; + } + + @Override + public String getSlabName() { + return "Polished Blackstone Brick"; + } + +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabBrickDeepslate.java b/src/main/java/cn/nukkit/block/BlockSlabBrickDeepslate.java new file mode 100644 index 00000000000..c7283cad770 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabBrickDeepslate.java @@ -0,0 +1,56 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockSlabBrickDeepslate extends BlockSlab { + + public BlockSlabBrickDeepslate() { + this(0); + } + + public BlockSlabBrickDeepslate(int meta) { + super(meta, DEEPSLATE_BRICK_SLAB); + } + + @Override + public int getId() { + return DEEPSLATE_BRICK_SLAB; + } + + @Override + public String getSlabName() { + return "Deepslate Brick"; + } + + + @Override + public double getHardness() { + return 3.5; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_WOODEN; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabCopperBase.java b/src/main/java/cn/nukkit/block/BlockSlabCopperBase.java new file mode 100644 index 00000000000..d466b8c7ad6 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabCopperBase.java @@ -0,0 +1,91 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public abstract class BlockSlabCopperBase extends BlockSlab implements Waxable, Oxidizable { + + public BlockSlabCopperBase(int meta, int doubleSlab) { + super(meta, doubleSlab); + } + + @Override + public boolean onActivate(@Nonnull Item item, @Nullable Player player) { + return Waxable.super.onActivate(item, player) + || Oxidizable.super.onActivate(item, player); + } + + @Override + public int onUpdate(int type) { + return Oxidizable.super.onUpdate(type); + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public BlockColor getColor() { + return BlockColor.ORANGE_BLOCK_COLOR; + } + + @Override + public double getHardness() { + return 3; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_STONE; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public Block getStateWithOxidizationLevel(OxidizationLevel oxidizationLevel) { + return Block.get(this.getCopperId(this.isWaxed(), oxidizationLevel), this.getDamage()); + } + + @Override + public boolean setOxidizationLevel(OxidizationLevel oxidizationLevel) { + if (this.getOxidizationLevel().equals(oxidizationLevel)) { + return true; + } + return this.level.setBlock(this, Block.get(this.getCopperId(this.isWaxed(), oxidizationLevel))); + } + + @Override + public boolean setWaxed(boolean waxed) { + if (this.isWaxed() == waxed) { + return true; + } + return this.level.setBlock(this, Block.get(getCopperId(waxed, getOxidizationLevel()))); + } + + @Override + public boolean isWaxed() { + return false; + } + + protected abstract int getCopperId(boolean waxed, OxidizationLevel oxidizationLevel); +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabCopperCut.java b/src/main/java/cn/nukkit/block/BlockSlabCopperCut.java new file mode 100644 index 00000000000..55373beb66c --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabCopperCut.java @@ -0,0 +1,62 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; + +public class BlockSlabCopperCut extends BlockSlabCopperBase { + + public BlockSlabCopperCut() { + this(0); + } + + public BlockSlabCopperCut(int meta) { + super(meta, DOUBLE_CUT_COPPER_SLAB); + } + + protected BlockSlabCopperCut(int meta, int doubleSlab) { + super(meta, doubleSlab); + } + + @Override + public int getId() { + return CUT_COPPER_SLAB; + } + + @Override + public String getSlabName() { + String name = ""; + if (this.isWaxed()) { + name += "Waxed "; + } + + OxidizationLevel oxidizationLevel = this.getOxidizationLevel(); + if (oxidizationLevel != OxidizationLevel.UNAFFECTED) { + String oxidationName = oxidizationLevel.name(); + name += oxidationName.charAt(0) + oxidationName.substring(1).toLowerCase(); + } + return name + " Cut Copper"; + } + + @Override + protected int getCopperId(boolean waxed, OxidizationLevel oxidizationLevel) { + if (oxidizationLevel == null) { + return getId(); + } + switch (oxidizationLevel) { + case UNAFFECTED: + return waxed ? WAXED_CUT_COPPER_SLAB : CUT_COPPER_SLAB; + case EXPOSED: + return waxed ? WAXED_EXPOSED_CUT_COPPER_SLAB : EXPOSED_CUT_COPPER_SLAB; + case WEATHERED: + return waxed ? WAXED_WEATHERED_CUT_COPPER_SLAB : WEATHERED_CUT_COPPER_SLAB; + case OXIDIZED: + return waxed ? WAXED_OXIDIZED_CUT_COPPER_SLAB : OXIDIZED_CUT_COPPER_SLAB; + default: + return getId(); + } + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.UNAFFECTED; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabCopperCutExposed.java b/src/main/java/cn/nukkit/block/BlockSlabCopperCutExposed.java new file mode 100644 index 00000000000..8f2580568fa --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabCopperCutExposed.java @@ -0,0 +1,34 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.utils.BlockColor; + +public class BlockSlabCopperCutExposed extends BlockSlabCopperCut { + + public BlockSlabCopperCutExposed() { + this(0); + } + + public BlockSlabCopperCutExposed(int meta) { + super(meta, EXPOSED_DOUBLE_CUT_COPPER_SLAB); + } + + protected BlockSlabCopperCutExposed(int meta, int doubleSlab) { + super(meta, doubleSlab); + } + + @Override + public int getId() { + return EXPOSED_CUT_COPPER_SLAB; + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.EXPOSED; + } + + @Override + public BlockColor getColor() { + return BlockColor.LIGHT_GRAY_TERRACOTA_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabCopperCutExposedWaxed.java b/src/main/java/cn/nukkit/block/BlockSlabCopperCutExposedWaxed.java new file mode 100644 index 00000000000..1cbc80b757d --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabCopperCutExposedWaxed.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockSlabCopperCutExposedWaxed extends BlockSlabCopperCutExposed { + + public BlockSlabCopperCutExposedWaxed() { + this(0); + } + + public BlockSlabCopperCutExposedWaxed(int meta) { + super(meta, WAXED_EXPOSED_DOUBLE_CUT_COPPER_SLAB); + } + + @Override + public int getId() { + return WAXED_EXPOSED_CUT_COPPER_SLAB; + } + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabCopperCutOxidized.java b/src/main/java/cn/nukkit/block/BlockSlabCopperCutOxidized.java new file mode 100644 index 00000000000..5cc2a84d04c --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabCopperCutOxidized.java @@ -0,0 +1,34 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.utils.BlockColor; + +public class BlockSlabCopperCutOxidized extends BlockSlabCopperCut { + + public BlockSlabCopperCutOxidized() { + this(0); + } + + public BlockSlabCopperCutOxidized(int meta) { + super(meta, OXIDIZED_DOUBLE_CUT_COPPER_SLAB); + } + + protected BlockSlabCopperCutOxidized(int meta, int doubleSlab) { + super(meta, doubleSlab); + } + + @Override + public int getId() { + return OXIDIZED_CUT_COPPER_SLAB; + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.OXIDIZED; + } + + @Override + public BlockColor getColor() { + return BlockColor.WARPED_NYLIUM_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabCopperCutOxidizedWaxed.java b/src/main/java/cn/nukkit/block/BlockSlabCopperCutOxidizedWaxed.java new file mode 100644 index 00000000000..d5c425c7247 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabCopperCutOxidizedWaxed.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockSlabCopperCutOxidizedWaxed extends BlockSlabCopperCutOxidized { + + public BlockSlabCopperCutOxidizedWaxed() { + this(0); + } + + public BlockSlabCopperCutOxidizedWaxed(int meta) { + super(meta, WAXED_OXIDIZED_DOUBLE_CUT_COPPER_SLAB); + } + + @Override + public int getId() { + return WAXED_OXIDIZED_CUT_COPPER_SLAB; + } + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabCopperCutWaxed.java b/src/main/java/cn/nukkit/block/BlockSlabCopperCutWaxed.java new file mode 100644 index 00000000000..2d8a8ac1495 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabCopperCutWaxed.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockSlabCopperCutWaxed extends BlockSlabCopperCut { + + public BlockSlabCopperCutWaxed() { + this(0); + } + + public BlockSlabCopperCutWaxed(int meta) { + super(meta, WAXED_DOUBLE_CUT_COPPER_SLAB); + } + + @Override + public int getId() { + return WAXED_CUT_COPPER_SLAB; + } + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabCopperCutWeathered.java b/src/main/java/cn/nukkit/block/BlockSlabCopperCutWeathered.java new file mode 100644 index 00000000000..7edf336bd05 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabCopperCutWeathered.java @@ -0,0 +1,34 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.utils.BlockColor; + +public class BlockSlabCopperCutWeathered extends BlockSlabCopperCut { + + public BlockSlabCopperCutWeathered() { + this(0); + } + + public BlockSlabCopperCutWeathered(int meta) { + super(meta, WEATHERED_DOUBLE_CUT_COPPER_SLAB); + } + + protected BlockSlabCopperCutWeathered(int meta, int doubleSlab) { + super(meta, doubleSlab); + } + + @Override + public int getId() { + return WEATHERED_CUT_COPPER_SLAB; + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.WEATHERED; + } + + @Override + public BlockColor getColor() { + return BlockColor.WARPED_STEM_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabCopperCutWeatheredWaxed.java b/src/main/java/cn/nukkit/block/BlockSlabCopperCutWeatheredWaxed.java new file mode 100644 index 00000000000..17eded2a46d --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabCopperCutWeatheredWaxed.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockSlabCopperCutWeatheredWaxed extends BlockSlabCopperCutWeathered { + + public BlockSlabCopperCutWeatheredWaxed() { + this(0); + } + + public BlockSlabCopperCutWeatheredWaxed(int meta) { + super(meta, WAXED_WEATHERED_DOUBLE_CUT_COPPER_SLAB); + } + + @Override + public int getId() { + return WAXED_WEATHERED_CUT_COPPER_SLAB; + } + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabCrimson.java b/src/main/java/cn/nukkit/block/BlockSlabCrimson.java new file mode 100644 index 00000000000..2d8720eaa97 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabCrimson.java @@ -0,0 +1,64 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockSlabCrimson extends BlockSlab { + + public BlockSlabCrimson() { + this(0); + } + + public BlockSlabCrimson(int meta) { + super(meta, CRIMSON_DOUBLE_SLAB); + } + + @Override + public String getSlabName() { + return "Crimson"; + } + + @Override + public int getId() { + return CRIMSON_SLAB; + } + + @Override + public boolean hasTopBit() { + return (this.getDamage() & 0x01) == 1; + } + + @Override + public void setTopBit(boolean topBit) { + this.setDamage(topBit ? 1 : 0); + } + + @Override + public int getToolType() { + return ItemTool.TYPE_AXE; + } + + @Override + public Item[] getDrops(Item item) { + return new Item[]{ + this.toItem() + }; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public double getResistance() { + return 3; + } + + @Override + public BlockColor getColor() { + return BlockColor.NETHERRACK_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabDeepslateCobbled.java b/src/main/java/cn/nukkit/block/BlockSlabDeepslateCobbled.java new file mode 100644 index 00000000000..ddd0ca85453 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabDeepslateCobbled.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockSlabDeepslateCobbled extends BlockSlab { + + public BlockSlabDeepslateCobbled() { + this(0); + } + + public BlockSlabDeepslateCobbled(int meta) { + super(meta, COBBLED_DEEPSLATE_DOUBLE_SLAB); + } + + @Override + public int getId() { + return COBBLED_DEEPSLATE_SLAB; + } + + @Override + public String getSlabName() { + return "Cobbled Deepslate"; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabDeepslatePolished.java b/src/main/java/cn/nukkit/block/BlockSlabDeepslatePolished.java new file mode 100644 index 00000000000..ea218f10b87 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabDeepslatePolished.java @@ -0,0 +1,55 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockSlabDeepslatePolished extends BlockSlab { + + public BlockSlabDeepslatePolished() { + this(0); + } + + public BlockSlabDeepslatePolished(int meta) { + super(meta, POLISHED_DEEPSLATE_SLAB); + } + + @Override + public int getId() { + return POLISHED_DEEPSLATE_SLAB; + } + + @Override + public String getSlabName() { + return "Polished Deepslate"; + } + + @Override + public double getHardness() { + return 3.5; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_WOODEN; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabRedSandstone.java b/src/main/java/cn/nukkit/block/BlockSlabRedSandstone.java index 3eb447dfdd7..44edf725534 100644 --- a/src/main/java/cn/nukkit/block/BlockSlabRedSandstone.java +++ b/src/main/java/cn/nukkit/block/BlockSlabRedSandstone.java @@ -2,7 +2,6 @@ import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; -import cn.nukkit.item.ItemTool; import cn.nukkit.utils.BlockColor; /** @@ -11,10 +10,10 @@ public class BlockSlabRedSandstone extends BlockSlab { public static final int RED_SANDSTONE = 0; - public static final int PURPUR = 1; //WHY THIS + public static final int PURPUR = 1; public BlockSlabRedSandstone() { - this(0); + this(RED_SANDSTONE); } public BlockSlabRedSandstone(int meta) { @@ -26,25 +25,25 @@ public int getId() { return RED_SANDSTONE_SLAB; } + private static final String[] NAMES = { + "Red Sandstone", + "Purpur", + "", + "", + "", + "", + "", + "" + }; + @Override public String getName() { - String[] names = new String[]{ - "Red Sandstone", - "Purpur", - "", - "", - "", - "", - "", - "" - }; - - return ((this.getDamage() & 0x08) > 0 ? "Upper " : "") + names[this.getDamage() & 0x07] + " Slab"; + return ((this.getDamage() & 0x08) > 0 ? "Upper " : "") + NAMES[this.getDamage() & 0x07] + " Slab"; } @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; @@ -55,7 +54,8 @@ public Item[] getDrops(Item item) { @Override public Item toItem() { - return new ItemBlock(this, this.getDamage() & 0x07); + int damage = this.getDamage() & 0x07; + return new ItemBlock(Block.get(this.getId(), damage), damage); } @Override @@ -65,6 +65,25 @@ public boolean canHarvestWithHand() { @Override public BlockColor getColor() { - return BlockColor.ORANGE_BLOCK_COLOR; + int damage = this.getDamage() & 0x07; + switch (damage) { + case 0: + return BlockColor.ORANGE_BLOCK_COLOR; + case 1: + return BlockColor.PURPLE_BLOCK_COLOR; + case 2: + return BlockColor.CYAN_BLOCK_COLOR; + case 3: + return BlockColor.DIAMOND_BLOCK_COLOR; + case 4: + return BlockColor.CYAN_BLOCK_COLOR; + case 5: + return BlockColor.STONE_BLOCK_COLOR; + case 6: + return BlockColor.SAND_BLOCK_COLOR; + case 7: + return BlockColor.NETHERRACK_BLOCK_COLOR; + } + return BlockColor.STONE_BLOCK_COLOR; } -} \ No newline at end of file +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabStone.java b/src/main/java/cn/nukkit/block/BlockSlabStone.java index 82cde51a5e2..07369ac664e 100644 --- a/src/main/java/cn/nukkit/block/BlockSlabStone.java +++ b/src/main/java/cn/nukkit/block/BlockSlabStone.java @@ -9,6 +9,7 @@ * Created by CreeperFace on 26. 11. 2016. */ public class BlockSlabStone extends BlockSlab { + public static final int STONE = 0; public static final int SANDSTONE = 1; public static final int WOODEN = 2; @@ -23,7 +24,11 @@ public BlockSlabStone() { } public BlockSlabStone(int meta) { - super(meta, DOUBLE_STONE_SLAB); + this(meta, DOUBLE_STONE_SLAB); + } + + public BlockSlabStone(int meta, int doubleSlab) { + super(meta, doubleSlab); } @Override @@ -31,25 +36,25 @@ public int getId() { return STONE_SLAB; } + private static final String[] NAMES = { + "Stone", + "Sandstone", + "Oak", + "Cobblestone", + "Brick", + "Stone Brick", + "Quartz", + "Nether Brick" + }; + @Override public String getName() { - String[] names = new String[]{ - "Stone", - "Sandstone", - "Wooden", - "Cobblestone", - "Brick", - "Stone Brick", - "Quartz", - "Nether Brick" - }; - - return ((this.getDamage() & 0x08) > 0 ? "Upper " : "") + names[this.getDamage() & 0x07] + " Slab"; + return ((this.getDamage() & 0x08) > 0 ? "Upper " : "") + NAMES[this.getDamage() & 0x07] + " Slab"; } @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; @@ -60,7 +65,8 @@ public Item[] getDrops(Item item) { @Override public Item toItem() { - return new ItemBlock(this, this.getDamage() & 0x07); + int damage = this.getDamage() & 0x07; + return new ItemBlock(Block.get(this.getId(), damage), damage); } @Override @@ -92,4 +98,4 @@ public BlockColor getColor() { public boolean canHarvestWithHand() { return false; } -} \ No newline at end of file +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabStone3.java b/src/main/java/cn/nukkit/block/BlockSlabStone3.java new file mode 100644 index 00000000000..2ad845f5639 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabStone3.java @@ -0,0 +1,72 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.utils.BlockColor; + +public class BlockSlabStone3 extends BlockSlabStone { + + public static final int END_STONE_BRICKS = 0; + public static final int SMOOTH_RED_SANDSTONE = 1; + public static final int POLISHED_ANDESITE = 2; + public static final int ANDESITE = 3; + public static final int DIORITE = 4; + public static final int POLISHED_DIORITE = 5; + public static final int GRANITE = 6; + public static final int POLISHED_GRANITE = 7; + + private static final String[] NAMES = { + "End Stone Brick", + "Smooth Red Sandstone", + "Polished Andesite", + "Andesite", + "Diorite", + "Polished Diorite", + "Granite", + "Polisehd Granite" + }; + + public BlockSlabStone3() { + this(0); + } + + public BlockSlabStone3(int meta) { + super(meta, DOUBLE_STONE_SLAB3); + } + + @Override + public String getName() { + return ((this.getDamage() & 0x08) > 0 ? "Upper " : "") + NAMES[this.getDamage() & 0x07] + " Slab"; + } + + @Override + public int getId() { + return STONE_SLAB3; + } + + @Override + public BlockColor getColor() { + switch (this.getDamage() & 0x07) { + case END_STONE_BRICKS: + return BlockColor.SAND_BLOCK_COLOR; + case SMOOTH_RED_SANDSTONE: + return BlockColor.ORANGE_BLOCK_COLOR; + default: + case POLISHED_ANDESITE: + case ANDESITE: + return BlockColor.STONE_BLOCK_COLOR; + case DIORITE: + case POLISHED_DIORITE: + return BlockColor.QUARTZ_BLOCK_COLOR; + case GRANITE: + case POLISHED_GRANITE: + return BlockColor.DIRT_BLOCK_COLOR; + } + } + + @Override + public Item toItem() { + int damage = this.getDamage() & 0x07; + return new ItemBlock(Block.get(this.getId(), damage), damage); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabStone4.java b/src/main/java/cn/nukkit/block/BlockSlabStone4.java new file mode 100644 index 00000000000..1e0e11ace9c --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabStone4.java @@ -0,0 +1,64 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.utils.BlockColor; + +public class BlockSlabStone4 extends BlockSlabStone { + + public static final int MOSSY_STONE_BRICKS = 0; + public static final int SMOOTH_QUARTZ = 1; + public static final int STONE = 2; + public static final int CUT_SANDSTONE = 3; + public static final int CUT_RED_SANDSTONE = 4; + + private static final String[] NAMES = { + "Mossy Stone Brick", + "Smooth Quartz", + "Stone", + "Cut Sandstone", + "Cut Red Sandstone" + }; + + public BlockSlabStone4() { + this(0); + } + + public BlockSlabStone4(int meta) { + super(meta, DOUBLE_STONE_SLAB4); + } + + @Override + public String getName() { + int variant = this.getDamage() & 0x07; + String name = variant >= NAMES.length ? NAMES[0] : NAMES[variant]; + return ((this.getDamage() & 0x08) > 0 ? "Upper " : "") + name + " Slab"; + } + + @Override + public BlockColor getColor() { + switch (this.getDamage() & 0x07) { + default: + case MOSSY_STONE_BRICKS: + case STONE: + return BlockColor.STONE_BLOCK_COLOR; + case SMOOTH_QUARTZ: + return BlockColor.QUARTZ_BLOCK_COLOR; + case CUT_SANDSTONE: + return BlockColor.SAND_BLOCK_COLOR; + case CUT_RED_SANDSTONE: + return BlockColor.ORANGE_BLOCK_COLOR; + } + } + + @Override + public int getId() { + return STONE_SLAB4; + } + + @Override + public Item toItem() { + int damage = this.getDamage() & 0x07; + return new ItemBlock(Block.get(this.getId(), damage), damage); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabTileDeepslate.java b/src/main/java/cn/nukkit/block/BlockSlabTileDeepslate.java new file mode 100644 index 00000000000..90a8d911626 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabTileDeepslate.java @@ -0,0 +1,55 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockSlabTileDeepslate extends BlockSlab { + + public BlockSlabTileDeepslate() { + this(0); + } + + public BlockSlabTileDeepslate(int meta) { + super(meta, DEEPSLATE_TILE_SLAB); + } + + @Override + public int getId() { + return DEEPSLATE_TILE_SLAB; + } + + @Override + public String getSlabName() { + return "Deepslate Tile"; + } + + @Override + public double getHardness() { + return 3.5; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_WOODEN; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabWarped.java b/src/main/java/cn/nukkit/block/BlockSlabWarped.java new file mode 100644 index 00000000000..5b2f07ab7af --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSlabWarped.java @@ -0,0 +1,62 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockSlabWarped extends BlockSlab { + + public BlockSlabWarped() { + this(0); + } + + public BlockSlabWarped(int meta) { + super(meta, WARPED_DOUBLE_SLAB); + } + + @Override + public String getSlabName() { + return "Warped"; + } + + @Override + public int getId() { + return WARPED_SLAB; + } + + @Override + public boolean hasTopBit() { + return (this.getDamage() & 0x01) == 1; + } + + @Override + public void setTopBit(boolean topBit) { + this.setDamage(topBit ? 1 : 0); + } + + @Override + public int getToolType() { + return ItemTool.TYPE_AXE; + } + + @Override + public Item[] getDrops(Item item) { + return new Item[]{ this.toItem() }; + } + + @Override + public double getResistance() { + return 3; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public BlockColor getColor() { + return BlockColor.CYAN_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSlabWood.java b/src/main/java/cn/nukkit/block/BlockSlabWood.java index 6f9b968e7be..374275411fc 100644 --- a/src/main/java/cn/nukkit/block/BlockSlabWood.java +++ b/src/main/java/cn/nukkit/block/BlockSlabWood.java @@ -19,19 +19,20 @@ public BlockSlabWood(int meta) { super(meta, DOUBLE_WOODEN_SLAB); } + private static final String[] NAMES = { + "Oak", + "Spruce", + "Birch", + "Jungle", + "Acacia", + "Dark Oak", + "", + "" + }; + @Override public String getName() { - String[] names = new String[]{ - "Oak", - "Spruce", - "Birch", - "Jungle", - "Acacia", - "Dark Oak", - "", - "" - }; - return (((this.getDamage() & 0x08) == 0x08) ? "Upper " : "") + names[this.getDamage() & 0x07] + " Wooden Slab"; + return (((this.getDamage() & 0x08) == 0x08) ? "Upper " : "") + NAMES[this.getDamage() & 0x07] + " Slab"; } @Override @@ -63,12 +64,13 @@ public Item[] getDrops(Item item) { @Override public Item toItem() { - return new ItemBlock(this, this.getDamage() & 0x07); + int damage = this.getDamage() & 0x07; + return new ItemBlock(Block.get(this.getId(), damage), damage); } @Override public BlockColor getColor() { - switch(getDamage() & 0x07){ + switch (getDamage() & 0x07) { default: case 0: //OAK return BlockColor.WOOD_BLOCK_COLOR; diff --git a/src/main/java/cn/nukkit/block/BlockSlime.java b/src/main/java/cn/nukkit/block/BlockSlime.java index 7b54d72c551..19ea184995c 100644 --- a/src/main/java/cn/nukkit/block/BlockSlime.java +++ b/src/main/java/cn/nukkit/block/BlockSlime.java @@ -7,9 +7,6 @@ */ public class BlockSlime extends BlockSolid { - public BlockSlime() { - } - @Override public double getHardness() { return 0; @@ -32,6 +29,6 @@ public double getResistance() { @Override public BlockColor getColor() { - return BlockColor.GRASS_BLOCK_COLOR; + return BlockColor.GREEN_BLOCK_COLOR; } } diff --git a/src/main/java/cn/nukkit/block/BlockSmithingTable.java b/src/main/java/cn/nukkit/block/BlockSmithingTable.java new file mode 100644 index 00000000000..582f0fc052f --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSmithingTable.java @@ -0,0 +1,60 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.inventory.SmithingInventory; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockSmithingTable extends BlockSolid { + + @Override + public String getName() { + return "Smithing Table"; + } + + @Override + public int getId() { + return SMITHING_TABLE; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_AXE; + } + + @Override + public double getResistance() { + return 12.5; + } + + @Override + public double getHardness() { + return 2.5; + } + + @Override + public BlockColor getColor() { + return BlockColor.WOOD_BLOCK_COLOR; + } + + @Override + public int getBurnChance() { + return 5; + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (player == null) { + return false; + } + + player.addWindow(new SmithingInventory(player.getUIInventory(), this), Player.SMITHING_WINDOW_ID); + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSmoker.java b/src/main/java/cn/nukkit/block/BlockSmoker.java new file mode 100644 index 00000000000..d99c5f94e60 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSmoker.java @@ -0,0 +1,27 @@ +package cn.nukkit.block; + +public class BlockSmoker extends BlockSmokerLit { + + public BlockSmoker() { + this(0); + } + + public BlockSmoker(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Smoker"; + } + + @Override + public int getId() { + return SMOKER; + } + + @Override + public int getLightLevel() { + return 0; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSmokerLit.java b/src/main/java/cn/nukkit/block/BlockSmokerLit.java new file mode 100644 index 00000000000..aad7f8d08bc --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSmokerLit.java @@ -0,0 +1,87 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.blockentity.BlockEntity; +import cn.nukkit.blockentity.BlockEntitySmoker; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.math.BlockFace; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.ListTag; +import cn.nukkit.nbt.tag.StringTag; +import cn.nukkit.nbt.tag.Tag; + +import java.util.Map; + +public class BlockSmokerLit extends BlockFurnaceBurning { + + public BlockSmokerLit() { + this(0); + } + + public BlockSmokerLit(int meta) { + super(meta); + } + + @Override + public int getId() { + return LIT_SMOKER; + } + + @Override + public String getName() { + return "Lit Smoker"; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(SMOKER)); + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + this.setDamage(Block.FACES2534[player != null ? player.getDirection().getHorizontalIndex() : 0]); + this.getLevel().setBlock(block, this, true, true); + CompoundTag nbt = new CompoundTag() + .putList(new ListTag<>("Items")) + .putString("id", BlockEntity.SMOKER) + .putInt("x", (int) this.x) + .putInt("y", (int) this.y) + .putInt("z", (int) this.z); + + if (item.hasCustomName()) { + nbt.putString("CustomName", item.getCustomName()); + } + + if (item.hasCustomBlockData()) { + Map customData = item.getCustomBlockData().getTags(); + for (Map.Entry tag : customData.entrySet()) { + nbt.put(tag.getKey(), tag.getValue()); + } + } + + BlockEntitySmoker smoker = (BlockEntitySmoker) BlockEntity.createBlockEntity(BlockEntity.SMOKER, this.getChunk(), nbt); + return smoker != null; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (player != null) { + BlockEntity t = this.getLevel().getBlockEntity(this); + if (!(t instanceof BlockEntitySmoker)) { + return false; + } + + BlockEntitySmoker smoker = (BlockEntitySmoker) t; + if (smoker.namedTag.contains("Lock") && smoker.namedTag.get("Lock") instanceof StringTag) { + if (!smoker.namedTag.getString("Lock").equals(item.getCustomName())) { + return true; + } + } + + player.addWindow(smoker.getInventory()); + } + + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSmoothStone.java b/src/main/java/cn/nukkit/block/BlockSmoothStone.java new file mode 100644 index 00000000000..b5d2db45a6b --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSmoothStone.java @@ -0,0 +1,36 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; + +public class BlockSmoothStone extends BlockSolid { + + @Override + public String getName() { + return "Smooth Stone"; + } + + @Override + public int getId() { + return SMOOTH_STONE; + } + + @Override + public double getHardness() { + return 2; + } + + @Override + public double getResistance() { + return 10; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSnow.java b/src/main/java/cn/nukkit/block/BlockSnow.java index 2ca14c92264..d452aee3dbc 100644 --- a/src/main/java/cn/nukkit/block/BlockSnow.java +++ b/src/main/java/cn/nukkit/block/BlockSnow.java @@ -2,15 +2,12 @@ import cn.nukkit.Player; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemSnowball; import cn.nukkit.item.ItemTool; +import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.utils.BlockColor; public class BlockSnow extends BlockSolid { - public BlockSnow() { - } - @Override public String getName() { return "Snow"; @@ -26,11 +23,6 @@ public double getHardness() { return 0.2; } - @Override - public double getResistance() { - return 1; - } - @Override public int getToolType() { return ItemTool.TYPE_SHOVEL; @@ -39,8 +31,11 @@ public int getToolType() { @Override public Item[] getDrops(Item item) { if (item.isShovel() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; + } return new Item[]{ - new ItemSnowball(0, 4) + Item.get(Item.SNOWBALL, 0, 4) }; } else { return new Item[0]; @@ -57,7 +52,7 @@ public BlockColor getColor() { public boolean canHarvestWithHand() { return false; } - + @Override public boolean canSilkTouch() { return true; @@ -70,11 +65,16 @@ public boolean canBeActivated() { @Override public boolean onActivate(Item item, Player player) { - if (item.isShovel()) { + if (item.isShovel() && (player == null || (player.gamemode & 0x2) == 0)) { item.useOn(this); this.level.useBreakOn(this, item.clone().clearNamedTag(), null, true); return true; } return false; } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockSnowLayer.java b/src/main/java/cn/nukkit/block/BlockSnowLayer.java index 6c9b959a492..d773e6d3547 100644 --- a/src/main/java/cn/nukkit/block/BlockSnowLayer.java +++ b/src/main/java/cn/nukkit/block/BlockSnowLayer.java @@ -3,7 +3,6 @@ import cn.nukkit.Player; import cn.nukkit.event.block.BlockFadeEvent; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemSnowball; import cn.nukkit.item.ItemTool; import cn.nukkit.level.GameRule; import cn.nukkit.level.Level; @@ -14,31 +13,14 @@ * Created on 2015/12/6 by xtypr. * Package cn.nukkit.block in project Nukkit . */ -public class BlockSnowLayer extends BlockFallable { - - private int meta; +public class BlockSnowLayer extends BlockFallableMeta { public BlockSnowLayer() { this(0); } public BlockSnowLayer(int meta) { - this.meta = meta; - } - - @Override - public final int getFullId() { - return (this.getId() << 4) + this.getDamage(); - } - - @Override - public final int getDamage() { - return this.meta; - } - - @Override - public final void setDamage(int meta) { - this.meta = meta; + super(meta); } @Override @@ -71,6 +53,11 @@ public boolean canBeReplaced() { return (this.getDamage() & 0x7) != 0x7; } + @Override + public boolean canPassThrough() { + return (this.getDamage() & 0x7) < 3; + } + @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { if (this.canSurvive()) { @@ -114,12 +101,12 @@ public int onUpdate(int type) { @Override public Item toItem() { - return new ItemSnowball(); + return Item.get(Item.SNOWBALL); } @Override public Item[] getDrops(Item item) { - if (item.isShovel() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isShovel()) { Item drop = this.toItem(); int height = this.getDamage() & 0x7; drop.setCount(height < 3 ? 1 : height < 5 ? 2 : height == 7 ? 4 : 3); @@ -134,11 +121,6 @@ public BlockColor getColor() { return BlockColor.SNOW_BLOCK_COLOR; } - @Override - public boolean canHarvestWithHand() { - return false; - } - @Override public boolean isTransparent() { return (this.getDamage() & 0x7) != 0x7; @@ -167,11 +149,11 @@ public boolean canBeActivated() { @Override public boolean onActivate(Item item, Player player) { - if (item.isShovel() && (player.gamemode & 0x2) == 0) { + if (item.isShovel() && (player == null || (player.gamemode & 0x2) == 0)) { item.useOn(this); this.level.useBreakOn(this, item.clone().clearNamedTag(), null, true); return true; - } else if (item.getId() == SNOW_LAYER && (player.gamemode & 0x2) == 0) { + } else if (item.getId() == SNOW_LAYER && (player == null || (player.gamemode & 0x2) == 0)) { if ((this.getDamage() & 0x7) != 0x7) { this.setDamage(this.getDamage() + 1); this.level.setBlock(this ,this, true); @@ -188,7 +170,7 @@ public boolean onActivate(Item item, Player player) { } @Override - public boolean canPassThrough() { - return (this.getDamage() & 0x7) < 3; + public boolean breakWhenPushed() { + return true; } } diff --git a/src/main/java/cn/nukkit/block/BlockSolid.java b/src/main/java/cn/nukkit/block/BlockSolid.java index d472699f769..889be6f58cb 100644 --- a/src/main/java/cn/nukkit/block/BlockSolid.java +++ b/src/main/java/cn/nukkit/block/BlockSolid.java @@ -3,7 +3,7 @@ import cn.nukkit.utils.BlockColor; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class BlockSolid extends Block { @@ -11,11 +11,6 @@ public abstract class BlockSolid extends Block { protected BlockSolid() { } - @Override - public boolean isSolid() { - return true; - } - @Override public BlockColor getColor() { return BlockColor.STONE_BLOCK_COLOR; diff --git a/src/main/java/cn/nukkit/block/BlockSolidMeta.java b/src/main/java/cn/nukkit/block/BlockSolidMeta.java index 463f797a9cd..f650f403bd3 100644 --- a/src/main/java/cn/nukkit/block/BlockSolidMeta.java +++ b/src/main/java/cn/nukkit/block/BlockSolidMeta.java @@ -3,15 +3,11 @@ import cn.nukkit.utils.BlockColor; public abstract class BlockSolidMeta extends BlockMeta { + protected BlockSolidMeta(int meta) { super(meta); } - @Override - public boolean isSolid() { - return true; - } - @Override public BlockColor getColor() { return BlockColor.STONE_BLOCK_COLOR; diff --git a/src/main/java/cn/nukkit/block/BlockSoulFire.java b/src/main/java/cn/nukkit/block/BlockSoulFire.java new file mode 100644 index 00000000000..bf70df73c0f --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSoulFire.java @@ -0,0 +1,42 @@ +package cn.nukkit.block; + +import cn.nukkit.level.Level; +import cn.nukkit.utils.BlockColor; + +public class BlockSoulFire extends BlockFire { + + public BlockSoulFire() { + this(0); + } + + public BlockSoulFire(int meta) { + super(meta); + } + + @Override + public int getId() { + return SOUL_FIRE; + } + + @Override + public String getName() { + return "Soul Fire"; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + int downId = down().getId(); + if (downId != Block.SOUL_SAND && downId != Block.SOUL_SOIL) { + this.getLevel().setBlock(this, Block.get(Block.FIRE, this.getDamage())); + } + return type; + } + return 0; + } + + @Override + public BlockColor getColor() { + return BlockColor.LIGHT_BLUE_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSoulLantern.java b/src/main/java/cn/nukkit/block/BlockSoulLantern.java new file mode 100644 index 00000000000..6fe086d8494 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSoulLantern.java @@ -0,0 +1,35 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; + +public class BlockSoulLantern extends BlockLantern { + + public BlockSoulLantern() { + this(0); + } + + public BlockSoulLantern(int meta) { + super(meta); + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(SOUL_LANTERN)); + } + + @Override + public int getId() { + return SOUL_LANTERN; + } + + @Override + public String getName() { + return "Soul Lantern"; + } + + @Override + public int getLightLevel() { + return 10; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSoulSand.java b/src/main/java/cn/nukkit/block/BlockSoulSand.java index e4dbd455cb0..e9407c86099 100644 --- a/src/main/java/cn/nukkit/block/BlockSoulSand.java +++ b/src/main/java/cn/nukkit/block/BlockSoulSand.java @@ -1,7 +1,10 @@ package cn.nukkit.block; +import cn.nukkit.Server; import cn.nukkit.entity.Entity; +import cn.nukkit.event.block.BlockFormEvent; import cn.nukkit.item.ItemTool; +import cn.nukkit.level.Level; import cn.nukkit.utils.BlockColor; /** @@ -9,9 +12,6 @@ */ public class BlockSoulSand extends BlockSolid { - public BlockSoulSand() { - } - @Override public String getName() { return "Soul Sand"; @@ -29,7 +29,7 @@ public double getHardness() { @Override public double getResistance() { - return 2.5; + return 0.5; } @Override @@ -39,7 +39,7 @@ public int getToolType() { @Override public double getMaxY() { - return this.y + 1 - 0.125; + return this.y + 0.875; } @Override @@ -58,4 +58,20 @@ public BlockColor getColor() { return BlockColor.BROWN_BLOCK_COLOR; } + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + Block up = this.up(); + if (up instanceof BlockWater && (up.getDamage() == 0 || up.getDamage() == 8)) { + BlockFormEvent event = new BlockFormEvent(up, Block.get(BUBBLE_COLUMN, BlockBubbleColumn.DIRECTION_UP)); + Server.getInstance().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + this.getLevel().setBlock(up, event.getNewState(), false, true); + } + } + } + + return 0; + } } diff --git a/src/main/java/cn/nukkit/block/BlockSoulSoil.java b/src/main/java/cn/nukkit/block/BlockSoulSoil.java new file mode 100644 index 00000000000..3ef745a54f1 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSoulSoil.java @@ -0,0 +1,53 @@ +package cn.nukkit.block; + +import cn.nukkit.entity.Entity; +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockSoulSoil extends BlockSolid { + + public BlockSoulSoil() { + super(); + } + + @Override + public int getId() { + return SOUL_SOIL; + } + + @Override + public String getName() { + return "Soul Soil"; + } + + @Override + public double getHardness() { + return 0.5; + } + + @Override + public double getResistance() { + return 0.5; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_SHOVEL; + } + + @Override + public boolean hasEntityCollision() { + return true; + } + + @Override + public void onEntityCollide(Entity entity) { + entity.motionX *= 0.4d; + entity.motionZ *= 0.4d; + } + + @Override + public BlockColor getColor() { + return BlockColor.BROWN_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSoulTorch.java b/src/main/java/cn/nukkit/block/BlockSoulTorch.java new file mode 100644 index 00000000000..fdeb4243312 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSoulTorch.java @@ -0,0 +1,27 @@ +package cn.nukkit.block; + +public class BlockSoulTorch extends BlockTorch { + + public BlockSoulTorch() { + this(0); + } + + public BlockSoulTorch(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Soul Torch"; + } + + @Override + public int getId() { + return SOUL_TORCH; + } + + @Override + public int getLightLevel() { + return 10; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSponge.java b/src/main/java/cn/nukkit/block/BlockSponge.java index db77752a515..331b60d6066 100644 --- a/src/main/java/cn/nukkit/block/BlockSponge.java +++ b/src/main/java/cn/nukkit/block/BlockSponge.java @@ -3,26 +3,27 @@ import cn.nukkit.Player; import cn.nukkit.item.Item; import cn.nukkit.item.ItemTool; -import cn.nukkit.level.GlobalBlockPalette; import cn.nukkit.level.Level; -import cn.nukkit.level.particle.SmokeParticle; +import cn.nukkit.level.particle.DestroyBlockParticle; +import cn.nukkit.level.particle.ExplodeParticle; import cn.nukkit.math.BlockFace; -import cn.nukkit.network.protocol.LevelEventPacket; +import cn.nukkit.network.protocol.LevelSoundEventPacket; import cn.nukkit.utils.BlockColor; import java.util.ArrayDeque; +import java.util.Map; import java.util.Queue; -import java.util.concurrent.ThreadLocalRandom; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class BlockSponge extends BlockSolidMeta { public static final int DRY = 0; public static final int WET = 1; - private static final String[] NAMES = new String[]{ + + private static final String[] NAMES = { "Sponge", "Wet sponge" }; @@ -50,11 +51,6 @@ public double getResistance() { return 3; } - @Override - public int getToolType() { - return ItemTool.TYPE_HOE; - } - @Override public String getName() { return NAMES[this.getDamage() & 0b1]; @@ -62,33 +58,26 @@ public String getName() { @Override public BlockColor getColor() { - return BlockColor.YELLOW_BLOCK_COLOR; + return BlockColor.CLOTH_BLOCK_COLOR; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_HOE; } @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { if (this.getDamage() == WET && level.getDimension() == Level.DIMENSION_NETHER) { level.setBlock(block, Block.get(BlockID.SPONGE, DRY), true, true); - this.getLevel().addLevelEvent(block.add(0.5, 0.875, 0.5), LevelEventPacket.EVENT_SOUND_EXPLODE); - - for (int i = 0; i < 8; ++i) { - level.addParticle(new SmokeParticle(block.getLocation().add(ThreadLocalRandom.current().nextDouble(), 1, ThreadLocalRandom.current().nextDouble()))); - } - + level.addLevelSoundEvent(block, LevelSoundEventPacket.SOUND_FIZZ); + level.addParticle(new ExplodeParticle(block.add(0.5, 1, 0.5))); return true; - } else if (this.getDamage() == DRY && block instanceof BlockWater && performWaterAbsorb(block)) { + } else if (this.getDamage() == DRY && performWaterAbsorb(block)) { level.setBlock(block, Block.get(BlockID.SPONGE, WET), true, true); - for (int i = 0; i < 4; i++) { - LevelEventPacket packet = new LevelEventPacket(); - packet.evid = LevelEventPacket.EVENT_PARTICLE_DESTROY; - packet.x = (float) block.getX() + 0.5f; - packet.y = (float) block.getY() + 1f; - packet.z = (float) block.getZ() + 0.5f; - packet.data = GlobalBlockPalette.getOrCreateRuntimeId(BlockID.WATER, 0); - level.addChunkPacket(getChunkX(), getChunkZ(), packet); - } - + Map players = this.level.getChunkPlayers(block.getChunkX(), block.getChunkZ()); + level.addParticle(new DestroyBlockParticle(block.add(0.5, 0.5, 0.5), Block.get(BlockID.WATER)), players.values().toArray(new Player[0])); return true; } @@ -96,6 +85,17 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl } private boolean performWaterAbsorb(Block block) { + boolean waterFound = false; + for (BlockFace side : BlockFace.values()) { + if (getSide(side) instanceof BlockWater) { + waterFound = true; + break; + } + } + if (!waterFound) { + return false; + } + Queue entries = new ArrayDeque<>(); entries.add(new Entry(block, 0)); @@ -106,7 +106,7 @@ private boolean performWaterAbsorb(Block block) { for (BlockFace face : BlockFace.values()) { Block faceBlock = entry.block.getSide(face); - if (faceBlock.getId() == BlockID.WATER || faceBlock.getId() == BlockID.STILL_WATER) { + if (Block.isWater(faceBlock.getId())) { this.level.setBlock(faceBlock, Block.get(BlockID.AIR)); ++waterRemoved; if (entry.distance < 6) { diff --git a/src/main/java/cn/nukkit/block/BlockSporeBlossom.java b/src/main/java/cn/nukkit/block/BlockSporeBlossom.java new file mode 100644 index 00000000000..c602bac4b27 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSporeBlossom.java @@ -0,0 +1,75 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; + +public class BlockSporeBlossom extends BlockTransparent { + + public BlockSporeBlossom() { + } + + @Override + public int getId() { + return SPORE_BLOSSOM; + } + + @Override + public String getName() { + return "Spore Blossom"; + } + + @Override + public double getResistance() { + return 0; + } + + @Override + public double getHardness() { + return 0; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (Block.canConnectToFullSolid(this.up())) { + return super.place(item, block, target, face, fx, fy, fz, player); + } + return false; + } + + @Override + public double getMinX() { + return this.x + 2D / 16D; + } + + @Override + public double getMinY() { + return this.y + 13D / 16D; + } + + @Override + public double getMinZ() { + return this.z + 2D / 16D; + } + + @Override + public double getMaxX() { + return this.x + 14D / 16D; + } + + @Override + public double getMaxZ() { + return this.z + 14D / 16D; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_SCHEDULED) { + this.getLevel().useBreakOn(this, null, null, true); + } else if (type == Level.BLOCK_UPDATE_NORMAL && !Block.canConnectToFullSolid(this.up())) { + this.getLevel().scheduleUpdate(this, 1); + } + return type; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSpruceSignStanding.java b/src/main/java/cn/nukkit/block/BlockSpruceSignStanding.java new file mode 100644 index 00000000000..df26ce756ca --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSpruceSignStanding.java @@ -0,0 +1,40 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; + +public class BlockSpruceSignStanding extends BlockSignPost { + + public BlockSpruceSignStanding() { + this(0); + } + + public BlockSpruceSignStanding(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Spruce Sign Post"; + } + + @Override + public int getId() { + return SPRUCE_STANDING_SIGN; + } + + @Override + public Item toItem() { + return Item.get(ItemID.SPRUCE_SIGN); + } + + @Override + protected int getPostId() { + return SPRUCE_STANDING_SIGN; + } + + @Override + protected int getWallId() { + return SPRUCE_WALL_SIGN; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSpruceWallSign.java b/src/main/java/cn/nukkit/block/BlockSpruceWallSign.java new file mode 100644 index 00000000000..c6f2674b3e8 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSpruceWallSign.java @@ -0,0 +1,40 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; + +public class BlockSpruceWallSign extends BlockWallSign { + + public BlockSpruceWallSign() { + this(0); + } + + public BlockSpruceWallSign(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Spruce Wall Sign"; + } + + @Override + public int getId() { + return SPRUCE_WALL_SIGN; + } + + @Override + public Item toItem() { + return Item.get(ItemID.SPRUCE_SIGN); + } + + @Override + protected int getPostId() { + return SPRUCE_STANDING_SIGN; + } + + @Override + protected int getWallId() { + return SPRUCE_WALL_SIGN; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairs.java b/src/main/java/cn/nukkit/block/BlockStairs.java index 135cc49704c..16739e52034 100644 --- a/src/main/java/cn/nukkit/block/BlockStairs.java +++ b/src/main/java/cn/nukkit/block/BlockStairs.java @@ -2,17 +2,19 @@ import cn.nukkit.Player; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemTool; +import cn.nukkit.item.ItemBlock; import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.math.BlockFace; import cn.nukkit.math.SimpleAxisAlignedBB; import cn.nukkit.utils.Faceable; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ -public abstract class BlockStairs extends BlockTransparentMeta implements Faceable { +public abstract class BlockStairs extends BlockSolidMeta implements Faceable { + + private static final short[] FACES = {2, 1, 3, 0}; protected BlockStairs(int meta) { super(meta); @@ -21,32 +23,31 @@ protected BlockStairs(int meta) { @Override public double getMinY() { // TODO: this seems wrong - return this.y + ((getDamage() & 0x04) > 0 ? 0.5 : 0); + return this.y + (this.getDamage() & 0x04) > 0 ? 0.5 : 0; } @Override public double getMaxY() { // TODO: this seems wrong - return this.y + ((getDamage() & 0x04) > 0 ? 1 : 0.5); + return this.y + (this.getDamage() & 0x04) > 0 ? 1 : 0.5; } + @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - int[] faces = new int[]{2, 1, 3, 0}; - this.setDamage(faces[player != null ? player.getDirection().getHorizontalIndex() : 0]); + this.setDamage(FACES[player != null ? player.getDirection().getHorizontalIndex() : 0]); if ((fy > 0.5 && face != BlockFace.UP) || face == BlockFace.DOWN) { this.setDamage(this.getDamage() | 0x04); //Upside-down stairs } - this.getLevel().setBlock(block, this, true, true); - + this.getLevel().setBlock(this, this, true, true); return true; } @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ - toItem() + toItem() }; } else { return new Item[0]; @@ -55,9 +56,7 @@ public Item[] getDrops(Item item) { @Override public Item toItem() { - Item item = super.toItem(); - item.setDamage(0); - return item; + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override @@ -88,49 +87,41 @@ public boolean collidesWithBB(AxisAlignedBB bb) { if (side == 0) { - if (bb.intersectsWith(new SimpleAxisAlignedBB( + return bb.intersectsWith(new SimpleAxisAlignedBB( this.x + 0.5, this.y + f2, this.z, this.x + 1, this.y + f3, this.z + 1 - ))) { - return true; - } + )); } else if (side == 1) { - if (bb.intersectsWith(new SimpleAxisAlignedBB( + return bb.intersectsWith(new SimpleAxisAlignedBB( this.x, this.y + f2, this.z, this.x + 0.5, this.y + f3, this.z + 1 - ))) { - return true; - } + )); } else if (side == 2) { - if (bb.intersectsWith(new SimpleAxisAlignedBB( + return bb.intersectsWith(new SimpleAxisAlignedBB( this.x, this.y + f2, this.z + 0.5, this.x + 1, this.y + f3, this.z + 1 - ))) { - return true; - } + )); } else if (side == 3) { - if (bb.intersectsWith(new SimpleAxisAlignedBB( + return bb.intersectsWith(new SimpleAxisAlignedBB( this.x, this.y + f2, this.z, this.x + 1, this.y + f3, this.z + 0.5 - ))) { - return true; - } + )); } return false; @@ -140,4 +131,9 @@ public boolean collidesWithBB(AxisAlignedBB bb) { public BlockFace getBlockFace() { return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } } diff --git a/src/main/java/cn/nukkit/block/BlockStairsAcacia.java b/src/main/java/cn/nukkit/block/BlockStairsAcacia.java index cd9481407d7..0c9a950a771 100644 --- a/src/main/java/cn/nukkit/block/BlockStairsAcacia.java +++ b/src/main/java/cn/nukkit/block/BlockStairsAcacia.java @@ -3,7 +3,7 @@ import cn.nukkit.utils.BlockColor; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockStairsAcacia extends BlockStairsWood { @@ -23,12 +23,11 @@ public int getId() { @Override public String getName() { - return "Acacia Wood Stairs"; + return "Acacia Stairs"; } @Override public BlockColor getColor() { return BlockColor.ORANGE_BLOCK_COLOR; } - } diff --git a/src/main/java/cn/nukkit/block/BlockStairsAndesite.java b/src/main/java/cn/nukkit/block/BlockStairsAndesite.java new file mode 100644 index 00000000000..cd52f6a49fe --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsAndesite.java @@ -0,0 +1,44 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; + +public class BlockStairsAndesite extends BlockStairs { + + public BlockStairsAndesite() { + this(0); + } + + public BlockStairsAndesite(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Andesite Stairs"; + } + + @Override + public int getId() { + return ANDESITE_STAIRS; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public double getHardness() { + return 1.5; + } + + @Override + public double getResistance() { + return 30; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsAndesitePolished.java b/src/main/java/cn/nukkit/block/BlockStairsAndesitePolished.java new file mode 100644 index 00000000000..a43c5f32b82 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsAndesitePolished.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockStairsAndesitePolished extends BlockStairsAndesite { + + public BlockStairsAndesitePolished() { + this(0); + } + + public BlockStairsAndesitePolished(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Polished Andesite Stairs"; + } + + @Override + public int getId() { + return POLISHED_ANDESITE_STAIRS; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsBirch.java b/src/main/java/cn/nukkit/block/BlockStairsBirch.java index fd3b0cb7f4a..05d9181ba05 100644 --- a/src/main/java/cn/nukkit/block/BlockStairsBirch.java +++ b/src/main/java/cn/nukkit/block/BlockStairsBirch.java @@ -23,12 +23,11 @@ public int getId() { @Override public String getName() { - return "Birch Wood Stairs"; + return "Birch Stairs"; } @Override public BlockColor getColor() { return BlockColor.SAND_BLOCK_COLOR; } - } diff --git a/src/main/java/cn/nukkit/block/BlockStairsBlackstone.java b/src/main/java/cn/nukkit/block/BlockStairsBlackstone.java new file mode 100644 index 00000000000..dbde24a74d3 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsBlackstone.java @@ -0,0 +1,50 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockStairsBlackstone extends BlockStairs { + + public BlockStairsBlackstone() { + this(0); + } + + public BlockStairsBlackstone(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Blackstone Stairs"; + } + + @Override + public int getId() { + return BLACKSTONE_STAIRS; + } + + @Override + public BlockColor getColor() { + return BlockColor.BLACK_BLOCK_COLOR; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public double getHardness() { + return 1.5; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsBlackstonePolished.java b/src/main/java/cn/nukkit/block/BlockStairsBlackstonePolished.java new file mode 100644 index 00000000000..52e703f6cdf --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsBlackstonePolished.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockStairsBlackstonePolished extends BlockStairsBlackstone { + + public BlockStairsBlackstonePolished() { + this(0); + } + + public BlockStairsBlackstonePolished(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Polished Blackstone Stairs"; + } + + @Override + public int getId() { + return POLISHED_BLACKSTONE_STAIRS; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsBrick.java b/src/main/java/cn/nukkit/block/BlockStairsBrick.java index a6ba171bc8e..d73f6de546c 100644 --- a/src/main/java/cn/nukkit/block/BlockStairsBrick.java +++ b/src/main/java/cn/nukkit/block/BlockStairsBrick.java @@ -8,6 +8,7 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockStairsBrick extends BlockStairs { + public BlockStairsBrick() { this(0); } @@ -42,12 +43,12 @@ public String getName() { } @Override - public BlockColor getColor() { - return BlockColor.RED_BLOCK_COLOR; + public boolean canHarvestWithHand() { + return false; } @Override - public boolean canHarvestWithHand() { - return false; + public BlockColor getColor() { + return BlockColor.RED_BLOCK_COLOR; } } diff --git a/src/main/java/cn/nukkit/block/BlockStairsBrickBlackstonePolished.java b/src/main/java/cn/nukkit/block/BlockStairsBrickBlackstonePolished.java new file mode 100644 index 00000000000..b55bbee1656 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsBrickBlackstonePolished.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockStairsBrickBlackstonePolished extends BlockStairsBlackstonePolished { + + public BlockStairsBrickBlackstonePolished() { + this(0); + } + + public BlockStairsBrickBlackstonePolished(int meta) { + super(meta); + } + + @Override + public int getId() { + return POLISHED_BLACKSTONE_BRICK_STAIRS; + } + + @Override + public String getName() { + return "Polished Blackstone Brick Stairs"; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsBrickDeepslate.java b/src/main/java/cn/nukkit/block/BlockStairsBrickDeepslate.java new file mode 100644 index 00000000000..80409525579 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsBrickDeepslate.java @@ -0,0 +1,55 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockStairsBrickDeepslate extends BlockStairs { + + public BlockStairsBrickDeepslate() { + this(0); + } + + public BlockStairsBrickDeepslate(int meta) { + super(meta); + } + + @Override + public int getId() { + return DEEPSLATE_BRICK_STAIRS; + } + + @Override + public String getName() { + return "Deepslate Brick Stairs"; + } + + @Override + public double getHardness() { + return 3.5; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_WOODEN; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsCobblestone.java b/src/main/java/cn/nukkit/block/BlockStairsCobblestone.java index 6abff3dd072..1497c3e4682 100644 --- a/src/main/java/cn/nukkit/block/BlockStairsCobblestone.java +++ b/src/main/java/cn/nukkit/block/BlockStairsCobblestone.java @@ -1,13 +1,13 @@ package cn.nukkit.block; import cn.nukkit.item.ItemTool; -import cn.nukkit.utils.BlockColor; /** * Created on 2015/11/25 by xtypr. * Package cn.nukkit.block in project Nukkit . */ public class BlockStairsCobblestone extends BlockStairs { + public BlockStairsCobblestone() { this(0); } @@ -41,11 +41,6 @@ public String getName() { return "Cobblestone Stairs"; } - @Override - public BlockColor getColor() { - return BlockColor.STONE_BLOCK_COLOR; - } - @Override public boolean canHarvestWithHand() { return false; diff --git a/src/main/java/cn/nukkit/block/BlockStairsCopperBase.java b/src/main/java/cn/nukkit/block/BlockStairsCopperBase.java new file mode 100644 index 00000000000..536fe95045d --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsCopperBase.java @@ -0,0 +1,86 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; + +public abstract class BlockStairsCopperBase extends BlockStairs implements Waxable, Oxidizable { + + public BlockStairsCopperBase() { + this(0); + } + + public BlockStairsCopperBase(int meta) { + super(meta); + } + + @Override + public double getHardness() { + return 3; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_STONE; + } + + @Override + public boolean onActivate(Item item, Player player) { + return Waxable.super.onActivate(item, player) + || Oxidizable.super.onActivate(item, player); + } + + @Override + public int onUpdate(int type) { + return Oxidizable.super.onUpdate(type); + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public Block getStateWithOxidizationLevel(OxidizationLevel oxidizationLevel) { + return Block.get(this.getCopperId(this.isWaxed(), oxidizationLevel), this.getDamage()); + } + + @Override + public boolean setOxidizationLevel(OxidizationLevel oxidizationLevel) { + if (this.getOxidizationLevel().equals(oxidizationLevel)) { + return true; + } + return this.level.setBlock(this, Block.get(this.getCopperId(this.isWaxed(), oxidizationLevel))); + } + + @Override + public boolean setWaxed(boolean waxed) { + if (this.isWaxed() == waxed) { + return true; + } + return this.level.setBlock(this, Block.get(getCopperId(waxed, getOxidizationLevel()))); + } + + @Override + public boolean isWaxed() { + return false; + } + + protected abstract int getCopperId(boolean waxed, OxidizationLevel oxidizationLevel); +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsCopperCut.java b/src/main/java/cn/nukkit/block/BlockStairsCopperCut.java new file mode 100644 index 00000000000..ccb8812101c --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsCopperCut.java @@ -0,0 +1,59 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; + +public class BlockStairsCopperCut extends BlockStairsCopperBase { + + public BlockStairsCopperCut() { + this(0); + } + + public BlockStairsCopperCut(int meta) { + super(meta); + } + + @Override + public String getName() { + String name = ""; + if (this.isWaxed()) { + name += "Waxed "; + } + + OxidizationLevel oxidizationLevel = this.getOxidizationLevel(); + if (oxidizationLevel != OxidizationLevel.UNAFFECTED) { + String oxidationName = oxidizationLevel.name(); + name += oxidationName.charAt(0) + oxidationName.substring(1).toLowerCase(); + } + return name + " Cut Copper Stairs"; + } + + @Override + public int getId() { + return CUT_COPPER_STAIRS; + } + + + @Override + protected int getCopperId(boolean waxed, OxidizationLevel oxidizationLevel) { + if (oxidizationLevel == null) { + return this.getId(); + } + switch (oxidizationLevel) { + case UNAFFECTED: + return waxed ? WAXED_CUT_COPPER_STAIRS : CUT_COPPER_STAIRS; + case EXPOSED: + return waxed ? WAXED_EXPOSED_CUT_COPPER_STAIRS : EXPOSED_CUT_COPPER_STAIRS; + case WEATHERED: + return waxed ? WAXED_WEATHERED_CUT_COPPER_STAIRS : WEATHERED_CUT_COPPER_STAIRS; + case OXIDIZED: + return waxed ? WAXED_OXIDIZED_CUT_COPPER_STAIRS : OXIDIZED_CUT_COPPER_STAIRS; + default: + return this.getId(); + } + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.UNAFFECTED; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsCopperCutExposed.java b/src/main/java/cn/nukkit/block/BlockStairsCopperCutExposed.java new file mode 100644 index 00000000000..7cd15258d06 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsCopperCutExposed.java @@ -0,0 +1,30 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.utils.BlockColor; + +public class BlockStairsCopperCutExposed extends BlockStairsCopperCut { + + public BlockStairsCopperCutExposed() { + this(0); + } + + public BlockStairsCopperCutExposed(int meta) { + super(meta); + } + + @Override + public int getId() { + return EXPOSED_CUT_COPPER_STAIRS; + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.EXPOSED; + } + + @Override + public BlockColor getColor() { + return BlockColor.LIGHT_GRAY_TERRACOTA_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsCopperCutExposedWaxed.java b/src/main/java/cn/nukkit/block/BlockStairsCopperCutExposedWaxed.java new file mode 100644 index 00000000000..bce28120047 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsCopperCutExposedWaxed.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockStairsCopperCutExposedWaxed extends BlockStairsCopperCutExposed { + + public BlockStairsCopperCutExposedWaxed() { + this(0); + } + + public BlockStairsCopperCutExposedWaxed(int meta) { + super(meta); + } + + @Override + public int getId() { + return WAXED_EXPOSED_CUT_COPPER_STAIRS; + } + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsCopperCutOxidized.java b/src/main/java/cn/nukkit/block/BlockStairsCopperCutOxidized.java new file mode 100644 index 00000000000..cd6ff03f596 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsCopperCutOxidized.java @@ -0,0 +1,31 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.utils.BlockColor; + +public class BlockStairsCopperCutOxidized extends BlockStairsCopperCut { + + public BlockStairsCopperCutOxidized() { + this(0); + } + + public BlockStairsCopperCutOxidized(int meta) { + super(meta); + } + + @Override + public int getId() { + return OXIDIZED_CUT_COPPER_STAIRS; + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.OXIDIZED; + } + + @Override + public BlockColor getColor() { + return BlockColor.WARPED_NYLIUM_BLOCK_COLOR; + } + +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsCopperCutOxidizedWaxed.java b/src/main/java/cn/nukkit/block/BlockStairsCopperCutOxidizedWaxed.java new file mode 100644 index 00000000000..998288aecc9 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsCopperCutOxidizedWaxed.java @@ -0,0 +1,24 @@ +package cn.nukkit.block; + +public class BlockStairsCopperCutOxidizedWaxed extends BlockStairsCopperCutOxidized { + + public BlockStairsCopperCutOxidizedWaxed() { + this(0); + } + + + public BlockStairsCopperCutOxidizedWaxed(int meta) { + super(meta); + } + + @Override + public int getId() { + return WAXED_OXIDIZED_CUT_COPPER_STAIRS; + } + + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsCopperCutWaxed.java b/src/main/java/cn/nukkit/block/BlockStairsCopperCutWaxed.java new file mode 100644 index 00000000000..78715d789a0 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsCopperCutWaxed.java @@ -0,0 +1,23 @@ +package cn.nukkit.block; + +public class BlockStairsCopperCutWaxed extends BlockStairsCopperCut { + + public BlockStairsCopperCutWaxed() { + this(0); + } + + public BlockStairsCopperCutWaxed(int meta) { + super(meta); + } + + @Override + public int getId() { + return WAXED_CUT_COPPER_STAIRS; + } + + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsCopperCutWeathered.java b/src/main/java/cn/nukkit/block/BlockStairsCopperCutWeathered.java new file mode 100644 index 00000000000..734730109f3 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsCopperCutWeathered.java @@ -0,0 +1,30 @@ +package cn.nukkit.block; + +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.utils.BlockColor; + +public class BlockStairsCopperCutWeathered extends BlockStairsCopperCut { + + public BlockStairsCopperCutWeathered() { + this(0); + } + + public BlockStairsCopperCutWeathered(int meta) { + super(meta); + } + + @Override + public int getId() { + return WEATHERED_CUT_COPPER_STAIRS; + } + + @Override + public OxidizationLevel getOxidizationLevel() { + return OxidizationLevel.WEATHERED; + } + + @Override + public BlockColor getColor() { + return BlockColor.WARPED_STEM_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsCopperCutWeatheredWaxed.java b/src/main/java/cn/nukkit/block/BlockStairsCopperCutWeatheredWaxed.java new file mode 100644 index 00000000000..8077378c085 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsCopperCutWeatheredWaxed.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockStairsCopperCutWeatheredWaxed extends BlockStairsCopperCutWeathered { + + public BlockStairsCopperCutWeatheredWaxed() { + this(0); + } + + public BlockStairsCopperCutWeatheredWaxed(int meta) { + super(meta); + } + + @Override + public int getId() { + return WAXED_WEATHERED_CUT_COPPER_STAIRS; + } + + @Override + public boolean isWaxed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsDarkOak.java b/src/main/java/cn/nukkit/block/BlockStairsDarkOak.java index 9df9077d6cf..da3f92cfc17 100644 --- a/src/main/java/cn/nukkit/block/BlockStairsDarkOak.java +++ b/src/main/java/cn/nukkit/block/BlockStairsDarkOak.java @@ -23,12 +23,11 @@ public int getId() { @Override public String getName() { - return "Dark Oak Wood Stairs"; + return "Dark Oak Stairs"; } @Override public BlockColor getColor() { return BlockColor.BROWN_BLOCK_COLOR; } - } diff --git a/src/main/java/cn/nukkit/block/BlockStairsDarkPrismarine.java b/src/main/java/cn/nukkit/block/BlockStairsDarkPrismarine.java new file mode 100644 index 00000000000..ab5a7b36550 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsDarkPrismarine.java @@ -0,0 +1,50 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockStairsDarkPrismarine extends BlockStairs { + + public BlockStairsDarkPrismarine() { + this(0); + } + + public BlockStairsDarkPrismarine(int meta) { + super(meta); + } + + @Override + public int getId() { + return DARK_PRISMARINE_STAIRS; + } + + @Override + public double getHardness() { + return 0.8; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public String getName() { + return "Dark Prismarine Stairs"; + } + + @Override + public BlockColor getColor() { + return BlockColor.DIAMOND_BLOCK_COLOR; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsDeepslateCobbled.java b/src/main/java/cn/nukkit/block/BlockStairsDeepslateCobbled.java new file mode 100644 index 00000000000..794129dee53 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsDeepslateCobbled.java @@ -0,0 +1,55 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockStairsDeepslateCobbled extends BlockStairs { + + public BlockStairsDeepslateCobbled() { + this(0); + } + + public BlockStairsDeepslateCobbled(int meta) { + super(meta); + } + + @Override + public int getId() { + return COBBLED_DEEPSLATE_STAIRS; + } + + @Override + public String getName() { + return "Cobbled Deepslate Stairs"; + } + + @Override + public double getHardness() { + return 3.5; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_WOODEN; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsDeepslatePolished.java b/src/main/java/cn/nukkit/block/BlockStairsDeepslatePolished.java new file mode 100644 index 00000000000..f1b8dd94989 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsDeepslatePolished.java @@ -0,0 +1,55 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockStairsDeepslatePolished extends BlockStairs { + + public BlockStairsDeepslatePolished() { + this(0); + } + + public BlockStairsDeepslatePolished(int meta) { + super(meta); + } + + @Override + public int getId() { + return POLISHED_DEEPSLATE_STAIRS; + } + + @Override + public String getName() { + return "Polished Deepslate Stairs"; + } + + @Override + public double getHardness() { + return 3.5; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_WOODEN; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsDiorite.java b/src/main/java/cn/nukkit/block/BlockStairsDiorite.java new file mode 100644 index 00000000000..647d9186b61 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsDiorite.java @@ -0,0 +1,50 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockStairsDiorite extends BlockStairs { + + public BlockStairsDiorite() { + this(0); + } + + public BlockStairsDiorite(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Diorite Stairs"; + } + + @Override + public int getId() { + return DIORITE_STAIRS; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public double getHardness() { + return 1.5; + } + + @Override + public double getResistance() { + return 30; + } + + @Override + public BlockColor getColor() { + return BlockColor.QUARTZ_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsDioritePolished.java b/src/main/java/cn/nukkit/block/BlockStairsDioritePolished.java new file mode 100644 index 00000000000..a440fd0429e --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsDioritePolished.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockStairsDioritePolished extends BlockStairsDiorite { + + public BlockStairsDioritePolished() { + this(0); + } + + public BlockStairsDioritePolished(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Polished Diorite Stairs"; + } + + @Override + public int getId() { + return POLISHED_DIORITE_STAIRS; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsEndBrick.java b/src/main/java/cn/nukkit/block/BlockStairsEndBrick.java new file mode 100644 index 00000000000..81f71de42f2 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsEndBrick.java @@ -0,0 +1,44 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; + +public class BlockStairsEndBrick extends BlockStairs { + + public BlockStairsEndBrick() { + this(0); + } + + public BlockStairsEndBrick(int meta) { + super(meta); + } + + @Override + public String getName() { + return "End Brick Stairs"; + } + + @Override + public int getId() { + return END_BRICK_STAIRS; + } + + @Override + public double getHardness() { + return 2; //3 + } + + @Override + public double getResistance() { + return 9; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsGranite.java b/src/main/java/cn/nukkit/block/BlockStairsGranite.java new file mode 100644 index 00000000000..33cdb328ffc --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsGranite.java @@ -0,0 +1,50 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockStairsGranite extends BlockStairs { + + public BlockStairsGranite() { + this(0); + } + + public BlockStairsGranite(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Granite Stairs"; + } + + @Override + public int getId() { + return GRANITE_STAIRS; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public double getHardness() { + return 1.5; + } + + @Override + public double getResistance() { + return 30; + } + + @Override + public BlockColor getColor() { + return BlockColor.DIRT_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsGranitePolished.java b/src/main/java/cn/nukkit/block/BlockStairsGranitePolished.java new file mode 100644 index 00000000000..64d7f6bc12f --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsGranitePolished.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockStairsGranitePolished extends BlockStairsGranite { + + public BlockStairsGranitePolished() { + this(0); + } + + public BlockStairsGranitePolished(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Polished Granite Stairs"; + } + + @Override + public int getId() { + return POLISHED_GRANITE_STAIRS; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsJungle.java b/src/main/java/cn/nukkit/block/BlockStairsJungle.java index 7af5f2b3d9a..987ca37dc7a 100644 --- a/src/main/java/cn/nukkit/block/BlockStairsJungle.java +++ b/src/main/java/cn/nukkit/block/BlockStairsJungle.java @@ -23,12 +23,11 @@ public int getId() { @Override public String getName() { - return "Jungle Wood Stairs"; + return "Jungle Stairs"; } @Override public BlockColor getColor() { return BlockColor.DIRT_BLOCK_COLOR; } - } diff --git a/src/main/java/cn/nukkit/block/BlockStairsMossyCobblestone.java b/src/main/java/cn/nukkit/block/BlockStairsMossyCobblestone.java new file mode 100644 index 00000000000..37515a34892 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsMossyCobblestone.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockStairsMossyCobblestone extends BlockStairsCobblestone { + + public BlockStairsMossyCobblestone() { + this(0); + } + + public BlockStairsMossyCobblestone(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Mossy Cobblestone Stairs"; + } + + @Override + public int getId() { + return MOSSY_COBBLESTONE_STAIRS; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsMossyStoneBrick.java b/src/main/java/cn/nukkit/block/BlockStairsMossyStoneBrick.java new file mode 100644 index 00000000000..b35398ff8a6 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsMossyStoneBrick.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockStairsMossyStoneBrick extends BlockStairsStoneBrick { + + public BlockStairsMossyStoneBrick() { + this(0); + } + + public BlockStairsMossyStoneBrick(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Mossy Stone Brick Stairs"; + } + + @Override + public int getId() { + return MOSSY_STONE_BRICK_STAIRS; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsNetherBrick.java b/src/main/java/cn/nukkit/block/BlockStairsNetherBrick.java index a45d63d204f..f64eae90c38 100644 --- a/src/main/java/cn/nukkit/block/BlockStairsNetherBrick.java +++ b/src/main/java/cn/nukkit/block/BlockStairsNetherBrick.java @@ -8,6 +8,7 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockStairsNetherBrick extends BlockStairs { + public BlockStairsNetherBrick() { this(0); } diff --git a/src/main/java/cn/nukkit/block/BlockStairsPrismarine.java b/src/main/java/cn/nukkit/block/BlockStairsPrismarine.java new file mode 100644 index 00000000000..276ea09ac99 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsPrismarine.java @@ -0,0 +1,50 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockStairsPrismarine extends BlockStairs { + + public BlockStairsPrismarine() { + this(0); + } + + public BlockStairsPrismarine(int meta) { + super(meta); + } + + @Override + public int getId() { + return PRISMARINE_STAIRS; + } + + @Override + public double getHardness() { + return 0.8; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public String getName() { + return "Prismarine Stairs"; + } + + @Override + public BlockColor getColor() { + return BlockColor.CYAN_BLOCK_COLOR; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsPrismarineBrick.java b/src/main/java/cn/nukkit/block/BlockStairsPrismarineBrick.java new file mode 100644 index 00000000000..428937e611a --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsPrismarineBrick.java @@ -0,0 +1,29 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockStairsPrismarineBrick extends BlockStairsPrismarine { + + public BlockStairsPrismarineBrick() { + this(0); + } + + public BlockStairsPrismarineBrick(int meta) { + super(meta); + } + + @Override + public int getId() { + return PRISMARINE_BRICKS_STAIRS; + } + + @Override + public String getName() { + return "Prismarine Brick Stairs"; + } + + @Override + public BlockColor getColor() { + return BlockColor.DIAMOND_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsPurpur.java b/src/main/java/cn/nukkit/block/BlockStairsPurpur.java index 46d4dd53533..d374d5f42b9 100644 --- a/src/main/java/cn/nukkit/block/BlockStairsPurpur.java +++ b/src/main/java/cn/nukkit/block/BlockStairsPurpur.java @@ -42,4 +42,9 @@ public String getName() { public BlockColor getColor() { return BlockColor.MAGENTA_BLOCK_COLOR; } + + @Override + public boolean canHarvestWithHand() { + return false; + } } diff --git a/src/main/java/cn/nukkit/block/BlockStairsQuartz.java b/src/main/java/cn/nukkit/block/BlockStairsQuartz.java index 9482765d3c3..d9aac17c7ef 100644 --- a/src/main/java/cn/nukkit/block/BlockStairsQuartz.java +++ b/src/main/java/cn/nukkit/block/BlockStairsQuartz.java @@ -8,6 +8,7 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockStairsQuartz extends BlockStairs { + public BlockStairsQuartz() { this(0); } @@ -23,12 +24,12 @@ public int getId() { @Override public double getHardness() { - return 0.8; + return 2; } @Override public double getResistance() { - return 4; + return 6; } @Override diff --git a/src/main/java/cn/nukkit/block/BlockStairsRedNetherBrick.java b/src/main/java/cn/nukkit/block/BlockStairsRedNetherBrick.java new file mode 100644 index 00000000000..a7b4f06aed3 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsRedNetherBrick.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockStairsRedNetherBrick extends BlockStairsNetherBrick { + + public BlockStairsRedNetherBrick() { + this(0); + } + + public BlockStairsRedNetherBrick(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Red Nether Brick Stairs"; + } + + @Override + public int getId() { + return RED_NETHER_BRICK_STAIRS; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsRedSandstone.java b/src/main/java/cn/nukkit/block/BlockStairsRedSandstone.java index 9aa25e29e27..0de03be8c2c 100644 --- a/src/main/java/cn/nukkit/block/BlockStairsRedSandstone.java +++ b/src/main/java/cn/nukkit/block/BlockStairsRedSandstone.java @@ -45,7 +45,7 @@ public String getName() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; @@ -68,4 +68,4 @@ public boolean canHarvestWithHand() { public BlockColor getColor() { return BlockColor.ORANGE_BLOCK_COLOR; } -} \ No newline at end of file +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsSandstone.java b/src/main/java/cn/nukkit/block/BlockStairsSandstone.java index 18557d87a85..a3597e02dd2 100644 --- a/src/main/java/cn/nukkit/block/BlockStairsSandstone.java +++ b/src/main/java/cn/nukkit/block/BlockStairsSandstone.java @@ -8,6 +8,7 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockStairsSandstone extends BlockStairs { + public BlockStairsSandstone() { this(0); } diff --git a/src/main/java/cn/nukkit/block/BlockStairsSmoothQuartz.java b/src/main/java/cn/nukkit/block/BlockStairsSmoothQuartz.java new file mode 100644 index 00000000000..66c0564d520 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsSmoothQuartz.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockStairsSmoothQuartz extends BlockStairsQuartz { + + public BlockStairsSmoothQuartz() { + this(0); + } + + public BlockStairsSmoothQuartz(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Smooth Quartz Stairs"; + } + + @Override + public int getId() { + return SMOOTH_QUARTZ_STAIRS; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsSmoothRedSandstone.java b/src/main/java/cn/nukkit/block/BlockStairsSmoothRedSandstone.java new file mode 100644 index 00000000000..9633b01fcdb --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsSmoothRedSandstone.java @@ -0,0 +1,30 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; + +public class BlockStairsSmoothRedSandstone extends BlockStairsRedSandstone { + + public BlockStairsSmoothRedSandstone() { + this(0); + } + + public BlockStairsSmoothRedSandstone(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Smooth RedSand stone Stairs"; + } + + @Override + public int getId() { + return SMOOTH_RED_SANDSTONE_STAIRS; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsSmoothSandstone.java b/src/main/java/cn/nukkit/block/BlockStairsSmoothSandstone.java new file mode 100644 index 00000000000..58b743c4fbc --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsSmoothSandstone.java @@ -0,0 +1,30 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; + +public class BlockStairsSmoothSandstone extends BlockStairsSandstone { + + public BlockStairsSmoothSandstone() { + this(0); + } + + public BlockStairsSmoothSandstone(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Smooth Sandstone Stairs"; + } + + @Override + public int getId() { + return SMOOTH_SANDSTONE_STAIRS; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsSpruce.java b/src/main/java/cn/nukkit/block/BlockStairsSpruce.java index 09a54a098fe..68f12d0e88a 100644 --- a/src/main/java/cn/nukkit/block/BlockStairsSpruce.java +++ b/src/main/java/cn/nukkit/block/BlockStairsSpruce.java @@ -23,12 +23,11 @@ public int getId() { @Override public String getName() { - return "Spruce Wood Stairs"; + return "Spruce Stairs"; } @Override public BlockColor getColor() { return BlockColor.SPRUCE_BLOCK_COLOR; } - } diff --git a/src/main/java/cn/nukkit/block/BlockStairsStone.java b/src/main/java/cn/nukkit/block/BlockStairsStone.java new file mode 100644 index 00000000000..9f357417130 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsStone.java @@ -0,0 +1,44 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; + +public class BlockStairsStone extends BlockStairs { + + public BlockStairsStone() { + this(0); + } + + public BlockStairsStone(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Stone Stairs"; + } + + @Override + public int getId() { + return NORMAL_STONE_STAIRS; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public double getHardness() { + return 1.5; + } + + @Override + public double getResistance() { + return 30; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsStoneBrick.java b/src/main/java/cn/nukkit/block/BlockStairsStoneBrick.java index d84255e8295..a7145c21dfa 100644 --- a/src/main/java/cn/nukkit/block/BlockStairsStoneBrick.java +++ b/src/main/java/cn/nukkit/block/BlockStairsStoneBrick.java @@ -7,6 +7,7 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockStairsStoneBrick extends BlockStairs { + public BlockStairsStoneBrick() { this(0); } diff --git a/src/main/java/cn/nukkit/block/BlockStairsTileDeepslate.java b/src/main/java/cn/nukkit/block/BlockStairsTileDeepslate.java new file mode 100644 index 00000000000..0984a0559a6 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStairsTileDeepslate.java @@ -0,0 +1,55 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockStairsTileDeepslate extends BlockStairs { + + public BlockStairsTileDeepslate() { + this(0); + } + + public BlockStairsTileDeepslate(int meta) { + super(meta); + } + + @Override + public int getId() { + return DEEPSLATE_TILE_STAIRS; + } + + @Override + public String getName() { + return "Deepslate Tile Stairs"; + } + + @Override + public double getHardness() { + return 3.5; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_WOODEN; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStairsWood.java b/src/main/java/cn/nukkit/block/BlockStairsWood.java index 11ae3209cf9..5b5a1425cf9 100644 --- a/src/main/java/cn/nukkit/block/BlockStairsWood.java +++ b/src/main/java/cn/nukkit/block/BlockStairsWood.java @@ -1,7 +1,6 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemTool; import cn.nukkit.utils.BlockColor; @@ -10,6 +9,7 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockStairsWood extends BlockStairs { + public BlockStairsWood() { this(0); } @@ -33,11 +33,6 @@ public int getToolType() { return ItemTool.TYPE_AXE; } - @Override - public Item toItem() { - return new ItemBlock(this, 0); - } - @Override public double getHardness() { return 2; @@ -62,6 +57,7 @@ public int getBurnAbility() { public BlockColor getColor() { return BlockColor.WOOD_BLOCK_COLOR; } + @Override public Item[] getDrops(Item item) { return new Item[]{ diff --git a/src/main/java/cn/nukkit/block/BlockStem.java b/src/main/java/cn/nukkit/block/BlockStem.java new file mode 100644 index 00000000000..24c19b134ba --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStem.java @@ -0,0 +1,73 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.math.BlockFace; + +public abstract class BlockStem extends BlockSolidMeta { + + private static final short[] FACES = { + 0, + 0, + 2, + 2, + 1, + 1 + }; + + public BlockStem() { + this(0); + } + + protected BlockStem(int meta) { + super(meta); + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + this.setDamage(FACES[face.getIndex()]); + this.getLevel().setBlock(block, this, true, true); + return true; + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (item.isAxe()) { + Block strippedBlock = Block.get(this.getStrippedId()); + strippedBlock.setDamage(this.getDamage()); + item.useOn(this); + this.level.setBlock(this, strippedBlock, true, true); + return true; + } + return false; + } + + public abstract int getStrippedId(); + + @Override + public int getToolType() { + return ItemTool.TYPE_AXE; + } + + @Override + public Item toItem() { + return new ItemBlock(this, 0); + } + + @Override + public double getHardness() { + return 2; + } + + @Override + public double getResistance() { + return 2; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockStemMelon.java b/src/main/java/cn/nukkit/block/BlockStemMelon.java index 90b32f823cc..abeaed8b0f7 100644 --- a/src/main/java/cn/nukkit/block/BlockStemMelon.java +++ b/src/main/java/cn/nukkit/block/BlockStemMelon.java @@ -3,11 +3,10 @@ import cn.nukkit.Server; import cn.nukkit.event.block.BlockGrowEvent; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemSeedsMelon; import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; import cn.nukkit.math.BlockFace.Plane; -import cn.nukkit.math.NukkitRandom; +import cn.nukkit.utils.Utils; /** * Created by Pub4Game on 15.01.2016. @@ -40,8 +39,7 @@ public int onUpdate(int type) { return Level.BLOCK_UPDATE_NORMAL; } } else if (type == Level.BLOCK_UPDATE_RANDOM) { - NukkitRandom random = new NukkitRandom(); - if (random.nextRange(1, 2) == 1) { + if (Utils.rand()) { if (this.getDamage() < 0x07) { Block block = this.clone(); block.setDamage(block.getDamage() + 1); @@ -58,10 +56,10 @@ public int onUpdate(int type) { return Level.BLOCK_UPDATE_RANDOM; } } - Block side = this.getSide(Plane.HORIZONTAL.random(random)); - Block d = side.down(); - if (side.getId() == AIR && (d.getId() == FARMLAND || d.getId() == GRASS || d.getId() == DIRT)) { - BlockGrowEvent ev = new BlockGrowEvent(side, Block.get(BlockID.MELON_BLOCK)); + Block side = this.getSide(Plane.HORIZONTAL.random()); + Block d; + if (side.getId() == AIR && ((d = side.down()).getId() == FARMLAND || d.getId() == GRASS || d.getId() == DIRT)) { + BlockGrowEvent ev = new BlockGrowEvent(side, Block.get(MELON_BLOCK)); Server.getInstance().getPluginManager().callEvent(ev); if (!ev.isCancelled()) { this.getLevel().setBlock(side, ev.getNewState(), true); @@ -76,14 +74,19 @@ public int onUpdate(int type) { @Override public Item toItem() { - return new ItemSeedsMelon(); + return Item.get(Item.MELON_SEEDS); } @Override public Item[] getDrops(Item item) { - NukkitRandom random = new NukkitRandom(); + if (this.getDamage() < 4) return new Item[0]; return new Item[]{ - new ItemSeedsMelon(0, random.nextRange(0, 3)) + Item.get(Item.MELON_SEEDS, 0, Utils.rand(0, 48) >> 4) }; } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockStemPumpkin.java b/src/main/java/cn/nukkit/block/BlockStemPumpkin.java index e5982255dca..308ded3d6ab 100644 --- a/src/main/java/cn/nukkit/block/BlockStemPumpkin.java +++ b/src/main/java/cn/nukkit/block/BlockStemPumpkin.java @@ -3,11 +3,10 @@ import cn.nukkit.Server; import cn.nukkit.event.block.BlockGrowEvent; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemSeedsPumpkin; import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; import cn.nukkit.math.BlockFace.Plane; -import cn.nukkit.math.NukkitRandom; +import cn.nukkit.utils.Utils; /** * Created by Pub4Game on 15.01.2016. @@ -40,8 +39,7 @@ public int onUpdate(int type) { return Level.BLOCK_UPDATE_NORMAL; } } else if (type == Level.BLOCK_UPDATE_RANDOM) { - NukkitRandom random = new NukkitRandom(); - if (random.nextRange(1, 2) == 1) { + if (Utils.rand()) { if (this.getDamage() < 0x07) { Block block = this.clone(); block.setDamage(block.getDamage() + 1); @@ -58,10 +56,10 @@ public int onUpdate(int type) { return Level.BLOCK_UPDATE_RANDOM; } } - Block side = this.getSide(Plane.HORIZONTAL.random(random)); - Block d = side.down(); - if (side.getId() == AIR && (d.getId() == FARMLAND || d.getId() == GRASS || d.getId() == DIRT)) { - BlockGrowEvent ev = new BlockGrowEvent(side, Block.get(BlockID.PUMPKIN)); + Block side = this.getSide(Plane.HORIZONTAL.random()); + Block d; + if (side.getId() == AIR && ((d = side.down()).getId() == FARMLAND || d.getId() == GRASS || d.getId() == DIRT)) { + BlockGrowEvent ev = new BlockGrowEvent(side, Block.get(PUMPKIN)); Server.getInstance().getPluginManager().callEvent(ev); if (!ev.isCancelled()) { this.getLevel().setBlock(side, ev.getNewState(), true); @@ -76,14 +74,19 @@ public int onUpdate(int type) { @Override public Item toItem() { - return new ItemSeedsPumpkin(); + return Item.get(Item.PUMPKIN_SEEDS); } @Override public Item[] getDrops(Item item) { - NukkitRandom random = new NukkitRandom(); + if (this.getDamage() < 4) return new Item[0]; return new Item[]{ - new ItemSeedsPumpkin(0, random.nextRange(0, 3)) + Item.get(Item.PUMPKIN_SEEDS, 0, Utils.rand(0, 48) >> 4) }; } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockStemStripped.java b/src/main/java/cn/nukkit/block/BlockStemStripped.java new file mode 100644 index 00000000000..affcf5cb935 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStemStripped.java @@ -0,0 +1,30 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; + +public abstract class BlockStemStripped extends BlockStem { + + public BlockStemStripped() { + this(0); + } + + public BlockStemStripped(int meta) { + super(meta); + } + + @Override + public boolean canBeActivated() { + return false; + } + + @Override + public boolean onActivate(Item item, Player player) { + return false; + } + + @Override + public int getStrippedId() { + return this.getId(); + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockStone.java b/src/main/java/cn/nukkit/block/BlockStone.java index 15f01b008ab..568b3577624 100644 --- a/src/main/java/cn/nukkit/block/BlockStone.java +++ b/src/main/java/cn/nukkit/block/BlockStone.java @@ -2,12 +2,15 @@ import cn.nukkit.item.Item; import cn.nukkit.item.ItemTool; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.utils.BlockColor; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockStone extends BlockSolidMeta { + public static final int NORMAL = 0; public static final int GRANITE = 1; public static final int POLISHED_GRANITE = 2; @@ -16,6 +19,16 @@ public class BlockStone extends BlockSolidMeta { public static final int ANDESITE = 5; public static final int POLISHED_ANDESITE = 6; + private static final String[] NAMES = { + "Stone", + "Granite", + "Polished Granite", + "Diorite", + "Polished Diorite", + "Andesite", + "Polished Andesite", + "Unknown Stone" + }; public BlockStone() { this(0); @@ -37,7 +50,7 @@ public double getHardness() { @Override public double getResistance() { - return 10; + return 30; } @Override @@ -47,22 +60,15 @@ public int getToolType() { @Override public String getName() { - String[] names = new String[]{ - "Stone", - "Granite", - "Polished Granite", - "Diorite", - "Polished Diorite", - "Andesite", - "Polished Andesite", - "Unknown Stone" - }; - return names[this.getDamage() & 0x07]; + return NAMES[this.getDamage() & 0x07]; } @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { + if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { + return new Item[]{this.toItem()}; + } return new Item[]{ Item.get(this.getDamage() == 0 ? Item.COBBLESTONE : Item.STONE, this.getDamage(), 1) }; @@ -80,4 +86,15 @@ public boolean canHarvestWithHand() { public boolean canSilkTouch() { return true; } + + @Override + public BlockColor getColor() { + int damage = this.getDamage() & 0x07; + if (damage == GRANITE || damage == POLISHED_GRANITE) { + return BlockColor.DIRT_BLOCK_COLOR; + } else if (damage == DIORITE || damage == POLISHED_DIORITE) { + return BlockColor.QUARTZ_BLOCK_COLOR; + } + return BlockColor.STONE_BLOCK_COLOR; + } } diff --git a/src/main/java/cn/nukkit/block/BlockStonecutter.java b/src/main/java/cn/nukkit/block/BlockStonecutter.java index f077ac20d58..14cd4bdc7aa 100644 --- a/src/main/java/cn/nukkit/block/BlockStonecutter.java +++ b/src/main/java/cn/nukkit/block/BlockStonecutter.java @@ -1,52 +1,53 @@ -package cn.nukkit.block; - -import cn.nukkit.item.Item; -import cn.nukkit.item.ItemTool; - -public class BlockStonecutter extends BlockSolid { - - public BlockStonecutter() { - - } - - @Override - public int getId() { - return STONECUTTER; - } - - @Override - public String getName() { - return "Stonecutter"; - } - - @Override - public double getHardness() { - return 3.5; - } - - @Override - public double getResistance() { - return 17.5; - } - - @Override - public int getToolType() { - return ItemTool.TYPE_PICKAXE; - } - - @Override - public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { - return new Item[]{ - this.toItem() - }; - } else { - return new Item[0]; - } - } - - @Override - public boolean canHarvestWithHand() { - return false; - } -} +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; + +public class BlockStonecutter extends BlockSolid { + + @Override + public int getId() { + return STONECUTTER; + } + + @Override + public double getHardness() { + return 3.5; + } + + @Override + public double getResistance() { + return 17.5; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public String getName() { + return "Stonecutter"; + } + + @Override + public Item[] getDrops(Item item) { + if (item.isPickaxe()) { + return new Item[]{ + toItem() + }; + } else { + return new Item[0]; + } + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStonecutterBlock.java b/src/main/java/cn/nukkit/block/BlockStonecutterBlock.java new file mode 100644 index 00000000000..479b1d4fd0c --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStonecutterBlock.java @@ -0,0 +1,64 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemTool; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.Faceable; + +public class BlockStonecutterBlock extends BlockSolidMeta implements Faceable { + + public BlockStonecutterBlock() { + this(0); + } + + public BlockStonecutterBlock(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Stonecutter Block"; + } + + @Override + public int getId() { + return STONECUTTER_BLOCK; + } + + @Override + public double getHardness() { + return 3.5; + } + + @Override + public double getResistance() { + return 17.5; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public double getMaxY() { + return y + 0.5625; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + this.setDamage(Block.FACES2534[player != null ? player.getDirection().getHorizontalIndex() : 0]); + return super.place(item, block, target, face, fx, fy, fz, player); + } + + @Override + public BlockFace getBlockFace() { + return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStrippedCrimsonStem.java b/src/main/java/cn/nukkit/block/BlockStrippedCrimsonStem.java new file mode 100644 index 00000000000..4c75f67c1a0 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStrippedCrimsonStem.java @@ -0,0 +1,39 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockStrippedCrimsonStem extends BlockStemStripped { + + public BlockStrippedCrimsonStem() { + this(0); + } + + public BlockStrippedCrimsonStem(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Stripped Crimson Stem"; + } + + @Override + public int getId() { + return STRIPPED_CRIMSON_STEM; + } + + @Override + public BlockColor getColor() { + return BlockColor.CRIMSON_STEM_BLOCK_COLOR; + } + + @Override + public int getBurnChance() { + return 0; + } + + @Override + public int getBurnAbility() { + return 0; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockStrippedWarpedStem.java b/src/main/java/cn/nukkit/block/BlockStrippedWarpedStem.java new file mode 100644 index 00000000000..25f559f2b7a --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStrippedWarpedStem.java @@ -0,0 +1,39 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockStrippedWarpedStem extends BlockStemStripped { + + public BlockStrippedWarpedStem() { + this(0); + } + + public BlockStrippedWarpedStem(int meta) { + super(meta); + } + + @Override + public int getId() { + return STRIPPED_WARPED_STEM; + } + + @Override + public String getName() { + return "Stripped Warped Stem"; + } + + @Override + public BlockColor getColor() { + return BlockColor.WARPED_STEM_BLOCK_COLOR; + } + + @Override + public int getBurnChance() { + return 0; + } + + @Override + public int getBurnAbility() { + return 0; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockStructureBlock.java b/src/main/java/cn/nukkit/block/BlockStructureBlock.java new file mode 100644 index 00000000000..7bda561e5f9 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockStructureBlock.java @@ -0,0 +1,47 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.utils.BlockColor; + +public class BlockStructureBlock extends BlockSolid { + + @Override + public int getId() { + return STRUCTURE_BLOCK; + } + + @Override + public double getHardness() { + return -1; + } + + @Override + public double getResistance() { + return 18000000; + } + + @Override + public String getName() { + return "Structure Block"; + } + + @Override + public boolean isBreakable(Item item) { + return false; + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public BlockColor getColor() { + return BlockColor.LIGHT_GRAY_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockSugarcane.java b/src/main/java/cn/nukkit/block/BlockSugarcane.java index a5c0eea8abb..ef2cef0f56a 100644 --- a/src/main/java/cn/nukkit/block/BlockSugarcane.java +++ b/src/main/java/cn/nukkit/block/BlockSugarcane.java @@ -4,11 +4,10 @@ import cn.nukkit.Server; import cn.nukkit.event.block.BlockGrowEvent; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemSugarcane; +import cn.nukkit.item.ItemDye; import cn.nukkit.level.Level; import cn.nukkit.level.particle.BoneMealParticle; import cn.nukkit.math.BlockFace; -import cn.nukkit.math.Vector3; import cn.nukkit.utils.BlockColor; /** @@ -26,7 +25,7 @@ public BlockSugarcane(int meta) { @Override public String getName() { - return "Sugarcane"; + return "Sugar Cane"; } @Override @@ -36,7 +35,7 @@ public int getId() { @Override public Item toItem() { - return new ItemSugarcane(); + return Item.get(Item.SUGARCANE); } @Override @@ -46,7 +45,7 @@ public boolean canBeActivated() { @Override public boolean onActivate(Item item, Player player) { - if (item.getId() == Item.DYE && item.getDamage() == 0x0F) { //Bonemeal + if (item.getId() == Item.DYE && item.getDamage() == ItemDye.BONE_MEAL) { int count = 1; for (int i = 1; i <= 2; i++) { @@ -64,7 +63,7 @@ public boolean onActivate(Item item, Player player) { for (int i = 1; i <= toGrow; i++) { Block block = this.up(i); if (block.getId() == 0) { - BlockGrowEvent ev = new BlockGrowEvent(block, Block.get(BlockID.SUGARCANE_BLOCK)); + BlockGrowEvent ev = new BlockGrowEvent(block, Block.get(SUGARCANE_BLOCK)); Server.getInstance().getPluginManager().callEvent(ev); if (!ev.isCancelled()) { @@ -77,14 +76,13 @@ public boolean onActivate(Item item, Player player) { } if (success) { - if (player != null && (player.gamemode & 0x01) == 0) { + if (player != null && !player.isCreative()) { item.count--; } this.level.addParticle(new BoneMealParticle(this)); } } - return true; } return false; @@ -102,23 +100,22 @@ public int onUpdate(int type) { if (this.down().getId() != SUGARCANE_BLOCK) { if (this.getDamage() == 0x0F) { for (int y = 1; y < 3; ++y) { - Block b = this.getLevel().getBlock(new Vector3(this.x, this.y + y, this.z)); + Block b = this.getLevel().getBlock((int) this.x, (int) this.y + y, (int) this.z); if (b.getId() == AIR) { BlockGrowEvent ev = new BlockGrowEvent(b, Block.get(BlockID.SUGARCANE_BLOCK)); Server.getInstance().getPluginManager().callEvent(ev); - + if (!ev.isCancelled()) { - this.getLevel().setBlock(b, Block.get(BlockID.SUGARCANE_BLOCK), false); + this.getLevel().setBlock(b, ev.getNewState(), false); } break; } } this.setDamage(0); - this.getLevel().setBlock(this, this, false); } else { this.setDamage(this.getDamage() + 1); - this.getLevel().setBlock(this, this, false); } + this.level.setBlock((int) this.x, (int) this.y, (int) this.z, BlockLayer.NORMAL, this, false, true, false); // No need to send this to client return Level.BLOCK_UPDATE_RANDOM; } } @@ -133,15 +130,15 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl Block down = this.down(); int id = down.getId(); if (id == SUGARCANE_BLOCK) { - this.getLevel().setBlock(block, Block.get(BlockID.SUGARCANE_BLOCK), true); + this.getLevel().setBlock(block, Block.get(SUGARCANE_BLOCK), true); return true; } else if (id == GRASS || id == DIRT || id == SAND || id == PODZOL || id == MYCELIUM) { Block block0 = down.north(); Block block1 = down.south(); Block block2 = down.west(); Block block3 = down.east(); - if ((block0 instanceof BlockWater) || (block1 instanceof BlockWater) || (block2 instanceof BlockWater) || (block3 instanceof BlockWater)) { - this.getLevel().setBlock(block, Block.get(BlockID.SUGARCANE_BLOCK), true); + if (block0 instanceof BlockWater || block1 instanceof BlockWater || block2 instanceof BlockWater || block3 instanceof BlockWater || block0 instanceof BlockIceFrosted || block1 instanceof BlockIceFrosted || block2 instanceof BlockIceFrosted || block3 instanceof BlockIceFrosted) { + this.getLevel().setBlock(block, Block.get(SUGARCANE_BLOCK), true); return true; } } @@ -152,4 +149,9 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl public BlockColor getColor() { return BlockColor.FOLIAGE_BLOCK_COLOR; } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockSweetBerryBush.java b/src/main/java/cn/nukkit/block/BlockSweetBerryBush.java new file mode 100644 index 00000000000..25b8cecd20d --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockSweetBerryBush.java @@ -0,0 +1,206 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityItem; +import cn.nukkit.event.block.BlockGrowEvent; +import cn.nukkit.event.block.BlockHarvestEvent; +import cn.nukkit.event.entity.EntityDamageByBlockEvent; +import cn.nukkit.event.entity.EntityDamageEvent; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; +import cn.nukkit.level.Level; +import cn.nukkit.level.Position; +import cn.nukkit.level.particle.BoneMealParticle; +import cn.nukkit.math.AxisAlignedBB; +import cn.nukkit.math.BlockFace; +import cn.nukkit.math.MathHelper; +import cn.nukkit.network.protocol.LevelSoundEventPacket; +import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.DyeColor; + +import java.util.concurrent.ThreadLocalRandom; + +public class BlockSweetBerryBush extends BlockFlowable { + + public BlockSweetBerryBush() { + this(0); + } + + public BlockSweetBerryBush(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Sweet Berry Bush"; + } + + @Override + public int getId() { + return SWEET_BERRY_BUSH; + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public int getBurnChance() { + return 30; + } + + @Override + public int getBurnAbility() { + return 60; + } + + @Override + public Item toItem() { + return Item.get(ItemID.SWEET_BERRIES); + } + + @Override + public void onEntityCollide(Entity entity) { + if (this.getDamage() > 0 && !(entity instanceof EntityItem)) { + entity.resetFallDistance(); + if (!entity.isSneaking() && ThreadLocalRandom.current().nextInt(20) == 0) { + if (entity.attack(new EntityDamageByBlockEvent(this, entity, EntityDamageEvent.DamageCause.CONTACT, 1))) { + this.level.addLevelSoundEvent(entity, LevelSoundEventPacket.SOUND_BLOCK_SWEET_BERRY_BUSH_HURT); + } + } + } + } + + @Override + public boolean hasEntityCollision() { + return this.getDamage() > 0; + } + + protected AxisAlignedBB recalculateBoundingBox() { + if (this.getDamage() > 0) { + return this; + } + return null; + } + + @Override + public Item[] getDrops(Item item) { + int age = MathHelper.clamp(getDamage(), 0, 3); + + int amount = 1; + if (age > 1) { + amount = 1 + ThreadLocalRandom.current().nextInt(2); + if (age == 3) { + amount++; + } + } + + return new Item[]{Item.get(ItemID.SWEET_BERRIES, 0, amount)}; + } + + @Override + public boolean onActivate(Item item, Player player) { + int age = MathHelper.clamp(this.getDamage(), 0, 3); + + if (age < 3 && item.getId() == ItemID.DYE && item.getDamage() == DyeColor.WHITE.getDyeData()) { + BlockSweetBerryBush block = (BlockSweetBerryBush) this.clone(); + block.setDamage(block.getDamage() + 1); + if (block.getDamage() > 3) { + block.setDamage(3); + } + + BlockGrowEvent ev = new BlockGrowEvent(this, block); + this.getLevel().getServer().getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + return false; + } + + this.getLevel().setBlock(this, ev.getNewState(), false, true); + this.level.addParticle(new BoneMealParticle(this)); + + if (player != null && (player.gamemode & 0x01) == 0) { + item.count--; + } + return true; + } + + if (age < 2) { + return true; + } + + int amount = 1 + ThreadLocalRandom.current().nextInt(2); + if (age == 3) { + amount++; + } + + BlockHarvestEvent event = new BlockHarvestEvent(this, Block.get(SWEET_BERRY_BUSH, 1), new Item[]{Item.get(ItemID.SWEET_BERRIES, 0, amount)}); + this.getLevel().getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + this.getLevel().setBlock(this, event.getNewState(), true, true); + Item[] drops = event.getDrops(); + if (drops != null) { + Position dropPos = add(0.5, 0.5, 0.5); + for (Item drop : drops) { + if (drop != null) { + this.getLevel().dropItem(dropPos, drop); + } + } + } + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_BLOCK_SWEET_BERRY_BUSH_PICK); + } + return true; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + if (!isSupportValid(this.down())) { + this.getLevel().useBreakOn(this); + return Level.BLOCK_UPDATE_NORMAL; + } + } else if (type == Level.BLOCK_UPDATE_RANDOM) { + if (this.getDamage() < 3 && ThreadLocalRandom.current().nextInt(5) == 0) { + BlockGrowEvent event = new BlockGrowEvent(this, Block.get(this.getId(), this.getDamage() + 1)); + if (!event.isCancelled()) { + this.getLevel().setBlock(this, event.getNewState(), true, true); + } + } + return type; + } + return 0; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (target.getId() == SWEET_BERRY_BUSH || block.getId() != AIR) { + return false; + } + if (isSupportValid(this.down())) { + this.getLevel().setBlock(block, this, true); + return true; + } + return false; + } + + + public static boolean isSupportValid(Block block) { + switch (block.getId()) { + case GRASS: + case DIRT: + case PODZOL: + case MYCELIUM: + case FARMLAND: + return true; + default: + return false; + } + } + + @Override + public BlockColor getColor() { + return BlockColor.FOLIAGE_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockTNT.java b/src/main/java/cn/nukkit/block/BlockTNT.java index 462093738dc..8fe6f21092e 100644 --- a/src/main/java/cn/nukkit/block/BlockTNT.java +++ b/src/main/java/cn/nukkit/block/BlockTNT.java @@ -2,15 +2,17 @@ import cn.nukkit.Player; import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityPrimedTNT; +import cn.nukkit.entity.projectile.EntityArrow; import cn.nukkit.item.Item; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.level.Level; +import cn.nukkit.level.Sound; import cn.nukkit.math.NukkitRandom; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.DoubleTag; import cn.nukkit.nbt.tag.FloatTag; import cn.nukkit.nbt.tag.ListTag; -import cn.nukkit.network.protocol.LevelEventPacket; import cn.nukkit.utils.BlockColor; /** @@ -19,9 +21,6 @@ */ public class BlockTNT extends BlockSolid { - public BlockTNT() { - } - @Override public String getName() { return "TNT"; @@ -65,9 +64,11 @@ public void prime(int fuse) { prime(fuse, null); } + private static final NukkitRandom RANDOM = new NukkitRandom(); + public void prime(int fuse, Entity source) { this.getLevel().setBlock(this, Block.get(BlockID.AIR), true); - double mot = (new NukkitRandom()).nextSignedFloat() * Math.PI * 2; + double mot = RANDOM.nextSignedFloat() * 6.283185307179586; CompoundTag nbt = new CompoundTag() .putList(new ListTag("Pos") .add(new DoubleTag("", this.x + 0.5)) @@ -80,21 +81,15 @@ public void prime(int fuse, Entity source) { .putList(new ListTag("Rotation") .add(new FloatTag("", 0)) .add(new FloatTag("", 0))) - .putShort("Fuse", fuse); - Entity tnt = Entity.createEntity("PrimedTnt", - this.getLevel().getChunk(this.getFloorX() >> 4, this.getFloorZ() >> 4), - nbt, source - ); - if(tnt == null) { - return; - } - tnt.spawnToAll(); - this.getLevel().addLevelEvent(this, LevelEventPacket.EVENT_SOUND_TNT); + .putByte("Fuse", fuse); + + Entity.createEntity(EntityPrimedTNT.NETWORK_ID, + this.getLevel().getChunk(this.getChunkX(), this.getChunkZ()), nbt, source).spawnToAll(); } @Override public int onUpdate(int type) { - if ((type == Level.BLOCK_UPDATE_NORMAL || type == Level.BLOCK_UPDATE_REDSTONE) && this.level.isBlockPowered(this.getLocation())) { + if ((type == Level.BLOCK_UPDATE_NORMAL || type == Level.BLOCK_UPDATE_REDSTONE) && this.level.isBlockPowered(this)) { this.prime(); } @@ -109,6 +104,7 @@ public boolean onActivate(Item item, Player player) { return true; } else if (item.getId() == Item.FIRE_CHARGE) { if (!player.isCreative()) item.count--; + this.level.addSound(this, Sound.MOB_GHAST_FIREBALL); this.prime(80, player); return true; } else if (item.hasEnchantment(Enchantment.ID_FIRE_ASPECT)) { @@ -116,6 +112,7 @@ public boolean onActivate(Item item, Player player) { this.prime(80, player); return true; } + return false; } @@ -123,4 +120,17 @@ public boolean onActivate(Item item, Player player) { public BlockColor getColor() { return BlockColor.TNT_BLOCK_COLOR; } + + @Override + public boolean hasEntityCollision() { + return true; + } + + @Override + public void onEntityCollide(Entity entity) { + if (entity instanceof EntityArrow && entity.isOnFire()) { + entity.close(); + this.prime(); + } + } } diff --git a/src/main/java/cn/nukkit/block/BlockTallGrass.java b/src/main/java/cn/nukkit/block/BlockTallGrass.java index 077b82b101f..05820c18327 100644 --- a/src/main/java/cn/nukkit/block/BlockTallGrass.java +++ b/src/main/java/cn/nukkit/block/BlockTallGrass.java @@ -2,16 +2,16 @@ import cn.nukkit.Player; import cn.nukkit.item.Item; +import cn.nukkit.item.ItemDye; import cn.nukkit.item.ItemTool; import cn.nukkit.level.Level; import cn.nukkit.level.particle.BoneMealParticle; import cn.nukkit.math.BlockFace; import cn.nukkit.utils.BlockColor; - -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class BlockTallGrass extends BlockFlowable { @@ -29,15 +29,16 @@ public int getId() { return TALL_GRASS; } + private static final String[] NAMES = { + "Grass", + "Grass", + "Fern", + "Fern" + }; + @Override public String getName() { - String[] names = new String[]{ - "Grass", - "Grass", - "Fern", - "Fern" - }; - return names[this.getDamage() & 0x03]; + return NAMES[this.getDamage() & 0x03]; } @Override @@ -64,7 +65,7 @@ public int getBurnAbility() { public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { Block down = this.down(); int id = down.getId(); - if (id == Block.GRASS || id == Block.DIRT || id == Block.PODZOL || id == FARMLAND || id == MYCELIUM) { + if (id == Block.GRASS || id == Block.DIRT || id == Block.PODZOL || id == FARMLAND || id == MYCELIUM || id == MOSS_BLOCK) { this.getLevel().setBlock(block, this, true); return true; } @@ -84,7 +85,7 @@ public int onUpdate(int type) { @Override public boolean onActivate(Item item, Player player) { - if (item.getId() == Item.DYE && item.getDamage() == 0x0f) { + if (item.getId() == Item.DYE && item.getDamage() == ItemDye.BONE_MEAL) { Block up = this.up(); if (up.getId() == AIR) { @@ -104,7 +105,7 @@ public boolean onActivate(Item item, Player player) { } if (meta != -1) { - if (player != null && (player.gamemode & 0x01) == 0) { + if (player != null && !player.isCreative()) { item.count--; } @@ -120,6 +121,7 @@ public boolean onActivate(Item item, Player player) { return false; } + @Override public Item[] getDrops(Item item) { if (item.isShears()) { @@ -128,7 +130,7 @@ public Item[] getDrops(Item item) { }; } - if (ThreadLocalRandom.current().nextInt(10) == 0) { + if (Utils.random.nextInt(10) == 0) { return new Item[]{ Item.get(Item.WHEAT_SEEDS) }; @@ -146,4 +148,9 @@ public int getToolType() { public BlockColor getColor() { return BlockColor.FOLIAGE_BLOCK_COLOR; } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockTarget.java b/src/main/java/cn/nukkit/block/BlockTarget.java new file mode 100644 index 00000000000..287c2144bca --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockTarget.java @@ -0,0 +1,109 @@ +package cn.nukkit.block; + +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.projectile.EntityArrow; +import cn.nukkit.entity.projectile.EntityProjectile; +import cn.nukkit.entity.projectile.EntityThrownTrident; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.BlockColor; + +public class BlockTarget extends BlockSolidMeta { + + public BlockTarget() { + this(0); + } + + public BlockTarget(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Target"; + } + + @Override + public int getId() { + return TARGET; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_HOE; + } + + @Override + public int getBurnChance() { + return 5; + } + + @Override + public int getBurnAbility() { + return 15; + } + + @Override + public double getHardness() { + return 0.5; + } + + @Override + public double getResistance() { + return 0.5; + } + + @Override + public BlockColor getColor() { + return BlockColor.WHITE_BLOCK_COLOR; + } + + @Override + public Item[] getDrops(Item item) { + return new Item[]{new ItemBlock(Block.get(TARGET))}; + } + + @Override + public boolean isPowerSource() { + return true; + } + + @Override + public int getWeakPower(BlockFace face) { + return this.getDamage() > 0 ? 10 : 0; + } + + @Override + public boolean hasEntityCollision() { + return true; + } + + @Override + public void onEntityCollide(Entity entity) { + if (entity instanceof EntityProjectile) { + this.setDamage(1); + this.level.setBlock((int) this.x, (int) this.y, (int) this.z, BlockLayer.NORMAL, this, false, true, false); // No need to send this to client + this.level.updateAroundRedstone(this, null); + + if (entity instanceof EntityArrow || entity instanceof EntityThrownTrident) { + this.level.scheduleUpdate(this, 20); + } else { + this.level.scheduleUpdate(this, 8); + } + } + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_SCHEDULED) { + this.setDamage(0); + this.level.setBlock((int) this.x, (int) this.y, (int) this.z, BlockLayer.NORMAL, this, false, true, false); // No need to send this to client + this.level.updateAroundRedstone(this, null); + return Level.BLOCK_UPDATE_SCHEDULED; + } + return 0; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockTerracotta.java b/src/main/java/cn/nukkit/block/BlockTerracotta.java index 58f163a0379..d7aa085192d 100644 --- a/src/main/java/cn/nukkit/block/BlockTerracotta.java +++ b/src/main/java/cn/nukkit/block/BlockTerracotta.java @@ -3,6 +3,7 @@ import cn.nukkit.item.Item; import cn.nukkit.item.ItemTool; import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.DyeColor; import cn.nukkit.utils.TerracottaColor; /** @@ -10,6 +11,7 @@ * Package cn.nukkit.block in project Nukkit . */ public class BlockTerracotta extends BlockSolidMeta { + public BlockTerracotta() { this(0); } @@ -18,6 +20,10 @@ public BlockTerracotta(int meta) { super(0); } + public BlockTerracotta(DyeColor dyeColor) { + this(dyeColor.getWoolData()); + } + public BlockTerracotta(TerracottaColor dyeColor) { this(dyeColor.getTerracottaData()); } @@ -49,7 +55,7 @@ public double getResistance() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; diff --git a/src/main/java/cn/nukkit/block/BlockTerracottaGlazed.java b/src/main/java/cn/nukkit/block/BlockTerracottaGlazed.java index 5edfde12f6d..381ed798412 100644 --- a/src/main/java/cn/nukkit/block/BlockTerracottaGlazed.java +++ b/src/main/java/cn/nukkit/block/BlockTerracottaGlazed.java @@ -2,14 +2,16 @@ import cn.nukkit.Player; import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemTool; import cn.nukkit.math.BlockFace; -import cn.nukkit.utils.Faceable; +import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.DyeColor; /** * Created by CreeperFace on 2.6.2017. */ -public abstract class BlockTerracottaGlazed extends BlockSolidMeta implements Faceable { +public abstract class BlockTerracottaGlazed extends BlockSolidMeta { public BlockTerracottaGlazed() { this(0); @@ -41,8 +43,7 @@ public Item[] getDrops(Item item) { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - int[] faces = {2, 5, 3, 4}; - this.setDamage(faces[player != null ? player.getDirection().getHorizontalIndex() : 0]); + this.setDamage(Block.FACES2534[player != null ? player.getDirection().getHorizontalIndex() : 0]); return this.getLevel().setBlock(block, this, true, true); } @@ -52,7 +53,16 @@ public boolean canHarvestWithHand() { } @Override - public BlockFace getBlockFace() { - return BlockFace.fromHorizontalIndex(this.getDamage() & 0x07); + public BlockColor getColor() { + return DyeColor.getByDyeData(getDyeColor().getDyeData()).getColor(); + } + + public DyeColor getDyeColor() { + return DyeColor.BLACK; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); } } diff --git a/src/main/java/cn/nukkit/block/BlockTerracottaGlazedLime.java b/src/main/java/cn/nukkit/block/BlockTerracottaGlazedLime.java index 3e7f4ec62b1..2c7f72b0bad 100644 --- a/src/main/java/cn/nukkit/block/BlockTerracottaGlazedLime.java +++ b/src/main/java/cn/nukkit/block/BlockTerracottaGlazedLime.java @@ -25,5 +25,7 @@ public String getName() { return "Lime Glazed Terracotta"; } - public DyeColor getDyeColor() { return DyeColor.LIME; } + public DyeColor getDyeColor() { + return DyeColor.LIME; + } } diff --git a/src/main/java/cn/nukkit/block/BlockTerracottaStained.java b/src/main/java/cn/nukkit/block/BlockTerracottaStained.java index fa538493acb..96df1ce9ef8 100644 --- a/src/main/java/cn/nukkit/block/BlockTerracottaStained.java +++ b/src/main/java/cn/nukkit/block/BlockTerracottaStained.java @@ -51,7 +51,7 @@ public int getToolType() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{toItem()}; } else { return new Item[0]; @@ -66,5 +66,4 @@ public BlockColor getColor() { public DyeColor getDyeColor() { return DyeColor.getByWoolData(getDamage()); } - } diff --git a/src/main/java/cn/nukkit/block/BlockThin.java b/src/main/java/cn/nukkit/block/BlockThin.java index 9b309160dcf..2997f42dbc5 100644 --- a/src/main/java/cn/nukkit/block/BlockThin.java +++ b/src/main/java/cn/nukkit/block/BlockThin.java @@ -19,38 +19,47 @@ public boolean isSolid() { } protected AxisAlignedBB recalculateBoundingBox() { - final double offNW = 7.0 / 16.0; - final double offSE = 9.0 / 16.0; - final double onNW = 0.0; - final double onSE = 1.0; - double w = offNW; - double e = offSE; - double n = offNW; - double s = offSE; + double f = 0.4375; + double f1 = 0.5625; + double f2 = 0.4375; + double f3 = 0.5625; try { - boolean north = this.canConnect(this.north()); - boolean south = this.canConnect(this.south()); - boolean west = this.canConnect(this.west()); - boolean east = this.canConnect(this.east()); - w = west ? onNW : offNW; - e = east ? onSE : offSE; - n = north ? onNW : offNW; - s = south ? onSE : offSE; - } catch (LevelException ignore) { - //null sucks - } + boolean flag = this.canConnect(this.north()); + boolean flag1 = this.canConnect(this.south()); + boolean flag2 = this.canConnect(this.west()); + boolean flag3 = this.canConnect(this.east()); + if ((!flag2 || !flag3) && (flag2 || flag3 || flag || flag1)) { + if (flag2) { + f = 0; + } else if (flag3) { + f1 = 1; + } + } else { + f = 0; + f1 = 1; + } + if ((!flag || !flag1) && (flag2 || flag3 || flag || flag1)) { + if (flag) { + f2 = 0; + } else if (flag1) { + f3 = 1; + } + } else { + f2 = 0; + f3 = 1; + } + } catch (LevelException ignore) {} return new SimpleAxisAlignedBB( - this.x + w, + this.x + f, this.y, - this.z + n, - this.x + e, + this.z + f2, + this.x + f1, this.y + 1, - this.z + s + this.z + f3 ); } public boolean canConnect(Block block) { return block.isSolid() || block.getId() == this.getId() || block.getId() == GLASS_PANE || block.getId() == GLASS; } - } diff --git a/src/main/java/cn/nukkit/block/BlockTilesDeepslate.java b/src/main/java/cn/nukkit/block/BlockTilesDeepslate.java new file mode 100644 index 00000000000..8b71ccd91a3 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockTilesDeepslate.java @@ -0,0 +1,52 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockTilesDeepslate extends BlockSolid { + + public BlockTilesDeepslate() { + // Does nothing + } + + @Override + public int getId() { + return DEEPSLATE_TILES; + } + + @Override + public String getName() { + return "Deepslate Tiles"; + } + + @Override + public double getHardness() { + return 3.5; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_WOODEN; + } + + + @Override + public BlockColor getColor() { + return BlockColor.DEEPSLATE_GRAY; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockTilesDeepslateCracked.java b/src/main/java/cn/nukkit/block/BlockTilesDeepslateCracked.java new file mode 100644 index 00000000000..504757997b9 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockTilesDeepslateCracked.java @@ -0,0 +1,18 @@ +package cn.nukkit.block; + +public class BlockTilesDeepslateCracked extends BlockTilesDeepslate { + + public BlockTilesDeepslateCracked() { + // Does nothing + } + + @Override + public int getId() { + return CRACKED_DEEPSLATE_TILES; + } + + @Override + public String getName() { + return "Cracked Deepslate Tiles"; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockTorch.java b/src/main/java/cn/nukkit/block/BlockTorch.java index f9f1b1316d3..4840a891caf 100644 --- a/src/main/java/cn/nukkit/block/BlockTorch.java +++ b/src/main/java/cn/nukkit/block/BlockTorch.java @@ -14,7 +14,7 @@ */ public class BlockTorch extends BlockFlowable implements Faceable { - private static final int[] faces = new int[]{ + private static final short[] FACES = { 0, //0, never used 5, //1 4, //2 @@ -23,7 +23,7 @@ public class BlockTorch extends BlockFlowable implements Faceable { 1, //5 }; - private static final int[] faces2 = new int[]{ + private static final short[] FACES_2 = { 0, //0 4, //1 5, //2 @@ -59,12 +59,8 @@ public int getLightLevel() { @Override public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_NORMAL) { - Block below = this.down(); int side = this.getDamage(); - Block block = this.getSide(BlockFace.fromIndex(faces2[side])); - int id = block.getId(); - - if ((block.isTransparent() && !(side == 0 && (below instanceof BlockFence || below.getId() == COBBLE_WALL))) && id != GLASS && id != STAINED_GLASS) { + if ((side != 0 && !Block.canConnectToFullSolid(this.getSide(BlockFace.fromIndex(FACES_2[side])))) || (side == 0 && !isSupportValidBelow())) { this.getLevel().useBreakOn(this); return Level.BLOCK_UPDATE_NORMAL; } @@ -75,26 +71,37 @@ public int onUpdate(int type) { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - int side = faces[face.getIndex()]; - int bid = this.getSide(BlockFace.fromIndex(faces2[side])).getId(); - if ((!target.isTransparent() || bid == GLASS || bid == STAINED_GLASS) && face != BlockFace.DOWN) { - this.setDamage(side); - this.getLevel().setBlock(block, this, true, true); - return true; + if (block instanceof BlockWater || block.level.isBlockWaterloggedAt(block.getChunk(), (int) block.x, (int) block.y, (int) block.z)) { + return false; } - Block below = this.down(); - if (!below.isTransparent() || below instanceof BlockFence || below.getId() == COBBLE_WALL || below.getId() == GLASS || below.getId() == STAINED_GLASS) { + int side = FACES[face.getIndex()]; + if (face != BlockFace.UP) { + if (Block.canConnectToFullSolid(this.getSide(BlockFace.fromIndex(FACES_2[side])))) { + this.setDamage(side); + return this.getLevel().setBlock(this, this, true, true); + } + return false; + } + + if (isSupportValidBelow()) { this.setDamage(0); - this.getLevel().setBlock(block, this, true, true); - return true; + return this.getLevel().setBlock(this, this, true, true); } return false; } + private boolean isSupportValidBelow() { + Block block = this.down(); + if (!block.isTransparent() || block.isNarrowSurface()) { + return true; + } + return Block.canStayOnFullSolid(block); + } + @Override public Item toItem() { - return new ItemBlock(this, 0); + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override @@ -121,4 +128,9 @@ public BlockFace getBlockFace(int meta) { return BlockFace.UP; } } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockTransparent.java b/src/main/java/cn/nukkit/block/BlockTransparent.java index 3ed36d2ca51..0499a649686 100644 --- a/src/main/java/cn/nukkit/block/BlockTransparent.java +++ b/src/main/java/cn/nukkit/block/BlockTransparent.java @@ -3,7 +3,7 @@ import cn.nukkit.utils.BlockColor; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class BlockTransparent extends Block { @@ -17,5 +17,4 @@ public boolean isTransparent() { public BlockColor getColor() { return BlockColor.TRANSPARENT_BLOCK_COLOR; } - } diff --git a/src/main/java/cn/nukkit/block/BlockTransparentMeta.java b/src/main/java/cn/nukkit/block/BlockTransparentMeta.java index 0ddf58d7a67..bc96d517fcb 100644 --- a/src/main/java/cn/nukkit/block/BlockTransparentMeta.java +++ b/src/main/java/cn/nukkit/block/BlockTransparentMeta.java @@ -3,7 +3,7 @@ import cn.nukkit.utils.BlockColor; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class BlockTransparentMeta extends BlockMeta { @@ -25,5 +25,4 @@ public boolean isTransparent() { public BlockColor getColor() { return BlockColor.TRANSPARENT_BLOCK_COLOR; } - } diff --git a/src/main/java/cn/nukkit/block/BlockTrapdoor.java b/src/main/java/cn/nukkit/block/BlockTrapdoor.java index bc6884b0d9b..dca2500b26b 100644 --- a/src/main/java/cn/nukkit/block/BlockTrapdoor.java +++ b/src/main/java/cn/nukkit/block/BlockTrapdoor.java @@ -7,10 +7,10 @@ import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemTool; import cn.nukkit.level.Level; +import cn.nukkit.level.Sound; import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.math.BlockFace; import cn.nukkit.math.SimpleAxisAlignedBB; -import cn.nukkit.network.protocol.LevelEventPacket; import cn.nukkit.utils.BlockColor; import cn.nukkit.utils.Faceable; @@ -22,6 +22,8 @@ public class BlockTrapdoor extends BlockTransparentMeta implements Faceable { public static final int TRAPDOOR_OPEN_BIT = 0x08; public static final int TRAPDOOR_TOP_BIT = 0x04; + private static final int[] FACES = {2, 1, 3, 0}; + public BlockTrapdoor() { this(0); } @@ -37,7 +39,7 @@ public int getId() { @Override public String getName() { - return "Wooden Trapdoor"; + return "Oak Trapdoor"; } @Override @@ -60,7 +62,7 @@ public int getToolType() { return ItemTool.TYPE_AXE; } - private static final AxisAlignedBB[] boundingBoxDamage = new AxisAlignedBB[16]; + private static final AxisAlignedBB[] BOUNDING_BOX_DAMAGE = new AxisAlignedBB[16]; static { for (int damage = 0; damage < 16; damage++) { @@ -126,12 +128,12 @@ public int getToolType() { ); } } - boundingBoxDamage[damage] = bb; + BOUNDING_BOX_DAMAGE[damage] = bb; } } private AxisAlignedBB getRelativeBoundingBox() { - return boundingBoxDamage[this.getDamage()]; + return BOUNDING_BOX_DAMAGE[this.getDamage()]; } @Override @@ -167,11 +169,16 @@ public double getMaxZ() { @Override public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_REDSTONE) { - if ((!isOpen() && this.level.isBlockPowered(this.getLocation())) || (isOpen() && !this.level.isBlockPowered(this.getLocation()))) { + boolean powered = this.level.isBlockPowered(this); + if ((!isOpen() && powered) || (isOpen() && !powered)) { this.level.getServer().getPluginManager().callEvent(new BlockRedstoneEvent(this, isOpen() ? 15 : 0, isOpen() ? 0 : 15)); this.setDamage(this.getDamage() ^ TRAPDOOR_OPEN_BIT); this.level.setBlock(this, this, true); - this.level.addLevelEvent(this.add(0.5, 0.5, 0.5), LevelEventPacket.EVENT_SOUND_DOOR); + if (this.isOpen()) { + this.level.addSound(this, Sound.RANDOM_DOOR_OPEN); + } else { + this.level.addSound(this, Sound.RANDOM_DOOR_CLOSE); + } return type; } } @@ -193,40 +200,41 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl top = face != BlockFace.UP; } - int[] faces = {2, 1, 3, 0}; - int faceBit = faces[facing.getHorizontalIndex()]; - meta |= faceBit; + meta |= FACES[facing.getHorizontalIndex()]; if (top) { meta |= TRAPDOOR_TOP_BIT; } + this.setDamage(meta); - this.getLevel().setBlock(block, this, true, true); + + this.getLevel().setBlock(this, this, true, true); return true; } @Override public Item toItem() { - return new ItemBlock(this, 0); + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override public boolean onActivate(Item item, Player player) { - if(toggle(player)) { - this.level.addLevelEvent(this.add(0.5, 0.5, 0.5), LevelEventPacket.EVENT_SOUND_DOOR); - return true; - } - return false; + return toggle(player); } public boolean toggle(Player player) { DoorToggleEvent ev = new DoorToggleEvent(this, player); - getLevel().getServer().getPluginManager().callEvent(ev); - if(ev.isCancelled()) { + level.getServer().getPluginManager().callEvent(ev); + if (ev.isCancelled()) { return false; } this.setDamage(this.getDamage() ^ TRAPDOOR_OPEN_BIT); - getLevel().setBlock(this, this, true); + level.setBlock(this, this, true, true); + if (this.isOpen()) { + this.level.addSound(this, Sound.RANDOM_DOOR_OPEN); + } else { + this.level.addSound(this, Sound.RANDOM_DOOR_CLOSE); + } return true; } @@ -245,6 +253,16 @@ public boolean isTop() { @Override public BlockFace getBlockFace() { - return BlockFace.fromHorizontalIndex(this.getDamage() & 0x07); + return BlockFace.fromHorizontalIndex(this.getDamage() & 0x7); + } + + @Override + public boolean canPassThrough() { + return this.isOpen(); + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; } } diff --git a/src/main/java/cn/nukkit/block/BlockTrapdoorAcacia.java b/src/main/java/cn/nukkit/block/BlockTrapdoorAcacia.java new file mode 100644 index 00000000000..ddaa2123418 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockTrapdoorAcacia.java @@ -0,0 +1,41 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.utils.BlockColor; + +public class BlockTrapdoorAcacia extends BlockTrapdoor { + + public BlockTrapdoorAcacia() { + this(0); + } + + public BlockTrapdoorAcacia(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Acacia Trapdoor"; + } + + @Override + public int getId() { + return ACACIA_TRAPDOOR; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public BlockColor getColor() { + return BlockColor.ORANGE_BLOCK_COLOR; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockTrapdoorBirch.java b/src/main/java/cn/nukkit/block/BlockTrapdoorBirch.java new file mode 100644 index 00000000000..0aced89bb68 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockTrapdoorBirch.java @@ -0,0 +1,36 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.utils.BlockColor; + +public class BlockTrapdoorBirch extends BlockTrapdoor { + + public BlockTrapdoorBirch() { + this(0); + } + + public BlockTrapdoorBirch(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Birch Trapdoor"; + } + + @Override + public int getId() { + return BIRCH_TRAPDOOR; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public BlockColor getColor() { + return BlockColor.SAND_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockTrapdoorDarkOak.java b/src/main/java/cn/nukkit/block/BlockTrapdoorDarkOak.java new file mode 100644 index 00000000000..b0fe6ef8e10 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockTrapdoorDarkOak.java @@ -0,0 +1,36 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.utils.BlockColor; + +public class BlockTrapdoorDarkOak extends BlockTrapdoor { + + public BlockTrapdoorDarkOak() { + this(0); + } + + public BlockTrapdoorDarkOak(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Dark Oak Trapdoor"; + } + + @Override + public int getId() { + return DARK_OAK_TRAPDOOR; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public BlockColor getColor() { + return BlockColor.BROWN_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockTrapdoorJungle.java b/src/main/java/cn/nukkit/block/BlockTrapdoorJungle.java new file mode 100644 index 00000000000..93c0c5464f6 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockTrapdoorJungle.java @@ -0,0 +1,36 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.utils.BlockColor; + +public class BlockTrapdoorJungle extends BlockTrapdoor { + + public BlockTrapdoorJungle() { + this(0); + } + + public BlockTrapdoorJungle(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Jungle Trapdoor"; + } + + @Override + public int getId() { + return JUNGLE_TRAPDOOR; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public BlockColor getColor() { + return BlockColor.DIRT_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockTrapdoorSpruce.java b/src/main/java/cn/nukkit/block/BlockTrapdoorSpruce.java new file mode 100644 index 00000000000..81ee2e6dc9d --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockTrapdoorSpruce.java @@ -0,0 +1,36 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.utils.BlockColor; + +public class BlockTrapdoorSpruce extends BlockTrapdoor { + + public BlockTrapdoorSpruce() { + this(0); + } + + public BlockTrapdoorSpruce(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Spruce Trapdoor"; + } + + @Override + public int getId() { + return SPRUCE_TRAPDOOR; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public BlockColor getColor() { + return BlockColor.SPRUCE_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockTrappedChest.java b/src/main/java/cn/nukkit/block/BlockTrappedChest.java index 6b4916c3699..88ea7931980 100644 --- a/src/main/java/cn/nukkit/block/BlockTrappedChest.java +++ b/src/main/java/cn/nukkit/block/BlockTrappedChest.java @@ -34,10 +34,8 @@ public String getName() { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - int[] faces = {2, 5, 3, 4}; - BlockEntityChest chest = null; - this.setDamage(faces[player != null ? player.getDirection().getHorizontalIndex() : 0]); + this.setDamage(Block.FACES2534[player != null ? player.getDirection().getHorizontalIndex() : 0]); for (BlockFace side : Plane.HORIZONTAL) { if ((this.getDamage() == 4 || this.getDamage() == 5) && (side == BlockFace.WEST || side == BlockFace.EAST)) { @@ -55,7 +53,8 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl } } - this.getLevel().setBlock(block, this, true, true); + this.getLevel().setBlock(this, this, true, true); + CompoundTag nbt = new CompoundTag("") .putList(new ListTag<>("Items")) .putString("id", BlockEntity.CHEST) @@ -74,11 +73,7 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl } } - BlockEntityChest blockEntity = (BlockEntityChest) BlockEntity.createBlockEntity(BlockEntity.CHEST, this.getLevel().getChunk((int) (this.x) >> 4, (int) (this.z) >> 4), nbt); - - if (blockEntity == null) { - return false; - } + BlockEntityChest blockEntity = (BlockEntityChest) BlockEntity.createBlockEntity(BlockEntity.CHEST, this.getChunk(), nbt); if (chest != null) { chest.pairWith(blockEntity); diff --git a/src/main/java/cn/nukkit/block/BlockTripWire.java b/src/main/java/cn/nukkit/block/BlockTripWire.java index 8d63ebf0564..e0a28186cd3 100644 --- a/src/main/java/cn/nukkit/block/BlockTripWire.java +++ b/src/main/java/cn/nukkit/block/BlockTripWire.java @@ -3,7 +3,6 @@ import cn.nukkit.Player; import cn.nukkit.entity.Entity; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemString; import cn.nukkit.level.Level; import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.math.BlockFace; @@ -31,21 +30,6 @@ public String getName() { return "Tripwire"; } - @Override - public boolean canPassThrough() { - return true; - } - - @Override - public double getResistance() { - return 0; - } - - @Override - public double getHardness() { - return 0; - } - @Override public AxisAlignedBB getBoundingBox() { return null; @@ -53,7 +37,7 @@ public AxisAlignedBB getBoundingBox() { @Override public Item toItem() { - return new ItemString(); + return Item.get(Item.STRING); } public boolean isPowered() { @@ -115,7 +99,7 @@ public void updateHook(boolean scheduleUpdate) { hook.calculateState(false, true, i, this); } - /*if(scheduleUpdate) { + /*if (scheduleUpdate) { this.level.scheduleUpdate(hook, 10); }*/ break; @@ -136,7 +120,8 @@ public int onUpdate(int type) { } boolean found = false; - for (Entity entity : this.level.getCollidingEntities(this.getCollisionBoundingBox())) { + Entity[] e = this.level.getCollidingEntities(this.getCollisionBoundingBox()); + for (Entity entity : e) { if (!entity.doesTriggerPressurePlate()) { continue; } @@ -190,4 +175,19 @@ public double getMaxY() { protected AxisAlignedBB recalculateCollisionBoundingBox() { return this; } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.FLOW_INTO_BLOCK; + } + + @Override + public boolean canBeFlowedInto() { + return false; + } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockTripWireHook.java b/src/main/java/cn/nukkit/block/BlockTripWireHook.java index c286e1be24c..73786b7f143 100644 --- a/src/main/java/cn/nukkit/block/BlockTripWireHook.java +++ b/src/main/java/cn/nukkit/block/BlockTripWireHook.java @@ -39,7 +39,7 @@ public BlockFace getFacing() { @Override public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_NORMAL) { - if (!this.getSide(this.getFacing().getOpposite()).isNormalBlock()) { + if (!isSupportValid(this.getSide(this.getFacing().getOpposite()))) { this.level.useBreakOn(this); } @@ -54,7 +54,7 @@ public int onUpdate(int type) { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - if (!this.getSide(face.getOpposite()).isNormalBlock() || face == BlockFace.DOWN || face == BlockFace.UP) { + if (face == BlockFace.DOWN || face == BlockFace.UP) { return false; } @@ -62,6 +62,10 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl this.setFace(face); } + if (!isSupportValid(this.getSide(this.getFacing().getOpposite()))) { + return false; + } + this.level.setBlock(this, this); if (player != null) { @@ -70,6 +74,10 @@ public boolean place(Item item, Block block, Block target, BlockFace face, doubl return true; } + private static boolean isSupportValid(Block block) { + return !block.isTransparent() || Block.canConnectToFullSolid(block); + } + @Override public boolean onBreak(Item item) { super.onBreak(item); @@ -82,7 +90,7 @@ public boolean onBreak(Item item) { if (powered) { this.level.updateAroundRedstone(this, null); - this.level.updateAroundRedstone(this.getLocation().getSide(getFacing().getOpposite()), null); + this.level.updateAroundRedstone(this.getSideVec(getFacing().getOpposite()), null); } return true; @@ -90,7 +98,6 @@ public boolean onBreak(Item item) { public void calculateState(boolean onBreak, boolean updateAround, int pos, Block block) { BlockFace facing = getFacing(); - Vector3 v = this.getLocation(); boolean attached = isAttached(); boolean powered = isPowered(); boolean canConnect = !onBreak; @@ -99,8 +106,7 @@ public void calculateState(boolean onBreak, boolean updateAround, int pos, Block Block[] blocks = new Block[42]; for (int i = 1; i < 42; ++i) { - Vector3 vector = v.getSide(facing, i); - Block b = this.level.getBlock(vector); + Block b = this.getSide(facing, i); if (b instanceof BlockTripWireHook) { if (((BlockTripWireHook) b).getFacing() == facing.getOpposite()) { @@ -133,36 +139,36 @@ public void calculateState(boolean onBreak, boolean updateAround, int pos, Block canConnect = canConnect & distance > 1; nextPowered = nextPowered & canConnect; - BlockTripWireHook hook = (BlockTripWireHook) Block.get(BlockID.TRIPWIRE_HOOK); + BlockTripWireHook hook = (BlockTripWireHook) Block.get(TRIPWIRE_HOOK); hook.setAttached(canConnect); hook.setPowered(nextPowered); if (distance > 0) { - Vector3 vec = v.getSide(facing, distance); + Vector3 vec = this.getSideVec(facing, distance); BlockFace face = facing.getOpposite(); hook.setFace(face); this.level.setBlock(vec, hook, true, false); this.level.updateAroundRedstone(vec, null); - this.level.updateAroundRedstone(vec.getSide(face.getOpposite()), null); + this.level.updateAroundRedstone(vec.getSideVec(face.getOpposite()), null); this.addSound(vec, canConnect, nextPowered, attached, powered); } - this.addSound(v, canConnect, nextPowered, attached, powered); + this.addSound(this, canConnect, nextPowered, attached, powered); if (!onBreak) { hook.setFace(facing); - this.level.setBlock(v, hook, true, false); + this.level.setBlock(this, hook, true, false); if (updateAround) { - this.level.updateAroundRedstone(v, null); - this.level.updateAroundRedstone(v.getSide(facing.getOpposite()), null); + this.level.updateAroundRedstone(this, null); + this.level.updateAroundRedstone(this.getSideVec(facing.getOpposite()), null); } } if (attached != canConnect) { for (int i = 1; i < distance; i++) { - Vector3 vc = v.getSide(facing, i); + Vector3 vc = this.getSideVec(facing, i); block = blocks[i]; if (block != null && this.level.getBlockIdAt(vc.getFloorX(), vc.getFloorY(), vc.getFloorZ()) != Block.AIR) { @@ -232,6 +238,21 @@ public int getStrongPower(BlockFace side) { @Override public Item toItem() { - return new ItemBlock(this, 0); + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.FLOW_INTO_BLOCK; + } + + @Override + public boolean canBeFlowedInto() { + return false; + } + + @Override + public boolean breakWhenPushed() { + return true; } } diff --git a/src/main/java/cn/nukkit/block/BlockTuff.java b/src/main/java/cn/nukkit/block/BlockTuff.java new file mode 100644 index 00000000000..c2491ae0925 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockTuff.java @@ -0,0 +1,51 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockTuff extends BlockSolid { + + public BlockTuff() { + // Does Nothing + } + + @Override + public String getName() { + return "Tuff"; + } + + @Override + public int getId() { + return TUFF; + } + + @Override + public double getHardness() { + return 1.5; + } + + @Override + public double getResistance() { + return 6; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_PICKAXE; + } + + @Override + public int getToolTier() { + return ItemTool.TIER_WOODEN; + } + + @Override + public BlockColor getColor() { + return BlockColor.GRAY_TERRACOTA_BLOCK_COLOR; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockTurtleEgg.java b/src/main/java/cn/nukkit/block/BlockTurtleEgg.java new file mode 100644 index 00000000000..5394b752141 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockTurtleEgg.java @@ -0,0 +1,111 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; + +public class BlockTurtleEgg extends BlockTransparentMeta { + + public BlockTurtleEgg() { + this(0); + } + + public BlockTurtleEgg(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Turtle Egg"; + } + + @Override + public int getId() { + return TURTLE_EGG; + } + + @Override + public double getResistance() { + return 0.5; + } + + @Override + public double getHardness() { + return 0.5; + } + + @Override + public boolean canHarvestWithHand() { + return false; + } + + @Override + public boolean canSilkTouch() { + return true; + } + + @Override + public Item[] getDrops(Item item) { + return new Item[0]; + } + + @Override + public double getMinX() { + return this.x + 0.2; + } + + @Override + public double getMinZ() { + return this.z + 0.2; + } + + @Override + public double getMaxX() { + return this.x + 0.8; + } + + @Override + public double getMaxY() { + return this.y + 0.45; + } + + @Override + public double getMaxZ() { + return this.z + 0.8; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + if (!canStayOnFullSolid(this.down())) { + this.getLevel().useBreakOn(this); + return Level.BLOCK_UPDATE_NORMAL; + } + } + return 0; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + if (target instanceof BlockTurtleEgg && this.getDamage() < 3) { + this.setDamage(this.getDamage() + 1); + return this.getLevel().setBlock(target, this, true, true); + } + if (!canStayOnFullSolid(this.down())) { + return false; + } + this.getLevel().setBlock(this, this, true, true); + return true; + } + + @Override + public boolean breakWhenPushed() { + return true; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockTypes.java b/src/main/java/cn/nukkit/block/BlockTypes.java new file mode 100644 index 00000000000..82b3d4f795d --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockTypes.java @@ -0,0 +1,714 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.material.BlockType; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import lombok.Data; + +public class BlockTypes { + + private static final Int2ObjectMap types = new Int2ObjectOpenHashMap<>(); + private static final Object2ObjectMap identifiers = new Object2ObjectOpenHashMap<>(); + + public static final BlockType AIR = register("minecraft:air", BlockID.AIR); + public static final BlockType STONE = register("minecraft:stone", BlockID.STONE); + public static final BlockType GRASS = register("minecraft:grass_block", BlockID.GRASS); + public static final BlockType GRASS_BLOCK = register("minecraft:grass_block", BlockID.GRASS_BLOCK); + public static final BlockType DIRT = register("minecraft:dirt", BlockID.DIRT); + public static final BlockType COBBLESTONE = register("minecraft:cobblestone", BlockID.COBBLESTONE); + public static final BlockType COBBLE = register("minecraft:cobblestone", BlockID.COBBLE); + public static final BlockType PLANK = register("minecraft:planks", BlockID.PLANK); + public static final BlockType PLANKS = register("minecraft:planks", BlockID.PLANKS); + public static final BlockType WOODEN_PLANK = register("minecraft:planks", BlockID.WOODEN_PLANK); + public static final BlockType WOODEN_PLANKS = register("minecraft:planks", BlockID.WOODEN_PLANKS); + public static final BlockType SAPLING = register("minecraft:sapling", BlockID.SAPLING); + public static final BlockType SAPLINGS = register("minecraft:sapling", BlockID.SAPLINGS); + public static final BlockType BEDROCK = register("minecraft:bedrock", BlockID.BEDROCK); + public static final BlockType WATER = register("minecraft:flowing_water", BlockID.WATER); + public static final BlockType STILL_WATER = register("minecraft:water", BlockID.STILL_WATER); + public static final BlockType LAVA = register("minecraft:flowing_lava", BlockID.LAVA); + public static final BlockType STILL_LAVA = register("minecraft:lava", BlockID.STILL_LAVA); + public static final BlockType SAND = register("minecraft:sand", BlockID.SAND); + public static final BlockType GRAVEL = register("minecraft:gravel", BlockID.GRAVEL); + public static final BlockType GOLD_ORE = register("minecraft:gold_ore", BlockID.GOLD_ORE); + public static final BlockType IRON_ORE = register("minecraft:iron_ore", BlockID.IRON_ORE); + public static final BlockType COAL_ORE = register("minecraft:coal_ore", BlockID.COAL_ORE); + public static final BlockType LOG = register("minecraft:log", BlockID.LOG); + public static final BlockType WOOD = register("minecraft:log", BlockID.WOOD); + public static final BlockType TRUNK = register("minecraft:log", BlockID.TRUNK); + public static final BlockType LEAVES = register("minecraft:leaves", BlockID.LEAVES); + public static final BlockType LEAVE = register("minecraft:leaves", BlockID.LEAVE); + public static final BlockType SPONGE = register("minecraft:sponge", BlockID.SPONGE); + public static final BlockType GLASS = register("minecraft:glass", BlockID.GLASS); + public static final BlockType LAPIS_ORE = register("minecraft:lapis_ore", BlockID.LAPIS_ORE); + public static final BlockType LAPIS_BLOCK = register("minecraft:lapis_block", BlockID.LAPIS_BLOCK); + public static final BlockType DISPENSER = register("minecraft:dispenser", BlockID.DISPENSER); + public static final BlockType SANDSTONE = register("minecraft:sandstone", BlockID.SANDSTONE); + public static final BlockType NOTEBLOCK = register("minecraft:noteblock", BlockID.NOTEBLOCK); + public static final BlockType BED_BLOCK = register("minecraft:item.bed", BlockID.BED_BLOCK); + public static final BlockType POWERED_RAIL = register("minecraft:golden_rail", BlockID.POWERED_RAIL); + public static final BlockType DETECTOR_RAIL = register("minecraft:detector_rail", BlockID.DETECTOR_RAIL); + public static final BlockType STICKY_PISTON = register("minecraft:sticky_piston", BlockID.STICKY_PISTON); + public static final BlockType COBWEB = register("minecraft:web", BlockID.COBWEB); + public static final BlockType WEB = register("minecraft:web", BlockID.WEB); + public static final BlockType TALL_GRASS = register("minecraft:tallgrass", BlockID.TALL_GRASS); + public static final BlockType BUSH = register("minecraft:deadbush", BlockID.BUSH); + public static final BlockType DEAD_BUSH = register("minecraft:deadbush", BlockID.DEAD_BUSH); + public static final BlockType DEADBUSH = register("minecraft:deadbush", BlockID.DEADBUSH); + public static final BlockType PISTON = register("minecraft:piston", BlockID.PISTON); + public static final BlockType PISTON_HEAD = register("minecraft:piston_arm_collision", BlockID.PISTON_HEAD); + public static final BlockType WOOL = register("minecraft:wool", BlockID.WOOL); + public static final BlockType WHITE_WOOL = register("minecraft:wool", BlockID.WHITE_WOOL); + public static final BlockType DANDELION = register("minecraft:yellow_flower", BlockID.DANDELION); + public static final BlockType POPPY = register("minecraft:red_flower", BlockID.POPPY); + public static final BlockType ROSE = register("minecraft:red_flower", BlockID.ROSE); + public static final BlockType FLOWER = register("minecraft:red_flower", BlockID.FLOWER); + public static final BlockType RED_FLOWER = register("minecraft:red_flower", BlockID.RED_FLOWER); + public static final BlockType BROWN_MUSHROOM = register("minecraft:brown_mushroom", BlockID.BROWN_MUSHROOM); + public static final BlockType RED_MUSHROOM = register("minecraft:red_mushroom", BlockID.RED_MUSHROOM); + public static final BlockType GOLD_BLOCK = register("minecraft:gold_block", BlockID.GOLD_BLOCK); + public static final BlockType IRON_BLOCK = register("minecraft:iron_block", BlockID.IRON_BLOCK); + public static final BlockType DOUBLE_SLAB = register("minecraft:double_stone_block_slab", BlockID.DOUBLE_SLAB); + public static final BlockType DOUBLE_STONE_SLAB = register("minecraft:double_stone_block_slab", BlockID.DOUBLE_STONE_SLAB); + public static final BlockType DOUBLE_SLABS = register("minecraft:double_stone_block_slab", BlockID.DOUBLE_SLABS); + public static final BlockType SLAB = register("minecraft:stone_block_slab", BlockID.SLAB); + public static final BlockType STONE_SLAB = register("minecraft:stone_block_slab", BlockID.STONE_SLAB); + public static final BlockType SLABS = register("minecraft:stone_block_slab", BlockID.SLABS); + public static final BlockType BRICKS = register("minecraft:brick_block", BlockID.BRICKS); + public static final BlockType BRICKS_BLOCK = register("minecraft:brick_block", BlockID.BRICKS_BLOCK); + public static final BlockType TNT = register("minecraft:tnt", BlockID.TNT); + public static final BlockType BOOKSHELF = register("minecraft:bookshelf", BlockID.BOOKSHELF); + public static final BlockType MOSS_STONE = register("minecraft:mossy_cobblestone", BlockID.MOSS_STONE); + public static final BlockType MOSSY_STONE = register("minecraft:mossy_cobblestone", BlockID.MOSSY_STONE); + public static final BlockType OBSIDIAN = register("minecraft:obsidian", BlockID.OBSIDIAN); + public static final BlockType TORCH = register("minecraft:torch", BlockID.TORCH); + public static final BlockType FIRE = register("minecraft:fire", BlockID.FIRE); + public static final BlockType MONSTER_SPAWNER = register("minecraft:mob_spawner", BlockID.MONSTER_SPAWNER); + public static final BlockType WOOD_STAIRS = register("minecraft:oak_stairs", BlockID.WOOD_STAIRS); + public static final BlockType WOODEN_STAIRS = register("minecraft:oak_stairs", BlockID.WOODEN_STAIRS); + public static final BlockType OAK_WOOD_STAIRS = register("minecraft:oak_stairs", BlockID.OAK_WOOD_STAIRS); + public static final BlockType OAK_WOODEN_STAIRS = register("minecraft:oak_stairs", BlockID.OAK_WOODEN_STAIRS); + public static final BlockType CHEST = register("minecraft:chest", BlockID.CHEST); + public static final BlockType REDSTONE_WIRE = register("minecraft:redstone_wire", BlockID.REDSTONE_WIRE); + public static final BlockType DIAMOND_ORE = register("minecraft:diamond_ore", BlockID.DIAMOND_ORE); + public static final BlockType DIAMOND_BLOCK = register("minecraft:diamond_block", BlockID.DIAMOND_BLOCK); + public static final BlockType CRAFTING_TABLE = register("minecraft:crafting_table", BlockID.CRAFTING_TABLE); + public static final BlockType WORKBENCH = register("minecraft:crafting_table", BlockID.WORKBENCH); + public static final BlockType WHEAT_BLOCK = register("minecraft:item.wheat", BlockID.WHEAT_BLOCK); + public static final BlockType FARMLAND = register("minecraft:farmland", BlockID.FARMLAND); + public static final BlockType FURNACE = register("minecraft:furnace", BlockID.FURNACE); + public static final BlockType BURNING_FURNACE = register("minecraft:lit_furnace", BlockID.BURNING_FURNACE); + public static final BlockType LIT_FURNACE = register("minecraft:lit_furnace", BlockID.LIT_FURNACE); + public static final BlockType SIGN_POST = register("minecraft:standing_sign", BlockID.SIGN_POST); + public static final BlockType DOOR_BLOCK = register("minecraft:item.wooden_door", BlockID.DOOR_BLOCK); + public static final BlockType WOODEN_DOOR_BLOCK = register("minecraft:item.wooden_door", BlockID.WOODEN_DOOR_BLOCK); + public static final BlockType WOOD_DOOR_BLOCK = register("minecraft:item.wooden_door", BlockID.WOOD_DOOR_BLOCK); + public static final BlockType LADDER = register("minecraft:ladder", BlockID.LADDER); + public static final BlockType RAIL = register("minecraft:rail", BlockID.RAIL); + public static final BlockType COBBLE_STAIRS = register("minecraft:stone_stairs", BlockID.COBBLE_STAIRS); + public static final BlockType COBBLESTONE_STAIRS = register("minecraft:stone_stairs", BlockID.COBBLESTONE_STAIRS); + public static final BlockType WALL_SIGN = register("minecraft:wall_sign", BlockID.WALL_SIGN); + public static final BlockType LEVER = register("minecraft:lever", BlockID.LEVER); + public static final BlockType STONE_PRESSURE_PLATE = register("minecraft:stone_pressure_plate", BlockID.STONE_PRESSURE_PLATE); + public static final BlockType IRON_DOOR_BLOCK = register("minecraft:item.iron_door", BlockID.IRON_DOOR_BLOCK); + public static final BlockType WOODEN_PRESSURE_PLATE = register("minecraft:wooden_pressure_plate", BlockID.WOODEN_PRESSURE_PLATE); + public static final BlockType REDSTONE_ORE = register("minecraft:redstone_ore", BlockID.REDSTONE_ORE); + public static final BlockType GLOWING_REDSTONE_ORE = register("minecraft:lit_redstone_ore", BlockID.GLOWING_REDSTONE_ORE); + public static final BlockType LIT_REDSTONE_ORE = register("minecraft:lit_redstone_ore", BlockID.LIT_REDSTONE_ORE); + public static final BlockType UNLIT_REDSTONE_TORCH = register("minecraft:unlit_redstone_torch", BlockID.UNLIT_REDSTONE_TORCH); + public static final BlockType REDSTONE_TORCH = register("minecraft:redstone_torch", BlockID.REDSTONE_TORCH); + public static final BlockType STONE_BUTTON = register("minecraft:stone_button", BlockID.STONE_BUTTON); + public static final BlockType SNOW = register("minecraft:snow_layer", BlockID.SNOW); + public static final BlockType SNOW_LAYER = register("minecraft:snow_layer", BlockID.SNOW_LAYER); + public static final BlockType ICE = register("minecraft:ice", BlockID.ICE); + public static final BlockType SNOW_BLOCK = register("minecraft:snow", BlockID.SNOW_BLOCK); + public static final BlockType CACTUS = register("minecraft:cactus", BlockID.CACTUS); + public static final BlockType CLAY_BLOCK = register("minecraft:clay", BlockID.CLAY_BLOCK); + public static final BlockType REEDS = register("minecraft:item.reeds", BlockID.REEDS); + public static final BlockType SUGARCANE_BLOCK = register("minecraft:item.reeds", BlockID.SUGARCANE_BLOCK); + public static final BlockType JUKEBOX = register("minecraft:jukebox", BlockID.JUKEBOX); + public static final BlockType FENCE = register("minecraft:fence", BlockID.FENCE); + public static final BlockType PUMPKIN = register("minecraft:pumpkin", BlockID.PUMPKIN); + public static final BlockType NETHERRACK = register("minecraft:netherrack", BlockID.NETHERRACK); + public static final BlockType SOUL_SAND = register("minecraft:soul_sand", BlockID.SOUL_SAND); + public static final BlockType GLOWSTONE = register("minecraft:glowstone", BlockID.GLOWSTONE); + public static final BlockType GLOWSTONE_BLOCK = register("minecraft:glowstone", BlockID.GLOWSTONE_BLOCK); + public static final BlockType NETHER_PORTAL = register("minecraft:portal", BlockID.NETHER_PORTAL); + public static final BlockType LIT_PUMPKIN = register("minecraft:lit_pumpkin", BlockID.LIT_PUMPKIN); + public static final BlockType JACK_O_LANTERN = register("minecraft:lit_pumpkin", BlockID.JACK_O_LANTERN); + public static final BlockType CAKE_BLOCK = register("minecraft:item.cake", BlockID.CAKE_BLOCK); + public static final BlockType UNPOWERED_REPEATER = register("minecraft:unpowered_repeater", BlockID.UNPOWERED_REPEATER); + public static final BlockType POWERED_REPEATER = register("minecraft:powered_repeater", BlockID.POWERED_REPEATER); + public static final BlockType INVISIBLE_BEDROCK = register("minecraft:invisible_bedrock", BlockID.INVISIBLE_BEDROCK); + public static final BlockType TRAPDOOR = register("minecraft:trapdoor", BlockID.TRAPDOOR); + public static final BlockType MONSTER_EGG = register("minecraft:monster_egg", BlockID.MONSTER_EGG); + public static final BlockType STONE_BRICKS = register("minecraft:stonebrick", BlockID.STONE_BRICKS); + public static final BlockType STONE_BRICK = register("minecraft:stonebrick", BlockID.STONE_BRICK); + public static final BlockType BROWN_MUSHROOM_BLOCK = register("minecraft:brown_mushroom_block", BlockID.BROWN_MUSHROOM_BLOCK); + public static final BlockType RED_MUSHROOM_BLOCK = register("minecraft:red_mushroom_block", BlockID.RED_MUSHROOM_BLOCK); + public static final BlockType IRON_BAR = register("minecraft:iron_bars", BlockID.IRON_BAR); + public static final BlockType IRON_BARS = register("minecraft:iron_bars", BlockID.IRON_BARS); + public static final BlockType GLASS_PANE = register("minecraft:glass_pane", BlockID.GLASS_PANE); + public static final BlockType GLASS_PANEL = register("minecraft:glass_pane", BlockID.GLASS_PANEL); + public static final BlockType MELON_BLOCK = register("minecraft:melon_block", BlockID.MELON_BLOCK); + public static final BlockType PUMPKIN_STEM = register("minecraft:pumpkin_stem", BlockID.PUMPKIN_STEM); + public static final BlockType MELON_STEM = register("minecraft:melon_stem", BlockID.MELON_STEM); + public static final BlockType VINE = register("minecraft:vine", BlockID.VINE); + public static final BlockType VINES = register("minecraft:vine", BlockID.VINES); + public static final BlockType FENCE_GATE = register("minecraft:fence_gate", BlockID.FENCE_GATE); + public static final BlockType FENCE_GATE_OAK = register("minecraft:fence_gate", BlockID.FENCE_GATE_OAK); + public static final BlockType BRICK_STAIRS = register("minecraft:brick_stairs", BlockID.BRICK_STAIRS); + public static final BlockType STONE_BRICK_STAIRS = register("minecraft:stone_brick_stairs", BlockID.STONE_BRICK_STAIRS); + public static final BlockType MYCELIUM = register("minecraft:mycelium", BlockID.MYCELIUM); + public static final BlockType WATER_LILY = register("minecraft:waterlily", BlockID.WATER_LILY); + public static final BlockType WATERLILY = register("minecraft:waterlily", BlockID.WATERLILY); + public static final BlockType LILY_PAD = register("minecraft:waterlily", BlockID.LILY_PAD); + public static final BlockType NETHER_BRICKS = register("minecraft:nether_brick", BlockID.NETHER_BRICKS); + public static final BlockType NETHER_BRICK_BLOCK = register("minecraft:nether_brick", BlockID.NETHER_BRICK_BLOCK); + public static final BlockType NETHER_BRICK_FENCE = register("minecraft:nether_brick_fence", BlockID.NETHER_BRICK_FENCE); + public static final BlockType NETHER_BRICKS_STAIRS = register("minecraft:nether_brick_stairs", BlockID.NETHER_BRICKS_STAIRS); + public static final BlockType NETHER_WART_BLOCK = register("minecraft:item.nether_wart", BlockID.NETHER_WART_BLOCK); + public static final BlockType ENCHANTING_TABLE = register("minecraft:enchanting_table", BlockID.ENCHANTING_TABLE); + public static final BlockType ENCHANT_TABLE = register("minecraft:enchanting_table", BlockID.ENCHANT_TABLE); + public static final BlockType ENCHANTMENT_TABLE = register("minecraft:enchanting_table", BlockID.ENCHANTMENT_TABLE); + public static final BlockType BREWING_STAND_BLOCK = register("minecraft:brewingstandblock", BlockID.BREWING_STAND_BLOCK); + public static final BlockType BREWING_BLOCK = register("minecraft:brewingstandblock", BlockID.BREWING_BLOCK); + public static final BlockType CAULDRON_BLOCK = register("minecraft:item.cauldron", BlockID.CAULDRON_BLOCK); + public static final BlockType END_PORTAL = register("minecraft:end_portal", BlockID.END_PORTAL); + public static final BlockType END_PORTAL_FRAME = register("minecraft:end_portal_frame", BlockID.END_PORTAL_FRAME); + public static final BlockType END_STONE = register("minecraft:end_stone", BlockID.END_STONE); + public static final BlockType DRAGON_EGG = register("minecraft:dragon_egg", BlockID.DRAGON_EGG); + public static final BlockType REDSTONE_LAMP = register("minecraft:redstone_lamp", BlockID.REDSTONE_LAMP); + public static final BlockType LIT_REDSTONE_LAMP = register("minecraft:lit_redstone_lamp", BlockID.LIT_REDSTONE_LAMP); + public static final BlockType DROPPER = register("minecraft:dropper", BlockID.DROPPER); + public static final BlockType ACTIVATOR_RAIL = register("minecraft:activator_rail", BlockID.ACTIVATOR_RAIL); + public static final BlockType COCOA = register("minecraft:cocoa", BlockID.COCOA); + public static final BlockType COCOA_BLOCK = register("minecraft:cocoa", BlockID.COCOA_BLOCK); + public static final BlockType SANDSTONE_STAIRS = register("minecraft:sandstone_stairs", BlockID.SANDSTONE_STAIRS); + public static final BlockType EMERALD_ORE = register("minecraft:emerald_ore", BlockID.EMERALD_ORE); + public static final BlockType ENDER_CHEST = register("minecraft:ender_chest", BlockID.ENDER_CHEST); + public static final BlockType TRIPWIRE_HOOK = register("minecraft:tripwire_hook", BlockID.TRIPWIRE_HOOK); + public static final BlockType TRIPWIRE = register("minecraft:trip_wire", BlockID.TRIPWIRE); + public static final BlockType EMERALD_BLOCK = register("minecraft:emerald_block", BlockID.EMERALD_BLOCK); + public static final BlockType SPRUCE_WOOD_STAIRS = register("minecraft:spruce_stairs", BlockID.SPRUCE_WOOD_STAIRS); + public static final BlockType SPRUCE_WOODEN_STAIRS = register("minecraft:spruce_stairs", BlockID.SPRUCE_WOODEN_STAIRS); + public static final BlockType BIRCH_WOOD_STAIRS = register("minecraft:birch_stairs", BlockID.BIRCH_WOOD_STAIRS); + public static final BlockType BIRCH_WOODEN_STAIRS = register("minecraft:birch_stairs", BlockID.BIRCH_WOODEN_STAIRS); + public static final BlockType JUNGLE_WOOD_STAIRS = register("minecraft:jungle_stairs", BlockID.JUNGLE_WOOD_STAIRS); + public static final BlockType JUNGLE_WOODEN_STAIRS = register("minecraft:jungle_stairs", BlockID.JUNGLE_WOODEN_STAIRS); + public static final BlockType COMMAND_BLOCK = register("minecraft:command_block", BlockID.COMMAND_BLOCK); + public static final BlockType BEACON = register("minecraft:beacon", BlockID.BEACON); + public static final BlockType COBBLE_WALL = register("minecraft:cobblestone_wall", BlockID.COBBLE_WALL); + public static final BlockType STONE_WALL = register("minecraft:cobblestone_wall", BlockID.STONE_WALL); + public static final BlockType COBBLESTONE_WALL = register("minecraft:cobblestone_wall", BlockID.COBBLESTONE_WALL); + public static final BlockType FLOWER_POT_BLOCK = register("minecraft:item.flower_pot", BlockID.FLOWER_POT_BLOCK); + public static final BlockType CARROT_BLOCK = register("minecraft:carrots", BlockID.CARROT_BLOCK); + public static final BlockType POTATO_BLOCK = register("minecraft:potatoes", BlockID.POTATO_BLOCK); + public static final BlockType WOODEN_BUTTON = register("minecraft:wooden_button", BlockID.WOODEN_BUTTON); + public static final BlockType SKULL_BLOCK = register("minecraft:item.skull", BlockID.SKULL_BLOCK); + public static final BlockType ANVIL = register("minecraft:anvil", BlockID.ANVIL); + public static final BlockType TRAPPED_CHEST = register("minecraft:trapped_chest", BlockID.TRAPPED_CHEST); + public static final BlockType LIGHT_WEIGHTED_PRESSURE_PLATE = register("minecraft:light_weighted_pressure_plate", BlockID.LIGHT_WEIGHTED_PRESSURE_PLATE); + public static final BlockType HEAVY_WEIGHTED_PRESSURE_PLATE = register("minecraft:heavy_weighted_pressure_plate", BlockID.HEAVY_WEIGHTED_PRESSURE_PLATE); + public static final BlockType UNPOWERED_COMPARATOR = register("minecraft:unpowered_comparator", BlockID.UNPOWERED_COMPARATOR); + public static final BlockType POWERED_COMPARATOR = register("minecraft:powered_comparator", BlockID.POWERED_COMPARATOR); + public static final BlockType DAYLIGHT_DETECTOR = register("minecraft:daylight_detector", BlockID.DAYLIGHT_DETECTOR); + public static final BlockType REDSTONE_BLOCK = register("minecraft:redstone_block", BlockID.REDSTONE_BLOCK); + public static final BlockType QUARTZ_ORE = register("minecraft:quartz_ore", BlockID.QUARTZ_ORE); + public static final BlockType HOPPER_BLOCK = register("minecraft:item.hopper", BlockID.HOPPER_BLOCK); + public static final BlockType QUARTZ_BLOCK = register("minecraft:quartz_block", BlockID.QUARTZ_BLOCK); + public static final BlockType QUARTZ_STAIRS = register("minecraft:quartz_stairs", BlockID.QUARTZ_STAIRS); + public static final BlockType DOUBLE_WOOD_SLAB = register("minecraft:double_wooden_slab", BlockID.DOUBLE_WOOD_SLAB); + public static final BlockType DOUBLE_WOODEN_SLAB = register("minecraft:double_wooden_slab", BlockID.DOUBLE_WOODEN_SLAB); + public static final BlockType DOUBLE_WOOD_SLABS = register("minecraft:double_wooden_slab", BlockID.DOUBLE_WOOD_SLABS); + public static final BlockType DOUBLE_WOODEN_SLABS = register("minecraft:double_wooden_slab", BlockID.DOUBLE_WOODEN_SLABS); + public static final BlockType WOOD_SLAB = register("minecraft:wooden_slab", BlockID.WOOD_SLAB); + public static final BlockType WOODEN_SLAB = register("minecraft:wooden_slab", BlockID.WOODEN_SLAB); + public static final BlockType WOOD_SLABS = register("minecraft:wooden_slab", BlockID.WOOD_SLABS); + public static final BlockType WOODEN_SLABS = register("minecraft:wooden_slab", BlockID.WOODEN_SLABS); + public static final BlockType STAINED_TERRACOTTA = register("minecraft:stained_hardened_clay", BlockID.STAINED_TERRACOTTA); + public static final BlockType STAINED_HARDENED_CLAY = register("minecraft:stained_hardened_clay", BlockID.STAINED_HARDENED_CLAY); + public static final BlockType STAINED_GLASS_PANE = register("minecraft:stained_glass_pane", BlockID.STAINED_GLASS_PANE); + public static final BlockType LEAVES2 = register("minecraft:leaves2", BlockID.LEAVES2); + public static final BlockType LEAVE2 = register("minecraft:leaves2", BlockID.LEAVE2); + public static final BlockType WOOD2 = register("minecraft:log2", BlockID.WOOD2); + public static final BlockType TRUNK2 = register("minecraft:log2", BlockID.TRUNK2); + public static final BlockType LOG2 = register("minecraft:log2", BlockID.LOG2); + public static final BlockType ACACIA_WOOD_STAIRS = register("minecraft:acacia_stairs", BlockID.ACACIA_WOOD_STAIRS); + public static final BlockType ACACIA_WOODEN_STAIRS = register("minecraft:acacia_stairs", BlockID.ACACIA_WOODEN_STAIRS); + public static final BlockType DARK_OAK_WOOD_STAIRS = register("minecraft:dark_oak_stairs", BlockID.DARK_OAK_WOOD_STAIRS); + public static final BlockType DARK_OAK_WOODEN_STAIRS = register("minecraft:dark_oak_stairs", BlockID.DARK_OAK_WOODEN_STAIRS); + public static final BlockType SLIME_BLOCK = register("minecraft:slime", BlockID.SLIME_BLOCK); + public static final BlockType SLIME = register("minecraft:slime", BlockID.SLIME); + public static final BlockType IRON_TRAPDOOR = register("minecraft:iron_trapdoor", BlockID.IRON_TRAPDOOR); + public static final BlockType PRISMARINE = register("minecraft:prismarine", BlockID.PRISMARINE); + public static final BlockType SEA_LANTERN = register("minecraft:sea_lantern", BlockID.SEA_LANTERN); + public static final BlockType HAY_BALE = register("minecraft:hay_block", BlockID.HAY_BALE); + public static final BlockType HAY_BLOCK = register("minecraft:hay_block", BlockID.HAY_BLOCK); + public static final BlockType CARPET = register("minecraft:carpet", BlockID.CARPET); + public static final BlockType TERRACOTTA = register("minecraft:hardened_clay", BlockID.TERRACOTTA); + public static final BlockType HARDENED_CLAY = register("minecraft:hardened_clay", BlockID.HARDENED_CLAY); + public static final BlockType COAL_BLOCK = register("minecraft:coal_block", BlockID.COAL_BLOCK); + public static final BlockType PACKED_ICE = register("minecraft:packed_ice", BlockID.PACKED_ICE); + public static final BlockType DOUBLE_PLANT = register("minecraft:double_plant", BlockID.DOUBLE_PLANT); + public static final BlockType STANDING_BANNER = register("minecraft:standing_banner", BlockID.STANDING_BANNER); + public static final BlockType WALL_BANNER = register("minecraft:wall_banner", BlockID.WALL_BANNER); + public static final BlockType DAYLIGHT_DETECTOR_INVERTED = register("minecraft:daylight_detector_inverted", BlockID.DAYLIGHT_DETECTOR_INVERTED); + public static final BlockType RED_SANDSTONE = register("minecraft:red_sandstone", BlockID.RED_SANDSTONE); + public static final BlockType RED_SANDSTONE_STAIRS = register("minecraft:red_sandstone_stairs", BlockID.RED_SANDSTONE_STAIRS); + public static final BlockType DOUBLE_RED_SANDSTONE_SLAB = register("minecraft:double_stone_block_slab2", BlockID.DOUBLE_RED_SANDSTONE_SLAB); + public static final BlockType RED_SANDSTONE_SLAB = register("minecraft:stone_block_slab2", BlockID.RED_SANDSTONE_SLAB); + public static final BlockType FENCE_GATE_SPRUCE = register("minecraft:spruce_fence_gate", BlockID.FENCE_GATE_SPRUCE); + public static final BlockType FENCE_GATE_BIRCH = register("minecraft:birch_fence_gate", BlockID.FENCE_GATE_BIRCH); + public static final BlockType FENCE_GATE_JUNGLE = register("minecraft:jungle_fence_gate", BlockID.FENCE_GATE_JUNGLE); + public static final BlockType FENCE_GATE_DARK_OAK = register("minecraft:dark_oak_fence_gate", BlockID.FENCE_GATE_DARK_OAK); + public static final BlockType FENCE_GATE_ACACIA = register("minecraft:acacia_fence_gate", BlockID.FENCE_GATE_ACACIA); + public static final BlockType REPEATING_COMMAND_BLOCK = register("minecraft:repeating_command_block", BlockID.REPEATING_COMMAND_BLOCK); + public static final BlockType CHAIN_COMMAND_BLOCK = register("minecraft:chain_command_block", BlockID.CHAIN_COMMAND_BLOCK); + public static final BlockType SPRUCE_DOOR_BLOCK = register("minecraft:item.spruce_door", BlockID.SPRUCE_DOOR_BLOCK); + public static final BlockType BIRCH_DOOR_BLOCK = register("minecraft:item.birch_door", BlockID.BIRCH_DOOR_BLOCK); + public static final BlockType JUNGLE_DOOR_BLOCK = register("minecraft:item.jungle_door", BlockID.JUNGLE_DOOR_BLOCK); + public static final BlockType ACACIA_DOOR_BLOCK = register("minecraft:item.acacia_door", BlockID.ACACIA_DOOR_BLOCK); + public static final BlockType DARK_OAK_DOOR_BLOCK = register("minecraft:item.dark_oak_door", BlockID.DARK_OAK_DOOR_BLOCK); + public static final BlockType GRASS_PATH = register("minecraft:grass_path", BlockID.GRASS_PATH); + public static final BlockType ITEM_FRAME_BLOCK = register("minecraft:item.frame", BlockID.ITEM_FRAME_BLOCK); + public static final BlockType CHORUS_FLOWER = register("minecraft:chorus_flower", BlockID.CHORUS_FLOWER); + public static final BlockType PURPUR_BLOCK = register("minecraft:purpur_block", BlockID.PURPUR_BLOCK); + public static final BlockType PURPUR_STAIRS = register("minecraft:purpur_stairs", BlockID.PURPUR_STAIRS); + public static final BlockType UNDYED_SHULKER_BOX = register("minecraft:undyed_shulker_box", BlockID.UNDYED_SHULKER_BOX); + public static final BlockType END_BRICKS = register("minecraft:end_bricks", BlockID.END_BRICKS); + public static final BlockType FROSTED_ICE = register("minecraft:frosted_ice", BlockID.FROSTED_ICE); + public static final BlockType ICE_FROSTED = register("minecraft:frosted_ice", BlockID.ICE_FROSTED); + public static final BlockType END_ROD = register("minecraft:end_rod", BlockID.END_ROD); + public static final BlockType END_GATEWAY = register("minecraft:end_gateway", BlockID.END_GATEWAY); + public static final BlockType ALLOW = register("minecraft:allow", BlockID.ALLOW); + public static final BlockType DENY = register("minecraft:deny", BlockID.DENY); + public static final BlockType BORDER_BLOCK = register("minecraft:border_block", BlockID.BORDER_BLOCK); + public static final BlockType MAGMA = register("minecraft:magma", BlockID.MAGMA); + public static final BlockType BLOCK_NETHER_WART_BLOCK = register("minecraft:nether_wart_block", BlockID.BLOCK_NETHER_WART_BLOCK); + public static final BlockType RED_NETHER_BRICK = register("minecraft:red_nether_brick", BlockID.RED_NETHER_BRICK); + public static final BlockType BONE_BLOCK = register("minecraft:bone_block", BlockID.BONE_BLOCK); + public static final BlockType SHULKER_BOX = register("minecraft:shulker_box", BlockID.SHULKER_BOX); + public static final BlockType PURPLE_GLAZED_TERRACOTTA = register("minecraft:purple_glazed_terracotta", BlockID.PURPLE_GLAZED_TERRACOTTA); + public static final BlockType WHITE_GLAZED_TERRACOTTA = register("minecraft:white_glazed_terracotta", BlockID.WHITE_GLAZED_TERRACOTTA); + public static final BlockType ORANGE_GLAZED_TERRACOTTA = register("minecraft:orange_glazed_terracotta", BlockID.ORANGE_GLAZED_TERRACOTTA); + public static final BlockType MAGENTA_GLAZED_TERRACOTTA = register("minecraft:magenta_glazed_terracotta", BlockID.MAGENTA_GLAZED_TERRACOTTA); + public static final BlockType LIGHT_BLUE_GLAZED_TERRACOTTA = register("minecraft:light_blue_glazed_terracotta", BlockID.LIGHT_BLUE_GLAZED_TERRACOTTA); + public static final BlockType YELLOW_GLAZED_TERRACOTTA = register("minecraft:yellow_glazed_terracotta", BlockID.YELLOW_GLAZED_TERRACOTTA); + public static final BlockType LIME_GLAZED_TERRACOTTA = register("minecraft:lime_glazed_terracotta", BlockID.LIME_GLAZED_TERRACOTTA); + public static final BlockType PINK_GLAZED_TERRACOTTA = register("minecraft:pink_glazed_terracotta", BlockID.PINK_GLAZED_TERRACOTTA); + public static final BlockType GRAY_GLAZED_TERRACOTTA = register("minecraft:gray_glazed_terracotta", BlockID.GRAY_GLAZED_TERRACOTTA); + public static final BlockType SILVER_GLAZED_TERRACOTTA = register("minecraft:silver_glazed_terracotta", BlockID.SILVER_GLAZED_TERRACOTTA); + public static final BlockType CYAN_GLAZED_TERRACOTTA = register("minecraft:cyan_glazed_terracotta", BlockID.CYAN_GLAZED_TERRACOTTA); + public static final BlockType BLUE_GLAZED_TERRACOTTA = register("minecraft:blue_glazed_terracotta", BlockID.BLUE_GLAZED_TERRACOTTA); + public static final BlockType BROWN_GLAZED_TERRACOTTA = register("minecraft:brown_glazed_terracotta", BlockID.BROWN_GLAZED_TERRACOTTA); + public static final BlockType GREEN_GLAZED_TERRACOTTA = register("minecraft:green_glazed_terracotta", BlockID.GREEN_GLAZED_TERRACOTTA); + public static final BlockType RED_GLAZED_TERRACOTTA = register("minecraft:red_glazed_terracotta", BlockID.RED_GLAZED_TERRACOTTA); + public static final BlockType BLACK_GLAZED_TERRACOTTA = register("minecraft:black_glazed_terracotta", BlockID.BLACK_GLAZED_TERRACOTTA); + public static final BlockType CONCRETE = register("minecraft:concrete", BlockID.CONCRETE); + public static final BlockType CONCRETE_POWDER = register("minecraft:concrete_powder", BlockID.CONCRETE_POWDER); + public static final BlockType CHORUS_PLANT = register("minecraft:chorus_plant", BlockID.CHORUS_PLANT); + public static final BlockType STAINED_GLASS = register("minecraft:stained_glass", BlockID.STAINED_GLASS); + public static final BlockType CAMERA_BLOCK = register("minecraft:item.camera", BlockID.CAMERA_BLOCK); + public static final BlockType PODZOL = register("minecraft:podzol", BlockID.PODZOL); + public static final BlockType BEETROOT_BLOCK = register("minecraft:item.beetroot", BlockID.BEETROOT_BLOCK); + public static final BlockType STONECUTTER = register("minecraft:stonecutter", BlockID.STONECUTTER); + public static final BlockType GLOWING_OBSIDIAN = register("minecraft:glowingobsidian", BlockID.GLOWING_OBSIDIAN); + public static final BlockType NETHER_REACTOR = register("minecraft:netherreactor", BlockID.NETHER_REACTOR); + public static final BlockType INFO_UPDATE = register("minecraft:info_update", BlockID.INFO_UPDATE); + public static final BlockType INFO_UPDATE2 = register("minecraft:info_update2", BlockID.INFO_UPDATE2); + public static final BlockType PISTON_EXTENSION = register("minecraft:moving_block", BlockID.PISTON_EXTENSION); + public static final BlockType MOVING_BLOCK = register("minecraft:moving_block", BlockID.MOVING_BLOCK); + public static final BlockType OBSERVER = register("minecraft:observer", BlockID.OBSERVER); + public static final BlockType STRUCTURE_BLOCK = register("minecraft:structure_block", BlockID.STRUCTURE_BLOCK); + public static final BlockType RESERVED6 = register("minecraft:reserved6", BlockID.RESERVED6); + public static final BlockType PRISMARINE_STAIRS = register("minecraft:prismarine_stairs", BlockID.PRISMARINE_STAIRS); + public static final BlockType DARK_PRISMARINE_STAIRS = register("minecraft:dark_prismarine_stairs", BlockID.DARK_PRISMARINE_STAIRS); + public static final BlockType PRISMARINE_BRICKS_STAIRS = register("minecraft:prismarine_bricks_stairs", BlockID.PRISMARINE_BRICKS_STAIRS); + public static final BlockType STRIPPED_SPRUCE_LOG = register("minecraft:stripped_spruce_log", BlockID.STRIPPED_SPRUCE_LOG); + public static final BlockType STRIPPED_BIRCH_LOG = register("minecraft:stripped_birch_log", BlockID.STRIPPED_BIRCH_LOG); + public static final BlockType STRIPPED_JUNGLE_LOG = register("minecraft:stripped_jungle_log", BlockID.STRIPPED_JUNGLE_LOG); + public static final BlockType STRIPPED_ACACIA_LOG = register("minecraft:stripped_acacia_log", BlockID.STRIPPED_ACACIA_LOG); + public static final BlockType STRIPPED_DARK_OAK_LOG = register("minecraft:stripped_dark_oak_log", BlockID.STRIPPED_DARK_OAK_LOG); + public static final BlockType STRIPPED_OAK_LOG = register("minecraft:stripped_oak_log", BlockID.STRIPPED_OAK_LOG); + public static final BlockType BLUE_ICE = register("minecraft:blue_ice", BlockID.BLUE_ICE); + public static final BlockType SEAGRASS = register("minecraft:seagrass", BlockID.SEAGRASS); + public static final BlockType CORAL = register("minecraft:coral", BlockID.CORAL); + public static final BlockType CORAL_BLOCK = register("minecraft:coral_block", BlockID.CORAL_BLOCK); + public static final BlockType CORAL_FAN = register("minecraft:coral_fan", BlockID.CORAL_FAN); + public static final BlockType CORAL_FAN_DEAD = register("minecraft:coral_fan_dead", BlockID.CORAL_FAN_DEAD); + public static final BlockType CORAL_FAN_HANG = register("minecraft:coral_fan_hang", BlockID.CORAL_FAN_HANG); + public static final BlockType CORAL_FAN_HANG2 = register("minecraft:coral_fan_hang2", BlockID.CORAL_FAN_HANG2); + public static final BlockType CORAL_FAN_HANG3 = register("minecraft:coral_fan_hang3", BlockID.CORAL_FAN_HANG3); + public static final BlockType BLOCK_KELP = register("minecraft:item.kelp", BlockID.BLOCK_KELP); + public static final BlockType DRIED_KELP_BLOCK = register("minecraft:dried_kelp_block", BlockID.DRIED_KELP_BLOCK); + public static final BlockType ACACIA_BUTTON = register("minecraft:acacia_button", BlockID.ACACIA_BUTTON); + public static final BlockType BIRCH_BUTTON = register("minecraft:birch_button", BlockID.BIRCH_BUTTON); + public static final BlockType DARK_OAK_BUTTON = register("minecraft:dark_oak_button", BlockID.DARK_OAK_BUTTON); + public static final BlockType JUNGLE_BUTTON = register("minecraft:jungle_button", BlockID.JUNGLE_BUTTON); + public static final BlockType SPRUCE_BUTTON = register("minecraft:spruce_button", BlockID.SPRUCE_BUTTON); + public static final BlockType ACACIA_TRAPDOOR = register("minecraft:acacia_trapdoor", BlockID.ACACIA_TRAPDOOR); + public static final BlockType BIRCH_TRAPDOOR = register("minecraft:birch_trapdoor", BlockID.BIRCH_TRAPDOOR); + public static final BlockType DARK_OAK_TRAPDOOR = register("minecraft:dark_oak_trapdoor", BlockID.DARK_OAK_TRAPDOOR); + public static final BlockType JUNGLE_TRAPDOOR = register("minecraft:jungle_trapdoor", BlockID.JUNGLE_TRAPDOOR); + public static final BlockType SPRUCE_TRAPDOOR = register("minecraft:spruce_trapdoor", BlockID.SPRUCE_TRAPDOOR); + public static final BlockType ACACIA_PRESSURE_PLATE = register("minecraft:acacia_pressure_plate", BlockID.ACACIA_PRESSURE_PLATE); + public static final BlockType BIRCH_PRESSURE_PLATE = register("minecraft:birch_pressure_plate", BlockID.BIRCH_PRESSURE_PLATE); + public static final BlockType DARK_OAK_PRESSURE_PLATE = register("minecraft:dark_oak_pressure_plate", BlockID.DARK_OAK_PRESSURE_PLATE); + public static final BlockType JUNGLE_PRESSURE_PLATE = register("minecraft:jungle_pressure_plate", BlockID.JUNGLE_PRESSURE_PLATE); + public static final BlockType SPRUCE_PRESSURE_PLATE = register("minecraft:spruce_pressure_plate", BlockID.SPRUCE_PRESSURE_PLATE); + public static final BlockType CARVED_PUMPKIN = register("minecraft:carved_pumpkin", BlockID.CARVED_PUMPKIN); + public static final BlockType SEA_PICKLE = register("minecraft:sea_pickle", BlockID.SEA_PICKLE); + public static final BlockType CONDUIT = register("minecraft:conduit", BlockID.CONDUIT); + public static final BlockType TURTLE_EGG = register("minecraft:turtle_egg", BlockID.TURTLE_EGG); + public static final BlockType BUBBLE_COLUMN = register("minecraft:bubble_column", BlockID.BUBBLE_COLUMN); + public static final BlockType BARRIER = register("minecraft:barrier", BlockID.BARRIER); + public static final BlockType STONE_SLAB3 = register("minecraft:stone_block_slab3", BlockID.STONE_SLAB3); + public static final BlockType BAMBOO = register("minecraft:bamboo", BlockID.BAMBOO); + public static final BlockType BAMBOO_SAPLING = register("minecraft:bamboo_sapling", BlockID.BAMBOO_SAPLING); + public static final BlockType SCAFFOLDING = register("minecraft:scaffolding", BlockID.SCAFFOLDING); + public static final BlockType STONE_SLAB4 = register("minecraft:stone_block_slab4", BlockID.STONE_SLAB4); + public static final BlockType DOUBLE_STONE_SLAB3 = register("minecraft:double_stone_block_slab3", BlockID.DOUBLE_STONE_SLAB3); + public static final BlockType DOUBLE_STONE_SLAB4 = register("minecraft:double_stone_block_slab4", BlockID.DOUBLE_STONE_SLAB4); + public static final BlockType GRANITE_STAIRS = register("minecraft:granite_stairs", BlockID.GRANITE_STAIRS); + public static final BlockType DIORITE_STAIRS = register("minecraft:diorite_stairs", BlockID.DIORITE_STAIRS); + public static final BlockType ANDESITE_STAIRS = register("minecraft:andesite_stairs", BlockID.ANDESITE_STAIRS); + public static final BlockType POLISHED_GRANITE_STAIRS = register("minecraft:polished_granite_stairs", BlockID.POLISHED_GRANITE_STAIRS); + public static final BlockType POLISHED_DIORITE_STAIRS = register("minecraft:polished_diorite_stairs", BlockID.POLISHED_DIORITE_STAIRS); + public static final BlockType POLISHED_ANDESITE_STAIRS = register("minecraft:polished_andesite_stairs", BlockID.POLISHED_ANDESITE_STAIRS); + public static final BlockType MOSSY_STONE_BRICK_STAIRS = register("minecraft:mossy_stone_brick_stairs", BlockID.MOSSY_STONE_BRICK_STAIRS); + public static final BlockType SMOOTH_RED_SANDSTONE_STAIRS = register("minecraft:smooth_red_sandstone_stairs", BlockID.SMOOTH_RED_SANDSTONE_STAIRS); + public static final BlockType SMOOTH_SANDSTONE_STAIRS = register("minecraft:smooth_sandstone_stairs", BlockID.SMOOTH_SANDSTONE_STAIRS); + public static final BlockType END_BRICK_STAIRS = register("minecraft:end_brick_stairs", BlockID.END_BRICK_STAIRS); + public static final BlockType MOSSY_COBBLESTONE_STAIRS = register("minecraft:mossy_cobblestone_stairs", BlockID.MOSSY_COBBLESTONE_STAIRS); + public static final BlockType NORMAL_STONE_STAIRS = register("minecraft:normal_stone_stairs", BlockID.NORMAL_STONE_STAIRS); + public static final BlockType SPRUCE_STANDING_SIGN = register("minecraft:spruce_standing_sign", BlockID.SPRUCE_STANDING_SIGN); + public static final BlockType SPRUCE_WALL_SIGN = register("minecraft:spruce_wall_sign", BlockID.SPRUCE_WALL_SIGN); + public static final BlockType SMOOTH_STONE = register("minecraft:smooth_stone", BlockID.SMOOTH_STONE); + public static final BlockType RED_NETHER_BRICK_STAIRS = register("minecraft:red_nether_brick_stairs", BlockID.RED_NETHER_BRICK_STAIRS); + public static final BlockType SMOOTH_QUARTZ_STAIRS = register("minecraft:smooth_quartz_stairs", BlockID.SMOOTH_QUARTZ_STAIRS); + public static final BlockType BIRCH_STANDING_SIGN = register("minecraft:birch_standing_sign", BlockID.BIRCH_STANDING_SIGN); + public static final BlockType BIRCH_WALL_SIGN = register("minecraft:birch_wall_sign", BlockID.BIRCH_WALL_SIGN); + public static final BlockType JUNGLE_STANDING_SIGN = register("minecraft:jungle_standing_sign", BlockID.JUNGLE_STANDING_SIGN); + public static final BlockType JUNGLE_WALL_SIGN = register("minecraft:jungle_wall_sign", BlockID.JUNGLE_WALL_SIGN); + public static final BlockType ACACIA_STANDING_SIGN = register("minecraft:acacia_standing_sign", BlockID.ACACIA_STANDING_SIGN); + public static final BlockType ACACIA_WALL_SIGN = register("minecraft:acacia_wall_sign", BlockID.ACACIA_WALL_SIGN); + public static final BlockType DARK_OAK_STANDING_SIGN = register("minecraft:darkoak_standing_sign", BlockID.DARK_OAK_STANDING_SIGN); + public static final BlockType DARK_OAK_WALL_SIGN = register("minecraft:darkoak_wall_sign", BlockID.DARK_OAK_WALL_SIGN); + public static final BlockType LECTERN = register("minecraft:lectern", BlockID.LECTERN); + public static final BlockType GRINDSTONE = register("minecraft:grindstone", BlockID.GRINDSTONE); + public static final BlockType BLAST_FURNACE = register("minecraft:blast_furnace", BlockID.BLAST_FURNACE); + public static final BlockType STONECUTTER_BLOCK = register("minecraft:stonecutter_block", BlockID.STONECUTTER_BLOCK); + public static final BlockType SMOKER = register("minecraft:smoker", BlockID.SMOKER); + public static final BlockType LIT_SMOKER = register("minecraft:lit_smoker", BlockID.LIT_SMOKER); + public static final BlockType CARTOGRAPHY_TABLE = register("minecraft:cartography_table", BlockID.CARTOGRAPHY_TABLE); + public static final BlockType FLETCHING_TABLE = register("minecraft:fletching_table", BlockID.FLETCHING_TABLE); + public static final BlockType SMITHING_TABLE = register("minecraft:smithing_table", BlockID.SMITHING_TABLE); + public static final BlockType BARREL = register("minecraft:barrel", BlockID.BARREL); + public static final BlockType LOOM = register("minecraft:loom", BlockID.LOOM); + public static final BlockType BELL = register("minecraft:bell", BlockID.BELL); + public static final BlockType SWEET_BERRY_BUSH = register("minecraft:sweet_berry_bush", BlockID.SWEET_BERRY_BUSH); + public static final BlockType LANTERN = register("minecraft:lantern", BlockID.LANTERN); + public static final BlockType CAMPFIRE_BLOCK = register("minecraft:item.campfire", BlockID.CAMPFIRE_BLOCK); + public static final BlockType LAVA_CAULDRON = register("minecraft:lava_cauldron", BlockID.LAVA_CAULDRON); + public static final BlockType JIGSAW = register("minecraft:jigsaw", BlockID.JIGSAW); + public static final BlockType WOOD_BARK = register("minecraft:wood", BlockID.WOOD_BARK); + public static final BlockType COMPOSTER = register("minecraft:composter", BlockID.COMPOSTER); + public static final BlockType LIT_BLAST_FURNACE = register("minecraft:lit_blast_furnace", BlockID.LIT_BLAST_FURNACE); + public static final BlockType LIGHT_BLOCK = register("minecraft:light_block", BlockID.LIGHT_BLOCK); + public static final BlockType WITHER_ROSE = register("minecraft:wither_rose", BlockID.WITHER_ROSE); + public static final BlockType PISTON_HEAD_STICKY = register("minecraft:sticky_piston_arm_collision", BlockID.PISTON_HEAD_STICKY); + public static final BlockType BEE_NEST = register("minecraft:bee_nest", BlockID.BEE_NEST); + public static final BlockType BEEHIVE = register("minecraft:beehive", BlockID.BEEHIVE); + public static final BlockType HONEY_BLOCK = register("minecraft:honey_block", BlockID.HONEY_BLOCK); + public static final BlockType HONEYCOMB_BLOCK = register("minecraft:honeycomb_block", BlockID.HONEYCOMB_BLOCK); + public static final BlockType LODESTONE = register("minecraft:lodestone", BlockID.LODESTONE); + public static final BlockType CRIMSON_ROOTS = register("minecraft:crimson_roots", BlockID.CRIMSON_ROOTS); + public static final BlockType WARPED_ROOTS = register("minecraft:warped_roots", BlockID.WARPED_ROOTS); + public static final BlockType CRIMSON_STEM = register("minecraft:crimson_stem", BlockID.CRIMSON_STEM); + public static final BlockType WARPED_STEM = register("minecraft:warped_stem", BlockID.WARPED_STEM); + public static final BlockType WARPED_WART_BLOCK = register("minecraft:warped_wart_block", BlockID.WARPED_WART_BLOCK); + public static final BlockType CRIMSON_FUNGUS = register("minecraft:crimson_fungus", BlockID.CRIMSON_FUNGUS); + public static final BlockType WARPED_FUNGUS = register("minecraft:warped_fungus", BlockID.WARPED_FUNGUS); + public static final BlockType SHROOMLIGHT = register("minecraft:shroomlight", BlockID.SHROOMLIGHT); + public static final BlockType WEEPING_VINES = register("minecraft:weeping_vines", BlockID.WEEPING_VINES); + public static final BlockType CRIMSON_NYLIUM = register("minecraft:crimson_nylium", BlockID.CRIMSON_NYLIUM); + public static final BlockType WARPED_NYLIUM = register("minecraft:warped_nylium", BlockID.WARPED_NYLIUM); + public static final BlockType BASALT = register("minecraft:basalt", BlockID.BASALT); + public static final BlockType POLISHED_BASALT = register("minecraft:polished_basalt", BlockID.POLISHED_BASALT); + public static final BlockType SOUL_SOIL = register("minecraft:soul_soil", BlockID.SOUL_SOIL); + public static final BlockType SOUL_FIRE = register("minecraft:soul_fire", BlockID.SOUL_FIRE); + public static final BlockType NETHER_SPROUTS_BLOCK = register("minecraft:item.nether_sprouts", BlockID.NETHER_SPROUTS_BLOCK); + public static final BlockType TARGET = register("minecraft:target", BlockID.TARGET); + public static final BlockType STRIPPED_CRIMSON_STEM = register("minecraft:stripped_crimson_stem", BlockID.STRIPPED_CRIMSON_STEM); + public static final BlockType STRIPPED_WARPED_STEM = register("minecraft:stripped_warped_stem", BlockID.STRIPPED_WARPED_STEM); + public static final BlockType CRIMSON_PLANKS = register("minecraft:crimson_planks", BlockID.CRIMSON_PLANKS); + public static final BlockType WARPED_PLANKS = register("minecraft:warped_planks", BlockID.WARPED_PLANKS); + public static final BlockType CRIMSON_DOOR_BLOCK = register("minecraft:item.crimson_door", BlockID.CRIMSON_DOOR_BLOCK); + public static final BlockType WARPED_DOOR_BLOCK = register("minecraft:item.warped_door", BlockID.WARPED_DOOR_BLOCK); + public static final BlockType CRIMSON_TRAPDOOR = register("minecraft:crimson_trapdoor", BlockID.CRIMSON_TRAPDOOR); + public static final BlockType WARPED_TRAPDOOR = register("minecraft:warped_trapdoor", BlockID.WARPED_TRAPDOOR); + public static final BlockType CRIMSON_STANDING_SIGN = register("minecraft:crimson_standing_sign", BlockID.CRIMSON_STANDING_SIGN); + public static final BlockType WARPED_STANDING_SIGN = register("minecraft:warped_standing_sign", BlockID.WARPED_STANDING_SIGN); + public static final BlockType CRIMSON_WALL_SIGN = register("minecraft:crimson_wall_sign", BlockID.CRIMSON_WALL_SIGN); + public static final BlockType WARPED_WALL_SIGN = register("minecraft:warped_wall_sign", BlockID.WARPED_WALL_SIGN); + public static final BlockType CRIMSON_STAIRS = register("minecraft:crimson_stairs", BlockID.CRIMSON_STAIRS); + public static final BlockType WARPED_STAIRS = register("minecraft:warped_stairs", BlockID.WARPED_STAIRS); + public static final BlockType CRIMSON_FENCE = register("minecraft:crimson_fence", BlockID.CRIMSON_FENCE); + public static final BlockType WARPED_FENCE = register("minecraft:warped_fence", BlockID.WARPED_FENCE); + public static final BlockType CRIMSON_FENCE_GATE = register("minecraft:crimson_fence_gate", BlockID.CRIMSON_FENCE_GATE); + public static final BlockType WARPED_FENCE_GATE = register("minecraft:warped_fence_gate", BlockID.WARPED_FENCE_GATE); + public static final BlockType CRIMSON_BUTTON = register("minecraft:crimson_button", BlockID.CRIMSON_BUTTON); + public static final BlockType WARPED_BUTTON = register("minecraft:warped_button", BlockID.WARPED_BUTTON); + public static final BlockType CRIMSON_PRESSURE_PLATE = register("minecraft:crimson_pressure_plate", BlockID.CRIMSON_PRESSURE_PLATE); + public static final BlockType WARPED_PRESSURE_PLATE = register("minecraft:warped_pressure_plate", BlockID.WARPED_PRESSURE_PLATE); + public static final BlockType CRIMSON_SLAB = register("minecraft:crimson_slab", BlockID.CRIMSON_SLAB); + public static final BlockType WARPED_SLAB = register("minecraft:warped_slab", BlockID.WARPED_SLAB); + public static final BlockType CRIMSON_DOUBLE_SLAB = register("minecraft:crimson_double_slab", BlockID.CRIMSON_DOUBLE_SLAB); + public static final BlockType WARPED_DOUBLE_SLAB = register("minecraft:warped_double_slab", BlockID.WARPED_DOUBLE_SLAB); + public static final BlockType SOUL_TORCH = register("minecraft:soul_torch", BlockID.SOUL_TORCH); + public static final BlockType SOUL_LANTERN = register("minecraft:soul_lantern", BlockID.SOUL_LANTERN); + public static final BlockType NETHERITE_BLOCK = register("minecraft:netherite_block", BlockID.NETHERITE_BLOCK); + public static final BlockType ANCIENT_DEBRIS = register("minecraft:ancient_debris", BlockID.ANCIENT_DEBRIS); + public static final BlockType RESPAWN_ANCHOR = register("minecraft:respawn_anchor", BlockID.RESPAWN_ANCHOR); + public static final BlockType BLACKSTONE = register("minecraft:blackstone", BlockID.BLACKSTONE); + public static final BlockType POLISHED_BLACKSTONE_BRICKS = register("minecraft:polished_blackstone_bricks", BlockID.POLISHED_BLACKSTONE_BRICKS); + public static final BlockType POLISHED_BLACKSTONE_BRICK_STAIRS = register("minecraft:polished_blackstone_brick_stairs", BlockID.POLISHED_BLACKSTONE_BRICK_STAIRS); + public static final BlockType BLACKSTONE_STAIRS = register("minecraft:blackstone_stairs", BlockID.BLACKSTONE_STAIRS); + public static final BlockType BLACKSTONE_WALL = register("minecraft:blackstone_wall", BlockID.BLACKSTONE_WALL); + public static final BlockType POLISHED_BLACKSTONE_BRICK_WALL = register("minecraft:polished_blackstone_brick_wall", BlockID.POLISHED_BLACKSTONE_BRICK_WALL); + public static final BlockType CHISELED_POLISHED_BLACKSTONE = register("minecraft:chiseled_polished_blackstone", BlockID.CHISELED_POLISHED_BLACKSTONE); + public static final BlockType CRACKED_POLISHED_BLACKSTONE_BRICKS = register("minecraft:cracked_polished_blackstone_bricks", BlockID.CRACKED_POLISHED_BLACKSTONE_BRICKS); + public static final BlockType GILDED_BLACKSTONE = register("minecraft:gilded_blackstone", BlockID.GILDED_BLACKSTONE); + public static final BlockType BLACKSTONE_SLAB = register("minecraft:blackstone_slab", BlockID.BLACKSTONE_SLAB); + public static final BlockType BLACKSTONE_DOUBLE_SLAB = register("minecraft:blackstone_double_slab", BlockID.BLACKSTONE_DOUBLE_SLAB); + public static final BlockType POLISHED_BLACKSTONE_BRICK_SLAB = register("minecraft:polished_blackstone_brick_slab", BlockID.POLISHED_BLACKSTONE_BRICK_SLAB); + public static final BlockType POLISHED_BLACKSTONE_BRICK_DOUBLE_SLAB = register("minecraft:polished_blackstone_brick_double_slab", BlockID.POLISHED_BLACKSTONE_BRICK_DOUBLE_SLAB); + public static final BlockType CHAIN_BLOCK = register("minecraft:item.chain", BlockID.CHAIN_BLOCK); + public static final BlockType TWISTING_VINES = register("minecraft:twisting_vines", BlockID.TWISTING_VINES); + public static final BlockType NETHER_GOLD_ORE = register("minecraft:nether_gold_ore", BlockID.NETHER_GOLD_ORE); + public static final BlockType CRYING_OBSIDIAN = register("minecraft:crying_obsidian", BlockID.CRYING_OBSIDIAN); + public static final BlockType SOUL_CAMPFIRE_BLOCK = register("minecraft:item.soul_campfire", BlockID.SOUL_CAMPFIRE_BLOCK); + public static final BlockType POLISHED_BLACKSTONE = register("minecraft:polished_blackstone", BlockID.POLISHED_BLACKSTONE); + public static final BlockType POLISHED_BLACKSTONE_STAIRS = register("minecraft:polished_blackstone_stairs", BlockID.POLISHED_BLACKSTONE_STAIRS); + public static final BlockType POLISHED_BLACKSTONE_SLAB = register("minecraft:polished_blackstone_slab", BlockID.POLISHED_BLACKSTONE_SLAB); + public static final BlockType POLISHED_BLACKSTONE_DOUBLE_SLAB = register("minecraft:polished_blackstone_double_slab", BlockID.POLISHED_BLACKSTONE_DOUBLE_SLAB); + public static final BlockType POLISHED_BLACKSTONE_PRESSURE_PLATE = register("minecraft:polished_blackstone_pressure_plate", BlockID.POLISHED_BLACKSTONE_PRESSURE_PLATE); + public static final BlockType POLISHED_BLACKSTONE_BUTTON = register("minecraft:polished_blackstone_button", BlockID.POLISHED_BLACKSTONE_BUTTON); + public static final BlockType POLISHED_BLACKSTONE_WALL = register("minecraft:polished_blackstone_wall", BlockID.POLISHED_BLACKSTONE_WALL); + public static final BlockType WARPED_HYPHAE = register("minecraft:warped_hyphae", BlockID.WARPED_HYPHAE); + public static final BlockType CRIMSON_HYPHAE = register("minecraft:crimson_hyphae", BlockID.CRIMSON_HYPHAE); + public static final BlockType STRIPPED_CRIMSON_HYPHAE = register("minecraft:stripped_crimson_hyphae", BlockID.STRIPPED_CRIMSON_HYPHAE); + public static final BlockType STRIPPED_WARPED_HYPHAE = register("minecraft:stripped_warped_hyphae", BlockID.STRIPPED_WARPED_HYPHAE); + public static final BlockType CHISELED_NETHER_BRICKS = register("minecraft:chiseled_nether_bricks", BlockID.CHISELED_NETHER_BRICKS); + public static final BlockType CRACKED_NETHER_BRICKS = register("minecraft:cracked_nether_bricks", BlockID.CRACKED_NETHER_BRICKS); + public static final BlockType QUARTZ_BRICKS = register("minecraft:quartz_bricks", BlockID.QUARTZ_BRICKS); + public static final BlockType POWDER_SNOW = register("minecraft:powder_snow", BlockID.POWDER_SNOW); + public static final BlockType SCULK_SENSOR = register("minecraft:sculk_sensor", BlockID.SCULK_SENSOR); + public static final BlockType POINTED_DRIPSTONE = register("minecraft:pointed_dripstone", BlockID.POINTED_DRIPSTONE); + public static final BlockType COPPER_ORE = register("minecraft:copper_ore", BlockID.COPPER_ORE); + public static final BlockType LIGHTNING_ROD = register("minecraft:lightning_rod", BlockID.LIGHTNING_ROD); + public static final BlockType DRIPSTONE_BLOCK = register("minecraft:dripstone_block", BlockID.DRIPSTONE_BLOCK); + public static final BlockType ROOTED_DIRT = register("minecraft:dirt_with_roots", BlockID.ROOTED_DIRT); + public static final BlockType HANGING_ROOTS = register("minecraft:hanging_roots", BlockID.HANGING_ROOTS); + public static final BlockType MOSS_BLOCK = register("minecraft:moss_block", BlockID.MOSS_BLOCK); + public static final BlockType SPORE_BLOSSOM = register("minecraft:spore_blossom", BlockID.SPORE_BLOSSOM); + public static final BlockType CAVE_VINES = register("minecraft:cave_vines", BlockID.CAVE_VINES); + public static final BlockType BIG_DRIPLEAF = register("minecraft:big_dripleaf", BlockID.BIG_DRIPLEAF); + public static final BlockType AZALEA_LEAVES = register("minecraft:azalea_leaves", BlockID.AZALEA_LEAVES); + public static final BlockType AZALEA_LEAVES_FLOWERED = register("minecraft:azalea_leaves_flowered", BlockID.AZALEA_LEAVES_FLOWERED); + public static final BlockType CALCITE = register("minecraft:calcite", BlockID.CALCITE); + public static final BlockType AMETHYST_BLOCK = register("minecraft:amethyst_block", BlockID.AMETHYST_BLOCK); + public static final BlockType BUDDING_AMETHYST = register("minecraft:budding_amethyst", BlockID.BUDDING_AMETHYST); + public static final BlockType AMETHYST_CLUSTER = register("minecraft:amethyst_cluster", BlockID.AMETHYST_CLUSTER); + public static final BlockType LARGE_AMETHYST_BUD = register("minecraft:large_amethyst_bud", BlockID.LARGE_AMETHYST_BUD); + public static final BlockType MEDIUM_AMETHYST_BUD = register("minecraft:medium_amethyst_bud", BlockID.MEDIUM_AMETHYST_BUD); + public static final BlockType SMALL_AMETHYST_BUD = register("minecraft:small_amethyst_bud", BlockID.SMALL_AMETHYST_BUD); + public static final BlockType TUFF = register("minecraft:tuff", BlockID.TUFF); + public static final BlockType TINTED_GLASS = register("minecraft:tinted_glass", BlockID.TINTED_GLASS); + public static final BlockType MOSS_CARPET = register("minecraft:moss_carpet", BlockID.MOSS_CARPET); + public static final BlockType SMALL_DRIPLEAF = register("minecraft:small_dripleaf_block", BlockID.SMALL_DRIPLEAF); + public static final BlockType AZALEA = register("minecraft:azalea", BlockID.AZALEA); + public static final BlockType FLOWERING_AZALEA = register("minecraft:flowering_azalea", BlockID.FLOWERING_AZALEA); + public static final BlockType GLOW_FRAME = register("minecraft:item.glow_frame", BlockID.GLOW_FRAME); + public static final BlockType COPPER_BLOCK = register("minecraft:copper_block", BlockID.COPPER_BLOCK); + public static final BlockType EXPOSED_COPPER = register("minecraft:exposed_copper", BlockID.EXPOSED_COPPER); + public static final BlockType WEATHERED_COPPER = register("minecraft:weathered_copper", BlockID.WEATHERED_COPPER); + public static final BlockType OXIDIZED_COPPER = register("minecraft:oxidized_copper", BlockID.OXIDIZED_COPPER); + public static final BlockType WAXED_COPPER = register("minecraft:waxed_copper", BlockID.WAXED_COPPER); + public static final BlockType WAXED_EXPOSED_COPPER = register("minecraft:waxed_exposed_copper", BlockID.WAXED_EXPOSED_COPPER); + public static final BlockType WAXED_WEATHERED_COPPER = register("minecraft:waxed_weathered_copper", BlockID.WAXED_WEATHERED_COPPER); + public static final BlockType CUT_COPPER = register("minecraft:cut_copper", BlockID.CUT_COPPER); + public static final BlockType EXPOSED_CUT_COPPER = register("minecraft:exposed_cut_copper", BlockID.EXPOSED_CUT_COPPER); + public static final BlockType WEATHERED_CUT_COPPER = register("minecraft:weathered_cut_copper", BlockID.WEATHERED_CUT_COPPER); + public static final BlockType OXIDIZED_CUT_COPPER = register("minecraft:oxidized_cut_copper", BlockID.OXIDIZED_CUT_COPPER); + public static final BlockType WAXED_CUT_COPPER = register("minecraft:waxed_cut_copper", BlockID.WAXED_CUT_COPPER); + public static final BlockType WAXED_EXPOSED_CUT_COPPER = register("minecraft:waxed_exposed_cut_copper", BlockID.WAXED_EXPOSED_CUT_COPPER); + public static final BlockType WAXED_WEATHERED_CUT_COPPER = register("minecraft:waxed_weathered_cut_copper", BlockID.WAXED_WEATHERED_CUT_COPPER); + public static final BlockType CUT_COPPER_STAIRS = register("minecraft:cut_copper_stairs", BlockID.CUT_COPPER_STAIRS); + public static final BlockType EXPOSED_CUT_COPPER_STAIRS = register("minecraft:exposed_cut_copper_stairs", BlockID.EXPOSED_CUT_COPPER_STAIRS); + public static final BlockType WEATHERED_CUT_COPPER_STAIRS = register("minecraft:weathered_cut_copper_stairs", BlockID.WEATHERED_CUT_COPPER_STAIRS); + public static final BlockType OXIDIZED_CUT_COPPER_STAIRS = register("minecraft:oxidized_cut_copper_stairs", BlockID.OXIDIZED_CUT_COPPER_STAIRS); + public static final BlockType WAXED_CUT_COPPER_STAIRS = register("minecraft:waxed_cut_copper_stairs", BlockID.WAXED_CUT_COPPER_STAIRS); + public static final BlockType WAXED_EXPOSED_CUT_COPPER_STAIRS = register("minecraft:waxed_exposed_cut_copper_stairs", BlockID.WAXED_EXPOSED_CUT_COPPER_STAIRS); + public static final BlockType WAXED_WEATHERED_CUT_COPPER_STAIRS = register("minecraft:waxed_weathered_cut_copper_stairs", BlockID.WAXED_WEATHERED_CUT_COPPER_STAIRS); + public static final BlockType CUT_COPPER_SLAB = register("minecraft:cut_copper_slab", BlockID.CUT_COPPER_SLAB); + public static final BlockType EXPOSED_CUT_COPPER_SLAB = register("minecraft:exposed_cut_copper_slab", BlockID.EXPOSED_CUT_COPPER_SLAB); + public static final BlockType WEATHERED_CUT_COPPER_SLAB = register("minecraft:weathered_cut_copper_slab", BlockID.WEATHERED_CUT_COPPER_SLAB); + public static final BlockType OXIDIZED_CUT_COPPER_SLAB = register("minecraft:oxidized_cut_copper_slab", BlockID.OXIDIZED_CUT_COPPER_SLAB); + public static final BlockType WAXED_CUT_COPPER_SLAB = register("minecraft:waxed_cut_copper_slab", BlockID.WAXED_CUT_COPPER_SLAB); + public static final BlockType WAXED_EXPOSED_CUT_COPPER_SLAB = register("minecraft:waxed_exposed_cut_copper_slab", BlockID.WAXED_EXPOSED_CUT_COPPER_SLAB); + public static final BlockType WAXED_WEATHERED_CUT_COPPER_SLAB = register("minecraft:waxed_weathered_cut_copper_slab", BlockID.WAXED_WEATHERED_CUT_COPPER_SLAB); + public static final BlockType DOUBLE_CUT_COPPER_SLAB = register("minecraft:double_cut_copper_slab", BlockID.DOUBLE_CUT_COPPER_SLAB); + public static final BlockType EXPOSED_DOUBLE_CUT_COPPER_SLAB = register("minecraft:exposed_double_cut_copper_slab", BlockID.EXPOSED_DOUBLE_CUT_COPPER_SLAB); + public static final BlockType WEATHERED_DOUBLE_CUT_COPPER_SLAB = register("minecraft:weathered_double_cut_copper_slab", BlockID.WEATHERED_DOUBLE_CUT_COPPER_SLAB); + public static final BlockType OXIDIZED_DOUBLE_CUT_COPPER_SLAB = register("minecraft:oxidized_double_cut_copper_slab", BlockID.OXIDIZED_DOUBLE_CUT_COPPER_SLAB); + public static final BlockType WAXED_DOUBLE_CUT_COPPER_SLAB = register("minecraft:waxed_double_cut_copper_slab", BlockID.WAXED_DOUBLE_CUT_COPPER_SLAB); + public static final BlockType WAXED_EXPOSED_DOUBLE_CUT_COPPER_SLAB = register("minecraft:waxed_exposed_double_cut_copper_slab", BlockID.WAXED_EXPOSED_DOUBLE_CUT_COPPER_SLAB); + public static final BlockType WAXED_WEATHERED_DOUBLE_CUT_COPPER_SLAB = register("minecraft:waxed_weathered_double_cut_copper_slab", BlockID.WAXED_WEATHERED_DOUBLE_CUT_COPPER_SLAB); + public static final BlockType CAVE_VINES_BODY_WITH_BERRIES = register("minecraft:cave_vines_body_with_berries", BlockID.CAVE_VINES_BODY_WITH_BERRIES); + public static final BlockType CAVE_VINES_HEAD_WITH_BERRIES = register("minecraft:cave_vines_head_with_berries", BlockID.CAVE_VINES_HEAD_WITH_BERRIES); + public static final BlockType SMOOTH_BASALT = register("minecraft:smooth_basalt", BlockID.SMOOTH_BASALT); + public static final BlockType DEEPSLATE = register("minecraft:deepslate", BlockID.DEEPSLATE); + public static final BlockType COBBLED_DEEPSLATE = register("minecraft:cobbled_deepslate", BlockID.COBBLED_DEEPSLATE); + public static final BlockType COBBLED_DEEPSLATE_SLAB = register("minecraft:cobbled_deepslate_slab", BlockID.COBBLED_DEEPSLATE_SLAB); + public static final BlockType COBBLED_DEEPSLATE_STAIRS = register("minecraft:cobbled_deepslate_stairs", BlockID.COBBLED_DEEPSLATE_STAIRS); + public static final BlockType COBBLED_DEEPSLATE_WALL = register("minecraft:cobbled_deepslate_wall", BlockID.COBBLED_DEEPSLATE_WALL); + public static final BlockType POLISHED_DEEPSLATE = register("minecraft:polished_deepslate", BlockID.POLISHED_DEEPSLATE); + public static final BlockType POLISHED_DEEPSLATE_SLAB = register("minecraft:polished_deepslate_slab", BlockID.POLISHED_DEEPSLATE_SLAB); + public static final BlockType POLISHED_DEEPSLATE_STAIRS = register("minecraft:polished_deepslate_stairs", BlockID.POLISHED_DEEPSLATE_STAIRS); + public static final BlockType POLISHED_DEEPSLATE_WALL = register("minecraft:polished_deepslate_wall", BlockID.POLISHED_DEEPSLATE_WALL); + public static final BlockType DEEPSLATE_TILES = register("minecraft:deepslate_tiles", BlockID.DEEPSLATE_TILES); + public static final BlockType DEEPSLATE_TILE_SLAB = register("minecraft:deepslate_tile_slab", BlockID.DEEPSLATE_TILE_SLAB); + public static final BlockType DEEPSLATE_TILE_STAIRS = register("minecraft:deepslate_tile_stairs", BlockID.DEEPSLATE_TILE_STAIRS); + public static final BlockType DEEPSLATE_TILE_WALL = register("minecraft:deepslate_tile_wall", BlockID.DEEPSLATE_TILE_WALL); + public static final BlockType DEEPSLATE_BRICKS = register("minecraft:deepslate_bricks", BlockID.DEEPSLATE_BRICKS); + public static final BlockType DEEPSLATE_BRICK_SLAB = register("minecraft:deepslate_brick_slab", BlockID.DEEPSLATE_BRICK_SLAB); + public static final BlockType DEEPSLATE_BRICK_STAIRS = register("minecraft:deepslate_brick_stairs", BlockID.DEEPSLATE_BRICK_STAIRS); + public static final BlockType DEEPSLATE_BRICK_WALL = register("minecraft:deepslate_brick_wall", BlockID.DEEPSLATE_BRICK_WALL); + public static final BlockType CHISELED_DEEPSLATE = register("minecraft:chiseled_deepslate", BlockID.CHISELED_DEEPSLATE); + public static final BlockType COBBLED_DEEPSLATE_DOUBLE_SLAB = register("minecraft:cobbled_deepslate_double_slab", BlockID.COBBLED_DEEPSLATE_DOUBLE_SLAB); + public static final BlockType POLISHED_DEEPSLATE_DOUBLE_SLAB = register("minecraft:polished_deepslate_double_slab", BlockID.POLISHED_DEEPSLATE_DOUBLE_SLAB); + public static final BlockType DEEPSLATE_TILE_DOUBLE_SLAB = register("minecraft:deepslate_tile_double_slab", BlockID.DEEPSLATE_TILE_DOUBLE_SLAB); + public static final BlockType DEEPSLATE_BRICK_DOUBLE_SLAB = register("minecraft:deepslate_brick_double_slab", BlockID.DEEPSLATE_BRICK_DOUBLE_SLAB); + public static final BlockType DEEPSLATE_LAPIS_ORE = register("minecraft:deepslate_lapis_ore", BlockID.DEEPSLATE_LAPIS_ORE); + public static final BlockType DEEPSLATE_IRON_ORE = register("minecraft:deepslate_iron_ore", BlockID.DEEPSLATE_IRON_ORE); + public static final BlockType DEEPSLATE_GOLD_ORE = register("minecraft:deepslate_gold_ore", BlockID.DEEPSLATE_GOLD_ORE); + public static final BlockType DEEPSLATE_REDSTONE_ORE = register("minecraft:deepslate_redstone_ore", BlockID.DEEPSLATE_REDSTONE_ORE); + public static final BlockType LIT_DEEPSLATE_REDSTONE_ORE = register("minecraft:lit_deepslate_redstone_ore", BlockID.LIT_DEEPSLATE_REDSTONE_ORE); + public static final BlockType DEEPSLATE_DIAMOND_ORE = register("minecraft:deepslate_diamond_ore", BlockID.DEEPSLATE_DIAMOND_ORE); + public static final BlockType DEEPSLATE_COAL_ORE = register("minecraft:deepslate_coal_ore", BlockID.DEEPSLATE_COAL_ORE); + public static final BlockType DEEPSLATE_EMERALD_ORE = register("minecraft:deepslate_emerald_ore", BlockID.DEEPSLATE_EMERALD_ORE); + public static final BlockType DEEPSLATE_COPPER_ORE = register("minecraft:deepslate_copper_ore", BlockID.DEEPSLATE_COPPER_ORE); + public static final BlockType CRACKED_DEEPSLATE_TILES = register("minecraft:cracked_deepslate_tiles", BlockID.CRACKED_DEEPSLATE_TILES); + public static final BlockType CRACKED_DEEPSLATE_BRICKS = register("minecraft:cracked_deepslate_bricks", BlockID.CRACKED_DEEPSLATE_BRICKS); + public static final BlockType GLOW_LICHEN = register("minecraft:glow_lichen", BlockID.GLOW_LICHEN); + public static final BlockType CANDLE = register("minecraft:candle", BlockID.CANDLE); + public static final BlockType WHITE_CANDLE = register("minecraft:white_candle", BlockID.WHITE_CANDLE); + public static final BlockType ORANGE_CANDLE = register("minecraft:orange_candle", BlockID.ORANGE_CANDLE); + public static final BlockType MAGENTA_CANDLE = register("minecraft:magenta_candle", BlockID.MAGENTA_CANDLE); + public static final BlockType LIGHT_BLUE_CANDLE = register("minecraft:light_blue_candle", BlockID.LIGHT_BLUE_CANDLE); + public static final BlockType YELLOW_CANDLE = register("minecraft:yellow_candle", BlockID.YELLOW_CANDLE); + public static final BlockType LIME_CANDLE = register("minecraft:lime_candle", BlockID.LIME_CANDLE); + public static final BlockType PINK_CANDLE = register("minecraft:pink_candle", BlockID.PINK_CANDLE); + public static final BlockType GRAY_CANDLE = register("minecraft:gray_candle", BlockID.GRAY_CANDLE); + public static final BlockType LIGHT_GRAY_CANDLE = register("minecraft:light_gray_candle", BlockID.LIGHT_GRAY_CANDLE); + public static final BlockType CYAN_CANDLE = register("minecraft:cyan_candle", BlockID.CYAN_CANDLE); + public static final BlockType PURPLE_CANDLE = register("minecraft:purple_candle", BlockID.PURPLE_CANDLE); + public static final BlockType BLUE_CANDLE = register("minecraft:blue_candle", BlockID.BLUE_CANDLE); + public static final BlockType BROWN_CANDLE = register("minecraft:brown_candle", BlockID.BROWN_CANDLE); + public static final BlockType GREEN_CANDLE = register("minecraft:green_candle", BlockID.GREEN_CANDLE); + public static final BlockType RED_CANDLE = register("minecraft:red_candle", BlockID.RED_CANDLE); + public static final BlockType BLACK_CANDLE = register("minecraft:black_candle", BlockID.BLACK_CANDLE); + public static final BlockType CANDLE_CAKE = register("minecraft:candle_cake", BlockID.CANDLE_CAKE); + public static final BlockType WHITE_CANDLE_CAKE = register("minecraft:white_candle_cake", BlockID.WHITE_CANDLE_CAKE); + public static final BlockType ORANGE_CANDLE_CAKE = register("minecraft:orange_candle_cake", BlockID.ORANGE_CANDLE_CAKE); + public static final BlockType MAGENTA_CANDLE_CAKE = register("minecraft:magenta_candle_cake", BlockID.MAGENTA_CANDLE_CAKE); + public static final BlockType LIGHT_BLUE_CANDLE_CAKE = register("minecraft:light_blue_candle_cake", BlockID.LIGHT_BLUE_CANDLE_CAKE); + public static final BlockType YELLOW_CANDLE_CAKE = register("minecraft:yellow_candle_cake", BlockID.YELLOW_CANDLE_CAKE); + public static final BlockType LIME_CANDLE_CAKE = register("minecraft:lime_candle_cake", BlockID.LIME_CANDLE_CAKE); + public static final BlockType PINK_CANDLE_CAKE = register("minecraft:pink_candle_cake", BlockID.PINK_CANDLE_CAKE); + public static final BlockType GRAY_CANDLE_CAKE = register("minecraft:gray_candle_cake", BlockID.GRAY_CANDLE_CAKE); + public static final BlockType LIGHT_GRAY_CANDLE_CAKE = register("minecraft:light_gray_candle_cake", BlockID.LIGHT_GRAY_CANDLE_CAKE); + public static final BlockType CYAN_CANDLE_CAKE = register("minecraft:cyan_candle_cake", BlockID.CYAN_CANDLE_CAKE); + public static final BlockType PURPLE_CANDLE_CAKE = register("minecraft:purple_candle_cake", BlockID.PURPLE_CANDLE_CAKE); + public static final BlockType BLUE_CANDLE_CAKE = register("minecraft:blue_candle_cake", BlockID.BLUE_CANDLE_CAKE); + public static final BlockType BROWN_CANDLE_CAKE = register("minecraft:brown_candle_cake", BlockID.BROWN_CANDLE_CAKE); + public static final BlockType GREEN_CANDLE_CAKE = register("minecraft:green_candle_cake", BlockID.GREEN_CANDLE_CAKE); + public static final BlockType RED_CANDLE_CAKE = register("minecraft:red_candle_cake", BlockID.RED_CANDLE_CAKE); + public static final BlockType BLACK_CANDLE_CAKE = register("minecraft:black_candle_cake", BlockID.BLACK_CANDLE_CAKE); + public static final BlockType WAXED_OXIDIZED_COPPER = register("minecraft:waxed_oxidized_copper", BlockID.WAXED_OXIDIZED_COPPER); + public static final BlockType WAXED_OXIDIZED_CUT_COPPER = register("minecraft:waxed_oxidized_cut_copper", BlockID.WAXED_OXIDIZED_CUT_COPPER); + public static final BlockType WAXED_OXIDIZED_CUT_COPPER_STAIRS = register("minecraft:waxed_oxidized_cut_copper_stairs", BlockID.WAXED_OXIDIZED_CUT_COPPER_STAIRS); + public static final BlockType WAXED_OXIDIZED_CUT_COPPER_SLAB = register("minecraft:waxed_oxidized_cut_copper_slab", BlockID.WAXED_OXIDIZED_CUT_COPPER_SLAB); + public static final BlockType WAXED_OXIDIZED_DOUBLE_CUT_COPPER_SLAB = register("minecraft:waxed_oxidized_double_cut_copper_slab", BlockID.WAXED_OXIDIZED_DOUBLE_CUT_COPPER_SLAB); + public static final BlockType RAW_IRON_BLOCK = register("minecraft:raw_iron_block", BlockID.RAW_IRON_BLOCK); + public static final BlockType RAW_COPPER_BLOCK = register("minecraft:raw_copper_block", BlockID.RAW_COPPER_BLOCK); + public static final BlockType RAW_GOLD_BLOCK = register("minecraft:raw_gold_block", BlockID.RAW_GOLD_BLOCK); + public static final BlockType INFESTED_DEEPSLATE = register("minecraft:infested_deepslate", BlockID.INFESTED_DEEPSLATE); + public static final BlockType SCULK = register("minecraft:sculk", BlockID.SCULK); + public static final BlockType SCULK_VEIN = register("minecraft:sculk_vein", BlockID.SCULK_VEIN); + public static final BlockType SCULK_CATALYST = register("minecraft:sculk_catalyst", BlockID.SCULK_CATALYST); + public static final BlockType SCULK_SHRIEKER = register("minecraft:sculk_shrieker", BlockID.SCULK_SHRIEKER); + public static final BlockType REINFORCED_DEEPSLATE = register("minecraft:reinforced_deepslate", BlockID.REINFORCED_DEEPSLATE); + public static final BlockType FROG_SPAWN = register("minecraft:frog_spawn", BlockID.FROG_SPAWN); + public static final BlockType PEARLESCENT_FROGLIGHT = register("minecraft:pearlescent_froglight", BlockID.PEARLESCENT_FROGLIGHT); + public static final BlockType VERDANT_FROGLIGHT = register("minecraft:verdant_froglight", BlockID.VERDANT_FROGLIGHT); + public static final BlockType OCHRE_FROGLIGHT = register("minecraft:ochre_froglight", BlockID.OCHRE_FROGLIGHT); + public static final BlockType MANGROVE_LEAVES = register("minecraft:mangrove_leaves", BlockID.MANGROVE_LEAVES); + public static final BlockType MUD = register("minecraft:mud", BlockID.MUD); + public static final BlockType MANGROVE_PROPAGULE = register("minecraft:mangrove_propagule", BlockID.MANGROVE_PROPAGULE); + public static final BlockType MUD_BRICKS = register("minecraft:mud_bricks", BlockID.MUD_BRICKS); + public static final BlockType PACKED_MUD = register("minecraft:packed_mud", BlockID.PACKED_MUD); + public static final BlockType MUD_BRICK_SLAB = register("minecraft:mud_brick_slab", BlockID.MUD_BRICK_SLAB); + public static final BlockType MUD_BRICK_DOUBLE_SLAB = register("minecraft:mud_brick_double_slab", BlockID.MUD_BRICK_DOUBLE_SLAB); + public static final BlockType MUD_BRICK_STAIRS = register("minecraft:mud_brick_stairs", BlockID.MUD_BRICK_STAIRS); + public static final BlockType MUD_BRICK_WALL = register("minecraft:mud_brick_wall", BlockID.MUD_BRICK_WALL); + public static final BlockType MANGROVE_ROOTS = register("minecraft:mangrove_roots", BlockID.MANGROVE_ROOTS); + public static final BlockType MUDDY_MANGROVE_ROOTS = register("minecraft:muddy_mangrove_roots", BlockID.MUDDY_MANGROVE_ROOTS); + public static final BlockType MANGROVE_LOG = register("minecraft:mangrove_log", BlockID.MANGROVE_LOG); + public static final BlockType STRIPPED_MANGROVE_LOG = register("minecraft:stripped_mangrove_log", BlockID.STRIPPED_MANGROVE_LOG); + public static final BlockType MANGROVE_PLANKS = register("minecraft:mangrove_planks", BlockID.MANGROVE_PLANKS); + public static final BlockType MANGROVE_BUTTON = register("minecraft:mangrove_button", BlockID.MANGROVE_BUTTON); + public static final BlockType MANGROVE_STAIRS = register("minecraft:mangrove_stairs", BlockID.MANGROVE_STAIRS); + public static final BlockType MANGROVE_SLAB = register("minecraft:mangrove_slab", BlockID.MANGROVE_SLAB); + public static final BlockType MANGROVE_PRESSURE_PLATE = register("minecraft:mangrove_pressure_plate", BlockID.MANGROVE_PRESSURE_PLATE); + public static final BlockType MANGROVE_FENCE = register("minecraft:mangrove_fence", BlockID.MANGROVE_FENCE); + public static final BlockType MANGROVE_FENCE_GATE = register("minecraft:mangrove_fence_gate", BlockID.MANGROVE_FENCE_GATE); + public static final BlockType MANGROVE_DOOR = register("minecraft:mangrove_door", BlockID.MANGROVE_DOOR); + public static final BlockType MANGROVE_STANDING_SIGN = register("minecraft:mangrove_standing_sign", BlockID.MANGROVE_STANDING_SIGN); + public static final BlockType MANGROVE_WALL_SIGN = register("minecraft:mangrove_wall_sign", BlockID.MANGROVE_WALL_SIGN); + public static final BlockType MANGROVE_TRAPDOOR = register("minecraft:mangrove_trapdoor", BlockID.MANGROVE_TRAPDOOR); + public static final BlockType MANGROVE_WOOD = register("minecraft:mangrove_wood", BlockID.MANGROVE_WOOD); + public static final BlockType STRIPPED_MANGROVE_WOOD = register("minecraft:stripped_mangrove_wood", BlockID.STRIPPED_MANGROVE_WOOD); + public static final BlockType MANGROVE_DOUBLE_SLAB = register("minecraft:mangrove_double_slab", BlockID.MANGROVE_DOUBLE_SLAB); + + private static BlockType register(String identifier, int legacyId) { + return register(new BlockTypeImpl(identifier, legacyId)); + } + + private static BlockType register(BlockType blockType) { + BlockType old = types.putIfAbsent(blockType.getLegacyId(), blockType); + /*if (old != null) { // TODO: there are alternate names for some items + throw new IllegalArgumentException("Block type with id " + itemType.getLegacyId() + " already exists: " + old); + }*/ + identifiers.putIfAbsent(blockType.getIdentifier(), blockType); // TODO: using identifiers.put() would be better + return old == null ? blockType : old; + } + + public static BlockType getFromLegacy(int legacyId) { + return types.get(legacyId); + } + + public static BlockType get(String identifier) { + return identifiers.get(identifier); + } + + @Data + private static class BlockTypeImpl implements BlockType { + private final String identifier; + private final int legacyId; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockUndyedShulkerBox.java b/src/main/java/cn/nukkit/block/BlockUndyedShulkerBox.java index 15f33862f1d..510cefa29a1 100644 --- a/src/main/java/cn/nukkit/block/BlockUndyedShulkerBox.java +++ b/src/main/java/cn/nukkit/block/BlockUndyedShulkerBox.java @@ -1,34 +1,15 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ package cn.nukkit.block; -import cn.nukkit.Player; import cn.nukkit.blockentity.BlockEntity; -import cn.nukkit.blockentity.BlockEntityShulkerBox; -import cn.nukkit.inventory.ShulkerBoxInventory; -import cn.nukkit.item.Item; -import cn.nukkit.item.ItemBlock; -import cn.nukkit.item.ItemTool; -import cn.nukkit.math.BlockFace; -import cn.nukkit.nbt.NBTIO; -import cn.nukkit.nbt.tag.CompoundTag; -import cn.nukkit.nbt.tag.ListTag; -import cn.nukkit.nbt.tag.Tag; +import cn.nukkit.inventory.ContainerInventory; +import cn.nukkit.inventory.InventoryHolder; import cn.nukkit.utils.BlockColor; +import cn.nukkit.utils.DyeColor; -import java.util.Map; - -/** - * - * @author Reece Mackie - */ -public class BlockUndyedShulkerBox extends BlockTransparent { +public class BlockUndyedShulkerBox extends BlockShulkerBox { public BlockUndyedShulkerBox() { - super(); + super(0); } @Override @@ -42,123 +23,32 @@ public String getName() { } @Override - public double getHardness() { - return 2; - } - - @Override - public double getResistance() { - return 10; - } - - @Override - public boolean canBeActivated() { - return true; + public BlockColor getColor() { + return BlockColor.PURPLE_BLOCK_COLOR; } @Override - public int getToolType() { - return ItemTool.TYPE_PICKAXE; + public DyeColor getDyeColor() { + return null; } @Override - public Item toItem() { - ItemBlock item = new ItemBlock(this, this.getDamage(), 1); - - BlockEntityShulkerBox t = (BlockEntityShulkerBox) this.getLevel().getBlockEntity(this); - - if (t != null) { - ShulkerBoxInventory i = t.getRealInventory(); - - if (!i.isEmpty()) { - CompoundTag nbt = item.getNamedTag(); - if (nbt == null) - nbt = new CompoundTag(""); - - ListTag items = new ListTag<>(); - - for (int it = 0; it < i.getSize(); it++) { - if (i.getItem(it).getId() != Item.AIR) { - CompoundTag d = NBTIO.putItemHelper(i.getItem(it), it); - items.add(d); - } - } - - nbt.put("Items", items); - - item.setCompoundTag(nbt); - } - - if (t.hasName()) { - item.setCustomName(t.getName()); - } - } - - return item; + public void setDamage(int meta) { } @Override - public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - this.getLevel().setBlock(block, this, true); - CompoundTag nbt = BlockEntity.getDefaultCompound(this, BlockEntity.SHULKER_BOX) - .putByte("facing", face.getIndex()); - - if (item.hasCustomName()) { - nbt.putString("CustomName", item.getCustomName()); - } - - CompoundTag t = item.getNamedTag(); - - // This code gets executed when the player has broken the shulker box and placed it back (©Kevims 2020) - if (t != null && t.contains("Items")) { - nbt.putList(t.getList("Items")); - } - - // This code gets executed when the player has copied the shulker box in creative mode (©Kevims 2020) - if (item.hasCustomBlockData()) { - Map customData = item.getCustomBlockData().getTags(); - for (Map.Entry tag : customData.entrySet()) { - nbt.put(tag.getKey(), tag.getValue()); - } - } - - BlockEntityShulkerBox box = (BlockEntityShulkerBox) BlockEntity.createBlockEntity(BlockEntity.SHULKER_BOX, this.getLevel().getChunk(this.getFloorX() >> 4, this.getFloorZ() >> 4), nbt); - return box != null; - } - - @Override - public boolean canHarvestWithHand() { - return false; + public boolean hasComparatorInputOverride() { + return true; } @Override - public boolean onActivate(Item item, Player player) { - if (player != null) { - BlockEntity t = this.getLevel().getBlockEntity(this); - BlockEntityShulkerBox box; - if (t instanceof BlockEntityShulkerBox) { - box = (BlockEntityShulkerBox) t; - } else { - CompoundTag nbt = BlockEntity.getDefaultCompound(this, BlockEntity.SHULKER_BOX); - box = (BlockEntityShulkerBox) BlockEntity.createBlockEntity(BlockEntity.SHULKER_BOX, this.getLevel().getChunk(this.getFloorX() >> 4, this.getFloorZ() >> 4), nbt); - if (box == null) { - return false; - } - } - - Block block = this.getSide(BlockFace.fromIndex(box.namedTag.getByte("facing"))); - if (!(block instanceof BlockAir) && !(block instanceof BlockLiquid) && !(block instanceof BlockFlowable)) { - return true; - } + public int getComparatorInputOverride() { + BlockEntity be = this.getLevel().getBlockEntity(this); - player.addWindow(box.getInventory()); + if (!(be instanceof InventoryHolder)) { + return 0; } - return true; - } - - @Override - public BlockColor getColor() { - return BlockColor.PURPLE_BLOCK_COLOR; + return ContainerInventory.calculateRedstone(((InventoryHolder) be).getInventory()); } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockUnknown.java b/src/main/java/cn/nukkit/block/BlockUnknown.java index 4a89311d83b..514e145976b 100644 --- a/src/main/java/cn/nukkit/block/BlockUnknown.java +++ b/src/main/java/cn/nukkit/block/BlockUnknown.java @@ -1,7 +1,7 @@ package cn.nukkit.block; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockUnknown extends BlockMeta { @@ -22,6 +22,11 @@ public int getId() { return id; } + @Override + public double getHardness() { + return 0.1; + } + @Override public String getName() { return "Unknown"; diff --git a/src/main/java/cn/nukkit/block/BlockVine.java b/src/main/java/cn/nukkit/block/BlockVine.java index bc097954203..72f49fb7bfb 100644 --- a/src/main/java/cn/nukkit/block/BlockVine.java +++ b/src/main/java/cn/nukkit/block/BlockVine.java @@ -13,9 +13,7 @@ import cn.nukkit.math.SimpleAxisAlignedBB; import cn.nukkit.utils.BlockColor; -import java.util.EnumSet; import java.util.Random; -import java.util.Set; import java.util.concurrent.ThreadLocalRandom; /** @@ -74,7 +72,6 @@ public boolean canBeClimbed() { @Override public void onEntityCollide(Entity entity) { entity.resetFallDistance(); - entity.onGround = true; } @Override @@ -140,7 +137,7 @@ protected AxisAlignedBB recalculateBoundingBox() { public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { if (block.getId() != VINE && target.isSolid() && face.getHorizontalIndex() != -1) { this.setDamage(getMetaFromFace(face.getOpposite())); - this.getLevel().setBlock(block, this, true, true); + this.getLevel().setBlock(this, this, true, true); return true; } @@ -160,25 +157,24 @@ public Item[] getDrops(Item item) { @Override public Item toItem() { - return new ItemBlock(this, 0); + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_NORMAL) { + int meta = this.getDamage(); Block up = this.up(); - Set upFaces = up instanceof BlockVine ? ((BlockVine) up).getFaces() : null; - Set faces = this.getFaces(); for (BlockFace face : BlockFace.Plane.HORIZONTAL) { - if (!this.getSide(face).isSolid() && (upFaces == null || !upFaces.contains(face))) { - faces.remove(face); + int faceMeta = getMetaFromFace(face); + if (!this.getSide(face).isSolid() && (up.getId() != VINE || (up.getDamage() & faceMeta) != faceMeta)) { + meta &= ~faceMeta; } } - if (faces.isEmpty() && !up.isSolid()) { + if (meta == 0 && !up.isSolid()) { this.getLevel().useBreakOn(this, null, null, true); return Level.BLOCK_UPDATE_NORMAL; } - int meta = getMetaFromFaces(faces); if (meta != this.getDamage()) { this.level.setBlock(this, Block.get(VINE, meta), true); return Level.BLOCK_UPDATE_NORMAL; @@ -191,7 +187,7 @@ public int onUpdate(int type) { int faceMeta = getMetaFromFace(face); int meta = this.getDamage(); - if (this.y < 255 && face == BlockFace.UP && block.getId() == AIR) { + if (this.y < this.level.getMaxBlockY() && face == BlockFace.UP && block.getId() == AIR) { if (this.canSpread()) { for (BlockFace horizontalFace : BlockFace.Plane.HORIZONTAL) { if (random.nextBoolean() || !this.getSide(horizontalFace).getSide(face).isSolid()) { @@ -228,7 +224,7 @@ public int onUpdate(int type) { putVine(this, meta, null); } } - } else if (this.y > 0) { + } else if (this.y > this.level.getMinBlockY()) { Block below = this.down(); int id = below.getId(); if (id == AIR || id == VINE) { @@ -255,7 +251,7 @@ private boolean canSpread() { for (int x = blockX - 4; x <= blockX + 4; x++) { for (int z = blockZ - 4; z <= blockZ + 4; z++) { for (int y = blockY - 1; y <= blockY + 1; y++) { - if (this.level.getBlock(x, y, z).getId() == VINE) { + if (this.level.getBlockIdAt(x, y, z) == VINE) { if (++count >= 5) return false; } } @@ -294,37 +290,6 @@ private void putVineOnHorizontalFace(Block block, int meta, Block source) { } } - private Set getFaces() { - Set faces = EnumSet.noneOf(BlockFace.class); - - int meta = this.getDamage(); - if ((meta & 1) > 0) { - faces.add(BlockFace.SOUTH); - } - if ((meta & 2) > 0) { - faces.add(BlockFace.WEST); - } - if ((meta & 4) > 0) { - faces.add(BlockFace.NORTH); - } - if ((meta & 8) > 0) { - faces.add(BlockFace.EAST); - } - - return faces; - } - - private static int getMetaFromFaces(Set faces) { - int meta = 0; - - for (BlockFace face : faces) { - meta |= getMetaFromFace(face); - - } - - return meta; - } - private static int getMetaFromFace(BlockFace face) { switch (face) { case SOUTH: @@ -353,4 +318,19 @@ public BlockColor getColor() { public boolean canSilkTouch() { return true; } + + @Override + public boolean breakWhenPushed() { + return true; + } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } + + @Override + public boolean canBeFlowedInto() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockVinesNether.java b/src/main/java/cn/nukkit/block/BlockVinesNether.java new file mode 100644 index 00000000000..0a6adeea540 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockVinesNether.java @@ -0,0 +1,404 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.Server; +import cn.nukkit.entity.Entity; +import cn.nukkit.event.block.BlockGrowEvent; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemDye; +import cn.nukkit.item.ItemID; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.level.Level; +import cn.nukkit.level.Position; +import cn.nukkit.level.particle.BoneMealParticle; +import cn.nukkit.math.BlockFace; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Optional; +import java.util.OptionalInt; +import java.util.concurrent.ThreadLocalRandom; + +/** + * Implements the main logic of all nether vines. + * @author joserobjr + */ +public abstract class BlockVinesNether extends BlockTransparentMeta { + + public BlockVinesNether() { + this(0); + } + + public BlockVinesNether(int meta) { + super(meta); + } + + /** + * The direction that the vine will grow, vertical direction is expected but future implementations + * may also add horizontal directions. + * @return Normally, up or down. + */ + public abstract BlockFace getGrowthDirection(); + + /** + * The current age of this block. + */ + public abstract int getVineAge(); + + /** + * Changes the age of this block. + * @param vineAge The new age + */ + public abstract void setVineAge(int vineAge); + + /** + * The maximum accepted age of this block. + * @return Positive, inclusive value. + */ + public abstract int getMaxVineAge(); + + /** + * Changes the current vine age to a random new random age. + * + * @param pseudorandom If the the randomization should be pseudorandom. + */ + public void randomizeVineAge(boolean pseudorandom) { + if (pseudorandom) { + setVineAge(ThreadLocalRandom.current().nextInt(getMaxVineAge())); + return; + } + + double chance = 1.0D; + int age; + + ThreadLocalRandom random = ThreadLocalRandom.current(); + for(age = 0; random.nextDouble() < chance; ++age) { + chance *= 0.826D; + } + + setVineAge(age); + } + + @Override + public boolean place(@Nonnull Item item, @Nonnull Block block, @Nonnull Block target, @Nonnull BlockFace face, double fx, double fy, double fz, @Nullable Player player) { + Block support = getSide(getGrowthDirection().getOpposite()); + if (!isSupportValid(support)) { + return false; + } + + if (support.getId() == getId()) { + setVineAge(Math.min(getMaxVineAge(), ((BlockVinesNether) support).getVineAge() + 1)); + } else { + randomizeVineAge(true); + } + + return super.place(item, block, target, face, fx, fy, fz, player); + } + + @Override + public int onUpdate(int type) { + switch (type) { + case Level.BLOCK_UPDATE_RANDOM: + int maxVineAge = getMaxVineAge(); + if (getVineAge() < maxVineAge && ThreadLocalRandom.current().nextInt(10) == 0 + && findVineAge(true).orElse(maxVineAge) < maxVineAge) { + grow(); + } + return Level.BLOCK_UPDATE_RANDOM; + case Level.BLOCK_UPDATE_NORMAL: + if (!this.isSupportValid()) { + this.getLevel().useBreakOn(this); + } + return Level.BLOCK_UPDATE_NORMAL; + default: + return 0; + } + } + + /** + * Grow a single vine if possible. Calls {@link BlockGrowEvent} passing the positioned new state and the source block. + * @return If the vine grew successfully. + */ + public boolean grow() { + Block pos = getSide(getGrowthDirection()); + if (pos.getId() != AIR || pos.y < level.getMinBlockY() || pos.y > level.getMaxBlockY()) { + return false; + } + + BlockVinesNether growing = clone(); + growing.x = pos.x; + growing.y = pos.y; + growing.z = pos.z; + growing.setVineAge(Math.min(getVineAge() + 1, getMaxVineAge())); + + BlockGrowEvent ev = new BlockGrowEvent(this, growing); + Server.getInstance().getPluginManager().callEvent(ev); + + if (ev.isCancelled()) { + return false; + } + + if (level.setBlock(pos, growing)) { + increaseRootAge(); + return true; + } + return false; + } + + /** + * Grow a random amount of vines. + * Calls {@link BlockGrowEvent} passing the positioned new state and the source block for each new vine being added + * to the world, if one of the events gets cancelled the growth gets interrupted. + * @return How many vines grew + */ + public int growMultiple() { + BlockFace growthDirection = getGrowthDirection(); + int age = getVineAge() + 1; + int maxAge = getMaxVineAge(); + BlockVinesNether growing = clone(); + growing.randomizeVineAge(false); + int blocksToGrow = growing.getVineAge(); + + int grew = 0; + for (int distance = 1; distance <= blocksToGrow; distance++) { + Block pos = getSide(growthDirection, distance); + if (pos.getId() != AIR || pos.y < level.getMinBlockY() || pos.y > level.getMaxBlockY()) { + break; + } + + growing.setVineAge(Math.min(age++, maxAge)); + growing.x = pos.x; + growing.y = pos.y; + growing.z = pos.z; + + BlockGrowEvent ev = new BlockGrowEvent(this, growing.clone()); + Server.getInstance().getPluginManager().callEvent(ev); + + if (ev.isCancelled()) { + break; + } + + if (!level.setBlock(pos, ev.getNewState())) { + break; + } + + grew++; + } + + if (grew > 0) { + increaseRootAge(); + } + + return grew; + } + + /** + * Attempt to get the age of the root or the head of the vine. + * @param base True to get the age of the base (oldest block), false to get the age of the head (newest block) + * @return Empty if the target could not be reached. The age of the target if it was found. + */ + @Nonnull + public OptionalInt findVineAge(boolean base) { + return findVineBlock(base) + .map(vine-> OptionalInt.of(vine.getVineAge())) + .orElse(OptionalInt.empty()); + } + + /** + * Attempt to find the root or the head of the vine transversing the growth direction for up to 256 blocks. + * @param base True to find the base (oldest block), false to find the head (newest block) + * @return Empty if the target could not be reached or the block there isn't an instance of {@link BlockVinesNether}. + * The positioned block of the target if it was found. + */ + @Nonnull + public Optional findVineBlock(boolean base) { + return findVine(base) + .map(Position::getLevelBlock) + .filter(BlockVinesNether.class::isInstance) + .map(BlockVinesNether.class::cast); + } + + /** + * Attempt to find the root or the head of the vine transversing the growth direction for up to 256 blocks. + * @param base True to find the base (oldest block), false to find the head (newest block) + * @return Empty if the target could not be reached. The position of the target if it was found. + */ + @Nonnull + public Optional findVine(boolean base) { + BlockFace supportFace = getGrowthDirection(); + if (base) { + supportFace = supportFace.getOpposite(); + } + Position result = getLocation(); + int id = getId(); + int limit = 256; + while (--limit > 0) { + Position next = result.getSide(supportFace); + if (next.getLevelBlock().getId() == id) { + result = next; + } else { + break; + } + } + + return Optional.of(result); + } + + public Optional increaseRootAge() { + Block base = findVine(true).map(Position::getLevelBlock).orElse(null); + if (!(base instanceof BlockVinesNether)) { + return Optional.empty(); + } + + BlockVinesNether baseVine = (BlockVinesNether) base; + int vineAge = baseVine.getVineAge(); + if (vineAge < baseVine.getMaxVineAge()) { + baseVine.setVineAge(vineAge + 1); + if (getLevel().setBlock(baseVine, baseVine)) { + return Optional.of(true); + } + } + + return Optional.of(false); + } + + @Override + public boolean onActivate(@Nonnull Item item, @Nullable Player player) { + if (!(item.getId() == ItemID.DYE && item.getDamage() == ItemDye.BONE_MEAL)) { + return false; + } + + this.getLevel().addParticle(new BoneMealParticle(this)); + this.findVineBlock(false).ifPresent(BlockVinesNether::growMultiple); + + if (player != null && !player.isCreative()) { + item.count--; + } + return true; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } + + @Override + public Item[] getDrops(Item item) { + // They have a 33% (3/9) chance to drop a single weeping vine when broken, + // increased to 55% (5/9) with Fortune I, + // 77% (7/9) with Fortune II, + // and 100% with Fortune III. + // + // They always drop a single weeping vine when broken with shears or a tool enchanted with Silk Touch. + + int enchantmentLevel; + if (item.isShears() || (enchantmentLevel = item.getEnchantmentLevel(Enchantment.ID_FORTUNE_DIGGING)) >= 3) { + return new Item[]{ toItem() }; + } + + int chance = 3 + enchantmentLevel * 2; + if (ThreadLocalRandom.current().nextInt(9) < chance) { + return new Item[]{ toItem() }; + } + + return new Item[0]; + } + + protected boolean isSupportValid(@Nonnull Block support) { + return support.getId() == getId() || !support.isTransparent(); + } + + public boolean isSupportValid() { + return isSupportValid(getSide(getGrowthDirection().getOpposite())); + } + + @Override + public void onEntityCollide(Entity entity) { + entity.resetFallDistance(); + } + + @Override + public boolean hasEntityCollision() { + return true; + } + + @Override + public double getHardness() { + return 0; + } + + @Override + public double getResistance() { + return 0; + } + + @Override + public boolean canBeClimbed() { + return true; + } + + @Override + public boolean canBeFlowedInto() { + return true; + } + + @Override + public boolean isSolid() { + return false; + } + + @Override + public double getMinX() { + return x+ (4/16.0); + } + + @Override + public double getMinZ() { + return z+ (4/16.0); + } + + @Override + public double getMaxX() { + return x+ (12/16.0); + } + + @Override + public double getMaxZ() { + return z+ (12/16.0); + } + + @Override + public double getMaxY() { + return y+ (15/16.0); + } + + @Override + public boolean canPassThrough() { + return true; + } + + @Override + public boolean breakWhenPushed() { + return true; + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean canSilkTouch() { + return true; + } + @Override + public BlockVinesNether clone() { + return (BlockVinesNether) super.clone(); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockVinesTwisting.java b/src/main/java/cn/nukkit/block/BlockVinesTwisting.java new file mode 100644 index 00000000000..2404d0f542d --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockVinesTwisting.java @@ -0,0 +1,50 @@ +package cn.nukkit.block; + +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.BlockColor; + +public class BlockVinesTwisting extends BlockVinesNether { + + public BlockVinesTwisting() { + this(0); + } + + public BlockVinesTwisting(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Twisting Vines"; + } + + @Override + public int getId() { + return TWISTING_VINES; + } + + @Override + public BlockFace getGrowthDirection() { + return BlockFace.UP; + } + + @Override + public int getVineAge() { + return this.getDamage(); + } + + @Override + public void setVineAge(int vineAge) { + this.setDamage(vineAge & 0x19); + } + + @Override + public int getMaxVineAge() { + return 25; + } + + @Override + public BlockColor getColor() { + return BlockColor.CYAN_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWall.java b/src/main/java/cn/nukkit/block/BlockWall.java index 64414a248a4..95fe7feb0f8 100644 --- a/src/main/java/cn/nukkit/block/BlockWall.java +++ b/src/main/java/cn/nukkit/block/BlockWall.java @@ -6,14 +6,14 @@ import cn.nukkit.math.SimpleAxisAlignedBB; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockWall extends BlockTransparentMeta { + public static final int NONE_MOSSY_WALL = 0; public static final int MOSSY_WALL = 1; - public BlockWall() { this(0); } @@ -44,16 +44,42 @@ public double getResistance() { @Override public String getName() { - if (this.getDamage() == 0x01) { - return "Mossy Cobblestone Wall"; + switch (this.getDamage()) { + case 0: + return "Cobblestone Wall"; + case 1: + return "Mossy Cobblestone Wall"; + case 2: + return "Granite Wall"; + case 3: + return "Diorite Wall"; + case 4: + return "Andesite Wall"; + case 5: + return "Sandstone Wall"; + case 6: + return "Brick Wall"; + case 7: + return "Stone Brick Wall"; + case 8: + return "Mossy Stone Brick Wall"; + case 9: + return "Nether Brick Wall"; + case 10: + return "End Stone Brick Wall"; + case 11: + return "Prismarine Wall"; + case 12: + return "Red Sandstone Wall"; + case 13: + return "Red Nether Brick Wall"; } - return "Cobblestone Wall"; + return "Wall"; } @Override protected AxisAlignedBB recalculateBoundingBox() { - boolean north = this.canConnect(this.getSide(BlockFace.NORTH)); boolean south = this.canConnect(this.getSide(BlockFace.SOUTH)); boolean west = this.canConnect(this.getSide(BlockFace.WEST)); @@ -95,4 +121,9 @@ public int getToolType() { public boolean canHarvestWithHand() { return false; } + + @Override + public WaterloggingType getWaterloggingType() { + return WaterloggingType.WHEN_PLACED_IN_WATER; + } } diff --git a/src/main/java/cn/nukkit/block/BlockWallBanner.java b/src/main/java/cn/nukkit/block/BlockWallBanner.java index a9f5f8a35db..4efe0ff6a6e 100644 --- a/src/main/java/cn/nukkit/block/BlockWallBanner.java +++ b/src/main/java/cn/nukkit/block/BlockWallBanner.java @@ -3,9 +3,6 @@ import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; -/** - * Created by PetteriM1 - */ public class BlockWallBanner extends BlockBanner { public BlockWallBanner() { diff --git a/src/main/java/cn/nukkit/block/BlockWallBrickDeepslate.java b/src/main/java/cn/nukkit/block/BlockWallBrickDeepslate.java new file mode 100644 index 00000000000..394580d90b8 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWallBrickDeepslate.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockWallBrickDeepslate extends BlockWall { + + public BlockWallBrickDeepslate() { + this(0); + } + + public BlockWallBrickDeepslate(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Deepslate Brick Wall"; + } + + @Override + public int getId() { + return DEEPSLATE_BRICK_WALL; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWallDeepslateCobbled.java b/src/main/java/cn/nukkit/block/BlockWallDeepslateCobbled.java new file mode 100644 index 00000000000..99f04665d12 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWallDeepslateCobbled.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockWallDeepslateCobbled extends BlockWall { + + public BlockWallDeepslateCobbled() { + this(0); + } + + public BlockWallDeepslateCobbled(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Cobbled Deepslate Wall"; + } + + @Override + public int getId() { + return COBBLED_DEEPSLATE_WALL; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWallDeepslatePolished.java b/src/main/java/cn/nukkit/block/BlockWallDeepslatePolished.java new file mode 100644 index 00000000000..3d2a245416d --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWallDeepslatePolished.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockWallDeepslatePolished extends BlockWall { + + public BlockWallDeepslatePolished() { + this(0); + } + + public BlockWallDeepslatePolished(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Polished Deepslate Wall"; + } + + @Override + public int getId() { + return POLISHED_DEEPSLATE_WALL; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWallSign.java b/src/main/java/cn/nukkit/block/BlockWallSign.java index d7cb421ea03..4f37c012312 100644 --- a/src/main/java/cn/nukkit/block/BlockWallSign.java +++ b/src/main/java/cn/nukkit/block/BlockWallSign.java @@ -9,6 +9,13 @@ */ public class BlockWallSign extends BlockSignPost { + private static final int[] FACES = { + 3, + 2, + 5, + 4, + }; + public BlockWallSign() { this(0); } @@ -29,15 +36,9 @@ public String getName() { @Override public int onUpdate(int type) { - int[] faces = { - 3, - 2, - 5, - 4, - }; if (type == Level.BLOCK_UPDATE_NORMAL) { if (this.getDamage() >= 2 && this.getDamage() <= 5) { - if (this.getSide(BlockFace.fromIndex(faces[this.getDamage() - 2])).getId() == Item.AIR) { + if (this.getSide(BlockFace.fromIndex(FACES[this.getDamage() - 2])).getId() == Item.AIR) { this.getLevel().useBreakOn(this); } return Level.BLOCK_UPDATE_NORMAL; diff --git a/src/main/java/cn/nukkit/block/BlockWallTileDeepslate.java b/src/main/java/cn/nukkit/block/BlockWallTileDeepslate.java new file mode 100644 index 00000000000..74d84b78bb6 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWallTileDeepslate.java @@ -0,0 +1,22 @@ +package cn.nukkit.block; + +public class BlockWallTileDeepslate extends BlockWall { + + public BlockWallTileDeepslate() { + this(0); + } + + public BlockWallTileDeepslate(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Deepslate Tile Wall"; + } + + @Override + public int getId() { + return DEEPSLATE_TILE_WALL; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWarpedDoor.java b/src/main/java/cn/nukkit/block/BlockWarpedDoor.java new file mode 100644 index 00000000000..a761896fcc1 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWarpedDoor.java @@ -0,0 +1,29 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; + +public class BlockWarpedDoor extends BlockDoor { + + public BlockWarpedDoor() { + this(0); + } + + public BlockWarpedDoor(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Warped Door"; + } + + @Override + public int getId() { + return WARPED_DOOR_BLOCK; + } + + @Override + public Item toItem() { + return Item.get(Item.WARPED_DOOR); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWarpedFungus.java b/src/main/java/cn/nukkit/block/BlockWarpedFungus.java new file mode 100644 index 00000000000..ed95a37d7c9 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWarpedFungus.java @@ -0,0 +1,99 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.level.Level; +import cn.nukkit.level.generator.object.tree.ObjectWarpedTree; +import cn.nukkit.level.particle.BoneMealParticle; +import cn.nukkit.level.Position; +import cn.nukkit.utils.BlockColor; +import cn.nukkit.math.NukkitRandom; +import cn.nukkit.math.Vector3; +import cn.nukkit.utils.DyeColor; + +import java.util.concurrent.ThreadLocalRandom; + +public class BlockWarpedFungus extends BlockFungus { + + public BlockWarpedFungus() { + // Does nothing + } + + @Override + public int getId() { + return WARPED_FUNGUS; + } + + @Override + public String getName() { + return "Warped Fungus"; + } + + @Override + protected boolean canGrowOn(Block support) { + return support.getId() == WARPED_NYLIUM; + } + + @Override + public boolean grow(Player cause) { + // TODO: + return false; + } + + @Override + public BlockColor getColor() { + return BlockColor.CYAN_BLOCK_COLOR; + } + + @Override + public int onUpdate(int type) { + if (type == Level.BLOCK_UPDATE_NORMAL) { + if (this.down().isTransparent()) { + this.getLevel().useBreakOn(this); + return Level.BLOCK_UPDATE_NORMAL; + } + } + + return 0; + } + + @Override + public boolean canPlaceOn(Block floor, Position pos) { + switch (floor.getId()) { + case BlockID.GRASS: + case BlockID.DIRT: + case BlockID.PODZOL: + case BlockID.FARMLAND: + case BlockID.CRIMSON_NYLIUM: + case BlockID.WARPED_NYLIUM: + case BlockID.MYCELIUM: + case BlockID.SOUL_SOIL: + return true; + default: + return false; + } + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (item.getId() == Item.DYE && item.getDamage() == DyeColor.WHITE.getDyeData()) { + if (player != null && (player.gamemode & 0x01) == 0) { + item.count--; + } + + if (ThreadLocalRandom.current().nextFloat() < 0.4 && this.level.getBlockIdAt((int) this.x, (int) this.y - 1, (int) this.z) == WARPED_NYLIUM) { + new ObjectWarpedTree().placeObject(this.level, (int) this.x, (int) this.y, (int) this.z, new NukkitRandom()); + this.level.setBlock(new Vector3((int) this.x, (int) this.y - 1, (int) this.z), Block.get(NETHERRACK), false, true); + } + + this.level.addParticle(new BoneMealParticle(this)); + return true; + } + return false; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWarpedNylium.java b/src/main/java/cn/nukkit/block/BlockWarpedNylium.java new file mode 100644 index 00000000000..8f087440bc5 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWarpedNylium.java @@ -0,0 +1,21 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockWarpedNylium extends BlockNylium { + + @Override + public String getName() { + return "Warped Nylium"; + } + + @Override + public int getId() { + return WARPED_NYLIUM; + } + + @Override + public BlockColor getColor() { + return BlockColor.WARPED_NYLIUM_BLOCK_COLOR; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockWarpedPlanks.java b/src/main/java/cn/nukkit/block/BlockWarpedPlanks.java new file mode 100644 index 00000000000..be1be0f9d77 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWarpedPlanks.java @@ -0,0 +1,55 @@ +package cn.nukkit.block; + +import cn.nukkit.item.ItemTool; +import cn.nukkit.utils.BlockColor; + +public class BlockWarpedPlanks extends BlockSolid { + + public BlockWarpedPlanks() { + this(0); + } + + public BlockWarpedPlanks(int meta) { + // super(meta); + } + + @Override + public int getId() { + return WARPED_PLANKS; + } + + @Override + public String getName() { + return "Warped Planks"; + } + + @Override + public double getHardness() { + return 2; + } + + @Override + public double getResistance() { + return 3; + } + + @Override + public int getToolType() { + return ItemTool.TYPE_AXE; + } + + @Override + public BlockColor getColor() { + return BlockColor.WARPED_STEM_BLOCK_COLOR; + } + + @Override + public int getBurnChance() { + return 0; + } + + @Override + public int getBurnAbility() { + return 0; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockWarpedRoots.java b/src/main/java/cn/nukkit/block/BlockWarpedRoots.java new file mode 100644 index 00000000000..6b223c1921d --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWarpedRoots.java @@ -0,0 +1,39 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockWarpedRoots extends BlockRoots { + + public BlockWarpedRoots() { + this(0); + } + + public BlockWarpedRoots(int meta) { + super(meta); + } + + @Override + public int getId() { + return WARPED_ROOTS; + } + + @Override + public String getName() { + return "Warped Roots"; + } + + @Override + public BlockColor getColor() { + return BlockColor.NETHERRACK_BLOCK_COLOR; + } + + @Override + public boolean canBeReplaced() { + return true; + } + + @Override + public boolean breakWhenPushed() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWarpedSign.java b/src/main/java/cn/nukkit/block/BlockWarpedSign.java new file mode 100644 index 00000000000..84b5c9d4934 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWarpedSign.java @@ -0,0 +1,40 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; + +public class BlockWarpedSign extends BlockSignPost { + + public BlockWarpedSign() { + this(0); + } + + public BlockWarpedSign(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Warped Sign"; + } + + @Override + public int getId() { + return WARPED_STANDING_SIGN; + } + + @Override + public Item toItem() { + return Item.get(ItemID.WARPED_SIGN); + } + + @Override + protected int getPostId() { + return WARPED_STANDING_SIGN; + } + + @Override + protected int getWallId() { + return WARPED_WALL_SIGN; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWarpedStairs.java b/src/main/java/cn/nukkit/block/BlockWarpedStairs.java new file mode 100644 index 00000000000..74cbb0b4b5b --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWarpedStairs.java @@ -0,0 +1,39 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockWarpedStairs extends BlockStairsWood { + + public BlockWarpedStairs() { + this(0); + } + + public BlockWarpedStairs(int meta) { + super(meta); + } + + @Override + public int getId() { + return WARPED_STAIRS; + } + + @Override + public String getName() { + return "Warped Stairs"; + } + + @Override + public BlockColor getColor() { + return BlockColor.CYAN_BLOCK_COLOR; + } + + @Override + public int getBurnChance() { + return 0; + } + + @Override + public int getBurnAbility() { + return 0; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWarpedStem.java b/src/main/java/cn/nukkit/block/BlockWarpedStem.java new file mode 100644 index 00000000000..a94b86608ff --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWarpedStem.java @@ -0,0 +1,44 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockWarpedStem extends BlockStem { + + public BlockWarpedStem() { + this(0); + } + + public BlockWarpedStem(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Warped Stem"; + } + + @Override + public int getId() { + return WARPED_STEM; + } + + @Override + public int getStrippedId() { + return STRIPPED_WARPED_STEM; + } + + @Override + public BlockColor getColor() { + return BlockColor.WARPED_STEM_BLOCK_COLOR; + } + + @Override + public int getBurnChance() { + return 0; + } + + @Override + public int getBurnAbility() { + return 0; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWarpedTrapdoor.java b/src/main/java/cn/nukkit/block/BlockWarpedTrapdoor.java new file mode 100644 index 00000000000..e12c5fb9fa2 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWarpedTrapdoor.java @@ -0,0 +1,30 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; + +public class BlockWarpedTrapdoor extends BlockTrapdoor { + + public BlockWarpedTrapdoor() { + this(0); + } + + public BlockWarpedTrapdoor(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Warped Trapdoor"; + } + + @Override + public int getId() { + return WARPED_TRAPDOOR; + } + + @Override + public Item toItem() { + return new ItemBlock(Block.get(this.getId(), 0), 0); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWarpedWallSign.java b/src/main/java/cn/nukkit/block/BlockWarpedWallSign.java new file mode 100644 index 00000000000..8619a4fe6e3 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWarpedWallSign.java @@ -0,0 +1,29 @@ +package cn.nukkit.block; + +import cn.nukkit.item.Item; + +public class BlockWarpedWallSign extends BlockWallSign { + + public BlockWarpedWallSign() { + this(0); + } + + public BlockWarpedWallSign(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Warped Wall Sign"; + } + + @Override + public int getId() { + return WARPED_WALL_SIGN; + } + + @Override + public Item toItem() { + return Item.get(Item.WARPED_SIGN); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWarpedWartBlock.java b/src/main/java/cn/nukkit/block/BlockWarpedWartBlock.java new file mode 100644 index 00000000000..13a7c7f0c67 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWarpedWartBlock.java @@ -0,0 +1,35 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockWarpedWartBlock extends BlockNetherWartBlock { + + public BlockWarpedWartBlock() { + super(); + } + + @Override + public String getName() { + return "Warped Wart Block"; + } + + @Override + public int getId() { + return WARPED_WART_BLOCK; + } + + @Override + public double getResistance() { + return 1; + } + + @Override + public double getHardness() { + return 1; + } + + @Override + public BlockColor getColor() { + return BlockColor.WARPED_WART_BLOCK_COLOR; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/BlockWater.java b/src/main/java/cn/nukkit/block/BlockWater.java index c2a4e1fcc23..ae35555ee39 100644 --- a/src/main/java/cn/nukkit/block/BlockWater.java +++ b/src/main/java/cn/nukkit/block/BlockWater.java @@ -2,16 +2,28 @@ import cn.nukkit.Player; import cn.nukkit.entity.Entity; +import cn.nukkit.event.block.WaterFrostEvent; import cn.nukkit.item.Item; +import cn.nukkit.level.Level; +import cn.nukkit.level.biome.Biome; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.format.anvil.Anvil; import cn.nukkit.math.BlockFace; import cn.nukkit.utils.BlockColor; +import java.util.concurrent.ThreadLocalRandom; + /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockWater extends BlockLiquid { + /** + * Used to cache biome check for freezing + * 1 = can't freeze, 2 = can freeze + */ + private byte freezing; public BlockWater() { this(0); @@ -46,7 +58,7 @@ public BlockColor getColor() { @Override public BlockLiquid getBlock(int meta) { - return (BlockLiquid) Block.get(BlockID.WATER, meta); + return (BlockLiquid) Block.get(WATER, meta); } @Override @@ -62,4 +74,30 @@ public void onEntityCollide(Entity entity) { public int tickRate() { return 5; } + + @Override + public int onUpdate(int type) { + if (freezing != 1 && type == Level.BLOCK_UPDATE_RANDOM && this.getDamage() == 0) { + FullChunk chunk = getChunk(); + if (freezing < 1) { + freezing = Biome.getBiome(chunk.getBiomeId((int) this.x & 0x0f, (int) this.z & 0x0f)).isFreezing() ? (byte) 2 : (byte) 1; + } + if (freezing == 2) { + if (ThreadLocalRandom.current().nextInt(10) == 0 && chunk.getBlockLight((int) this.x & 0x0f, (int) this.y, (int) this.z & 0x0f) < 12 && chunk.getHighestBlockAt((int) this.x & 0x0f, (int) this.z & 0x0f, false) <= this.y) { + WaterFrostEvent ev = new WaterFrostEvent(this); + level.getServer().getPluginManager().callEvent(ev); + if (!ev.isCancelled()) { + level.setBlock(this, Block.get(Block.ICE), true, true); + } + } + } + return Level.BLOCK_UPDATE_RANDOM; + } + return super.onUpdate(type); + } + + @Override + public boolean usesWaterLogging() { + return level == null || !(level.getProvider() instanceof Anvil); + } } diff --git a/src/main/java/cn/nukkit/block/BlockWaterLily.java b/src/main/java/cn/nukkit/block/BlockWaterLily.java index fb4095683fc..7a7e1ad855f 100644 --- a/src/main/java/cn/nukkit/block/BlockWaterLily.java +++ b/src/main/java/cn/nukkit/block/BlockWaterLily.java @@ -2,7 +2,6 @@ import cn.nukkit.Player; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemBlock; import cn.nukkit.level.Level; import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.math.BlockFace; @@ -19,7 +18,6 @@ public BlockWaterLily() { } public BlockWaterLily(int meta) { - // Lily pad can't have meta. Also stops the server from throwing an exception with the block palette. super(0); } @@ -33,6 +31,11 @@ public int getId() { return WATER_LILY; } + @Override + protected AxisAlignedBB recalculateBoundingBox() { + return this; + } + @Override public double getMinX() { return this.x + 0.0625; @@ -58,11 +61,6 @@ public double getMaxZ() { return this.z + 0.9375; } - @Override - protected AxisAlignedBB recalculateBoundingBox() { - return this; - } - @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { if (target instanceof BlockWater) { @@ -86,11 +84,6 @@ public int onUpdate(int type) { return 0; } - @Override - public Item toItem() { - return new ItemBlock(this, 0); - } - @Override public BlockColor getColor() { return BlockColor.FOLIAGE_BLOCK_COLOR; @@ -102,12 +95,7 @@ public boolean canPassThrough() { } @Override - public int getFullId() { - return this.getId() << 4; - } - - @Override - public void setDamage(int meta) { - + public boolean breakWhenPushed() { + return true; } } diff --git a/src/main/java/cn/nukkit/block/BlockWaterStill.java b/src/main/java/cn/nukkit/block/BlockWaterStill.java index ba28df1d508..40822a32fe6 100644 --- a/src/main/java/cn/nukkit/block/BlockWaterStill.java +++ b/src/main/java/cn/nukkit/block/BlockWaterStill.java @@ -1,7 +1,7 @@ package cn.nukkit.block; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class BlockWaterStill extends BlockWater { @@ -26,7 +26,6 @@ public String getName() { @Override public BlockLiquid getBlock(int meta) { - return (BlockLiquid) Block.get(BlockID.STILL_WATER, meta); + return (BlockLiquid) Block.get(STILL_WATER, meta); } - } diff --git a/src/main/java/cn/nukkit/block/BlockWeepingVines.java b/src/main/java/cn/nukkit/block/BlockWeepingVines.java new file mode 100644 index 00000000000..9735f1858eb --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWeepingVines.java @@ -0,0 +1,49 @@ +package cn.nukkit.block; + +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.BlockColor; + +public class BlockWeepingVines extends BlockVinesNether { + + public BlockWeepingVines() { + this(0); + } + + public BlockWeepingVines(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Weeping Vines"; + } + + @Override + public int getId() { + return WEEPING_VINES; + } + + @Override + public BlockFace getGrowthDirection() { + return BlockFace.DOWN; + } + + @Override + public int getVineAge() { + return this.getDamage(); + } + + @Override + public void setVineAge(int vineAge) { + this.setDamage(vineAge & 0x19); + } + + public int getMaxVineAge() { + return 25; + } + + @Override + public BlockColor getColor() { + return BlockColor.NETHERRACK_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWeightedPressurePlateHeavy.java b/src/main/java/cn/nukkit/block/BlockWeightedPressurePlateHeavy.java index c71f007a618..af93d51bafd 100644 --- a/src/main/java/cn/nukkit/block/BlockWeightedPressurePlateHeavy.java +++ b/src/main/java/cn/nukkit/block/BlockWeightedPressurePlateHeavy.java @@ -48,7 +48,7 @@ public int getToolType() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; @@ -59,7 +59,7 @@ public Item[] getDrops(Item item) { @Override public Item toItem() { - return new ItemBlock(this, 0); + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override diff --git a/src/main/java/cn/nukkit/block/BlockWeightedPressurePlateLight.java b/src/main/java/cn/nukkit/block/BlockWeightedPressurePlateLight.java index e718b675c81..2c397f3bff7 100644 --- a/src/main/java/cn/nukkit/block/BlockWeightedPressurePlateLight.java +++ b/src/main/java/cn/nukkit/block/BlockWeightedPressurePlateLight.java @@ -48,7 +48,7 @@ public int getToolType() { @Override public Item[] getDrops(Item item) { - if (item.isPickaxe() && item.getTier() >= ItemTool.TIER_WOODEN) { + if (item.isPickaxe()) { return new Item[]{ toItem() }; @@ -59,7 +59,7 @@ public Item[] getDrops(Item item) { @Override public Item toItem() { - return new ItemBlock(this, 0); + return new ItemBlock(Block.get(this.getId(), 0), 0); } @Override diff --git a/src/main/java/cn/nukkit/block/BlockWheat.java b/src/main/java/cn/nukkit/block/BlockWheat.java index c20f9007ae1..d4cf81c5fc9 100644 --- a/src/main/java/cn/nukkit/block/BlockWheat.java +++ b/src/main/java/cn/nukkit/block/BlockWheat.java @@ -1,8 +1,7 @@ package cn.nukkit.block; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemSeedsWheat; -import cn.nukkit.item.ItemWheat; +import cn.nukkit.utils.Utils; /** * Created on 2015/12/2 by xtypr. @@ -30,20 +29,25 @@ public int getId() { @Override public Item toItem() { - return new ItemSeedsWheat(); + return Item.get(Item.WHEAT_SEEDS); } @Override public Item[] getDrops(Item item) { if (this.getDamage() >= 0x07) { return new Item[]{ - new ItemWheat(), - new ItemSeedsWheat(0, (int) (4d * Math.random())) + Item.get(Item.WHEAT), + Item.get(Item.WHEAT_SEEDS, 0, Utils.random.nextInt(0, 4)) }; } else { return new Item[]{ - new ItemSeedsWheat() + Item.get(Item.WHEAT_SEEDS) }; } } + + @Override + public boolean breakWhenPushed() { + return true; + } } diff --git a/src/main/java/cn/nukkit/block/BlockWitherRose.java b/src/main/java/cn/nukkit/block/BlockWitherRose.java new file mode 100644 index 00000000000..fb275d6fc88 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWitherRose.java @@ -0,0 +1,76 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.EntityLiving; +import cn.nukkit.event.entity.EntityPotionEffectEvent; +import cn.nukkit.math.AxisAlignedBB; +import cn.nukkit.potion.Effect; + +public class BlockWitherRose extends BlockFlower { + + public BlockWitherRose() { + this(0); + } + + public BlockWitherRose(int meta) { + super(0); + } + + @Override + public int getId() { + return WITHER_ROSE; + } + @Override + public boolean canBeActivated() { + return false; + } + + @Override + public void onEntityCollide(Entity entity) { + if (level.getServer().getDifficulty() != 0 && entity instanceof EntityLiving) { + EntityLiving living = (EntityLiving) entity; + if (!living.invulnerable && !living.hasEffect(Effect.WITHER) + && (!(living instanceof Player) || !((Player) living).isCreative() && !((Player) living).isSpectator())) { + Effect effect = Effect.getEffect(Effect.WITHER); + effect.setDuration(40); + living.addEffect(effect, EntityPotionEffectEvent.Cause.WITHER_ROSE); + } + } + } + + @Override + public boolean hasEntityCollision() { + return true; + } + + @Override + protected AxisAlignedBB recalculateBoundingBox() { + return this; + } + + @Override + public double getMinX() { + return this.x + 0.2; + } + + @Override + public double getMinZ() { + return this.z + 0.2; + } + + @Override + public double getMaxX() { + return this.x + 0.8; + } + + @Override + public double getMaxY() { + return this.y + 0.8; + } + + @Override + public double getMaxZ() { + return this.z + 0.8; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWood.java b/src/main/java/cn/nukkit/block/BlockWood.java index c9aebf02a9f..a4e37f9d0c1 100644 --- a/src/main/java/cn/nukkit/block/BlockWood.java +++ b/src/main/java/cn/nukkit/block/BlockWood.java @@ -8,15 +8,31 @@ import cn.nukkit.utils.BlockColor; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockWood extends BlockSolidMeta { + public static final int OAK = 0; public static final int SPRUCE = 1; public static final int BIRCH = 2; public static final int JUNGLE = 3; + private static final short[] FACES = { + 0, + 0, + 0b1000, + 0b1000, + 0b0100, // full bark + 0b0100 + }; + + private static final int[] STRIPPED_IDS = { + STRIPPED_OAK_LOG, + STRIPPED_SPRUCE_LOG, + STRIPPED_BIRCH_LOG, + STRIPPED_JUNGLE_LOG + }; public BlockWood() { this(0); @@ -38,19 +54,19 @@ public double getHardness() { @Override public double getResistance() { - return 10; + return 2; } + private static final String[] NAMES = { + "Oak Wood", + "Spruce Wood", + "Birch Wood", + "Jungle Wood" + }; + @Override public String getName() { - String[] names = new String[]{ - "Oak Wood", - "Spruce Wood", - "Birch Wood", - "Jungle Wood" - }; - - return names[this.getDamage() & 0x03]; + return NAMES[this.getDamage() & 0x03]; } @Override @@ -65,23 +81,17 @@ public int getBurnAbility() { @Override public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { - short[] faces = new short[]{ - 0, - 0, - 0b1000, - 0b1000, - 0b0100, - 0b0100 - }; - - this.setDamage(((this.getDamage() & 0x03) | faces[face.getIndex()])); + this.setDamage(((this.getDamage() & 0x03) | FACES[face.getIndex()])); this.getLevel().setBlock(block, this, true, true); - return true; } @Override public Item toItem() { + if (this.getDamage() > 11) { + int variant = this.getDamage() & 0x03; + return new ItemBlock(Block.get(WOOD_BARK, variant), variant); + } return new ItemBlock(this, this.getDamage() & 0x03); } @@ -92,7 +102,7 @@ public int getToolType() { @Override public BlockColor getColor() { - switch(getDamage() & 0x07){ + switch (getDamage() & 0x03) { default: case OAK: return BlockColor.WOOD_BLOCK_COLOR; @@ -104,4 +114,38 @@ public BlockColor getColor() { return BlockColor.DIRT_BLOCK_COLOR; } } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Item item, Player player) { + if (item.isAxe() && player != null && (player.isSurvival() || player.isCreative()) && (!(this instanceof BlockWoodBark) || this.getDamage() < 8)) { + Block strippedBlock = Block.get(getStrippedId(), getStrippedDamage()); + item.useOn(this); + this.level.setBlock(this, strippedBlock, true, true); + return true; + } + return false; + } + + protected int getStrippedId() { + int damage = getDamage(); + if ((damage & 0b1100) == 0b1100) { // Only bark + return WOOD_BARK; + } + + return STRIPPED_IDS[damage & 0x03]; + } + + protected int getStrippedDamage() { + int damage = getDamage(); + if ((damage & 0b1100) == 0b1100) { // Only bark + return damage & 0x03 | 0x8; + } + + return damage >> 2; + } } diff --git a/src/main/java/cn/nukkit/block/BlockWood2.java b/src/main/java/cn/nukkit/block/BlockWood2.java index 1de3f2c7eaf..668978c1c32 100644 --- a/src/main/java/cn/nukkit/block/BlockWood2.java +++ b/src/main/java/cn/nukkit/block/BlockWood2.java @@ -1,9 +1,11 @@ package cn.nukkit.block; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; import cn.nukkit.utils.BlockColor; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockWood2 extends BlockWood { @@ -11,7 +13,7 @@ public class BlockWood2 extends BlockWood { public static final int ACACIA = 0; public static final int DARK_OAK = 1; - private static final String[] NAMES = new String[]{ + private static final String[] NAMES = { "Acacia Wood", "Dark Oak Wood", "" @@ -37,7 +39,7 @@ public String getName() { @Override public BlockColor getColor() { - switch(getDamage() & 0x07){ + switch (getDamage() & 0x07) { case ACACIA: return BlockColor.ORANGE_BLOCK_COLOR; case DARK_OAK: @@ -46,4 +48,48 @@ public BlockColor getColor() { return BlockColor.WOOD_BLOCK_COLOR; } } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public Item toItem() { + if (this.getDamage() > 11) { + int variant = this.getDamage() & 0x07; + return new ItemBlock(Block.get(WOOD_BARK, variant), variant); + } + return new ItemBlock(this, this.getDamage() & 0x03); + } + + @Override + protected int getStrippedId() { + int damage = getDamage(); + if ((damage & 0b1100) == 0b1100) { // Only bark + return WOOD_BARK; + } + + int typeId = damage & 0x3; + if (typeId == 0) { + return STRIPPED_ACACIA_LOG; + } else { + return STRIPPED_DARK_OAK_LOG; + } + } + + @Override + protected int getStrippedDamage() { + int damage = getDamage(); + if ((damage & 0b1100) == 0b1100) { // Only bark + int typeId = damage & 0x3; + if (typeId == 0) { + return 0x4 | 0x8; + } else { + return 0x5 | 0x8; + } + } + + return super.getStrippedDamage(); + } } diff --git a/src/main/java/cn/nukkit/block/BlockWoodBark.java b/src/main/java/cn/nukkit/block/BlockWoodBark.java new file mode 100644 index 00000000000..a8d3a29f22f --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWoodBark.java @@ -0,0 +1,75 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.math.BlockFace; + +public class BlockWoodBark extends BlockWood { + + private static final String[] NAMES = { + "Oak Wood", + "Spruce Wood", + "Birch Wood", + "Jungle Wood", + "Acacia Wood", + "Dark Oak Wood", + }; + + + public BlockWoodBark() { + this(0); + } + + public BlockWoodBark(int meta) { + super(meta); + } + + @Override + public void setDamage(int meta) { + super.setDamage(meta); + } + + @Override + public int getId() { + return WOOD_BARK; + } + + @Override + public String getName() { + int variant = (this.getDamage() & 0x7); + if (NAMES.length <= variant) { + return NAMES[0]; + } + return NAMES[variant]; + } + + @Override + protected int getStrippedId() { + return this.getId(); + } + + @Override + protected int getStrippedDamage() { + return getDamage() | 0x8; + } + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + /*if (face.getAxis().isHorizontal()) { + if (face.getAxis() == BlockFace.Axis.X) { + setDamage(getDamage() | 0x10); + } else { + setDamage(getDamage() | 0x20); + } + }*/ + this.getLevel().setBlock(block, this, true, true); + return true; + } + + @Override + public Item toItem() { + int meta = this.getDamage() & 0xF; + return new ItemBlock(Block.get(WOOD_BARK, meta), meta); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWoodStripped.java b/src/main/java/cn/nukkit/block/BlockWoodStripped.java new file mode 100644 index 00000000000..fbee7af91b8 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWoodStripped.java @@ -0,0 +1,51 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.math.BlockFace; + +public abstract class BlockWoodStripped extends BlockWood { + + private static final short[] FACES = { + 0, + 0, + 0b10, + 0b10, + 0b01, + 0b01 + }; + + public BlockWoodStripped() { + this(0); + } + + public BlockWoodStripped(int meta) { + super(meta); + } + + @Override + public abstract int getId(); + + @Override + public abstract String getName(); + + @Override + public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) { + this.setDamage(FACES[face.getIndex()]); + this.getLevel().setBlock(block, this, true, true); + return true; + } + + @Override + public boolean canBeActivated() { + return false; + } + + @Override + public Item toItem() { + // I was this before merge from upstream + // return new ItemBlock(this, this.getDamage()); + return new ItemBlock(Block.get(this.getId(), 0), 0); + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWoodStrippedAcacia.java b/src/main/java/cn/nukkit/block/BlockWoodStrippedAcacia.java new file mode 100644 index 00000000000..8dda9abec07 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWoodStrippedAcacia.java @@ -0,0 +1,29 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockWoodStrippedAcacia extends BlockWoodStripped { + + public BlockWoodStrippedAcacia() { + this(0); + } + + public BlockWoodStrippedAcacia(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Stripped Acacia Log"; + } + + @Override + public int getId() { + return STRIPPED_ACACIA_LOG; + } + + @Override + public BlockColor getColor() { + return BlockColor.ORANGE_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWoodStrippedBirch.java b/src/main/java/cn/nukkit/block/BlockWoodStrippedBirch.java new file mode 100644 index 00000000000..116747d2844 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWoodStrippedBirch.java @@ -0,0 +1,29 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockWoodStrippedBirch extends BlockWoodStripped { + + public BlockWoodStrippedBirch() { + this(0); + } + + public BlockWoodStrippedBirch(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Stripped Birch Log"; + } + + @Override + public int getId() { + return STRIPPED_BIRCH_LOG; + } + + @Override + public BlockColor getColor() { + return BlockColor.SAND_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWoodStrippedDarkOak.java b/src/main/java/cn/nukkit/block/BlockWoodStrippedDarkOak.java new file mode 100644 index 00000000000..63466210a97 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWoodStrippedDarkOak.java @@ -0,0 +1,29 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockWoodStrippedDarkOak extends BlockWoodStripped { + + public BlockWoodStrippedDarkOak() { + this(0); + } + + public BlockWoodStrippedDarkOak(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Stripped Dark Oak Log"; + } + + @Override + public int getId() { + return STRIPPED_DARK_OAK_LOG; + } + + @Override + public BlockColor getColor() { + return BlockColor.BROWN_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWoodStrippedJungle.java b/src/main/java/cn/nukkit/block/BlockWoodStrippedJungle.java new file mode 100644 index 00000000000..04f8d706fc4 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWoodStrippedJungle.java @@ -0,0 +1,29 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockWoodStrippedJungle extends BlockWoodStripped { + + public BlockWoodStrippedJungle() { + this(0); + } + + public BlockWoodStrippedJungle(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Stripped Jungle Log"; + } + + @Override + public int getId() { + return STRIPPED_JUNGLE_LOG; + } + + @Override + public BlockColor getColor() { + return BlockColor.DIRT_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWoodStrippedOak.java b/src/main/java/cn/nukkit/block/BlockWoodStrippedOak.java new file mode 100644 index 00000000000..7a3bae4643f --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWoodStrippedOak.java @@ -0,0 +1,28 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockWoodStrippedOak extends BlockWoodStripped { + + public BlockWoodStrippedOak() { + this(0); + } + + public BlockWoodStrippedOak(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Stripped Oak Log"; + } + + @Override + public int getId() { + return STRIPPED_OAK_LOG; + } + @Override + public BlockColor getColor() { + return BlockColor.WOOD_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/BlockWoodStrippedSpruce.java b/src/main/java/cn/nukkit/block/BlockWoodStrippedSpruce.java new file mode 100644 index 00000000000..1154cad9487 --- /dev/null +++ b/src/main/java/cn/nukkit/block/BlockWoodStrippedSpruce.java @@ -0,0 +1,28 @@ +package cn.nukkit.block; + +import cn.nukkit.utils.BlockColor; + +public class BlockWoodStrippedSpruce extends BlockWoodStripped { + + public BlockWoodStrippedSpruce() { + this(0); + } + + public BlockWoodStrippedSpruce(int meta) { + super(meta); + } + + @Override + public String getName() { + return "Stripped Spruce Log"; + } + + @Override + public int getId() { + return STRIPPED_SPRUCE_LOG; + } + @Override + public BlockColor getColor() { + return BlockColor.SPRUCE_BLOCK_COLOR; + } +} diff --git a/src/main/java/cn/nukkit/block/Blocks.java b/src/main/java/cn/nukkit/block/Blocks.java new file mode 100644 index 00000000000..d2fe4e12819 --- /dev/null +++ b/src/main/java/cn/nukkit/block/Blocks.java @@ -0,0 +1,640 @@ +package cn.nukkit.block; + +import static cn.nukkit.block.Block.list; +import static cn.nukkit.block.BlockID.*; + +class Blocks { + + static { + list[AIR] = BlockAir.class; //0 + list[STONE] = BlockStone.class; //1 + list[GRASS] = BlockGrass.class; //2 + list[DIRT] = BlockDirt.class; //3 + list[COBBLESTONE] = BlockCobblestone.class; //4 + list[PLANKS] = BlockPlanks.class; //5 + list[SAPLING] = BlockSapling.class; //6 + list[BEDROCK] = BlockBedrock.class; //7 + list[WATER] = BlockWater.class; //8 + list[STILL_WATER] = BlockWaterStill.class; //9 + list[LAVA] = BlockLava.class; //10 + list[STILL_LAVA] = BlockLavaStill.class; //11 + list[SAND] = BlockSand.class; //12 + list[GRAVEL] = BlockGravel.class; //13 + list[GOLD_ORE] = BlockOreGold.class; //14 + list[IRON_ORE] = BlockOreIron.class; //15 + list[COAL_ORE] = BlockOreCoal.class; //16 + list[WOOD] = BlockWood.class; //17 + list[LEAVES] = BlockLeaves.class; //18 + list[SPONGE] = BlockSponge.class; //19 + list[GLASS] = BlockGlass.class; //20 + list[LAPIS_ORE] = BlockOreLapis.class; //21 + list[LAPIS_BLOCK] = BlockLapis.class; //22 + list[DISPENSER] = BlockDispenser.class; //23 + list[SANDSTONE] = BlockSandstone.class; //24 + list[NOTEBLOCK] = BlockNoteblock.class; //25 + list[BED_BLOCK] = BlockBed.class; //26 + list[POWERED_RAIL] = BlockRailPowered.class; //27 + list[DETECTOR_RAIL] = BlockRailDetector.class; //28 + list[STICKY_PISTON] = BlockPistonSticky.class; //29 + list[COBWEB] = BlockCobweb.class; //30 + list[TALL_GRASS] = BlockTallGrass.class; //31 + list[DEAD_BUSH] = BlockDeadBush.class; //32 + list[PISTON] = BlockPiston.class; //33 + list[PISTON_HEAD] = BlockPistonHead.class; //34 + list[WOOL] = BlockWool.class; //35 + list[DANDELION] = BlockDandelion.class; //37 + list[FLOWER] = BlockFlower.class; //38 + list[BROWN_MUSHROOM] = BlockMushroomBrown.class; //39 + list[RED_MUSHROOM] = BlockMushroomRed.class; //40 + list[GOLD_BLOCK] = BlockGold.class; //41 + list[IRON_BLOCK] = BlockIron.class; //42 + list[DOUBLE_STONE_SLAB] = BlockDoubleSlabStone.class; //43 + list[STONE_SLAB] = BlockSlabStone.class; //44 + list[BRICKS_BLOCK] = BlockBricks.class; //45 + list[TNT] = BlockTNT.class; //46 + list[BOOKSHELF] = BlockBookshelf.class; //47 + list[MOSS_STONE] = BlockMossStone.class; //48 + list[OBSIDIAN] = BlockObsidian.class; //49 + list[TORCH] = BlockTorch.class; //50 + list[FIRE] = BlockFire.class; //51 + list[MONSTER_SPAWNER] = BlockMobSpawner.class; //52 + list[WOOD_STAIRS] = BlockStairsWood.class; //53 + list[CHEST] = BlockChest.class; //54 + list[REDSTONE_WIRE] = BlockRedstoneWire.class; //55 + list[DIAMOND_ORE] = BlockOreDiamond.class; //56 + list[DIAMOND_BLOCK] = BlockDiamond.class; //57 + list[WORKBENCH] = BlockCraftingTable.class; //58 + list[WHEAT_BLOCK] = BlockWheat.class; //59 + list[FARMLAND] = BlockFarmland.class; //60 + list[FURNACE] = BlockFurnace.class; //61 + list[BURNING_FURNACE] = BlockFurnaceBurning.class; //62 + list[SIGN_POST] = BlockSignPost.class; //63 + list[WOOD_DOOR_BLOCK] = BlockDoorWood.class; //64 + list[LADDER] = BlockLadder.class; //65 + list[RAIL] = BlockRail.class; //66 + list[COBBLESTONE_STAIRS] = BlockStairsCobblestone.class; //67 + list[WALL_SIGN] = BlockWallSign.class; //68 + list[LEVER] = BlockLever.class; //69 + list[STONE_PRESSURE_PLATE] = BlockPressurePlateStone.class; //70 + list[IRON_DOOR_BLOCK] = BlockDoorIron.class; //71 + list[WOODEN_PRESSURE_PLATE] = BlockPressurePlateWood.class; //72 + list[REDSTONE_ORE] = BlockOreRedstone.class; //73 + list[GLOWING_REDSTONE_ORE] = BlockOreRedstoneGlowing.class; //74 + list[UNLIT_REDSTONE_TORCH] = BlockRedstoneTorchUnlit.class; + list[REDSTONE_TORCH] = BlockRedstoneTorch.class; //76 + list[STONE_BUTTON] = BlockButtonStone.class; //77 + list[SNOW_LAYER] = BlockSnowLayer.class; //78 + list[ICE] = BlockIce.class; //79 + list[SNOW_BLOCK] = BlockSnow.class; //80 + list[CACTUS] = BlockCactus.class; //81 + list[CLAY_BLOCK] = BlockClay.class; //82 + list[SUGARCANE_BLOCK] = BlockSugarcane.class; //83 + list[JUKEBOX] = BlockJukebox.class; //84 + list[FENCE] = BlockFence.class; //85 + list[PUMPKIN] = BlockPumpkin.class; //86 + list[NETHERRACK] = BlockNetherrack.class; //87 + list[SOUL_SAND] = BlockSoulSand.class; //88 + list[GLOWSTONE_BLOCK] = BlockGlowstone.class; //89 + list[NETHER_PORTAL] = BlockNetherPortal.class; //90 + list[LIT_PUMPKIN] = BlockPumpkinLit.class; //91 + list[CAKE_BLOCK] = BlockCake.class; //92 + list[UNPOWERED_REPEATER] = BlockRedstoneRepeaterUnpowered.class; //93 + list[POWERED_REPEATER] = BlockRedstoneRepeaterPowered.class; //94 + list[INVISIBLE_BEDROCK] = BlockBedrockInvisible.class; //95 + list[TRAPDOOR] = BlockTrapdoor.class; //96 + list[MONSTER_EGG] = BlockMonsterEgg.class; //97 + list[STONE_BRICKS] = BlockBricksStone.class; //98 + list[BROWN_MUSHROOM_BLOCK] = BlockHugeMushroomBrown.class; //99 + list[RED_MUSHROOM_BLOCK] = BlockHugeMushroomRed.class; //100 + list[IRON_BARS] = BlockIronBars.class; //101 + list[GLASS_PANE] = BlockGlassPane.class; //102 + list[MELON_BLOCK] = BlockMelon.class; //103 + list[PUMPKIN_STEM] = BlockStemPumpkin.class; //104 + list[MELON_STEM] = BlockStemMelon.class; //105 + list[VINE] = BlockVine.class; //106 + list[FENCE_GATE] = BlockFenceGate.class; //107 + list[BRICK_STAIRS] = BlockStairsBrick.class; //108 + list[STONE_BRICK_STAIRS] = BlockStairsStoneBrick.class; //109 + list[MYCELIUM] = BlockMycelium.class; //110 + list[WATER_LILY] = BlockWaterLily.class; //111 + list[NETHER_BRICKS] = BlockBricksNether.class; //112 + list[NETHER_BRICK_FENCE] = BlockFenceNetherBrick.class; //113 + list[NETHER_BRICKS_STAIRS] = BlockStairsNetherBrick.class; //114 + list[NETHER_WART_BLOCK] = BlockNetherWart.class; //115 + list[ENCHANTING_TABLE] = BlockEnchantingTable.class; //116 + list[BREWING_STAND_BLOCK] = BlockBrewingStand.class; //117 + list[CAULDRON_BLOCK] = BlockCauldron.class; //118 + list[END_PORTAL] = BlockEndPortal.class; //119 + list[END_PORTAL_FRAME] = BlockEndPortalFrame.class; //120 + list[END_STONE] = BlockEndStone.class; //121 + list[DRAGON_EGG] = BlockDragonEgg.class; //122 + list[REDSTONE_LAMP] = BlockRedstoneLamp.class; //123 + list[LIT_REDSTONE_LAMP] = BlockRedstoneLampLit.class; //124 + list[DROPPER] = BlockDropper.class; //125 + list[ACTIVATOR_RAIL] = BlockRailActivator.class; //126 + list[COCOA] = BlockCocoa.class; //127 + list[SANDSTONE_STAIRS] = BlockStairsSandstone.class; //128 + list[EMERALD_ORE] = BlockOreEmerald.class; //129 + list[ENDER_CHEST] = BlockEnderChest.class; //130 + list[TRIPWIRE_HOOK] = BlockTripWireHook.class; + list[TRIPWIRE] = BlockTripWire.class; //132 + list[EMERALD_BLOCK] = BlockEmerald.class; //133 + list[SPRUCE_WOOD_STAIRS] = BlockStairsSpruce.class; //134 + list[BIRCH_WOOD_STAIRS] = BlockStairsBirch.class; //135 + list[JUNGLE_WOOD_STAIRS] = BlockStairsJungle.class; //136 + list[COMMAND_BLOCK] = BlockCommandBlock.class; //137 + list[BEACON] = BlockBeacon.class; //138 + list[STONE_WALL] = BlockWall.class; //139 + list[FLOWER_POT_BLOCK] = BlockFlowerPot.class; //140 + list[CARROT_BLOCK] = BlockCarrot.class; //141 + list[POTATO_BLOCK] = BlockPotato.class; //142 + list[WOODEN_BUTTON] = BlockButtonWooden.class; //143 + list[SKULL_BLOCK] = BlockSkull.class; //144 + list[ANVIL] = BlockAnvil.class; //145 + list[TRAPPED_CHEST] = BlockTrappedChest.class; //146 + list[LIGHT_WEIGHTED_PRESSURE_PLATE] = BlockWeightedPressurePlateLight.class; //147 + list[HEAVY_WEIGHTED_PRESSURE_PLATE] = BlockWeightedPressurePlateHeavy.class; //148 + list[UNPOWERED_COMPARATOR] = BlockRedstoneComparatorUnpowered.class; //149 + list[POWERED_COMPARATOR] = BlockRedstoneComparatorPowered.class; //149 + list[DAYLIGHT_DETECTOR] = BlockDaylightDetector.class; //151 + list[REDSTONE_BLOCK] = BlockRedstone.class; //152 + list[QUARTZ_ORE] = BlockOreQuartz.class; //153 + list[HOPPER_BLOCK] = BlockHopper.class; //154 + list[QUARTZ_BLOCK] = BlockQuartz.class; //155 + list[QUARTZ_STAIRS] = BlockStairsQuartz.class; //156 + list[DOUBLE_WOOD_SLAB] = BlockDoubleSlabWood.class; //157 + list[WOOD_SLAB] = BlockSlabWood.class; //158 + list[STAINED_TERRACOTTA] = BlockTerracottaStained.class; //159 + list[STAINED_GLASS_PANE] = BlockGlassPaneStained.class; //160 + list[LEAVES2] = BlockLeaves2.class; //161 + list[WOOD2] = BlockWood2.class; //162 + list[ACACIA_WOOD_STAIRS] = BlockStairsAcacia.class; //163 + list[DARK_OAK_WOOD_STAIRS] = BlockStairsDarkOak.class; //164 + list[SLIME_BLOCK] = BlockSlime.class; //165 + //list[GLOW_STICK] = BlockGlowStick.class; //166 + list[IRON_TRAPDOOR] = BlockTrapdoorIron.class; //167 + list[PRISMARINE] = BlockPrismarine.class; //168 + list[SEA_LANTERN] = BlockSeaLantern.class; //169 + list[HAY_BALE] = BlockHayBale.class; //170 + list[CARPET] = BlockCarpet.class; //171 + list[TERRACOTTA] = BlockTerracotta.class; //172 + list[COAL_BLOCK] = BlockCoal.class; //173 + list[PACKED_ICE] = BlockIcePacked.class; //174 + list[DOUBLE_PLANT] = BlockDoublePlant.class; //175 + list[STANDING_BANNER] = BlockBanner.class; //176 + list[WALL_BANNER] = BlockWallBanner.class; //177 + list[DAYLIGHT_DETECTOR_INVERTED] = BlockDaylightDetectorInverted.class; //178 + list[RED_SANDSTONE] = BlockRedSandstone.class; //179 + list[RED_SANDSTONE_STAIRS] = BlockStairsRedSandstone.class; //180 + list[DOUBLE_RED_SANDSTONE_SLAB] = BlockDoubleSlabRedSandstone.class; //181 + list[RED_SANDSTONE_SLAB] = BlockSlabRedSandstone.class; //182 + list[FENCE_GATE_SPRUCE] = BlockFenceGateSpruce.class; //183 + list[FENCE_GATE_BIRCH] = BlockFenceGateBirch.class; //184 + list[FENCE_GATE_JUNGLE] = BlockFenceGateJungle.class; //185 + list[FENCE_GATE_DARK_OAK] = BlockFenceGateDarkOak.class; //186 + list[FENCE_GATE_ACACIA] = BlockFenceGateAcacia.class; //187 + list[REPEATING_COMMAND_BLOCK] = BlockCommandBlockRepeating.class; //188 + list[CHAIN_COMMAND_BLOCK] = BlockCommandBlockChain.class; //189 + //list[HARD_GLASS_PANE] = BlockHardGlassPane.class; //190 + //list[HARD_STAINED_GLASS_PANE] = BlockHardGlassPaneStained.class; //191 + //list[CHEMICAL_HEAT] = BlockChemicalHeat.class; //192 + list[SPRUCE_DOOR_BLOCK] = BlockDoorSpruce.class; //193 + list[BIRCH_DOOR_BLOCK] = BlockDoorBirch.class; //194 + list[JUNGLE_DOOR_BLOCK] = BlockDoorJungle.class; //195 + list[ACACIA_DOOR_BLOCK] = BlockDoorAcacia.class; //196 + list[DARK_OAK_DOOR_BLOCK] = BlockDoorDarkOak.class; //197 + list[GRASS_PATH] = BlockGrassPath.class; //198 + list[ITEM_FRAME_BLOCK] = BlockItemFrame.class; //199 + list[CHORUS_FLOWER] = BlockChorusFlower.class; //200 + list[PURPUR_BLOCK] = BlockPurpur.class; //201 + //list[COLORED_TORCH_RG] = BlockColoredTorchRG.class; //202 + list[PURPUR_STAIRS] = BlockStairsPurpur.class; //203 + //list[COLORED_TORCH_BP] = BlockColoredTorchBP.class; //204 + list[UNDYED_SHULKER_BOX] = BlockUndyedShulkerBox.class; //205 + list[END_BRICKS] = BlockBricksEndStone.class; //206 + list[FROSTED_ICE] = BlockIceFrosted.class; //207 + list[END_ROD] = BlockEndRod.class; //208 + list[END_GATEWAY] = BlockEndGateway.class; //209 + list[ALLOW] = BlockAllow.class; //210 + list[DENY] = BlockDeny.class; //211 + list[BORDER_BLOCK] = BlockBorder.class; //212 + list[MAGMA] = BlockMagma.class; //213 + list[BLOCK_NETHER_WART_BLOCK] = BlockNetherWartBlock.class; //214 + list[RED_NETHER_BRICK] = BlockBricksRedNether.class; //215 + list[BONE_BLOCK] = BlockBone.class; //216 + // 217 not yet in Minecraft + list[SHULKER_BOX] = BlockShulkerBox.class; //218 + list[PURPLE_GLAZED_TERRACOTTA] = BlockTerracottaGlazedPurple.class; //219 + list[WHITE_GLAZED_TERRACOTTA] = BlockTerracottaGlazedWhite.class; //220 + list[ORANGE_GLAZED_TERRACOTTA] = BlockTerracottaGlazedOrange.class; //221 + list[MAGENTA_GLAZED_TERRACOTTA] = BlockTerracottaGlazedMagenta.class; //222 + list[LIGHT_BLUE_GLAZED_TERRACOTTA] = BlockTerracottaGlazedLightBlue.class; //223 + list[YELLOW_GLAZED_TERRACOTTA] = BlockTerracottaGlazedYellow.class; //224 + list[LIME_GLAZED_TERRACOTTA] = BlockTerracottaGlazedLime.class; //225 + list[PINK_GLAZED_TERRACOTTA] = BlockTerracottaGlazedPink.class; //226 + list[GRAY_GLAZED_TERRACOTTA] = BlockTerracottaGlazedGray.class; //227 + list[SILVER_GLAZED_TERRACOTTA] = BlockTerracottaGlazedSilver.class; //228 + list[CYAN_GLAZED_TERRACOTTA] = BlockTerracottaGlazedCyan.class; //229 + // 230 Chalkboard in Education Edition + list[BLUE_GLAZED_TERRACOTTA] = BlockTerracottaGlazedBlue.class; //231 + list[BROWN_GLAZED_TERRACOTTA] = BlockTerracottaGlazedBrown.class; //232 + list[GREEN_GLAZED_TERRACOTTA] = BlockTerracottaGlazedGreen.class; //233 + list[RED_GLAZED_TERRACOTTA] = BlockTerracottaGlazedRed.class; //234 + list[BLACK_GLAZED_TERRACOTTA] = BlockTerracottaGlazedBlack.class; //235 + list[CONCRETE] = BlockConcrete.class; //236 + list[CONCRETE_POWDER] = BlockConcretePowder.class; //237 + //list[CHEMISTRY_TABLE] = BlockChemistryTable.class; //238 + //list[UNDERWATER_TORCH] = BlockUnderwaterTorch.class; //239 + list[CHORUS_PLANT] = BlockChorusPlant.class; //240 + list[STAINED_GLASS] = BlockGlassStained.class; //241 + // 242 Camera in Education Edition + list[PODZOL] = BlockPodzol.class; //243 + list[BEETROOT_BLOCK] = BlockBeetroot.class; //244 + list[STONECUTTER] = BlockStonecutter.class; //244 + list[GLOWING_OBSIDIAN] = BlockObsidianGlowing.class; //246 + list[NETHER_REACTOR] = BlockNetherReactor.class; //247 + list[INFO_UPDATE] = BlockInfoUpdate.class; //248 + list[INFO_UPDATE2] = BlockInfoUpdate2.class; //249 + list[PISTON_EXTENSION] = BlockPistonExtension.class; //250 + list[OBSERVER] = BlockObserver.class; //251 + list[STRUCTURE_BLOCK] = BlockStructureBlock.class; //252 + //list[HARD_GLASS] = BlockHardGlass.class; //253 + //list[HARD_STAINED_GLASS] = BlockHardGlassStained.class; //254 + //list[RESERVED6] = BlockReserved6.class; //255 + // 256 not yet in Minecraft + list[PRISMARINE_STAIRS] = BlockStairsPrismarine.class; //257 + list[DARK_PRISMARINE_STAIRS] = BlockStairsDarkPrismarine.class; //258 + list[PRISMARINE_BRICKS_STAIRS] = BlockStairsPrismarineBrick.class; //259 + list[STRIPPED_SPRUCE_LOG] = BlockWoodStrippedSpruce.class; //260 + list[STRIPPED_BIRCH_LOG] = BlockWoodStrippedBirch.class; //261 + list[STRIPPED_JUNGLE_LOG] = BlockWoodStrippedJungle.class; //262 + list[STRIPPED_ACACIA_LOG] = BlockWoodStrippedAcacia.class; //263 + list[STRIPPED_DARK_OAK_LOG] = BlockWoodStrippedDarkOak.class; //264 + list[STRIPPED_OAK_LOG] = BlockWoodStrippedOak.class; //265 + list[BLUE_ICE] = BlockBlueIce.class; //266 + // + list[SEAGRASS] = BlockSeagrass.class; //385 + list[CORAL] = BlockCoral.class; //386 + list[CORAL_BLOCK] = BlockCoralBlock.class; //387 + list[CORAL_FAN] = BlockCoralFan.class; //388 + list[CORAL_FAN_DEAD] = BlockCoralFanDead.class; //389 + list[CORAL_FAN_HANG] = BlockCoralFanHang.class; //390 + list[CORAL_FAN_HANG2] = BlockCoralFanHang2.class; //391 + list[CORAL_FAN_HANG3] = BlockCoralFanHang3.class; //392 + list[BLOCK_KELP] = BlockKelp.class; //393 + list[DRIED_KELP_BLOCK] = BlockDriedKelpBlock.class; //394 + list[ACACIA_BUTTON] = BlockButtonAcacia.class; //395 + list[BIRCH_BUTTON] = BlockButtonBirch.class; //396 + list[DARK_OAK_BUTTON] = BlockButtonDarkOak.class; //397 + list[JUNGLE_BUTTON] = BlockButtonJungle.class; //398 + list[SPRUCE_BUTTON] = BlockButtonSpruce.class; //399 + list[ACACIA_TRAPDOOR] = BlockTrapdoorAcacia.class; //400 + list[BIRCH_TRAPDOOR] = BlockTrapdoorBirch.class; //401 + list[DARK_OAK_TRAPDOOR] = BlockTrapdoorDarkOak.class; //402 + list[JUNGLE_TRAPDOOR] = BlockTrapdoorJungle.class; //403 + list[SPRUCE_TRAPDOOR] = BlockTrapdoorSpruce.class; //404 + list[ACACIA_PRESSURE_PLATE] = BlockPressurePlateAcacia.class; //405 + list[BIRCH_PRESSURE_PLATE] = BlockPressurePlateBirch.class; //406 + list[DARK_OAK_PRESSURE_PLATE] = BlockPressurePlateDarkOak.class; //407 + list[JUNGLE_PRESSURE_PLATE] = BlockPressurePlateJungle.class; //408 + list[SPRUCE_PRESSURE_PLATE] = BlockPressurePlateSpruce.class; //409 + list[CARVED_PUMPKIN] = BlockPumpkinCarved.class; //410 + list[SEA_PICKLE] = BlockSeaPickle.class; //411 + list[CONDUIT] = BlockConduit.class; //412 + // + list[TURTLE_EGG] = BlockTurtleEgg.class; //414 + list[BUBBLE_COLUMN] = BlockBubbleColumn.class; //415 + list[BARRIER] = BlockBarrier.class; //416 + list[STONE_SLAB3] = BlockSlabStone3.class; //417 + list[BAMBOO] = BlockBamboo.class; //418 + list[BAMBOO_SAPLING] = BlockBambooSapling.class; //419 + list[STONE_SLAB4] = BlockSlabStone4.class; //421 + list[SCAFFOLDING] = BlockScaffolding.class; //420 + list[DOUBLE_STONE_SLAB3] = BlockDoubleSlabStone3.class; //422 + list[DOUBLE_STONE_SLAB4] = BlockDoubleSlabStone4.class; //423 + list[GRANITE_STAIRS] = BlockStairsGranite.class; //424 + list[DIORITE_STAIRS] = BlockStairsDiorite.class; //425 + list[ANDESITE_STAIRS] = BlockStairsAndesite.class; //426 + list[POLISHED_GRANITE_STAIRS] = BlockStairsGranitePolished.class; //427 + list[POLISHED_DIORITE_STAIRS] = BlockStairsDioritePolished.class; //428 + list[POLISHED_ANDESITE_STAIRS] = BlockStairsAndesitePolished.class; //429 + list[MOSSY_STONE_BRICK_STAIRS] = BlockStairsMossyStoneBrick.class; //430 + list[SMOOTH_RED_SANDSTONE_STAIRS] = BlockStairsSmoothRedSandstone.class; //431 + list[SMOOTH_SANDSTONE_STAIRS] = BlockStairsSmoothSandstone.class; //432 + list[END_BRICK_STAIRS] = BlockStairsEndBrick.class; //433 + list[MOSSY_COBBLESTONE_STAIRS] = BlockStairsMossyCobblestone.class; //434 + list[NORMAL_STONE_STAIRS] = BlockStairsStone.class; //435 + list[SPRUCE_STANDING_SIGN] = BlockSpruceSignStanding.class; //436 + list[SPRUCE_WALL_SIGN] = BlockSpruceWallSign.class; //437 + list[SMOOTH_STONE] = BlockSmoothStone.class; //438 + list[RED_NETHER_BRICK_STAIRS] = BlockStairsRedNetherBrick.class; //439 + list[SMOOTH_QUARTZ_STAIRS] = BlockStairsSmoothQuartz.class; //440 + list[BIRCH_STANDING_SIGN] = BlockBirchSignStanding.class; //441 + list[BIRCH_WALL_SIGN] = BlockBirchWallSign.class; //442 + list[JUNGLE_STANDING_SIGN] = BlockJungleSignStanding.class; //443 + list[JUNGLE_WALL_SIGN] = BlockJungleWallSign.class; //444 + list[ACACIA_STANDING_SIGN] = BlockAcaciaSignStanding.class; //445 + list[ACACIA_WALL_SIGN] = BlockAcaciaWallSign.class; //446 + list[DARK_OAK_STANDING_SIGN] = BlockDarkOakSignStanding.class; //447 + list[DARK_OAK_WALL_SIGN] = BlockDarkOakWallSign.class; //448 + list[LECTERN] = BlockLectern.class; //449 + list[GRINDSTONE] = BlockGrindstone.class; //450 + list[BLAST_FURNACE] = BlockBlastFurnace.class; //451 + list[STONECUTTER_BLOCK] = BlockStonecutterBlock.class; //452 + list[SMOKER] = BlockSmoker.class; //453 + list[LIT_SMOKER] = BlockSmokerLit.class; //454 + list[CARTOGRAPHY_TABLE] = BlockCartographyTable.class; //455 + list[FLETCHING_TABLE] = BlockFletchingTable.class; //456 + list[SMITHING_TABLE] = BlockSmithingTable.class; //457 + list[BARREL] = BlockBarrel.class; //458 + list[LOOM] = BlockLoom.class; //459 + // + list[BELL] = BlockBell.class; //461 + list[SWEET_BERRY_BUSH] = BlockSweetBerryBush.class; //462 + list[LANTERN] = BlockLantern.class; //463 + list[CAMPFIRE_BLOCK] = BlockCampfire.class; //464 + list[LAVA_CAULDRON] = BlockCauldronLava.class; //465 + list[JIGSAW] = BlockJigsaw.class; //466 + list[WOOD_BARK] = BlockWoodBark.class; //467 + list[COMPOSTER] = BlockComposter.class; //468 + list[LIT_BLAST_FURNACE] = BlockBlastFurnaceLit.class; //469 + list[LIGHT_BLOCK] = BlockLightBlock.class; //470 + list[WITHER_ROSE] = BlockWitherRose.class; //471 + list[PISTON_HEAD_STICKY] = BlockPistonHeadSticky.class; //472 + list[BEE_NEST] = BlockBeeNest.class; //473 + list[BEEHIVE] = BlockBeehive.class; //474 + list[HONEY_BLOCK] = BlockHoneyBlock.class; //475 + list[HONEYCOMB_BLOCK] = BlockHoneycombBlock.class; //476 + list[LODESTONE] = BlockLodestone.class; //477 + list[CRIMSON_ROOTS] = BlockCrimsonRoots.class; //478 + list[WARPED_ROOTS] = BlockWarpedRoots.class; //479 + list[CRIMSON_STEM] = BlockCrimsonStem.class; //480 + list[WARPED_STEM] = BlockWarpedStem.class; //481 + list[WARPED_WART_BLOCK] = BlockWarpedWartBlock.class; //482 + list[CRIMSON_FUNGUS] = BlockCrimsonFungus.class; //483 + list[WARPED_FUNGUS] = BlockWarpedFungus.class; //484 + list[SHROOMLIGHT] = BlockShroomlight.class; //485 + list[WEEPING_VINES] = BlockWeepingVines.class; //486 + list[CRIMSON_NYLIUM] = BlockCrimsonNylium.class; //487 + list[WARPED_NYLIUM] = BlockWarpedNylium.class; //488 + list[BASALT] = BlockBasalt.class; //489 + list[POLISHED_BASALT] = BlockPolishedBasalt.class; //490 + list[SOUL_SOIL] = BlockSoulSoil.class; //491 + list[SOUL_FIRE] = BlockSoulFire.class; //492 + list[NETHER_SPROUTS_BLOCK] = BlockNetherSprouts.class; //493 + list[TARGET] = BlockTarget.class; //494 + list[STRIPPED_CRIMSON_STEM] = BlockStrippedCrimsonStem.class; //495 + list[STRIPPED_WARPED_STEM] = BlockStrippedWarpedStem.class; //496 + list[CRIMSON_PLANKS] = BlockCrimsonPlanks.class; //497 + list[WARPED_PLANKS] = BlockWarpedPlanks.class; //498 + list[CRIMSON_DOOR_BLOCK] = BlockCrimsonDoor.class; //499 + list[WARPED_DOOR_BLOCK] = BlockWarpedDoor.class; //500 + list[CRIMSON_TRAPDOOR] = BlockCrimsonTrapdoor.class; //501 + list[WARPED_TRAPDOOR] = BlockWarpedTrapdoor.class; //502 + // + list[CRIMSON_STANDING_SIGN] = BlockCrimsonSign.class; //505 + list[WARPED_STANDING_SIGN] = BlockWarpedSign.class; //506 + list[CRIMSON_WALL_SIGN] = BlockCrimsonWallSign.class; //507 + list[WARPED_WALL_SIGN] = BlockWarpedWallSign.class; //508 + list[CRIMSON_STAIRS] = BlockCrimsonStairs.class; //509 + list[WARPED_STAIRS] = BlockWarpedStairs.class; //510 + list[CRIMSON_FENCE] = BlockFenceCrimson.class; // 511 + list[WARPED_FENCE] = BlockFenceWarped.class; // 512 + list[CRIMSON_FENCE_GATE] = BlockFenceGateCrimson.class; // 513 + list[WARPED_FENCE_GATE] = BlockFenceGateWarped.class; // 514 + list[CRIMSON_BUTTON] = BlockButtonCrimson.class; // 515 + list[WARPED_BUTTON] = BlockButtonWarped.class; // 516 + list[CRIMSON_PRESSURE_PLATE] = BlockPressurePlateCrimson.class; // 517 + list[WARPED_PRESSURE_PLATE] = BlockPressurePlateWarped.class; // 518 + list[CRIMSON_SLAB] = BlockSlabCrimson.class; //519 + list[WARPED_SLAB] = BlockSlabWarped.class; //520 + list[CRIMSON_DOUBLE_SLAB] = BlockDoubleSlabCrimson.class; //521 + list[WARPED_DOUBLE_SLAB] = BlockDoubleSlabWarped.class; //522 + list[SOUL_TORCH] = BlockSoulTorch.class; //523 + list[SOUL_LANTERN] = BlockSoulLantern.class; //524 + list[NETHERITE_BLOCK] = BlockNetheriteBlock.class; //525 + list[ANCIENT_DEBRIS] = BlockAncientDebris.class; //526 + list[RESPAWN_ANCHOR] = BlockRespawnAnchor.class; //527 + list[BLACKSTONE] = BlockBlackstone.class; //528 + list[POLISHED_BLACKSTONE_BRICKS] = BlockBricksBlackstonePolished.class; //529 + list[POLISHED_BLACKSTONE_BRICK_STAIRS] = BlockStairsBrickBlackstonePolished.class; //530 + list[BLACKSTONE_STAIRS] = BlockStairsBlackstone.class; //531 + list[BLACKSTONE_WALL] = BlockBlackstoneWall.class; //532 + list[POLISHED_BLACKSTONE_BRICK_WALL] = BlockPolishedBlackstoneBrickWall.class; //533 + list[CHISELED_POLISHED_BLACKSTONE] = BlockBlackstonePolishedChiseled.class; //534 + list[CRACKED_POLISHED_BLACKSTONE_BRICKS] = BlockBricksBlackstonePolishedCracked.class; //535 + list[GILDED_BLACKSTONE] = BlockBlackstoneGilded.class; //536 + list[BLACKSTONE_SLAB] = BlockSlabBlackstone.class; //537 + list[BLACKSTONE_DOUBLE_SLAB] = BlockDoubleSlabBlackstone.class; //538 + list[POLISHED_BLACKSTONE_BRICK_SLAB] = BlockSlabBrickBlackstonePolished.class; //539 + list[POLISHED_BLACKSTONE_BRICK_DOUBLE_SLAB] = BlockDoubleSlabBrickBlackstonePolished.class; //540 + list[CHAIN_BLOCK] = BlockChain.class; //541 + list[TWISTING_VINES] = BlockVinesTwisting.class; //542 + list[NETHER_GOLD_ORE] = BlockOreGoldNether.class; //543 + list[CRYING_OBSIDIAN] = BlockObsidianCrying.class; //544 + list[SOUL_CAMPFIRE_BLOCK] = BlockCampfireSoul.class; //545 + list[POLISHED_BLACKSTONE] = BlockBlackstonePolished.class; //546 + list[POLISHED_BLACKSTONE_STAIRS] = BlockStairsBlackstonePolished.class; //547 + list[POLISHED_BLACKSTONE_SLAB] = BlockSlabBlackstonePolished.class; //548 + list[POLISHED_BLACKSTONE_DOUBLE_SLAB] = BlockDoubleSlabBlackstonePolished.class; //549 + list[POLISHED_BLACKSTONE_PRESSURE_PLATE] = BlockPressurePlatePolishedBlackstone.class; //550 + list[POLISHED_BLACKSTONE_BUTTON] = BlockButtonPolishedBlackstone.class; //551 + list[POLISHED_BLACKSTONE_WALL] = BlockPolishedBlackstoneWall.class; //552 + list[WARPED_HYPHAE] = BlockHyphaeWarped.class; //553 + list[CRIMSON_HYPHAE] = BlockHyphaeCrimson.class; //554 + list[STRIPPED_CRIMSON_HYPHAE] = BlockHyphaeStrippedCrimson.class; //555 + list[STRIPPED_WARPED_HYPHAE] = BlockHyphaeStrippedWarped.class; //556 + list[CHISELED_NETHER_BRICKS] = BlockBricksNetherChiseled.class; //557 + list[CRACKED_NETHER_BRICKS] = BlockBricksNetherCracked.class; //558 + list[QUARTZ_BRICKS] = BlockQuartzBricks.class; //559 + // + list[POWDER_SNOW] = BlockPowderSnow.class; // 561 + list[SCULK_SENSOR] = BlockSculkSensor.class; // 562 + list[POINTED_DRIPSTONE] = BlockPointedDripstone.class; // 563 + // + list[COPPER_ORE] = BlockOreCopper.class; //566 + list[LIGHTNING_ROD] = BlockLightningRod.class; //567 + // + list[DRIPSTONE_BLOCK] = BlockDripstone.class; //572 + list[ROOTED_DIRT] = BlockDirtRooted.class; //573 + list[HANGING_ROOTS] = BlockRootsHanging.class; //574 + list[MOSS_BLOCK] = BlockMoss.class; //575 + list[SPORE_BLOSSOM] = BlockSporeBlossom.class; //576 + list[CAVE_VINES] = BlockCaveVines.class; //577 + list[BIG_DRIPLEAF] = BlockDripleafBig.class; //578 + list[AZALEA_LEAVES] = BlockAzaleaLeaves.class; //579 + list[AZALEA_LEAVES_FLOWERED] = BlockAzaleaLeavesFlowered.class; //580 + list[CALCITE] = BlockCalcite.class; //581 + list[AMETHYST_BLOCK] = BlockAmethyst.class; //582 + list[BUDDING_AMETHYST] = BlockBuddingAmethyst.class; //583 + list[AMETHYST_CLUSTER] = BlockAmethystCluster.class; //584 + list[LARGE_AMETHYST_BUD] = BlockAmethystBudLarge.class; //585 + list[MEDIUM_AMETHYST_BUD] = BlockAmethystBudMedium.class; //586 + list[SMALL_AMETHYST_BUD] = BlockAmethystBudSmall.class; //587 + list[TUFF] = BlockTuff.class; //588 + list[TINTED_GLASS] = BlockGlassTinted.class; //589 + list[MOSS_CARPET] = BlockMossCarpet.class; //590 + list[SMALL_DRIPLEAF] = BlockDripleafSmall.class; //591 + list[AZALEA] = BlockAzalea.class; //592 + list[FLOWERING_AZALEA] = BlockAzaleaFlowering.class; //593 + list[GLOW_FRAME] = BlockItemFrameGlow.class; //594 + list[COPPER_BLOCK] = BlockCopper.class; //595 + list[EXPOSED_COPPER] = BlockCopperExposed.class; //596 + list[WEATHERED_COPPER] = BlockCopperWeathered.class; //597 + list[OXIDIZED_COPPER] = BlockCopperOxidized.class; //598 + list[WAXED_COPPER] = BlockCopperWaxed.class; //599 + list[WAXED_EXPOSED_COPPER] = BlockCopperExposedWaxed.class; //600 + list[WAXED_WEATHERED_COPPER] = BlockCopperWeatheredWaxed.class; //601 + list[CUT_COPPER] = BlockCopperCut.class; //602 + list[EXPOSED_CUT_COPPER] = BlockCopperCutExposed.class; //603 + list[WEATHERED_CUT_COPPER] = BlockCopperCutWeathered.class; //604 + list[OXIDIZED_CUT_COPPER] = BlockCopperCutOxidized.class; //605 + list[WAXED_CUT_COPPER] = BlockCopperCutWaxed.class; //606 + list[WAXED_EXPOSED_CUT_COPPER] = BlockCopperCutExposedWaxed.class; //607 + list[WAXED_WEATHERED_CUT_COPPER] = BlockCopperCutWeatheredWaxed.class; //608 + list[CUT_COPPER_STAIRS] = BlockStairsCopperCut.class; //609 + list[EXPOSED_CUT_COPPER_STAIRS] = BlockStairsCopperCutExposed.class; //610 + list[WEATHERED_CUT_COPPER_STAIRS] = BlockStairsCopperCutWeathered.class; //611 + list[OXIDIZED_CUT_COPPER_STAIRS] = BlockStairsCopperCutOxidized.class; //612 + list[WAXED_CUT_COPPER_STAIRS] = BlockStairsCopperCutWaxed.class; //613 + list[WAXED_EXPOSED_CUT_COPPER_STAIRS] = BlockStairsCopperCutExposedWaxed.class; //614 + list[WAXED_WEATHERED_CUT_COPPER_STAIRS] = BlockStairsCopperCutWeatheredWaxed.class; //615 + list[CUT_COPPER_SLAB] = BlockSlabCopperCut.class; //616 + list[EXPOSED_CUT_COPPER_SLAB] = BlockSlabCopperCutExposed.class; //617 + list[WEATHERED_CUT_COPPER_SLAB] = BlockSlabCopperCutWeathered.class; //618 + list[OXIDIZED_CUT_COPPER_SLAB] = BlockSlabCopperCutOxidized.class; //619 + list[WAXED_CUT_COPPER_SLAB] = BlockSlabCopperCutWaxed.class; //620 + list[WAXED_EXPOSED_CUT_COPPER_SLAB] = BlockSlabCopperCutExposedWaxed.class; //621 + list[WAXED_WEATHERED_CUT_COPPER_SLAB] = BlockSlabCopperCutWeatheredWaxed.class; //622 + list[DOUBLE_CUT_COPPER_SLAB] = BlockDoubleSlabCopperCut.class; //623 + list[EXPOSED_DOUBLE_CUT_COPPER_SLAB] = BlockDoubleSlabCopperCutExposed.class; //624 + list[WEATHERED_DOUBLE_CUT_COPPER_SLAB] = BlockDoubleSlabCopperCutWeathered.class; //625 + list[OXIDIZED_DOUBLE_CUT_COPPER_SLAB] = BlockDoubleSlabCopperCutOxidized.class; //626 + list[WAXED_DOUBLE_CUT_COPPER_SLAB] = BlockDoubleSlabCopperCutWaxed.class; //627 + list[WAXED_EXPOSED_DOUBLE_CUT_COPPER_SLAB] = BlockDoubleSlabCopperCutExposedWaxed.class; //628 + list[WAXED_WEATHERED_DOUBLE_CUT_COPPER_SLAB] = BlockDoubleSlabCopperCutWeatheredWaxed.class; //629 + list[CAVE_VINES_BODY_WITH_BERRIES] = BlockCaveVinesBerriesBody.class; //630 + list[CAVE_VINES_HEAD_WITH_BERRIES] = BlockCaveVinesBerriesHead.class; //631 + list[SMOOTH_BASALT] = BlockBasaltSmooth.class; //632 + list[DEEPSLATE] = BlockDeepslate.class; //633 + list[COBBLED_DEEPSLATE] = BlockDeepslateCobbled.class; //634 + list[COBBLED_DEEPSLATE_SLAB] = BlockSlabDeepslateCobbled.class; //635 + list[COBBLED_DEEPSLATE_STAIRS] = BlockStairsDeepslateCobbled.class; //636 + list[COBBLED_DEEPSLATE_WALL] = BlockWallDeepslateCobbled.class; //637 + list[POLISHED_DEEPSLATE] = BlockDeepslatePolished.class; //638 + list[POLISHED_DEEPSLATE_SLAB] = BlockSlabDeepslatePolished.class; //639 + list[POLISHED_DEEPSLATE_STAIRS] = BlockStairsDeepslatePolished.class; //640 + list[POLISHED_DEEPSLATE_WALL] = BlockWallDeepslatePolished.class; //641 + list[DEEPSLATE_TILES] = BlockTilesDeepslate.class; //642 + list[DEEPSLATE_TILE_SLAB] = BlockSlabTileDeepslate.class; //643 + list[DEEPSLATE_TILE_STAIRS] = BlockStairsTileDeepslate.class; //644 + list[DEEPSLATE_TILE_WALL] = BlockWallTileDeepslate.class; //645 + list[DEEPSLATE_BRICKS] = BlockBricksDeepslate.class; //646 + list[DEEPSLATE_BRICK_SLAB] = BlockSlabBrickDeepslate.class; //647 + list[DEEPSLATE_BRICK_STAIRS] = BlockStairsBrickDeepslate.class; //648 + list[DEEPSLATE_BRICK_WALL] = BlockWallBrickDeepslate.class; //649 + list[CHISELED_DEEPSLATE] = BlockDeepslateChiseled.class; //650 + list[COBBLED_DEEPSLATE_DOUBLE_SLAB] = BlockDoubleSlabDeepslateCobbled.class; //651 + list[POLISHED_DEEPSLATE_DOUBLE_SLAB] = BlockDoubleSlabDeepslatePolished.class; //652 + list[DEEPSLATE_TILE_DOUBLE_SLAB] = BlockDoubleSlabTileDeepslate.class; //653 + list[DEEPSLATE_BRICK_DOUBLE_SLAB] = BlockDoubleSlabBrickDeepslate.class; //654 + list[DEEPSLATE_LAPIS_ORE] = BlockOreLapisDeepslate.class; //655 + list[DEEPSLATE_IRON_ORE] = BlockOreIronDeepslate.class; //656 + list[DEEPSLATE_GOLD_ORE] = BlockOreGoldDeepslate.class; //657 + list[DEEPSLATE_REDSTONE_ORE] = BlockOreRedstoneDeepslate.class; //658 + list[LIT_DEEPSLATE_REDSTONE_ORE] = BlockOreRedstoneDeepslateGlowing.class; //659 + list[DEEPSLATE_DIAMOND_ORE] = BlockOreDiamondDeepslate.class; //660 + list[DEEPSLATE_COAL_ORE] = BlockOreCoalDeepslate.class; //661 + list[DEEPSLATE_EMERALD_ORE] = BlockOreEmeraldDeepslate.class; //662 + list[DEEPSLATE_COPPER_ORE] = BlockOreCopperDeepslate.class; //663 + list[CRACKED_DEEPSLATE_TILES] = BlockTilesDeepslateCracked.class; //664 + list[CRACKED_DEEPSLATE_BRICKS] = BlockBricksDeepslateCracked.class; //665 + list[GLOW_LICHEN] = BlockGlowLichen.class; //666 + /*list[CANDLE] = BlockCandle.class; //667 + list[WHITE_CANDLE] = BlockCandleWhite.class; //668 + list[ORANGE_CANDLE] = BlockCandleOrange.class; //669 + list[MAGENTA_CANDLE] = BlockCandleMagenta.class; //670 + list[LIGHT_BLUE_CANDLE] = BlockCandleLightBlue.class; //671 + list[YELLOW_CANDLE] = BlockCandleYellow.class; //672 + list[LIME_CANDLE] = BlockCandleLime.class; //673 + list[PINK_CANDLE] = BlockCandlePink.class; //674 + list[GRAY_CANDLE] = BlockCandleGray.class; //675 + list[LIGHT_GRAY_CANDLE] = BlockCandleLightGray.class; //676 + list[CYAN_CANDLE] = BlockCandleCyan.class; //677 + list[PURPLE_CANDLE] = BlockCandlePurple.class; //678 + list[BLUE_CANDLE] = BlockCandleBlue.class; //679 + list[BROWN_CANDLE] = BlockCandleBrown.class; //680 + list[GREEN_CANDLE] = BlockCandleGreen.class; //681 + list[RED_CANDLE] = BlockCandleRed.class; //682 + list[BLACK_CANDLE] = BlockCandleBlack.class; //683 + list[CANDLE_CAKE] = BlockCandle.class; //684 + list[WHITE_CANDLE_CAKE] = BlockCandleCakeWhite.class; //685 + list[ORANGE_CANDLE_CAKE] = BlockCandleCakeOrange.class; //686 + list[MAGENTA_CANDLE_CAKE] = BlockCandleCakeMagenta.class; //687 + list[LIGHT_BLUE_CANDLE_CAKE] = BlockCandleCakeLightBlue.class; //688 + list[YELLOW_CANDLE_CAKE] = BlockCandleCakeYellow.class; //689 + list[LIME_CANDLE_CAKE] = BlockCandleCakeLime.class; //690 + list[PINK_CANDLE_CAKE] = BlockCandleCakePink.class; //691 + list[GRAY_CANDLE_CAKE] = BlockCandleCakeGray.class; //692 + list[LIGHT_GRAY_CANDLE_CAKE] = BlockCandleCakeLightGray.class; //693 + list[CYAN_CANDLE_CAKE] = BlockCandleCakeCyan.class; //694 + list[PURPLE_CANDLE_CAKE] = BlockCandleCakePurple.class; //6965 + list[BLUE_CANDLE_CAKE] = BlockCandleCakeBlue.class; //696 + list[BROWN_CANDLE_CAKE] = BlockCandleCakeBrown.class; //697 + list[GREEN_CANDLE_CAKE] = BlockCandleCakeGreen.class; //698 + list[RED_CANDLE_CAKE] = BlockCandleCakeRed.class; //699 + list[BLACK_CANDLE_CAKE] = BlockCandleCakeBlack.class; //700*/ + list[WAXED_OXIDIZED_COPPER] = BlockCopperOxidizedWaxed.class; //701 + list[WAXED_OXIDIZED_CUT_COPPER] = BlockCopperCutOxidizedWaxed.class; //702 + list[WAXED_OXIDIZED_CUT_COPPER_STAIRS] = BlockStairsCopperCutOxidizedWaxed.class; //703 + list[WAXED_OXIDIZED_CUT_COPPER_SLAB] = BlockSlabCopperCutOxidizedWaxed.class; //704 + list[WAXED_OXIDIZED_DOUBLE_CUT_COPPER_SLAB] = BlockDoubleSlabCopperCutOxidizedWaxed.class; //705 + list[RAW_IRON_BLOCK] = BlockRawIron.class; //706 + list[RAW_COPPER_BLOCK] = BlockRawCopper.class; //707 + list[RAW_GOLD_BLOCK] = BlockRawGold.class; //708 + list[INFESTED_DEEPSLATE] = BlockInfestedDeepslate.class; //709 + // + list[SCULK] = BlockSculk.class; //713 + //list[SCULK_VEIN] = BlockSculkVein.class; //714 + list[SCULK_CATALYST] = BlockSculkCatalyst.class; //715 + list[SCULK_SHRIEKER] = BlockSculkShrieker.class; //716 + // + list[REINFORCED_DEEPSLATE] = BlockReinforcedDeeplsate.class; //721 + // + list[FROG_SPAWN] = BlockFrogspawn.class; //723 + list[PEARLESCENT_FROGLIGHT] = BlockFroglightPearlescent.class; //724 + list[VERDANT_FROGLIGHT] = BlockFroglightVerdant.class; //725 + list[OCHRE_FROGLIGHT] = BlockFroglightOchre.class; //726 + //list[MANGROVE_LEAVES] = BlockLeavesMangrove.class; //727 + list[MUD] = BlockMud.class; //728 + list[MANGROVE_PROPAGULE] = BlockMangrovePropagule.class; //729 + list[MUD_BRICKS] = BlockMudBrick.class; //730 + list[PACKED_MUD] = BlockPackedMud.class; //732 + list[MUD_BRICK_SLAB] = BlockMudBrickSlab.class; //733 + list[MUD_BRICK_DOUBLE_SLAB] = BlockDoubleMudBrickSlab.class; //734 + list[MUD_BRICK_STAIRS] = BlockMudBrickStairs.class; //735 + list[MUD_BRICK_WALL] = BlockMudBrickWall.class; //736 + list[MANGROVE_ROOTS] = BlockMangroveRoots.class; //737 + //list[MUDDY_MANGROVE_ROOTS] = BlockMangroveRootsMuddy.class; //738 + //list[MANGROVE_LOG] = .class; //739 + //list[STRIPPED_MANGROVE_LOG] = .class; //740 + //list[MANGROVE_PLANKS] = .class; //741 + //list[MANGROVE_BUTTON] = .class; //742 + //list[MANGROVE_STAIRS] = .class; //743 + //list[MANGROVE_SLAB] = .class; //744 + //list[MANGROVE_PRESSURE_PLATE] = .class; //745 + //list[MANGROVE_FENCE] = .class; //746 + //list[MANGROVE_FENCE_GATE] = .class; //747 + // + //list[MANGROVE_STANDING_SIGN] = .class; //749 + //list[MANGROVE_WALL_SIGN] = .class; //750 + //list[MANGROVE_TRAPDOOR] = .class; //751 + //list[MANGROVE_WOOD] = .class; //752 + //list[STRIPPED_MANGROVE_WOOD] = .class; //753 + //list[MANGROVE_DOUBLE_SLAB] = .class; //754 + } + + static void init() { + // Init + } +} diff --git a/src/main/java/cn/nukkit/block/Oxidizable.java b/src/main/java/cn/nukkit/block/Oxidizable.java new file mode 100644 index 00000000000..7c9869f2c2b --- /dev/null +++ b/src/main/java/cn/nukkit/block/Oxidizable.java @@ -0,0 +1,118 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.block.properties.OxidizationLevel; +import cn.nukkit.event.block.BlockFadeEvent; +import cn.nukkit.item.Item; +import cn.nukkit.level.Level; +import cn.nukkit.level.Location; +import cn.nukkit.level.Position; +import cn.nukkit.level.particle.ScrapeParticle; + +import java.util.concurrent.ThreadLocalRandom; + +/** + * @author joserobjr + */ +public interface Oxidizable { + + Location getLocation(); + + default int onUpdate(int type) { + if (type != Level.BLOCK_UPDATE_RANDOM) { + return 0; + } + ThreadLocalRandom random = ThreadLocalRandom.current(); + if (!(random.nextFloat() < 64F / 1125F)) { + return 0; + } + + int oxiLvl = this.getOxidizationLevel().ordinal(); + if (oxiLvl == OxidizationLevel.OXIDIZED.ordinal()) { + return 0; + } + + // Just to make sure we don't accidentally degrade a waxed block. + if ((this instanceof Waxable) && ((Waxable) this).isWaxed()) { + return 0; + } + + Block block = this instanceof Block? (Block) this : getLocation().getLevelBlock(); + Location mutableLocation = block.getLocation(); + + int odds = 0; + int cons = 0; + + scan: + for (int x = -4; x <= 4; x++) { + for (int y = -4; y <= 4; y++) { + for (int z = -4; z <= 4; z++) { + if (x == 0 && y == 0 && z == 0) { + continue; + } + mutableLocation.setComponents(block.x + x, block.y + y, block.z + z); + if (block.distanceSquared(mutableLocation) > 4) { + continue ; + } + Block relative = mutableLocation.getLevelBlock(); + if (!(relative instanceof Oxidizable)) { + continue; + } + int relOxiLvl = ((Oxidizable) relative).getOxidizationLevel().ordinal(); + if (relOxiLvl < oxiLvl) { + return type; + } + + if (relOxiLvl > oxiLvl) { + cons++; + } else { + odds++; + } + } + } + } + + float chance = (float)(cons + 1) / (float)(cons + odds + 1); + float multiplier = oxiLvl == 0? 0.75F : 1.0F; + chance = chance * chance * multiplier; + if (random.nextFloat() < chance) { + Block nextBlock = this.getStateWithOxidizationLevel(OxidizationLevel.values()[oxiLvl + 1]); + BlockFadeEvent event = new BlockFadeEvent(block, nextBlock); + block.getLevel().getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + block.getLevel().setBlock(block, event.getNewState()); + } + } + return type; + } + + + default boolean onActivate(Item item, Player player) { + if (!item.isAxe()) { + return false; + } + + OxidizationLevel oxidizationLevel = getOxidizationLevel(); + if (OxidizationLevel.UNAFFECTED.equals(oxidizationLevel)) { + return false; + } + + oxidizationLevel = OxidizationLevel.values()[oxidizationLevel.ordinal() - 1]; + if (!setOxidizationLevel(oxidizationLevel)) { + return false; + } + + Position location = this instanceof Block? (Position) this : getLocation(); + if (player == null || !player.isCreative()) { + item.useOn(this instanceof Block? (Block) this : location.getLevelBlock()); + } + location.getLevel().addParticle(new ScrapeParticle(location)); + return true; + } + + OxidizationLevel getOxidizationLevel(); + + boolean setOxidizationLevel(OxidizationLevel oxidizationLevel); + + Block getStateWithOxidizationLevel(OxidizationLevel oxidizationLevel); +} diff --git a/src/main/java/cn/nukkit/block/Waxable.java b/src/main/java/cn/nukkit/block/Waxable.java new file mode 100644 index 00000000000..e8408a1626a --- /dev/null +++ b/src/main/java/cn/nukkit/block/Waxable.java @@ -0,0 +1,40 @@ +package cn.nukkit.block; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; +import cn.nukkit.level.Location; +import cn.nukkit.level.Position; +import cn.nukkit.level.particle.WaxOffParticle; +import cn.nukkit.level.particle.WaxOnParticle; + +public interface Waxable { + + Location getLocation(); + + default boolean onActivate(Item item, Player player) { + boolean waxed = isWaxed(); + if ((item.getId() != ItemID.HONEYCOMB || waxed) && (!item.isAxe() || !waxed)) { + return false; + } + + waxed = !waxed; + if (!setWaxed(waxed)) { + return false; + } + + Position location = this instanceof Block? (Position) this : getLocation(); + if (player == null || !player.isCreative()) { + if (waxed) { + item.count--; + } else { + item.useOn(this instanceof Block? (Block) this : location.getLevelBlock()); + } + } + location.getLevel().addParticle(waxed ? new WaxOnParticle(location) : new WaxOffParticle(location)); + return true; + } + + boolean isWaxed(); + boolean setWaxed(boolean waxed); +} diff --git a/src/main/java/cn/nukkit/block/custom/container/BlockContainer.java b/src/main/java/cn/nukkit/block/custom/container/BlockContainer.java new file mode 100644 index 00000000000..22ee3ecd454 --- /dev/null +++ b/src/main/java/cn/nukkit/block/custom/container/BlockContainer.java @@ -0,0 +1,16 @@ +package cn.nukkit.block.custom.container; + +import cn.nukkit.level.GlobalBlockPalette; + +public interface BlockContainer { + + int getNukkitId(); + + default int getNukkitDamage() { + return 0; + } + + default int getRuntimeId() { + return GlobalBlockPalette.getOrCreateRuntimeId(this.getNukkitId(), this.getNukkitDamage()); + } +} diff --git a/src/main/java/cn/nukkit/block/custom/container/BlockStorageContainer.java b/src/main/java/cn/nukkit/block/custom/container/BlockStorageContainer.java new file mode 100644 index 00000000000..3801751c3bd --- /dev/null +++ b/src/main/java/cn/nukkit/block/custom/container/BlockStorageContainer.java @@ -0,0 +1,78 @@ +package cn.nukkit.block.custom.container; + +import cn.nukkit.block.Block; +import cn.nukkit.block.custom.properties.BlockProperties; +import cn.nukkit.block.custom.properties.BlockProperty; + +import java.io.Serializable; + +public interface BlockStorageContainer extends BlockContainer { + + int getStorage(); + void setStorage(int damage); + + BlockProperties getBlockProperties(); + + default int getNukkitDamage() { + return getStorage() & Block.DATA_MASK; + } + + default void setBooleanValue(BlockProperty property, boolean value) { + this.setBooleanValue(property.getName(), value); + } + + default void setBooleanValue(String propertyName, boolean value) { + this.setStorage(this.getBlockProperties().setBooleanValue(this.getStorage(), propertyName, value)); + } + + default void setPropertyValue(String propertyName, Serializable value) { + this.setStorage(this.getBlockProperties().setValue(this.getStorage(), propertyName, value)); + } + + default void setPropertyValue(BlockProperty property, T value) { + this.setPropertyValue(property.getName(), value); + } + + default void setIntValue(String propertyName, int value) { + this.setStorage(this.getBlockProperties().setIntValue(this.getStorage(), propertyName, value)); + } + + default Serializable getPropertyValue(String propertyName) { + return this.getBlockProperties().getValue(this.getStorage(), propertyName); + } + + default V getPropertyValue(BlockProperty property) { + return this.getCheckedPropertyValue(property.getName(), property.getValueClass()); + } + + default T getCheckedPropertyValue(String propertyName, Class tClass) { + return tClass.cast(this.getPropertyValue(propertyName)); + } + + default int getIntValue(String propertyName) { + return this.getBlockProperties().getIntValue(this.getStorage(), propertyName); + } + + default boolean getBooleanValue(BlockProperty property) { + return this.getBooleanValue(property.getName()); + } + + default boolean getBooleanValue(String propertyName) { + return this.getBlockProperties().getBooleanValue(this.getStorage(), propertyName); + } + + default void setStorageFromItem(int itemMeta) { + BlockProperties properties = this.getBlockProperties(); + BlockProperties itemProperties = properties.getItemBlockProperties(); + if (itemProperties.equals(properties)) { + this.setStorage(itemMeta); + return; + } + + int damage = 0; + for (String propertyName : itemProperties.getItemPropertyNames()) { + damage = properties.setValue(damage, propertyName, itemProperties.getValue(itemMeta, propertyName)); + } + this.setStorage(damage); + } +} diff --git a/src/main/java/cn/nukkit/block/custom/properties/BlockProperties.java b/src/main/java/cn/nukkit/block/custom/properties/BlockProperties.java new file mode 100644 index 00000000000..95db464a68f --- /dev/null +++ b/src/main/java/cn/nukkit/block/custom/properties/BlockProperties.java @@ -0,0 +1,420 @@ +package cn.nukkit.block.custom.properties; + +import cn.nukkit.block.custom.properties.exception.BlockPropertyNotFoundException; +import cn.nukkit.utils.functional.ToIntTriFunctionTwoInts; +import cn.nukkit.utils.functional.ToLongTriFunctionOneIntOneLong; +import com.google.common.base.Preconditions; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import net.daporkchop.lib.common.function.plain.TriFunction; + +import java.io.Serializable; +import java.math.BigInteger; +import java.util.*; +import java.util.function.Consumer; +import java.util.function.ObjIntConsumer; + +public class BlockProperties { + private final Map byName; + private final int bitSize; + private final BlockProperties itemBlockProperties; + + public BlockProperties(BlockProperty... properties) { + this(null, properties); + } + + public BlockProperties(BlockProperties itemBlockProperties, BlockProperty... properties) { + if (itemBlockProperties == null) { + this.itemBlockProperties = this; + } else { + this.itemBlockProperties = itemBlockProperties; + } + + Map registry = new Object2ObjectLinkedOpenHashMap<>(properties.length); + Map byPersistenceName = new Object2ObjectLinkedOpenHashMap<>(properties.length); + + int offset = 0; + boolean allowItemExport = true; + for (BlockProperty property : properties) { + Preconditions.checkArgument(property != null, "The properties can not contains null values"); + if (property.isExportedToItem()) { + Preconditions.checkArgument(allowItemExport, "Cannot export a property to item if the previous property does not export"); + Preconditions.checkArgument(offset <= 6); // Only 6 bits of data can be stored in item blocks, client side limitation. + } else { + allowItemExport = false; + } + + RegisteredBlockProperty register = new RegisteredBlockProperty(property, offset); + offset += property.getBitSize(); + + Preconditions.checkArgument(registry.put(property.getName(), register) == null, "The property %s is duplicated by it's normal name", property.getName()); + Preconditions.checkArgument(byPersistenceName.put(property.getPersistenceName(), register) == null, "The property %s is duplicated by it's persistence name", property.getPersistenceName()); + } + + this.byName = Collections.unmodifiableMap(registry); + bitSize = offset; + } + + public BlockProperties getItemBlockProperties() { + return this.itemBlockProperties; + } + + @SuppressWarnings("unchecked") + public int setValue(int currentMeta, String propertyName, Serializable value) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + BlockProperty unchecked = registry.getProperty(); + return unchecked.setValue(currentMeta, registry.getOffset(), value); + } + + @SuppressWarnings("unchecked") + public long setValue(long currentMeta, String propertyName, Serializable value) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + BlockProperty unchecked = registry.getProperty(); + return unchecked.setValue(currentMeta, registry.getOffset(), value); + } + + @SuppressWarnings("unchecked") + public int setBooleanValue(int currentMeta, String propertyName, boolean value) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + BlockProperty property = registry.getProperty(); + if (BooleanBlockProperty.class == property.getClass()) { + return ((BooleanBlockProperty) property).setValue(currentMeta, registry.getOffset(), value); + } + + BlockProperty unchecked = registry.getProperty(); + return unchecked.setValue(currentMeta, registry.getOffset(), value); + } + + @SuppressWarnings("unchecked") + public long setBooleanValue(long currentMeta, String propertyName, boolean value) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + BlockProperty property = registry.getProperty(); + if (BooleanBlockProperty.class == property.getClass()) { + return ((BooleanBlockProperty) property).setValue(currentMeta, registry.getOffset(), value); + } + + BlockProperty unchecked = registry.getProperty(); + return unchecked.setValue(currentMeta, registry.getOffset(), value); + } + + @SuppressWarnings("unchecked") + public BigInteger setBooleanValue(BigInteger currentMeta, String propertyName, boolean value) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + BlockProperty property = registry.getProperty(); + if (BooleanBlockProperty.class == property.getClass()) { + return ((BooleanBlockProperty) property).setValue(currentMeta, registry.getOffset(), value); + } + + BlockProperty unchecked = registry.getProperty(); + return unchecked.setValue(currentMeta, registry.getOffset(), value); + } + + @SuppressWarnings("unchecked") + public int setIntValue(int currentMeta, String propertyName, int value) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + BlockProperty property = registry.getProperty(); + if (IntBlockProperty.class == property.getClass()) { + return ((IntBlockProperty) property).setValue(currentMeta, registry.getOffset(), value); + } else if (UnsignedIntBlockProperty.class == property.getClass()) { + return ((UnsignedIntBlockProperty) property).setValue(currentMeta, registry.getOffset(), value); + } + + BlockProperty unchecked = registry.getProperty(); + return unchecked.setValue(currentMeta, registry.getOffset(), value); + } + + @SuppressWarnings("unchecked") + public long setIntValue(long currentMeta, String propertyName, int value) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + BlockProperty property = registry.getProperty(); + if (IntBlockProperty.class == property.getClass()) { + return ((IntBlockProperty) property).setValue(currentMeta, registry.getOffset(), value); + } else if (UnsignedIntBlockProperty.class == property.getClass()) { + return ((UnsignedIntBlockProperty) property).setValue(currentMeta, registry.getOffset(), value); + } + + BlockProperty unchecked = registry.getProperty(); + return unchecked.setValue(currentMeta, registry.getOffset(), value); + } + + @SuppressWarnings("unchecked") + public BigInteger setIntValue(BigInteger currentMeta, String propertyName, int value) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + BlockProperty property = registry.getProperty(); + if (IntBlockProperty.class == property.getClass()) { + return ((IntBlockProperty) property).setValue(currentMeta, registry.getOffset(), value); + } else if (UnsignedIntBlockProperty.class == property.getClass()) { + return ((UnsignedIntBlockProperty) property).setValue(currentMeta, registry.getOffset(), value); + } + + BlockProperty unchecked = registry.getProperty(); + return unchecked.setValue(currentMeta, registry.getOffset(), value); + } + + @SuppressWarnings("unchecked") + public int setPersistenceValue(int currentMeta, String propertyName, String persistenceValue) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + BlockProperty property = registry.getProperty(); + int meta = property.getMetaForPersistenceValue(persistenceValue); + Serializable value = property.getValueForMeta(meta); + return property.setValue(currentMeta, registry.getOffset(), value); + } + + @SuppressWarnings("unchecked") + public long setPersistenceValue(long currentMeta, String propertyName, String persistenceValue) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + BlockProperty property = registry.getProperty(); + int meta = property.getMetaForPersistenceValue(persistenceValue); + Serializable value = property.getValueForMeta(meta); + return property.setValue(currentMeta, registry.getOffset(), value); + } + + @SuppressWarnings("unchecked") + public BigInteger setPersistenceValue(BigInteger currentMeta, String propertyName, String persistenceValue) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + BlockProperty property = registry.getProperty(); + int meta = property.getMetaForPersistenceValue(persistenceValue); + Serializable value = property.getValueForMeta(meta); + return property.setValue(currentMeta, registry.getOffset(), value); + } + + @SuppressWarnings("unchecked") + public BigInteger setValue(BigInteger currentMeta, String propertyName, Serializable value) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + BlockProperty unchecked = registry.getProperty(); + return unchecked.setValue(currentMeta, registry.getOffset(), value); + } + + public Serializable getValue(int currentMeta, String propertyName) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + return registry.getProperty().getValue(currentMeta, registry.getOffset()); + } + + public Serializable getValue(long currentMeta, String propertyName) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + return registry.getProperty().getValue(currentMeta, registry.getOffset()); + } + + public Serializable getValue(BigInteger currentMeta, String propertyName) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + return registry.getProperty().getValue(currentMeta, registry.getOffset()); + } + + public T getCheckedValue(int currentMeta, String propertyName, Class clazz) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + return clazz.cast(registry.getProperty().getValue(currentMeta, registry.getOffset())); + } + + public T getCheckedValue(long currentMeta, String propertyName, Class clazz) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + return clazz.cast(registry.getProperty().getValue(currentMeta, registry.getOffset())); + } + + public T getCheckedValue(BigInteger currentMeta, String propertyName, Class clazz) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + return clazz.cast(registry.getProperty().getValue(currentMeta, registry.getOffset())); + } + + @SuppressWarnings("unchecked") + public T getUncheckedValue(int currentMeta, String propertyName) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + return (T) registry.getProperty().getValue(currentMeta, registry.getOffset()); + } + + @SuppressWarnings("unchecked") + public T getUncheckedValue(long currentMeta, String propertyName) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + return (T) registry.getProperty().getValue(currentMeta, registry.getOffset()); + } + + @SuppressWarnings("unchecked") + public T getUncheckedValue(BigInteger currentMeta, String propertyName) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + return (T) registry.getProperty().getValue(currentMeta, registry.getOffset()); + } + + public int getIntValue(int currentMeta, String propertyName) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + return registry.getProperty().getIntValue(currentMeta, registry.getOffset()); + } + + public int getIntValue(long currentMeta, String propertyName) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + return registry.getProperty().getIntValue(currentMeta, registry.getOffset()); + } + + public int getIntValue(BigInteger currentMeta, String propertyName) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + return registry.getProperty().getIntValue(currentMeta, registry.getOffset()); + } + + public Serializable getPersistenceValue(int currentMeta, String propertyName) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + return registry.getProperty().getPersistenceValue(currentMeta, registry.getOffset()); + } + + public Serializable getPersistenceValue(long currentMeta, String propertyName) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + return registry.getProperty().getPersistenceValue(currentMeta, registry.getOffset()); + } + + public Serializable getPersistenceValue(BigInteger currentMeta, String propertyName) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + return registry.getProperty().getPersistenceValue(currentMeta, registry.getOffset()); + } + + public boolean getBooleanValue(int currentMeta, String propertyName) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + if (registry.getProperty() instanceof BooleanBlockProperty) { + return ((BooleanBlockProperty) registry.getProperty()).getBooleanValue(currentMeta, registry.getOffset()); + } + + return (Boolean) registry.getProperty().getValue(currentMeta, registry.getOffset()); + } + + public boolean getBooleanValue(long currentMeta, String propertyName) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + if (registry.getProperty() instanceof BooleanBlockProperty) { + return ((BooleanBlockProperty) registry.getProperty()).getBooleanValue(currentMeta, registry.getOffset()); + } + + return (Boolean) registry.getProperty().getValue(currentMeta, registry.getOffset()); + } + + public boolean getBooleanValue(BigInteger currentMeta, String propertyName) { + RegisteredBlockProperty registry = requireRegisteredProperty(propertyName); + if (registry.getProperty() instanceof BooleanBlockProperty) { + return ((BooleanBlockProperty) registry.getProperty()).getBooleanValue(currentMeta, registry.getOffset()); + } + + return (Boolean) registry.getProperty().getValue(currentMeta, registry.getOffset()); + } + + public R reduce(R identity, TriFunction, Integer, R, R> accumulator) { + R result = identity; + for (RegisteredBlockProperty registry : byName.values()) { + result = accumulator.apply(registry.getProperty(), registry.getOffset(), result); + } + return result; + } + + public int reduceInt(int identity, ToIntTriFunctionTwoInts> accumulator) { + int result = identity; + for (RegisteredBlockProperty registry : byName.values()) { + result = accumulator.apply(registry.getProperty(), registry.getOffset(), result); + } + return result; + } + + public long reduceLong(long identity, ToLongTriFunctionOneIntOneLong> accumulator) { + long result = identity; + for (RegisteredBlockProperty registry : byName.values()) { + result = accumulator.apply(registry.getProperty(), registry.getOffset(), result); + } + return result; + } + + public boolean isDefaultValue(String propertyName, Serializable value) { + BlockProperty blockProperty = getBlockProperty(propertyName); + return blockProperty.isDefaultValue(value); + } + + public boolean isDefaultValue(BlockProperty property, T value) { + return isDefaultValue(property.getName(), value); + } + + public boolean isDefaultIntValue(String propertyName, int value) { + BlockProperty blockProperty = getBlockProperty(propertyName); + return blockProperty.isDefaultIntValue(value); + } + + public boolean isDefaultIntValue(BlockProperty property, int value) { + return isDefaultIntValue(property.getName(), value); + } + + public boolean isDefaultBooleanValue(String propertyName, boolean value) { + BlockProperty blockProperty = getBlockProperty(propertyName); + return blockProperty.isDefaultBooleanValue(value); + } + + public boolean isDefaultBooleanValue(BlockProperty property, boolean value) { + return isDefaultBooleanValue(property.getName(), value); + } + + public int getOffset(String propertyName) { + return this.requireRegisteredProperty(propertyName).getOffset(); + } + + public boolean contains(String propertyName) { + return this.byName.containsKey(propertyName); + } + + public boolean contains(BlockProperty property) { + RegisteredBlockProperty registry = this.byName.get(property.getName()); + if (registry == null) { + return false; + } + return registry.getProperty().getValueClass().equals(property.getValueClass()); + } + + @SuppressWarnings("java:S1452") + public BlockProperty getBlockProperty(String propertyName) { + return this.requireRegisteredProperty(propertyName).getProperty(); + } + + public > T getBlockProperty(String propertyName, Class clazz) { + return clazz.cast(this.requireRegisteredProperty(propertyName).getProperty()); + } + + public RegisteredBlockProperty requireRegisteredProperty(String propertyName) { + RegisteredBlockProperty registry = this.byName.get(propertyName); + if (registry == null) { + throw new BlockPropertyNotFoundException(propertyName, this); + } + return registry; + } + + public Set getNames() { + return this.byName.keySet(); + } + + public Collection getAllProperties() { + return this.byName.values(); + } + + public int getBitSize() { + return this.bitSize; + } + + public List getItemPropertyNames() { + List itemProperties = new ArrayList<>(this.byName.size()); + for (RegisteredBlockProperty registry : this.byName.values()) { + if (registry.getProperty().isExportedToItem()) { + itemProperties.add(registry.getProperty().getName()); + } else { + break; + } + } + return itemProperties; + } + + public void forEach(ObjIntConsumer> consumer) { + for (RegisteredBlockProperty registry : this.byName.values()) { + consumer.accept(registry.getProperty(), registry.getOffset()); + } + } + + public void forEach(Consumer> consumer) { + for (RegisteredBlockProperty registry : this.byName.values()) { + consumer.accept(registry.getProperty()); + } + } + + @Override + public String toString() { + return "BlockProperties{" + + "bitSize=" + bitSize + + ", properties=" + byName.values() + + '}'; + } + +} diff --git a/src/main/java/cn/nukkit/block/custom/properties/BlockProperty.java b/src/main/java/cn/nukkit/block/custom/properties/BlockProperty.java new file mode 100644 index 00000000000..85341422eeb --- /dev/null +++ b/src/main/java/cn/nukkit/block/custom/properties/BlockProperty.java @@ -0,0 +1,333 @@ +package cn.nukkit.block.custom.properties; + +import cn.nukkit.block.custom.properties.exception.InvalidBlockPropertyMetaException; +import cn.nukkit.block.custom.properties.exception.InvalidBlockPropertyValueException; +import com.google.common.base.Preconditions; + +import java.io.Serializable; +import java.math.BigInteger; + +public abstract class BlockProperty implements Serializable { + private static final long serialVersionUID = -2594821043880025191L; + + private final String name; + private final boolean exportedToItem; + private final String persistenceName; + private final int bitSize; + + public BlockProperty(String name, boolean exportedToItem, String persistenceName, int bitSize) { + Preconditions.checkArgument(bitSize > 0, "Bit size (%s) must be positive", bitSize); + this.name = name; + this.exportedToItem = exportedToItem; + this.persistenceName = persistenceName; + this.bitSize = bitSize; + } + + public abstract int getMetaForValue(T value); + public abstract T getValueForMeta(int meta); + public abstract int getIntValueForMeta(int meta); + + public abstract Serializable getPersistenceValueForMeta(int meta); + public abstract int getMetaForPersistenceValue(String persistenceValue); + + public abstract Class getValueClass(); + + public abstract boolean isDefaultValue(T value); + public abstract T getDefaultValue(); + public abstract BlockProperty exportingToItems(boolean exportedToItem); + + public int setValue(int currentMeta, int bitOffset, T newValue) { + int mask = computeValueMask(bitOffset); + try { + int value = getMetaForValue(newValue) << bitOffset; + + if ((value & ~mask) != 0) { + throw new IllegalStateException("Attempted to set a value which overflows the size of " + bitSize + " bits. Current:" + currentMeta + ", offset:" + bitOffset + ", meta:" + value + ", value:" + newValue); + } + + return currentMeta & ~mask | (value & mask); + } catch (Exception e) { + T oldValue = null; + InvalidBlockPropertyMetaException suppressed = null; + try { + oldValue = getValue(currentMeta, bitOffset); + } catch (Exception e2) { + suppressed = new InvalidBlockPropertyMetaException(this, currentMeta, currentMeta & mask, e2); + } + InvalidBlockPropertyValueException toThrow = new InvalidBlockPropertyValueException(this, oldValue, newValue, e); + if (suppressed != null) { + toThrow.addSuppressed(suppressed); + } + throw toThrow; + } + } + + public long setValue(long currentBigMeta, int bitOffset, T newValue) { + long mask = computeBigValueMask(bitOffset); + try { + long value = getMetaForValue(newValue) << bitOffset; + + if ((value & ~mask) != 0L) { + throw new IllegalStateException("Attempted to set a value which overflows the size of " + bitSize + " bits. Current:" + currentBigMeta + ", offset:" + bitOffset + ", meta:" + value + ", value:" + newValue); + } + + return currentBigMeta & ~mask | (value & mask); + } catch (Exception e) { + T oldValue = null; + InvalidBlockPropertyMetaException suppressed = null; + try { + oldValue = getValue(currentBigMeta, bitOffset); + } catch (Exception e2) { + suppressed = new InvalidBlockPropertyMetaException(this, currentBigMeta, currentBigMeta & mask, e2); + } + InvalidBlockPropertyValueException toThrow = new InvalidBlockPropertyValueException(this, oldValue, newValue, e); + if (suppressed != null) { + toThrow.addSuppressed(suppressed); + } + throw toThrow; + } + } + + public BigInteger setValue(BigInteger currentHugeMeta, int bitOffset, T newValue) { + BigInteger mask = computeHugeValueMask(bitOffset); + try { + BigInteger value = BigInteger.valueOf(getMetaForValue(newValue)).shiftLeft(bitOffset); + + if (!value.andNot(mask).equals(BigInteger.ZERO)) { + throw new IllegalStateException("Attempted to set a value which overflows the size of " + bitSize + " bits. Current:" + currentHugeMeta + ", offset:" + bitOffset + ", meta:" + value + ", value:" + newValue); + } + + return currentHugeMeta.andNot(mask).or(value.and(mask)); + } catch (Exception e) { + T oldValue = null; + InvalidBlockPropertyMetaException suppressed = null; + try { + oldValue = getValue(currentHugeMeta, bitOffset); + } catch (Exception e2) { + suppressed = new InvalidBlockPropertyMetaException(this, currentHugeMeta, currentHugeMeta.and(mask), e2); + } + InvalidBlockPropertyValueException toThrow = new InvalidBlockPropertyValueException(this, oldValue, newValue, e); + if (suppressed != null) { + toThrow.addSuppressed(suppressed); + } + throw toThrow; + } + } + + public T getValue(int currentMeta, int bitOffset) { + int meta = getMetaFromInt(currentMeta, bitOffset); + try { + return getValueForMeta(meta); + } catch (Exception e) { + throw new InvalidBlockPropertyMetaException(this, currentMeta, currentMeta & computeValueMask(bitOffset), e); + } + } + + public T getValue(long currentBigMeta, int bitOffset) { + int meta = getMetaFromLong(currentBigMeta, bitOffset); + try { + return getValueForMeta(meta); + } catch (Exception e) { + throw new InvalidBlockPropertyMetaException(this, currentBigMeta, currentBigMeta & computeBigValueMask(bitOffset), e); + } + } + + public T getValue(BigInteger currentHugeMeta, int bitOffset) { + int meta = getMetaFromBigInt(currentHugeMeta, bitOffset); + try { + return getValueForMeta(meta); + } catch (Exception e) { + throw new InvalidBlockPropertyMetaException(this, currentHugeMeta, currentHugeMeta.and(computeHugeValueMask(bitOffset)), e); + } + } + + public int getIntValue(int currentMeta, int bitOffset) { + int meta = getMetaFromInt(currentMeta, bitOffset); + try { + return getIntValueForMeta(meta); + } catch (Exception e) { + throw new InvalidBlockPropertyMetaException(this, currentMeta, currentMeta & computeValueMask(bitOffset), e); + } + } + + public int getIntValue(long currentMeta, int bitOffset) { + int meta = getMetaFromLong(currentMeta, bitOffset); + try { + return getIntValueForMeta(meta); + } catch (Exception e) { + throw new InvalidBlockPropertyMetaException(this, currentMeta, currentMeta & computeBigValueMask(bitOffset), e); + } + } + + public int getIntValue(BigInteger currentMeta, int bitOffset) { + int meta = getMetaFromBigInt(currentMeta, bitOffset); + try { + return getIntValueForMeta(meta); + } catch (Exception e) { + throw new InvalidBlockPropertyMetaException(this, currentMeta, currentMeta.and(computeHugeValueMask(bitOffset)), e); + } + } + + public Serializable getPersistenceValue(int currentMeta, int bitOffset) { + int meta = getMetaFromInt(currentMeta, bitOffset); + try { + return this.getPersistenceValueForMeta(meta); + } catch (Exception e) { + throw new InvalidBlockPropertyMetaException(this, currentMeta, currentMeta & computeValueMask(bitOffset), e); + } + } + + public Serializable getPersistenceValue(long currentMeta, int bitOffset) { + int meta = getMetaFromLong(currentMeta, bitOffset); + try { + return this.getPersistenceValueForMeta(meta); + } catch (Exception e) { + throw new InvalidBlockPropertyMetaException(this, currentMeta, currentMeta & computeBigValueMask(bitOffset), e); + } + } + + public Serializable getPersistenceValue(BigInteger currentMeta, int bitOffset) { + int meta = getMetaFromBigInt(currentMeta, bitOffset); + try { + return this.getPersistenceValueForMeta(meta); + } catch (Exception e) { + throw new InvalidBlockPropertyMetaException(this, currentMeta, currentMeta.and(computeHugeValueMask(bitOffset)), e); + } + } + + + private int computeRightMask(int bitOffset) { + return bitOffset == 0? 0 : -1 >>> (32 - bitOffset); + } + + private long computeBigRightMask(int bitOffset) { + return bitOffset == 0L? 0L : -1L >>> (64 - bitOffset); + } + + private BigInteger computeHugeRightMask(int bitOffset) { + return BigInteger.ONE.shiftLeft(bitOffset).subtract(BigInteger.ONE); + } + + private int computeValueMask(int bitOffset) { + Preconditions.checkArgument(bitOffset >= 0, "Bit offset can not be negative. Got %s", bitOffset); + + int maskBits = bitSize + bitOffset; + Preconditions.checkArgument(0 < maskBits && maskBits <= 32, "The bit offset %s plus the bit size %s causes memory overflow (32 bits)", bitOffset, bitSize); + + int rightMask = computeRightMask(bitOffset); + int leftMask = -1 << maskBits; + return ~rightMask & ~leftMask; + } + + private long computeBigValueMask(int bitOffset) { + Preconditions.checkArgument(bitOffset >= 0, "Bit offset can not be negative. Got %s", bitOffset); + + int maskBits = bitSize + bitOffset; + Preconditions.checkArgument(0 < maskBits && maskBits <= 64, "The bit offset %s plus the bit size %s causes memory overflow (64 bits)", bitOffset, bitSize); + + long rightMask = computeBigRightMask(bitOffset); + long leftMask = -1L << maskBits; + return ~rightMask & ~leftMask; + } + + private BigInteger computeHugeValueMask(int bitOffset) { + Preconditions.checkArgument(bitOffset >= 0, "Bit offset can not be negative. Got %s", bitOffset); + + int maskBits = bitSize + bitOffset; + Preconditions.checkArgument(0 < maskBits, "The bit offset %s plus the bit size %s causes memory overflow (huge)", bitOffset, bitSize); + + BigInteger rightMask = computeHugeRightMask(bitOffset); + BigInteger leftMask = BigInteger.valueOf(-1).shiftLeft(maskBits); + + return rightMask.not().andNot(leftMask); + } + + public final int getMetaFromInt(int currentMeta, int bitOffset) { + return (currentMeta & computeValueMask(bitOffset)) >>> bitOffset; + } + + public final int getMetaFromLong(long currentMeta, int bitOffset) { + return (int) ((currentMeta & computeBigValueMask(bitOffset)) >>> bitOffset); + } + + public final int getMetaFromBigInt(BigInteger currentMeta, int bitOffset) { + return currentMeta.and(computeHugeValueMask(bitOffset)).shiftRight(bitOffset).intValue(); + } + + protected void validateDirectly(T value) { + // Does nothing by default + } + + protected abstract void validateMetaDirectly(int meta); + + public final void validateMeta(int meta, int offset) { + int propMeta = getMetaFromInt(meta, offset); + try { + validateMetaDirectly(propMeta); + } catch (Exception e) { + throw new InvalidBlockPropertyMetaException(this, meta, meta & computeValueMask(offset), e); + } + } + + public final void validateMeta(long meta, int offset) { + int propMeta = getMetaFromLong(meta, offset); + try { + validateMetaDirectly(propMeta); + } catch (Exception e) { + throw new InvalidBlockPropertyMetaException(this, meta, meta & computeBigValueMask(offset), e); + } + } + + public final void validateMeta(BigInteger meta, int offset) { + int propMeta = getMetaFromBigInt(meta, offset); + try { + validateMetaDirectly(propMeta); + } catch (Exception e) { + throw new InvalidBlockPropertyMetaException(this, meta, meta.and(computeHugeRightMask(offset)), e); + } + } + + public boolean isDefaultIntValue(int value) { + return value == getDefaultIntValue(); + } + + public boolean isDefaultBooleanValue(boolean value) { + return value == getDefaultBooleanValue(); + } + + public int getDefaultIntValue() { + return 0; + } + + public boolean getDefaultBooleanValue() { + return false; + } + + public int getBitSize() { + return this.bitSize; + } + + public String getName() { + return this.name; + } + + public String getPersistenceName() { + return this.persistenceName; + } + + public boolean isExportedToItem() { + return this.exportedToItem; + } + + public abstract BlockProperty copy(); + + @Override + public String toString() { + return getClass().getSimpleName()+"{" + + "name='" + name + '\'' + + ", bitSize=" + bitSize + + ", exportedToItem=" + exportedToItem + + ", persistenceName='" + persistenceName + '\'' + + '}'; + } +} diff --git a/src/main/java/cn/nukkit/block/custom/properties/BlockPropertyUtils.java b/src/main/java/cn/nukkit/block/custom/properties/BlockPropertyUtils.java new file mode 100644 index 00000000000..383b39a4904 --- /dev/null +++ b/src/main/java/cn/nukkit/block/custom/properties/BlockPropertyUtils.java @@ -0,0 +1,68 @@ +package cn.nukkit.block.custom.properties; + +import java.math.BigInteger; + +public class BlockPropertyUtils { + + public static int bitLength(byte data) { + if (data < 0) { + return 32; + } + + if (data == 0) { + return 1; + } + + int bits = 0; + while (data != 0) { + data >>>= 1; + bits++; + } + + return bits; + } + + public static int bitLength(int data) { + if (data < 0) { + return 32; + } + + if (data == 0) { + return 1; + } + + int bits = 0; + while (data != 0) { + data >>>= 1; + bits++; + } + + return bits; + } + + public static int bitLength(long data) { + if (data < 0) { + return 64; + } + + if (data == 0) { + return 1; + } + + int bits = 0; + while (data != 0) { + data >>>= 1; + bits++; + } + + return bits; + } + + public static int bitLength(BigInteger data) { + if (data.compareTo(BigInteger.ZERO) < 0) { + throw new UnsupportedOperationException("Negative BigIntegers are not supported (nearly infinite bits)"); + } + + return data.bitLength(); + } +} diff --git a/src/main/java/cn/nukkit/block/custom/properties/BooleanBlockProperty.java b/src/main/java/cn/nukkit/block/custom/properties/BooleanBlockProperty.java new file mode 100644 index 00000000000..06c844269c4 --- /dev/null +++ b/src/main/java/cn/nukkit/block/custom/properties/BooleanBlockProperty.java @@ -0,0 +1,147 @@ +package cn.nukkit.block.custom.properties; + +import cn.nukkit.block.custom.properties.exception.InvalidBlockPropertyMetaException; +import cn.nukkit.block.custom.properties.exception.InvalidBlockPropertyPersistenceValueException; +import com.google.common.base.Preconditions; + +import java.io.Serializable; +import java.math.BigInteger; + +public class BooleanBlockProperty extends BlockProperty { + private static final long serialVersionUID = 8249827149092664486L; + + public BooleanBlockProperty(String name, boolean exportedToItem, String persistenceName) { + super(name, exportedToItem, persistenceName, 1); + } + + public BooleanBlockProperty(String name, boolean exportedToItem) { + super(name, exportedToItem, name, 1); + } + + @Override + public int setValue(int currentMeta, int bitOffset, Boolean newValue) { + boolean value = newValue != null && newValue; + return this.setValue(currentMeta, bitOffset, value); + } + + @Override + public long setValue(long currentBigMeta, int bitOffset, Boolean newValue) { + boolean value = newValue != null && newValue; + return this.setValue(currentBigMeta, bitOffset, value); + } + + public int setValue(int currentMeta, int bitOffset, boolean newValue) { + int mask = 1 << bitOffset; + return newValue ? (currentMeta | mask) : (currentMeta & ~mask); + } + + @Override + public Boolean getValue(int currentMeta, int bitOffset) { + return this.getBooleanValue(currentMeta, bitOffset); + } + + @Override + public Boolean getValue(long currentBigMeta, int bitOffset) { + return this.getBooleanValue(currentBigMeta, bitOffset); + } + + public boolean getBooleanValue(int currentMeta, int bitOffset) { + int mask = 1 << bitOffset; + return (currentMeta & mask) == mask; + } + + public boolean getBooleanValue(long currentBigMeta, int bitOffset) { + long mask = 1L << bitOffset; + return (currentBigMeta & mask) == mask; + } + + public boolean getBooleanValue(BigInteger currentHugeData, int bitOffset) { + BigInteger mask = BigInteger.ONE.shiftLeft(bitOffset); + return mask.equals(currentHugeData.and(mask)); + } + + @Override + public int getIntValue(int currentMeta, int bitOffset) { + return this.getBooleanValue(currentMeta, bitOffset)? 1 : 0; + } + + @Override + public int getIntValueForMeta(int meta) { + if (meta == 1 || meta == 0) { + return meta; + } + throw new InvalidBlockPropertyMetaException(this, meta, meta, "Only 1 or 0 was expected"); + } + + @Override + public int getMetaForValue(Boolean value) { + return Boolean.TRUE.equals(value)? 1 : 0; + } + + @Override + public Boolean getValueForMeta(int meta) { + return this.getBooleanValueForMeta(meta); + } + + public boolean getBooleanValueForMeta(int meta) { + if (meta == 0) { + return false; + } else if (meta == 1) { + return true; + } else { + throw new InvalidBlockPropertyMetaException(this, meta, meta, "Only 1 or 0 was expected"); + } + } + + @Override + public Serializable getPersistenceValueForMeta(int meta) { + if (meta == 1) { + return true; + } else if (meta == 0) { + return false; + } else { + throw new InvalidBlockPropertyMetaException(this, meta, meta, "Only 1 or 0 was expected"); + } + } + + @Override + public int getMetaForPersistenceValue(String persistenceValue) { + if ("1".equals(persistenceValue)) { + return 1; + } else if ("0".equals(persistenceValue)) { + return 0; + } else { + throw new InvalidBlockPropertyPersistenceValueException(this, null, persistenceValue, "Only 1 or 0 was expected"); + } + } + + @Override + public Boolean getDefaultValue() { + return Boolean.FALSE; + } + + @Override + public boolean isDefaultValue(Boolean value) { + return value == null || Boolean.FALSE.equals(value); + } + + @Override + protected void validateMetaDirectly(int meta) { + Preconditions.checkArgument(meta == 1 || meta == 0, "Must be 1 or 0"); + } + + @Override + public Class getValueClass() { + return Boolean.class; + } + + @Override + public BooleanBlockProperty exportingToItems(boolean exportedToItem) { + return new BooleanBlockProperty(this.getName(), exportedToItem, this.getPersistenceName()); + } + + @Override + public BooleanBlockProperty copy() { + return new BooleanBlockProperty(this.getName(), this.isExportedToItem(), this.getPersistenceName()); + } +} diff --git a/src/main/java/cn/nukkit/block/custom/properties/EnumBlockProperty.java b/src/main/java/cn/nukkit/block/custom/properties/EnumBlockProperty.java new file mode 100644 index 00000000000..b21597ea486 --- /dev/null +++ b/src/main/java/cn/nukkit/block/custom/properties/EnumBlockProperty.java @@ -0,0 +1,201 @@ +package cn.nukkit.block.custom.properties; + +import cn.nukkit.block.custom.properties.exception.InvalidBlockPropertyMetaException; +import cn.nukkit.block.custom.properties.exception.InvalidBlockPropertyPersistenceValueException; +import cn.nukkit.block.custom.properties.exception.InvalidBlockPropertyValueException; +import com.google.common.base.Preconditions; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.Objects; +import java.util.Set; + +public class EnumBlockProperty extends BlockProperty { + private static final long serialVersionUID = 507174531989068430L; + + private final E[] values; + // This is null if ordinal = true + private final String[] persistenceNames; + private final Class typeOf; + private final boolean ordinal; + + + public EnumBlockProperty(String name, boolean exportedToItem, E[] values, int bitSize, String persistenceName) { + this(name, exportedToItem, values, bitSize, persistenceName, false); + } + + public EnumBlockProperty(String name, boolean exportedToItem, E[] values, int bitSize, String persistenceName, boolean ordinal) { + this(name, exportedToItem, values, bitSize, persistenceName, ordinal, ordinal ? null : + Arrays.stream(values).map(Objects::toString).map(String::toLowerCase).toArray(String[]::new)); + } + + public EnumBlockProperty(String name, boolean exportedToItem, E[] values, int bitSize) { + this(name, exportedToItem, values, bitSize, name); + } + + public EnumBlockProperty(String name, boolean exportedToItem, E[] values) { + this(name, exportedToItem, checkUniverseLength(values), BlockPropertyUtils.bitLength(values.length - 1)); + } + + public EnumBlockProperty(String name, boolean exportedToItem, Class enumClass) { + this(name, exportedToItem, enumClass.getEnumConstants()); + } + + public EnumBlockProperty(String name, boolean exportedToItem, E[] values, int bitSize, String persistenceName, boolean ordinal, String[] persistenceNames) { + super(name, exportedToItem, persistenceName, bitSize); + checkUniverseLength(values); + + if (ordinal) { + this.persistenceNames = null; + } else { + Preconditions.checkArgument(persistenceNames != null, "persistenceNames can't be null when ordinal is false"); + Preconditions.checkArgument(persistenceNames.length == values.length, "persistenceNames and universe must have the same length when ordinal is false"); + this.persistenceNames = persistenceNames.clone(); + } + + this.ordinal = ordinal; + this.values = values.clone(); + this.typeOf = (Class) values.getClass().getComponentType(); + + Set elements = new ObjectOpenHashSet<>(); + Set persistenceNamesCheck = new ObjectOpenHashSet<>(); + + for (int i = 0; i < this.values.length; i++) { + E element = this.values[i]; + Preconditions.checkNotNull(element, "Value can not be null"); + Preconditions.checkArgument(elements.add(element), "Duplicates are not allowed"); + if (!ordinal) { + String elementName = this.persistenceNames[i]; + Preconditions.checkNotNull(elementName, "The persistenceNames can not contain null values"); + Preconditions.checkArgument(persistenceNamesCheck.add(elementName), "The persistenceNames can not have duplicated elements"); + } + } + } + + public EnumBlockProperty ordinal(boolean ordinal) { + if (ordinal == this.ordinal) { + return this; + } + return new EnumBlockProperty<>(this.getName(), this.isExportedToItem(), this.values, this.getBitSize(), this.getPersistenceName(), ordinal); + } + + @Override + public int getMetaForValue( E value) { + if (value == null) { + return 0; + } + for (int i = 0; i < this.values.length; i++) { + if (this.values[i].equals(value)) { + return i; + } + } + throw new InvalidBlockPropertyValueException(this, null, value, "Element is not part of this property"); + } + + @Override + public E getValueForMeta(int meta) { + return this.values[meta]; + } + + @Override + public int getIntValueForMeta(int meta) { + try { + this.validateMetaDirectly(meta); + } catch (IllegalArgumentException e) { + throw new InvalidBlockPropertyMetaException(this, meta, meta, e); + } + return meta; + } + + @Override + protected void validateDirectly( E value) { + for (E object : this.values) { + if (object == value) { + return; + } + } + throw new IllegalArgumentException(value+" is not valid for this property"); + } + + @Override + protected void validateMetaDirectly(int meta) { + Preconditions.checkElementIndex(meta, this.values.length); + } + + @Override + public Serializable getPersistenceValueForMeta(int meta) { + try { + this.validateMetaDirectly(meta); + } catch (IllegalArgumentException e) { + throw new InvalidBlockPropertyMetaException(this, meta, meta, e); + } + + if (this.isOrdinal()) { + return meta; + } + return persistenceNames[meta]; + } + + @Override + public int getMetaForPersistenceValue(String persistenceValue) { + int meta; + if (this.isOrdinal()) { + try { + meta = Integer.parseInt(persistenceValue); + this.validateMetaDirectly(meta); + } catch (IndexOutOfBoundsException|IllegalArgumentException e) { + throw new InvalidBlockPropertyPersistenceValueException(this, null, persistenceValue, + "Expected a number from 0 to " + (this.values.length - 1), e); + } + return meta; + } + + for (int index = 0; index < persistenceNames.length; index++) { + if (persistenceNames[index].equals(persistenceValue)) { + return index; + } + } + + throw new InvalidBlockPropertyPersistenceValueException(this, null, persistenceValue, "The value does not exists in this property."); + } + + public E[] getValues() { + return this.values.clone(); + } + + public boolean isOrdinal() { + return this.ordinal; + } + + @Override + public E getDefaultValue() { + return this.values[0]; + } + + @Override + public boolean isDefaultValue( E value) { + return value == null || this.values[0].equals(value); + } + + @Override + public Class getValueClass() { + return this.typeOf; + } + + @Override + public EnumBlockProperty copy() { + return new EnumBlockProperty<>(this.getName(), this.isExportedToItem(), values, this.getBitSize(), this.getPersistenceName(), this.isOrdinal(), persistenceNames); + } + + @Override + public EnumBlockProperty exportingToItems(boolean exportedToItem) { + return new EnumBlockProperty<>(this.getName(), exportedToItem, values, this.getBitSize(), this.getPersistenceName(), this.isOrdinal(), persistenceNames); + } + + private static E[] checkUniverseLength(E[] universe) { + Preconditions.checkNotNull(universe, "universe can't be null"); + Preconditions.checkArgument(universe.length > 0, "The universe can't be empty"); + return universe; + } +} diff --git a/src/main/java/cn/nukkit/block/custom/properties/IntBlockProperty.java b/src/main/java/cn/nukkit/block/custom/properties/IntBlockProperty.java new file mode 100644 index 00000000000..263a8b0a568 --- /dev/null +++ b/src/main/java/cn/nukkit/block/custom/properties/IntBlockProperty.java @@ -0,0 +1,154 @@ +package cn.nukkit.block.custom.properties; + +import cn.nukkit.block.custom.properties.exception.InvalidBlockPropertyMetaException; +import cn.nukkit.block.custom.properties.exception.InvalidBlockPropertyPersistenceValueException; +import cn.nukkit.block.custom.properties.exception.InvalidBlockPropertyValueException; +import cn.nukkit.math.NukkitMath; +import com.google.common.base.Preconditions; + +import java.io.Serializable; + +public class IntBlockProperty extends BlockProperty { + private static final long serialVersionUID = -2239010977496415152L; + + private final int minValue; + private final int maxValue; + + public IntBlockProperty(String name, boolean exportedToItem, int maxValue, int minValue, int bitSize) { + this(name, exportedToItem, maxValue, minValue, bitSize, name); + } + + public IntBlockProperty(String name, boolean exportedToItem, int maxValue, int minValue) { + this(name, exportedToItem, maxValue, minValue, BlockPropertyUtils.bitLength(maxValue - minValue)); + } + + public IntBlockProperty(String name, boolean exportedToItem, int maxValue) { + this(name, exportedToItem, maxValue, 0); + } + + public IntBlockProperty(String name, boolean exportedToItem, int maxValue, int minValue, int bitSize, String persistenceName) { + super(name, exportedToItem, persistenceName, bitSize); + int delta = maxValue - minValue; + Preconditions.checkArgument(delta > 0, "maxValue must be higher than minValue. Got min:%s and max:%s", minValue, maxValue); + + int mask = -1 >>> (32 - bitSize); + Preconditions.checkArgument(delta <= mask, "The data range from %s to %s can't be stored in %s bits", minValue, maxValue, bitSize); + + this.minValue = minValue; + this.maxValue = maxValue; + } + + @Override + public int getMetaForValue(Integer value) { + if (value == null) { + return 0; + } + return this.getMetaForValue(value.intValue()); + } + + public int getMetaForValue(int value) { + try { + this.validateDirectly(value); + } catch (IllegalArgumentException e) { + throw new InvalidBlockPropertyValueException(this, null, value, e); + } + return value - minValue; + } + + @Override + public Integer getValueForMeta(int meta) { + return this.getIntValueForMeta(meta); + } + + @Override + public int getIntValueForMeta(int meta) { + try { + this.validateMetaDirectly(meta); + } catch (IllegalArgumentException e) { + throw new InvalidBlockPropertyMetaException(this, meta, meta, e); + } + return minValue + meta; + } + + @Override + protected void validateDirectly(Integer value) { + if (value == null) { + return; + } + this.validateDirectly(value.intValue()); + } + + private void validateDirectly(int newValue) { + Preconditions.checkArgument(newValue >= minValue, "New value (%s) must be higher or equals to %s", newValue, minValue); + Preconditions.checkArgument(maxValue >= newValue, "New value (%s) must be less or equals to %s", newValue, maxValue); + } + + + @Override + protected void validateMetaDirectly(int meta) { + int max = maxValue - minValue; + Preconditions.checkArgument(0 <= meta && meta <= max, "The meta %s is outside the range of 0 .. ", meta, max); + } + + @Override + public Serializable getPersistenceValueForMeta(int meta) { + return this.getIntValueForMeta(meta); + } + + @Override + public int getMetaForPersistenceValue(String persistenceValue) { + try { + return this.getMetaForValue(Integer.parseInt(persistenceValue)); + } catch (NumberFormatException | InvalidBlockPropertyValueException e) { + throw new InvalidBlockPropertyPersistenceValueException(this, null, persistenceValue, e); + } + } + + public int clamp(int value) { + return NukkitMath.clamp(value, this.getMinValue(), this.getMaxValue()); + } + + + public int getMaxValue() { + return this.maxValue; + } + + public int getMinValue() { + return this.minValue; + } + + @Override + public Integer getDefaultValue() { + return this.minValue; + } + + @Override + public boolean isDefaultIntValue(int value) { + return this.minValue == value; + } + + @Override + public int getDefaultIntValue() { + return this.minValue; + } + + @Override + public boolean isDefaultValue(Integer value) { + return value == null || this.minValue == value; + } + + @Override + public Class getValueClass() { + return Integer.class; + } + + @Override + public IntBlockProperty exportingToItems(boolean exportedToItem) { + return new IntBlockProperty(this.getName(), exportedToItem, this.getMaxValue(), this.getMinValue(), this.getBitSize(), this.getPersistenceName()); + } + + @Override + public IntBlockProperty copy() { + return new IntBlockProperty(this.getName(), this.isExportedToItem(), this.getMaxValue(), this.getMinValue(), this.getBitSize(), this.getPersistenceName()); + } +} diff --git a/src/main/java/cn/nukkit/block/custom/properties/RegisteredBlockProperty.java b/src/main/java/cn/nukkit/block/custom/properties/RegisteredBlockProperty.java new file mode 100644 index 00000000000..aaa02cba3c1 --- /dev/null +++ b/src/main/java/cn/nukkit/block/custom/properties/RegisteredBlockProperty.java @@ -0,0 +1,28 @@ +package cn.nukkit.block.custom.properties; + +import lombok.Value; + +import java.math.BigInteger; + +@Value +public class RegisteredBlockProperty { + BlockProperty property; + int offset; + + public void validateMeta(int meta) { + this.property.validateMeta(meta, this.offset); + } + + public void validateMeta(long meta) { + this.property.validateMeta(meta, this.offset); + } + + public void validateMeta(BigInteger meta) { + this.property.validateMeta(meta, this.offset); + } + + @Override + public String toString() { + return this.offset + "-" + (this.offset + this.property.getBitSize()) + ":" + this.property.getName(); + } +} diff --git a/src/main/java/cn/nukkit/block/custom/properties/UnsignedIntBlockProperty.java b/src/main/java/cn/nukkit/block/custom/properties/UnsignedIntBlockProperty.java new file mode 100644 index 00000000000..5af9052a071 --- /dev/null +++ b/src/main/java/cn/nukkit/block/custom/properties/UnsignedIntBlockProperty.java @@ -0,0 +1,155 @@ +package cn.nukkit.block.custom.properties; + +import cn.nukkit.block.custom.properties.exception.InvalidBlockPropertyMetaException; +import cn.nukkit.block.custom.properties.exception.InvalidBlockPropertyPersistenceValueException; +import cn.nukkit.block.custom.properties.exception.InvalidBlockPropertyValueException; +import com.google.common.base.Preconditions; + +import java.io.Serializable; + +public class UnsignedIntBlockProperty extends BlockProperty { + private static final long serialVersionUID = 7896101036099245755L; + + private final long minValue; + private final long maxValue; + + public UnsignedIntBlockProperty(String name, boolean exportedToItem, int maxValue, int minValue, int bitSize) { + this(name, exportedToItem, maxValue, minValue, bitSize, name); + } + + public UnsignedIntBlockProperty(String name, boolean exportedToItem, int maxValue, int minValue) { + this(name, exportedToItem, maxValue, minValue, BlockPropertyUtils.bitLength(maxValue - minValue)); + } + + public UnsignedIntBlockProperty(String name, boolean exportedToItem, int maxValue) { + this(name, exportedToItem, maxValue, 0); + } + + public UnsignedIntBlockProperty(String name, boolean exportedToItem, int maxValue, int minValue, int bitSize, String persistenceName) { + super(name, exportedToItem, persistenceName, bitSize); + long unsignedMinValue = removeSign(minValue); + long unsignedMaxValue = removeSign(maxValue); + long delta = unsignedMaxValue - unsignedMinValue; + Preconditions.checkArgument(delta > 0, "maxValue must be higher than minValue. Got min:%s and max:%s", unsignedMinValue, unsignedMaxValue); + + long mask = removeSign(-1 >>> (32 - bitSize)); + Preconditions.checkArgument(delta <= mask, "The data range from %s to %s can't be stored in %s bits", unsignedMinValue, unsignedMaxValue, bitSize); + + this.minValue = unsignedMinValue; + this.maxValue = unsignedMaxValue; + } + + @Override + public int getMetaForValue(Integer value) { + if (value == null) { + return 0; + } + + long unsigned = removeSign(value); + try { + this.validateDirectly(unsigned); + } catch (IllegalArgumentException e) { + throw new InvalidBlockPropertyValueException(this, null, value, e); + } + return (int) (unsigned - minValue); + } + + @Override + public Integer getValueForMeta(int meta) { + return this.getIntValueForMeta(meta); + } + + @Override + public int getIntValueForMeta(int meta) { + try { + this.validateMetaDirectly(meta); + } catch (IllegalArgumentException e) { + throw new InvalidBlockPropertyMetaException(this, meta, meta, e); + } + return (int) (this.minValue + meta); + } + + @Override + protected void validateDirectly(Integer value) { + if (value == null) { + return; + } + this.validateDirectly(removeSign(value)); + } + + private void validateDirectly(long unsigned) { + Preconditions.checkArgument(unsigned >= this.minValue, "New value (%s) must be higher or equals to %s", unsigned, this.minValue); + Preconditions.checkArgument(this.maxValue >= unsigned, "New value (%s) must be less or equals to %s", unsigned, this.maxValue); + } + + @Override + protected void validateMetaDirectly(int meta) { + long max = this.maxValue - this.minValue; + Preconditions.checkArgument(0 <= meta && meta <= max, "The meta %s is outside the range of 0 .. ", meta, max); + } + + public long getMaxValue() { + return this.maxValue; + } + + public long getMinValue() { + return this.minValue; + } + + @Override + public Integer getDefaultValue() { + return (int) this.minValue; + } + + @Override + public boolean isDefaultValue(Integer value) { + return value == null || removeSign(value) == this.minValue; + } + + @Override + public boolean isDefaultIntValue(int value) { + return removeSign(value) == this.minValue; + } + + @Override + public int getDefaultIntValue() { + return (int) this.minValue; + } + + @Override + public Serializable getPersistenceValueForMeta(int meta) { + return removeSign(this.getIntValueForMeta(meta)); + } + + @Override + public int getMetaForPersistenceValue(String persistenceValue) { + try { + return this.getMetaForValue(addSign(Long.parseLong(persistenceValue))); + } catch (NumberFormatException | InvalidBlockPropertyValueException e) { + throw new InvalidBlockPropertyPersistenceValueException(this, null, persistenceValue, e); + } + } + + @Override + public UnsignedIntBlockProperty copy() { + return new UnsignedIntBlockProperty(this.getName(), this.isExportedToItem(), (int) this.getMaxValue(), (int) this.getMinValue(), this.getBitSize(), this.getPersistenceName()); + } + + @Override + public UnsignedIntBlockProperty exportingToItems(boolean exportedToItem) { + return new UnsignedIntBlockProperty(this.getName(), exportedToItem, (int) this.getMaxValue(), (int) this.getMinValue(), this.getBitSize(), this.getPersistenceName()); + } + + @Override + public Class getValueClass() { + return Integer.class; + } + + private static long removeSign(int value) { + return (long) value & 0xFFFFFFFFL; + } + + private static int addSign(long value) { + return (int) (value & 0xFFFFFFFFL); + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/custom/properties/exception/BlockPropertyNotFoundException.java b/src/main/java/cn/nukkit/block/custom/properties/exception/BlockPropertyNotFoundException.java new file mode 100644 index 00000000000..c10b65b3787 --- /dev/null +++ b/src/main/java/cn/nukkit/block/custom/properties/exception/BlockPropertyNotFoundException.java @@ -0,0 +1,28 @@ +package cn.nukkit.block.custom.properties.exception; + +import cn.nukkit.block.custom.properties.BlockProperties; + +import java.util.NoSuchElementException; + +public class BlockPropertyNotFoundException extends NoSuchElementException { + private final String propertyName; + + public BlockPropertyNotFoundException(String propertyName) { + super("The property \""+propertyName+"\" was not found."); + this.propertyName = propertyName; + } + + public BlockPropertyNotFoundException(String propertyName, String details) { + super(propertyName+": " + details); + this.propertyName = propertyName; + } + + public BlockPropertyNotFoundException(String propertyName, BlockProperties properties) { + super("The property " + propertyName + " was not found. Valid properties: " + properties.getNames()); + this.propertyName = propertyName; + } + + public String getPropertyName() { + return propertyName; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/custom/properties/exception/InvalidBlockPropertyException.java b/src/main/java/cn/nukkit/block/custom/properties/exception/InvalidBlockPropertyException.java new file mode 100644 index 00000000000..7bb55c4ee76 --- /dev/null +++ b/src/main/java/cn/nukkit/block/custom/properties/exception/InvalidBlockPropertyException.java @@ -0,0 +1,37 @@ +package cn.nukkit.block.custom.properties.exception; + +import cn.nukkit.block.custom.properties.BlockProperty; + +public class InvalidBlockPropertyException extends IllegalArgumentException { + private static final long serialVersionUID = -6934630506175381230L; + + private final BlockProperty property; + + public InvalidBlockPropertyException(BlockProperty property) { + super(buildMessage(property)); + this.property = property; + } + + public InvalidBlockPropertyException(BlockProperty property, String message) { + super(buildMessage(property) + ". "+message); + this.property = property; + } + + public InvalidBlockPropertyException(BlockProperty property, String message, Throwable cause) { + super(buildMessage(property) + ". "+message, cause); + this.property = property; + } + + public InvalidBlockPropertyException(BlockProperty property, Throwable cause) { + super(buildMessage(property), cause); + this.property = property; + } + + private static String buildMessage(BlockProperty property) { + return "Property: " + property.getName(); + } + + public BlockProperty getProperty() { + return property; + } +} diff --git a/src/main/java/cn/nukkit/block/custom/properties/exception/InvalidBlockPropertyMetaException.java b/src/main/java/cn/nukkit/block/custom/properties/exception/InvalidBlockPropertyMetaException.java new file mode 100644 index 00000000000..db889ed8d51 --- /dev/null +++ b/src/main/java/cn/nukkit/block/custom/properties/exception/InvalidBlockPropertyMetaException.java @@ -0,0 +1,46 @@ +package cn.nukkit.block.custom.properties.exception; + +import cn.nukkit.block.custom.properties.BlockProperty; + +public class InvalidBlockPropertyMetaException extends InvalidBlockPropertyException { + private static final long serialVersionUID = -8493494844859767053L; + + private final Number currentMeta; + private final Number invalidMeta; + + public InvalidBlockPropertyMetaException(BlockProperty property, Number currentMeta, Number invalidMeta) { + super(property, buildMessage(currentMeta, invalidMeta)); + this.currentMeta = currentMeta; + this.invalidMeta = invalidMeta; + } + + public InvalidBlockPropertyMetaException(BlockProperty property, Number currentMeta, Number invalidMeta, String message) { + super(property, buildMessage(currentMeta, invalidMeta)+". "+message); + this.currentMeta = currentMeta; + this.invalidMeta = invalidMeta; + } + + public InvalidBlockPropertyMetaException(BlockProperty property, Number currentMeta, Number invalidMeta, String message, Throwable cause) { + super(property, buildMessage(currentMeta, invalidMeta)+". "+message, cause); + this.currentMeta = currentMeta; + this.invalidMeta = invalidMeta; + } + + public InvalidBlockPropertyMetaException(BlockProperty property, Number currentMeta, Number invalidMeta, Throwable cause) { + super(property, buildMessage(currentMeta, invalidMeta), cause); + this.currentMeta = currentMeta; + this.invalidMeta = invalidMeta; + } + + private static String buildMessage(Object currentValue, Object invalidValue) { + return "Current Meta: "+currentValue+", Invalid Meta: "+invalidValue; + } + + public Number getCurrentMeta() { + return this.currentMeta; + } + + public Number getInvalidMeta() { + return this.invalidMeta; + } +} diff --git a/src/main/java/cn/nukkit/block/custom/properties/exception/InvalidBlockPropertyPersistenceValueException.java b/src/main/java/cn/nukkit/block/custom/properties/exception/InvalidBlockPropertyPersistenceValueException.java new file mode 100644 index 00000000000..95ac8d1a6f5 --- /dev/null +++ b/src/main/java/cn/nukkit/block/custom/properties/exception/InvalidBlockPropertyPersistenceValueException.java @@ -0,0 +1,47 @@ +package cn.nukkit.block.custom.properties.exception; + +import cn.nukkit.block.custom.properties.BlockProperty; + +public class InvalidBlockPropertyPersistenceValueException extends InvalidBlockPropertyException { + private static final long serialVersionUID = 1L; + + private final String currentValue; + private final String invalidValue; + + public InvalidBlockPropertyPersistenceValueException(BlockProperty property, String currentValue, String invalidValue) { + super(property, buildMessage(currentValue, invalidValue)); + this.currentValue = currentValue; + this.invalidValue = invalidValue; + } + + + public InvalidBlockPropertyPersistenceValueException(BlockProperty property, String currentValue, String invalidValue, String message) { + super(property, buildMessage(currentValue, invalidValue)+". "+message); + this.currentValue = currentValue; + this.invalidValue = invalidValue; + } + + public InvalidBlockPropertyPersistenceValueException(BlockProperty property, String currentValue, String invalidValue, String message, Throwable cause) { + super(property, buildMessage(currentValue, invalidValue)+". "+message, cause); + this.currentValue = currentValue; + this.invalidValue = invalidValue; + } + + public InvalidBlockPropertyPersistenceValueException(BlockProperty property, String currentValue, String invalidValue, Throwable cause) { + super(property, buildMessage(currentValue, invalidValue), cause); + this.currentValue = currentValue; + this.invalidValue = invalidValue; + } + + private static String buildMessage(Object currentValue, Object invalidValue) { + return "Current Value: "+currentValue+", Invalid Value: "+invalidValue; + } + + public String getCurrentValue() { + return this.currentValue; + } + + public String getInvalidValue() { + return this.invalidValue; + } +} diff --git a/src/main/java/cn/nukkit/block/custom/properties/exception/InvalidBlockPropertyValueException.java b/src/main/java/cn/nukkit/block/custom/properties/exception/InvalidBlockPropertyValueException.java new file mode 100644 index 00000000000..f68d28edc11 --- /dev/null +++ b/src/main/java/cn/nukkit/block/custom/properties/exception/InvalidBlockPropertyValueException.java @@ -0,0 +1,49 @@ +package cn.nukkit.block.custom.properties.exception; + +import cn.nukkit.block.custom.properties.BlockProperty; + +import java.io.Serializable; + +public class InvalidBlockPropertyValueException extends InvalidBlockPropertyException { + private static final long serialVersionUID = -1087431932428639175L; + + private final Serializable currentValue; + private final Serializable invalidValue; + + public InvalidBlockPropertyValueException(BlockProperty property, Serializable currentValue, Serializable invalidValue) { + super(property, buildMessage(currentValue, invalidValue)); + this.currentValue = currentValue; + this.invalidValue = invalidValue; + } + + public InvalidBlockPropertyValueException(BlockProperty property, Serializable currentValue, Serializable invalidValue, String message) { + super(property, buildMessage(currentValue, invalidValue)+". "+message); + this.currentValue = currentValue; + this.invalidValue = invalidValue; + } + + public InvalidBlockPropertyValueException(BlockProperty property, Serializable currentValue, Serializable invalidValue, String message, Throwable cause) { + super(property, buildMessage(currentValue, invalidValue)+". "+message, cause); + this.currentValue = currentValue; + this.invalidValue = invalidValue; + } + + public InvalidBlockPropertyValueException(BlockProperty property, Serializable currentValue, Serializable invalidValue, Throwable cause) { + super(property, buildMessage(currentValue, invalidValue), cause); + this.currentValue = currentValue; + this.invalidValue = invalidValue; + } + + private static String buildMessage(Object currentValue, Object invalidValue) { + return "Current Value: "+currentValue+", Invalid Value: "+invalidValue; + } + + + public Serializable getCurrentValue() { + return this.currentValue; + } + + public Serializable getInvalidValue() { + return this.invalidValue; + } +} diff --git a/src/main/java/cn/nukkit/block/properties/BlockPropertiesHelper.java b/src/main/java/cn/nukkit/block/properties/BlockPropertiesHelper.java new file mode 100644 index 00000000000..6107ac6e16f --- /dev/null +++ b/src/main/java/cn/nukkit/block/properties/BlockPropertiesHelper.java @@ -0,0 +1,26 @@ +package cn.nukkit.block.properties; + +import cn.nukkit.block.custom.container.BlockStorageContainer; + +public interface BlockPropertiesHelper extends BlockStorageContainer { + + int getId(); + + int getDamage(); + void setDamage(int meta); + + @Override + default int getStorage() { + return this.getDamage(); + } + + @Override + default void setStorage(int damage) { + this.setDamage(damage); + } + + @Override + default int getNukkitId() { + return this.getId(); + } +} diff --git a/src/main/java/cn/nukkit/block/properties/DripleafTilt.java b/src/main/java/cn/nukkit/block/properties/DripleafTilt.java new file mode 100644 index 00000000000..97c1e897b22 --- /dev/null +++ b/src/main/java/cn/nukkit/block/properties/DripleafTilt.java @@ -0,0 +1,19 @@ +package cn.nukkit.block.properties; + +import lombok.Getter; + +@Getter +public enum DripleafTilt { + NONE(true, -1), + UNSTABLE(false, 10), + PARTIAL_TILT(true, 10), + FULL_TILT(false, 100); + + private final boolean stable; + private final int netxStateDelay; + + DripleafTilt(boolean stable, int netxStateDelay) { + this.stable = stable; + this.netxStateDelay = netxStateDelay; + } +} diff --git a/src/main/java/cn/nukkit/block/properties/DripstoneThickness.java b/src/main/java/cn/nukkit/block/properties/DripstoneThickness.java new file mode 100644 index 00000000000..f8da5c92fdb --- /dev/null +++ b/src/main/java/cn/nukkit/block/properties/DripstoneThickness.java @@ -0,0 +1,9 @@ +package cn.nukkit.block.properties; + +public enum DripstoneThickness { + TIP, + FRUSTUM, + MIDDLE, + BASE, + MERGE; +} diff --git a/src/main/java/cn/nukkit/block/properties/OxidizationLevel.java b/src/main/java/cn/nukkit/block/properties/OxidizationLevel.java new file mode 100644 index 00000000000..4ac6a610f44 --- /dev/null +++ b/src/main/java/cn/nukkit/block/properties/OxidizationLevel.java @@ -0,0 +1,8 @@ +package cn.nukkit.block.properties; + +public enum OxidizationLevel { + UNAFFECTED, + EXPOSED, + WEATHERED, + OXIDIZED +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/block/properties/VanillaProperties.java b/src/main/java/cn/nukkit/block/properties/VanillaProperties.java new file mode 100644 index 00000000000..5215b3fad33 --- /dev/null +++ b/src/main/java/cn/nukkit/block/properties/VanillaProperties.java @@ -0,0 +1,20 @@ +package cn.nukkit.block.properties; + +import cn.nukkit.block.custom.properties.BlockProperty; +import cn.nukkit.block.custom.properties.BooleanBlockProperty; +import cn.nukkit.block.custom.properties.EnumBlockProperty; +import cn.nukkit.math.BlockFace; + +public class VanillaProperties { + + public static final BooleanBlockProperty UPPER_BLOCK = new BooleanBlockProperty("upper_block_bit", false); + + public static final BlockProperty DIRECTION = new EnumBlockProperty<>("direction", false, + new BlockFace[]{ BlockFace.SOUTH, BlockFace.WEST, BlockFace.NORTH, BlockFace.EAST }).ordinal(true); + + public static final BlockProperty FACING_DIRECTION = new EnumBlockProperty<>("facing_direction", false, + new BlockFace[] { BlockFace.DOWN, BlockFace.UP, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.WEST, BlockFace.EAST }).ordinal(true); + + public static final BlockProperty STAIRS_DIRECTION = new EnumBlockProperty<>("weirdo_direction", false, + new BlockFace[]{ BlockFace.EAST, BlockFace.WEST, BlockFace.SOUTH, BlockFace.NORTH }).ordinal(true); +} diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntity.java b/src/main/java/cn/nukkit/blockentity/BlockEntity.java index cbc97c453e7..a7433392530 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntity.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntity.java @@ -2,14 +2,15 @@ import cn.nukkit.Server; import cn.nukkit.block.Block; +import cn.nukkit.block.BlockLayer; import cn.nukkit.level.Position; import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.persistence.PersistentDataContainer; +import cn.nukkit.level.persistence.impl.PersistentDataContainerBlockWrapper; import cn.nukkit.math.Vector3; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.utils.ChunkException; -import cn.nukkit.utils.MainLogger; -import co.aikar.timings.Timing; -import co.aikar.timings.Timings; +import cn.nukkit.utils.LevelException; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; @@ -19,6 +20,7 @@ * @author MagicDroidX */ public abstract class BlockEntity extends Position { + //WARNING: DO NOT CHANGE ANY NAME HERE, OR THE CLIENT WILL CRASH public static final String CHEST = "Chest"; public static final String ENDER_CHEST = "EnderChest"; @@ -32,6 +34,7 @@ public abstract class BlockEntity extends Position { public static final String DAYLIGHT_DETECTOR = "DaylightDetector"; public static final String MUSIC = "Music"; public static final String ITEM_FRAME = "ItemFrame"; + public static final String GLOW_ITEM_FRAME = "GlowItemFrame"; public static final String CAULDRON = "Cauldron"; public static final String BEACON = "Beacon"; public static final String PISTON_ARM = "PistonArm"; @@ -42,41 +45,49 @@ public abstract class BlockEntity extends Position { public static final String JUKEBOX = "Jukebox"; public static final String SHULKER_BOX = "ShulkerBox"; public static final String BANNER = "Banner"; - + public static final String DROPPER = "Dropper"; + public static final String DISPENSER = "Dispenser"; + public static final String BARREL = "Barrel"; + public static final String CAMPFIRE = "Campfire"; + public static final String BELL = "Bell"; + public static final String LECTERN = "Lectern"; + public static final String BLAST_FURNACE = "BlastFurnace"; + public static final String SMOKER = "Smoker"; + + // Not a vanilla block entity + public static final String PERSISTENT_CONTAINER = "PersistentContainer"; public static long count = 1; - private static final BiMap> knownBlockEntities = HashBiMap.create(21); + private static final BiMap> knownBlockEntities = HashBiMap.create(30); public FullChunk chunk; public String name; public long id; - public boolean movable = true; + public boolean movable; public boolean closed = false; public CompoundTag namedTag; - protected long lastUpdate; protected Server server; - protected Timing timing; + + private PersistentDataContainer persistentContainer; public BlockEntity(FullChunk chunk, CompoundTag nbt) { if (chunk == null || chunk.getProvider() == null) { - throw new ChunkException("Invalid garbage Chunk given to Block Entity"); + throw new ChunkException("Invalid garbage chunk given to BlockEntity"); } - this.timing = Timings.getBlockEntityTiming(this); this.server = chunk.getProvider().getLevel().getServer(); this.chunk = chunk; this.setLevel(chunk.getProvider().getLevel()); this.namedTag = nbt; this.name = ""; - this.lastUpdate = System.currentTimeMillis(); this.id = BlockEntity.count++; this.x = this.namedTag.getInt("x"); this.y = this.namedTag.getInt("y"); this.z = this.namedTag.getInt("z"); - this.movable = this.namedTag.getBoolean("isMovable"); + this.movable = this.namedTag.getBoolean("isMovable", true); this.initBlockEntity(); @@ -89,7 +100,6 @@ protected void initBlockEntity() { } public static BlockEntity createBlockEntity(String type, FullChunk chunk, CompoundTag nbt, Object... args) { - type = type.replaceFirst("BlockEntity", ""); //TODO: Remove this after the first release BlockEntity blockEntity = null; if (knownBlockEntities.containsKey(type)) { @@ -99,7 +109,7 @@ public static BlockEntity createBlockEntity(String type, FullChunk chunk, Compou return null; } - for (Constructor constructor : clazz.getConstructors()) { + for (Constructor constructor : clazz.getConstructors()) { if (blockEntity != null) { break; } @@ -120,11 +130,10 @@ public static BlockEntity createBlockEntity(String type, FullChunk chunk, Compou blockEntity = (BlockEntity) constructor.newInstance(objects); } - } catch (Exception e) { - MainLogger.getLogger().logException(e); - } - + } catch (Exception ignored) {} } + } else { + Server.getInstance().getLogger().warning("Tried to create block entity that doesn't exists: " + type); } return blockEntity; @@ -159,7 +168,7 @@ public CompoundTag getCleanedNBT() { this.saveNBT(); CompoundTag tag = this.namedTag.clone(); tag.remove("x").remove("y").remove("z").remove("id"); - if (tag.getTags().size() > 0) { + if (!tag.isEmpty()) { return tag; } else { return null; @@ -170,6 +179,18 @@ public Block getBlock() { return this.getLevelBlock(); } + @Override + public Block getLevelBlock() { + if (this.isValid()) return this.level.getBlock(this.chunk, this.getFloorX(), this.getFloorY(), this.getFloorZ(), BlockLayer.NORMAL, true); + else throw new LevelException("Undefined Level reference"); + } + + @Override + public Block getLevelBlock(BlockLayer layer) { + if (this.isValid()) return this.level.getBlock(this.chunk, this.getFloorX(), this.getFloorY(), this.getFloorZ(), layer, true); + else throw new LevelException("Undefined Level reference"); + } + public abstract boolean isBlockEntityValid(); public boolean onUpdate() { @@ -177,6 +198,9 @@ public boolean onUpdate() { } public final void scheduleUpdate() { + if (this.level.isBeingConverted) { + return; + } this.level.scheduleBlockEntityUpdate(this); } @@ -198,7 +222,9 @@ public void onBreak() { } public void setDirty() { - chunk.setChanged(); + if (this.chunk != null) { + this.chunk.setChanged(); + } } public String getName() { @@ -210,10 +236,34 @@ public boolean isMovable() { } public static CompoundTag getDefaultCompound(Vector3 pos, String id) { - return new CompoundTag("") + return new CompoundTag() .putString("id", id) .putInt("x", pos.getFloorX()) .putInt("y", pos.getFloorY()) .putInt("z", pos.getFloorZ()); } -} + + public PersistentDataContainer getPersistentDataContainer() { + if (this.persistentContainer == null) { + this.persistentContainer = new PersistentDataContainerBlockWrapper(this); + } + return this.persistentContainer; + } + + public boolean hasPersistentDataContainer() { + return !this.getPersistentDataContainer().isEmpty(); + } + + public void onReplacedWith(BlockEntity blockEntity) { + blockEntity.getPersistentDataContainer().setStorage(this.getPersistentDataContainer().getStorage().clone()); + } + + @Override + public boolean equals(Object obj) { + return obj instanceof BlockEntity && this.getClass().equals(obj.getClass()) && super.equals(obj); + } + + public boolean canSaveToStorage() { + return true; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityBanner.java b/src/main/java/cn/nukkit/blockentity/BlockEntityBanner.java index 66a7a38cfff..94bbeadc7d6 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityBanner.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityBanner.java @@ -28,7 +28,8 @@ protected void initBlockEntity() { @Override public boolean isBlockEntityValid() { - return this.getBlock().getId() == Block.WALL_BANNER || this.getBlock().getId() == Block.STANDING_BANNER; + int id = level.getBlockIdAt(chunk, (int) x, (int) y, (int) z); + return id == Block.WALL_BANNER || id == Block.STANDING_BANNER; } @Override @@ -48,6 +49,7 @@ public int getBaseColor() { public void setBaseColor(DyeColor color) { this.namedTag.putInt("Base", color.getDyeData() & 0x0f); + setDirty(); } public int getType() { @@ -56,6 +58,7 @@ public int getType() { public void setType(int type) { this.namedTag.putInt("Type", type); + setDirty(); } public void addPattern(BannerPattern pattern) { @@ -64,6 +67,7 @@ public void addPattern(BannerPattern pattern) { putInt("Color", pattern.getColor().getDyeData() & 0x0f). putString("Pattern", pattern.getType().getName())); this.namedTag.putList(patterns); + setDirty(); } public BannerPattern getPattern(int index) { @@ -72,9 +76,10 @@ public BannerPattern getPattern(int index) { public void removePattern(int index) { ListTag patterns = this.namedTag.getList("Patterns", CompoundTag.class); - if(patterns.size() > index && index >= 0) { + if (patterns.size() > index && index >= 0) { patterns.remove(index); } + setDirty(); } public int getPatternsSize() { diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityBarrel.java b/src/main/java/cn/nukkit/blockentity/BlockEntityBarrel.java new file mode 100644 index 00000000000..6ac918397fe --- /dev/null +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityBarrel.java @@ -0,0 +1,169 @@ +package cn.nukkit.blockentity; + +import cn.nukkit.Player; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; +import cn.nukkit.inventory.BarrelInventory; +import cn.nukkit.inventory.InventoryHolder; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.NBTIO; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.ListTag; + +import java.util.ArrayList; + +public class BlockEntityBarrel extends BlockEntitySpawnable implements InventoryHolder, BlockEntityContainer, BlockEntityNameable { + + protected BarrelInventory inventory; + + public BlockEntityBarrel(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + private void initInventory() { + if (!this.namedTag.contains("Items") || !(this.namedTag.get("Items") instanceof ListTag)) { + this.namedTag.putList(new ListTag("Items")); + } + ListTag list = (ListTag) this.namedTag.getList("Items"); + + this.inventory = new BarrelInventory(this); + + for (CompoundTag compound : list.getAll()) { + Item item = NBTIO.getItemHelper(compound); + if (item.getId() != 0 && item.getCount() > 0) { + this.inventory.slots.put(compound.getByte("Slot"), item); + } + } + } + + @Override + public void close() { + if (!this.closed && this.inventory != null) { + for (Player player : new ArrayList<>(this.inventory.getViewers())) { + player.removeWindow(this.inventory); + } + } + + super.close(); + } + + @Override + public void onBreak() { + if (this.inventory == null) { + this.initInventory(); + } + for (Item content : inventory.getContents().values()) { + level.dropItem(this, content); + } + inventory.clearAll(); // Stop items from being moved around by another player in the inventory + } + + @Override + public void saveNBT() { + super.saveNBT(); + + if (this.inventory != null) { + this.namedTag.putList(new ListTag("Items")); + for (int index = 0; index < this.getSize(); index++) { + this.setItem(index, this.inventory.getItem(index)); + } + } + } + + @Override + public boolean isBlockEntityValid() { + return level.getBlockIdAt(chunk, (int) x, (int) y, (int) z) == BlockID.BARREL; + } + + @Override + public int getSize() { + return 27; + } + + protected int getSlotIndex(int index) { + ListTag list = this.namedTag.getList("Items", CompoundTag.class); + for (int i = 0; i < list.size(); i++) { + if (list.get(i).getByte("Slot") == index) { + return i; + } + } + + return -1; + } + + @Override + public Item getItem(int index) { + int i = this.getSlotIndex(index); + if (i < 0) { + return new ItemBlock(Block.get(BlockID.AIR), 0, 0); + } else { + CompoundTag data = (CompoundTag) this.namedTag.getList("Items").get(i); + return NBTIO.getItemHelper(data); + } + } + + @Override + public void setItem(int index, Item item) { + int i = this.getSlotIndex(index); + + CompoundTag d = NBTIO.putItemHelper(item, index); + + // If item is air or count less than 0, remove the item from the "Items" list + if (item.getId() == Item.AIR || item.getCount() <= 0) { + if (i >= 0) { + this.namedTag.getList("Items").remove(i); + } + } else if (i < 0) { + // If it is less than i, then it is a new item, so we are going to add it at the end of the list + (this.namedTag.getList("Items", CompoundTag.class)).add(d); + } else { + // If it is more than i, then it is an update on a inventorySlot, so we are going to overwrite the item in the list + (this.namedTag.getList("Items", CompoundTag.class)).add(i, d); + } + } + + @Override + public BarrelInventory getInventory() { + if (this.inventory == null) { + this.initInventory(); + } + return this.inventory; + } + + @Override + public String getName() { + return this.hasName() ? this.namedTag.getString("CustomName") : "Barrel"; + } + + @Override + public boolean hasName() { + return this.namedTag.contains("CustomName"); + } + + @Override + public void setName(String name) { + if (name == null || name.isEmpty()) { + this.namedTag.remove("CustomName"); + return; + } + + this.namedTag.putString("CustomName", name); + } + + @Override + public CompoundTag getSpawnCompound() { + CompoundTag c = new CompoundTag() + .putString("id", BlockEntity.BARREL) + .putInt("x", (int) this.x) + .putInt("y", (int) this.y) + .putInt("z", (int) this.z); + + if (this.hasName()) { + c.put("CustomName", this.namedTag.get("CustomName")); + } + + return c; + } +} diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityBeacon.java b/src/main/java/cn/nukkit/blockentity/BlockEntityBeacon.java index ac72e7a1771..0b60b55f955 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityBeacon.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityBeacon.java @@ -4,6 +4,7 @@ import cn.nukkit.Server; import cn.nukkit.block.Block; import cn.nukkit.event.entity.EntityPotionEffectEvent; +import cn.nukkit.inventory.BeaconInventory; import cn.nukkit.inventory.Inventory; import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; @@ -16,10 +17,12 @@ import java.util.Map; /** - * author: Rover656 + * @author Rover656 */ public class BlockEntityBeacon extends BlockEntitySpawnable { + private long currentTick; + public BlockEntityBeacon(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @@ -42,15 +45,14 @@ protected void initBlockEntity() { namedTag.putInt("Secondary", 0); } - scheduleUpdate(); + this.scheduleUpdate(); super.initBlockEntity(); } @Override public boolean isBlockEntityValid() { - int blockID = getBlock().getId(); - return blockID == Block.BEACON; + return level.getBlockIdAt(chunk, (int) x, (int) y, (int) z) == Block.BEACON; } @Override @@ -66,22 +68,28 @@ public CompoundTag getSpawnCompound() { .putInt("Secondary", this.namedTag.getInt("Secondary")); } - private long currentTick = 0; - @Override public boolean onUpdate() { + if (this.closed) { + return false; + } + //Only apply effects every 4 secs if (currentTick++ % 80 != 0) { return true; } - int oldPowerLevel = this.getPowerLevel(); //Get the power level based on the pyramid - setPowerLevel(calculatePowerLevel()); - int newPowerLevel = this.getPowerLevel(); + int power = this.calculatePowerLevel(); + if (power == -1) { //Couldn't calculate due to unloaded chunks + return true; + } + + int oldPowerLevel = this.getPowerLevel(); + this.setPowerLevel(power); //Skip beacons that do not have a pyramid or sky access - if (newPowerLevel < 1 || !hasSkyAccess()) { + if (this.getPowerLevel() < 1 || !hasSkyAccess()) { if (oldPowerLevel > 0) { this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_BEACON_DEACTIVATE); } @@ -92,18 +100,15 @@ public boolean onUpdate() { this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_BEACON_AMBIENT); } - //Get all players in game - Map players = this.level.getPlayers(); + int powerLevel = getPowerLevel(); + //In seconds + int duration = (9 + (powerLevel << 1)) * 20; - //Calculate vars for beacon power - int range = 10 + getPowerLevel() * 10; - int duration = 9 + getPowerLevel() * 2; - - for(Map.Entry entry : players.entrySet()) { + for (Map.Entry entry : this.level.getPlayers().entrySet()) { Player p = entry.getValue(); //If the player is in range - if (p.distance(this) < range) { + if (p.distance(this) < 10 + powerLevel * 10) { Effect e; if (getPrimaryPower() != 0) { @@ -111,7 +116,7 @@ public boolean onUpdate() { e = Effect.getEffect(getPrimaryPower()); //Set duration - e.setDuration(duration * 20); + e.setDuration(duration); //If secondary is selected as the primary too, apply 2 amplification if (getSecondaryPower() == getPrimaryPower()) { @@ -133,10 +138,10 @@ public boolean onUpdate() { e = Effect.getEffect(Effect.REGENERATION); //Set duration - e.setDuration(duration * 20); + e.setDuration(duration); //Regen I - e.setAmplifier(1); + e.setAmplifier(0); //Hide particles e.setVisible(false); @@ -144,6 +149,10 @@ public boolean onUpdate() { //Add effect p.addEffect(e, EntityPotionEffectEvent.Cause.BEACON); } + + if (powerLevel >= POWER_LEVEL_MAX) { + p.awardAchievement("fullBeacon"); + } } } @@ -158,9 +167,9 @@ private boolean hasSkyAccess() { int tileZ = getFloorZ(); //Check every block from our y coord to the top of the world - for (int y = tileY + 1; y <= 255; y++) { - int testBlockId = level.getBlockIdAt(tileX, y, tileZ); - if (!Block.transparent[testBlockId]) { + for (int y = tileY + 1; y <= this.level.getMaxBlockY(); y++) { + int testBlockId = level.getBlockIdAt(chunk, tileX, y, tileZ); + if (!Block.isBlockTransparentById(testBlockId)) { //There is no sky access return false; } @@ -181,16 +190,20 @@ private int calculatePowerLevel() { for (int queryX = tileX - powerLevel; queryX <= tileX + powerLevel; queryX++) { for (int queryZ = tileZ - powerLevel; queryZ <= tileZ + powerLevel; queryZ++) { - int testBlockId = level.getBlockIdAt(queryX, queryY, queryZ); + int testBlockId = getBlockIdIfLoaded(queryX, queryY, queryZ); + if (testBlockId == -1) { + return -1; + } + if ( testBlockId != Block.IRON_BLOCK && testBlockId != Block.GOLD_BLOCK && testBlockId != Block.EMERALD_BLOCK && - testBlockId != Block.DIAMOND_BLOCK - ) { + testBlockId != Block.DIAMOND_BLOCK && + testBlockId != Block.NETHERITE_BLOCK + ) { return powerLevel - 1; } - } } } @@ -198,6 +211,26 @@ private int calculatePowerLevel() { return POWER_LEVEL_MAX; } + private int getBlockIdIfLoaded(int bx, int by, int bz) { + if (by < this.level.getMinBlockY() || by > this.level.getMaxBlockY()) return 0; + int cx = bx >> 4; + int cz = bz >> 4; + FullChunk fullChunk = this.chunk; + if (fullChunk == null || cx != fullChunk.getX() || cz != fullChunk.getZ()) { + fullChunk = level.getChunkIfLoaded(cx, cz); + if (fullChunk == null) { + return -1; + } + } + return fullChunk.getBlockId(bx & 0x0f, by, bz & 0x0f); + } + + @Override + public void setDirty() { + super.setDirty(); + this.spawnToAll(); + } + public int getPowerLevel() { return namedTag.getInt("Level"); } @@ -207,7 +240,6 @@ public void setPowerLevel(int level) { if (level != currentLevel) { namedTag.putInt("Level", level); setDirty(); - this.spawnToAll(); } } @@ -220,7 +252,6 @@ public void setPrimaryPower(int power) { if (power != currentPower) { namedTag.putInt("Primary", power); setDirty(); - this.spawnToAll(); } } @@ -233,7 +264,6 @@ public void setSecondaryPower(int power) { if (power != currentPower) { namedTag.putInt("Secondary", power); setDirty(); - this.spawnToAll(); } } @@ -247,6 +277,10 @@ public boolean updateCompoundTag(CompoundTag nbt, Player player) { Inventory inv = player.getWindowById(Player.BEACON_WINDOW_ID); if (inv != null) { + if (!BeaconInventory.ITEMS.contains(inv.getItemFast(0).getId())) { + Server.getInstance().getLogger().debug(player.getName() + " tried to set effect but there's no payment in beacon inventory"); + return false; + } inv.setItem(0, Item.get(Item.AIR)); } else { Server.getInstance().getLogger().debug(player.getName() + " tried to set effect but beacon inventory is null"); diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityBed.java b/src/main/java/cn/nukkit/blockentity/BlockEntityBed.java index 9fc6c2b8e70..db6851e73d4 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityBed.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityBed.java @@ -29,7 +29,7 @@ protected void initBlockEntity() { @Override public boolean isBlockEntityValid() { - return this.level.getBlockIdAt(this.getFloorX(), this.getFloorY(), this.getFloorZ()) == Item.BED_BLOCK; + return level.getBlockIdAt(chunk, (int) x, (int) y, (int) z) == Item.BED_BLOCK; } @Override diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityBell.java b/src/main/java/cn/nukkit/blockentity/BlockEntityBell.java new file mode 100644 index 00000000000..30e788bf4d6 --- /dev/null +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityBell.java @@ -0,0 +1,149 @@ +package cn.nukkit.blockentity; + +import cn.nukkit.Player; +import cn.nukkit.block.BlockID; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.ByteTag; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.IntTag; +import cn.nukkit.network.protocol.LevelSoundEventPacket; +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; + +public class BlockEntityBell extends BlockEntitySpawnable { + + private boolean ringing; + private int direction; + private int ticks; + public final LongOpenHashSet spawnExceptions = new LongOpenHashSet(2); + + public BlockEntityBell(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + @Override + protected void initBlockEntity() { + if (!namedTag.contains("Ringing") || !(namedTag.get("Ringing") instanceof ByteTag)) { + ringing = false; + } else { + ringing = namedTag.getBoolean("Ringing"); + } + + if (!namedTag.contains("Direction") || !(namedTag.get("Direction") instanceof IntTag)) { + direction = 255; + } else { + direction = namedTag.getInt("Direction"); + } + + if (!namedTag.contains("Ticks") || !(namedTag.get("Ticks") instanceof IntTag)) { + ticks = 0; + } else { + ticks = namedTag.getInt("Ticks"); + } + + super.initBlockEntity(); + scheduleUpdate(); + } + + @Override + public void saveNBT() { + namedTag.putBoolean("Ringing", ringing); + namedTag.putInt("Direction", direction); + namedTag.putInt("Ticks", ticks); + super.saveNBT(); + } + + @Override + public boolean onUpdate() { + if (this.closed) { + return false; + } + + if (ringing) { + if (ticks == 0) { + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_BLOCK_BELL_HIT); + spawnToAllWithExceptions(); + spawnExceptions.clear(); + } else if (ticks >= 50) { + ringing = false; + ticks = 0; + spawnToAllWithExceptions(); + spawnExceptions.clear(); + return false; + } + //spawnToAll(); + ticks++; + return true; + } else if (ticks > 0) { + ticks = 0; + spawnToAllWithExceptions(); + spawnExceptions.clear(); + } + + return false; + } + + private void spawnToAllWithExceptions() { + for (Player player : this.getLevel().getChunkPlayers(this.chunk.getX(), this.chunk.getZ()).values()) { + if (player.spawned && !spawnExceptions.contains(player.getId())) { + this.spawnTo(player); + } + } + } + + public boolean isRinging() { + return ringing; + } + + public void setRinging(boolean ringing) { + if (this.level != null && this.ringing != ringing) { + this.ringing = ringing; + scheduleUpdate(); + setDirty(); + } + } + + public int getDirection() { + return direction; + } + + public void setDirection(int direction) { + if (this.direction != direction) { + this.direction = direction; + setDirty(); + } + } + + public int getTicks() { + return ticks; + } + + public void setTicks(int ticks) { + if (this.ticks != ticks) { + this.ticks = ticks; + setDirty(); + } + } + + @Override + public CompoundTag getSpawnCompound() { + CompoundTag tag = new CompoundTag() + .putString("id", BlockEntity.BELL) + .putInt("x", (int) this.x) + .putInt("y", (int) this.y) + .putInt("z", (int) this.z) + .putBoolean("Ringing", this.ringing) + .putInt("Direction", this.direction) + .putInt("Ticks", this.ticks); + return tag; + } + + @Override + public String getName() { + return "Bell"; + } + + @Override + public boolean isBlockEntityValid() { + return level.getBlockIdAt(chunk, (int) x, (int) y, (int) z) == BlockID.BELL; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityBlastFurnace.java b/src/main/java/cn/nukkit/blockentity/BlockEntityBlastFurnace.java new file mode 100644 index 00000000000..71678eaec1e --- /dev/null +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityBlastFurnace.java @@ -0,0 +1,149 @@ +package cn.nukkit.blockentity; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; +import cn.nukkit.event.inventory.FurnaceSmeltEvent; +import cn.nukkit.inventory.FurnaceRecipe; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemArmor; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemTool; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.network.protocol.LevelSoundEventPacket; +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntSet; + +import java.util.concurrent.ThreadLocalRandom; + +public class BlockEntityBlastFurnace extends BlockEntityFurnace { + + public BlockEntityBlastFurnace(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + @Override + public String getName() { + return this.hasName() ? this.namedTag.getString("CustomName") : "Blast Furnace"; + } + + @Override + public boolean isBlockEntityValid() { + int blockID = level.getBlockIdAt(chunk, (int) x, (int) y, (int) z); + return blockID == Block.BLAST_FURNACE || blockID == Block.LIT_BLAST_FURNACE; + } + + private static final IntSet CAN_SMELT_EXCLUDING_TOOLS_AND_ARMOR = new IntOpenHashSet(new int[]{ + Item.IRON_ORE, Item.GOLD_ORE, Item.DIAMOND_ORE, Item.LAPIS_ORE, Item.REDSTONE_ORE, Item.COAL_ORE, Item.EMERALD_ORE, Item.QUARTZ_ORE, + 255 - Block.NETHER_GOLD_ORE, 255 - Block.ANCIENT_DEBRIS, Item.RAW_COPPER, Item.RAW_IRON, Item.RAW_GOLD, + 255 - Block.DEEPSLATE_COAL_ORE, 255 - Block.DEEPSLATE_IRON_ORE, 255 - Block.DEEPSLATE_GOLD_ORE, 255 - Block.DEEPSLATE_LAPIS_ORE, + 255 - Block.DEEPSLATE_EMERALD_ORE, 255 - Block.DEEPSLATE_COPPER_ORE, 255 - Block.DEEPSLATE_REDSTONE_ORE, 255 - Block.DEEPSLATE_DIAMOND_ORE + }); + + @Override + public boolean onUpdate() { + if (this.closed) { + return false; + } + + Item raw = this.inventory.getSmelting(); + // TODO: blast furnace recipes + if (!CAN_SMELT_EXCLUDING_TOOLS_AND_ARMOR.contains(raw.getId()) && !(raw instanceof ItemTool && (raw.getTier() == ItemTool.TIER_IRON || raw.getTier() == ItemTool.TIER_GOLD)) && !(raw instanceof ItemArmor && raw.getTier() >= ItemArmor.TIER_IRON && raw.getTier() <= ItemArmor.TIER_GOLD)) { + if (burnTime > 0) { + burnTime--; + burnDuration = (int) Math.ceil((float) burnTime / maxTime * 100); + + if (burnTime == 0) { + Block block = this.level.getBlock(this.chunk, (int) x, (int) y, (int) z, true); + if (block.getId() == BlockID.LIT_BLAST_FURNACE) { + this.level.setBlock(this, Block.get(BlockID.BLAST_FURNACE, block.getDamage()), true); + } + return false; + } + } + + cookTime = 0; + sendPacket(); + return true; + } + + boolean ret = false; + Item product = this.inventory.getResult(); + FurnaceRecipe smelt = this.server.getCraftingManager().matchFurnaceRecipe(raw); + boolean canSmelt = (smelt != null && raw.getCount() > 0 && ((smelt.getResult().equals(product) && product.getCount() < product.getMaxStackSize()) || product.getId() == Item.AIR)); + + Item fuel; + if (burnTime <= 0 && canSmelt && (fuel = this.inventory.getItemFast(1)).getFuelTime() != null && fuel.getCount() > 0) { + this.checkFuel(fuel.clone()); + } + + if (burnTime > 0) { + burnTime--; + burnDuration = (int) Math.ceil((float) burnTime / maxTime * 100); + + if (this.crackledTime-- <= 0) { + this.crackledTime = ThreadLocalRandom.current().nextInt(30, 110); + this.getLevel().addLevelSoundEvent(this.add(0.5, 0.5, 0.5), LevelSoundEventPacket.SOUND_BLOCK_FURNACE_LIT); + } + + if (smelt != null && canSmelt) { + cookTime++; + if (cookTime >= 100) { + product = Item.get(smelt.getResult().getId(), smelt.getResult().getDamage(), product.isNull() ? 1 : product.getCount() + 1); + + FurnaceSmeltEvent ev = new FurnaceSmeltEvent(this, raw, product); + this.server.getPluginManager().callEvent(ev); + if (!ev.isCancelled()) { + this.inventory.setResult(ev.getResult()); + this.experience += FURNACE_XP.getOrDefault(ev.getResult().getId(), 0d); + raw.setCount(raw.getCount() - 1); + if (raw.getCount() == 0) { + raw = new ItemBlock(Block.get(BlockID.AIR), 0, 0); + } + this.inventory.setSmelting(raw); + } + + cookTime -= 100; + } + } else if (burnTime <= 0) { + burnTime = 0; + cookTime = 0; + burnDuration = 0; + } else { + cookTime = 0; + } + ret = true; + } else { + Block block = this.level.getBlock(this.chunk, (int) x, (int) y, (int) z, true); + if (block.getId() == BlockID.LIT_BLAST_FURNACE) { + this.level.setBlock(this, Block.get(BlockID.BLAST_FURNACE, block.getDamage()), true); + } + burnTime = 0; + cookTime = 0; + burnDuration = 0; + crackledTime = 0; + } + + sendPacket(); + + return ret; + } + + @Override + public CompoundTag getSpawnCompound() { + CompoundTag c = new CompoundTag() + .putString("id", BlockEntity.BLAST_FURNACE) + .putInt("x", (int) this.x) + .putInt("y", (int) this.y) + .putInt("z", (int) this.z) + .putShort("BurnDuration", burnDuration) + .putShort("BurnTime", burnTime) + .putShort("CookTime", cookTime); + + if (this.hasName()) { + c.put("CustomName", this.namedTag.get("CustomName")); + } + + return c; + } +} diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityBrewingStand.java b/src/main/java/cn/nukkit/blockentity/BlockEntityBrewingStand.java index 29045ca294e..cf2508e01f1 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityBrewingStand.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityBrewingStand.java @@ -1,18 +1,15 @@ package cn.nukkit.blockentity; import cn.nukkit.Player; -import cn.nukkit.Server; import cn.nukkit.block.Block; import cn.nukkit.block.BlockBrewingStand; import cn.nukkit.block.BlockID; import cn.nukkit.event.inventory.BrewEvent; import cn.nukkit.event.inventory.StartBrewEvent; -import cn.nukkit.inventory.BrewingInventory; -import cn.nukkit.inventory.BrewingRecipe; -import cn.nukkit.inventory.ContainerRecipe; -import cn.nukkit.inventory.InventoryHolder; +import cn.nukkit.inventory.*; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemID; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.CompoundTag; @@ -21,9 +18,6 @@ import cn.nukkit.network.protocol.LevelSoundEventPacket; import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; public class BlockEntityBrewingStand extends BlockEntitySpawnable implements InventoryHolder, BlockEntityContainer, BlockEntityNameable { @@ -35,12 +29,6 @@ public class BlockEntityBrewingStand extends BlockEntitySpawnable implements Inv public int fuelTotal; public int fuelAmount; - public static final List ingredients = new ArrayList() { - { - addAll(Arrays.asList(Item.NETHER_WART, Item.GHAST_TEAR, Item.GLOWSTONE_DUST, Item.REDSTONE_DUST, Item.GUNPOWDER, Item.MAGMA_CREAM, Item.BLAZE_POWDER, Item.GOLDEN_CARROT, Item.SPIDER_EYE, Item.FERMENTED_SPIDER_EYE, Item.GLISTERING_MELON, Item.SUGAR, Item.RABBIT_FOOT, Item.PUFFERFISH, Item.TURTLE_SHELL, Item.PHANTOM_MEMBRANE, 437)); - } - }; - public BlockEntityBrewingStand(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @@ -53,8 +41,12 @@ protected void initBlockEntity() { namedTag.putList(new ListTag("Items")); } - for (int i = 0; i < getSize(); i++) { - inventory.setItem(i, this.getItem(i)); + ListTag list = (ListTag) this.namedTag.getList("Items"); + for (CompoundTag compound : list.getAll()) { + Item item = NBTIO.getItemHelper(compound); + if (item.getId() != 0 && item.getCount() > 0) { + this.inventory.slots.put(compound.getByte("Slot"), item); + } } if (!namedTag.contains("CookTime") || namedTag.getShort("CookTime") > MAX_BREW_TIME) { @@ -85,7 +77,7 @@ public boolean hasName() { @Override public void setName(String name) { - if (name == null || name.equals("")) { + if (name == null || name.isEmpty()) { namedTag.remove("CustomName"); return; } @@ -96,8 +88,8 @@ public void setName(String name) { @Override public void close() { if (!closed) { - for (Player player : new HashSet<>(getInventory().getViewers())) { - player.removeWindow(getInventory()); + for (Player player : new ArrayList<>(this.inventory.getViewers())) { + player.removeWindow(this.inventory); } super.close(); } @@ -108,11 +100,12 @@ public void onBreak() { for (Item content : inventory.getContents().values()) { level.dropItem(this, content); } - this.inventory.clearAll(); + inventory.clearAll(); } @Override public void saveNBT() { + super.saveNBT(); namedTag.putList(new ListTag("Items")); for (int index = 0; index < getSize(); index++) { this.setItem(index, inventory.getItem(index)); @@ -125,7 +118,7 @@ public void saveNBT() { @Override public boolean isBlockEntityValid() { - return getBlock().getId() == Block.BREWING_STAND_BLOCK; + return level.getBlockIdAt(chunk, (int) x, (int) y, (int) z) == Block.BREWING_STAND_BLOCK; } @Override @@ -177,101 +170,130 @@ public BrewingInventory getInventory() { return inventory; } - protected boolean checkIngredient(Item ingredient) { - return ingredients.contains(ingredient.getId()); - } - @Override public boolean onUpdate() { if (closed) { return false; } - boolean ret = false; + restockFuel(); - Item ingredient = this.inventory.getIngredient(); - boolean canBrew = false; + if (this.fuelAmount <= 0 || matchRecipes(true)[0] == null) { + stopBrewing(); + return false; + } - Item fuel = this.getInventory().getFuel(); - if (this.fuelAmount <= 0 && fuel.getId() == Item.BLAZE_POWDER && fuel.getCount() > 0) { - fuel.count--; - this.fuelAmount = 20; - this.fuelTotal = 20; + if (brewTime == MAX_BREW_TIME) { + StartBrewEvent e = new StartBrewEvent(this); + this.server.getPluginManager().callEvent(e); - this.inventory.setFuel(fuel); - this.sendFuel(); + if (e.isCancelled()) { + return false; + } + + this.sendBrewTime(); } - if (this.fuelAmount > 0) { - for (int i = 1; i <= 3; i++) { - if (this.inventory.getItem(i).getId() == Item.POTION) { - canBrew = true; - } + if (--brewTime > 0) { + + if (brewTime % 40 == 0) { + sendBrewTime(); } - if (this.brewTime <= MAX_BREW_TIME && canBrew && ingredient.getCount() > 0) { - if (!this.checkIngredient(ingredient)) { - canBrew = false; + return true; + } + + //20 seconds + BrewEvent e = new BrewEvent(this); + this.server.getPluginManager().callEvent(e); + + if (e.isCancelled()) { + stopBrewing(); + return true; + } + + boolean mixed = false; + MixRecipe[] recipes = matchRecipes(false); + for (int i = 0; i < 3; i++) { + MixRecipe recipe = recipes[i]; + if (recipe == null) { + continue; + } + + Item previous = inventory.getItem(i + 1); + if (!previous.isNull()) { + Item result = recipe.getResult(); + result.setCount(previous.getCount()); + if (recipe instanceof ContainerRecipe) { + result.setDamage(previous.getDamage()); } - } else { - canBrew = false; + inventory.setItem(i + 1, result); + mixed = true; } } - if (canBrew) { - if (this.brewTime == MAX_BREW_TIME) { - this.sendBrewTime(); - StartBrewEvent e = new StartBrewEvent(this); - this.server.getPluginManager().callEvent(e); + if (mixed) { + Item ingredient = this.inventory.getIngredient(); + ingredient.count--; + this.inventory.setIngredient(ingredient); - if (e.isCancelled()) { - return false; - } + this.fuelAmount--; + this.sendFuel(); + + this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_POTION_BREWED); + } + + stopBrewing(); + return true; + } + + private void restockFuel() { + Item fuel = this.getInventory().getFuel(); + if (this.fuelAmount > 0 || fuel.getId() != ItemID.BLAZE_POWDER || fuel.getCount() <= 0) { + return; + } + + fuel.count--; + this.fuelAmount = 20; + this.fuelTotal = 20; + + this.inventory.setFuel(fuel); + this.sendFuel(); + } + + private void stopBrewing() { + this.brewTime = 0; + this.sendBrewTime(); + this.brewTime = MAX_BREW_TIME; + } + + private MixRecipe[] matchRecipes(boolean quickTest) { + MixRecipe[] recipes = new MixRecipe[quickTest? 1 : 3]; + Item ingredient = inventory.getIngredient(); + CraftingManager craftingManager = getLevel().getServer().getCraftingManager(); + for (int i = 0; i < 3; i++) { + Item potion = inventory.getItem(i + 1); + if (potion.isNull()) { + continue; } - this.brewTime--; - - if (this.brewTime <= 0) { //20 seconds - BrewEvent e = new BrewEvent(this); - this.server.getPluginManager().callEvent(e); - - if (!e.isCancelled()) { - for (int i = 1; i <= 3; i++) { - Item potion = this.inventory.getItem(i); - - ContainerRecipe containerRecipe = Server.getInstance().getCraftingManager().matchContainerRecipe(ingredient, potion); - if (containerRecipe != null) { - Item result = containerRecipe.getResult(); - result.setDamage(potion.getDamage()); - this.inventory.setItem(i, result); - } else { - BrewingRecipe recipe = Server.getInstance().getCraftingManager().matchBrewingRecipe(ingredient, potion); - if (recipe != null) { - this.inventory.setItem(i, recipe.getResult()); - } - } - } - this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_POTION_BREWED); - - ingredient.count--; - this.inventory.setIngredient(ingredient); - - this.fuelAmount--; - this.sendFuel(); - } + MixRecipe recipe = craftingManager.matchBrewingRecipe(ingredient, potion); + if (recipe == null) { + recipe = craftingManager.matchContainerRecipe(ingredient, potion); + } + if (recipe == null) { + continue; + } - this.brewTime = MAX_BREW_TIME; + if (quickTest) { + recipes[0] = recipe; + return recipes; } - ret = true; - } else { - this.brewTime = MAX_BREW_TIME; + recipes[i] = recipe; } - //this.sendBrewTime(); - lastUpdate = System.currentTimeMillis(); - - return ret; + return recipes; } protected void sendFuel() { @@ -328,6 +350,10 @@ public void updateBlock() { block.setDamage(meta); this.level.setBlock(block, block, false, false); + + if (brewTime != MAX_BREW_TIME && matchRecipes(true)[0] == null) { + stopBrewing(); + } } public int getFuel() { @@ -358,4 +384,4 @@ public CompoundTag getSpawnCompound() { return nbt; } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityCampfire.java b/src/main/java/cn/nukkit/blockentity/BlockEntityCampfire.java new file mode 100644 index 00000000000..33819d9e5f0 --- /dev/null +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityCampfire.java @@ -0,0 +1,229 @@ +package cn.nukkit.blockentity; + +import cn.nukkit.Player; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockCampfire; +import cn.nukkit.block.BlockID; +import cn.nukkit.event.block.CampfireSmeltEvent; +import cn.nukkit.inventory.CampfireInventory; +import cn.nukkit.inventory.CampfireRecipe; +import cn.nukkit.inventory.InventoryHolder; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.NBTIO; +import cn.nukkit.nbt.tag.CompoundTag; + +import java.util.ArrayList; +import java.util.concurrent.ThreadLocalRandom; + +public class BlockEntityCampfire extends BlockEntitySpawnable implements InventoryHolder, BlockEntityContainer { + + private CampfireInventory inventory; + private int[] burnTime; + private CampfireRecipe[] recipes; + private boolean[] keepItem; + + public BlockEntityCampfire(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + @Override + protected void initBlockEntity() { + this.inventory = new CampfireInventory(this); + this.burnTime = new int[4]; + this.recipes = new CampfireRecipe[4]; + this.keepItem = new boolean[4]; + + for (int i = 1; i <= burnTime.length; i++) { + burnTime[i -1] = namedTag.getInt("ItemTime" + i); + keepItem[i -1] = namedTag.getBoolean("KeepItem" + 1); + + if (this.namedTag.contains("Item" + i) && this.namedTag.get("Item" + i) instanceof CompoundTag) { + inventory.setItem(i - 1, NBTIO.getItemHelper(this.namedTag.getCompound("Item" + i))); + } + } + + super.initBlockEntity(); + this.scheduleUpdate(); + } + + @Override + public boolean onUpdate() { + if (this.closed) { + return false; + } + + boolean needsUpdate = false; + Block block = this.getBlock(); + boolean isLit = block instanceof BlockCampfire && !((BlockCampfire) block).isExtinguished(); + for (int slot = 0; slot < inventory.getSize(); slot++) { + Item item = inventory.getItem(slot); + if (item == null || item.getId() == BlockID.AIR || item.getCount() <= 0) { + burnTime[slot] = 0; + recipes[slot] = null; + } else if (!keepItem[slot]) { + CampfireRecipe recipe = recipes[slot]; + if (recipe == null) { + recipe = this.server.getCraftingManager().matchCampfireRecipe(item); + if (recipe == null) { + inventory.setItem(slot, Item.get(0)); + ThreadLocalRandom random = ThreadLocalRandom.current(); + this.level.dropItem(add(random.nextFloat(), 0.5, random.nextFloat()), item); + burnTime[slot] = 0; + recipes[slot] = null; + continue; + } else { + burnTime[slot] = 600; + recipes[slot] = recipe; + } + } + + int burnTimeLeft = burnTime[slot]; + if (burnTimeLeft <= 0) { + Item product = Item.get(recipe.getResult().getId(), recipe.getResult().getDamage(), item.getCount()); + CampfireSmeltEvent event = new CampfireSmeltEvent(this, item, product); + if (!event.isCancelled()) { + inventory.setItem(slot, Item.get(0)); + ThreadLocalRandom random = ThreadLocalRandom.current(); + this.level.dropItem(add(random.nextFloat(), 0.5, random.nextFloat()), event.getResult()); + burnTime[slot] = 0; + recipes[slot] = null; + } else if (event.getKeepItem()) { + keepItem[slot] = true; + burnTime[slot] = 0; + recipes[slot] = null; + } + } else if (isLit) { + burnTime[slot]--; + needsUpdate = true; + } else { + burnTime[slot] = 600; + } + } + } + + return needsUpdate; + } + + public boolean getKeepItem(int slot) { + if (slot < 0 || slot >= keepItem.length) { + return false; + } + return keepItem[slot]; + } + + public void setKeepItem(int slot, boolean keep) { + if (slot < 0 || slot >= keepItem.length) { + return; + } + this.keepItem[slot] = keep; + } + + @Override + public void saveNBT() { + super.saveNBT(); + + for (int i = 1; i <= burnTime.length; i++) { + Item item = inventory.getItem(i - 1); + if (item == null || item.getId() == BlockID.AIR || item.getCount() <= 0) { + namedTag.remove("Item"+i); + namedTag.putInt("ItemTime" + i, 0); + namedTag.remove("KeepItem"+i); + } else { + namedTag.putCompound("Item"+i, NBTIO.putItemHelper(item)); + namedTag.putInt("ItemTime" + i, burnTime[i - 1]); + namedTag.putBoolean("KeepItem"+i, keepItem[i-1]); + } + } + } + + public void setRecipe(int index, CampfireRecipe recipe) { + this.recipes[index] = recipe; + } + + @Override + public void close() { + if (!closed) { + for (Player player : new ArrayList<>(this.inventory.getViewers())) { + player.removeWindow(this.inventory); + } + super.close(); + } + } + + @Override + public void onBreak() { + for (Item content : inventory.getContents().values()) { + level.dropItem(this, content); + } + inventory.clearAll(); + } + + @Override + public String getName() { + return "Campfire"; + } + + @Override + public void spawnTo(Player player) { + if (!this.closed) { + player.dataPacket(this.createSpawnPacket()); + } + } + + @Override + public CompoundTag getSpawnCompound() { + CompoundTag c = new CompoundTag() + .putString("id", BlockEntity.CAMPFIRE) + .putInt("x", (int) this.x) + .putInt("y", (int) this.y) + .putInt("z", (int) this.z); + + for (int i = 1; i <= burnTime.length; i++) { + Item item = inventory.getItem(i - 1); + if (item == null || item.getId() == BlockID.AIR || item.getCount() <= 0) { + c.remove("Item"+i); + } else { + c.putCompound("Item"+i, NBTIO.putNetworkItemHelper(item)); + } + } + + return c; + } + + @Override + public boolean isBlockEntityValid() { + return level.getBlockIdAt(chunk, (int) x, (int) y, (int) z) == BlockID.CAMPFIRE_BLOCK; + } + + @Override + public int getSize() { + return 4; + } + + @Override + public Item getItem(int index) { + if (index < 0 || index >= getSize()) { + return new ItemBlock(Block.get(0), 0, 0); + } else { + CompoundTag data = this.namedTag.getCompound("Item" + (index + 1)); + return NBTIO.getItemHelper(data); + } + } + + @Override + public void setItem(int index, Item item) { + if (index < 0 || index >= getSize()) { + return; + } + + CompoundTag nbt = NBTIO.putItemHelper(item); + this.namedTag.putCompound("Item" + (index + 1), nbt); + } + + @Override + public CampfireInventory getInventory() { + return inventory; + } +} diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityCauldron.java b/src/main/java/cn/nukkit/blockentity/BlockEntityCauldron.java index e986c1578ac..0c3742b9e4c 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityCauldron.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityCauldron.java @@ -1,29 +1,46 @@ package cn.nukkit.blockentity; +import cn.nukkit.Player; import cn.nukkit.block.Block; +import cn.nukkit.level.GlobalBlockPalette; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; - +import cn.nukkit.network.protocol.UpdateBlockPacket; import cn.nukkit.utils.BlockColor; +import java.util.Collection; + /** - * author: CreeperFace + * @author CreeperFace * Nukkit Project */ public class BlockEntityCauldron extends BlockEntitySpawnable { + public static final int POTION_TYPE_EMPTY = 0xFFFF; + public static final int POTION_TYPE_NORMAL = 0; + public static final int POTION_TYPE_SPLASH = 1; + public static final int POTION_TYPE_LINGERING = 2; + public BlockEntityCauldron(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override protected void initBlockEntity() { + int potionId; if (!namedTag.contains("PotionId")) { namedTag.putShort("PotionId", 0xffff); } + potionId = namedTag.getShort("PotionId"); - if (!namedTag.contains("SplashPotion")) { - namedTag.putByte("SplashPotion", 0); + int potionType = (potionId & 0xFFFF) == 0xFFFF? POTION_TYPE_EMPTY : POTION_TYPE_NORMAL; + if (namedTag.getBoolean("SplashPotion")) { + potionType = POTION_TYPE_SPLASH; + namedTag.remove("SplashPotion"); + } + + if (!namedTag.contains("PotionType")) { + namedTag.putShort("PotionType", potionType); } super.initBlockEntity(); @@ -35,6 +52,7 @@ public int getPotionId() { public void setPotionId(int potionId) { namedTag.putShort("PotionId", potionId); + setDirty(); this.spawnToAll(); } @@ -42,12 +60,22 @@ public boolean hasPotion() { return getPotionId() != 0xffff; } + public void setPotionType(int potionType) { + this.namedTag.putShort("PotionType", potionType & 0xFFFF); + setDirty(); + } + + public int getPotionType() { + return this.namedTag.getShort("PotionType") & 0xFFFF; + } + public boolean isSplashPotion() { - return namedTag.getByte("SplashPotion") > 0; + return namedTag.getShort("PotionType") == POTION_TYPE_SPLASH; } public void setSplashPotion(boolean value) { - namedTag.putByte("SplashPotion", value ? 1 : 0); + namedTag.putShort("PotionType", value ? 1 : 0); + setDirty(); } public BlockColor getCustomColor() { @@ -75,28 +103,53 @@ public void setCustomColor(BlockColor color) { public void setCustomColor(int r, int g, int b) { int color = (r << 16 | g << 8 | b) & 0xffffff; - namedTag.putInt("CustomColor", color); - spawnToAll(); + if (color != namedTag.getInt("CustomColor")) { + namedTag.putInt("CustomColor", color); + Block block = getBlock(); + Collection pl = level.getChunkPlayers(getChunkX(), getChunkZ()).values(); + for (Player p : pl) { + UpdateBlockPacket air = new UpdateBlockPacket(); + air.blockRuntimeId = GlobalBlockPalette.getOrCreateRuntimeId(0); + air.flags = UpdateBlockPacket.FLAG_ALL_PRIORITY; + air.x = (int) x; + air.y = (int) y; + air.z = (int) z; + UpdateBlockPacket self = (UpdateBlockPacket) air.clone(); + self.blockRuntimeId = GlobalBlockPalette.getOrCreateRuntimeId(block.getId(), block.getDamage()); + p.dataPacket(air); + p.dataPacket(self); + } + + setDirty(); + + spawnToAll(); + } } public void clearCustomColor() { namedTag.remove("CustomColor"); + setDirty(); spawnToAll(); } @Override public boolean isBlockEntityValid() { - return getBlock().getId() == Block.CAULDRON_BLOCK; + int id = level.getBlockIdAt(chunk, (int) x, (int) y, (int) z); + return id == Block.CAULDRON_BLOCK || id == Block.LAVA_CAULDRON; } @Override public CompoundTag getSpawnCompound() { - return new CompoundTag() + CompoundTag compoundTag = new CompoundTag() .putString("id", BlockEntity.CAULDRON) .putInt("x", (int) this.x) .putInt("y", (int) this.y) .putInt("z", (int) this.z) .putShort("PotionId", namedTag.getShort("PotionId")) - .putByte("SplashPotion", namedTag.getByte("SplashPotion")); + .putByte("PotionType", namedTag.getShort("PotionType")); + if (namedTag.contains("CustomColor")) { + compoundTag.putInt("CustomColor", namedTag.getInt("CustomColor")); + } + return compoundTag; } } diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityChest.java b/src/main/java/cn/nukkit/blockentity/BlockEntityChest.java index a7a1d58495e..b793c2a19ca 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityChest.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityChest.java @@ -15,63 +15,63 @@ import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.ListTag; -import java.util.HashSet; +import java.util.ArrayList; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockEntityChest extends BlockEntitySpawnable implements InventoryHolder, BlockEntityContainer, BlockEntityNameable { protected ChestInventory inventory; - protected DoubleChestInventory doubleInventory = null; + protected DoubleChestInventory doubleInventory; public BlockEntityChest(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } - @Override - protected void initBlockEntity() { - this.inventory = new ChestInventory(this); - + private void initInventory() { if (!this.namedTag.contains("Items") || !(this.namedTag.get("Items") instanceof ListTag)) { this.namedTag.putList(new ListTag("Items")); } + ListTag list = (ListTag) this.namedTag.getList("Items"); - /* for (int i = 0; i < this.getSize(); i++) { - this.inventory.setItem(i, this.getItem(i)); - } */ + this.inventory = new ChestInventory(this); - ListTag list = (ListTag) this.namedTag.getList("Items"); for (CompoundTag compound : list.getAll()) { Item item = NBTIO.getItemHelper(compound); - this.inventory.slots.put(compound.getByte("Slot"), item); + if (item.getId() != 0 && item.getCount() > 0) { + this.inventory.slots.put(compound.getByte("Slot"), item); + } } - - super.initBlockEntity(); } @Override public void close() { - if (!closed) { + if (!this.closed && this.inventory != null) { + if (this.doubleInventory != null) { + for (Player player : new ArrayList<>(this.doubleInventory.getViewers())) { + player.removeWindow(this.doubleInventory); + } - for (Player player : new HashSet<>(this.getInventory().getViewers())) { - player.removeWindow(this.getInventory()); + this.doubleInventory = null; } - for (Player player : new HashSet<>(this.getInventory().getViewers())) { - player.removeWindow(this.getRealInventory()); + for (Player player : new ArrayList<>(this.inventory.getViewers())) { + player.removeWindow(this.inventory); } - super.close(); } + + super.close(); } @Override public void onBreak() { - if (this.isPaired()) { - unpair(); + if (this.inventory == null) { + this.initInventory(); } + unpair(); for (Item content : inventory.getContents().values()) { level.dropItem(this, content); } @@ -80,16 +80,20 @@ public void onBreak() { @Override public void saveNBT() { - this.namedTag.putList(new ListTag("Items")); - for (int index = 0; index < this.getSize(); index++) { - this.setItem(index, this.inventory.getItem(index)); + super.saveNBT(); + + if (this.inventory != null) { + this.namedTag.putList(new ListTag("Items")); + for (int index = 0; index < this.getSize(); index++) { + this.setItem(index, this.inventory.getItem(index)); + } } } @Override public boolean isBlockEntityValid() { - int blockID = this.getBlock().getId(); - return blockID == Block.CHEST || blockID == Block.TRAPPED_CHEST; + int id = level.getBlockIdAt(chunk, (int) x, (int) y, (int) z); + return id == Block.CHEST || id == Block.TRAPPED_CHEST; } @Override @@ -141,6 +145,9 @@ public void setItem(int index, Item item) { @Override public BaseInventory getInventory() { + if (this.inventory == null) { + this.initInventory(); + } if (this.doubleInventory == null && this.isPaired()) { this.checkPairing(); } @@ -149,6 +156,9 @@ public BaseInventory getInventory() { } public ChestInventory getRealInventory() { + if (this.inventory == null) { + this.initInventory(); + } return inventory; } @@ -191,7 +201,7 @@ public boolean hasName() { @Override public void setName(String name) { - if (name == null || name.equals("")) { + if (name == null || name.isEmpty()) { this.namedTag.remove("CustomName"); return; } @@ -205,7 +215,7 @@ public boolean isPaired() { public BlockEntityChest getPair() { if (this.isPaired()) { - BlockEntity blockEntity = this.getLevel().getBlockEntityIfLoaded(new Vector3(this.namedTag.getInt("pairx"), this.y, this.namedTag.getInt("pairz"))); + BlockEntity blockEntity = this.getLevel().getBlockEntityIfLoaded(this.chunk, new Vector3(this.namedTag.getInt("pairx"), this.y, this.namedTag.getInt("pairz"))); if (blockEntity instanceof BlockEntityChest) { return (BlockEntityChest) blockEntity; } @@ -285,5 +295,4 @@ public CompoundTag getSpawnCompound() { return c; } - } diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityComparator.java b/src/main/java/cn/nukkit/blockentity/BlockEntityComparator.java index 5409ec5245c..ed2fc7c796d 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityComparator.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityComparator.java @@ -1,6 +1,6 @@ package cn.nukkit.blockentity; -import cn.nukkit.block.BlockRedstoneComparator; +import cn.nukkit.block.Block; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; @@ -23,7 +23,8 @@ public BlockEntityComparator(FullChunk chunk, CompoundTag nbt) { @Override public boolean isBlockEntityValid() { - return this.getLevelBlock() instanceof BlockRedstoneComparator; + int blockID = level.getBlockIdAt(chunk, (int) x, (int) y, (int) z); + return blockID == Block.POWERED_COMPARATOR || blockID == Block.UNPOWERED_COMPARATOR; } public int getOutputSignal() { @@ -31,7 +32,10 @@ public int getOutputSignal() { } public void setOutputSignal(int outputSignal) { - this.outputSignal = outputSignal; + if (this.outputSignal != outputSignal) { + this.outputSignal = outputSignal; + setDirty(); + } } @Override diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityContainer.java b/src/main/java/cn/nukkit/blockentity/BlockEntityContainer.java index 79e21d0e4f9..2ba09419372 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityContainer.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityContainer.java @@ -5,15 +5,14 @@ /** * 表达一个容器的接口。
* An interface describes a container. - * - *

{@code BlockEntityContainer}容器必须包含物品的{@code Item}对象。
- * A {@code BlockEntityContainer} must contain items as {@code Item} objects.

+ *

+ * {@code BlockEntityContainer}容器必须包含物品的{@code Item}对象。
+ * A {@code BlockEntityContainer} must contain items as {@code Item} objects. * * @author MagicDroidX(code) @ Nukkit Project * @author 粉鞋大妈(javadoc) @ Nukkit Project * @see BlockEntityChest * @see BlockEntityFurnace - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public interface BlockEntityContainer { @@ -23,20 +22,18 @@ public interface BlockEntityContainer { * * @param index 这个物品的索引序号。
The index number of this item. * @return 这个物品的 {@code Item}对象。
An {@code Item} object for this item. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ Item getItem(int index); /** * 把一个物品存储进容器。
* Sets or stores this item into this container. - * - *

注意:如果这个容器相应的索引序号已经有了物品,那么新存储的物品将会替换原有的物品。
- * Notice: If there is already an item for this index number, the new item being stored will REPLACE the old one.

+ *

+ * 注意:如果这个容器相应的索引序号已经有了物品,那么新存储的物品将会替换原有的物品。
+ * Notice: If there is already an item for this index number, the new item being stored will REPLACE the old one. * * @param index 这个物品的索引序号。
The index number of this item. * @param item 描述这个物品的 {@code Item}对象。
The {@code Item} object that describes this item. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ void setItem(int index, Item item); @@ -45,7 +42,6 @@ public interface BlockEntityContainer { * Returns the max number of items that this container can contain. * * @return 最多能包含的物品数量。
The max number. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ int getSize(); } diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityDispenser.java b/src/main/java/cn/nukkit/blockentity/BlockEntityDispenser.java new file mode 100644 index 00000000000..7d571b38b8f --- /dev/null +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityDispenser.java @@ -0,0 +1,166 @@ +package cn.nukkit.blockentity; + +import cn.nukkit.Player; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; +import cn.nukkit.inventory.DispenserInventory; +import cn.nukkit.inventory.InventoryHolder; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.NBTIO; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.ListTag; + +import java.util.ArrayList; + +public class BlockEntityDispenser extends BlockEntitySpawnable implements InventoryHolder, BlockEntityContainer, BlockEntityNameable { + + protected DispenserInventory inventory; + + public BlockEntityDispenser(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + private void initInventory() { + if (!this.namedTag.contains("Items") || !(this.namedTag.get("Items") instanceof ListTag)) { + this.namedTag.putList(new ListTag("Items")); + } + ListTag list = (ListTag) this.namedTag.getList("Items"); + + this.inventory = new DispenserInventory(this); + + for (CompoundTag compound : list.getAll()) { + Item item = NBTIO.getItemHelper(compound); + if (item.getId() != 0 && item.getCount() > 0) { + this.inventory.slots.put(compound.getByte("Slot"), item); + } + } + } + + @Override + public boolean isBlockEntityValid() { + return level.getBlockIdAt(chunk, (int) x, (int) y, (int) z) == BlockID.DISPENSER; + } + + @Override + public String getName() { + return this.hasName() ? this.namedTag.getString("CustomName") : "Dispenser"; + } + + @Override + public boolean hasName() { + return this.namedTag.contains("CustomName"); + } + + @Override + public void setName(String name) { + if (name == null || name.isEmpty()) { + this.namedTag.remove("CustomName"); + return; + } + + this.namedTag.putString("CustomName", name); + } + + @Override + public int getSize() { + return 9; + } + + protected int getSlotIndex(int index) { + ListTag list = this.namedTag.getList("Items", CompoundTag.class); + for (int i = 0; i < list.size(); i++) { + if (list.get(i).getByte("Slot") == index) { + return i; + } + } + + return -1; + } + + @Override + public Item getItem(int index) { + int i = this.getSlotIndex(index); + if (i < 0) { + return new ItemBlock(Block.get(BlockID.AIR), 0, 0); + } else { + CompoundTag data = (CompoundTag) this.namedTag.getList("Items").get(i); + return NBTIO.getItemHelper(data); + } + } + + @Override + public void setItem(int index, Item item) { + int i = this.getSlotIndex(index); + + CompoundTag d = NBTIO.putItemHelper(item, index); + + if (item.getId() == Item.AIR || item.getCount() <= 0) { + if (i >= 0) { + this.namedTag.getList("Items").getAll().remove(i); + } + } else if (i < 0) { + (this.namedTag.getList("Items", CompoundTag.class)).add(d); + } else { + (this.namedTag.getList("Items", CompoundTag.class)).add(i, d); + } + } + + @Override + public void saveNBT() { + super.saveNBT(); + + if (this.inventory != null) { + this.namedTag.putList(new ListTag("Items")); + for (int index = 0; index < this.getSize(); index++) { + this.setItem(index, this.inventory.getItem(index)); + } + } + } + + @Override + public DispenserInventory getInventory() { + if (this.inventory == null) { + this.initInventory(); + } + return this.inventory; + } + + @Override + public CompoundTag getSpawnCompound() { + CompoundTag c = new CompoundTag() + .putString("id", BlockEntity.DISPENSER) + .putInt("x", (int) this.x) + .putInt("y", (int) this.y) + .putInt("z", (int) this.z); + + if (this.hasName()) { + c.put("CustomName", this.namedTag.get("CustomName")); + } + + return c; + } + + @Override + public void close() { + if (!this.closed && this.inventory != null) { + for (Player player : new ArrayList<>(this.inventory.getViewers())) { + player.removeWindow(this.inventory); + } + } + + super.close(); + } + + @Override + public void onBreak() { + if (this.inventory == null) { + this.initInventory(); + } + for (Item content : inventory.getContents().values()) { + level.dropItem(this, content); + } + inventory.clearAll(); + } +} diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityDropper.java b/src/main/java/cn/nukkit/blockentity/BlockEntityDropper.java new file mode 100644 index 00000000000..1dd8d944aa5 --- /dev/null +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityDropper.java @@ -0,0 +1,166 @@ +package cn.nukkit.blockentity; + +import cn.nukkit.Player; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; +import cn.nukkit.inventory.DropperInventory; +import cn.nukkit.inventory.InventoryHolder; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.NBTIO; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.ListTag; + +import java.util.ArrayList; + +public class BlockEntityDropper extends BlockEntitySpawnable implements InventoryHolder, BlockEntityContainer, BlockEntityNameable { + + protected DropperInventory inventory; + + public BlockEntityDropper(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + private void initInventory() { + if (!this.namedTag.contains("Items") || !(this.namedTag.get("Items") instanceof ListTag)) { + this.namedTag.putList(new ListTag("Items")); + } + ListTag list = (ListTag) this.namedTag.getList("Items"); + + this.inventory = new DropperInventory(this); + + for (CompoundTag compound : list.getAll()) { + Item item = NBTIO.getItemHelper(compound); + if (item.getId() != 0 && item.getCount() > 0) { + this.inventory.slots.put(compound.getByte("Slot"), item); + } + } + } + + @Override + public boolean isBlockEntityValid() { + return level.getBlockIdAt(chunk, (int) x, (int) y, (int) z) == Block.DROPPER; + } + + @Override + public String getName() { + return this.hasName() ? this.namedTag.getString("CustomName") : "Dropper"; + } + + @Override + public boolean hasName() { + return this.namedTag.contains("CustomName"); + } + + @Override + public void setName(String name) { + if (name == null || name.isEmpty()) { + this.namedTag.remove("CustomName"); + return; + } + + this.namedTag.putString("CustomName", name); + } + + @Override + public int getSize() { + return 9; + } + + protected int getSlotIndex(int index) { + ListTag list = this.namedTag.getList("Items", CompoundTag.class); + for (int i = 0; i < list.size(); i++) { + if (list.get(i).getByte("Slot") == index) { + return i; + } + } + + return -1; + } + + @Override + public Item getItem(int index) { + int i = this.getSlotIndex(index); + if (i < 0) { + return new ItemBlock(Block.get(BlockID.AIR), 0, 0); + } else { + CompoundTag data = (CompoundTag) this.namedTag.getList("Items").get(i); + return NBTIO.getItemHelper(data); + } + } + + @Override + public void setItem(int index, Item item) { + int i = this.getSlotIndex(index); + + CompoundTag d = NBTIO.putItemHelper(item, index); + + if (item.getId() == Item.AIR || item.getCount() <= 0) { + if (i >= 0) { + this.namedTag.getList("Items").getAll().remove(i); + } + } else if (i < 0) { + (this.namedTag.getList("Items", CompoundTag.class)).add(d); + } else { + (this.namedTag.getList("Items", CompoundTag.class)).add(i, d); + } + } + + @Override + public void saveNBT() { + super.saveNBT(); + + if (this.inventory != null) { + this.namedTag.putList(new ListTag("Items")); + for (int index = 0; index < this.getSize(); index++) { + this.setItem(index, this.inventory.getItem(index)); + } + } + } + + @Override + public DropperInventory getInventory() { + if (this.inventory == null) { + this.initInventory(); + } + return this.inventory; + } + + @Override + public CompoundTag getSpawnCompound() { + CompoundTag c = new CompoundTag() + .putString("id", BlockEntity.DROPPER) + .putInt("x", (int) this.x) + .putInt("y", (int) this.y) + .putInt("z", (int) this.z); + + if (this.hasName()) { + c.put("CustomName", this.namedTag.get("CustomName")); + } + + return c; + } + + @Override + public void close() { + if (!this.closed && this.inventory != null) { + for (Player player : new ArrayList<>(this.inventory.getViewers())) { + player.removeWindow(this.inventory); + } + } + + super.close(); + } + + @Override + public void onBreak() { + if (this.inventory == null) { + this.initInventory(); + } + for (Item content : inventory.getContents().values()) { + level.dropItem(this, content); + } + inventory.clearAll(); + } +} diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityEnchantTable.java b/src/main/java/cn/nukkit/blockentity/BlockEntityEnchantTable.java index 34cb11043e5..f6324121805 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityEnchantTable.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityEnchantTable.java @@ -5,7 +5,7 @@ import cn.nukkit.nbt.tag.CompoundTag; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockEntityEnchantTable extends BlockEntitySpawnable implements BlockEntityNameable { @@ -16,7 +16,7 @@ public BlockEntityEnchantTable(FullChunk chunk, CompoundTag nbt) { @Override public boolean isBlockEntityValid() { - return getBlock().getId() == Block.ENCHANT_TABLE; + return level.getBlockIdAt(chunk, (int) x, (int) y, (int) z) == Block.ENCHANT_TABLE; } @Override @@ -31,7 +31,9 @@ public boolean hasName() { @Override public void setName(String name) { - if (name == null || name.equals("")) { + setDirty(); + + if (name == null || name.isEmpty()) { this.namedTag.remove("CustomName"); return; } @@ -53,5 +55,4 @@ public CompoundTag getSpawnCompound() { return c; } - } diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityEnderChest.java b/src/main/java/cn/nukkit/blockentity/BlockEntityEnderChest.java index ef834c937cd..a515f6bbaba 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityEnderChest.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityEnderChest.java @@ -12,7 +12,7 @@ public BlockEntityEnderChest(FullChunk chunk, CompoundTag nbt) { @Override public boolean isBlockEntityValid() { - return this.getBlock().getId() == Block.ENDER_CHEST; + return level.getBlockIdAt(chunk, (int) x, (int) y, (int) z) == Block.ENDER_CHEST; } @Override diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityFlowerPot.java b/src/main/java/cn/nukkit/blockentity/BlockEntityFlowerPot.java index b83e63e07fb..1ee488b0f90 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityFlowerPot.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityFlowerPot.java @@ -1,8 +1,10 @@ package cn.nukkit.blockentity; import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; /** * Created by Snake1999 on 2016/2/4. @@ -33,8 +35,16 @@ protected void initBlockEntity() { @Override public boolean isBlockEntityValid() { - int blockID = getBlock().getId(); - return blockID == Block.FLOWER_POT_BLOCK; + return level.getBlockIdAt(chunk, (int) x, (int) y, (int) z) == Block.FLOWER_POT_BLOCK; + } + + private static final Int2ObjectOpenHashMap HAS_STRING_ITEM_OVERRIDE = new Int2ObjectOpenHashMap<>(); + + static { + HAS_STRING_ITEM_OVERRIDE.put(BlockID.CRIMSON_ROOTS, "minecraft:crimson_roots"); + HAS_STRING_ITEM_OVERRIDE.put(BlockID.WARPED_ROOTS, "minecraft:warped_roots"); + HAS_STRING_ITEM_OVERRIDE.put(BlockID.CRIMSON_FUNGUS, "minecraft:crimson_fungus"); + HAS_STRING_ITEM_OVERRIDE.put(BlockID.WARPED_FUNGUS, "minecraft:warped_fungus"); } @Override @@ -47,10 +57,14 @@ public CompoundTag getSpawnCompound() { int item = namedTag.getShort("item"); if (item != Block.AIR) { - tag.putShort("item", this.namedTag.getShort("item")) - .putInt("mData", this.namedTag.getInt("data")); + // Fix latest game versions not displaying legacy items correctly + if (HAS_STRING_ITEM_OVERRIDE.containsKey(item)) { + tag.putCompound("PlantBlock", new CompoundTag().putString("name", HAS_STRING_ITEM_OVERRIDE.get(item))); + } else { + tag.putShort("item", this.namedTag.getShort("item")) + .putInt("mData", this.namedTag.getInt("data")); + } } return tag; } - -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityFurnace.java b/src/main/java/cn/nukkit/blockentity/BlockEntityFurnace.java index 6bf2223a965..da4685be253 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityFurnace.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityFurnace.java @@ -1,22 +1,24 @@ package cn.nukkit.blockentity; import cn.nukkit.Player; -import cn.nukkit.block.*; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; import cn.nukkit.event.inventory.FurnaceBurnEvent; import cn.nukkit.event.inventory.FurnaceSmeltEvent; -import cn.nukkit.inventory.FurnaceInventory; -import cn.nukkit.inventory.FurnaceRecipe; -import cn.nukkit.inventory.InventoryHolder; +import cn.nukkit.inventory.*; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.level.format.FullChunk; +import cn.nukkit.math.NukkitMath; import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.ListTag; import cn.nukkit.network.protocol.ContainerSetDataPacket; import cn.nukkit.network.protocol.LevelSoundEventPacket; -import java.util.HashSet; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; import java.util.concurrent.ThreadLocalRandom; /** @@ -30,8 +32,45 @@ public class BlockEntityFurnace extends BlockEntitySpawnable implements Inventor protected int burnDuration; protected int cookTime; protected int maxTime; - - private int crackledTime; + protected int crackledTime; + protected double experience; + + public static final Map FURNACE_XP = new HashMap<>(); + + static { + FURNACE_XP.put(Item.BAKED_POTATO, 0.35d); + FURNACE_XP.put(Item.DRIED_KELP, 0.1d); + FURNACE_XP.put(Item.STEAK, 0.35d); + FURNACE_XP.put(Item.COOKED_PORKCHOP, 0.35d); + FURNACE_XP.put(Item.COOKED_MUTTON, 0.35d); + FURNACE_XP.put(Item.COOKED_CHICKEN, 0.35d); + FURNACE_XP.put(Item.COOKED_RABBIT, 0.35d); + FURNACE_XP.put(Item.COOKED_FISH, 0.35d); + FURNACE_XP.put(Item.COOKED_SALMON, 0.35d); + + FURNACE_XP.put(Item.REDSTONE_DUST, 0.3d); + FURNACE_XP.put(Item.COAL, 0.1d); + FURNACE_XP.put(Item.EMERALD, 1d); + FURNACE_XP.put(Item.DYE, 0.2d); // Lapis & Cactus + FURNACE_XP.put(Item.DIAMOND, 1d); + FURNACE_XP.put(Item.NETHER_QUARTZ, 0.2d); + FURNACE_XP.put(Item.IRON_INGOT, 0.7d); + FURNACE_XP.put(Item.COPPER_INGOT, 0.7d); + FURNACE_XP.put(Item.GOLD_INGOT, 1d); + FURNACE_XP.put(Item.NETHERITE_SCRAP, 1d); + FURNACE_XP.put(Item.IRON_NUGGET, 0.1d); + FURNACE_XP.put(Item.GOLD_NUGGET, 0.1d); + + FURNACE_XP.put(Item.STONE, 0.1d); + FURNACE_XP.put(Item.TERRACOTTA, 0.35d); + FURNACE_XP.put(Item.GLASS, 0.1d); + FURNACE_XP.put(Item.SPONGE, 0.15d); + FURNACE_XP.put(Item.POPPED_CHORUS_FRUIT, 0.1d); + FURNACE_XP.put(Item.BRICK, 0.3d); + FURNACE_XP.put(Item.NETHER_BRICK, 0.1d); + + FURNACE_XP.put(255 - Item.SMOOTH_BASALT, 0.1d); + } public BlockEntityFurnace(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); @@ -39,14 +78,24 @@ public BlockEntityFurnace(FullChunk chunk, CompoundTag nbt) { @Override protected void initBlockEntity() { - this.inventory = new FurnaceInventory(this); + if (this instanceof BlockEntityBlastFurnace) { + this.inventory = new BlastFurnaceInventory((BlockEntityBlastFurnace) this); + } else if (this instanceof BlockEntitySmoker) { + this.inventory = new SmokerInventory((BlockEntitySmoker) this); + } else { + this.inventory = new FurnaceInventory(this); + } if (!this.namedTag.contains("Items") || !(this.namedTag.get("Items") instanceof ListTag)) { this.namedTag.putList(new ListTag("Items")); } - for (int i = 0; i < this.getSize(); i++) { - this.inventory.setItem(i, this.getItem(i)); + ListTag list = (ListTag) this.namedTag.getList("Items"); + for (CompoundTag compound : list.getAll()) { + Item item = NBTIO.getItemHelper(compound); + if (item.getId() != 0 && item.getCount() > 0) { + this.inventory.slots.put(compound.getByte("Slot"), item); + } } if (!this.namedTag.contains("BurnTime") || this.namedTag.getShort("BurnTime") < 0) { @@ -79,6 +128,12 @@ protected void initBlockEntity() { this.namedTag.remove("BurnTicks"); } + if (this.namedTag.contains("Experience") && this.namedTag.getDouble("Experience") > 0) { + this.experience = this.namedTag.getDouble("Experience"); + } else { + this.experience = 0; + } + if (burnTime > 0) { this.scheduleUpdate(); } @@ -98,7 +153,7 @@ public boolean hasName() { @Override public void setName(String name) { - if (name == null || name.equals("")) { + if (name == null || name.isEmpty()) { this.namedTag.remove("CustomName"); return; } @@ -109,9 +164,10 @@ public void setName(String name) { @Override public void close() { if (!closed) { - for (Player player : new HashSet<>(this.getInventory().getViewers())) { - player.removeWindow(this.getInventory()); + for (Player player : new ArrayList<>(this.inventory.getViewers())) { + player.removeWindow(this.inventory); } + super.close(); } } @@ -121,11 +177,12 @@ public void onBreak() { for (Item content : inventory.getContents().values()) { level.dropItem(this, content); } - this.inventory.clearAll(); + inventory.clearAll(); } @Override public void saveNBT() { + super.saveNBT(); this.namedTag.putList(new ListTag("Items")); for (int index = 0; index < this.getSize(); index++) { this.setItem(index, this.inventory.getItem(index)); @@ -135,11 +192,12 @@ public void saveNBT() { this.namedTag.putShort("BurnTime", burnTime); this.namedTag.putShort("BurnDuration", burnDuration); this.namedTag.putShort("MaxTime", maxTime); + this.namedTag.putDouble("Experience", experience); } @Override public boolean isBlockEntityValid() { - int blockID = getBlock().getId(); + int blockID = level.getBlockIdAt(chunk, (int) x, (int) y, (int) z); return blockID == Block.FURNACE || blockID == Block.BURNING_FURNACE; } @@ -194,7 +252,9 @@ public FurnaceInventory getInventory() { protected void checkFuel(Item fuel) { FurnaceBurnEvent ev = new FurnaceBurnEvent(this, fuel, fuel.getFuelTime() == null ? 0 : fuel.getFuelTime()); + this.server.getPluginManager().callEvent(ev); + if (ev.isCancelled()) { return; } @@ -202,8 +262,14 @@ protected void checkFuel(Item fuel) { maxTime = ev.getBurnTime(); burnTime = ev.getBurnTime(); burnDuration = 0; - if (this.getBlock().getId() == Item.FURNACE) { - this.getLevel().setBlock(this, Block.get(BlockID.BURNING_FURNACE, this.getBlock().getDamage()), true); + + Block block = this.level.getBlock(this.chunk, (int) x, (int) y, (int) z, true); + if (block.getId() == Item.FURNACE) { + this.getLevel().setBlock(this, Block.get(BlockID.BURNING_FURNACE, block.getDamage()), true); + } else if (block.getId() == Item.SMOKER) { + this.getLevel().setBlock(this, Block.get(BlockID.LIT_SMOKER, block.getDamage()), true); + } else if (block.getId() == Item.BLAST_FURNACE) { + this.getLevel().setBlock(this, Block.get(BlockID.LIT_BLAST_FURNACE, block.getDamage()), true); } if (burnTime > 0 && ev.isBurning()) { @@ -226,17 +292,15 @@ public boolean onUpdate() { return false; } - this.timing.startTiming(); - boolean ret = false; - Item fuel = this.inventory.getFuel(); Item raw = this.inventory.getSmelting(); Item product = this.inventory.getResult(); FurnaceRecipe smelt = this.server.getCraftingManager().matchFurnaceRecipe(raw); - boolean canSmelt = (smelt != null && raw.getCount() > 0 && ((smelt.getResult().equals(product, true) && product.getCount() < product.getMaxStackSize()) || product.getId() == Item.AIR)); + boolean canSmelt = (smelt != null && raw.getCount() > 0 && ((smelt.getResult().equals(product) && product.getCount() < product.getMaxStackSize()) || product.getId() == Item.AIR)); - if (burnTime <= 0 && canSmelt && fuel.getFuelTime() != null && fuel.getCount() > 0) { - this.checkFuel(fuel); + Item fuel; + if (burnTime <= 0 && canSmelt && (fuel = this.inventory.getItemFast(1)).getFuelTime() != null && fuel.getCount() > 0) { + this.checkFuel(fuel.clone()); } if (burnTime > 0) { @@ -244,19 +308,20 @@ public boolean onUpdate() { burnDuration = (int) Math.ceil((float) burnTime / maxTime * 200); if (this.crackledTime-- <= 0) { - this.crackledTime = ThreadLocalRandom.current().nextInt(20, 100); + this.crackledTime = ThreadLocalRandom.current().nextInt(30, 110); this.getLevel().addLevelSoundEvent(this.add(0.5, 0.5, 0.5), LevelSoundEventPacket.SOUND_BLOCK_FURNACE_LIT); } if (smelt != null && canSmelt) { cookTime++; if (cookTime >= 200) { - product = Item.get(smelt.getResult().getId(), smelt.getResult().getDamage(), product.getCount() + 1); + product = Item.get(smelt.getResult().getId(), smelt.getResult().getDamage(), product.isNull() ? 1 : product.getCount() + 1); FurnaceSmeltEvent ev = new FurnaceSmeltEvent(this, raw, product); this.server.getPluginManager().callEvent(ev); if (!ev.isCancelled()) { this.inventory.setResult(ev.getResult()); + this.experience += FURNACE_XP.getOrDefault(ev.getResult().getId(), 0d); raw.setCount(raw.getCount() - 1); if (raw.getCount() == 0) { raw = new ItemBlock(Block.get(BlockID.AIR), 0, 0); @@ -275,22 +340,28 @@ public boolean onUpdate() { } ret = true; } else { - if (this.getBlock().getId() == Item.BURNING_FURNACE) { - this.getLevel().setBlock(this, Block.get(BlockID.FURNACE, this.getBlock().getDamage()), true); + Block block = this.level.getBlock(this.chunk, (int) x, (int) y, (int) z, true); + if (block.getId() == Item.BURNING_FURNACE) { + this.getLevel().setBlock(this, Block.get(BlockID.FURNACE, block.getDamage()), true); } burnTime = 0; cookTime = 0; burnDuration = 0; - this.crackledTime = 0; + crackledTime = 0; } - for (Player player : this.getInventory().getViewers()) { - int windowId = player.getWindowId(this.getInventory()); + sendPacket(); + + return ret; + } + + protected void sendPacket() { + for (Player player : this.inventory.getViewers()) { + int windowId = player.getWindowId(this.inventory); if (windowId > 0) { ContainerSetDataPacket pk = new ContainerSetDataPacket(); pk.windowId = windowId; pk.property = ContainerSetDataPacket.PROPERTY_FURNACE_TICK_COUNT; - pk.value = cookTime; player.dataPacket(pk); @@ -301,12 +372,6 @@ public boolean onUpdate() { player.dataPacket(pk); } } - - this.lastUpdate = System.currentTimeMillis(); - - this.timing.stopTiming(); - - return ret; } @Override @@ -358,4 +423,20 @@ public int getMaxTime() { public void setMaxTime(int maxTime) { this.maxTime = maxTime; } + + public double getExperience() { + return this.experience; + } + + public void setExperience(double experience) { + this.experience = experience; + } + + public void releaseExperience() { + int experience = NukkitMath.floorDouble(this.experience); + if (experience >= 1) { + this.experience = 0; + this.level.dropExpOrb(this, experience); + } + } } diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityHopper.java b/src/main/java/cn/nukkit/blockentity/BlockEntityHopper.java index db34f1f3bf9..245f0267a7e 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityHopper.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityHopper.java @@ -2,6 +2,7 @@ import cn.nukkit.Player; import cn.nukkit.block.Block; +import cn.nukkit.block.BlockComposter; import cn.nukkit.block.BlockID; import cn.nukkit.entity.Entity; import cn.nukkit.entity.item.EntityItem; @@ -16,8 +17,9 @@ import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.ListTag; +import lombok.Setter; -import java.util.HashSet; +import java.util.ArrayList; /** * Created by CreeperFace on 8.5.2017. @@ -30,6 +32,11 @@ public class BlockEntityHopper extends BlockEntitySpawnable implements Inventory private AxisAlignedBB pickupArea; + @Setter + private InventoryHolder minecartPickupInventory; + @Setter + private InventoryHolder minecartPushInventory; + public BlockEntityHopper(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @@ -48,8 +55,12 @@ protected void initBlockEntity() { this.namedTag.putList(new ListTag("Items")); } - for (int i = 0; i < this.getSize(); i++) { - this.inventory.setItem(i, this.getItem(i)); + ListTag list = (ListTag) this.namedTag.getList("Items"); + for (CompoundTag compound : list.getAll()) { + Item item = NBTIO.getItemHelper(compound); + if (item.getId() != 0 && item.getCount() > 0) { + this.inventory.slots.put(compound.getByte("Slot"), item); + } } this.pickupArea = new SimpleAxisAlignedBB(this.x, this.y, this.z, this.x + 1, this.y + 2, this.z + 1); @@ -61,7 +72,7 @@ protected void initBlockEntity() { @Override public boolean isBlockEntityValid() { - return this.level.getBlockIdAt(this.getFloorX(), this.getFloorY(), this.getFloorZ()) == Block.HOPPER_BLOCK; + return level.getBlockIdAt(chunk, (int) x, (int) y, (int) z) == Block.HOPPER_BLOCK; } @Override @@ -76,7 +87,7 @@ public boolean hasName() { @Override public void setName(String name) { - if (name == null || name.equals("")) { + if (name == null || name.isEmpty()) { this.namedTag.remove("CustomName"); return; } @@ -138,6 +149,7 @@ public void setItem(int index, Item item) { @Override public void saveNBT() { + super.saveNBT(); this.namedTag.putList(new ListTag("Items")); for (int index = 0; index < this.getSize(); index++) { this.setItem(index, this.inventory.getItem(index)); @@ -158,21 +170,23 @@ public boolean onUpdate() { } this.transferCooldown--; - - if (this.level.isBlockPowered(getBlock())) { - return true; - } if (!this.isOnTransferCooldown()) { - BlockEntity blockEntity = this.level.getBlockEntity(this.up()); + if (this.level.isBlockPowered(this.chunk, this)) { + return true; + } + + // Note: Initial inventory full/empty checks are moved here from pull/push methods - boolean changed = pushItems(); + boolean changed = !this.inventory.slots.isEmpty() && (pushItems() || pushItemsToMinecart()); - if (!changed) { - if (!(blockEntity instanceof BlockEntityContainer)) { - changed = pickupItems(); + if (!changed && !this.inventory.isFull()) { + BlockEntity blockEntity = this.level.getBlockEntity(this.chunk, this.up()); + Block block = null; + if (blockEntity instanceof BlockEntityContainer || (block = this.level.getBlock(this.chunk, this.getFloorX(), this.getFloorY() + 1, this.getFloorZ(), false)) instanceof BlockComposter) { + changed = pullItems(blockEntity, block); } else { - changed = pullItems(); + changed = pullItemsFromMinecart() || pickupItems(); } } @@ -186,13 +200,93 @@ public boolean onUpdate() { return true; } - public boolean pullItems() { - if (this.inventory.isFull()) { - return false; + private boolean pullItemsFromMinecart() { + if (this.minecartPickupInventory != null) { + Inventory inv = this.minecartPickupInventory.getInventory(); + + for (int i = 0; i < inv.getSize(); i++) { + Item item = inv.getItem(i); + + if (!item.isNull()) { + Item itemToAdd = item.clone(); + itemToAdd.count = 1; + if (!this.inventory.canAddItem(itemToAdd)) { + continue; + } + + InventoryMoveItemEvent ev = new InventoryMoveItemEvent(inv, this.inventory, this, itemToAdd, InventoryMoveItemEvent.Action.SLOT_CHANGE); + this.server.getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + continue; + } + + Item[] items = this.inventory.addItem(itemToAdd); + if (items.length >= 1) { + continue; + } + + item.count--; + inv.setItem(i, item); + + this.minecartPickupInventory = null; + return true; + } + } } - BlockEntity blockEntity = this.level.getBlockEntity(this.up()); - //Fix for furnace outputs + return false; + } + + private boolean pushItemsToMinecart() { + if (this.minecartPushInventory != null) { + Inventory holderInventory = this.minecartPushInventory.getInventory(); + + if (holderInventory.isFull()) { + return false; + } + + for (int i = 0; i < this.inventory.getSize(); i++) { + Item item = this.inventory.getItem(i); + + if (!item.isNull()) { + Item itemToAdd = item.clone(); + itemToAdd.setCount(1); + + if (!holderInventory.canAddItem(itemToAdd)) { + continue; + } + + InventoryMoveItemEvent ev = new InventoryMoveItemEvent(this.inventory, holderInventory, this, itemToAdd, InventoryMoveItemEvent.Action.SLOT_CHANGE); + this.server.getPluginManager().callEvent(ev); + + if (ev.isCancelled()) { + continue; + } + + Item[] items = holderInventory.addItem(itemToAdd); + if (items.length > 0) { + continue; + } + + item.count--; + this.inventory.setItem(i, item); + + this.minecartPushInventory = null; + return true; + } + } + } + + return false; + } + + public boolean pullItems() { + return this.pullItems( + this.level.getBlockEntity(this.chunk, this.up()), + this.level.getBlock(this.chunk, this.getFloorX(), this.getFloorY() + 1, this.getFloorZ(), false)); + } + + private boolean pullItems(BlockEntity blockEntity, Block block) { if (blockEntity instanceof BlockEntityFurnace) { FurnaceInventory inv = ((BlockEntityFurnace) blockEntity).getInventory(); Item item = inv.getResult(); @@ -214,7 +308,7 @@ public boolean pullItems() { Item[] items = this.inventory.addItem(itemToAdd); - if (items.length <= 0) { + if (items.length == 0) { item.count--; inv.setResult(item); return true; @@ -253,15 +347,29 @@ public boolean pullItems() { return true; } } + } else if (block instanceof BlockComposter) { + BlockComposter composter = (BlockComposter) block; + Item item = composter.empty(); + if (item == null || item.isNull()) { + return false; + } + Item itemToAdd = item.clone(); + itemToAdd.setCount(1); + if (!this.inventory.canAddItem(itemToAdd)) { + return false; + } + InventoryMoveItemEvent ev = new InventoryMoveItemEvent(null, this.inventory, this, item, InventoryMoveItemEvent.Action.PICKUP); + this.server.getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + return false; + } + Item[] items = inventory.addItem(itemToAdd); + return items.length < 1; } return false; } public boolean pickupItems() { - if (this.inventory.isFull()) { - return false; - } - boolean pickedUpItem = false; for (Entity entity : this.level.getCollidingEntities(this.pickupArea)) { @@ -303,15 +411,14 @@ public boolean pickupItems() { } } - //TODO: check for minecart return pickedUpItem; } @Override public void close() { if (!closed) { - for (Player player : new HashSet<>(this.getInventory().getViewers())) { - player.removeWindow(this.getInventory()); + for (Player player : new ArrayList<>(this.inventory.getViewers())) { + player.removeWindow(this.inventory); } super.close(); } @@ -322,25 +429,21 @@ public void onBreak() { for (Item content : inventory.getContents().values()) { level.dropItem(this, content); } - this.inventory.clearAll(); + inventory.clearAll(); } public boolean pushItems() { - if (this.inventory.isEmpty()) { - return false; - } + int blockData = this.level.getBlockDataAt(this.chunk, (int) x, (int) y, (int) z, Block.LAYER_NORMAL); + BlockEntity be = this.level.getBlockEntity(this.chunk, this.getSide(BlockFace.fromIndex(blockData))); - BlockEntity be = this.level.getBlockEntity(this.getSide(BlockFace.fromIndex(this.level.getBlockDataAt(this.getFloorX(), this.getFloorY(), this.getFloorZ())))); - - if (be instanceof BlockEntityHopper && this.getBlock().getDamage() == 0 || !(be instanceof InventoryHolder)) + if (!(be instanceof InventoryHolder) || (be instanceof BlockEntityHopper && blockData == 0)) { return false; + } InventoryMoveItemEvent event; - //Fix for furnace inputs if (be instanceof BlockEntityFurnace) { - BlockEntityFurnace furnace = (BlockEntityFurnace) be; - FurnaceInventory inventory = furnace.getInventory(); + FurnaceInventory inventory = ((BlockEntityFurnace) be).getInventory(); if (inventory.isFull()) { return false; } @@ -353,8 +456,7 @@ public boolean pushItems() { Item itemToAdd = item.clone(); itemToAdd.setCount(1); - //Check direction of hopper - if (this.getBlock().getDamage() == 0) { + if (blockData == 0) { Item smelting = inventory.getSmelting(); if (smelting.isNull()) { event = new InventoryMoveItemEvent(this.inventory, inventory, this, itemToAdd, InventoryMoveItemEvent.Action.SLOT_CHANGE); @@ -365,7 +467,7 @@ public boolean pushItems() { item.count--; pushedItem = true; } - } else if (inventory.getSmelting().getId() == itemToAdd.getId() && inventory.getSmelting().getDamage() == itemToAdd.getDamage() && smelting.count < smelting.getMaxStackSize()) { + } else if (smelting.getId() == itemToAdd.getId() && smelting.getDamage() == itemToAdd.getDamage() && smelting.count < smelting.getMaxStackSize()) { event = new InventoryMoveItemEvent(this.inventory, inventory, this, itemToAdd, InventoryMoveItemEvent.Action.SLOT_CHANGE); this.server.getPluginManager().callEvent(event); @@ -402,11 +504,89 @@ public boolean pushItems() { if (pushedItem) { this.inventory.setItem(i, item); + return true; } } } - return pushedItem; + return false; + } else if (be instanceof BlockEntityBrewingStand) { + BrewingInventory inventory = ((BlockEntityBrewingStand) be).getInventory(); + if (inventory.isFull()) { + return false; + } + + boolean pushedItem = false; + + for (int i = 0; i < this.inventory.getSize(); i++) { + Item item = this.inventory.getItem(i); + if (!item.isNull()) { + Item itemToAdd = item.clone(); + itemToAdd.setCount(1); + + boolean isPotion = itemToAdd.getId() == Item.GLASS_BOTTLE || itemToAdd.getId() == Item.POTION || itemToAdd.getId() == Item.SPLASH_POTION; + + if (blockData == 0) { // Hopper is above the brewing stand + if (isPotion) { + continue; // No potions as ingredient + } + + Item ingredient = inventory.getIngredient(); + if (ingredient.isNull()) { + event = new InventoryMoveItemEvent(this.inventory, inventory, this, itemToAdd, InventoryMoveItemEvent.Action.SLOT_CHANGE); + this.server.getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + inventory.setIngredient(itemToAdd); + pushedItem = true; + } + } else if (ingredient.getId() == itemToAdd.getId() && ingredient.getDamage() == itemToAdd.getDamage() && ingredient.count < ingredient.getMaxStackSize()) { + event = new InventoryMoveItemEvent(this.inventory, inventory, this, itemToAdd, InventoryMoveItemEvent.Action.SLOT_CHANGE); + this.server.getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + ingredient.count++; + inventory.setIngredient(ingredient); + pushedItem = true; + } + } + } else if (itemToAdd.getId() == Item.BLAZE_POWDER) { // Only blaze powder to fuel slot + Item fuel = inventory.getFuel(); + if (fuel.isNull()) { + event = new InventoryMoveItemEvent(this.inventory, inventory, this, itemToAdd, InventoryMoveItemEvent.Action.SLOT_CHANGE); + this.server.getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + inventory.setFuel(itemToAdd); + pushedItem = true; + } + } else if (fuel.getId() == itemToAdd.getId() && fuel.getDamage() == itemToAdd.getDamage() && fuel.count < fuel.getMaxStackSize()) { + event = new InventoryMoveItemEvent(this.inventory, inventory, this, itemToAdd, InventoryMoveItemEvent.Action.SLOT_CHANGE); + this.server.getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + fuel.count++; + inventory.setFuel(fuel); + pushedItem = true; + } + } + } else if (isPotion) { // Only bottles/potions to bottle slots + if (inventory.addItem(itemToAdd).length > 0) { // BrewingInventory overrides addItemSize to check the correct slots + continue; + } else { + pushedItem = true; + } + } + + if (pushedItem) { + item.count--; + this.inventory.setItem(i, item); + return true; + } + } + } + + return false; } else { Inventory inventory = ((InventoryHolder) be).getInventory(); @@ -445,7 +625,6 @@ public boolean pushItems() { } } - //TODO: check for minecart return false; } diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityItemFrame.java b/src/main/java/cn/nukkit/blockentity/BlockEntityItemFrame.java index 5a6b34700a5..cb44aa3f8c7 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityItemFrame.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityItemFrame.java @@ -7,9 +7,11 @@ import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.item.RuntimeItems; +import cn.nukkit.level.GameRule; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.ListTag; import cn.nukkit.network.protocol.LevelEventPacket; import java.util.concurrent.ThreadLocalRandom; @@ -19,6 +21,8 @@ */ public class BlockEntityItemFrame extends BlockEntitySpawnable { + private Item item_; + public BlockEntityItemFrame(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @@ -26,11 +30,13 @@ public BlockEntityItemFrame(FullChunk chunk, CompoundTag nbt) { @Override protected void initBlockEntity() { if (!namedTag.contains("Item")) { - namedTag.putCompound("Item", NBTIO.putItemHelper(new ItemBlock(Block.get(BlockID.AIR)))); + namedTag.putCompound("Item", NBTIO.putItemHelper(item_ = new ItemBlock(Block.get(BlockID.AIR)))); } + if (!namedTag.contains("ItemRotation")) { namedTag.putByte("ItemRotation", 0); } + if (!namedTag.contains("ItemDropChance")) { namedTag.putFloat("ItemDropChance", 1.0f); } @@ -47,7 +53,7 @@ public String getName() { @Override public boolean isBlockEntityValid() { - return this.getBlock().getId() == Block.ITEM_FRAME_BLOCK; + return level.getBlockIdAt(chunk, (int) x, (int) y, (int) z) == Block.ITEM_FRAME_BLOCK; } public int getItemRotation() { @@ -61,8 +67,11 @@ public void setItemRotation(int itemRotation) { } public Item getItem() { - CompoundTag NBTTag = this.namedTag.getCompound("Item"); - return NBTIO.getItemHelper(NBTTag); + if (item_ == null) { + CompoundTag NBTTag = this.namedTag.getCompound("Item"); + item_ = NBTIO.getItemHelper(NBTTag); + } + return item_; } public void setItem(Item item) { @@ -70,6 +79,7 @@ public void setItem(Item item) { } public void setItem(Item item, boolean setChanged) { + item_ = item; this.namedTag.putCompound("Item", NBTIO.putItemHelper(item)); if (setChanged) { this.setDirty(); @@ -84,11 +94,13 @@ public float getItemDropChance() { public void setItemDropChance(float chance) { this.namedTag.putFloat("ItemDropChance", chance); + super.setDirty(); // No need to spawnToAll } + @Override public void setDirty() { - this.spawnToAll(); super.setDirty(); + this.spawnToAll(); } @Override @@ -96,19 +108,62 @@ public CompoundTag getSpawnCompound() { if (!this.namedTag.contains("Item")) { this.setItem(new ItemBlock(Block.get(BlockID.AIR)), false); } - CompoundTag item = namedTag.getCompound("Item").copy(); - item.setName("Item"); + CompoundTag itemOriginal = namedTag.getCompound("Item"); + CompoundTag tag = new CompoundTag() - .putString("id", BlockEntity.ITEM_FRAME) + .putString("id", this instanceof BlockEntityItemFrameGlow ? BlockEntity.GLOW_ITEM_FRAME : BlockEntity.ITEM_FRAME) .putInt("x", (int) this.x) .putInt("y", (int) this.y) .putInt("z", (int) this.z); - int itemId = item.getShort("id"); + int itemId = itemOriginal.getShort("id"); if (itemId != Item.AIR) { - String identifier = RuntimeItems.getMapping().toRuntime(itemId, item.getShort("Damage")).getIdentifier(); - item.putString("Name", identifier); - item.remove("id"); + CompoundTag item; + if (itemId == Item.MAP) { + item = itemOriginal.copy(); + item.setName("Item"); + + String identifier = RuntimeItems.getMapping().toRuntime(itemId, itemOriginal.getShort("Damage")).getIdentifier(); + item.putString("Name", identifier); + item.remove("id"); + + item.getCompound("tag").remove("Colors"); + } else { + // Instead of copying the item's whole nbt just send the data necessary to display the item + item = new CompoundTag("Item") + .putByte("Count", itemOriginal.getByte("Count")) + .putShort("Damage", itemOriginal.getShort("Damage")); + + String identifier = RuntimeItems.getMapping().toRuntime(itemId, itemOriginal.getShort("Damage")).getIdentifier(); + item.putString("Name", identifier); + + if (itemOriginal.contains("tag")) { + CompoundTag oldTag = itemOriginal.getCompound("tag"); + CompoundTag newTag = new CompoundTag(); + + if (oldTag.contains("ench")) { + newTag.putList(new ListTag<>("ench")); + } + + if (oldTag.contains("Base")) { + newTag.put("Base", oldTag.get("Base")); + } + + if (oldTag.contains("Patterns")) { + newTag.put("Patterns", oldTag.get("Patterns")); + } + + if (oldTag.contains("customColor")) { + newTag.put("customColor", oldTag.get("customColor")); + } + + if (oldTag.contains("display") && oldTag.get("display") instanceof CompoundTag) { + newTag.putCompound("display", new CompoundTag("display").putString("Name", ((CompoundTag) oldTag.get("display")).getString("Name"))); + } + + item.put("tag", newTag); + } + } tag.putCompound("Item", item) .putByte("ItemRotation", this.getItemRotation()); @@ -131,15 +186,30 @@ public boolean dropItem(Player player) { return true; } } - + this.setItem(Item.get(Item.AIR)); + this.setItemRotation(0); if (this.getItemDropChance() > ThreadLocalRandom.current().nextFloat()) { this.level.dropItem(this.add(0.5, 0, 0.5), item); } - this.setItem(Item.get(Item.AIR)); - this.setItemRotation(0); this.level.addLevelEvent(this, LevelEventPacket.EVENT_SOUND_ITEM_FRAME_ITEM_REMOVED); return true; } return false; } + + @Override + public void onBreak() { + Item item = null; + + if (level.getGameRules().getBoolean(GameRule.DO_TILE_DROPS)) { + item = getItem(); + } + + this.namedTag.remove("Item"); + item_ = null; + + if (item != null && item.getId() != BlockID.AIR) { + level.dropItem(this, item); + } + } } diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityItemFrameGlow.java b/src/main/java/cn/nukkit/blockentity/BlockEntityItemFrameGlow.java new file mode 100644 index 00000000000..511aa57b3b6 --- /dev/null +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityItemFrameGlow.java @@ -0,0 +1,22 @@ +package cn.nukkit.blockentity; + +import cn.nukkit.block.Block; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; + +public class BlockEntityItemFrameGlow extends BlockEntityItemFrame { + + public BlockEntityItemFrameGlow(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + @Override + public String getName() { + return "Glow Item Frame"; + } + + @Override + public boolean isBlockEntityValid() { + return level.getBlockIdAt(chunk, (int) x, (int) y, (int) z) == Block.GLOW_FRAME; + } +} diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityJukebox.java b/src/main/java/cn/nukkit/blockentity/BlockEntityJukebox.java index ce7e18ee4ff..d5f15c7c9c7 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityJukebox.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityJukebox.java @@ -34,12 +34,13 @@ protected void initBlockEntity() { @Override public boolean isBlockEntityValid() { - return this.getLevel().getBlockIdAt(getFloorX(), getFloorY(), getFloorZ()) == Block.JUKEBOX; + return level.getBlockIdAt(chunk, (int) x, (int) y, (int) z) == Block.JUKEBOX; } public void setRecordItem(Item recordItem) { Objects.requireNonNull(recordItem, "Record item cannot be null"); - this.recordItem = recordItem; + this.recordItem = recordItem.clone(); + setDirty(); } public Item getRecordItem() { @@ -110,6 +111,7 @@ public void dropItem() { stop(); this.level.dropItem(this.up(), this.recordItem); this.recordItem = Item.get(0); + setDirty(); } } diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityLectern.java b/src/main/java/cn/nukkit/blockentity/BlockEntityLectern.java new file mode 100644 index 00000000000..e4386f41a10 --- /dev/null +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityLectern.java @@ -0,0 +1,163 @@ +package cn.nukkit.blockentity; + +import cn.nukkit.Player; +import cn.nukkit.block.BlockID; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; +import cn.nukkit.level.GameRule; +import cn.nukkit.level.format.Chunk; +import cn.nukkit.nbt.NBTIO; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.IntTag; + +public class BlockEntityLectern extends BlockEntitySpawnable { + + private int totalPages; + private Item item_; + + public BlockEntityLectern(Chunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + @Override + protected void initBlockEntity() { + if (!(this.namedTag.get("book") instanceof CompoundTag)) { + this.namedTag.remove("book"); + } + + if (!(this.namedTag.get("page") instanceof IntTag)) { + this.namedTag.remove("page"); + } + + updateTotalPages(false); + } + + @Override + public CompoundTag getSpawnCompound() { + CompoundTag c = new CompoundTag() + .putString("id", BlockEntity.LECTERN) + .putInt("x", (int) this.x) + .putInt("y", (int) this.y) + .putInt("z", (int) this.z); + + Item book = getBook(); + if (book.getId() != BlockID.AIR) { + c.putCompound("book", NBTIO.putItemHelper(book)); + c.putBoolean("hasBook", true); + c.putInt("page", getRawPage()); + c.putInt("totalPages", totalPages); + } else { + c.putBoolean("hasBook", false); + } + + return c; + } + + @Override + public boolean isBlockEntityValid() { + return level.getBlockIdAt(chunk, (int) x, (int) y, (int) z) == BlockID.LECTERN; + } + + @Override + public void onBreak() { + Item item = null; + + if (level.getGameRules().getBoolean(GameRule.DO_TILE_DROPS)) { + item = getBook(); + } + + this.namedTag.remove("Item"); + item_ = null; + + if (item != null && item.getId() != BlockID.AIR) { + level.dropItem(this, item); + } + } + + public boolean hasBook() { + return this.namedTag.get("book") instanceof CompoundTag; + } + + public Item getBook() { + if (item_ != null) { + return item_; + } + if (!hasBook()) { + return Item.get(BlockID.AIR, 0, 0); + } else { + return item_ = NBTIO.getItemHelper(this.namedTag.getCompound("book")); + } + } + + public void setBook(Item item) { + if (item != null && (item.getId() == ItemID.WRITTEN_BOOK || item.getId() == ItemID.BOOK_AND_QUILL)) { + this.namedTag.putCompound("book", NBTIO.putItemHelper(item_ = item)); + } else { + this.namedTag.remove("book"); + this.namedTag.remove("page"); + item_ = null; + } + + updateTotalPages(true); + setDirty(); + } + + public int getLeftPage() { + return (getRawPage() * 2) + 1; + } + + public int getRightPage() { + return getLeftPage() + 1; + } + + public void setLeftPage(int newLeftPage) { + setRawPage((newLeftPage - 1) >> 1); + } + + public void setRightPage(int newRightPage) { + setLeftPage(newRightPage - 1); + } + + public void setRawPage(int page) { + this.namedTag.putInt("page", Math.min(page, totalPages)); + setDirty(); + this.getLevel().updateAround(this); + } + + public int getRawPage() { + return this.namedTag.getInt("page"); + } + + public int getTotalPages() { + return totalPages; + } + + private void updateTotalPages(boolean updateRedstone) { + Item book = getBook(); + if (book.getId() == BlockID.AIR || !book.hasCompoundTag()) { + totalPages = 0; + } else { + totalPages = book.getNamedTag().getList("pages", CompoundTag.class).size(); + } + + if (updateRedstone) { + this.getLevel().updateAroundRedstone(this, null); + } + } + + public boolean dropBook(Player player) { + Item item = this.getBook(); + if (item != null && item.getId() != Item.AIR) { + this.setBook(null); + this.level.dropItem(this.add(0.5, 1, 0.5), item); + return true; + } + return false; + } + + @Override + public void setDirty() { + super.setDirty(); + this.spawnToAll(); + } +} diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityMovingBlock.java b/src/main/java/cn/nukkit/blockentity/BlockEntityMovingBlock.java index 564a9649fb4..b823d250a1d 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityMovingBlock.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityMovingBlock.java @@ -42,7 +42,7 @@ public Block getBlock() { @Override public boolean isBlockEntityValid() { - return true; + return true; // TODO } @Override @@ -54,4 +54,4 @@ public CompoundTag getSpawnCompound() { .putInt("pistonPosY", this.piston.y) .putInt("pistonPosZ", this.piston.z); } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityMusic.java b/src/main/java/cn/nukkit/blockentity/BlockEntityMusic.java index 101c13a9cc3..d465e6384fc 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityMusic.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityMusic.java @@ -15,6 +15,7 @@ protected void initBlockEntity() { if (!this.namedTag.contains("note")) { this.namedTag.putByte("note", 0); } + if (!this.namedTag.contains("powered")) { this.namedTag.putBoolean("powered", false); } @@ -24,11 +25,12 @@ protected void initBlockEntity() { @Override public boolean isBlockEntityValid() { - return this.getBlock().getId() == Block.NOTEBLOCK; + return level.getBlockIdAt(chunk, (int) x, (int) y, (int) z) == Block.NOTEBLOCK; } public void changePitch() { this.namedTag.putByte("note", (this.namedTag.getByte("note") + 1) % 25); + setDirty(); } public int getPitch() { @@ -37,6 +39,7 @@ public int getPitch() { public void setPowered(boolean powered) { this.namedTag.putBoolean("powered", powered); + setDirty(); } public boolean isPowered() { diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityNameable.java b/src/main/java/cn/nukkit/blockentity/BlockEntityNameable.java index e7bea12b7cf..914c93ef096 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityNameable.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityNameable.java @@ -6,7 +6,6 @@ * * @author MagicDroidX(code) @ Nukkit Project * @author 粉鞋大妈(javadoc) @ Nukkit Project - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public interface BlockEntityNameable { @@ -15,7 +14,6 @@ public interface BlockEntityNameable { * Gets the name of this object. * * @return 这个事物的名字。
The name of this object. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ String getName(); @@ -24,7 +22,6 @@ public interface BlockEntityNameable { * Changes the name of this object, or names it. * * @param name 这个事物的新名字。
The new name of this object. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ void setName(String name); @@ -33,7 +30,6 @@ public interface BlockEntityNameable { * Whether this object has a name. * * @return 如果有名字,返回 {@code true}。
{@code true} for this object has a name. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ boolean hasName(); } diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityPistonArm.java b/src/main/java/cn/nukkit/blockentity/BlockEntityPistonArm.java index c722c423bbc..b7f9aba31b4 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityPistonArm.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityPistonArm.java @@ -1,10 +1,8 @@ package cn.nukkit.blockentity; -import cn.nukkit.entity.Entity; +import cn.nukkit.block.Block; import cn.nukkit.level.format.FullChunk; -import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.math.BlockFace; -import cn.nukkit.math.SimpleAxisAlignedBB; import cn.nukkit.math.Vector3; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.IntTag; @@ -13,18 +11,17 @@ /** * @author CreeperFace */ -public class BlockEntityPistonArm extends BlockEntity { +public class BlockEntityPistonArm extends BlockEntitySpawnable { - public float progress = 1.0F; - public float lastProgress = 1.0F; + public float progress; + public float lastProgress; public BlockFace facing; public boolean extending = false; public boolean sticky = false; - public byte state = 1; + public byte state; public byte newState = 1; public Vector3 attachedBlock = null; public boolean isMovable = true; - public boolean powered = false; public BlockEntityPistonArm(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); @@ -32,6 +29,8 @@ public BlockEntityPistonArm(FullChunk chunk, CompoundTag nbt) { @Override protected void initBlockEntity() { + this.isMovable = true; + if (namedTag.contains("Progress")) { this.progress = namedTag.getFloat("Progress"); } @@ -48,8 +47,8 @@ protected void initBlockEntity() { this.extending = namedTag.getBoolean("Extending"); } - if (namedTag.contains("powered")) { - this.powered = namedTag.getBoolean("powered"); + if (namedTag.contains("State")) { + this.state = (byte) namedTag.getByte("State"); } if (namedTag.contains("AttachedBlocks")) { @@ -64,25 +63,25 @@ protected void initBlockEntity() { super.initBlockEntity(); } - private void pushEntities() { - float lastProgress = this.getExtendedProgress(this.lastProgress); - double x = lastProgress * (float) this.facing.getXOffset(); - double y = lastProgress * (float) this.facing.getYOffset(); - double z = lastProgress * (float) this.facing.getZOffset(); - AxisAlignedBB bb = new SimpleAxisAlignedBB(x, y, z, x + 1.0D, y + 1.0D, z + 1.0D); - Entity[] entities = this.level.getCollidingEntities(bb); - if (entities.length != 0) { - - } + public void setExtended(boolean extending) { + this.extending = extending; + this.newState = this.state; + this.lastProgress = this.progress; + this.state = (byte) (extending ? 1 : 0); + this.progress = extending ? 1.0f : 0; + } + public boolean isExtended() { + return this.extending; } - private float getExtendedProgress(float progress) { - return this.extending ? progress - 1.0F : 1.0F - progress; + public void broadcastMove() { + this.level.addChunkPacket(this.getChunkX(), this.getChunkZ(), this.createSpawnPacket()); } public boolean isBlockEntityValid() { - return true; + int blockId = getBlock().getId(); + return blockId == Block.PISTON || blockId == Block.STICKY_PISTON; } public void saveNBT() { @@ -92,10 +91,19 @@ public void saveNBT() { this.namedTag.putByte("NewState", this.newState); this.namedTag.putFloat("Progress", this.progress); this.namedTag.putFloat("LastProgress", this.lastProgress); - this.namedTag.putBoolean("powered", this.powered); + this.namedTag.putBoolean("Sticky", this.sticky); } public CompoundTag getSpawnCompound() { - return (new CompoundTag()).putString("id", "PistonArm").putInt("x", (int) this.x).putInt("y", (int) this.y).putInt("z", (int) this.z); + return new CompoundTag() + .putString("id", BlockEntity.PISTON_ARM) + .putInt("x", (int) this.x) + .putInt("y", (int) this.y) + .putInt("z", (int) this.z) + .putFloat("Progress", this.progress) + .putFloat("LastProgress", this.lastProgress) + .putBoolean("Sticky", this.sticky) + .putByte("State", this.state) + .putByte("NewState", this.newState); } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntityShulkerBox.java b/src/main/java/cn/nukkit/blockentity/BlockEntityShulkerBox.java index a9362fb6b43..bd5f512851a 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntityShulkerBox.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntityShulkerBox.java @@ -13,11 +13,8 @@ import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.ListTag; -import java.util.HashSet; +import java.util.ArrayList; -/** - * Created by PetteriM1 - */ public class BlockEntityShulkerBox extends BlockEntitySpawnable implements InventoryHolder, BlockEntityContainer, BlockEntityNameable { protected ShulkerBoxInventory inventory; @@ -28,46 +25,55 @@ public BlockEntityShulkerBox(FullChunk chunk, CompoundTag nbt) { @Override protected void initBlockEntity() { - this.inventory = new ShulkerBoxInventory(this); + if (!this.namedTag.contains("facing")) { + this.namedTag.putByte("facing", 0); + } + + super.initBlockEntity(); + } + private void initInventory() { if (!this.namedTag.contains("Items") || !(this.namedTag.get("Items") instanceof ListTag)) { this.namedTag.putList(new ListTag("Items")); } - ListTag list = (ListTag) this.namedTag.getList("Items"); + + this.inventory = new ShulkerBoxInventory(this); + for (CompoundTag compound : list.getAll()) { Item item = NBTIO.getItemHelper(compound); - this.inventory.slots.put(compound.getByte("Slot"), item); - } - - if (!this.namedTag.contains("facing")) { - this.namedTag.putByte("facing", 0); + if (item.getId() != 0 && item.getCount() > 0) { + this.inventory.slots.put(compound.getByte("Slot"), item); + } } - - super.initBlockEntity(); } @Override public void close() { - if (!closed) { - for (Player player : new HashSet<>(this.getInventory().getViewers())) { - player.removeWindow(this.getInventory()); + if (!this.closed && this.inventory != null) { + for (Player player : new ArrayList<>(this.inventory.getViewers())) { + player.removeWindow(this.inventory); } - super.close(); } + + super.close(); } @Override public void saveNBT() { - this.namedTag.putList(new ListTag("Items")); - for (int index = 0; index < this.getSize(); index++) { - this.setItem(index, this.inventory.getItem(index)); + super.saveNBT(); + + if (this.inventory != null) { + this.namedTag.putList(new ListTag("Items")); + for (int index = 0; index < this.getSize(); index++) { + this.setItem(index, this.inventory.getItem(index)); + } } } @Override public boolean isBlockEntityValid() { - int blockID = this.getBlock().getId(); + int blockID = level.getBlockIdAt(chunk, (int) x, (int) y, (int) z); return blockID == Block.SHULKER_BOX || blockID == Block.UNDYED_SHULKER_BOX; } @@ -117,13 +123,12 @@ public void setItem(int index, Item item) { @Override public BaseInventory getInventory() { + if (this.inventory == null) { + this.initInventory(); + } return this.inventory; } - public ShulkerBoxInventory getRealInventory() { - return inventory; - } - @Override public String getName() { return this.hasName() ? this.namedTag.getString("CustomName") : "Shulker Box"; diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntitySign.java b/src/main/java/cn/nukkit/blockentity/BlockEntitySign.java index ca41f212770..1c50aad232f 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntitySign.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntitySign.java @@ -1,7 +1,7 @@ package cn.nukkit.blockentity; import cn.nukkit.Player; -import cn.nukkit.block.Block; +import cn.nukkit.block.BlockSignPost; import cn.nukkit.event.block.SignChangeEvent; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.ByteTag; @@ -15,7 +15,7 @@ import java.util.Objects; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockEntitySign extends BlockEntitySpawnable { @@ -31,26 +31,28 @@ protected void initBlockEntity() { text = new String[4]; if (!namedTag.contains("Text")) { - - for (int i = 1; i <= 4; i++) { - String key = "Text" + i; - - if (namedTag.contains(key)) { - String line = namedTag.getString(key); - - this.text[i - 1] = line; - - this.namedTag.remove(key); + if (namedTag.contains("FrontText")) { // Bedrock vanilla + this.setText(((CompoundTag) namedTag.removeAndGet("FrontText")).getString("Text").split("\n", 4)); + } else { + for (int i = 1; i <= 4; i++) { + String key = "Text" + i; + + if (namedTag.contains(key)) { + String line = namedTag.getString(key); + this.text[i - 1] = line; + this.namedTag.remove(key); + } } } } else { String[] lines = namedTag.getString("Text").split("\n", 4); for (int i = 0; i < text.length; i++) { - if (i < lines.length) + if (i < lines.length) { text[i] = lines[i]; - else + } else { text[i] = ""; + } } } @@ -59,10 +61,10 @@ protected void initBlockEntity() { sanitizeText(text); } - if (!this.namedTag.contains("SignTextColor") || !(this.namedTag.get("SignTextColor") instanceof IntTag)) { + if (!(this.namedTag.get("SignTextColor") instanceof IntTag)) { this.setColor(DyeColor.BLACK.getSignColor()); } - if (!this.namedTag.contains("IgnoreLighting") || !(this.namedTag.get("IgnoreLighting") instanceof ByteTag)) { + if (!(this.namedTag.get("IgnoreLighting") instanceof ByteTag)) { this.setGlowing(false); } @@ -77,8 +79,7 @@ public void saveNBT() { @Override public boolean isBlockEntityValid() { - int blockID = getBlock().getId(); - return blockID == Block.SIGN_POST || blockID == Block.WALL_SIGN; + return getLevelBlock() instanceof BlockSignPost; } public boolean setText(String... lines) { @@ -90,12 +91,9 @@ public boolean setText(String... lines) { } this.namedTag.putString("Text", String.join("\n", text)); - this.spawnToAll(); - - if (this.chunk != null) { - setDirty(); - } + setDirty(); + this.spawnToAll(); return true; } @@ -109,6 +107,7 @@ public BlockColor getColor() { public void setColor(BlockColor color) { this.namedTag.putInt("SignTextColor", color.getARGB()); + setDirty(); } public boolean isGlowing() { @@ -117,6 +116,7 @@ public boolean isGlowing() { public void setGlowing(boolean glowing) { this.namedTag.putBoolean("IgnoreLighting", glowing); + setDirty(); } @Override @@ -126,7 +126,8 @@ public boolean updateCompoundTag(CompoundTag nbt, Player player) { } String[] lines = new String[4]; Arrays.fill(lines, ""); - String[] splitLines = nbt.getCompound("FrontText").getString("Text").split("\n", 4); + String receivedText = nbt.getCompound("FrontText").getString("Text"); + String[] splitLines = receivedText.split("\n", 4); System.arraycopy(splitLines, 0, lines, 0, splitLines.length); sanitizeText(lines); @@ -168,9 +169,9 @@ public CompoundTag getSpawnCompound() { private static void sanitizeText(String[] lines) { for (int i = 0; i < lines.length; i++) { - // Don't allow excessive text per line. + // Don't allow excessive text per line if (lines[i] != null) { - lines[i] = lines[i].substring(0, Math.min(255, lines[i].length())); + lines[i] = lines[i].substring(0, Math.min(200, lines[i].length())); } } } diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntitySkull.java b/src/main/java/cn/nukkit/blockentity/BlockEntitySkull.java index 2d141e79dfd..3a70362f3d6 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntitySkull.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntitySkull.java @@ -33,7 +33,7 @@ public void saveNBT() { @Override public boolean isBlockEntityValid() { - return getBlock().getId() == Block.SKULL_BLOCK; + return level.getBlockIdAt(chunk, (int) x, (int) y, (int) z) == Block.SKULL_BLOCK; } @Override @@ -46,5 +46,4 @@ public CompoundTag getSpawnCompound() { .putInt("z", (int) this.z) .put("Rot", this.namedTag.get("Rot")); } - } \ No newline at end of file diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntitySmoker.java b/src/main/java/cn/nukkit/blockentity/BlockEntitySmoker.java new file mode 100644 index 00000000000..8faa4ac7b67 --- /dev/null +++ b/src/main/java/cn/nukkit/blockentity/BlockEntitySmoker.java @@ -0,0 +1,144 @@ +package cn.nukkit.blockentity; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; +import cn.nukkit.event.inventory.FurnaceSmeltEvent; +import cn.nukkit.inventory.FurnaceRecipe; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBlock; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.network.protocol.LevelSoundEventPacket; +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntSet; + +import java.util.concurrent.ThreadLocalRandom; + +public class BlockEntitySmoker extends BlockEntityFurnace { + + public BlockEntitySmoker(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + @Override + public String getName() { + return this.hasName() ? this.namedTag.getString("CustomName") : "Smoker"; + } + + @Override + public boolean isBlockEntityValid() { + int blockID = level.getBlockIdAt(chunk, (int) x, (int) y, (int) z); + return blockID == Block.SMOKER || blockID == Block.LIT_SMOKER; + } + + private static final IntSet CAN_SMELT = new IntOpenHashSet(new int[]{ + Item.RAW_PORKCHOP, Item.RAW_BEEF, Item.RAW_RABBIT, Item.RAW_FISH, Item.RAW_CHICKEN, Item.RAW_MUTTON, Item.RAW_SALMON, Item.POTATO + }); + + @Override + public boolean onUpdate() { + if (this.closed) { + return false; + } + + Item raw = this.inventory.getSmelting(); + // TODO: smoker recipes + if (!CAN_SMELT.contains(raw.getId())) { + if (burnTime > 0) { + burnTime--; + burnDuration = (int) Math.ceil((float) burnTime / maxTime * 100); + + if (burnTime == 0) { + Block block = this.level.getBlock(this.chunk, (int) x, (int) y, (int) z, true); + if (block.getId() == BlockID.LIT_SMOKER) { + this.level.setBlock(this, Block.get(BlockID.SMOKER, block.getDamage()), true); + } + return false; + } + } + + cookTime = 0; + sendPacket(); + return true; + } + + boolean ret = false; + Item product = this.inventory.getResult(); + FurnaceRecipe smelt = this.server.getCraftingManager().matchFurnaceRecipe(raw); + boolean canSmelt = (smelt != null && raw.getCount() > 0 && ((smelt.getResult().equals(product) && product.getCount() < product.getMaxStackSize()) || product.getId() == Item.AIR)); + + Item fuel; + if (burnTime <= 0 && canSmelt && (fuel = this.inventory.getItemFast(1)).getFuelTime() != null && fuel.getCount() > 0) { + this.checkFuel(fuel.clone()); + } + + if (burnTime > 0) { + burnTime--; + burnDuration = (int) Math.ceil((float) burnTime / maxTime * 100); + + if (this.crackledTime-- <= 0) { + this.crackledTime = ThreadLocalRandom.current().nextInt(30, 110); + this.getLevel().addLevelSoundEvent(this.add(0.5, 0.5, 0.5), LevelSoundEventPacket.SOUND_BLOCK_FURNACE_LIT); + } + + if (smelt != null && canSmelt) { + cookTime++; + if (cookTime >= 100) { + product = Item.get(smelt.getResult().getId(), smelt.getResult().getDamage(), product.isNull() ? 1 : product.getCount() + 1); + + FurnaceSmeltEvent ev = new FurnaceSmeltEvent(this, raw, product); + this.server.getPluginManager().callEvent(ev); + if (!ev.isCancelled()) { + this.inventory.setResult(ev.getResult()); + this.experience += FURNACE_XP.getOrDefault(ev.getResult().getId(), 0d); + raw.setCount(raw.getCount() - 1); + if (raw.getCount() == 0) { + raw = new ItemBlock(Block.get(BlockID.AIR), 0, 0); + } + this.inventory.setSmelting(raw); + } + + cookTime -= 100; + } + } else if (burnTime <= 0) { + burnTime = 0; + cookTime = 0; + burnDuration = 0; + } else { + cookTime = 0; + } + ret = true; + } else { + Block block = this.level.getBlock(this.chunk, (int) x, (int) y, (int) z, true); + if (block.getId() == BlockID.LIT_SMOKER) { + this.level.setBlock(this, Block.get(BlockID.SMOKER, block.getDamage()), true); + } + burnTime = 0; + cookTime = 0; + burnDuration = 0; + crackledTime = 0; + } + + sendPacket(); + + return ret; + } + + @Override + public CompoundTag getSpawnCompound() { + CompoundTag c = new CompoundTag() + .putString("id", BlockEntity.SMOKER) + .putInt("x", (int) this.x) + .putInt("y", (int) this.y) + .putInt("z", (int) this.z) + .putShort("BurnDuration", burnDuration) + .putShort("BurnTime", burnTime) + .putShort("CookTime", cookTime); + + if (this.hasName()) { + c.put("CustomName", this.namedTag.get("CustomName")); + } + + return c; + } +} diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntitySpawnable.java b/src/main/java/cn/nukkit/blockentity/BlockEntitySpawnable.java index e0d8651346d..309311986ac 100644 --- a/src/main/java/cn/nukkit/blockentity/BlockEntitySpawnable.java +++ b/src/main/java/cn/nukkit/blockentity/BlockEntitySpawnable.java @@ -10,7 +10,7 @@ import java.nio.ByteOrder; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class BlockEntitySpawnable extends BlockEntity { @@ -28,22 +28,27 @@ protected void initBlockEntity() { public abstract CompoundTag getSpawnCompound(); - public void spawnTo(Player player) { - if (this.closed) { - return; - } - + public BlockEntityDataPacket createSpawnPacket() { CompoundTag tag = this.getSpawnCompound(); + BlockEntityDataPacket pk = new BlockEntityDataPacket(); pk.x = (int) this.x; pk.y = (int) this.y; pk.z = (int) this.z; + try { pk.namedTag = NBTIO.write(tag, ByteOrder.LITTLE_ENDIAN, true); } catch (IOException e) { throw new RuntimeException(e); } - player.dataPacket(pk); + + return pk; + } + + public void spawnTo(Player player) { + if (!this.closed) { + player.dataPacket(this.createSpawnPacket()); + } } public void spawnToAll() { diff --git a/src/main/java/cn/nukkit/blockentity/BlockEntitySpawner.java b/src/main/java/cn/nukkit/blockentity/BlockEntitySpawner.java new file mode 100644 index 00000000000..32433b4877c --- /dev/null +++ b/src/main/java/cn/nukkit/blockentity/BlockEntitySpawner.java @@ -0,0 +1,26 @@ +package cn.nukkit.blockentity; + +import cn.nukkit.block.Block; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.*; + +public class BlockEntitySpawner extends BlockEntitySpawnable { + + public BlockEntitySpawner(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + @Override + public CompoundTag getSpawnCompound() { + return new CompoundTag() + .putString("id", BlockEntity.MOB_SPAWNER) + .putInt("x", (int) this.x) + .putInt("y", (int) this.y) + .putInt("z", (int) this.z); + } + + @Override + public boolean isBlockEntityValid() { + return level.getBlockIdAt(chunk, (int) x, (int) y, (int) z) == Block.MONSTER_SPAWNER; + } +} diff --git a/src/main/java/cn/nukkit/blockentity/PersistentDataContainerBlockEntity.java b/src/main/java/cn/nukkit/blockentity/PersistentDataContainerBlockEntity.java new file mode 100644 index 00000000000..be41d5241b2 --- /dev/null +++ b/src/main/java/cn/nukkit/blockentity/PersistentDataContainerBlockEntity.java @@ -0,0 +1,70 @@ +package cn.nukkit.blockentity; + +import cn.nukkit.block.BlockID; +import cn.nukkit.level.persistence.PersistentDataContainer; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; +import lombok.ToString; + +@ToString(callSuper = true) +public class PersistentDataContainerBlockEntity extends BlockEntity implements PersistentDataContainer { + + public PersistentDataContainerBlockEntity(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + @Override + public boolean onUpdate() { + if (!this.isBlockEntityValid()) { + this.close(); + } + return false; + } + + @Override + public boolean isBlockEntityValid() { + return this.level.getBlockIdAt(this.chunk, (int) this.x, (int) this.y, (int) this.z) != BlockID.AIR; + } + + @Override + public boolean isValid() { + return super.isValid() && this.isBlockEntityValid(); + } + + @Override + public CompoundTag getStorage() { + if (this.namedTag.contains(STORAGE_TAG)) { + return this.namedTag.getCompound(STORAGE_TAG); + } + + CompoundTag storage = new CompoundTag(); + this.setStorage(storage); + return storage; + } + + @Override + public void setStorage(CompoundTag storage) { + this.namedTag.put(STORAGE_TAG, storage); + setDirty(); + } + + @Override + public PersistentDataContainer getPersistentDataContainer() { + return this; + } + + @Override + public boolean equals(Object obj) { + return obj instanceof PersistentDataContainerBlockEntity && super.equals(obj); + } + + @Override + public boolean canSaveToStorage() { + return !this.isEmpty(); + } + + @Override + public void write() { + setDirty(); + } +} diff --git a/src/main/java/cn/nukkit/command/Command.java b/src/main/java/cn/nukkit/command/Command.java index fbbd4954eb7..f6d54ad7c6b 100644 --- a/src/main/java/cn/nukkit/command/Command.java +++ b/src/main/java/cn/nukkit/command/Command.java @@ -7,19 +7,15 @@ import cn.nukkit.lang.TranslationContainer; import cn.nukkit.permission.Permissible; import cn.nukkit.utils.TextFormat; -import co.aikar.timings.Timing; -import co.aikar.timings.Timings; import java.util.*; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class Command { - private static CommandData defaultDataTemplate = null; - protected CommandData commandData; private final String name; @@ -28,24 +24,22 @@ public abstract class Command { private String label; - private String[] aliases = new String[0]; + private String[] aliases; - private String[] activeAliases = new String[0]; + private String[] activeAliases; - private CommandMap commandMap = null; + private CommandMap commandMap; - protected String description = ""; + protected String description; - protected String usageMessage = ""; + protected String usageMessage; - private String permission = null; + private String permission; - private String permissionMessage = null; + private String permissionMessage; protected Map commandParameters = new HashMap<>(); - public Timing timing; - public Command(String name) { this(name, "", null, new String[0]); } @@ -60,14 +54,13 @@ public Command(String name, String description, String usageMessage) { public Command(String name, String description, String usageMessage, String[] aliases) { this.commandData = new CommandData(); - this.name = name.toLowerCase(); // Uppercase letters crash the client?!? + this.name = name.toLowerCase(); // Prevent client crash this.nextLabel = name; this.label = name; this.description = description; - this.usageMessage = usageMessage == null ? "/" + name : usageMessage; + this.usageMessage = usageMessage == null ? '/' + name : usageMessage; this.aliases = aliases; this.activeAliases = aliases; - this.timing = Timings.getCommandTiming(this); this.commandParameters.put("default", new CommandParameter[]{CommandParameter.newType("args", true, CommandParamType.RAWTEXT)}); } @@ -104,7 +97,7 @@ public void addCommandParameters(String key, CommandParameter[] parameters) { * @return CommandData|null */ public CommandDataVersions generateCustomCommandData(Player player) { - if (!this.testPermission(player)) { + if (!this.testPermissionSilent(player)) { return null; } @@ -125,7 +118,7 @@ public CommandDataVersions generateCustomCommandData(Player player) { overload.input.parameters = par; customData.overloads.put(key, overload); }); - if (customData.overloads.size() == 0) customData.overloads.put("default", new CommandOverload()); + if (customData.overloads.isEmpty()) customData.overloads.put("default", new CommandOverload()); CommandDataVersions versions = new CommandDataVersions(); versions.versions.add(customData); return versions; @@ -156,7 +149,7 @@ public boolean testPermission(CommandSender target) { if (this.permissionMessage == null) { target.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.unknown", this.name)); - } else if (!this.permissionMessage.equals("")) { + } else if (!this.permissionMessage.isEmpty()) { target.sendMessage(this.permissionMessage.replace("", this.permission)); } @@ -164,7 +157,7 @@ public boolean testPermission(CommandSender target) { } public boolean testPermissionSilent(CommandSender target) { - if (this.permission == null || this.permission.equals("")) { + if (this.permission == null || this.permission.isEmpty()) { return true; } @@ -186,7 +179,6 @@ public boolean setLabel(String name) { this.nextLabel = name; if (!this.isRegistered()) { this.label = name; - this.timing = Timings.getCommandTiming(this); return true; } return false; @@ -253,11 +245,9 @@ public void setUsage(String usageMessage) { this.usageMessage = usageMessage; } + @Deprecated public static CommandData generateDefaultData() { - if (defaultDataTemplate == null) { - //defaultDataTemplate = new Gson().fromJson(new InputStreamReader(Server.class.getClassLoader().getResourceAsStream("command_default.json"))); - } - return defaultDataTemplate.clone(); + return null; //defaultDataTemplate.clone(); } public static void broadcastCommandMessage(CommandSender source, String message) { @@ -292,7 +282,7 @@ public static void broadcastCommandMessage(CommandSender source, TextContainer m public static void broadcastCommandMessage(CommandSender source, TextContainer message, boolean sendToSource) { TextContainer m = message.clone(); - String resultStr = "[" + source.getName() + ": " + (!m.getText().equals(source.getServer().getLanguage().get(m.getText())) ? "%" : "") + m.getText() + "]"; + String resultStr = '[' + source.getName() + ": " + (!m.getText().equals(source.getServer().getLanguage().get(m.getText())) ? "%" : "") + m.getText() + ']'; Set users = source.getServer().getPluginManager().getPermissionSubscriptions(Server.BROADCAST_CHANNEL_ADMINISTRATIVE); @@ -322,5 +312,4 @@ public static void broadcastCommandMessage(CommandSender source, TextContainer m public String toString() { return this.name; } - } diff --git a/src/main/java/cn/nukkit/command/CommandExecutor.java b/src/main/java/cn/nukkit/command/CommandExecutor.java index 3ad4780b7ba..596906dcece 100644 --- a/src/main/java/cn/nukkit/command/CommandExecutor.java +++ b/src/main/java/cn/nukkit/command/CommandExecutor.java @@ -8,31 +8,30 @@ * @author 粉鞋大妈(javadoc) @ Nukkit Project * @see cn.nukkit.plugin.PluginBase * @see cn.nukkit.command.CommandExecutor#onCommand - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public interface CommandExecutor { /** * 在命令执行时会调用的方法。
* Called when a command is executed. - * - *

一个命令可以是{@code /a_LABEL an_arg1 AN_ARG2...}的形式,这时{@code label}变量的值为{@code "a_label"}, + *

+ * 一个命令可以是{@code /a_LABEL an_arg1 AN_ARG2...}的形式,这时{@code label}变量的值为{@code "a_label"}, * {@code args}数组的元素有{@code "an_arg1","AN_ARG2",...}。注意到{@code label}变量会被转化成小写, * 而{@code args}数组内字符串元素的大小写不变。
* A command can be such a form like {@code /a_LABEL an_arg1 AN_ARG2...}. At this time, the value of * variable {@code label} is {@code "a_label"}, and the values of elements of array {@code args} are * {@code "an_arg1","AN_ARG2",...}. Notice that the value of variable {@code label} will be converted to - * lower case, but the cases of elements of array {@code args} won't change.

- * - *

关于返回值,如果返回{@code false},Nukkit会给sender发送这个命令的使用方法等信息,来表示这个命令没有使用成功。 + * lower case, but the cases of elements of array {@code args} won't change. + *

+ * 关于返回值,如果返回{@code false},Nukkit会给sender发送这个命令的使用方法等信息,来表示这个命令没有使用成功。 * 如果你的命令成功的发挥了作用,你应该返回{@code true}来表示这个命令已执行成功。
* If this function returns {@code false}, Nukkit will send command usages to command sender, to explain that * the command didn't work normally. If your command works properly, a {@code true} should be returned to explain - * that the command works.

- * - *

如果你想测试一个命令发送者是否有权限执行这个命令, + * that the command works. + *

+ * 如果你想测试一个命令发送者是否有权限执行这个命令, * 可以使用{@link cn.nukkit.command.Command#testPermissionSilent}。
* If you want to test whether a command sender has the permission to execute a command, - * you can use {@link cn.nukkit.command.Command#testPermissionSilent}.

+ * you can use {@link cn.nukkit.command.Command#testPermissionSilent}. * * @param sender 这个命令的发送者,可以是玩家或控制台等。
* The sender of this command, this can be a player or a console. @@ -43,7 +42,6 @@ public interface CommandExecutor { * @param args 这个命令的参数列表。
* Arguments of this command. * @return 这个命令执行是否执行成功。
whether this command is executed successfully. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ boolean onCommand(CommandSender sender, Command command, String label, String[] args); } diff --git a/src/main/java/cn/nukkit/command/CommandMap.java b/src/main/java/cn/nukkit/command/CommandMap.java index 0bc577e6746..7d1be68a5f9 100644 --- a/src/main/java/cn/nukkit/command/CommandMap.java +++ b/src/main/java/cn/nukkit/command/CommandMap.java @@ -3,7 +3,7 @@ import java.util.List; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface CommandMap { @@ -21,5 +21,4 @@ public interface CommandMap { void clearCommands(); Command getCommand(String name); - } diff --git a/src/main/java/cn/nukkit/command/CommandSender.java b/src/main/java/cn/nukkit/command/CommandSender.java index 00d6e119138..b90fb51af93 100644 --- a/src/main/java/cn/nukkit/command/CommandSender.java +++ b/src/main/java/cn/nukkit/command/CommandSender.java @@ -7,14 +7,13 @@ /** * 能发送命令的人。
* Who sends commands. - * - *

可以是一个玩家或者一个控制台。
- * That can be a player or a console.

+ *

+ * 可以是一个玩家或者一个控制台。
+ * That can be a player or a console. * * @author MagicDroidX(code) @ Nukkit Project * @author 粉鞋大妈(javadoc) @ Nukkit Project * @see cn.nukkit.command.CommandExecutor#onCommand - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public interface CommandSender extends Permissible { @@ -24,7 +23,6 @@ public interface CommandSender extends Permissible { * * @param message 要发送的信息。
Message to send. * @see cn.nukkit.utils.TextFormat - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ void sendMessage(String message); @@ -33,7 +31,6 @@ public interface CommandSender extends Permissible { * Sends a message to the command sender. * * @param message 要发送的信息。
Message to send. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ void sendMessage(TextContainer message); @@ -42,30 +39,27 @@ public interface CommandSender extends Permissible { * Returns the server of the command sender. * * @return 命令发送者所在的服务器。
the server of the command sender. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ Server getServer(); /** * 返回命令发送者的名称。
* Returns the name of the command sender. - * - *

如果命令发送者是一个玩家,将会返回他的玩家名字(name)不是显示名字(display name)。 + *

+ * 如果命令发送者是一个玩家,将会返回他的玩家名字(name)不是显示名字(display name)。 * 如果命令发送者是控制台,将会返回{@code "CONSOLE"}。
* If this command sender is a player, will return his/her player name(not display name). - * If it is a console, will return {@code "CONSOLE"}.

- *

当你需要判断命令的执行者是不是控制台时,可以用这个:
+ * If it is a console, will return {@code "CONSOLE"}. + * 当你需要判断命令的执行者是不是控制台时,可以用这个:
* When you need to determine if the sender is a console, use this:
- * {@code if(sender instanceof ConsoleCommandSender) .....;}

+ * {@code if (sender instanceof ConsoleCommandSender) .....;} * * @return 命令发送者的名称。
the name of the command sender. * @see cn.nukkit.Player#getName() * @see cn.nukkit.command.ConsoleCommandSender#getName() * @see cn.nukkit.plugin.PluginDescription - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ String getName(); boolean isPlayer(); - } diff --git a/src/main/java/cn/nukkit/command/ConsoleCommandSender.java b/src/main/java/cn/nukkit/command/ConsoleCommandSender.java index 95e363de72d..a2c001ed2f8 100644 --- a/src/main/java/cn/nukkit/command/ConsoleCommandSender.java +++ b/src/main/java/cn/nukkit/command/ConsoleCommandSender.java @@ -12,7 +12,7 @@ import java.util.Map; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ConsoleCommandSender implements CommandSender { @@ -107,6 +107,5 @@ public boolean isOp() { @Override public void setOp(boolean value) { - } } diff --git a/src/main/java/cn/nukkit/command/FormattedCommandAlias.java b/src/main/java/cn/nukkit/command/FormattedCommandAlias.java index 8e84261e176..25126ccb55c 100644 --- a/src/main/java/cn/nukkit/command/FormattedCommandAlias.java +++ b/src/main/java/cn/nukkit/command/FormattedCommandAlias.java @@ -9,7 +9,7 @@ import java.util.List; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class FormattedCommandAlias extends Command { @@ -55,13 +55,13 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) } private String buildCommand(String formatString, String[] args) { - int index = formatString.indexOf("$"); + int index = formatString.indexOf('$'); while (index != -1) { int start = index; if (index > 0 && formatString.charAt(start - 1) == '\\') { formatString = formatString.substring(0, start - 1) + formatString.substring(start); - index = formatString.indexOf("$", index); + index = formatString.indexOf('$', index); continue; } @@ -120,12 +120,12 @@ private String buildCommand(String formatString, String[] args) { replacement.append(args[position]); } - formatString = formatString.substring(0, start) + replacement.toString() + formatString.substring(end); + formatString = formatString.substring(0, start) + replacement + formatString.substring(end); // Move index past the replaced data so we don't process it again index = start + replacement.length(); // Move to the next replacement token - index = formatString.indexOf("$", index); + index = formatString.indexOf('$', index); } return formatString; @@ -134,5 +134,4 @@ private String buildCommand(String formatString, String[] args) { private static boolean inRange(int i, int j, int k) { return i >= j && i <= k; } - } diff --git a/src/main/java/cn/nukkit/command/PluginCommand.java b/src/main/java/cn/nukkit/command/PluginCommand.java index 597ecedfb43..07d07da0a12 100644 --- a/src/main/java/cn/nukkit/command/PluginCommand.java +++ b/src/main/java/cn/nukkit/command/PluginCommand.java @@ -4,7 +4,7 @@ import cn.nukkit.plugin.Plugin; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class PluginCommand extends Command implements PluginIdentifiableCommand { @@ -32,7 +32,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) boolean success = this.executor.onCommand(sender, this, commandLabel, args); - if (!success && !this.usageMessage.equals("")) { + if (!success && !this.usageMessage.isEmpty()) { sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); } diff --git a/src/main/java/cn/nukkit/command/PluginIdentifiableCommand.java b/src/main/java/cn/nukkit/command/PluginIdentifiableCommand.java index c8aaf4c873e..a22ab9446c0 100644 --- a/src/main/java/cn/nukkit/command/PluginIdentifiableCommand.java +++ b/src/main/java/cn/nukkit/command/PluginIdentifiableCommand.java @@ -3,7 +3,7 @@ import cn.nukkit.plugin.Plugin; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface PluginIdentifiableCommand { diff --git a/src/main/java/cn/nukkit/command/RemoteConsoleCommandSender.java b/src/main/java/cn/nukkit/command/RemoteConsoleCommandSender.java index f0d08618309..b2864caea13 100644 --- a/src/main/java/cn/nukkit/command/RemoteConsoleCommandSender.java +++ b/src/main/java/cn/nukkit/command/RemoteConsoleCommandSender.java @@ -8,12 +8,13 @@ * @author Tee7even */ public class RemoteConsoleCommandSender extends ConsoleCommandSender { + private final StringBuilder messages = new StringBuilder(); @Override public void sendMessage(String message) { message = this.getServer().getLanguage().translateString(message); - this.messages.append(message.trim()).append("\n"); + this.messages.append(message.trim()).append('\n'); } @Override @@ -25,6 +26,10 @@ public String getMessages() { return messages.toString(); } + public void clearMessages() { + messages.delete(0, messages.length()); + } + @Override public String getName() { return "Rcon"; diff --git a/src/main/java/cn/nukkit/command/SimpleCommandMap.java b/src/main/java/cn/nukkit/command/SimpleCommandMap.java index 0d5e0da2bfa..cf8402e9123 100644 --- a/src/main/java/cn/nukkit/command/SimpleCommandMap.java +++ b/src/main/java/cn/nukkit/command/SimpleCommandMap.java @@ -5,7 +5,6 @@ import cn.nukkit.command.defaults.*; import cn.nukkit.command.simple.*; import cn.nukkit.lang.TranslationContainer; -import cn.nukkit.utils.MainLogger; import cn.nukkit.utils.TextFormat; import cn.nukkit.utils.Utils; @@ -15,10 +14,11 @@ import java.util.stream.Collectors; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class SimpleCommandMap implements CommandMap { + protected final Map knownCommands = new HashMap<>(); private final Server server; @@ -31,51 +31,46 @@ public SimpleCommandMap(Server server) { private void setDefaultCommands() { this.register("nukkit", new VersionCommand("version")); this.register("nukkit", new PluginsCommand("plugins")); - this.register("nukkit", new SeedCommand("seed")); this.register("nukkit", new HelpCommand("help")); this.register("nukkit", new StopCommand("stop")); this.register("nukkit", new TellCommand("tell")); - this.register("nukkit", new DefaultGamemodeCommand("defaultgamemode")); this.register("nukkit", new BanCommand("ban")); this.register("nukkit", new BanIpCommand("ban-ip")); this.register("nukkit", new BanListCommand("banlist")); this.register("nukkit", new PardonCommand("pardon")); this.register("nukkit", new PardonIpCommand("pardon-ip")); - this.register("nukkit", new SayCommand("say")); - this.register("nukkit", new MeCommand("me")); this.register("nukkit", new ListCommand("list")); - this.register("nukkit", new DifficultyCommand("difficulty")); this.register("nukkit", new KickCommand("kick")); this.register("nukkit", new OpCommand("op")); this.register("nukkit", new DeopCommand("deop")); - this.register("nukkit", new WhitelistCommand("whitelist")); - this.register("nukkit", new SaveOnCommand("save-on")); - this.register("nukkit", new SaveOffCommand("save-off")); - this.register("nukkit", new SaveCommand("save-all")); + this.register("nukkit", new SaveCommand("save")); this.register("nukkit", new GiveCommand("give")); this.register("nukkit", new ClearCommand("clear")); this.register("nukkit", new EffectCommand("effect")); this.register("nukkit", new EnchantCommand("enchant")); - this.register("nukkit", new ParticleCommand("particle")); this.register("nukkit", new GamemodeCommand("gamemode")); - this.register("nukkit", new GameruleCommand("gamerule")); this.register("nukkit", new KillCommand("kill")); - this.register("nukkit", new SpawnpointCommand("spawnpoint")); this.register("nukkit", new SetWorldSpawnCommand("setworldspawn")); this.register("nukkit", new TeleportCommand("tp")); this.register("nukkit", new TimeCommand("time")); - this.register("nukkit", new TitleCommand("title")); this.register("nukkit", new ReloadCommand("reload")); this.register("nukkit", new WeatherCommand("weather")); this.register("nukkit", new XpCommand("xp")); - -// if ((boolean) this.server.getConfig("debug.commands", false)) { this.register("nukkit", new StatusCommand("status")); + this.register("nukkit", new SummonCommand("summon")); + this.register("nukkit", new WhitelistCommand("whitelist")); + this.register("nukkit", new GameruleCommand("gamerule")); + this.register("nukkit", new ConvertCommand("convert")); + this.register("nukkit", new DefaultGamemodeCommand("defaultgamemode")); + this.register("nukkit", new SayCommand("say")); + this.register("nukkit", new MeCommand("me")); + this.register("nukkit", new DifficultyCommand("difficulty")); + this.register("nukkit", new ParticleCommand("particle")); + this.register("nukkit", new SpawnpointCommand("spawnpoint")); + this.register("nukkit", new TitleCommand("title")); + this.register("nukkit", new SeedCommand("seed")); + this.register("nukkit", new PlaySoundCommand("playsound")); this.register("nukkit", new GarbageCollectorCommand("gc")); - this.register("nukkit", new TimingsCommand("timings")); - //this.register("nukkit", new DebugPasteCommand("debugpaste")); // No more unauthenticated API access, TODO: find a replacement for hastebin.com - //this.register("nukkit", new DumpMemoryCommand("dumpmemory")); -// } } @Override @@ -111,7 +106,7 @@ public boolean register(String fallbackPrefix, Command command, String label) { command.setAliases(aliases.toArray(new String[0])); if (!registered) { - command.setLabel(fallbackPrefix + ":" + label); + command.setLabel(fallbackPrefix + ':' + label); } command.register(this); @@ -145,7 +140,7 @@ public void registerSimpleCommands(Object object) { if (commandParameters != null) { Map map = Arrays.stream(commandParameters.parameters()) .collect(Collectors.toMap(Parameters::name, parameters -> Arrays.stream(parameters.parameters()) - .map(parameter -> CommandParameter.newType(parameter.name(), parameter.optional(), parameter.type())) + .map(parameter -> new CommandParameter(parameter.name(), parameter.type(), parameter.optional())) .distinct() .toArray(CommandParameter[]::new))); @@ -158,7 +153,7 @@ public void registerSimpleCommands(Object object) { } private boolean registerAlias(Command command, boolean isAlias, String fallbackPrefix, String label) { - this.knownCommands.put(fallbackPrefix + ":" + label, command); + this.knownCommands.put(fallbackPrefix + ':' + label, command); //if you're registering a command alias that is already registered, then return false boolean alreadyRegistered = this.knownCommands.containsKey(label); @@ -169,15 +164,15 @@ private boolean registerAlias(Command command, boolean isAlias, String fallbackP return false; } - //if you're registering a name (alias or label) which is identical to another command who's primary name is the same - //so basically we can't override the main name of a command, but we can override aliases if we're not an alias + // If you're registering a name (alias or label) which is identical to another command who's primary name is the same + // So basically we can't override the main name of a command, but we can override aliases if we're not an alias - //added the last statement which will allow us to override a VanillaCommand unconditionally + // Added the last statement which will allow us to override a VanillaCommand unconditionally if (alreadyRegistered && existingCommand.getLabel() != null && existingCommand.getLabel().equals(label) && existingCommandIsNotVanilla) { return false; } - //you can now assume that the command is either uniquely named, or overriding another command's alias (and is not itself, an alias) + // You can now assume that the command is either uniquely named, or overriding another command's alias (and is not itself, an alias) if (!isAlias) { command.setLabel(label); @@ -206,7 +201,7 @@ private boolean registerAlias(Command command, boolean isAlias, String fallbackP return true; } - private ArrayList parseArguments(String cmdLine) { + private static ArrayList parseArguments(String cmdLine) { StringBuilder sb = new StringBuilder(cmdLine); ArrayList args = new ArrayList<>(); boolean notQuoted = true; @@ -241,7 +236,7 @@ private ArrayList parseArguments(String cmdLine) { @Override public boolean dispatch(CommandSender sender, String cmdLine) { ArrayList parsed = parseArguments(cmdLine); - if (parsed.size() == 0) { + if (parsed.isEmpty()) { return false; } @@ -253,18 +248,12 @@ public boolean dispatch(CommandSender sender, String cmdLine) { return false; } - target.timing.startTiming(); try { target.execute(sender, sentCommandLabel, args); } catch (Exception e) { sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.exception")); - this.server.getLogger().critical(this.server.getLanguage().translateString("nukkit.command.exception", cmdLine, target.toString(), Utils.getExceptionMessage(e))); - MainLogger logger = sender.getServer().getLogger(); - if (logger != null) { - logger.logException(e); - } + this.server.getLogger().critical(this.server.getLanguage().translateString("nukkit.command.exception", cmdLine, target.toString(), Utils.getExceptionMessage(e)), e); } - target.timing.stopTiming(); return true; } @@ -280,10 +269,7 @@ public void clearCommands() { @Override public Command getCommand(String name) { - if (this.knownCommands.containsKey(name)) { - return this.knownCommands.get(name); - } - return null; + return this.knownCommands.get(name); } public Map getCommands() { diff --git a/src/main/java/cn/nukkit/command/data/CommandArgs.java b/src/main/java/cn/nukkit/command/data/CommandArgs.java deleted file mode 100644 index 3c369db69f9..00000000000 --- a/src/main/java/cn/nukkit/command/data/CommandArgs.java +++ /dev/null @@ -1,9 +0,0 @@ -package cn.nukkit.command.data; - -import com.google.gson.JsonElement; - -import java.util.HashMap; - -public class CommandArgs extends HashMap { - -} diff --git a/src/main/java/cn/nukkit/command/data/CommandDataVersions.java b/src/main/java/cn/nukkit/command/data/CommandDataVersions.java index 0434d8542e4..6950dee9917 100644 --- a/src/main/java/cn/nukkit/command/data/CommandDataVersions.java +++ b/src/main/java/cn/nukkit/command/data/CommandDataVersions.java @@ -6,5 +6,4 @@ public class CommandDataVersions { public List versions = new ArrayList<>(); - } diff --git a/src/main/java/cn/nukkit/command/data/CommandEnum.java b/src/main/java/cn/nukkit/command/data/CommandEnum.java index 6e18e36039b..a9e8f4d49c8 100644 --- a/src/main/java/cn/nukkit/command/data/CommandEnum.java +++ b/src/main/java/cn/nukkit/command/data/CommandEnum.java @@ -2,9 +2,11 @@ import cn.nukkit.block.BlockID; import cn.nukkit.item.ItemID; +import cn.nukkit.potion.Effect; import com.google.common.collect.ImmutableList; import java.lang.reflect.Field; +import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List; @@ -14,10 +16,11 @@ public class CommandEnum { public static final CommandEnum ENUM_BOOLEAN = new CommandEnum("Boolean", ImmutableList.of("true", "false")); - public static final CommandEnum ENUM_GAMEMODE = new CommandEnum("GameMode", - ImmutableList.of("survival", "creative", "s", "c", "adventure", "a", "spectator", "view", "v", "spc")); + public static final CommandEnum ENUM_GAMEMODE = new CommandEnum("GameMode", ImmutableList.of("default", "creative", "spectator", "survival", "adventure", "d", "c", "s", "a")); + public static final CommandEnum ENUM_DIFFICULTY = new CommandEnum("Difficulty", ImmutableList.of("peaceful", "p", "easy", "e", "normal", "n", "hard", "h")); public static final CommandEnum ENUM_BLOCK; public static final CommandEnum ENUM_ITEM; + public static final CommandEnum ENUM_EFFECTS; static { ImmutableList.Builder blocks = ImmutableList.builder(); @@ -32,10 +35,18 @@ public class CommandEnum { } items.addAll(ENUM_BLOCK.getValues()); ENUM_ITEM = new CommandEnum("Item", items.build()); + + ImmutableList.Builder effects = ImmutableList.builder(); + for (Field field : Effect.class.getDeclaredFields()) { + if (field.getType() == int.class && field.getModifiers() == (Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL)) { + effects.add(field.getName().toLowerCase()); + } + } + ENUM_EFFECTS = new CommandEnum("Effect", effects.build()); } - private String name; - private List values; + private final String name; + private final List values; public CommandEnum(String name, String... values) { this(name, Arrays.asList(values)); diff --git a/src/main/java/cn/nukkit/command/data/CommandInput.java b/src/main/java/cn/nukkit/command/data/CommandInput.java index 9fb056dc5a0..124e916320d 100644 --- a/src/main/java/cn/nukkit/command/data/CommandInput.java +++ b/src/main/java/cn/nukkit/command/data/CommandInput.java @@ -3,5 +3,4 @@ public class CommandInput { public CommandParameter[] parameters = new CommandParameter[0]; - } diff --git a/src/main/java/cn/nukkit/command/data/CommandOutput.java b/src/main/java/cn/nukkit/command/data/CommandOutput.java deleted file mode 100644 index cc168f58506..00000000000 --- a/src/main/java/cn/nukkit/command/data/CommandOutput.java +++ /dev/null @@ -1,7 +0,0 @@ -package cn.nukkit.command.data; - -public class CommandOutput { - - public String[] format_strings = new String[0]; - -} diff --git a/src/main/java/cn/nukkit/command/data/CommandOverload.java b/src/main/java/cn/nukkit/command/data/CommandOverload.java index 7b2bbd31696..48d8a311725 100644 --- a/src/main/java/cn/nukkit/command/data/CommandOverload.java +++ b/src/main/java/cn/nukkit/command/data/CommandOverload.java @@ -3,6 +3,4 @@ public class CommandOverload { public CommandInput input = new CommandInput(); - public CommandOutput output = new CommandOutput(); - } diff --git a/src/main/java/cn/nukkit/command/data/CommandParamType.java b/src/main/java/cn/nukkit/command/data/CommandParamType.java index 8f109fa4850..a4e05316377 100644 --- a/src/main/java/cn/nukkit/command/data/CommandParamType.java +++ b/src/main/java/cn/nukkit/command/data/CommandParamType.java @@ -6,6 +6,7 @@ * @author CreeperFace */ public enum CommandParamType { + INT(ARG_TYPE_INT), FLOAT(ARG_TYPE_FLOAT), VALUE(ARG_TYPE_VALUE), @@ -37,4 +38,4 @@ public enum CommandParamType { public int getId() { return id; } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/command/data/args/CommandArg.java b/src/main/java/cn/nukkit/command/data/args/CommandArg.java deleted file mode 100644 index c2f8a888b5f..00000000000 --- a/src/main/java/cn/nukkit/command/data/args/CommandArg.java +++ /dev/null @@ -1,15 +0,0 @@ -package cn.nukkit.command.data.args; - -public class CommandArg { - - private CommandArgRules[] rules; - private String selector; - - public CommandArgRules[] getRules() { - return rules; - } - - public String getSelector() { - return selector; - } -} diff --git a/src/main/java/cn/nukkit/command/data/args/CommandArgBlockVector.java b/src/main/java/cn/nukkit/command/data/args/CommandArgBlockVector.java deleted file mode 100644 index 83cc78b7ca8..00000000000 --- a/src/main/java/cn/nukkit/command/data/args/CommandArgBlockVector.java +++ /dev/null @@ -1,35 +0,0 @@ -package cn.nukkit.command.data.args; - -public class CommandArgBlockVector { - - private int x; - private int y; - private int z; - private boolean xrelative; - private boolean yrelative; - private boolean zrelative; - - public int getX() { - return x; - } - - public int getY() { - return y; - } - - public int getZ() { - return z; - } - - public boolean isXrelative() { - return xrelative; - } - - public boolean isYrelative() { - return yrelative; - } - - public boolean isZrelative() { - return zrelative; - } -} diff --git a/src/main/java/cn/nukkit/command/data/args/CommandArgRules.java b/src/main/java/cn/nukkit/command/data/args/CommandArgRules.java deleted file mode 100644 index e719c44c2a1..00000000000 --- a/src/main/java/cn/nukkit/command/data/args/CommandArgRules.java +++ /dev/null @@ -1,21 +0,0 @@ -package cn.nukkit.command.data.args; - -public class CommandArgRules { - - private boolean inverted; - private String name; - private String value; - - public boolean isInverted() { - return inverted; - } - - public String getName() { - return name; - } - - public String getValue() { - return value; - } - -} diff --git a/src/main/java/cn/nukkit/command/defaults/BanCommand.java b/src/main/java/cn/nukkit/command/defaults/BanCommand.java index 33282b8c4c4..3cb1ba11909 100644 --- a/src/main/java/cn/nukkit/command/defaults/BanCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/BanCommand.java @@ -9,7 +9,7 @@ import cn.nukkit.lang.TranslationContainer; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BanCommand extends VanillaCommand { @@ -20,7 +20,7 @@ public BanCommand(String name) { this.commandParameters.clear(); this.commandParameters.put("default", new CommandParameter[]{ - CommandParameter.newType("player", CommandParamType.TARGET), + CommandParameter.newType("player", false, CommandParamType.TARGET), CommandParameter.newType("reason", true, CommandParamType.STRING) }); } @@ -40,7 +40,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) String name = args[0].replace("@s", sender.getName()); StringBuilder reason = new StringBuilder(); for (int i = 1; i < args.length; i++) { - reason.append(args[i]).append(" "); + reason.append(args[i]).append(' '); } if (reason.length() > 0) { @@ -51,7 +51,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) Player player = sender.getServer().getPlayerExact(name); if (player != null) { - player.kick(PlayerKickEvent.Reason.NAME_BANNED, (reason.length() > 0) ? "Banned by admin. Reason: " + reason : "Banned by admin"); + player.kick(PlayerKickEvent.Reason.NAME_BANNED, (reason.length() > 0) ? "You are banned! Reason: " + reason : "You are banned!", true); } Command.broadcastCommandMessage(sender, new TranslationContainer("%commands.ban.success", player != null ? player.getName() : name)); diff --git a/src/main/java/cn/nukkit/command/defaults/BanIpCommand.java b/src/main/java/cn/nukkit/command/defaults/BanIpCommand.java index 7a1b48bb89e..e8c7d7c4948 100644 --- a/src/main/java/cn/nukkit/command/defaults/BanIpCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/BanIpCommand.java @@ -11,15 +11,14 @@ import cn.nukkit.nbt.tag.CompoundTag; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; -import java.util.ArrayList; +import java.nio.file.Files; import java.util.regex.Pattern; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BanIpCommand extends VanillaCommand { @@ -54,7 +53,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) String value = args[0]; StringBuilder reason = new StringBuilder(); for (int i = 1; i < args.length; i++) { - reason.append(args[i]).append(" "); + reason.append(args[i]).append(' '); } if (reason.length() > 0) { @@ -62,13 +61,13 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) } if (Pattern.matches("^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$", value)) { - this.processIPBan(value, sender, reason.toString()); + processIPBan(value, sender, reason.toString()); Command.broadcastCommandMessage(sender, new TranslationContainer("commands.banip.success", value)); } else { - Player player = sender.getServer().getPlayer(value); + Player player = sender.getServer().getPlayerExact(value); if (player != null) { - this.processIPBan(player.getAddress(), sender, reason.toString()); + processIPBan(player.getAddress(), sender, reason.toString()); Command.broadcastCommandMessage(sender, new TranslationContainer("commands.banip.success.players", player.getAddress(), player.getName())); } else { @@ -78,14 +77,14 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) CompoundTag nbt = null; if (file.exists()) { try { - nbt = NBTIO.readCompressed(new FileInputStream(file)); + nbt = NBTIO.readCompressed(Files.newInputStream(file.toPath())); } catch (IOException e) { throw new RuntimeException(e); } } if (nbt != null && nbt.contains("lastIP") && Pattern.matches("^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$", (value = nbt.getString("lastIP")))) { - this.processIPBan(value, sender, reason.toString()); + processIPBan(value, sender, reason.toString()); Command.broadcastCommandMessage(sender, new TranslationContainer("commands.banip.success", value)); } else { @@ -98,19 +97,17 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) return true; } - private void processIPBan(String ip, CommandSender sender, String reason) { + private static void processIPBan(String ip, CommandSender sender, String reason) { sender.getServer().getIPBans().addBan(ip, reason, null, sender.getName()); - for (Player player : new ArrayList<>(sender.getServer().getOnlinePlayers().values())) { + for (Player player : sender.getServer().getOnlinePlayers().values()) { if (player.getAddress().equals(ip)) { - player.kick(PlayerKickEvent.Reason.IP_BANNED, !reason.isEmpty() ? reason : "IP banned"); + player.kick(PlayerKickEvent.Reason.IP_BANNED, !reason.isEmpty() ? reason : "IP banned", true); } } try { - sender.getServer().getNetwork().blockAddress(InetAddress.getByName(ip), -1); - } catch (UnknownHostException e) { - // ignore - } + sender.getServer().getNetwork().blockAddress(InetAddress.getByName(ip)); + } catch (UnknownHostException ignore) {} } } diff --git a/src/main/java/cn/nukkit/command/defaults/BanListCommand.java b/src/main/java/cn/nukkit/command/defaults/BanListCommand.java index 0ca654c4e88..e0594ec608a 100644 --- a/src/main/java/cn/nukkit/command/defaults/BanListCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/BanListCommand.java @@ -14,6 +14,7 @@ * Package cn.nukkit.command.defaults in project Nukkit . */ public class BanListCommand extends VanillaCommand { + public BanListCommand(String name) { super(name, "%nukkit.command.banlist.description", "%commands.banlist.usage"); this.setPermission("nukkit.command.ban.list"); diff --git a/src/main/java/cn/nukkit/command/defaults/ClearCommand.java b/src/main/java/cn/nukkit/command/defaults/ClearCommand.java index fad7ba1074e..5a7cc71c5ca 100644 --- a/src/main/java/cn/nukkit/command/defaults/ClearCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/ClearCommand.java @@ -9,14 +9,14 @@ import cn.nukkit.lang.TranslationContainer; import cn.nukkit.utils.TextFormat; -import java.util.ArrayList; -import java.util.List; +import java.util.Collection; +import java.util.Collections; /** - * Created on 2024/26/2 by Sherko231. - * Package cn.nukkit.command.defaults in project Nukkit . + * @author Sherko231 */ public class ClearCommand extends VanillaCommand { + public ClearCommand(String name) { super(name, "%nukkit.command.clear.description", "%nukkit.command.clear.usage"); this.setPermission("nukkit.command.clear"); @@ -38,16 +38,14 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) return false; } - List targets = new ArrayList<>(); + Collection targets; if (args[0].equals("@a")) { - targets.addAll(Server.getInstance().getOnlinePlayers().values()); - } - else { - Player target = sender.getServer().getPlayer(args[0].replace("@s", sender.getName())); + targets = Server.getInstance().getOnlinePlayers().values(); + } else { + Player target = sender.getServer().getPlayerExact(args[0].replace("@s", sender.getName())); if (target != null) { - targets.add(target); - } - else { + targets = Collections.singletonList(target); + } else { sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.player.notFound")); return false; } diff --git a/src/main/java/cn/nukkit/command/defaults/ConvertCommand.java b/src/main/java/cn/nukkit/command/defaults/ConvertCommand.java new file mode 100644 index 00000000000..5a1092d946f --- /dev/null +++ b/src/main/java/cn/nukkit/command/defaults/ConvertCommand.java @@ -0,0 +1,80 @@ +package cn.nukkit.command.defaults; + +import cn.nukkit.Player; +import cn.nukkit.Server; +import cn.nukkit.command.CommandSender; +import cn.nukkit.command.data.CommandParamType; +import cn.nukkit.command.data.CommandParameter; +import cn.nukkit.lang.TranslationContainer; +import cn.nukkit.level.Level; +import cn.nukkit.level.format.generic.Anvil2LevelDBConverter; +import cn.nukkit.level.format.leveldb.LevelDBProvider; + +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +public class ConvertCommand extends VanillaCommand { + + private static final Set CONVERSION_IN_PROGRESS = ConcurrentHashMap.newKeySet(); + + public ConvertCommand(String name) { + super(name, "%nukkit.command.world.convert.description", "%nukkit.command.world.convert.usage"); + this.setPermission("nukkit.command.world.convert"); + this.commandParameters.clear(); + this.commandParameters.put("default", new CommandParameter[]{ + CommandParameter.newType("world", CommandParamType.STRING) + }); + } + + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + if (!this.testPermission(sender)) { + return true; + } + + if (sender instanceof Player) { + sender.sendMessage("§cThis command can be used only via console"); + return true; + } + + if (args.length < 1) { + sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); + return false; + } + + String worldName = String.join(" ", args); + Level level = Server.getInstance().getLevelByName(worldName); + if (level == null) { + sender.sendMessage("Unknown level: " + worldName); + return true; + } + + if (level.getProvider() instanceof LevelDBProvider) { + sender.sendMessage(worldName + " is already in LevelDB format"); + return true; + } + + if (!level.getPlayers().isEmpty()) { + sender.sendMessage(worldName + " has players in it! Make sure the world is not used while it's being converted"); + return true; + } + + if (CONVERSION_IN_PROGRESS.contains(worldName)) { + sender.sendMessage(worldName + " is already being converted"); + return true; + } + + CONVERSION_IN_PROGRESS.add(worldName); + + Anvil2LevelDBConverter converter = new Anvil2LevelDBConverter(level); + converter.convert().whenComplete((ignore, error) -> { + if (error != null) { + sender.sendMessage("Error during conversion!"); + Server.getInstance().getLogger().logException(error); + } + + CONVERSION_IN_PROGRESS.remove(worldName); + }); + return true; + } +} diff --git a/src/main/java/cn/nukkit/command/defaults/DebugPasteCommand.java b/src/main/java/cn/nukkit/command/defaults/DebugPasteCommand.java deleted file mode 100644 index 57e765d08bb..00000000000 --- a/src/main/java/cn/nukkit/command/defaults/DebugPasteCommand.java +++ /dev/null @@ -1,90 +0,0 @@ -package cn.nukkit.command.defaults; - -import cn.nukkit.Server; -import cn.nukkit.command.CommandSender; -import cn.nukkit.network.protocol.ProtocolInfo; -import cn.nukkit.plugin.Plugin; -import cn.nukkit.plugin.PluginDescription; -import cn.nukkit.scheduler.AsyncTask; -import cn.nukkit.utils.HastebinUtility; -import cn.nukkit.utils.MainLogger; -import cn.nukkit.utils.Utils; -import java.io.File; -import java.io.IOException; -import java.lang.management.ManagementFactory; - -public class DebugPasteCommand extends VanillaCommand { - - public DebugPasteCommand(String name) { - super(name, "%nukkit.command.debug.description", "%nukkit.command.debug.usage"); - this.setPermission("nukkit.command.debug.perform"); - this.commandParameters.clear(); - } - - @Override - public boolean execute(CommandSender sender, String commandLabel, String[] args) { - if (!this.testPermission(sender)) { - return true; - } - Server server = Server.getInstance(); - server.getScheduler().scheduleAsyncTask(new AsyncTask() { - @Override - public void onRun() { - try { - new StatusCommand("status").execute(server.getConsoleSender(), "status", new String[]{}); - String dataPath = server.getDataPath(); - String nukkitYML = HastebinUtility.upload(new File(dataPath, "nukkit.yml")); - String serverProperties = HastebinUtility.upload(new File(dataPath, "server.properties")); - String latestLog = HastebinUtility.upload(new File(dataPath, "/logs/server.log")); - String threadDump = HastebinUtility.upload(Utils.getAllThreadDumps()); - - StringBuilder b = new StringBuilder(); - b.append("# Files\n"); - b.append("links.nukkit_yml: ").append(nukkitYML).append('\n'); - b.append("links.server_properties: ").append(serverProperties).append('\n'); - b.append("links.server_log: ").append(latestLog).append('\n'); - b.append("links.thread_dump: ").append(threadDump).append('\n'); - b.append("\n# Server Information\n"); - - b.append("version.api: ").append(server.getApiVersion()).append('\n'); - b.append("version.nukkit: ").append(server.getNukkitVersion()).append('\n'); - b.append("version.minecraft: ").append(server.getVersion()).append('\n'); - b.append("version.protocol: ").append(ProtocolInfo.CURRENT_PROTOCOL).append('\n'); - b.append("plugins:"); - for (Plugin plugin : server.getPluginManager().getPlugins().values()) { - boolean enabled = plugin.isEnabled(); - String name = plugin.getName(); - PluginDescription desc = plugin.getDescription(); - String version = desc.getVersion(); - b.append("\n ") - .append(name) - .append(":\n ") - .append("version: '") - .append(version) - .append('\'') - .append("\n enabled: ") - .append(enabled); - } - b.append("\n\n# Java Details\n"); - Runtime runtime = Runtime.getRuntime(); - b.append("memory.free: ").append(runtime.freeMemory()).append('\n'); - b.append("memory.max: ").append(runtime.maxMemory()).append('\n'); - b.append("cpu.runtime: ").append(ManagementFactory.getRuntimeMXBean().getUptime()).append('\n'); - b.append("cpu.processors: ").append(runtime.availableProcessors()).append('\n'); - b.append("java.specification.version: '").append(System.getProperty("java.specification.version")).append("'\n"); - b.append("java.vendor: '").append(System.getProperty("java.vendor")).append("'\n"); - b.append("java.version: '").append(System.getProperty("java.version")).append("'\n"); - b.append("os.arch: '").append(System.getProperty("os.arch")).append("'\n"); - b.append("os.name: '").append(System.getProperty("os.name")).append("'\n"); - b.append("os.version: '").append(System.getProperty("os.version")).append("'\n\n"); - b.append("\n# Create a ticket: https://github.com/NukkitX/Nukkit/issues/new"); - String link = HastebinUtility.upload(b.toString()); - sender.sendMessage(link); - } catch (IOException e) { - MainLogger.getLogger().logException(e); - } - } - }); - return true; - } -} diff --git a/src/main/java/cn/nukkit/command/defaults/DefaultGamemodeCommand.java b/src/main/java/cn/nukkit/command/defaults/DefaultGamemodeCommand.java index 73604ce3cd3..bd2333ea268 100644 --- a/src/main/java/cn/nukkit/command/defaults/DefaultGamemodeCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/DefaultGamemodeCommand.java @@ -1,11 +1,14 @@ package cn.nukkit.command.defaults; import cn.nukkit.Server; +import cn.nukkit.command.Command; import cn.nukkit.command.CommandSender; import cn.nukkit.command.data.CommandEnum; import cn.nukkit.command.data.CommandParamType; import cn.nukkit.command.data.CommandParameter; import cn.nukkit.lang.TranslationContainer; +import cn.nukkit.network.protocol.SetDefaultGameTypePacket; +import cn.nukkit.utils.TextFormat; /** * Created on 2015/11/12 by xtypr. @@ -31,15 +34,21 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) return true; } if (args.length == 0) { - sender.sendMessage(new TranslationContainer("commands.generic.usage", new String[]{this.usageMessage})); + sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); return false; } int gameMode = Server.getGamemodeFromString(args[0]); if (gameMode != -1) { sender.getServer().setPropertyInt("gamemode", gameMode); + sender.getServer().gamemode = gameMode; sender.sendMessage(new TranslationContainer("commands.defaultgamemode.success", new String[]{Server.getGamemodeString(gameMode)})); + Command.broadcastCommandMessage(sender, new TranslationContainer("commands.defaultgamemode.success", new String[]{Server.getGamemodeString(sender.getServer().getDefaultGamemode())})); + + SetDefaultGameTypePacket gameTypePacket = new SetDefaultGameTypePacket(); + gameTypePacket.gamemode = sender.getServer().getDefaultGamemode(); + Server.broadcastPacket(sender.getServer().getOnlinePlayers().values(), gameTypePacket); } else { - sender.sendMessage("Unknown game mode"); // + sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.gamemode.fail.invalid", args[0])); } return true; } diff --git a/src/main/java/cn/nukkit/command/defaults/DeopCommand.java b/src/main/java/cn/nukkit/command/defaults/DeopCommand.java index 08ba7b58c16..49c533297b6 100644 --- a/src/main/java/cn/nukkit/command/defaults/DeopCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/DeopCommand.java @@ -14,9 +14,11 @@ * Package cn.nukkit.command.defaults in project Nukkit . */ public class DeopCommand extends VanillaCommand { + public DeopCommand(String name) { super(name, "%nukkit.command.deop.description", "%commands.deop.description"); this.setPermission("nukkit.command.op.take"); + this.commandParameters.clear(); this.commandParameters.put("default", new CommandParameter[]{ CommandParameter.newType("player", CommandParamType.TARGET) }); @@ -34,16 +36,16 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) return false; } - String playerName = args[0].replace("@s", sender.getName()); - IPlayer player = sender.getServer().getOfflinePlayer(playerName); - player.setOp(false); - + String name = args[0].replace("@s", sender.getName()); + IPlayer player = sender.getServer().getOfflinePlayer(name); if (player instanceof Player) { + player.setOp(false); ((Player) player).sendMessage(new TranslationContainer(TextFormat.GRAY + "%commands.deop.message")); + } else { + sender.getServer().removeOp(name); } Command.broadcastCommandMessage(sender, new TranslationContainer("commands.deop.success", new String[]{player.getName()})); - return true; } } diff --git a/src/main/java/cn/nukkit/command/defaults/DifficultyCommand.java b/src/main/java/cn/nukkit/command/defaults/DifficultyCommand.java index 1b0dcf97a53..dbf725d089c 100644 --- a/src/main/java/cn/nukkit/command/defaults/DifficultyCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/DifficultyCommand.java @@ -9,8 +9,6 @@ import cn.nukkit.lang.TranslationContainer; import cn.nukkit.network.protocol.SetDifficultyPacket; -import java.util.ArrayList; - /** * Created on 2015/11/12 by xtypr. * Package cn.nukkit.command.defaults in project Nukkit . @@ -25,7 +23,7 @@ public DifficultyCommand(String name) { CommandParameter.newType("difficulty", CommandParamType.INT) }); this.commandParameters.put("byString", new CommandParameter[]{ - CommandParameter.newEnum("difficulty", new CommandEnum("Difficulty", "peaceful", "p", "easy", "e", "normal", "n", "hard", "h")) + CommandParameter.newEnum("difficulty", CommandEnum.ENUM_DIFFICULTY) }); } @@ -51,7 +49,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) SetDifficultyPacket pk = new SetDifficultyPacket(); pk.difficulty = sender.getServer().getDifficulty(); - Server.broadcastPacket(new ArrayList<>(sender.getServer().getOnlinePlayers().values()), pk); + Server.broadcastPacket(sender.getServer().getOnlinePlayers().values(), pk); Command.broadcastCommandMessage(sender, new TranslationContainer("commands.difficulty.success", String.valueOf(difficulty))); } else { diff --git a/src/main/java/cn/nukkit/command/defaults/EffectCommand.java b/src/main/java/cn/nukkit/command/defaults/EffectCommand.java index 58697cc68f9..e348c2b5122 100644 --- a/src/main/java/cn/nukkit/command/defaults/EffectCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/EffectCommand.java @@ -13,31 +13,19 @@ import cn.nukkit.utils.ServerException; import cn.nukkit.utils.TextFormat; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.List; - /** * Created by Snake1999 and Pub4Game on 2016/1/23. * Package cn.nukkit.command.defaults in project nukkit. */ -public class EffectCommand extends Command { +public class EffectCommand extends VanillaCommand { + public EffectCommand(String name) { super(name, "%nukkit.command.effect.description", "%commands.effect.usage"); this.setPermission("nukkit.command.effect"); this.commandParameters.clear(); - - List effects = new ArrayList<>(); - for (Field field : Effect.class.getDeclaredFields()) { - if (field.getType() == int.class && field.getModifiers() == (Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL)) { - effects.add(field.getName().toLowerCase()); - } - } - this.commandParameters.put("default", new CommandParameter[]{ CommandParameter.newType("player", CommandParamType.TARGET), - CommandParameter.newEnum("effect", new CommandEnum("Effect", effects)), + CommandParameter.newEnum("effect", CommandEnum.ENUM_EFFECTS), CommandParameter.newType("seconds", true, CommandParamType.INT), CommandParameter.newType("amplifier", true, CommandParamType.INT), CommandParameter.newEnum("hideParticle", true, CommandEnum.ENUM_BOOLEAN) @@ -57,7 +45,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); return true; } - Player player = sender.getServer().getPlayer(args[0].replace("@s", sender.getName())); + Player player = sender.getServer().getPlayerExact(args[0].replace("@s", sender.getName())); if (player == null) { sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.player.notFound")); return true; @@ -77,7 +65,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) sender.sendMessage(new TranslationContainer("commands.effect.notFound", args[1])); return true; } - int duration = 300; + int duration = 600; int amplification = 0; if (args.length >= 3) { try { @@ -108,7 +96,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) } if (duration == 0) { if (!player.hasEffect(effect.getId())) { - if (player.getEffects().size() == 0) { + if (player.getEffects().isEmpty()) { sender.sendMessage(new TranslationContainer("commands.effect.failure.notActive.all", player.getDisplayName())); } else { sender.sendMessage(new TranslationContainer("commands.effect.failure.notActive", effect.getName(), player.getDisplayName())); diff --git a/src/main/java/cn/nukkit/command/defaults/EnchantCommand.java b/src/main/java/cn/nukkit/command/defaults/EnchantCommand.java index 77228636b95..080c1619da7 100644 --- a/src/main/java/cn/nukkit/command/defaults/EnchantCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/EnchantCommand.java @@ -32,7 +32,7 @@ public EnchantCommand(String name) { "aqua_affinity", "depth_strider", "sharpness", "smite", "bane_of_arthropods", "knockback", "fire_aspect", "looting", "efficiency", "silk_touch", "durability", "fortune", "power", "punch", "flame", "infinity", "luck_of_the_sea", "lure", "frost_walker", "mending", "binding_curse", "vanishing_curse", "impaling", "loyalty", "riptide", "channeling", "multishot", "piercing", "quick_charge", - "soul_speed")), + "soul_speed", "swift_sneak")), CommandParameter.newType("level", true, CommandParamType.INT) }); } @@ -46,7 +46,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); return true; } - Player player = sender.getServer().getPlayer(args[0].replace("@s", sender.getName())); + Player player = sender.getServer().getPlayerExact(args[0].replace("@s", sender.getName())); if (player == null) { sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.player.notFound")); return true; @@ -73,7 +73,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) } item.addEnchantment(enchantment); player.getInventory().setItemInHand(item); - Command.broadcastCommandMessage(sender, new TranslationContainer("%commands.enchant.success")); + Command.broadcastCommandMessage(sender, new TranslationContainer("%commands.enchant.success", player.getDisplayName())); return true; } @@ -88,7 +88,7 @@ public int getIdByName(String value) throws NumberFormatException { return 2; case "blast_protection": return 3; - case "projectile_projection": + case "projectile_protection": return 4; case "thorns": return 5; diff --git a/src/main/java/cn/nukkit/command/defaults/GamemodeCommand.java b/src/main/java/cn/nukkit/command/defaults/GamemodeCommand.java index ef43d0476fb..e22a00484ff 100644 --- a/src/main/java/cn/nukkit/command/defaults/GamemodeCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/GamemodeCommand.java @@ -44,14 +44,14 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) int gameMode = Server.getGamemodeFromString(args[0]); if (gameMode == -1) { - sender.sendMessage("Unknown game mode"); + sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.gamemode.fail.invalid", args[0])); return true; } CommandSender target = sender; if (args.length > 1) { if (sender.hasPermission("nukkit.command.gamemode.other")) { - target = sender.getServer().getPlayer(args[1].replace("@s", sender.getName())); + target = sender.getServer().getPlayerExact(args[1].replace("@s", sender.getName())); if (target == null) { sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.player.notFound")); return true; @@ -79,7 +79,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) if (target.equals(sender)) { Command.broadcastCommandMessage(sender, new TranslationContainer("commands.gamemode.success.self", Server.getGamemodeString(gameMode))); } else { - target.sendMessage(new TranslationContainer("gameMode.changed", Server.getGamemodeString(gameMode))); + target.sendMessage(new TranslationContainer("gameMode.changed")); Command.broadcastCommandMessage(sender, new TranslationContainer("commands.gamemode.success.other", target.getName(), Server.getGamemodeString(gameMode))); } } diff --git a/src/main/java/cn/nukkit/command/defaults/GameruleCommand.java b/src/main/java/cn/nukkit/command/defaults/GameruleCommand.java index 1015a4cc662..d0b79299af8 100644 --- a/src/main/java/cn/nukkit/command/defaults/GameruleCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/GameruleCommand.java @@ -9,16 +9,12 @@ import cn.nukkit.level.GameRule; import cn.nukkit.level.GameRules; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.StringJoiner; +import java.util.*; public class GameruleCommand extends VanillaCommand { public GameruleCommand(String name) { - super(name, "%nukkit.command.gamerule.description", "%nukkit.command.gamerule.usage"); + super(name, "%nukkit.command.gamerule.description", "%commands.gamerule.usage"); this.setPermission("nukkit.command.gamerule"); this.commandParameters.clear(); @@ -79,16 +75,26 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) } if (!sender.isPlayer()) { - sender.sendMessage(new TranslationContainer("%commands.generic.ingame")); + sender.sendMessage(new TranslationContainer("commands.generic.ingame")); return true; } GameRules rules = ((Player) sender).getLevel().getGameRules(); switch (args.length) { case 0: - StringJoiner rulesJoiner = new StringJoiner(", "); + int splitCounter = 0; + StringJoiner rulesJoiner = new StringJoiner("\n"); for (GameRule rule: rules.getRules()) { - rulesJoiner.add(rule.getName().toLowerCase()); + rulesJoiner.add(rule.getName().toLowerCase() + " = " + rules.getString(rule)); + + // 1.21 disconnects on too long message + // TODO: do this the same way as on vanilla + if (splitCounter++ > 15) { + rulesJoiner.add(""); + sender.sendMessage(rulesJoiner.toString()); + splitCounter = 0; + rulesJoiner = new StringJoiner("\n"); + } } sender.sendMessage(rulesJoiner.toString()); return true; @@ -99,14 +105,13 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) return true; } - sender.sendMessage(gameRule.get().getName() .toLowerCase()+ " = " + rules.getString(gameRule.get())); + sender.sendMessage(gameRule.get().getName().toLowerCase() + " = " + rules.getString(gameRule.get())); return true; default: Optional optionalRule = GameRule.parseString(args[0]); if (!optionalRule.isPresent()) { - sender.sendMessage(new TranslationContainer("commands.generic.syntax", - "/gamerule ", args[0], " " + String.join(" ", Arrays.copyOfRange(args, 1, args.length)))); + sender.sendMessage(new TranslationContainer("commands.generic.syntax", "/gamerule ", args[0], ' ' + String.join(" ", Arrays.copyOfRange(args, 1, args.length)))); return true; } @@ -114,9 +119,9 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) rules.setGameRules(optionalRule.get(), args[1]); sender.sendMessage(new TranslationContainer("commands.gamerule.success", optionalRule.get().getName().toLowerCase(), args[1])); } catch (IllegalArgumentException e) { - sender.sendMessage(new TranslationContainer("commands.generic.syntax", "/gamerule " + args[0] + " ", args[1], " " + String.join(" ", Arrays.copyOfRange(args, 2, args.length)))); + sender.sendMessage(new TranslationContainer("commands.generic.syntax", "/gamerule " + args[0] + ' ', args[1], ' ' + String.join(" ", Arrays.copyOfRange(args, 2, args.length)))); } return true; } } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/command/defaults/GarbageCollectorCommand.java b/src/main/java/cn/nukkit/command/defaults/GarbageCollectorCommand.java index 94cb5c126c9..adc74d229e5 100644 --- a/src/main/java/cn/nukkit/command/defaults/GarbageCollectorCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/GarbageCollectorCommand.java @@ -30,12 +30,12 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) for (Level level : sender.getServer().getLevels().values()) { int chunksCount = level.getChunks().size(); - int entitiesCount = level.getEntities().length; + int entitiesCount = level.entities.size(); int tilesCount = level.getBlockEntities().size(); level.doChunkGarbageCollection(); level.unloadChunks(true); chunksCollected += chunksCount - level.getChunks().size(); - entitiesCollected += entitiesCount - level.getEntities().length; + entitiesCollected += entitiesCount - level.entities.size(); tilesCollected += tilesCount - level.getBlockEntities().size(); } diff --git a/src/main/java/cn/nukkit/command/defaults/GiveCommand.java b/src/main/java/cn/nukkit/command/defaults/GiveCommand.java index 0c325aea344..ea5eec19330 100644 --- a/src/main/java/cn/nukkit/command/defaults/GiveCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/GiveCommand.java @@ -4,28 +4,30 @@ import cn.nukkit.Server; import cn.nukkit.command.Command; import cn.nukkit.command.CommandSender; -import cn.nukkit.command.data.CommandEnum; import cn.nukkit.command.data.CommandParamType; import cn.nukkit.command.data.CommandParameter; import cn.nukkit.item.Item; +import cn.nukkit.item.RuntimeItemMapping; +import cn.nukkit.item.RuntimeItems; import cn.nukkit.lang.TranslationContainer; import cn.nukkit.utils.TextFormat; -import java.util.ArrayList; -import java.util.List; +import java.util.Collection; +import java.util.Collections; /** * Created on 2015/12/9 by xtypr. * Package cn.nukkit.command.defaults in project Nukkit . */ public class GiveCommand extends VanillaCommand { + public GiveCommand(String name) { super(name, "%nukkit.command.give.description", "%nukkit.command.give.usage"); this.setPermission("nukkit.command.give"); this.commandParameters.clear(); this.commandParameters.put("default", new CommandParameter[]{ CommandParameter.newType("player", CommandParamType.TARGET), - CommandParameter.newEnum("itemName", CommandEnum.ENUM_ITEM), + new CommandParameter("itemName", false, "Item"), CommandParameter.newType("amount", true, CommandParamType.INT), CommandParameter.newType("tags", true, CommandParamType.RAWTEXT) }); @@ -46,41 +48,58 @@ public GiveCommand(String name) { @Override public boolean execute(CommandSender sender, String commandLabel, String[] args) { if (!this.testPermission(sender)) { - return false; + return true; } if (args.length < 2) { sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); - return false; + return true; } - List targets = new ArrayList<>(); + Collection targets; if (args[0].equals("@a")) { - targets.addAll(Server.getInstance().getOnlinePlayers().values()); - } - else { - Player target = sender.getServer().getPlayer(args[0].replace("@s", sender.getName())); + targets = Server.getInstance().getOnlinePlayers().values(); + } else { + Player target = sender.getServer().getPlayerExact(args[0].replace("@s", sender.getName())); if (target != null) { - targets.add(target); - } - else { + targets = Collections.singletonList(target); + } else { sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.player.notFound")); return false; } } Item item; + try { item = Item.fromString(args[1]); } catch (Exception e) { sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); - return false; + return true; } + if (item.getDamage() < 0) { + sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); + return true; + } + + int count = 1; try { - item.setCount(Integer.parseInt(args[2])); - } catch (Exception e) { - item.setCount(item.getMaxStackSize()); + count = Integer.parseInt(args[2]); + } catch (Exception ignore) { + } + item.setCount(count); + + if (item.getId() == 0) { + String identifier = args[1].toLowerCase(); + if (!identifier.contains(":")) { + identifier = "minecraft:" + identifier; + } + RuntimeItemMapping.LegacyEntry entry = RuntimeItems.getMapping().fromIdentifier(identifier); + + if (entry != null) { + item = Item.get(entry.getLegacyId(), entry.getDamage(), count); + } } if (item.getId() == 0) { diff --git a/src/main/java/cn/nukkit/command/defaults/HelpCommand.java b/src/main/java/cn/nukkit/command/defaults/HelpCommand.java index 124c35b46f1..e581c4011b1 100644 --- a/src/main/java/cn/nukkit/command/defaults/HelpCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/HelpCommand.java @@ -12,7 +12,7 @@ import java.util.TreeMap; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class HelpCommand extends VanillaCommand { @@ -50,16 +50,16 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) args = new String[0]; }*/ for (String arg : args) { - if (!command.toString().equals("")) { - command.append(" "); + if (command.length() > 0) { + command.append(' '); } command.append(arg); } } catch (NumberFormatException e) { pageNumber = 1; for (String arg : args) { - if (!command.toString().equals("")) { - command.append(" "); + if (command.length() > 0) { + command.append(' '); } command.append(arg); } @@ -70,7 +70,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) pageHeight = Integer.MAX_VALUE; } - if (command.toString().equals("")) { + if (command.length() == 0) { Map commands = new TreeMap<>(); for (Command cmd : sender.getServer().getCommandMap().getCommands().values()) { if (cmd.testPermissionSilent(sender)) { @@ -98,16 +98,16 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) if (cmd != null) { if (cmd.testPermissionSilent(sender)) { String message = TextFormat.YELLOW + "--------- " + TextFormat.WHITE + " Help: /" + cmd.getName() + TextFormat.YELLOW + " ---------\n"; - message += TextFormat.GOLD + "Description: " + TextFormat.WHITE + cmd.getDescription() + "\n"; + message += TextFormat.GOLD + "Description: " + TextFormat.WHITE + cmd.getDescription() + '\n'; StringBuilder usage = new StringBuilder(); String[] usages = cmd.getUsage().split("\n"); for (String u : usages) { - if (!usage.toString().equals("")) { + if (usage.length() > 0) { usage.append("\n" + TextFormat.WHITE); } usage.append(u); } - message += TextFormat.GOLD + "Usage: " + TextFormat.WHITE + usage + "\n"; + message += TextFormat.GOLD + "Usage: " + TextFormat.WHITE + usage + '\n'; sender.sendMessage(message); return true; } diff --git a/src/main/java/cn/nukkit/command/defaults/KickCommand.java b/src/main/java/cn/nukkit/command/defaults/KickCommand.java index a73db169b5d..ce785fed0ce 100644 --- a/src/main/java/cn/nukkit/command/defaults/KickCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/KickCommand.java @@ -39,16 +39,16 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) StringBuilder reason = new StringBuilder(); for (int i = 1; i < args.length; i++) { - reason.append(args[i]).append(" "); + reason.append(args[i]).append(' '); } if (reason.length() > 0) { reason = new StringBuilder(reason.substring(0, reason.length() - 1)); } - Player player = sender.getServer().getPlayer(name); + Player player = sender.getServer().getPlayerExact(name); if (player != null) { - player.kick(PlayerKickEvent.Reason.KICKED_BY_ADMIN, reason.toString()); + player.kick(PlayerKickEvent.Reason.KICKED_BY_ADMIN, reason.toString(), true); if (reason.length() >= 1) { Command.broadcastCommandMessage(sender, new TranslationContainer("commands.kick.success.reason", player.getName(), reason.toString()) ); diff --git a/src/main/java/cn/nukkit/command/defaults/KillCommand.java b/src/main/java/cn/nukkit/command/defaults/KillCommand.java index e51262dcec1..423e0b6c7af 100644 --- a/src/main/java/cn/nukkit/command/defaults/KillCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/KillCommand.java @@ -9,6 +9,7 @@ import cn.nukkit.entity.Entity; import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; +import cn.nukkit.event.entity.EntityPotionEffectEvent; import cn.nukkit.lang.TranslationContainer; import cn.nukkit.level.Level; import cn.nukkit.utils.TextFormat; @@ -23,8 +24,7 @@ public class KillCommand extends VanillaCommand { public KillCommand(String name) { super(name, "%nukkit.command.kill.description", "%nukkit.command.kill.usage", new String[]{"suicide"}); - this.setPermission("nukkit.command.kill.self;" - + "nukkit.command.kill.other"); + this.setPermission("nukkit.command.kill.self;nukkit.command.kill.other"); this.commandParameters.clear(); this.commandParameters.put("default", new CommandParameter[]{ CommandParameter.newType("player", true, CommandParamType.TARGET) @@ -45,20 +45,15 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.permission")); return true; } - Player player = sender.getServer().getPlayer(args[0].replace("@s", sender.getName())); + Player player = sender.getServer().getPlayerExact(args[0]); if (player != null) { if (player.isCreative() || player.isSpectator()) { sender.sendMessage(TextFormat.RED + "No targets matched selector"); return true; } - EntityDamageEvent ev = new EntityDamageEvent(player, DamageCause.SUICIDE, 1000); - sender.getServer().getPluginManager().callEvent(ev); - if (ev.isCancelled()) { - return true; + if (resetHealth(player)) { + Command.broadcastCommandMessage(sender, new TranslationContainer("commands.kill.successful", player.getName())); } - player.setLastDamageCause(ev); - player.setHealth(0); - Command.broadcastCommandMessage(sender, new TranslationContainer("commands.kill.successful", player.getName())); } else if (args[0].equals("@e")) { StringJoiner joiner = new StringJoiner(", "); for (Level level : Server.getInstance().getLevels().values()) { @@ -91,19 +86,15 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) sender.sendMessage(TextFormat.RED + "No targets matched selector"); return true; } - EntityDamageEvent ev = new EntityDamageEvent(p, DamageCause.SUICIDE, 1000); - sender.getServer().getPluginManager().callEvent(ev); - if (ev.isCancelled()) { - return true; + if (resetHealth(p)) { + sender.sendMessage(new TranslationContainer("commands.kill.successful", sender.getName())); } - p.setLastDamageCause(ev); - p.setHealth(0); - sender.sendMessage(new TranslationContainer("commands.kill.successful", sender.getName())); } else if (args[0].equals("@a")) { if (!sender.hasPermission("nukkit.command.kill.other")) { sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.permission")); return true; } + StringJoiner joiner = new StringJoiner(", "); for (Level level : Server.getInstance().getLevels().values()) { for (Entity entity : level.getEntities()) { if (entity instanceof Player) { @@ -111,23 +102,19 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) if (p.isCreative() || p.isSpectator()) { continue; } - EntityDamageEvent ev = new EntityDamageEvent(entity, DamageCause.SUICIDE, 1000); - sender.getServer().getPluginManager().callEvent(ev); - if (ev.isCancelled()) { - continue; - } - entity.setLastDamageCause(ev); - entity.setHealth(0); + resetHealth(p); + + joiner.add(entity.getName()); } } } - sender.sendMessage(new TranslationContainer(TextFormat.GOLD + "%commands.kill.all.successful")); + String entities = joiner.toString(); + sender.sendMessage(new TranslationContainer("commands.kill.successful", entities.isEmpty() ? "0" : entities)); } else { sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.player.notFound")); } return true; - } - if (sender instanceof Player) { + } else if (sender instanceof Player) { if (!sender.hasPermission("nukkit.command.kill.self")) { sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.permission")); return true; @@ -137,18 +124,24 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) sender.sendMessage(TextFormat.RED + "No targets matched selector"); return true; } - EntityDamageEvent ev = new EntityDamageEvent(player, DamageCause.SUICIDE, 1000); - sender.getServer().getPluginManager().callEvent(ev); - if (ev.isCancelled()) { - return true; + if (resetHealth(player)) { + sender.sendMessage(new TranslationContainer("commands.kill.successful", sender.getName())); } - player.setLastDamageCause(ev); - player.setHealth(0); - sender.sendMessage(new TranslationContainer("commands.kill.successful", sender.getName())); } else { sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); + } + return true; + } + + private boolean resetHealth(Entity entity) { + EntityDamageEvent ev = new EntityDamageEvent(entity, DamageCause.SUICIDE, 1000); + entity.getServer().getPluginManager().callEvent(ev); + if (ev.isCancelled()) { return false; } + entity.setLastDamageCause(ev); + entity.removeAllEffects(EntityPotionEffectEvent.Cause.DEATH); // Fix issue with absorption + entity.setHealth(0); return true; } } diff --git a/src/main/java/cn/nukkit/command/defaults/ListCommand.java b/src/main/java/cn/nukkit/command/defaults/ListCommand.java index 7417211d0c2..60a0ca31ad5 100644 --- a/src/main/java/cn/nukkit/command/defaults/ListCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/ListCommand.java @@ -34,8 +34,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) online = new StringBuilder(online.substring(0, online.length() - 2)); } - sender.sendMessage(new TranslationContainer("commands.players.list", - String.valueOf(onlineCount), String.valueOf(sender.getServer().getMaxPlayers()))); + sender.sendMessage(new TranslationContainer("commands.players.list", String.valueOf(onlineCount), String.valueOf(sender.getServer().getMaxPlayers()))); sender.sendMessage(online.toString()); return true; } diff --git a/src/main/java/cn/nukkit/command/defaults/MeCommand.java b/src/main/java/cn/nukkit/command/defaults/MeCommand.java index 57a35cfc010..a3a36d8c83d 100644 --- a/src/main/java/cn/nukkit/command/defaults/MeCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/MeCommand.java @@ -14,7 +14,7 @@ public class MeCommand extends VanillaCommand { public MeCommand(String name) { - super(name, "%nukkit.command.me.description", "%commands.me.usage"); + super(name, "%nukkit.command.me.description", "%nukkit.command.me.usage"); this.setPermission("nukkit.command.me"); this.commandParameters.clear(); this.commandParameters.put("default", new CommandParameter[]{ @@ -43,7 +43,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) StringBuilder msg = new StringBuilder(); for (String arg : args) { - msg.append(arg).append(" "); + msg.append(arg).append(' '); } if (msg.length() > 0) { diff --git a/src/main/java/cn/nukkit/command/defaults/OpCommand.java b/src/main/java/cn/nukkit/command/defaults/OpCommand.java index 6afc9fdcc6c..dfa2cb459b4 100644 --- a/src/main/java/cn/nukkit/command/defaults/OpCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/OpCommand.java @@ -16,7 +16,7 @@ public class OpCommand extends VanillaCommand { public OpCommand(String name) { - super(name, "%nukkit.command.op.description", "%commands.op.description"); + super(name, "%nukkit.command.op.description", "%nukkit.command.op.usage"); this.setPermission("nukkit.command.op.give"); this.commandParameters.clear(); this.commandParameters.put("default", new CommandParameter[]{ @@ -29,21 +29,22 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) if (!this.testPermission(sender)) { return true; } + if (args.length == 0) { - sender.sendMessage(new TranslationContainer("commands.op.usage", this.usageMessage)); + sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); return false; } String name = args[0]; IPlayer player = sender.getServer().getOfflinePlayer(name); - - Command.broadcastCommandMessage(sender, new TranslationContainer("commands.op.success", player.getName())); if (player instanceof Player) { + player.setOp(true); ((Player) player).sendMessage(new TranslationContainer(TextFormat.GRAY + "%commands.op.message")); + } else { + sender.getServer().addOp(name); } - player.setOp(true); - + Command.broadcastCommandMessage(sender, new TranslationContainer("commands.op.success", player.getName())); return true; } } diff --git a/src/main/java/cn/nukkit/command/defaults/PardonCommand.java b/src/main/java/cn/nukkit/command/defaults/PardonCommand.java index 0ffd5296b72..2b3c6db12c8 100644 --- a/src/main/java/cn/nukkit/command/defaults/PardonCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/PardonCommand.java @@ -7,7 +7,7 @@ import cn.nukkit.lang.TranslationContainer; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class PardonCommand extends VanillaCommand { diff --git a/src/main/java/cn/nukkit/command/defaults/PardonIpCommand.java b/src/main/java/cn/nukkit/command/defaults/PardonIpCommand.java index d3ae0695a85..4a830a9a1d6 100644 --- a/src/main/java/cn/nukkit/command/defaults/PardonIpCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/PardonIpCommand.java @@ -11,7 +11,7 @@ import java.util.regex.Pattern; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class PardonIpCommand extends VanillaCommand { diff --git a/src/main/java/cn/nukkit/command/defaults/ParticleCommand.java b/src/main/java/cn/nukkit/command/defaults/ParticleCommand.java index aea1e78c51e..f4f58503af4 100644 --- a/src/main/java/cn/nukkit/command/defaults/ParticleCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/ParticleCommand.java @@ -12,7 +12,6 @@ import cn.nukkit.level.particle.*; import cn.nukkit.math.Vector3; -import java.util.Random; import java.util.concurrent.ThreadLocalRandom; /** @@ -20,10 +19,12 @@ * Package cn.nukkit.command.defaults in project Nukkit . */ public class ParticleCommand extends VanillaCommand { - private static final String[] ENUM_VALUES = new String[]{"explode", "hugeexplosion", "hugeexplosionseed", "bubble" + + private static final String[] ENUM_VALUES = {"explode", "hugeexplosion", "hugeexplosionseed", "bubble" , "splash", "wake", "water", "crit", "smoke", "spell", "instantspell", "dripwater", "driplava", "townaura" , "spore", "portal", "flame", "lava", "reddust", "snowballpoof", "slime", "itembreak", "terrain", "heart" , "ink", "droplet", "enchantmenttable", "happyvillager", "angryvillager", "forcefield"}; + public ParticleCommand(String name) { super(name, "%nukkit.command.particle.description", "%nukkit.command.particle.usage"); this.setPermission("nukkit.command.particle"); @@ -44,7 +45,6 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) if (args.length < 4) { sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); - return true; } @@ -75,23 +75,18 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) try { double c = Double.parseDouble(args[4]); count = (int) c; - } catch (Exception e) { - //ignore - } + } catch (Exception ignored) {} } count = Math.max(1, count); int data = -1; if (args.length > 5) { try { - double d = Double.parseDouble(args[5]); + double d = Double.parseDouble(args[8]); data = (int) d; - } catch (Exception e) { - //ignore - } + } catch (Exception ignored) {} } - - Particle particle = this.getParticle(name, position, data); + Particle particle = getParticle(name, position, data); if (particle == null) { position.level.addParticleEffect(position.asVector3f(), args[0], -1, position.level.getDimension()); @@ -100,7 +95,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) sender.sendMessage(new TranslationContainer("commands.particle.success", name, String.valueOf(count))); - Random random = ThreadLocalRandom.current(); + ThreadLocalRandom random = ThreadLocalRandom.current(); for (int i = 0; i < count; i++) { particle.setComponents( @@ -114,7 +109,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) return true; } - private Particle getParticle(String name, Vector3 pos, int data) { + private static Particle getParticle(String name, Vector3 pos, int data) { switch (name) { case "explode": return new ExplodeParticle(pos); @@ -202,7 +197,7 @@ private Particle getParticle(String name, Vector3 pos, int data) { return null; } - private static double getDouble(String arg, double defaultValue) throws Exception { + private static double getDouble(String arg, double defaultValue) { if (arg.startsWith("~")) { String relativePos = arg.substring(1); if (relativePos.isEmpty()) { diff --git a/src/main/java/cn/nukkit/command/defaults/PlaySoundCommand.java b/src/main/java/cn/nukkit/command/defaults/PlaySoundCommand.java new file mode 100644 index 00000000000..63b6a8272d3 --- /dev/null +++ b/src/main/java/cn/nukkit/command/defaults/PlaySoundCommand.java @@ -0,0 +1,97 @@ +package cn.nukkit.command.defaults; + +import cn.nukkit.Player; +import cn.nukkit.Server; +import cn.nukkit.command.CommandSender; +import cn.nukkit.command.data.CommandParamType; +import cn.nukkit.command.data.CommandParameter; +import cn.nukkit.lang.TranslationContainer; +import cn.nukkit.level.Level; +import cn.nukkit.math.Vector3; +import cn.nukkit.network.protocol.PlaySoundPacket; + +public class PlaySoundCommand extends VanillaCommand { + + public PlaySoundCommand(String name) { + super(name, "%nukkit.command.playsound.description", "%commands.playsound.usage"); + this.setPermission("nukkit.command.playsound"); + this.commandParameters.clear(); + this.commandParameters.put("default", new CommandParameter[]{ + new CommandParameter("sound", CommandParamType.STRING, false), + new CommandParameter("player", CommandParamType.TARGET, true) + }); + } + + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + if (!this.testPermission(sender)) { + return true; + } + + if (args.length == 0) { + sender.sendMessage(new TranslationContainer("%commands.playsound.usage", this.usageMessage)); + return false; + } + + if (args.length == 1) { + if (!(sender instanceof Player)) { + sender.sendMessage(new TranslationContainer("commands.generic.ingame")); + return true; + } + + Player p = (Player) sender; + + addSound(p.getLevel(), p, args[0], p); + p.sendMessage(new TranslationContainer("commands.playsound.success", args[0], p.getName())); + + return true; + } + + if (args[1].equalsIgnoreCase("@a")) { + for (Player p : Server.getInstance().getOnlinePlayers().values()) { + addSound(p.getLevel(), p, args[0], p); + } + + sender.sendMessage(new TranslationContainer("commands.playsound.success", args[0], "@a")); + + return true; + } + + if (args[1].equalsIgnoreCase("@s") && sender instanceof Player) { + Player p = (Player) sender; + + addSound(p.getLevel(), p, args[0], p); + sender.sendMessage(new TranslationContainer("commands.playsound.success", args[0], p.getName())); + + return true; + } + + Player p = Server.getInstance().getPlayerExact(args[1]); + + if (p == null) { + sender.sendMessage(new TranslationContainer("commands.generic.player.notFound")); + return true; + } + + addSound(p.getLevel(), p, args[0], p); + sender.sendMessage(new TranslationContainer("commands.playsound.success", args[0], p.getName())); + + return true; + } + + private static void addSound(Level level, Vector3 pos, String sound, Player... players) { + PlaySoundPacket packet = new PlaySoundPacket(); + packet.name = sound; + packet.volume = 1f; + packet.pitch = 1f; + packet.x = pos.getFloorX(); + packet.y = pos.getFloorY(); + packet.z = pos.getFloorZ(); + + if (players == null || players.length == 0) { + level.addChunkPacket(pos.getChunkX(), pos.getChunkZ(), packet); + } else { + Server.broadcastPacket(players, packet); + } + } +} diff --git a/src/main/java/cn/nukkit/command/defaults/PluginsCommand.java b/src/main/java/cn/nukkit/command/defaults/PluginsCommand.java index b3377bfd251..52438e9dc02 100644 --- a/src/main/java/cn/nukkit/command/defaults/PluginsCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/PluginsCommand.java @@ -14,12 +14,9 @@ public class PluginsCommand extends VanillaCommand { public PluginsCommand(String name) { - super(name, - "%nukkit.command.plugins.description", - "%nukkit.command.plugins.usage", - new String[]{"pl"} - ); + super(name, "%nukkit.command.plugins.description", "%nukkit.command.plugins.usage"); this.setPermission("nukkit.command.plugins"); + this.setAliases(new String[]{"pl"}); this.commandParameters.clear(); } @@ -29,18 +26,18 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) return true; } - this.sendPluginList(sender); + sendPluginList(sender); return true; } - private void sendPluginList(CommandSender sender) { + private static void sendPluginList(CommandSender sender) { StringBuilder list = new StringBuilder(); Map plugins = sender.getServer().getPluginManager().getPlugins(); for (Plugin plugin : plugins.values()) { if (list.length() > 0) { list.append(TextFormat.WHITE + ", "); } - list.append(plugin.isEnabled() ? TextFormat.GREEN : TextFormat.RED); + list.append(plugin.isEnabled() ? TextFormat.GREEN : TextFormat.RED + "*"); list.append(plugin.getDescription().getFullName()); } diff --git a/src/main/java/cn/nukkit/command/defaults/ReloadCommand.java b/src/main/java/cn/nukkit/command/defaults/ReloadCommand.java index 718c140b5b5..cf584839a73 100644 --- a/src/main/java/cn/nukkit/command/defaults/ReloadCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/ReloadCommand.java @@ -6,7 +6,7 @@ import cn.nukkit.utils.TextFormat; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ReloadCommand extends VanillaCommand { diff --git a/src/main/java/cn/nukkit/command/defaults/SaveCommand.java b/src/main/java/cn/nukkit/command/defaults/SaveCommand.java index 9e119f2d104..ac4d768ebf5 100644 --- a/src/main/java/cn/nukkit/command/defaults/SaveCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/SaveCommand.java @@ -15,6 +15,7 @@ public class SaveCommand extends VanillaCommand { public SaveCommand(String name) { super(name, "%nukkit.command.save.description", "%commands.save.usage"); this.setPermission("nukkit.command.save.perform"); + this.setAliases(new String[]{"save-all"}); this.commandParameters.clear(); } @@ -24,6 +25,30 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) return true; } + if (args.length > 0) { + switch (args[0].toLowerCase()) { + case "on": + sender.getServer().setAutoSave(true); + Command.broadcastCommandMessage(sender, new TranslationContainer("commands.save.enabled")); + return true; + case "off": + sender.getServer().setAutoSave(false); + Command.broadcastCommandMessage(sender, new TranslationContainer("commands.save.disabled")); + return true; + case "hold": + sender.getServer().holdWorldSave = true; + Command.broadcastCommandMessage(sender, new TranslationContainer("commands.save.hold-on")); + return true; + case "resume": + sender.getServer().holdWorldSave = false; + Command.broadcastCommandMessage(sender, new TranslationContainer("commands.save.hold-off")); + return true; + default: + sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); + return false; + } + } + Command.broadcastCommandMessage(sender, new TranslationContainer("commands.save.start")); for (Player player : sender.getServer().getOnlinePlayers().values()) { diff --git a/src/main/java/cn/nukkit/command/defaults/SaveOffCommand.java b/src/main/java/cn/nukkit/command/defaults/SaveOffCommand.java deleted file mode 100644 index 762cd3140bb..00000000000 --- a/src/main/java/cn/nukkit/command/defaults/SaveOffCommand.java +++ /dev/null @@ -1,28 +0,0 @@ -package cn.nukkit.command.defaults; - -import cn.nukkit.command.Command; -import cn.nukkit.command.CommandSender; -import cn.nukkit.lang.TranslationContainer; - -/** - * Created on 2015/11/13 by xtypr. - * Package cn.nukkit.command.defaults in project Nukkit . - */ -public class SaveOffCommand extends VanillaCommand { - - public SaveOffCommand(String name) { - super(name, "%nukkit.command.saveoff.description", "%commands.save-off.usage"); - this.setPermission("nukkit.command.save.disable"); - this.commandParameters.clear(); - } - - @Override - public boolean execute(CommandSender sender, String commandLabel, String[] args) { - if (!this.testPermission(sender)) { - return true; - } - sender.getServer().setAutoSave(false); - Command.broadcastCommandMessage(sender, new TranslationContainer("commands.save.disabled")); - return true; - } -} diff --git a/src/main/java/cn/nukkit/command/defaults/SaveOnCommand.java b/src/main/java/cn/nukkit/command/defaults/SaveOnCommand.java deleted file mode 100644 index a3f6a5dfdd3..00000000000 --- a/src/main/java/cn/nukkit/command/defaults/SaveOnCommand.java +++ /dev/null @@ -1,28 +0,0 @@ -package cn.nukkit.command.defaults; - -import cn.nukkit.command.Command; -import cn.nukkit.command.CommandSender; -import cn.nukkit.lang.TranslationContainer; - -/** - * Created on 2015/11/13 by xtypr. - * Package cn.nukkit.command.defaults in project Nukkit . - */ -public class SaveOnCommand extends VanillaCommand { - - public SaveOnCommand(String name) { - super(name, "%nukkit.command.saveon.description", "%commands.save-on.usage"); - this.setPermission("nukkit.command.save.enable"); - this.commandParameters.clear(); - } - - @Override - public boolean execute(CommandSender sender, String commandLabel, String[] args) { - if (!this.testPermission(sender)) { - return true; - } - sender.getServer().setAutoSave(true); - Command.broadcastCommandMessage(sender, new TranslationContainer("commands.save.enabled")); - return true; - } -} diff --git a/src/main/java/cn/nukkit/command/defaults/SayCommand.java b/src/main/java/cn/nukkit/command/defaults/SayCommand.java index a55d3c459cf..4b6cdc34fd6 100644 --- a/src/main/java/cn/nukkit/command/defaults/SayCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/SayCommand.java @@ -45,7 +45,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) StringBuilder msg = new StringBuilder(); for (String arg : args) { - msg.append(arg).append(" "); + msg.append(arg).append(' '); } if (msg.length() > 0) { msg = new StringBuilder(msg.substring(0, msg.length() - 1)); diff --git a/src/main/java/cn/nukkit/command/defaults/SeedCommand.java b/src/main/java/cn/nukkit/command/defaults/SeedCommand.java index 3c70e7dd5f1..b269df22c97 100644 --- a/src/main/java/cn/nukkit/command/defaults/SeedCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/SeedCommand.java @@ -5,7 +5,7 @@ import cn.nukkit.lang.TranslationContainer; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class SeedCommand extends VanillaCommand { diff --git a/src/main/java/cn/nukkit/command/defaults/SetWorldSpawnCommand.java b/src/main/java/cn/nukkit/command/defaults/SetWorldSpawnCommand.java index fcb93688eb2..480a66179af 100644 --- a/src/main/java/cn/nukkit/command/defaults/SetWorldSpawnCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/SetWorldSpawnCommand.java @@ -16,6 +16,7 @@ * Package cn.nukkit.command.defaults in project Nukkit . */ public class SetWorldSpawnCommand extends VanillaCommand { + public SetWorldSpawnCommand(String name) { super(name, "%nukkit.command.setworldspawn.description", "%commands.setworldspawn.usage"); this.setPermission("nukkit.command.setworldspawn"); @@ -54,9 +55,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) } level.setSpawnLocation(pos); DecimalFormat round2 = new DecimalFormat("##0.00"); - Command.broadcastCommandMessage(sender, new TranslationContainer("commands.setworldspawn.success", round2.format(pos.x), - round2.format(pos.y), - round2.format(pos.z))); + Command.broadcastCommandMessage(sender, new TranslationContainer("commands.setworldspawn.success", round2.format(pos.x), round2.format(pos.y), round2.format(pos.z))); return true; } } diff --git a/src/main/java/cn/nukkit/command/defaults/SpawnpointCommand.java b/src/main/java/cn/nukkit/command/defaults/SpawnpointCommand.java index 1afd5d68e3d..3919114c731 100644 --- a/src/main/java/cn/nukkit/command/defaults/SpawnpointCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/SpawnpointCommand.java @@ -17,6 +17,7 @@ * Package cn.nukkit.command.defaults in project Nukkit . */ public class SpawnpointCommand extends VanillaCommand { + public SpawnpointCommand(String name) { super(name, "%nukkit.command.spawnpoint.description", "%commands.spawnpoint.usage"); this.setPermission("nukkit.command.spawnpoint"); @@ -41,7 +42,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) return true; } } else { - target = sender.getServer().getPlayer(args[0].replace("@s", sender.getName())); + target = sender.getServer().getPlayerExact(args[0].replace("@s", sender.getName())); if (target == null) { sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.player.notFound")); return true; @@ -62,8 +63,8 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); return true; } - if (y < 0) y = 0; - if (y > 256) y = 256; + if (y < target.getLevel().getMinBlockY()) y = target.getLevel().getMinBlockY(); + if (y > target.getLevel().getMaxBlockY()) y = target.getLevel().getMaxBlockY(); target.setSpawn(new Position(x, y, z, level)); Command.broadcastCommandMessage(sender, new TranslationContainer("commands.spawnpoint.success", target.getName(), round2.format(x), @@ -88,4 +89,4 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); return true; } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/command/defaults/StatusCommand.java b/src/main/java/cn/nukkit/command/defaults/StatusCommand.java index 7dc9c054975..2d0afdae143 100644 --- a/src/main/java/cn/nukkit/command/defaults/StatusCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/StatusCommand.java @@ -15,6 +15,7 @@ * Package cn.nukkit.command.defaults in project Nukkit . */ public class StatusCommand extends VanillaCommand { + private static final String UPTIME_FORMAT = TextFormat.RED + "%d" + TextFormat.GOLD + " days " + TextFormat.RED + "%d" + TextFormat.GOLD + " hours " + TextFormat.RED + "%d" + TextFormat.GOLD + " minutes " + @@ -47,13 +48,13 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) tpsColor = TextFormat.GOLD; } - sender.sendMessage(TextFormat.GOLD + "Current TPS: " + tpsColor + NukkitMath.round(tps, 2)); + sender.sendMessage(TextFormat.GOLD + "TPS / Average: " + tpsColor + NukkitMath.round(tps, 2) + " / " + NukkitMath.round(server.getTicksPerSecondAverage(), 2)); - sender.sendMessage(TextFormat.GOLD + "Load: " + tpsColor + server.getTickUsage() + "%"); + sender.sendMessage(TextFormat.GOLD + "Load / Average: " + tpsColor + server.getTickUsage() + "% / " + server.getTickUsageAverage() * 100 + '%'); - sender.sendMessage(TextFormat.GOLD + "Network upload: " + TextFormat.GREEN + NukkitMath.round((server.getNetwork().getUpload() / 1024 * 1000), 2) + " kB/s"); + //sender.sendMessage(TextFormat.GOLD + "Network upload: " + TextFormat.GREEN + NukkitMath.round((server.getNetwork().getUpload() / 1024 * 1000), 2) + " kB/s"); - sender.sendMessage(TextFormat.GOLD + "Network download: " + TextFormat.GREEN + NukkitMath.round((server.getNetwork().getDownload() / 1024 * 1000), 2) + " kB/s"); + //sender.sendMessage(TextFormat.GOLD + "Network download: " + TextFormat.GREEN + NukkitMath.round((server.getNetwork().getDownload() / 1024 * 1000), 2) + " kB/s"); sender.sendMessage(TextFormat.GOLD + "Thread count: " + TextFormat.GREEN + Thread.getAllStackTraces().size()); @@ -69,38 +70,40 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) usageColor = TextFormat.GOLD; } - sender.sendMessage(TextFormat.GOLD + "Used memory: " + usageColor + usedMB + " MB. (" + NukkitMath.round(usage, 2) + "%)"); + sender.sendMessage(TextFormat.GOLD + "Used memory: " + usageColor + usedMB + " MB (" + NukkitMath.round(usage, 2) + "%)"); - sender.sendMessage(TextFormat.GOLD + "Total memory: " + TextFormat.RED + totalMB + " MB."); + sender.sendMessage(TextFormat.GOLD + "Total memory: " + TextFormat.RED + totalMB + " MB"); - sender.sendMessage(TextFormat.GOLD + "Maximum VM memory: " + TextFormat.RED + maxMB + " MB."); + sender.sendMessage(TextFormat.GOLD + "Maximum VM memory: " + TextFormat.RED + maxMB + " MB"); sender.sendMessage(TextFormat.GOLD + "Available processors: " + TextFormat.GREEN + runtime.availableProcessors()); + int players = server.getOnlinePlayersCount(); + TextFormat playerColor = TextFormat.GREEN; - if (((float) server.getOnlinePlayers().size() / (float) server.getMaxPlayers()) > 0.85) { + if (((float) players / (float) server.getMaxPlayers()) > 0.85) { playerColor = TextFormat.GOLD; } - sender.sendMessage(TextFormat.GOLD + "Players: " + playerColor + server.getOnlinePlayers().size() + TextFormat.GREEN + " online, " + - TextFormat.RED + server.getMaxPlayers() + TextFormat.GREEN + " max. "); + sender.sendMessage(TextFormat.GOLD + "Players: " + playerColor + players + TextFormat.GREEN + " online, " + + TextFormat.RED + server.getMaxPlayers() + TextFormat.GREEN + " max"); for (Level level : server.getLevels().values()) { sender.sendMessage( - TextFormat.GOLD + "World \"" + level.getFolderName() + "\"" + (!Objects.equals(level.getFolderName(), level.getName()) ? " (" + level.getName() + ")" : "") + ": " + + TextFormat.GOLD + "World \"" + level.getFolderName() + '"' + (!Objects.equals(level.getFolderName(), level.getName()) ? " (" + level.getName() + ')' : "") + ": " + TextFormat.RED + level.getChunks().size() + TextFormat.GREEN + " chunks, " + - TextFormat.RED + level.getEntities().length + TextFormat.GREEN + " entities, " + - TextFormat.RED + level.getBlockEntities().size() + TextFormat.GREEN + " blockEntities." + + TextFormat.RED + level.entities.size() + TextFormat.GREEN + " entities, " + + TextFormat.RED + level.getBlockEntities().size() + TextFormat.GREEN + " block entities." + " Time " + ((level.getTickRate() > 1 || level.getTickRateTime() > 40) ? TextFormat.RED : TextFormat.YELLOW) + NukkitMath.round(level.getTickRateTime(), 2) + "ms" + - (level.getTickRate() > 1 ? " (tick rate " + level.getTickRate() + ")" : "") + (level.getTickRate() > 1 ? " (tick rate " + level.getTickRate() + ')' : "") ); } return true; } - private static String formatUptime(long uptime) { + public static String formatUptime(long uptime) { long days = TimeUnit.MILLISECONDS.toDays(uptime); uptime -= TimeUnit.DAYS.toMillis(days); long hours = TimeUnit.MILLISECONDS.toHours(uptime); @@ -110,4 +113,4 @@ private static String formatUptime(long uptime) { long seconds = TimeUnit.MILLISECONDS.toSeconds(uptime); return String.format(UPTIME_FORMAT, days, hours, minutes, seconds); } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/command/defaults/StopCommand.java b/src/main/java/cn/nukkit/command/defaults/StopCommand.java index 0c89133e00f..e4c22b0601d 100644 --- a/src/main/java/cn/nukkit/command/defaults/StopCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/StopCommand.java @@ -5,7 +5,7 @@ import cn.nukkit.lang.TranslationContainer; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class StopCommand extends VanillaCommand { diff --git a/src/main/java/cn/nukkit/command/defaults/SummonCommand.java b/src/main/java/cn/nukkit/command/defaults/SummonCommand.java new file mode 100644 index 00000000000..d596c44fa2b --- /dev/null +++ b/src/main/java/cn/nukkit/command/defaults/SummonCommand.java @@ -0,0 +1,82 @@ +package cn.nukkit.command.defaults; + +import cn.nukkit.Player; +import cn.nukkit.Server; +import cn.nukkit.command.CommandSender; +import cn.nukkit.command.data.CommandParamType; +import cn.nukkit.command.data.CommandParameter; +import cn.nukkit.entity.Entity; +import cn.nukkit.lang.TranslationContainer; +import cn.nukkit.level.Position; +import cn.nukkit.network.protocol.AddEntityPacket; +import cn.nukkit.utils.TextFormat; + +import java.util.ArrayList; +import java.util.List; + +public class SummonCommand extends VanillaCommand { + + public SummonCommand(String name) { + super(name, "%nukkit.command.summon.description", "%nukkit.command.summon.usage"); + this.setPermission("nukkit.command.summon"); + this.commandParameters.clear(); + List entityNames = new ArrayList<>(); + for (String key : AddEntityPacket.LEGACY_IDS.values()) { + entityNames.add(key.substring(10)); + } + this.commandParameters.put("default", new CommandParameter[]{ + CommandParameter.newEnum("entityType", false, entityNames.toArray(new String[0])), + CommandParameter.newType("player", true, CommandParamType.TARGET) + }); + } + + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + if (!this.testPermission(sender)) { + return true; + } + + if (args.length == 0 || (args.length == 1 && !(sender instanceof Player))) { + sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); + return false; + } + + String mob = args[0]; + + // Convert Minecraft format to the format what Nukkit uses + if (!Entity.isKnown(mob)) { + mob = Character.toUpperCase(args[0].charAt(0)) + args[0].substring(1); + StringBuilder sb = new StringBuilder(mob); + for (int x = 2; x < sb.length() - 1; x++) { + if (sb.charAt(x) == '_') { + sb.setCharAt(x + 1, Character.toUpperCase(sb.charAt(x + 1))); + sb.deleteCharAt(x); + } + } + mob = sb.toString(); + } + + Player playerThatSpawns; + + if (args.length == 2) { + playerThatSpawns = Server.getInstance().getPlayerExact(args[1].replace("@s", sender.getName())); + } else { + playerThatSpawns = (Player) sender; + } + + if (playerThatSpawns != null) { + Position pos = playerThatSpawns.floor().add(0.5, 0, 0.5); + Entity ent; + if ((ent = Entity.createEntity(mob, pos)) != null) { + ent.spawnToAll(); + sender.sendMessage(new TranslationContainer("%commands.summon.success")); + } else { + sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.summon.failed")); + } + } else { + sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.player.notFound")); + } + + return true; + } +} diff --git a/src/main/java/cn/nukkit/command/defaults/TeleportCommand.java b/src/main/java/cn/nukkit/command/defaults/TeleportCommand.java index e69aa948808..024b5a75295 100644 --- a/src/main/java/cn/nukkit/command/defaults/TeleportCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/TeleportCommand.java @@ -16,12 +16,13 @@ * Package cn.nukkit.command.defaults in project Nukkit . */ public class TeleportCommand extends VanillaCommand { + public TeleportCommand(String name) { super(name, "%nukkit.command.tp.description", "%commands.tp.usage"); this.setPermission("nukkit.command.teleport"); this.commandParameters.clear(); this.commandParameters.put("->Player", new CommandParameter[]{ - CommandParameter.newType("destination", CommandParamType.TARGET), + CommandParameter.newType("destination", CommandParamType.TARGET) }); this.commandParameters.put("Player->Player", new CommandParameter[]{ CommandParameter.newType("victim", CommandParamType.TARGET), @@ -59,21 +60,21 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) return true; } if (args.length == 1) { - target = sender.getServer().getPlayer(args[0].replace("@s", sender.getName())); + target = sender.getServer().getPlayerExact(args[0].replace("@s", sender.getName())); if (target == null) { sender.sendMessage(TextFormat.RED + "Can't find player " + args[0]); return true; } } } else { - target = sender.getServer().getPlayer(args[0].replace("@s", sender.getName())); + target = sender.getServer().getPlayerExact(args[0].replace("@s", sender.getName())); if (target == null) { sender.sendMessage(TextFormat.RED + "Can't find player " + args[0]); return true; } if (args.length == 2) { origin = target; - target = sender.getServer().getPlayer(args[1].replace("@s", sender.getName())); + target = sender.getServer().getPlayerExact(args[1].replace("@s", sender.getName())); if (target == null) { sender.sendMessage(TextFormat.RED + "Can't find player " + args[1]); return true; @@ -106,11 +107,17 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); return true; } - if (y < 0) y = 0; - if (y > 256) y = 256; + + if (x < -30000000) x = -30000000; + if (x > 30000000) x = 30000000; + if (y < -30000000) y = -30000000; + if (y > 30000000) y = 30000000; + if (z < -30000000) z = -30000000; + if (z > 30000000) z = 30000000; + if (args.length == 6 || (args.length == 5 && pos == 3)) { yaw = Integer.parseInt(args[pos++]); - pitch = Integer.parseInt(args[pos++]); + pitch = Integer.parseInt(args[pos]); } ((Player) target).teleport(new Location(x, y, z, yaw, pitch, ((Player) target).getLevel()), PlayerTeleportEvent.TeleportCause.COMMAND); Command.broadcastCommandMessage(sender, new TranslationContainer("commands.tp.success.coordinates", target.getName(), String.valueOf(NukkitMath.round(x, 2)), String.valueOf(NukkitMath.round(y, 2)), String.valueOf(NukkitMath.round(z, 2)))); diff --git a/src/main/java/cn/nukkit/command/defaults/TellCommand.java b/src/main/java/cn/nukkit/command/defaults/TellCommand.java index 58cf3004cf4..a8421e9b99e 100644 --- a/src/main/java/cn/nukkit/command/defaults/TellCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/TellCommand.java @@ -33,13 +33,12 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) if (args.length < 2) { sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); - return false; } String name = args[0].replace("@s", sender.getName()); - Player player = sender.getServer().getPlayer(name); + Player player = sender.getServer().getPlayerExact(name); if (player == null) { sender.sendMessage(new TranslationContainer("commands.generic.player.notFound")); return true; @@ -52,16 +51,22 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) StringBuilder msg = new StringBuilder(); for (int i = 1; i < args.length; i++) { - msg.append(args[i]).append(" "); + msg.append(args[i]).append(' '); } - if (msg.length() > 0) { + if (msg.length() > 512) { + sender.sendMessage(TextFormat.RED + "The message is too long"); + return true; + } else if (msg.length() > 0) { msg = new StringBuilder(msg.substring(0, msg.length() - 1)); } String displayName = (sender instanceof Player ? ((Player) sender).getDisplayName() : sender.getName()); - sender.sendMessage("[" + sender.getName() + " -> " + player.getDisplayName() + "] " + msg); - player.sendMessage("[" + displayName + " -> " + player.getName() + "] " + msg); + sender.sendMessage('[' + sender.getName() + " -> " + player.getDisplayName() + "] " + msg); + player.sendMessage('[' + displayName + " -> " + player.getName() + "] " + msg); + if (sender instanceof Player) { + sender.getServer().getLogger().info('[' + sender.getName() + " -> " + player.getDisplayName() + "] " + msg); + } return true; } diff --git a/src/main/java/cn/nukkit/command/defaults/TimeCommand.java b/src/main/java/cn/nukkit/command/defaults/TimeCommand.java index 5d6f39ad95d..b180aa6bf27 100644 --- a/src/main/java/cn/nukkit/command/defaults/TimeCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/TimeCommand.java @@ -18,10 +18,7 @@ public class TimeCommand extends VanillaCommand { public TimeCommand(String name) { super(name, "%nukkit.command.time.description", "%nukkit.command.time.usage"); - this.setPermission("nukkit.command.time.add;" + - "nukkit.command.time.set;" + - "nukkit.command.time.start;" + - "nukkit.command.time.stop"); + this.setPermission("nukkit.command.time.add;nukkit.command.time.set;nukkit.command.time.start;nukkit.command.time.stop"); this.commandParameters.clear(); this.commandParameters.put("1arg", new CommandParameter[]{ CommandParameter.newEnum("mode", new CommandEnum("TimeMode", "query", "start", "stop")) diff --git a/src/main/java/cn/nukkit/command/defaults/TimingsCommand.java b/src/main/java/cn/nukkit/command/defaults/TimingsCommand.java deleted file mode 100644 index beb9354e2ba..00000000000 --- a/src/main/java/cn/nukkit/command/defaults/TimingsCommand.java +++ /dev/null @@ -1,74 +0,0 @@ -package cn.nukkit.command.defaults; - -import cn.nukkit.command.CommandSender; -import cn.nukkit.command.data.CommandEnum; -import cn.nukkit.command.data.CommandParameter; -import cn.nukkit.lang.TranslationContainer; -import co.aikar.timings.Timings; -import co.aikar.timings.TimingsExport; - -/** - * @author fromgate - * @author Pub4Game - */ -public class TimingsCommand extends VanillaCommand { - - public TimingsCommand(String name) { - super(name, "%nukkit.command.timings.description", "%nukkit.command.timings.usage"); - this.setPermission("nukkit.command.timings"); - this.commandParameters.clear(); - this.commandParameters.put("default", new CommandParameter[]{ - CommandParameter.newEnum("action", new CommandEnum("TimingsAction", "on", "off", "paste", "verbon", "verboff", "reset", "report")) - }); - } - - @Override - public boolean execute(CommandSender sender, String commandLabel, String[] args) { - if (!this.testPermission(sender)) { - return true; - } - - if (args.length != 1) { - sender.sendMessage(new TranslationContainer("commands.generic.usage", usageMessage)); - return true; - } - - String mode = args[0].toLowerCase(); - - if (mode.equals("on")) { - Timings.setTimingsEnabled(true); - Timings.reset(); - sender.sendMessage(new TranslationContainer("nukkit.command.timings.enable")); - return true; - } else if (mode.equals("off")) { - Timings.setTimingsEnabled(false); - sender.sendMessage(new TranslationContainer("nukkit.command.timings.disable")); - return true; - } - - if (!Timings.isTimingsEnabled()) { - sender.sendMessage(new TranslationContainer("nukkit.command.timings.timingsDisabled")); - return true; - } - - switch (mode) { - case "verbon": - sender.sendMessage(new TranslationContainer("nukkit.command.timings.verboseEnable")); - Timings.setVerboseEnabled(true); - break; - case "verboff": - sender.sendMessage(new TranslationContainer("nukkit.command.timings.verboseDisable")); - Timings.setVerboseEnabled(true); - break; - case "reset": - Timings.reset(); - sender.sendMessage(new TranslationContainer("nukkit.command.timings.reset")); - break; - case "report": - case "paste": - TimingsExport.reportTimings(sender); - break; - } - return true; - } -} diff --git a/src/main/java/cn/nukkit/command/defaults/TitleCommand.java b/src/main/java/cn/nukkit/command/defaults/TitleCommand.java index b7be1a97d31..cc6f2085bb0 100644 --- a/src/main/java/cn/nukkit/command/defaults/TitleCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/TitleCommand.java @@ -3,7 +3,6 @@ import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.command.CommandSender; -import cn.nukkit.command.data.CommandEnum; import cn.nukkit.command.data.CommandParamType; import cn.nukkit.command.data.CommandParameter; import cn.nukkit.lang.TranslationContainer; @@ -13,30 +12,41 @@ * @author Tee7even */ public class TitleCommand extends VanillaCommand { + public TitleCommand(String name) { super(name, "%nukkit.command.title.description", "%nukkit.command.title.usage"); this.setPermission("nukkit.command.title"); this.commandParameters.clear(); this.commandParameters.put("clear", new CommandParameter[]{ - CommandParameter.newType("player", CommandParamType.TARGET), - CommandParameter.newEnum("clear", new CommandEnum("TitleClear", "clear")) + new CommandParameter("player", CommandParamType.TARGET, false), + new CommandParameter("clear", new String[]{"clear"}) }); this.commandParameters.put("reset", new CommandParameter[]{ - CommandParameter.newType("player", CommandParamType.TARGET), - CommandParameter.newEnum("reset", new CommandEnum("TitleReset", "reset")) + new CommandParameter("player", CommandParamType.TARGET, false), + new CommandParameter("reset", new String[]{"reset"}) + }); + this.commandParameters.put("title", new CommandParameter[]{ + new CommandParameter("player", CommandParamType.TARGET, false), + new CommandParameter("title", new String[]{"title"}), + new CommandParameter("titleText", CommandParamType.STRING, false) }); - this.commandParameters.put("set", new CommandParameter[]{ - CommandParameter.newType("player", CommandParamType.TARGET), - CommandParameter.newEnum("titleLocation", new CommandEnum("TitleSet", "title", "subtitle", "actionbar")), - CommandParameter.newType("titleText", CommandParamType.MESSAGE) + this.commandParameters.put("subtitle", new CommandParameter[]{ + new CommandParameter("player", CommandParamType.TARGET, false), + new CommandParameter("subtitle", new String[]{"subtitle"}), + new CommandParameter("titleText", CommandParamType.STRING, false) + }); + this.commandParameters.put("actionbar", new CommandParameter[]{ + new CommandParameter("player", CommandParamType.TARGET, false), + new CommandParameter("actionbar", new String[]{"actionbar"}), + new CommandParameter("titleText", CommandParamType.STRING, false) }); this.commandParameters.put("times", new CommandParameter[]{ - CommandParameter.newType("player", CommandParamType.TARGET), - CommandParameter.newEnum("times", new CommandEnum("TitleTimes", "times")), - CommandParameter.newType("fadeIn", CommandParamType.INT), - CommandParameter.newType("stay", CommandParamType.INT), - CommandParameter.newType("fadeOut", CommandParamType.INT) + new CommandParameter("player", CommandParamType.TARGET, false), + new CommandParameter("times", new String[]{"times"}), + new CommandParameter("fadeIn", CommandParamType.INT, false), + new CommandParameter("stay", CommandParamType.INT, false), + new CommandParameter("fadeOut", CommandParamType.INT, false) }); } @@ -81,10 +91,10 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) player.setSubtitle(args[2]); sender.sendMessage(new TranslationContainer("nukkit.command.title.subtitle", TextFormat.clean(args[2]), player.getName())); break; - /*case "actionbar": - player.sendActionBarTitle(args[2]); - sender.sendMessage(new TranslationContainer("nukkit.command.title.actionbar", new String[]{TextFormat.clean(args[2]), player.getName()})); - break;*/ + case "actionbar": + player.sendActionBar(args[2]); + sender.sendMessage(new TranslationContainer("nukkit.command.title.actionbar", TextFormat.clean(args[2]), player.getName())); + break; default: sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); return false; @@ -111,4 +121,4 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) return true; } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/command/defaults/VanillaCommand.java b/src/main/java/cn/nukkit/command/defaults/VanillaCommand.java index 10d4276fd58..3d7193b44ac 100644 --- a/src/main/java/cn/nukkit/command/defaults/VanillaCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/VanillaCommand.java @@ -3,7 +3,8 @@ import cn.nukkit.command.Command; /** - * author: MagicDroidX + * Commands provided by Nukkit + * @author MagicDroidX * Nukkit Project */ public abstract class VanillaCommand extends Command { diff --git a/src/main/java/cn/nukkit/command/defaults/VersionCommand.java b/src/main/java/cn/nukkit/command/defaults/VersionCommand.java index 5c4e9234aa1..09bdd6da777 100644 --- a/src/main/java/cn/nukkit/command/defaults/VersionCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/VersionCommand.java @@ -35,7 +35,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) if (!this.testPermission(sender)) { return true; } - if (args.length == 0) { + if (args.length == 0 || !sender.hasPermission("nukkit.command.version.plugins")) { sender.sendMessage(new TranslationContainer("nukkit.server.info.extended", sender.getServer().getName(), sender.getServer().getNukkitVersion(), sender.getServer().getCodename(), @@ -44,7 +44,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) String.valueOf(ProtocolInfo.CURRENT_PROTOCOL))); } else { StringBuilder pluginName = new StringBuilder(); - for (String arg : args) pluginName.append(arg).append(" "); + for (String arg : args) pluginName.append(arg).append(' '); pluginName = new StringBuilder(pluginName.toString().trim()); final boolean[] found = {false}; final Plugin[] exactPlugin = {sender.getServer().getPluginManager().getPlugin(pluginName.toString())}; diff --git a/src/main/java/cn/nukkit/command/defaults/WeatherCommand.java b/src/main/java/cn/nukkit/command/defaults/WeatherCommand.java index f85de3c6d19..b65753f6b85 100644 --- a/src/main/java/cn/nukkit/command/defaults/WeatherCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/WeatherCommand.java @@ -10,7 +10,7 @@ import cn.nukkit.level.Level; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class WeatherCommand extends VanillaCommand { @@ -81,6 +81,5 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) sender.sendMessage(new TranslationContainer("commands.weather.usage", this.usageMessage)); return false; } - } } diff --git a/src/main/java/cn/nukkit/command/defaults/WhitelistCommand.java b/src/main/java/cn/nukkit/command/defaults/WhitelistCommand.java index 39b3a487e21..45a5ec175a3 100644 --- a/src/main/java/cn/nukkit/command/defaults/WhitelistCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/WhitelistCommand.java @@ -34,6 +34,7 @@ public WhitelistCommand(String name) { }); } + @Override public boolean execute(CommandSender sender, String commandLabel, String[] args) { if (!this.testPermission(sender)) { @@ -46,24 +47,23 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) } if (args.length == 1) { - if (this.badPerm(sender, args[0].toLowerCase())) { + if (badPerm(sender, args[0].toLowerCase())) { return false; } switch (args[0].toLowerCase()) { case "reload": sender.getServer().reloadWhitelist(); Command.broadcastCommandMessage(sender, new TranslationContainer("commands.whitelist.reloaded")); - return true; case "on": sender.getServer().setPropertyBoolean("white-list", true); + sender.getServer().whitelistEnabled = true; Command.broadcastCommandMessage(sender, new TranslationContainer("commands.whitelist.enabled")); - return true; case "off": sender.getServer().setPropertyBoolean("white-list", false); + sender.getServer().whitelistEnabled = false; Command.broadcastCommandMessage(sender, new TranslationContainer("commands.whitelist.disabled")); - return true; case "list": StringBuilder result = new StringBuilder(); @@ -85,8 +85,8 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) sender.sendMessage(new TranslationContainer("commands.generic.usage", "%commands.whitelist.remove.usage")); return true; } - } else if (args.length == 2) { - if (this.badPerm(sender, args[0].toLowerCase())) { + } else { + if (badPerm(sender, args[0].toLowerCase())) { return false; } switch (args[0].toLowerCase()) { @@ -106,7 +106,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) return true; } - private boolean badPerm(CommandSender sender, String perm) { + private static boolean badPerm(CommandSender sender, String perm) { if (!sender.hasPermission("nukkit.command.whitelist." + perm)) { sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.permission")); diff --git a/src/main/java/cn/nukkit/command/defaults/XpCommand.java b/src/main/java/cn/nukkit/command/defaults/XpCommand.java index 9ca01f11b92..c4e2003904b 100644 --- a/src/main/java/cn/nukkit/command/defaults/XpCommand.java +++ b/src/main/java/cn/nukkit/command/defaults/XpCommand.java @@ -1,7 +1,6 @@ package cn.nukkit.command.defaults; import cn.nukkit.Player; -import cn.nukkit.command.Command; import cn.nukkit.command.CommandSender; import cn.nukkit.command.data.CommandParamType; import cn.nukkit.command.data.CommandParameter; @@ -12,18 +11,15 @@ * Created by Snake1999 on 2016/1/22. * Package cn.nukkit.command.defaults in project nukkit. */ -public class XpCommand extends Command { +public class XpCommand extends VanillaCommand { + public XpCommand(String name) { super(name, "%nukkit.command.xp.description", "%commands.xp.usage"); this.setPermission("nukkit.command.xp"); this.commandParameters.clear(); this.commandParameters.put("default", new CommandParameter[]{ - CommandParameter.newType("amount", CommandParamType.INT), - CommandParameter.newType("player", true, CommandParamType.TARGET) - }); - this.commandParameters.put("level", new CommandParameter[]{ - CommandParameter.newPostfix("amount", "l"), - CommandParameter.newType("player", true, CommandParamType.TARGET) + new CommandParameter("amount|level", CommandParamType.INT, false), + new CommandParameter("player", CommandParamType.TARGET, true) }); } @@ -45,7 +41,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) } amountString = args[0]; playerName = args[1]; - player = sender.getServer().getPlayer(playerName); + player = sender.getServer().getPlayerExact(playerName); } else { if (args.length == 1) { amountString = args[0]; @@ -53,7 +49,7 @@ public boolean execute(CommandSender sender, String commandLabel, String[] args) } else if (args.length == 2) { amountString = args[0]; playerName = args[1].replace("@s", sender.getName()); - player = sender.getServer().getPlayer(playerName); + player = sender.getServer().getPlayerExact(playerName); } else { sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); return true; diff --git a/src/main/java/cn/nukkit/command/simple/SimpleCommand.java b/src/main/java/cn/nukkit/command/simple/SimpleCommand.java index 6fae8ab119f..d111773dcd0 100644 --- a/src/main/java/cn/nukkit/command/simple/SimpleCommand.java +++ b/src/main/java/cn/nukkit/command/simple/SimpleCommand.java @@ -12,8 +12,8 @@ * @author Tee7even */ public class SimpleCommand extends Command { - private Object object; - private Method method; + private final Object object; + private final Method method; private boolean forbidConsole; private int maxArgs; private int minArgs; @@ -37,7 +37,7 @@ public void setMinArgs(int minArgs) { } public void sendUsageMessage(CommandSender sender) { - if (!this.usageMessage.equals("")) { + if (!this.usageMessage.isEmpty()) { sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); } } diff --git a/src/main/java/cn/nukkit/console/NukkitConsole.java b/src/main/java/cn/nukkit/console/NukkitConsole.java index a83a589b770..248c91e9895 100644 --- a/src/main/java/cn/nukkit/console/NukkitConsole.java +++ b/src/main/java/cn/nukkit/console/NukkitConsole.java @@ -2,7 +2,6 @@ import cn.nukkit.Server; import cn.nukkit.event.server.ServerCommandEvent; -import co.aikar.timings.Timings; import lombok.RequiredArgsConstructor; import net.minecrell.terminalconsole.SimpleTerminalConsole; import org.jline.reader.LineReader; @@ -14,27 +13,25 @@ @RequiredArgsConstructor public class NukkitConsole extends SimpleTerminalConsole { - private final Server server; + private final BlockingQueue consoleQueue = new LinkedBlockingQueue<>(); - private AtomicBoolean executingCommands = new AtomicBoolean(false); + private final AtomicBoolean executingCommands = new AtomicBoolean(false); @Override protected boolean isRunning() { - return server.isRunning(); + return Server.getInstance().isRunning(); } @Override protected void runCommand(String command) { if (executingCommands.get()) { - Timings.serverCommandTimer.startTiming(); - ServerCommandEvent event = new ServerCommandEvent(server.getConsoleSender(), command); - if (server.getPluginManager() != null) { - server.getPluginManager().callEvent(event); + ServerCommandEvent event = new ServerCommandEvent(Server.getInstance().getConsoleSender(), command); + if (Server.getInstance().getPluginManager() != null) { + Server.getInstance().getPluginManager().callEvent(event); } if (!event.isCancelled()) { - Server.getInstance().getScheduler().scheduleTask(() -> server.dispatchCommand(event.getSender(), event.getCommand())); + Server.getInstance().getScheduler().scheduleTask(null, () -> Server.getInstance().dispatchCommand(event.getSender(), event.getCommand())); } - Timings.serverCommandTimer.stopTiming(); } else { consoleQueue.add(command); } @@ -50,12 +47,12 @@ public String readLine() { @Override protected void shutdown() { - server.shutdown(); + Server.getInstance().shutdown(); } @Override protected LineReader buildReader(LineReaderBuilder builder) { - builder.completer(new NukkitConsoleCompleter(server)); + builder.completer(new NukkitConsoleCompleter()); builder.appName("Nukkit"); builder.option(LineReader.Option.HISTORY_BEEP, false); builder.option(LineReader.Option.HISTORY_IGNORE_DUPS, true); diff --git a/src/main/java/cn/nukkit/console/NukkitConsoleCompleter.java b/src/main/java/cn/nukkit/console/NukkitConsoleCompleter.java index 60d4943ed46..e898cea8cc7 100644 --- a/src/main/java/cn/nukkit/console/NukkitConsoleCompleter.java +++ b/src/main/java/cn/nukkit/console/NukkitConsoleCompleter.java @@ -14,7 +14,6 @@ @RequiredArgsConstructor public class NukkitConsoleCompleter implements Completer { - private final Server server; @Override public void complete(LineReader lineReader, ParsedLine parsedLine, List candidates) { @@ -35,7 +34,7 @@ public void complete(LineReader lineReader, ParsedLine parsedLine, List 0 && !parsedLine.word().isEmpty()) { String word = parsedLine.word(); SortedSet names = new TreeSet<>(); - server.getOnlinePlayers().values().forEach((p) -> names.add(p.getName())); + Server.getInstance().getOnlinePlayers().values().forEach((p) -> names.add(p.getName())); for (String match : names) { if (!match.toLowerCase().startsWith(word.toLowerCase())) { continue; @@ -46,8 +45,8 @@ public void complete(LineReader lineReader, ParsedLine parsedLine, List commandConsumer) { - for (String command : server.getCommandMap().getCommands().keySet()) { + private static void addCandidates(Consumer commandConsumer) { + for (String command : Server.getInstance().getCommandMap().getCommands().keySet()) { if (!command.contains(":")) { commandConsumer.accept(command); } diff --git a/src/main/java/cn/nukkit/dispenser/BoatDispenseBehavior.java b/src/main/java/cn/nukkit/dispenser/BoatDispenseBehavior.java new file mode 100644 index 00000000000..153698321e1 --- /dev/null +++ b/src/main/java/cn/nukkit/dispenser/BoatDispenseBehavior.java @@ -0,0 +1,36 @@ +package cn.nukkit.dispenser; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockDispenser; +import cn.nukkit.block.BlockID; +import cn.nukkit.block.BlockWater; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityBoat; +import cn.nukkit.item.Item; +import cn.nukkit.level.Location; +import cn.nukkit.math.BlockFace; + +public class BoatDispenseBehavior extends DefaultDispenseBehavior { + + @Override + public Item dispense(BlockDispenser block, BlockFace face, Item item) { + Block target = block.getSide(face); + + if (!(target instanceof BlockWater)) { + if (target.getId() != BlockID.AIR || !(target.down() instanceof BlockWater)) { + return super.dispense(block, face, item); + } + } + + Location pos = target.getLocation().setYaw(face.getHorizontalAngle()); + + EntityBoat boat = (EntityBoat) Entity.createEntity(EntityBoat.NETWORK_ID, block.level.getChunk(pos.getChunkX(), pos.getChunkZ()), + Entity.getDefaultNBT(pos) + .putByte("woodID", item.getDamage()) + ); + + boat.spawnToAll(); + + return null; + } +} diff --git a/src/main/java/cn/nukkit/dispenser/BucketDispenseBehavior.java b/src/main/java/cn/nukkit/dispenser/BucketDispenseBehavior.java index 73cf483bd85..ad35453fe07 100644 --- a/src/main/java/cn/nukkit/dispenser/BucketDispenseBehavior.java +++ b/src/main/java/cn/nukkit/dispenser/BucketDispenseBehavior.java @@ -1,15 +1,42 @@ package cn.nukkit.dispenser; +import cn.nukkit.block.Block; import cn.nukkit.block.BlockDispenser; +import cn.nukkit.block.BlockID; +import cn.nukkit.block.BlockLiquid; import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBucket; +import cn.nukkit.level.Level; +import cn.nukkit.level.particle.SmokeParticle; +import cn.nukkit.math.BlockFace; /** * @author CreeperFace */ -public class BucketDispenseBehavior implements DispenseBehavior { +public class BucketDispenseBehavior extends DefaultDispenseBehavior { @Override - public void dispense(BlockDispenser block, Item stack) { + public Item dispense(BlockDispenser block, BlockFace face, Item item) { + Block target = block.getSide(face); + if (item.getDamage() > 0) { + if (target.canBeFlowedInto()) { + Block replace = Block.get(ItemBucket.getBlockByDamage(item.getDamage())); + + if (replace instanceof BlockLiquid) { + if (block.level.getDimension() == Level.DIMENSION_NETHER) { + replace = Block.get(Block.AIR); + block.level.addParticle(new SmokeParticle(target.add(0.5, 0.5, 0.5)), null, 4); + } + block.level.setBlock(target, replace); + return Item.get(Item.BUCKET); + } + } + } else if (target instanceof BlockLiquid && target.getDamage() == 0) { + target.level.setBlock(target, Block.get(BlockID.AIR)); + return Item.get(Item.BUCKET, ItemBucket.getDamageByTarget(target.getId())); + } + + return super.dispense(block, face, item); } } diff --git a/src/main/java/cn/nukkit/dispenser/ChestBoatDispenseBehavior.java b/src/main/java/cn/nukkit/dispenser/ChestBoatDispenseBehavior.java new file mode 100644 index 00000000000..c84380d0842 --- /dev/null +++ b/src/main/java/cn/nukkit/dispenser/ChestBoatDispenseBehavior.java @@ -0,0 +1,56 @@ +package cn.nukkit.dispenser; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockDispenser; +import cn.nukkit.block.BlockID; +import cn.nukkit.block.BlockWater; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityBoat; +import cn.nukkit.entity.item.EntityChestBoat; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; +import cn.nukkit.level.Location; +import cn.nukkit.math.BlockFace; + +public class ChestBoatDispenseBehavior extends DefaultDispenseBehavior { + + @Override + public Item dispense(BlockDispenser block, BlockFace face, Item item) { + Block target = block.getSide(face); + + if (!(target instanceof BlockWater)) { + if (target.getId() != BlockID.AIR || !(target.down() instanceof BlockWater)) { + return super.dispense(block, face, item); + } + } + + Location pos = target.getLocation().setYaw(face.getHorizontalAngle()); + + EntityBoat boat = (EntityChestBoat) Entity.createEntity(EntityChestBoat.NETWORK_ID, block.level.getChunk(pos.getChunkX(), pos.getChunkZ()), + Entity.getDefaultNBT(pos) + .putByte("Variant", getBoatId(item)) + ); + + boat.spawnToAll(); + + return null; + } + + private static int getBoatId(Item item) { + switch (item.getId()) { + case ItemID.SPRUCE_CHEST_BOAT: + return 1; + case ItemID.BIRCH_CHEST_BOAT: + return 2; + case ItemID.JUNGLE_CHEST_BOAT: + return 3; + case ItemID.ACACIA_CHEST_BOAT: + return 4; + case ItemID.DARK_OAK_CHEST_BOAT: + return 5; + case ItemID.MANGROVE_CHEST_BOAT: + return 6; + } + return 0; + } +} diff --git a/src/main/java/cn/nukkit/dispenser/DefaultDispenseBehavior.java b/src/main/java/cn/nukkit/dispenser/DefaultDispenseBehavior.java index c13002af48e..0e5054ff3a6 100644 --- a/src/main/java/cn/nukkit/dispenser/DefaultDispenseBehavior.java +++ b/src/main/java/cn/nukkit/dispenser/DefaultDispenseBehavior.java @@ -3,6 +3,10 @@ import cn.nukkit.block.BlockDispenser; import cn.nukkit.item.Item; import cn.nukkit.math.BlockFace; +import cn.nukkit.math.BlockFace.Axis; +import cn.nukkit.math.Vector3; + +import java.util.concurrent.ThreadLocalRandom; /** * @author CreeperFace @@ -10,11 +14,31 @@ public class DefaultDispenseBehavior implements DispenseBehavior { @Override - public void dispense(BlockDispenser block, Item stack) { + public Item dispense(BlockDispenser block, BlockFace face, Item item) { + Vector3 dispensePos = block.getDispensePosition(); - } + if (face.getAxis() == Axis.Y) { + dispensePos.y -= 0.125; + } else { + dispensePos.y -= 0.15625; + } + + ThreadLocalRandom rand = ThreadLocalRandom.current(); + Vector3 motion = new Vector3(); + + double offset = rand.nextDouble() * 0.1 + 0.2; + + motion.x = face.getXOffset() * offset; + motion.y = 0.20000000298023224; + motion.z = face.getZOffset() * offset; + + motion.x += rand.nextGaussian() * 0.007499999832361937 * 6; + motion.y += rand.nextGaussian() * 0.007499999832361937 * 6; + motion.z += rand.nextGaussian() * 0.007499999832361937 * 6; - private int getParticleMetadataForFace(BlockFace face) { - return face.getXOffset() + 1 + (face.getZOffset() + 1) * 3; + Item i = item.clone(); + i.setCount(1); + block.level.dropItem(dispensePos, i, motion); + return null; } } diff --git a/src/main/java/cn/nukkit/dispenser/DispenseBehavior.java b/src/main/java/cn/nukkit/dispenser/DispenseBehavior.java index 9019b20ff16..54d2905a56d 100644 --- a/src/main/java/cn/nukkit/dispenser/DispenseBehavior.java +++ b/src/main/java/cn/nukkit/dispenser/DispenseBehavior.java @@ -2,12 +2,12 @@ import cn.nukkit.block.BlockDispenser; import cn.nukkit.item.Item; +import cn.nukkit.math.BlockFace; /** * @author CreeperFace */ public interface DispenseBehavior { - void dispense(BlockDispenser block, Item item); - + Item dispense(BlockDispenser block, BlockFace face, Item item); } diff --git a/src/main/java/cn/nukkit/dispenser/DispenseBehaviorRegister.java b/src/main/java/cn/nukkit/dispenser/DispenseBehaviorRegister.java index 9cf02b8558b..78e3ae5a143 100644 --- a/src/main/java/cn/nukkit/dispenser/DispenseBehaviorRegister.java +++ b/src/main/java/cn/nukkit/dispenser/DispenseBehaviorRegister.java @@ -1,15 +1,17 @@ package cn.nukkit.dispenser; -import java.util.HashMap; -import java.util.Map; +import cn.nukkit.block.BlockID; +import cn.nukkit.item.ItemID; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; /** * @author CreeperFace */ -public class DispenseBehaviorRegister { +public final class DispenseBehaviorRegister { - private static final Map behaviors = new HashMap<>(); - private static DispenseBehavior defaultBehavior = new DefaultDispenseBehavior(); + private static final Int2ObjectMap behaviors = new Int2ObjectOpenHashMap<>(); + private static final DispenseBehavior defaultBehavior = new DefaultDispenseBehavior(); public static void registerBehavior(int itemId, DispenseBehavior behavior) { behaviors.put(itemId, behavior); @@ -22,4 +24,85 @@ public static DispenseBehavior getBehavior(int id) { public static void removeDispenseBehavior(int id) { behaviors.remove(id); } + + public static void init() { + registerBehavior(ItemID.BOAT, new BoatDispenseBehavior()); + registerBehavior(ItemID.BUCKET, new BucketDispenseBehavior()); + registerBehavior(ItemID.DYE, new DyeDispenseBehavior()); + registerBehavior(ItemID.FIREWORKS, new FireworksDispenseBehavior()); + registerBehavior(ItemID.FLINT_AND_STEEL, new FlintAndSteelDispenseBehavior()); + registerBehavior(BlockID.SHULKER_BOX, new ShulkerBoxDispenseBehavior()); + registerBehavior(BlockID.UNDYED_SHULKER_BOX, new UndyedShulkerBoxDispenseBehavior()); + registerBehavior(ItemID.SPAWN_EGG, new SpawnEggDispenseBehavior()); + registerBehavior(BlockID.TNT, new TNTDispenseBehavior()); + registerBehavior(ItemID.FIRE_CHARGE, new FireChargeDispenseBehavior()); + registerBehavior(ItemID.SHEARS, new ShearsDispenseBehaviour()); + registerBehavior(ItemID.ARROW, new ProjectileDispenseBehavior("Arrow") { + @Override + protected double getMotion() { + return super.getMotion() * 1.5; + } + }); + //TODO: tipped arrow + //TODO: spectral arrow + registerBehavior(ItemID.EGG, new ProjectileDispenseBehavior("Egg")); + registerBehavior(ItemID.SNOWBALL, new ProjectileDispenseBehavior("Snowball")); + registerBehavior(ItemID.EXPERIENCE_BOTTLE, new ProjectileDispenseBehavior("ThrownExpBottle") { + @Override + protected float getAccuracy() { + return super.getAccuracy() * 0.5f; + } + + @Override + protected double getMotion() { + return super.getMotion() * 1.25; + } + }); + registerBehavior(ItemID.SPLASH_POTION, new ProjectileDispenseBehavior("ThrownPotion") { + @Override + protected float getAccuracy() { + return super.getAccuracy() * 0.5f; + } + + @Override + protected double getMotion() { + return super.getMotion() * 1.25; + } + }); + registerBehavior(ItemID.LINGERING_POTION, new ProjectileDispenseBehavior("LingeringPotion") { + @Override + protected float getAccuracy() { + return super.getAccuracy() * 0.5f; + } + + @Override + protected double getMotion() { + return super.getMotion() * 1.25; + } + }); + registerBehavior(ItemID.TRIDENT, new ProjectileDispenseBehavior("ThrownTrident") { + @Override + protected float getAccuracy() { + return super.getAccuracy() * 0.5f; + } + + @Override + protected double getMotion() { + return super.getMotion() * 1.25; + } + }); + + registerBehavior(ItemID.ACACIA_CHEST_BOAT, new ChestBoatDispenseBehavior()); + registerBehavior(ItemID.DARK_OAK_CHEST_BOAT, new ChestBoatDispenseBehavior()); + registerBehavior(ItemID.BIRCH_CHEST_BOAT, new ChestBoatDispenseBehavior()); + registerBehavior(ItemID.JUNGLE_CHEST_BOAT, new ChestBoatDispenseBehavior()); + registerBehavior(ItemID.MANGROVE_CHEST_BOAT, new ChestBoatDispenseBehavior()); + registerBehavior(ItemID.SPRUCE_CHEST_BOAT, new ChestBoatDispenseBehavior()); + registerBehavior(ItemID.OAK_CHEST_BOAT, new ChestBoatDispenseBehavior()); + + registerBehavior(ItemID.MINECART, new MinecartDispenseBehavior()); + registerBehavior(ItemID.MINECART_WITH_CHEST, new MinecartDispenseBehavior()); + registerBehavior(ItemID.MINECART_WITH_HOPPER, new MinecartDispenseBehavior()); + registerBehavior(ItemID.MINECART_WITH_TNT, new MinecartDispenseBehavior()); + } } diff --git a/src/main/java/cn/nukkit/dispenser/DyeDispenseBehavior.java b/src/main/java/cn/nukkit/dispenser/DyeDispenseBehavior.java new file mode 100644 index 00000000000..e226d6886ab --- /dev/null +++ b/src/main/java/cn/nukkit/dispenser/DyeDispenseBehavior.java @@ -0,0 +1,26 @@ +package cn.nukkit.dispenser; + +import cn.nukkit.block.*; +import cn.nukkit.item.Item; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.DyeColor; + +public class DyeDispenseBehavior extends DefaultDispenseBehavior { + + @Override + public Item dispense(BlockDispenser block, BlockFace face, Item item) { + Block target = block.getSide(face); + + if (DyeColor.getByDyeData(item.getDamage()) == DyeColor.WHITE) { + if (target instanceof BlockCrops || target instanceof BlockSapling || target instanceof BlockTallGrass + || target instanceof BlockDoublePlant || target instanceof BlockMushroom) { + target.onActivate(item); + + } + + return null; + } + + return super.dispense(block, face, item); + } +} diff --git a/src/main/java/cn/nukkit/dispenser/EmptyBucketDispenseBehavior.java b/src/main/java/cn/nukkit/dispenser/EmptyBucketDispenseBehavior.java deleted file mode 100644 index f01f4e1619f..00000000000 --- a/src/main/java/cn/nukkit/dispenser/EmptyBucketDispenseBehavior.java +++ /dev/null @@ -1,15 +0,0 @@ -package cn.nukkit.dispenser; - -import cn.nukkit.block.BlockDispenser; -import cn.nukkit.item.Item; - -/** - * @author CreeperFace - */ -public class EmptyBucketDispenseBehavior implements DispenseBehavior { - - @Override - public void dispense(BlockDispenser block, Item item) { - - } -} diff --git a/src/main/java/cn/nukkit/dispenser/FireChargeDispenseBehavior.java b/src/main/java/cn/nukkit/dispenser/FireChargeDispenseBehavior.java new file mode 100644 index 00000000000..bb16d68c492 --- /dev/null +++ b/src/main/java/cn/nukkit/dispenser/FireChargeDispenseBehavior.java @@ -0,0 +1,29 @@ +package cn.nukkit.dispenser; + +import cn.nukkit.block.BlockDispenser; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.projectile.EntityProjectile; +import cn.nukkit.item.Item; +import cn.nukkit.math.BlockFace; +import cn.nukkit.math.Vector3; + +public class FireChargeDispenseBehavior extends DefaultDispenseBehavior { + + @Override + public Item dispense(BlockDispenser block, BlockFace face, Item item) { + Vector3 dispensePos = block.getDispensePosition(); + + Entity projectile = Entity.createEntity("BlazeFireBall", block.level.getChunk(dispensePos.getChunkX(), dispensePos.getChunkZ()), Entity.getDefaultNBT(dispensePos)); + + if (!(projectile instanceof EntityProjectile)) { + return super.dispense(block, face, item); + } + + projectile.setMotion(new Vector3(face.getXOffset(), face.getYOffset() + 0.1f, face.getZOffset()).normalize().multiply(1.3)); + ((EntityProjectile) projectile).inaccurate(6f); + ((EntityProjectile) projectile).updateRotation(); + + projectile.spawnToAll(); + return null; + } +} diff --git a/src/main/java/cn/nukkit/dispenser/FireworksDispenseBehavior.java b/src/main/java/cn/nukkit/dispenser/FireworksDispenseBehavior.java new file mode 100644 index 00000000000..ad792d40883 --- /dev/null +++ b/src/main/java/cn/nukkit/dispenser/FireworksDispenseBehavior.java @@ -0,0 +1,23 @@ +package cn.nukkit.dispenser; + +import cn.nukkit.block.BlockDispenser; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityFirework; +import cn.nukkit.item.Item; +import cn.nukkit.math.BlockFace; +import cn.nukkit.math.Vector3; +import cn.nukkit.nbt.NBTIO; +import cn.nukkit.nbt.tag.CompoundTag; + +public class FireworksDispenseBehavior extends DefaultDispenseBehavior { + + @Override + public Item dispense(BlockDispenser block, BlockFace face, Item item) { + BlockFace opposite = face.getOpposite(); + Vector3 pos = block.getSide(face).add(0.5 + opposite.getXOffset() * 0.2, 0.5 + opposite.getYOffset() * 0.2, 0.5 + opposite.getZOffset() * 0.2); + CompoundTag nbt = Entity.getDefaultNBT(pos); + nbt.putCompound("FireworkItem", NBTIO.putItemHelper(item)); + Entity.createEntity(EntityFirework.NETWORK_ID, block.level.getChunk(pos.getChunkX(), pos.getChunkZ()), nbt).spawnToAll(); + return null; + } +} diff --git a/src/main/java/cn/nukkit/dispenser/FlintAndSteelDispenseBehavior.java b/src/main/java/cn/nukkit/dispenser/FlintAndSteelDispenseBehavior.java new file mode 100644 index 00000000000..599251f29d0 --- /dev/null +++ b/src/main/java/cn/nukkit/dispenser/FlintAndSteelDispenseBehavior.java @@ -0,0 +1,30 @@ +package cn.nukkit.dispenser; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockDispenser; +import cn.nukkit.block.BlockID; +import cn.nukkit.item.Item; +import cn.nukkit.math.BlockFace; + +public class FlintAndSteelDispenseBehavior extends DefaultDispenseBehavior { + + @Override + public Item dispense(BlockDispenser block, BlockFace face, Item item) { + Block target = block.getSide(face); + + if (target.getId() == BlockID.AIR) { + Block down = target.down(); + if (down.getId() != BlockID.OBSIDIAN || !down.level.createPortal(down)) { + boolean soulFire = down.getId() == Block.SOUL_SAND || down.getId() == Block.SOUL_SOIL; + block.level.setBlock(target, Block.get(soulFire ? BlockID.SOUL_FIRE : BlockID.FIRE)); + } + down.level.addSound(down, cn.nukkit.level.Sound.MOB_GHAST_FIREBALL); + item.useOn(target); + } else if (target.getId() == BlockID.TNT) { + target.onActivate(item); + item.useOn(target); + } + + return item; + } +} diff --git a/src/main/java/cn/nukkit/dispenser/MinecartDispenseBehavior.java b/src/main/java/cn/nukkit/dispenser/MinecartDispenseBehavior.java new file mode 100644 index 00000000000..ef681d626c7 --- /dev/null +++ b/src/main/java/cn/nukkit/dispenser/MinecartDispenseBehavior.java @@ -0,0 +1,62 @@ +package cn.nukkit.dispenser; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockDispenser; +import cn.nukkit.block.BlockRail; +import cn.nukkit.entity.Entity; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; +import cn.nukkit.math.BlockFace; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.DoubleTag; +import cn.nukkit.nbt.tag.FloatTag; +import cn.nukkit.nbt.tag.ListTag; +import cn.nukkit.utils.Rail; + +public class MinecartDispenseBehavior extends DefaultDispenseBehavior { + + @Override + public Item dispense(BlockDispenser block, BlockFace face, Item item) { + Block target = block.getSide(face); + + if (Rail.isRailBlock(target)) { + Rail.Orientation type = ((BlockRail) target).getOrientation(); + double adjacent = 0.0D; + if (type.isAscending()) { + adjacent = 0.5D; + } + + Entity minecart = Entity.createEntity(getMinecartId(item), + block.level.getChunk(target.getChunkX(), target.getChunkZ()), new CompoundTag("") + .putList(new ListTag<>("Pos") + .add(new DoubleTag("", target.getX() + 0.5)) + .add(new DoubleTag("", target.getY() + 0.0625D + adjacent)) + .add(new DoubleTag("", target.getZ() + 0.5))) + .putList(new ListTag<>("Motion") + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0))) + .putList(new ListTag<>("Rotation") + .add(new FloatTag("", 0)) + .add(new FloatTag("", 0))) + ); + + minecart.spawnToAll(); + return null; + } + + return super.dispense(block, face, item); + } + + private String getMinecartId(Item item) { + switch (item.getId()) { + case ItemID.MINECART_WITH_CHEST: + return "MinecartChest"; + case ItemID.MINECART_WITH_HOPPER: + return "MinecartHopper"; + case ItemID.MINECART_WITH_TNT: + return "MinecartTnt"; + } + return "MinecartRideable"; + } +} diff --git a/src/main/java/cn/nukkit/dispenser/ProjectileDispenseBehavior.java b/src/main/java/cn/nukkit/dispenser/ProjectileDispenseBehavior.java index 52c2006408c..19993682f54 100644 --- a/src/main/java/cn/nukkit/dispenser/ProjectileDispenseBehavior.java +++ b/src/main/java/cn/nukkit/dispenser/ProjectileDispenseBehavior.java @@ -2,8 +2,9 @@ import cn.nukkit.block.BlockDispenser; import cn.nukkit.entity.Entity; +import cn.nukkit.entity.projectile.EntityProjectile; import cn.nukkit.item.Item; -import cn.nukkit.level.Position; +import cn.nukkit.item.ItemID; import cn.nukkit.math.BlockFace; import cn.nukkit.math.Vector3; import cn.nukkit.nbt.tag.CompoundTag; @@ -11,45 +12,61 @@ /** * @author CreeperFace */ -public class ProjectileDispenseBehavior implements DispenseBehavior { +public class ProjectileDispenseBehavior extends DefaultDispenseBehavior { - private String entityType; - - public ProjectileDispenseBehavior() { - - } + private final String entityType; public ProjectileDispenseBehavior(String entity) { this.entityType = entity; } @Override - public void dispense(BlockDispenser source, Item item) { - Position dispensePos = Position.fromObject(source.getDispensePosition(), source.getLevel()); + public Item dispense(BlockDispenser source, BlockFace face, Item item) { + Vector3 dispensePos = source.getDispensePosition(); + CompoundTag nbt = Entity.getDefaultNBT(dispensePos); - this.correctNBT(nbt); + this.correctNBT(nbt, item); - BlockFace face = source.getFacing(); + Entity projectile = Entity.createEntity(entityType, source.level.getChunk(dispensePos.getChunkX(), dispensePos.getChunkZ()), nbt); - Entity projectile = Entity.createEntity(getEntityType(), dispensePos.getLevel().getChunk(dispensePos.getFloorX(), dispensePos.getFloorZ()), nbt); - if (projectile == null) { - return; + if (!(projectile instanceof EntityProjectile)) { + return super.dispense(source, face, item); } - projectile.setMotion(new Vector3(face.getXOffset(), face.getYOffset() + 0.1f, face.getZOffset()).multiply(6)); + Vector3 motion = new Vector3(face.getXOffset(), face.getYOffset() + 0.1f, face.getZOffset()) + .normalize(); + + projectile.setMotion(motion); + ((EntityProjectile) projectile).inaccurate(getAccuracy()); + projectile.setMotion(projectile.getMotion().multiply(getMotion())); + + ((EntityProjectile) projectile).updateRotation(); + projectile.spawnToAll(); + return null; + } + + protected double getMotion() { + return 1.1; } - protected String getEntityType() { - return this.entityType; + protected float getAccuracy() { + return 6; } /** - * you can add extra data of projectile here + * You can add extra data of projectile here * * @param nbt tag + * @param item item */ - protected void correctNBT(CompoundTag nbt) { - + protected void correctNBT(CompoundTag nbt, Item item) { + if (item != null) { + if (item.getId() == ItemID.SPLASH_POTION || item.getId() == ItemID.LINGERING_POTION) { + nbt.putInt("PotionId", item.getDamage()); + } else if (item.getId() == ItemID.ARROW && item.getDamage() > 0) { + nbt.putByte("arrowData", item.getDamage()); + } + } } } diff --git a/src/main/java/cn/nukkit/dispenser/ShearsDispenseBehaviour.java b/src/main/java/cn/nukkit/dispenser/ShearsDispenseBehaviour.java new file mode 100644 index 00000000000..e0f805a11a1 --- /dev/null +++ b/src/main/java/cn/nukkit/dispenser/ShearsDispenseBehaviour.java @@ -0,0 +1,35 @@ +package cn.nukkit.dispenser; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockDispenser; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.passive.EntitySheep; +import cn.nukkit.item.Item; +import cn.nukkit.math.BlockFace; +import cn.nukkit.math.SimpleAxisAlignedBB; + +public class ShearsDispenseBehaviour extends DefaultDispenseBehavior { + + @Override + public Item dispense(BlockDispenser block, BlockFace face, Item item) { + Block target = block.getSide(face); + item = item.clone(); + for (Entity entity : block.getLevel().getNearbyEntities(new SimpleAxisAlignedBB( + target.x, + target.y, + target.z, + target.x + 1, + target.y + 1, + target.z + 1 + ))) { + if (entity instanceof EntitySheep) { + if (!((EntitySheep) entity).isSheared()) { + ((EntitySheep) entity).shear(true); + item.useOn(entity); + return item.getDamage() >= item.getMaxDurability() ? null : item; + } + } + } + return item; + } +} diff --git a/src/main/java/cn/nukkit/dispenser/ShulkerBoxDispenseBehavior.java b/src/main/java/cn/nukkit/dispenser/ShulkerBoxDispenseBehavior.java new file mode 100644 index 00000000000..aa72281a048 --- /dev/null +++ b/src/main/java/cn/nukkit/dispenser/ShulkerBoxDispenseBehavior.java @@ -0,0 +1,40 @@ +package cn.nukkit.dispenser; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockDispenser; +import cn.nukkit.block.BlockID; +import cn.nukkit.blockentity.BlockEntity; +import cn.nukkit.item.Item; +import cn.nukkit.math.BlockFace; +import cn.nukkit.nbt.tag.CompoundTag; + +public class ShulkerBoxDispenseBehavior extends DefaultDispenseBehavior { + + @Override + public Item dispense(BlockDispenser block, BlockFace face, Item item) { + Block target = block.getSide(face); + + if (target.getId() == Block.AIR) { + CompoundTag nbt = BlockEntity.getDefaultCompound(target, BlockEntity.SHULKER_BOX); + nbt.putByte("facing", BlockFace.UP.getIndex()); + + if (item.hasCustomName()) { + nbt.putString("CustomName", item.getCustomName()); + } + + CompoundTag tag = item.getNamedTag(); + + if (tag != null) { + if (tag.contains("Items")) { + nbt.putList(tag.getList("Items")); + } + } + + block.level.setBlock(target, Block.get(BlockID.SHULKER_BOX, item.getDamage()), true); + BlockEntity.createBlockEntity(BlockEntity.SHULKER_BOX, block.level.getChunk(target.getChunkX(), target.getChunkZ()), nbt); + return null; + } + + return item; + } +} diff --git a/src/main/java/cn/nukkit/dispenser/SpawnEggDispenseBehavior.java b/src/main/java/cn/nukkit/dispenser/SpawnEggDispenseBehavior.java new file mode 100644 index 00000000000..7d495adeb6f --- /dev/null +++ b/src/main/java/cn/nukkit/dispenser/SpawnEggDispenseBehavior.java @@ -0,0 +1,30 @@ +package cn.nukkit.dispenser; + +import cn.nukkit.block.BlockDispenser; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.EntityLiving; +import cn.nukkit.item.Item; +import cn.nukkit.math.BlockFace; +import cn.nukkit.math.Vector3; + +public class SpawnEggDispenseBehavior extends DefaultDispenseBehavior { + + @Override + public Item dispense(BlockDispenser block, BlockFace face, Item item) { + Vector3 pos = block.getSide(face).add(0.5, 0.7, 0.5); + + Entity entity = Entity.createEntity(item.getDamage(), block.level.getChunk(pos.getChunkX(), pos.getChunkZ()), + Entity.getDefaultNBT(pos)); + + if (entity != null) { + if (item.hasCustomName() && entity instanceof EntityLiving) { + entity.setNameTag(item.getCustomName()); + } + + entity.spawnToAll(); + return null; + } + + return super.dispense(block, face, item); + } +} diff --git a/src/main/java/cn/nukkit/dispenser/TNTDispenseBehavior.java b/src/main/java/cn/nukkit/dispenser/TNTDispenseBehavior.java new file mode 100644 index 00000000000..1f577815deb --- /dev/null +++ b/src/main/java/cn/nukkit/dispenser/TNTDispenseBehavior.java @@ -0,0 +1,22 @@ +package cn.nukkit.dispenser; + +import cn.nukkit.block.BlockDispenser; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityPrimedTNT; +import cn.nukkit.item.Item; +import cn.nukkit.math.BlockFace; +import cn.nukkit.math.Vector3; + +public class TNTDispenseBehavior extends DefaultDispenseBehavior { + + @Override + public Item dispense(BlockDispenser block, BlockFace face, Item item) { + Vector3 pos = block.getSide(face).add(0.5, 0, 0.5); + + Entity.createEntity(EntityPrimedTNT.NETWORK_ID, + block.getLevel().getChunk(pos.getChunkX(), pos.getChunkZ()), + Entity.getDefaultNBT(pos)).spawnToAll(); + + return null; + } +} diff --git a/src/main/java/cn/nukkit/dispenser/UndyedShulkerBoxDispenseBehavior.java b/src/main/java/cn/nukkit/dispenser/UndyedShulkerBoxDispenseBehavior.java new file mode 100644 index 00000000000..b14129f4134 --- /dev/null +++ b/src/main/java/cn/nukkit/dispenser/UndyedShulkerBoxDispenseBehavior.java @@ -0,0 +1,40 @@ +package cn.nukkit.dispenser; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockDispenser; +import cn.nukkit.block.BlockID; +import cn.nukkit.blockentity.BlockEntity; +import cn.nukkit.item.Item; +import cn.nukkit.math.BlockFace; +import cn.nukkit.nbt.tag.CompoundTag; + +public class UndyedShulkerBoxDispenseBehavior extends DefaultDispenseBehavior { + + @Override + public Item dispense(BlockDispenser block, BlockFace face, Item item) { + Block target = block.getSide(face); + + if (target.getId() == Block.AIR) { + CompoundTag nbt = BlockEntity.getDefaultCompound(target, BlockEntity.SHULKER_BOX); + nbt.putByte("facing", BlockFace.UP.getIndex()); + + if (item.hasCustomName()) { + nbt.putString("CustomName", item.getCustomName()); + } + + CompoundTag tag = item.getNamedTag(); + + if (tag != null) { + if (tag.contains("Items")) { + nbt.putList(tag.getList("Items")); + } + } + + block.level.setBlock(target, Block.get(BlockID.UNDYED_SHULKER_BOX, 0), true); + BlockEntity.createBlockEntity(BlockEntity.SHULKER_BOX, block.level.getChunk(target.getChunkX(), target.getChunkZ()), nbt); + return null; + } + + return item; + } +} diff --git a/src/main/java/cn/nukkit/entity/Attribute.java b/src/main/java/cn/nukkit/entity/Attribute.java index 68faacc5653..bd7566e1744 100644 --- a/src/main/java/cn/nukkit/entity/Attribute.java +++ b/src/main/java/cn/nukkit/entity/Attribute.java @@ -1,17 +1,16 @@ package cn.nukkit.entity; -/** - * Attribute - * - * @author Box, MagicDroidX(code), PeratX @ Nukkit Project - * @since Nukkit 1.0 | Nukkit API 1.0.0 - */ import cn.nukkit.utils.ServerException; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import java.util.HashMap; -import java.util.Map; import java.util.Objects; +/** + * Attribute + * + * @author Box, MagicDroidX(code), PeratX @ Nukkit Project + */ public class Attribute implements Cloneable { public static final int ABSORPTION = 0; @@ -21,14 +20,18 @@ public class Attribute implements Cloneable { public static final int MAX_HEALTH = 4; public static final int MOVEMENT_SPEED = 5; public static final int FOLLOW_RANGE = 6; - public static final int MAX_HUNGER = 7; - public static final int FOOD = 7; + public static final int FOOD = 7, MAX_HUNGER = FOOD; public static final int ATTACK_DAMAGE = 8; public static final int EXPERIENCE_LEVEL = 9; public static final int EXPERIENCE = 10; - public static final int LUCK = 11; + public static final int UNDERWATER_MOVEMENT = 11; + public static final int LUCK = 12; + public static final int FALL_DAMAGE = 13; + public static final int HORSE_JUMP_STRENGTH = 14; + public static final int ZOMBIE_SPAWN_REINFORCEMENTS = 15; + public static final int LAVA_MOVEMENT = 16; - protected static Map attributes = new HashMap<>(); + protected static Int2ObjectMap attributes = new Int2ObjectOpenHashMap<>(); protected float minValue; protected float maxValue; @@ -36,7 +39,7 @@ public class Attribute implements Cloneable { protected float currentValue; protected String name; protected boolean shouldSend; - private int id; + private final int id; private Attribute(int id, String name, float minValue, float maxValue, float defaultValue, boolean shouldSend) { this.id = id; @@ -51,7 +54,7 @@ private Attribute(int id, String name, float minValue, float maxValue, float def public static void init() { addAttribute(ABSORPTION, "minecraft:absorption", 0.00f, 340282346638528859811704183484516925440.00f, 0.00f); addAttribute(SATURATION, "minecraft:player.saturation", 0.00f, 20.00f, 5.00f); - addAttribute(EXHAUSTION, "minecraft:player.exhaustion", 0.00f, 5.00f, 0.41f); + addAttribute(EXHAUSTION, "minecraft:player.exhaustion", 0.00f, 5.00f, 0.00f, false); addAttribute(KNOCKBACK_RESISTANCE, "minecraft:knockback_resistance", 0.00f, 1.00f, 0.00f); addAttribute(MAX_HEALTH, "minecraft:health", 0.00f, 20.00f, 20.00f); addAttribute(MOVEMENT_SPEED, "minecraft:movement", 0.00f, 340282346638528859811704183484516925440.00f, 0.10f); @@ -60,7 +63,12 @@ public static void init() { addAttribute(ATTACK_DAMAGE, "minecraft:attack_damage", 0.00f, 340282346638528859811704183484516925440.00f, 1.00f, false); addAttribute(EXPERIENCE_LEVEL, "minecraft:player.level", 0.00f, 24791.00f, 0.00f); addAttribute(EXPERIENCE, "minecraft:player.experience", 0.00f, 1.00f, 0.00f); - addAttribute(LUCK, "minecraft:luck", -1024, 1024, 0); + addAttribute(UNDERWATER_MOVEMENT, "minecraft:underwater_movement", 0.0f, 340282346638528859811704183484516925440.0f, 0.02f); + addAttribute(LUCK, "minecraft:luck", -1024.0f, 1024.0f, 0.0f); + addAttribute(FALL_DAMAGE, "minecraft:fall_damage", 0.0f, 340282346638528859811704183484516925440.0f, 1.0f); + addAttribute(HORSE_JUMP_STRENGTH, "minecraft:horse.jump_strength", 0.0f, 2.0f, 0.7f); + addAttribute(ZOMBIE_SPAWN_REINFORCEMENTS, "minecraft:zombie.spawn_reinforcements", 0.0f, 1.0f, 0.0f); + addAttribute(LAVA_MOVEMENT, "minecraft:lava_movement", 0.00f, 340282346638528859811704183484516925440.00f, 0.02f); } public static Attribute addAttribute(int id, String name, float minValue, float maxValue, float defaultValue) { @@ -88,7 +96,7 @@ public static Attribute getAttribute(int id) { */ public static Attribute getAttributeByName(String name) { for (Attribute a : attributes.values()) { - if (Objects.equals(a.getName(), name)) { + if (Objects.equals(a.name, name)) { return a.clone(); } } @@ -100,7 +108,7 @@ public float getMinValue() { } public Attribute setMinValue(float minValue) { - if (minValue > this.getMaxValue()) { + if (minValue > this.maxValue) { throw new IllegalArgumentException("Value " + minValue + " is bigger than the maxValue!"); } this.minValue = minValue; @@ -112,7 +120,7 @@ public float getMaxValue() { } public Attribute setMaxValue(float maxValue) { - if (maxValue < this.getMinValue()) { + if (maxValue < this.minValue) { throw new IllegalArgumentException("Value " + maxValue + " is bigger than the minValue!"); } this.maxValue = maxValue; @@ -124,7 +132,7 @@ public float getDefaultValue() { } public Attribute setDefaultValue(float defaultValue) { - if (defaultValue > this.getMaxValue() || defaultValue < this.getMinValue()) { + if (defaultValue > this.maxValue || defaultValue < this.minValue) { throw new IllegalArgumentException("Value " + defaultValue + " exceeds the range!"); } this.defaultValue = defaultValue; @@ -140,11 +148,11 @@ public Attribute setValue(float value) { } public Attribute setValue(float value, boolean fit) { - if (value > this.getMaxValue() || value < this.getMinValue()) { + if (value > this.maxValue || value < this.minValue) { if (!fit) { throw new IllegalArgumentException("Value " + value + " exceeds the range!"); } - value = Math.min(Math.max(value, this.getMinValue()), this.getMaxValue()); + value = Math.min(Math.max(value, this.minValue), this.maxValue); } this.currentValue = value; return this; diff --git a/src/main/java/cn/nukkit/entity/BaseEntity.java b/src/main/java/cn/nukkit/entity/BaseEntity.java new file mode 100644 index 00000000000..f27a4c8a608 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/BaseEntity.java @@ -0,0 +1,98 @@ +package cn.nukkit.entity; + +import cn.nukkit.Player; +import cn.nukkit.block.Block; +import cn.nukkit.item.Item; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; + +/** + * The base class of all mobs + */ +public abstract class BaseEntity extends EntityCreature implements EntityAgeable { + + public BaseEntity(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + public abstract int getKillExperience(); + + @Override + protected boolean applyNameTag(Player player, Item nameTag) { + String name = nameTag.getCustomName(); + + if (!name.isEmpty()) { + this.namedTag.putString("CustomName", name); + this.namedTag.putBoolean("CustomNameVisible", true); + this.setNameTag(name); + this.setNameTagVisible(true); + return true; // onInteract: true = decrease count + } + + return false; + } + + @Override + protected void checkGroundState(double movX, double movY, double movZ, double dx, double dy, double dz) { + if (onGround && movX == 0 && movY == 0 && movZ == 0 && dx == 0 && dy == 0 && dz == 0) { + return; + } + this.isCollidedVertically = movY != dy; + this.isCollidedHorizontally = (movX != dx || movZ != dz); + this.isCollided = (this.isCollidedHorizontally || this.isCollidedVertically); + this.onGround = (movY != dy && movY < 0); + } + + @Override + protected void checkBlockCollision() { + for (Block block : this.getCollisionBlocks()) { + block.onEntityCollide(this); + } + + // TODO: portals + } + + @Override + public boolean entityBaseTick(int tickDiff) { + if (!this.closed) { + if (!this.isAlive()) { + this.despawnFromAll(); + this.close(); + return false; + } + + if (!this.isImmobile()) { + if (this.age % 10 == 0) { + if (this.onGround) { + if (level.getBlock(chunk, getFloorX(), getFloorY() - 1, getFloorZ(), false).canPassThrough()) { + this.onGround = false; + } + } + } + + if (!this.onGround || Math.abs(this.motionX) > 0.1 || Math.abs(this.motionY) > 0.1 || Math.abs(this.motionZ) > 0.1) { + this.motionY -= 0.08; + this.move(this.motionX, this.motionY, this.motionZ); + } + + this.motionX *= 0.9; + this.motionY *= 0.9; + this.motionZ *= 0.9; + } + + super.entityBaseTick(tickDiff); // updateMovement is called at the end of onUpdate after entityBaseTick is called + return true; + } + return false; + } + + @Override + public boolean isBaby() { + return false; + } + + @Override + public void setBaby(boolean baby) { + //TODO + } +} diff --git a/src/main/java/cn/nukkit/entity/Entity.java b/src/main/java/cn/nukkit/entity/Entity.java index 75c5829669c..aa96f40b6f3 100644 --- a/src/main/java/cn/nukkit/entity/Entity.java +++ b/src/main/java/cn/nukkit/entity/Entity.java @@ -2,20 +2,32 @@ import cn.nukkit.Player; import cn.nukkit.Server; -import cn.nukkit.block.*; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockFire; +import cn.nukkit.block.BlockID; +import cn.nukkit.entity.custom.CustomEntity; +import cn.nukkit.entity.custom.EntityDefinition; +import cn.nukkit.entity.custom.EntityManager; import cn.nukkit.entity.data.*; +import cn.nukkit.entity.item.EntityItem; +import cn.nukkit.entity.item.EntityMinecartEmpty; +import cn.nukkit.entity.item.EntityVehicle; import cn.nukkit.event.Event; import cn.nukkit.event.entity.*; import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; -import cn.nukkit.event.entity.EntityPortalEnterEvent.PortalType; import cn.nukkit.event.player.PlayerInteractEvent; import cn.nukkit.event.player.PlayerInteractEvent.Action; import cn.nukkit.event.player.PlayerTeleportEvent; import cn.nukkit.item.Item; import cn.nukkit.item.ItemID; import cn.nukkit.item.enchantment.Enchantment; -import cn.nukkit.level.*; +import cn.nukkit.level.GameRule; +import cn.nukkit.level.Level; +import cn.nukkit.level.Location; +import cn.nukkit.level.Position; import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.persistence.PersistentDataContainer; +import cn.nukkit.level.persistence.impl.PersistentDataContainerEntityWrapper; import cn.nukkit.math.*; import cn.nukkit.metadata.MetadataValue; import cn.nukkit.metadata.Metadatable; @@ -27,17 +39,15 @@ import cn.nukkit.network.protocol.types.EntityLink; import cn.nukkit.plugin.Plugin; import cn.nukkit.potion.Effect; -import cn.nukkit.scheduler.Task; import cn.nukkit.utils.ChunkException; import cn.nukkit.utils.MainLogger; -import co.aikar.timings.Timing; -import co.aikar.timings.Timings; -import co.aikar.timings.TimingsHistory; +import cn.nukkit.utils.Utils; import com.google.common.collect.Iterables; import java.lang.reflect.Constructor; import java.util.*; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ThreadLocalRandom; import static cn.nukkit.network.protocol.SetEntityLinkPacket.*; @@ -63,7 +73,7 @@ public abstract class Entity extends Location implements Metadatable { public static final int DATA_FLAGS = 0; public static final int DATA_HEALTH = 1; //int (minecart/boat) public static final int DATA_VARIANT = 2; //int - public static final int DATA_COLOR = 3, DATA_COLOUR = 3; //byte + public static final int DATA_COLOR = 3, DATA_COLOUR = DATA_COLOR; //byte public static final int DATA_NAMETAG = 4; //string public static final int DATA_OWNER_EID = 5; //long public static final int DATA_TARGET_EID = 6; //long @@ -83,7 +93,7 @@ public abstract class Entity extends Location implements Metadatable { public static final int DATA_OLD_SWELL = 20; public static final int DATA_SWELL_DIR = 21; public static final int DATA_CHARGE_AMOUNT = 22; - public static final int DATA_ENDERMAN_HELD_RUNTIME_ID = 23; //short + public static final int DATA_ENDERMAN_HELD_RUNTIME_ID = 23; //int (block runtime id) public static final int DATA_ENTITY_AGE = 24; //short public static final int DATA_PLAYER_FLAGS = 26; //byte public static final int DATA_PLAYER_INDEX = 27; @@ -151,7 +161,7 @@ public abstract class Entity extends Location implements Metadatable { public static final int DATA_SITTING_AMOUNT = 89; public static final int DATA_SITTING_AMOUNT_PREVIOUS = 90; public static final int DATA_EATING_COUNTER = 91; - public static final int DATA_FLAGS_EXTENDED = 92; + public static final int DATA_FLAGS_EXTENDED = 92; //long (extended data flags) public static final int DATA_LAYING_AMOUNT = 93; public static final int DATA_LAYING_AMOUNT_PREVIOUS = 94; public static final int DATA_DURATION = 95; @@ -163,10 +173,10 @@ public abstract class Entity extends Location implements Metadatable { public static final int DATA_TRADE_TIER = 101; public static final int DATA_MAX_TRADE_TIER = 102; public static final int DATA_TRADE_EXPERIENCE = 103; - public static final int DATA_SKIN_ID = 104; // int ??? + public static final int DATA_SKIN_ID = 104; // int public static final int DATA_SPAWNING_FRAMES = 105; - public static final int DATA_COMMAND_BLOCK_TICK_DELAY = 106; - public static final int DATA_COMMAND_BLOCK_EXECUTE_ON_FIRST_TICK = 107; + public static final int DATA_COMMAND_BLOCK_TICK_DELAY = 106; //int + public static final int DATA_COMMAND_BLOCK_EXECUTE_ON_FIRST_TICK = 107; //byte public static final int DATA_AMBIENT_SOUND_INTERVAL = 108; public static final int DATA_AMBIENT_SOUND_INTERVAL_RANGE = 109; public static final int DATA_AMBIENT_SOUND_EVENT_NAME = 110; @@ -209,7 +219,7 @@ public abstract class Entity extends Location implements Metadatable { public static final int DATA_FLAG_CRITICAL = 13; public static final int DATA_FLAG_CAN_SHOW_NAMETAG = 14; public static final int DATA_FLAG_ALWAYS_SHOW_NAMETAG = 15; - public static final int DATA_FLAG_IMMOBILE = 16, DATA_FLAG_NO_AI = 16; + public static final int DATA_FLAG_IMMOBILE = 16, DATA_FLAG_NO_AI = DATA_FLAG_IMMOBILE; public static final int DATA_FLAG_SILENT = 17; public static final int DATA_FLAG_WALLCLIMBING = 18; public static final int DATA_FLAG_CAN_CLIMB = 19; @@ -309,12 +319,14 @@ public abstract class Entity extends Location implements Metadatable { public static final int DATA_FLAG_SEARCHING = 113; public static final int DATA_FLAG_CRAWLING = 114; + public static final double STEP_CLIP_MULTIPLIER = 0.4; + public static long entityCount = 1; private static final Map> knownEntities = new HashMap<>(); private static final Map shortNames = new HashMap<>(); - protected final Map hasSpawned = new HashMap<>(); + public final Map hasSpawned = new HashMap<>(); protected final Map effects = new ConcurrentHashMap<>(); @@ -324,18 +336,18 @@ public abstract class Entity extends Location implements Metadatable { .putLong(DATA_FLAGS, 0) .putByte(DATA_COLOR, 0) .putShort(DATA_AIR, 400) - .putShort(DATA_MAX_AIR, 400) + .putShort(DATA_MAX_AIR, 400) // Should be 300? .putString(DATA_NAMETAG, "") .putLong(DATA_LEAD_HOLDER_EID, -1) .putFloat(DATA_SCALE, 1f); public final List passengers = new ArrayList<>(); - public Entity riding = null; + public Entity riding; public FullChunk chunk; - protected EntityDamageEvent lastDamageCause = null; + protected EntityDamageEvent lastDamageCause; public List blocksAround = new ArrayList<>(); public List collisionBlocks = new ArrayList<>(); @@ -355,64 +367,87 @@ public abstract class Entity extends Location implements Metadatable { public double lastMotionY; public double lastMotionZ; - public double lastPitch; public double lastYaw; + public double lastPitch; public double lastHeadYaw; - public double pitchDelta; - public double yawDelta; - public double headYawDelta; + @Deprecated + public double PitchDelta; + @Deprecated + public double YawDelta; - public double entityCollisionReduction = 0; // Higher than 0.9 will result a fast collisions + public double entityCollisionReduction; // Higher than 0.9 will result a fast collisions public AxisAlignedBB boundingBox; public boolean onGround; - public boolean inBlock = false; + @Deprecated + public boolean inBlock; + @Deprecated public boolean positionChanged; + @Deprecated public boolean motionChanged; - public int deadTicks = 0; - protected int age = 0; + public int deadTicks; + public int age; + public int ticksLived; + protected int airTicks = 400; + protected boolean noFallDamage; protected float health = 20; - private int maxHealth = 20; + protected int maxHealth = 20; - protected float absorption = 0; + protected float absorption; - protected float ySize = 0; - public boolean keepMovement = false; + protected float ySize; + public boolean keepMovement; - public float fallDistance = 0; - public int ticksLived = 0; + public float fallDistance; public int lastUpdate; - public int maxFireTicks; - public int fireTicks = 0; - public int inPortalTicks = 0; - + public int fireTicks; + public int inPortalTicks; + public int inEndPortalTicks; + protected Position portalPos; + public boolean noClip; public float scale = 1; public CompoundTag namedTag; - protected boolean isStatic = false; - - public boolean isCollided = false; - public boolean isCollidedHorizontally = false; - public boolean isCollidedVertically = false; + public boolean isCollided; + public boolean isCollidedHorizontally; + public boolean isCollidedVertically; public int noDamageTicks; public boolean justCreated; public boolean fireProof; public boolean invulnerable; + // Allow certain entities to be ticked only when a nearby block is updated or the entity is moving already + // 1 = has pending update, 3 = update on block update only, 5 = update on block update + schedule occasional updates + // updateMode % 2: 1 = has update mode, updateMode % 3: 1 = nearby update (only), 2 = occasional update + public int updateMode; + + private boolean gliding; + private boolean immobile; + private boolean sprinting; + private boolean swimming; + private boolean sneaking; + private boolean crawling; + protected Server server; public double highestPosition; - public boolean closed = false; + public boolean closed; + + @Deprecated + public final boolean isPlayer = this instanceof Player; + + private volatile boolean init; + private volatile boolean initEntity; - protected Timing timing; + private volatile boolean saveToStorage = true; - protected boolean isPlayer = this instanceof Player; + private PersistentDataContainer persistentContainer; - private volatile boolean initialized; + private Vector3 enterMinecartPos; // Used to check the minecart achievement public float getHeight() { return 0; @@ -451,14 +486,18 @@ protected float getBaseOffset() { } public Entity(FullChunk chunk, CompoundTag nbt) { - if (this instanceof Player) { - return; + if (!(this instanceof Player)) { + this.init(chunk, nbt); } - - this.init(chunk, nbt); } protected void initEntity() { + if (this.initEntity) { + throw new RuntimeException("Entity is already initialized: " + this.getName() + " (" + this.id + ')'); + } + + this.initEntity = true; + if (this.namedTag.contains("ActiveEffects")) { ListTag effects = this.namedTag.getList("ActiveEffects", CompoundTag.class); for (CompoundTag e : effects.getAll()) { @@ -475,18 +514,20 @@ protected void initEntity() { if (this.namedTag.contains("CustomName")) { this.setNameTag(this.namedTag.getString("CustomName")); + if (this.namedTag.contains("CustomNameVisible")) { this.setNameTagVisible(this.namedTag.getBoolean("CustomNameVisible")); } - if(this.namedTag.contains("CustomNameAlwaysVisible")){ + + if (this.namedTag.contains("CustomNameAlwaysVisible")) { this.setNameTagAlwaysVisible(this.namedTag.getBoolean("CustomNameAlwaysVisible")); } } - this.setDataFlag(DATA_FLAGS, DATA_FLAG_HAS_COLLISION, true); + this.setDataFlag(DATA_FLAGS, DATA_FLAG_HAS_COLLISION, true, false); this.dataProperties.putFloat(DATA_BOUNDING_BOX_HEIGHT, this.getHeight()); this.dataProperties.putFloat(DATA_BOUNDING_BOX_WIDTH, this.getWidth()); - this.dataProperties.putInt(DATA_HEALTH, (int) this.getHealth()); + this.dataProperties.putInt(DATA_HEALTH, (int) this.health); this.scheduleUpdate(); } @@ -496,17 +537,15 @@ protected final void init(FullChunk chunk, CompoundTag nbt) { throw new ChunkException("Invalid garbage Chunk given to Entity"); } - if (this.initialized) { - // We've already initialized this entity - return; + if (this.init) { + throw new RuntimeException("Entity is already initialized: " + this.getName() + " (" + this.id + ')'); } - this.initialized = true; - this.timing = Timings.getEntityTiming(this); + this.init = true; this.temporalVector = new Vector3(); - this.id = Entity.entityCount++; + this.id = entityCount++; this.justCreated = true; this.namedTag = nbt; @@ -514,19 +553,25 @@ protected final void init(FullChunk chunk, CompoundTag nbt) { this.setLevel(chunk.getProvider().getLevel()); this.server = chunk.getProvider().getLevel().getServer(); + if (!this.server.isPrimaryThread() && !this.level.isBeingConverted) { + this.server.getLogger().warning("Entity initialized asynchronously: " + this.getClass().getSimpleName()); + } + this.boundingBox = new SimpleAxisAlignedBB(0, 0, 0, 0, 0, 0); ListTag posList = this.namedTag.getList("Pos", DoubleTag.class); ListTag rotationList = this.namedTag.getList("Rotation", FloatTag.class); ListTag motionList = this.namedTag.getList("Motion", DoubleTag.class); + float correctedYaw = rotationList.get(0).data; + if (!(correctedYaw >= 0 && correctedYaw <= 360)) correctedYaw = 0; + float correctedPitch = rotationList.get(1).data; + if (!(correctedPitch >= 0 && correctedPitch <= 360)) correctedPitch = 0; this.setPositionAndRotation( this.temporalVector.setComponents( posList.get(0).data, posList.get(1).data, posList.get(2).data - ), - rotationList.get(0).data, - rotationList.get(1).data + ), correctedYaw, correctedPitch ); this.setMotion(this.temporalVector.setComponents( @@ -547,7 +592,7 @@ protected final void init(FullChunk chunk, CompoundTag nbt) { this.fireTicks = this.namedTag.getShort("Fire"); if (!this.namedTag.contains("Air")) { - this.namedTag.putShort("Air", 300); + this.namedTag.putShort("Air", 400); } this.setDataProperty(new ShortEntityData(DATA_AIR, this.namedTag.getShort("Air")), false); @@ -564,6 +609,7 @@ protected final void init(FullChunk chunk, CompoundTag nbt) { if (!this.namedTag.contains("Scale")) { this.namedTag.putFloat("Scale", 1); } + this.scale = this.namedTag.getFloat("Scale"); this.setDataProperty(new FloatEntityData(DATA_SCALE, scale), false); @@ -623,7 +669,7 @@ public String getScoreTag() { } public boolean isSneaking() { - return this.getDataFlag(DATA_FLAGS, DATA_FLAG_SNEAKING); + return this.sneaking; } public void setSneaking() { @@ -631,11 +677,15 @@ public void setSneaking() { } public void setSneaking(boolean value) { - this.setDataFlag(DATA_FLAGS, DATA_FLAG_SNEAKING, value); + if (this.sneaking != value) { + this.sneaking = value; + this.setDataFlag(DATA_FLAGS, DATA_FLAG_SNEAKING, value); + this.recalculateBoundingBox(true); + } } public boolean isSwimming() { - return this.getDataFlag(DATA_FLAGS, DATA_FLAG_SWIMMING); + return this.swimming; } public void setSwimming() { @@ -643,11 +693,15 @@ public void setSwimming() { } public void setSwimming(boolean value) { - this.setDataFlag(DATA_FLAGS, DATA_FLAG_SWIMMING, value); + if (this.swimming != value) { + this.swimming = value; + this.setDataFlag(DATA_FLAGS, DATA_FLAG_SWIMMING, value); + this.recalculateBoundingBox(true); + } } public boolean isSprinting() { - return this.getDataFlag(DATA_FLAGS, DATA_FLAG_SPRINTING); + return this.sprinting; } public void setSprinting() { @@ -655,11 +709,14 @@ public void setSprinting() { } public void setSprinting(boolean value) { - this.setDataFlag(DATA_FLAGS, DATA_FLAG_SPRINTING, value); + if (this.sprinting != value) { + this.sprinting = value; + this.setDataFlag(DATA_FLAGS, DATA_FLAG_SPRINTING, value); + } } public boolean isGliding() { - return this.getDataFlag(DATA_FLAGS, DATA_FLAG_GLIDING); + return this.gliding; } public void setGliding() { @@ -667,11 +724,31 @@ public void setGliding() { } public void setGliding(boolean value) { - this.setDataFlag(DATA_FLAGS, DATA_FLAG_GLIDING, value); + if (this.gliding != value) { + this.gliding = value; + this.setDataFlag(DATA_FLAGS, DATA_FLAG_GLIDING, value); + this.recalculateBoundingBox(true); + } + } + + public boolean isCrawling() { + return this.crawling; + } + + public void setCrawling() { + this.setCrawling(true); + } + + public void setCrawling(boolean value) { + if (this.crawling != value) { + this.crawling = value; + this.setDataFlag(DATA_FLAGS_EXTENDED, DATA_FLAG_CRAWLING, value); + this.recalculateBoundingBox(true); + } } public boolean isImmobile() { - return this.getDataFlag(DATA_FLAGS, DATA_FLAG_IMMOBILE); + return this.immobile; } public void setImmobile() { @@ -679,6 +756,7 @@ public void setImmobile() { } public void setImmobile(boolean value) { + this.immobile = value; this.setDataFlag(DATA_FLAGS, DATA_FLAG_IMMOBILE, value); } @@ -707,9 +785,11 @@ public void setCanClimbWalls(boolean value) { } public void setScale(float scale) { - this.scale = scale; - this.setDataProperty(new FloatEntityData(DATA_SCALE, this.scale)); - this.recalculateBoundingBox(); + if (this.scale != scale) { + this.scale = scale; + this.setDataProperty(new FloatEntityData(DATA_SCALE, this.scale)); + this.recalculateBoundingBox(true); + } } public float getScale() { @@ -733,7 +813,7 @@ public boolean isControlling(Entity entity) { } public boolean hasControllingPassenger() { - return !this.passengers.isEmpty() && isControlling(this.passengers.get(0)); + return !this.passengers.isEmpty() && this.passengers.get(0) != null; } public Entity getRiding() { @@ -820,45 +900,79 @@ public void addEffect(Effect effect, EntityPotionEffectEvent.Cause cause) { this.recalculateEffectColor(); if (effect.getId() == Effect.HEALTH_BOOST) { - this.setHealth(this.getHealth() + 4 * (effect.getAmplifier() + 1)); + this.setHealth(this.health + ((effect.getAmplifier() + 1) << 2)); + } + } + + protected static void addEffectFromTippedArrow(Entity entity, Effect effect, float damage) { + if (effect == null) { + return; } + Effect oldEffect = entity.effects.get(effect.getId()); + + EntityPotionEffectEvent event = new EntityPotionEffectEvent( + entity, + oldEffect, + effect, + oldEffect == null ? EntityPotionEffectEvent.Action.ADDED : EntityPotionEffectEvent.Action.CHANGED, + EntityPotionEffectEvent.Cause.ARROW); + + entity.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return; + } + + switch (effect.getId()) { + case Effect.HEALING: + if (entity.isAlive()) { // Avoid dupes + entity.heal(new EntityRegainHealthEvent(entity, 4 * (effect.getAmplifier() + 1), EntityRegainHealthEvent.CAUSE_MAGIC)); + } + break; + case Effect.HARMING: + float attackDamage = (effect.getAmplifier() < 1 ? 6 : 12) - damage; + if (attackDamage > 0) { + EntityDamageEvent ev = new EntityDamageEvent(entity, DamageCause.MAGIC, attackDamage); + entity.attack(ev); + } + break; + default: + effect.add(entity); + entity.effects.put(effect.getId(), effect); + entity.recalculateEffectColor(); + } } public void recalculateBoundingBox() { - this.recalculateBoundingBox(true); + this.recalculateBoundingBox(false); } public void recalculateBoundingBox(boolean send) { - float height = this.getHeight() * this.scale; + float height = this.getHeight(); double radius = (this.getWidth() * this.scale) / 2d; - this.boundingBox.setBounds(x - radius, y, z - radius, x + radius, y + height, z + radius); + this.boundingBox.setBounds( + this.x - radius, + this.y + this.ySize, + z - radius, + x + radius, + y + height * this.scale + this.ySize, + z + radius + ); - FloatEntityData bbH = new FloatEntityData(DATA_BOUNDING_BOX_HEIGHT, this.getHeight()); - FloatEntityData bbW = new FloatEntityData(DATA_BOUNDING_BOX_WIDTH, this.getWidth()); - this.dataProperties.put(bbH); - this.dataProperties.put(bbW); if (send) { + FloatEntityData bbH = new FloatEntityData(DATA_BOUNDING_BOX_HEIGHT, height); + FloatEntityData bbW = new FloatEntityData(DATA_BOUNDING_BOX_WIDTH, this.getWidth()); + this.dataProperties.put(bbH); + this.dataProperties.put(bbW); sendData(this.hasSpawned.values().toArray(new Player[0]), new EntityMetadata().put(bbH).put(bbW)); } } protected void recalculateEffectColor() { - int[] color = new int[3]; - int count = 0; - boolean ambient = true; long effectsData = 0; int packedEffectsCount = 0; for (Effect effect : this.effects.values()) { if (effect.isVisible()) { - int[] c = effect.getColor(); - color[0] += c[0] * (effect.getAmplifier() + 1); - color[1] += c[1] * (effect.getAmplifier() + 1); - color[2] += c[2] * (effect.getAmplifier() + 1); - count += effect.getAmplifier() + 1; - if (!effect.isAmbient()) { - ambient = false; - } if (packedEffectsCount < 8) { effectsData = effectsData << 7 | ((effect.getId() & 0x3f) << 1) | (effect.isAmbient() ? 1 : 0); packedEffectsCount++; @@ -866,17 +980,6 @@ protected void recalculateEffectColor() { } } - if (count > 0) { - int r = (color[0] / count) & 0xff; - int g = (color[1] / count) & 0xff; - int b = (color[2] / count) & 0xff; - - this.setDataProperty(new IntEntityData(Entity.DATA_POTION_COLOR, (r << 16) + (g << 8) + b)); - this.setDataProperty(new ByteEntityData(Entity.DATA_POTION_AMBIENT, ambient ? 1 : 0)); - } else { - this.setDataProperty(new IntEntityData(Entity.DATA_POTION_COLOR, 0)); - this.setDataProperty(new ByteEntityData(Entity.DATA_POTION_AMBIENT, 0)); - } this.setDataProperty(new LongEntityData(Entity.DATA_VISIBLE_MOB_EFFECTS, effectsData)); } @@ -889,48 +992,64 @@ public static Entity createEntity(int type, Position pos, Object... args) { } public static Entity createEntity(String name, FullChunk chunk, CompoundTag nbt, Object... args) { - Entity entity = null; - - if (knownEntities.containsKey(name)) { - Class clazz = knownEntities.get(name); - - if (clazz == null) { + Class clazz = knownEntities.get(name); + if (clazz == null) { + EntityDefinition definition = EntityManager.get().getDefinition(name); + if (definition == null) { return null; } + clazz = definition.getImplementation(); + } + return createEntity0(clazz, chunk, nbt, args); + } - for (Constructor constructor : clazz.getConstructors()) { - if (entity != null) { - break; - } + public static Entity createEntity(int type, FullChunk chunk, CompoundTag nbt, Object... args) { + String identifier = String.valueOf(type); + if (knownEntities.containsKey(identifier)) { + return createEntity(identifier, chunk, nbt, args); + } - if (constructor.getParameterCount() != (args == null ? 2 : args.length + 2)) { - continue; - } + EntityDefinition definition = EntityManager.get().getDefinition(type); + if (definition != null) { + return createEntity0(definition.getImplementation(), chunk, nbt, args); + } + return null; + } - try { - if (args == null || args.length == 0) { - entity = (Entity) constructor.newInstance(chunk, nbt); - } else { - Object[] objects = new Object[args.length + 2]; + private static Entity createEntity0(Class clazz, FullChunk chunk, CompoundTag nbt, Object... args) { + Entity entity = null; - objects[0] = chunk; - objects[1] = nbt; - System.arraycopy(args, 0, objects, 2, args.length); - entity = (Entity) constructor.newInstance(objects); + for (Constructor constructor : clazz.getConstructors()) { + if (entity != null) { + break; + } - } - } catch (Exception e) { - MainLogger.getLogger().logException(e); - } + if (constructor.getParameterCount() != (args == null ? 2 : args.length + 2)) { + continue; + } + try { + if (args == null || args.length == 0) { + entity = (Entity) constructor.newInstance(chunk, nbt); + } else { + Object[] objects = new Object[args.length + 2]; + + objects[0] = chunk; + objects[1] = nbt; + System.arraycopy(args, 0, objects, 2, args.length); + entity = (Entity) constructor.newInstance(objects); + + } + } catch (Exception e) { + MainLogger.getLogger().error("Failed to create an instance of " + clazz.getName(), e); } } return entity; } - public static Entity createEntity(int type, FullChunk chunk, CompoundTag nbt, Object... args) { - return createEntity(String.valueOf(type), chunk, nbt, args); + public static boolean isKnown(String name) { + return knownEntities.containsKey(name); } public static boolean registerEntity(String name, Class clazz) { @@ -987,8 +1106,9 @@ public static CompoundTag getDefaultNBT(Vector3 pos, Vector3 motion, float yaw, public void saveNBT() { if (!(this instanceof Player)) { this.namedTag.putString("id", this.getSaveId()); - if (!this.getNameTag().equals("")) { - this.namedTag.putString("CustomName", this.getNameTag()); + String customName = this.getNameTag(); + if (!customName.isEmpty()) { + this.namedTag.putString("CustomName", customName); this.namedTag.putBoolean("CustomNameVisible", this.isNameTagVisible()); this.namedTag.putBoolean("CustomNameAlwaysVisible", this.isNameTagAlwaysVisible()); } else { @@ -1017,7 +1137,7 @@ public void saveNBT() { this.namedTag.putFloat("FallDistance", this.fallDistance); this.namedTag.putShort("Fire", this.fireTicks); - this.namedTag.putShort("Air", this.getDataPropertyShort(DATA_AIR)); + this.namedTag.putShort("Air", this.airTicks); this.namedTag.putBoolean("OnGround", this.onGround); this.namedTag.putBoolean("Invulnerable", this.invulnerable); this.namedTag.putFloat("Scale", this.scale); @@ -1049,34 +1169,44 @@ public String getName() { } public final String getSaveId() { + if (this instanceof CustomEntity) { + EntityDefinition definition = ((CustomEntity) this).getEntityDefinition(); + return definition == null ? "" : definition.getIdentifier(); + } return shortNames.getOrDefault(this.getClass().getSimpleName(), ""); } public void spawnTo(Player player) { - - if (!this.hasSpawned.containsKey(player.getLoaderId()) && this.chunk != null && player.usedChunks.containsKey(Level.chunkHash(this.chunk.getX(), this.chunk.getZ()))) { - this.hasSpawned.put(player.getLoaderId(), player); - player.dataPacket(createAddEntityPacket()); + if (!this.init || !this.initEntity) { + this.server.getLogger().warning("Spawned an entity that is not initialized yet: " + this.getClass().getName() + " (" + this.id + ')'); } - if (this.riding != null) { - this.riding.spawnTo(player); + if (!this.hasSpawned.containsKey(player.getLoaderId())) { + Boolean hasChunk = player.usedChunks.get(Level.chunkHash(this.chunk.getX(), this.chunk.getZ())); + if (hasChunk != null && hasChunk) { + player.dataPacket(createAddEntityPacket()); + this.hasSpawned.put(player.getLoaderId(), player); + + if (this.riding != null) { + this.riding.spawnTo(player); - SetEntityLinkPacket pkk = new SetEntityLinkPacket(); - pkk.vehicleUniqueId = this.riding.getId(); - pkk.riderUniqueId = this.getId(); - pkk.type = 1; - pkk.immediate = 1; + SetEntityLinkPacket pkk = new SetEntityLinkPacket(); + pkk.vehicleUniqueId = this.riding.id; + pkk.riderUniqueId = this.id; + pkk.type = 1; + pkk.immediate = 1; - player.dataPacket(pkk); + player.dataPacket(pkk); + } + } } } protected DataPacket createAddEntityPacket() { AddEntityPacket addEntity = new AddEntityPacket(); addEntity.type = this.getNetworkId(); - addEntity.entityUniqueId = this.getId(); - addEntity.entityRuntimeId = this.getId(); + addEntity.entityUniqueId = this.id; + addEntity.entityRuntimeId = this.id; addEntity.yaw = (float) this.yaw; addEntity.headYaw = (float) this.yaw; addEntity.pitch = (float) this.pitch; @@ -1086,11 +1216,11 @@ protected DataPacket createAddEntityPacket() { addEntity.speedX = (float) this.motionX; addEntity.speedY = (float) this.motionY; addEntity.speedZ = (float) this.motionZ; - addEntity.metadata = this.dataProperties; + addEntity.metadata = this.dataProperties.clone(); addEntity.links = new EntityLink[this.passengers.size()]; for (int i = 0; i < addEntity.links.length; i++) { - addEntity.links[i] = new EntityLink(this.getId(), this.passengers.get(i).getId(), i == 0 ? EntityLink.TYPE_RIDER : TYPE_PASSENGER, false, false, 0f); + addEntity.links[i] = new EntityLink(this.id, this.passengers.get(i).id, i == 0 ? EntityLink.TYPE_RIDER : TYPE_PASSENGER, false, false, 0f); } return addEntity; @@ -1103,7 +1233,7 @@ public Map getViewers() { public void sendPotionEffects(Player player) { for (Effect effect : this.effects.values()) { MobEffectPacket pk = new MobEffectPacket(); - pk.eid = this.getId(); + pk.eid = this.id; pk.effectId = effect.getId(); pk.amplifier = effect.getAmplifier(); pk.particles = effect.isVisible(); @@ -1120,9 +1250,8 @@ public void sendData(Player player) { public void sendData(Player player, EntityMetadata data) { SetEntityDataPacket pk = new SetEntityDataPacket(); - pk.eid = this.getId(); - pk.metadata = data == null ? this.dataProperties : data; - + pk.eid = this.id; + pk.metadata = data == null ? this.dataProperties.clone() : data; player.dataPacket(pk); } @@ -1132,29 +1261,40 @@ public void sendData(Player[] players) { public void sendData(Player[] players, EntityMetadata data) { SetEntityDataPacket pk = new SetEntityDataPacket(); - pk.eid = this.getId(); - pk.metadata = data == null ? this.dataProperties : data; + pk.eid = this.id; + pk.metadata = data == null ? this.dataProperties.clone() : data; for (Player player : players) { if (player == this) { continue; } - player.dataPacket(pk.clone()); + player.dataPacket(pk); } + if (this instanceof Player) { ((Player) this).dataPacket(pk); } } public void despawnFrom(Player player) { - if (this.hasSpawned.containsKey(player.getLoaderId())) { + if (this.hasSpawned.remove(player.getLoaderId()) != null) { RemoveEntityPacket pk = new RemoveEntityPacket(); - pk.eid = this.getId(); + pk.eid = this.id; player.dataPacket(pk); - this.hasSpawned.remove(player.getLoaderId()); } } + /** + * Check if player's hit should be critical + * @param player player + * @return can make a critical hit + */ + private static boolean canCriticalHit(Player player) { + if (player.isOnGround() || player.riding != null || player.speed == null || player.speed.y <= 0 || player.hasEffect(Effect.BLINDNESS)) return false; + int b = player.getLevel().getBlockIdAt(player.chunk, player.getFloorX(), player.getFloorY(), player.getFloorZ()); + return b != Block.LADDER && b != Block.VINES && !Block.isWater(b); + } + public boolean attack(EntityDamageEvent source) { if (hasEffect(Effect.FIRE_RESISTANCE) && (source.getCause() == DamageCause.FIRE @@ -1163,13 +1303,29 @@ public boolean attack(EntityDamageEvent source) { return false; } - getServer().getPluginManager().callEvent(source); + if (this instanceof EntityLiving && source instanceof EntityDamageByEntityEvent && !(source instanceof EntityDamageByChildEntityEvent)) { + Entity damager = ((EntityDamageByEntityEvent) source).getDamager(); + if (damager instanceof Player && canCriticalHit((Player) damager)) { + source.setDamage(source.getFinalDamage() * 0.5f, EntityDamageEvent.DamageModifier.CRITICAL); + } + } + + server.getPluginManager().callEvent(source); if (source.isCancelled()) { return false; } - // Make fire aspect to set the target in fire before dealing any damage so the target is in fire on death even if killed by the first hit + if (source.isApplicable(EntityDamageEvent.DamageModifier.CRITICAL)) { + AnimatePacket animate = new AnimatePacket(); + animate.action = AnimatePacket.Action.CRITICAL_HIT; + animate.eid = this.getId(); + + this.getLevel().addChunkPacket(this.getChunkX(), this.getChunkZ(), animate); + this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_ATTACK_STRONG); + } + if (source instanceof EntityDamageByEntityEvent) { + // Make fire aspect to set the target in fire before dealing any damage so the target is in fire on death even if killed by the first hit Enchantment[] enchantments = ((EntityDamageByEntityEvent) source).getWeaponEnchantments(); if (enchantments != null) { for (Enchantment enchantment : enchantments) { @@ -1178,21 +1334,38 @@ public boolean attack(EntityDamageEvent source) { } } - if (this.absorption > 0) { // Damage Absorption - this.setAbsorption(Math.max(0, this.getAbsorption() + source.getDamage(EntityDamageEvent.DamageModifier.ABSORPTION))); + float finalDamage = source.getFinalDamage(); + float a = this.absorption; + + if (a > 0) { // Damage Absorption + //this.setAbsorption(Math.max(0, this.absorption + source.getDamage(EntityDamageEvent.DamageModifier.ABSORPTION))); + this.setAbsorption(Math.max(0, a - finalDamage)); + finalDamage = Math.max(0, finalDamage - a); } - setLastDamageCause(source); - float newHealth = getHealth() - source.getFinalDamage(); + setLastDamageCause(source); + float newHealth = this.health - finalDamage; if (newHealth < 1 && this instanceof Player) { if (source.getCause() != DamageCause.VOID && source.getCause() != DamageCause.SUICIDE) { Player p = (Player) this; boolean totem = false; - boolean isOffhand = false; - if (p.getOffhandInventory().getItem(0).getId() == ItemID.TOTEM) { + if (p.getOffhandInventory().getItemFast(0).getId() == ItemID.TOTEM) { + // Must be sent before removing the item + EntityEventPacket pk = new EntityEventPacket(); + pk.eid = this.getId(); + pk.event = EntityEventPacket.CONSUME_TOTEM; + p.dataPacket(pk); + + p.getOffhandInventory().clear(0); totem = true; - isOffhand = true; - } else if (p.getInventory().getItemInHand().getId() == ItemID.TOTEM) { + } else if (p.getInventory().getItemInHandFast().getId() == ItemID.TOTEM) { + // Must be sent before removing the item + EntityEventPacket pk = new EntityEventPacket(); + pk.eid = this.getId(); + pk.event = EntityEventPacket.CONSUME_TOTEM; + p.dataPacket(pk); + + p.getInventory().clear(p.getInventory().getHeldItemIndex()); totem = true; } if (totem) { @@ -1206,24 +1379,17 @@ public boolean attack(EntityDamageEvent source) { this.addEffect(Effect.getEffect(Effect.FIRE_RESISTANCE).setDuration(800), EntityPotionEffectEvent.Cause.TOTEM); this.addEffect(Effect.getEffect(Effect.ABSORPTION).setDuration(100).setAmplifier(1), EntityPotionEffectEvent.Cause.TOTEM); - EntityEventPacket pk = new EntityEventPacket(); - pk.eid = this.getId(); - pk.event = EntityEventPacket.CONSUME_TOTEM; - p.dataPacket(pk); - - if (isOffhand) { - p.getOffhandInventory().clear(0); - } else { - p.getInventory().clear(p.getInventory().getHeldItemIndex()); - } - - source.setCancelled(true); return false; } } } - setHealth(newHealth); + if (finalDamage >= 18 && source instanceof EntityDamageByEntityEvent && source.getCause() == DamageCause.ENTITY_ATTACK) { + Entity p = ((EntityDamageByEntityEvent) source).getDamager(); + if (p instanceof Player) { + ((Player) p).awardAchievement("overkill"); + } + } return true; } @@ -1236,7 +1402,7 @@ public void heal(EntityRegainHealthEvent source) { if (source.isCancelled()) { return; } - this.setHealth(this.getHealth() + source.getAmount()); + this.setHealth(this.health + source.getAmount()); } public void heal(float amount) { @@ -1248,7 +1414,7 @@ public float getHealth() { } public boolean isAlive() { - return this.health > 0; + return this.health >= 1; } public boolean isClosed() { @@ -1270,7 +1436,12 @@ public void setHealth(float health) { this.health = this.getMaxHealth(); } - setDataProperty(new IntEntityData(DATA_HEALTH, (int) this.health)); + // Sending health updates to viewers is not necessary in most cases + /*if (this instanceof Player) { + setDataPropertyAndSendOnlyToSelf(new IntEntityData(DATA_HEALTH, (int) this.health)); + } else { + setDataProperty(new IntEntityData(DATA_HEALTH, (int) this.health), this instanceof EntityRideable || this instanceof EntityBoss); + }*/ } public void setLastDamageCause(EntityDamageEvent type) { @@ -1281,8 +1452,20 @@ public EntityDamageEvent getLastDamageCause() { return lastDamageCause; } + /** + * Get maximum health including health from health boost effect + * @return current max health + */ public int getMaxHealth() { - return maxHealth + (this.hasEffect(Effect.HEALTH_BOOST) ? 4 * (this.getEffect(Effect.HEALTH_BOOST).getAmplifier() + 1) : 0); + return maxHealth + (this.hasEffect(Effect.HEALTH_BOOST) ? (this.getEffect(Effect.HEALTH_BOOST).getAmplifier() + 1) << 2 : 0); + } + + /** + * Get normal maximum health excluding health from effects + * @return real max health + */ + public int getRealMaxHealth() { + return maxHealth; } public void setMaxHealth(int maxHealth) { @@ -1290,11 +1473,11 @@ public void setMaxHealth(int maxHealth) { } public boolean canCollideWith(Entity entity) { - return !this.justCreated && this != entity; + return entity != null && !this.justCreated && this != entity && !entity.noClip && !this.noClip; } protected boolean checkObstruction(double x, double y, double z) { - if (this.level.getCollisionCubes(this, this.getBoundingBox(), false).length == 0) { + if (this.noClip || this.level.getCollisionCubes(this, this.boundingBox, false).length == 0) { return false; } @@ -1306,13 +1489,13 @@ protected boolean checkObstruction(double x, double y, double z) { double diffY = y - j; double diffZ = z - k; - if (!Block.transparent[this.level.getBlockIdAt(i, j, k)]) { - boolean flag = Block.transparent[this.level.getBlockIdAt(i - 1, j, k)]; - boolean flag1 = Block.transparent[this.level.getBlockIdAt(i + 1, j, k)]; - boolean flag2 = Block.transparent[this.level.getBlockIdAt(i, j - 1, k)]; - boolean flag3 = Block.transparent[this.level.getBlockIdAt(i, j + 1, k)]; - boolean flag4 = Block.transparent[this.level.getBlockIdAt(i, j, k - 1)]; - boolean flag5 = Block.transparent[this.level.getBlockIdAt(i, j, k + 1)]; + if (!Block.isBlockTransparentById(this.level.getBlockIdAt(this.chunk, i, j, k))) { + boolean flag = Block.isBlockTransparentById(this.level.getBlockIdAt(this.chunk, i - 1, j, k)); + boolean flag1 = Block.isBlockTransparentById(this.level.getBlockIdAt(this.chunk, i + 1, j, k)); + boolean flag2 = Block.isBlockTransparentById(this.level.getBlockIdAt(this.chunk, i, j - 1, k)); + boolean flag3 = Block.isBlockTransparentById(this.level.getBlockIdAt(this.chunk, i, j + 1, k)); + boolean flag4 = Block.isBlockTransparentById(this.level.getBlockIdAt(this.chunk, i, j, k - 1)); + boolean flag5 = Block.isBlockTransparentById(this.level.getBlockIdAt(this.chunk, i, j, k + 1)); int direction = -1; double limit = 9999; @@ -1346,7 +1529,7 @@ protected boolean checkObstruction(double x, double y, double z) { direction = 5; } - double force = new Random().nextDouble() * 0.2 + 0.1; + double force = Utils.random.nextDouble() * 0.2 + 0.1; if (direction == 0) { this.motionX = -force; @@ -1393,26 +1576,24 @@ public boolean entityBaseTick() { } public boolean entityBaseTick(int tickDiff) { - Timings.entityBaseTickTimer.startTiming(); - - if (!this.isPlayer) { - this.blocksAround = null; + if (!(this instanceof Player)) { + //this.blocksAround = null; // Use only when entity moves for better performance this.collisionBlocks = null; } + this.justCreated = false; if (!this.isAlive()) { - this.removeAllEffects(EntityPotionEffectEvent.Cause.DEATH); + //this.removeAllEffects(); // Why to remove them if the entity is dead anyways? this.despawnFromAll(); - if (!this.isPlayer) { + if (!(this instanceof Player)) { this.close(); } - Timings.entityBaseTickTimer.stopTiming(); return false; } - if (riding != null && !riding.isAlive() && riding instanceof EntityRideable) { - ((EntityRideable) riding).dismountEntity(this); - } + /*if (riding != null && !riding.isAlive() && riding instanceof EntityRideable) { + ((EntityRideable) riding).mountEntity(this); + }*/ updatePassengers(); @@ -1433,10 +1614,9 @@ public boolean entityBaseTick(int tickDiff) { this.checkBlockCollision(); - if (this.y <= -16 && this.isAlive()) { + if (this.y <= (this.level.getMinBlockY() - 16) && this.isAlive()) { if (this instanceof Player) { - Player player = (Player) this; - if (!player.isCreative()) this.attack(new EntityDamageEvent(this, DamageCause.VOID, 10)); + if (((Player) this).getGamemode() != Player.CREATIVE) this.attack(new EntityDamageEvent(this, DamageCause.VOID, 10)); } else { this.attack(new EntityDamageEvent(this, DamageCause.VOID, 10)); hasUpdate = true; @@ -1445,19 +1625,19 @@ public boolean entityBaseTick(int tickDiff) { if (this.fireTicks > 0) { if (this.fireProof) { - this.fireTicks -= 4 * tickDiff; + this.fireTicks -= tickDiff << 2; if (this.fireTicks < 0) { this.fireTicks = 0; } } else { - if (!this.hasEffect(Effect.FIRE_RESISTANCE) && ((this.fireTicks % 20) == 0 || tickDiff > 20)) { + if (((this.fireTicks % 20) == 0 || tickDiff > 20) && !this.hasEffect(Effect.FIRE_RESISTANCE)) { this.attack(new EntityDamageEvent(this, DamageCause.FIRE_TICK, 1)); } this.fireTicks -= tickDiff; } if (this.fireTicks <= 0) { this.extinguish(); - } else if (!this.fireProof && (!(this instanceof Player) || !((Player) this).isSpectator())) { + } else if (!this.fireProof && (!(this instanceof Player) || !((Player) this).isSpectator()) && !(this instanceof EntityBoss)) { this.setDataFlag(DATA_FLAGS, DATA_FLAG_ONFIRE, true); hasUpdate = true; } @@ -1470,45 +1650,34 @@ public boolean entityBaseTick(int tickDiff) { } } - if (this.inPortalTicks == 80) { - EntityPortalEnterEvent ev = new EntityPortalEnterEvent(this, PortalType.NETHER); - getServer().getPluginManager().callEvent(ev); + if (this.inPortalTicks == 80 && Server.getInstance().isNetherAllowed() && this instanceof BaseEntity) { + EntityPortalEnterEvent ev = new EntityPortalEnterEvent(this, EntityPortalEnterEvent.PortalType.NETHER); + this.server.getPluginManager().callEvent(ev); if (!ev.isCancelled()) { - Position newPos = EnumLevel.moveToNether(this); - if (newPos != null) { - for (int x = -1; x < 2; x++) { - for (int z = -1; z < 2; z++) { - int chunkX = (newPos.getFloorX() >> 4) + x, chunkZ = (newPos.getFloorZ() >> 4) + z; - FullChunk chunk = newPos.level.getChunk(chunkX, chunkZ, false); - if (chunk == null || !(chunk.isGenerated() || chunk.isPopulated())) { - newPos.level.generateChunk(chunkX, chunkZ, true); - } - } - } - this.teleport(newPos.add(1.5, 1, 0.5)); - server.getScheduler().scheduleDelayedTask(new Task() { - @Override - public void onRun(int currentTick) { - // dirty hack to make sure chunks are loaded and generated before spawning - // player - teleport(newPos.add(1.5, 1, 0.5)); - BlockNetherPortal.spawnPortal(newPos); - } - }, 20); + if (this.getLevel().getDimension() == Level.DIMENSION_NETHER) { + this.switchLevel(server.getDefaultLevel()); + } else { + this.switchLevel(server.getLevelByName("nether")); } } } this.age += tickDiff; this.ticksLived += tickDiff; - TimingsHistory.activatedEntityTicks++; - - Timings.entityBaseTickTimer.stopTiming(); return hasUpdate; } public void updateMovement() { + // Reset motion when it approaches 0 to avoid unnecessary processing of move() + if (Math.abs(this.motionX) < 0.00001) { + this.motionX = 0; + } + + if (Math.abs(this.motionZ) < 0.00001) { + this.motionZ = 0; + } + double diffPosition = (this.x - this.lastX) * (this.x - this.lastX) + (this.y - this.lastY) * (this.y - this.lastY) + (this.z - this.lastZ) * (this.z - this.lastZ); double diffRotation = (this.yaw - this.lastYaw) * (this.yaw - this.lastYaw) + (this.pitch - this.lastPitch) * (this.pitch - this.lastPitch); @@ -1519,12 +1688,11 @@ public void updateMovement() { this.lastY = this.y; this.lastZ = this.z; - this.lastPitch = this.pitch; this.lastYaw = this.yaw; + this.lastPitch = this.pitch; this.lastHeadYaw = this.headYaw; - // If you want to achieve headYaw in movement. You can override it by yourself. Changing would break some mob plugins. - this.addMovement(this.x, this.isPlayer ? this.y : this.y + this.getBaseOffset(), this.z, this.yaw, this.pitch, this.yaw); + this.addMovement(this.x, this instanceof Player ? this.y : this.y + this.getBaseOffset(), this.z, this.yaw, this.pitch, this.headYaw == 0 || this instanceof Player ? this.yaw : this.headYaw); } if (diffMotion > 0.0025 || (diffMotion > 0.0001 && this.getMotion().lengthSquared() <= 0.0001)) { //0.05 ** 2 @@ -1541,22 +1709,19 @@ public void addMovement(double x, double y, double z, double yaw, double pitch, } public void addMotion(double motionX, double motionY, double motionZ) { + if (this instanceof EntityItem) return; // Seems to be unnecessary SetEntityMotionPacket pk = new SetEntityMotionPacket(); pk.eid = this.id; pk.motionX = (float) motionX; pk.motionY = (float) motionY; pk.motionZ = (float) motionZ; - - Server.broadcastPacket(this.hasSpawned.values(), pk); - } - - public Vector3 getDirectionVector() { - Vector3 vector = super.getDirectionVector(); - return this.temporalVector.setComponents(vector.x, vector.y, vector.z); + for (Player p : this.hasSpawned.values()) { + p.dataPacket(pk); + } } public Vector2 getDirectionPlane() { - return (new Vector2((float) (-Math.cos(Math.toRadians(this.yaw) - Math.PI / 2)), (float) (-Math.sin(Math.toRadians(this.yaw) - Math.PI / 2)))).normalize(); + return (new Vector2((float) (-Math.cos(Math.toRadians(this.yaw) - 1.5707963267948966)), (float) (-Math.sin(Math.toRadians(this.yaw) - 1.5707963267948966)))).normalize(); } public BlockFace getHorizontalFacing() { @@ -1572,7 +1737,7 @@ public boolean onUpdate(int currentTick) { ++this.deadTicks; if (this.deadTicks >= 10) { this.despawnFromAll(); - if (!this.isPlayer) { + if (!(this instanceof Player)) { this.close(); } } @@ -1580,7 +1745,6 @@ public boolean onUpdate(int currentTick) { } int tickDiff = currentTick - this.lastUpdate; - if (tickDiff <= 0) { return false; } @@ -1599,7 +1763,7 @@ public boolean mountEntity(Entity entity) { } /** - * Mount an Entity from a/into vehicle + * Mount an Entity into a vehicle * * @param entity The target Entity * @return {@code true} if the mounting successful @@ -1607,24 +1771,32 @@ public boolean mountEntity(Entity entity) { public boolean mountEntity(Entity entity, byte mode) { Objects.requireNonNull(entity, "The target of the mounting entity can't be null"); - if (isPassenger(entity) || entity.riding != null && !entity.riding.dismountEntity(entity, false)) { + if (entity instanceof Player && ((Player) entity).isSleeping()) { return false; } - // Entity entering a vehicle - EntityVehicleEnterEvent ev = new EntityVehicleEnterEvent(entity, this); - server.getPluginManager().callEvent(ev); - if (ev.isCancelled()) { + if (isPassenger(entity) || entity.riding != null && !entity.riding.dismountEntity(entity, false)) { return false; } - broadcastLinkPacket(entity, mode); + // Entity entering a vehicle + if (this instanceof EntityVehicle) { + EntityVehicleEnterEvent ev = new EntityVehicleEnterEvent(entity, (EntityVehicle) this); + server.getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + return false; + } + } // Add variables to entity entity.riding = this; entity.setDataFlag(DATA_FLAGS, DATA_FLAG_RIDING, true); passengers.add(entity); + if (this instanceof EntityMinecartEmpty) { + entity.enterMinecartPos = new Vector3(entity.x, entity.y, entity.z); + } + entity.setSeatPosition(getMountedOffset(entity)); updatePassengerPosition(entity); return true; @@ -1635,17 +1807,19 @@ public boolean dismountEntity(Entity entity) { } public boolean dismountEntity(Entity entity, boolean sendLinks) { - // Run the events - EntityVehicleExitEvent ev = new EntityVehicleExitEvent(entity, this); - server.getPluginManager().callEvent(ev); - if (ev.isCancelled()) { - int seatIndex = this.passengers.indexOf(entity); - if (seatIndex == 0) { - this.broadcastLinkPacket(entity, TYPE_RIDE); - } else if (seatIndex != -1) { - this.broadcastLinkPacket(entity, TYPE_PASSENGER); + if (this instanceof EntityVehicle) { + // Run the events + EntityVehicleExitEvent ev = new EntityVehicleExitEvent(entity, (EntityVehicle) this); + server.getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + int seatIndex = this.passengers.indexOf(entity); + if (seatIndex == 0) { + this.broadcastLinkPacket(entity, TYPE_RIDE); + } else if (seatIndex != -1) { + this.broadcastLinkPacket(entity, TYPE_PASSENGER); + } + return false; } - return false; } if (sendLinks) { @@ -1660,13 +1834,22 @@ public boolean dismountEntity(Entity entity, boolean sendLinks) { entity.setSeatPosition(new Vector3f()); updatePassengerPosition(entity); + // Avoid issues with anti fly + entity.resetFallDistance(); + + if (this instanceof EntityMinecartEmpty) { + if (entity instanceof Player && entity.enterMinecartPos != null && this.distanceSquared(entity.enterMinecartPos) >= 1000000) { // 1000 blocks + ((Player) entity).awardAchievement("onARail"); + } + entity.enterMinecartPos = null; + } return true; } protected void broadcastLinkPacket(Entity rider, byte type) { SetEntityLinkPacket pk = new SetEntityLinkPacket(); - pk.vehicleUniqueId = getId(); // To the? - pk.riderUniqueId = rider.getId(); // From who? + pk.vehicleUniqueId = id; // To the? + pk.riderUniqueId = rider.id; // From who? pk.type = type; Server.broadcastPacket(this.hasSpawned.values(), pk); @@ -1704,7 +1887,9 @@ public Vector3f getMountedOffset(Entity entity) { } public final void scheduleUpdate() { - this.level.updateEntities.put(this.id, this); + if (!this.closed && !this.level.isBeingConverted) { + this.level.updateEntities.put(this.id, this); + } } public boolean isOnFire() { @@ -1725,8 +1910,7 @@ public float getAbsorption() { public void setAbsorption(float absorption) { if (absorption != this.absorption) { this.absorption = absorption; - if (this instanceof Player) - ((Player) this).setAttribute(Attribute.getAttribute(Attribute.ABSORPTION).setValue(absorption)); + if (this instanceof Player) ((Player) this).setAttribute(Attribute.getAttribute(Attribute.ABSORPTION).setValue(absorption)); } } @@ -1744,6 +1928,7 @@ public BlockFace getDirection() { } else if (225 <= rotation && rotation < 315) { return BlockFace.EAST; } else { + this.server.getLogger().debug("Failed to getDirection for yaw=" + this.yaw); return null; } } @@ -1753,12 +1938,13 @@ public void extinguish() { this.setDataFlag(DATA_FLAGS, DATA_FLAG_ONFIRE, false); } + @Deprecated public boolean canTriggerWalking() { return true; } public void resetFallDistance() { - this.highestPosition = 0; + this.highestPosition = this.y; } protected void updateFallState(boolean onGround) { @@ -1766,9 +1952,8 @@ protected void updateFallState(boolean onGround) { fallDistance = (float) (this.highestPosition - this.y); if (fallDistance > 0) { - // check if we fell into at least 1 block of water - if (this instanceof EntityLiving && !(this.getLevelBlock() instanceof BlockWater)) { - this.fall(fallDistance); + if (this instanceof EntityLiving && !(this instanceof EntityFlying)) { + this.fall(fallDistance); // NOTE -- if you override fall(): water check was moved INSIDE fall() } this.resetFallDistance(); } @@ -1780,48 +1965,55 @@ public AxisAlignedBB getBoundingBox() { } public void fall(float fallDistance) { - if (this.hasEffect(Effect.SLOW_FALLING)) { - return; - } - - Block down = this.level.getBlock(this.floor().down()); - - if (!this.isPlayer || level.getGameRules().getBoolean(GameRule.FALL_DAMAGE)) { - float damage = (float) Math.floor(fallDistance - 3 - (this.hasEffect(Effect.JUMP) ? this.getEffect(Effect.JUMP).getAmplifier() + 1 : 0)); - - if (down instanceof BlockHayBale) { - damage -= (damage * 0.8f); - } - - if (damage > 0) { - this.attack(new EntityDamageEvent(this, DamageCause.FALL, damage)); - } - } - if (fallDistance > 0.75) { + int block = this.level.getBlockIdAt(this.chunk, this.getFloorX(), this.getFloorY(), this.getFloorZ()); + if (Block.isWater(block)) { + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_SPLASH, ThreadLocalRandom.current().nextInt(600000, 800000), "minecraft:player", false, false); + return; // TODO: Some waterlogged blocks prevent fall damage + } + if (!this.hasEffect(Effect.SLOW_FALLING)) { + Block down = this.level.getBlock(this.chunk, this.getFloorX(), this.getFloorY() - 1, this.getFloorZ(), true); + int floor = down.getId(); + + if (!this.noFallDamage) { + float damage = (float) Math.floor(fallDistance - 3 - (this.hasEffect(Effect.JUMP) ? this.getEffect(Effect.JUMP).getAmplifier() + 1 : 0)); + + if (floor == BlockID.HAY_BALE || block == BlockID.HAY_BALE) { + damage -= (damage * 0.8f); + } else if (floor == BlockID.BED_BLOCK || block == BlockID.BED_BLOCK) { + damage -= (damage * 0.5f); + } else if (floor == BlockID.SWEET_BERRY_BUSH || floor == BlockID.SCAFFOLDING || block == BlockID.SWEET_BERRY_BUSH || block == BlockID.SCAFFOLDING) { + damage = 0; + } else if ((floor == BlockID.SLIME_BLOCK || floor == BlockID.COBWEB || block == BlockID.SLIME_BLOCK || block == BlockID.COBWEB) && !this.isSneaking()) { + damage = 0; + } - if (down.getId() == Item.FARMLAND) { - Event ev; - - if (this instanceof Player) { - ev = new PlayerInteractEvent((Player) this, null, down, null, Action.PHYSICAL); - } else { - ev = new EntityInteractEvent(this, down); + if (damage > 0) { + if (!(this instanceof Player) || level.getGameRules().getBoolean(GameRule.FALL_DAMAGE)) { + this.attack(new EntityDamageEvent(this, DamageCause.FALL, damage)); + } + } } - this.server.getPluginManager().callEvent(ev); - if (ev.isCancelled()) { - return; + if (floor == BlockID.FARMLAND) { + Event ev; + if (this instanceof Player) { + ev = new PlayerInteractEvent((Player) this, null, down, null, Action.PHYSICAL); + } else { + ev = new EntityInteractEvent(this, down); + } + + this.server.getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + return; + } + this.level.setBlock(down, Block.get(BlockID.DIRT), true, true); } - this.level.setBlock(down, Block.get(BlockID.DIRT), false, true); } } } - public void handleLavaMovement() { - //todo - } - + @Deprecated public void moveFlying(float strafe, float forward, float friction) { // This is special for Nukkit! :) float speed = strafe * strafe + forward * forward; @@ -1840,10 +2032,6 @@ public void moveFlying(float strafe, float forward, float friction) { } } - public void onCollideWithPlayer(EntityHuman entityPlayer) { - - } - public void applyEntityCollision(Entity entity) { if (entity.riding != this && !entity.passengers.contains(this)) { double dx = entity.x - this.x; @@ -1865,7 +2053,6 @@ public void applyEntityCollision(Entity entity) { dx *= 0.05000000074505806; dy *= 0.05000000074505806; dx *= 1F + entityCollisionReduction; - if (this.riding == null) { motionX -= dx; motionZ -= dy; @@ -1874,9 +2061,9 @@ public void applyEntityCollision(Entity entity) { } } - public void onStruckByLightning(Entity entity) { - if (this.attack(new EntityDamageByEntityEvent(entity, this, DamageCause.LIGHTNING, 5))) { - if (this.fireTicks < 8 * 20) { + public void onStruckByLightning(Entity lightning) { + if (this.attack(new EntityDamageByEntityEvent(lightning, this, DamageCause.LIGHTNING, 5))) { + if (this.fireTicks < 160) { this.setOnFire(8); } } @@ -1886,6 +2073,7 @@ public boolean onInteract(Player player, Item item, Vector3 clickedPos) { return onInteract(player, item); } + @Deprecated public boolean onInteract(Player player, Item item) { return false; } @@ -1907,15 +2095,26 @@ protected boolean switchLevel(Level targetLevel) { this.chunk.removeEntity(this); } this.despawnFromAll(); + + this.preSwitchLevel(); } this.setLevel(targetLevel); this.level.addEntity(this); this.chunk = null; + this.afterSwitchLevel(); return true; } + protected void preSwitchLevel() { + // Override in Player + } + + protected void afterSwitchLevel() { + // Override in Player + } + public Position getPosition() { return new Position(this.x, this.y, this.z, this.level); } @@ -1924,31 +2123,36 @@ public Location getLocation() { return new Location(this.x, this.y, this.z, this.yaw, this.pitch, this.headYaw, this.level); } - public boolean isInsideOfWater() { - double y = this.y + this.getEyeHeight(); - Block block = this.level.getBlock(this.temporalVector.setComponents(NukkitMath.floorDouble(this.x), NukkitMath.floorDouble(y), NukkitMath.floorDouble(this.z))); + public boolean isSubmerged() { + int fx = this.getFloorX(); + int fy = NukkitMath.floorDouble(this.y + this.getEyeHeight()); + int fz = this.getFloorZ(); + int bid = level.getBlockIdAt(this.chunk, fx, fy, fz); - if (block instanceof BlockWater) { - double f = (block.y + 1) - (((BlockWater) block).getFluidHeightPercent() - 0.1111111); - return y < f; - } + return bid != Block.BUBBLE_COLUMN && + (Block.isWater(bid) || this.level.isBlockWaterloggedAt(this.chunk, fx, fy, fz)); + } - return false; + public boolean isInsideOfWater() { + int fx = this.getFloorX(); + int fy = this.getFloorY(); + int fz = this.getFloorZ(); + int bid = level.getBlockIdAt(this.chunk, fx, fy, fz); + + return Block.isWater(bid) || this.level.isBlockWaterloggedAt(this.chunk, fx, fy, fz); } public boolean isInsideOfSolid() { double y = this.y + this.getEyeHeight(); - Block block = this.level.getBlock( - this.temporalVector.setComponents( + Block block = this.level.getBlock(this.chunk, NukkitMath.floorDouble(this.x), NukkitMath.floorDouble(y), - NukkitMath.floorDouble(this.z)) + NukkitMath.floorDouble(this.z), true ); AxisAlignedBB bb = block.getBoundingBox(); - return bb != null && block.isSolid() && !block.isTransparent() && bb.intersectsWith(this.getBoundingBox()); - + return bb != null && block.isSolid() && !block.isTransparent() && bb.intersectsWith(this.boundingBox); } public boolean isInsideOfFire() { @@ -1961,22 +2165,18 @@ public boolean isInsideOfFire() { return false; } - public boolean isOnLadder() { - Block b = this.getLevelBlock(); - - return b.getId() == Block.LADDER; - } - public boolean fastMove(double dx, double dy, double dz) { if (dx == 0 && dy == 0 && dz == 0) { return true; } - Timings.entityMoveTimer.startTiming(); + if (!(this instanceof Player)) { + this.blocksAround = null; + } AxisAlignedBB newBB = this.boundingBox.getOffsetBoundingBox(dx, dy, dz); - if (server.getAllowFlight() || !this.level.hasCollision(this, newBB, false)) { + if (server.getAllowFlight() || (this instanceof Player && ((Player) this).isSpectator()) || !this.level.hasCollision(this, this.getStepHeight() == 0 ? newBB : newBB.shrink(0, this.getStepHeight(), 0), false)) { this.boundingBox = newBB; } @@ -1986,33 +2186,34 @@ public boolean fastMove(double dx, double dy, double dz) { this.checkChunks(); - if (!this.onGround || dy != 0) { + if (!this.noClip && (!this.onGround || dy != 0) && (!(this instanceof Player) || !((Player) this).isSpectator())) { AxisAlignedBB bb = this.boundingBox.clone(); bb.setMinY(bb.getMinY() - 0.75); - this.onGround = this.level.getCollisionBlocks(bb).length > 0; + this.onGround = this.level.hasCollisionBlocks(this, bb); } + this.isCollided = this.onGround; this.updateFallState(this.onGround); - Timings.entityMoveTimer.stopTiming(); return true; } public boolean move(double dx, double dy, double dz) { if (dx == 0 && dz == 0 && dy == 0) { - return true; + return false; + } + + if (!(this instanceof Player)) { + this.blocksAround = null; } if (this.keepMovement) { this.boundingBox.offset(dx, dy, dz); this.setPosition(this.temporalVector.setComponents((this.boundingBox.getMinX() + this.boundingBox.getMaxX()) / 2, this.boundingBox.getMinY(), (this.boundingBox.getMinZ() + this.boundingBox.getMaxZ()) / 2)); - this.onGround = this.isPlayer; + this.onGround = this instanceof Player; // This should be false? Maybe use noClip instead? return true; } else { - - Timings.entityMoveTimer.startTiming(); - - this.ySize *= 0.4; + this.ySize *= STEP_CLIP_MULTIPLIER; double movX = dx; double movY = dy; @@ -2020,7 +2221,7 @@ public boolean move(double dx, double dy, double dz) { AxisAlignedBB axisalignedbb = this.boundingBox.clone(); - AxisAlignedBB[] list = this.level.getCollisionCubes(this, this.boundingBox.addCoord(dx, dy, dz), false); + AxisAlignedBB[] list = this.noClip ? new AxisAlignedBB[0] : this.level.getCollisionCubes(this, this.boundingBox.addCoord(dx, dy, dz), false); for (AxisAlignedBB bb : list) { dy = bb.calculateYOffset(this.boundingBox, dy); @@ -2042,7 +2243,7 @@ public boolean move(double dx, double dy, double dz) { this.boundingBox.offset(0, 0, dz); - if (this.getStepHeight() > 0 && fallingFlag && this.ySize < 0.05 && (movX != dx || movZ != dz)) { + if (this.getStepHeight() > 0 && fallingFlag && (movX != dx || movZ != dz)) { double cx = dx; double cy = dy; double cz = dz; @@ -2074,7 +2275,12 @@ public boolean move(double dx, double dy, double dz) { this.boundingBox.offset(0, 0, dz); - this.boundingBox.offset(0, 0, dz); + double reverseDY = -dy; + for (AxisAlignedBB bb : list) { + reverseDY = bb.calculateYOffset(this.boundingBox, reverseDY); + } + dy += reverseDY; + this.boundingBox.offset(0, reverseDY, 0); if ((cx * cx + cz * cz) >= (dx * dx + dz * dz)) { dx = cx; @@ -2082,9 +2288,8 @@ public boolean move(double dx, double dy, double dz) { dz = cz; this.boundingBox.setBB(axisalignedbb1); } else { - this.ySize += 0.5; + this.ySize += dy; } - } this.x = (this.boundingBox.getMinX() + this.boundingBox.getMaxX()) / 2; @@ -2107,18 +2312,22 @@ public boolean move(double dx, double dy, double dz) { if (movZ != dz) { this.motionZ = 0; } - - //TODO: vehicle collision events (first we need to spawn them!) - Timings.entityMoveTimer.stopTiming(); return true; } } protected void checkGroundState(double movX, double movY, double movZ, double dx, double dy, double dz) { - this.isCollidedVertically = movY != dy; - this.isCollidedHorizontally = (movX != dx || movZ != dz); - this.isCollided = (this.isCollidedHorizontally || this.isCollidedVertically); - this.onGround = (movY != dy && movY < 0); + if (this.noClip) { + this.isCollidedVertically = false; + this.isCollidedHorizontally = false; + this.isCollided = false; + this.onGround = false; + } else { + this.isCollidedVertically = movY != dy; + this.isCollidedHorizontally = (movX != dx || movZ != dz); + this.isCollided = (this.isCollidedHorizontally || this.isCollidedVertically); + this.onGround = (movY != dy && movY < 0); + } } public List getBlocksAround() { @@ -2135,7 +2344,7 @@ public List getBlocksAround() { for (int z = minZ; z <= maxZ; ++z) { for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { - Block block = this.level.getBlock(this.temporalVector.setComponents(x, y, z)); + Block block = this.level.getBlock(chunk, x, y, z, false); this.blocksAround.add(block); } } @@ -2149,8 +2358,9 @@ public List getCollisionBlocks() { if (this.collisionBlocks == null) { this.collisionBlocks = new ArrayList<>(); - for (Block b : getBlocksAround()) { - if (b.collidesWithBB(this.getBoundingBox(), true)) { + List bl = this.getBlocksAround(); + for (Block b : bl) { + if (b.collidesWithBB(this.boundingBox, true)) { this.collisionBlocks.add(b); } } @@ -2169,6 +2379,8 @@ public boolean canBeMovedByCurrents() { } protected void checkBlockCollision() { + if (this.noClip) return; + Vector3 vector = new Vector3(0, 0, 0); boolean portal = false; @@ -2183,11 +2395,7 @@ protected void checkBlockCollision() { } if (portal) { - if (this.inPortalTicks < 80) { - this.inPortalTicks = 80; - } else { - this.inPortalTicks++; - } + inPortalTicks++; } else { this.inPortalTicks = 0; } @@ -2202,12 +2410,7 @@ protected void checkBlockCollision() { } public boolean setPositionAndRotation(Vector3 pos, double yaw, double pitch) { - if (this.setPosition(pos)) { - this.setRotation(yaw, pitch); - return true; - } - - return false; + return this.setPositionAndRotation(pos, yaw, pitch, yaw); } public boolean setPositionAndRotation(Vector3 pos, double yaw, double pitch, double headYaw) { @@ -2220,9 +2423,7 @@ public boolean setPositionAndRotation(Vector3 pos, double yaw, double pitch, dou } public void setRotation(double yaw, double pitch) { - this.yaw = yaw; - this.pitch = pitch; - this.scheduleUpdate(); + this.setRotation(yaw, pitch, yaw); } public void setRotation(double yaw, double pitch, double headYaw) { @@ -2233,8 +2434,7 @@ public void setRotation(double yaw, double pitch, double headYaw) { } /** - * Whether the entity can active pressure plates. - * Used for {@link cn.nukkit.entity.passive.EntityBat}s only. + * Whether the entity can activate pressure plates. * * @return triggers pressure plate */ @@ -2247,14 +2447,16 @@ public boolean canPassThrough() { } protected void checkChunks() { - if (this.chunk == null || (this.chunk.getX() != ((int) this.x >> 4)) || this.chunk.getZ() != ((int) this.z >> 4)) { + int cx = this.getChunkX(); + int cz = this.getChunkZ(); + if (this.chunk == null || (this.chunk.getX() != cx) || this.chunk.getZ() != cz) { if (this.chunk != null) { this.chunk.removeEntity(this); } - this.chunk = this.level.getChunk((int) this.x >> 4, (int) this.z >> 4, true); + this.chunk = this.level.getChunk(cx, cz, true); if (!this.justCreated) { - Map newChunk = this.level.getChunkPlayers((int) this.x >> 4, (int) this.z >> 4); + Map newChunk = this.level.getChunkPlayers(cx, cz); for (Player player : new ArrayList<>(this.hasSpawned.values())) { if (!newChunk.containsKey(player.getLoaderId())) { this.despawnFrom(player); @@ -2281,17 +2483,39 @@ public boolean setPosition(Vector3 pos) { return false; } - if (pos instanceof Position && ((Position) pos).level != null && ((Position) pos).level != this.level) { - if (!this.switchLevel(((Position) pos).getLevel())) { - return false; + if (pos instanceof Position) { + Level oldLevel = this.level; + Level newLevel = ((Position) pos).level; + + if (newLevel != null && newLevel != oldLevel) { + if (!this.switchLevel(newLevel)) { + return false; + } + + this.x = pos.x; + this.y = pos.y; + this.z = pos.z; + + // Dimension change + if (this instanceof Player && newLevel.getDimension() != oldLevel.getDimension()) { + ((Player) this).setDimension(newLevel.getDimension()); + } + } else { + this.x = pos.x; + this.y = pos.y; + this.z = pos.z; } + } else { + this.x = pos.x; + this.y = pos.y; + this.z = pos.z; } - this.x = pos.x; - this.y = pos.y; - this.z = pos.z; + this.recalculateBoundingBox(); - this.recalculateBoundingBox(false); // Don't need to send BB height/width to client on position change + if (!(this instanceof Player)) { + this.blocksAround = null; + } this.checkChunks(); @@ -2330,8 +2554,11 @@ public void kill() { this.health = 0; this.scheduleUpdate(); - for (Entity passenger : new ArrayList<>(this.passengers)) { - dismountEntity(passenger); + if (!passengers.isEmpty()) { + for (Entity passenger : new ArrayList<>(passengers)) { + dismountEntity(passenger); + passenger.riding = null; // Make sure it's really removed even if a plugin tries to cancel it + } } } @@ -2356,12 +2583,16 @@ public boolean teleport(Location location) { } public boolean teleport(Location location, PlayerTeleportEvent.TeleportCause cause) { + if (!this.server.isPrimaryThread()) { + this.server.getLogger().warning("Entity teleported asynchronously: " + this.getClass().getSimpleName()); + } + double yaw = location.yaw; double pitch = location.pitch; - Location from = this.getLocation(); Location to = location; if (cause != null) { + Location from = this.getLocation(); EntityTeleportEvent ev = new EntityTeleportEvent(this, from, to, cause); this.server.getPluginManager().callEvent(ev); if (ev.isCancelled()) { @@ -2376,11 +2607,13 @@ public boolean teleport(Location location, PlayerTeleportEvent.TeleportCause cau this.ySize = 0; - this.setMotion(this.temporalVector.setComponents(0, 0, 0)); + if (cause != PlayerTeleportEvent.TeleportCause.ENDER_PEARL) { + this.setMotion(this.temporalVector.setComponents(0, 0, 0)); + } if (this.setPositionAndRotation(to, yaw, pitch)) { this.resetFallDistance(); - this.onGround = true; + this.onGround = !this.noClip; this.updateMovement(); @@ -2424,6 +2657,11 @@ public void despawnFromAll() { public void close() { if (!this.closed) { this.closed = true; + + if (!this.server.isPrimaryThread() && !this.level.isBeingConverted) { + this.server.getLogger().warning("Entity closed asynchronously: " + this.getClass().getSimpleName()); + } + this.server.getPluginManager().callEvent(new EntityDespawnEvent(this)); this.despawnFromAll(); if (this.chunk != null) { @@ -2437,24 +2675,42 @@ public void close() { } public boolean setDataProperty(EntityData data) { - return setDataProperty(data, true); + return this.setDataProperty(data, true); } public boolean setDataProperty(EntityData data, boolean send) { - if (Objects.equals(data, this.dataProperties.get(data.getId()))) { - return false; + if (!Objects.equals(data, this.dataProperties.get(data.getId()))) { + this.dataProperties.put(data); + if (send) { + EntityMetadata metadata = new EntityMetadata(); + metadata.put(this.dataProperties.get(data.getId())); + if (data.getId() == DATA_FLAGS_EXTENDED) { + metadata.put(this.dataProperties.get(DATA_FLAGS)); + } + this.sendData(this.hasSpawned.values().toArray(new Player[0]), metadata); + } + return true; } + return false; + } - this.dataProperties.put(data); - if (send) { - EntityMetadata metadata = new EntityMetadata(); - metadata.put(this.dataProperties.get(data.getId())); - if (data.getId() == DATA_FLAGS_EXTENDED) { - metadata.put(this.dataProperties.get(DATA_FLAGS)); + protected boolean setDataPropertyAndSendOnlyToSelf(EntityData data) { + if (data == null) { + throw new IllegalArgumentException("setDataPropertyAndSendOnlyToSelf: EntityData must not be null"); + } + if (!Objects.equals(data, this.dataProperties.get(data.getId()))) { + this.dataProperties.put(data); + if (this instanceof Player) { + EntityMetadata metadata = new EntityMetadata(); + metadata.put(this.dataProperties.get(data.getId())); + SetEntityDataPacket pk = new SetEntityDataPacket(); + pk.eid = this.id; + pk.metadata = metadata; + ((Player) this).dataPacket(pk); } - this.sendData(this.hasSpawned.values().toArray(new Player[0]), metadata); + return true; } - return true; + return false; } public EntityMetadata getDataProperties() { @@ -2462,51 +2718,52 @@ public EntityMetadata getDataProperties() { } public EntityData getDataProperty(int id) { - return this.getDataProperties().get(id); + return this.dataProperties.get(id); } public int getDataPropertyInt(int id) { - return this.getDataProperties().getInt(id); + return this.dataProperties.getInt(id); } public int getDataPropertyShort(int id) { - return this.getDataProperties().getShort(id); + return this.dataProperties.getShort(id); } public int getDataPropertyByte(int id) { - return this.getDataProperties().getByte(id); + return this.dataProperties.getByte(id); } public boolean getDataPropertyBoolean(int id) { - return this.getDataProperties().getBoolean(id); + return this.dataProperties.getBoolean(id); } public long getDataPropertyLong(int id) { - return this.getDataProperties().getLong(id); + return this.dataProperties.getLong(id); } public String getDataPropertyString(int id) { - return this.getDataProperties().getString(id); + return this.dataProperties.getString(id); } public float getDataPropertyFloat(int id) { - return this.getDataProperties().getFloat(id); + return this.dataProperties.getFloat(id); } public CompoundTag getDataPropertyNBT(int id) { - return this.getDataProperties().getNBT(id); + return this.dataProperties.getNBT(id); } public Vector3 getDataPropertyPos(int id) { - return this.getDataProperties().getPosition(id); + return this.dataProperties.getPosition(id); } public Vector3f getDataPropertyVector3f(int id) { - return this.getDataProperties().getFloatPosition(id); + return this.dataProperties.getFloatPosition(id); } public int getDataPropertyType(int id) { - return this.getDataProperties().exists(id) ? this.getDataProperty(id).getType() : -1; + EntityData data = this.getDataProperty(id); + return data == null ? -1 : data.getType(); } public void setDataFlag(int propertyId, int id) { @@ -2514,17 +2771,36 @@ public void setDataFlag(int propertyId, int id) { } public void setDataFlag(int propertyId, int id, boolean value) { + this.setDataFlag(propertyId, id, value, true); + } + + public void setDataFlag(int propertyId, int id, boolean value, boolean send) { if (this.getDataFlag(propertyId, id) != value) { if (propertyId == EntityHuman.DATA_PLAYER_FLAGS) { byte flags = (byte) this.getDataPropertyByte(propertyId); flags ^= 1 << id; - this.setDataProperty(new ByteEntityData(propertyId, flags)); + this.setDataProperty(new ByteEntityData(propertyId, flags), send); } else { - long flags = this.getDataPropertyLong(propertyId); - flags ^= 1L << id; - this.setDataProperty(new LongEntityData(propertyId, flags)); + LongEntityData oldData = (LongEntityData) this.dataProperties.getOrDefault(propertyId, new LongEntityData(propertyId, 0)); + long flags = oldData.getData() ^ 1L << id; + LongEntityData newData = new LongEntityData(propertyId, flags); + this.setDataProperty(newData, send); } + } + } + protected void setDataFlagSelfOnly(int propertyId, int id, boolean value) { + if (this.getDataFlag(propertyId, id) != value) { + if (propertyId == EntityHuman.DATA_PLAYER_FLAGS) { + byte flags = (byte) this.getDataPropertyByte(propertyId); + flags ^= 1 << id; + this.setDataPropertyAndSendOnlyToSelf(new ByteEntityData(propertyId, flags)); + } else { + LongEntityData oldData = (LongEntityData) this.dataProperties.getOrDefault(propertyId, new LongEntityData(propertyId, 0)); + long flags = oldData.getData() ^ 1L << id; + LongEntityData newData = new LongEntityData(propertyId, flags); + this.setDataPropertyAndSendOnlyToSelf(newData); + } } } @@ -2532,6 +2808,14 @@ public boolean getDataFlag(int propertyId, int id) { return (((propertyId == EntityHuman.DATA_PLAYER_FLAGS ? this.getDataPropertyByte(propertyId) & 0xff : this.getDataPropertyLong(propertyId))) & (1L << id)) > 0; } + public void setGenericFlag(int propertyId, boolean value) { + this.setDataFlag(propertyId >= 64 ? DATA_FLAGS_EXTENDED : DATA_FLAGS, propertyId % 64, value); + } + + public boolean getGenericFlag(int propertyId) { + return this.getDataFlag(propertyId >= 64 ? DATA_FLAGS_EXTENDED : DATA_FLAGS, propertyId % 64); + } + @Override public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { this.server.getEntityMetadata().setMetadata(this, metadataKey, newMetadataValue); @@ -2565,14 +2849,68 @@ public boolean equals(Object obj) { return false; } Entity other = (Entity) obj; - return this.getId() == other.getId(); + return this.id == other.id; } @Override public int hashCode() { - int hash = 7; - hash = (int) (29 * hash + this.getId()); - return hash; + return (int) (203 + this.id); + } + + public boolean isOnLadder() { + int b = this.level.getBlockIdAt(this.chunk, this.getFloorX(), this.getFloorY(), this.getFloorZ()); + return b == Block.LADDER || b == Block.VINES || b == Block.TWISTING_VINES || b == Block.WEEPING_VINES || b == Block.CAVE_VINES_BODY_WITH_BERRIES || b == Block.CAVE_VINES_HEAD_WITH_BERRIES; + } + + /** + * Check whether there is blocks above the entity + * + * @return no blocks above + */ + public boolean canSeeSky() { + int px = this.getFloorX(); + int py = this.getFloorY(); + int pz = this.getFloorZ(); + for (int i = level.getMaxBlockY(); i > py; i--) { + if (level.getBlockIdAt(chunk, px, i, pz) != 0) { + return false; + } + } + return true; + } + + public void setSaveToStorage(boolean saveToStorage) { + this.saveToStorage = saveToStorage; + } + + public boolean canSaveToStorage() { + return this.saveToStorage; + } + + public PersistentDataContainer getPersistentDataContainer() { + if (this.persistentContainer == null) { + this.persistentContainer = new PersistentDataContainerEntityWrapper(this); + } + return this.persistentContainer; + } + + public boolean hasPersistentDataContainer() { + return !this.getPersistentDataContainer().isEmpty(); + } + + protected void minimalEntityTick(int currentTick, int tickDiff) { + this.justCreated = false; + this.lastUpdate = currentTick; + + this.age += tickDiff; + this.ticksLived += tickDiff; + + if (this.noDamageTicks > 0) { + this.noDamageTicks -= tickDiff; + if (this.noDamageTicks < 0) { + this.noDamageTicks = 0; + } + } } public void playAnimation(String animation) { @@ -2581,4 +2919,11 @@ public void playAnimation(String animation) { animateEntityPacket.runtimeEntityIds.add(this.id); Server.broadcastPacket(this.hasSpawned.values(), animateEntityPacket); } + + /** + * Whether this entity can be modified only by creating or destroying it and doesn't need to cause a chunk save + */ + public boolean ignoredAsSaveReason() { + return false; + } } diff --git a/src/main/java/cn/nukkit/entity/EntityAgeable.java b/src/main/java/cn/nukkit/entity/EntityAgeable.java index 9cb95096fc5..297d0ec5665 100644 --- a/src/main/java/cn/nukkit/entity/EntityAgeable.java +++ b/src/main/java/cn/nukkit/entity/EntityAgeable.java @@ -1,9 +1,14 @@ package cn.nukkit.entity; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface EntityAgeable { + boolean isBaby(); + + default void setBaby(boolean baby) { + + } } diff --git a/src/main/java/cn/nukkit/entity/EntityArthropod.java b/src/main/java/cn/nukkit/entity/EntityArthropod.java index 1a99378394d..35ea6532d55 100644 --- a/src/main/java/cn/nukkit/entity/EntityArthropod.java +++ b/src/main/java/cn/nukkit/entity/EntityArthropod.java @@ -1,7 +1,7 @@ package cn.nukkit.entity; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface EntityArthropod { diff --git a/src/main/java/cn/nukkit/entity/EntityBoss.java b/src/main/java/cn/nukkit/entity/EntityBoss.java new file mode 100644 index 00000000000..9c2127c0852 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/EntityBoss.java @@ -0,0 +1,4 @@ +package cn.nukkit.entity; + +public interface EntityBoss { +} diff --git a/src/main/java/cn/nukkit/entity/EntityControllable.java b/src/main/java/cn/nukkit/entity/EntityControllable.java new file mode 100644 index 00000000000..de9ba1e516a --- /dev/null +++ b/src/main/java/cn/nukkit/entity/EntityControllable.java @@ -0,0 +1,11 @@ +package cn.nukkit.entity; + +import cn.nukkit.Player; + +public interface EntityControllable { + + void onPlayerInput(Player player, double strafe, double forward); + + default void onJump(Player player, int duration) { + } +} diff --git a/src/main/java/cn/nukkit/entity/EntityCreature.java b/src/main/java/cn/nukkit/entity/EntityCreature.java index 17937e6e679..a935de8e0d8 100644 --- a/src/main/java/cn/nukkit/entity/EntityCreature.java +++ b/src/main/java/cn/nukkit/entity/EntityCreature.java @@ -7,31 +7,31 @@ import cn.nukkit.nbt.tag.CompoundTag; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class EntityCreature extends EntityLiving { + public EntityCreature(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } - // Armor stands, when implemented, should also check this. @Override public boolean onInteract(Player player, Item item, Vector3 clickedPos) { if (item.getId() == Item.NAME_TAG && !player.isAdventure()) { return applyNameTag(player, item); } + return false; } - // Structured like this so I can override nametags in player and dragon classes - // without overriding onInteract. - protected boolean applyNameTag(Player player, Item item) { - if (item.hasCustomName()) { - this.setNameTag(item.getCustomName()); - this.setNameTagVisible(true); - return true; // onInteract: true = decrease count - } - return false; + /** + * Called when player interacts the entity with a name tag item + * @param player player + * @param nameTag name tag item + * @return true to reduce name tag item count + */ + protected boolean applyNameTag(Player player, Item nameTag) { + return false; // Override in BaseEntity } } diff --git a/src/main/java/cn/nukkit/entity/EntityDamageable.java b/src/main/java/cn/nukkit/entity/EntityDamageable.java index 9b9785ce9ef..9f6bd252002 100644 --- a/src/main/java/cn/nukkit/entity/EntityDamageable.java +++ b/src/main/java/cn/nukkit/entity/EntityDamageable.java @@ -1,7 +1,7 @@ package cn.nukkit.entity; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface EntityDamageable { diff --git a/src/main/java/cn/nukkit/entity/EntityExplosive.java b/src/main/java/cn/nukkit/entity/EntityExplosive.java index b5df06eabe1..f69f05844e8 100644 --- a/src/main/java/cn/nukkit/entity/EntityExplosive.java +++ b/src/main/java/cn/nukkit/entity/EntityExplosive.java @@ -6,5 +6,4 @@ public interface EntityExplosive { void explode(); - } diff --git a/src/main/java/cn/nukkit/entity/EntityFlying.java b/src/main/java/cn/nukkit/entity/EntityFlying.java new file mode 100644 index 00000000000..f42b5715f46 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/EntityFlying.java @@ -0,0 +1,12 @@ +package cn.nukkit.entity; + +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; + +public abstract class EntityFlying extends BaseEntity { + + public EntityFlying(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + this.noFallDamage = true; + } +} diff --git a/src/main/java/cn/nukkit/entity/EntityHanging.java b/src/main/java/cn/nukkit/entity/EntityHanging.java index 8fe70a69c18..f153b74d804 100644 --- a/src/main/java/cn/nukkit/entity/EntityHanging.java +++ b/src/main/java/cn/nukkit/entity/EntityHanging.java @@ -5,21 +5,23 @@ import cn.nukkit.nbt.tag.CompoundTag; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class EntityHanging extends Entity { + protected int direction; public EntityHanging(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); + + this.updateMode = 3; } @Override protected void initEntity() { - super.initEntity(); - this.setMaxHealth(1); + super.initEntity(); this.setHealth(1); if (this.namedTag.contains("Direction")) { @@ -32,7 +34,6 @@ protected void initEntity() { this.direction = 2; } } - } @Override @@ -56,14 +57,30 @@ public boolean onUpdate(int currentTick) { return false; } + if (this.updateMode % 2 == 1) { + this.updateMode = 3; + } + + int tickDiff = currentTick - this.lastUpdate; + if (tickDiff <= 0 && !this.justCreated) { + return false; + } + + this.minimalEntityTick(currentTick, tickDiff); + if (!this.isAlive()) { + this.close(); + } - this.despawnFromAll(); - if (!this.isPlayer) { - this.close(); - } + if (!this.isAlive()) { + this.close(); + return false; + } - return true; + if (!this.isSurfaceValid()) { + this.dropItem(); + this.close(); + return false; } if (this.lastYaw != this.yaw || this.lastX != this.x || this.lastY != this.y || this.lastZ != this.z) { @@ -77,15 +94,17 @@ public boolean onUpdate(int currentTick) { this.lastZ = this.z; this.spawnToAll(); - - return true; + return false; } return false; } + protected void dropItem() { + + } + protected boolean isSurfaceValid() { return true; } - } diff --git a/src/main/java/cn/nukkit/entity/EntityHuman.java b/src/main/java/cn/nukkit/entity/EntityHuman.java index cb6881409cd..f6de2da1d52 100644 --- a/src/main/java/cn/nukkit/entity/EntityHuman.java +++ b/src/main/java/cn/nukkit/entity/EntityHuman.java @@ -3,12 +3,16 @@ import cn.nukkit.Player; import cn.nukkit.entity.data.IntPositionEntityData; import cn.nukkit.entity.data.Skin; +import cn.nukkit.event.entity.EntityDamageBlockedEvent; +import cn.nukkit.event.entity.EntityDamageEvent; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.ListTag; import cn.nukkit.nbt.tag.StringTag; import cn.nukkit.network.protocol.AddPlayerPacket; -import cn.nukkit.network.protocol.RemoveEntityPacket; +import cn.nukkit.network.protocol.MobArmorEquipmentPacket; import cn.nukkit.network.protocol.SetEntityLinkPacket; import cn.nukkit.utils.*; @@ -18,7 +22,7 @@ import java.util.stream.Collectors; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntityHuman extends EntityHumanType { @@ -27,13 +31,13 @@ public class EntityHuman extends EntityHumanType { public static final int DATA_PLAYER_FLAG_DEAD = 2; public static final int DATA_PLAYER_FLAGS = 26; - - public static final int DATA_PLAYER_BED_POSITION = 28; public static final int DATA_PLAYER_BUTTON_TEXT = 40; protected UUID uuid; protected byte[] rawUUID; + protected Skin skin; + @Override public float getWidth() { return 0.6f; @@ -46,21 +50,24 @@ public float getLength() { @Override public float getHeight() { - return 1.8f; + return isSwimming() || isGliding() || isCrawling() ? 0.6f : isSneaking() ? 1.5f : 1.8f; + } + + @Override + protected double getStepHeight() { + return 0.6; } @Override public float getEyeHeight() { - return 1.62f; + return isSwimming() || isGliding() || isCrawling() ? 0.42f : isSneaking() ? 1.26f : 1.62f; } @Override protected float getBaseOffset() { - return this.getEyeHeight(); + return 1.62f; } - protected Skin skin; - @Override public int getNetworkId() { return -1; @@ -88,9 +95,8 @@ public void setSkin(Skin skin) { @Override protected void initEntity() { - this.setDataFlag(DATA_PLAYER_FLAGS, DATA_PLAYER_FLAG_SLEEP, false); - this.setDataFlag(DATA_FLAGS, DATA_FLAG_GRAVITY); - + this.setDataFlag(DATA_PLAYER_FLAGS, DATA_PLAYER_FLAG_SLEEP, false, false); + this.setDataFlag(DATA_FLAGS, DATA_FLAG_GRAVITY, true, false); this.setDataProperty(new IntPositionEntityData(DATA_PLAYER_BED_POSITION, 0, 0, 0), false); if (!(this instanceof Player)) { @@ -113,9 +119,7 @@ protected void initEntity() { if (skinTag.contains("Data")) { byte[] data = skinTag.getByteArray("Data"); if (skinTag.contains("SkinImageWidth") && skinTag.contains("SkinImageHeight")) { - int width = skinTag.getInt("SkinImageWidth"); - int height = skinTag.getInt("SkinImageHeight"); - newSkin.setSkinData(new SerializedImage(width, height, data)); + newSkin.setSkinData(new SerializedImage(skinTag.getInt("SkinImageWidth"), skinTag.getInt("SkinImageHeight"), data)); } else { newSkin.setSkinData(data); } @@ -126,9 +130,7 @@ protected void initEntity() { if (skinTag.contains("CapeData")) { byte[] data = skinTag.getByteArray("CapeData"); if (skinTag.contains("CapeImageWidth") && skinTag.contains("CapeImageHeight")) { - int width = skinTag.getInt("CapeImageWidth"); - int height = skinTag.getInt("CapeImageHeight"); - newSkin.setCapeData(new SerializedImage(width, height, data)); + newSkin.setCapeData(new SerializedImage(skinTag.getInt("CapeImageWidth"), skinTag.getInt("CapeImageHeight"), data)); } else { newSkin.setCapeData(data); } @@ -144,7 +146,7 @@ protected void initEntity() { } if (skinTag.contains("SkinAnimationData")) { newSkin.setAnimationData(new String(skinTag.getByteArray("SkinAnimationData"), StandardCharsets.UTF_8)); - } else if (skinTag.contains("AnimationData")) { // backwards compatible + } else if (skinTag.contains("AnimationData")) { // Backwards compatible newSkin.setAnimationData(new String(skinTag.getByteArray("AnimationData"), StandardCharsets.UTF_8)); } if (skinTag.contains("PremiumSkin")) { @@ -157,15 +159,8 @@ protected void initEntity() { newSkin.setCapeOnClassic(skinTag.getBoolean("CapeOnClassicSkin")); } if (skinTag.contains("AnimatedImageData")) { - ListTag list = skinTag.getList("AnimatedImageData", CompoundTag.class); - for (CompoundTag animationTag : list.getAll()) { - float frames = animationTag.getFloat("Frames"); - int type = animationTag.getInt("Type"); - byte[] image = animationTag.getByteArray("Image"); - int width = animationTag.getInt("ImageWidth"); - int height = animationTag.getInt("ImageHeight"); - int expression = animationTag.getInt("AnimationExpression"); - newSkin.getAnimations().add(new SkinAnimation(new SerializedImage(width, height, image), type, frames, expression)); + for (CompoundTag animationTag : skinTag.getList("AnimatedImageData", CompoundTag.class).getAll()) { + newSkin.getAnimations().add(new SkinAnimation(new SerializedImage(animationTag.getInt("ImageWidth"), animationTag.getInt("ImageHeight"), animationTag.getByteArray("Image")), animationTag.getInt("Type"), animationTag.getFloat("Frames"), animationTag.getInt("AnimationExpression"))); } } if (skinTag.contains("ArmSize")) { @@ -202,7 +197,7 @@ protected void initEntity() { this.setSkin(newSkin); } - this.uuid = Utils.dataToUUID(String.valueOf(this.getId()).getBytes(StandardCharsets.UTF_8), this.getSkin() + this.uuid = Utils.dataToUUID(String.valueOf(this.getId()).getBytes(StandardCharsets.UTF_8), this.skin .getSkinData().data, this.getNameTag().getBytes(StandardCharsets.UTF_8)); } @@ -223,13 +218,13 @@ public void saveNBT() { .putByteArray("Data", this.getSkin().getSkinData().data) .putInt("SkinImageWidth", this.getSkin().getSkinData().width) .putInt("SkinImageHeight", this.getSkin().getSkinData().height) - .putString("ModelId", this.getSkin().getSkinId()) + .putString("ModelId", this.skin.getSkinId()) .putString("CapeId", this.getSkin().getCapeId()) .putByteArray("CapeData", this.getSkin().getCapeData().data) .putInt("CapeImageWidth", this.getSkin().getCapeData().width) .putInt("CapeImageHeight", this.getSkin().getCapeData().height) .putByteArray("SkinResourcePatch", this.getSkin().getSkinResourcePatch().getBytes(StandardCharsets.UTF_8)) - .putByteArray("GeometryData", this.getSkin().getGeometryData().getBytes(StandardCharsets.UTF_8)) + .putByteArray("GeometryData", this.skin.getGeometryData().getBytes(StandardCharsets.UTF_8)) .putByteArray("SkinAnimationData", this.getSkin().getAnimationData().getBytes(StandardCharsets.UTF_8)) .putBoolean("PremiumSkin", this.getSkin().isPremium()) .putBoolean("PersonaSkin", this.getSkin().isPersona()) @@ -299,13 +294,14 @@ public void spawnTo(Player player) { throw new IllegalStateException(this.getClass().getSimpleName() + " must have a valid skin set"); } - if (this instanceof Player) - this.server.updatePlayerListData(this.getUniqueId(), this.getId(), ((Player) this).getDisplayName(), this.skin, ((Player) this).getLoginChainData().getXUID(), new Player[]{player}); - else - this.server.updatePlayerListData(this.getUniqueId(), this.getId(), this.getName(), this.skin, new Player[]{player}); + if (this instanceof Player) { + this.server.updatePlayerListData(this.uuid, this.getId(), ((Player) this).getDisplayName(), this.skin, ((Player) this).getLoginChainData().getXUID(), new Player[]{player}); + } else { + this.server.updatePlayerListData(this.uuid, this.getId(), this.getName(), this.skin, new Player[]{player}); + } AddPlayerPacket pk = new AddPlayerPacket(); - pk.uuid = this.getUniqueId(); + pk.uuid = this.uuid; pk.username = this.getName(); pk.entityUniqueId = this.getId(); pk.entityRuntimeId = this.getId(); @@ -318,10 +314,20 @@ public void spawnTo(Player player) { pk.yaw = (float) this.yaw; pk.pitch = (float) this.pitch; pk.item = this.getInventory().getItemInHand(); - pk.metadata = this.dataProperties; + pk.metadata = this.dataProperties.clone(); player.dataPacket(pk); - this.inventory.sendArmorContents(player); + if (this instanceof Player) { + this.inventory.sendArmorContents(player); + } else { + Item[] armor = this.inventory.getArmorContents(); + if (armor[0].getId() != 0 || armor[1].getId() != 0 || armor[2].getId() != 0 || armor[3].getId() != 0) { + MobArmorEquipmentPacket pk2 = new MobArmorEquipmentPacket(); + pk2.eid = this.getId(); + pk2.slots = armor; + player.dataPacket(pk2); + } + } this.offhandInventory.sendContents(player); if (this.riding != null) { @@ -330,27 +336,15 @@ public void spawnTo(Player player) { pkk.riderUniqueId = this.getId(); pkk.type = 1; pkk.immediate = 1; - player.dataPacket(pkk); } if (!(this instanceof Player)) { - this.server.removePlayerListData(this.getUniqueId(), player); + this.server.removePlayerListData(this.uuid, player); } } } - @Override - public void despawnFrom(Player player) { - if (this.hasSpawned.containsKey(player.getLoaderId())) { - - RemoveEntityPacket pk = new RemoveEntityPacket(); - pk.eid = this.getId(); - player.dataPacket(pk); - this.hasSpawned.remove(player.getLoaderId()); - } - } - @Override public void close() { if (!this.closed) { @@ -364,4 +358,17 @@ public void close() { } } + @Override + protected void onBlock(Entity damager, EntityDamageBlockedEvent event, EntityDamageEvent source) { + super.onBlock(damager, event, source); + Item shieldOffhand = getOffhandInventory().getItem(0); + if (shieldOffhand.getId() == ItemID.SHIELD) { + getOffhandInventory().setItem(0, damageArmor(shieldOffhand, damager, source.getDamage(), true, null)); + } else { + Item shield = getInventory().getItemInHand(); + if (shield.getId() == ItemID.SHIELD) { + getInventory().setItemInHand(damageArmor(shield, damager, source.getDamage(), true, null)); + } + } + } } diff --git a/src/main/java/cn/nukkit/entity/EntityHumanType.java b/src/main/java/cn/nukkit/entity/EntityHumanType.java index d736eda23cc..ab67441fbf5 100644 --- a/src/main/java/cn/nukkit/entity/EntityHumanType.java +++ b/src/main/java/cn/nukkit/entity/EntityHumanType.java @@ -1,18 +1,14 @@ package cn.nukkit.entity; -import cn.nukkit.Player; -import cn.nukkit.block.Block; import cn.nukkit.block.BlockID; import cn.nukkit.event.entity.EntityDamageByEntityEvent; import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; -import cn.nukkit.event.entity.EntityDamageEvent.DamageModifier; import cn.nukkit.inventory.InventoryHolder; import cn.nukkit.inventory.PlayerEnderChestInventory; import cn.nukkit.inventory.PlayerInventory; import cn.nukkit.inventory.PlayerOffhandInventory; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemSkull; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.level.format.FullChunk; @@ -20,10 +16,10 @@ import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.ListTag; +import cn.nukkit.utils.Utils; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.ThreadLocalRandom; public abstract class EntityHumanType extends EntityCreature implements InventoryHolder { @@ -57,8 +53,8 @@ protected void initEntity() { ListTag inventoryList = this.namedTag.getList("Inventory", CompoundTag.class); for (CompoundTag item : inventoryList.getAll()) { int slot = item.getByte("Slot"); - if (slot >= 0 && slot < 9) { //hotbar - //Old hotbar saving stuff, remove it (useless now) + if (slot >= 0 && slot < 9) { + // Old hotbar saving stuff, remove it (useless now) inventoryList.remove(item); } else if (slot >= 100 && slot < 104) { this.inventory.setItem(this.inventory.getSize() + slot - 100, NBTIO.getItemHelper(item)); @@ -101,7 +97,7 @@ public void saveNBT() { ); } - int slotCount = Player.SURVIVAL_SLOTS + 9; + int slotCount = 45; // SURVIVAL_SLOTS + 9 for (int slot = 9; slot < slotCount; ++slot) { Item item = this.inventory.getItem(slot - 9); inventoryTag.add(NBTIO.putItemHelper(item, slot)); @@ -149,50 +145,39 @@ public Item[] getDrops() { @Override public boolean attack(EntityDamageEvent source) { - if (this.isClosed() || !this.isAlive()) { + if (closed || !this.isAlive()) { return false; } - if (source.getCause() != DamageCause.VOID && source.getCause() != DamageCause.CUSTOM && source.getCause() != DamageCause.MAGIC && source.getCause() != DamageCause.HUNGER) { + if (source.getCause() != DamageCause.VOID && source.getCause() != DamageCause.CUSTOM && source.getCause() != DamageCause.HUNGER) { int armorPoints = 0; int epf = 0; - //int toughness = 0; for (Item armor : inventory.getArmorContents()) { armorPoints += armor.getArmorPoints(); epf += calculateEnchantmentProtectionFactor(armor, source); - //toughness += armor.getToughness(); } + //float originalDamage = source.getDamage(); + //float r = (source.getDamage(EntityDamageEvent.DamageModifier.ARMOR) - (originalDamage - originalDamage * (1 - Math.max(armorPoints / 5, armorPoints - originalDamage / 2) / 25))); + //originalDamage += r; + //epf = Math.min(20, epf); + //source.setDamage(r, EntityDamageEvent.DamageModifier.ARMOR); + //source.setDamage(source.getDamage(EntityDamageEvent.DamageModifier.ARMOR_ENCHANTMENTS) - (originalDamage - originalDamage * (1 - epf / 25f)), EntityDamageEvent.DamageModifier.ARMOR_ENCHANTMENTS); + if (source.canBeReducedByArmor()) { - source.setDamage(-source.getFinalDamage() * armorPoints * 0.04f, DamageModifier.ARMOR); + source.setDamage(-source.getFinalDamage() * armorPoints * 0.04f, EntityDamageEvent.DamageModifier.ARMOR); } - source.setDamage(-source.getFinalDamage() * Math.min(NukkitMath.ceilFloat(Math.min(epf, 25) * ((float) ThreadLocalRandom.current().nextInt(50, 100) / 100)), 20) * 0.04f, - DamageModifier.ARMOR_ENCHANTMENTS); - } - - source.setDamage(-Math.min(this.getAbsorption(), source.getFinalDamage()), DamageModifier.ABSORPTION); + source.setDamage(-source.getFinalDamage() * Math.min(NukkitMath.ceilFloat(Math.min(epf, 25) * ((float) Utils.random.nextInt(50, 100) / 100)), 20) * 0.04f, + EntityDamageEvent.DamageModifier.ARMOR_ENCHANTMENTS); - if (super.attack(source)) { - Entity damager = null; - - if (source instanceof EntityDamageByEntityEvent) { - damager = ((EntityDamageByEntityEvent) source).getDamager(); - } + //source.setDamage(-Math.min(this.getAbsorption(), source.getFinalDamage()), EntityDamageEvent.DamageModifier.ABSORPTION); - for (int slot = 0; slot < 4; slot++) { - Item armor = this.inventory.getArmorItem(slot); - - if (damager != null) { - for (Enchantment enchantment : armor.getEnchantments()) { - enchantment.doPostAttack(damager, this); - } - } - - Enchantment durability = armor.getEnchantment(Enchantment.ID_DURABILITY); - if (durability != null && durability.getLevel() > 0 && (100 / (durability.getLevel() + 1)) <= ThreadLocalRandom.current().nextInt(100)) { - continue; + if (super.attack(source)) { + Entity damager = null; + if (source instanceof EntityDamageByEntityEvent) { + damager = ((EntityDamageByEntityEvent) source).getDamager(); } if (source.getCause() != DamageCause.VOID && @@ -204,34 +189,67 @@ public boolean attack(EntityDamageEvent source) { source.getCause() != DamageCause.FIRE_TICK && source.getCause() != DamageCause.FALL) { // No armor damage - if (armor.isUnbreakable() || armor instanceof ItemSkull) { - continue; + for (int slot = 0; slot < 4; slot++) { + Item armor = damageArmor(this.inventory.getArmorItem(slot), damager, source.getDamage(), false, source.getCause()); + inventory.setArmorItem(slot, armor, armor.getId() != BlockID.AIR); } - - armor.setDamage(armor.getDamage() + 1); - - if (armor.getDamage() >= armor.getMaxDurability()) { - inventory.setArmorItem(slot, new ItemBlock(Block.get(BlockID.AIR))); - } else { - inventory.setArmorItem(slot, armor, true); + } else if (damager != null && source.getCause() != DamageCause.THORNS) { // Do post attack only + for (int slot = 0; slot < 4; slot++) { + Item armor = this.inventory.getArmorItem(slot); + for (Enchantment enchantment : armor.getEnchantments()) { + enchantment.doPostAttack(damager, this); + } } } + return true; + } else { + return false; + } + } else { + return super.attack(source); + } + } + + protected Item damageArmor(Item armor, Entity damager, float damage, boolean shield, DamageCause cause) { + if (armor.isUnbreakable() || armor instanceof ItemSkull || armor.getId() == (255 - BlockID.CARVED_PUMPKIN)) { + return armor; + } + + if (damager != null && cause != DamageCause.THORNS) { + for (Enchantment enchantment : armor.getEnchantments()) { + enchantment.doPostAttack(damager, this); } + } + + Enchantment durability = armor.getEnchantment(Enchantment.ID_DURABILITY); + if (durability != null + && durability.getLevel() > 0 + && (100 / (durability.getLevel() + 1)) <= Utils.random.nextInt(100)) { + return armor; + } - return true; + if (shield) { + armor.setDamage(armor.getDamage() + (damage >= 4.0f ? ((int) damage) : 1)); } else { - return false; + armor.setDamage(armor.getDamage() + Math.max((int) (damage / 4), 1)); + } + + if (armor.getDamage() >= armor.getMaxDurability()) { + return Item.get(BlockID.AIR, 0, 0); } + + return armor; } + protected double calculateEnchantmentProtectionFactor(Item item, EntityDamageEvent source) { - double epf = 0; + double epf = 0; for (Enchantment ench : item.getEnchantments()) { - epf += ench.getProtectionFactor(source); + epf += ench.getProtectionFactor(source); } - return epf; + return epf ; } @Override @@ -250,9 +268,4 @@ public void setOnFire(int seconds) { super.setOnFire(seconds); } - - @Override - protected boolean applyNameTag(Player player, Item item) { - return false; - } } diff --git a/src/main/java/cn/nukkit/entity/EntityInteractable.java b/src/main/java/cn/nukkit/entity/EntityInteractable.java index aceb5f8f131..ec6cacfbc3b 100644 --- a/src/main/java/cn/nukkit/entity/EntityInteractable.java +++ b/src/main/java/cn/nukkit/entity/EntityInteractable.java @@ -9,11 +9,9 @@ public interface EntityInteractable { String getInteractButtonText(); - //TODO: Mob entity stuff (e.g. feed) default String getInteractButtonText(Player player) { return this.getInteractButtonText(); } boolean canDoInteraction(); - } diff --git a/src/main/java/cn/nukkit/entity/EntityJumping.java b/src/main/java/cn/nukkit/entity/EntityJumping.java new file mode 100644 index 00000000000..117c9847d11 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/EntityJumping.java @@ -0,0 +1,11 @@ +package cn.nukkit.entity; + +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; + +public abstract class EntityJumping extends BaseEntity { + + public EntityJumping(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } +} diff --git a/src/main/java/cn/nukkit/entity/EntityLiving.java b/src/main/java/cn/nukkit/entity/EntityLiving.java index 12d0d9d6e55..8cd225563de 100644 --- a/src/main/java/cn/nukkit/entity/EntityLiving.java +++ b/src/main/java/cn/nukkit/entity/EntityLiving.java @@ -3,15 +3,18 @@ import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.block.Block; +import cn.nukkit.block.BlockCactus; import cn.nukkit.block.BlockMagma; -import cn.nukkit.entity.data.ShortEntityData; -import cn.nukkit.entity.passive.EntityWaterAnimal; -import cn.nukkit.event.entity.EntityDamageByChildEntityEvent; -import cn.nukkit.event.entity.EntityDamageByEntityEvent; -import cn.nukkit.event.entity.EntityDamageEvent; +import cn.nukkit.entity.mob.*; +import cn.nukkit.entity.passive.EntityIronGolem; +import cn.nukkit.entity.passive.EntitySkeletonHorse; +import cn.nukkit.entity.projectile.EntityProjectile; +import cn.nukkit.entity.weather.EntityWeather; +import cn.nukkit.event.entity.*; import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; -import cn.nukkit.event.entity.EntityDeathEvent; +import cn.nukkit.inventory.PlayerInventory; import cn.nukkit.item.Item; +import cn.nukkit.item.ItemArmor; import cn.nukkit.item.ItemTurtleShell; import cn.nukkit.level.GameRule; import cn.nukkit.level.format.FullChunk; @@ -19,12 +22,10 @@ import cn.nukkit.math.Vector3; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.FloatTag; -import cn.nukkit.network.protocol.AnimatePacket; import cn.nukkit.network.protocol.EntityEventPacket; import cn.nukkit.network.protocol.LevelSoundEventPacket; import cn.nukkit.potion.Effect; import cn.nukkit.utils.BlockIterator; -import co.aikar.timings.Timings; import java.util.ArrayList; import java.util.Arrays; @@ -32,7 +33,7 @@ import java.util.Map; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class EntityLiving extends Entity implements EntityDamageable { @@ -51,13 +52,13 @@ protected float getDrag() { return 0.02f; } - protected int attackTime = 0; - - protected boolean invisible = false; - + protected int attackTime; + protected int knockBackTime; + private float currentDamage; protected float movementSpeed = 0.1f; - - protected int turtleTicks = 0; + protected int turtleTicks; + private boolean blocking; + private boolean spinAttack; @Override protected void initEntity() { @@ -90,15 +91,15 @@ public void setHealth(float health) { @Override public void saveNBT() { super.saveNBT(); + this.namedTag.putFloat("Health", this.getHealth()); } public boolean hasLineOfSight(Entity entity) { - //todo return true; } - public void collidingWith(Entity ent) { // can override (IronGolem|Bats) + public void collidingWith(Entity ent) { ent.applyEntityCollision(this); } @@ -106,34 +107,35 @@ public void collidingWith(Entity ent) { // can override (IronGolem|Bats) public boolean attack(EntityDamageEvent source) { if (this.noDamageTicks > 0) { return false; - } else if (this.attackTime > 0) { - EntityDamageEvent lastCause = this.getLastDamageCause(); - if (lastCause != null && lastCause.getDamage() >= source.getDamage()) { + } + + float unmodifiedBaseDamage = source.getDamage(); + + if (this.attackTime > 0) { + if (unmodifiedBaseDamage > this.currentDamage) { + source.setDamage(Math.max(0, unmodifiedBaseDamage - this.currentDamage)); // https://minecraft.fandom.com/wiki/Damage#Immunity + } else { return false; } } - if (super.attack(source)) { + if (this.blockedByShield(source)) { + if (unmodifiedBaseDamage > this.currentDamage) { + this.currentDamage = unmodifiedBaseDamage; + } + return false; + } + + boolean attacked = super.attack(source); + if (attacked) { if (source instanceof EntityDamageByEntityEvent) { Entity damager = ((EntityDamageByEntityEvent) source).getDamager(); if (source instanceof EntityDamageByChildEntityEvent) { damager = ((EntityDamageByChildEntityEvent) source).getChild(); } - //Critical hit - if (damager instanceof Player && !damager.onGround) { - AnimatePacket animate = new AnimatePacket(); - animate.action = AnimatePacket.Action.CRITICAL_HIT; - animate.eid = getId(); - - this.getLevel().addChunkPacket(damager.getChunkX(), damager.getChunkZ(), animate); - this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_ATTACK_STRONG); - - source.setDamage(source.getDamage() * 1.5f); - } - if (damager.isOnFire() && !(damager instanceof Player)) { - this.setOnFire(2 * this.server.getDifficulty()); + this.setOnFire(this.server.getDifficulty() << 1); } double deltaX = this.x - damager.x; @@ -143,19 +145,71 @@ public boolean attack(EntityDamageEvent source) { EntityEventPacket pk = new EntityEventPacket(); pk.eid = this.getId(); - pk.event = this.getHealth() <= 0 ? EntityEventPacket.DEATH_ANIMATION : EntityEventPacket.HURT_ANIMATION; + pk.event = this.getHealth() < 1 ? EntityEventPacket.DEATH_ANIMATION : EntityEventPacket.HURT_ANIMATION; Server.broadcastPacket(this.hasSpawned.values(), pk); + } - this.attackTime = source.getAttackCooldown(); + if (!source.isCancelled()) { // attacked == false can also mean a totem was used + this.updateAttackTime(source); + if (unmodifiedBaseDamage > this.currentDamage) { + this.currentDamage = unmodifiedBaseDamage; + } + this.scheduleUpdate(); + } + + return attacked; + } + + protected boolean blockedByShield(EntityDamageEvent source) { + if (!this.isBlocking()) { + return false; + } + + Entity damager = source instanceof EntityDamageByChildEntityEvent ? ((EntityDamageByChildEntityEvent) source).getChild() : source instanceof EntityDamageByEntityEvent ? ((EntityDamageByEntityEvent) source).getDamager() : null; + if (damager == null || damager instanceof EntityWeather) { + return false; + } + + Vector3 entityPos = damager.getPosition(); + Vector3 direction = this.getDirectionVector(); + Vector3 normalizedVector = this.getPosition().subtract(entityPos).normalize(); + boolean blocked = (normalizedVector.x * direction.x) + (normalizedVector.z * direction.z) < 0.0; + boolean knockBack = !(damager instanceof EntityProjectile); + EntityDamageBlockedEvent event = new EntityDamageBlockedEvent(this, source, knockBack, true); + if (!blocked || !source.canBeReducedByArmor() || damager instanceof EntityProjectile && ((EntityProjectile) damager).piercing > 0) { + event.setCancelled(); + } - return true; - } else { + getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { return false; } + + if (event.getKnockBackAttacker() && damager instanceof EntityLiving) { + double deltaX = damager.getX() - this.getX(); + double deltaZ = damager.getZ() - this.getZ(); + this.updateAttackTime(source); + ((EntityLiving) damager).knockBack(this, 0, deltaX, deltaZ, 0.25); + } + + this.onBlock(damager, event, source); + return true; + } + + private void updateAttackTime(EntityDamageEvent source) { + if (this.attackTime < 1) { // Does not reset the immunity period + this.attackTime = source.getAttackCooldown(); + } + } + + protected void onBlock(Entity damager, EntityDamageBlockedEvent event, EntityDamageEvent source) { + if (event.getAnimation()) { + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_ITEM_SHIELD_BLOCK); + } } public void knockBack(Entity attacker, double damage, double x, double z) { - this.knockBack(attacker, damage, x, z, 0.4); + this.knockBack(attacker, damage, x, z, 0.3); } public void knockBack(Entity attacker, double damage, double x, double z, double base) { @@ -164,6 +218,18 @@ public void knockBack(Entity attacker, double damage, double x, double z, double return; } + if (this instanceof Player) { + int netheritePieces = 0; + for (Item armor : ((Player) this).getInventory().getArmorContents()) { + if (armor.getTier() == ItemArmor.TIER_NETHERITE) { + netheritePieces++; + } + } + if (netheritePieces > 0) { + base *= 1 - 0.1 * netheritePieces; + } + } + f = 1 / f; Vector3 motion = new Vector3(this.motionX, this.motionY, this.motionZ); @@ -179,7 +245,11 @@ public void knockBack(Entity attacker, double damage, double x, double z, double motion.y = base; } + this.resetFallDistance(); + this.setMotion(motion); + + this.knockBackTime = 10; } @Override @@ -191,107 +261,149 @@ public void kill() { EntityDeathEvent ev = new EntityDeathEvent(this, this.getDrops()); this.server.getPluginManager().callEvent(ev); - if (this.level.getGameRules().getBoolean(GameRule.DO_ENTITY_DROPS)) { - for (cn.nukkit.item.Item item : ev.getDrops()) { - this.getLevel().dropItem(this, item); + // Monster Hunter Achievement + int id = ev.getEntity().getNetworkId(); + if (id == EntityEnderman.NETWORK_ID || id == EntityZombiePigman.NETWORK_ID || id == EntitySpider.NETWORK_ID || id == EntityCaveSpider.NETWORK_ID) { + if (ev.getEntity().getLastDamageCause() instanceof EntityDamageByEntityEvent) { + Entity damager = ((EntityDamageByEntityEvent) ev.getEntity().getLastDamageCause()).getDamager(); + if (damager instanceof Player) { + ((Player) damager).awardAchievement("killEnemy"); + } } } - } - @Override - public boolean entityBaseTick() { - return this.entityBaseTick(1); + if (this.level.getGameRules().getBoolean(GameRule.DO_MOB_LOOT) && this.lastDamageCause != null && DamageCause.VOID != this.lastDamageCause.getCause()) { + if (ev.getEntity() instanceof BaseEntity) { + BaseEntity baseEntity = (BaseEntity) ev.getEntity(); + if (baseEntity.getLastDamageCause() instanceof EntityDamageByEntityEvent) { + Entity damager = ((EntityDamageByEntityEvent) baseEntity.getLastDamageCause()).getDamager(); + if (damager instanceof Player) { + this.getLevel().dropExpOrb(this, baseEntity.getKillExperience()); + + if (!this.dropsOnNaturalDeath()) { + for (cn.nukkit.item.Item item : ev.getDrops()) { + this.getLevel().dropItem(this, item); + } + } + } + } + } + + if (this.dropsOnNaturalDeath()) { + for (cn.nukkit.item.Item item : ev.getDrops()) { + this.getLevel().dropItem(this, item); + } + } + } } @Override public boolean entityBaseTick(int tickDiff) { - Timings.livingEntityBaseTickTimer.startTiming(); - boolean isBreathing = !this.isInsideOfWater(); + boolean inWater = this.isSubmerged(); - if (this instanceof Player) { - if (isBreathing && ((Player) this).getInventory().getHelmet() instanceof ItemTurtleShell) { + if (this instanceof Player && !this.closed) { + Player p = (Player) this; + boolean isBreathing = !inWater; + + PlayerInventory inv = p.getInventory(); + if (isBreathing && inv != null && inv.getHelmetFast() instanceof ItemTurtleShell) { turtleTicks = 200; } else if (turtleTicks > 0) { isBreathing = true; turtleTicks--; } - if ((((Player) this).isCreative() || ((Player) this).isSpectator())) { + if (p.isCreative() || p.isSpectator()) { isBreathing = true; } + + this.setDataFlagSelfOnly(DATA_FLAGS, DATA_FLAG_BREATHING, isBreathing); } - - this.setDataFlag(DATA_FLAGS, DATA_FLAG_BREATHING, isBreathing); boolean hasUpdate = super.entityBaseTick(tickDiff); if (this.isAlive()) { - if (this.isInsideOfSolid()) { hasUpdate = true; this.attack(new EntityDamageEvent(this, DamageCause.SUFFOCATION, 1)); } - if (this.isOnLadder() || this.hasEffect(Effect.LEVITATION) || this.hasEffect(Effect.SLOW_FALLING)) { + if (this.hasEffect(Effect.LEVITATION) || this.hasEffect(Effect.SLOW_FALLING)) { this.resetFallDistance(); } - if (!this.hasEffect(Effect.WATER_BREATHING) && this.isInsideOfWater()) { - if (this instanceof EntityWaterAnimal || (this instanceof Player && (((Player) this).isCreative() || ((Player) this).isSpectator()))) { + if (inWater && !this.hasEffect(Effect.WATER_BREATHING)) { + if (this instanceof EntitySwimming || this instanceof EntityDrowned || this instanceof EntitySkeletonHorse || this instanceof EntityIronGolem || + (this instanceof Player && (((Player) this).isCreative() || ((Player) this).isSpectator()))) { this.setAirTicks(400); } else { - if (turtleTicks == 0 || turtleTicks == 200) { + if (turtleTicks == 0) { hasUpdate = true; int airTicks = this.getAirTicks() - tickDiff; if (airTicks <= -20) { airTicks = 0; - this.attack(new EntityDamageEvent(this, DamageCause.DROWNING, 2)); + if (!(this instanceof Player) || level.getGameRules().getBoolean(GameRule.DROWNING_DAMAGE)) { + this.attack(new EntityDamageEvent(this, DamageCause.DROWNING, 2)); + } } - setAirTicks(airTicks); + this.setAirTicks(airTicks); } } } else { - if (this instanceof EntityWaterAnimal) { + if (this instanceof EntitySwimming) { hasUpdate = true; - int airTicks = getAirTicks() - tickDiff; + int airTicks = this.getAirTicks() - tickDiff; if (airTicks <= -20) { airTicks = 0; this.attack(new EntityDamageEvent(this, DamageCause.SUFFOCATION, 2)); } - setAirTicks(airTicks); + this.setAirTicks(airTicks); } else { int airTicks = getAirTicks(); - if (airTicks < 400) { setAirTicks(Math.min(400, airTicks + tickDiff * 5)); } } } - } - if (this.attackTime > 0) { - this.attackTime -= tickDiff; - } + // Check collisions with blocks + if ((this instanceof Player || this instanceof BaseEntity) && this.riding == null && this.age % (this instanceof Player ? 2 : 10) == 0) { + int floorY = NukkitMath.floorDouble(this.y - 0.25); + if (floorY != getFloorY()) { + Block block = this.level.getBlock(this.chunk, getFloorX(), floorY, getFloorZ(), false); + if (block instanceof BlockCactus) { + block.onEntityCollide(this); + } else if (block instanceof BlockMagma) { + block.onEntityCollide(this); + } + } + } - if (this.riding == null) { - for (Entity entity : level.getNearbyEntities(this.boundingBox.grow(0.20000000298023224, 0.0D, 0.20000000298023224), this)) { - if (entity instanceof EntityRideable) { - this.collidingWith(entity); + if (this.attackTime > 0) { + this.attackTime -= tickDiff; + if (this.attackTime < 1) { + this.currentDamage = 0; } + hasUpdate = true; } - } - // Check collision with magma blocks because Nukkit doesn't do collisions to full blocks below - if (this.isPlayer || this.age % 2 == 0) { - Block block = this.level.getBlock(getFloorX(), NukkitMath.floorDouble(this.y + 0.53) - 1, getFloorZ()); - if (block instanceof BlockMagma) block.onEntityCollide(this); - } + if (this.knockBackTime > 0) { + this.knockBackTime -= tickDiff; + } - Timings.livingEntityBaseTickTimer.stopTiming(); + if (this.riding == null && this.age % 2 == 1 && !this.closed && this.isAlive()) { + Entity[] e = level.getNearbyEntities(this.boundingBox.grow(0.20000000298023224, 0.0D, 0.20000000298023224), this); + for (Entity entity : e) { + if (entity instanceof EntityRideable && !entity.closed && entity.isAlive()) { + this.collidingWith(entity); + } + } + } + } return hasUpdate; } @@ -372,9 +484,7 @@ public Block getTargetBlock(int maxDistance, Integer[] transparent) { return block; } } - } catch (Exception ignored) { - - } + } catch (Exception ignored) {} return null; } @@ -386,12 +496,38 @@ public void setMovementSpeed(float speed) { public float getMovementSpeed() { return this.movementSpeed; } - + public int getAirTicks() { - return this.getDataPropertyShort(DATA_AIR); + return this.airTicks; } public void setAirTicks(int ticks) { - this.setDataProperty(new ShortEntityData(DATA_AIR, ticks)); + this.airTicks = ticks; + } + + public boolean isBlocking() { + return this.blocking; + } + + public void setBlocking(boolean value) { + if (this.blocking != value) { + this.blocking = value; + this.setDataFlag(DATA_FLAGS_EXTENDED, DATA_FLAG_BLOCKING, value); + } + } + + public boolean dropsOnNaturalDeath() { + return true; + } + + public boolean isSpinAttack() { + return this.spinAttack; + } + + public void setSpinAttack(boolean value) { + if (this.spinAttack != value) { + this.spinAttack = value; + this.setDataFlag(DATA_FLAGS, DATA_FLAG_SPIN_ATTACK, value); + } } } diff --git a/src/main/java/cn/nukkit/entity/EntityOwnable.java b/src/main/java/cn/nukkit/entity/EntityOwnable.java index 31086b6b8b5..1408c976c3a 100644 --- a/src/main/java/cn/nukkit/entity/EntityOwnable.java +++ b/src/main/java/cn/nukkit/entity/EntityOwnable.java @@ -3,10 +3,11 @@ import cn.nukkit.Player; /** - * Author: BeYkeRYkt + * @author BeYkeRYkt * Nukkit Project */ public interface EntityOwnable { + String getOwnerName(); void setOwnerName(String playerName); diff --git a/src/main/java/cn/nukkit/entity/EntityRideable.java b/src/main/java/cn/nukkit/entity/EntityRideable.java index 9b5c42603bf..8375f0bc0a1 100644 --- a/src/main/java/cn/nukkit/entity/EntityRideable.java +++ b/src/main/java/cn/nukkit/entity/EntityRideable.java @@ -1,7 +1,7 @@ package cn.nukkit.entity; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface EntityRideable { diff --git a/src/main/java/cn/nukkit/entity/EntitySmite.java b/src/main/java/cn/nukkit/entity/EntitySmite.java index 90e33128ce0..e97c622ef5a 100644 --- a/src/main/java/cn/nukkit/entity/EntitySmite.java +++ b/src/main/java/cn/nukkit/entity/EntitySmite.java @@ -1,7 +1,7 @@ package cn.nukkit.entity; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface EntitySmite { diff --git a/src/main/java/cn/nukkit/entity/EntitySwimming.java b/src/main/java/cn/nukkit/entity/EntitySwimming.java new file mode 100644 index 00000000000..aad34c46d69 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/EntitySwimming.java @@ -0,0 +1,11 @@ +package cn.nukkit.entity; + +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; + +public abstract class EntitySwimming extends BaseEntity { + + public EntitySwimming(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } +} diff --git a/src/main/java/cn/nukkit/entity/EntityTameable.java b/src/main/java/cn/nukkit/entity/EntityTameable.java new file mode 100644 index 00000000000..0475c21b933 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/EntityTameable.java @@ -0,0 +1,28 @@ +package cn.nukkit.entity; + +import cn.nukkit.Player; + +public interface EntityTameable { + + String NAMED_TAG_OWNER_UUID = "OwnerUUID"; + + String NAMED_TAG_SITTING = "Sitting"; + + Player getOwner(); + + boolean hasOwner(); + + void setOwner(Player player); + + String getOwnerUUID(); + + void setOwnerUUID(String uuid); + + boolean isSitting(); + + void setSitting(boolean sitting); + + default boolean isOwner(Entity entity) { + return entity instanceof Player && ((Player) entity).getUniqueId().toString().equals(this.getOwnerUUID()); + } +} diff --git a/src/main/java/cn/nukkit/entity/EntityWalking.java b/src/main/java/cn/nukkit/entity/EntityWalking.java new file mode 100644 index 00000000000..d7c3252307b --- /dev/null +++ b/src/main/java/cn/nukkit/entity/EntityWalking.java @@ -0,0 +1,11 @@ +package cn.nukkit.entity; + +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; + +public abstract class EntityWalking extends BaseEntity { + + public EntityWalking(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } +} diff --git a/src/main/java/cn/nukkit/entity/custom/CustomEntity.java b/src/main/java/cn/nukkit/entity/custom/CustomEntity.java new file mode 100644 index 00000000000..509d12161be --- /dev/null +++ b/src/main/java/cn/nukkit/entity/custom/CustomEntity.java @@ -0,0 +1,14 @@ +package cn.nukkit.entity.custom; + +public interface CustomEntity { + + EntityDefinition getEntityDefinition(); + + default String getIdentifier() { + return this.getEntityDefinition().getIdentifier(); + } + + default int getNetworkId() { + return this.getEntityDefinition().getRuntimeId(); + } +} diff --git a/src/main/java/cn/nukkit/entity/custom/EntityDefinition.java b/src/main/java/cn/nukkit/entity/custom/EntityDefinition.java new file mode 100644 index 00000000000..d6bdefeb4f8 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/custom/EntityDefinition.java @@ -0,0 +1,71 @@ +package cn.nukkit.entity.custom; + +import cn.nukkit.entity.Entity; +import cn.nukkit.nbt.tag.CompoundTag; +import lombok.Builder; +import lombok.Getter; + +import java.util.concurrent.atomic.AtomicInteger; + +@Getter +public class EntityDefinition { + + public static final AtomicInteger ID_ALLOCATOR = new AtomicInteger(10000); + + private final String identifier; + private final String parentEntity; + private final boolean spawnEgg; + + private final String alternateName; + private final Class implementation; + + private final boolean serverSideOnly; + private final int runtimeId; + + private CompoundTag networkTag; + + @Builder + public EntityDefinition(String identifier, String parentEntity, boolean spawnEgg, String alternateName, Class implementation, boolean serverSideOnly) { + if (!CustomEntity.class.isAssignableFrom(implementation)) { + throw new IllegalArgumentException("Implementation class must implement CustomEntity interface"); + } + + if (serverSideOnly && parentEntity == null) { + throw new IllegalArgumentException("Server side entity must have parent entity set"); + } + + this.identifier = identifier; + this.parentEntity = parentEntity; + this.spawnEgg = spawnEgg; + this.alternateName = alternateName; + this.implementation = implementation; + this.serverSideOnly = serverSideOnly; + + if (this.serverSideOnly) { + int runtimeId = EntityManager.get().getRuntimeId(this.parentEntity); + if (runtimeId == 0) { + throw new IllegalArgumentException("Unknown entity type " + this.parentEntity); + } + this.runtimeId = runtimeId; + } else { + this.runtimeId = ID_ALLOCATOR.getAndIncrement(); + } + } + + private CompoundTag createNetworkTag() { + CompoundTag nbt = new CompoundTag(""); + nbt.putBoolean("hasspawnegg", this.spawnEgg); + nbt.putBoolean("summonable", true); + nbt.putString("id", this.identifier); + nbt.putString("bid", this.parentEntity == null ? "" : this.parentEntity); + nbt.putInt("rid", this.runtimeId); + return nbt; + } + + public CompoundTag getNetworkTag() { + if (this.networkTag == null) { + this.networkTag = this.createNetworkTag(); + } + return this.networkTag; + } +} diff --git a/src/main/java/cn/nukkit/entity/custom/EntityManager.java b/src/main/java/cn/nukkit/entity/custom/EntityManager.java new file mode 100644 index 00000000000..c41e2d35554 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/custom/EntityManager.java @@ -0,0 +1,145 @@ +package cn.nukkit.entity.custom; + +import cn.nukkit.Nukkit; +import cn.nukkit.nbt.NBTIO; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.ListTag; +import cn.nukkit.network.protocol.AddEntityPacket; +import cn.nukkit.network.protocol.AvailableEntityIdentifiersPacket; +import cn.nukkit.network.protocol.BatchPacket; +import com.google.common.io.ByteStreams; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.zip.Deflater; + +/** + * Handles custom entity registry. + *

+ * See CustomEntityExample for example usage + */ +public class EntityManager { + + private static final EntityManager INSTANCE = new EntityManager(); + + /** + * Get EntityManager instance + */ + public static EntityManager get() { + return INSTANCE; + } + + private final Map entityDefinitions = new HashMap<>(); + private final Map alternateNameDefinitions = new HashMap<>(); + private final Int2ObjectMap runtimeDefinitions = new Int2ObjectOpenHashMap<>(); + + private final byte[] vanillaTag; + private final Map vanillaEntitiesMap = new HashMap<>(); + + private volatile boolean closed; + + private BatchPacket cachedPacket; + + private EntityManager() { + try { + InputStream inputStream = Nukkit.class.getClassLoader().getResourceAsStream("entity_identifiers.dat"); + if (inputStream == null) throw new AssertionError("Could not find entity_identifiers.dat"); + this.vanillaTag = ByteStreams.toByteArray(inputStream); + } catch (Exception e) { + throw new AssertionError("Error whilst loading entity_identifiers.dat", e); + } + + AddEntityPacket.LEGACY_IDS.forEach((id, identifier) -> this.vanillaEntitiesMap.put(identifier, id)); + } + + public BatchPacket getCachedPacket() { + if (this.cachedPacket == null) { + AvailableEntityIdentifiersPacket pk = new AvailableEntityIdentifiersPacket(); + pk.tryEncode(); + this.cachedPacket = pk.compress(Deflater.BEST_COMPRESSION); + } + return this.cachedPacket; + } + + @SuppressWarnings("unused") + public void registerDefinition(EntityDefinition definition) { + if (this.closed) { + throw new IllegalStateException("Entity registry was already closed"); + } + + if (this.entityDefinitions.containsKey(definition.getIdentifier())) { + throw new IllegalArgumentException("Custom entity " + definition.getIdentifier() + " was already registered"); + } + + this.entityDefinitions.put(definition.getIdentifier(), definition); + this.runtimeDefinitions.put(definition.getRuntimeId(), definition); + + if (definition.getAlternateName() != null) { + this.alternateNameDefinitions.put(definition.getAlternateName(), definition); + } + + this.cachedPacket = null; + } + + public EntityDefinition getDefinition(String identifier) { + EntityDefinition definition = this.entityDefinitions.get(identifier); + if (definition == null) { + definition = this.alternateNameDefinitions.get(identifier); + } + return definition; + } + + public EntityDefinition getDefinition(int runtimeId) { + return this.runtimeDefinitions.get(runtimeId); + } + + public int getRuntimeId(String identifier) { + EntityDefinition definition = this.entityDefinitions.get(identifier); + if (definition == null) { + return this.vanillaEntitiesMap.getOrDefault(identifier, 0); + } + return definition.getRuntimeId(); + } + + public byte[] createNetworkTag() { + try { + CompoundTag networkTag = (CompoundTag) NBTIO.readNetwork(new ByteArrayInputStream(this.vanillaTag)); + ListTag identifiers = networkTag.getList("idlist", CompoundTag.class); + + for (EntityDefinition definition : this.entityDefinitions.values()) { + if (!definition.isServerSideOnly()) { + identifiers.add(definition.getNetworkTag()); + } + } + + networkTag.putList(identifiers); + + return NBTIO.writeNetwork(networkTag); + } catch (IOException e) { + throw new RuntimeException("Unable to init entityIdentifiers", e); + } + } + + @SuppressWarnings("unused") + public boolean hasCustomEntities() { + return !this.entityDefinitions.isEmpty(); + } + + /** + * Internal: close registry to prepare for data generation + */ + public void closeRegistry() { + if (this.closed) { + throw new IllegalStateException("Entity registry was already closed"); + } + + this.closed = true; + + this.getCachedPacket(); + } +} diff --git a/src/main/java/cn/nukkit/entity/data/ByteEntityData.java b/src/main/java/cn/nukkit/entity/data/ByteEntityData.java index 75ca4425762..79f03d2062e 100644 --- a/src/main/java/cn/nukkit/entity/data/ByteEntityData.java +++ b/src/main/java/cn/nukkit/entity/data/ByteEntityData.java @@ -3,10 +3,11 @@ import cn.nukkit.entity.Entity; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ByteEntityData extends EntityData { + public int data; public ByteEntityData(int id, int data) { diff --git a/src/main/java/cn/nukkit/entity/data/EntityData.java b/src/main/java/cn/nukkit/entity/data/EntityData.java index cd308b024a2..37552b1ee27 100644 --- a/src/main/java/cn/nukkit/entity/data/EntityData.java +++ b/src/main/java/cn/nukkit/entity/data/EntityData.java @@ -3,10 +3,11 @@ import java.util.Objects; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class EntityData { + private int id; protected EntityData(int id) { @@ -30,6 +31,6 @@ public EntityData setId(int id) { @Override public boolean equals(Object obj) { - return obj instanceof EntityData && ((EntityData) obj).getId() == this.getId() && Objects.equals(((EntityData) obj).getData(), this.getData()); + return obj instanceof EntityData && ((EntityData) obj).id == this.id && Objects.equals(((EntityData) obj).getData(), this.getData()); } } diff --git a/src/main/java/cn/nukkit/entity/data/EntityMetadata.java b/src/main/java/cn/nukkit/entity/data/EntityMetadata.java index bd9351475ba..bea49e0e10f 100644 --- a/src/main/java/cn/nukkit/entity/data/EntityMetadata.java +++ b/src/main/java/cn/nukkit/entity/data/EntityMetadata.java @@ -4,19 +4,27 @@ import cn.nukkit.math.Vector3; import cn.nukkit.math.Vector3f; import cn.nukkit.nbt.tag.CompoundTag; -import lombok.extern.log4j.Log4j2; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import java.util.HashMap; import java.util.Map; +import java.util.TreeMap; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ -@Log4j2 public class EntityMetadata { - private final Map map = new HashMap<>(); + private final Int2ObjectMap map; + + public EntityMetadata() { + this.map = new Int2ObjectOpenHashMap<>(); + } + + private EntityMetadata(Int2ObjectMap map) { + this.map = map; + } public EntityData get(int id) { return this.getOrDefault(id, null); @@ -39,7 +47,6 @@ public boolean exists(int id) { public EntityMetadata put(EntityData data) { this.map.put(data.getId(), data); - //log.info("Updated entity data {}", this::toString); return this; } @@ -121,11 +128,10 @@ public EntityMetadata putString(int id, String value) { } public Map getMap() { - return new HashMap<>(map); + return new TreeMap<>(this.map); // Ordered } - @Override - public String toString() { - return map.toString(); + public EntityMetadata clone() { + return new EntityMetadata(new Int2ObjectOpenHashMap<>(this.map)); } } diff --git a/src/main/java/cn/nukkit/entity/data/FloatEntityData.java b/src/main/java/cn/nukkit/entity/data/FloatEntityData.java index 86ede31bca7..9f8bb3955c0 100644 --- a/src/main/java/cn/nukkit/entity/data/FloatEntityData.java +++ b/src/main/java/cn/nukkit/entity/data/FloatEntityData.java @@ -3,10 +3,11 @@ import cn.nukkit.entity.Entity; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class FloatEntityData extends EntityData { + public float data; public FloatEntityData(int id, float data) { @@ -24,7 +25,6 @@ public void setData(Float data) { } else { this.data = data; } - } @Override diff --git a/src/main/java/cn/nukkit/entity/data/IntEntityData.java b/src/main/java/cn/nukkit/entity/data/IntEntityData.java index 51cf4a94888..e704efbbf67 100644 --- a/src/main/java/cn/nukkit/entity/data/IntEntityData.java +++ b/src/main/java/cn/nukkit/entity/data/IntEntityData.java @@ -3,10 +3,11 @@ import cn.nukkit.entity.Entity; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class IntEntityData extends EntityData { + public int data; public IntEntityData(int id, int data) { diff --git a/src/main/java/cn/nukkit/entity/data/IntPositionEntityData.java b/src/main/java/cn/nukkit/entity/data/IntPositionEntityData.java index f053d8f4be8..aeecebdc9cf 100644 --- a/src/main/java/cn/nukkit/entity/data/IntPositionEntityData.java +++ b/src/main/java/cn/nukkit/entity/data/IntPositionEntityData.java @@ -5,10 +5,11 @@ import cn.nukkit.math.Vector3; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class IntPositionEntityData extends EntityData { + public int x; public int y; public int z; diff --git a/src/main/java/cn/nukkit/entity/data/LongEntityData.java b/src/main/java/cn/nukkit/entity/data/LongEntityData.java index a51ae44aa6f..a9d19454330 100644 --- a/src/main/java/cn/nukkit/entity/data/LongEntityData.java +++ b/src/main/java/cn/nukkit/entity/data/LongEntityData.java @@ -3,10 +3,11 @@ import cn.nukkit.entity.Entity; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class LongEntityData extends EntityData { + public long data; public LongEntityData(int id, long data) { diff --git a/src/main/java/cn/nukkit/entity/data/NBTEntityData.java b/src/main/java/cn/nukkit/entity/data/NBTEntityData.java index 9c6e1e0fd0c..bdf21631d6a 100644 --- a/src/main/java/cn/nukkit/entity/data/NBTEntityData.java +++ b/src/main/java/cn/nukkit/entity/data/NBTEntityData.java @@ -1,20 +1,29 @@ package cn.nukkit.entity.data; import cn.nukkit.entity.Entity; +import cn.nukkit.item.Item; import cn.nukkit.nbt.tag.CompoundTag; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class NBTEntityData extends EntityData { + public CompoundTag tag; + public Item item; public NBTEntityData(int id, CompoundTag tag) { super(id); this.tag = tag; } + public NBTEntityData(int id, Item item) { + super(id); + this.item = item; + this.tag = item.getNamedTag(); + } + @Override public CompoundTag getData() { return this.tag; diff --git a/src/main/java/cn/nukkit/entity/data/ShortEntityData.java b/src/main/java/cn/nukkit/entity/data/ShortEntityData.java index 1e9cf0a308c..7b775a8f6b8 100644 --- a/src/main/java/cn/nukkit/entity/data/ShortEntityData.java +++ b/src/main/java/cn/nukkit/entity/data/ShortEntityData.java @@ -3,10 +3,11 @@ import cn.nukkit.entity.Entity; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ShortEntityData extends EntityData { + public int data; public ShortEntityData(int id, int data) { diff --git a/src/main/java/cn/nukkit/entity/data/Skin.java b/src/main/java/cn/nukkit/entity/data/Skin.java index 4ea4dcc59a9..74aabb49c5f 100644 --- a/src/main/java/cn/nukkit/entity/data/Skin.java +++ b/src/main/java/cn/nukkit/entity/data/Skin.java @@ -1,5 +1,6 @@ package cn.nukkit.entity.data; +import cn.nukkit.Server; import cn.nukkit.nbt.stream.FastByteArrayOutputStream; import cn.nukkit.utils.*; import com.google.common.base.Preconditions; @@ -10,27 +11,29 @@ import java.awt.*; import java.awt.image.BufferedImage; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; import java.util.List; -import java.util.Objects; -import java.util.UUID; +import java.util.*; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ -@ToString(exclude = {"geometryData", "animationData"}) +@ToString public class Skin { + private static final int PIXEL_SIZE = 4; public static final int SINGLE_SKIN_SIZE = 64 * 32 * PIXEL_SIZE; public static final int DOUBLE_SKIN_SIZE = 64 * 64 * PIXEL_SIZE; public static final int SKIN_128_64_SIZE = 128 * 64 * PIXEL_SIZE; public static final int SKIN_128_128_SIZE = 128 * 128 * PIXEL_SIZE; + + private static final int MAX_DATA_SIZE = 262144; public static final String GEOMETRY_CUSTOM = convertLegacyGeometryName("geometry.humanoid.custom"); public static final String GEOMETRY_CUSTOM_SLIM = convertLegacyGeometryName("geometry.humanoid.customSlim"); + private boolean noPlayFab; // Don't attempt to generate missing play fab id multiple times private String fullSkinId; private String skinId; private String playFabId = ""; @@ -58,15 +61,24 @@ public boolean isValid() { } private boolean isValidSkin() { - return skinId != null && !skinId.trim().isEmpty() && skinId.length() < 100 && - skinData != null && skinData.width >= 64 && skinData.height >= 32 && - skinData.data.length >= SINGLE_SKIN_SIZE && - (playFabId == null || playFabId.length() < 100) && - (capeId == null || capeId.length() < 100) && - (skinColor == null || skinColor.length() < 100) && - (armSize == null || armSize.length() < 100) && - (fullSkinId == null || fullSkinId.length() < 200) && - (geometryDataEngineVersion == null || geometryDataEngineVersion.length() < 100); + try { + return (skinId != null && !skinId.trim().isEmpty() && skinId.length() < 100) && + (skinData != null && skinData.width >= 64 && skinData.height >= 32 && skinData.data.length >= SINGLE_SKIN_SIZE) && + (geometryData != null && !geometryData.isEmpty()) && + ((geometryData.getBytes().length <= MAX_DATA_SIZE && + skinData.data.length <= MAX_DATA_SIZE && + (capeData == null || capeData.data.length <= MAX_DATA_SIZE) && + (animationData == null || animationData.getBytes().length <= MAX_DATA_SIZE))) && + (playFabId == null || playFabId.length() < 100) && + (capeId == null || capeId.length() < 100) && + (skinColor == null || skinColor.length() < 100) && + (armSize == null || armSize.length() < 100) && + (fullSkinId == null || fullSkinId.length() < 200) && + (geometryDataEngineVersion == null || geometryDataEngineVersion.length() < 100); + } catch (Exception ex) { + Server.getInstance().getLogger().logException(ex); + return false; + } } private boolean isValidResourcePatch() { @@ -74,8 +86,7 @@ private boolean isValidResourcePatch() { return false; } try { - JSONObject object = (JSONObject) JSONValue.parse(skinResourcePatch); - JSONObject geometry = (JSONObject) object.get("geometry"); + JSONObject geometry = (JSONObject) ((JSONObject) JSONValue.parse(skinResourcePatch)).get("geometry"); return geometry.containsKey("default") && geometry.get("default") instanceof String; } catch (ClassCastException | NullPointerException e) { return false; @@ -91,6 +102,7 @@ public SerializedImage getSkinData() { public String getSkinId() { if (this.skinId == null) { + Server.getInstance().getLogger().debug("Missing skin ID, generating new"); this.generateSkinId("Custom"); } return skinId; @@ -98,6 +110,7 @@ public String getSkinId() { public void setSkinId(String skinId) { if (skinId == null || skinId.trim().isEmpty()) { + Server.getInstance().getLogger().debug("Skin ID cannot be empty! ", new Throwable("")); return; } this.skinId = skinId; @@ -123,14 +136,15 @@ public void setSkinData(SerializedImage skinData) { public void setSkinResourcePatch(String skinResourcePatch) { if (skinResourcePatch == null || skinResourcePatch.trim().isEmpty()) { - skinResourcePatch = GEOMETRY_CUSTOM; + this.skinResourcePatch = GEOMETRY_CUSTOM; + return; } this.skinResourcePatch = skinResourcePatch; } public void setGeometryName(String geometryName) { - if (geometryName == null || geometryName.trim().isEmpty()) { - skinResourcePatch = GEOMETRY_CUSTOM; + if (geometryName.trim().isEmpty()) { + this.skinResourcePatch = GEOMETRY_CUSTOM; return; } @@ -167,8 +181,9 @@ public void setCapeId(String capeId) { public void setCapeData(byte[] capeData) { Objects.requireNonNull(capeData, "capeData"); - Preconditions.checkArgument(capeData.length == SINGLE_SKIN_SIZE || capeData.length == 0, "Invalid legacy cape"); - setCapeData(new SerializedImage(64, 32, capeData)); + if (capeData.length == SINGLE_SKIN_SIZE) { + setCapeData(new SerializedImage(64, 32, capeData)); + } } public void setCapeData(BufferedImage image) { @@ -286,32 +301,47 @@ public void setArmSize(String armSize) { public void setFullSkinId(String fullSkinId) { this.fullSkinId = fullSkinId; + this.noPlayFab = false; // Allow another attempt to generate it using the new id } public String getFullSkinId() { if (this.fullSkinId == null) { this.fullSkinId = this.getSkinId() + this.getCapeId(); + this.noPlayFab = false; // Allow another attempt to generate it using the new id } return this.fullSkinId; } public void setPlayFabId(String playFabId) { this.playFabId = playFabId; + this.noPlayFab = false; } public String getPlayFabId() { - if (this.persona && (this.playFabId == null || this.playFabId.isEmpty())) { - try { - this.playFabId = this.skinId.split("-")[5]; - } catch (Exception e) { - this.playFabId = this.getFullSkinId().replace("-", "").substring(16); + if (this.noPlayFab) { + return ""; + } + if ((this.playFabId == null || this.playFabId.isEmpty())) { + String[] split = this.getFullSkinId().split("-", 6); + if (split.length > 5) { + this.playFabId = split[5]; + this.noPlayFab = false; + } else { + try { + this.playFabId = this.getFullSkinId().replace("-", "").substring(16); + this.noPlayFab = false; + } catch (Exception ignore) { + Server.getInstance().getLogger().debug("Couldn't generate Skin playFabId for " + this.getFullSkinId()); + this.playFabId = ""; + this.noPlayFab = true; + } } } return this.playFabId; } private static SerializedImage parseBufferedImage(BufferedImage image) { - FastByteArrayOutputStream outputStream = new FastByteArrayOutputStream(); + FastByteArrayOutputStream outputStream = ThreadCache.fbaos.get().reset(); for (int y = 0; y < image.getHeight(); y++) { for (int x = 0; x < image.getWidth(); x++) { Color color = new Color(image.getRGB(x, y), true); diff --git a/src/main/java/cn/nukkit/entity/data/StringEntityData.java b/src/main/java/cn/nukkit/entity/data/StringEntityData.java index 447b8226d7e..80771a36ad6 100644 --- a/src/main/java/cn/nukkit/entity/data/StringEntityData.java +++ b/src/main/java/cn/nukkit/entity/data/StringEntityData.java @@ -3,10 +3,11 @@ import cn.nukkit.entity.Entity; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class StringEntityData extends EntityData { + public String data; public StringEntityData(int id, String data) { diff --git a/src/main/java/cn/nukkit/entity/data/Vector3fEntityData.java b/src/main/java/cn/nukkit/entity/data/Vector3fEntityData.java index dbb37278fcb..3d8b9410b77 100644 --- a/src/main/java/cn/nukkit/entity/data/Vector3fEntityData.java +++ b/src/main/java/cn/nukkit/entity/data/Vector3fEntityData.java @@ -4,10 +4,11 @@ import cn.nukkit.math.Vector3f; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class Vector3fEntityData extends EntityData { + public float x; public float y; public float z; diff --git a/src/main/java/cn/nukkit/entity/item/EntityAreaEffectCloud.java b/src/main/java/cn/nukkit/entity/item/EntityAreaEffectCloud.java new file mode 100644 index 00000000000..8969d7df19b --- /dev/null +++ b/src/main/java/cn/nukkit/entity/item/EntityAreaEffectCloud.java @@ -0,0 +1,410 @@ +package cn.nukkit.entity.item; + +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.EntityBoss; +import cn.nukkit.entity.EntityLiving; +import cn.nukkit.entity.EntitySmite; +import cn.nukkit.entity.data.FloatEntityData; +import cn.nukkit.entity.data.IntEntityData; +import cn.nukkit.entity.data.LongEntityData; +import cn.nukkit.entity.data.ShortEntityData; +import cn.nukkit.event.entity.EntityDamageByEntityEvent; +import cn.nukkit.event.entity.EntityDamageEvent; +import cn.nukkit.event.entity.EntityPotionEffectEvent; +import cn.nukkit.event.entity.EntityRegainHealthEvent; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.ListTag; +import cn.nukkit.potion.Effect; +import cn.nukkit.potion.InstantEffect; +import cn.nukkit.potion.Potion; + +import java.util.ArrayList; +import java.util.List; + +public class EntityAreaEffectCloud extends Entity { + + public static final int NETWORK_ID = 95; + + private int reapplicationDelay; + private int durationOnUse; + private float initialRadius; + private float radiusOnUse; + private int nextApply; + public List cloudEffects; + private int lastAge; + + public EntityAreaEffectCloud(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + public int getWaitTime() { + return this.getDataPropertyInt(DATA_AREA_EFFECT_CLOUD_WAITING); + } + + public void setWaitTime(int waitTime) { + setWaitTime(waitTime, true); + } + + public void setWaitTime(int waitTime, boolean send) { + this.setDataProperty(new IntEntityData(DATA_AREA_EFFECT_CLOUD_WAITING, waitTime), send); + } + + public int getPotionId() { + return this.getDataPropertyShort(DATA_POTION_AUX_VALUE); + } + + public void setPotionId(int potionId) { + setPotionId(potionId, true); + } + + public void setPotionId(int potionId, boolean send) { + this.setDataProperty(new ShortEntityData(DATA_POTION_AUX_VALUE, potionId & 0xFFFF), send); + } + + public void recalculatePotionColor() { + recalculatePotionColor(true); + } + + public void recalculatePotionColor(boolean send) { + int a; + int r; + int g; + int b; + + int color; + if (namedTag.contains("ParticleColor")) { + color = namedTag.getInt("ParticleColor"); + a = (color & 0xFF000000) >> 24; + r = (color & 0x00FF0000) >> 16; + g = (color & 0x0000FF00) >> 8; + b = color & 0x000000FF; + } else { + a = 255; + Effect effect = Potion.getEffect(getPotionId(), true); + if (effect == null) { + r = 40; + g = 40; + b = 255; + } else { + int[] colors = effect.getColor(); + r = colors[0]; + g = colors[1]; + b = colors[2]; + } + } + + setPotionColor(a, r, g, b, send); + } + + public int getPotionColor() { + return this.getDataPropertyInt(DATA_POTION_COLOR); + } + + public void setPotionColor(int alpha, int red, int green, int blue, boolean send) { + setPotionColor(((alpha & 0xff) << 24) | ((red & 0xff) << 16) | ((green & 0xff) << 8) | (blue & 0xff), send); + } + + public void setPotionColor(int argp) { + setPotionColor(argp, true); + } + + public void setPotionColor(int argp, boolean send) { + this.setDataProperty(new IntEntityData(DATA_POTION_COLOR, argp), send); + } + + public int getPickupCount() { + return this.getDataPropertyInt(DATA_PICKUP_COUNT); + } + + public void setPickupCount(int pickupCount) { + setPickupCount(pickupCount, true); + } + + public void setPickupCount(int pickupCount, boolean send) { + this.setDataProperty(new IntEntityData(DATA_PICKUP_COUNT, pickupCount), send); + } + + public float getRadiusChangeOnPickup() { + return this.getDataPropertyFloat(DATA_CHANGE_ON_PICKUP); + } + + public void setRadiusChangeOnPickup(float radiusChangeOnPickup) { + setRadiusChangeOnPickup(radiusChangeOnPickup, true); + } + + public void setRadiusChangeOnPickup(float radiusChangeOnPickup, boolean send) { + this.setDataProperty(new FloatEntityData(DATA_CHANGE_ON_PICKUP, radiusChangeOnPickup), send); + } + + public float getRadiusPerTick() { + return this.getDataPropertyFloat(DATA_CHANGE_RATE); + } + + public void setRadiusPerTick(float radiusPerTick) { + setRadiusPerTick(radiusPerTick, true); + } + + public void setRadiusPerTick(float radiusPerTick, boolean send) { + this.setDataProperty(new FloatEntityData(DATA_CHANGE_RATE, radiusPerTick), send); + } + + public long getSpawnTime() { + return this.getDataPropertyInt(DATA_SPAWN_TIME); + } + + public void setSpawnTime(long spawnTime) { + setSpawnTime(spawnTime, true); + } + + public void setSpawnTime(long spawnTime, boolean send) { + this.setDataProperty(new LongEntityData(DATA_SPAWN_TIME, spawnTime), send); + } + + public int getDuration() { + return this.getDataPropertyInt(DATA_DURATION); + } + + public void setDuration(int duration) { + setDuration(duration, true); + } + + public void setDuration(int duration, boolean send) { + this.setDataProperty(new IntEntityData(DATA_DURATION, duration), send); + } + + public float getRadius() { + return this.getDataPropertyFloat(DATA_AREA_EFFECT_CLOUD_RADIUS); + } + + public void setRadius(float radius) { + setRadius(radius, true); + } + + public void setRadius(float radius, boolean send) { + this.setDataProperty(new FloatEntityData(DATA_AREA_EFFECT_CLOUD_RADIUS, radius), send); + } + + public int getParticleId() { + return this.getDataPropertyInt(DATA_AREA_EFFECT_CLOUD_PARTICLE_ID); + } + + public void setParticleId(int particleId) { + setParticleId(particleId, true); + } + + public void setParticleId(int particleId, boolean send) { + this.setDataProperty(new IntEntityData(DATA_AREA_EFFECT_CLOUD_PARTICLE_ID, particleId), send); + } + + @Override + protected void initEntity() { + super.initEntity(); + this.invulnerable = true; + this.fireProof = true; + //this.setDataFlag(DATA_FLAGS, DATA_FLAG_FIRE_IMMUNE, true); + //this.setDataFlag(DATA_FLAGS, DATA_FLAG_IMMOBILE, true); + this.setDataProperty(new ShortEntityData(DATA_AREA_EFFECT_CLOUD_PARTICLE_ID, 32), false); + this.setDataProperty(new LongEntityData(DATA_SPAWN_TIME, this.level.getCurrentTick()), false); + this.setDataProperty(new IntEntityData(DATA_PICKUP_COUNT, 0), false); + + cloudEffects = new ArrayList<>(1); + for (CompoundTag effectTag : namedTag.getList("mobEffects", CompoundTag.class).getAll()) { + Effect effect = Effect.getEffect(effectTag.getByte("Id")) + .setAmbient(effectTag.getBoolean("Ambient")) + .setAmplifier(effectTag.getByte("Amplifier")) + .setVisible(effectTag.getBoolean("DisplayOnScreenTextureAnimation")) + .setDuration(effectTag.getInt("Duration")); + cloudEffects.add(effect); + } + int displayedPotionId = namedTag.getShort("PotionId"); + setPotionId(displayedPotionId, false); + recalculatePotionColor(); + + if (namedTag.contains("Duration")) { + setDuration(namedTag.getInt("Duration"), false); + } else { + setDuration(600, false); + } + if (namedTag.contains("DurationOnUse")) { + durationOnUse = namedTag.getInt("DurationOnUse"); + } else { + durationOnUse = 0; + } + if (namedTag.contains("ReapplicationDelay")) { + reapplicationDelay = namedTag.getInt("ReapplicationDelay"); + } else { + reapplicationDelay = 0; + } + if (namedTag.contains("InitialRadius")) { + initialRadius = namedTag.getFloat("InitialRadius"); + } else { + initialRadius = 3.0F; + } + if (namedTag.contains("Radius")) { + setRadius(namedTag.getFloat("Radius"), false); + } else { + setRadius(initialRadius, false); + } + if (namedTag.contains("RadiusChangeOnPickup")) { + setRadiusChangeOnPickup(namedTag.getFloat("RadiusChangeOnPickup"), false); + } else { + setRadiusChangeOnPickup(-0.5F, false); + } + if (namedTag.contains("RadiusOnUse")) { + radiusOnUse = namedTag.getFloat("RadiusOnUse"); + } else { + radiusOnUse = -0.5F; + } + if (namedTag.contains("RadiusPerTick")) { + setRadiusPerTick(namedTag.getFloat("RadiusPerTick"), false); + } else { + setRadiusPerTick(-0.005F, false); + } + if (namedTag.contains("WaitTime")) { + setWaitTime(namedTag.getInt("WaitTime"), false); + } else { + setWaitTime(10, false); + } + } + + @Override + public boolean attack(EntityDamageEvent source) { + return false; + } + + @Override + public void saveNBT() { + super.saveNBT(); + ListTag effectsTag = new ListTag<>("mobEffects"); + for (Effect effect : cloudEffects) { + effectsTag.add(new CompoundTag().putByte("Id", effect.getId()) + .putBoolean("Ambient", effect.isAmbient()) + .putByte("Amplifier", effect.getAmplifier()) + .putBoolean("DisplayOnScreenTextureAnimation", effect.isVisible()) + .putInt("Duration", effect.getDuration()) + ); + } + namedTag.putList(effectsTag); + namedTag.putInt("ParticleColor", getPotionColor()); + namedTag.putShort("PotionId", getPotionId()); + namedTag.putInt("Duration", getDuration()); + namedTag.putInt("DurationOnUse", durationOnUse); + namedTag.putInt("ReapplicationDelay", reapplicationDelay); + namedTag.putFloat("Radius", getRadius()); + namedTag.putFloat("RadiusChangeOnPickup", getRadiusChangeOnPickup()); + namedTag.putFloat("RadiusOnUse", radiusOnUse); + namedTag.putFloat("RadiusPerTick", getRadiusPerTick()); + namedTag.putInt("WaitTime", getWaitTime()); + namedTag.putFloat("InitialRadius", initialRadius); + } + + @Override + public boolean onUpdate(int currentTick) { + if (this.closed) { + return false; + } + + super.onUpdate(currentTick); + + boolean sendRadius = age % 10 == 0; + + int age = this.age; + float radius = getRadius(); + int waitTime = getWaitTime(); + if (age < waitTime) { + radius = initialRadius; + } else if (age > waitTime + getDuration()) { + close(); + return false; + } else { + int tickDiff = age - lastAge; + radius += getRadiusPerTick() * tickDiff; + if ((nextApply -= tickDiff) <= 0) { + nextApply = reapplicationDelay + 10; + + Entity[] collidingEntities = level.getCollidingEntities(getBoundingBox()); + if (collidingEntities.length > 1) { // This entity counts + radius += radiusOnUse; + radiusOnUse /= 2; + + setDuration(getDuration() + durationOnUse, false); + + for (Entity collidingEntity : collidingEntities) { + if (collidingEntity == null || collidingEntity == this || collidingEntity.closed || !collidingEntity.isAlive() || !(collidingEntity instanceof EntityLiving) || collidingEntity instanceof EntityBoss) { + continue; + } + + for (Effect effect : cloudEffects) { + if (effect instanceof InstantEffect) { + boolean damage = false; + if (effect.getId() == Effect.HARMING) damage = true; + if (collidingEntity instanceof EntitySmite) damage = !damage; // invert effect if undead + + if (damage) + collidingEntity.attack(new EntityDamageByEntityEvent(this, collidingEntity, EntityDamageEvent.DamageCause.MAGIC, (float) (0.5 * (double) (6 << (effect.getAmplifier() + 1))))); + else + collidingEntity.heal(new EntityRegainHealthEvent(collidingEntity, (float) (0.5 * (double) (4 << (effect.getAmplifier() + 1))), EntityRegainHealthEvent.CAUSE_MAGIC)); + + continue; + } + + collidingEntity.addEffect(effect, EntityPotionEffectEvent.Cause.AREA_EFFECT_CLOUD); + } + } + } + } + } + + this.lastAge = age; + + if (radius <= 1.5 && age >= waitTime) { + setRadius(radius, false); + close(); + return false; + } else { + setRadius(radius, sendRadius); + } + + float height = getHeight(); + boundingBox.setBounds(x - radius, y - height, z - radius, x + radius, y + height, z + radius); + this.setDataProperty(new FloatEntityData(DATA_BOUNDING_BOX_HEIGHT, height), false); + this.setDataProperty(new FloatEntityData(DATA_BOUNDING_BOX_WIDTH, radius), false); + return true; + } + + @Override + public boolean canCollideWith(Entity entity) { + return entity instanceof EntityLiving; + } + + @Override + public float getHeight() { + return 0.3F + (getRadius() / 2F); + } + + @Override + public float getWidth() { + return getRadius(); + } + + @Override + public float getLength() { + return getRadius(); + } + + @Override + protected float getGravity() { + return 0; + } + + @Override + protected float getDrag() { + return 0; + } + + @Override + public int getNetworkId() { + return NETWORK_ID; + } +} diff --git a/src/main/java/cn/nukkit/entity/item/EntityArmorStand.java b/src/main/java/cn/nukkit/entity/item/EntityArmorStand.java new file mode 100644 index 00000000000..d05ce1074a1 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/item/EntityArmorStand.java @@ -0,0 +1,378 @@ +package cn.nukkit.entity.item; + +import cn.nukkit.Player; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.EntityInteractable; +import cn.nukkit.entity.data.StringEntityData; +import cn.nukkit.event.entity.EntityDamageByEntityEvent; +import cn.nukkit.event.entity.EntityDamageEvent; +import cn.nukkit.inventory.EntityArmorInventory; +import cn.nukkit.inventory.EntityEquipmentInventory; +import cn.nukkit.inventory.InventoryHolder; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemArmor; +import cn.nukkit.level.GameRule; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.particle.DestroyBlockParticle; +import cn.nukkit.math.Vector3; +import cn.nukkit.nbt.NBTIO; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.ListTag; + +import java.util.Collection; + +public class EntityArmorStand extends Entity implements InventoryHolder, EntityInteractable { + + public static final int NETWORK_ID = 61; + + public static final String TAG_MAINHAND = "Mainhand"; + public static final String TAG_OFFHAND = "Offhand"; + public static final String TAG_POSE_INDEX = "PoseIndex"; + public static final String TAG_ARMOR = "Armor"; + + private EntityEquipmentInventory equipmentInventory; + private EntityArmorInventory armorInventory; + + private int pose; + private String nameTag; + + public EntityArmorStand(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + + this.updateMode = 3; + + if (nbt.contains(TAG_POSE_INDEX)) { + this.setPose(nbt.getInt(TAG_POSE_INDEX)); + } + } + + private static int getArmorSlot(ItemArmor armorItem) { + if (armorItem.canBePutInHelmetSlot()) { + return 0; + } else if (armorItem.isChestplate()) { + return 1; + } else if (armorItem.isLeggings()) { + return 2; + } else { + return 3; + } + } + + @Override + public int getNetworkId() { + return NETWORK_ID; + } + + @Override + protected float getGravity() { + return 0.04f; + } + + @Override + public float getHeight() { + return 1.975f; + } + + @Override + public float getWidth() { + return 0.5f; + } + + @Override + protected void initEntity() { + this.setMaxHealth(6); + + super.initEntity(); + + this.setHealth(6); + this.setImmobile(true); + + this.equipmentInventory = new EntityEquipmentInventory(this); + this.armorInventory = new EntityArmorInventory(this); + + if (this.namedTag.contains(TAG_MAINHAND)) { + this.equipmentInventory.setItemInHand(NBTIO.getItemHelper(this.namedTag.getCompound(TAG_MAINHAND)), true); + } + + if (this.namedTag.contains(TAG_OFFHAND)) { + this.equipmentInventory.setOffhandItem(NBTIO.getItemHelper(this.namedTag.getCompound(TAG_OFFHAND)), true); + } + + if (this.namedTag.contains(TAG_ARMOR)) { + ListTag armorList = this.namedTag.getList(TAG_ARMOR, CompoundTag.class); + for (CompoundTag armorTag : armorList.getAll()) { + this.armorInventory.setItem(armorTag.getByte("Slot"), NBTIO.getItemHelper(armorTag)); + } + } + + if (this.namedTag.contains(TAG_POSE_INDEX)) { + this.setPose(this.namedTag.getInt(TAG_POSE_INDEX)); + } + } + + @Override + public boolean onInteract(Player player, Item item, Vector3 clickedPos) { + if (!this.isAlive()) { + return false; + } + + if (item.getId() == Item.NAME_TAG && !player.isAdventure()) { + if (item.hasCustomName()) { + String name = item.getCustomName(); + this.namedTag.putString("CustomName", name); + this.namedTag.putBoolean("CustomNameVisible", true); + this.setNameTag(name); + this.setNameTagVisible(true); + return true; // onInteract: true = decrease count + } + } + + if (player.sneakToBlockInteract()) { + if (this.getPose() >= 12) { + this.setPose(0); + } else { + this.setPose(this.getPose() + 1); + } + this.sendData(this.getViewers().values().toArray(new Player[0])); + return false; // do not consume item + } + + if (this.isValid() && !player.isSpectator()) { + int i = 0; + boolean flag = !item.isNull(); + boolean isArmorSlot = false; + + if (flag && item instanceof ItemArmor) { + ItemArmor itemArmor = (ItemArmor) item; + i = getArmorSlot(itemArmor); + isArmorSlot = true; + } + + if (flag && (item.getId() == Item.SKULL) || item.getId() == (255 - BlockID.CARVED_PUMPKIN)) { + i = 0; + isArmorSlot = true; + } + + int j = 0; + double d3 = clickedPos.y - this.y; + boolean flag2 = false; + + if (d3 >= 0.1 && d3 < 0.55 && !this.armorInventory.getItemFast(EntityArmorInventory.SLOT_FEET).isNull()) { + j = 3; + flag2 = isArmorSlot = true; + } else if (d3 >= 0.9 && d3 < 1.6 && !this.armorInventory.getItemFast(EntityArmorInventory.SLOT_CHEST).isNull()) { + j = 1; + flag2 = isArmorSlot = true; + } else if (d3 >= 0.4 && d3 < 1.2 && !this.armorInventory.getItemFast(EntityArmorInventory.SLOT_LEGS).isNull()) { + j = 2; + flag2 = isArmorSlot = true; + } else if (d3 >= 1.6 && !this.armorInventory.getItemFast(EntityArmorInventory.SLOT_HEAD).isNull()) { + flag2 = isArmorSlot = true; + } else if (!this.equipmentInventory.getItemFast(j).isNull()) { + flag2 = true; + } + + if (flag) { + this.tryChangeEquipment(player, item, i, isArmorSlot); + } else if (flag2) { + this.tryChangeEquipment(player, item, j, isArmorSlot); + } + return false; // Item set in tryChangeEquipment + } + return false; + } + + private void tryChangeEquipment(Player player, Item newItem, int slot, boolean isArmorSlot) { + Item currentItem = isArmorSlot ? this.armorInventory.getItem(slot) : this.equipmentInventory.getItem(slot); + + if (currentItem.equals(newItem)) { + return; + } + + if (newItem.isNull()) { + if (isArmorSlot) { + this.armorInventory.setItem(slot, Item.get(Item.AIR)); + } else { + this.equipmentInventory.setItem(slot, Item.get(Item.AIR)); + } + } else { + if (!player.isCreative()) { + player.getInventory().decreaseCount(player.getInventory().getHeldItemIndex()); + } + + Item itemToAdd = newItem.clone(); + itemToAdd.setCount(1); + if (isArmorSlot) { + this.armorInventory.setItem(slot, itemToAdd); + } else { + this.equipmentInventory.setItem(slot, itemToAdd); + } + } + + if (!currentItem.isNull()) { + player.getInventory().addItem(currentItem); + } + + Collection viewers = this.getViewers().values(); + this.equipmentInventory.sendContents(viewers); + this.armorInventory.sendContents(viewers); + } + + public int getPose() { + return this.pose; + } + + public void setPose(int pose) { + this.pose = pose; + this.dataProperties.putInt(Entity.DATA_ARMOR_STAND_POSE_INDEX, pose); + } + + @Override + public void saveNBT() { + super.saveNBT(); + + this.namedTag.put(TAG_MAINHAND, NBTIO.putItemHelper(this.equipmentInventory.getItemInHand())); + this.namedTag.put(TAG_OFFHAND, NBTIO.putItemHelper(this.equipmentInventory.getOffHandItem())); + + if (this.armorInventory != null) { + ListTag armorTag = new ListTag<>(TAG_ARMOR); + for (int i = 0; i < 4; i++) { + armorTag.add(NBTIO.putItemHelper(this.armorInventory.getItem(i), i)); + } + this.namedTag.putList(armorTag); + } + + this.namedTag.putInt(TAG_POSE_INDEX, this.getPose()); + } + + @Override + public void spawnTo(Player player) { + super.spawnTo(player); + this.equipmentInventory.sendContents(player); + this.armorInventory.sendContents(player); + } + + @Override + public boolean attack(EntityDamageEvent source) { + if (source.getCause() == EntityDamageEvent.DamageCause.CONTACT) { + source.setCancelled(true); + } + + if (!this.isAlive() || !super.attack(source)) { + return false; + } + + if (!source.isCancelled() && !this.closed) { + this.setGenericFlag(Entity.DATA_FLAG_VIBRATING, true); + this.level.addParticle(new DestroyBlockParticle(this, Block.get(Block.WOODEN_PLANKS))); + this.kill(); // Using close() here would not leave any time for the vibrating effect to display + if (source instanceof EntityDamageByEntityEvent) { + EntityDamageByEntityEvent event = (EntityDamageByEntityEvent) source; + if (event.getDamager() instanceof Player) { + Player player = (Player) event.getDamager(); + if (player.isCreative()) { + this.close(); + return true; + } + + boolean drop = this.level.getGameRules().getBoolean(GameRule.DO_ENTITY_DROPS); + if (drop) { + this.level.dropItem(this, Item.get(Item.ARMOR_STAND)); + } + if (this.equipmentInventory != null) { + if (drop) { + this.equipmentInventory.getContents().values().forEach(items -> this.level.dropItem(this, items)); + } + this.equipmentInventory.clearAll(); + } + if (this.armorInventory != null) { + if (drop) { + this.armorInventory.getContents().values().forEach(items -> this.level.dropItem(this, items)); + } + this.armorInventory.clearAll(); + } + } + } + } + return true; + } + + @Override + public String getName() { + return this.hasCustomName() ? this.getNameTag() : "Armor Stand"; + } + + public EntityEquipmentInventory getEquipmentInventory() { + return this.equipmentInventory; + } + + @Override + public EntityArmorInventory getInventory() { + return this.armorInventory; + } + + @Override + public boolean onUpdate(int currentTick) { + if (this.closed) { + return false; + } + + boolean hasUpdate = super.onUpdate(currentTick); + + if (this.updateMode % 2 == 1) { + this.updateMode = 3; + + if (this.onGround) { + if (level.getBlockIdAt(chunk, getFloorX(), getFloorY() - 1, getFloorZ()) == 0) { + this.onGround = false; + } + } + } + + if (!this.onGround) { + this.motionY -= getGravity(); + } else { + this.motionY = 0; + } + + this.move(this.motionX, this.motionY, this.motionZ); + + this.motionX *= 0.9; + this.motionY *= 0.9; + this.motionZ *= 0.9; + + this.updateMovement(); + + return hasUpdate || !(this.motionX == 0 && this.motionY == 0 && this.motionZ == 0); + } + + @Override + public String getInteractButtonText() { + return "action.interact.armorstand.equip"; + } + + @Override + public boolean canDoInteraction() { + return true; + } + + @Override + public void setNameTag(String name) { + this.nameTag = name; + if (this.namedTag.contains("CustomNameVisible") || this.namedTag.contains("CustomNameAlwaysVisible")) { // Hack: Vanilla: Disable client side name tag while keeping custom name in nbt + this.setDataProperty(new StringEntityData(DATA_NAMETAG, name)); + } + } + + @Override + public boolean hasCustomName() { + return this.nameTag != null; + } + + @Override + public String getNameTag() { + return this.nameTag == null ? "" : this.nameTag; + } +} diff --git a/src/main/java/cn/nukkit/entity/item/EntityBoat.java b/src/main/java/cn/nukkit/entity/item/EntityBoat.java index ff3a6fdf7ac..5c9fdffa2ac 100644 --- a/src/main/java/cn/nukkit/entity/item/EntityBoat.java +++ b/src/main/java/cn/nukkit/entity/item/EntityBoat.java @@ -13,14 +13,10 @@ import cn.nukkit.event.vehicle.VehicleMoveEvent; import cn.nukkit.event.vehicle.VehicleUpdateEvent; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemBoat; import cn.nukkit.level.GameRule; import cn.nukkit.level.Location; import cn.nukkit.level.format.FullChunk; -import cn.nukkit.math.AxisAlignedBB; -import cn.nukkit.math.NukkitMath; -import cn.nukkit.math.Vector3; -import cn.nukkit.math.Vector3f; +import cn.nukkit.math.*; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.network.protocol.AnimatePacket; import cn.nukkit.network.protocol.SetEntityLinkPacket; @@ -52,21 +48,21 @@ public class EntityBoat extends EntityVehicle { public EntityBoat(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); - - this.setMaxHealth(40); - this.setHealth(40); } @Override protected void initEntity() { + this.setMaxHealth(40); super.initEntity(); - this.dataProperties.putInt(DATA_VARIANT, woodID = this.namedTag.getByte("woodID")); - this.dataProperties.putByte(DATA_CONTROLLING_RIDER_SEAT_NUMBER, 0); + this.setHealth(40); + + if (this.namedTag.contains("Variant")) { + this.woodID = this.namedTag.getInt("Variant"); + } + this.dataProperties.putInt(DATA_VARIANT, this.woodID); this.dataProperties.putBoolean(DATA_IS_BUOYANT, true); this.dataProperties.putString(DATA_BUOYANCY_DATA, "{\"apply_gravity\":true,\"base_buoyancy\":1.0,\"big_wave_probability\":0.02999999932944775,\"big_wave_speed\":10.0,\"drag_down_on_buoyancy_removed\":0.0,\"liquid_blocks\":[\"minecraft:water\",\"minecraft:flowing_water\"],\"simulate_waves\":true}"); - this.setDataFlag(DATA_FLAGS, DATA_FLAG_GRAVITY, true); - this.setDataFlag(DATA_FLAGS, DATA_FLAG_STACKABLE, true); } @Override @@ -86,12 +82,12 @@ protected float getDrag() { @Override protected float getGravity() { - return 0.03999999910593033F; + return 0.04f; } @Override public float getBaseOffset() { - return 0.375F; + return 0.375f; } @Override @@ -120,8 +116,11 @@ public boolean attack(EntityDamageEvent source) { public void close() { super.close(); - for (Entity linkedEntity : this.passengers) { - linkedEntity.riding = null; + if (!passengers.isEmpty()) { + for (Entity passenger : new ArrayList<>(passengers)) { + dismountEntity(passenger); + passenger.riding = null; // Make sure it's really removed even if a plugin tries to cancel it + } } } @@ -146,18 +145,16 @@ public boolean onUpdate(int currentTick) { double waterDiff = getWaterLevel(); if (!hasControllingPassenger()) { - if (waterDiff > SINKING_DEPTH && !sinking) { sinking = true; - } else if (waterDiff < -SINKING_DEPTH && sinking) { + } else if (waterDiff < -0.07 && sinking) { sinking = false; } - if (waterDiff < -SINKING_DEPTH) { + if (waterDiff < -0.07) { this.motionY = Math.min(0.05, this.motionY + 0.005); } else if (waterDiff < 0 || !sinking) { this.motionY = this.motionY > SINKING_MAX_SPEED ? Math.max(this.motionY - 0.02, SINKING_MAX_SPEED) : this.motionY + SINKING_SPEED; -// this.motionY = this.motionY + SINKING_SPEED > SINKING_MAX_SPEED ? this.motionY - SINKING_SPEED : this.motionY + SINKING_SPEED; } } @@ -165,19 +162,19 @@ public boolean onUpdate(int currentTick) { hasUpdate = true; } - this.move(this.motionX, this.motionY, this.motionZ); + //this.move(this.motionX, this.motionY, this.motionZ); double friction = 1 - this.getDrag(); if (this.onGround && (Math.abs(this.motionX) > 0.00001 || Math.abs(this.motionZ) > 0.00001)) { - friction *= this.getLevel().getBlock(this.temporalVector.setComponents((int) Math.floor(this.x), (int) Math.floor(this.y - 1), (int) Math.floor(this.z) - 1)).getFrictionFactor(); + friction *= this.getLevel().getBlock(this.chunk, getFloorX(), getFloorY() - 1, getFloorZ(), false).getFrictionFactor(); } this.motionX *= friction; if (!hasControllingPassenger()) { if (waterDiff > SINKING_DEPTH || sinking) { - this.motionY = waterDiff > 0.5 ? this.motionY - this.getGravity() : (this.motionY - SINKING_SPEED < -SINKING_MAX_SPEED ? this.motionY : this.motionY - SINKING_SPEED); + this.motionY = waterDiff > 0.5 ? this.motionY - this.getGravity() : (this.motionY - SINKING_SPEED < -0.005 ? this.motionY : this.motionY - SINKING_SPEED); } } @@ -192,19 +189,18 @@ public boolean onUpdate(int currentTick) { this.getServer().getPluginManager().callEvent(new VehicleMoveEvent(this, from, to)); } - //TODO: lily pad collision - this.updateMovement(); - - if (!this.isFull()) { - for (Entity entity : this.level.getCollidingEntities(this.boundingBox.grow(0.20000000298023224, 0.0D, 0.20000000298023224), this)) { - if (entity.riding != null || !(entity instanceof EntityLiving) || entity instanceof Player || entity instanceof EntityWaterAnimal || isPassenger(entity)) { - continue; - } + this.move(this.motionX, this.motionY, this.motionZ); - this.mountEntity(entity); + this.updateMovement(); - if (this.isFull()) { - break; + if (this.age % 5 == 0) { + if (!this.passengers.isEmpty() && this.passengers.get(0) instanceof Player) { + Block[] blocks = this.level.getCollisionBlocks(this.getBoundingBox().grow(0.1, 0.3, 0.1)); + for (Block b : blocks) { + if (b.getId() == Block.LILY_PAD) { + this.level.setBlockAt((int) b.x, (int) b.y, (int) b.z, 0, 0); + this.level.dropItem(b, Item.get(Item.LILY_PAD, 0, 1)); + } } } } @@ -231,19 +227,19 @@ public void updatePassengers(boolean sendLinks) { Entity ent; if (passengers.size() == 1) { - (ent = this.passengers.get(0)).setSeatPosition(getMountedOffset(ent)); + (ent = this.passengers.get(RIDER_INDEX)).setSeatPosition(getMountedOffset(ent)); super.updatePassengerPosition(ent); if (sendLinks) { broadcastLinkPacket(ent, SetEntityLinkPacket.TYPE_RIDE); } } else if (passengers.size() == 2) { - if (!((ent = passengers.get(0)) instanceof Player)) { //swap - Entity passenger2 = passengers.get(1); + if (!((ent = passengers.get(RIDER_INDEX)) instanceof Player)) { //swap + Entity passenger2 = passengers.get(PASSENGER_INDEX); if (passenger2 instanceof Player) { - this.passengers.set(0, passenger2); - this.passengers.set(1, ent); + this.passengers.set(RIDER_INDEX, passenger2); + this.passengers.set(PASSENGER_INDEX, ent); ent = passenger2; } @@ -255,7 +251,7 @@ public void updatePassengers(boolean sendLinks) { broadcastLinkPacket(ent, SetEntityLinkPacket.TYPE_RIDE); } - (ent = this.passengers.get(1)).setSeatPosition(getMountedOffset(ent).add(PASSENGER_OFFSET)); + (ent = this.passengers.get(PASSENGER_INDEX)).setSeatPosition(getMountedOffset(ent).add(PASSENGER_OFFSET)); super.updatePassengerPosition(ent); @@ -275,18 +271,15 @@ public void updatePassengers(boolean sendLinks) { public double getWaterLevel() { double maxY = this.boundingBox.getMinY() + getBaseOffset(); - AxisAlignedBB.BBConsumer consumer = new AxisAlignedBB.BBConsumer() { + AxisAlignedBB.BBConsumer consumer = new SimpleAxisAlignedBB.BBConsumer() { private double diffY = Double.MAX_VALUE; @Override public void accept(int x, int y, int z) { Block block = EntityBoat.this.level.getBlock(EntityBoat.this.temporalVector.setComponents(x, y, z)); - if (block instanceof BlockWater) { - double level = block.getMaxY(); - - diffY = Math.min(maxY - level, diffY); + diffY = Math.min(maxY - block.getMaxY(), diffY); } } @@ -302,23 +295,26 @@ public Double get() { } @Override - public boolean mountEntity(Entity entity) { - boolean player = this.passengers.size() >= 1 && this.passengers.get(0) instanceof Player; - byte mode = SetEntityLinkPacket.TYPE_PASSENGER; + public boolean mountEntity(Entity entity, byte mode) { + boolean player = !this.passengers.isEmpty() && this.passengers.get(RIDER_INDEX) instanceof Player; + mode = SetEntityLinkPacket.TYPE_PASSENGER; - if (!player && (entity instanceof Player || this.passengers.size() == 0)) { + if (!player && (entity instanceof Player || this.passengers.isEmpty())) { mode = SetEntityLinkPacket.TYPE_RIDE; } boolean r = super.mountEntity(entity, mode); - if (entity.riding != null) { + if (r) { updatePassengers(true); - entity.setDataProperty(new ByteEntityData(DATA_RIDER_ROTATION_LOCKED, 1)); - entity.setDataProperty(new FloatEntityData(DATA_RIDER_MAX_ROTATION, 90)); - entity.setDataProperty(new FloatEntityData(DATA_RIDER_MIN_ROTATION, 1)); - entity.setDataProperty(new FloatEntityData(DATA_RIDER_ROTATION_OFFSET, -90)); + entity.setDataProperty(new ByteEntityData(DATA_RIDER_ROTATION_LOCKED, 1), !(entity instanceof Player)); + if (entity instanceof Player) { + entity.setDataProperty(new FloatEntityData(DATA_RIDER_MAX_ROTATION, 90), false); + entity.setDataProperty(new FloatEntityData(DATA_RIDER_MIN_ROTATION, 1), false); + entity.setDataProperty(new FloatEntityData(DATA_RIDER_ROTATION_OFFSET, -90), false); + entity.sendData(((Player) entity)); + } } return r; @@ -333,20 +329,21 @@ protected void updatePassengerPosition(Entity passenger) { public boolean dismountEntity(Entity entity, boolean sendLinks) { boolean r = super.dismountEntity(entity, sendLinks); - updatePassengers(); - entity.setDataProperty(new ByteEntityData(DATA_RIDER_ROTATION_LOCKED, 0)); - + if (r) { + updatePassengers(); + entity.setDataProperty(new ByteEntityData(DATA_RIDER_ROTATION_LOCKED, 0), true); + } return r; } @Override public boolean isControlling(Entity entity) { - return entity instanceof Player && this.passengers.indexOf(entity) == 0; + return entity instanceof Player && this.passengers.indexOf(entity) == RIDER_INDEX; } @Override public boolean onInteract(Player player, Item item, Vector3 clickedPos) { - if (this.isFull()) { + if (this.isFull() || getWaterLevel() < -SINKING_DEPTH) { return false; } @@ -369,9 +366,19 @@ public void onPaddle(AnimatePacket.Action animation, float value) { @Override public void applyEntityCollision(Entity entity) { + if (entity instanceof Player && entity.riding != this) { + ((Player) entity).resetInAirTicks(); // Hack: Don't kick players standing on a boat for flying + } + + if (this.passengers.size() < 2) { + if (!(entity.riding != null || !(entity instanceof EntityLiving) || entity instanceof Player || entity instanceof EntityWaterAnimal || this.isPassenger(entity))) { + this.mountEntity(entity); + } + } + if (this.riding == null && entity.riding != this && !entity.passengers.contains(this)) { if (!entity.boundingBox.intersectsWith(this.boundingBox.grow(0.20000000298023224, -0.1, 0.20000000298023224)) - || entity instanceof Player && ((Player) entity).isSpectator()) { + || entity instanceof Player && ((Player) entity).getGamemode() == Player.SPECTATOR) { return; } @@ -392,6 +399,7 @@ public void applyEntityCollision(Entity entity) { diffX *= 0.05000000074505806; diffZ *= 0.05000000074505806; diffX *= 1 + entityCollisionReduction; + diffZ *= 1 + entityCollisionReduction; if (this.riding == null) { motionX -= diffX; @@ -408,24 +416,36 @@ public boolean canPassThrough() { @Override public void kill() { + if (!this.isAlive()) { + return; + } + super.kill(); - if (this.lastDamageCause instanceof EntityDamageByEntityEvent) { - Entity damager = ((EntityDamageByEntityEvent) this.lastDamageCause).getDamager(); - if (damager instanceof Player && ((Player) damager).isCreative()) { - return; - } - } if (level.getGameRules().getBoolean(GameRule.DO_ENTITY_DROPS)) { - this.level.dropItem(this, new ItemBoat(this.woodID)); + if (this.lastDamageCause instanceof EntityDamageByEntityEvent) { + Entity damager = ((EntityDamageByEntityEvent) this.lastDamageCause).getDamager(); + if (damager instanceof Player && ((Player) damager).isCreative()) { + return; + } + } + this.dropItem(); } } @Override public void saveNBT() { super.saveNBT(); + this.namedTag.putInt("Variant", this.woodID); + } + + public int getVariant() { + return this.woodID; + } - this.namedTag.putByte("woodID", this.woodID); + public void setVariant(int variant) { + this.woodID = variant; + this.dataProperties.putInt(DATA_VARIANT, variant); } public void onInput(double x, double y, double z, double yaw) { @@ -440,4 +460,8 @@ public boolean isFull() { public String getInteractButtonText() { return !this.isFull() ? "action.interact.ride.boat" : ""; } + + protected void dropItem() { + this.level.dropItem(this, Item.get(Item.BOAT, this.woodID)); + } } diff --git a/src/main/java/cn/nukkit/entity/item/EntityChestBoat.java b/src/main/java/cn/nukkit/entity/item/EntityChestBoat.java new file mode 100644 index 00000000000..edeea50d25e --- /dev/null +++ b/src/main/java/cn/nukkit/entity/item/EntityChestBoat.java @@ -0,0 +1,143 @@ +package cn.nukkit.entity.item; + +import cn.nukkit.Player; +import cn.nukkit.inventory.*; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.math.Vector3; +import cn.nukkit.nbt.NBTIO; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.ListTag; + +public class EntityChestBoat extends EntityBoat implements InventoryHolder { + + public static final int NETWORK_ID = 218; + + protected ChestBoatInventory inventory; + + public EntityChestBoat(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + @Override + public int getNetworkId() { + return NETWORK_ID; + } + + @Override + public String getName() { + return "Boat with Chest"; + } + + @Override + public String getInteractButtonText(Player player) { + if (player.sneakToBlockInteract()) { + return "action.interact.opencontainer"; + } + return super.getInteractButtonText(); + } + + @Override + public boolean isFull() { + return !this.passengers.isEmpty(); + } + + @Override + public ChestBoatInventory getInventory() { + if (this.inventory == null) { + this.initInventory(); + } + return this.inventory; + } + + @Override + public boolean onInteract(Player player, Item item, Vector3 clickedPos) { + if (player.sneakToBlockInteract() && this.isAlive()) { + player.addWindow(this.getInventory()); + return false; + } + + return super.onInteract(player, item, clickedPos); + } + + @Override + public void initEntity() { + super.initEntity(); + + this.dataProperties + .putByte(DATA_CONTAINER_TYPE, InventoryType.CHEST_BOAT.getNetworkType()) + .putInt(DATA_CONTAINER_BASE_SIZE, 27) + .putInt(DATA_CONTAINER_EXTRA_SLOTS_PER_STRENGTH, 0); + } + + private void initInventory() { + if (!this.namedTag.contains("Items") || !(this.namedTag.get("Items") instanceof ListTag)) { + this.namedTag.putList(new ListTag("Items")); + } + ListTag list = (ListTag) this.namedTag.getList("Items"); + + this.inventory = new ChestBoatInventory(this); + + for (CompoundTag compound : list.getAll()) { + Item item = NBTIO.getItemHelper(compound); + if (item.getId() != 0 && item.getCount() > 0) { + this.inventory.slots.put(compound.getByte("Slot"), item); + } + } + } + + @Override + public void saveNBT() { + super.saveNBT(); + + if (this.inventory != null) { + this.namedTag.putList(new ListTag("Items")); + for (int slot = 0; slot < 27; ++slot) { + Item item = this.inventory.getItem(slot); + if (item != null && item.getId() != Item.AIR) { + this.namedTag.getList("Items", CompoundTag.class) + .add(NBTIO.putItemHelper(item, slot)); + } + } + } + } + + @Override + protected void dropItem() { + switch (this.getVariant()) { + case 0: + this.level.dropItem(this, Item.get(ItemID.OAK_CHEST_BOAT)); + break; + case 1: + this.level.dropItem(this, Item.get(ItemID.SPRUCE_CHEST_BOAT)); + break; + case 2: + this.level.dropItem(this, Item.get(ItemID.BIRCH_CHEST_BOAT)); + break; + case 3: + this.level.dropItem(this, Item.get(ItemID.JUNGLE_CHEST_BOAT)); + break; + case 4: + this.level.dropItem(this, Item.get(ItemID.ACACIA_CHEST_BOAT)); + break; + case 5: + this.level.dropItem(this, Item.get(ItemID.DARK_OAK_CHEST_BOAT)); + break; + case 6: + this.level.dropItem(this, Item.get(ItemID.MANGROVE_CHEST_BOAT)); + break; + } + + if (this.inventory == null) { + this.initInventory(); + } + if (this.inventory != null) { + this.inventory.getViewers().clear(); + for (Item item : this.inventory.getContents().values()) { + this.level.dropItem(this, item); + } + this.inventory.clearAll(); + } + } +} diff --git a/src/main/java/cn/nukkit/entity/item/EntityEndCrystal.java b/src/main/java/cn/nukkit/entity/item/EntityEndCrystal.java index cd7d96dae02..69638d7eff1 100644 --- a/src/main/java/cn/nukkit/entity/item/EntityEndCrystal.java +++ b/src/main/java/cn/nukkit/entity/item/EntityEndCrystal.java @@ -1,7 +1,9 @@ package cn.nukkit.entity.item; +import cn.nukkit.block.Block; import cn.nukkit.entity.Entity; import cn.nukkit.entity.EntityExplosive; +import cn.nukkit.entity.data.StringEntityData; import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.event.entity.EntityExplosionPrimeEvent; import cn.nukkit.level.Explosion; @@ -9,14 +11,27 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -/** - * Created by PetteriM1 - */ public class EntityEndCrystal extends Entity implements EntityExplosive { public static final int NETWORK_ID = 71; - protected boolean detonated = false; + private boolean detonated = false; + private String nameTag; + + @Override + public float getLength() { + return 2f; + } + + @Override + public float getHeight() { + return 2f; + } + + @Override + public float getWidth() { + return 2f; + } @Override public int getNetworkId() { @@ -36,7 +51,6 @@ protected void initEntity() { } this.fireProof = true; - this.setDataFlag(DATA_FLAGS, DATA_FLAG_FIRE_IMMUNE, true); } @Override @@ -46,35 +60,45 @@ public void saveNBT() { this.namedTag.putBoolean("ShowBottom", this.showBase()); } - @Override - public float getHeight() { - return 0.98f; - } - - @Override - public float getWidth() { - return 0.98f; - } - @Override public boolean attack(EntityDamageEvent source) { - if (source.getCause() == EntityDamageEvent.DamageCause.FIRE || source.getCause() == EntityDamageEvent.DamageCause.FIRE_TICK || source.getCause() == EntityDamageEvent.DamageCause.LAVA) { + if (this.closed) { return false; } - if (!super.attack(source)) { + if (source.getCause() == EntityDamageEvent.DamageCause.FIRE || source.getCause() == EntityDamageEvent.DamageCause.FIRE_TICK || source.getCause() == EntityDamageEvent.DamageCause.LAVA || + (source.getCause() == EntityDamageEvent.DamageCause.ENTITY_ATTACK && source.getFinalDamage() < 0.8)) { + source.setCancelled(true); + } + + this.getServer().getPluginManager().callEvent(source); + if (source.isCancelled()) { return false; } - explode(); + this.setLastDamageCause(source); + + this.explode(); return true; } + @Override + public boolean canCollideWith(Entity entity) { + return true; + } + + public boolean showBase() { + return this.getDataFlag(DATA_FLAGS, DATA_FLAG_SHOWBASE); + } + + public void setShowBase(boolean value) { + this.setDataFlag(DATA_FLAGS, DATA_FLAG_SHOWBASE, value); + } + @Override public void explode() { this.close(); - if (!this.detonated && this.level.getGameRules().getBoolean(GameRule.MOB_GRIEFING)) { EntityExplosionPrimeEvent ev = new EntityExplosionPrimeEvent(this, 6); this.server.getPluginManager().callEvent(ev); @@ -85,6 +109,13 @@ public void explode() { this.detonated = true; Explosion explosion = new Explosion(this, (float) ev.getForce(), this); + + int floor = this.getFloorY(); + int down = this.level.getBlockIdAt(this.chunk, this.getFloorX(), floor - 1, this.getFloorZ()); + if (down == Block.BEDROCK || down == Block.OBSIDIAN) { + explosion.setMinHeight(floor); + } + if (ev.isBlockBreaking()) { explosion.explodeA(); } @@ -93,15 +124,50 @@ public void explode() { } @Override - public boolean canCollideWith(Entity entity) { - return false; + public String getName() { + return this.hasCustomName() ? this.getNameTag() : "End Crystal"; } - public boolean showBase() { - return this.getDataFlag(DATA_FLAGS, DATA_FLAG_SHOWBASE); + @Override + public void setNameTag(String name) { + this.nameTag = name; + if (this.namedTag.contains("CustomNameVisible") || this.namedTag.contains("CustomNameAlwaysVisible")) { // Hack: Vanilla: Disable client side name tag while keeping custom name in nbt + this.setDataProperty(new StringEntityData(DATA_NAMETAG, name)); + } } - public void setShowBase(boolean value) { - this.setDataFlag(DATA_FLAGS, DATA_FLAG_SHOWBASE, value); + @Override + public boolean hasCustomName() { + return this.nameTag != null; + } + + @Override + public String getNameTag() { + return this.nameTag == null ? "" : this.nameTag; + } + + @Override // Minimal + public boolean onUpdate(int currentTick) { + if (this.closed) { + return false; + } + + if (!this.isAlive() || this.y < (this.getLevel().getMinBlockY() - 16)) { + this.close(); + return false; + } + + int tickDiff = currentTick - this.lastUpdate; + if (tickDiff <= 0 && !this.justCreated) { + return false; + } + + this.minimalEntityTick(currentTick, tickDiff); + return false; + } + + @Override + public boolean ignoredAsSaveReason() { + return true; } } diff --git a/src/main/java/cn/nukkit/entity/item/EntityExpBottle.java b/src/main/java/cn/nukkit/entity/item/EntityExpBottle.java index 16963a25c9a..9ba9a4d6574 100644 --- a/src/main/java/cn/nukkit/entity/item/EntityExpBottle.java +++ b/src/main/java/cn/nukkit/entity/item/EntityExpBottle.java @@ -3,12 +3,10 @@ import cn.nukkit.entity.Entity; import cn.nukkit.entity.projectile.EntityProjectile; import cn.nukkit.level.format.FullChunk; -import cn.nukkit.level.particle.Particle; import cn.nukkit.level.particle.SpellParticle; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.network.protocol.LevelSoundEventPacket; - -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; /** * @author xtypr @@ -57,42 +55,33 @@ public EntityExpBottle(FullChunk chunk, CompoundTag nbt, Entity shootingEntity) @Override public boolean onUpdate(int currentTick) { - if (this.closed) { + if (this.age > 1200) { + this.close(); return false; } + boolean update = super.onUpdate(currentTick); - this.timing.startTiming(); - - boolean hasUpdate = super.onUpdate(currentTick); - - if (this.age > 1200) { - this.kill(); - hasUpdate = true; + if (this.closed) { + return false; } if (this.isCollided) { - this.kill(); + this.close(); this.dropXp(); - hasUpdate = true; + return false; } - - this.timing.stopTiming(); - - return hasUpdate; + return update; } @Override public void onCollideWithEntity(Entity entity) { - this.kill(); + this.close(); this.dropXp(); } public void dropXp() { - Particle particle2 = new SpellParticle(this, 0x00385dc6); - this.getLevel().addParticle(particle2); - this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_GLASS); - - this.getLevel().dropExpOrb(this, ThreadLocalRandom.current().nextInt(3, 12)); + this.getLevel().addParticle(new SpellParticle(this, 0x00385dc6)); + this.getLevel().dropExpOrb(this, Utils.rand(3, 12)); } } diff --git a/src/main/java/cn/nukkit/entity/item/EntityFallingBlock.java b/src/main/java/cn/nukkit/entity/item/EntityFallingBlock.java index 1d146ea97b0..9340c02849d 100644 --- a/src/main/java/cn/nukkit/entity/item/EntityFallingBlock.java +++ b/src/main/java/cn/nukkit/entity/item/EntityFallingBlock.java @@ -14,6 +14,7 @@ import cn.nukkit.level.GameRule; import cn.nukkit.level.GlobalBlockPalette; import cn.nukkit.level.format.FullChunk; +import cn.nukkit.math.BlockFace; import cn.nukkit.math.Vector3; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.network.protocol.LevelEventPacket; @@ -90,13 +91,12 @@ protected void initEntity() { } this.fireProof = true; - this.setDataFlag(DATA_FLAGS, DATA_FLAG_FIRE_IMMUNE, true); - setDataProperty(new IntEntityData(DATA_VARIANT, GlobalBlockPalette.getOrCreateRuntimeId(this.getBlock(), this.getDamage()))); + this.setDataProperty(new IntEntityData(DATA_VARIANT, GlobalBlockPalette.getOrCreateRuntimeId(this.blockId, this.damage))); } public boolean canCollideWith(Entity entity) { - return blockId == BlockID.ANVIL; + return blockId == BlockID.ANVIL || blockId == BlockID.POINTED_DRIPSTONE; } @Override @@ -106,13 +106,10 @@ public boolean attack(EntityDamageEvent source) { @Override public boolean onUpdate(int currentTick) { - if (closed) { return false; } - this.timing.startTiming(); - int tickDiff = currentTick - lastUpdate; if (tickDiff <= 0 && !justCreated) { return true; @@ -133,27 +130,25 @@ public boolean onUpdate(int currentTick) { motionY *= 1 - getDrag(); motionZ *= friction; - Vector3 pos = (new Vector3(x - 0.5, y, z - 0.5)).round(); - - if (onGround) { + if (onGround && !closed) { close(); - Block block = level.getBlock(pos); - Vector3 floorPos = (new Vector3(x - 0.5, y, z - 0.5)).floor(); - Block floorBlock = this.level.getBlock(floorPos); + Block floorBlock = level.getBlock(this.add(0, 0.0001, 0)); if (this.getBlock() == Block.SNOW_LAYER && floorBlock.getId() == Block.SNOW_LAYER && (floorBlock.getDamage() & 0x7) != 0x7) { int mergedHeight = (floorBlock.getDamage() & 0x7) + 1 + (this.getDamage() & 0x7) + 1; if (mergedHeight > 8) { EntityBlockChangeEvent event = new EntityBlockChangeEvent(this, floorBlock, Block.get(Block.SNOW_LAYER, 0x7)); this.server.getPluginManager().callEvent(event); + if (!event.isCancelled()) { - this.level.setBlock(floorPos, event.getTo(), true); + this.level.setBlock(floorBlock, event.getTo(), true); - Vector3 abovePos = floorPos.up(); + Vector3 abovePos = floorBlock.getSideVec(BlockFace.UP); Block aboveBlock = this.level.getBlock(abovePos); if (aboveBlock.getId() == Block.AIR) { - EntityBlockChangeEvent event2 = new EntityBlockChangeEvent(this, aboveBlock, Block.get(Block.SNOW_LAYER, mergedHeight - 8 - 1)); + EntityBlockChangeEvent event2 = new EntityBlockChangeEvent(this, aboveBlock, Block.get(Block.SNOW_LAYER, mergedHeight - 9)); // -8-1 this.server.getPluginManager().callEvent(event2); + if (!event2.isCancelled()) { this.level.setBlock(abovePos, event2.getTo(), true); } @@ -162,22 +157,31 @@ public boolean onUpdate(int currentTick) { } else { EntityBlockChangeEvent event = new EntityBlockChangeEvent(this, floorBlock, Block.get(Block.SNOW_LAYER, mergedHeight - 1)); this.server.getPluginManager().callEvent(event); + if (!event.isCancelled()) { - this.level.setBlock(floorPos, event.getTo(), true); + this.level.setBlock(floorBlock, event.getTo(), true); } } - } else if (block.getId() > 0 && block.isTransparent() && !block.canBeReplaced() || this.getBlock() == Block.SNOW_LAYER && block instanceof BlockLiquid) { + } else if ((floorBlock.isTransparent() && !floorBlock.canBeReplaced() || this.getBlock() == Block.SNOW_LAYER && floorBlock instanceof BlockLiquid)) { if (this.getBlock() != Block.SNOW_LAYER ? this.level.getGameRules().getBoolean(GameRule.DO_ENTITY_DROPS) : this.level.getGameRules().getBoolean(GameRule.DO_TILE_DROPS)) { - getLevel().dropItem(this, Block.get(this.getBlock(), this.getDamage()).toItem()); + getLevel().dropItem(this, Item.get(this.blockId, this.damage, 1)); } - } else { - EntityBlockChangeEvent event = new EntityBlockChangeEvent(this, block, Block.get(getBlock(), getDamage())); + } else if (floorBlock.canBeReplaced()) { + EntityBlockChangeEvent event = new EntityBlockChangeEvent(this, floorBlock, Block.get(blockId, damage)); server.getPluginManager().callEvent(event); + if (!event.isCancelled()) { - getLevel().setBlock(pos, event.getTo(), true); + int blockId = event.getTo().getId(); + if (blockId != Item.POINTED_DRIPSTONE) { + getLevel().setBlock(floorBlock, event.getTo(), true, true); + } - if (event.getTo().getId() == Item.ANVIL) { - getLevel().addLevelEvent(block, LevelEventPacket.EVENT_SOUND_ANVIL_FALL); + if (blockId == Item.ANVIL || blockId == Item.POINTED_DRIPSTONE) { + if (blockId == Item.ANVIL) { + this.getLevel().addLevelEvent(this, LevelEventPacket.EVENT_SOUND_ANVIL_FALL); + } else { + this.getLevel().dropItem(this, Block.get(blockId, event.getTo().getDamage()).toItem()); + } Entity[] e = level.getCollidingEntities(this.getBoundingBox(), this); for (Entity entity : e) { @@ -194,8 +198,6 @@ public boolean onUpdate(int currentTick) { updateMovement(); } - this.timing.stopTiming(); - return hasUpdate || !onGround || Math.abs(motionX) > 0.00001 || Math.abs(motionY) > 0.00001 || Math.abs(motionZ) > 0.00001; } diff --git a/src/main/java/cn/nukkit/entity/item/EntityFirework.java b/src/main/java/cn/nukkit/entity/item/EntityFirework.java index 88a9aa74733..c05282781bc 100644 --- a/src/main/java/cn/nukkit/entity/item/EntityFirework.java +++ b/src/main/java/cn/nukkit/entity/item/EntityFirework.java @@ -1,22 +1,21 @@ package cn.nukkit.entity.item; -import cn.nukkit.Server; import cn.nukkit.entity.Entity; -import cn.nukkit.entity.data.LongEntityData; import cn.nukkit.entity.data.NBTEntityData; -import cn.nukkit.entity.data.Vector3fEntityData; import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; +import cn.nukkit.event.entity.EntityExplosionPrimeEvent; import cn.nukkit.item.Item; import cn.nukkit.item.ItemFirework; +import cn.nukkit.level.Explosion; import cn.nukkit.level.format.FullChunk; -import cn.nukkit.math.Vector3f; import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.ListTag; +import cn.nukkit.nbt.tag.Tag; import cn.nukkit.network.protocol.EntityEventPacket; import cn.nukkit.network.protocol.LevelSoundEventPacket; -import java.util.Random; import java.util.concurrent.ThreadLocalRandom; /** @@ -26,30 +25,35 @@ public class EntityFirework extends Entity { public static final int NETWORK_ID = 72; - private int fireworkAge; private int lifetime; private Item firework; public EntityFirework(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); + } + + @Override + public void initEntity() { + super.initEntity(); - this.fireworkAge = 0; - Random rand = ThreadLocalRandom.current(); - this.lifetime = 30 + rand.nextInt(12); + ThreadLocalRandom rand = ThreadLocalRandom.current(); this.motionX = rand.nextGaussian() * 0.001D; this.motionZ = rand.nextGaussian() * 0.001D; this.motionY = 0.05D; - if (nbt.contains("FireworkItem")) { - firework = NBTIO.getItemHelper(nbt.getCompound("FireworkItem")); - } else { - firework = new ItemFirework(); + if (namedTag.contains("FireworkItem")) { + this.setFirework(NBTIO.getItemHelper(namedTag.getCompound("FireworkItem"))); } + } + + @Override + public void saveNBT() { + super.saveNBT(); - this.setDataProperty(new NBTEntityData(Entity.DATA_DISPLAY_ITEM, firework.getNamedTag())); - this.setDataProperty(new Vector3fEntityData(Entity.DATA_DISPLAY_OFFSET, new Vector3f(0, 1, 0))); - this.setDataProperty(new LongEntityData(Entity.DATA_HAS_DISPLAY, -1)); + if (this.firework != null) { + this.namedTag.putCompound("FireworkItem", NBTIO.putItemHelper(this.firework)); + } } @Override @@ -61,6 +65,9 @@ public int getNetworkId() { public boolean onUpdate(int currentTick) { if (this.closed) { return false; + } else if (this.age > this.lifetime) { + this.close(); + return false; } int tickDiff = currentTick - this.lastUpdate; @@ -71,51 +78,60 @@ public boolean onUpdate(int currentTick) { this.lastUpdate = currentTick; - this.timing.startTiming(); - - boolean hasUpdate = this.entityBaseTick(tickDiff); if (this.isAlive()) { - this.motionX *= 1.15D; this.motionZ *= 1.15D; this.motionY += 0.04D; + this.move(this.motionX, this.motionY, this.motionZ); this.updateMovement(); - float f = (float) Math.sqrt(this.motionX * this.motionX + this.motionZ * this.motionZ); - this.yaw = (float) (Math.atan2(this.motionX, this.motionZ) * (180D / Math.PI)); - - this.pitch = (float) (Math.atan2(this.motionY, f) * (180D / Math.PI)); - + this.yaw = (float) (Math.atan2(this.motionX, this.motionZ) * (57.29577951308232)); + this.pitch = (float) (Math.atan2(this.motionY, f) * (57.29577951308232)); - if (this.fireworkAge == 0) { + if (this.age == 0) { this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_LAUNCH); } - this.fireworkAge++; - - hasUpdate = true; - if (this.fireworkAge >= this.lifetime) { + if (this.age >= this.lifetime) { EntityEventPacket pk = new EntityEventPacket(); - pk.data = 0; pk.event = EntityEventPacket.FIREWORK_EXPLOSION; pk.eid = this.getId(); + this.level.addChunkPacket(this.getChunkX(), this.getChunkZ(), pk); + + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_LARGE_BLAST, -1, NETWORK_ID); + + if (this.firework != null) { + Tag nbt = this.firework.getNamedTag(); + if (nbt != null) { + nbt = ((CompoundTag) nbt).get("Fireworks"); + if (nbt instanceof CompoundTag) { + nbt = ((CompoundTag) nbt).get("Explosions"); + if (nbt instanceof ListTag) { + if (((ListTag) nbt).size() != 0) { + EntityExplosionPrimeEvent ev = new EntityExplosionPrimeEvent(this, 2.5); + ev.setBlockBreaking(false); + server.getPluginManager().callEvent(ev); + if (!ev.isCancelled()) { + Explosion explosion = new Explosion(this, ev.getForce(), this); + explosion.explodeEntity(); + } + } + } + } + } + } + + this.kill(); // Using close() here would remove the firework before the explosion is displayed - level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_LARGE_BLAST, -1, NETWORK_ID); - - Server.broadcastPacket(getViewers().values(), pk); - - this.kill(); hasUpdate = true; } } - this.timing.stopTiming(); - return hasUpdate || !this.onGround || Math.abs(this.motionX) > 0.00001 || Math.abs(this.motionY) > 0.00001 || Math.abs(this.motionZ) > 0.00001; } @@ -130,7 +146,11 @@ public boolean attack(EntityDamageEvent source) { public void setFirework(Item item) { this.firework = item; - this.setDataProperty(new NBTEntityData(Entity.DATA_DISPLAY_ITEM, item.getNamedTag())); + this.setDataProperty(new NBTEntityData(Entity.DATA_DISPLAY_ITEM, this.firework)); + + int level = Math.max(1, this.firework instanceof ItemFirework ? ((ItemFirework) this.firework).getFlight() : 1); // Level 1 minimum + ThreadLocalRandom rand = ThreadLocalRandom.current(); + this.lifetime = 10 * (level + 1) + rand.nextInt(5) + rand.nextInt(6); // Wiki } @Override @@ -142,4 +162,4 @@ public float getWidth() { public float getHeight() { return 0.25f; } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/entity/item/EntityFishingHook.java b/src/main/java/cn/nukkit/entity/item/EntityFishingHook.java index de9f2ab94fa..5f207eed56c 100644 --- a/src/main/java/cn/nukkit/entity/item/EntityFishingHook.java +++ b/src/main/java/cn/nukkit/entity/item/EntityFishingHook.java @@ -13,6 +13,9 @@ import cn.nukkit.event.entity.ProjectileHitEvent; import cn.nukkit.event.player.PlayerFishEvent; import cn.nukkit.item.Item; +import cn.nukkit.item.ItemBookEnchanted; +import cn.nukkit.item.ItemFishingRod; +import cn.nukkit.item.ItemTool; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.item.randomitem.Fishing; import cn.nukkit.level.MovingObjectPosition; @@ -25,295 +28,323 @@ import cn.nukkit.network.protocol.AddEntityPacket; import cn.nukkit.network.protocol.DataPacket; import cn.nukkit.network.protocol.EntityEventPacket; +import cn.nukkit.utils.Utils; import java.util.Collection; -import java.util.Random; import java.util.concurrent.ThreadLocalRandom; -/** - * Created by PetteriM1 - */ public class EntityFishingHook extends EntityProjectile { - public static final int NETWORK_ID = 77; - - public int waitChance = 120; - public int waitTimer = 240; - public boolean attracted = false; - public int attractTimer = 0; - public boolean caught = false; - public int caughtTimer = 0; - public boolean canCollide = true; - - public Vector3 fish = null; - - public Item rod = null; - - public EntityFishingHook(FullChunk chunk, CompoundTag nbt) { - this(chunk, nbt, null); - } - - public EntityFishingHook(FullChunk chunk, CompoundTag nbt, Entity shootingEntity) { - super(chunk, nbt, shootingEntity); - } - - @Override - protected void initEntity() { - super.initEntity(); - if (this.age > 0) { - this.close(); - } - } - - @Override - public int getNetworkId() { - return NETWORK_ID; - } - - @Override - public float getWidth() { - return 0.2f; - } - - @Override - public float getLength() { - return 0.2f; - } - - @Override - public float getHeight() { - return 0.2f; - } - - @Override - public float getGravity() { - return 0.07f; - } - - @Override - public float getDrag() { - return 0.05f; - } - - @Override - public boolean canCollide() { - return this.canCollide; - } - - @Override - public boolean onUpdate(int currentTick) { - boolean hasUpdate = super.onUpdate(currentTick); - - long target = this.getDataPropertyLong(DATA_TARGET_EID); - if (target != 0) { - Entity ent = level.getEntity(target); - if (ent == null || !ent.isAlive()) { - this.setTarget(0); - } else { - this.setPosition(new Vector3(ent.x, ent.y + (getHeight() * 0.75f), ent.z)); - } - hasUpdate = true; - } - - if (hasUpdate) { - return false; - } - - boolean inWater = this.isInsideOfWater(); - if (inWater) { - this.motionX = 0; - this.motionY -= getGravity() * -0.04; - this.motionZ = 0; - hasUpdate = true; - } else if (this.isCollided && this.keepMovement) { - this.motionX = 0; - this.motionY = 0; - this.motionZ = 0; - this.keepMovement = false; - hasUpdate = true; - } - - Random random = ThreadLocalRandom.current(); - - if (inWater) { - if (this.waitTimer == 240) { - this.waitTimer = this.waitChance << 1; - } else if (this.waitTimer == 360) { - this.waitTimer = this.waitChance * 3; - } - if (!this.attracted) { - if (this.waitTimer > 0) { - --this.waitTimer; - } - if (this.waitTimer == 0) { - if (random.nextInt(100) < 90) { - this.attractTimer = (random.nextInt(40) + 20); - this.spawnFish(); - this.caught = false; - this.attracted = true; - } else { - this.waitTimer = this.waitChance; - } - } - } else if (!this.caught) { - if (this.attractFish()) { - this.caughtTimer = (random.nextInt(20) + 30); - this.fishBites(); - this.caught = true; - } - } else { - if (this.caughtTimer > 0) { - --this.caughtTimer; - } - if (this.caughtTimer == 0) { - this.attracted = false; - this.caught = false; - this.waitTimer = this.waitChance * 3; - } - } - } - - return hasUpdate; - } - - public int getWaterHeight() { - for (int y = this.getFloorY(); y < 256; y++) { - int id = this.level.getBlockIdAt(this.getFloorX(), y, this.getFloorZ()); - if (id == Block.AIR) { - return y; - } - } - return this.getFloorY(); - } - - public void fishBites() { - Collection viewers = this.getViewers().values(); - - EntityEventPacket pk = new EntityEventPacket(); - pk.eid = this.getId(); - pk.event = EntityEventPacket.FISH_HOOK_HOOK; - Server.broadcastPacket(viewers, pk); - - EntityEventPacket bubblePk = new EntityEventPacket(); - bubblePk.eid = this.getId(); - bubblePk.event = EntityEventPacket.FISH_HOOK_BUBBLE; - Server.broadcastPacket(viewers, bubblePk); - - EntityEventPacket teasePk = new EntityEventPacket(); - teasePk.eid = this.getId(); - teasePk.event = EntityEventPacket.FISH_HOOK_TEASE; - Server.broadcastPacket(viewers, teasePk); - - Random random = ThreadLocalRandom.current(); - for (int i = 0; i < 5; i++) { - this.level.addParticle(new BubbleParticle(this.setComponents( - this.x + random.nextDouble() * 0.5 - 0.25, - this.getWaterHeight(), - this.z + random.nextDouble() * 0.5 - 0.25 - ))); - } - } - - public void spawnFish() { - Random random = ThreadLocalRandom.current(); - this.fish = new Vector3( - this.x + (random.nextDouble() * 1.2 + 1) * (random.nextBoolean() ? -1 : 1), - this.getWaterHeight(), - this.z + (random.nextDouble() * 1.2 + 1) * (random.nextBoolean() ? -1 : 1) - ); - } - - public boolean attractFish() { - double multiply = 0.1; - this.fish.setComponents( - this.fish.x + (this.x - this.fish.x) * multiply, - this.fish.y, - this.fish.z + (this.z - this.fish.z) * multiply - ); - if (ThreadLocalRandom.current().nextInt(100) < 85) { - this.level.addParticle(new WaterParticle(this.fish)); - } - double dist = Math.abs(Math.sqrt(this.x * this.x + this.z * this.z) - Math.sqrt(this.fish.x * this.fish.x + this.fish.z * this.fish.z)); - return dist < 0.15; - } - - public void reelLine() { - if (this.shootingEntity instanceof Player && this.caught) { - Player player = (Player) this.shootingEntity; - Item item = Fishing.getFishingResult(this.rod); - int experience = ThreadLocalRandom.current().nextInt(3) + 1; - Vector3 motion = player.subtract(this).multiply(0.1); - motion.y += Math.sqrt(player.distance(this)) * 0.08; - - PlayerFishEvent event = new PlayerFishEvent(player, this, item, experience, motion); - this.getServer().getPluginManager().callEvent(event); - - if (!event.isCancelled()) { - EntityItem itemEntity = new EntityItem( - this.level.getChunk((int) this.x >> 4, (int) this.z >> 4, true), - Entity.getDefaultNBT(new Vector3(this.x, this.getWaterHeight(), this.z), event.getMotion(), ThreadLocalRandom.current().nextFloat() * 360, 0).putShort("Health", 5).putCompound("Item", NBTIO.putItemHelper(event.getLoot())).putShort("PickupDelay", 1)); - - itemEntity.setOwner(player.getName()); - itemEntity.spawnToAll(); - - player.getLevel().dropExpOrb(player, event.getExperience()); - } - } - this.close(); - } - - @Override - protected DataPacket createAddEntityPacket() { - AddEntityPacket pk = new AddEntityPacket(); - pk.entityRuntimeId = this.getId(); - pk.entityUniqueId = this.getId(); - pk.type = NETWORK_ID; - pk.x = (float) this.x; - pk.y = (float) this.y; - pk.z = (float) this.z; - pk.speedX = (float) this.motionX; - pk.speedY = (float) this.motionY; - pk.speedZ = (float) this.motionZ; - pk.yaw = (float) this.yaw; - pk.pitch = (float) this.pitch; - - long ownerId = -1; - if (this.shootingEntity != null) { - ownerId = this.shootingEntity.getId(); - } - pk.metadata = this.dataProperties.putLong(DATA_OWNER_EID, ownerId); - return pk; - } - - @Override - public void onCollideWithEntity(Entity entity) { - this.server.getPluginManager().callEvent(new ProjectileHitEvent(this, MovingObjectPosition.fromEntity(entity))); - float damage = this.getResultDamage(); - - EntityDamageEvent ev; - if (this.shootingEntity == null) { - ev = new EntityDamageByEntityEvent(this, entity, DamageCause.PROJECTILE, damage); - } else { - ev = new EntityDamageByChildEntityEvent(this.shootingEntity, this, entity, DamageCause.PROJECTILE, damage); - } - - if (entity.attack(ev)) { - this.setTarget(entity.getId()); - } - } - - public void checkLure() { - if (rod != null) { - Enchantment ench = rod.getEnchantment(Enchantment.ID_LURE); - if (ench != null) { - this.waitChance = 120 - (25 * ench.getLevel()); - } - } - } - - public void setTarget(long eid) { - this.setDataProperty(new LongEntityData(DATA_TARGET_EID, eid)); - this.canCollide = eid == 0; - } + public static final int NETWORK_ID = 77; + + public int waitChance = 120; + public int waitTimer = 240; + public boolean attracted; + public int attractTimer; + public boolean caught; + public int caughtTimer; + public boolean canCollide = true; + public Entity caughtEntity; + private long target; + public Vector3 fish; + public Item rod; + + public EntityFishingHook(FullChunk chunk, CompoundTag nbt) { + this(chunk, nbt, null); + } + + public EntityFishingHook(FullChunk chunk, CompoundTag nbt, Entity shootingEntity) { + super(chunk, nbt, shootingEntity); + } + + @Override + protected void initEntity() { + super.initEntity(); + if (this.age > 0) { + this.close(); + } + } + + @Override + public int getNetworkId() { + return NETWORK_ID; + } + + @Override + public float getWidth() { + return 0.2f; + } + + @Override + public float getLength() { + return 0.2f; + } + + @Override + public float getHeight() { + return 0.2f; + } + + @Override + public float getGravity() { + return 0.07f; + } + + @Override + public float getDrag() { + return 0.05f; + } + + @Override + public boolean onUpdate(int currentTick) { + if (this.target != 0) { + Entity ent = this.level.getEntity(this.target); + if (ent == null || !ent.isAlive()) { + caughtEntity = null; + this.setTarget(0); + } else { + this.setPosition(ent.add(0, getHeight() * 0.75f, 0)); + } + return false; + } + + boolean hasUpdate = super.onUpdate(currentTick); + + boolean inWater = this.isInsideOfWater(); + if (inWater) { + this.motionX = 0; + this.motionY -= getGravity() * -0.04; + this.motionZ = 0; + hasUpdate = true; + } + + if (inWater) { + if (this.waitTimer == 240) { + this.waitTimer = this.waitChance << 1; + } else if (this.waitTimer == 360) { + this.waitTimer = this.waitChance * 3; + } + if (!this.attracted) { + if (this.waitTimer > 0) { + --this.waitTimer; + } + if (this.waitTimer == 0) { + if (Utils.random.nextInt(100) < 90) { + this.attractTimer = (Utils.random.nextInt(40) + 20); + this.spawnFish(); + this.caught = false; + this.attracted = true; + } else { + this.waitTimer = this.waitChance; + } + } + } else if (!this.caught) { + if (this.attractFish()) { + this.caughtTimer = (Utils.random.nextInt(20) + 30); + this.fishBites(); + this.caught = true; + } + } else { + if (this.caughtTimer > 0) { + --this.caughtTimer; + } + if (this.caughtTimer == 0) { + this.attracted = false; + this.caught = false; + this.waitTimer = this.waitChance * 3; + } + } + } + + return hasUpdate; + } + + public int getWaterHeight() { + for (int y = this.getFloorY(); y < level.getMaxBlockY(); y++) { + int id = this.level.getBlockIdAt(chunk, this.getFloorX(), y, this.getFloorZ()); + if (id == Block.AIR) { + return y; + } + } + return this.getFloorY(); + } + + public void fishBites() { + Collection viewers = this.getViewers().values(); + + EntityEventPacket pk = new EntityEventPacket(); + pk.eid = this.getId(); + pk.event = EntityEventPacket.FISH_HOOK_HOOK; + Server.broadcastPacket(viewers, pk); + + EntityEventPacket bubblePk = new EntityEventPacket(); + bubblePk.eid = this.getId(); + bubblePk.event = EntityEventPacket.FISH_HOOK_BUBBLE; + Server.broadcastPacket(viewers, bubblePk); + + EntityEventPacket teasePk = new EntityEventPacket(); + teasePk.eid = this.getId(); + teasePk.event = EntityEventPacket.FISH_HOOK_TEASE; + Server.broadcastPacket(viewers, teasePk); + + this.level.addParticle(new BubbleParticle(this.setComponents( + this.x + Utils.random.nextDouble() * 0.5 - 0.25, + this.getWaterHeight(), + this.z + Utils.random.nextDouble() * 0.5 - 0.25 + )), null, 5); + } + + public void spawnFish() { + this.fish = new Vector3( + this.x + (Utils.random.nextDouble() * 1.2 + 1) * (Utils.rand() ? -1 : 1), + this.getWaterHeight(), + this.z + (Utils.random.nextDouble() * 1.2 + 1) * (Utils.rand() ? -1 : 1) + ); + } + + public boolean attractFish() { + double multiply = 0.1; + this.fish.setComponents( + this.fish.x + (this.x - this.fish.x) * multiply, + this.fish.y, + this.fish.z + (this.z - this.fish.z) * multiply + ); + if (Utils.random.nextInt(100) < 85) { + this.level.addParticle(new WaterParticle(this.fish)); + } + double dist = Math.abs(Math.sqrt(this.x * this.x + this.z * this.z) - Math.sqrt(this.fish.x * this.fish.x + this.fish.z * this.fish.z)); + return dist < 0.15; + } + + private static final int[] ROD_ENCHANTMENTS = {Enchantment.ID_LURE, Enchantment.ID_FORTUNE_FISHING, Enchantment.ID_DURABILITY, Enchantment.ID_MENDING, Enchantment.ID_VANISHING_CURSE}; + + public void reelLine() { + if (this.shootingEntity instanceof Player && !this.closed) { + if (this.caught) { + Player player = (Player) this.shootingEntity; + Item item = Fishing.getFishingResult(this.rod); + if (item instanceof ItemTool) { + item.setDamage(Utils.rand(1, item.getMaxDurability() - 2)); + } + // TODO: improve loot selectors so this hack won't be needed + if (item instanceof ItemBookEnchanted) { + if (!item.hasEnchantments()) { + item = item.clone(); + Enchantment enchantment = Enchantment.getEnchantment(Utils.rand(0, 35)); + if (Utils.random.nextDouble() < 0.3) { + enchantment.setLevel(Utils.rand(1, enchantment.getMaxLevel())); + } + item.addEnchantment(enchantment); + } + } else if (item instanceof ItemFishingRod) { + if (Utils.rand(1, 3) == 2 && !item.hasEnchantments()) { + item = item.clone(); + Enchantment enchantment = Enchantment.getEnchantment(ROD_ENCHANTMENTS[Utils.rand(0, 4)]); + if (Utils.random.nextDouble() < 0.3) { + enchantment.setLevel(Utils.rand(1, enchantment.getMaxLevel())); + } + item.addEnchantment(enchantment); + } + } + int experience = Utils.random.nextInt(3) + 1; + Vector3 motion = player.subtract(this).multiply(0.1); + motion.y += Math.sqrt(player.distance(this)) * 0.05; + + PlayerFishEvent event = new PlayerFishEvent(player, this, item, experience, motion); + this.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + EntityItem itemEntity = (EntityItem) Entity.createEntity(EntityItem.NETWORK_ID, + this.level.getChunk(this.getChunkX(), this.getChunkZ(), true), + Entity.getDefaultNBT(new Vector3(this.x, this.getWaterHeight(), this.z), event.getMotion(), ThreadLocalRandom.current().nextFloat() * 360, 0).putShort("Health", 5).putCompound("Item", NBTIO.putItemHelper(event.getLoot())).putShort("PickupDelay", 1)); + + itemEntity.setOwner(player.getName()); + itemEntity.spawnToAll(); + + player.getLevel().dropExpOrb(player, event.getExperience()); + } + } + if (this.caughtEntity != null) { + Vector3 motion = this.shootingEntity.subtract(this).multiply(0.1); + motion.y += Math.sqrt(this.shootingEntity.distance(this)) * 0.08; + this.caughtEntity.setMotion(motion); + } + } + this.close(); + } + + @Override + protected DataPacket createAddEntityPacket() { + AddEntityPacket pk = new AddEntityPacket(); + pk.entityRuntimeId = this.getId(); + pk.entityUniqueId = this.getId(); + pk.type = NETWORK_ID; + pk.x = (float) this.x; + pk.y = (float) this.y; + pk.z = (float) this.z; + pk.speedX = (float) this.motionX; + pk.speedY = (float) this.motionY; + pk.speedZ = (float) this.motionZ; + pk.yaw = (float) this.yaw; + pk.pitch = (float) this.pitch; + + long ownerId = -1; + if (this.shootingEntity != null) { + ownerId = this.shootingEntity.getId(); + } + pk.metadata = this.dataProperties.putLong(DATA_OWNER_EID, ownerId).clone(); + return pk; + } + + @Override + public boolean canCollide() { + return this.canCollide; + } + + @Override + public void onCollideWithEntity(Entity entity) { + if (entity == this.shootingEntity) { + return; + } + + this.server.getPluginManager().callEvent(new ProjectileHitEvent(this, MovingObjectPosition.fromEntity(entity))); + float damage = this.getResultDamage(); + + EntityDamageEvent ev; + if (this.shootingEntity == null) { + ev = new EntityDamageByEntityEvent(this, entity, DamageCause.PROJECTILE, damage, knockBack); + } else { + ev = new EntityDamageByChildEntityEvent(this.shootingEntity, this, entity, DamageCause.PROJECTILE, damage, knockBack); + } + + if (entity.attack(ev)) { + this.caughtEntity = entity; + this.setTarget(entity.getId()); + } + } + + public void checkLure() { + if (rod != null) { + Enchantment ench = rod.getEnchantment(Enchantment.ID_LURE); + if (ench != null) { + this.waitChance = 120 - (25 * ench.getLevel()); + } + } + } + + public void setTarget(long eid) { + this.target = eid; + this.setDataProperty(new LongEntityData(DATA_TARGET_EID, eid)); + this.canCollide = eid == 0; + } + + public long getTarget() { + return this.target; + } + + @Override + public boolean canSaveToStorage() { + return false; + } } diff --git a/src/main/java/cn/nukkit/entity/item/EntityItem.java b/src/main/java/cn/nukkit/entity/item/EntityItem.java index 86d7f5257c4..e2f1b0a41e2 100644 --- a/src/main/java/cn/nukkit/entity/item/EntityItem.java +++ b/src/main/java/cn/nukkit/entity/item/EntityItem.java @@ -1,9 +1,11 @@ package cn.nukkit.entity.item; +import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.block.Block; import cn.nukkit.block.BlockID; import cn.nukkit.entity.Entity; +import cn.nukkit.event.entity.EntityDamageByBlockEvent; import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; import cn.nukkit.event.entity.ItemDespawnEvent; @@ -24,9 +26,19 @@ public class EntityItem extends Entity { public static final int NETWORK_ID = 64; + protected String owner; + protected String thrower; + protected Item item; + protected int pickupDelay; + protected boolean floatsInLava; + public Player droppedBy; + + private boolean deadOnceAndForAll; public EntityItem(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); + + this.updateMode = 5; } @Override @@ -34,14 +46,6 @@ public int getNetworkId() { return NETWORK_ID; } - protected String owner; - protected String thrower; - - protected Item item; - - protected int pickupDelay; - protected boolean floatsInLava; - @Override public float getWidth() { return 0.25f; @@ -79,10 +83,15 @@ public boolean canCollide() { @Override protected void initEntity() { + this.setMaxHealth(5); + super.initEntity(); - this.setMaxHealth(5); - this.setHealth(this.namedTag.getShort("Health")); + if (namedTag.contains("Health")) { + this.setHealth(namedTag.getShort("Health")); + } else { + this.setHealth(5); + } if (this.namedTag.contains("Age")) { this.age = this.namedTag.getShort("Age"); @@ -105,8 +114,13 @@ protected void initEntity() { return; } - this.item = NBTIO.getItemHelper(this.namedTag.getCompound("Item")); - this.setDataFlag(DATA_FLAGS, DATA_FLAG_GRAVITY, true); + try { + this.item = NBTIO.getItemHelper(this.namedTag.getCompound("Item")); + } catch (Exception ex) { + server.getLogger().error("Item couldn't be loaded", ex); + this.close(); + return; + } int id = this.item.getId(); if (id >= Item.NETHERITE_INGOT && id <= Item.NETHERITE_SCRAP) { @@ -123,9 +137,10 @@ public boolean attack(EntityDamageEvent source) { if ((cause == DamageCause.VOID || cause == DamageCause.CONTACT || cause == DamageCause.FIRE_TICK || (cause == DamageCause.ENTITY_EXPLOSION || cause == DamageCause.BLOCK_EXPLOSION) && !this.isInsideOfWater() && (this.item == null || this.item.getId() != Item.NETHER_STAR)) && super.attack(source)) { - if (this.item == null || this.isAlive()) { + if (this.item == null || this.isAlive() || this.deadOnceAndForAll) { return true; } + this.deadOnceAndForAll = true; int id = this.item.getId(); if (id != Item.SHULKER_BOX && id != Item.UNDYED_SHULKER_BOX) { return true; @@ -155,49 +170,22 @@ public boolean onUpdate(int currentTick) { } int tickDiff = currentTick - this.lastUpdate; - if (tickDiff <= 0 && !this.justCreated) { return true; } - this.lastUpdate = currentTick; - - this.timing.startTiming(); - - if (this.age % 60 == 0 && this.onGround && this.getItem() != null && this.isAlive()) { - if (this.getItem().getCount() < this.getItem().getMaxStackSize()) { - for (Entity entity : this.getLevel().getNearbyEntities(getBoundingBox().grow(1, 1, 1), this, false)) { - if (entity instanceof EntityItem) { - if (!entity.isAlive()) { - continue; - } - Item closeItem = ((EntityItem) entity).getItem(); - if (!closeItem.equals(getItem(), true, true)) { - continue; - } - if (!entity.isOnGround()) { - continue; - } - int newAmount = this.getItem().getCount() + closeItem.getCount(); - if (newAmount > this.getItem().getMaxStackSize()) { - continue; - } - entity.close(); - this.getItem().setCount(newAmount); - EntityEventPacket packet = new EntityEventPacket(); - packet.eid = getId(); - packet.data = newAmount; - packet.event = EntityEventPacket.MERGE_ITEMS; - Server.broadcastPacket(this.getViewers().values(), packet); - } - } - } - } + this.minimalEntityTick(currentTick, tickDiff); - boolean hasUpdate = this.entityBaseTick(tickDiff); + if (this.age > 6000) { + ItemDespawnEvent ev = new ItemDespawnEvent(this); + this.server.getPluginManager().callEvent(ev); - if (!this.fireProof && this.isInsideOfFire()) { - this.kill(); + if (ev.isCancelled()) { + this.age = 0; + } else { + this.close(); + return false; + } } if (this.isAlive()) { @@ -206,34 +194,108 @@ public boolean onUpdate(int currentTick) { if (this.pickupDelay < 0) { this.pickupDelay = 0; } - }/* else { // Done in Player#checkNearEntities - for (Entity entity : this.level.getNearbyEntities(this.boundingBox.grow(1, 0.5, 1), this)) { - if (entity instanceof Player) { - if (((Player) entity).pickupEntity(this, true)) { - return true; + } + + // updateMode % 3 or age % 20 basically means on every reduced update, don't use updateMode % 2 because that would include every update with default updateMode + if (this.onGround && this.item != null && (this.updateMode % 3 == 1 || this.age % 20 == 0)) { + if (this.item.getCount() < this.item.getMaxStackSize()) { + Entity[] e = this.getLevel().getNearbyEntities(getBoundingBox().grow(1, 1, 1), this); + + for (Entity entity : e) { + if (entity instanceof EntityItem) { + if (entity.closed || !entity.isAlive() || !entity.isOnGround()) { + continue; + } + Item closeItem = ((EntityItem) entity).getItem(); + if (!closeItem.equals(item, true, true)) { + continue; + } + int newAmount = this.item.getCount() + closeItem.getCount(); + if (newAmount > this.item.getMaxStackSize()) { + continue; + } + closeItem.setCount(0); + entity.close(); + this.item.setCount(newAmount); + EntityEventPacket packet = new EntityEventPacket(); + packet.eid = getId(); + packet.data = newAmount; + packet.event = EntityEventPacket.MERGE_ITEMS; + Server.broadcastPacket(this.getViewers().values(), packet); + } + if (this.item.getCount() >= this.item.getMaxStackSize()) { + break; } } } - }*/ + } - int bid = level.getBlock(this.getFloorX(), NukkitMath.floorDouble(this.y + 0.53), this.getFloorZ(), false).getId(); - if (bid == BlockID.WATER || bid == BlockID.STILL_WATER || - (this.floatsInLava && (bid == Block.LAVA || bid == Block.STILL_LAVA))) { + int blockId; + if (this.isOnGround()) { + this.motionY = 0; + } else if (Block.isWater((blockId = level.getBlockIdAt(this.chunk, this.getFloorX(), NukkitMath.floorDouble(this.y + 0.53), this.getFloorZ()))) || + (this.floatsInLava && (blockId == Block.LAVA || blockId == Block.STILL_LAVA))) { this.motionY = this.getGravity() / 2; - } else if (!this.isOnGround()) { + } else { this.motionY -= this.getGravity(); } - if (this.checkObstruction(this.x, this.y, this.z)) { - hasUpdate = true; + this.checkBlockCollision(); + + this.checkObstruction(this.x, this.y, this.z); + + // Check nearby blocks changed + if (this.updateMode % 3 == 1) { + this.updateMode = 5; + + // Force check for nearby blocks changed even if not moving + if (this.motionY == 0) { + this.motionY = 0.00001; + } + + if (!this.fireProof) { // Fix missed collisions + Block block = level.getBlock(this.chunk, this.getFloorX(), this.getFloorY(), this.getFloorZ(), false); + int bid = block.getId(); + if (bid == BlockID.FIRE || bid == BlockID.SOUL_FIRE || bid == BlockID.LAVA || bid == BlockID.STILL_LAVA) { + this.attack(new EntityDamageByBlockEvent(block, this, DamageCause.FIRE, 1)); + } else if (bid == BlockID.CACTUS) { + this.attack(new EntityDamageByBlockEvent(block, this, DamageCause.CONTACT, 1)); + return true; + } + } + } + + // Flowing water + if (this.move(this.motionX, this.motionY, this.motionZ) && !(this.motionX == 0 && this.motionZ == 0)) { + this.collisionBlocks = null; } - this.move(this.motionX, this.motionY, this.motionZ); + if (this.y < (this.getLevel().getMinBlockY() - 16)) { + this.attack(new EntityDamageEvent(this, DamageCause.VOID, 10)); + } - double friction = 1 - this.getDrag(); + if (this.fireTicks > 0) { + if (this.fireProof) { + this.fireTicks -= tickDiff << 2; + if (this.fireTicks < 0) { + this.fireTicks = 0; + } + } else { + if (((this.fireTicks % 20) == 0 || tickDiff > 20)) { + this.attack(new EntityDamageEvent(this, DamageCause.FIRE_TICK, 1)); + } + this.fireTicks -= tickDiff; + } + if (this.fireTicks <= 0) { + this.extinguish(); + } else if (!this.fireProof) { + this.setDataFlag(DATA_FLAGS, DATA_FLAG_ONFIRE, true); + } + } + double friction = 1 - this.getDrag(); if (this.onGround && (Math.abs(this.motionX) > 0.00001 || Math.abs(this.motionZ) > 0.00001)) { - friction *= this.getLevel().getBlock(this.temporalVector.setComponents((int) Math.floor(this.x), (int) Math.floor(this.y - 1), (int) Math.floor(this.z) - 1)).getFrictionFactor(); + friction *= this.getLevel().getBlock(this.chunk, getFloorX(), getFloorY() - 1, getFloorZ(), false).getFrictionFactor(); } this.motionX *= friction; @@ -241,26 +303,18 @@ public boolean onUpdate(int currentTick) { this.motionZ *= friction; if (this.onGround) { - this.motionY *= -0.5; + this.motionY = 0; } this.updateMovement(); - - if (this.age > 6000) { - ItemDespawnEvent ev = new ItemDespawnEvent(this); - this.server.getPluginManager().callEvent(ev); - if (ev.isCancelled()) { - this.age = 0; - } else { - this.kill(); - hasUpdate = true; - } - } } - this.timing.stopTiming(); + if (!this.isAlive()) { + this.close(); + return false; + } - return hasUpdate || !this.onGround || Math.abs(this.motionX) > 0.00001 || Math.abs(this.motionY) > 0.00001 || Math.abs(this.motionZ) > 0.00001; + return !(this.motionX == 0 && this.motionY == 0 && this.motionZ == 0); } @Override @@ -283,7 +337,7 @@ public void saveNBT() { @Override public String getName() { - return this.hasCustomName() ? this.getNameTag() : (this.item == null ? "" : this.item.hasCustomName() ? this.item.getCustomName() : this.item.getName()); + return this.hasCustomName() ? this.getNameTag() : (this.item.hasCustomName() ? this.item.getCustomName() : this.item.getName()); } public Item getItem() { @@ -330,13 +384,8 @@ public DataPacket createAddEntityPacket() { addEntity.speedX = (float) this.motionX; addEntity.speedY = (float) this.motionY; addEntity.speedZ = (float) this.motionZ; - addEntity.metadata = this.dataProperties; - addEntity.item = this.getItem(); + addEntity.metadata = this.dataProperties.clone(); + addEntity.item = this.item; return addEntity; } - - @Override - public boolean doesTriggerPressurePlate() { - return true; - } } diff --git a/src/main/java/cn/nukkit/entity/item/EntityMinecartAbstract.java b/src/main/java/cn/nukkit/entity/item/EntityMinecartAbstract.java index dfeabbcf52d..4358c340cc3 100644 --- a/src/main/java/cn/nukkit/entity/item/EntityMinecartAbstract.java +++ b/src/main/java/cn/nukkit/entity/item/EntityMinecartAbstract.java @@ -1,15 +1,11 @@ package cn.nukkit.entity.item; import cn.nukkit.Player; -import cn.nukkit.api.API; -import cn.nukkit.api.API.Definition; -import cn.nukkit.api.API.Usage; -import cn.nukkit.block.Block; -import cn.nukkit.block.BlockRail; -import cn.nukkit.block.BlockRailActivator; -import cn.nukkit.block.BlockRailPowered; +import cn.nukkit.block.*; +import cn.nukkit.blockentity.BlockEntity; +import cn.nukkit.blockentity.BlockEntityHopper; import cn.nukkit.entity.Entity; -import cn.nukkit.entity.EntityHuman; +import cn.nukkit.entity.EntityControllable; import cn.nukkit.entity.EntityLiving; import cn.nukkit.entity.data.ByteEntityData; import cn.nukkit.entity.data.IntEntityData; @@ -17,19 +13,18 @@ import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.event.vehicle.VehicleMoveEvent; import cn.nukkit.event.vehicle.VehicleUpdateEvent; +import cn.nukkit.inventory.InventoryHolder; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemMinecart; import cn.nukkit.level.GameRule; import cn.nukkit.level.Location; import cn.nukkit.level.format.FullChunk; -import cn.nukkit.math.MathHelper; -import cn.nukkit.math.NukkitMath; -import cn.nukkit.math.Vector3; +import cn.nukkit.math.*; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.utils.MinecartType; import cn.nukkit.utils.Rail; import cn.nukkit.utils.Rail.Orientation; +import java.util.ArrayList; import java.util.Iterator; import java.util.Objects; @@ -40,9 +35,10 @@ * Minecart and Riding Project, * Package cn.nukkit.entity.item in project Nukkit. */ -public abstract class EntityMinecartAbstract extends EntityVehicle { +public abstract class EntityMinecartAbstract extends EntityVehicle implements EntityControllable { - private static final int[][][] matrix = new int[][][]{ + private String entityName; + private static final int[][][] matrix = { {{0, 0, -1}, {0, 0, 1}}, {{-1, 0, 0}, {1, 0, 0}}, {{-1, -1, 0}, {1, 0, 0}}, @@ -65,7 +61,6 @@ public abstract class EntityMinecartAbstract extends EntityVehicle { private double flyingY = 0.95; private double flyingZ = 0.95; private double maxSpeed = 0.4D; - private final boolean devs = false; // Avoid maintained features into production public abstract MinecartType getType(); @@ -73,9 +68,6 @@ public abstract class EntityMinecartAbstract extends EntityVehicle { public EntityMinecartAbstract(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); - - setMaxHealth(40); - setHealth(40); } @Override @@ -93,21 +85,37 @@ protected float getDrag() { return 0.1F; } + public void setName(String name) { + entityName = name; + } + + @Override + public String getName() { + return entityName; + } + @Override public float getBaseOffset() { return 0.35F; } + @Override + public boolean hasCustomName() { + return entityName != null; + } + @Override public boolean canDoInteraction() { - return passengers.isEmpty() && this.getDisplayBlock() == null; + return passengers.isEmpty() && this.blockInside == null; } @Override public void initEntity() { + this.setMaxHealth(40); super.initEntity(); - prepareDataProperty(); + this.setHealth(40); + //this.prepareDataProperty(); // TODO: DATA_DISPLAY_ITEM NBTEntityData } @Override @@ -117,25 +125,27 @@ public boolean onUpdate(int currentTick) { } if (!this.isAlive()) { - ++this.deadTicks; - if (this.deadTicks >= 10) { - this.despawnFromAll(); - this.close(); - } - return this.deadTicks < 10; + this.despawnFromAll(); + this.close(); + return false; } int tickDiff = currentTick - this.lastUpdate; - - if (tickDiff <= 0) { - return false; + if (tickDiff <= 0 && !this.justCreated) { + return true; } - this.lastUpdate = currentTick; + boolean firstTick = this.justCreated; + + this.minimalEntityTick(currentTick, tickDiff); if (isAlive()) { super.onUpdate(currentTick); + if (this.closed) { + return false; + } + // The damage token if (getHealth() < 20) { setHealth(getHealth() + 1); @@ -145,7 +155,7 @@ public boolean onUpdate(int currentTick) { lastX = x; lastY = y; lastZ = z; - motionY -= 0.03999999910593033D; + motionY -= 0.04; int dx = MathHelper.floor(x); int dy = MathHelper.floor(y); int dz = MathHelper.floor(z); @@ -155,7 +165,7 @@ public boolean onUpdate(int currentTick) { --dy; } - Block block = level.getBlock(new Vector3(dx, dy, dz)); + Block block = level.getBlock(chunk, dx, dy, dz, true); // Ensure that the block is a rail if (Rail.isRailBlock(block)) { @@ -196,9 +206,11 @@ public boolean onUpdate(int currentTick) { } // Collisions - for (cn.nukkit.entity.Entity entity : level.getNearbyEntities(boundingBox.grow(0.2D, 0, 0.2D), this)) { - if (!passengers.contains(entity) && entity instanceof EntityMinecartAbstract) { - entity.applyEntityCollision(this); + if (this instanceof InventoryHolder) { + for (cn.nukkit.entity.Entity entity : level.getNearbyEntities(boundingBox.grow(0.2D, 0, 0.2D), this)) { + if (entity instanceof EntityMinecartAbstract && !passengers.contains(entity)) { + entity.applyEntityCollision(this); + } } } @@ -216,8 +228,39 @@ public boolean onUpdate(int currentTick) { } } - // No need to onGround or Motion diff! This always have an update - return true; + if (this instanceof InventoryHolder) { + AxisAlignedBB pickupArea = new SimpleAxisAlignedBB(this.x, this.y - 1, this.z, this.x + 1, this.y, this.z + 1); + Block[] hopperPickupArray = this.level.getCollisionBlocks(this, pickupArea, false); + if (hopperPickupArray.length >= 1) { + Block hopper = hopperPickupArray[0]; + if (hopper instanceof BlockHopper) { + BlockEntity hopperBE = hopper.getLevel().getBlockEntityIfLoaded(hopper); + if (hopperBE instanceof BlockEntityHopper) { + ((BlockEntityHopper) hopperBE).setMinecartPickupInventory((InventoryHolder) this); + } + } + return true; + } + + if (!(this instanceof EntityMinecartHopper)) { + AxisAlignedBB pushArea = new SimpleAxisAlignedBB(this.x, this.y, this.z, this.x + 1, this.y + 2, this.z + 1); + Block[] hopperPushArray = this.level.getCollisionBlocks(this, pushArea, false); + if (hopperPushArray.length >= 1) { + Block hopper = hopperPushArray[0]; + if (hopper instanceof BlockHopper) { + BlockEntity hopperBE = hopper.getLevel().getBlockEntityIfLoaded(hopper); + if (hopperBE instanceof BlockEntityHopper) { + ((BlockEntityHopper) hopperBE).setMinecartPushInventory((InventoryHolder) this); + } + } + return true; + } + } + } + + this.updateMovement(); + + return firstTick || this.getRollingAmplitude() > 0 || !this.passengers.isEmpty() || !(this.motionX == 0 && this.motionY == 0 && this.motionZ == 0); } return false; @@ -247,15 +290,19 @@ public void dropItem() { return; } } - level.dropItem(this, new ItemMinecart()); + this.level.dropItem(this, Item.get(Item.MINECART)); } @Override public void kill() { + if (!this.isAlive()) { + return; + } + super.kill(); if (level.getGameRules().getBoolean(GameRule.DO_ENTITY_DROPS)) { - dropItem(); + this.dropItem(); } } @@ -263,16 +310,21 @@ public void kill() { public void close() { super.close(); - for (cn.nukkit.entity.Entity entity : passengers) { - if (entity instanceof Player) { - entity.riding = null; + if (!passengers.isEmpty()) { + for (Entity passenger : new ArrayList<>(passengers)) { + dismountEntity(passenger); + passenger.riding = null; // Make sure it's really removed even if a plugin tries to cancel it } } } @Override public boolean onInteract(Player p, Item item, Vector3 clickedPos) { - if (!passengers.isEmpty() && isRideable()) { + if (!isRideable()) { + return false; + } + + if (!passengers.isEmpty()) { return false; } @@ -285,18 +337,7 @@ public boolean onInteract(Player p, Item item, Vector3 clickedPos) { @Override public void applyEntityCollision(cn.nukkit.entity.Entity entity) { - if (entity != riding && !(entity instanceof Player && ((Player) entity).isSpectator())) { - if (entity instanceof EntityLiving - && !(entity instanceof EntityHuman) - && motionX * motionX + motionZ * motionZ > 0.01D - && passengers.isEmpty() - && entity.riding == null - && blockInside == null) { - if (riding == null && devs) { - mountEntity(entity);// TODO: rewrite (weird riding) - } - } - + if (entity != riding && !(entity instanceof Player && ((Player) entity).getGamemode() == Player.SPECTATOR)) { double motiveX = entity.x - x; double motiveZ = entity.z - z; double square = motiveX * motiveX + motiveZ * motiveZ; @@ -385,8 +426,8 @@ protected void activate(int x, int y, int z, boolean flag) { private boolean hasUpdated = false; private void setFalling() { - motionX = NukkitMath.clamp(motionX, -getMaxSpeed(), getMaxSpeed()); - motionZ = NukkitMath.clamp(motionZ, -getMaxSpeed(), getMaxSpeed()); + motionX = NukkitMath.clamp(motionX, -maxSpeed, maxSpeed); + motionZ = NukkitMath.clamp(motionZ, -maxSpeed, maxSpeed); if (!hasUpdated) { for (cn.nukkit.entity.Entity linked : passengers) { @@ -411,11 +452,13 @@ private void setFalling() { } } + private final Vector3 tempMoveVec = new Vector3(0, 0, 0); + private void processMovement(int dx, int dy, int dz, BlockRail block) { fallDistance = 0.0F; Vector3 vector = getNextRail(x, y, z); - y = dy; + int y = dy; boolean isPowered = false; boolean isSlowed = false; @@ -510,10 +553,10 @@ private void processMovement(int dx, int dy, int dz, BlockRail block) { double motZ; if (facing1 == 0) { - x = (double) dx + 0.5D; + //x = (double) dx + 0.5D; expectedSpeed = z - (double) dz; } else if (facing2 == 0) { - z = (double) dz + 0.5D; + //z = (double) dz + 0.5D; expectedSpeed = x - (double) dx; } else { motX = x - playerYawNeg; @@ -523,7 +566,8 @@ private void processMovement(int dx, int dy, int dz, BlockRail block) { x = playerYawNeg + facing1 * expectedSpeed; z = playerYawPos + facing2 * expectedSpeed; - setPosition(new Vector3(x, y, z)); // Hehe, my minstake :3 + this.y = y; // Idk why we set these before setPosition + setPosition(tempMoveVec.setComponents(x, y, z)); motX = motionX; motZ = motionZ; @@ -531,14 +575,14 @@ private void processMovement(int dx, int dy, int dz, BlockRail block) { motX *= 0.75D; motZ *= 0.75D; } - motX = NukkitMath.clamp(motX, -getMaxSpeed(), getMaxSpeed()); - motZ = NukkitMath.clamp(motZ, -getMaxSpeed(), getMaxSpeed()); + motX = NukkitMath.clamp(motX, -maxSpeed, maxSpeed); + motZ = NukkitMath.clamp(motZ, -maxSpeed, maxSpeed); move(motX, 0, motZ); if (facing[0][1] != 0 && MathHelper.floor(x) - dx == facing[0][0] && MathHelper.floor(z) - dz == facing[0][2]) { - setPosition(new Vector3(x, y + (double) facing[0][1], z)); + setPosition(tempMoveVec.setComponents(x, y + (double) facing[0][1], z)); } else if (facing[1][1] != 0 && MathHelper.floor(x) - dx == facing[1][0] && MathHelper.floor(z) - dz == facing[1][2]) { - setPosition(new Vector3(x, y + (double) facing[1][1], z)); + setPosition(tempMoveVec.setComponents(x, y + (double) facing[1][1], z)); } applyDrag(); @@ -553,7 +597,7 @@ private void processMovement(int dx, int dy, int dz, BlockRail block) { motionZ = motionZ / squareOfFame * (squareOfFame + d14); } - setPosition(new Vector3(x, vector1.y, z)); + setPosition(tempMoveVec.setComponents(x, vector1.y, z)); } int floorX = MathHelper.floor(x); @@ -574,20 +618,19 @@ private void processMovement(int dx, int dy, int dz, BlockRail block) { motionX += motionX / newMovie * nextMovie; motionZ += motionZ / newMovie * nextMovie; } else if (block.getOrientation() == Orientation.STRAIGHT_NORTH_SOUTH) { - if (level.getBlock(new Vector3(dx - 1, dy, dz)).isNormalBlock()) { + if (level.getBlock(chunk, dx - 1, dy, dz, true).isNormalBlock()) { motionX = 0.02D; - } else if (level.getBlock(new Vector3(dx + 1, dy, dz)).isNormalBlock()) { - motionX = -0.02D; + } else if (level.getBlock(chunk, dx + 1, dy, dz, true).isNormalBlock()) { + motionX = -0.02; } } else if (block.getOrientation() == Orientation.STRAIGHT_EAST_WEST) { - if (level.getBlock(new Vector3(dx, dy, dz - 1)).isNormalBlock()) { + if (level.getBlock(chunk, dx, dy, dz - 1, true).isNormalBlock()) { motionZ = 0.02D; - } else if (level.getBlock(new Vector3(dx, dy, dz + 1)).isNormalBlock()) { - motionZ = -0.02D; + } else if (level.getBlock(chunk, dx, dy, dz + 1, true).isNormalBlock()) { + motionZ = -0.02; } } } - } private void applyDrag() { @@ -611,7 +654,7 @@ private Vector3 getNextRail(double dx, double dy, double dz) { --checkY; } - Block block = level.getBlock(new Vector3(checkX, checkY, checkZ)); + Block block = level.getBlock(chunk, checkX, checkY, checkZ, true); if (Rail.isRailBlock(block)) { int[][] facing = matrix[((BlockRail) block).getRealMeta()]; @@ -655,16 +698,21 @@ private Vector3 getNextRail(double dx, double dy, double dz) { } } + @Override + public void onPlayerInput(Player player, double strafe, double forward) { + this.setCurrentSpeed(forward); + } + /** * Used to multiply the minecart current speed * * @param speed The speed of the minecart that will be calculated */ public void setCurrentSpeed(double speed) { - currentSpeed = speed; + this.currentSpeed = speed; } - private void prepareDataProperty() { + /*private void prepareDataProperty() { setRollingAmplitude(0); setRollingDirection(1); if (namedTag.contains("CustomDisplayTile")) { @@ -687,17 +735,15 @@ private void prepareDataProperty() { setDataProperty(new IntEntityData(DATA_DISPLAY_ITEM, display)); setDataProperty(new IntEntityData(DATA_DISPLAY_OFFSET, 6)); } - } + }*/ private void saveEntityData() { - boolean hasDisplay = super.getDataPropertyByte(DATA_HAS_DISPLAY) == 1 - || blockInside != null; + boolean hasDisplay = super.getDataPropertyByte(DATA_HAS_DISPLAY) == 1 || blockInside != null; int display; int offSet; namedTag.putBoolean("CustomDisplayTile", hasDisplay); if (hasDisplay) { - display = blockInside.getId() - | blockInside.getDamage() << 16; + display = blockInside.getId() | blockInside.getDamage() << 16; offSet = getDataPropertyInt(DATA_DISPLAY_OFFSET); namedTag.putInt("DisplayTile", display); namedTag.putInt("DisplayOffset", offSet); @@ -710,7 +756,7 @@ private void saveEntityData() { * @param block The block that will changed. Set {@code null} for BlockAir * @return {@code true} if the block is normal block */ - public boolean setDisplayBlock(Block block){ + public boolean setDisplayBlock(Block block) { return setDisplayBlock(block, true); } @@ -721,9 +767,8 @@ public boolean setDisplayBlock(Block block){ * @param update Do update for the block. (This state changes if you want to show the block) * @return {@code true} if the block is normal block */ - @API(usage = Usage.MAINTAINED, definition = Definition.UNIVERSAL) public boolean setDisplayBlock(Block block, boolean update) { - if(!update){ + if (!update) { if (block.isNormalBlock()) { blockInside = block; } else { @@ -731,6 +776,7 @@ public boolean setDisplayBlock(Block block, boolean update) { } return true; } + //TODO: DATA_DISPLAY_ITEM NBTEntityData if (block != null) { if (block.isNormalBlock()) { blockInside = block; @@ -755,7 +801,6 @@ public boolean setDisplayBlock(Block block, boolean update) { * * @return Block of minecart display block */ - @API(usage = Usage.STABLE, definition = Definition.UNIVERSAL) public Block getDisplayBlock() { return blockInside; } @@ -765,7 +810,6 @@ public Block getDisplayBlock() { * * @param offset The offset */ - @API(usage = Usage.EXPERIMENTAL, definition = Definition.PLATFORM_NATIVE) public void setDisplayBlockOffset(int offset) { setDataProperty(new IntEntityData(DATA_DISPLAY_OFFSET, offset)); } @@ -775,7 +819,6 @@ public void setDisplayBlockOffset(int offset) { * * @return integer */ - @API(usage = Usage.EXPERIMENTAL, definition = Definition.UNIVERSAL) public int getDisplayBlockOffset() { return super.getDataPropertyInt(DATA_DISPLAY_OFFSET); } @@ -785,7 +828,6 @@ public int getDisplayBlockOffset() { * * @return boolean */ - @API(usage = Usage.EXPERIMENTAL, definition = Definition.UNIVERSAL) public boolean isSlowWhenEmpty() { return slowWhenEmpty; } @@ -795,7 +837,6 @@ public boolean isSlowWhenEmpty() { * * @param slow The slowdown flag */ - @API(usage = Usage.EXPERIMENTAL, definition = Definition.UNIVERSAL) public void setSlowWhenEmpty(boolean slow) { slowWhenEmpty = slow; } @@ -825,4 +866,9 @@ public void setDerailedVelocityMod(Vector3 derailed) { public void setMaximumSpeed(double speed) { maxSpeed = speed; } + + @Override + public String getInteractButtonText() { + return ""; + } } diff --git a/src/main/java/cn/nukkit/entity/item/EntityMinecartChest.java b/src/main/java/cn/nukkit/entity/item/EntityMinecartChest.java index 8ce57da5390..f37b0e18853 100644 --- a/src/main/java/cn/nukkit/entity/item/EntityMinecartChest.java +++ b/src/main/java/cn/nukkit/entity/item/EntityMinecartChest.java @@ -27,11 +27,7 @@ public class EntityMinecartChest extends EntityMinecartAbstract implements Inven public EntityMinecartChest(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); setDisplayBlock(Block.get(Block.CHEST), false); - } - - @Override - public String getName() { - return getType().getName(); + setName("Minecart with Chest"); } @Override @@ -40,7 +36,7 @@ public MinecartType getType() { } @Override - public boolean isRideable(){ + public boolean isRideable() { return false; } @@ -51,10 +47,6 @@ public int getNetworkId() { @Override public void dropItem() { - for (Item item : this.inventory.getContents().values()) { - this.level.dropItem(this, item); - } - if (this.lastDamageCause instanceof EntityDamageByEntityEvent) { Entity damager = ((EntityDamageByEntityEvent) this.lastDamageCause).getDamager(); if (damager instanceof Player && ((Player) damager).isCreative()) { @@ -62,12 +54,17 @@ public void dropItem() { } } this.level.dropItem(this, Item.get(Item.CHEST_MINECART)); - } - @Override - public void kill() { - super.kill(); - this.inventory.clearAll(); + if (this.inventory == null) { + this.initInventory(); + } + if (this.inventory != null) { + this.inventory.getViewers().clear(); + for (Item item : this.inventory.getContents().values()) { + this.level.dropItem(this, item); + } + this.inventory.clearAll(); + } } @Override @@ -77,12 +74,17 @@ public boolean mountEntity(Entity entity, byte mode) { @Override public boolean onInteract(Player player, Item item, Vector3 clickedPos) { - player.addWindow(this.inventory); + if (this.isAlive()) { + player.addWindow(this.getInventory()); + } return false; // If true, the count of items player has in hand decreases } @Override public MinecartChestInventory getInventory() { + if (this.inventory == null) { + this.initInventory(); + } return inventory; } @@ -90,26 +92,34 @@ public MinecartChestInventory getInventory() { public void initEntity() { super.initEntity(); - this.inventory = new MinecartChestInventory(this); - if (this.namedTag.contains("Items") && this.namedTag.get("Items") instanceof ListTag) { - ListTag inventoryList = this.namedTag.getList("Items", CompoundTag.class); - for (CompoundTag item : inventoryList.getAll()) { - this.inventory.setItem(item.getByte("Slot"), NBTIO.getItemHelper(item)); - } - } - this.dataProperties .putByte(DATA_CONTAINER_TYPE, 10) - .putInt(DATA_CONTAINER_BASE_SIZE, this.inventory.getSize()) + .putInt(DATA_CONTAINER_BASE_SIZE, 27) .putInt(DATA_CONTAINER_EXTRA_SLOTS_PER_STRENGTH, 0); } + private void initInventory() { + if (!this.namedTag.contains("Items") || !(this.namedTag.get("Items") instanceof ListTag)) { + this.namedTag.putList(new ListTag("Items")); + } + ListTag list = (ListTag) this.namedTag.getList("Items"); + + this.inventory = new MinecartChestInventory(this); + + for (CompoundTag compound : list.getAll()) { + Item item = NBTIO.getItemHelper(compound); + if (item.getId() != 0 && item.getCount() > 0) { + this.inventory.slots.put(compound.getByte("Slot"), item); + } + } + } + @Override public void saveNBT() { super.saveNBT(); - this.namedTag.putList(new ListTag("Items")); if (this.inventory != null) { + this.namedTag.putList(new ListTag("Items")); for (int slot = 0; slot < 27; ++slot) { Item item = this.inventory.getItem(slot); if (item != null && item.getId() != Item.AIR) { diff --git a/src/main/java/cn/nukkit/entity/item/EntityMinecartEmpty.java b/src/main/java/cn/nukkit/entity/item/EntityMinecartEmpty.java index 997fdb8e6d5..97bd261bda0 100644 --- a/src/main/java/cn/nukkit/entity/item/EntityMinecartEmpty.java +++ b/src/main/java/cn/nukkit/entity/item/EntityMinecartEmpty.java @@ -5,8 +5,9 @@ import cn.nukkit.entity.EntityLiving; import cn.nukkit.entity.passive.EntityWaterAnimal; import cn.nukkit.event.entity.EntityDamageByBlockEvent; -import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; +import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.level.format.FullChunk; +import cn.nukkit.math.Vector3f; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.utils.MinecartType; @@ -18,6 +19,9 @@ public class EntityMinecartEmpty extends EntityMinecartAbstract { public static final int NETWORK_ID = 84; + private static final Vector3f RIDER_OFFSET = new Vector3f(0f, -0.35f); + private static final Vector3f RIDER_PLAYER_OFFSET = new Vector3f(0f, 0.525f); + @Override public int getNetworkId() { return NETWORK_ID; @@ -25,18 +29,14 @@ public int getNetworkId() { public EntityMinecartEmpty(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); - } - - @Override - public String getName() { - return getType().getName(); + setName("Minecart"); } @Override public MinecartType getType() { return MinecartType.valueOf(0); } - + @Override public boolean isRideable() { return true; @@ -45,33 +45,30 @@ public boolean isRideable() { @Override protected void activate(int x, int y, int z, boolean flag) { if (flag && this.getHealth() > 15 - && this.attack(new EntityDamageByBlockEvent(this.level.getBlock(x, y, z), this, DamageCause.CONTACT, 1)) + && this.attack(new EntityDamageByBlockEvent(this.level.getBlock(x, y, z), this, EntityDamageEvent.DamageCause.CONTACT, 1)) && !this.passengers.isEmpty()) { this.dismountEntity(this.getPassenger()); } } @Override - public boolean onUpdate(int currentTick) { - boolean update = super.onUpdate(currentTick); - + public void applyEntityCollision(Entity entity) { if (this.passengers.isEmpty()) { - for (Entity entity : this.level.getCollidingEntities(this.boundingBox.grow(0.20000000298023224, 0.0D, 0.20000000298023224), this)) { - if (entity.riding != null || !(entity instanceof EntityLiving) || entity instanceof Player || entity instanceof EntityWaterAnimal) { - continue; - } - + if (!(entity.riding != null || !(entity instanceof EntityLiving) || entity instanceof Player || entity instanceof EntityWaterAnimal)) { this.mountEntity(entity); - update = true; - break; } } - return update; + super.applyEntityCollision(entity); } @Override public String getInteractButtonText() { return this.passengers.isEmpty() ? "action.interact.ride.minecart" : ""; } + + @Override + public Vector3f getMountedOffset(Entity entity) { + return entity instanceof Player ? RIDER_PLAYER_OFFSET : RIDER_OFFSET; + } } diff --git a/src/main/java/cn/nukkit/entity/item/EntityMinecartHopper.java b/src/main/java/cn/nukkit/entity/item/EntityMinecartHopper.java index 0b3107e0de9..664078062b1 100644 --- a/src/main/java/cn/nukkit/entity/item/EntityMinecartHopper.java +++ b/src/main/java/cn/nukkit/entity/item/EntityMinecartHopper.java @@ -2,12 +2,22 @@ import cn.nukkit.Player; import cn.nukkit.block.Block; +import cn.nukkit.block.BlockComposter; +import cn.nukkit.block.BlockRailActivator; +import cn.nukkit.blockentity.BlockEntity; +import cn.nukkit.blockentity.BlockEntityContainer; +import cn.nukkit.blockentity.BlockEntityFurnace; import cn.nukkit.entity.Entity; import cn.nukkit.event.entity.EntityDamageByEntityEvent; +import cn.nukkit.event.inventory.InventoryMoveItemEvent; +import cn.nukkit.inventory.FurnaceInventory; +import cn.nukkit.inventory.Inventory; import cn.nukkit.inventory.InventoryHolder; import cn.nukkit.inventory.MinecartHopperInventory; import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; +import cn.nukkit.math.AxisAlignedBB; +import cn.nukkit.math.SimpleAxisAlignedBB; import cn.nukkit.math.Vector3; import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.CompoundTag; @@ -20,14 +30,12 @@ public class EntityMinecartHopper extends EntityMinecartAbstract implements Inve protected MinecartHopperInventory inventory; + public int transferCooldown; + public EntityMinecartHopper(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); setDisplayBlock(Block.get(Block.HOPPER_BLOCK), false); - } - - @Override - public String getName() { - return getType().getName(); + setName("Minecart with Hopper"); } @Override @@ -36,7 +44,7 @@ public MinecartType getType() { } @Override - public boolean isRideable(){ + public boolean isRideable() { return false; } @@ -47,10 +55,6 @@ public int getNetworkId() { @Override public void dropItem() { - for (Item item : this.inventory.getContents().values()) { - this.level.dropItem(this, item); - } - if (this.lastDamageCause instanceof EntityDamageByEntityEvent) { Entity damager = ((EntityDamageByEntityEvent) this.lastDamageCause).getDamager(); if (damager instanceof Player && ((Player) damager).isCreative()) { @@ -58,12 +62,13 @@ public void dropItem() { } } this.level.dropItem(this, Item.get(Item.HOPPER_MINECART)); - } - - @Override - public void kill() { - super.kill(); - this.inventory.clearAll(); + if (this.inventory != null) { + this.inventory.getViewers().clear(); + for (Item item : this.inventory.getContents().values()) { + this.level.dropItem(this, item); + } + this.inventory.clearAll(); + } } @Override @@ -73,7 +78,9 @@ public boolean mountEntity(Entity entity, byte mode) { @Override public boolean onInteract(Player player, Item item, Vector3 clickedPos) { - player.addWindow(this.inventory); + if (this.isAlive()) { + player.addWindow(this.inventory); + } return false; // If true, the count of items player has in hand decreases } @@ -116,8 +123,184 @@ public void saveNBT() { } } + @Override + public boolean onUpdate(int currentTick) { + if (super.onUpdate(currentTick) && !this.closed && isAlive()) { + if (this.isOnTransferCooldown()) { + this.transferCooldown--; + return true; + } + + Block rail = level.getBlock(this.chunk, getFloorX(), getFloorY(), getFloorZ(), false); + if (rail instanceof BlockRailActivator && ((BlockRailActivator) rail).isActive()) { + return false; + } + + boolean changed; + BlockEntity blockEntity = this.level.getBlockEntity(this.chunk, this.up()); + Block block = null; + if (blockEntity instanceof BlockEntityContainer || (block = this.level.getBlock(this.chunk, this.getFloorX(), this.getFloorY() + 1, this.getFloorZ(), false)) instanceof BlockComposter) { + changed = pullItems(blockEntity, block); + } else { + changed = pickupItems(new SimpleAxisAlignedBB(this.x, this.y, this.z, this.x + 1, this.y + 2, this.z + 1)); + } + + if (changed) { + this.setTransferCooldown(8); + } + + return true; + } + + return false; + } + @Override public String getInteractButtonText() { return "action.interact.opencontainer"; } + + public boolean isOnTransferCooldown() { + return this.transferCooldown > 0; + } + + public void setTransferCooldown(int transferCooldown) { + this.transferCooldown = transferCooldown; + } + + private boolean pullItems(BlockEntity blockEntity, Block block) { + if (this.inventory.isFull()) { + return false; + } + + if (blockEntity instanceof BlockEntityFurnace) { + FurnaceInventory inv = ((BlockEntityFurnace) blockEntity).getInventory(); + Item item = inv.getResult(); + + if (!item.isNull()) { + Item itemToAdd = item.clone(); + itemToAdd.count = 1; + + if (!this.inventory.canAddItem(itemToAdd)) { + return false; + } + + InventoryMoveItemEvent ev = new InventoryMoveItemEvent(inv, this.inventory, this, itemToAdd, InventoryMoveItemEvent.Action.SLOT_CHANGE); + this.server.getPluginManager().callEvent(ev); + + if (ev.isCancelled()) { + return false; + } + + Item[] items = this.inventory.addItem(itemToAdd); + + if (items.length == 0) { + item.count--; + inv.setResult(item); + return true; + } + } + } else if (blockEntity instanceof InventoryHolder) { + Inventory inv = ((InventoryHolder) blockEntity).getInventory(); + + for (int i = 0; i < inv.getSize(); i++) { + Item item = inv.getItem(i); + + if (!item.isNull()) { + Item itemToAdd = item.clone(); + itemToAdd.count = 1; + + if (!this.inventory.canAddItem(itemToAdd)) { + continue; + } + + InventoryMoveItemEvent ev = new InventoryMoveItemEvent(inv, this.inventory, this, itemToAdd, InventoryMoveItemEvent.Action.SLOT_CHANGE); + this.server.getPluginManager().callEvent(ev); + + if (ev.isCancelled()) { + continue; + } + + Item[] items = this.inventory.addItem(itemToAdd); + + if (items.length >= 1) { + continue; + } + + item.count--; + + inv.setItem(i, item); + return true; + } + } + } else if (block instanceof BlockComposter) { + BlockComposter composter = (BlockComposter) block; + Item item = composter.empty(); + if (item == null || item.isNull()) { + return false; + } + Item itemToAdd = item.clone(); + itemToAdd.setCount(1); + if (!this.inventory.canAddItem(itemToAdd)) { + return false; + } + InventoryMoveItemEvent ev = new InventoryMoveItemEvent(null, this.inventory, this, item, InventoryMoveItemEvent.Action.PICKUP); + this.server.getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + return false; + } + Item[] items = inventory.addItem(itemToAdd); + return items.length == 0; + } + return false; + } + + private boolean pickupItems(AxisAlignedBB pickupArea) { + if (this.inventory.isFull()) { + return false; + } + + boolean pickedUpItem = false; + + for (Entity entity : this.level.getCollidingEntities(pickupArea)) { + if (entity.isClosed() || !(entity instanceof EntityItem)) { + continue; + } + + EntityItem itemEntity = (EntityItem) entity; + Item item = itemEntity.getItem(); + + if (item.isNull()) { + continue; + } + + int originalCount = item.getCount(); + + if (!this.inventory.canAddItem(item)) { + continue; + } + + InventoryMoveItemEvent ev = new InventoryMoveItemEvent(null, this.inventory, this, item, InventoryMoveItemEvent.Action.PICKUP); + this.server.getPluginManager().callEvent(ev); + + if (ev.isCancelled()) { + continue; + } + + Item[] items = this.inventory.addItem(item); + + if (items.length == 0) { + entity.close(); + pickedUpItem = true; + continue; + } + + if (items[0].getCount() != originalCount) { + pickedUpItem = true; + item.setCount(items[0].getCount()); + } + } + + return pickedUpItem; + } } diff --git a/src/main/java/cn/nukkit/entity/item/EntityMinecartTNT.java b/src/main/java/cn/nukkit/entity/item/EntityMinecartTNT.java index c5ce3074bed..9aaac688a16 100644 --- a/src/main/java/cn/nukkit/entity/item/EntityMinecartTNT.java +++ b/src/main/java/cn/nukkit/entity/item/EntityMinecartTNT.java @@ -9,7 +9,6 @@ import cn.nukkit.event.entity.EntityDamageByEntityEvent; import cn.nukkit.event.entity.EntityExplosionPrimeEvent; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemMinecartTNT; import cn.nukkit.level.Explosion; import cn.nukkit.level.GameRule; import cn.nukkit.level.format.FullChunk; @@ -17,23 +16,22 @@ import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.network.protocol.LevelSoundEventPacket; import cn.nukkit.utils.MinecartType; - -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; /** - * Author: Adam Matthew [larryTheCoder] - *

+ * @author Adam Matthew [larryTheCoder] + * * Nukkit Project. */ public class EntityMinecartTNT extends EntityMinecartAbstract implements EntityExplosive { public static final int NETWORK_ID = 97; private int fuse; - private boolean activated = false; public EntityMinecartTNT(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); - super.setDisplayBlock(Block.get(BlockID.TNT), false); + setDisplayBlock(Block.get(BlockID.TNT), false); + setName("Minecart with TNT"); } @Override @@ -41,11 +39,6 @@ public boolean isRideable() { return false; } - @Override - public String getInteractButtonText() { - return ""; - } - @Override public void initEntity() { super.initEntity(); @@ -55,13 +48,11 @@ public void initEntity() { } else { fuse = 80; } - this.setDataFlag(DATA_FLAGS, DATA_FLAG_CHARGED, false); + //this.setDataFlag(DATA_FLAGS, DATA_FLAG_CHARGED, false); } @Override public boolean onUpdate(int currentTick) { - this.timing.startTiming(); - if (fuse < 80) { int tickDiff = currentTick - lastUpdate; @@ -75,15 +66,13 @@ public boolean onUpdate(int currentTick) { if (isAlive() && fuse <= 0) { if (this.level.getGameRules().getBoolean(GameRule.TNT_EXPLODES)) { - this.explode(ThreadLocalRandom.current().nextInt(5)); + this.explode(Utils.random.nextInt(5)); } this.close(); return false; } } - this.timing.stopTiming(); - return super.onUpdate(currentTick); } @@ -105,7 +94,7 @@ public void explode(double square) { root = 5.0D; } - EntityExplosionPrimeEvent event = new EntityExplosionPrimeEvent(this, (4.0D + ThreadLocalRandom.current().nextDouble() * 1.5D * root)); + EntityExplosionPrimeEvent event = new EntityExplosionPrimeEvent(this, (4.0D + Utils.random.nextDouble() * 1.5D * root)); server.getPluginManager().callEvent(event); if (event.isCancelled()) { return; @@ -126,12 +115,7 @@ public void dropItem() { return; } } - level.dropItem(this, new ItemMinecartTNT()); - } - - @Override - public String getName() { - return getType().getName(); + level.dropItem(this, Item.get(Item.MINECART_WITH_TNT)); } @Override @@ -150,17 +134,16 @@ public void saveNBT() { super.namedTag.putInt("TNTFuse", this.fuse); } - + @Override public boolean onInteract(Player player, Item item, Vector3 clickedPos) { - boolean interact = super.onInteract(player, item, clickedPos); if (item.getId() == Item.FLINT_AND_STEEL || item.getId() == Item.FIRE_CHARGE) { level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_IGNITE); this.fuse = 79; return true; } - return interact; + return super.onInteract(player, item, clickedPos); } @Override diff --git a/src/main/java/cn/nukkit/entity/item/EntityPainting.java b/src/main/java/cn/nukkit/entity/item/EntityPainting.java index f59f2ca860c..6f2c25bb69e 100644 --- a/src/main/java/cn/nukkit/entity/item/EntityPainting.java +++ b/src/main/java/cn/nukkit/entity/item/EntityPainting.java @@ -1,13 +1,16 @@ package cn.nukkit.entity.item; import cn.nukkit.Player; +import cn.nukkit.block.Block; import cn.nukkit.entity.Entity; import cn.nukkit.entity.EntityHanging; import cn.nukkit.event.entity.EntityDamageByEntityEvent; import cn.nukkit.event.entity.EntityDamageEvent; -import cn.nukkit.item.ItemPainting; +import cn.nukkit.item.Item; import cn.nukkit.level.GameRule; import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.particle.DestroyBlockParticle; +import cn.nukkit.math.SimpleAxisAlignedBB; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.network.protocol.AddPaintingPacket; import cn.nukkit.network.protocol.DataPacket; @@ -16,7 +19,7 @@ import java.util.Map; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntityPainting extends EntityHanging { @@ -24,7 +27,9 @@ public class EntityPainting extends EntityHanging { public static final int NETWORK_ID = 83; public final static Motive[] motives = Motive.values(); + private Motive motive; + private SimpleAxisAlignedBB cachedBoundingBox; public EntityPainting(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); @@ -63,10 +68,11 @@ public boolean attack(EntityDamageEvent source) { if (super.attack(source)) { if (source instanceof EntityDamageByEntityEvent) { Entity damager = ((EntityDamageByEntityEvent) source).getDamager(); - if (damager instanceof Player && (((Player) damager).isAdventure() || ((Player) damager).isSurvival()) && this.level.getGameRules().getBoolean(GameRule.DO_ENTITY_DROPS)) { - this.level.dropItem(this, new ItemPainting()); + if (damager instanceof Player && ((Player) damager).isSurvival()) { + this.dropItem(); } } + this.level.addParticle(new DestroyBlockParticle(this, Block.get(Block.WOODEN_PLANKS))); this.close(); return true; } else { @@ -134,4 +140,24 @@ public enum Motive { this.height = height; } } + + @Override + protected boolean isSurfaceValid() { + if (this.cachedBoundingBox == null) { + this.cachedBoundingBox = new SimpleAxisAlignedBB(this.x - 0.1, this.y, this.z - 0.1, this.x + 0.1, this.y + 0.1, this.z + 0.1); + } + return this.level.hasCollisionBlocks(this, this.cachedBoundingBox); + } + + @Override + protected void dropItem() { + if (this.level.getGameRules().getBoolean(GameRule.DO_ENTITY_DROPS)) { + this.level.dropItem(this, Item.get(Item.PAINTING)); + } + } + + @Override + public boolean ignoredAsSaveReason() { + return true; + } } diff --git a/src/main/java/cn/nukkit/entity/item/EntityPotion.java b/src/main/java/cn/nukkit/entity/item/EntityPotion.java index 54062ee422a..852654158c0 100644 --- a/src/main/java/cn/nukkit/entity/item/EntityPotion.java +++ b/src/main/java/cn/nukkit/entity/item/EntityPotion.java @@ -1,6 +1,8 @@ package cn.nukkit.entity.item; +import cn.nukkit.Player; import cn.nukkit.entity.Entity; +import cn.nukkit.entity.data.IntEntityData; import cn.nukkit.entity.projectile.EntityProjectile; import cn.nukkit.event.potion.PotionCollideEvent; import cn.nukkit.level.format.FullChunk; @@ -18,12 +20,10 @@ public class EntityPotion extends EntityProjectile { public static final int NETWORK_ID = 86; - public static final int DATA_POTION_ID = 37; - public int potionId; public EntityPotion(FullChunk chunk, CompoundTag nbt) { - super(chunk, nbt); + this(chunk, nbt, null); } public EntityPotion(FullChunk chunk, CompoundTag nbt, Entity shootingEntity) { @@ -38,9 +38,9 @@ protected void initEntity() { this.dataProperties.putShort(DATA_POTION_AUX_VALUE, this.potionId); - /*Effect effect = Potion.getEffect(potionId, true); TODO: potion color + Effect effect = Potion.getEffect(potionId, true); - if(effect != null) { + if (effect != null) { int count = 0; int[] c = effect.getColor(); count += effect.getAmplifier() + 1; @@ -49,8 +49,8 @@ protected void initEntity() { int g = ((c[1] * (effect.getAmplifier() + 1)) / count) & 0xff; int b = ((c[2] * (effect.getAmplifier() + 1)) / count) & 0xff; - this.setDataProperty(new IntEntityData(Entity.DATA_UNKNOWN, (r << 16) + (g << 8) + b)); - }*/ + this.setDataProperty(new IntEntityData(Entity.DATA_POTION_COLOR, (r << 16) + (g << 8) + b)); + } } @Override @@ -83,12 +83,7 @@ protected float getDrag() { return 0.01f; } - @Override - public void onCollideWithEntity(Entity entity) { - this.splash(entity); - } - - private void splash(Entity collidedWith) { + protected void splash(Entity collidedWith) { Potion potion = Potion.getPotion(this.potionId); PotionCollideEvent event = new PotionCollideEvent(potion, this); this.server.getPluginManager().callEvent(event); @@ -129,8 +124,11 @@ private void splash(Entity collidedWith) { this.getLevel().addParticle(particle); this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_GLASS); - Entity[] entities = this.getLevel().getNearbyEntities(this.getBoundingBox().grow(4.125, 2.125, 4.125)); + Entity[] entities = this.getLevel().getNearbyEntities(this.getBoundingBox().grow(4.125, 2.125, 4.125), this); for (Entity anEntity : entities) { + if (anEntity == null || anEntity.closed || !anEntity.isAlive() || anEntity instanceof Player && ((Player) anEntity).isSpectator()) { + continue; + } double distance = anEntity.distanceSquared(this); if (distance < 16) { double d = anEntity.equals(collidedWith) ? 1 : 1 - Math.sqrt(distance) / 4; @@ -139,25 +137,28 @@ private void splash(Entity collidedWith) { } } + @Override + public void onCollideWithEntity(Entity entity) { + this.splash(entity); + this.close(); + } + @Override public boolean onUpdate(int currentTick) { + boolean update = super.onUpdate(currentTick); + if (this.closed) { return false; } - this.timing.startTiming(); - - boolean hasUpdate = super.onUpdate(currentTick); - - if (this.age > 1200) { - this.kill(); - hasUpdate = true; - } else if (this.isCollided) { + if (this.isCollided) { this.splash(null); - hasUpdate = true; } - this.timing.stopTiming(); - return hasUpdate; + if (this.age > 1200 || this.isCollided) { + this.close(); + return false; + } + return update; } } diff --git a/src/main/java/cn/nukkit/entity/item/EntityPotionLingering.java b/src/main/java/cn/nukkit/entity/item/EntityPotionLingering.java new file mode 100644 index 00000000000..918e40cbd2c --- /dev/null +++ b/src/main/java/cn/nukkit/entity/item/EntityPotionLingering.java @@ -0,0 +1,41 @@ +package cn.nukkit.entity.item; + +import cn.nukkit.entity.Entity; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.potion.Effect; +import cn.nukkit.potion.Potion; + +public class EntityPotionLingering extends EntityPotion { + + public static final int NETWORK_ID = 101; + + public EntityPotionLingering(FullChunk chunk, CompoundTag nbt) { + this(chunk, nbt, null); + } + + public EntityPotionLingering(FullChunk chunk, CompoundTag nbt, Entity shootingEntity) { + super(chunk, nbt, shootingEntity); + } + + @Override + protected void initEntity() { + super.initEntity(); + setDataFlag(DATA_FLAGS, DATA_FLAG_LINGER, true); + } + + @Override + protected void splash(Entity collidedWith) { + super.splash(collidedWith); + EntityAreaEffectCloud entity = (EntityAreaEffectCloud) Entity.createEntity("AreaEffectCloud", this.chunk, + getDefaultNBT(this).putShort("PotionId", potionId) + ); + + Effect effect = Potion.getEffect(potionId, true); + + if (effect != null && entity != null) { + entity.cloudEffects.add(effect.setDuration(1).setVisible(false).setAmbient(false)); + entity.spawnToAll(); + } + } +} diff --git a/src/main/java/cn/nukkit/entity/item/EntityPrimedTNT.java b/src/main/java/cn/nukkit/entity/item/EntityPrimedTNT.java index 01fa145d0c4..600b608e9c1 100644 --- a/src/main/java/cn/nukkit/entity/item/EntityPrimedTNT.java +++ b/src/main/java/cn/nukkit/entity/item/EntityPrimedTNT.java @@ -1,5 +1,6 @@ package cn.nukkit.entity.item; +import cn.nukkit.block.BlockSlab; import cn.nukkit.entity.Entity; import cn.nukkit.entity.EntityExplosive; import cn.nukkit.entity.data.IntEntityData; @@ -10,7 +11,7 @@ import cn.nukkit.level.GameRule; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -import cn.nukkit.network.protocol.LevelSoundEventPacket; +import cn.nukkit.network.protocol.LevelEventPacket; /** * @author MagicDroidX @@ -49,11 +50,6 @@ protected float getBaseOffset() { return 0.49f; } - @Override - public boolean canCollide() { - return false; - } - protected int fuse; protected Entity source; @@ -77,6 +73,7 @@ public boolean attack(EntityDamageEvent source) { return source.getCause() == DamageCause.VOID && super.attack(source); } + @Override protected void initEntity() { super.initEntity(); @@ -89,27 +86,27 @@ protected void initEntity() { this.setDataFlag(DATA_FLAGS, DATA_FLAG_IGNITED, true); this.setDataProperty(new IntEntityData(DATA_FUSE_LENGTH, fuse)); - this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_FIZZ); + this.getLevel().addLevelEvent(this, LevelEventPacket.EVENT_SOUND_TNT); } - + @Override public boolean canCollideWith(Entity entity) { return false; } + @Override public void saveNBT() { super.saveNBT(); namedTag.putByte("Fuse", fuse); } + @Override public boolean onUpdate(int currentTick) { if (closed) { return false; } - this.timing.startTiming(); - int tickDiff = currentTick - lastUpdate; if (tickDiff <= 0 && !justCreated) { @@ -126,7 +123,9 @@ public boolean onUpdate(int currentTick) { if (isAlive()) { - motionY -= getGravity(); + if (!isOnGround()) { + motionY -= getGravity(); + } move(motionX, motionY, motionZ); @@ -147,15 +146,14 @@ public boolean onUpdate(int currentTick) { fuse -= tickDiff; if (fuse <= 0) { - if (this.level.getGameRules().getBoolean(GameRule.TNT_EXPLODES)) - explode(); - kill(); + if (this.level.getGameRules().getBoolean(GameRule.TNT_EXPLODES)) { + this.explode(); + } + this.close(); + return false; } - } - this.timing.stopTiming(); - return hasUpdate || fuse >= 0 || Math.abs(motionX) > 0.00001 || Math.abs(motionY) > 0.00001 || Math.abs(motionZ) > 0.00001; } @@ -165,7 +163,7 @@ public void explode() { if (event.isCancelled()) { return; } - Explosion explosion = new Explosion(this, event.getForce(), this); + Explosion explosion = new Explosion(level.getBlock(this) instanceof BlockSlab ? this.add(0, 0.1, 0) : this, event.getForce(), this); if (event.isBlockBreaking()) { explosion.explodeA(); } diff --git a/src/main/java/cn/nukkit/entity/item/EntityVehicle.java b/src/main/java/cn/nukkit/entity/item/EntityVehicle.java index f0a2da30830..40b7542dcfc 100644 --- a/src/main/java/cn/nukkit/entity/item/EntityVehicle.java +++ b/src/main/java/cn/nukkit/entity/item/EntityVehicle.java @@ -13,37 +13,44 @@ import cn.nukkit.nbt.tag.CompoundTag; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class EntityVehicle extends Entity implements EntityRideable, EntityInteractable { + private int hurtTime; + private int hurtDirection; + private int damage; + public EntityVehicle(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } public int getRollingAmplitude() { - return this.getDataPropertyInt(DATA_HURT_TIME); + return hurtTime; } public void setRollingAmplitude(int time) { + this.hurtTime = time; this.setDataProperty(new IntEntityData(DATA_HURT_TIME, time)); } public int getRollingDirection() { - return this.getDataPropertyInt(DATA_HURT_DIRECTION); + return hurtDirection; } public void setRollingDirection(int direction) { + this.hurtDirection = direction; this.setDataProperty(new IntEntityData(DATA_HURT_DIRECTION, direction)); } public int getDamage() { - return this.getDataPropertyInt(DATA_HEALTH); // false data name (should be DATA_DAMAGE_TAKEN) + return damage; } public void setDamage(int damage) { - this.setDataProperty(new IntEntityData(DATA_HEALTH, damage)); + this.damage = damage; + this.setDataProperty(new IntEntityData(DATA_HEALTH, damage)); // false data name (should be DATA_DAMAGE_TAKEN) } @Override @@ -58,16 +65,18 @@ public boolean canDoInteraction() { @Override public boolean onUpdate(int currentTick) { - // The rolling amplitude + if (y < (this.getLevel().getMinBlockY() - 16)) { + this.close(); + } + + if (closed) { + return false; + } + if (getRollingAmplitude() > 0) { setRollingAmplitude(getRollingAmplitude() - 1); } - // A killer task - if (y < -16) { - kill(); - } - // Movement code updateMovement(); return true; } @@ -111,4 +120,4 @@ public boolean attack(EntityDamageEvent source) { return super.attack(source); } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/entity/item/EntityXPOrb.java b/src/main/java/cn/nukkit/entity/item/EntityXPOrb.java index 93fb79a3cd9..40e7d53f784 100644 --- a/src/main/java/cn/nukkit/entity/item/EntityXPOrb.java +++ b/src/main/java/cn/nukkit/entity/item/EntityXPOrb.java @@ -1,11 +1,14 @@ package cn.nukkit.entity.item; import cn.nukkit.Player; +import cn.nukkit.block.Block; import cn.nukkit.entity.Entity; import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; import cn.nukkit.level.format.FullChunk; +import cn.nukkit.math.NukkitMath; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.potion.Effect; import it.unimi.dsi.fastutil.ints.IntArrayList; import java.util.List; @@ -19,9 +22,45 @@ public class EntityXPOrb extends Entity { public static final int NETWORK_ID = 69; /** - * Split sizes used for dropping experience orbs. + * Split sizes used for dropping experience orbs */ - public static final int[] ORB_SPLIT_SIZES = {2477, 1237, 617, 307, 149, 73, 37, 17, 7, 3, 1}; //This is indexed biggest to smallest so that we can return as soon as we found the biggest value. + public static final int[] ORB_SPLIT_SIZES = {2477, 1237, 617, 307, 149, 73, 37, 17, 7, 3, 1}; // This is indexed biggest to smallest so that we can return as soon as we found the biggest value + public Player closestPlayer = null; + private int pickupDelay; + private int exp; + + public EntityXPOrb(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + /** + * Returns the largest size of normal XP orb that will be spawned for the specified amount of XP. Used to split XP + * up into multiple orbs when an amount of XP is dropped. + */ + public static int getMaxOrbSize(int amount) { + for (int split : ORB_SPLIT_SIZES) { + if (amount >= split) { + return split; + } + } + + return 1; + } + + /** + * Splits the specified amount of XP into an array of acceptable XP orb sizes. + */ + public static List splitIntoOrbSizes(int amount) { + List result = new IntArrayList(); + + while (amount > 0) { + int size = getMaxOrbSize(amount); + result.add(size); + amount -= size; + } + + return result; + } @Override public int getNetworkId() { @@ -30,17 +69,17 @@ public int getNetworkId() { @Override public float getWidth() { - return 0.25f; + return 0.1f; } @Override public float getLength() { - return 0.25f; + return 0.1f; } @Override public float getHeight() { - return 0.25f; + return 0.1f; } @Override @@ -58,32 +97,25 @@ public boolean canCollide() { return false; } - public EntityXPOrb(FullChunk chunk, CompoundTag nbt) { - super(chunk, nbt); - } - - private int age; - private int pickupDelay; - private int exp; - - public Player closestPlayer = null; - @Override protected void initEntity() { + this.setMaxHealth(5); super.initEntity(); - setMaxHealth(5); - setHealth(5); - if (namedTag.contains("Health")) { this.setHealth(namedTag.getShort("Health")); + } else { + this.setHealth(5); } + if (namedTag.contains("Age")) { this.age = namedTag.getShort("Age"); } + if (namedTag.contains("PickupDelay")) { this.pickupDelay = namedTag.getShort("PickupDelay"); } + if (namedTag.contains("Value")) { this.exp = namedTag.getShort("Value"); } @@ -93,17 +125,15 @@ protected void initEntity() { } this.dataProperties.putInt(DATA_EXPERIENCE_VALUE, this.exp); - - //call event item spawn event } @Override public boolean attack(EntityDamageEvent source) { return (source.getCause() == DamageCause.VOID || source.getCause() == DamageCause.FIRE_TICK || - (source.getCause() == DamageCause.ENTITY_EXPLOSION || + source.getCause() == DamageCause.ENTITY_EXPLOSION || source.getCause() == DamageCause.BLOCK_EXPLOSION) && - !this.isInsideOfWater()) && super.attack(source); + super.attack(source); } @Override @@ -116,43 +146,60 @@ public boolean onUpdate(int currentTick) { if (tickDiff <= 0 && !this.justCreated) { return true; } - this.lastUpdate = currentTick; - boolean hasUpdate = entityBaseTick(tickDiff); - if (this.isAlive()) { + this.minimalEntityTick(currentTick, tickDiff); + + if (this.age > 6000) { + this.close(); + return false; + } - if (this.pickupDelay > 0 && this.pickupDelay < 32767) { //Infinite delay + if (this.isAlive()) { + if (this.pickupDelay > 0) { this.pickupDelay -= tickDiff; if (this.pickupDelay < 0) { this.pickupDelay = 0; } - }/* else { // Done in Player#checkNearEntities - for (Entity entity : this.level.getCollidingEntities(this.boundingBox, this)) { - if (entity instanceof Player) { - if (((Player) entity).pickupEntity(this, false)) { - return true; - } - } - } - }*/ + } - this.motionY -= this.getGravity(); + if (this.isOnGround()) { + this.motionY = 0; + } else if (Block.isWater(level.getBlockIdAt(this.chunk, this.getFloorX(), NukkitMath.floorDouble(this.y + 0.53), this.getFloorZ()))) { + this.motionY = this.getGravity() / 2; + } else { + this.motionY -= this.getGravity(); + } + + this.checkBlockCollision(); - if (this.checkObstruction(this.x, this.y, this.z)) { + /*if (this.checkObstruction(this.x, this.y, this.z)) { hasUpdate = true; + }*/ + + // Force occasional check for nearby blocks changed even if the item doesn't move + if (this.motionY == 0 && this.age % 20 == 0) { + this.motionY = 0.00001; } - if (this.closestPlayer == null || this.closestPlayer.distanceSquared(this) > 64.0D) { - for (Player p : this.getViewers().values()) { - if (!p.isSpectator() && p.distance(this) <= 8) { - this.closestPlayer = p; - break; - } + if (this.age % 2 == 0) { + if (this.closestPlayer != null && + (this.closestPlayer.level != this.level || + this.closestPlayer.closed || + !this.closestPlayer.isAlive() || + this.closestPlayer.isSpectator() || + !this.closestPlayer.canPickupXP() || + this.closestPlayer.distanceSquared(this) > 64.0D)) { + this.closestPlayer = null; } - } - if (this.closestPlayer != null && this.closestPlayer.isSpectator()) { - this.closestPlayer = null; + if (this.closestPlayer == null) { + for (Player p : this.getViewers().values()) { + if (!p.isSpectator() && p.canPickupXP() && p.distanceSquared(this) <= 64.0D) { + this.closestPlayer = p; + break; + } + } + } } if (this.closestPlayer != null) { @@ -172,10 +219,33 @@ public boolean onUpdate(int currentTick) { this.move(this.motionX, this.motionY, this.motionZ); + if (this.y < (this.getLevel().getMinBlockY() - 16)) { + this.attack(new EntityDamageEvent(this, DamageCause.VOID, 10)); + } + + if (this.fireTicks > 0) { + if (this.fireProof) { + this.fireTicks -= tickDiff << 2; + if (this.fireTicks < 0) { + this.fireTicks = 0; + } + } else { + if (((this.fireTicks % 20) == 0 || tickDiff > 20) && !this.hasEffect(Effect.FIRE_RESISTANCE)) { + this.attack(new EntityDamageEvent(this, DamageCause.FIRE_TICK, 1)); + } + this.fireTicks -= tickDiff; + } + if (this.fireTicks <= 0) { + this.extinguish(); + } else if (!this.fireProof) { + this.setDataFlag(DATA_FLAGS, DATA_FLAG_ONFIRE, true); + } + } + double friction = 1d - this.getDrag(); if (this.onGround && (Math.abs(this.motionX) > 0.00001 || Math.abs(this.motionZ) > 0.00001)) { - friction = this.getLevel().getBlock(this.temporalVector.setComponents((int) Math.floor(this.x), (int) Math.floor(this.y - 1), (int) Math.floor(this.z) - 1)).getFrictionFactor() * friction; + friction = this.getLevel().getBlock(this.chunk, getFloorX(), getFloorY() - 1, getFloorZ(), false).getFrictionFactor() * friction; } this.motionX *= friction; @@ -183,19 +253,16 @@ public boolean onUpdate(int currentTick) { this.motionZ *= friction; if (this.onGround) { - this.motionY *= -0.5; + this.motionY = 0; } this.updateMovement(); - - if (this.age > 6000) { - this.kill(); - hasUpdate = true; - } - + } else { + this.close(); + return false; } - return hasUpdate || !this.onGround || Math.abs(this.motionX) > 0.00001 || Math.abs(this.motionY) > 0.00001 || Math.abs(this.motionZ) > 0.00001; + return !(this.motionX == 0 && this.motionY == 0 && this.motionZ == 0); } @Override @@ -230,33 +297,4 @@ public int getPickupDelay() { public void setPickupDelay(int pickupDelay) { this.pickupDelay = pickupDelay; } - - /** - * Returns the largest size of normal XP orb that will be spawned for the specified amount of XP. Used to split XP - * up into multiple orbs when an amount of XP is dropped. - */ - public static int getMaxOrbSize(int amount) { - for (int split : ORB_SPLIT_SIZES){ - if (amount >= split) { - return split; - } - } - - return 1; - } - - /** - * Splits the specified amount of XP into an array of acceptable XP orb sizes. - */ - public static List splitIntoOrbSizes(int amount) { - List result = new IntArrayList(); - - while (amount > 0) { - int size = getMaxOrbSize(amount); - result.add(size); - amount -= size; - } - - return result; - } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityBlaze.java b/src/main/java/cn/nukkit/entity/mob/EntityBlaze.java index 52ffea538c0..cac53cb927f 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityBlaze.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityBlaze.java @@ -1,28 +1,21 @@ package cn.nukkit.entity.mob; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityBlaze extends EntityMob { +public class EntityBlaze extends EntityFlyingMob { public static final int NETWORK_ID = 43; - @Override - public int getNetworkId() { - return NETWORK_ID; - } - public EntityBlaze(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(20); + public int getNetworkId() { + return NETWORK_ID; } @Override @@ -36,7 +29,19 @@ public float getHeight() { } @Override - public String getName() { - return "Blaze"; + public void initEntity() { + this.setMaxHealth(20); + super.initEntity(); + this.fireProof = true; + } + + @Override + public Item[] getDrops() { + return new Item[]{Item.get(Item.BLAZE_ROD, 0, Utils.rand(0, 1))}; + } + + @Override + public int getKillExperience() { + return 10; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityBogged.java b/src/main/java/cn/nukkit/entity/mob/EntityBogged.java new file mode 100644 index 00000000000..bda812df270 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/mob/EntityBogged.java @@ -0,0 +1,113 @@ +package cn.nukkit.entity.mob; + +import cn.nukkit.Player; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.EntitySmite; +import cn.nukkit.entity.projectile.EntityArrow; +import cn.nukkit.event.entity.EntityDamageByChildEntityEvent; +import cn.nukkit.item.Item; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.math.Vector2; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.network.protocol.MobEquipmentPacket; +import cn.nukkit.utils.Utils; + +import java.util.ArrayList; +import java.util.List; + +public class EntityBogged extends EntityWalkingMob implements EntitySmite { + + public static final int NETWORK_ID = 144; + + public EntityBogged(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + @Override + public void initEntity() { + this.setMaxHealth(20); + super.initEntity(); + } + + @Override + public int getNetworkId() { + return NETWORK_ID; + } + + @Override + public float getWidth() { + return 0.6f; + } + + @Override + public float getHeight() { + return 1.9f; + } + + @Override + public void spawnTo(Player player) { + super.spawnTo(player); + + MobEquipmentPacket pk = new MobEquipmentPacket(); + pk.eid = this.getId(); + pk.item = Item.get(Item.BOW); + pk.hotbarSlot = 0; + player.dataPacket(pk); + } + + @Override + public boolean entityBaseTick(int tickDiff) { + boolean hasUpdate; + + if (getServer().getDifficulty() == 0) { + this.close(); + return true; + } + + hasUpdate = super.entityBaseTick(tickDiff); + + return hasUpdate; + } + + @Override + public Item[] getDrops() { + List drops = new ArrayList<>(); + + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.BONE, 0, 1)); + } + + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.ARROW, 0, 1)); + } + + if (Utils.rand()) { + drops.add(Item.get(Item.ARROW, 26, 1)); + } + + return drops.toArray(new Item[0]); + } + + @Override + public int getKillExperience() { + return 5; + } + + @Override + public void kill() { + if (!this.isAlive()) { + return; + } + + super.kill(); + + if (this.lastDamageCause instanceof EntityDamageByChildEntityEvent) { + Entity damager; + if (((EntityDamageByChildEntityEvent) this.lastDamageCause).getChild() instanceof EntityArrow && (damager = ((EntityDamageByChildEntityEvent) this.lastDamageCause).getDamager()) instanceof Player) { + if (new Vector2(this.x, this.z).distance(new Vector2(damager.x, damager.z)) >= 50) { + ((Player) damager).awardAchievement("snipeSkeleton"); + } + } + } + } +} diff --git a/src/main/java/cn/nukkit/entity/mob/EntityBreeze.java b/src/main/java/cn/nukkit/entity/mob/EntityBreeze.java new file mode 100644 index 00000000000..15367e40d87 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/mob/EntityBreeze.java @@ -0,0 +1,45 @@ +package cn.nukkit.entity.mob; + +import cn.nukkit.item.Item; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; + +public class EntityBreeze extends EntityFlyingMob { + + public static final int NETWORK_ID = 140; + + public EntityBreeze(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + @Override + public int getNetworkId() { + return NETWORK_ID; + } + + @Override + public float getWidth() { + return 0.6f; + } + + @Override + public float getHeight() { + return 1.77f; + } + + @Override + public void initEntity() { + this.setMaxHealth(30); + super.initEntity(); + } + + @Override + public Item[] getDrops() { + return new Item[]{/*Item.get(Item.BREEZE_ROD, 0, Utils.rand(1, 2))*/}; + } + + @Override + public int getKillExperience() { + return 10; + } +} diff --git a/src/main/java/cn/nukkit/entity/mob/EntityCaveSpider.java b/src/main/java/cn/nukkit/entity/mob/EntityCaveSpider.java index f0453c33e57..1cfed437071 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityCaveSpider.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityCaveSpider.java @@ -1,29 +1,25 @@ package cn.nukkit.entity.mob; import cn.nukkit.entity.EntityArthropod; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityCaveSpider extends EntityMob implements EntityArthropod { +import java.util.ArrayList; +import java.util.List; - public static final int NETWORK_ID = 40; +public class EntityCaveSpider extends EntityWalkingMob implements EntityArthropod { - @Override - public int getNetworkId() { - return NETWORK_ID; - } + public static final int NETWORK_ID = 40; public EntityCaveSpider(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(12); + public int getNetworkId() { + return NETWORK_ID; } @Override @@ -36,8 +32,32 @@ public float getHeight() { return 0.5f; } + @Override + public void initEntity() { + this.setMaxHealth(12); + super.initEntity(); + } + + @Override + public Item[] getDrops() { + List drops = new ArrayList<>(); + + drops.add(Item.get(Item.STRING, 0, Utils.rand(0, 2))); + + for (int i = 0; i < (Utils.rand(0, 2) == 0 ? 1 : 0); i++) { + drops.add(Item.get(Item.SPIDER_EYE, 0, 1)); + } + + return drops.toArray(new Item[0]); + } + + @Override + public int getKillExperience() { + return 5; + } + @Override public String getName() { - return "CaveSpider"; + return this.hasCustomName() ? this.getNameTag() : "Cave Spider"; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityCreeper.java b/src/main/java/cn/nukkit/entity/mob/EntityCreeper.java index 293a73321c3..8dec52ac5c3 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityCreeper.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityCreeper.java @@ -1,27 +1,29 @@ package cn.nukkit.entity.mob; import cn.nukkit.entity.Entity; -import cn.nukkit.entity.data.ByteEntityData; +import cn.nukkit.entity.EntityExplosive; import cn.nukkit.entity.weather.EntityLightningStrike; import cn.nukkit.event.entity.CreeperPowerEvent; import cn.nukkit.event.entity.EntityDamageByEntityEvent; +import cn.nukkit.event.entity.EntityDamageEvent; +import cn.nukkit.event.entity.EntityExplosionPrimeEvent; import cn.nukkit.item.Item; +import cn.nukkit.level.Explosion; +import cn.nukkit.level.GameRule; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -import java.util.concurrent.ThreadLocalRandom; +import java.util.ArrayList; +import java.util.List; -/** - * @author Box. - */ -public class EntityCreeper extends EntityMob { +public class EntityCreeper extends EntityWalkingMob implements EntityExplosive { public static final int NETWORK_ID = 33; - public static final int DATA_SWELL_DIRECTION = 16; - public static final int DATA_SWELL = 17; - public static final int DATA_SWELL_OLD = 18; - public static final int DATA_POWERED = 19; + public EntityCreeper(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } @Override public int getNetworkId() { @@ -38,58 +40,80 @@ public float getHeight() { return 1.7f; } - public EntityCreeper(FullChunk chunk, CompoundTag nbt) { - super(chunk, nbt); - } + @Override + public void initEntity() { + this.setMaxHealth(20); + super.initEntity(); - public boolean isPowered() { - return getDataPropertyBoolean(DATA_POWERED); + if (this.namedTag.contains("powered")) { + this.setPowered(this.namedTag.getBoolean("powered")); + } } - public void setPowered(EntityLightningStrike bolt) { - CreeperPowerEvent ev = new CreeperPowerEvent(this, bolt, CreeperPowerEvent.PowerCause.LIGHTNING); - this.getServer().getPluginManager().callEvent(ev); + public void explode() { + if (this.closed) return; + + EntityExplosionPrimeEvent ev = new EntityExplosionPrimeEvent(this, this.isPowered() ? 6 : 3); + this.server.getPluginManager().callEvent(ev); if (!ev.isCancelled()) { - this.setDataProperty(new ByteEntityData(DATA_POWERED, 1)); - this.namedTag.putBoolean("powered", true); + Explosion explosion = new Explosion(this, (float) ev.getForce(), this); + + if (ev.isBlockBreaking() && this.level.getGameRules().getBoolean(GameRule.MOB_GRIEFING)) { + explosion.explodeA(); + } + + explosion.explodeB(); } + + this.close(); } - public void setPowered(boolean powered) { - CreeperPowerEvent ev = new CreeperPowerEvent(this, powered ? CreeperPowerEvent.PowerCause.SET_ON : CreeperPowerEvent.PowerCause.SET_OFF); - this.getServer().getPluginManager().callEvent(ev); + @Override + public Item[] getDrops() { + List drops = new ArrayList<>(); - if (!ev.isCancelled()) { - this.setDataProperty(new ByteEntityData(DATA_POWERED, powered ? 1 : 0)); - this.namedTag.putBoolean("powered", powered); + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.GUNPOWDER, 0, 1)); } - } - public void onStruckByLightning(Entity entity) { - this.setPowered(true); + return drops.toArray(new Item[0]); } @Override - protected void initEntity() { - super.initEntity(); + public int getKillExperience() { + return 5; + } - if (this.namedTag.getBoolean("powered") || this.namedTag.getBoolean("IsPowered")) { - this.dataProperties.putBoolean(DATA_POWERED, true); - } - this.setMaxHealth(20); + public boolean isPowered() { + return this.getDataFlag(DATA_FLAGS, DATA_FLAG_POWERED); + } + + public void setPowered(boolean charged) { + this.setDataFlag(DATA_FLAGS, DATA_FLAG_POWERED, charged); } @Override - public String getName() { - return "Creeper"; + public void saveNBT() { + super.saveNBT(); + + this.namedTag.putBoolean("powered", this.isPowered()); } @Override - public Item[] getDrops() { - if (this.lastDamageCause instanceof EntityDamageByEntityEvent) { - return new Item[]{Item.get(Item.GUNPOWDER, ThreadLocalRandom.current().nextInt(2) + 1)}; + public void onStruckByLightning(Entity lightning) { + if (this.attack(new EntityDamageByEntityEvent(lightning, this, EntityDamageEvent.DamageCause.LIGHTNING, 5))) { + if (this.fireTicks < 160) { + this.setOnFire(8); + } + + if (lightning instanceof EntityLightningStrike) { + CreeperPowerEvent event = new CreeperPowerEvent(this, (EntityLightningStrike) lightning, CreeperPowerEvent.PowerCause.LIGHTNING); + server.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + this.setPowered(true); + } + } } - return new Item[0]; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityDrowned.java b/src/main/java/cn/nukkit/entity/mob/EntityDrowned.java index 7a105ac5aed..072499ba338 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityDrowned.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityDrowned.java @@ -4,11 +4,12 @@ import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * Created by PetteriM1 - */ -public class EntityDrowned extends EntityMob implements EntitySmite { +import java.util.ArrayList; +import java.util.List; + +public class EntityDrowned extends EntityWalkingMob implements EntitySmite { public static final int NETWORK_ID = 110; @@ -21,12 +22,6 @@ public int getNetworkId() { return NETWORK_ID; } - @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(20); - } - @Override public float getWidth() { return 0.6f; @@ -38,12 +33,30 @@ public float getHeight() { } @Override - public String getName() { - return "Drowned"; + protected void initEntity() { + this.setMaxHealth(20); + super.initEntity(); } @Override public Item[] getDrops() { - return new Item[]{Item.get(Item.ROTTEN_FLESH)}; + List drops = new ArrayList<>(); + + if (!this.isBaby()) { + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.ROTTEN_FLESH, 0, 1)); + } + + if (Utils.rand(1, 100) <= 11) { + drops.add(Item.get(Item.GOLD_INGOT, 0, 1)); + } + } + + return drops.toArray(new Item[0]); + } + + @Override + public int getKillExperience() { + return this.isBaby() ? 0 : 5; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityElderGuardian.java b/src/main/java/cn/nukkit/entity/mob/EntityElderGuardian.java index 93ac8f39bc0..b763f4ec925 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityElderGuardian.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityElderGuardian.java @@ -1,43 +1,71 @@ package cn.nukkit.entity.mob; +import cn.nukkit.Player; +import cn.nukkit.block.BlockSponge; +import cn.nukkit.event.entity.EntityDamageByEntityEvent; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityElderGuardian extends EntityMob { +import java.util.ArrayList; +import java.util.List; + +public class EntityElderGuardian extends EntitySwimmingMob { public static final int NETWORK_ID = 50; + public EntityElderGuardian(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + @Override public int getNetworkId() { return NETWORK_ID; } - public EntityElderGuardian(FullChunk chunk, CompoundTag nbt) { - super(chunk, nbt); + @Override + public float getWidth() { + return 1.9975f; } @Override - protected void initEntity() { - super.initEntity(); + public float getHeight() { + return 1.9975f; + } + + @Override + public void initEntity() { this.setMaxHealth(80); + super.initEntity(); + this.setDataFlag(DATA_FLAGS, DATA_FLAG_ELDER, true); } @Override - public float getWidth() { - return 1.9975f; + public Item[] getDrops() { + List drops = new ArrayList<>(); + + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.PRISMARINE_SHARD, 0, 1)); + } + + if (this.lastDamageCause instanceof EntityDamageByEntityEvent) { + if (((EntityDamageByEntityEvent) this.lastDamageCause).getDamager() instanceof Player) { + drops.add(Item.get(Item.SPONGE, BlockSponge.WET, 1)); + } + } + + return drops.toArray(new Item[0]); } @Override - public float getHeight() { - return 1.9975f; + public int getKillExperience() { + return 10; } @Override public String getName() { - return "Elder Guardian"; + return this.hasCustomName() ? this.getNameTag() : "Elder Guardian"; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityEnderDragon.java b/src/main/java/cn/nukkit/entity/mob/EntityEnderDragon.java index 230808a5bae..9fc3e8ce4d8 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityEnderDragon.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityEnderDragon.java @@ -1,14 +1,15 @@ package cn.nukkit.entity.mob; import cn.nukkit.Player; +import cn.nukkit.entity.Attribute; +import cn.nukkit.entity.EntityBoss; import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.network.protocol.AddEntityPacket; +import cn.nukkit.network.protocol.DataPacket; -/** - * @author PikyCZ - */ -public class EntityEnderDragon extends EntityMob { +public class EntityEnderDragon extends EntityFlyingMob implements EntityBoss { public static final int NETWORK_ID = 53; @@ -23,27 +24,55 @@ public EntityEnderDragon(FullChunk chunk, CompoundTag nbt) { @Override public float getWidth() { - return 13f; + return 16f; } @Override public float getHeight() { - return 4f; + return 8f; } @Override public void initEntity() { - super.initEntity(); this.setMaxHealth(200); + super.initEntity(); + + this.fireProof = true; + this.setDataFlag(DATA_FLAGS, DATA_FLAG_FIRE_IMMUNE, true); } @Override - protected boolean applyNameTag(Player player, Item item) { - return false; + public int getKillExperience() { + return 0; } @Override public String getName() { - return "EnderDragon"; + return this.hasCustomName() ? this.getNameTag() : "Ender Dragon"; + } + + @Override + protected DataPacket createAddEntityPacket() { + AddEntityPacket addEntity = new AddEntityPacket(); + addEntity.type = NETWORK_ID; + addEntity.entityUniqueId = this.getId(); + addEntity.entityRuntimeId = this.getId(); + addEntity.yaw = (float) this.yaw; + addEntity.headYaw = (float) this.yaw; + addEntity.pitch = (float) this.pitch; + addEntity.x = (float) this.x; + addEntity.y = (float) this.y; + addEntity.z = (float) this.z; + addEntity.speedX = (float) this.motionX; + addEntity.speedY = (float) this.motionY; + addEntity.speedZ = (float) this.motionZ; + addEntity.metadata = this.dataProperties.clone(); + addEntity.attributes = new Attribute[]{Attribute.getAttribute(Attribute.MAX_HEALTH).setMaxValue(200).setValue(200)}; + return addEntity; + } + + @Override + protected boolean applyNameTag(Player player, Item nameTag) { + return false; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityEnderman.java b/src/main/java/cn/nukkit/entity/mob/EntityEnderman.java index d3f3cbd6784..860cd99f2d8 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityEnderman.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityEnderman.java @@ -1,28 +1,21 @@ package cn.nukkit.entity.mob; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityEnderman extends EntityMob { +public class EntityEnderman extends EntityWalkingMob { public static final int NETWORK_ID = 38; - @Override - public int getNetworkId() { - return NETWORK_ID; - } - public EntityEnderman(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(40); + public int getNetworkId() { + return NETWORK_ID; } @Override @@ -36,7 +29,18 @@ public float getHeight() { } @Override - public String getName() { - return "Enderman"; + protected void initEntity() { + this.setMaxHealth(40); + super.initEntity(); + } + + @Override + public Item[] getDrops() { + return new Item[]{Item.get(Item.ENDER_PEARL, 0, Utils.rand(0, 1))}; + } + + @Override + public int getKillExperience() { + return 5; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityEndermite.java b/src/main/java/cn/nukkit/entity/mob/EntityEndermite.java index 4a7d8f21ed3..2dbc3bb5b06 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityEndermite.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityEndermite.java @@ -4,26 +4,17 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -/** - * @author Box. - */ -public class EntityEndermite extends EntityMob implements EntityArthropod { +public class EntityEndermite extends EntityWalkingMob implements EntityArthropod { public static final int NETWORK_ID = 55; - @Override - public int getNetworkId() { - return NETWORK_ID; - } - public EntityEndermite(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(8); + public int getNetworkId() { + return NETWORK_ID; } @Override @@ -37,7 +28,13 @@ public float getHeight() { } @Override - public String getName() { - return "Endermite"; + public void initEntity() { + this.setMaxHealth(8); + super.initEntity(); + } + + @Override + public int getKillExperience() { + return 3; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityEvoker.java b/src/main/java/cn/nukkit/entity/mob/EntityEvoker.java index 6796e1c4b1b..81241717421 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityEvoker.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityEvoker.java @@ -1,12 +1,11 @@ package cn.nukkit.entity.mob; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityEvoker extends EntityMob { +public class EntityEvoker extends EntityWalkingMob { public static final int NETWORK_ID = 104; @@ -19,12 +18,6 @@ public int getNetworkId() { return NETWORK_ID; } - @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(24); - } - @Override public float getWidth() { return 0.6f; @@ -36,7 +29,18 @@ public float getHeight() { } @Override - public String getName() { - return "Evoker"; + protected void initEntity() { + this.setMaxHealth(24); + super.initEntity(); + } + + @Override + public Item[] getDrops() { + return new Item[]{Item.get(Item.EMERALD, 0, Utils.rand(0, 1)), Item.get(Item.TOTEM, 0, 1)}; + } + + @Override + public int getKillExperience() { + return 10; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityFlyingMob.java b/src/main/java/cn/nukkit/entity/mob/EntityFlyingMob.java new file mode 100644 index 00000000000..645f2f18a72 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/mob/EntityFlyingMob.java @@ -0,0 +1,12 @@ +package cn.nukkit.entity.mob; + +import cn.nukkit.entity.EntityFlying; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; + +public abstract class EntityFlyingMob extends EntityFlying implements EntityMob { + + public EntityFlyingMob(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } +} diff --git a/src/main/java/cn/nukkit/entity/mob/EntityGhast.java b/src/main/java/cn/nukkit/entity/mob/EntityGhast.java index e2c159c8f2c..917d423b1ee 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityGhast.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityGhast.java @@ -1,28 +1,24 @@ package cn.nukkit.entity.mob; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityGhast extends EntityMob { +import java.util.ArrayList; +import java.util.List; - public static final int NETWORK_ID = 41; +public class EntityGhast extends EntityFlyingMob { - @Override - public int getNetworkId() { - return NETWORK_ID; - } + public static final int NETWORK_ID = 41; public EntityGhast(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(10); + public int getNetworkId() { + return NETWORK_ID; } @Override @@ -36,7 +32,29 @@ public float getHeight() { } @Override - public String getName() { - return "Ghast"; + public void initEntity() { + this.setMaxHealth(10); + super.initEntity(); + + this.fireProof = true; + this.setDataFlag(DATA_FLAGS, DATA_FLAG_FIRE_IMMUNE, true); + } + + @Override + public Item[] getDrops() { + List drops = new ArrayList<>(); + + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.GUNPOWDER, 0, 1)); + } + + drops.add(Item.get(Item.GHAST_TEAR, 0, Utils.rand(0, 1))); + + return drops.toArray(new Item[0]); + } + + @Override + public int getKillExperience() { + return 5; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityGuardian.java b/src/main/java/cn/nukkit/entity/mob/EntityGuardian.java index d36e4754f42..d03344904c4 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityGuardian.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityGuardian.java @@ -1,42 +1,46 @@ package cn.nukkit.entity.mob; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityGuardian extends EntityMob { +public class EntityGuardian extends EntitySwimmingMob { public static final int NETWORK_ID = 49; + public EntityGuardian(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + @Override public int getNetworkId() { return NETWORK_ID; } - public EntityGuardian(FullChunk chunk, CompoundTag nbt) { - super(chunk, nbt); + @Override + public float getWidth() { + return 0.85f; } @Override - public void initEntity() { - super.initEntity(); - this.setMaxHealth(30); + public float getHeight() { + return 0.85f; } @Override - public String getName() { - return "Guardian"; + public void initEntity() { + this.setMaxHealth(30); + super.initEntity(); } @Override - public float getWidth() { - return 0.85f; + public Item[] getDrops() { + return new Item[]{Item.get(Item.PRISMARINE_SHARD, 0, Utils.rand(0, 2))}; } @Override - public float getHeight() { - return 0.85f; + public int getKillExperience() { + return 10; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityHoglin.java b/src/main/java/cn/nukkit/entity/mob/EntityHoglin.java index f5f3f8bc136..ef0b7f7d1de 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityHoglin.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityHoglin.java @@ -1,12 +1,17 @@ package cn.nukkit.entity.mob; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; + +import java.util.ArrayList; +import java.util.List; /** * @author Erik Miller | EinBexiii */ -public class EntityHoglin extends EntityMob { +public class EntityHoglin extends EntityWalkingMob { public final static int NETWORK_ID = 124; @@ -19,10 +24,15 @@ public EntityHoglin(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } + @Override + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); + } + @Override protected void initEntity() { - super.initEntity(); this.setMaxHealth(40); + super.initEntity(); } @Override @@ -36,7 +46,19 @@ public float getHeight() { } @Override - public String getName() { - return "Hoglin"; + public Item[] getDrops() { + List drops = new ArrayList<>(); + + if (!this.isBaby()) { + for (int i = 0; i < Utils.rand(2, 4); i++) { + drops.add(Item.get(this.isOnFire() ? Item.COOKED_PORKCHOP : Item.RAW_PORKCHOP, 0, 1)); + } + + if (Utils.rand()) { + drops.add(Item.get(Item.LEATHER)); + } + } + + return drops.toArray(new Item[0]); } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityHusk.java b/src/main/java/cn/nukkit/entity/mob/EntityHusk.java index 14d51dcd41b..82f25fea6b2 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityHusk.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityHusk.java @@ -1,29 +1,22 @@ package cn.nukkit.entity.mob; import cn.nukkit.entity.EntitySmite; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityHusk extends EntityMob implements EntitySmite { +public class EntityHusk extends EntityWalkingMob implements EntitySmite { public static final int NETWORK_ID = 47; - @Override - public int getNetworkId() { - return NETWORK_ID; - } - public EntityHusk(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(20); + public int getNetworkId() { + return NETWORK_ID; } @Override @@ -37,7 +30,18 @@ public float getHeight() { } @Override - public String getName() { - return "Husk"; + protected void initEntity() { + this.setMaxHealth(20); + super.initEntity(); + } + + @Override + public Item[] getDrops() { + return this.isBaby() ? new Item[0] : new Item[]{Item.get(Item.ROTTEN_FLESH, 0, Utils.rand(0, 2))}; + } + + @Override + public int getKillExperience() { + return this.isBaby() ? 0 : 5; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityJumpingMob.java b/src/main/java/cn/nukkit/entity/mob/EntityJumpingMob.java new file mode 100644 index 00000000000..7dea9748f66 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/mob/EntityJumpingMob.java @@ -0,0 +1,12 @@ +package cn.nukkit.entity.mob; + +import cn.nukkit.entity.EntityJumping; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; + +public abstract class EntityJumpingMob extends EntityJumping implements EntityMob { + + public EntityJumpingMob(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } +} diff --git a/src/main/java/cn/nukkit/entity/mob/EntityMagmaCube.java b/src/main/java/cn/nukkit/entity/mob/EntityMagmaCube.java index 14e85f22c72..4bcaa1db4dd 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityMagmaCube.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityMagmaCube.java @@ -1,42 +1,59 @@ package cn.nukkit.entity.mob; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityMagmaCube extends EntityMob { +public class EntityMagmaCube extends EntityJumpingMob { public static final int NETWORK_ID = 42; + public EntityMagmaCube(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + @Override public int getNetworkId() { return NETWORK_ID; } - public EntityMagmaCube(FullChunk chunk, CompoundTag nbt) { - super(chunk, nbt); + @Override + public float getWidth() { + return 1f; + } + + @Override + public float getHeight() { + return 1f; + } + + @Override + public float getLength() { + return 1f; } @Override protected void initEntity() { - super.initEntity(); this.setMaxHealth(16); + super.initEntity(); + + this.fireProof = true; + this.noFallDamage = true; } @Override - public float getWidth() { - return 2.04f; + public Item[] getDrops() { + return new Item[]{Item.get(Item.MAGMA_CREAM, 0, Utils.rand(0, 1))}; } @Override - public float getHeight() { - return 2.04f; + public int getKillExperience() { + return 4; } @Override public String getName() { - return "Magma Cube"; + return this.hasCustomName() ? this.getNameTag() : "Magma Cube"; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityMob.java b/src/main/java/cn/nukkit/entity/mob/EntityMob.java index f80fb439067..32203c66df1 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityMob.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityMob.java @@ -1,17 +1,4 @@ package cn.nukkit.entity.mob; -import cn.nukkit.entity.EntityCreature; -import cn.nukkit.level.format.FullChunk; -import cn.nukkit.nbt.tag.CompoundTag; - -/** - * author: MagicDroidX - * Nukkit Project - */ -public abstract class EntityMob extends EntityCreature { - - public EntityMob(FullChunk chunk, CompoundTag nbt) { - super(chunk, nbt); - } - +public interface EntityMob { } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityPhantom.java b/src/main/java/cn/nukkit/entity/mob/EntityPhantom.java index 0ca90c05810..15abd62e6af 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityPhantom.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityPhantom.java @@ -4,11 +4,9 @@ import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * Created by PetteriM1 - */ -public class EntityPhantom extends EntityMob implements EntitySmite { +public class EntityPhantom extends EntityFlyingMob implements EntitySmite { public static final int NETWORK_ID = 58; @@ -21,12 +19,6 @@ public int getNetworkId() { return NETWORK_ID; } - @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(20); - } - @Override public float getWidth() { return 0.9f; @@ -38,12 +30,23 @@ public float getHeight() { } @Override - public String getName() { - return "Phantom"; + public void initEntity() { + this.setMaxHealth(20); + super.initEntity(); } @Override public Item[] getDrops() { - return new Item[]{Item.get(470)}; + return new Item[]{Item.get(Item.PHANTOM_MEMBRANE, 0, Utils.rand(0, 1))}; + } + + @Override + public int getKillExperience() { + return 5; + } + + @Override + public boolean dropsOnNaturalDeath() { + return false; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityPiglin.java b/src/main/java/cn/nukkit/entity/mob/EntityPiglin.java index 2501de7ad8f..e25ff1483f3 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityPiglin.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityPiglin.java @@ -6,7 +6,7 @@ /** * @author Erik Miller | EinBexiii */ -public class EntityPiglin extends EntityMob { +public class EntityPiglin extends EntityWalkingMob { public final static int NETWORK_ID = 123; @@ -19,10 +19,15 @@ public EntityPiglin(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } + @Override + public int getKillExperience() { + return 5; + } + @Override protected void initEntity() { - super.initEntity(); this.setMaxHealth(16); + super.initEntity(); } @Override @@ -34,9 +39,4 @@ public float getWidth() { public float getHeight() { return 1.95f; } - - @Override - public String getName() { - return "Piglin"; - } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityPiglinBrute.java b/src/main/java/cn/nukkit/entity/mob/EntityPiglinBrute.java index 06dc5f991d7..cf650ac8296 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityPiglinBrute.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityPiglinBrute.java @@ -3,7 +3,7 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -public class EntityPiglinBrute extends EntityMob { +public class EntityPiglinBrute extends EntityWalkingMob { public static final int NETWORK_ID = 127; @@ -12,28 +12,33 @@ public EntityPiglinBrute(FullChunk chunk, CompoundTag nbt) { } @Override - public int getNetworkId() { - return NETWORK_ID; + public void initEntity() { + this.setMaxHealth(50); + super.initEntity(); + } + + @Override + public float getWidth() { + return 0.6f; } @Override public float getHeight() { - return 1.9f; + return 1.95f; } @Override - public float getWidth() { - return 0.6f; + public int getKillExperience() { + return 10; } @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(50); + public int getNetworkId() { + return NETWORK_ID; } @Override public String getName() { - return "PiglinBrute"; + return this.hasCustomName() ? this.getNameTag() : "Piglin Brute"; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityPillager.java b/src/main/java/cn/nukkit/entity/mob/EntityPillager.java index ff73d77f03a..06d62459ecf 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityPillager.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityPillager.java @@ -1,12 +1,18 @@ package cn.nukkit.entity.mob; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -public class EntityPillager extends EntityMob { +import java.util.ArrayList; +import java.util.List; + +public class EntityPillager extends EntityWalkingMob { public static final int NETWORK_ID = 114; + public EntityPillager(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @@ -16,12 +22,6 @@ public int getNetworkId() { return NETWORK_ID; } - @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(24); - } - @Override public float getWidth() { return 0.6f; @@ -33,7 +33,28 @@ public float getHeight() { } @Override - public String getName() { - return "Pillager"; + public void initEntity() { + this.setMaxHealth(24); + super.initEntity(); + } + + @Override + public Item[] getDrops() { + List drops = new ArrayList<>(); + + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.ARROW, 0, 1)); + } + + if (Utils.rand(1, 12) == 1) { + drops.add(Item.get(Item.CROSSBOW, Utils.rand(300, 380), Utils.rand(0, 1))); + } + + return drops.toArray(new Item[0]); + } + + @Override + public int getKillExperience() { + return 5; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityRavager.java b/src/main/java/cn/nukkit/entity/mob/EntityRavager.java index d082e3e7ccf..52e6c1ea166 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityRavager.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityRavager.java @@ -3,7 +3,7 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -public class EntityRavager extends EntityMob { +public class EntityRavager extends EntityWalkingMob { public static final int NETWORK_ID = 59; @@ -18,22 +18,22 @@ public int getNetworkId() { @Override protected void initEntity() { - super.initEntity(); this.setMaxHealth(100); + super.initEntity(); } @Override public float getHeight() { - return 1.9f; + return 2.2f; } @Override public float getWidth() { - return 1.2f; + return 1.95f; } @Override - public String getName() { - return "Ravager"; + public int getKillExperience() { + return 0; } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/entity/mob/EntityShulker.java b/src/main/java/cn/nukkit/entity/mob/EntityShulker.java index 02e176c1d38..0d62d1a6fed 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityShulker.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityShulker.java @@ -1,28 +1,21 @@ package cn.nukkit.entity.mob; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityShulker extends EntityMob { +public class EntityShulker extends EntityWalkingMob { public static final int NETWORK_ID = 54; - @Override - public int getNetworkId() { - return NETWORK_ID; - } - public EntityShulker(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(30); + public int getNetworkId() { + return NETWORK_ID; } @Override @@ -36,7 +29,26 @@ public float getHeight() { } @Override - public String getName() { - return "Shulker"; + protected void initEntity() { + this.setMaxHealth(15); + super.initEntity(); + this.fireProof = true; + this.noFallDamage = true; + + if (this.namedTag.contains("Color")) { + this.dataProperties.putInt(DATA_VARIANT, this.namedTag.getByte("Color")); + } else { + this.dataProperties.putInt(DATA_VARIANT, 16); + } + } + + @Override + public Item[] getDrops() { + return new Item[]{Item.get(Item.SHULKER_SHELL, 0, Utils.rand(0, 1))}; + } + + @Override + public int getKillExperience() { + return 5; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntitySilverfish.java b/src/main/java/cn/nukkit/entity/mob/EntitySilverfish.java index b864ba047d4..8a1346beb48 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntitySilverfish.java +++ b/src/main/java/cn/nukkit/entity/mob/EntitySilverfish.java @@ -4,25 +4,17 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -/** - * @author PikyCZ - */ -public class EntitySilverfish extends EntityMob implements EntityArthropod { +public class EntitySilverfish extends EntityWalkingMob implements EntityArthropod { public static final int NETWORK_ID = 39; - @Override - public int getNetworkId() { - return NETWORK_ID; - } - public EntitySilverfish(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override - public String getName() { - return "Silverfish"; + public int getNetworkId() { + return NETWORK_ID; } @Override @@ -37,7 +29,12 @@ public float getHeight() { @Override public void initEntity() { - super.initEntity(); this.setMaxHealth(8); + super.initEntity(); + } + + @Override + public int getKillExperience() { + return 5; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntitySkeleton.java b/src/main/java/cn/nukkit/entity/mob/EntitySkeleton.java index 79253f66dca..7517d5eeb50 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntitySkeleton.java +++ b/src/main/java/cn/nukkit/entity/mob/EntitySkeleton.java @@ -1,30 +1,37 @@ package cn.nukkit.entity.mob; +import cn.nukkit.Player; +import cn.nukkit.entity.Entity; import cn.nukkit.entity.EntitySmite; +import cn.nukkit.entity.projectile.EntityArrow; +import cn.nukkit.event.entity.EntityDamageByChildEntityEvent; import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; +import cn.nukkit.math.Vector2; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntitySkeleton extends EntityMob implements EntitySmite { +import java.util.ArrayList; +import java.util.List; + +public class EntitySkeleton extends EntityWalkingMob implements EntitySmite { public static final int NETWORK_ID = 34; - @Override - public int getNetworkId() { - return NETWORK_ID; - } public EntitySkeleton(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override - protected void initEntity() { - super.initEntity(); + public void initEntity() { this.setMaxHealth(20); + super.initEntity(); + } + + @Override + public int getNetworkId() { + return NETWORK_ID; } @Override @@ -38,12 +45,40 @@ public float getHeight() { } @Override - public String getName() { - return "Skeleton"; + public Item[] getDrops() { + List drops = new ArrayList<>(); + + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.BONE, 0, 1)); + } + + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.ARROW, 0, 1)); + } + + return drops.toArray(new Item[0]); } @Override - public Item[] getDrops() { - return new Item[]{Item.get(Item.BONE, Item.ARROW)}; + public int getKillExperience() { + return 5; + } + + @Override + public void kill() { + if (!this.isAlive()) { + return; + } + + super.kill(); + + if (this.lastDamageCause instanceof EntityDamageByChildEntityEvent) { + Entity damager; + if (((EntityDamageByChildEntityEvent) this.lastDamageCause).getChild() instanceof EntityArrow && (damager = ((EntityDamageByChildEntityEvent) this.lastDamageCause).getDamager()) instanceof Player) { + if (new Vector2(this.x, this.z).distance(new Vector2(damager.x, damager.z)) >= 50) { + ((Player) damager).awardAchievement("snipeSkeleton"); + } + } + } } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntitySlime.java b/src/main/java/cn/nukkit/entity/mob/EntitySlime.java index 34ba44764b2..a9a60296716 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntitySlime.java +++ b/src/main/java/cn/nukkit/entity/mob/EntitySlime.java @@ -3,46 +3,58 @@ import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntitySlime extends EntityMob { +import java.util.ArrayList; +import java.util.List; - public static final int NETWORK_ID = 37; +public class EntitySlime extends EntityJumpingMob { - @Override - public int getNetworkId() { - return NETWORK_ID; - } + public static final int NETWORK_ID = 37; public EntitySlime(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(16); + public int getNetworkId() { + return NETWORK_ID; } @Override public float getWidth() { - return 2.04f; + return 1f; } @Override public float getHeight() { - return 2.04f; + return 1f; } @Override - public String getName() { - return "Slime"; + public float getLength() { + return 1f; + } + + @Override + protected void initEntity() { + this.setMaxHealth(16); + super.initEntity(); } @Override public Item[] getDrops() { - return new Item[]{Item.get(Item.SLIMEBALL)}; + List drops = new ArrayList<>(); + + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.SLIMEBALL, 0, 1)); + } + + return drops.toArray(new Item[0]); + } + + @Override + public int getKillExperience() { + return 4; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntitySnowGolem.java b/src/main/java/cn/nukkit/entity/mob/EntitySnowGolem.java index 7b3967c7f00..f6b4c070e93 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntitySnowGolem.java +++ b/src/main/java/cn/nukkit/entity/mob/EntitySnowGolem.java @@ -1,25 +1,23 @@ package cn.nukkit.entity.mob; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; + +public class EntitySnowGolem extends EntityWalkingMob { + + public static final int NETWORK_ID = 21; -public class EntitySnowGolem extends EntityMob { public EntitySnowGolem(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } - - public static final int NETWORK_ID = 21; @Override public int getNetworkId() { return NETWORK_ID; } - @Override - public String getName() { - return "Snow Golem"; - } - @Override public float getWidth() { return 0.7f; @@ -31,8 +29,24 @@ public float getHeight() { } @Override - protected void initEntity() { - super.initEntity(); + public void initEntity() { this.setMaxHealth(4); + super.initEntity(); + this.noFallDamage = true; + } + + @Override + public Item[] getDrops() { + return new Item[]{Item.get(Item.SNOWBALL, 0, Utils.rand(0, 15))}; + } + + @Override + public int getKillExperience() { + return 0; + } + + @Override + public String getName() { + return this.hasCustomName() ? this.getNameTag() : "Snow Golem"; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntitySpider.java b/src/main/java/cn/nukkit/entity/mob/EntitySpider.java index efc0c021115..7183edcb238 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntitySpider.java +++ b/src/main/java/cn/nukkit/entity/mob/EntitySpider.java @@ -4,27 +4,22 @@ import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntitySpider extends EntityMob implements EntityArthropod { +import java.util.ArrayList; +import java.util.List; - public static final int NETWORK_ID = 35; +public class EntitySpider extends EntityWalkingMob implements EntityArthropod { - @Override - public int getNetworkId() { - return NETWORK_ID; - } + public static final int NETWORK_ID = 35; public EntitySpider(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(16); + public int getNetworkId() { + return NETWORK_ID; } @Override @@ -38,12 +33,28 @@ public float getHeight() { } @Override - public String getName() { - return "Spider"; + public void initEntity() { + this.setMaxHealth(16); + super.initEntity(); } @Override public Item[] getDrops() { - return new Item[]{Item.get(Item.STRING, Item.SPIDER_EYE)}; + List drops = new ArrayList<>(); + + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.STRING, 0, 1)); + } + + for (int i = 0; i < (Utils.rand(0, 2) == 0 ? 1 : 0); i++) { + drops.add(Item.get(Item.SPIDER_EYE, 0, 1)); + } + + return drops.toArray(new Item[0]); + } + + @Override + public int getKillExperience() { + return 5; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityStray.java b/src/main/java/cn/nukkit/entity/mob/EntityStray.java index 868f12614fd..07257f0703b 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityStray.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityStray.java @@ -1,30 +1,36 @@ package cn.nukkit.entity.mob; +import cn.nukkit.Player; +import cn.nukkit.entity.Entity; import cn.nukkit.entity.EntitySmite; +import cn.nukkit.entity.projectile.EntityArrow; +import cn.nukkit.event.entity.EntityDamageByChildEntityEvent; import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; +import cn.nukkit.math.Vector2; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityStray extends EntityMob implements EntitySmite { +import java.util.ArrayList; +import java.util.List; - public static final int NETWORK_ID = 46; +public class EntityStray extends EntityWalkingMob implements EntitySmite { - @Override - public int getNetworkId() { - return NETWORK_ID; - } + public static final int NETWORK_ID = 46; public EntityStray(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override - protected void initEntity() { - super.initEntity(); + public void initEntity() { this.setMaxHealth(20); + super.initEntity(); + } + + @Override + public int getNetworkId() { + return NETWORK_ID; } @Override @@ -34,16 +40,48 @@ public float getWidth() { @Override public float getHeight() { - return 1.99f; + return 1.9f; + } + + @Override + public Item[] getDrops() { + List drops = new ArrayList<>(); + + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.BONE, 0, 1)); + } + + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.ARROW, 0, 1)); + } + + if (Utils.rand()) { + drops.add(Item.get(Item.ARROW, 18, 1)); + } + + return drops.toArray(new Item[0]); } @Override - public String getName() { - return "Stray"; + public int getKillExperience() { + return 5; } @Override - public Item[] getDrops() { - return new Item[]{Item.get(Item.BONE, Item.ARROW)}; + public void kill() { + if (!this.isAlive()) { + return; + } + + super.kill(); + + if (this.lastDamageCause instanceof EntityDamageByChildEntityEvent) { + Entity damager; + if (((EntityDamageByChildEntityEvent) this.lastDamageCause).getChild() instanceof EntityArrow && (damager = ((EntityDamageByChildEntityEvent) this.lastDamageCause).getDamager()) instanceof Player) { + if (new Vector2(this.x, this.z).distance(new Vector2(damager.x, damager.z)) >= 50) { + ((Player) damager).awardAchievement("snipeSkeleton"); + } + } + } } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntitySwimmingMob.java b/src/main/java/cn/nukkit/entity/mob/EntitySwimmingMob.java new file mode 100644 index 00000000000..a21fbe6c550 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/mob/EntitySwimmingMob.java @@ -0,0 +1,12 @@ +package cn.nukkit.entity.mob; + +import cn.nukkit.entity.EntitySwimming; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; + +public abstract class EntitySwimmingMob extends EntitySwimming implements EntityMob { + + public EntitySwimmingMob(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } +} diff --git a/src/main/java/cn/nukkit/entity/mob/EntityTameableMob.java b/src/main/java/cn/nukkit/entity/mob/EntityTameableMob.java new file mode 100644 index 00000000000..f6ebb06279e --- /dev/null +++ b/src/main/java/cn/nukkit/entity/mob/EntityTameableMob.java @@ -0,0 +1,11 @@ +package cn.nukkit.entity.mob; + +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; + +public abstract class EntityTameableMob extends EntityWalkingMob /*implements EntityTameable*/ { + + public EntityTameableMob(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } +} diff --git a/src/main/java/cn/nukkit/entity/mob/EntityVex.java b/src/main/java/cn/nukkit/entity/mob/EntityVex.java index ee869bbde49..ebb50685a15 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityVex.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityVex.java @@ -3,10 +3,7 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -/** - * @author PikyCZ - */ -public class EntityVex extends EntityMob { +public class EntityVex extends EntityFlyingMob { public static final int NETWORK_ID = 105; @@ -20,23 +17,23 @@ public int getNetworkId() { } @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(14); + public float getWidth() { + return 0.8f; } @Override - public float getWidth() { + public float getHeight() { return 0.4f; } @Override - public float getHeight() { - return 0.8f; + public void initEntity() { + this.setMaxHealth(14); + super.initEntity(); } @Override - public String getName() { - return "Vex"; + public int getKillExperience() { + return 3; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityVindicator.java b/src/main/java/cn/nukkit/entity/mob/EntityVindicator.java index 6dc8d09d690..c5450f3d08c 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityVindicator.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityVindicator.java @@ -3,11 +3,9 @@ import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityVindicator extends EntityMob { +public class EntityVindicator extends EntityWalkingMob { public static final int NETWORK_ID = 57; @@ -20,12 +18,6 @@ public int getNetworkId() { return NETWORK_ID; } - @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(24); - } - @Override public float getWidth() { return 0.6f; @@ -37,12 +29,18 @@ public float getHeight() { } @Override - public String getName() { - return "Vindicator"; + protected void initEntity() { + this.setMaxHealth(24); + super.initEntity(); } @Override public Item[] getDrops() { - return new Item[]{Item.get(Item.IRON_AXE)}; + return new Item[]{Item.get(Item.EMERALD, 0, Utils.rand(0, 1))}; + } + + @Override + public int getKillExperience() { + return 5; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityWalkingMob.java b/src/main/java/cn/nukkit/entity/mob/EntityWalkingMob.java new file mode 100644 index 00000000000..ddddfc13fb7 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/mob/EntityWalkingMob.java @@ -0,0 +1,12 @@ +package cn.nukkit.entity.mob; + +import cn.nukkit.entity.EntityWalking; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; + +public abstract class EntityWalkingMob extends EntityWalking implements EntityMob { + + public EntityWalkingMob(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } +} diff --git a/src/main/java/cn/nukkit/entity/mob/EntityWarden.java b/src/main/java/cn/nukkit/entity/mob/EntityWarden.java index 2fa585880c9..2259184cd30 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityWarden.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityWarden.java @@ -3,7 +3,7 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -public class EntityWarden extends EntityMob { +public class EntityWarden extends EntityWalkingMob { public static final int NETWORK_ID = 131; @@ -11,6 +11,11 @@ public EntityWarden(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } + @Override + public int getKillExperience() { + return 5; + } + @Override public int getNetworkId() { return NETWORK_ID; @@ -28,12 +33,7 @@ public float getWidth() { @Override protected void initEntity() { - super.initEntity(); this.setMaxHealth(500); - } - - @Override - public String getName() { - return "Warden"; + super.initEntity(); } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityWitch.java b/src/main/java/cn/nukkit/entity/mob/EntityWitch.java index 57fbe490993..21e2e45f0a8 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityWitch.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityWitch.java @@ -1,28 +1,24 @@ package cn.nukkit.entity.mob; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityWitch extends EntityMob { +import java.util.ArrayList; +import java.util.List; - public static final int NETWORK_ID = 45; +public class EntityWitch extends EntityWalkingMob { - @Override - public int getNetworkId() { - return NETWORK_ID; - } + public static final int NETWORK_ID = 45; public EntityWitch(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(26); + public int getNetworkId() { + return NETWORK_ID; } @Override @@ -36,7 +32,46 @@ public float getHeight() { } @Override - public String getName() { - return "Witch"; + protected void initEntity() { + this.setMaxHealth(26); + super.initEntity(); + } + + @Override + public Item[] getDrops() { + List drops = new ArrayList<>(); + + drops.add(Item.get(Item.REDSTONE, 0, Utils.rand(4, 8))); + + if (Utils.rand(1, 4) == 1) { + drops.add(Item.get(Item.STICK, 0, Utils.rand(0, 2))); + } + + if (Utils.rand(1, 3) == 1) { + switch (Utils.rand(1, 5)) { + case 1: + drops.add(Item.get(Item.BOTTLE, 0, Utils.rand(0, 2))); + break; + case 2: + drops.add(Item.get(Item.GLOWSTONE_DUST, 0, Utils.rand(0, 2))); + break; + case 3: + drops.add(Item.get(Item.GUNPOWDER, 0, Utils.rand(0, 2))); + break; + case 4: + drops.add(Item.get(Item.SPIDER_EYE, 0, Utils.rand(0, 2))); + break; + case 5: + drops.add(Item.get(Item.SUGAR, 0, Utils.rand(0, 2))); + break; + } + } + + return drops.toArray(new Item[0]); + } + + @Override + public int getKillExperience() { + return 5; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityWither.java b/src/main/java/cn/nukkit/entity/mob/EntityWither.java index d90cf2929bb..8eed3f7165e 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityWither.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityWither.java @@ -1,25 +1,26 @@ package cn.nukkit.entity.mob; -import cn.nukkit.entity.EntitySmite; +import cn.nukkit.block.Block; +import cn.nukkit.entity.*; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.network.protocol.AddEntityPacket; +import cn.nukkit.network.protocol.DataPacket; -/** - * @author PikyCZ - */ -public class EntityWither extends EntityMob implements EntitySmite { +public class EntityWither extends EntityFlyingMob implements EntityBoss, EntitySmite { public static final int NETWORK_ID = 52; + public EntityWither(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + @Override public int getNetworkId() { return NETWORK_ID; } - public EntityWither(FullChunk chunk, CompoundTag nbt) { - super(chunk, nbt); - } - @Override public float getWidth() { return 0.9f; @@ -31,13 +32,51 @@ public float getHeight() { } @Override - protected void initEntity() { + public void initEntity() { + this.setMaxHealth(witherMaxHealth()); super.initEntity(); - this.setMaxHealth(300); + + this.fireProof = true; } @Override - public String getName() { - return "Wither"; + public int getKillExperience() { + return 50; + } + + @Override + public Item[] getDrops() { + return new Item[]{Item.get(Item.NETHER_STAR, 0, 1), Block.get(Item.WITHER_ROSE, 0).toItem()}; + } + + @Override + protected DataPacket createAddEntityPacket() { + AddEntityPacket addEntity = new AddEntityPacket(); + addEntity.type = NETWORK_ID; + addEntity.entityUniqueId = this.getId(); + addEntity.entityRuntimeId = this.getId(); + addEntity.yaw = (float) this.yaw; + addEntity.headYaw = (float) this.yaw; + addEntity.pitch = (float) this.pitch; + addEntity.x = (float) this.x; + addEntity.y = (float) this.y; + addEntity.z = (float) this.z; + addEntity.speedX = (float) this.motionX; + addEntity.speedY = (float) this.motionY; + addEntity.speedZ = (float) this.motionZ; + addEntity.metadata = this.dataProperties.clone(); + addEntity.attributes = new Attribute[]{Attribute.getAttribute(Attribute.MAX_HEALTH).setMaxValue(witherMaxHealth()).setValue(witherMaxHealth())}; + return addEntity; + } + + private int witherMaxHealth() { + switch (this.getServer().getDifficulty()) { + case 2: + return 450; + case 3: + return 600; + default: + return 300; + } } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityWitherSkeleton.java b/src/main/java/cn/nukkit/entity/mob/EntityWitherSkeleton.java index 4f7f9411ad0..414fa3297a3 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityWitherSkeleton.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityWitherSkeleton.java @@ -1,28 +1,38 @@ package cn.nukkit.entity.mob; +import cn.nukkit.Player; +import cn.nukkit.entity.Entity; import cn.nukkit.entity.EntitySmite; +import cn.nukkit.entity.projectile.EntityArrow; +import cn.nukkit.event.entity.EntityDamageByChildEntityEvent; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; +import cn.nukkit.math.Vector2; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityWitherSkeleton extends EntityMob implements EntitySmite { +import java.util.ArrayList; +import java.util.List; + +public class EntityWitherSkeleton extends EntityWalkingMob implements EntitySmite { public static final int NETWORK_ID = 48; + public EntityWitherSkeleton(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + @Override public int getNetworkId() { return NETWORK_ID; } - public EntityWitherSkeleton(FullChunk chunk, CompoundTag nbt) { - super(chunk, nbt); - } - @Override protected void initEntity() { + this.setMaxHealth(20); super.initEntity(); + + this.fireProof = true; } @Override @@ -35,8 +45,54 @@ public float getHeight() { return 2.4f; } + @Override + public Item[] getDrops() { + List drops = new ArrayList<>(); + + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.BONE, 0, 1)); + } + + if (Utils.rand(1, 3) == 1) { + drops.add(Item.get(Item.COAL, 0, 1)); + } + + if (Utils.rand(1, 40) == 1) { + drops.add(Item.get(Item.SKULL, 1, 1)); + } + + if (Utils.rand(1, 200) <= 17) { + drops.add(Item.get(Item.STONE_SWORD, Utils.rand(0, 131), 1)); + } + + return drops.toArray(new Item[0]); + } + + @Override + public int getKillExperience() { + return 5; + } + @Override public String getName() { - return "WitherSkeleton"; + return this.hasCustomName() ? this.getNameTag() : "Wither Skeleton"; + } + + @Override + public void kill() { + if (!this.isAlive()) { + return; + } + + super.kill(); + + if (this.lastDamageCause instanceof EntityDamageByChildEntityEvent) { + Entity damager; + if (((EntityDamageByChildEntityEvent) this.lastDamageCause).getChild() instanceof EntityArrow && (damager = ((EntityDamageByChildEntityEvent) this.lastDamageCause).getDamager()) instanceof Player) { + if (new Vector2(this.x, this.z).distance(new Vector2(damager.x, damager.z)) >= 50) { + ((Player) damager).awardAchievement("snipeSkeleton"); + } + } + } } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityZoglin.java b/src/main/java/cn/nukkit/entity/mob/EntityZoglin.java index 1be82ee3714..9626d452760 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityZoglin.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityZoglin.java @@ -1,12 +1,14 @@ package cn.nukkit.entity.mob; +import cn.nukkit.entity.EntitySmite; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; /** * @author Erik Miller | EinBexiii */ -public class EntityZoglin extends EntityMob { +public class EntityZoglin extends EntityWalkingMob implements EntitySmite { public final static int NETWORK_ID = 126; @@ -19,10 +21,15 @@ public EntityZoglin(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } + @Override + public int getKillExperience() { + return this.isBaby() ? 1 : Utils.rand(1, 3); + } + @Override protected void initEntity() { - super.initEntity(); this.setMaxHealth(40); + super.initEntity(); } @Override @@ -34,9 +41,4 @@ public float getWidth() { public float getHeight() { return 0.9f; } - - @Override - public String getName() { - return "Zoglin"; - } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityZombie.java b/src/main/java/cn/nukkit/entity/mob/EntityZombie.java index c47e2ffaa3d..1f931b738ac 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityZombie.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityZombie.java @@ -4,26 +4,17 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -/** - * Created by Dr. Nick Doran on 4/23/2017. - */ -public class EntityZombie extends EntityMob implements EntitySmite { +public class EntityZombie extends EntityWalkingMob implements EntitySmite { public static final int NETWORK_ID = 32; - @Override - public int getNetworkId() { - return NETWORK_ID; - } - public EntityZombie(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(20); + public int getNetworkId() { + return NETWORK_ID; } @Override @@ -37,7 +28,13 @@ public float getHeight() { } @Override - public String getName() { - return "Zombie"; + protected void initEntity() { + this.setMaxHealth(20); + super.initEntity(); + } + + @Override + public int getKillExperience() { + return this.isBaby() ? 12 : 5; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityZombiePigman.java b/src/main/java/cn/nukkit/entity/mob/EntityZombiePigman.java index 15b5280145f..98d127a9b8d 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityZombiePigman.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityZombiePigman.java @@ -1,43 +1,68 @@ package cn.nukkit.entity.mob; import cn.nukkit.entity.EntitySmite; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityZombiePigman extends EntityMob implements EntitySmite { +import java.util.ArrayList; +import java.util.List; + +public class EntityZombiePigman extends EntityWalkingMob implements EntitySmite { public static final int NETWORK_ID = 36; + public EntityZombiePigman(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + @Override public int getNetworkId() { return NETWORK_ID; } - public EntityZombiePigman(FullChunk chunk, CompoundTag nbt) { - super(chunk, nbt); + @Override + public float getWidth() { + return 0.6f; + } + + @Override + public float getHeight() { + return 1.95f; } @Override protected void initEntity() { - super.initEntity(); this.setMaxHealth(20); + super.initEntity(); + + this.fireProof = true; } @Override - public float getWidth() { - return 0.6f; + public Item[] getDrops() { + List drops = new ArrayList<>(); + + if (!this.isBaby()) { + drops.add(Item.get(Item.ROTTEN_FLESH, 0, Utils.rand(0, 1))); + drops.add(Item.get(Item.GOLD_NUGGET, 0, Utils.rand(0, 1))); + + for (int i = 0; i < (Utils.rand(0, 101) <= 9 ? 1 : 0); i++) { + drops.add(Item.get(Item.GOLD_SWORD, Utils.rand(20, 30), 1)); + } + } + + return drops.toArray(new Item[0]); } @Override - public float getHeight() { - return 1.95f; + public int getKillExperience() { + return this.isBaby() ? 0 : 5; } @Override public String getName() { - return "ZombiePigman"; + return this.hasCustomName() ? this.getNameTag() : "Zombified Piglin"; } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityZombieVillager.java b/src/main/java/cn/nukkit/entity/mob/EntityZombieVillager.java index 25f84616d30..08e3cd9ad14 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityZombieVillager.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityZombieVillager.java @@ -4,7 +4,7 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -public class EntityZombieVillager extends EntityMob implements EntitySmite { +public class EntityZombieVillager extends EntityZombieVillagerV1 implements EntitySmite { public static final int NETWORK_ID = 116; @@ -16,25 +16,4 @@ public EntityZombieVillager(FullChunk chunk, CompoundTag nbt) { public int getNetworkId() { return NETWORK_ID; } - - @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(20); - } - - @Override - public float getWidth() { - return 0.6f; - } - - @Override - public float getHeight() { - return 1.95f; - } - - @Override - public String getName() { - return "Zombie Villager"; - } } diff --git a/src/main/java/cn/nukkit/entity/mob/EntityZombieVillagerV1.java b/src/main/java/cn/nukkit/entity/mob/EntityZombieVillagerV1.java index f6d63d33271..13e60b026ab 100644 --- a/src/main/java/cn/nukkit/entity/mob/EntityZombieVillagerV1.java +++ b/src/main/java/cn/nukkit/entity/mob/EntityZombieVillagerV1.java @@ -1,43 +1,23 @@ package cn.nukkit.entity.mob; -import cn.nukkit.entity.EntitySmite; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -/** - * @author PikyCZ - */ -public class EntityZombieVillagerV1 extends EntityMob implements EntitySmite { +public class EntityZombieVillagerV1 extends EntityZombie { public static final int NETWORK_ID = 44; - @Override - public int getNetworkId() { - return NETWORK_ID; - } - public EntityZombieVillagerV1(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(20); - } - - @Override - public float getWidth() { - return 0.6f; - } - - @Override - public float getHeight() { - return 1.95f; + public int getNetworkId() { + return NETWORK_ID; } @Override public String getName() { - return "Zombie Villager"; + return this.hasCustomName() ? this.getNameTag() : "Zombie Villager"; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityAllay.java b/src/main/java/cn/nukkit/entity/passive/EntityAllay.java index 21733cbf4a9..7fbae4ceac8 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityAllay.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityAllay.java @@ -3,7 +3,7 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -public class EntityAllay extends EntityAnimal { +public class EntityAllay extends EntityFlyingAnimal { public static final int NETWORK_ID = 134; @@ -17,23 +17,23 @@ public int getNetworkId() { } @Override - public float getHeight() { + public float getWidth() { return 0.6f; } @Override - public float getWidth() { + public float getHeight() { return 0.6f; } @Override - protected void initEntity() { - super.initEntity(); + public void initEntity() { this.setMaxHealth(20); + super.initEntity(); } @Override - public String getName() { - return "Allay"; + public int getKillExperience() { + return 0; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityAnimal.java b/src/main/java/cn/nukkit/entity/passive/EntityAnimal.java index a8943d2b50c..1be98d23874 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityAnimal.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityAnimal.java @@ -1,28 +1,4 @@ package cn.nukkit.entity.passive; -import cn.nukkit.entity.Entity; -import cn.nukkit.entity.EntityAgeable; -import cn.nukkit.entity.EntityCreature; -import cn.nukkit.item.Item; -import cn.nukkit.level.format.FullChunk; -import cn.nukkit.nbt.tag.CompoundTag; - -/** - * author: MagicDroidX - * Nukkit Project - */ -public abstract class EntityAnimal extends EntityCreature implements EntityAgeable { - public EntityAnimal(FullChunk chunk, CompoundTag nbt) { - super(chunk, nbt); - } - - @Override - public boolean isBaby() { - return this.getDataFlag(DATA_FLAGS, Entity.DATA_FLAG_BABY); - } - - public boolean isBreedingItem(Item item) { - return item.getId() == Item.WHEAT; //default - } - +public interface EntityAnimal { } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityArmadillo.java b/src/main/java/cn/nukkit/entity/passive/EntityArmadillo.java new file mode 100644 index 00000000000..f06daf1bd2e --- /dev/null +++ b/src/main/java/cn/nukkit/entity/passive/EntityArmadillo.java @@ -0,0 +1,46 @@ +package cn.nukkit.entity.passive; + +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; + +public class EntityArmadillo extends EntityWalkingAnimal { + + public static final int NETWORK_ID = 142; + + public EntityArmadillo(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + @Override + public void initEntity() { + this.setMaxHealth(12); + super.initEntity(); + } + + @Override + public float getWidth() { + if (this.isBaby()) { + return 0.42f; + } + return 0.7f; + } + + @Override + public float getHeight() { + if (this.isBaby()) { + return 0.39f; + } + return 0.65f; + } + + @Override + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); + } + + @Override + public int getNetworkId() { + return NETWORK_ID; + } +} diff --git a/src/main/java/cn/nukkit/entity/passive/EntityAxolotl.java b/src/main/java/cn/nukkit/entity/passive/EntityAxolotl.java index 428bb0014a6..05290633d52 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityAxolotl.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityAxolotl.java @@ -3,7 +3,7 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -public class EntityAxolotl extends EntityAnimal { +public class EntityAxolotl extends EntityFish { public static final int NETWORK_ID = 130; @@ -12,13 +12,14 @@ public EntityAxolotl(FullChunk chunk, CompoundTag nbt) { } @Override - public int getNetworkId() { - return NETWORK_ID; + public void initEntity() { + this.setMaxHealth(14); + super.initEntity(); } @Override - public float getHeight() { - return 0.42f; + public int getNetworkId() { + return NETWORK_ID; } @Override @@ -27,13 +28,12 @@ public float getWidth() { } @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(14); + public float getHeight() { + return 0.42f; } @Override - public String getName() { - return "Axolotl"; + int getBucketMeta() { + return 12; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityBat.java b/src/main/java/cn/nukkit/entity/passive/EntityBat.java index de801a1efe8..b755369ac26 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityBat.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityBat.java @@ -3,10 +3,7 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -/** - * @author PikyCZ - */ -public class EntityBat extends EntityAnimal { +public class EntityBat extends EntityFlyingAnimal { public static final int NETWORK_ID = 19; @@ -31,7 +28,12 @@ public float getHeight() { @Override public void initEntity() { - super.initEntity(); this.setMaxHealth(6); + super.initEntity(); + } + + @Override + public int getKillExperience() { + return 0; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityBee.java b/src/main/java/cn/nukkit/entity/passive/EntityBee.java index 8bd10b0db07..58b59e51069 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityBee.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityBee.java @@ -1,13 +1,11 @@ package cn.nukkit.entity.passive; +import cn.nukkit.entity.mob.EntityFlyingMob; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author Kaooot - * @version 1.0 - */ -public class EntityBee extends EntityAnimal { +public class EntityBee extends EntityFlyingMob { public static final int NETWORK_ID = 122; @@ -15,6 +13,11 @@ public EntityBee(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } + @Override + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); + } + @Override public int getNetworkId() { return NETWORK_ID; @@ -23,22 +26,22 @@ public int getNetworkId() { @Override public float getWidth() { if (this.isBaby()) { - return 0.35f; + return 0.275f; } - return 0.7f; + return 0.55f; } @Override public float getHeight() { if (this.isBaby()) { - return 0.30f; + return 0.25f; } - return 0.6f; + return 0.5f; } @Override - protected void initEntity() { - super.initEntity(); + public void initEntity() { this.setMaxHealth(10); + super.initEntity(); } -} \ No newline at end of file +} diff --git a/src/main/java/cn/nukkit/entity/passive/EntityCamel.java b/src/main/java/cn/nukkit/entity/passive/EntityCamel.java new file mode 100644 index 00000000000..2f26eff7c01 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/passive/EntityCamel.java @@ -0,0 +1,46 @@ +package cn.nukkit.entity.passive; + +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; + +public class EntityCamel extends EntityWalkingAnimal { + + public static final int NETWORK_ID = 138; + + public EntityCamel(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + @Override + public void initEntity() { + this.setMaxHealth(32); + super.initEntity(); + } + + @Override + public float getWidth() { + if (this.isBaby()) { + return 0.85f; + } + return 1.77f; + } + + @Override + public float getHeight() { + if (this.isBaby()) { + return 1.1875f; + } + return 2.375f; + } + + @Override + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); + } + + @Override + public int getNetworkId() { + return NETWORK_ID; + } +} diff --git a/src/main/java/cn/nukkit/entity/passive/EntityCat.java b/src/main/java/cn/nukkit/entity/passive/EntityCat.java index 6381ea60561..4f5e183cae8 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityCat.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityCat.java @@ -1,9 +1,14 @@ package cn.nukkit.entity.passive; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -public class EntityCat extends EntityAnimal { +import java.util.ArrayList; +import java.util.List; + +public class EntityCat extends EntityWalkingAnimal { public static final int NETWORK_ID = 75; @@ -34,7 +39,26 @@ public float getHeight() { @Override public void initEntity() { - super.initEntity(); this.setMaxHealth(10); + super.initEntity(); + this.noFallDamage = true; + } + + @Override + public Item[] getDrops() { + List drops = new ArrayList<>(); + + if (!this.isBaby()) { + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.STRING, 0, 1)); + } + } + + return drops.toArray(new Item[0]); + } + + @Override + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityChicken.java b/src/main/java/cn/nukkit/entity/passive/EntityChicken.java index 844461254f8..d9bbf09a666 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityChicken.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityChicken.java @@ -1,13 +1,15 @@ package cn.nukkit.entity.passive; +import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * Author: BeYkeRYkt Nukkit Project - */ -public class EntityChicken extends EntityAnimal { +import java.util.ArrayList; +import java.util.List; + +public class EntityChicken extends EntityWalkingAnimal { public static final int NETWORK_ID = 10; @@ -15,6 +17,11 @@ public EntityChicken(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } + @Override + public int getNetworkId() { + return NETWORK_ID; + } + @Override public float getWidth() { if (this.isBaby()) { @@ -32,30 +39,48 @@ public float getHeight() { } @Override - public String getName() { - return "Chicken"; + public float getDrag() { + return 0.2f; } @Override - public Item[] getDrops() { - return new Item[]{Item.get(((this.isOnFire()) ? Item.COOKED_CHICKEN : Item.RAW_CHICKEN)), Item.get(Item.FEATHER)}; + public float getGravity() { + return 0.08f; //Should be lower but that breaks jumping } @Override - public int getNetworkId() { - return NETWORK_ID; + public void initEntity() { + this.setMaxHealth(4); + super.initEntity(); + this.noFallDamage = true; } @Override - protected void initEntity() { - super.initEntity(); - setMaxHealth(4); + public Item[] getDrops() { + List drops = new ArrayList<>(); + + if (!this.isBaby()) { + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.FEATHER, 0, 1)); + } + + drops.add(Item.get(this.isOnFire() ? Item.COOKED_CHICKEN : Item.RAW_CHICKEN, 0, 1)); + } + + return drops.toArray(new Item[0]); } @Override - public boolean isBreedingItem(Item item) { - int id = item.getId(); + public boolean attack(EntityDamageEvent ev) { + if (ev.getCause() != EntityDamageEvent.DamageCause.FALL) { + return super.attack(ev); + } - return id == Item.WHEAT_SEEDS || id == Item.MELON_SEEDS || id == Item.PUMPKIN_SEEDS || id == Item.BEETROOT_SEEDS; + return false; + } + + @Override + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityCod.java b/src/main/java/cn/nukkit/entity/passive/EntityCod.java index 795174f7e3c..b637454fbad 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityCod.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityCod.java @@ -1,12 +1,11 @@ package cn.nukkit.entity.passive; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * Created by PetteriM1 - */ -public class EntityCod extends EntityAnimal { +public class EntityCod extends EntityFish { public static final int NETWORK_ID = 112; @@ -15,12 +14,13 @@ public EntityCod(FullChunk chunk, CompoundTag nbt) { } @Override - public int getNetworkId() { - return NETWORK_ID; + int getBucketMeta() { + return 2; } - public String getName() { - return "Cod"; + @Override + public int getNetworkId() { + return NETWORK_ID; } @Override @@ -35,7 +35,12 @@ public float getHeight() { @Override public void initEntity() { - super.initEntity(); this.setMaxHealth(3); + super.initEntity(); + } + + @Override + public Item[] getDrops() { + return new Item[]{Item.get(Item.RAW_FISH, 0, 1), Item.get(Item.BONE, 0, Utils.rand(0, 2))}; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityCow.java b/src/main/java/cn/nukkit/entity/passive/EntityCow.java index 17f13ac2640..71fcd7bbc27 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityCow.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityCow.java @@ -3,11 +3,12 @@ import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * Author: BeYkeRYkt Nukkit Project - */ -public class EntityCow extends EntityAnimal { +import java.util.ArrayList; +import java.util.List; + +public class EntityCow extends EntityWalkingAnimal { public static final int NETWORK_ID = 11; @@ -15,6 +16,11 @@ public EntityCow(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } + @Override + public int getNetworkId() { + return NETWORK_ID; + } + @Override public float getWidth() { if (this.isBaby()) { @@ -32,23 +38,30 @@ public float getHeight() { } @Override - public String getName() { - return "Cow"; + public void initEntity() { + this.setMaxHealth(10); + super.initEntity(); } @Override public Item[] getDrops() { - return new Item[]{Item.get(Item.LEATHER), Item.get(((this.isOnFire()) ? Item.COOKED_BEEF : Item.RAW_BEEF))}; - } + List drops = new ArrayList<>(); - @Override - public int getNetworkId() { - return NETWORK_ID; + if (!this.isBaby()) { + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.LEATHER, 0, 1)); + } + + for (int i = 0; i < Utils.rand(1, 3); i++) { + drops.add(Item.get(this.isOnFire() ? Item.STEAK : Item.RAW_BEEF, 0, 1)); + } + } + + return drops.toArray(new Item[0]); } @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(10); + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityDolphin.java b/src/main/java/cn/nukkit/entity/passive/EntityDolphin.java index 27585ac8727..db197330417 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityDolphin.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityDolphin.java @@ -3,11 +3,9 @@ import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * Created by PetteriM1 - */ -public class EntityDolphin extends EntityAnimal { +public class EntityDolphin extends EntityWaterAnimal { public static final int NETWORK_ID = 31; @@ -20,10 +18,6 @@ public int getNetworkId() { return NETWORK_ID; } - public String getName() { - return "Dolphin"; - } - @Override public float getWidth() { return 0.9f; @@ -36,12 +30,17 @@ public float getHeight() { @Override public void initEntity() { - super.initEntity(); this.setMaxHealth(10); + super.initEntity(); } @Override public Item[] getDrops() { - return new Item[]{Item.get(Item.RAW_FISH)}; + return new Item[]{Item.get(Item.RAW_FISH, 0, Utils.rand(0, 1))}; + } + + @Override + public int getKillExperience() { + return 0; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityDonkey.java b/src/main/java/cn/nukkit/entity/passive/EntityDonkey.java index 143bbaa6f58..d23a29c22e0 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityDonkey.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityDonkey.java @@ -3,11 +3,12 @@ import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityDonkey extends EntityAnimal { +import java.util.ArrayList; +import java.util.List; + +public class EntityDonkey extends EntityHorseBase { public static final int NETWORK_ID = 24; @@ -38,12 +39,20 @@ public float getHeight() { @Override public void initEntity() { - super.initEntity(); this.setMaxHealth(15); + super.initEntity(); } @Override public Item[] getDrops() { - return new Item[]{Item.get(Item.LEATHER)}; + List drops = new ArrayList<>(); + + if (!this.isBaby()) { + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.LEATHER, 0, 1)); + } + } + + return drops.toArray(new Item[0]); } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityFish.java b/src/main/java/cn/nukkit/entity/passive/EntityFish.java new file mode 100644 index 00000000000..53a41cdb408 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/passive/EntityFish.java @@ -0,0 +1,40 @@ +package cn.nukkit.entity.passive; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.math.Vector3; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; + +public abstract class EntityFish extends EntityWaterAnimal { + + public EntityFish(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + @Override + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); + } + + @Override + public boolean onInteract(Player player, Item item, Vector3 clickedPos) { + if (item.getId() == Item.BUCKET && (item.getDamage() == 0 || item.getDamage() == 8) && this.isInsideOfWater()) { + this.close(); + if (item.getCount() <= 1) { + player.getInventory().setItemInHand(Item.get(Item.BUCKET, this.getBucketMeta(), 1)); + return false; + } else { + if (!player.isCreative()) { + player.getInventory().decreaseCount(player.getInventory().getHeldItemIndex()); + } + player.getInventory().addItem(Item.get(Item.BUCKET, this.getBucketMeta(), 1)); + return true; + } + } + return super.onInteract(player, item, clickedPos); + } + + abstract int getBucketMeta(); +} diff --git a/src/main/java/cn/nukkit/entity/passive/EntityFlyingAnimal.java b/src/main/java/cn/nukkit/entity/passive/EntityFlyingAnimal.java new file mode 100644 index 00000000000..b3a57050512 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/passive/EntityFlyingAnimal.java @@ -0,0 +1,12 @@ +package cn.nukkit.entity.passive; + +import cn.nukkit.entity.EntityFlying; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; + +public abstract class EntityFlyingAnimal extends EntityFlying implements EntityAnimal { + + public EntityFlyingAnimal(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } +} diff --git a/src/main/java/cn/nukkit/entity/passive/EntityFox.java b/src/main/java/cn/nukkit/entity/passive/EntityFox.java index 825c17108da..5bc676a787a 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityFox.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityFox.java @@ -2,12 +2,9 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author Kaooot - * @version 1.0 - */ -public class EntityFox extends EntityAnimal { +public class EntityFox extends EntityWalkingAnimal { public static final int NETWORK_ID = 121; @@ -31,13 +28,13 @@ public float getHeight() { } @Override - protected void initEntity() { - super.initEntity(); + public void initEntity() { this.setMaxHealth(20); + super.initEntity(); } @Override - public String getName() { - return "Fox"; + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 2); } -} \ No newline at end of file +} diff --git a/src/main/java/cn/nukkit/entity/passive/EntityFrog.java b/src/main/java/cn/nukkit/entity/passive/EntityFrog.java index a1c7492d6ee..936e03f671c 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityFrog.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityFrog.java @@ -2,8 +2,9 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -public class EntityFrog extends EntityAnimal { +public class EntityFrog extends EntityJumpingAnimal { public static final int NETWORK_ID = 132; @@ -11,6 +12,11 @@ public EntityFrog(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } + @Override + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); + } + @Override public int getNetworkId() { return NETWORK_ID; @@ -28,12 +34,7 @@ public float getWidth() { @Override protected void initEntity() { - super.initEntity(); this.setMaxHealth(10); - } - - @Override - public String getName() { - return "Frog"; + super.initEntity(); } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityGlowSquid.java b/src/main/java/cn/nukkit/entity/passive/EntityGlowSquid.java index c408c718b96..ed7e6621e24 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityGlowSquid.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityGlowSquid.java @@ -3,7 +3,7 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -public class EntityGlowSquid extends EntityWaterAnimal { +public class EntityGlowSquid extends EntitySquid { public static final int NETWORK_ID = 129; @@ -15,25 +15,4 @@ public EntityGlowSquid(FullChunk chunk, CompoundTag nbt) { public int getNetworkId() { return NETWORK_ID; } - - @Override - public float getHeight() { - return 0.95f; - } - - @Override - public float getWidth() { - return 0.475f; - } - - @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(10); - } - - @Override - public String getName() { - return "GlowSquid"; - } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityGoat.java b/src/main/java/cn/nukkit/entity/passive/EntityGoat.java index e337b8ce825..583aeac0f8f 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityGoat.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityGoat.java @@ -2,8 +2,9 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -public class EntityGoat extends EntityAnimal { +public class EntityGoat extends EntityWalkingAnimal { public static final int NETWORK_ID = 128; @@ -12,28 +13,34 @@ public EntityGoat(FullChunk chunk, CompoundTag nbt) { } @Override - public int getNetworkId() { - return NETWORK_ID; + public void initEntity() { + this.setMaxHealth(10); + super.initEntity(); } @Override - public float getHeight() { - return this.isBaby() ? 0.65f : 1.3f; + public float getWidth() { + if (this.isBaby()) { + return 0.65f; + } + return 1.3f; } @Override - public float getWidth() { - return this.isBaby() ? 0.45f : 0.9f; + public float getHeight() { + if (this.isBaby()) { + return 0.45f; + } + return 0.9f; } @Override - protected void initEntity() { - super.initEntity(); - this.setMaxHealth(10); + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); } @Override - public String getName() { - return "Goat"; + public int getNetworkId() { + return NETWORK_ID; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityHorse.java b/src/main/java/cn/nukkit/entity/passive/EntityHorse.java index a0c84895329..20ede148e77 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityHorse.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityHorse.java @@ -1,16 +1,23 @@ package cn.nukkit.entity.passive; +import cn.nukkit.entity.data.IntEntityData; import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityHorse extends EntityAnimal { +import java.util.ArrayList; +import java.util.List; + +public class EntityHorse extends EntityHorseBase { public static final int NETWORK_ID = 23; + public int variant; + + private static final int[] VARIANTS = {0, 1, 2, 3, 4, 5, 6, 256, 257, 258, 259, 260, 261, 262, 512, 513, 514, 515, 516, 517, 518, + 768, 769, 770, 771, 772, 773, 774, 1024, 1025, 1026, 1027, 1028, 1029, 1030}; + public EntityHorse(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @@ -38,12 +45,39 @@ public float getHeight() { @Override public void initEntity() { + this.setMaxHealth(Utils.rand(15, 30)); //TODO: save this super.initEntity(); - this.setMaxHealth(15); + + if (this.namedTag.contains("Variant")) { + this.variant = this.namedTag.getInt("Variant"); + } else { + this.variant = getRandomVariant(); + } + + this.setDataProperty(new IntEntityData(DATA_VARIANT, this.variant)); + } + + @Override + public void saveNBT() { + super.saveNBT(); + + this.namedTag.putInt("Variant", this.variant); } @Override public Item[] getDrops() { - return new Item[]{Item.get(Item.LEATHER)}; + List drops = new ArrayList<>(); + + if (!this.isBaby()) { + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.LEATHER, 0, 1)); + } + } + + return drops.toArray(new Item[0]); + } + + private static int getRandomVariant() { + return VARIANTS[Utils.rand(0, VARIANTS.length - 1)]; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityHorseBase.java b/src/main/java/cn/nukkit/entity/passive/EntityHorseBase.java new file mode 100644 index 00000000000..5f33a61e462 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/passive/EntityHorseBase.java @@ -0,0 +1,16 @@ +package cn.nukkit.entity.passive; + +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; + +public abstract class EntityHorseBase extends EntityWalkingAnimal /*implements EntityRideable, EntityControllable*/ { + + public EntityHorseBase(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + @Override + public int getKillExperience() { + return 0; + } +} diff --git a/src/main/java/cn/nukkit/entity/passive/EntityIronGolem.java b/src/main/java/cn/nukkit/entity/passive/EntityIronGolem.java new file mode 100644 index 00000000000..746b1ec2aa5 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/passive/EntityIronGolem.java @@ -0,0 +1,94 @@ +package cn.nukkit.entity.passive; + +import cn.nukkit.Player; +import cn.nukkit.Server; +import cn.nukkit.entity.Attribute; +import cn.nukkit.entity.mob.EntityWalkingMob; +import cn.nukkit.item.Item; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.network.protocol.UpdateAttributesPacket; +import cn.nukkit.utils.Utils; + +import java.util.ArrayList; +import java.util.List; + +public class EntityIronGolem extends EntityWalkingMob { + + public static final int NETWORK_ID = 20; + + public EntityIronGolem(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + @Override + public int getNetworkId() { + return NETWORK_ID; + } + + @Override + public float getWidth() { + return 1.4f; + } + + @Override + public float getHeight() { + return 2.9f; + } + + @Override + public void initEntity() { + this.setMaxHealth(100); + super.initEntity(); + this.noFallDamage = true; + } + + @Override + public Item[] getDrops() { + List drops = new ArrayList<>(); + + for (int i = 0; i < Utils.rand(3, 5); i++) { + drops.add(Item.get(Item.IRON_INGOT, 0, 1)); + } + + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.POPPY, 0, 1)); + } + + return drops.toArray(new Item[0]); + } + + @Override + public int getKillExperience() { + return 0; + } + + @Override + public String getName() { + return this.hasCustomName() ? this.getNameTag() : "Iron Golem"; + } + + @Override + public void spawnTo(Player player) { + super.spawnTo(player); + + this.sendHealth(); + } + + @Override + public void setHealth(float health) { + super.setHealth(health); + + this.sendHealth(); + } + + private void sendHealth() { + if (this.isAlive()) { + UpdateAttributesPacket pk = new UpdateAttributesPacket(); + int max = this.getMaxHealth(); + pk.entries = new Attribute[]{Attribute.getAttribute(Attribute.MAX_HEALTH).setMaxValue(max).setValue(this.health < max ? this.health : max)}; + pk.entityId = this.id; + Server.broadcastPacket(this.getViewers().values(), pk); + } + } +} diff --git a/src/main/java/cn/nukkit/entity/passive/EntityJumpingAnimal.java b/src/main/java/cn/nukkit/entity/passive/EntityJumpingAnimal.java new file mode 100644 index 00000000000..e81cc88c585 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/passive/EntityJumpingAnimal.java @@ -0,0 +1,12 @@ +package cn.nukkit.entity.passive; + +import cn.nukkit.entity.EntityJumping; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; + +public abstract class EntityJumpingAnimal extends EntityJumping implements EntityAnimal { + + public EntityJumpingAnimal(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } +} diff --git a/src/main/java/cn/nukkit/entity/passive/EntityLlama.java b/src/main/java/cn/nukkit/entity/passive/EntityLlama.java index 6536a79ee0c..62ecda1b7fa 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityLlama.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityLlama.java @@ -1,15 +1,19 @@ package cn.nukkit.entity.passive; +import cn.nukkit.entity.data.IntEntityData; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityLlama extends EntityAnimal { +public class EntityLlama extends EntityHorseBase { public static final int NETWORK_ID = 29; + private int variant; + + private static final int[] VARIANTS = {0, 1, 2, 3}; + public EntityLlama(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @@ -35,17 +39,33 @@ public float getHeight() { return 1.87f; } + @Override - public float getEyeHeight() { - if (this.isBaby()) { - return 0.65f; + public void initEntity() { + this.setMaxHealth(15); + super.initEntity(); + + if (this.namedTag.contains("Variant")) { + this.variant = this.namedTag.getInt("Variant"); + } else { + this.variant = getRandomVariant(); } - return 1.2f; + + this.setDataProperty(new IntEntityData(DATA_VARIANT, this.variant)); } @Override - public void initEntity() { - super.initEntity(); - this.setMaxHealth(15); + public void saveNBT() { + super.saveNBT(); + this.namedTag.putInt("Variant", this.variant); + } + + @Override + public Item[] getDrops() { + return new Item[]{Item.get(Item.LEATHER, 0, Utils.rand(0, 2))}; + } + + private static int getRandomVariant() { + return VARIANTS[Utils.rand(0, VARIANTS.length - 1)]; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityMooshroom.java b/src/main/java/cn/nukkit/entity/passive/EntityMooshroom.java index 9d2e2cd76e6..015f1cb39cd 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityMooshroom.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityMooshroom.java @@ -1,13 +1,16 @@ package cn.nukkit.entity.passive; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.data.IntEntityData; import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * Author: BeYkeRYkt Nukkit Project - */ -public class EntityMooshroom extends EntityAnimal { +import java.util.ArrayList; +import java.util.List; + +public class EntityMooshroom extends EntityWalkingAnimal { public static final int NETWORK_ID = 16; @@ -15,9 +18,14 @@ public EntityMooshroom(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } + @Override + public int getNetworkId() { + return NETWORK_ID; + } + @Override public float getWidth() { - if (isBaby()) { + if (this.isBaby()) { return 0.45f; } return 0.9f; @@ -25,30 +33,61 @@ public float getWidth() { @Override public float getHeight() { - if (isBaby()) { + if (this.isBaby()) { return 0.7f; } return 1.4f; } @Override - public String getName() { - return "Mooshroom"; + public void initEntity() { + this.setMaxHealth(10); + super.initEntity(); + + if (this.namedTag.contains("Variant")) { + this.setBrown(this.namedTag.getInt("Variant") == 1); + } } @Override public Item[] getDrops() { - return new Item[]{Item.get(Item.LEATHER), Item.get(Item.RAW_BEEF)}; + List drops = new ArrayList<>(); + + if (!this.isBaby()) { + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.LEATHER, 0, 1)); + } + + for (int i = 0; i < Utils.rand(1, 3); i++) { + drops.add(Item.get(this.isOnFire() ? Item.STEAK : Item.RAW_BEEF, 0, 1)); + } + } + + return drops.toArray(new Item[0]); } @Override - public int getNetworkId() { - return NETWORK_ID; + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); } @Override - protected void initEntity() { - super.initEntity(); - setMaxHealth(10); + public void saveNBT() { + super.saveNBT(); + this.namedTag.putInt("Variant", this.isBrown() ? 1 : 0); + } + + @Override + public void onStruckByLightning(Entity lightning) { + this.setBrown(!this.isBrown()); + super.onStruckByLightning(lightning); + } + + public boolean isBrown() { + return this.getDataPropertyInt(DATA_VARIANT) == 1; + } + + public void setBrown(boolean brown) { + this.setDataProperty(new IntEntityData(DATA_VARIANT, brown ? 1 : 0)); } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityMule.java b/src/main/java/cn/nukkit/entity/passive/EntityMule.java index 29303769205..eaa3afce09d 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityMule.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityMule.java @@ -1,13 +1,14 @@ package cn.nukkit.entity.passive; +import cn.nukkit.utils.Utils; import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -/** - * @author PikyCZ - */ -public class EntityMule extends EntityAnimal { +import java.util.ArrayList; +import java.util.List; + +public class EntityMule extends EntityHorseBase { public static final int NETWORK_ID = 25; @@ -15,11 +16,6 @@ public EntityMule(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } - @Override - public Item[] getDrops() { - return new Item[]{Item.get(Item.LEATHER)}; - } - @Override public int getNetworkId() { return NETWORK_ID; @@ -43,7 +39,20 @@ public float getHeight() { @Override public void initEntity() { - super.initEntity(); this.setMaxHealth(15); + super.initEntity(); + } + + @Override + public Item[] getDrops() { + List drops = new ArrayList<>(); + + if (!this.isBaby()) { + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.LEATHER, 0, 1)); + } + } + + return drops.toArray(new Item[0]); } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityNPC.java b/src/main/java/cn/nukkit/entity/passive/EntityNPC.java index f84595c72f1..93c6033d73d 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityNPC.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityNPC.java @@ -4,5 +4,4 @@ * Created by Pub4Game on 21.06.2016. */ public interface EntityNPC { - } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityOcelot.java b/src/main/java/cn/nukkit/entity/passive/EntityOcelot.java index 552e5fcc227..47d4a7bfad4 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityOcelot.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityOcelot.java @@ -1,13 +1,10 @@ package cn.nukkit.entity.passive; -import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * Author: BeYkeRYkt Nukkit Project - */ -public class EntityOcelot extends EntityAnimal { +public class EntityOcelot extends EntityTameableAnimal { public static final int NETWORK_ID = 22; @@ -15,6 +12,11 @@ public EntityOcelot(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } + @Override + public int getNetworkId() { + return NETWORK_ID; + } + @Override public float getWidth() { if (this.isBaby()) { @@ -32,23 +34,14 @@ public float getHeight() { } @Override - public String getName() { - return "Ocelot"; - } - - @Override - public int getNetworkId() { - return NETWORK_ID; - } - - @Override - public void initEntity() { + protected void initEntity() { + this.setMaxHealth(10); super.initEntity(); - setMaxHealth(10); + this.noFallDamage = true; } @Override - public boolean isBreedingItem(Item item) { - return item.getId() == Item.RAW_FISH; + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityPanda.java b/src/main/java/cn/nukkit/entity/passive/EntityPanda.java index c9520c750cc..f40b46f87b1 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityPanda.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityPanda.java @@ -1,9 +1,10 @@ package cn.nukkit.entity.passive; +import cn.nukkit.utils.Utils; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -public class EntityPanda extends EntityAnimal { +public class EntityPanda extends EntityWalkingAnimal { public static final int NETWORK_ID = 113; @@ -33,7 +34,12 @@ public float getHeight() { @Override public void initEntity() { - super.initEntity(); this.setMaxHealth(20); + super.initEntity(); + } + + @Override + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityParrot.java b/src/main/java/cn/nukkit/entity/passive/EntityParrot.java index 8195000fb54..be32a221f2a 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityParrot.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityParrot.java @@ -1,16 +1,19 @@ package cn.nukkit.entity.passive; +import cn.nukkit.entity.data.IntEntityData; import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityParrot extends EntityAnimal { +public class EntityParrot extends EntityFlyingAnimal { public static final int NETWORK_ID = 30; + private int variant; + + private static final int[] VARIANTS = {0, 1, 2, 3, 4}; + public EntityParrot(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @@ -20,10 +23,6 @@ public int getNetworkId() { return NETWORK_ID; } - public String getName() { - return "Parrot"; - } - @Override public float getWidth() { return 0.5f; @@ -36,12 +35,35 @@ public float getHeight() { @Override public void initEntity() { - super.initEntity(); this.setMaxHealth(6); + super.initEntity(); + + if (this.namedTag.contains("Variant")) { + this.variant = this.namedTag.getInt("Variant"); + } else { + this.variant = getRandomVariant(); + } + + this.setDataProperty(new IntEntityData(DATA_VARIANT, this.variant)); + } + + @Override + public void saveNBT() { + super.saveNBT(); + this.namedTag.putInt("Variant", this.variant); } @Override public Item[] getDrops() { - return new Item[]{Item.get(Item.FEATHER)}; + return new Item[]{Item.get(Item.FEATHER, 0, Utils.rand(1, 2))}; + } + + @Override + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); + } + + private static int getRandomVariant() { + return VARIANTS[Utils.rand(0, VARIANTS.length - 1)]; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityPig.java b/src/main/java/cn/nukkit/entity/passive/EntityPig.java index 4b5ef278fff..d14938ec796 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityPig.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityPig.java @@ -1,13 +1,17 @@ package cn.nukkit.entity.passive; +import cn.nukkit.entity.*; +import cn.nukkit.entity.mob.EntityZombiePigman; +import cn.nukkit.event.entity.CreatureSpawnEvent; import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * Author: BeYkeRYkt Nukkit Project - */ -public class EntityPig extends EntityAnimal { +import java.util.ArrayList; +import java.util.List; + +public class EntityPig extends EntityWalkingAnimal /*implements EntityRideable, EntityControllable*/ { public static final int NETWORK_ID = 12; @@ -15,6 +19,11 @@ public EntityPig(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } + @Override + public int getNetworkId() { + return NETWORK_ID; + } + @Override public float getWidth() { if (this.isBaby()) { @@ -33,29 +42,71 @@ public float getHeight() { @Override public void initEntity() { - super.initEntity(); this.setMaxHealth(10); + super.initEntity(); } @Override - public String getName() { - return "Pig"; + public Item[] getDrops() { + List drops = new ArrayList<>(); + + if (!this.isBaby()) { + for (int i = 0; i < Utils.rand(1, 3); i++) { + drops.add(Item.get(this.isOnFire() ? Item.COOKED_PORKCHOP : Item.RAW_PORKCHOP, 0, 1)); + } + } + + return drops.toArray(new Item[0]); } - @Override - public Item[] getDrops() { - return new Item[]{Item.get(((this.isOnFire()) ? Item.COOKED_PORKCHOP : Item.RAW_PORKCHOP))}; + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); } @Override - public int getNetworkId() { - return NETWORK_ID; + public void onStruckByLightning(Entity lightning) { + Entity ent = Entity.createEntity("ZombiePigman", this); + if (ent != null) { + CreatureSpawnEvent cse = new CreatureSpawnEvent(EntityZombiePigman.NETWORK_ID, this, ent.namedTag, CreatureSpawnEvent.SpawnReason.LIGHTNING); + this.getServer().getPluginManager().callEvent(cse); + + if (cse.isCancelled()) { + ent.close(); + return; + } + + ent.yaw = this.yaw; + ent.pitch = this.pitch; + ent.setImmobile(this.isImmobile()); + if (this.hasCustomName()) { + ent.setNameTag(this.getNameTag()); + ent.setNameTagVisible(this.isNameTagVisible()); + ent.setNameTagAlwaysVisible(this.isNameTagAlwaysVisible()); + } + /*if (this.isBaby()) { + ent.setBaby(); // TODO + }*/ + + this.close(); + ent.spawnToAll(); + } else { + super.onStruckByLightning(lightning); + } } @Override - public boolean isBreedingItem(Item item) { - int id = item.getId(); + public void updatePassengers() { + if (this.passengers.isEmpty()) { + return; + } - return id == Item.CARROT || id == Item.POTATO || id == Item.BEETROOT; + for (Entity passenger : new ArrayList<>(this.passengers)) { + if (!passenger.isAlive() || this.isInsideOfWater()) { + dismountEntity(passenger); + continue; + } + + updatePassengerPosition(passenger); + } } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityPolarBear.java b/src/main/java/cn/nukkit/entity/passive/EntityPolarBear.java index 21f29c0458d..6ae5e4b0ae4 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityPolarBear.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityPolarBear.java @@ -1,13 +1,15 @@ package cn.nukkit.entity.passive; +import cn.nukkit.entity.mob.EntityWalkingMob; import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityPolarBear extends EntityAnimal { +import java.util.ArrayList; +import java.util.List; + +public class EntityPolarBear extends EntityWalkingMob { public static final int NETWORK_ID = 28; @@ -38,12 +40,29 @@ public float getHeight() { @Override public void initEntity() { - super.initEntity(); this.setMaxHealth(30); + super.initEntity(); } @Override public Item[] getDrops() { - return new Item[]{Item.get(Item.RAW_FISH), Item.get(Item.RAW_SALMON)}; + List drops = new ArrayList<>(); + + if (!this.isBaby()) { + drops.add(Item.get(Item.RAW_FISH, 0, Utils.rand(0, 2))); + drops.add(Item.get(Item.RAW_SALMON, 0, Utils.rand(0, 2))); + } + + return drops.toArray(new Item[0]); + } + + @Override + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); + } + + @Override + public String getName() { + return this.hasCustomName() ? this.getNameTag() : "Polar Bear"; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityPufferfish.java b/src/main/java/cn/nukkit/entity/passive/EntityPufferfish.java index 727a67fc51b..7dd0a83bbc6 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityPufferfish.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityPufferfish.java @@ -1,26 +1,35 @@ package cn.nukkit.entity.passive; +import cn.nukkit.Player; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.data.ByteEntityData; +import cn.nukkit.event.entity.EntityDamageByEntityEvent; +import cn.nukkit.event.entity.EntityDamageEvent; +import cn.nukkit.event.entity.EntityPotionEffectEvent; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.potion.Effect; +import cn.nukkit.utils.Utils; -/** - * Created by PetteriM1 - */ -public class EntityPufferfish extends EntityAnimal { +public class EntityPufferfish extends EntityFish { public static final int NETWORK_ID = 108; + private int puffed = 0; + public EntityPufferfish(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override - public int getNetworkId() { - return NETWORK_ID; + int getBucketMeta() { + return 5; } - public String getName() { - return "Pufferfish"; + @Override + public int getNetworkId() { + return NETWORK_ID; } @Override @@ -35,7 +44,50 @@ public float getHeight() { @Override public void initEntity() { - super.initEntity(); this.setMaxHealth(3); + super.initEntity(); + } + + @Override + public Item[] getDrops() { + return new Item[]{Item.get(Item.PUFFERFISH, 0, 1), Item.get(Item.BONE, 0, Utils.rand(0, 2))}; + } + + @Override + public boolean attack(EntityDamageEvent ev) { + super.attack(ev); + + if (ev instanceof EntityDamageByEntityEvent && ev.getCause() == EntityDamageEvent.DamageCause.ENTITY_ATTACK) { + Entity damager = ((EntityDamageByEntityEvent) ev).getDamager(); + if (damager instanceof Player) { + if (this.isPuffed()) return true; + this.puffed = 200; + damager.addEffect(Effect.getEffect(Effect.POISON).setDuration(200), EntityPotionEffectEvent.Cause.ATTACK); + this.setDataProperty(new ByteEntityData(DATA_PUFFERFISH_SIZE, 2)); + } + } + + return true; + } + + @Override + public boolean entityBaseTick(int tickDiff) { + if (this.puffed > 0) { + this.puffed--; + + if (this.puffed <= 0) { + this.setDataProperty(new ByteEntityData(DATA_PUFFERFISH_SIZE, 0)); + } + } + + return super.entityBaseTick(tickDiff); + } + + /** + * Is puffed + * @return whether the pufferfish is puffed + */ + public boolean isPuffed() { + return this.puffed > 0; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityRabbit.java b/src/main/java/cn/nukkit/entity/passive/EntityRabbit.java index 8917295a505..b7bf7283a3b 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityRabbit.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityRabbit.java @@ -1,13 +1,14 @@ package cn.nukkit.entity.passive; +import cn.nukkit.utils.Utils; import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -/** - * Author: BeYkeRYkt Nukkit Project - */ -public class EntityRabbit extends EntityAnimal { +import java.util.ArrayList; +import java.util.List; + +public class EntityRabbit extends EntityJumpingAnimal { public static final int NETWORK_ID = 18; @@ -15,6 +16,11 @@ public EntityRabbit(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } + @Override + public int getNetworkId() { + return NETWORK_ID; + } + @Override public float getWidth() { if (this.isBaby()) { @@ -32,23 +38,29 @@ public float getHeight() { } @Override - public String getName() { - return "Rabbit"; + public void initEntity() { + this.setMaxHealth(3); + super.initEntity(); } @Override public Item[] getDrops() { - return new Item[]{Item.get(((this.isOnFire()) ? Item.COOKED_RABBIT : Item.RAW_RABBIT)), Item.get(Item.RABBIT_HIDE), Item.get(Item.RABBIT_FOOT)}; - } + List drops = new ArrayList<>(); - @Override - public int getNetworkId() { - return NETWORK_ID; + if (!this.isBaby()) { + drops.add(Item.get(Item.RABBIT_HIDE, 0, Utils.rand(0, 1))); + drops.add(Item.get(this.isOnFire() ? Item.COOKED_RABBIT : Item.RAW_RABBIT, 0, Utils.rand(0, 1))); + + for (int i = 0; i < (Utils.rand(0, 101) <= 9 ? 1 : 0); i++) { + drops.add(Item.get(Item.RABBIT_FOOT, 0, 1)); + } + } + + return drops.toArray(new Item[0]); } @Override - protected void initEntity() { - super.initEntity(); - setMaxHealth(10); + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntitySalmon.java b/src/main/java/cn/nukkit/entity/passive/EntitySalmon.java index 30709191046..be299167080 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntitySalmon.java +++ b/src/main/java/cn/nukkit/entity/passive/EntitySalmon.java @@ -1,12 +1,11 @@ package cn.nukkit.entity.passive; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * Created by PetteriM1 - */ -public class EntitySalmon extends EntityAnimal { +public class EntitySalmon extends EntityFish { public static final int NETWORK_ID = 109; @@ -15,12 +14,13 @@ public EntitySalmon(FullChunk chunk, CompoundTag nbt) { } @Override - public int getNetworkId() { - return NETWORK_ID; + int getBucketMeta() { + return 3; } - public String getName() { - return "Salmon"; + @Override + public int getNetworkId() { + return NETWORK_ID; } @Override @@ -35,7 +35,12 @@ public float getHeight() { @Override public void initEntity() { - super.initEntity(); this.setMaxHealth(3); + super.initEntity(); + } + + @Override + public Item[] getDrops() { + return new Item[]{Item.get(Item.RAW_SALMON, 0, 1), Item.get(Item.BONE, 0, Utils.rand(0, 2))}; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntitySheep.java b/src/main/java/cn/nukkit/entity/passive/EntitySheep.java index 8a50ee51881..3d2c6653937 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntitySheep.java +++ b/src/main/java/cn/nukkit/entity/passive/EntitySheep.java @@ -2,30 +2,33 @@ import cn.nukkit.Player; import cn.nukkit.entity.data.ByteEntityData; -import cn.nukkit.event.entity.EntityDamageByEntityEvent; import cn.nukkit.item.Item; import cn.nukkit.item.ItemDye; import cn.nukkit.level.format.FullChunk; import cn.nukkit.math.Vector3; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.utils.DyeColor; +import cn.nukkit.utils.Utils; -import java.util.concurrent.ThreadLocalRandom; +import java.util.ArrayList; +import java.util.List; -/** - * Author: BeYkeRYkt Nukkit Project - */ -public class EntitySheep extends EntityAnimal { +public class EntitySheep extends EntityWalkingAnimal { public static final int NETWORK_ID = 13; - public boolean sheared = false; - public int color = 0; + private boolean sheared = false; + private int color; public EntitySheep(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } + @Override + public int getNetworkId() { + return NETWORK_ID; + } + @Override public float getWidth() { if (this.isBaby()) { @@ -42,19 +45,10 @@ public float getHeight() { return 1.3f; } - @Override - public String getName() { - return "Sheep"; - } - - @Override - public int getNetworkId() { - return NETWORK_ID; - } - @Override public void initEntity() { this.setMaxHealth(8); + super.initEntity(); if (!this.namedTag.contains("Color")) { this.setColor(randomColor()); @@ -63,74 +57,98 @@ public void initEntity() { } if (!this.namedTag.contains("Sheared")) { - this.namedTag.putByte("Sheared", 0); - } else { - this.sheared = this.namedTag.getBoolean("Sheared"); + this.namedTag.putBoolean("Sheared", false); } - - this.setDataFlag(DATA_FLAGS, DATA_FLAG_SHEARED, this.sheared); } - @Override public void saveNBT() { super.saveNBT(); this.namedTag.putByte("Color", this.color); - this.namedTag.putBoolean("Sheared", this.sheared); + this.namedTag.putBoolean("Sheared", this.isSheared()); } @Override public boolean onInteract(Player player, Item item, Vector3 clickedPos) { if (item.getId() == Item.DYE) { - this.setColor(((ItemDye) item).getDyeColor().getWoolData()); + switch (item.getDamage()) { + case ItemDye.BONE_MEAL: + case ItemDye.LAPIS_LAZULI: + return false; + case ItemDye.WHITE_NEW: + this.setColor(DyeColor.WHITE.getWoolData()); + break; + case ItemDye.BLUE_NEW: + this.setColor(DyeColor.BLUE.getWoolData()); + break; + case ItemDye.BROWN_NEW: + this.setColor(DyeColor.BROWN.getWoolData()); + break; + case ItemDye.BLACK_NEW: + this.setColor(DyeColor.BLACK.getWoolData()); + break; + default: + this.setColor(((ItemDye) item).getDyeColor().getWoolData()); + } return true; } - - return item.getId() == Item.SHEARS && shear(); + return super.onInteract(player, item, clickedPos); } - public boolean shear() { - if (sheared) { - return false; + public void shear(boolean shear) { + this.sheared = shear; + this.setDataFlag(DATA_FLAGS, DATA_FLAG_SHEARED, shear); + if (shear) { + this.level.dropItem(this, Item.get(Item.WOOL, getColor(), Utils.rand(1, 3))); } - - this.sheared = true; - this.setDataFlag(DATA_FLAGS, DATA_FLAG_SHEARED, true); - - this.level.dropItem(this, Item.get(Item.WOOL, getColor(), ThreadLocalRandom.current().nextInt(2) + 1)); - return true; } @Override public Item[] getDrops() { - if (this.lastDamageCause instanceof EntityDamageByEntityEvent) { - return new Item[]{Item.get(((this.isOnFire()) ? Item.COOKED_MUTTON : Item.RAW_MUTTON)), Item.get(Item.WOOL, getColor(), 1)}; + List drops = new ArrayList<>(); + + if (!this.isBaby()) { + if (!this.sheared) drops.add(Item.get(Item.WOOL, this.getColor(), 1)); + + for (int i = 0; i < Utils.rand(1, 2); i++) { + drops.add(Item.get(this.isOnFire() ? Item.COOKED_MUTTON : Item.RAW_MUTTON, 0, 1)); + } } - return new Item[0]; + + return drops.toArray(new Item[0]); } - public void setColor(int color) { - this.color = color; - this.setDataProperty(new ByteEntityData(DATA_COLOUR, color)); - this.namedTag.putByte("Color", this.color); + + public void setColor(int woolColor) { + this.color = woolColor; + this.namedTag.putByte("Color", woolColor); + this.setDataProperty(new ByteEntityData(DATA_COLOR, woolColor)); } public int getColor() { - return namedTag.getByte("Color"); + return this.color; } private int randomColor() { - ThreadLocalRandom random = ThreadLocalRandom.current(); - double rand = random.nextDouble(1, 100); - - if (rand <= 0.164) { - return DyeColor.PINK.getWoolData(); - } + int rand = Utils.rand(1, 200); + + if (rand == 1) return DyeColor.PINK.getWoolData(); + else if (rand < 8) return DyeColor.BROWN.getWoolData(); + else if (rand < 18) return DyeColor.GRAY.getWoolData(); + else if (rand < 28) return DyeColor.LIGHT_GRAY.getWoolData(); + else if (rand < 38) return DyeColor.BLACK.getWoolData(); + else return DyeColor.WHITE.getWoolData(); + } - if (rand <= 15) { - return random.nextBoolean() ? DyeColor.BLACK.getWoolData() : random.nextBoolean() ? DyeColor.GRAY.getWoolData() : DyeColor.LIGHT_GRAY.getWoolData(); - } + @Override + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); + } - return DyeColor.WHITE.getWoolData(); + /** + * @return whether the sheep is sheared + */ + public boolean isSheared() { + return this.sheared; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntitySkeletonHorse.java b/src/main/java/cn/nukkit/entity/passive/EntitySkeletonHorse.java index 95a3956ab0c..7588b863192 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntitySkeletonHorse.java +++ b/src/main/java/cn/nukkit/entity/passive/EntitySkeletonHorse.java @@ -4,11 +4,12 @@ import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntitySkeletonHorse extends EntityAnimal implements EntitySmite { +import java.util.ArrayList; +import java.util.List; + +public class EntitySkeletonHorse extends EntityHorseBase implements EntitySmite { public static final int NETWORK_ID = 26; @@ -23,22 +24,43 @@ public int getNetworkId() { @Override public float getWidth() { - return 1.4f; + if (this.isBaby()) { + return 0.6982f; + } + return 1.3965f; } @Override public float getHeight() { + if (this.isBaby()) { + return 0.8f; + } return 1.6f; } @Override public void initEntity() { - super.initEntity(); this.setMaxHealth(15); + super.initEntity(); } @Override public Item[] getDrops() { - return new Item[]{Item.get(Item.BONE)}; + List drops = new ArrayList<>(); + + if (!this.isBaby()) { + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.LEATHER, 0, 1)); + } + + drops.add(Item.get(Item.BONE, 0, Utils.rand(0, 1))); + } + + return drops.toArray(new Item[0]); + } + + @Override + public String getName() { + return this.hasCustomName() ? this.getNameTag() : "Skeleton Horse"; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntitySniffer.java b/src/main/java/cn/nukkit/entity/passive/EntitySniffer.java new file mode 100644 index 00000000000..5bcf454669a --- /dev/null +++ b/src/main/java/cn/nukkit/entity/passive/EntitySniffer.java @@ -0,0 +1,46 @@ +package cn.nukkit.entity.passive; + +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; + +public class EntitySniffer extends EntityWalkingAnimal { + + public static final int NETWORK_ID = 139; + + public EntitySniffer(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } + + @Override + public void initEntity() { + this.setMaxHealth(14); + super.initEntity(); + } + + @Override + public float getWidth() { + if (this.isBaby()) { + return 0.855f; + } + return 1.9f; + } + + @Override + public float getHeight() { + if (this.isBaby()) { + return 0.7875f; + } + return 1.75f; + } + + @Override + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); + } + + @Override + public int getNetworkId() { + return NETWORK_ID; + } +} diff --git a/src/main/java/cn/nukkit/entity/passive/EntitySquid.java b/src/main/java/cn/nukkit/entity/passive/EntitySquid.java index 12430abea18..0a6506be516 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntitySquid.java +++ b/src/main/java/cn/nukkit/entity/passive/EntitySquid.java @@ -1,14 +1,14 @@ package cn.nukkit.entity.passive; +import cn.nukkit.event.entity.EntityDamageByEntityEvent; +import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemDye; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.network.protocol.EntityEventPacket; import cn.nukkit.utils.DyeColor; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ public class EntitySquid extends EntityWaterAnimal { public static final int NETWORK_ID = 17; @@ -24,22 +24,43 @@ public int getNetworkId() { @Override public float getWidth() { - return 0.8f; + return 0.95f; } @Override public float getHeight() { - return 0.8f; + return 0.95f; } @Override public void initEntity() { - super.initEntity(); this.setMaxHealth(10); + super.initEntity(); } @Override public Item[] getDrops() { - return new Item[]{new ItemDye(DyeColor.BLACK.getDyeData())}; + return new Item[]{Item.get(Item.DYE, DyeColor.BLACK.getDyeData(), Utils.rand(1, 3))}; + } + + @Override + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); + } + + @Override + public boolean attack(EntityDamageEvent source) { + boolean att = super.attack(source); + if (source.isCancelled()) { + return att; + } + + if (source instanceof EntityDamageByEntityEvent) { + EntityEventPacket pk = new EntityEventPacket(); + pk.eid = this.getId(); + pk.event = EntityEventPacket.SQUID_INK_CLOUD; + this.level.addChunkPacket(this.getChunkX(), this.getChunkZ(), pk); + } + return att; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityStrider.java b/src/main/java/cn/nukkit/entity/passive/EntityStrider.java index 64558d8bb30..51fda8fb71c 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityStrider.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityStrider.java @@ -1,15 +1,21 @@ package cn.nukkit.entity.passive; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; + +import java.util.ArrayList; +import java.util.List; /** * @author Erik Miller | EinBexiii */ -public class EntityStrider extends EntityAnimal { +public class EntityStrider extends EntityWalkingAnimal /*implements EntityRideable, EntityControllable*/ { public final static int NETWORK_ID = 125; + @Override public int getNetworkId() { return NETWORK_ID; @@ -19,10 +25,16 @@ public EntityStrider(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } + @Override + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); + } + @Override protected void initEntity() { + this.setMaxHealth(20); super.initEntity(); - this.setMaxHealth(15); + this.fireProof = true; } @Override @@ -36,7 +48,15 @@ public float getHeight() { } @Override - public String getName() { - return "Strider"; + public Item[] getDrops() { + List drops = new ArrayList<>(); + + if (!this.isBaby()) { + for (int i = 0; i < Utils.rand(2, 5); i++) { + drops.add(Item.get(Item.STRING, 0, 1)); + } + } + + return drops.toArray(new Item[0]); } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityTadpole.java b/src/main/java/cn/nukkit/entity/passive/EntityTadpole.java index 0ee26ec23e6..09a045cd14c 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityTadpole.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityTadpole.java @@ -3,7 +3,7 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -public class EntityTadpole extends EntityAnimal { +public class EntityTadpole extends EntityFish { public static final int NETWORK_ID = 133; @@ -11,6 +11,16 @@ public EntityTadpole(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } + @Override + public int getKillExperience() { + return 0; + } + + @Override + int getBucketMeta() { + return 13; + } + @Override public int getNetworkId() { return NETWORK_ID; @@ -28,12 +38,7 @@ public float getWidth() { @Override protected void initEntity() { - super.initEntity(); this.setMaxHealth(6); - } - - @Override - public String getName() { - return "Tadpole"; + super.initEntity(); } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityTameable.java b/src/main/java/cn/nukkit/entity/passive/EntityTameable.java deleted file mode 100644 index 57d6ae0bb3d..00000000000 --- a/src/main/java/cn/nukkit/entity/passive/EntityTameable.java +++ /dev/null @@ -1,110 +0,0 @@ -package cn.nukkit.entity.passive; - -import cn.nukkit.Player; -import cn.nukkit.entity.EntityOwnable; -import cn.nukkit.entity.data.ByteEntityData; -import cn.nukkit.entity.data.StringEntityData; -import cn.nukkit.level.format.FullChunk; -import cn.nukkit.nbt.tag.CompoundTag; - -/** - * Author: BeYkeRYkt - * Nukkit Project - */ -public abstract class EntityTameable extends EntityAnimal implements EntityOwnable { - - public static final int DATA_TAMED_FLAG = 16; - public static final int DATA_OWNER_NAME = 17; - - public EntityTameable(FullChunk chunk, CompoundTag nbt) { - super(chunk, nbt); - } - - @Override - protected void initEntity() { - super.initEntity(); - if (getDataProperty(DATA_TAMED_FLAG) == null) { - setDataProperty(new ByteEntityData(DATA_TAMED_FLAG, (byte) 0)); - } - - if (getDataProperty(DATA_OWNER_NAME) == null) { - setDataProperty(new StringEntityData(DATA_OWNER_NAME, "")); - } - - String ownerName = ""; - - if (namedTag != null) { - if (namedTag.contains("Owner")) { - ownerName = namedTag.getString("Owner"); - } - - if (ownerName.length() > 0) { - this.setOwnerName(ownerName); - this.setTamed(true); - } - - this.setSitting(namedTag.getBoolean("Sitting")); - } - } - - @Override - public void saveNBT() { - super.saveNBT(); - - if (this.getOwnerName() == null) { - namedTag.putString("Owner", ""); - } else { - namedTag.putString("Owner", getOwnerName()); - } - - namedTag.putBoolean("Sitting", isSitting()); - } - - @Override - public String getOwnerName() { - return getDataPropertyString(DATA_OWNER_NAME); - } - - @Override - public void setOwnerName(String playerName) { - setDataProperty(new StringEntityData(DATA_OWNER_NAME, playerName)); - } - - @Override - public Player getOwner() { - return getServer().getPlayer(getOwnerName()); - } - - @Override - public String getName() { - return getNameTag(); - } - - public boolean isTamed() { - return (getDataPropertyByte(DATA_TAMED_FLAG) & 4) != 0; - } - - public void setTamed(boolean flag) { - int var = getDataPropertyByte(DATA_TAMED_FLAG); // ? - - if (flag) { - setDataProperty(new ByteEntityData(DATA_TAMED_FLAG, (byte) (var | 4))); - } else { - setDataProperty(new ByteEntityData(DATA_TAMED_FLAG, (byte) (var & -5))); - } - } - - public boolean isSitting() { - return (getDataPropertyByte(DATA_TAMED_FLAG) & 1) != 0; - } - - public void setSitting(boolean flag) { - int var = getDataPropertyByte(DATA_TAMED_FLAG); // ? - - if (flag) { - setDataProperty(new ByteEntityData(DATA_TAMED_FLAG, (byte) (var | 1))); - } else { - setDataProperty(new ByteEntityData(DATA_TAMED_FLAG, (byte) (var & -2))); - } - } -} diff --git a/src/main/java/cn/nukkit/entity/passive/EntityTameableAnimal.java b/src/main/java/cn/nukkit/entity/passive/EntityTameableAnimal.java new file mode 100644 index 00000000000..d5bdcc01851 --- /dev/null +++ b/src/main/java/cn/nukkit/entity/passive/EntityTameableAnimal.java @@ -0,0 +1,11 @@ +package cn.nukkit.entity.passive; + +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; + +public abstract class EntityTameableAnimal extends EntityWalkingAnimal /*implements EntityTameable*/ { + + public EntityTameableAnimal(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } +} diff --git a/src/main/java/cn/nukkit/entity/passive/EntityTropicalFish.java b/src/main/java/cn/nukkit/entity/passive/EntityTropicalFish.java index 60db3244a62..46ca238fc6e 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityTropicalFish.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityTropicalFish.java @@ -1,26 +1,68 @@ package cn.nukkit.entity.passive; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * Created by PetteriM1 - */ -public class EntityTropicalFish extends EntityAnimal { +public class EntityTropicalFish extends EntityFish { public static final int NETWORK_ID = 111; + private int variantA; + private int variantB; + private int color; + public EntityTropicalFish(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override - public int getNetworkId() { - return NETWORK_ID; + protected void initEntity() { + this.setMaxHealth(3); + super.initEntity(); + + if (this.namedTag.contains("VariantA")) { + this.variantA = this.namedTag.getInt("VariantA"); + } else { + this.variantA = Utils.rand(0, 5); + + } + this.dataProperties.putInt(DATA_VARIANT, this.variantA); + + if (this.namedTag.contains("VariantB")) { + this.variantB = this.namedTag.getInt("VariantB"); + } else { + this.variantB = Utils.rand(0, 5); + + } + this.dataProperties.putInt(DATA_MARK_VARIANT, this.variantB); + + if (this.namedTag.contains("Color")) { + this.color = this.namedTag.getInt("Color"); + } else { + this.color = Utils.rand(0, 15); + + } + this.dataProperties.putByte(DATA_COLOR, this.color); } - public String getName() { - return "Tropical Fish"; + @Override + public void saveNBT() { + super.saveNBT(); + this.namedTag.putInt("VariantA", this.variantA); + this.namedTag.putInt("VariantB", this.variantB); + this.namedTag.putInt("Color", this.color); + } + + @Override + int getBucketMeta() { + return 4; + } + + @Override + public int getNetworkId() { + return NETWORK_ID; } @Override @@ -34,8 +76,12 @@ public float getHeight() { } @Override - public void initEntity() { - super.initEntity(); - this.setMaxHealth(3); + public Item[] getDrops() { + return new Item[]{Item.get(Item.CLOWNFISH, 0, 1), Item.get(Item.BONE, 0, Utils.rand(0, 2))}; + } + + @Override + public String getName() { + return this.hasCustomName() ? this.getNameTag() : "Tropical Fish"; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityTurtle.java b/src/main/java/cn/nukkit/entity/passive/EntityTurtle.java index aa9a25c79ac..1ca30347854 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityTurtle.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityTurtle.java @@ -1,12 +1,10 @@ package cn.nukkit.entity.passive; +import cn.nukkit.utils.Utils; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -/** - * Created by PetteriM1 - */ -public class EntityTurtle extends EntityAnimal { +public class EntityTurtle extends EntityWaterAnimal { public static final int NETWORK_ID = 74; @@ -19,10 +17,6 @@ public int getNetworkId() { return NETWORK_ID; } - public String getName() { - return "Turtle"; - } - @Override public float getWidth() { return 1.2f; @@ -35,7 +29,12 @@ public float getHeight() { @Override public void initEntity() { - super.initEntity(); this.setMaxHealth(30); + super.initEntity(); + } + + @Override + public int getKillExperience() { + return this.isBaby() ? 0 : Utils.rand(1, 3); } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityVillager.java b/src/main/java/cn/nukkit/entity/passive/EntityVillager.java index fca7bc48fe8..2148b4ef873 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityVillager.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityVillager.java @@ -1,11 +1,9 @@ package cn.nukkit.entity.passive; -import cn.nukkit.entity.EntityAgeable; -import cn.nukkit.entity.EntityCreature; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -public class EntityVillager extends EntityCreature implements EntityNPC, EntityAgeable { +public class EntityVillager extends EntityVillagerV1 { public static final int NETWORK_ID = 115; @@ -18,39 +16,8 @@ public int getNetworkId() { return NETWORK_ID; } - @Override - public float getWidth() { - if (this.isBaby()) { - return 0.3f; - } - return 0.6f; - } - - @Override - public float getHeight() { - if (this.isBaby()) { - return 0.9f; - } - return 1.8f; - } - @Override public String getName() { - return "Villager"; - } - - @Override - public void initEntity() { - super.initEntity(); - this.setMaxHealth(20); - } - - public boolean isBaby() { - return this.getDataFlag(DATA_FLAGS, DATA_FLAG_BABY); - } - - public void setBaby(boolean baby) { - this.setDataFlag(DATA_FLAGS, DATA_FLAG_BABY, baby); - this.setScale(baby ? 0.5f : 1); + return this.hasCustomName() ? this.getNameTag() : "Villager"; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityVillagerV1.java b/src/main/java/cn/nukkit/entity/passive/EntityVillagerV1.java index 0349f46ac5c..89e5543f585 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityVillagerV1.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityVillagerV1.java @@ -1,15 +1,22 @@ package cn.nukkit.entity.passive; +import cn.nukkit.Player; import cn.nukkit.entity.Entity; -import cn.nukkit.entity.EntityAgeable; -import cn.nukkit.entity.EntityCreature; +import cn.nukkit.entity.mob.EntityWitch; +import cn.nukkit.event.entity.CreatureSpawnEvent; +import cn.nukkit.inventory.InventoryHolder; +import cn.nukkit.inventory.TradeInventory; +import cn.nukkit.inventory.TradeInventoryRecipe; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; +import cn.nukkit.math.Vector3; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.ListTag; -/** - * Created by Pub4Game on 21.06.2016. - */ -public class EntityVillagerV1 extends EntityCreature implements EntityNPC, EntityAgeable { +import java.util.ArrayList; +import java.util.List; + +public class EntityVillagerV1 extends EntityWalkingAnimal implements InventoryHolder { public static final int PROFESSION_FARMER = 0; public static final int PROFESSION_LIBRARIAN = 1; @@ -17,12 +24,23 @@ public class EntityVillagerV1 extends EntityCreature implements EntityNPC, Entit public static final int PROFESSION_BLACKSMITH = 3; public static final int PROFESSION_BUTCHER = 4; public static final int PROFESSION_GENERIC = 5; + public static final int NETWORK_ID = 15; + private TradeInventory inventory; + private final List recipes = new ArrayList<>(); + private int tradeTier = 0; + private boolean willing = true; + public EntityVillagerV1(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } + @Override + public int getNetworkId() { + return NETWORK_ID; + } + @Override public float getWidth() { if (this.isBaby()) { @@ -34,25 +52,29 @@ public float getWidth() { @Override public float getHeight() { if (this.isBaby()) { - return 0.9f; + return 0.975f; } - return 1.8f; - } - - @Override - public String getName() { - return "Villager"; - } - - @Override - public int getNetworkId() { - return NETWORK_ID; + return 1.95f; } @Override public void initEntity() { + this.setMaxHealth(10); super.initEntity(); - this.setMaxHealth(20); + + this.inventory = new TradeInventory(this); + + try { + CompoundTag offers = this.namedTag.getCompound("Offers"); + if (offers != null) { + ListTag nbtRecipes = offers.getList("Recipes", CompoundTag.class); + for (CompoundTag nbt : nbtRecipes.getAll()) { + recipes.add(TradeInventoryRecipe.toNBT(nbt)); + } + } + } catch (Exception ex) { + server.getLogger().error("Failed to load trade recipes for a villager with entity id " + this.id, ex); + } if (!this.namedTag.contains("Profession")) { this.setProfession(PROFESSION_GENERIC); @@ -68,7 +90,101 @@ public void setProfession(int profession) { } @Override - public boolean isBaby() { - return this.getDataFlag(DATA_FLAGS, Entity.DATA_FLAG_BABY); + public int getKillExperience() { + return 0; + } + + @Override + public void onStruckByLightning(Entity lightning) { + Entity ent = Entity.createEntity("Witch", this); + if (ent != null) { + CreatureSpawnEvent cse = new CreatureSpawnEvent(EntityWitch.NETWORK_ID, this, ent.namedTag, CreatureSpawnEvent.SpawnReason.LIGHTNING); + this.getServer().getPluginManager().callEvent(cse); + + if (cse.isCancelled()) { + ent.close(); + return; + } + + ent.yaw = this.yaw; + ent.pitch = this.pitch; + ent.setImmobile(this.isImmobile()); + if (this.hasCustomName()) { + ent.setNameTag(this.getNameTag()); + ent.setNameTagVisible(this.isNameTagVisible()); + ent.setNameTagAlwaysVisible(this.isNameTagAlwaysVisible()); + } + /*if (this.isBaby()) { + ent.setBaby(); // TODO + }*/ + + this.close(); + ent.spawnToAll(); + } else { + super.onStruckByLightning(lightning); + } + } + + public void setTradeTier(int tier) { + this.tradeTier = tier; + } + + public int getTradeTier() { + return this.tradeTier; + } + + public void setWilling(boolean value) { + this.willing = value; + } + + public boolean isWilling() { + return this.willing; + } + + @Override + public boolean onInteract(Player player, Item item, Vector3 clickedPos) { + if (!recipes.isEmpty()) { + player.addWindow(this.getInventory()); + return true; + } + return false; + } + + public void addTradeRecipe(TradeInventoryRecipe recipe) { + this.recipes.add(recipe); + } + + public List getRecipes() { + return this.recipes; + } + + public CompoundTag getOffers() { + CompoundTag nbt = new CompoundTag(); + nbt.putList(recipesToNbt()); + nbt.putList(getDefaultTierExpRequirements()); + return nbt; + } + + private ListTag recipesToNbt() { + ListTag tag = new ListTag<>("Recipes"); + for (TradeInventoryRecipe recipe : this.recipes) { + tag.add(recipe.toNBT()); + } + return tag; + } + + private ListTag getDefaultTierExpRequirements() { + ListTag tag = new ListTag<>("TierExpRequirements"); + tag.add(new CompoundTag().putInt("0", 0)); + tag.add(new CompoundTag().putInt("1", 10)); + tag.add(new CompoundTag().putInt("2", 70)); + tag.add(new CompoundTag().putInt("3", 150)); + tag.add(new CompoundTag().putInt("4", 250)); + return tag; + } + + @Override + public TradeInventory getInventory() { + return this.inventory; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityWalkingAnimal.java b/src/main/java/cn/nukkit/entity/passive/EntityWalkingAnimal.java new file mode 100644 index 00000000000..35859b85cce --- /dev/null +++ b/src/main/java/cn/nukkit/entity/passive/EntityWalkingAnimal.java @@ -0,0 +1,12 @@ +package cn.nukkit.entity.passive; + +import cn.nukkit.entity.EntityWalking; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.nbt.tag.CompoundTag; + +public abstract class EntityWalkingAnimal extends EntityWalking implements EntityAnimal { + + public EntityWalkingAnimal(FullChunk chunk, CompoundTag nbt) { + super(chunk, nbt); + } +} diff --git a/src/main/java/cn/nukkit/entity/passive/EntityWanderingTrader.java b/src/main/java/cn/nukkit/entity/passive/EntityWanderingTrader.java index 911cbf30383..500c7922073 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityWanderingTrader.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityWanderingTrader.java @@ -1,10 +1,9 @@ package cn.nukkit.entity.passive; -import cn.nukkit.entity.EntityCreature; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -public class EntityWanderingTrader extends EntityCreature implements EntityNPC { +public class EntityWanderingTrader extends EntityWalkingAnimal { public static final int NETWORK_ID = 118; @@ -12,6 +11,11 @@ public EntityWanderingTrader(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } + @Override + public int getNetworkId() { + return NETWORK_ID; + } + @Override public float getWidth() { return 0.6f; @@ -19,22 +23,22 @@ public float getWidth() { @Override public float getHeight() { - return 1.8f; + return 1.95f; } @Override - public String getName() { - return "Wandering Trader"; + public void initEntity() { + this.setMaxHealth(20); + super.initEntity(); } @Override - public int getNetworkId() { - return NETWORK_ID; + public int getKillExperience() { + return 0; } @Override - public void initEntity() { - super.initEntity(); - this.setMaxHealth(20); + public String getName() { + return this.hasCustomName() ? this.getNameTag() : "Wandering Trader"; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityWaterAnimal.java b/src/main/java/cn/nukkit/entity/passive/EntityWaterAnimal.java index 617b426204f..3258634f47f 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityWaterAnimal.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityWaterAnimal.java @@ -1,22 +1,12 @@ package cn.nukkit.entity.passive; -import cn.nukkit.entity.Entity; -import cn.nukkit.entity.EntityAgeable; -import cn.nukkit.entity.EntityCreature; +import cn.nukkit.entity.EntitySwimming; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -/** - * author: MagicDroidX - * Nukkit Project - */ -public abstract class EntityWaterAnimal extends EntityCreature implements EntityAgeable { +public abstract class EntityWaterAnimal extends EntitySwimming implements EntityAnimal { + public EntityWaterAnimal(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } - - @Override - public boolean isBaby() { - return this.getDataFlag(DATA_FLAGS, Entity.DATA_FLAG_BABY); - } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityWolf.java b/src/main/java/cn/nukkit/entity/passive/EntityWolf.java index 656442b6793..eaff8465940 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityWolf.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityWolf.java @@ -1,13 +1,10 @@ package cn.nukkit.entity.passive; -import cn.nukkit.item.Item; +import cn.nukkit.entity.mob.EntityTameableMob; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; -/** - * Author: BeYkeRYkt Nukkit Project - */ -public class EntityWolf extends EntityAnimal { +public class EntityWolf extends EntityTameableMob { public static final int NETWORK_ID = 14; @@ -16,33 +13,33 @@ public EntityWolf(FullChunk chunk, CompoundTag nbt) { } @Override - public float getWidth() { - return 0.6f; + public int getNetworkId() { + return NETWORK_ID; } @Override - public float getHeight() { - return 0.85f; + public float getWidth() { + return 0.6f; } @Override - public String getName() { - return "Wolf"; + public float getHeight() { + return 0.8f; } @Override - public int getNetworkId() { - return NETWORK_ID; + protected void initEntity() { + this.setMaxHealth(8); + super.initEntity(); } @Override - public void initEntity() { - super.initEntity(); - this.setMaxHealth(8); + public int getKillExperience() { + return this.isBaby() ? 0 : 3; } @Override - public boolean isBreedingItem(Item item) { - return false; //only certain food + public String getName() { + return this.hasCustomName() ? this.getNameTag() : "Wolf"; } } diff --git a/src/main/java/cn/nukkit/entity/passive/EntityZombieHorse.java b/src/main/java/cn/nukkit/entity/passive/EntityZombieHorse.java index e6ec30f18f0..6db158c51e6 100644 --- a/src/main/java/cn/nukkit/entity/passive/EntityZombieHorse.java +++ b/src/main/java/cn/nukkit/entity/passive/EntityZombieHorse.java @@ -4,11 +4,12 @@ import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.Utils; -/** - * @author PikyCZ - */ -public class EntityZombieHorse extends EntityAnimal implements EntitySmite { +import java.util.ArrayList; +import java.util.List; + +public class EntityZombieHorse extends EntityHorseBase implements EntitySmite { public static final int NETWORK_ID = 27; @@ -23,22 +24,45 @@ public int getNetworkId() { @Override public float getWidth() { - return 1.4f; + if (this.isBaby()) { + return 0.6982f; + } + return 1.3965f; } @Override public float getHeight() { + if (this.isBaby()) { + return 0.8f; + } return 1.6f; } @Override public void initEntity() { - super.initEntity(); this.setMaxHealth(15); + super.initEntity(); } @Override public Item[] getDrops() { - return new Item[]{Item.get(Item.ROTTEN_FLESH, 1, 1)}; + List drops = new ArrayList<>(); + + if (!this.isBaby()) { + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.LEATHER, 0, 1)); + } + + for (int i = 0; i < Utils.rand(0, 2); i++) { + drops.add(Item.get(Item.ROTTEN_FLESH, 0, 1)); + } + } + + return drops.toArray(new Item[0]); + } + + @Override + public String getName() { + return "Zombie Horse"; } } diff --git a/src/main/java/cn/nukkit/entity/projectile/EntityArrow.java b/src/main/java/cn/nukkit/entity/projectile/EntityArrow.java index 74a4a266b45..eb48e455a7e 100644 --- a/src/main/java/cn/nukkit/entity/projectile/EntityArrow.java +++ b/src/main/java/cn/nukkit/entity/projectile/EntityArrow.java @@ -1,13 +1,16 @@ package cn.nukkit.entity.projectile; import cn.nukkit.entity.Entity; +import cn.nukkit.entity.data.ByteEntityData; import cn.nukkit.level.format.FullChunk; +import cn.nukkit.math.NukkitMath; +import cn.nukkit.math.Vector3; import cn.nukkit.nbt.tag.CompoundTag; - -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.network.protocol.LevelSoundEventPacket; +import cn.nukkit.utils.Utils; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntityArrow extends EntityProjectile { @@ -15,6 +18,9 @@ public class EntityArrow extends EntityProjectile { public static final int NETWORK_ID = 80; protected int pickupMode; + protected boolean critical; + private int arrowData; + private boolean isFromCrossbow; @Override public int getNetworkId() { @@ -23,7 +29,7 @@ public int getNetworkId() { @Override public float getWidth() { - return 0.5f; + return 0.05f; } @Override @@ -33,7 +39,7 @@ public float getLength() { @Override public float getHeight() { - return 0.5f; + return 0.05f; } @Override @@ -46,9 +52,6 @@ public float getDrag() { return 0.01f; } - protected float gravity = 0.05f; - protected float drag = 0.01f; - public EntityArrow(FullChunk chunk, CompoundTag nbt) { this(chunk, nbt, null); } @@ -58,16 +61,58 @@ public EntityArrow(FullChunk chunk, CompoundTag nbt, Entity shootingEntity) { } public EntityArrow(FullChunk chunk, CompoundTag nbt, Entity shootingEntity, boolean critical) { + this(chunk, nbt, shootingEntity, critical, false); + } + + public EntityArrow(FullChunk chunk, CompoundTag nbt, Entity shootingEntity, boolean critical, boolean isFromCrossbow) { super(chunk, nbt, shootingEntity); this.setCritical(critical); + this.isFromCrossbow = isFromCrossbow; + } + + /** + * Set arrow data. + * Used internally for tipped arrows. + * Notice: The data is not updated to players unless you call sendData(). + * + * @param data arrow data + */ + public void setData(int data) { + if (data < 0) throw new IllegalArgumentException("data < 0"); + this.arrowData = data; + this.setDataProperty(new ByteEntityData(DATA_HAS_DISPLAY, this.arrowData), false); + } + + /** + * Get arrow data. + * + * @return arrow data + */ + public int getData() { + return this.arrowData; + } + + /** + * Get whether the arrow was shot from a crossbow. + * + * @return arrow is from crossbow + */ + public boolean isFromCrossbow() { + return this.isFromCrossbow; } @Override protected void initEntity() { super.initEntity(); - this.damage = namedTag.contains("damage") ? namedTag.getDouble("damage") : 2; this.pickupMode = namedTag.contains("pickup") ? namedTag.getByte("pickup") : PICKUP_ANY; + + int data = namedTag.getByte("arrowData"); + if (data != 0) { + this.setData(data); + } + + this.isFromCrossbow = namedTag.getBoolean("isFromCrossbow"); } public void setCritical() { @@ -75,19 +120,26 @@ public void setCritical() { } public void setCritical(boolean value) { - this.setDataFlag(DATA_FLAGS, DATA_FLAG_CRITICAL, value); + if (this.critical != value) { + this.critical = value; + this.setDataFlag(DATA_FLAGS, DATA_FLAG_CRITICAL, value); + } } public boolean isCritical() { - return this.getDataFlag(DATA_FLAGS, DATA_FLAG_CRITICAL); + return this.critical; } @Override public int getResultDamage() { - int base = super.getResultDamage(); + int base = NukkitMath.ceilDouble(Math.sqrt(this.motionX * this.motionX + this.motionY * this.motionY + this.motionZ * this.motionZ) * getDamage()); if (this.isCritical()) { - base += ThreadLocalRandom.current().nextInt(base / 2 + 2); + base += Utils.random.nextInt((base >> 1) + 2); + } + + if (this.isFromCrossbow) { + base += 2; // magic value } return base; @@ -104,22 +156,16 @@ public boolean onUpdate(int currentTick) { return false; } - this.timing.startTiming(); - - boolean hasUpdate = super.onUpdate(currentTick); - - if (this.onGround || this.hadCollision) { - this.setCritical(false); - } - if (this.age > 1200) { this.close(); - hasUpdate = true; + return false; } - this.timing.stopTiming(); + if (this.fireTicks > 0 && this.level.isRaining() && this.canSeeSky()) { + this.extinguish(); + } - return hasUpdate; + return super.onUpdate(currentTick); } @Override @@ -127,6 +173,8 @@ public void saveNBT() { super.saveNBT(); this.namedTag.putByte("pickup", this.pickupMode); + this.namedTag.putByte("arrowData", this.arrowData); + this.namedTag.putBoolean("isFromCrossbow", this.isFromCrossbow); } public int getPickupMode() { @@ -136,4 +184,16 @@ public int getPickupMode() { public void setPickupMode(int pickupMode) { this.pickupMode = pickupMode; } + + @Override + public void onHit() { + this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_BOW_HIT); + } + + @Override + public void onHitGround(Vector3 moveVector) { + super.onHitGround(moveVector); + + this.setCritical(false); + } } diff --git a/src/main/java/cn/nukkit/entity/projectile/EntityEgg.java b/src/main/java/cn/nukkit/entity/projectile/EntityEgg.java index 3b45d59e7e1..389cf2c1ce5 100644 --- a/src/main/java/cn/nukkit/entity/projectile/EntityEgg.java +++ b/src/main/java/cn/nukkit/entity/projectile/EntityEgg.java @@ -1,14 +1,17 @@ package cn.nukkit.entity.projectile; import cn.nukkit.entity.Entity; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.particle.ItemBreakParticle; import cn.nukkit.nbt.tag.CompoundTag; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntityEgg extends EntityProjectile { + public static final int NETWORK_ID = 82; @Override @@ -33,7 +36,7 @@ public float getHeight() { @Override protected float getGravity() { - return 0.03f; + return 0.04f; } @Override @@ -55,13 +58,18 @@ public boolean onUpdate(int currentTick) { return false; } - boolean hasUpdate = super.onUpdate(currentTick); - - if (this.age > 1200 || this.isCollided) { - this.kill(); - hasUpdate = true; + if (this.age > 1200) { + this.close(); + } else if (this.isCollided) { + this.close(); } - return hasUpdate; + super.onUpdate(currentTick); + return !this.closed; + } + + @Override + public void onHit() { + level.addParticle(new ItemBreakParticle(this, Item.get(Item.EGG)), null, 5); } } diff --git a/src/main/java/cn/nukkit/entity/projectile/EntityEnderEye.java b/src/main/java/cn/nukkit/entity/projectile/EntityEnderEye.java new file mode 100644 index 00000000000..812aa0de06a --- /dev/null +++ b/src/main/java/cn/nukkit/entity/projectile/EntityEnderEye.java @@ -0,0 +1,50 @@ +package cn.nukkit.entity.projectile; + +import cn.nukkit.entity.Entity; +import cn.nukkit.item.Item; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.math.Vector3; +import cn.nukkit.nbt.tag.CompoundTag; + +import java.util.concurrent.ThreadLocalRandom; + +public class EntityEnderEye extends EntityProjectile { + + public static final int NETWORK_ID = 70; + + public EntityEnderEye(FullChunk chunk, CompoundTag nbt) { + this(chunk, nbt, null); + } + + public EntityEnderEye(FullChunk chunk, CompoundTag nbt, Entity shootingEntity) { + super(chunk, nbt, shootingEntity); + } + + @Override + public int getNetworkId() { + return NETWORK_ID; + } + + @Override + public boolean onUpdate(int currentTick) { + boolean hasUpdate = super.onUpdate(currentTick); + + if (!this.isAlive()) return hasUpdate; + + if (this.age >= 60) { + if (ThreadLocalRandom.current().nextFloat() > 0.2) { + this.level.dropItem(this, Item.get(Item.ENDER_EYE)); + } + + this.close(); + + hasUpdate = true; + } else if (this.age == 40) { + this.setMotion(new Vector3(0, 0.2, 0)); + + hasUpdate = true; + } + + return hasUpdate; + } +} diff --git a/src/main/java/cn/nukkit/entity/projectile/EntityEnderPearl.java b/src/main/java/cn/nukkit/entity/projectile/EntityEnderPearl.java index 8d59b5c78f5..7ac2c8557a0 100644 --- a/src/main/java/cn/nukkit/entity/projectile/EntityEnderPearl.java +++ b/src/main/java/cn/nukkit/entity/projectile/EntityEnderPearl.java @@ -10,11 +10,14 @@ import cn.nukkit.math.NukkitMath; import cn.nukkit.math.Vector3; import cn.nukkit.nbt.tag.CompoundTag; -import cn.nukkit.network.protocol.LevelEventPacket; +import cn.nukkit.network.protocol.LevelSoundEventPacket; public class EntityEnderPearl extends EntityProjectile { + public static final int NETWORK_ID = 87; + private int currentLevel; + @Override public int getNetworkId() { return NETWORK_ID; @@ -51,59 +54,65 @@ public EntityEnderPearl(FullChunk chunk, CompoundTag nbt) { public EntityEnderPearl(FullChunk chunk, CompoundTag nbt, Entity shootingEntity) { super(chunk, nbt, shootingEntity); + + if (this.shootingEntity != null) { + this.currentLevel = this.shootingEntity.getLevel().getId(); + } } @Override public boolean onUpdate(int currentTick) { + boolean hasUpdate = super.onUpdate(currentTick); + if (this.closed) { return false; } - this.timing.startTiming(); - - boolean hasUpdate = super.onUpdate(currentTick); - if (this.isCollided && this.shootingEntity instanceof Player) { boolean portal = false; for (Block collided : this.getCollisionBlocks()) { if (collided.getId() == Block.NETHER_PORTAL) { portal = true; + break; } } + + this.close(); + if (!portal) { teleport(); } - } - if (this.age > 1200 || this.isCollided) { - this.kill(); - hasUpdate = true; + return false; } - this.timing.stopTiming(); + if (this.isCollided || this.hadCollision || (this.shootingEntity instanceof Player && !((Player) this.shootingEntity).isOnline())) { + this.close(); + return false; + } return hasUpdate; } - + @Override public void onCollideWithEntity(Entity entity) { - if (this.shootingEntity instanceof Player) { - teleport(); - } + teleport(); + super.onCollideWithEntity(entity); } private void teleport() { - if (!this.level.equals(this.shootingEntity.getLevel())) { + if (!(this.shootingEntity instanceof Player) || this.shootingEntity.getLevel().getId() != this.currentLevel || !((Player) this.shootingEntity).isOnline()) { return; } - this.level.addLevelEvent(this.shootingEntity.add(0.5, 0.5, 0.5), LevelEventPacket.EVENT_SOUND_PORTAL); this.shootingEntity.teleport(new Vector3(NukkitMath.floorDouble(this.x) + 0.5, this.y, NukkitMath.floorDouble(this.z) + 0.5), TeleportCause.ENDER_PEARL); - if ((((Player) this.shootingEntity).getGamemode() & 0x01) == 0) { - this.shootingEntity.attack(new EntityDamageByEntityEvent(this, shootingEntity, EntityDamageEvent.DamageCause.PROJECTILE, 5f, 0f)); + + int gamemode = ((Player) this.shootingEntity).getGamemode(); + if (gamemode == 0 || gamemode == 2) { + this.shootingEntity.attack(new EntityDamageByEntityEvent(this, shootingEntity, EntityDamageEvent.DamageCause.FALL, 5f, 0f)); } - this.level.addLevelEvent(this, LevelEventPacket.EVENT_PARTICLE_ENDERMAN_TELEPORT); - this.level.addLevelEvent(this.shootingEntity.add(0.5, 0.5, 0.5), LevelEventPacket.EVENT_SOUND_PORTAL); + + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_TELEPORT); } } diff --git a/src/main/java/cn/nukkit/entity/projectile/EntityProjectile.java b/src/main/java/cn/nukkit/entity/projectile/EntityProjectile.java index 7efb621f93b..96d71efd59d 100644 --- a/src/main/java/cn/nukkit/entity/projectile/EntityProjectile.java +++ b/src/main/java/cn/nukkit/entity/projectile/EntityProjectile.java @@ -1,14 +1,14 @@ package cn.nukkit.entity.projectile; +import cn.nukkit.Player; +import cn.nukkit.block.Block; import cn.nukkit.entity.Entity; import cn.nukkit.entity.EntityLiving; -import cn.nukkit.entity.data.LongEntityData; -import cn.nukkit.entity.item.EntityBoat; -import cn.nukkit.entity.item.EntityEndCrystal; -import cn.nukkit.entity.item.EntityMinecartAbstract; +import cn.nukkit.entity.item.*; import cn.nukkit.entity.mob.EntityBlaze; import cn.nukkit.event.entity.*; import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; +import cn.nukkit.item.ItemArrow; import cn.nukkit.level.MovingObjectPosition; import cn.nukkit.level.format.FullChunk; import cn.nukkit.math.AxisAlignedBB; @@ -16,15 +16,42 @@ import cn.nukkit.math.Vector3; import cn.nukkit.nbt.tag.CompoundTag; +import java.util.concurrent.ThreadLocalRandom; + /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class EntityProjectile extends Entity { public static final int DATA_SHOOTER_ID = 17; - public Entity shootingEntity = null; + /** + * Arrow will be removed on pickup. + */ + public static final int PICKUP_NONE_REMOVE = -1; + /** + * No player can pick up the arrow. + */ + public static final int PICKUP_NONE = 0; + /** + * All players can pick up the arrow. + */ + public static final int PICKUP_ANY = 1; + /** + * All players on creative mode can pick up the arrow. + */ + public static final int PICKUP_CREATIVE = 2; + + /** + * The entity who shot this arrow. May be null. + */ + public Entity shootingEntity; + + /** + * The knockback this arrow causes on hit. + */ + public float knockBack = 0.3f; protected double getDamage() { return namedTag.contains("damage") ? namedTag.getDouble("damage") : getBaseDamage(); @@ -36,13 +63,7 @@ protected double getBaseDamage() { public boolean hadCollision = false; - public boolean closeOnCollide = true; - - protected double damage = 0; - - public static final int PICKUP_NONE = 0; - public static final int PICKUP_ANY = 1; - public static final int PICKUP_CREATIVE = 2; + public int piercing; public EntityProjectile(FullChunk chunk, CompoundTag nbt) { this(chunk, nbt, null); @@ -51,13 +72,17 @@ public EntityProjectile(FullChunk chunk, CompoundTag nbt) { public EntityProjectile(FullChunk chunk, CompoundTag nbt, Entity shootingEntity) { super(chunk, nbt); this.shootingEntity = shootingEntity; - if (shootingEntity != null) { + /*if (shootingEntity != null) { this.setDataProperty(new LongEntityData(DATA_SHOOTER_ID, shootingEntity.getId())); - } + }*/ } + /** + * Get the amount of damage this projectile will deal to the entity it hits. + * @return damage + */ public int getResultDamage() { - return NukkitMath.ceilDouble(Math.sqrt(this.motionX * this.motionX + this.motionY * this.motionY + this.motionZ * this.motionZ) * getDamage()); + return NukkitMath.ceilDouble(this.getDamage()); } public boolean attack(EntityDamageEvent source) { @@ -66,44 +91,56 @@ public boolean attack(EntityDamageEvent source) { public void onCollideWithEntity(Entity entity) { this.server.getPluginManager().callEvent(new ProjectileHitEvent(this, MovingObjectPosition.fromEntity(entity))); - float damage = this instanceof EntitySnowball && entity.getNetworkId() == EntityBlaze.NETWORK_ID ? 3f : this.getResultDamage(); + float damage = this instanceof EntitySnowball && entity instanceof EntityBlaze ? 3 : this.getResultDamage(); EntityDamageEvent ev; if (this.shootingEntity == null) { - ev = new EntityDamageByEntityEvent(this, entity, DamageCause.PROJECTILE, damage); + ev = new EntityDamageByEntityEvent(this, entity, DamageCause.PROJECTILE, damage, knockBack); } else { - ev = new EntityDamageByChildEntityEvent(this.shootingEntity, this, entity, DamageCause.PROJECTILE, damage); + ev = new EntityDamageByChildEntityEvent(this.shootingEntity, this, entity, DamageCause.PROJECTILE, damage, knockBack); } + if (entity.attack(ev)) { this.hadCollision = true; - if (this.fireTicks > 0) { + this.onHit(); + + if (this.fireTicks > 0 && entity.isAlive()) { EntityCombustByEntityEvent event = new EntityCombustByEntityEvent(this, entity, 5); this.server.getPluginManager().callEvent(event); if (!event.isCancelled()) { entity.setOnFire(event.getDuration()); } } + + if (this instanceof EntityArrow && entity instanceof EntityLiving) { + addEffectFromTippedArrow(entity, ItemArrow.getEffect(((EntityArrow) this).getData()), ev.getFinalDamage()); + } } - if (closeOnCollide) { - this.close(); - } + + this.close(); } @Override protected void initEntity() { - super.initEntity(); - this.setMaxHealth(1); + super.initEntity(); this.setHealth(1); + if (this.namedTag.contains("Age")) { this.age = this.namedTag.getShort("Age"); } + + if (this.namedTag.contains("knockback")) { + this.knockBack = this.namedTag.getFloat("knockback"); + } + + this.updateRotation(); } @Override public boolean canCollideWith(Entity entity) { - return (entity instanceof EntityLiving || entity instanceof EntityEndCrystal || entity instanceof EntityMinecartAbstract || entity instanceof EntityBoat) && !this.onGround; + return (entity instanceof EntityLiving || entity instanceof EntityEndCrystal || entity instanceof EntityMinecartAbstract || entity instanceof EntityBoat || entity instanceof EntityPainting) && !this.onGround && !entity.noClip && !this.noClip; } @Override @@ -127,24 +164,36 @@ public boolean onUpdate(int currentTick) { boolean hasUpdate = this.entityBaseTick(tickDiff); if (this.isAlive()) { - MovingObjectPosition movingObjectPosition = null; if (!this.isCollided) { - this.motionY -= this.getGravity(); + if (this.isInsideOfWater()) { + this.motionY -= this.getGravity() - (this.getGravity() / 2); + } else { + this.motionY -= this.getGravity(); + } + this.motionX *= 1 - this.getDrag(); + this.motionZ *= 1 - this.getDrag(); + } else if (this.updateMode % 3 == 1) { + this.updateMode = 5; + + // Force check for nearby blocks changed + this.blocksAround = null; + this.collisionBlocks = null; + if (!this.level.hasCollisionBlocks(this, this.boundingBox.grow(0.01, 0.01, 0.01))) { + this.motionY = -0.00001; + } } Vector3 moveVector = new Vector3(this.x + this.motionX, this.y + this.motionY, this.z + this.motionZ); - Entity[] list = this.getLevel().getCollidingEntities(this.boundingBox.addCoord(this.motionX, this.motionY, this.motionZ).expand(1, 1, 1), this); + Entity[] list = this.noClip ? new Entity[0] : this.getLevel().getCollidingEntities(this.boundingBox.addCoord(this.motionX, this.motionY, this.motionZ).expand(1, 1, 1), this); double nearDistance = Integer.MAX_VALUE; Entity nearEntity = null; for (Entity entity : list) { - if (/*!entity.canCollideWith(this) or */ - (entity == this.shootingEntity && this.ticksLived < 5) - ) { + if (/*!entity.canCollideWith(this) || */(entity == this.shootingEntity && this.age < 5) || (entity instanceof Player && ((Player) entity).getGamemode() == Player.SPECTATOR)) { continue; } @@ -176,7 +225,11 @@ public boolean onUpdate(int currentTick) { this.move(this.motionX, this.motionY, this.motionZ); - if (this.isCollided && !this.hadCollision) { //collide with block + if (this.isCollided && !this.hadCollision) { // Collide with block + // Make sure last move tick is broadcast + // However previous yaw & pitch are actually the correct ones + if (!(this instanceof EntityFishingHook)) this.addMovement(this.x, this.y, this.z, this.lastYaw, this.lastPitch, this.lastYaw); + this.hadCollision = true; this.motionX = 0; @@ -184,22 +237,56 @@ public boolean onUpdate(int currentTick) { this.motionZ = 0; this.server.getPluginManager().callEvent(new ProjectileHitEvent(this, MovingObjectPosition.fromBlock(this.getFloorX(), this.getFloorY(), this.getFloorZ(), -1, this))); + this.onHit(); + this.onHitGround(moveVector); + + if (this instanceof EntityArrow || this instanceof EntityThrownTrident) { + this.updateMode = 5; // The projectile is collided with a block so only update it if the block changes or to check age for despawn + } return false; } else if (!this.isCollided && this.hadCollision) { this.hadCollision = false; } if (!this.hadCollision || Math.abs(this.motionX) > 0.00001 || Math.abs(this.motionY) > 0.00001 || Math.abs(this.motionZ) > 0.00001) { - double f = Math.sqrt((this.motionX * this.motionX) + (this.motionZ * this.motionZ)); - this.yaw = Math.atan2(this.motionX, this.motionZ) * 180 / Math.PI; - this.pitch = Math.atan2(this.motionY, f) * 180 / Math.PI; + updateRotation(); hasUpdate = true; } this.updateMovement(); - } return hasUpdate; } + + /** + * Update projectile rotation to match its motion. + */ + public void updateRotation() { + double f = Math.sqrt((this.motionX * this.motionX) + (this.motionZ * this.motionZ)); + this.yaw = Math.atan2(this.motionX, this.motionZ) * 180 / Math.PI; + this.pitch = Math.atan2(this.motionY, f) * 180 / Math.PI; + } + + /** + * Add inaccuracy to projectile movement. Used internally with dispensers. + * + * @param modifier multiplier + */ + public void inaccurate(float modifier) { + ThreadLocalRandom rand = ThreadLocalRandom.current(); + + this.motionX += rand.nextGaussian() * 0.007499999832361937 * modifier; + this.motionY += rand.nextGaussian() * 0.007499999832361937 * modifier; + this.motionZ += rand.nextGaussian() * 0.007499999832361937 * modifier; + } + + protected void onHit() { + + } + + protected void onHitGround(Vector3 moveVector) { + Block block = level.getBlock(this.chunk, moveVector.getFloorX(), moveVector.getFloorY(), moveVector.getFloorZ(), false); + block.onEntityCollide(this); + } } diff --git a/src/main/java/cn/nukkit/entity/projectile/EntitySnowball.java b/src/main/java/cn/nukkit/entity/projectile/EntitySnowball.java index ebad4aa4e94..36a32ec5cb4 100644 --- a/src/main/java/cn/nukkit/entity/projectile/EntitySnowball.java +++ b/src/main/java/cn/nukkit/entity/projectile/EntitySnowball.java @@ -1,14 +1,17 @@ package cn.nukkit.entity.projectile; import cn.nukkit.entity.Entity; +import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.particle.ItemBreakParticle; import cn.nukkit.nbt.tag.CompoundTag; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntitySnowball extends EntityProjectile { + public static final int NETWORK_ID = 81; @Override @@ -55,17 +58,17 @@ public boolean onUpdate(int currentTick) { return false; } - this.timing.startTiming(); - - boolean hasUpdate = super.onUpdate(currentTick); - - if (this.age > 1200 || this.isCollided) { - this.kill(); - hasUpdate = true; + if (this.age > 1200 || this.isCollided || this.hadCollision) { + this.close(); + return false; } - this.timing.stopTiming(); + super.onUpdate(currentTick); + return !this.closed; + } - return hasUpdate; + @Override + public void onHit() { + level.addParticle(new ItemBreakParticle(this, Item.get(Item.SNOWBALL)), null, 5); } } diff --git a/src/main/java/cn/nukkit/entity/projectile/EntityThrownTrident.java b/src/main/java/cn/nukkit/entity/projectile/EntityThrownTrident.java index 35602725646..b73df408379 100644 --- a/src/main/java/cn/nukkit/entity/projectile/EntityThrownTrident.java +++ b/src/main/java/cn/nukkit/entity/projectile/EntityThrownTrident.java @@ -1,6 +1,8 @@ package cn.nukkit.entity.projectile; +import cn.nukkit.Player; import cn.nukkit.entity.Entity; +import cn.nukkit.entity.data.LongEntityData; import cn.nukkit.entity.weather.EntityLightning; import cn.nukkit.event.entity.EntityDamageByChildEntityEvent; import cn.nukkit.event.entity.EntityDamageByEntityEvent; @@ -10,15 +12,18 @@ import cn.nukkit.event.weather.LightningStrikeEvent; import cn.nukkit.item.Item; import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.level.GameRule; import cn.nukkit.level.MovingObjectPosition; import cn.nukkit.level.format.FullChunk; +import cn.nukkit.math.BlockVector3; +import cn.nukkit.math.Vector3; import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.DoubleTag; +import cn.nukkit.nbt.tag.IntTag; +import cn.nukkit.nbt.tag.ListTag; import cn.nukkit.network.protocol.LevelSoundEventPacket; -/** - * Created by PetteriM1 - */ public class EntityThrownTrident extends EntityProjectile { public static final int NETWORK_ID = 73; @@ -26,7 +31,25 @@ public class EntityThrownTrident extends EntityProjectile { protected Item trident; protected int pickupMode; - public boolean alreadyCollided; + + private Vector3 collisionPos; + + private BlockVector3 stuckToBlockPos; + + private int favoredSlot; + + private boolean player; + + private int loyaltyLevel; + + private boolean hasChanneling; + private boolean didHit; + + private int impalingLevel; + + private static final Vector3 defaultCollisionPos = new Vector3(0, 0, 0); + + private static final BlockVector3 defaultStuckToBlockPos = new BlockVector3(0, 0, 0); @Override public int getNetworkId() { @@ -35,22 +58,22 @@ public int getNetworkId() { @Override public float getWidth() { - return 0.05f; + return 0.25f; } @Override public float getLength() { - return 0.5f; + return 0.25f; } @Override public float getHeight() { - return 0.05f; + return 0.35f; } @Override public float getGravity() { - return 0.05f; + return 0.04f; } @Override @@ -66,17 +89,49 @@ public EntityThrownTrident(FullChunk chunk, CompoundTag nbt, Entity shootingEnti super(chunk, nbt, shootingEntity); } - @Deprecated - public EntityThrownTrident(FullChunk chunk, CompoundTag nbt, Entity shootingEntity, boolean critical) { - this(chunk, nbt, shootingEntity); - } - @Override protected void initEntity() { super.initEntity(); - this.trident = namedTag.contains("Trident") ? NBTIO.getItemHelper(namedTag.getCompound("Trident")) : Item.get(0); this.pickupMode = namedTag.contains("pickup") ? namedTag.getByte("pickup") : PICKUP_ANY; + + if (namedTag.contains("Trident")) { + this.trident = NBTIO.getItemHelper(namedTag.getCompound("Trident")); + this.loyaltyLevel = this.trident.getEnchantmentLevel(Enchantment.ID_TRIDENT_LOYALTY); + this.hasChanneling = this.trident.hasEnchantment(Enchantment.ID_TRIDENT_CHANNELING); + this.impalingLevel = this.trident.getEnchantmentLevel(Enchantment.ID_TRIDENT_IMPALING); + } else { + this.trident = Item.get(0); + this.loyaltyLevel = 0; + this.hasChanneling = false; + this.impalingLevel = 0; + } + + if (namedTag.contains("CollisionPos")) { + ListTag collisionPosList = this.namedTag.getList("CollisionPos", DoubleTag.class); + collisionPos = new Vector3(collisionPosList.get(0).data, collisionPosList.get(1).data, collisionPosList.get(2).data); + } else { + collisionPos = defaultCollisionPos.clone(); + } + + if (namedTag.contains("StuckToBlockPos")) { + ListTag stuckToBlockPosList = this.namedTag.getList("StuckToBlockPos", IntTag.class); + stuckToBlockPos = new BlockVector3(stuckToBlockPosList.get(0).data, stuckToBlockPosList.get(1).data, stuckToBlockPosList.get(2).data); + } else { + stuckToBlockPos = defaultStuckToBlockPos.clone(); + } + + if (namedTag.contains("favoredSlot")) { + this.favoredSlot = namedTag.getInt("favoredSlot"); + } else { + this.favoredSlot = -1; + } + + if (namedTag.contains("player")) { + this.player = namedTag.getBoolean("player"); + } else { + this.player = true; + } } @Override @@ -85,6 +140,18 @@ public void saveNBT() { this.namedTag.put("Trident", NBTIO.putItemHelper(this.trident)); this.namedTag.putByte("pickup", this.pickupMode); + this.namedTag.putList(new ListTag("CollisionPos") + .add(new DoubleTag("0", this.collisionPos.x)) + .add(new DoubleTag("1", this.collisionPos.y)) + .add(new DoubleTag("2", this.collisionPos.z)) + ); + this.namedTag.putList(new ListTag("StuckToBlockPos") + .add(new IntTag("0", this.stuckToBlockPos.x)) + .add(new IntTag("1", this.stuckToBlockPos.y)) + .add(new IntTag("2", this.stuckToBlockPos.z)) + ); + this.namedTag.putInt("favoredSlot", this.favoredSlot); + this.namedTag.putBoolean("player", this.player); } public Item getItem() { @@ -93,6 +160,9 @@ public Item getItem() { public void setItem(Item item) { this.trident = item.clone(); + this.loyaltyLevel = this.trident.getEnchantmentLevel(Enchantment.ID_TRIDENT_LOYALTY); + this.hasChanneling = this.trident.hasEnchantment(Enchantment.ID_TRIDENT_CHANNELING); + this.impalingLevel = this.trident.getEnchantmentLevel(Enchantment.ID_TRIDENT_IMPALING); } @Override @@ -100,43 +170,160 @@ protected double getBaseDamage() { return 8; } + @Override + public boolean onUpdate(int currentTick) { + if (this.closed) { + return false; + } + + if (this.age > 1200 && this.pickupMode < 1) { // On Bedrock tridents shouldn't despawn + this.close(); + return false; + } + + boolean hasUpdate = super.onUpdate(currentTick); + + if (this.noClip) { + if (this.canReturnToShooter()) { + Entity shooter = this.shootingEntity; + Vector3 vector3 = new Vector3(shooter.x - this.x, shooter.y + shooter.getEyeHeight() - this.y, shooter.z - this.z); + this.setPosition(new Vector3(this.x, this.y + vector3.y * 0.015 * ((double) loyaltyLevel), this.z)); + this.setMotion(this.getMotion().multiply(0.95).add(vector3.multiply(loyaltyLevel * 0.05))); + hasUpdate = true; + } else { + if (!this.closed && level.getGameRules().getBoolean(GameRule.DO_ENTITY_DROPS)) { + this.level.dropItem(this, this.trident); + } + this.close(); + } + } + + return hasUpdate; + } + @Override public void onCollideWithEntity(Entity entity) { - if (this.alreadyCollided) { - this.move(this.motionX, this.motionY, this.motionZ); + if (this.noClip) { return; } this.server.getPluginManager().callEvent(new ProjectileHitEvent(this, MovingObjectPosition.fromEntity(entity))); float damage = this.getResultDamage(); + if (this.impalingLevel > 0 && (entity.isInsideOfWater() || (entity.getLevel().isRaining() && entity.canSeeSky()))) { + damage = damage + (2.5f * (float) this.impalingLevel); + } + EntityDamageEvent ev; if (this.shootingEntity == null) { - ev = new EntityDamageByEntityEvent(this, entity, DamageCause.PROJECTILE, damage); + ev = new EntityDamageByEntityEvent(this, entity, DamageCause.PROJECTILE, damage, knockBack); } else { - ev = new EntityDamageByChildEntityEvent(this.shootingEntity, this, entity, DamageCause.PROJECTILE, damage); + ev = new EntityDamageByChildEntityEvent(this.shootingEntity, this, entity, DamageCause.PROJECTILE, damage, knockBack); } entity.attack(ev); this.hadCollision = true; - this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_ITEM_TRIDENT_HIT); - this.close(); - if (trident != null && level.isThundering() && trident.hasEnchantment(Enchantment.ID_TRIDENT_CHANNELING) && level.canBlockSeeSky(this)) { - EntityLightning bolt = new EntityLightning(this.getChunk(), getDefaultNBT(this)); - LightningStrikeEvent strikeEvent = new LightningStrikeEvent(level, bolt); - server.getPluginManager().callEvent(strikeEvent); - if (!strikeEvent.isCancelled()) { - bolt.spawnToAll(); - level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_ITEM_TRIDENT_THUNDER); - } else { - bolt.setEffect(false); + this.onHit(); + this.setCollisionPos(this); + this.setMotion(new Vector3(this.getMotion().getX() * -0.01, this.getMotion().getY() * -0.1, this.getMotion().getZ() * -0.01)); + + if (this.hasChanneling && !this.didHit) { + this.didHit = true; + if (level.isThundering() && this.canSeeSky()) { + EntityLightning bolt = (EntityLightning) Entity.createEntity(EntityLightning.NETWORK_ID, this.getChunk(), getDefaultNBT(this)); + LightningStrikeEvent strikeEvent = new LightningStrikeEvent(level, bolt); + server.getPluginManager().callEvent(strikeEvent); + if (!strikeEvent.isCancelled()) { + bolt.spawnToAll(); + level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_ITEM_TRIDENT_THUNDER); + } else { + bolt.setEffect(false); + } } } - EntityThrownTrident newTrident = (EntityThrownTrident) Entity.createEntity("ThrownTrident", this); - newTrident.alreadyCollided = true; - newTrident.pickupMode = this.pickupMode; - newTrident.shootingEntity = this.shootingEntity; - newTrident.setItem(this.trident); - newTrident.spawnToAll(); + + if (this.canReturnToShooter()) { + this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_ITEM_TRIDENT_RETURN); + this.noClip = true; + this.hadCollision = false; + this.setRope(true); + } + } + + @Override + public void onHit() { + this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_ITEM_TRIDENT_HIT); + } + + @Override + public void onHitGround(Vector3 moveVector) { + if (this.noClip) { + return; + } + super.onHitGround(moveVector); + + this.setStuckToBlockPos(new BlockVector3(moveVector.getFloorX(), moveVector.getFloorY(), moveVector.getFloorZ())); + if (this.canReturnToShooter()) { + this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_ITEM_TRIDENT_RETURN); + this.noClip = true; + this.setRope(true); + } + } + + public Vector3 getCollisionPos() { + return collisionPos; + } + + public void setCollisionPos(Vector3 collisionPos) { + this.collisionPos = collisionPos; + } + + public BlockVector3 getStuckToBlockPos() { + return stuckToBlockPos; + } + + public void setStuckToBlockPos(BlockVector3 stuckToBlockPos) { + this.stuckToBlockPos = stuckToBlockPos; + } + + public int getFavoredSlot() { + return favoredSlot; + } + + public void setFavoredSlot(int favoredSlot) { + this.favoredSlot = favoredSlot; + } + + public boolean shotByPlayer() { + return player; + } + + public void setShotByPlayer(boolean player) { + this.player = player; + } + + public void setRope(boolean tridentRope) { + if (tridentRope) { + this.setDataProperty(new LongEntityData(DATA_OWNER_EID, this.shootingEntity.getId())); + } else { + this.setDataProperty(new LongEntityData(DATA_OWNER_EID, -1)); + } + this.setDataFlag(DATA_FLAGS, DATA_FLAG_SHOW_TRIDENT_ROPE, tridentRope); + } + + private boolean canReturnToShooter() { + if (this.loyaltyLevel <= 0) { + return false; + } + + if (this.getCollisionPos().equals(defaultCollisionPos) && this.getStuckToBlockPos().equals(defaultStuckToBlockPos)) { + return false; + } + + Entity shooter = this.shootingEntity; + if (shooter != null) { + return shooter instanceof Player && shooter.isAlive() && !shooter.isClosed() && shooter.getLevel().getId() == this.getLevel().getId() && !(((Player) shooter).isSpectator()); + } + return false; } public int getPickupMode() { diff --git a/src/main/java/cn/nukkit/entity/weather/EntityLightning.java b/src/main/java/cn/nukkit/entity/weather/EntityLightning.java index f624fd37a2b..5228093a62c 100644 --- a/src/main/java/cn/nukkit/entity/weather/EntityLightning.java +++ b/src/main/java/cn/nukkit/entity/weather/EntityLightning.java @@ -11,8 +11,7 @@ import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.network.protocol.LevelSoundEventPacket; - -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; /** * Created by boybook on 2016/2/27. @@ -26,7 +25,6 @@ public class EntityLightning extends Entity implements EntityLightningStrike { public int state; public int liveTime; - @Override public int getNetworkId() { return NETWORK_ID; @@ -40,14 +38,11 @@ public EntityLightning(FullChunk chunk, CompoundTag nbt) { protected void initEntity() { super.initEntity(); - this.setHealth(4); - this.setMaxHealth(4); - this.state = 2; - this.liveTime = ThreadLocalRandom.current().nextInt(3) + 1; + this.liveTime = Utils.random.nextInt(3) + 1; if (isEffect && this.level.gameRules.getBoolean(GameRule.DO_FIRE_TICK) && (this.server.getDifficulty() >= 2)) { - Block block = this.getLevelBlock(); + Block block = this.level.getBlock(this.chunk, this.getFloorX(), this.getFloorY(), this.getFloorZ(), true); if (block.getId() == 0 || block.getId() == Block.TALL_GRASS) { BlockFire fire = (BlockFire) Block.get(BlockID.FIRE); fire.x = block.x; @@ -62,7 +57,7 @@ protected void initEntity() { if (!e.isCancelled()) { level.setBlock(fire, fire, true); - level.scheduleUpdate(fire, fire.tickRate() + ThreadLocalRandom.current().nextInt(10)); + level.scheduleUpdate(fire, fire.tickRate() + Utils.random.nextInt(10)); } } } @@ -79,7 +74,6 @@ public void setEffect(boolean e) { @Override public boolean attack(EntityDamageEvent source) { - //false? source.setDamage(0); return super.attack(source); } @@ -101,8 +95,8 @@ public boolean onUpdate(int currentTick) { this.entityBaseTick(tickDiff); if (this.state == 2) { - this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_THUNDER); - this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_EXPLODE); + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_THUNDER, -1, EntityLightning.NETWORK_ID); + this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_EXPLODE, -1, EntityLightning.NETWORK_ID); } this.state--; @@ -111,12 +105,12 @@ public boolean onUpdate(int currentTick) { if (this.liveTime == 0) { this.close(); return false; - } else if (this.state < -ThreadLocalRandom.current().nextInt(10)) { + } else if (this.state < -Utils.random.nextInt(10)) { this.liveTime--; this.state = 1; if (this.isEffect && this.level.gameRules.getBoolean(GameRule.DO_FIRE_TICK)) { - Block block = this.getLevelBlock(); + Block block = this.level.getBlock(this.chunk, this.getFloorX(), this.getFloorY(), this.getFloorZ(), true); if (block.getId() == Block.AIR || block.getId() == Block.TALL_GRASS) { BlockIgniteEvent e = new BlockIgniteEvent(block, null, this, BlockIgniteEvent.BlockIgniteCause.LIGHTNING); @@ -146,5 +140,8 @@ public boolean onUpdate(int currentTick) { return true; } - + @Override + public boolean canSaveToStorage() { + return false; + } } diff --git a/src/main/java/cn/nukkit/entity/weather/EntityLightningStrike.java b/src/main/java/cn/nukkit/entity/weather/EntityLightningStrike.java index a82f8c28972..21fd57fc39d 100644 --- a/src/main/java/cn/nukkit/entity/weather/EntityLightningStrike.java +++ b/src/main/java/cn/nukkit/entity/weather/EntityLightningStrike.java @@ -8,5 +8,4 @@ public interface EntityLightningStrike extends EntityWeather { boolean isEffect(); void setEffect(boolean e); - } diff --git a/src/main/java/cn/nukkit/event/Event.java b/src/main/java/cn/nukkit/event/Event.java index 1c320636e62..c218705fbee 100644 --- a/src/main/java/cn/nukkit/event/Event.java +++ b/src/main/java/cn/nukkit/event/Event.java @@ -5,21 +5,20 @@ /** * 描述服务器中可能发生的事情的类。
* Describes things that happens in the server. - * - *

服务器中可能发生的事情称作事件。定义一个需要它在一个事件发生时被运行的过程,这个过程称作监听器
+ *

+ * 服务器中可能发生的事情称作事件。定义一个需要它在一个事件发生时被运行的过程,这个过程称作监听器
* Things that happens in the server is called a event. Define a procedure that should be executed - * when a event happens, this procedure is called a listener.

- * - *

Nukkit调用事件的处理器时,会通过参数的类型判断需要被监听的事件。
- * When Nukkit is calling a handler, the event needed to listen is judged by the type of the parameter.

- * - *

关于监听器的实现,参阅:{@link Listener}
- * For the way to implement a listener, see: {@link cn.nukkit.event.Listener}

+ * when a event happens, this procedure is called a listener. + *

+ * Nukkit调用事件的处理器时,会通过参数的类型判断需要被监听的事件。
+ * When Nukkit is calling a handler, the event needed to listen is judged by the type of the parameter. + *

+ * 关于监听器的实现,参阅:{@link Listener}
+ * For the way to implement a listener, see: {@link cn.nukkit.event.Listener} * * @author Unknown(code) @ Nukkit Project * @author 粉鞋大妈(javadoc) @ Nukkit Project * @see cn.nukkit.event.EventHandler - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public abstract class Event { diff --git a/src/main/java/cn/nukkit/event/EventHandler.java b/src/main/java/cn/nukkit/event/EventHandler.java index 156f9ed807b..bae636ad27a 100644 --- a/src/main/java/cn/nukkit/event/EventHandler.java +++ b/src/main/java/cn/nukkit/event/EventHandler.java @@ -8,19 +8,18 @@ /** * 定义一个事件的处理器的注解。
* Annotation that defines a handler. - * - *

一个处理器的重要程度被称作处理器的优先级,优先级高的处理器有更多的决定权。参见:{@link #priority()}
+ *

+ * 一个处理器的重要程度被称作处理器的优先级,优先级高的处理器有更多的决定权。参见:{@link #priority()}
* The importance of a handler is called its priority, handlers with higher priority speaks louder then - * lower ones. See: {@link #priority()}

- * - *

处理器可以选择忽略或不忽略被取消的事件,这种特性可以在{@link #ignoreCancelled()}中定义。
- * A handler can choose to ignore a cancelled event or not, that can be defined in {@link #ignoreCancelled()}.

+ * lower ones. See: {@link #priority()} + * + * 处理器可以选择忽略或不忽略被取消的事件,这种特性可以在{@link #ignoreCancelled()}中定义。
+ * A handler can choose to ignore a cancelled event or not, that can be defined in {@link #ignoreCancelled()}. * * @author MagicDroidX(code) @ Nukkit Project * @author null(javadoc) @ Nukkit Project * @see cn.nukkit.event.Listener * @see cn.nukkit.event.Event - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ @Target(ElementType.METHOD) @@ -29,9 +28,9 @@ /** * 定义这个处理器的优先级。
* Define the priority of the handler. - * - *

Nukkit调用处理器时会按照优先级从低到高的顺序调用,这样保证了高优先级的监听器能覆盖低优先级监听器做出的处理。 - * 调用的先后顺序如下:

+ *

+ * Nukkit调用处理器时会按照优先级从低到高的顺序调用,这样保证了高优先级的监听器能覆盖低优先级监听器做出的处理。 + * 调用的先后顺序如下:
* When Nukkit calls all handlers, ones with lower priority is called earlier, * that make handlers with higher priority can replace the decisions made by lower ones. * The order that Nukkit call handlers is from the first to the last as: @@ -45,20 +44,18 @@ * * * @return 这个处理器的优先级。
The priority of this handler. - * @see cn.nukkit.event.EventHandler */ EventPriority priority() default EventPriority.NORMAL; /** * 定义这个处理器是否忽略被取消的事件。
* Define if the handler ignores a cancelled event. - * - *

如果为{@code true}而且事件发生,这个处理器不会被调用,反之相反。
+ *

+ * 如果为{@code true}而且事件发生,这个处理器不会被调用,反之相反。
* If ignoreCancelled is {@code true} and the event is cancelled, the method is - * not called. Otherwise, the method is always called.

+ * not called. Otherwise, the method is always called. * * @return 这个处理器是否忽略被取消的事件。
Whether cancelled events should be ignored. - * @see cn.nukkit.event.EventHandler */ boolean ignoreCancelled() default false; } diff --git a/src/main/java/cn/nukkit/event/EventPriority.java b/src/main/java/cn/nukkit/event/EventPriority.java index f0e6304f20e..8193de3bb74 100644 --- a/src/main/java/cn/nukkit/event/EventPriority.java +++ b/src/main/java/cn/nukkit/event/EventPriority.java @@ -1,7 +1,7 @@ package cn.nukkit.event; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public enum EventPriority { diff --git a/src/main/java/cn/nukkit/event/HandlerList.java b/src/main/java/cn/nukkit/event/HandlerList.java index c63b9fe0efc..0423967d126 100644 --- a/src/main/java/cn/nukkit/event/HandlerList.java +++ b/src/main/java/cn/nukkit/event/HandlerList.java @@ -2,6 +2,8 @@ import cn.nukkit.plugin.Plugin; import cn.nukkit.plugin.RegisteredListener; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; import java.util.*; @@ -12,9 +14,9 @@ public class HandlerList { private volatile RegisteredListener[] handlers = null; - private final EnumMap> handlerslots; - - private static final ArrayList allLists = new ArrayList<>(); + private final EnumMap> handlerslots; + private static final List allLists = new ObjectArrayList<>(); + private static final Map, HandlerList> eventHandlerLists = new Object2ObjectOpenHashMap<>(); public static void bakeAll() { synchronized (allLists) { @@ -56,7 +58,7 @@ public static void unregisterAll(Listener listener) { public HandlerList() { handlerslots = new EnumMap<>(EventPriority.class); for (EventPriority o : EventPriority.values()) { - handlerslots.put(o, new ArrayList<>()); + handlerslots.put(o, new ObjectArrayList<>()); } synchronized (allLists) { allLists.add(this); @@ -110,8 +112,8 @@ public synchronized void unregister(Listener listener) { public synchronized void bake() { if (handlers != null) return; // don't re-bake when still valid - List entries = new ArrayList<>(); - for (Map.Entry> entry : handlerslots.entrySet()) { + List entries = new ObjectArrayList<>(); + for (Map.Entry> entry : handlerslots.entrySet()) { entries.addAll(entry.getValue()); } handlers = entries.toArray(new RegisteredListener[0]); @@ -150,4 +152,11 @@ public static ArrayList getHandlerLists() { } } + public static HandlerList getCachedHandlerList(Class clazz) { + return eventHandlerLists.get(clazz); + } + + public static void putCachedHandlerList(Class clazz, HandlerList handlerList) { + eventHandlerLists.put(clazz, handlerList); + } } diff --git a/src/main/java/cn/nukkit/event/Listener.java b/src/main/java/cn/nukkit/event/Listener.java index 5bd029f168f..3decd2d1d21 100644 --- a/src/main/java/cn/nukkit/event/Listener.java +++ b/src/main/java/cn/nukkit/event/Listener.java @@ -3,26 +3,26 @@ /** * 所有的监听事件的类必须实现的接口。
* An interface implemented by all classes that handles events. - * - *

插件要监听事件,需要一个类实现这个接口,在这个类里编写方法来监听。这个类称作监听类。 + *

+ * 插件要监听事件,需要一个类实现这个接口,在这个类里编写方法来监听。这个类称作监听类。 * 监听类中监听事件的方法称作事件的处理器。一个监听类可以包含多个不同的事件处理器。 * 实现监听类后,插件需要在插件管理器中注册这个监听类。
* If a plugin need to listen events, there must be a class implement this interface. This class is called a listener class. * Methods with specified parameters should be written in order to listen events. This method is called a handler. * One listener class could contain many different handlers. - * After implemented the listener class, plugin should register it in plugin manager.

- * - *

事件监听器被注册后,Nukkit会在需要监听的事件发生时,使用反射来调用监听类中对应的处理器。
- * After registered, Nukkit will call the handler in the listener classes by reflection when a event happens.

- * - *

这是一个编写监听类和处理器的例子。注意的是,标签{@code @EventHandler}和参数的类型是必需的:
+ * After implemented the listener class, plugin should register it in plugin manager. + *

+ * 事件监听器被注册后,Nukkit会在需要监听的事件发生时,使用反射来调用监听类中对应的处理器。
+ * After registered, Nukkit will call the handler in the listener classes by reflection when a event happens. + *

+ * 这是一个编写监听类和处理器的例子。注意的是,标签{@code @EventHandler}和参数的类型是必需的:
* Here is an example for writing a listener class and a handler method. - * Note that for the handler, tag {@code @EventHandler} and the parameter is required:

+ * Note that for the handler, tag {@code @EventHandler} and the parameter is required: *
  * public class ExampleListener implements Listener {
  *    {@code @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = false)}
  *     public void onBlockBreak(BlockBreakEvent event) {
- *          int blockID = event.getBlock().getPackId();
+ *          int blockID = event.getBlock().getId();
  *          if (blockID == Block.STONE) {
  *              event.getPlayer().sendMessage("Oops, my ExampleListener won't let you break a stone!")
  *              event.setCancelled(true);
@@ -31,16 +31,15 @@
  * }
  * 
* - *

关于注册监听类,请看:{@link cn.nukkit.plugin.PluginManager#registerEvents}.
- * For registering listener class, See: {@link cn.nukkit.plugin.PluginManager#registerEvents}.

- * - *

关于处理器的优先级和处理器是否忽略被取消的事件,请看:{@link EventHandler}.
- * For the priority of handler and whether the handler ignore cancelled events or not, See: {@link EventHandler}.

+ * 关于注册监听类,请看:{@link cn.nukkit.plugin.PluginManager#registerEvents}.
+ * For registering listener class, See: {@link cn.nukkit.plugin.PluginManager#registerEvents}. + *

+ * 关于处理器的优先级和处理器是否忽略被取消的事件,请看:{@link EventHandler}.
+ * For the priority of handler and whether the handler ignore cancelled events or not, See: {@link EventHandler}. * * @author Unknown(code) @ Nukkit Project * @author 粉鞋大妈(javadoc) @ Nukkit Project * @see cn.nukkit.event.Event - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public interface Listener { } diff --git a/src/main/java/cn/nukkit/event/block/AnvilDamageEvent.java b/src/main/java/cn/nukkit/event/block/AnvilDamageEvent.java index aee8e00eefe..043f2844bf2 100644 --- a/src/main/java/cn/nukkit/event/block/AnvilDamageEvent.java +++ b/src/main/java/cn/nukkit/event/block/AnvilDamageEvent.java @@ -15,9 +15,17 @@ public static HandlerList getHandlers() { private final int oldDamage; private int newDamage; - private DamageCause cause; + private final DamageCause cause; private final Player player; + /** + * This event is called when an anvil is damaged. + * @param block The block (anvil) that has been damaged. + * @param oldDamage Old damage value. + * @param newDamage New damage value. + * @param cause Cause of the anvil being damaged. + * @param player The player who used the anvil. + */ public AnvilDamageEvent(Block block, int oldDamage, int newDamage, DamageCause cause, Player player) { super(block); this.oldDamage = oldDamage; diff --git a/src/main/java/cn/nukkit/event/block/BellRingEvent.java b/src/main/java/cn/nukkit/event/block/BellRingEvent.java new file mode 100644 index 00000000000..1129b76f08c --- /dev/null +++ b/src/main/java/cn/nukkit/event/block/BellRingEvent.java @@ -0,0 +1,46 @@ +package cn.nukkit.event.block; + +import cn.nukkit.block.BlockBell; +import cn.nukkit.entity.Entity; +import cn.nukkit.event.Cancellable; +import cn.nukkit.event.HandlerList; + +public class BellRingEvent extends BlockEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlers() { + return handlers; + } + + private final RingCause cause; + private final Entity entity; + + public BellRingEvent(BlockBell bell, RingCause cause, Entity entity) { + super(bell); + this.cause = cause; + this.entity = entity; + } + + @Override + public BlockBell getBlock() { + return (BlockBell) super.getBlock(); + } + + public Entity getEntity() { + return entity; + } + + public RingCause getCause() { + return cause; + } + + public enum RingCause { + HUMAN_INTERACTION, + REDSTONE, + PROJECTILE, + DROPPED_ITEM, + UNKNOWN + } + +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/event/block/BlockBreakEvent.java b/src/main/java/cn/nukkit/event/block/BlockBreakEvent.java index c2b7995cae9..7b6d683468b 100644 --- a/src/main/java/cn/nukkit/event/block/BlockBreakEvent.java +++ b/src/main/java/cn/nukkit/event/block/BlockBreakEvent.java @@ -6,10 +6,11 @@ import cn.nukkit.event.HandlerList; import cn.nukkit.item.Item; import cn.nukkit.math.BlockFace; +import cn.nukkit.math.Vector3; /** - * author: MagicDroidX - * Nukkit Project + * Event for Block being broken. + * @author MagicDroidX */ public class BlockBreakEvent extends BlockEvent implements Cancellable { @@ -24,12 +25,21 @@ public static HandlerList getHandlers() { protected final Item item; protected final BlockFace face; - protected boolean instaBreak = false; - protected Item[] blockDrops = new Item[0]; - protected int blockXP = 0; + protected boolean instaBreak; + protected Item[] blockDrops; + protected int blockXP; - protected boolean fastBreak = false; + protected boolean fastBreak; + protected Vector3 dropPosition; + + /** + * This event is called when a block is broken. + * @param player Player who broke the block. + * @param block Block that was broken. + * @param item Item used to break the block. + * @param drops Items dropped by the block. + */ public BlockBreakEvent(Player player, Block block, Item item, Item[] drops) { this(player, block, item, drops, false, false); } @@ -39,10 +49,10 @@ public BlockBreakEvent(Player player, Block block, Item item, Item[] drops, bool } public BlockBreakEvent(Player player, Block block, Item item, Item[] drops, boolean instaBreak, boolean fastBreak) { - this(player, block, null, item, drops, instaBreak, fastBreak); + this(player, block, null, item, drops, instaBreak, fastBreak, null); } - public BlockBreakEvent(Player player, Block block, BlockFace face, Item item, Item[] drops, boolean instaBreak, boolean fastBreak) { + public BlockBreakEvent(Player player, Block block, BlockFace face, Item item, Item[] drops, boolean instaBreak, boolean fastBreak, Vector3 dropPosition) { super(block); this.face = face; this.item = item; @@ -74,12 +84,20 @@ public Item[] getDrops() { } public void setDrops(Item[] drops) { + if (drops == null) { + drops = new Item[0]; + } + this.blockDrops = drops; } - public int getDropExp() { return this.blockXP; } + public int getDropExp() { + return this.blockXP; + } - public void setDropExp(int xp) { this.blockXP = xp; } + public void setDropExp(int xp) { + this.blockXP = xp; + } public void setInstaBreak(boolean instaBreak) { this.instaBreak = instaBreak; @@ -88,4 +106,12 @@ public void setInstaBreak(boolean instaBreak) { public boolean isFastBreak() { return this.fastBreak; } -} + + public void setDropPosition(Vector3 dropPosition) { + this.dropPosition = dropPosition; + } + + public Vector3 getDropPosition() { + return this.dropPosition; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/event/block/BlockBurnEvent.java b/src/main/java/cn/nukkit/event/block/BlockBurnEvent.java index f9f88f39125..5710e7181db 100644 --- a/src/main/java/cn/nukkit/event/block/BlockBurnEvent.java +++ b/src/main/java/cn/nukkit/event/block/BlockBurnEvent.java @@ -5,13 +5,17 @@ import cn.nukkit.event.HandlerList; /** - * author: MagicDroidX - * Nukkit Project + * Event for Block being burned. + * @author MagicDroidX */ public class BlockBurnEvent extends BlockEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); + /** + * This event is called when a block is burned. + * @param block Block that is burned. + */ public BlockBurnEvent(Block block) { super(block); } @@ -19,5 +23,4 @@ public BlockBurnEvent(Block block) { public static HandlerList getHandlers() { return handlers; } - } diff --git a/src/main/java/cn/nukkit/event/block/BlockEvent.java b/src/main/java/cn/nukkit/event/block/BlockEvent.java index 438ddfa56f3..bb1e39abece 100644 --- a/src/main/java/cn/nukkit/event/block/BlockEvent.java +++ b/src/main/java/cn/nukkit/event/block/BlockEvent.java @@ -4,13 +4,18 @@ import cn.nukkit.event.Event; /** - * author: MagicDroidX - * Nukkit Project + * Generic block event. + * @author MagicDroidX */ public abstract class BlockEvent extends Event { protected final Block block; + /** + * Generic block event. + * NOTICE: This event isn't meant to be called. + * @param block Block. + */ public BlockEvent(Block block) { this.block = block; } diff --git a/src/main/java/cn/nukkit/event/block/BlockExplodeEvent.java b/src/main/java/cn/nukkit/event/block/BlockExplodeEvent.java new file mode 100644 index 00000000000..5fbd3490c1d --- /dev/null +++ b/src/main/java/cn/nukkit/event/block/BlockExplodeEvent.java @@ -0,0 +1,55 @@ +package cn.nukkit.event.block; + +import cn.nukkit.block.Block; +import cn.nukkit.event.Cancellable; +import cn.nukkit.event.HandlerList; +import cn.nukkit.level.Position; + +import java.util.List; + +public class BlockExplodeEvent extends BlockEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlers() { + return handlers; + } + + protected final Position position; + protected List blocks; + protected double yield; + + /** + * Block explode event is called when a block explodes (For example a bed in nether) + * @param block Block that exploded + * @param position Position + * @param blocks Blocks affected by the explosion + * @param yield Explosion yield + */ + public BlockExplodeEvent(Block block, Position position, List blocks, double yield) { + super(block); + this.position = position; + this.blocks = blocks; + this.yield = yield; + } + + public Position getPosition() { + return this.position; + } + + public List getBlockList() { + return this.blocks; + } + + public void setBlockList(List blocks) { + this.blocks = blocks; + } + + public double getYield() { + return this.yield; + } + + public void setYield(double yield) { + this.yield = yield; + } +} diff --git a/src/main/java/cn/nukkit/event/block/BlockFadeEvent.java b/src/main/java/cn/nukkit/event/block/BlockFadeEvent.java index 950247145ba..24865a187fc 100644 --- a/src/main/java/cn/nukkit/event/block/BlockFadeEvent.java +++ b/src/main/java/cn/nukkit/event/block/BlockFadeEvent.java @@ -4,6 +4,9 @@ import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; +/** + * Event for Block fading. + */ public class BlockFadeEvent extends BlockEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); @@ -14,6 +17,14 @@ public static HandlerList getHandlers() { private final Block newState; + /** + * Currently used when: + * - Snow melts because of block light. + * - Ice melts because of block light. + * - Glowing redstone ore turns to normal redstone ore. + * @param block Block that has faded/melted. + * @param newState New state of the block. + */ public BlockFadeEvent(Block block, Block newState) { super(block); this.newState = newState; diff --git a/src/main/java/cn/nukkit/event/block/BlockFallEvent.java b/src/main/java/cn/nukkit/event/block/BlockFallEvent.java index 5f3c2001787..d4b5f59d7bd 100644 --- a/src/main/java/cn/nukkit/event/block/BlockFallEvent.java +++ b/src/main/java/cn/nukkit/event/block/BlockFallEvent.java @@ -4,6 +4,9 @@ import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; +/** + * Event for Block falling + */ public class BlockFallEvent extends BlockEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); @@ -12,6 +15,10 @@ public static HandlerList getHandlers() { return handlers; } + /** + * This event is called when a block is falling. + * @param block Block that has fallen. + */ public BlockFallEvent(Block block) { super(block); } diff --git a/src/main/java/cn/nukkit/event/block/BlockFormEvent.java b/src/main/java/cn/nukkit/event/block/BlockFormEvent.java index 5b2b025fc04..1f631c67fca 100644 --- a/src/main/java/cn/nukkit/event/block/BlockFormEvent.java +++ b/src/main/java/cn/nukkit/event/block/BlockFormEvent.java @@ -5,8 +5,8 @@ import cn.nukkit.event.HandlerList; /** - * author: MagicDroidX - * Nukkit Project + * Event for forming blocks. + * @author MagicDroidX */ public class BlockFormEvent extends BlockGrowEvent implements Cancellable { @@ -15,9 +15,13 @@ public class BlockFormEvent extends BlockGrowEvent implements Cancellable { public static HandlerList getHandlers() { return handlers; } - + /** + * Event for forming blocks. + * NOTICE: This event isn't meant to be called. + * @param block Block affected by the event. + * @param newState New state of the block. + */ public BlockFormEvent(Block block, Block newState) { super(block, newState); } - } diff --git a/src/main/java/cn/nukkit/event/block/BlockFromToEvent.java b/src/main/java/cn/nukkit/event/block/BlockFromToEvent.java index 106e7d5dbdd..bbb9c9f94a9 100644 --- a/src/main/java/cn/nukkit/event/block/BlockFromToEvent.java +++ b/src/main/java/cn/nukkit/event/block/BlockFromToEvent.java @@ -4,6 +4,9 @@ import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; +/** + * Event for Block change "From To". + */ public class BlockFromToEvent extends BlockEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); @@ -14,6 +17,11 @@ public static HandlerList getHandlers() { private Block to; + /** + * Event called on block changed from one type to another. E.g Redstone. + * @param block Block that is being replaced. + * @param to The replacement Block + */ public BlockFromToEvent(Block block, Block to) { super(block); this.to = to; diff --git a/src/main/java/cn/nukkit/event/block/BlockGrowEvent.java b/src/main/java/cn/nukkit/event/block/BlockGrowEvent.java index 9dba0550982..03a18ba3085 100644 --- a/src/main/java/cn/nukkit/event/block/BlockGrowEvent.java +++ b/src/main/java/cn/nukkit/event/block/BlockGrowEvent.java @@ -5,8 +5,8 @@ import cn.nukkit.event.HandlerList; /** - * author: MagicDroidX - * Nukkit Project + * Event for Block growth. + * @author MagicDroidX */ public class BlockGrowEvent extends BlockEvent implements Cancellable { @@ -18,6 +18,11 @@ public static HandlerList getHandlers() { private final Block newState; + /** + * Called on block grow. + * @param block Block affected by event E.g Vine. + * @param newState New state of the affected block. + */ public BlockGrowEvent(Block block, Block newState) { super(block); this.newState = newState; @@ -26,5 +31,4 @@ public BlockGrowEvent(Block block, Block newState) { public Block getNewState() { return newState; } - } diff --git a/src/main/java/cn/nukkit/event/block/BlockHarvestEvent.java b/src/main/java/cn/nukkit/event/block/BlockHarvestEvent.java new file mode 100644 index 00000000000..937bec30be8 --- /dev/null +++ b/src/main/java/cn/nukkit/event/block/BlockHarvestEvent.java @@ -0,0 +1,41 @@ +package cn.nukkit.event.block; + +import cn.nukkit.block.Block; +import cn.nukkit.event.Cancellable; +import cn.nukkit.event.HandlerList; +import cn.nukkit.item.Item; + +public class BlockHarvestEvent extends BlockEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + private Block newState; + private Item[] drops; + + public BlockHarvestEvent(Block block, Block newState, Item[] drops) { + super(block); + this.newState = newState; + this.drops = drops; + } + + public Block getNewState() { + return newState; + } + + public void setNewState(Block newState) { + this.newState = newState; + } + + public Item[] getDrops() { + return drops; + } + + public void setDrops(Item[] drops) { + this.drops = drops; + } + + public static HandlerList getHandlers() { + return handlers; + } + +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/event/block/BlockIgniteEvent.java b/src/main/java/cn/nukkit/event/block/BlockIgniteEvent.java index 7bad13ea485..de85bb22b04 100644 --- a/src/main/java/cn/nukkit/event/block/BlockIgniteEvent.java +++ b/src/main/java/cn/nukkit/event/block/BlockIgniteEvent.java @@ -5,6 +5,9 @@ import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; +/** + * Event for Block fire (ignite). + */ public class BlockIgniteEvent extends BlockEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); @@ -17,6 +20,13 @@ public static HandlerList getHandlers() { private final Entity entity; private final BlockIgniteCause cause; + /** + * Block ignite event is called when a block is ignited (lit on fire). + * @param block Block that has been ignited. + * @param source Block source of ignition. + * @param entity Entity source of ignition. + * @param cause Cause of the ignition. + */ public BlockIgniteEvent(Block block, Block source, Entity entity, BlockIgniteCause cause) { super(block); this.source = source; diff --git a/src/main/java/cn/nukkit/event/block/BlockPistonChangeEvent.java b/src/main/java/cn/nukkit/event/block/BlockPistonChangeEvent.java index ab5d0184f07..f81178af9cb 100644 --- a/src/main/java/cn/nukkit/event/block/BlockPistonChangeEvent.java +++ b/src/main/java/cn/nukkit/event/block/BlockPistonChangeEvent.java @@ -4,7 +4,8 @@ import cn.nukkit.event.HandlerList; /** - * Created by CreeperFace on 2.8.2017. + * Event for Block piston change. + * @author CreeperFace on 2.8.2017. */ public class BlockPistonChangeEvent extends BlockEvent { @@ -14,9 +15,15 @@ public static HandlerList getHandlers() { return handlers; } - private int oldPower; - private int newPower; + private final int oldPower; + private final int newPower; + /** + * This event is called on piston activation/deactivation/change. + * @param block Block (Piston) that is affected. + * @param oldPower Old power (charge) of piston. + * @param newPower New charge (updated) of piston. + */ public BlockPistonChangeEvent(Block block, int oldPower, int newPower) { super(block); this.oldPower = oldPower; diff --git a/src/main/java/cn/nukkit/event/block/BlockPistonEvent.java b/src/main/java/cn/nukkit/event/block/BlockPistonEvent.java new file mode 100644 index 00000000000..2d1cc3debd7 --- /dev/null +++ b/src/main/java/cn/nukkit/event/block/BlockPistonEvent.java @@ -0,0 +1,53 @@ +package cn.nukkit.event.block; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockPistonBase; +import cn.nukkit.event.Cancellable; +import cn.nukkit.event.HandlerList; +import cn.nukkit.math.BlockFace; + +import java.util.ArrayList; +import java.util.List; + +public class BlockPistonEvent extends BlockEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlers() { + return handlers; + } + + private final BlockFace direction; + private final List blocks; + private final List destroyedBlocks; + private final boolean extending; + + public BlockPistonEvent(BlockPistonBase piston, BlockFace direction, List blocks, List destroyedBlocks, boolean extending) { + super(piston); + this.direction = direction; + this.blocks = blocks; + this.destroyedBlocks = destroyedBlocks; + this.extending = extending; + } + + public BlockFace getDirection() { + return direction; + } + + public List getBlocks() { + return new ArrayList<>(blocks); + } + + public List getDestroyedBlocks() { + return destroyedBlocks; + } + + public boolean isExtending() { + return extending; + } + + @Override + public BlockPistonBase getBlock() { + return (BlockPistonBase) super.getBlock(); + } +} diff --git a/src/main/java/cn/nukkit/event/block/BlockPlaceEvent.java b/src/main/java/cn/nukkit/event/block/BlockPlaceEvent.java index 7ba1c6ceefe..3ada1db8105 100644 --- a/src/main/java/cn/nukkit/event/block/BlockPlaceEvent.java +++ b/src/main/java/cn/nukkit/event/block/BlockPlaceEvent.java @@ -7,8 +7,8 @@ import cn.nukkit.item.Item; /** - * author: MagicDroidX - * Nukkit Project + * Event for a block being placed. + * @author MagicDroidX */ public class BlockPlaceEvent extends BlockEvent implements Cancellable { @@ -25,6 +25,14 @@ public static HandlerList getHandlers() { protected final Block blockReplace; protected final Block blockAgainst; + /** + * This event is called when a block is placed. + * @param player Player who placed block. + * @param blockPlace Placed Block. + * @param blockReplace Block replace. + * @param blockAgainst Block against. + * @param item Item that was placed. + */ public BlockPlaceEvent(Player player, Block blockPlace, Block blockReplace, Block blockAgainst, Item item) { super(blockPlace); this.blockReplace = blockReplace; diff --git a/src/main/java/cn/nukkit/event/block/BlockRedstoneEvent.java b/src/main/java/cn/nukkit/event/block/BlockRedstoneEvent.java index 38f1d13e7ac..49fdb932249 100644 --- a/src/main/java/cn/nukkit/event/block/BlockRedstoneEvent.java +++ b/src/main/java/cn/nukkit/event/block/BlockRedstoneEvent.java @@ -4,7 +4,8 @@ import cn.nukkit.event.HandlerList; /** - * Created by CreeperFace on 12.5.2017. + * Event for Redstone Block. + * @author CreeperFace on 12.5.2017. */ public class BlockRedstoneEvent extends BlockEvent { @@ -14,9 +15,15 @@ public static HandlerList getHandlers() { return handlers; } - private int oldPower; - private int newPower; + private final int oldPower; + private final int newPower; + /** + * Event called on redstone change. E.g Redstone power. + * @param block Block that is affected. + * @param oldPower Old power of the block. + * @param newPower New power of the block. + */ public BlockRedstoneEvent(Block block, int oldPower, int newPower) { super(block); this.oldPower = oldPower; diff --git a/src/main/java/cn/nukkit/event/block/BlockSpreadEvent.java b/src/main/java/cn/nukkit/event/block/BlockSpreadEvent.java index b687d92e14b..baad5406cf8 100644 --- a/src/main/java/cn/nukkit/event/block/BlockSpreadEvent.java +++ b/src/main/java/cn/nukkit/event/block/BlockSpreadEvent.java @@ -5,8 +5,8 @@ import cn.nukkit.event.HandlerList; /** - * author: MagicDroidX - * Nukkit Project + * Event for Block spread. + * @author MagicDroidX */ public class BlockSpreadEvent extends BlockFormEvent implements Cancellable { @@ -18,6 +18,12 @@ public static HandlerList getHandlers() { private final Block source; + /** + * Event for block spread, such as grass or mycelium. + * @param block Block that is being spread. + * @param source The source block. + * @param newState New state of spread block. + */ public BlockSpreadEvent(Block block, Block source, Block newState) { super(block, newState); this.source = source; diff --git a/src/main/java/cn/nukkit/event/block/BlockUpdateEvent.java b/src/main/java/cn/nukkit/event/block/BlockUpdateEvent.java index 9f2c1066bc2..35127f03d54 100644 --- a/src/main/java/cn/nukkit/event/block/BlockUpdateEvent.java +++ b/src/main/java/cn/nukkit/event/block/BlockUpdateEvent.java @@ -5,8 +5,8 @@ import cn.nukkit.event.HandlerList; /** - * author: MagicDroidX - * Nukkit Project + * Event for Block Update + * @author MagicDroidX */ public class BlockUpdateEvent extends BlockEvent implements Cancellable { @@ -16,8 +16,11 @@ public static HandlerList getHandlers() { return handlers; } + /** + * Event called on a block being updated. + * @param block Block updated. + */ public BlockUpdateEvent(Block block) { super(block); } - } diff --git a/src/main/java/cn/nukkit/event/block/CampfireSmeltEvent.java b/src/main/java/cn/nukkit/event/block/CampfireSmeltEvent.java new file mode 100644 index 00000000000..860a5145358 --- /dev/null +++ b/src/main/java/cn/nukkit/event/block/CampfireSmeltEvent.java @@ -0,0 +1,52 @@ +package cn.nukkit.event.block; + +import cn.nukkit.blockentity.BlockEntityCampfire; +import cn.nukkit.event.Cancellable; +import cn.nukkit.event.HandlerList; +import cn.nukkit.item.Item; + +public class CampfireSmeltEvent extends BlockEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlers() { + return handlers; + } + + private final BlockEntityCampfire campfire; + private final Item source; + private Item result; + private boolean keepItem; + + public CampfireSmeltEvent(BlockEntityCampfire campfire, Item source, Item result) { + super(campfire.getBlock()); + this.source = source.clone(); + this.source.setCount(1); + this.result = result; + this.campfire = campfire; + } + + public BlockEntityCampfire getCampfire() { + return campfire; + } + + public Item getSource() { + return source; + } + + public Item getResult() { + return result; + } + + public void setResult(Item result) { + this.result = result; + } + + public boolean getKeepItem() { + return keepItem; + } + + public void setKeepItem(boolean keepItem) { + this.keepItem = keepItem; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/event/block/ComposterEmptyEvent.java b/src/main/java/cn/nukkit/event/block/ComposterEmptyEvent.java new file mode 100644 index 00000000000..7d070aa6b37 --- /dev/null +++ b/src/main/java/cn/nukkit/event/block/ComposterEmptyEvent.java @@ -0,0 +1,73 @@ +package cn.nukkit.event.block; + +import cn.nukkit.Player; +import cn.nukkit.block.Block; +import cn.nukkit.event.Cancellable; +import cn.nukkit.event.HandlerList; +import cn.nukkit.item.Item; +import cn.nukkit.math.Vector3; + +public class ComposterEmptyEvent extends BlockEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + private final Player player; + private Item drop; + private Item itemUsed; + private int newLevel; + private Vector3 motion; + + public ComposterEmptyEvent(Block block, Player player, Item itemUsed, Item drop, int newLevel) { + super(block); + this.player = player; + this.drop = drop; + this.itemUsed = itemUsed; + this.newLevel = Math.max(0, Math.min(newLevel, 8)); + } + + public Player getPlayer() { + return player; + } + + public Item getDrop() { + return drop.clone(); + } + + public void setDrop(Item drop) { + if (drop == null) { + drop = Item.get(Item.AIR); + } else { + drop = drop.clone(); + } + this.drop = drop; + } + + public Item getItemUsed() { + return itemUsed; + } + + public void setItemUsed(Item itemUsed) { + this.itemUsed = itemUsed; + } + + public int getNewLevel() { + return newLevel; + } + + public void setNewLevel(int newLevel) { + this.newLevel = Math.max(0, Math.min(newLevel, 8)); + } + + public Vector3 getMotion() { + return motion; + } + + public void setMotion(Vector3 motion) { + this.motion = motion; + } + + public static HandlerList getHandlers() { + return handlers; + } + +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/event/block/ComposterFillEvent.java b/src/main/java/cn/nukkit/event/block/ComposterFillEvent.java new file mode 100644 index 00000000000..84e2a13cfee --- /dev/null +++ b/src/main/java/cn/nukkit/event/block/ComposterFillEvent.java @@ -0,0 +1,49 @@ +package cn.nukkit.event.block; + +import cn.nukkit.Player; +import cn.nukkit.block.Block; +import cn.nukkit.event.Cancellable; +import cn.nukkit.event.HandlerList; +import cn.nukkit.item.Item; + +public class ComposterFillEvent extends BlockEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + private final Player player; + private final Item item; + private final int chance; + private boolean success; + + public ComposterFillEvent(Block block, Player player, Item item, int chance, boolean success) { + super(block); + this.player = player; + this.item = item; + this.chance = chance; + this.success = success; + } + + public Player getPlayer() { + return player; + } + + public Item getItem() { + return item; + } + + public int getChance() { + return chance; + } + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + public static HandlerList getHandlers() { + return handlers; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/event/block/DoorToggleEvent.java b/src/main/java/cn/nukkit/event/block/DoorToggleEvent.java index 5f60578b3b7..40ec3019f96 100644 --- a/src/main/java/cn/nukkit/event/block/DoorToggleEvent.java +++ b/src/main/java/cn/nukkit/event/block/DoorToggleEvent.java @@ -6,8 +6,8 @@ import cn.nukkit.event.HandlerList; /** - * Created by Snake1999 on 2016/1/22. - * Package cn.nukkit.event.block in project nukkit. + * Event for door Interactions. + * @author Snake1999 on 2016/1/22. */ public class DoorToggleEvent extends BlockUpdateEvent implements Cancellable { @@ -19,6 +19,11 @@ public static HandlerList getHandlers() { private Player player; + /** + * Event for player door interactions. + * @param block Door block that has been affected by the player. + * @param player Player that is interacting with the door. + */ public DoorToggleEvent(Block block, Player player) { super(block); this.player = player; diff --git a/src/main/java/cn/nukkit/event/block/ItemFrameDropItemEvent.java b/src/main/java/cn/nukkit/event/block/ItemFrameDropItemEvent.java index 4753c478bb7..ca9fb143e0e 100644 --- a/src/main/java/cn/nukkit/event/block/ItemFrameDropItemEvent.java +++ b/src/main/java/cn/nukkit/event/block/ItemFrameDropItemEvent.java @@ -8,7 +8,8 @@ import cn.nukkit.item.Item; /** - * Created by Pub4Game on 03.07.2016. + * Event for Item Frame drops. + * @author Pub4Game on 03.07.2016. */ public class ItemFrameDropItemEvent extends BlockEvent implements Cancellable { @@ -17,6 +18,13 @@ public class ItemFrameDropItemEvent extends BlockEvent implements Cancellable { private final Item item; private final BlockEntityItemFrame itemFrame; + /** + * Event for item being dropped from an item frame + * @param player Player related to the event. + * @param block Block (item frame) affected by change. + * @param itemFrame Item frame block entity. + * @param item Item that is dropped/contained in the item frame. + */ public ItemFrameDropItemEvent(Player player, Block block, BlockEntityItemFrame itemFrame, Item item) { super(block); this.player = player; diff --git a/src/main/java/cn/nukkit/event/block/LeavesDecayEvent.java b/src/main/java/cn/nukkit/event/block/LeavesDecayEvent.java index 19eca2ef8e7..98050b20364 100644 --- a/src/main/java/cn/nukkit/event/block/LeavesDecayEvent.java +++ b/src/main/java/cn/nukkit/event/block/LeavesDecayEvent.java @@ -5,8 +5,8 @@ import cn.nukkit.event.HandlerList; /** - * author: MagicDroidX - * Nukkit Project + * Event for Leaves decay. + * @author MagicDroidX */ public class LeavesDecayEvent extends BlockEvent implements Cancellable { @@ -16,8 +16,11 @@ public static HandlerList getHandlers() { return handlers; } + /** + * Event for leaves decaying / disappearing. + * @param block Leaves block. + */ public LeavesDecayEvent(Block block) { super(block); } - } diff --git a/src/main/java/cn/nukkit/event/block/LiquidFlowEvent.java b/src/main/java/cn/nukkit/event/block/LiquidFlowEvent.java index 16a30c4f52b..d2badb633c3 100644 --- a/src/main/java/cn/nukkit/event/block/LiquidFlowEvent.java +++ b/src/main/java/cn/nukkit/event/block/LiquidFlowEvent.java @@ -5,6 +5,9 @@ import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; +/** + * Event for liquid flow. + */ public class LiquidFlowEvent extends BlockEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); @@ -16,7 +19,12 @@ public static HandlerList getHandlers() { private final Block to; private final BlockLiquid source; private final int newFlowDecay; - + /** + * Event for liquid flowing (water/lava). + * @param to Flowing from one place to another. + * @param source Source of liquid flow. + * @param newFlowDecay Number for when water stops flowing. + */ public LiquidFlowEvent(Block to, BlockLiquid source, int newFlowDecay) { super(to); this.to = to; diff --git a/src/main/java/cn/nukkit/event/block/SignChangeEvent.java b/src/main/java/cn/nukkit/event/block/SignChangeEvent.java index 62727e9eef6..6cf41029006 100644 --- a/src/main/java/cn/nukkit/event/block/SignChangeEvent.java +++ b/src/main/java/cn/nukkit/event/block/SignChangeEvent.java @@ -6,8 +6,8 @@ import cn.nukkit.event.HandlerList; /** - * author: MagicDroidX - * Nukkit Project + * Event for sign text change. + * @author MagicDroidX */ public class SignChangeEvent extends BlockEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); @@ -18,8 +18,14 @@ public static HandlerList getHandlers() { private final Player player; - private String[] lines = new String[4]; + private final String[] lines; + /** + * This event is called when a sign is being edited. + * @param block Sign block. + * @param player Player that edited the sign. + * @param lines Sign text (String[4]) after the edit. + */ public SignChangeEvent(Block block, Player player, String[] lines) { super(block); this.player = player; diff --git a/src/main/java/cn/nukkit/event/block/WaterFrostEvent.java b/src/main/java/cn/nukkit/event/block/WaterFrostEvent.java new file mode 100644 index 00000000000..8e752842e4d --- /dev/null +++ b/src/main/java/cn/nukkit/event/block/WaterFrostEvent.java @@ -0,0 +1,25 @@ +package cn.nukkit.event.block; + +import cn.nukkit.block.Block; +import cn.nukkit.event.Cancellable; +import cn.nukkit.event.HandlerList; + +/** + * Event for water freezing. + */ +public class WaterFrostEvent extends BlockEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlers() { + return handlers; + } + + /** + * Event called on water freezing. + * @param block Block frozen. + */ + public WaterFrostEvent(Block block) { + super(block); + } +} diff --git a/src/main/java/cn/nukkit/event/entity/CreatureSpawnEvent.java b/src/main/java/cn/nukkit/event/entity/CreatureSpawnEvent.java index bcd86b314b5..1c05c4c4444 100644 --- a/src/main/java/cn/nukkit/event/entity/CreatureSpawnEvent.java +++ b/src/main/java/cn/nukkit/event/entity/CreatureSpawnEvent.java @@ -65,7 +65,7 @@ public enum SpawnReason { */ EGG, /** - * When a creature spawns from a Spawner Egg + * When a creature spawns from a spawn egg */ SPAWN_EGG, /** @@ -159,7 +159,7 @@ public enum SpawnReason { */ CUSTOM, /** - * When an entity is missing a SpawnReason + * When SpawnReason is missing */ DEFAULT } diff --git a/src/main/java/cn/nukkit/event/entity/CreeperPowerEvent.java b/src/main/java/cn/nukkit/event/entity/CreeperPowerEvent.java index 3c02167c363..c02b00342c5 100644 --- a/src/main/java/cn/nukkit/event/entity/CreeperPowerEvent.java +++ b/src/main/java/cn/nukkit/event/entity/CreeperPowerEvent.java @@ -6,7 +6,7 @@ import cn.nukkit.event.HandlerList; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class CreeperPowerEvent extends EntityEvent implements Cancellable { diff --git a/src/main/java/cn/nukkit/event/entity/EndermanBlockPickUpEvent.java b/src/main/java/cn/nukkit/event/entity/EndermanBlockPickUpEvent.java new file mode 100644 index 00000000000..37a3ee46cc5 --- /dev/null +++ b/src/main/java/cn/nukkit/event/entity/EndermanBlockPickUpEvent.java @@ -0,0 +1,31 @@ +package cn.nukkit.event.entity; + +import cn.nukkit.block.Block; +import cn.nukkit.entity.mob.EntityEnderman; +import cn.nukkit.event.Cancellable; +import cn.nukkit.event.HandlerList; + +public class EndermanBlockPickUpEvent extends EntityEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlers() { + return handlers; + } + + private final Block block; + + public EndermanBlockPickUpEvent(EntityEnderman entity, Block block) { + this.entity = entity; + this.block = block; + } + + public Block getBlock() { + return this.block; + } + + @Override + public EntityEnderman getEntity() { + return (EntityEnderman) super.getEntity(); + } +} diff --git a/src/main/java/cn/nukkit/event/entity/EntityArmorChangeEvent.java b/src/main/java/cn/nukkit/event/entity/EntityArmorChangeEvent.java index 0983830f022..d2131139c1d 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityArmorChangeEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityArmorChangeEvent.java @@ -6,7 +6,7 @@ import cn.nukkit.item.Item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntityArmorChangeEvent extends EntityEvent implements Cancellable { diff --git a/src/main/java/cn/nukkit/event/entity/EntityBlockChangeEvent.java b/src/main/java/cn/nukkit/event/entity/EntityBlockChangeEvent.java index 9e72203944d..507dfcd8693 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityBlockChangeEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityBlockChangeEvent.java @@ -5,9 +5,6 @@ import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; -/** - * Created on 15-10-26. - */ public class EntityBlockChangeEvent extends EntityEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); @@ -31,5 +28,4 @@ public Block getFrom() { public Block getTo() { return to; } - } diff --git a/src/main/java/cn/nukkit/event/entity/EntityCombustByBlockEvent.java b/src/main/java/cn/nukkit/event/entity/EntityCombustByBlockEvent.java index 0e8d24061d6..903430ff1ab 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityCombustByBlockEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityCombustByBlockEvent.java @@ -4,7 +4,7 @@ import cn.nukkit.entity.Entity; /** - * author: Box + * @author Box * Nukkit Project */ public class EntityCombustByBlockEvent extends EntityCombustEvent { diff --git a/src/main/java/cn/nukkit/event/entity/EntityCombustByEntityEvent.java b/src/main/java/cn/nukkit/event/entity/EntityCombustByEntityEvent.java index 6b81b12eceb..6c4477b5bc2 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityCombustByEntityEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityCombustByEntityEvent.java @@ -3,7 +3,7 @@ import cn.nukkit.entity.Entity; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntityCombustByEntityEvent extends EntityCombustEvent { diff --git a/src/main/java/cn/nukkit/event/entity/EntityCombustEvent.java b/src/main/java/cn/nukkit/event/entity/EntityCombustEvent.java index 129962a61ce..c125568ddc5 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityCombustEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityCombustEvent.java @@ -5,7 +5,7 @@ import cn.nukkit.event.HandlerList; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntityCombustEvent extends EntityEvent implements Cancellable { diff --git a/src/main/java/cn/nukkit/event/entity/EntityDamageBlockedEvent.java b/src/main/java/cn/nukkit/event/entity/EntityDamageBlockedEvent.java new file mode 100644 index 00000000000..a40c91cf65e --- /dev/null +++ b/src/main/java/cn/nukkit/event/entity/EntityDamageBlockedEvent.java @@ -0,0 +1,56 @@ +package cn.nukkit.event.entity; + +import cn.nukkit.entity.Entity; +import cn.nukkit.event.Cancellable; +import cn.nukkit.event.HandlerList; + +public class EntityDamageBlockedEvent extends EntityEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlers() { + return handlers; + } + + private final EntityDamageEvent damage; + private boolean knockBackAttacker; + private boolean animation; + + public EntityDamageBlockedEvent(Entity entity, EntityDamageEvent damage, boolean knockBack, boolean animation) { + this.entity = entity; + this.damage = damage; + this.knockBackAttacker = knockBack; + this.animation = animation; + } + + public EntityDamageEvent.DamageCause getCause() { + return damage.getCause(); + } + + public Entity getAttacker() { + if (damage instanceof EntityDamageByEntityEvent) { + return ((EntityDamageByEntityEvent) damage).getDamager(); + } + return damage.getEntity(); + } + + public EntityDamageEvent getDamage() { + return damage; + } + + public boolean getKnockBackAttacker() { + return knockBackAttacker; + } + + public boolean getAnimation() { + return animation; + } + + public void setKnockBackAttacker(boolean val) { + knockBackAttacker = val; + } + + public void setAnimation(boolean val) { + animation = val; + } +} diff --git a/src/main/java/cn/nukkit/event/entity/EntityDamageByBlockEvent.java b/src/main/java/cn/nukkit/event/entity/EntityDamageByBlockEvent.java index 740869dd951..a193f71d87e 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityDamageByBlockEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityDamageByBlockEvent.java @@ -4,7 +4,7 @@ import cn.nukkit.entity.Entity; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntityDamageByBlockEvent extends EntityDamageEvent { @@ -19,5 +19,4 @@ public EntityDamageByBlockEvent(Block damager, Entity entity, DamageCause cause, public Block getDamager() { return damager; } - } diff --git a/src/main/java/cn/nukkit/event/entity/EntityDamageByChildEntityEvent.java b/src/main/java/cn/nukkit/event/entity/EntityDamageByChildEntityEvent.java index b4bff9357d8..d3c471a6f6c 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityDamageByChildEntityEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityDamageByChildEntityEvent.java @@ -3,7 +3,7 @@ import cn.nukkit.entity.Entity; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntityDamageByChildEntityEvent extends EntityDamageByEntityEvent { @@ -11,7 +11,11 @@ public class EntityDamageByChildEntityEvent extends EntityDamageByEntityEvent { private final Entity childEntity; public EntityDamageByChildEntityEvent(Entity damager, Entity childEntity, Entity entity, DamageCause cause, float damage) { - super(damager, entity, cause, damage); + this(damager, childEntity, entity, cause, damage, 0.3f); + } + + public EntityDamageByChildEntityEvent(Entity damager, Entity childEntity, Entity entity, DamageCause cause, float damage, float knockBack) { + super(damager, entity, cause, damage, knockBack); this.childEntity = childEntity; } diff --git a/src/main/java/cn/nukkit/event/entity/EntityDamageByEntityEvent.java b/src/main/java/cn/nukkit/event/entity/EntityDamageByEntityEvent.java index 402ec40f1e9..2f09d063a03 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityDamageByEntityEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityDamageByEntityEvent.java @@ -7,7 +7,7 @@ import java.util.Map; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntityDamageByEntityEvent extends EntityDamageEvent { diff --git a/src/main/java/cn/nukkit/event/entity/EntityDamageEvent.java b/src/main/java/cn/nukkit/event/entity/EntityDamageEvent.java index 5f640894c85..473da0bff79 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityDamageEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityDamageEvent.java @@ -3,18 +3,22 @@ import cn.nukkit.entity.Entity; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; +import cn.nukkit.item.Item; import cn.nukkit.potion.Effect; import cn.nukkit.utils.EventException; import com.google.common.collect.ImmutableMap; +import lombok.Getter; +import lombok.Setter; import java.util.EnumMap; import java.util.Map; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntityDamageEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { @@ -27,19 +31,18 @@ public static HandlerList getHandlers() { private final Map modifiers; private final Map originals; + @Getter + @Setter + private Item weapon; + public EntityDamageEvent(Entity entity, DamageCause cause, float damage) { - this(entity, cause, new EnumMap(DamageModifier.class) { - { - put(DamageModifier.BASE, damage); - } - }); + this(entity, cause, new DamageModifierFloatEnumMap(damage)); } public EntityDamageEvent(Entity entity, DamageCause cause, Map modifiers) { this.entity = entity; this.cause = cause; this.modifiers = new EnumMap<>(modifiers); - this.originals = ImmutableMap.copyOf(this.modifiers); if (!this.modifiers.containsKey(DamageModifier.BASE)) { @@ -99,13 +102,13 @@ public float getFinalDamage() { } } - return damage; + return Math.max(damage, 0); } - + public int getAttackCooldown() { return this.attackCooldown; } - + public void setAttackCooldown(int attackCooldown) { this.attackCooldown = attackCooldown; } @@ -151,9 +154,13 @@ public enum DamageModifier { */ ABSORPTION, /** - * Damage reduction caused by the armor enchantments worn. + * Damage reduction caused by armor's enchantments + */ + ARMOR_ENCHANTMENTS, + /** + * Additional damage caused by critical hit */ - ARMOR_ENCHANTMENTS + CRITICAL } public enum DamageCause { @@ -189,6 +196,10 @@ public enum DamageCause { * Damage caused by standing in lava */ LAVA, + /** + * Damage caused by standing on magma block + */ + MAGMA, /** * Damage caused by running out of air underwater */ @@ -224,6 +235,18 @@ public enum DamageCause { /** * Damage caused by hunger */ - HUNGER + HUNGER, + /** + * Damage caused by thorns enchantment + */ + THORNS + } + + private static class DamageModifierFloatEnumMap extends EnumMap { + + public DamageModifierFloatEnumMap(float damage) { + super(DamageModifier.class); + put(DamageModifier.BASE, damage); + } } } diff --git a/src/main/java/cn/nukkit/event/entity/EntityDeathEvent.java b/src/main/java/cn/nukkit/event/entity/EntityDeathEvent.java index 80a1a0e5c18..6085eac7d4f 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityDeathEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityDeathEvent.java @@ -5,7 +5,7 @@ import cn.nukkit.item.Item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntityDeathEvent extends EntityEvent { diff --git a/src/main/java/cn/nukkit/event/entity/EntityDespawnEvent.java b/src/main/java/cn/nukkit/event/entity/EntityDespawnEvent.java index 71193b61e7c..3f1e49c9502 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityDespawnEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityDespawnEvent.java @@ -4,12 +4,13 @@ import cn.nukkit.entity.EntityCreature; import cn.nukkit.entity.EntityHuman; import cn.nukkit.entity.item.EntityItem; +import cn.nukkit.entity.item.EntityVehicle; import cn.nukkit.entity.projectile.EntityProjectile; import cn.nukkit.event.HandlerList; import cn.nukkit.level.Position; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntityDespawnEvent extends EntityEvent { @@ -21,7 +22,7 @@ public static HandlerList getHandlers() { private final int entityType; - public EntityDespawnEvent(cn.nukkit.entity.Entity entity) { + public EntityDespawnEvent(Entity entity) { this.entity = entity; this.entityType = entity.getNetworkId(); } @@ -47,11 +48,10 @@ public boolean isProjectile() { } public boolean isVehicle() { - return this.entity instanceof Entity; + return this.entity instanceof EntityVehicle; } public boolean isItem() { return this.entity instanceof EntityItem; } - } diff --git a/src/main/java/cn/nukkit/event/entity/EntityEvent.java b/src/main/java/cn/nukkit/event/entity/EntityEvent.java index da93a9a87e2..c96a8c15bd9 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityEvent.java @@ -4,7 +4,7 @@ import cn.nukkit.event.Event; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class EntityEvent extends Event { diff --git a/src/main/java/cn/nukkit/event/entity/EntityExplodeEvent.java b/src/main/java/cn/nukkit/event/entity/EntityExplodeEvent.java index cbc96f9b3a9..cc91fae0ddc 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityExplodeEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityExplodeEvent.java @@ -9,7 +9,7 @@ import java.util.List; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class EntityExplodeEvent extends EntityEvent implements Cancellable { @@ -50,5 +50,4 @@ public double getYield() { public void setYield(double yield) { this.yield = yield; } - } diff --git a/src/main/java/cn/nukkit/event/entity/EntityExplosionPrimeEvent.java b/src/main/java/cn/nukkit/event/entity/EntityExplosionPrimeEvent.java index 97d6c901298..80aea0948ff 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityExplosionPrimeEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityExplosionPrimeEvent.java @@ -4,9 +4,6 @@ import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; -/** - * Created on 15-10-27. - */ public class EntityExplosionPrimeEvent extends EntityEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); @@ -39,5 +36,4 @@ public boolean isBlockBreaking() { public void setBlockBreaking(boolean blockBreaking) { this.blockBreaking = blockBreaking; } - } diff --git a/src/main/java/cn/nukkit/event/entity/EntityInteractEvent.java b/src/main/java/cn/nukkit/event/entity/EntityInteractEvent.java index 5d198f2e9c2..de9c82ec9d6 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityInteractEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityInteractEvent.java @@ -16,7 +16,7 @@ public static HandlerList getHandlers() { return handlers; } - private Block block; + private final Block block; public EntityInteractEvent(Entity entity, Block block) { this.entity = entity; diff --git a/src/main/java/cn/nukkit/event/entity/EntityInventoryChangeEvent.java b/src/main/java/cn/nukkit/event/entity/EntityInventoryChangeEvent.java index aca7a6f4ad0..a90a6ed848c 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityInventoryChangeEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityInventoryChangeEvent.java @@ -6,7 +6,7 @@ import cn.nukkit.item.Item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntityInventoryChangeEvent extends EntityEvent implements Cancellable { diff --git a/src/main/java/cn/nukkit/event/entity/EntityLevelChangeEvent.java b/src/main/java/cn/nukkit/event/entity/EntityLevelChangeEvent.java index 9f40a740b45..fbbfb929048 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityLevelChangeEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityLevelChangeEvent.java @@ -6,7 +6,7 @@ import cn.nukkit.level.Level; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntityLevelChangeEvent extends EntityEvent implements Cancellable { diff --git a/src/main/java/cn/nukkit/event/entity/EntityMotionEvent.java b/src/main/java/cn/nukkit/event/entity/EntityMotionEvent.java index 82a7cd9fbc3..857da24840b 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityMotionEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityMotionEvent.java @@ -6,7 +6,7 @@ import cn.nukkit.math.Vector3; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntityMotionEvent extends EntityEvent implements Cancellable { diff --git a/src/main/java/cn/nukkit/event/entity/EntityRegainHealthEvent.java b/src/main/java/cn/nukkit/event/entity/EntityRegainHealthEvent.java index 265ec089713..bd7c52e71eb 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityRegainHealthEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityRegainHealthEvent.java @@ -5,7 +5,7 @@ import cn.nukkit.event.HandlerList; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntityRegainHealthEvent extends EntityEvent implements Cancellable { diff --git a/src/main/java/cn/nukkit/event/entity/EntityShootBowEvent.java b/src/main/java/cn/nukkit/event/entity/EntityShootBowEvent.java index 8992f9f26a7..1d6a9a82514 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityShootBowEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityShootBowEvent.java @@ -8,10 +8,11 @@ import cn.nukkit.item.Item; /** - * author: Box + * @author Box * Nukkit Project */ public class EntityShootBowEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { @@ -48,8 +49,7 @@ public EntityProjectile getProjectile() { public void setProjectile(Entity projectile) { if (projectile != this.projectile) { - if (this.projectile.getViewers().size() == 0) { - this.projectile.kill(); + if (this.projectile.getViewers().isEmpty()) { this.projectile.close(); } this.projectile = (EntityProjectile) projectile; diff --git a/src/main/java/cn/nukkit/event/entity/EntitySpawnEvent.java b/src/main/java/cn/nukkit/event/entity/EntitySpawnEvent.java index c922109dc44..123be58a667 100644 --- a/src/main/java/cn/nukkit/event/entity/EntitySpawnEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntitySpawnEvent.java @@ -4,12 +4,13 @@ import cn.nukkit.entity.EntityCreature; import cn.nukkit.entity.EntityHuman; import cn.nukkit.entity.item.EntityItem; +import cn.nukkit.entity.item.EntityVehicle; import cn.nukkit.entity.projectile.EntityProjectile; import cn.nukkit.event.HandlerList; import cn.nukkit.level.Position; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntitySpawnEvent extends EntityEvent { @@ -21,7 +22,7 @@ public static HandlerList getHandlers() { private final int entityType; - public EntitySpawnEvent(cn.nukkit.entity.Entity entity) { + public EntitySpawnEvent(Entity entity) { this.entity = entity; this.entityType = entity.getNetworkId(); } @@ -47,11 +48,10 @@ public boolean isProjectile() { } public boolean isVehicle() { - return this.entity instanceof Entity; + return this.entity instanceof EntityVehicle; } public boolean isItem() { return this.entity instanceof EntityItem; } - } diff --git a/src/main/java/cn/nukkit/event/entity/EntityTeleportEvent.java b/src/main/java/cn/nukkit/event/entity/EntityTeleportEvent.java index 60c203628e8..3fae1c86d8b 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityTeleportEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityTeleportEvent.java @@ -7,10 +7,11 @@ import cn.nukkit.level.Location; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntityTeleportEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { diff --git a/src/main/java/cn/nukkit/event/entity/EntityVehicleEnterEvent.java b/src/main/java/cn/nukkit/event/entity/EntityVehicleEnterEvent.java index c1edf7072b5..247289b068c 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityVehicleEnterEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityVehicleEnterEvent.java @@ -1,6 +1,7 @@ package cn.nukkit.event.entity; import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityVehicle; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; @@ -12,15 +13,14 @@ public static HandlerList getHandlers() { return handlers; } - private final Entity vehicle; + private final EntityVehicle vehicle; - public EntityVehicleEnterEvent(Entity entity, Entity vehicle) { + public EntityVehicleEnterEvent(Entity entity, EntityVehicle vehicle) { this.entity = entity; this.vehicle = vehicle; } - public Entity getVehicle() { + public EntityVehicle getVehicle() { return vehicle; } - } diff --git a/src/main/java/cn/nukkit/event/entity/EntityVehicleExitEvent.java b/src/main/java/cn/nukkit/event/entity/EntityVehicleExitEvent.java index cbee54dfa52..68cf50ac917 100644 --- a/src/main/java/cn/nukkit/event/entity/EntityVehicleExitEvent.java +++ b/src/main/java/cn/nukkit/event/entity/EntityVehicleExitEvent.java @@ -1,6 +1,7 @@ package cn.nukkit.event.entity; import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityVehicle; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; @@ -12,15 +13,14 @@ public static HandlerList getHandlers() { return handlers; } - private final Entity vehicle; + private final EntityVehicle vehicle; - public EntityVehicleExitEvent(Entity entity, Entity vehicle) { + public EntityVehicleExitEvent(Entity entity, EntityVehicle vehicle) { this.entity = entity; this.vehicle = vehicle; } - public Entity getVehicle() { + public EntityVehicle getVehicle() { return vehicle; } - } diff --git a/src/main/java/cn/nukkit/event/entity/ExplosionPrimeEvent.java b/src/main/java/cn/nukkit/event/entity/ExplosionPrimeEvent.java index cd8d79690da..6fb1e90d8f0 100644 --- a/src/main/java/cn/nukkit/event/entity/ExplosionPrimeEvent.java +++ b/src/main/java/cn/nukkit/event/entity/ExplosionPrimeEvent.java @@ -5,12 +5,13 @@ import cn.nukkit.event.HandlerList; /** - * author: Box + * @author Box * Nukkit Project - *

+ * * Called when a entity decides to explode */ public class ExplosionPrimeEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { diff --git a/src/main/java/cn/nukkit/event/entity/ItemDespawnEvent.java b/src/main/java/cn/nukkit/event/entity/ItemDespawnEvent.java index d449c3c5fd5..b871ff990e0 100644 --- a/src/main/java/cn/nukkit/event/entity/ItemDespawnEvent.java +++ b/src/main/java/cn/nukkit/event/entity/ItemDespawnEvent.java @@ -5,7 +5,7 @@ import cn.nukkit.event.HandlerList; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemDespawnEvent extends EntityEvent implements Cancellable { diff --git a/src/main/java/cn/nukkit/event/entity/ItemSpawnEvent.java b/src/main/java/cn/nukkit/event/entity/ItemSpawnEvent.java index 9816d555836..3d454745818 100644 --- a/src/main/java/cn/nukkit/event/entity/ItemSpawnEvent.java +++ b/src/main/java/cn/nukkit/event/entity/ItemSpawnEvent.java @@ -4,7 +4,7 @@ import cn.nukkit.event.HandlerList; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemSpawnEvent extends EntityEvent { diff --git a/src/main/java/cn/nukkit/event/entity/ProjectileHitEvent.java b/src/main/java/cn/nukkit/event/entity/ProjectileHitEvent.java index c751fa8c6e8..9e4dbdb621e 100644 --- a/src/main/java/cn/nukkit/event/entity/ProjectileHitEvent.java +++ b/src/main/java/cn/nukkit/event/entity/ProjectileHitEvent.java @@ -6,7 +6,7 @@ import cn.nukkit.level.MovingObjectPosition; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ProjectileHitEvent extends EntityEvent implements Cancellable { @@ -34,5 +34,4 @@ public MovingObjectPosition getMovingObjectPosition() { public void setMovingObjectPosition(MovingObjectPosition movingObjectPosition) { this.movingObjectPosition = movingObjectPosition; } - } diff --git a/src/main/java/cn/nukkit/event/inventory/CraftItemEvent.java b/src/main/java/cn/nukkit/event/inventory/CraftItemEvent.java index 855b83c4a01..f63a82beff8 100644 --- a/src/main/java/cn/nukkit/event/inventory/CraftItemEvent.java +++ b/src/main/java/cn/nukkit/event/inventory/CraftItemEvent.java @@ -9,7 +9,7 @@ import cn.nukkit.item.Item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class CraftItemEvent extends Event implements Cancellable { @@ -20,7 +20,7 @@ public static HandlerList getHandlers() { return handlers; } - private Item[] input = new Item[0]; + private final Item[] input; private final Recipe recipe; @@ -30,7 +30,6 @@ public static HandlerList getHandlers() { public CraftItemEvent(CraftingTransaction transaction) { this.transaction = transaction; - this.player = transaction.getSource(); this.input = transaction.getInputList().toArray(new Item[0]); this.recipe = transaction.getRecipe(); @@ -57,4 +56,4 @@ public Recipe getRecipe() { public Player getPlayer() { return this.player; } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/event/inventory/EnchantItemEvent.java b/src/main/java/cn/nukkit/event/inventory/EnchantItemEvent.java index f67d3abbcc2..004e20ae8ac 100644 --- a/src/main/java/cn/nukkit/event/inventory/EnchantItemEvent.java +++ b/src/main/java/cn/nukkit/event/inventory/EnchantItemEvent.java @@ -11,6 +11,7 @@ @Getter @Setter public class EnchantItemEvent extends InventoryEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { diff --git a/src/main/java/cn/nukkit/event/inventory/FurnaceBurnEvent.java b/src/main/java/cn/nukkit/event/inventory/FurnaceBurnEvent.java index 001455b54e7..cae4831281c 100644 --- a/src/main/java/cn/nukkit/event/inventory/FurnaceBurnEvent.java +++ b/src/main/java/cn/nukkit/event/inventory/FurnaceBurnEvent.java @@ -7,7 +7,7 @@ import cn.nukkit.item.Item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class FurnaceBurnEvent extends BlockEvent implements Cancellable { diff --git a/src/main/java/cn/nukkit/event/inventory/FurnaceSmeltEvent.java b/src/main/java/cn/nukkit/event/inventory/FurnaceSmeltEvent.java index a612d93a3ce..19623f44ee2 100644 --- a/src/main/java/cn/nukkit/event/inventory/FurnaceSmeltEvent.java +++ b/src/main/java/cn/nukkit/event/inventory/FurnaceSmeltEvent.java @@ -7,7 +7,7 @@ import cn.nukkit.item.Item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class FurnaceSmeltEvent extends BlockEvent implements Cancellable { diff --git a/src/main/java/cn/nukkit/event/inventory/InventoryClickEvent.java b/src/main/java/cn/nukkit/event/inventory/InventoryClickEvent.java index 91eb7e8270a..91f97312a81 100644 --- a/src/main/java/cn/nukkit/event/inventory/InventoryClickEvent.java +++ b/src/main/java/cn/nukkit/event/inventory/InventoryClickEvent.java @@ -7,7 +7,7 @@ import cn.nukkit.item.Item; /** - * author: boybook + * @author boybook * Nukkit Project */ public class InventoryClickEvent extends InventoryEvent implements Cancellable { diff --git a/src/main/java/cn/nukkit/event/inventory/InventoryCloseEvent.java b/src/main/java/cn/nukkit/event/inventory/InventoryCloseEvent.java index a9202cfde0f..9b8de2211f1 100644 --- a/src/main/java/cn/nukkit/event/inventory/InventoryCloseEvent.java +++ b/src/main/java/cn/nukkit/event/inventory/InventoryCloseEvent.java @@ -5,7 +5,7 @@ import cn.nukkit.inventory.Inventory; /** - * author: Box + * @author Box * Nukkit Project */ public class InventoryCloseEvent extends InventoryEvent { diff --git a/src/main/java/cn/nukkit/event/inventory/InventoryEvent.java b/src/main/java/cn/nukkit/event/inventory/InventoryEvent.java index b01c333f94d..d11adb185a6 100644 --- a/src/main/java/cn/nukkit/event/inventory/InventoryEvent.java +++ b/src/main/java/cn/nukkit/event/inventory/InventoryEvent.java @@ -5,7 +5,7 @@ import cn.nukkit.inventory.Inventory; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class InventoryEvent extends Event { @@ -23,5 +23,4 @@ public Inventory getInventory() { public Player[] getViewers() { return this.inventory.getViewers().toArray(new Player[0]); } - } diff --git a/src/main/java/cn/nukkit/event/inventory/InventoryOpenEvent.java b/src/main/java/cn/nukkit/event/inventory/InventoryOpenEvent.java index 2838d6844d3..ce78783f626 100644 --- a/src/main/java/cn/nukkit/event/inventory/InventoryOpenEvent.java +++ b/src/main/java/cn/nukkit/event/inventory/InventoryOpenEvent.java @@ -6,7 +6,7 @@ import cn.nukkit.inventory.Inventory; /** - * author: Box + * @author Box * Nukkit Project */ public class InventoryOpenEvent extends InventoryEvent implements Cancellable { diff --git a/src/main/java/cn/nukkit/event/inventory/InventoryPickupArrowEvent.java b/src/main/java/cn/nukkit/event/inventory/InventoryPickupArrowEvent.java index 4c8604e8b91..585c48d363b 100644 --- a/src/main/java/cn/nukkit/event/inventory/InventoryPickupArrowEvent.java +++ b/src/main/java/cn/nukkit/event/inventory/InventoryPickupArrowEvent.java @@ -6,7 +6,7 @@ import cn.nukkit.inventory.Inventory; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class InventoryPickupArrowEvent extends InventoryEvent implements Cancellable { diff --git a/src/main/java/cn/nukkit/event/inventory/InventoryPickupItemEvent.java b/src/main/java/cn/nukkit/event/inventory/InventoryPickupItemEvent.java index 3200d6efa4b..b064b09d75e 100644 --- a/src/main/java/cn/nukkit/event/inventory/InventoryPickupItemEvent.java +++ b/src/main/java/cn/nukkit/event/inventory/InventoryPickupItemEvent.java @@ -6,7 +6,7 @@ import cn.nukkit.inventory.Inventory; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class InventoryPickupItemEvent extends InventoryEvent implements Cancellable { diff --git a/src/main/java/cn/nukkit/event/inventory/InventoryTransactionEvent.java b/src/main/java/cn/nukkit/event/inventory/InventoryTransactionEvent.java index c416b726e63..c0e6ce46dd0 100644 --- a/src/main/java/cn/nukkit/event/inventory/InventoryTransactionEvent.java +++ b/src/main/java/cn/nukkit/event/inventory/InventoryTransactionEvent.java @@ -6,7 +6,7 @@ import cn.nukkit.inventory.transaction.InventoryTransaction; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class InventoryTransactionEvent extends Event implements Cancellable { diff --git a/src/main/java/cn/nukkit/event/inventory/LoomItemEvent.java b/src/main/java/cn/nukkit/event/inventory/LoomItemEvent.java new file mode 100644 index 00000000000..fd91c7607a7 --- /dev/null +++ b/src/main/java/cn/nukkit/event/inventory/LoomItemEvent.java @@ -0,0 +1,33 @@ +package cn.nukkit.event.inventory; + +import cn.nukkit.Player; +import cn.nukkit.event.Cancellable; +import cn.nukkit.event.HandlerList; +import cn.nukkit.inventory.LoomInventory; +import cn.nukkit.item.Item; + +public class LoomItemEvent extends InventoryEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlers() { + return handlers; + } + + private final Item newItem; + private final Player player; + + public LoomItemEvent(LoomInventory inventory, Item newItem, Player player) { + super(inventory); + this.newItem = newItem; + this.player = player; + } + + public Item getNewItem() { + return this.newItem; + } + + public Player getPlayer() { + return this.player; + } +} diff --git a/src/main/java/cn/nukkit/event/inventory/RepairItemEvent.java b/src/main/java/cn/nukkit/event/inventory/RepairItemEvent.java index dd7acdc3df3..e2917bf2ff3 100644 --- a/src/main/java/cn/nukkit/event/inventory/RepairItemEvent.java +++ b/src/main/java/cn/nukkit/event/inventory/RepairItemEvent.java @@ -14,11 +14,11 @@ public static HandlerList getHandlers() { return handlers; } - private Item oldItem; - private Item newItem; - private Item materialItem; + private final Item oldItem; + private final Item newItem; + private final Item materialItem; private int cost; - private Player player; + private final Player player; public RepairItemEvent(AnvilInventory inventory, Item oldItem, Item newItem, Item materialItem, int cost, Player player) { super(inventory); diff --git a/src/main/java/cn/nukkit/event/inventory/SmithItemEvent.java b/src/main/java/cn/nukkit/event/inventory/SmithItemEvent.java new file mode 100644 index 00000000000..40fcda71576 --- /dev/null +++ b/src/main/java/cn/nukkit/event/inventory/SmithItemEvent.java @@ -0,0 +1,45 @@ +package cn.nukkit.event.inventory; + +import cn.nukkit.Player; +import cn.nukkit.event.Cancellable; +import cn.nukkit.event.HandlerList; +import cn.nukkit.inventory.SmithingInventory; +import cn.nukkit.item.Item; + +public class SmithItemEvent extends InventoryEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlers() { + return handlers; + } + + private final Item oldItem; + private final Item newItem; + private final Item materialItem; + private final Player player; + + public SmithItemEvent(SmithingInventory inventory, Item oldItem, Item newItem, Item materialItem, Player player) { + super(inventory); + this.oldItem = oldItem; + this.newItem = newItem; + this.materialItem = materialItem; + this.player = player; + } + + public Item getOldItem() { + return this.oldItem; + } + + public Item getNewItem() { + return this.newItem; + } + + public Item getMaterialItem() { + return this.materialItem; + } + + public Player getPlayer() { + return this.player; + } +} diff --git a/src/main/java/cn/nukkit/event/level/ChunkEvent.java b/src/main/java/cn/nukkit/event/level/ChunkEvent.java index 12ee9a1c758..7b932a35d72 100644 --- a/src/main/java/cn/nukkit/event/level/ChunkEvent.java +++ b/src/main/java/cn/nukkit/event/level/ChunkEvent.java @@ -3,7 +3,7 @@ import cn.nukkit.level.format.FullChunk; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class ChunkEvent extends LevelEvent { diff --git a/src/main/java/cn/nukkit/event/level/ChunkLoadEvent.java b/src/main/java/cn/nukkit/event/level/ChunkLoadEvent.java index f922e0b7427..23520f4ed19 100644 --- a/src/main/java/cn/nukkit/event/level/ChunkLoadEvent.java +++ b/src/main/java/cn/nukkit/event/level/ChunkLoadEvent.java @@ -4,7 +4,7 @@ import cn.nukkit.level.format.FullChunk; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ChunkLoadEvent extends ChunkEvent { diff --git a/src/main/java/cn/nukkit/event/level/ChunkPopulateEvent.java b/src/main/java/cn/nukkit/event/level/ChunkPopulateEvent.java index b25b145c366..4694bca35a1 100644 --- a/src/main/java/cn/nukkit/event/level/ChunkPopulateEvent.java +++ b/src/main/java/cn/nukkit/event/level/ChunkPopulateEvent.java @@ -4,7 +4,7 @@ import cn.nukkit.level.format.FullChunk; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ChunkPopulateEvent extends ChunkEvent { @@ -18,5 +18,4 @@ public static HandlerList getHandlers() { public ChunkPopulateEvent(FullChunk chunk) { super(chunk); } - } \ No newline at end of file diff --git a/src/main/java/cn/nukkit/event/level/ChunkUnloadEvent.java b/src/main/java/cn/nukkit/event/level/ChunkUnloadEvent.java index 3621f519bf2..b557169cef2 100644 --- a/src/main/java/cn/nukkit/event/level/ChunkUnloadEvent.java +++ b/src/main/java/cn/nukkit/event/level/ChunkUnloadEvent.java @@ -5,7 +5,7 @@ import cn.nukkit.level.format.FullChunk; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ChunkUnloadEvent extends ChunkEvent implements Cancellable { @@ -19,5 +19,4 @@ public static HandlerList getHandlers() { public ChunkUnloadEvent(FullChunk chunk) { super(chunk); } - } \ No newline at end of file diff --git a/src/main/java/cn/nukkit/event/level/LevelEvent.java b/src/main/java/cn/nukkit/event/level/LevelEvent.java index 766e01e9731..9fcc470765e 100644 --- a/src/main/java/cn/nukkit/event/level/LevelEvent.java +++ b/src/main/java/cn/nukkit/event/level/LevelEvent.java @@ -4,7 +4,7 @@ import cn.nukkit.level.Level; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class LevelEvent extends Event { diff --git a/src/main/java/cn/nukkit/event/level/LevelInitEvent.java b/src/main/java/cn/nukkit/event/level/LevelInitEvent.java index 5bfdbb7ec8b..03d76e5d796 100644 --- a/src/main/java/cn/nukkit/event/level/LevelInitEvent.java +++ b/src/main/java/cn/nukkit/event/level/LevelInitEvent.java @@ -4,7 +4,7 @@ import cn.nukkit.level.Level; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class LevelInitEvent extends LevelEvent { @@ -18,5 +18,4 @@ public static HandlerList getHandlers() { public LevelInitEvent(Level level) { super(level); } - } diff --git a/src/main/java/cn/nukkit/event/level/LevelLoadEvent.java b/src/main/java/cn/nukkit/event/level/LevelLoadEvent.java index e78f025ae0f..3a54164f08d 100644 --- a/src/main/java/cn/nukkit/event/level/LevelLoadEvent.java +++ b/src/main/java/cn/nukkit/event/level/LevelLoadEvent.java @@ -4,7 +4,7 @@ import cn.nukkit.level.Level; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class LevelLoadEvent extends LevelEvent { @@ -18,5 +18,4 @@ public static HandlerList getHandlers() { public LevelLoadEvent(Level level) { super(level); } - } diff --git a/src/main/java/cn/nukkit/event/level/LevelSaveEvent.java b/src/main/java/cn/nukkit/event/level/LevelSaveEvent.java index 6b6e1d6a53d..4e18629b2c7 100644 --- a/src/main/java/cn/nukkit/event/level/LevelSaveEvent.java +++ b/src/main/java/cn/nukkit/event/level/LevelSaveEvent.java @@ -4,7 +4,7 @@ import cn.nukkit.level.Level; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class LevelSaveEvent extends LevelEvent { @@ -18,5 +18,4 @@ public static HandlerList getHandlers() { public LevelSaveEvent(Level level) { super(level); } - } diff --git a/src/main/java/cn/nukkit/event/level/LevelUnloadEvent.java b/src/main/java/cn/nukkit/event/level/LevelUnloadEvent.java index ed3852470ce..8dd81f9c31d 100644 --- a/src/main/java/cn/nukkit/event/level/LevelUnloadEvent.java +++ b/src/main/java/cn/nukkit/event/level/LevelUnloadEvent.java @@ -5,7 +5,7 @@ import cn.nukkit.level.Level; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class LevelUnloadEvent extends LevelEvent implements Cancellable { @@ -19,5 +19,4 @@ public static HandlerList getHandlers() { public LevelUnloadEvent(Level level) { super(level); } - } diff --git a/src/main/java/cn/nukkit/event/level/NetherPortalSpawnEvent.java b/src/main/java/cn/nukkit/event/level/NetherPortalSpawnEvent.java new file mode 100644 index 00000000000..d3326332a91 --- /dev/null +++ b/src/main/java/cn/nukkit/event/level/NetherPortalSpawnEvent.java @@ -0,0 +1,26 @@ +package cn.nukkit.event.level; + +import cn.nukkit.event.Cancellable; +import cn.nukkit.event.HandlerList; +import cn.nukkit.level.Position; + +public class NetherPortalSpawnEvent extends LevelEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlers() { + return handlers; + } + + private final Position portalPosition; + + public NetherPortalSpawnEvent(Position portalPosition) { + super(portalPosition.getLevel()); + + this.portalPosition = portalPosition.clone(); + } + + public Position getPortalPosition() { + return this.portalPosition; + } +} diff --git a/src/main/java/cn/nukkit/event/level/SpawnChangeEvent.java b/src/main/java/cn/nukkit/event/level/SpawnChangeEvent.java index c5c4303a253..78781f75ee3 100644 --- a/src/main/java/cn/nukkit/event/level/SpawnChangeEvent.java +++ b/src/main/java/cn/nukkit/event/level/SpawnChangeEvent.java @@ -5,7 +5,7 @@ import cn.nukkit.level.Position; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class SpawnChangeEvent extends LevelEvent { diff --git a/src/main/java/cn/nukkit/event/level/StructureGrowEvent.java b/src/main/java/cn/nukkit/event/level/StructureGrowEvent.java index 1bea3eeb218..ed7d87fde28 100644 --- a/src/main/java/cn/nukkit/event/level/StructureGrowEvent.java +++ b/src/main/java/cn/nukkit/event/level/StructureGrowEvent.java @@ -37,8 +37,8 @@ public List getBlockList() { public void setBlockList(List blocks) { this.blocks.clear(); - if(blocks != null) + if (blocks != null) { this.blocks.addAll(blocks); + } } - } diff --git a/src/main/java/cn/nukkit/event/level/ThunderChangeEvent.java b/src/main/java/cn/nukkit/event/level/ThunderChangeEvent.java index 93e4d0a86ef..36497d120ae 100644 --- a/src/main/java/cn/nukkit/event/level/ThunderChangeEvent.java +++ b/src/main/java/cn/nukkit/event/level/ThunderChangeEvent.java @@ -5,7 +5,7 @@ import cn.nukkit.level.Level; /** - * author: funcraft + * @author funcraft * Nukkit Project */ public class ThunderChangeEvent extends WeatherEvent implements Cancellable { @@ -31,5 +31,4 @@ public ThunderChangeEvent(Level level, boolean to) { public boolean toThunderState() { return to; } - } diff --git a/src/main/java/cn/nukkit/event/level/WeatherChangeEvent.java b/src/main/java/cn/nukkit/event/level/WeatherChangeEvent.java index d0e1c2157bb..7d9e80a7bb8 100644 --- a/src/main/java/cn/nukkit/event/level/WeatherChangeEvent.java +++ b/src/main/java/cn/nukkit/event/level/WeatherChangeEvent.java @@ -5,7 +5,7 @@ import cn.nukkit.level.Level; /** - * author: funcraft + * @author funcraft * Nukkit Project */ public class WeatherChangeEvent extends WeatherEvent implements Cancellable { @@ -31,5 +31,4 @@ public WeatherChangeEvent(Level level, boolean to) { public boolean toWeatherState() { return to; } - } diff --git a/src/main/java/cn/nukkit/event/level/WeatherEvent.java b/src/main/java/cn/nukkit/event/level/WeatherEvent.java index 0537a10838d..634fa79506f 100644 --- a/src/main/java/cn/nukkit/event/level/WeatherEvent.java +++ b/src/main/java/cn/nukkit/event/level/WeatherEvent.java @@ -4,7 +4,7 @@ import cn.nukkit.level.Level; /** - * author: funcraft + * @author funcraft * Nukkit Project */ public abstract class WeatherEvent extends Event { diff --git a/src/main/java/cn/nukkit/event/player/CraftingTableOpenEvent.java b/src/main/java/cn/nukkit/event/player/CraftingTableOpenEvent.java new file mode 100644 index 00000000000..43fc42e4386 --- /dev/null +++ b/src/main/java/cn/nukkit/event/player/CraftingTableOpenEvent.java @@ -0,0 +1,26 @@ +package cn.nukkit.event.player; + +import cn.nukkit.Player; +import cn.nukkit.block.Block; +import cn.nukkit.event.Cancellable; +import cn.nukkit.event.HandlerList; + +public class CraftingTableOpenEvent extends PlayerEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlers() { + return handlers; + } + + private final Block craftingTable; + + public CraftingTableOpenEvent(Player player, Block craftingTable) { + this.player = player; + this.craftingTable = craftingTable; + } + + public Block getCraftingTable() { + return this.craftingTable; + } +} diff --git a/src/main/java/cn/nukkit/event/player/PlayerAsyncPreLoginEvent.java b/src/main/java/cn/nukkit/event/player/PlayerAsyncPreLoginEvent.java index 58bebb1dad7..2c3c95724bd 100644 --- a/src/main/java/cn/nukkit/event/player/PlayerAsyncPreLoginEvent.java +++ b/src/main/java/cn/nukkit/event/player/PlayerAsyncPreLoginEvent.java @@ -77,7 +77,7 @@ public int getPort() { } public LoginResult getLoginResult() { - return this.loginResult; + return loginResult; } public void setLoginResult(LoginResult loginResult) { @@ -113,4 +113,4 @@ public enum LoginResult { SUCCESS, KICK } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/event/player/PlayerBedEnterEvent.java b/src/main/java/cn/nukkit/event/player/PlayerBedEnterEvent.java index 8c1eaf14930..d71b3ae5733 100644 --- a/src/main/java/cn/nukkit/event/player/PlayerBedEnterEvent.java +++ b/src/main/java/cn/nukkit/event/player/PlayerBedEnterEvent.java @@ -6,6 +6,7 @@ import cn.nukkit.event.HandlerList; public class PlayerBedEnterEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { @@ -13,13 +14,27 @@ public static HandlerList getHandlers() { } private final Block bed; + private final boolean onlySetSpawn; public PlayerBedEnterEvent(Player player, Block bed) { + this(player, bed, false); + } + + public PlayerBedEnterEvent(Player player, Block bed, boolean onlySetSpawn) { this.player = player; this.bed = bed; + this.onlySetSpawn = onlySetSpawn; } public Block getBed() { return bed; } + + /** + * Whether the event is called when a player is trying to only set spawn point and not actually sleep on the bed (on day). + * @return is only setting spawn point + */ + public boolean isOnlySetSpawn() { + return onlySetSpawn; + } } diff --git a/src/main/java/cn/nukkit/event/player/PlayerBucketEmptyEvent.java b/src/main/java/cn/nukkit/event/player/PlayerBucketEmptyEvent.java index fb1a02c4fbe..142402d82de 100644 --- a/src/main/java/cn/nukkit/event/player/PlayerBucketEmptyEvent.java +++ b/src/main/java/cn/nukkit/event/player/PlayerBucketEmptyEvent.java @@ -26,7 +26,8 @@ public PlayerBucketEmptyEvent(Player who, Block blockClicked, BlockFace blockFac } /** - * Whether a fish can be spawned when a fish bucket is emptied. + * Whether a fish can be spawned if a fish bucket is emptied. + * Notice: Disabling 'block-listener' in server.properties disables fish spawning from buckets. * * @return can spawn a fish */ @@ -35,7 +36,8 @@ public boolean isMobSpawningAllowed() { } /** - * Set whether a fish can be spawned when a fish bucket is emptied. + * Whether a fish can be spawned if a fish bucket is emptied. + * Notice: Disabling 'block-listener' in server.properties disables fish spawning from buckets. * * @param mobSpawningAllowed can spawn a fish */ diff --git a/src/main/java/cn/nukkit/event/player/PlayerBucketFillEvent.java b/src/main/java/cn/nukkit/event/player/PlayerBucketFillEvent.java index e3771d32fa0..9f10e52ac70 100644 --- a/src/main/java/cn/nukkit/event/player/PlayerBucketFillEvent.java +++ b/src/main/java/cn/nukkit/event/player/PlayerBucketFillEvent.java @@ -16,5 +16,4 @@ public static HandlerList getHandlers() { public PlayerBucketFillEvent(Player who, Block blockClicked, BlockFace blockFace, Item bucket, Item itemInHand) { super(who, blockClicked, blockFace, bucket, itemInHand); } - } diff --git a/src/main/java/cn/nukkit/event/player/PlayerChangeSkinEvent.java b/src/main/java/cn/nukkit/event/player/PlayerChangeSkinEvent.java index 637b1ac9543..4a32d4ea845 100644 --- a/src/main/java/cn/nukkit/event/player/PlayerChangeSkinEvent.java +++ b/src/main/java/cn/nukkit/event/player/PlayerChangeSkinEvent.java @@ -6,7 +6,7 @@ import cn.nukkit.event.HandlerList; /** - * author: KCodeYT + * @author KCodeYT * Nukkit Project */ public class PlayerChangeSkinEvent extends PlayerEvent implements Cancellable { @@ -27,5 +27,4 @@ public PlayerChangeSkinEvent(Player player, Skin skin) { public Skin getSkin() { return this.skin; } - } diff --git a/src/main/java/cn/nukkit/event/player/PlayerChatEvent.java b/src/main/java/cn/nukkit/event/player/PlayerChatEvent.java index 7cbd5841737..69565d79904 100644 --- a/src/main/java/cn/nukkit/event/player/PlayerChatEvent.java +++ b/src/main/java/cn/nukkit/event/player/PlayerChatEvent.java @@ -37,7 +37,6 @@ public PlayerChatEvent(Player player, String message, String format, Set name; private final Optional uuid; @@ -21,9 +22,7 @@ public PlayerDataSerializeEvent(String name, PlayerDataSerializer serializer) { UUID uuid = null; try { uuid = UUID.fromString(name); - } catch (Exception e) { - // ignore - } + } catch (Exception ignored) {} this.uuid = Optional.ofNullable(uuid); this.name = this.uuid.isPresent() ? Optional.empty() : Optional.of(name); } diff --git a/src/main/java/cn/nukkit/event/server/QueryRegenerateEvent.java b/src/main/java/cn/nukkit/event/server/QueryRegenerateEvent.java index 0383b7dd896..d75938d8a30 100644 --- a/src/main/java/cn/nukkit/event/server/QueryRegenerateEvent.java +++ b/src/main/java/cn/nukkit/event/server/QueryRegenerateEvent.java @@ -3,21 +3,19 @@ import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.event.HandlerList; -import cn.nukkit.nbt.stream.FastByteArrayOutputStream; import cn.nukkit.plugin.Plugin; import cn.nukkit.plugin.PluginDescription; import cn.nukkit.utils.Binary; -import java.io.IOException; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.*; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class QueryRegenerateEvent extends ServerEvent { - //alot todo private static final HandlerList handlers = new HandlerList(); @@ -25,17 +23,13 @@ public static HandlerList getHandlers() { return handlers; } - private static final String GAME_ID = "MINECRAFTPE"; - private int timeout; private String serverName; private boolean listPlugins; private Plugin[] plugins; private Player[] players; - private final String gameType; private final String version; - private final String server_engine; private String map; private int numPlayers; private int maxPlayers; @@ -43,8 +37,6 @@ public static HandlerList getHandlers() { private final int port; private final String ip; - private Map extraData = new HashMap<>(); - public QueryRegenerateEvent(Server server) { this(server, 5); } @@ -52,12 +44,11 @@ public QueryRegenerateEvent(Server server) { public QueryRegenerateEvent(Server server, int timeout) { this.timeout = timeout; this.serverName = server.getMotd(); - this.listPlugins = server.getConfig("settings.query-plugins", true); + this.listPlugins = server.queryPlugins; this.plugins = server.getPluginManager().getPlugins().values().toArray(new Plugin[0]); this.players = server.getOnlinePlayers().values().toArray(new Player[0]); - this.gameType = (server.getGamemode() & 0x01) == 0 ? "SMP" : "CMP"; + this.gameType = server.getGamemode() == 1 ? "CMP" : "SMP"; this.version = server.getVersion(); - this.server_engine = server.getName() + " " + server.getNukkitVersion(); this.map = server.getDefaultLevel() == null ? "unknown" : server.getDefaultLevel().getName(); this.numPlayers = this.players.length; this.maxPlayers = server.getMaxPlayers(); @@ -130,91 +121,70 @@ public void setWorld(String world) { this.map = world; } - public Map getExtraData() { - return extraData; - } - - public void setExtraData(Map extraData) { - this.extraData = extraData; - } - - public byte[] getLongQuery(byte[] buffer) { - if (buffer == null) buffer = new byte[Character.MAX_VALUE]; - FastByteArrayOutputStream query = new FastByteArrayOutputStream(buffer); - try { - StringBuilder plist = new StringBuilder(this.server_engine); - if (this.plugins.length > 0 && this.listPlugins) { - plist.append(":"); - for (Plugin p : this.plugins) { - PluginDescription d = p.getDescription(); - plist.append(" ").append(d.getName().replace(";", "").replace(":", "").replace(" ", "_")).append(" ").append(d.getVersion().replace(";", "").replace(":", "").replace(" ", "_")).append(";"); - } - plist = new StringBuilder(plist.substring(0, plist.length() - 2)); - } - - query.write("splitnum".getBytes()); - query.write((byte) 0x00); - query.write((byte) 128); - query.write((byte) 0x00); - - LinkedHashMap KVdata = new LinkedHashMap<>(); - KVdata.put("hostname", this.serverName); - KVdata.put("gametype", this.gameType); - KVdata.put("game_id", GAME_ID); - KVdata.put("version", this.version); - KVdata.put("server_engine", this.server_engine); - KVdata.put("plugins", plist.toString()); - KVdata.put("map", this.map); - KVdata.put("numplayers", String.valueOf(this.numPlayers)); - KVdata.put("maxplayers", String.valueOf(this.maxPlayers)); - KVdata.put("whitelist", this.whitelist); - KVdata.put("hostip", this.ip); - KVdata.put("hostport", String.valueOf(this.port)); - - for (Map.Entry entry : KVdata.entrySet()) { - query.write(entry.getKey().getBytes(StandardCharsets.UTF_8)); - query.write((byte) 0x00); - query.write(entry.getValue().getBytes(StandardCharsets.UTF_8)); - query.write((byte) 0x00); + public byte[] getLongQuery() { + ByteBuffer query = ByteBuffer.allocate(65536); + StringBuilder plist = new StringBuilder("Nukkit"); + if (this.listPlugins && this.plugins.length > 0) { + plist.append(':'); + for (Plugin p : this.plugins) { + PluginDescription d = p.getDescription(); + plist.append(' ').append(d.getName().replace(";", "").replace(":", "").replace(" ", "_")).append(' ').append(d.getVersion().replace(";", "").replace(":", "").replace(" ", "_")).append(';'); } + plist = new StringBuilder(plist.substring(0, plist.length() - 2)); + } - query.write(new byte[]{0x00, 0x01}); - query.write("player_".getBytes()); - query.write(new byte[]{0x00, 0x00}); + query.put("splitnum".getBytes(StandardCharsets.UTF_8)); + query.put((byte) 0x00); + query.put((byte) 128); + query.put((byte) 0x00); + + Map KVdata = new LinkedHashMap<>(); + KVdata.put("hostname", this.serverName); + KVdata.put("gametype", this.gameType); + KVdata.put("game_id", "MINECRAFTPE"); + KVdata.put("version", this.version); + KVdata.put("server_engine", "Nukkit"); + KVdata.put("plugins", plist.toString()); + KVdata.put("map", this.map); + KVdata.put("numplayers", String.valueOf(this.numPlayers)); + KVdata.put("maxplayers", String.valueOf(this.maxPlayers)); + KVdata.put("whitelist", this.whitelist); + KVdata.put("hostip", this.ip); + KVdata.put("hostport", String.valueOf(this.port)); + + for (Map.Entry entry : KVdata.entrySet()) { + query.put(entry.getKey().getBytes(StandardCharsets.UTF_8)); + query.put((byte) 0x00); + query.put(entry.getValue().getBytes(StandardCharsets.UTF_8)); + query.put((byte) 0x00); + } - for (Player player : this.players) { - query.write(player.getName().getBytes(StandardCharsets.UTF_8)); - query.write((byte) 0x00); - } + query.put(new byte[]{0x00, 0x01}).put("player_".getBytes(StandardCharsets.UTF_8)).put(new byte[]{0x00, 0x00}); - query.write((byte) 0x00); - } catch (IOException e) { - e.printStackTrace(); + for (Player player : this.players) { + query.put(player.getName().getBytes(StandardCharsets.UTF_8)); + query.put((byte) 0x00); } - return query.toByteArray(); - } - - public byte[] getShortQuery(byte[] buffer) { - if (buffer == null) buffer = new byte[Character.MAX_VALUE]; - FastByteArrayOutputStream query = new FastByteArrayOutputStream(buffer); - try { - query.write(this.serverName.getBytes(StandardCharsets.UTF_8)); - query.write((byte) 0x00); - query.write(this.gameType.getBytes(StandardCharsets.UTF_8)); - query.write((byte) 0x00); - query.write(this.map.getBytes(StandardCharsets.UTF_8)); - query.write((byte) 0x00); - query.write(String.valueOf(this.numPlayers).getBytes(StandardCharsets.UTF_8)); - query.write((byte) 0x00); - query.write(String.valueOf(this.maxPlayers).getBytes(StandardCharsets.UTF_8)); - query.write((byte) 0x00); - query.write(Binary.writeLShort(this.port)); - query.write(this.ip.getBytes(StandardCharsets.UTF_8)); - query.write((byte) 0x00); - } catch (IOException e) { - e.printStackTrace(); - } - return query.toByteArray(); - } + query.put((byte) 0x00); + return Arrays.copyOf(query.array(), query.position()); + } + + public byte[] getShortQuery() { + ByteBuffer query = ByteBuffer.allocate(65536); + query.put(this.serverName.getBytes(StandardCharsets.UTF_8)); + query.put((byte) 0x00); + query.put(this.gameType.getBytes(StandardCharsets.UTF_8)); + query.put((byte) 0x00); + query.put(this.map.getBytes(StandardCharsets.UTF_8)); + query.put((byte) 0x00); + query.put(String.valueOf(this.numPlayers).getBytes(StandardCharsets.UTF_8)); + query.put((byte) 0x00); + query.put(String.valueOf(this.maxPlayers).getBytes(StandardCharsets.UTF_8)); + query.put((byte) 0x00); + query.put(Binary.writeLShort(this.port)); + query.put(this.ip.getBytes(StandardCharsets.UTF_8)); + query.put((byte) 0x00); + return Arrays.copyOf(query.array(), query.position()); + } } diff --git a/src/main/java/cn/nukkit/event/server/RemoteServerCommandEvent.java b/src/main/java/cn/nukkit/event/server/RemoteServerCommandEvent.java index 47ae4afd8a2..58be9956cd6 100644 --- a/src/main/java/cn/nukkit/event/server/RemoteServerCommandEvent.java +++ b/src/main/java/cn/nukkit/event/server/RemoteServerCommandEvent.java @@ -9,6 +9,7 @@ * @author Tee7even */ public class RemoteServerCommandEvent extends ServerCommandEvent { + private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { diff --git a/src/main/java/cn/nukkit/event/server/ServerCommandEvent.java b/src/main/java/cn/nukkit/event/server/ServerCommandEvent.java index c3da65869c0..4d4ab50d066 100644 --- a/src/main/java/cn/nukkit/event/server/ServerCommandEvent.java +++ b/src/main/java/cn/nukkit/event/server/ServerCommandEvent.java @@ -5,7 +5,7 @@ import cn.nukkit.event.HandlerList; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ServerCommandEvent extends ServerEvent implements Cancellable { diff --git a/src/main/java/cn/nukkit/event/server/ServerEvent.java b/src/main/java/cn/nukkit/event/server/ServerEvent.java index ad7032615a4..a90a329cd6d 100644 --- a/src/main/java/cn/nukkit/event/server/ServerEvent.java +++ b/src/main/java/cn/nukkit/event/server/ServerEvent.java @@ -3,7 +3,7 @@ import cn.nukkit.event.Event; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ abstract public class ServerEvent extends Event { diff --git a/src/main/java/cn/nukkit/event/server/ServerStopEvent.java b/src/main/java/cn/nukkit/event/server/ServerStopEvent.java index 65b46996c57..8b80ff24449 100644 --- a/src/main/java/cn/nukkit/event/server/ServerStopEvent.java +++ b/src/main/java/cn/nukkit/event/server/ServerStopEvent.java @@ -3,7 +3,7 @@ import cn.nukkit.event.HandlerList; /** - * author: NycuRO + * @author NycuRO * NukkitX Project */ public class ServerStopEvent extends ServerEvent { diff --git a/src/main/java/cn/nukkit/event/vehicle/EntityEnterVehicleEvent.java b/src/main/java/cn/nukkit/event/vehicle/EntityEnterVehicleEvent.java index f7fcd4b1c56..370f4b94c7b 100644 --- a/src/main/java/cn/nukkit/event/vehicle/EntityEnterVehicleEvent.java +++ b/src/main/java/cn/nukkit/event/vehicle/EntityEnterVehicleEvent.java @@ -2,6 +2,7 @@ import cn.nukkit.Player; import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityVehicle; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; @@ -13,19 +14,18 @@ public static HandlerList getHandlers() { return handlers; } - private final cn.nukkit.entity.Entity riding; + private final Entity riding; - public EntityEnterVehicleEvent(cn.nukkit.entity.Entity riding, Entity vehicle) { + public EntityEnterVehicleEvent(Entity riding, EntityVehicle vehicle) { super(vehicle); this.riding = riding; } - public cn.nukkit.entity.Entity getEntity() { + public Entity getEntity() { return riding; } public boolean isPlayer() { return riding instanceof Player; } - } diff --git a/src/main/java/cn/nukkit/event/vehicle/EntityExitVehicleEvent.java b/src/main/java/cn/nukkit/event/vehicle/EntityExitVehicleEvent.java index 818988c2b40..b120373dbb1 100644 --- a/src/main/java/cn/nukkit/event/vehicle/EntityExitVehicleEvent.java +++ b/src/main/java/cn/nukkit/event/vehicle/EntityExitVehicleEvent.java @@ -2,6 +2,7 @@ import cn.nukkit.Player; import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityVehicle; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; @@ -13,19 +14,18 @@ public static HandlerList getHandlers() { return handlers; } - private final cn.nukkit.entity.Entity riding; + private final Entity riding; - public EntityExitVehicleEvent(cn.nukkit.entity.Entity riding, Entity vehicle) { + public EntityExitVehicleEvent(Entity riding, EntityVehicle vehicle) { super(vehicle); this.riding = riding; } - public cn.nukkit.entity.Entity getEntity() { + public Entity getEntity() { return riding; } public boolean isPlayer() { return riding instanceof Player; } - } diff --git a/src/main/java/cn/nukkit/event/vehicle/VehicleCreateEvent.java b/src/main/java/cn/nukkit/event/vehicle/VehicleCreateEvent.java index f81f7997b9a..15d4cf94a6e 100644 --- a/src/main/java/cn/nukkit/event/vehicle/VehicleCreateEvent.java +++ b/src/main/java/cn/nukkit/event/vehicle/VehicleCreateEvent.java @@ -1,7 +1,6 @@ package cn.nukkit.event.vehicle; - -import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityVehicle; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; @@ -13,8 +12,7 @@ public static HandlerList getHandlers() { return handlers; } - public VehicleCreateEvent(Entity vehicle) { + public VehicleCreateEvent(EntityVehicle vehicle) { super(vehicle); } - } diff --git a/src/main/java/cn/nukkit/event/vehicle/VehicleDamageEvent.java b/src/main/java/cn/nukkit/event/vehicle/VehicleDamageEvent.java index 36de23c4295..f9c40d8903e 100644 --- a/src/main/java/cn/nukkit/event/vehicle/VehicleDamageEvent.java +++ b/src/main/java/cn/nukkit/event/vehicle/VehicleDamageEvent.java @@ -1,6 +1,7 @@ package cn.nukkit.event.vehicle; import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityVehicle; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; @@ -12,16 +13,16 @@ public static HandlerList getHandlers() { return handlers; } - private final cn.nukkit.entity.Entity attacker; + private final Entity attacker; private double damage; - public VehicleDamageEvent(Entity vehicle, Entity attacker, double damage) { + public VehicleDamageEvent(EntityVehicle vehicle, Entity attacker, double damage) { super(vehicle); this.attacker = attacker; this.damage = damage; } - public cn.nukkit.entity.Entity getAttacker() { + public Entity getAttacker() { return attacker; } @@ -32,5 +33,4 @@ public double getDamage() { public void setDamage(double damage) { this.damage = damage; } - } diff --git a/src/main/java/cn/nukkit/event/vehicle/VehicleDestroyEvent.java b/src/main/java/cn/nukkit/event/vehicle/VehicleDestroyEvent.java index 0cfaca9c3c9..ebb2fc1c309 100644 --- a/src/main/java/cn/nukkit/event/vehicle/VehicleDestroyEvent.java +++ b/src/main/java/cn/nukkit/event/vehicle/VehicleDestroyEvent.java @@ -1,6 +1,7 @@ package cn.nukkit.event.vehicle; import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityVehicle; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; @@ -12,15 +13,14 @@ public static HandlerList getHandlers() { return handlers; } - private final cn.nukkit.entity.Entity attacker; + private final Entity attacker; - public VehicleDestroyEvent(Entity vehicle, cn.nukkit.entity.Entity attacker) { + public VehicleDestroyEvent(EntityVehicle vehicle, Entity attacker) { super(vehicle); this.attacker = attacker; } - public cn.nukkit.entity.Entity getAttacker() { + public Entity getAttacker() { return attacker; } - } diff --git a/src/main/java/cn/nukkit/event/vehicle/VehicleEvent.java b/src/main/java/cn/nukkit/event/vehicle/VehicleEvent.java index dab135f059d..ba5346212e1 100644 --- a/src/main/java/cn/nukkit/event/vehicle/VehicleEvent.java +++ b/src/main/java/cn/nukkit/event/vehicle/VehicleEvent.java @@ -1,6 +1,6 @@ package cn.nukkit.event.vehicle; -import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityVehicle; import cn.nukkit.event.Event; /** @@ -10,13 +10,13 @@ */ public abstract class VehicleEvent extends Event { - private final Entity vehicle; + private final EntityVehicle vehicle; - public VehicleEvent(Entity vehicle) { + public VehicleEvent(EntityVehicle vehicle) { this.vehicle = vehicle; } - public Entity getVehicle() { + public EntityVehicle getVehicle() { return vehicle; } } diff --git a/src/main/java/cn/nukkit/event/vehicle/VehicleMoveEvent.java b/src/main/java/cn/nukkit/event/vehicle/VehicleMoveEvent.java index 814590c451d..0cf898755e8 100644 --- a/src/main/java/cn/nukkit/event/vehicle/VehicleMoveEvent.java +++ b/src/main/java/cn/nukkit/event/vehicle/VehicleMoveEvent.java @@ -1,6 +1,6 @@ package cn.nukkit.event.vehicle; -import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityVehicle; import cn.nukkit.event.HandlerList; import cn.nukkit.level.Location; @@ -15,7 +15,7 @@ public static HandlerList getHandlers() { private final Location from; private final Location to; - public VehicleMoveEvent(Entity vehicle, Location from, Location to) { + public VehicleMoveEvent(EntityVehicle vehicle, Location from, Location to) { super(vehicle); this.from = from; this.to = to; diff --git a/src/main/java/cn/nukkit/event/vehicle/VehicleUpdateEvent.java b/src/main/java/cn/nukkit/event/vehicle/VehicleUpdateEvent.java index 2078c54909a..4f56750f411 100644 --- a/src/main/java/cn/nukkit/event/vehicle/VehicleUpdateEvent.java +++ b/src/main/java/cn/nukkit/event/vehicle/VehicleUpdateEvent.java @@ -1,6 +1,6 @@ package cn.nukkit.event.vehicle; -import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityVehicle; import cn.nukkit.event.HandlerList; public class VehicleUpdateEvent extends VehicleEvent { @@ -11,8 +11,7 @@ public static HandlerList getHandlers() { return handlers; } - public VehicleUpdateEvent(Entity vehicle) { + public VehicleUpdateEvent(EntityVehicle vehicle) { super(vehicle); } - } diff --git a/src/main/java/cn/nukkit/event/weather/LightningStrikeEvent.java b/src/main/java/cn/nukkit/event/weather/LightningStrikeEvent.java index 3a4e2d40f85..d667d5608a9 100644 --- a/src/main/java/cn/nukkit/event/weather/LightningStrikeEvent.java +++ b/src/main/java/cn/nukkit/event/weather/LightningStrikeEvent.java @@ -7,7 +7,7 @@ import cn.nukkit.level.Level; /** - * author: funcraft + * @author funcraft * Nukkit Project */ public class LightningStrikeEvent extends WeatherEvent implements Cancellable { @@ -31,5 +31,4 @@ public LightningStrikeEvent(Level level, final EntityLightningStrike bolt) { public EntityLightningStrike getLightning() { return bolt; } - } diff --git a/src/main/java/cn/nukkit/form/element/Element.java b/src/main/java/cn/nukkit/form/element/Element.java index fc80c0b7db7..0bb96a433fe 100644 --- a/src/main/java/cn/nukkit/form/element/Element.java +++ b/src/main/java/cn/nukkit/form/element/Element.java @@ -1,5 +1,4 @@ package cn.nukkit.form.element; public abstract class Element { - } diff --git a/src/main/java/cn/nukkit/form/element/ElementButton.java b/src/main/java/cn/nukkit/form/element/ElementButton.java index a95846582ff..9126cc1ec5d 100644 --- a/src/main/java/cn/nukkit/form/element/ElementButton.java +++ b/src/main/java/cn/nukkit/form/element/ElementButton.java @@ -29,5 +29,4 @@ public ElementButtonImageData getImage() { public void addImage(ElementButtonImageData image) { if (!image.getData().isEmpty() && !image.getType().isEmpty()) this.image = image; } - } diff --git a/src/main/java/cn/nukkit/form/element/ElementDropdown.java b/src/main/java/cn/nukkit/form/element/ElementDropdown.java index ec204f00467..4cfd810e057 100644 --- a/src/main/java/cn/nukkit/form/element/ElementDropdown.java +++ b/src/main/java/cn/nukkit/form/element/ElementDropdown.java @@ -7,8 +7,10 @@ public class ElementDropdown extends Element { + @SuppressWarnings("unused") private final String type = "dropdown"; //This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999 private String text = ""; + @SuppressWarnings("FieldMayBeFinal") private List options; @SerializedName("default") private int defaultOptionIndex = 0; @@ -56,5 +58,4 @@ public void addOption(String option, boolean isDefault) { options.add(option); if (isDefault) this.defaultOptionIndex = options.size() - 1; } - } diff --git a/src/main/java/cn/nukkit/form/element/ElementInput.java b/src/main/java/cn/nukkit/form/element/ElementInput.java index 33638ae01bb..18b3f9c8bda 100644 --- a/src/main/java/cn/nukkit/form/element/ElementInput.java +++ b/src/main/java/cn/nukkit/form/element/ElementInput.java @@ -4,6 +4,7 @@ public class ElementInput extends Element { + @SuppressWarnings("unused") private final String type = "input"; //This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999 private String text = ""; private String placeholder = ""; diff --git a/src/main/java/cn/nukkit/form/element/ElementLabel.java b/src/main/java/cn/nukkit/form/element/ElementLabel.java index 449eae05613..a14a322cc3a 100644 --- a/src/main/java/cn/nukkit/form/element/ElementLabel.java +++ b/src/main/java/cn/nukkit/form/element/ElementLabel.java @@ -2,6 +2,7 @@ public class ElementLabel extends Element { + @SuppressWarnings("unused") private final String type = "label"; //This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999 private String text = ""; diff --git a/src/main/java/cn/nukkit/form/element/ElementSlider.java b/src/main/java/cn/nukkit/form/element/ElementSlider.java index 16a8380e3dd..1f1c6e39f45 100644 --- a/src/main/java/cn/nukkit/form/element/ElementSlider.java +++ b/src/main/java/cn/nukkit/form/element/ElementSlider.java @@ -4,6 +4,7 @@ public class ElementSlider extends Element { + @SuppressWarnings("unused") private final String type = "slider"; //This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999 private String text = ""; private float min = 0f; diff --git a/src/main/java/cn/nukkit/form/element/ElementStepSlider.java b/src/main/java/cn/nukkit/form/element/ElementStepSlider.java index 0c93e0a7568..ef942764cc6 100644 --- a/src/main/java/cn/nukkit/form/element/ElementStepSlider.java +++ b/src/main/java/cn/nukkit/form/element/ElementStepSlider.java @@ -7,8 +7,10 @@ public class ElementStepSlider extends Element { + @SuppressWarnings("unused") private final String type = "step_slider"; //This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999 private String text = ""; + @SuppressWarnings("FieldMayBeFinal") private List steps; @SerializedName("default") private int defaultStepIndex = 0; @@ -56,5 +58,4 @@ public void addStep(String step, boolean isDefault) { steps.add(step); if (isDefault) this.defaultStepIndex = steps.size() - 1; } - } diff --git a/src/main/java/cn/nukkit/form/element/ElementToggle.java b/src/main/java/cn/nukkit/form/element/ElementToggle.java index bd65ced16f5..eb24b24fa16 100644 --- a/src/main/java/cn/nukkit/form/element/ElementToggle.java +++ b/src/main/java/cn/nukkit/form/element/ElementToggle.java @@ -4,6 +4,7 @@ public class ElementToggle extends Element { + @SuppressWarnings("unused") private final String type = "toggle"; //This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999 private String text; @SerializedName("default") diff --git a/src/main/java/cn/nukkit/form/handler/FormResponseHandler.java b/src/main/java/cn/nukkit/form/handler/FormResponseHandler.java index d3192e63f31..5d52099c67a 100644 --- a/src/main/java/cn/nukkit/form/handler/FormResponseHandler.java +++ b/src/main/java/cn/nukkit/form/handler/FormResponseHandler.java @@ -11,5 +11,4 @@ static FormResponseHandler withoutPlayer(IntConsumer formIDConsumer) { } void handle(Player player, int formID); - } diff --git a/src/main/java/cn/nukkit/form/response/FormResponse.java b/src/main/java/cn/nukkit/form/response/FormResponse.java index 1d128d60f45..8f83c5892c6 100644 --- a/src/main/java/cn/nukkit/form/response/FormResponse.java +++ b/src/main/java/cn/nukkit/form/response/FormResponse.java @@ -1,5 +1,4 @@ package cn.nukkit.form.response; public abstract class FormResponse { - } diff --git a/src/main/java/cn/nukkit/form/response/FormResponseData.java b/src/main/java/cn/nukkit/form/response/FormResponseData.java index fffb87dad28..6a96cda0440 100644 --- a/src/main/java/cn/nukkit/form/response/FormResponseData.java +++ b/src/main/java/cn/nukkit/form/response/FormResponseData.java @@ -17,5 +17,4 @@ public int getElementID() { public String getElementContent() { return elementContent; } - } diff --git a/src/main/java/cn/nukkit/form/response/FormResponseModal.java b/src/main/java/cn/nukkit/form/response/FormResponseModal.java index e09a6173593..6b610096d70 100644 --- a/src/main/java/cn/nukkit/form/response/FormResponseModal.java +++ b/src/main/java/cn/nukkit/form/response/FormResponseModal.java @@ -17,5 +17,4 @@ public int getClickedButtonId() { public String getClickedButtonText() { return clickedButtonText; } - } diff --git a/src/main/java/cn/nukkit/form/response/FormResponseSimple.java b/src/main/java/cn/nukkit/form/response/FormResponseSimple.java index 6fa48b38fa0..1e308415916 100644 --- a/src/main/java/cn/nukkit/form/response/FormResponseSimple.java +++ b/src/main/java/cn/nukkit/form/response/FormResponseSimple.java @@ -19,5 +19,4 @@ public int getClickedButtonId() { public ElementButton getClickedButton() { return clickedButton; } - } diff --git a/src/main/java/cn/nukkit/form/window/FormWindow.java b/src/main/java/cn/nukkit/form/window/FormWindow.java index 1d48a5d35c7..b934973f5ce 100644 --- a/src/main/java/cn/nukkit/form/window/FormWindow.java +++ b/src/main/java/cn/nukkit/form/window/FormWindow.java @@ -9,7 +9,7 @@ public abstract class FormWindow { - protected static final Gson GSON = new Gson(); + static final Gson GSON = new Gson(); protected transient boolean closed = false; protected final transient List handlers = new ObjectArrayList<>(); @@ -33,5 +33,4 @@ public void addHandler(FormResponseHandler handler) { public List getHandlers() { return handlers; } - } diff --git a/src/main/java/cn/nukkit/form/window/FormWindowCustom.java b/src/main/java/cn/nukkit/form/window/FormWindowCustom.java index 1919a1370ef..756b16eaab4 100644 --- a/src/main/java/cn/nukkit/form/window/FormWindowCustom.java +++ b/src/main/java/cn/nukkit/form/window/FormWindowCustom.java @@ -11,9 +11,11 @@ public class FormWindowCustom extends FormWindow { - private final String type = "custom_form"; //This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999 + @SuppressWarnings("unused") + private final String type = "custom_form"; // This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999 private String title = ""; private ElementButtonImageData icon; + @SuppressWarnings("FieldMayBeFinal") private List content; private FormResponseCustom response; @@ -74,9 +76,7 @@ public void setResponse(String data) { return; } - List elementResponses = GSON.fromJson(data, new TypeToken>() { - }.getType()); - //elementResponses.remove(elementResponses.size() - 1); //submit button //maybe mojang removed that? + List elementResponses = GSON.fromJson(data, new ListTypeToken().getType()); int i = 0; @@ -150,4 +150,6 @@ public void setElementsFromResponse() { } } + private static class ListTypeToken extends TypeToken> { + } } diff --git a/src/main/java/cn/nukkit/form/window/FormWindowModal.java b/src/main/java/cn/nukkit/form/window/FormWindowModal.java index 9eb7e95c2ce..63da91229d8 100644 --- a/src/main/java/cn/nukkit/form/window/FormWindowModal.java +++ b/src/main/java/cn/nukkit/form/window/FormWindowModal.java @@ -4,7 +4,8 @@ public class FormWindowModal extends FormWindow { - private final String type = "modal"; //This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999 + @SuppressWarnings("unused") + private final String type = "modal"; // This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999 private String title = ""; private String content = ""; private String button1 = ""; @@ -63,5 +64,4 @@ public void setResponse(String data) { if (data.equals("true")) response = new FormResponseModal(0, button1); else response = new FormResponseModal(1, button2); } - } diff --git a/src/main/java/cn/nukkit/form/window/FormWindowSimple.java b/src/main/java/cn/nukkit/form/window/FormWindowSimple.java index 0b7ff67ef2e..0b4e63f73f7 100644 --- a/src/main/java/cn/nukkit/form/window/FormWindowSimple.java +++ b/src/main/java/cn/nukkit/form/window/FormWindowSimple.java @@ -8,9 +8,11 @@ public class FormWindowSimple extends FormWindow { - private final String type = "form"; //This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999 + @SuppressWarnings("unused") + private final String type = "form"; // This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999 private String title = ""; private String content = ""; + @SuppressWarnings("FieldMayBeFinal") private List buttons; private FormResponseSimple response = null; @@ -70,5 +72,4 @@ public void setResponse(String data) { } this.response = new FormResponseSimple(buttonID, buttons.get(buttonID)); } - } diff --git a/src/main/java/cn/nukkit/inventory/AnvilInventory.java b/src/main/java/cn/nukkit/inventory/AnvilInventory.java index b359a10ab47..c91e7cd464d 100644 --- a/src/main/java/cn/nukkit/inventory/AnvilInventory.java +++ b/src/main/java/cn/nukkit/inventory/AnvilInventory.java @@ -5,7 +5,7 @@ import cn.nukkit.level.Position; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class AnvilInventory extends FakeBlockUIComponent { @@ -24,18 +24,6 @@ public AnvilInventory(PlayerUIInventory playerUI, Position position) { super(playerUI, InventoryType.ANVIL, 1, position); } - @Override - public void onClose(Player who) { - super.onClose(who); - who.craftingType = Player.CRAFTING_SMALL; - who.resetCraftingGridType(); - - for (int i = 0; i < 2; ++i) { - this.getHolder().getLevel().dropItem(this.getHolder().add(0.5, 0.5, 0.5), this.getItem(i)); - this.clear(i); - } - } - @Override public void onOpen(Player who) { super.onOpen(who); diff --git a/src/main/java/cn/nukkit/inventory/BarrelInventory.java b/src/main/java/cn/nukkit/inventory/BarrelInventory.java new file mode 100644 index 00000000000..c28de6a32c6 --- /dev/null +++ b/src/main/java/cn/nukkit/inventory/BarrelInventory.java @@ -0,0 +1,68 @@ +package cn.nukkit.inventory; + +import cn.nukkit.Player; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockBarrel; +import cn.nukkit.blockentity.BlockEntityBarrel; +import cn.nukkit.level.Level; +import cn.nukkit.network.protocol.LevelSoundEventPacket; + +public class BarrelInventory extends ContainerInventory { + + public BarrelInventory(BlockEntityBarrel barrel) { + super(barrel, InventoryType.BARREL); + } + + @Override + public BlockEntityBarrel getHolder() { + return (BlockEntityBarrel) this.holder; + } + + @Override + public void onOpen(Player who) { + super.onOpen(who); + if (this.getViewers().size() != 1) { + return; + } + + BlockEntityBarrel barrel = this.getHolder(); + Level level = barrel.getLevel(); + if (level == null) { + return; + } + + Block block = barrel.getBlock(); + if (block instanceof BlockBarrel) { + BlockBarrel blockBarrel = (BlockBarrel) block; + if (!blockBarrel.isOpen()) { + blockBarrel.setOpen(true); + level.setBlock(blockBarrel, blockBarrel, true, true); + level.addLevelSoundEvent(blockBarrel, LevelSoundEventPacket.SOUND_BLOCK_BARREL_OPEN); + } + } + } + + @Override + public void onClose(Player who) { + super.onClose(who); + if (!this.getViewers().isEmpty()) { + return; + } + + BlockEntityBarrel barrel = this.getHolder(); + Level level = barrel.getLevel(); + if (level == null) { + return; + } + + Block block = barrel.getBlock(); + if (block instanceof BlockBarrel) { + BlockBarrel blockBarrel = (BlockBarrel) block; + if (blockBarrel.isOpen()) { + blockBarrel.setOpen(false); + level.setBlock(blockBarrel, blockBarrel, true, true); + level.addLevelSoundEvent(blockBarrel, LevelSoundEventPacket.SOUND_BLOCK_BARREL_CLOSE); + } + } + } +} diff --git a/src/main/java/cn/nukkit/inventory/BaseInventory.java b/src/main/java/cn/nukkit/inventory/BaseInventory.java index c6b110ec34d..cb8d4867079 100644 --- a/src/main/java/cn/nukkit/inventory/BaseInventory.java +++ b/src/main/java/cn/nukkit/inventory/BaseInventory.java @@ -12,11 +12,12 @@ import cn.nukkit.item.ItemBlock; import cn.nukkit.network.protocol.InventoryContentPacket; import cn.nukkit.network.protocol.InventorySlotPacket; +import it.unimi.dsi.fastutil.ints.IntArrayList; import java.util.*; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class BaseInventory implements Inventory { @@ -37,6 +38,8 @@ public abstract class BaseInventory implements Inventory { protected InventoryHolder holder; + final Item air; + public BaseInventory(InventoryHolder holder, InventoryType type) { this(holder, type, new HashMap<>()); } @@ -50,6 +53,8 @@ public BaseInventory(InventoryHolder holder, InventoryType type, Map items, Integer overrideSize, String overrideTitle) { + air = new ItemBlock(Block.get(BlockID.AIR, null), 0, 0); + this.holder = holder; this.type = type; @@ -99,7 +104,14 @@ public String getTitle() { @Override public Item getItem(int index) { - return this.slots.containsKey(index) ? this.slots.get(index).clone() : new ItemBlock(Block.get(BlockID.AIR), null, 0); + Item get = this.slots.get(index); + return get == null ? new ItemBlock(Block.get(BlockID.AIR), null, 0) : get.clone(); + } + + @Override + public Item getItemFast(int index) { + Item get = this.slots.get(index); + return get == null ? air : get; } @Override @@ -110,12 +122,8 @@ public Map getContents() { @Override public void setContents(Map items) { if (items.size() > this.size) { + items = new TreeMap<>(items); TreeMap newItems = new TreeMap<>(); - for (Map.Entry entry : items.entrySet()) { - newItems.put(entry.getKey(), entry.getValue()); - } - items = newItems; - newItems = new TreeMap<>(); int i = 0; for (Map.Entry entry : items.entrySet()) { newItems.put(entry.getKey(), entry.getValue()); @@ -142,7 +150,7 @@ public void setContents(Map items) { @Override public boolean setItem(int index, Item item, boolean send) { - item = item.clone(); + //item = item.clone(); if (index < 0 || index >= this.size) { return false; } else if (item.getId() == 0 || item.getCount() <= 0) { @@ -168,7 +176,6 @@ public boolean setItem(int index, Item item, boolean send) { Item old = this.getItem(index); this.slots.put(index, item.clone()); this.onSlotChange(index, old, send); - return true; } @@ -231,7 +238,7 @@ public int first(Item item, boolean exact) { @Override public int firstEmpty(Item item) { for (int i = 0; i < this.size; ++i) { - if (this.getItem(i).getId() == Item.AIR) { + if (this.getItemFast(i).getId() == Item.AIR) { return i; } } @@ -248,24 +255,25 @@ public void decreaseCount(int slot) { this.setItem(slot, item); } } - + @Override public boolean canAddItem(Item item) { - item = item.clone(); + int count = item.getCount(); boolean checkDamage = item.hasMeta(); boolean checkTag = item.getCompoundTag() != null; - for (int i = 0; i < this.getSize(); ++i) { - Item slot = this.getItem(i); + int i1 = this.getSize(); + for (int i = 0; i < i1; ++i) { + Item slot = this.getItemFast(i); if (item.equals(slot, checkDamage, checkTag)) { int diff; if ((diff = slot.getMaxStackSize() - slot.getCount()) > 0) { - item.setCount(item.getCount() - diff); + count -= diff; } } else if (slot.getId() == Item.AIR) { - item.setCount(item.getCount() - this.getMaxStackSize()); + count -= this.getMaxStackSize(); } - if (item.getCount() <= 0) { + if (count <= 0) { return true; } } @@ -282,7 +290,7 @@ public Item[] addItem(Item... slots) { } } - List emptySlots = new ArrayList<>(); + IntArrayList emptySlots = new IntArrayList(); for (int i = 0; i < this.getSize(); ++i) { Item item = this.getItem(i); @@ -293,7 +301,7 @@ public Item[] addItem(Item... slots) { for (Item slot : new ArrayList<>(itemSlots)) { if (slot.equals(item) && item.getCount() < item.getMaxStackSize()) { int amount = Math.min(item.getMaxStackSize() - item.getCount(), slot.getCount()); - amount = Math.min(amount, this.getMaxStackSize()); + amount = Math.min(amount, this.maxStackSize); if (amount > 0) { slot.setCount(slot.getCount() - amount); item.setCount(item.getCount() + amount); @@ -314,7 +322,7 @@ public Item[] addItem(Item... slots) { if (!itemSlots.isEmpty()) { Item slot = itemSlots.get(0); int amount = Math.min(slot.getMaxStackSize(), slot.getCount()); - amount = Math.min(amount, this.getMaxStackSize()); + amount = Math.min(amount, this.maxStackSize); slot.setCount(slot.getCount() - amount); Item item = slot.clone(); item.setCount(amount); @@ -353,11 +361,10 @@ public Item[] removeItem(Item... slots) { if (slot.getCount() <= 0) { itemSlots.remove(slot); } - } } - if (itemSlots.size() == 0) { + if (itemSlots.isEmpty()) { break; } } @@ -380,6 +387,7 @@ public boolean clear(int index, boolean send) { } item = ev.getNewItem(); } + if (holder instanceof BlockEntity) { ((BlockEntity) holder).setDirty(); } @@ -420,7 +428,6 @@ public void setMaxStackSize(int maxStackSize) { @Override public boolean open(Player who) { - //if (this.viewers.contains(who)) return false; InventoryOpenEvent ev = new InventoryOpenEvent(this, who); who.getServer().getPluginManager().callEvent(ev); if (ev.isCancelled()) { @@ -468,7 +475,7 @@ public void sendContents(Player... players) { for (Player player : players) { int id = player.getWindowId(this); - if (id == -1 || !player.spawned) { + if (id == -1 /*|| !player.spawned*/) { this.close(player); continue; } @@ -484,7 +491,7 @@ public boolean isFull() { } for (Item item : this.slots.values()) { - if (item == null || item.getId() == 0 || item.getCount() < item.getMaxStackSize() || item.getCount() < this.getMaxStackSize()) { + if (item == null || item.getId() == 0 || item.getCount() < item.getMaxStackSize() || item.getCount() < this.maxStackSize) { return false; } } @@ -494,7 +501,7 @@ public boolean isFull() { @Override public boolean isEmpty() { - if (this.getMaxStackSize() <= 0) { + if (this.maxStackSize <= 0) { return false; } @@ -508,7 +515,7 @@ public boolean isEmpty() { } public int getFreeSpace(Item item) { - int maxStackSize = Math.min(item.getMaxStackSize(), this.getMaxStackSize()); + int maxStackSize = Math.min(item.getMaxStackSize(), this.maxStackSize); int space = (this.getSize() - this.slots.size()) * maxStackSize; for (Item slot : this.getContents().values()) { @@ -532,14 +539,23 @@ public void sendContents(Collection players) { @Override public void sendSlot(int index, Player player) { - this.sendSlot(index, new Player[]{player}); + InventorySlotPacket pk = new InventorySlotPacket(); + pk.slot = index; + pk.item = this.getItem(index); + int id = player.getWindowId(this); + if (id == -1) { + this.close(player); + return; + } + pk.inventoryId = id; + player.dataPacket(pk); } @Override public void sendSlot(int index, Player... players) { InventorySlotPacket pk = new InventorySlotPacket(); pk.slot = index; - pk.item = this.getItem(index).clone(); + pk.item = this.getItem(index); for (Player player : players) { int id = player.getWindowId(this); diff --git a/src/main/java/cn/nukkit/inventory/BeaconInventory.java b/src/main/java/cn/nukkit/inventory/BeaconInventory.java index 51af284d77d..ef83bd03eb9 100644 --- a/src/main/java/cn/nukkit/inventory/BeaconInventory.java +++ b/src/main/java/cn/nukkit/inventory/BeaconInventory.java @@ -1,25 +1,35 @@ package cn.nukkit.inventory; import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; import cn.nukkit.level.Position; +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntSet; /** - * author: Rover656 + * @author Rover656 */ public class BeaconInventory extends FakeBlockUIComponent { + + /** + * Items that can be put into beacon inventory + */ + public static final IntSet ITEMS = new IntOpenHashSet(new int[]{Item.AIR, ItemID.NETHERITE_INGOT, ItemID.EMERALD, ItemID.DIAMOND, ItemID.GOLD_INGOT, ItemID. IRON_INGOT}); + public BeaconInventory(PlayerUIInventory playerUI, Position position) { super(playerUI, InventoryType.BEACON, 27, position); } @Override - public void onClose(Player who) { - super.onClose(who); + public void onOpen(Player who) { + super.onOpen(who); + who.craftingType = Player.CRAFTING_BEACON; + } - // Drop item in slot if client doesn't automatically move it to player's inventory - if (!who.isConnected()) { - this.getHolder().getLevel().dropItem(this.getHolder().add(0.5, 0.5, 0.5), this.getItem(0)); - } - this.clear(0); + @Override + public boolean allowedToAdd(Item item) { + return ITEMS.contains(item.getId()); } } diff --git a/src/main/java/cn/nukkit/inventory/BigCraftingGrid.java b/src/main/java/cn/nukkit/inventory/BigCraftingGrid.java index bcf0bdf0ca6..9cc4fed1a74 100644 --- a/src/main/java/cn/nukkit/inventory/BigCraftingGrid.java +++ b/src/main/java/cn/nukkit/inventory/BigCraftingGrid.java @@ -4,6 +4,7 @@ * @author CreeperFace */ public class BigCraftingGrid extends CraftingGrid { + BigCraftingGrid(PlayerUIInventory playerUI) { super(playerUI, 32, 9); } diff --git a/src/main/java/cn/nukkit/inventory/BlastFurnaceInventory.java b/src/main/java/cn/nukkit/inventory/BlastFurnaceInventory.java new file mode 100644 index 00000000000..bbe84def40e --- /dev/null +++ b/src/main/java/cn/nukkit/inventory/BlastFurnaceInventory.java @@ -0,0 +1,15 @@ +package cn.nukkit.inventory; + +import cn.nukkit.blockentity.BlockEntityBlastFurnace; + +public class BlastFurnaceInventory extends FurnaceInventory { + + public BlastFurnaceInventory(BlockEntityBlastFurnace furnace) { + super(furnace, InventoryType.BLAST_FURNACE); + } + + @Override + public BlockEntityBlastFurnace getHolder() { + return (BlockEntityBlastFurnace) this.holder; + } +} diff --git a/src/main/java/cn/nukkit/inventory/BrewingInventory.java b/src/main/java/cn/nukkit/inventory/BrewingInventory.java index 8d7454be766..dad52e33361 100644 --- a/src/main/java/cn/nukkit/inventory/BrewingInventory.java +++ b/src/main/java/cn/nukkit/inventory/BrewingInventory.java @@ -3,8 +3,14 @@ import cn.nukkit.blockentity.BlockEntityBrewingStand; import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; +import it.unimi.dsi.fastutil.ints.IntArrayList; + +import java.util.ArrayList; +import java.util.List; public class BrewingInventory extends ContainerInventory { + public BrewingInventory(BlockEntityBrewingStand brewingStand) { super(brewingStand, InventoryType.BREWING_STAND); } @@ -39,5 +45,67 @@ public void onSlotChange(int index, Item before, boolean send) { } this.getHolder().scheduleUpdate(); + + this.getHolder().chunk.setChanged(); + } + + @Override + public Item[] addItem(Item... slots) { + List itemSlots = new ArrayList<>(); + for (Item slot : slots) { + if (slot.getId() != 0 && slot.getCount() > 0) { + itemSlots.add(slot.clone()); + } + } + + IntArrayList emptySlots = new IntArrayList(); + + boolean isFuel = slots.length > 0 && slots[0].getId() == ItemID.BLAZE_POWDER; + for (int i = (isFuel ? 4 : 1); + i < (isFuel ? 5 : this.getSize() - 1); + ++i) { // Brewing: Separate fuel & bottles + ignore ingredient + + Item item = this.getItem(i); + if (item.getId() == Item.AIR || item.getCount() <= 0) { + emptySlots.add(i); + } + + for (Item slot : new ArrayList<>(itemSlots)) { + if (slot.equals(item) && item.getCount() < item.getMaxStackSize()) { + int amount = Math.min(item.getMaxStackSize() - item.getCount(), slot.getCount()); + amount = Math.min(amount, this.maxStackSize); + if (amount > 0) { + slot.setCount(slot.getCount() - amount); + item.setCount(item.getCount() + amount); + this.setItem(i, item); + if (slot.getCount() <= 0) { + itemSlots.remove(slot); + } + } + } + } + if (itemSlots.isEmpty()) { + break; + } + } + + if (!itemSlots.isEmpty() && !emptySlots.isEmpty()) { + for (int slotIndex : emptySlots) { + if (!itemSlots.isEmpty()) { + Item slot = itemSlots.get(0); + int amount = Math.min(slot.getMaxStackSize(), slot.getCount()); + amount = Math.min(amount, this.maxStackSize); + slot.setCount(slot.getCount() - amount); + Item item = slot.clone(); + item.setCount(amount); + this.setItem(slotIndex, item); + if (slot.getCount() <= 0) { + itemSlots.remove(slot); + } + } + } + } + + return itemSlots.toArray(new Item[0]); } -} \ No newline at end of file +} diff --git a/src/main/java/cn/nukkit/inventory/BrewingRecipe.java b/src/main/java/cn/nukkit/inventory/BrewingRecipe.java index 51017b4661c..6b14f765504 100644 --- a/src/main/java/cn/nukkit/inventory/BrewingRecipe.java +++ b/src/main/java/cn/nukkit/inventory/BrewingRecipe.java @@ -3,7 +3,6 @@ import cn.nukkit.item.Item; - public class BrewingRecipe extends MixRecipe { public BrewingRecipe(Item input, Item ingredient, Item output) { diff --git a/src/main/java/cn/nukkit/inventory/CampfireInventory.java b/src/main/java/cn/nukkit/inventory/CampfireInventory.java new file mode 100644 index 00000000000..f73bed2df07 --- /dev/null +++ b/src/main/java/cn/nukkit/inventory/CampfireInventory.java @@ -0,0 +1,115 @@ +package cn.nukkit.inventory; + +import cn.nukkit.blockentity.BlockEntityCampfire; +import cn.nukkit.item.Item; +import it.unimi.dsi.fastutil.ints.IntArrayList; + +import java.util.ArrayList; +import java.util.List; + +public class CampfireInventory extends ContainerInventory { + + public CampfireInventory(BlockEntityCampfire campfire) { + super(campfire, InventoryType.CAMPFIRE); + } + + @Override + public BlockEntityCampfire getHolder() { + return (BlockEntityCampfire) this.holder; + } + + @Override + public void onSlotChange(int index, Item before, boolean send) { + super.onSlotChange(index, before, send); + + this.getHolder().scheduleUpdate(); + this.getHolder().spawnToAll(); + + this.getHolder().chunk.setChanged(); + } + + @Override + public int getMaxStackSize() { + return 1; + } + + @Override // Max stack size 1 + public boolean canAddItem(Item item) { + int count = item.getCount(); + boolean checkDamage = item.hasMeta(); + boolean checkTag = item.getCompoundTag() != null; + int i1 = this.getSize(); + for (int i = 0; i < i1; ++i) { + Item slot = this.getItemFast(i); + if (item.equals(slot, checkDamage, checkTag)) { + int diff; + if ((diff = 1 - slot.getCount()) > 0) { + count -= diff; + } + } else if (slot.getId() == Item.AIR) { + count -= 1; + } + + if (count <= 0) { + return true; + } + } + + return false; + } + + @Override // Max stack size 1 + public Item[] addItem(Item... slots) { + List itemSlots = new ArrayList<>(); + for (Item slot : slots) { + if (slot.getId() != 0 && slot.getCount() > 0) { + itemSlots.add(slot.clone()); + } + } + + IntArrayList emptySlots = new IntArrayList(); + + for (int i = 0; i < this.getSize(); ++i) { + Item item = this.getItem(i); + if (item.getId() == Item.AIR || item.getCount() <= 0) { + emptySlots.add(i); + } + + for (Item slot : new ArrayList<>(itemSlots)) { + if (slot.equals(item) && item.getCount() < 1) { + int amount = Math.min(1 - item.getCount(), slot.getCount()); + amount = Math.min(amount, 1); + if (amount > 0) { + slot.setCount(slot.getCount() - amount); + item.setCount(item.getCount() + amount); + this.setItem(i, item); + if (slot.getCount() <= 0) { + itemSlots.remove(slot); + } + } + } + } + if (itemSlots.isEmpty()) { + break; + } + } + + if (!itemSlots.isEmpty() && !emptySlots.isEmpty()) { + for (int slotIndex : emptySlots) { + if (!itemSlots.isEmpty()) { + Item slot = itemSlots.get(0); + int amount = Math.min(1, slot.getCount()); + slot.setCount(slot.getCount() - amount); + Item item = slot.clone(); + item.setCount(amount); + this.setItem(slotIndex, item); + if (slot.getCount() <= 0) { + itemSlots.remove(slot); + } + } + } + } + + return itemSlots.toArray(new Item[0]); + } +} diff --git a/src/main/java/cn/nukkit/inventory/CampfireRecipe.java b/src/main/java/cn/nukkit/inventory/CampfireRecipe.java new file mode 100644 index 00000000000..f82b4562dc0 --- /dev/null +++ b/src/main/java/cn/nukkit/inventory/CampfireRecipe.java @@ -0,0 +1,38 @@ +package cn.nukkit.inventory; + +import cn.nukkit.item.Item; + +public class CampfireRecipe implements Recipe { + + private final Item output; + + private Item ingredient; + + public CampfireRecipe(Item result, Item ingredient) { + this.output = result.clone(); + this.ingredient = ingredient.clone(); + } + + public void setInput(Item item) { + this.ingredient = item.clone(); + } + + public Item getInput() { + return this.ingredient.clone(); + } + + @Override + public Item getResult() { + return this.output.clone(); + } + + @Override + public void registerToCraftingManager(CraftingManager manager) { + manager.registerCampfireRecipe(this); + } + + @Override + public RecipeType getType() { + return this.ingredient.hasMeta() ? RecipeType.CAMPFIRE_DATA : RecipeType.CAMPFIRE; + } +} diff --git a/src/main/java/cn/nukkit/inventory/ChestBoatInventory.java b/src/main/java/cn/nukkit/inventory/ChestBoatInventory.java new file mode 100644 index 00000000000..1d11c609a70 --- /dev/null +++ b/src/main/java/cn/nukkit/inventory/ChestBoatInventory.java @@ -0,0 +1,44 @@ +package cn.nukkit.inventory; + +import cn.nukkit.Player; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityChestBoat; +import cn.nukkit.math.Vector3; +import cn.nukkit.network.protocol.ContainerOpenPacket; + +public class ChestBoatInventory extends ContainerInventory { + + public ChestBoatInventory(EntityChestBoat holder) { + super(holder, InventoryType.CHEST_BOAT); + } + + @Override + public EntityChestBoat getHolder() { + return (EntityChestBoat) super.getHolder(); + } + + @Override + public void onOpen(Player who) { + this.viewers.add(who); + + ContainerOpenPacket pk = new ContainerOpenPacket(); + pk.windowId = who.getWindowId(this); + pk.type = InventoryType.CHEST_BOAT.getNetworkType(); + InventoryHolder holder = this.getHolder(); + if (holder != null) { + pk.x = (int) ((Vector3) holder).getX(); + pk.y = (int) ((Vector3) holder).getY(); + pk.z = (int) ((Vector3) holder).getZ(); + } else { + pk.x = pk.y = pk.z = 0; + } + + if (holder != null) { + pk.entityId = ((Entity) holder).getId(); + } + + who.dataPacket(pk); + + this.sendContents(who); + } +} diff --git a/src/main/java/cn/nukkit/inventory/ChestInventory.java b/src/main/java/cn/nukkit/inventory/ChestInventory.java index 33cb80ea98e..e206cd55032 100644 --- a/src/main/java/cn/nukkit/inventory/ChestInventory.java +++ b/src/main/java/cn/nukkit/inventory/ChestInventory.java @@ -1,13 +1,15 @@ package cn.nukkit.inventory; import cn.nukkit.Player; +import cn.nukkit.block.BlockTrappedChest; import cn.nukkit.blockentity.BlockEntityChest; +import cn.nukkit.item.Item; import cn.nukkit.level.Level; import cn.nukkit.network.protocol.BlockEventPacket; import cn.nukkit.network.protocol.LevelSoundEventPacket; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ChestInventory extends ContainerInventory { @@ -39,6 +41,10 @@ public void onOpen(Player who) { if (level != null) { level.addLevelSoundEvent(this.getHolder().add(0.5, 0.5, 0.5), LevelSoundEventPacket.SOUND_CHEST_OPEN); level.addChunkPacket((int) this.getHolder().getX() >> 4, (int) this.getHolder().getZ() >> 4, pk); + + if (this.getHolder().getBlock() instanceof BlockTrappedChest) { + level.updateAroundRedstone(this.getHolder(), null); + } } } } @@ -61,6 +67,15 @@ public void onClose(Player who) { } super.onClose(who); + + if (this.getViewers().isEmpty()) { + Level level = this.getHolder().getLevel(); + if (level != null) { + if (this.getHolder().getBlock() instanceof BlockTrappedChest) { + level.updateAroundRedstone(this.getHolder(), null); + } + } + } } public void setDoubleInventory(DoubleChestInventory doubleInventory) { @@ -79,4 +94,11 @@ public void sendSlot(int index, Player... players) { super.sendSlot(index, players); } } + + @Override + public void onSlotChange(int index, Item before, boolean send) { + super.onSlotChange(index, before, send); + + this.getHolder().chunk.setChanged(); + } } diff --git a/src/main/java/cn/nukkit/inventory/ContainerInventory.java b/src/main/java/cn/nukkit/inventory/ContainerInventory.java index 0b8af477475..99a4787f9fe 100644 --- a/src/main/java/cn/nukkit/inventory/ContainerInventory.java +++ b/src/main/java/cn/nukkit/inventory/ContainerInventory.java @@ -11,7 +11,7 @@ import java.util.Map; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class ContainerInventory extends BaseInventory { @@ -45,6 +45,7 @@ public void onOpen(Player who) { } else { pk.x = pk.y = pk.z = 0; } + if (holder instanceof Entity) { pk.entityId = ((Entity) holder).getId(); } diff --git a/src/main/java/cn/nukkit/inventory/ContainerRecipe.java b/src/main/java/cn/nukkit/inventory/ContainerRecipe.java index 01d46624454..72226dfb721 100644 --- a/src/main/java/cn/nukkit/inventory/ContainerRecipe.java +++ b/src/main/java/cn/nukkit/inventory/ContainerRecipe.java @@ -3,6 +3,7 @@ import cn.nukkit.item.Item; public class ContainerRecipe extends MixRecipe { + public ContainerRecipe(Item input, Item ingredient, Item output) { super(input, ingredient, output); } diff --git a/src/main/java/cn/nukkit/inventory/CraftingGrid.java b/src/main/java/cn/nukkit/inventory/CraftingGrid.java index 9cd6eab3522..125176071df 100644 --- a/src/main/java/cn/nukkit/inventory/CraftingGrid.java +++ b/src/main/java/cn/nukkit/inventory/CraftingGrid.java @@ -1,7 +1,7 @@ package cn.nukkit.inventory; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class CraftingGrid extends PlayerUIComponent { diff --git a/src/main/java/cn/nukkit/inventory/CraftingManager.java b/src/main/java/cn/nukkit/inventory/CraftingManager.java index d1b5601761d..b4411d0a677 100644 --- a/src/main/java/cn/nukkit/inventory/CraftingManager.java +++ b/src/main/java/cn/nukkit/inventory/CraftingManager.java @@ -1,23 +1,22 @@ package cn.nukkit.inventory; import cn.nukkit.Server; -import cn.nukkit.item.Item; +import cn.nukkit.item.*; import cn.nukkit.network.protocol.CraftingDataPacket; import cn.nukkit.network.protocol.DataPacket; -import cn.nukkit.utils.BinaryStream; -import cn.nukkit.utils.Config; -import cn.nukkit.utils.MainLogger; -import cn.nukkit.utils.Utils; +import cn.nukkit.utils.*; import io.netty.util.collection.CharObjectHashMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import lombok.Getter; import lombok.extern.log4j.Log4j2; import java.io.File; import java.io.InputStream; import java.util.*; +import java.util.zip.Deflater; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @Log4j2 @@ -25,18 +24,21 @@ public class CraftingManager { public final Collection recipes = new ArrayDeque<>(); - public static DataPacket packet = null; + public static DataPacket packet; protected final Map> shapedRecipes = new Int2ObjectOpenHashMap<>(); - - public final Map furnaceRecipes = new Int2ObjectOpenHashMap<>(); + protected final Map> shapelessRecipes = new Int2ObjectOpenHashMap<>(); public final Map multiRecipes = new HashMap<>(); - + public final Map furnaceRecipes = new Int2ObjectOpenHashMap<>(); public final Map brewingRecipes = new Int2ObjectOpenHashMap<>(); public final Map containerRecipes = new Int2ObjectOpenHashMap<>(); + @Getter + private final Map campfireRecipes = new Int2ObjectOpenHashMap<>(); // Server only + @Getter + private final Map smithingRecipes = new Int2ObjectOpenHashMap<>(); private static int RECIPE_COUNT = 0; - protected final Map> shapelessRecipes = new Int2ObjectOpenHashMap<>(); + static int NEXT_NETWORK_ID; public static final Comparator recipeComparator = (i1, i2) -> { if (i1.getId() > i2.getId()) { @@ -67,9 +69,36 @@ public CraftingManager() { Config customRecipes = new Config(filePath, Config.JSON); this.loadRecipes(customRecipes); } + + this.registerSmithingRecipes(); + this.rebuildPacket(); - MainLogger.getLogger().info("Loaded " + this.recipes.size() + " recipes"); + MainLogger.getLogger().info("Successfully loaded " + this.recipes.size() + " recipes"); + } + + private void registerSmithingRecipes() { + ConfigSection smithing = new Config(Config.YAML).loadFromStream(Server.class.getClassLoader().getResourceAsStream("smithing.json")).getRootSection(); + for (Map recipe : (List>) smithing.get((Object) "smithing")) { + List outputs = ((List) recipe.get("output")); + if (outputs.size() > 1) { + continue; + } + + String recipeId = (String) recipe.get("id"); + + Map first = outputs.get(0); + Item item = Item.get(RuntimeItems.getMapping().fromIdentifier((String) first.get("id")).getLegacyId(), 0, 1); + + List ingredients = new ArrayList<>(); + for (Map ingredient : ((List) recipe.get("input"))) { + Item ing = Item.get(RuntimeItems.getMapping().fromIdentifier((String) ingredient.get("id")).getLegacyId(), 0, 1); + ingredients.add(ing); + } + + this.registerRecipe(new SmithingRecipe(recipeId, 0, ingredients, item)); + this.registerRecipe(new SmithingRecipe(recipeId, 0, ingredients, item)); + } } @SuppressWarnings("unchecked") @@ -77,7 +106,6 @@ private void loadRecipes(Config config) { List recipes = config.getMapList("recipes"); MainLogger.getLogger().info("Loading recipes..."); for (Map recipe : recipes) { - top: try { switch (Utils.toInt(recipe.get("type"))) { case 0: @@ -99,8 +127,7 @@ private void loadRecipes(Config config) { // Bake sorted list sorted.sort(recipeComparator); - Item resultItem = Item.fromJson(first, true); - if (resultItem == null) continue; // TODO: remove when new blocks are supported + Item resultItem = Item.fromJson(first); this.registerRecipe(new ShapelessRecipe(null, Utils.toInt(recipe.get("priority")), resultItem, sorted)); // null recipeId will be replaced with recipe uuid break; case 1: @@ -120,13 +147,6 @@ private void loadRecipes(Config config) { for (Map.Entry> ingredientEntry : input.entrySet()) { char ingredientChar = ingredientEntry.getKey().charAt(0); Item ingredient = Item.fromJson(ingredientEntry.getValue()); - - // TODO: update recipes - if (ingredient.getId() == Item.PLANKS && Utils.toInt(ingredientEntry.getValue().getOrDefault("damage", 0)) == -1) { - createLegacyPlanksRecipe(recipe, first); - break top; - } - ingredients.put(ingredientChar, ingredient); } @@ -134,28 +154,26 @@ private void loadRecipes(Config config) { extraResults.add(Item.fromJson(data)); } - resultItem = Item.fromJson(first, true); - if (resultItem == null) continue; // TODO: remove when new blocks are supported + resultItem = Item.fromJson(first); this.registerRecipe(new ShapedRecipe(null, Utils.toInt(recipe.get("priority")), resultItem, shape, ingredients, extraResults)); break; - case 2: case 3: craftingBlock = (String) recipe.get("block"); - if (!"furnace".equals(craftingBlock)) { - // Ignore other recipes than furnaces + if (!"furnace".equals(craftingBlock) && !"campfire".equals(craftingBlock)) { continue; } Map resultMap = (Map) recipe.get("output"); - resultItem = Item.fromJson(resultMap, true); - if (resultItem == null) continue; // TODO: remove when new blocks are supported - Item inputItem; - try { - Map inputMap = (Map) recipe.get("input"); - inputItem = Item.fromJson(inputMap); - } catch (Exception old) { - inputItem = Item.get(Utils.toInt(recipe.get("inputId")), recipe.containsKey("inputDamage") ? Utils.toInt(recipe.get("inputDamage")) : -1, 1); + resultItem = Item.fromJson(resultMap); + Map inputMap = (Map) recipe.get("input"); + Item inputItem = Item.fromJson(inputMap); + switch (craftingBlock) { + case "furnace": + this.registerRecipe(new FurnaceRecipe(resultItem, inputItem)); + break; + case "campfire": + this.registerRecipe(new CampfireRecipe(resultItem, inputItem)); + break; } - this.registerRecipe(new FurnaceRecipe(resultItem, inputItem)); break; case 4: this.registerRecipe(new MultiRecipe(UUID.fromString((String) recipe.get("uuid")))); @@ -193,30 +211,6 @@ private void loadRecipes(Config config) { } } - private void createLegacyPlanksRecipe(Map recipe, Map first) { - List outputs = (List) recipe.get("output"); - String[] shape = ((List) recipe.get("shape")).toArray(new String[0]); - List extraResults = new ArrayList<>(); - for (Map data : outputs) { - extraResults.add(Item.fromJson(data)); - } - for (int planksMeta = 0; planksMeta <= 5; planksMeta++) { - Map ingredients = new CharObjectHashMap<>(); - Map> input = (Map) recipe.get("input"); - for (Map.Entry> ingredientEntry : input.entrySet()) { - char ingredientChar = ingredientEntry.getKey().charAt(0); - ingredientEntry.getValue().put("damage", 0); - Item ingredient = Item.fromJson(ingredientEntry.getValue()); - if (ingredient.getId() == Item.PLANKS) { - ingredient.setDamage(planksMeta); - } - ingredients.put(ingredientChar, ingredient); - } - this.registerRecipe( - new ShapedRecipe(null, Utils.toInt(recipe.get("priority")), Item.fromJson(first), shape, ingredients, extraResults)); - } - } - public void rebuildPacket() { CraftingDataPacket pk = new CraftingDataPacket(); pk.cleanRecipes = true; @@ -245,9 +239,7 @@ public void rebuildPacket() { } pk.tryEncode(); - // TODO: find out whats wrong with compression - // packet = pk.compress(Deflater.BEST_COMPRESSION); - packet = pk; + packet = pk.compress(Deflater.BEST_COMPRESSION); } public Collection getRecipes() { @@ -265,7 +257,7 @@ public FurnaceRecipe matchFurnaceRecipe(Item input) { } private static UUID getMultiItemHash(Collection items) { - BinaryStream stream = new BinaryStream(); + BinaryStream stream = new BinaryStream(new byte[5 * items.size()]).reset(); for (Item item : items) { stream.putVarInt(getFullItemHash(item)); } @@ -296,7 +288,6 @@ public void registerShapedRecipe(ShapedRecipe recipe) { map.put(getMultiItemHash(inputList), recipe); } - public void registerRecipe(Recipe recipe) { if (recipe instanceof CraftingRecipe) { UUID id = Utils.dataToUUID(String.valueOf(++RECIPE_COUNT), String.valueOf(recipe.getResult().getId()), String.valueOf(recipe.getResult().getDamage()), String.valueOf(recipe.getResult().getCount()), Arrays.toString(recipe.getResult().getCompoundTag())); @@ -319,8 +310,10 @@ public void registerShapelessRecipe(ShapelessRecipe recipe) { map.put(hash, recipe); } - private static int getPotionHash(int ingredientId, int potionType) { - return (ingredientId << 15) | potionType; + private static int getPotionHash(Item ingredient, Item potion) { + int ingredientHash = ((ingredient.getId() & 0x3FF) << 6) | (ingredient.getDamage() & 0x3F); + int potionHash = ((potion.getId() & 0x3FF) << 6) | (potion.getDamage() & 0x3F); + return ingredientHash << 16 | potionHash; } private static int getContainerHash(int ingredientId, int containerId) { @@ -331,7 +324,7 @@ public void registerBrewingRecipe(BrewingRecipe recipe) { Item input = recipe.getIngredient(); Item potion = recipe.getInput(); - this.brewingRecipes.put(getPotionHash(input.getId(), potion.getDamage()), recipe); + this.brewingRecipes.put(getPotionHash(input, potion), recipe); } public void registerContainerRecipe(ContainerRecipe recipe) { @@ -344,7 +337,7 @@ public void registerContainerRecipe(ContainerRecipe recipe) { public BrewingRecipe matchBrewingRecipe(Item input, Item potion) { int id = potion.getId(); if (id == Item.POTION || id == Item.SPLASH_POTION || id == Item.LINGERING_POTION) { - return this.brewingRecipes.get(getPotionHash(input.getId(), potion.getDamage())); + return this.brewingRecipes.get(getPotionHash(input, potion)); } return null; @@ -407,6 +400,12 @@ public CraftingRecipe matchRecipe(List inputList, Item primaryOutput, List return null; } + public CampfireRecipe matchCampfireRecipe(Item input) { + CampfireRecipe recipe = this.campfireRecipes.get(getItemHash(input)); + if (recipe == null) recipe = this.campfireRecipes.get(getItemHash(input.getId(), 0)); + return recipe; + } + private boolean matchItemsAccumulation(CraftingRecipe recipe, List inputList, Item primaryOutput, List extraOutputList) { Item recipeResult = recipe.getResult(); if (primaryOutput.equals(recipeResult, recipeResult.hasMeta(), recipeResult.hasCompoundTag()) && primaryOutput.getCount() % recipeResult.getCount() == 0) { @@ -416,25 +415,21 @@ private boolean matchItemsAccumulation(CraftingRecipe recipe, List inputLi return false; } + public SmithingRecipe matchSmithingRecipe(Item equipment, Item ingredient) { + return this.smithingRecipes.get(getContainerHash(ingredient.getId(), equipment.getId())); + } + public void registerMultiRecipe(MultiRecipe recipe) { this.multiRecipes.put(recipe.getId(), recipe); } - public static class Entry { - final int resultItemId; - final int resultMeta; - final int ingredientItemId; - final int ingredientMeta; - final String recipeShape; - final int resultAmount; - - public Entry(int resultItemId, int resultMeta, int ingredientItemId, int ingredientMeta, String recipeShape, int resultAmount) { - this.resultItemId = resultItemId; - this.resultMeta = resultMeta; - this.ingredientItemId = ingredientItemId; - this.ingredientMeta = ingredientMeta; - this.recipeShape = recipeShape; - this.resultAmount = resultAmount; - } + public void registerCampfireRecipe(CampfireRecipe recipe) { + this.campfireRecipes.put(getItemHash(recipe.getInput()), recipe); + } + + public void registerSmithingRecipe(SmithingRecipe recipe) { + Item input = recipe.getIngredient(); + Item potion = recipe.getEquipment(); + this.smithingRecipes.put(getContainerHash(input.getId(), potion.getId()), recipe); } } diff --git a/src/main/java/cn/nukkit/inventory/CraftingRecipe.java b/src/main/java/cn/nukkit/inventory/CraftingRecipe.java index 2c21e8fbccf..550c1010a9e 100644 --- a/src/main/java/cn/nukkit/inventory/CraftingRecipe.java +++ b/src/main/java/cn/nukkit/inventory/CraftingRecipe.java @@ -28,7 +28,7 @@ public interface CraftingRecipe extends Recipe { * Returns whether the specified list of crafting grid inputs and outputs matches this recipe. Outputs DO NOT * include the primary result item. * - * @param inputList list of items taken from the crafting grid + * @param inputList list of items taken from the crafting grid * @param extraOutputList list of items put back into the crafting grid (secondary results) * @return bool */ diff --git a/src/main/java/cn/nukkit/inventory/CustomInventory.java b/src/main/java/cn/nukkit/inventory/CustomInventory.java index 2d93e24bdc9..0caed17a772 100644 --- a/src/main/java/cn/nukkit/inventory/CustomInventory.java +++ b/src/main/java/cn/nukkit/inventory/CustomInventory.java @@ -5,10 +5,11 @@ import java.util.Map; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class CustomInventory extends ContainerInventory { + public CustomInventory(InventoryHolder holder, InventoryType type) { super(holder, type); } diff --git a/src/main/java/cn/nukkit/inventory/DispenserInventory.java b/src/main/java/cn/nukkit/inventory/DispenserInventory.java new file mode 100644 index 00000000000..ef5b71020ed --- /dev/null +++ b/src/main/java/cn/nukkit/inventory/DispenserInventory.java @@ -0,0 +1,23 @@ +package cn.nukkit.inventory; + +import cn.nukkit.blockentity.BlockEntityDispenser; +import cn.nukkit.item.Item; + +public class DispenserInventory extends ContainerInventory { + + public DispenserInventory(BlockEntityDispenser dispenser) { + super(dispenser, InventoryType.DISPENSER); + } + + @Override + public BlockEntityDispenser getHolder() { + return (BlockEntityDispenser) super.getHolder(); + } + + @Override + public void onSlotChange(int index, Item before, boolean send) { + super.onSlotChange(index, before, send); + + this.getHolder().chunk.setChanged(); + } +} diff --git a/src/main/java/cn/nukkit/inventory/DoubleChestInventory.java b/src/main/java/cn/nukkit/inventory/DoubleChestInventory.java index 378db5fd058..30c1a56f471 100644 --- a/src/main/java/cn/nukkit/inventory/DoubleChestInventory.java +++ b/src/main/java/cn/nukkit/inventory/DoubleChestInventory.java @@ -5,14 +5,14 @@ import cn.nukkit.item.Item; import cn.nukkit.level.Level; import cn.nukkit.network.protocol.BlockEventPacket; -import cn.nukkit.network.protocol.InventorySlotPacket; import cn.nukkit.network.protocol.LevelSoundEventPacket; +import cn.nukkit.network.protocol.InventorySlotPacket; import java.util.HashMap; import java.util.Map; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class DoubleChestInventory extends ContainerInventory implements InventoryHolder { @@ -62,6 +62,11 @@ public Item getItem(int index) { return index < this.left.getSize() ? this.left.getItem(index) : this.right.getItem(index - this.right.getSize()); } + @Override + public Item getItemFast(int index) { + return index < this.left.getSize() ? this.left.getItemFast(index) : this.right.getItemFast(index - this.right.getSize()); + } + @Override public boolean setItem(int index, Item item, boolean send) { return index < this.left.getSize() ? this.left.setItem(index, item, send) : this.right.setItem(index - this.right.getSize(), item, send); @@ -115,28 +120,24 @@ public void onOpen(Player who) { this.right.viewers.add(who); if (this.getViewers().size() == 1) { - BlockEventPacket pk1 = new BlockEventPacket(); - pk1.x = (int) this.left.getHolder().getX(); - pk1.y = (int) this.left.getHolder().getY(); - pk1.z = (int) this.left.getHolder().getZ(); - pk1.case1 = 1; - pk1.case2 = 2; Level level = this.left.getHolder().getLevel(); if (level != null) { + BlockEventPacket pk1 = new BlockEventPacket(); + pk1.x = (int) this.left.getHolder().getX(); + pk1.y = (int) this.left.getHolder().getY(); + pk1.z = (int) this.left.getHolder().getZ(); + pk1.case1 = 1; + pk1.case2 = 2; + + BlockEventPacket pk2 = new BlockEventPacket(); + pk2.x = (int) this.right.getHolder().getX(); + pk2.y = (int) this.right.getHolder().getY(); + pk2.z = (int) this.right.getHolder().getZ(); + pk2.case1 = 1; + pk2.case2 = 2; + level.addLevelSoundEvent(this.left.getHolder().add(0.5, 0.5, 0.5), LevelSoundEventPacket.SOUND_CHEST_OPEN); level.addChunkPacket((int) this.left.getHolder().getX() >> 4, (int) this.left.getHolder().getZ() >> 4, pk1); - } - - BlockEventPacket pk2 = new BlockEventPacket(); - pk2.x = (int) this.right.getHolder().getX(); - pk2.y = (int) this.right.getHolder().getY(); - pk2.z = (int) this.right.getHolder().getZ(); - pk2.case1 = 1; - pk2.case2 = 2; - - level = this.right.getHolder().getLevel(); - if (level != null) { - level.addLevelSoundEvent(this.right.getHolder().add(0.5, 0.5, 0.5), LevelSoundEventPacket.SOUND_CHEST_OPEN); level.addChunkPacket((int) this.right.getHolder().getX() >> 4, (int) this.right.getHolder().getZ() >> 4, pk2); } } @@ -145,29 +146,24 @@ public void onOpen(Player who) { @Override public void onClose(Player who) { if (this.getViewers().size() == 1) { - BlockEventPacket pk1 = new BlockEventPacket(); - pk1.x = (int) this.right.getHolder().getX(); - pk1.y = (int) this.right.getHolder().getY(); - pk1.z = (int) this.right.getHolder().getZ(); - pk1.case1 = 1; - pk1.case2 = 0; - Level level = this.right.getHolder().getLevel(); if (level != null) { - level.addLevelSoundEvent(this.right.getHolder().add(0.5, 0.5, 0.5), LevelSoundEventPacket.SOUND_CHEST_CLOSED); - level.addChunkPacket((int) this.right.getHolder().getX() >> 4, (int) this.right.getHolder().getZ() >> 4, pk1); - } + BlockEventPacket pk1 = new BlockEventPacket(); + pk1.x = (int) this.right.getHolder().getX(); + pk1.y = (int) this.right.getHolder().getY(); + pk1.z = (int) this.right.getHolder().getZ(); + pk1.case1 = 1; + pk1.case2 = 0; + + BlockEventPacket pk2 = new BlockEventPacket(); + pk2.x = (int) this.left.getHolder().getX(); + pk2.y = (int) this.left.getHolder().getY(); + pk2.z = (int) this.left.getHolder().getZ(); + pk2.case1 = 1; + pk2.case2 = 0; - BlockEventPacket pk2 = new BlockEventPacket(); - pk2.x = (int) this.left.getHolder().getX(); - pk2.y = (int) this.left.getHolder().getY(); - pk2.z = (int) this.left.getHolder().getZ(); - pk2.case1 = 1; - pk2.case2 = 0; - - level = this.left.getHolder().getLevel(); - if (level != null) { level.addLevelSoundEvent(this.left.getHolder().add(0.5, 0.5, 0.5), LevelSoundEventPacket.SOUND_CHEST_CLOSED); + level.addChunkPacket((int) this.right.getHolder().getX() >> 4, (int) this.right.getHolder().getZ() >> 4, pk1); level.addChunkPacket((int) this.left.getHolder().getX() >> 4, (int) this.left.getHolder().getZ() >> 4, pk2); } } @@ -200,4 +196,12 @@ public void sendSlot(Inventory inv, int index, Player... players) { player.dataPacket(pk); } } + + @Override + public void onSlotChange(int index, Item before, boolean send) { + super.onSlotChange(index, before, send); + + this.left.getHolder().chunk.setChanged(); + this.right.getHolder().chunk.setChanged(); + } } diff --git a/src/main/java/cn/nukkit/inventory/DropperInventory.java b/src/main/java/cn/nukkit/inventory/DropperInventory.java new file mode 100644 index 00000000000..b80f79b0435 --- /dev/null +++ b/src/main/java/cn/nukkit/inventory/DropperInventory.java @@ -0,0 +1,23 @@ +package cn.nukkit.inventory; + +import cn.nukkit.blockentity.BlockEntityDropper; +import cn.nukkit.item.Item; + +public class DropperInventory extends ContainerInventory { + + public DropperInventory(BlockEntityDropper dropper) { + super(dropper, InventoryType.DROPPER); + } + + @Override + public BlockEntityDropper getHolder() { + return (BlockEntityDropper) super.getHolder(); + } + + @Override + public void onSlotChange(int index, Item before, boolean send) { + super.onSlotChange(index, before, send); + + this.getHolder().chunk.setChanged(); + } +} diff --git a/src/main/java/cn/nukkit/inventory/EnchantInventory.java b/src/main/java/cn/nukkit/inventory/EnchantInventory.java index 16cdf629830..0f08ed569d0 100644 --- a/src/main/java/cn/nukkit/inventory/EnchantInventory.java +++ b/src/main/java/cn/nukkit/inventory/EnchantInventory.java @@ -4,9 +4,8 @@ import cn.nukkit.item.Item; import cn.nukkit.level.Position; - /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantInventory extends FakeBlockUIComponent { @@ -24,19 +23,6 @@ public void onOpen(Player who) { who.craftingType = Player.CRAFTING_ENCHANT; } - @Override - public void onClose(Player who) { - super.onClose(who); - if (this.getViewers().size() == 0) { - for (int i = 0; i < 2; ++i) { - who.getInventory().addItem(this.getItem(i)); - this.clear(i); - } - } - who.craftingType = Player.CRAFTING_SMALL; - who.resetCraftingGridType(); - } - public Item getInputSlot() { return this.getItem(0); } diff --git a/src/main/java/cn/nukkit/inventory/EntityArmorInventory.java b/src/main/java/cn/nukkit/inventory/EntityArmorInventory.java new file mode 100644 index 00000000000..9a856f6907d --- /dev/null +++ b/src/main/java/cn/nukkit/inventory/EntityArmorInventory.java @@ -0,0 +1,137 @@ +package cn.nukkit.inventory; + +import cn.nukkit.Player; +import cn.nukkit.entity.item.EntityArmorStand; +import cn.nukkit.item.Item; +import cn.nukkit.network.protocol.InventoryContentPacket; +import cn.nukkit.network.protocol.InventorySlotPacket; +import cn.nukkit.network.protocol.MobArmorEquipmentPacket; + +import java.util.HashSet; +import java.util.Set; + +public class EntityArmorInventory extends BaseInventory { + + private final EntityArmorStand entityLiving; + + private final Set viewers = new HashSet<>(); + + public static final int SLOT_HEAD = 0; + public static final int SLOT_CHEST = 1; + public static final int SLOT_LEGS = 2; + public static final int SLOT_FEET = 3; + + public EntityArmorInventory(EntityArmorStand entity) { + super(entity, InventoryType.ENTITY_ARMOR); + this.entityLiving = entity; + } + + @Override + public InventoryHolder getHolder() { + return this.holder; + } + + @Override + public String getName() { + return "Entity Armor"; + } + + @Override + public int getSize() { + return 4; + } + + public Item getHelmet() { + return this.getItem(SLOT_HEAD); + } + + public Item getChestplate() { + return this.getItem(SLOT_CHEST); + } + + public Item getLeggings() { + return this.getItem(SLOT_LEGS); + } + + public Item getBoots() { + return this.getItem(SLOT_FEET); + } + + public void setHelmet(Item item) { + this.setItem(SLOT_CHEST, item); + } + + public void setChestplate(Item item) { + this.setItem(SLOT_CHEST, item); + } + + public void setLeggings(Item item) { + this.setItem(SLOT_LEGS, item); + } + + public void setBoots(Item item) { + this.setItem(SLOT_FEET, item); + } + + @Override + public void sendSlot(int index, Player... players) { + for (Player player : players) { + this.sendSlot(index, player); + } + } + + @Override + public void sendSlot(int index, Player player) { + MobArmorEquipmentPacket mobArmorEquipmentPacket = new MobArmorEquipmentPacket(); + mobArmorEquipmentPacket.eid = this.entityLiving.getId(); + mobArmorEquipmentPacket.slots = new Item[]{this.getHelmet(), this.getChestplate(), this.getLeggings(), this.getBoots()}; + + if (player == this.holder) { + InventorySlotPacket inventorySlotPacket = new InventorySlotPacket(); + inventorySlotPacket.inventoryId = player.getWindowId(this); + inventorySlotPacket.slot = index; + inventorySlotPacket.item = this.getItem(index); + player.dataPacket(inventorySlotPacket); + } else { + player.dataPacket(mobArmorEquipmentPacket); + } + } + + @Override + public void sendContents(Player... players) { + for (Player player : players) { + this.sendContents(player); + } + } + + @Override + public void sendContents(Player player) { + MobArmorEquipmentPacket mobArmorEquipmentPacket = new MobArmorEquipmentPacket(); + mobArmorEquipmentPacket.eid = this.entityLiving.getId(); + mobArmorEquipmentPacket.slots = new Item[]{this.getHelmet(), this.getChestplate(), this.getLeggings(), this.getBoots()}; + + if (player == this.holder) { + InventoryContentPacket inventoryContentPacket = new InventoryContentPacket(); + inventoryContentPacket.inventoryId = player.getWindowId(this); + inventoryContentPacket.slots = new Item[]{this.getHelmet(), this.getChestplate(), this.getLeggings(), this.getBoots()}; + player.dataPacket(inventoryContentPacket); + } else { + player.dataPacket(mobArmorEquipmentPacket); + } + } + + @Override + public void onOpen(Player who) { + this.viewers.add(who); + } + + @Override + public void onClose(Player who) { + this.viewers.remove(who); + } + + @Override + public Set getViewers() { + return this.viewers; + } +} diff --git a/src/main/java/cn/nukkit/inventory/EntityEquipmentInventory.java b/src/main/java/cn/nukkit/inventory/EntityEquipmentInventory.java new file mode 100644 index 00000000000..3109fe0b1e7 --- /dev/null +++ b/src/main/java/cn/nukkit/inventory/EntityEquipmentInventory.java @@ -0,0 +1,80 @@ +package cn.nukkit.inventory; + +import cn.nukkit.Player; +import cn.nukkit.entity.item.EntityArmorStand; +import cn.nukkit.item.Item; +import cn.nukkit.network.protocol.MobEquipmentPacket; + +public class EntityEquipmentInventory extends BaseInventory { + + private final EntityArmorStand entityLiving; + + private static final int MAINHAND = 0; + private static final int OFFHAND = 1; + + public EntityEquipmentInventory(EntityArmorStand entity) { + super(entity, InventoryType.ENTITY_EQUIPMENT); + this.entityLiving = entity; + } + + + @Override + public String getName() { + return "Entity Equipment"; + } + + @Override + public int getSize() { + return 2; + } + + @Override + public InventoryHolder getHolder() { + return this.holder; + } + + @Override + public void sendSlot(int index, Player... players) { + for (Player player : players) { + this.sendSlot(index, player); + } + } + + @Override + public void sendSlot(int index, Player player) { + MobEquipmentPacket mobEquipmentPacket = new MobEquipmentPacket(); + mobEquipmentPacket.eid = this.entityLiving.getId(); + mobEquipmentPacket.inventorySlot = mobEquipmentPacket.hotbarSlot = index; + mobEquipmentPacket.item = this.getItem(index); + player.dataPacket(mobEquipmentPacket); + } + + public Item getItemInHand() { + return this.getItem(MAINHAND); + } + + public Item getOffHandItem() { + return this.getItem(OFFHAND); + } + + public boolean setItemInHand(Item item, boolean send) { + return this.setItem(MAINHAND, item, send); + } + + public boolean setOffhandItem(Item item, boolean send) { + return this.setItem(OFFHAND, item, send); + } + + @Override + public void sendContents(Player target) { + this.sendSlot(MAINHAND, target); + this.sendSlot(OFFHAND, target); + } + + @Override + public void sendContents(Player... target) { + for (Player player : target) { + this.sendContents(player); + } + } +} diff --git a/src/main/java/cn/nukkit/inventory/FakeBlockMenu.java b/src/main/java/cn/nukkit/inventory/FakeBlockMenu.java index fab31b5e7fc..574c75e5f52 100644 --- a/src/main/java/cn/nukkit/inventory/FakeBlockMenu.java +++ b/src/main/java/cn/nukkit/inventory/FakeBlockMenu.java @@ -3,7 +3,7 @@ import cn.nukkit.level.Position; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class FakeBlockMenu extends Position implements InventoryHolder { diff --git a/src/main/java/cn/nukkit/inventory/FakeBlockUIComponent.java b/src/main/java/cn/nukkit/inventory/FakeBlockUIComponent.java index 0c802b22460..baccee9334c 100644 --- a/src/main/java/cn/nukkit/inventory/FakeBlockUIComponent.java +++ b/src/main/java/cn/nukkit/inventory/FakeBlockUIComponent.java @@ -9,6 +9,7 @@ import cn.nukkit.network.protocol.ContainerOpenPacket; public class FakeBlockUIComponent extends PlayerUIComponent { + private final InventoryType type; FakeBlockUIComponent(PlayerUIInventory playerUI, InventoryType type, int offset, Position position) { @@ -35,14 +36,6 @@ public boolean open(Player who) { return true; } - @Override - public void close(Player who) { - InventoryCloseEvent ev = new InventoryCloseEvent(this, who); - who.getServer().getPluginManager().callEvent(ev); - - this.onClose(who); - } - @Override public void onOpen(Player who) { super.onOpen(who); @@ -65,10 +58,20 @@ public void onOpen(Player who) { @Override public void onClose(Player who) { + who.resetCraftingGridType(); // Handles moving of UI inventory contents + ContainerClosePacket pk = new ContainerClosePacket(); pk.windowId = who.getWindowId(this); pk.wasServerInitiated = who.getClosingWindowId() != pk.windowId; who.dataPacket(pk); + super.onClose(who); } + + @Override + public void close(Player who) { + InventoryCloseEvent ev = new InventoryCloseEvent(this, who); + who.getServer().getPluginManager().callEvent(ev); + this.onClose(who); + } } diff --git a/src/main/java/cn/nukkit/inventory/Fuel.java b/src/main/java/cn/nukkit/inventory/Fuel.java index 87bffb2c581..e974e033d07 100644 --- a/src/main/java/cn/nukkit/inventory/Fuel.java +++ b/src/main/java/cn/nukkit/inventory/Fuel.java @@ -1,21 +1,23 @@ package cn.nukkit.inventory; +import cn.nukkit.block.BlockID; import cn.nukkit.item.Item; import java.util.Map; import java.util.TreeMap; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class Fuel { + public static final Map duration = new TreeMap<>(); static { duration.put(Item.COAL, (short) 1600); duration.put(Item.COAL_BLOCK, (short) 16000); - duration.put(Item.TRUNK, (short) 300); + duration.put(Item.WOOD, (short) 300); duration.put(Item.WOODEN_PLANKS, (short) 300); duration.put(Item.SAPLING, (short) 100); duration.put(Item.WOODEN_AXE, (short) 200); @@ -55,6 +57,13 @@ public abstract class Fuel { duration.put(Item.WOOD_SLAB, (short) 300); duration.put(Item.DOUBLE_WOOD_SLAB, (short) 300); duration.put(Item.BOAT, (short) 1200); + duration.put(Item.ACACIA_CHEST_BOAT, (short) 1200); + duration.put(Item.BIRCH_CHEST_BOAT, (short) 1200); + duration.put(Item.JUNGLE_CHEST_BOAT, (short) 1200); + duration.put(Item.DARK_OAK_CHEST_BOAT, (short) 1200); + duration.put(Item.MANGROVE_CHEST_BOAT, (short) 1200); + duration.put(Item.OAK_CHEST_BOAT, (short) 1200); + duration.put(Item.SPRUCE_CHEST_BOAT, (short) 1200); duration.put(Item.BLAZE_ROD, (short) 2400); duration.put(Item.BROWN_MUSHROOM_BLOCK, (short) 300); duration.put(Item.RED_MUSHROOM_BLOCK, (short) 300); @@ -67,7 +76,51 @@ public abstract class Fuel { duration.put(Item.ACACIA_DOOR, (short) 200); duration.put(Item.DARK_OAK_DOOR, (short) 200); duration.put(Item.BANNER, (short) 300); + duration.put(Item.CROSSBOW, (short) 200); duration.put(Item.DEAD_BUSH, (short) 100); duration.put(Item.SIGN, (short) 200); + duration.put(Item.ACACIA_SIGN, (short) 200); + duration.put(Item.BIRCH_SIGN, (short) 200); + duration.put(Item.SPRUCE_SIGN, (short) 200); + duration.put(Item.DARKOAK_SIGN, (short) 200); + duration.put(Item.JUNGLE_SIGN, (short) 200); + + /* New blocks use negative IDs in their item form */ + duration.put(255 - BlockID.DRIED_KELP_BLOCK, (short) 4000); + duration.put(255 - BlockID.SCAFFOLDING, (short) 50); + duration.put(255 - BlockID.BEE_NEST, (short) 300); + duration.put(255 - BlockID.BEEHIVE, (short) 300); + duration.put(255 - BlockID.BAMBOO, (short) 50); + duration.put(255 - BlockID.BARREL, (short) 300); + duration.put(255 - BlockID.LECTERN, (short) 300); + duration.put(255 - BlockID.CARTOGRAPHY_TABLE, (short) 300); + duration.put(255 - BlockID.FLETCHING_TABLE, (short) 300); + duration.put(255 - BlockID.SMITHING_TABLE, (short) 300); + duration.put(255 - BlockID.COMPOSTER, (short) 300); + duration.put(255 - BlockID.LOOM, (short) 300); + duration.put(255 - BlockID.WOOD_BARK, (short) 300); + duration.put(255 - BlockID.STRIPPED_OAK_LOG, (short) 300); + duration.put(255 - BlockID.STRIPPED_SPRUCE_LOG, (short) 300); + duration.put(255 - BlockID.STRIPPED_BIRCH_LOG, (short) 300); + duration.put(255 - BlockID.STRIPPED_JUNGLE_LOG, (short) 300); + duration.put(255 - BlockID.STRIPPED_ACACIA_LOG, (short) 300); + duration.put(255 - BlockID.STRIPPED_DARK_OAK_LOG, (short) 300); + duration.put(255 - BlockID.SPRUCE_TRAPDOOR, (short) 300); + duration.put(255 - BlockID.BIRCH_TRAPDOOR, (short) 300); + duration.put(255 - BlockID.JUNGLE_TRAPDOOR, (short) 300); + duration.put(255 - BlockID.ACACIA_TRAPDOOR, (short) 300); + duration.put(255 - BlockID.DARK_OAK_TRAPDOOR, (short) 300); + duration.put(255 - BlockID.SPRUCE_BUTTON, (short) 300); + duration.put(255 - BlockID.BIRCH_BUTTON, (short) 300); + duration.put(255 - BlockID.JUNGLE_BUTTON, (short) 300); + duration.put(255 - BlockID.ACACIA_BUTTON, (short) 300); + duration.put(255 - BlockID.DARK_OAK_BUTTON, (short) 300); + duration.put(255 - BlockID.SPRUCE_PRESSURE_PLATE, (short) 300); + duration.put(255 - BlockID.BIRCH_PRESSURE_PLATE, (short) 300); + duration.put(255 - BlockID.JUNGLE_PRESSURE_PLATE, (short) 300); + duration.put(255 - BlockID.ACACIA_PRESSURE_PLATE, (short) 300); + duration.put(255 - BlockID.DARK_OAK_PRESSURE_PLATE, (short) 300); + duration.put(255 - BlockID.AZALEA, (short) 100); + duration.put(255 - BlockID.FLOWERING_AZALEA, (short) 100); } } diff --git a/src/main/java/cn/nukkit/inventory/FurnaceInventory.java b/src/main/java/cn/nukkit/inventory/FurnaceInventory.java index 34cef286466..4db693064aa 100644 --- a/src/main/java/cn/nukkit/inventory/FurnaceInventory.java +++ b/src/main/java/cn/nukkit/inventory/FurnaceInventory.java @@ -4,7 +4,7 @@ import cn.nukkit.item.Item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class FurnaceInventory extends ContainerInventory { @@ -13,6 +13,10 @@ public FurnaceInventory(BlockEntityFurnace furnace) { super(furnace, InventoryType.FURNACE); } + public FurnaceInventory(BlockEntityFurnace furnace, InventoryType type) { + super(furnace, type); // For blast furnace + } + @Override public BlockEntityFurnace getHolder() { return (BlockEntityFurnace) this.holder; @@ -47,5 +51,7 @@ public void onSlotChange(int index, Item before, boolean send) { super.onSlotChange(index, before, send); this.getHolder().scheduleUpdate(); + + this.getHolder().chunk.setChanged(); } } diff --git a/src/main/java/cn/nukkit/inventory/FurnaceRecipe.java b/src/main/java/cn/nukkit/inventory/FurnaceRecipe.java index bab63a69bbe..a0e1e2e2d16 100644 --- a/src/main/java/cn/nukkit/inventory/FurnaceRecipe.java +++ b/src/main/java/cn/nukkit/inventory/FurnaceRecipe.java @@ -3,7 +3,7 @@ import cn.nukkit.item.Item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class FurnaceRecipe implements Recipe { diff --git a/src/main/java/cn/nukkit/inventory/HopperInventory.java b/src/main/java/cn/nukkit/inventory/HopperInventory.java index 531c74ff0ff..c1776e7d9c9 100644 --- a/src/main/java/cn/nukkit/inventory/HopperInventory.java +++ b/src/main/java/cn/nukkit/inventory/HopperInventory.java @@ -1,6 +1,7 @@ package cn.nukkit.inventory; import cn.nukkit.blockentity.BlockEntityHopper; +import cn.nukkit.item.Item; /** * Created by CreeperFace on 8.5.2017. @@ -15,4 +16,11 @@ public HopperInventory(BlockEntityHopper hopper) { public BlockEntityHopper getHolder() { return (BlockEntityHopper) super.getHolder(); } + + @Override + public void onSlotChange(int index, Item before, boolean send) { + super.onSlotChange(index, before, send); + + this.getHolder().chunk.setChanged(); + } } diff --git a/src/main/java/cn/nukkit/inventory/Inventory.java b/src/main/java/cn/nukkit/inventory/Inventory.java index 9b62bfd3bf8..f074c6a3ad6 100644 --- a/src/main/java/cn/nukkit/inventory/Inventory.java +++ b/src/main/java/cn/nukkit/inventory/Inventory.java @@ -8,7 +8,7 @@ import java.util.Set; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface Inventory { @@ -27,6 +27,10 @@ public interface Inventory { Item getItem(int index); + default Item getItemFast(int index) { + return getItem(index); + } + default boolean setItem(int index, Item item) { return setItem(index, item, true); } @@ -37,6 +41,10 @@ default boolean setItem(int index, Item item) { boolean canAddItem(Item item); + default boolean allowedToAdd(Item item) { + return true; + } + Item[] removeItem(Item... slots); Map getContents(); diff --git a/src/main/java/cn/nukkit/inventory/InventoryHolder.java b/src/main/java/cn/nukkit/inventory/InventoryHolder.java index 85897e18a50..a55aa4efb07 100644 --- a/src/main/java/cn/nukkit/inventory/InventoryHolder.java +++ b/src/main/java/cn/nukkit/inventory/InventoryHolder.java @@ -1,7 +1,7 @@ package cn.nukkit.inventory; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface InventoryHolder { diff --git a/src/main/java/cn/nukkit/inventory/InventoryType.java b/src/main/java/cn/nukkit/inventory/InventoryType.java index 1b16ae7b9a6..bdad1d1437d 100644 --- a/src/main/java/cn/nukkit/inventory/InventoryType.java +++ b/src/main/java/cn/nukkit/inventory/InventoryType.java @@ -1,29 +1,42 @@ package cn.nukkit.inventory; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public enum InventoryType { - CHEST(27, "Chest", 0), - ENDER_CHEST(27, "Ender Chest", 0), - DOUBLE_CHEST(27 + 27, "Double Chest", 0), + + CHEST(27, "Chest", 0), //27 CONTAINER + ENDER_CHEST(27, "Ender Chest", 0), //27 CONTAINER + DOUBLE_CHEST(54, "Double Chest", 0), //27 + 27 CONTAINER PLAYER(40, "Player", -1), //36 CONTAINER, 4 ARMOR - FURNACE(3, "Furnace", 2), - CRAFTING(5, "Crafting", 1), //4 CRAFTING slots, 1 RESULT - WORKBENCH(10, "Crafting", 1), //9 CRAFTING slots, 1 RESULT - BREWING_STAND(5, "Brewing", 4), //1 INPUT, 3 POTION, 1 fuel + FURNACE(3, "Furnace", 2), //1 INPUT/OUTPUT, 1 FUEL + BLAST_FURNACE(3, "Blast Furnace", 27), //1 INPUT/OUTPUT, 1 FUEL + SMOKER(3, "Smoker", 28), //1 INPUT/OUTPUT, 1 FUEL + CAMPFIRE(4, "Campfire", -1), //4 CONTAINER + CRAFTING(5, "Crafting", 1), //4 CRAFTING SLOTS, 1 RESULT + WORKBENCH(10, "Crafting", 1), //9 CRAFTING SLOTS, 1 RESULT + BREWING_STAND(5, "Brewing", 4), //1 INPUT, 3 POTION, 1 FUEL ANVIL(3, "Anvil", 5), //2 INPUT, 1 OUTPUT - ENCHANT_TABLE(2, "Enchant", 3), //1 INPUT/OUTPUT, 1 LAPIS - DISPENSER(0, "Dispenser", 6), //9 CONTAINER + ENCHANT_TABLE(2, "Enchantment Table", 3), //1 INPUT/OUTPUT, 1 LAPIS + DISPENSER(9, "Dispenser", 6), //9 CONTAINER DROPPER(9, "Dropper", 7), //9 CONTAINER HOPPER(5, "Hopper", 8), //5 CONTAINER - UI(1, "UI", -1), - SHULKER_BOX(27, "Shulker Box", 0), - BEACON(1, "Beacon", 13), - OFFHAND(1, "Offhand", -1), - MINECART_CHEST(27, "Minecart with Chest", 0), - MINECART_HOPPER(5, "Minecart with Hopper", 8); + UI(1, "UI", -1), //1 CONTAINER + SHULKER_BOX(27, "Shulker Box", 0), //27 CONTAINER + BEACON(1, "Beacon", 13), //1 INPUT + ENTITY_ARMOR(4, "Entity Armor", -1), //4 ARMOR + ENTITY_EQUIPMENT(36, "Entity Equipment", -1), //36 CONTAINER + MINECART_CHEST(27, "Minecart with Chest", 0), //27 CONTAINER + MINECART_HOPPER(5, "Minecart with Hopper", 8), //5 CONTAINER + OFFHAND(1, "Offhand", -1), //1 CONTAINER + TRADING(3, "Villager Trade", 15), //3 CONTAINER + BARREL(27, "Barrel", 0), //27 CONTAINER + LOOM(4, "Loom", 24), //4 CONTAINER + CHEST_BOAT(27, "Boat with Chest", 0), //27 CONTAINER + DONKEY(15, "Donkey", 12), //15 CONTAINER + SMITHING_TABLE(2, "Smithing Table", 33), + LECTERN(0, "Lectern", 25); private final int size; private final String title; diff --git a/src/main/java/cn/nukkit/inventory/LoomInventory.java b/src/main/java/cn/nukkit/inventory/LoomInventory.java new file mode 100644 index 00000000000..f0900c80c45 --- /dev/null +++ b/src/main/java/cn/nukkit/inventory/LoomInventory.java @@ -0,0 +1,54 @@ +package cn.nukkit.inventory; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; +import cn.nukkit.level.Position; +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntSet; + +public class LoomInventory extends FakeBlockUIComponent { + + public static final int OFFSET = 9; + + public static final IntSet ITEMS = new IntOpenHashSet(new int[]{Item.AIR, ItemID.BANNER, ItemID.DYE, ItemID.BANNER_PATTERN}); + + public LoomInventory(PlayerUIInventory playerUI, Position position) { + super(playerUI, InventoryType.LOOM, OFFSET, position); + } + + @Override + public void onOpen(Player who) { + super.onOpen(who); + who.craftingType = Player.CRAFTING_LOOM; + } + + public Item getBanner() { + return getItem(0); + } + + public Item getDye() { + return getItem(1); + } + + public Item getPattern() { + return getItem(2); + } + + public void setBanner(Item item) { + this.setItem(0, item); + } + + public void setDye(Item item) { + this.setItem(1, item); + } + + public void setPattern(Item item) { + this.setItem(2, item); + } + + @Override + public boolean allowedToAdd(Item item) { + return ITEMS.contains(item.getId()); + } +} diff --git a/src/main/java/cn/nukkit/inventory/MultiRecipe.java b/src/main/java/cn/nukkit/inventory/MultiRecipe.java index adf791436b9..dd9834e05a4 100644 --- a/src/main/java/cn/nukkit/inventory/MultiRecipe.java +++ b/src/main/java/cn/nukkit/inventory/MultiRecipe.java @@ -8,8 +8,11 @@ public class MultiRecipe implements Recipe { private final UUID id; + private final int networkId; + public MultiRecipe(UUID id) { this.id = id; + this.networkId = ++CraftingManager.NEXT_NETWORK_ID; } @Override @@ -30,4 +33,8 @@ public RecipeType getType() { public UUID getId() { return this.id; } + + public int getNetworkId() { + return this.networkId; + } } diff --git a/src/main/java/cn/nukkit/inventory/PlayerCursorInventory.java b/src/main/java/cn/nukkit/inventory/PlayerCursorInventory.java index 97643f3c8c5..38d85d98751 100644 --- a/src/main/java/cn/nukkit/inventory/PlayerCursorInventory.java +++ b/src/main/java/cn/nukkit/inventory/PlayerCursorInventory.java @@ -6,6 +6,7 @@ * @author CreeperFace */ public class PlayerCursorInventory extends PlayerUIComponent { + private final PlayerUIInventory playerUI; PlayerCursorInventory(PlayerUIInventory playerUI) { diff --git a/src/main/java/cn/nukkit/inventory/PlayerEnderChestInventory.java b/src/main/java/cn/nukkit/inventory/PlayerEnderChestInventory.java index faf894b73f6..e75585e2f66 100755 --- a/src/main/java/cn/nukkit/inventory/PlayerEnderChestInventory.java +++ b/src/main/java/cn/nukkit/inventory/PlayerEnderChestInventory.java @@ -4,7 +4,6 @@ import cn.nukkit.block.BlockEnderChest; import cn.nukkit.entity.EntityHuman; import cn.nukkit.entity.EntityHumanType; -import cn.nukkit.level.Level; import cn.nukkit.network.protocol.BlockEventPacket; import cn.nukkit.network.protocol.ContainerClosePacket; import cn.nukkit.network.protocol.ContainerOpenPacket; @@ -51,10 +50,9 @@ public void onOpen(Player who) { blockEventPacket.case1 = 1; blockEventPacket.case2 = 2; - Level level = this.getHolder().getLevel(); - if (level != null) { - level.addLevelSoundEvent(this.getHolder().add(0.5, 0.5, 0.5), LevelSoundEventPacket.SOUND_ENDERCHEST_OPEN); - level.addChunkPacket((int) this.getHolder().getX() >> 4, (int) this.getHolder().getZ() >> 4, blockEventPacket); + if (chest.level != null && chest.level == who.level) { + chest.level.addLevelSoundEvent(chest.add(0.5, 0.5, 0.5), LevelSoundEventPacket.SOUND_ENDERCHEST_OPEN); + chest.level.addChunkPacket((int) chest.getX() >> 4, (int) chest.getZ() >> 4, blockEventPacket); } } } @@ -76,15 +74,14 @@ public void onClose(Player who) { blockEventPacket.case1 = 1; blockEventPacket.case2 = 0; - Level level = this.getHolder().getLevel(); - if (level != null) { - level.addLevelSoundEvent(this.getHolder().add(0.5, 0.5, 0.5), LevelSoundEventPacket.SOUND_ENDERCHEST_CLOSED); - level.addChunkPacket((int) this.getHolder().getX() >> 4, (int) this.getHolder().getZ() >> 4, blockEventPacket); + if (chest.level != null && chest.level == who.level) { + chest.level.addLevelSoundEvent(chest.add(0.5, 0.5, 0.5), LevelSoundEventPacket.SOUND_ENDERCHEST_CLOSED); + chest.level.addChunkPacket((int) chest.getX() >> 4, (int) chest.getZ() >> 4, blockEventPacket); } - - who.setViewingEnderChest(null); } + who.setViewingEnderChest(null); + super.onClose(who); } } diff --git a/src/main/java/cn/nukkit/inventory/PlayerInventory.java b/src/main/java/cn/nukkit/inventory/PlayerInventory.java index 6febe54ea13..12283a80786 100644 --- a/src/main/java/cn/nukkit/inventory/PlayerInventory.java +++ b/src/main/java/cn/nukkit/inventory/PlayerInventory.java @@ -17,22 +17,15 @@ import java.util.Collection; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class PlayerInventory extends BaseInventory { - protected int itemInHandIndex = 0; - private int[] hotbar; + protected int itemInHandIndex; public PlayerInventory(EntityHumanType player) { super(player, InventoryType.PLAYER); - this.hotbar = new int[this.getHotbarSize()]; - - for (int i = 0; i < this.hotbar.length; i++) { - this.hotbar[i] = i; - } - } @Override @@ -55,7 +48,10 @@ public void setSize(int size) { */ public boolean equipItem(int slot) { if (!isHotbarSlot(slot)) { - this.sendContents((Player) this.getHolder()); + Server.getInstance().getLogger().debug(this.getHolder().getName() + ": equipItem: slot is not a hotbar slot: " + slot); + /*if (this.getHolder() instanceof Player) { + this.sendContents((Player) this.getHolder()); + }*/ return false; } @@ -81,7 +77,7 @@ public boolean equipItem(int slot) { } private boolean isHotbarSlot(int slot) { - return slot >= 0 && slot <= this.getHotbarSize(); + return slot >= 0 && slot < this.getHotbarSize(); } @Deprecated @@ -91,7 +87,6 @@ public int getHotbarSlotIndex(int index) { @Deprecated public void setHotbarSlotIndex(int index, int slot) { - } public int getHeldItemIndex() { @@ -115,7 +110,7 @@ public void setHeldItemIndex(int index, boolean send) { } public Item getItemInHand() { - Item item = this.getItem(this.getHeldItemIndex()); + Item item = this.getItem(this.itemInHandIndex); if (item != null) { return item; } else { @@ -123,8 +118,17 @@ public Item getItemInHand() { } } + public Item getItemInHandFast() { + Item item = this.getItemFast(this.getHeldItemIndex()); + if (item != null) { + return item; + } else { + return air; + } + } + public boolean setItemInHand(Item item) { - return this.setItem(this.getHeldItemIndex(), item); + return this.setItem(this.itemInHandIndex, item); } @Deprecated @@ -147,20 +151,24 @@ public void setHeldItemSlot(int slot) { } public void sendHeldItem(Player... players) { - Item item = this.getItemInHand(); - - MobEquipmentPacket pk = new MobEquipmentPacket(); - pk.item = item; - pk.inventorySlot = pk.hotbarSlot = this.getHeldItemIndex(); + Item item = this.getItemInHandFast(); for (Player player : players) { - pk.eid = this.getHolder().getId(); if (player.equals(this.getHolder())) { - pk.eid = player.getId(); - this.sendSlot(this.getHeldItemIndex(), player); - } + this.sendSlot(this.itemInHandIndex, player); - player.dataPacket(pk); + MobEquipmentPacket pk = new MobEquipmentPacket(); + pk.item = item; + pk.inventorySlot = pk.hotbarSlot = this.itemInHandIndex; + pk.eid = this.getHolder().getId(); + player.dataPacket(pk); + } else { + MobEquipmentPacket pk = new MobEquipmentPacket(); + pk.item = item; + pk.inventorySlot = pk.hotbarSlot = this.itemInHandIndex; + pk.eid = this.getHolder().getId(); + player.dataPacket(pk); + } } } @@ -203,18 +211,34 @@ public Item getHelmet() { return this.getItem(this.getSize()); } + public Item getHelmetFast() { + return this.getItemFast(36); + } + public Item getChestplate() { return this.getItem(this.getSize() + 1); } + public Item getChestplateFast() { + return this.getItemFast(37); + } + public Item getLeggings() { return this.getItem(this.getSize() + 2); } + public Item getLeggingsFast() { + return this.getItemFast(38); + } + public Item getBoots() { return this.getItem(this.getSize() + 3); } + public Item getBootsFast() { + return this.getItemFast(39); + } + public boolean setHelmet(Item helmet) { return this.setItem(this.getSize(), helmet); } @@ -233,18 +257,18 @@ public boolean setBoots(Item boots) { @Override public boolean setItem(int index, Item item) { - return setItem(index, item, true, false); + return setItem(index, item, true); } - private boolean setItem(int index, Item item, boolean send, boolean ignoreArmorEvents) { + @Override + public boolean setItem(int index, Item item, boolean send) { if (index < 0 || index >= this.size) { return false; } else if (item.getId() == 0 || item.getCount() <= 0) { - return this.clear(index); + return this.clear(index, send); } - //Armor change - if (!ignoreArmorEvents && index >= this.getSize()) { + if (index >= this.getSize()) { // Armor change EntityArmorChangeEvent ev = new EntityArmorChangeEvent(this.getHolder(), this.getItem(index), item, index); Server.getInstance().getPluginManager().callEvent(ev); if (ev.isCancelled() && this.getHolder() != null) { @@ -261,6 +285,7 @@ private boolean setItem(int index, Item item, boolean send, boolean ignoreArmorE } item = ev.getNewItem(); } + Item old = this.getItem(index); this.slots.put(index, item.clone()); this.onSlotChange(index, old, send); @@ -335,18 +360,16 @@ public void sendArmorContents(Player player) { public void sendArmorContents(Player[] players) { Item[] armor = this.getArmorContents(); - MobArmorEquipmentPacket pk = new MobArmorEquipmentPacket(); - pk.eid = this.getHolder().getId(); - pk.slots = armor; - pk.tryEncode(); - for (Player player : players) { if (player.equals(this.getHolder())) { - InventoryContentPacket pk2 = new InventoryContentPacket(); - pk2.inventoryId = InventoryContentPacket.SPECIAL_ARMOR; - pk2.slots = armor; - player.dataPacket(pk2); + InventoryContentPacket pk = new InventoryContentPacket(); + pk.inventoryId = InventoryContentPacket.SPECIAL_ARMOR; + pk.slots = armor; + player.dataPacket(pk); } else { + MobArmorEquipmentPacket pk = new MobArmorEquipmentPacket(); + pk.eid = this.getHolder().getId(); + pk.slots = armor; player.dataPacket(pk); } } @@ -383,19 +406,17 @@ public void sendArmorSlot(int index, Player player) { public void sendArmorSlot(int index, Player[] players) { Item[] armor = this.getArmorContents(); - MobArmorEquipmentPacket pk = new MobArmorEquipmentPacket(); - pk.eid = this.getHolder().getId(); - pk.slots = armor; - pk.tryEncode(); - for (Player player : players) { if (player.equals(this.getHolder())) { - InventorySlotPacket pk2 = new InventorySlotPacket(); - pk2.inventoryId = InventoryContentPacket.SPECIAL_ARMOR; - pk2.slot = index - this.getSize(); - pk2.item = this.getItem(index); - player.dataPacket(pk2); + InventorySlotPacket pk = new InventorySlotPacket(); + pk.inventoryId = InventoryContentPacket.SPECIAL_ARMOR; + pk.slot = index - this.getSize(); + pk.item = this.getItem(index); + player.dataPacket(pk); } else { + MobArmorEquipmentPacket pk = new MobArmorEquipmentPacket(); + pk.eid = this.getHolder().getId(); + pk.slots = armor; player.dataPacket(pk); } } @@ -423,22 +444,14 @@ public void sendContents(Player[] players) { pk.slots[i] = this.getItem(i); } - /*//Because PE is stupid and shows 9 less slots than you send it, give it 9 dummy slots so it shows all the REAL slots. - for(int i = this.getSize(); i < this.getSize() + this.getHotbarSize(); ++i){ - pk.slots[i] = new ItemBlock(Block.get(BlockID.AIR)); - } - pk.slots[i] = new ItemBlock(Block.get(BlockID.AIR)); - }*/ - for (Player player : players) { int id = player.getWindowId(this); - if (id == -1 || !player.spawned) { + if (id == -1 /*|| !player.spawned*/) { if (this.getHolder() != player) this.close(player); continue; } pk.inventoryId = id; - player.dataPacket(pk.clone()); - + player.dataPacket(pk); } } @@ -456,12 +469,11 @@ public void sendSlot(int index, Collection players) { public void sendSlot(int index, Player... players) { InventorySlotPacket pk = new InventorySlotPacket(); pk.slot = index; - pk.item = this.getItem(index).clone(); + pk.item = this.getItem(index); for (Player player : players) { if (player.equals(this.getHolder())) { pk.inventoryId = ContainerIds.INVENTORY; - player.dataPacket(pk); } else { int id = player.getWindowId(this); if (id == -1) { @@ -469,8 +481,8 @@ public void sendSlot(int index, Player... players) { continue; } pk.inventoryId = id; - player.dataPacket(pk.clone()); } + player.dataPacket(pk); } } @@ -481,11 +493,7 @@ public void sendCreativeContents() { Player p = (Player) this.getHolder(); CreativeContentPacket pk = new CreativeContentPacket(); - - if (!p.isSpectator()) { //fill it for all gamemodes except spectator - pk.entries = Item.getCreativeItems().toArray(new Item[0]); - } - + pk.entries = p.isSpectator() ? new Item[0] : Item.getCreativeItems().toArray(new Item[0]); p.dataPacket(pk); } @@ -513,7 +521,7 @@ public void onClose(Player who) { pk.windowId = who.getWindowId(this); pk.wasServerInitiated = who.getClosingWindowId() != pk.windowId; who.dataPacket(pk); - // player can never stop viewing their own inventory + // Player can never stop viewing their own inventory if (who != holder) { super.onClose(who); } diff --git a/src/main/java/cn/nukkit/inventory/PlayerOffhandInventory.java b/src/main/java/cn/nukkit/inventory/PlayerOffhandInventory.java index 7e2d3e5ae43..69f760fd986 100644 --- a/src/main/java/cn/nukkit/inventory/PlayerOffhandInventory.java +++ b/src/main/java/cn/nukkit/inventory/PlayerOffhandInventory.java @@ -34,15 +34,15 @@ public void onSlotChange(int index, Item before, boolean send) { @Override public void sendContents(Player... players) { Item item = this.getItem(0); - MobEquipmentPacket pk = this.createMobEquipmentPacket(item); for (Player player : players) { if (player == this.getHolder()) { - InventoryContentPacket pk2 = new InventoryContentPacket(); - pk2.inventoryId = ContainerIds.OFFHAND; - pk2.slots = new Item[]{item}; - player.dataPacket(pk2); + InventoryContentPacket pk = new InventoryContentPacket(); // content vs slot + pk.inventoryId = ContainerIds.OFFHAND; + pk.slots = new Item[]{item}; + player.dataPacket(pk); } else { + MobEquipmentPacket pk = this.createMobEquipmentPacket(item); player.dataPacket(pk); } } @@ -51,15 +51,15 @@ public void sendContents(Player... players) { @Override public void sendSlot(int index, Player... players) { Item item = this.getItem(0); - MobEquipmentPacket pk = this.createMobEquipmentPacket(item); for (Player player : players) { if (player == this.getHolder()) { - InventorySlotPacket pk2 = new InventorySlotPacket(); - pk2.inventoryId = ContainerIds.OFFHAND; - pk2.item = item; - player.dataPacket(pk2); + InventorySlotPacket pk = new InventorySlotPacket(); // slot vs content + pk.inventoryId = ContainerIds.OFFHAND; + pk.item = item; + player.dataPacket(pk); } else { + MobEquipmentPacket pk = this.createMobEquipmentPacket(item); player.dataPacket(pk); } } @@ -71,7 +71,6 @@ private MobEquipmentPacket createMobEquipmentPacket(Item item) { pk.item = item; pk.inventorySlot = 1; pk.windowId = ContainerIds.OFFHAND; - pk.tryEncode(); return pk; } @@ -79,4 +78,9 @@ private MobEquipmentPacket createMobEquipmentPacket(Item item) { public EntityHuman getHolder() { return (EntityHuman) super.getHolder(); } + + @Override + public boolean allowedToAdd(Item item) { + return item.allowOffhand(); + } } diff --git a/src/main/java/cn/nukkit/inventory/PlayerUIComponent.java b/src/main/java/cn/nukkit/inventory/PlayerUIComponent.java index 41bc32d7a5f..e3abc2a6673 100644 --- a/src/main/java/cn/nukkit/inventory/PlayerUIComponent.java +++ b/src/main/java/cn/nukkit/inventory/PlayerUIComponent.java @@ -11,7 +11,7 @@ public class PlayerUIComponent extends BaseInventory { public static final int CREATED_ITEM_OUTPUT_UI_SLOT = 50; - private final PlayerUIInventory playerUI; + private final PlayerUIInventory playerUI; private final int offset; private final int size; @@ -48,6 +48,11 @@ public Item getItem(int index) { return this.playerUI.getItem(index + this.offset); } + @Override + public Item getItemFast(int index) { + return this.playerUI.getItemFast(index + this.offset); + } + @Override public boolean setItem(int index, Item item, boolean send) { return this.playerUI.setItem(index + this.offset, item, send); diff --git a/src/main/java/cn/nukkit/inventory/PlayerUIInventory.java b/src/main/java/cn/nukkit/inventory/PlayerUIInventory.java index cf5753e35de..0a5899f0cbc 100644 --- a/src/main/java/cn/nukkit/inventory/PlayerUIInventory.java +++ b/src/main/java/cn/nukkit/inventory/PlayerUIInventory.java @@ -1,12 +1,14 @@ package cn.nukkit.inventory; import cn.nukkit.Player; +import cn.nukkit.item.Item; import cn.nukkit.network.protocol.InventorySlotPacket; import cn.nukkit.network.protocol.types.ContainerIds; import java.util.HashMap; public class PlayerUIInventory extends BaseInventory { + private final Player player; private final PlayerCursorInventory cursorInventory; @@ -14,7 +16,7 @@ public class PlayerUIInventory extends BaseInventory { private final BigCraftingGrid bigCraftingGrid; public PlayerUIInventory(Player player) { - super(player, InventoryType.UI, new HashMap<>(), 51); + super(player, InventoryType.UI, new HashMap<>(), 54); this.player = player; this.cursorInventory = new PlayerCursorInventory(this); @@ -41,11 +43,12 @@ public void setSize(int size) { @Override public void sendSlot(int index, Player... target) { - InventorySlotPacket pk = new InventorySlotPacket(); - pk.slot = index; - pk.item = this.getItem(index); + Item item = this.getItem(index); for (Player p : target) { + InventorySlotPacket pk = new InventorySlotPacket(); + pk.slot = index; + pk.item = item; if (p == this.getHolder()) { pk.inventoryId = ContainerIds.UI; } else { @@ -63,7 +66,7 @@ public void sendSlot(int index, Player... target) { @Override public void sendContents(Player... target) { - //doesn't work here + } @Override diff --git a/src/main/java/cn/nukkit/inventory/Recipe.java b/src/main/java/cn/nukkit/inventory/Recipe.java index 53a04e3221b..033c5c59ce3 100644 --- a/src/main/java/cn/nukkit/inventory/Recipe.java +++ b/src/main/java/cn/nukkit/inventory/Recipe.java @@ -3,7 +3,7 @@ import cn.nukkit.item.Item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface Recipe { diff --git a/src/main/java/cn/nukkit/inventory/RecipeType.java b/src/main/java/cn/nukkit/inventory/RecipeType.java index ccaf06ddd59..9d22aa9cc6b 100644 --- a/src/main/java/cn/nukkit/inventory/RecipeType.java +++ b/src/main/java/cn/nukkit/inventory/RecipeType.java @@ -1,6 +1,7 @@ package cn.nukkit.inventory; public enum RecipeType { + SHAPELESS, SHAPED, FURNACE, @@ -8,5 +9,9 @@ public enum RecipeType { MULTI, SHULKER_BOX, SHAPELESS_CHEMISTRY, - SHAPED_CHEMISTRY + SHAPED_CHEMISTRY, + REPAIR, + CAMPFIRE, + CAMPFIRE_DATA, + SMITHING_TRANSFORM // not the correct id, map to 8 on 1.19.60+ } diff --git a/src/main/java/cn/nukkit/inventory/ShapedRecipe.java b/src/main/java/cn/nukkit/inventory/ShapedRecipe.java index 1163e53fc99..a37d88be371 100644 --- a/src/main/java/cn/nukkit/inventory/ShapedRecipe.java +++ b/src/main/java/cn/nukkit/inventory/ShapedRecipe.java @@ -6,7 +6,7 @@ import java.util.*; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ShapedRecipe implements CraftingRecipe { @@ -17,18 +17,23 @@ public class ShapedRecipe implements CraftingRecipe { private final List ingredientsAggregate; - private long least,most; + private long least, most; private final String[] shape; private final int priority; private final CharObjectHashMap ingredients = new CharObjectHashMap<>(); + private final int networkId; public ShapedRecipe(Item primaryResult, String[] shape, Map ingredients, List extraResults) { this(null, 1, primaryResult, shape, ingredients, extraResults); } + public ShapedRecipe(String recipeId, int priority, Item primaryResult, String[] shape, Map ingredients, List extraResults) { + this(recipeId, priority, primaryResult, shape, ingredients, extraResults, null); + } + /** * Constructs a ShapedRecipe instance. * @@ -41,10 +46,11 @@ public ShapedRecipe(Item primaryResult, String[] shape, Map ing * array MUST have a corresponding item in this list. Space character is automatically treated as air. * @param extraResults
List of additional result items to leave in the crafting grid afterwards. Used for things like cake recipe * empty buckets. - *

+ * @param networkId Unique network id of this recipe. If null, a new networkId will be assigned to this recipe. + * * Note: Recipes **do not** need to be square. Do NOT add padding for empty rows/columns. */ - public ShapedRecipe(String recipeId, int priority, Item primaryResult, String[] shape, Map ingredients, List extraResults) { + public ShapedRecipe(String recipeId, int priority, Item primaryResult, String[] shape, Map ingredients, List extraResults, Integer networkId) { this.recipeId = recipeId; this.priority = priority; int rowCount = shape.length; @@ -58,17 +64,16 @@ public ShapedRecipe(String recipeId, int priority, Item primaryResult, String[] } - //for($shape as $y => $row) { for (String row : shape) { if (row.length() != columnCount) { - throw new RuntimeException("Shaped recipe rows must all have the same length (expected " + columnCount + ", got " + row.length() + ")"); + throw new RuntimeException("Shaped recipe rows must all have the same length (expected " + columnCount + ", got " + row.length() + ')'); } for (int x = 0; x < columnCount; ++x) { char c = row.charAt(x); if (c != ' ' && !ingredients.containsKey(c)) { - throw new RuntimeException("No item specified for symbol '" + c + "'"); + throw new RuntimeException("No item specified for symbol '" + c + '\''); } } } @@ -84,8 +89,9 @@ public ShapedRecipe(String recipeId, int priority, Item primaryResult, String[] this.ingredientsAggregate = new ArrayList<>(); for (char c : String.join("", this.shape).toCharArray()) { - if (c == ' ') + if (c == ' ') { continue; + } Item ingredient = this.ingredients.get(c).clone(); for (Item existingIngredient : this.ingredientsAggregate) { if (existingIngredient.equals(ingredient, ingredient.hasMeta(), ingredient.hasCompoundTag())) { @@ -94,10 +100,12 @@ public ShapedRecipe(String recipeId, int priority, Item primaryResult, String[] break; } } - if (ingredient != null) + if (ingredient != null) { this.ingredientsAggregate.add(ingredient); + } } this.ingredientsAggregate.sort(CraftingManager.recipeComparator); + this.networkId = networkId != null ? networkId : ++CraftingManager.NEXT_NETWORK_ID; } public int getWidth() { @@ -127,6 +135,7 @@ public UUID getId() { public void setId(UUID uuid) { this.least = uuid.getLeastSignificantBits(); this.most = uuid.getMostSignificantBits(); + if (this.recipeId == null) { this.recipeId = getId().toString(); } @@ -218,7 +227,7 @@ public boolean matchItems(List inputList, List extraOutputList, int haveInputs.add(item.clone()); } List needInputs = new ArrayList<>(); - if(multiplier != 1){ + if (multiplier != 1) { for (Item item : ingredientsAggregate) { if (item.isNull()) continue; @@ -246,7 +255,7 @@ public boolean matchItems(List inputList, List extraOutputList, int } haveOutputs.sort(CraftingManager.recipeComparator); List needOutputs = new ArrayList<>(); - if(multiplier != 1){ + if (multiplier != 1) { for (Item item : getExtraResults()) { if (item.isNull()) continue; @@ -263,7 +272,7 @@ public boolean matchItems(List inputList, List extraOutputList, int } needOutputs.sort(CraftingManager.recipeComparator); - return this.matchItemList(haveOutputs, needOutputs); + return matchItemList(haveOutputs, needOutputs); } /** @@ -279,7 +288,7 @@ public boolean matchItems(List inputList, List extraOutputList) { return matchItems(inputList, extraOutputList, 1); } - private boolean matchItemList(List haveItems, List needItems) { + private static boolean matchItemList(List haveItems, List needItems) { for (Item needItem : new ArrayList<>(needItems)) { for (Item haveItem : new ArrayList<>(haveItems)) { if (needItem.equals(haveItem, needItem.hasMeta(), needItem.hasCompoundTag())) { @@ -303,7 +312,7 @@ private boolean matchItemList(List haveItems, List needItems) { public String toString() { StringJoiner joiner = new StringJoiner(", "); - ingredients.forEach((character, item) -> joiner.add(item.getName() + ":" + item.getDamage())); + ingredients.forEach((character, item) -> joiner.add(item.getName() + ':' + item.getDamage())); return joiner.toString(); } @@ -317,6 +326,10 @@ public List getIngredientsAggregate() { return ingredientsAggregate; } + public int getNetworkId() { + return this.networkId; + } + public static class Entry { public final int x; public final int y; @@ -326,4 +339,4 @@ public Entry(int x, int y) { this.y = y; } } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/inventory/ShapelessRecipe.java b/src/main/java/cn/nukkit/inventory/ShapelessRecipe.java index a3fb10a9191..43607aa75c5 100644 --- a/src/main/java/cn/nukkit/inventory/ShapelessRecipe.java +++ b/src/main/java/cn/nukkit/inventory/ShapelessRecipe.java @@ -5,7 +5,7 @@ import java.util.*; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ShapelessRecipe implements CraftingRecipe { @@ -14,18 +14,24 @@ public class ShapelessRecipe implements CraftingRecipe { private final Item output; - private long least,most; + private long least, most; private final List ingredients; private final List ingredientsAggregate; private final int priority; + private final int networkId; + public ShapelessRecipe(Item result, Collection ingredients) { this(null, 10, result, ingredients); } public ShapelessRecipe(String recipeId, int priority, Item result, Collection ingredients) { + this(recipeId, priority, result, ingredients, null); + } + + public ShapelessRecipe(String recipeId, int priority, Item result, Collection ingredients, Integer networkId) { this.recipeId = recipeId; this.priority = priority; this.output = result.clone(); @@ -38,7 +44,7 @@ public ShapelessRecipe(String recipeId, int priority, Item result, Collection inputList, List extraOutputList, int haveInputs.add(item.clone()); } List needInputs = new ArrayList<>(); - if(multiplier != 1){ + if (multiplier != 1) { for (Item item : ingredientsAggregate) { if (item.isNull()) continue; @@ -160,7 +168,7 @@ public boolean matchItems(List inputList, List extraOutputList, int } haveOutputs.sort(CraftingManager.recipeComparator); List needOutputs = new ArrayList<>(); - if(multiplier != 1){ + if (multiplier != 1) { for (Item item : getExtraResults()) { if (item.isNull()) continue; @@ -177,7 +185,7 @@ public boolean matchItems(List inputList, List extraOutputList, int } needOutputs.sort(CraftingManager.recipeComparator); - return this.matchItemList(haveOutputs, needOutputs); + return matchItemList(haveOutputs, needOutputs); } /** @@ -193,7 +201,7 @@ public boolean matchItems(List inputList, List extraOutputList) { return matchItems(inputList, extraOutputList, 1); } - private boolean matchItemList(List haveItems, List needItems) { + private static boolean matchItemList(List haveItems, List needItems) { for (Item needItem : new ArrayList<>(needItems)) { for (Item haveItem : new ArrayList<>(haveItems)) { if (needItem.equals(haveItem, needItem.hasMeta(), needItem.hasCompoundTag())) { @@ -217,4 +225,8 @@ private boolean matchItemList(List haveItems, List needItems) { public List getIngredientsAggregate() { return ingredientsAggregate; } + + public int getNetworkId() { + return this.networkId; + } } diff --git a/src/main/java/cn/nukkit/inventory/ShulkerBoxInventory.java b/src/main/java/cn/nukkit/inventory/ShulkerBoxInventory.java index ec0600a3712..4b71e098ca1 100644 --- a/src/main/java/cn/nukkit/inventory/ShulkerBoxInventory.java +++ b/src/main/java/cn/nukkit/inventory/ShulkerBoxInventory.java @@ -8,9 +8,6 @@ import cn.nukkit.network.protocol.BlockEventPacket; import cn.nukkit.network.protocol.LevelSoundEventPacket; -/** - * Created by PetteriM1 - */ public class ShulkerBoxInventory extends ContainerInventory { public ShulkerBoxInventory(BlockEntityShulkerBox box) { @@ -64,15 +61,19 @@ public void onClose(Player who) { @Override public boolean canAddItem(Item item) { - if (item.getId() == BlockID.SHULKER_BOX || item.getId() == BlockID.UNDYED_SHULKER_BOX) { - // Do not allow nested shulker boxes. - return false; - } - return super.canAddItem(item); + return this.allowedToAdd(item) && super.canAddItem(item); } @Override - public void sendSlot(int index, Player... players) { - super.sendSlot(index, players); + public boolean allowedToAdd(Item item) { + int itemId = item.getId(); + return itemId != BlockID.SHULKER_BOX && itemId != BlockID.UNDYED_SHULKER_BOX; + } + + @Override + public void onSlotChange(int index, Item before, boolean send) { + super.onSlotChange(index, before, send); + + this.getHolder().chunk.setChanged(); } } diff --git a/src/main/java/cn/nukkit/inventory/SmithingInventory.java b/src/main/java/cn/nukkit/inventory/SmithingInventory.java new file mode 100644 index 00000000000..cfbbd9e1bac --- /dev/null +++ b/src/main/java/cn/nukkit/inventory/SmithingInventory.java @@ -0,0 +1,100 @@ +package cn.nukkit.inventory; + +import cn.nukkit.Player; +import cn.nukkit.Server; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; +import cn.nukkit.level.Position; +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntSet; + +/** + * @author joserobjr + */ +public class SmithingInventory extends FakeBlockUIComponent { + + private static final int EQUIPMENT = 0; + private static final int INGREDIENT = 1; + + public static final int SMITHING_EQUIPMENT_UI_SLOT = 51; + + public static final int SMITHING_INGREDIENT_UI_SLOT = 52; + + private Item currentResult = Item.get(0); + + private static final IntSet ITEMS = new IntOpenHashSet(new int[]{ + Item.AIR, ItemID.NETHERITE_INGOT, ItemID.DIAMOND_SWORD, ItemID.DIAMOND_SHOVEL, ItemID.DIAMOND_PICKAXE, ItemID.DIAMOND_AXE, + ItemID.DIAMOND_HOE, ItemID.DIAMOND_HELMET, ItemID.DIAMOND_CHESTPLATE, ItemID.DIAMOND_LEGGINGS, ItemID.DIAMOND_BOOTS, + ItemID.NETHERITE_SWORD, ItemID.NETHERITE_SHOVEL, ItemID.NETHERITE_PICKAXE, ItemID.NETHERITE_AXE, ItemID.NETHERITE_HOE, + ItemID.NETHERITE_HELMET, ItemID.NETHERITE_CHESTPLATE, ItemID.NETHERITE_LEGGINGS, ItemID.NETHERITE_BOOTS}); + + public SmithingInventory(PlayerUIInventory playerUI, Position position) { + super(playerUI, InventoryType.SMITHING_TABLE, 51, position); + } + + public SmithingRecipe matchRecipe() { + return Server.getInstance().getCraftingManager().matchSmithingRecipe(getEquipment(), getIngredient()); + } + + @Override + public void onSlotChange(int index, Item before, boolean send) { + if (index == EQUIPMENT || index == INGREDIENT) { + updateResult(); + } + super.onSlotChange(index, before, send); + } + + public void updateResult() { + Item result; + SmithingRecipe recipe = matchRecipe(); + if (recipe == null) { + result = Item.get(0); + } else { + result = recipe.getFinalResult(getEquipment()); + } + setResult(result); + } + + private void setResult(Item result) { + this.currentResult = result; + } + + public Item getResult() { + SmithingRecipe recipe = matchRecipe(); + if (recipe == null) { + return Item.get(0); + } + return recipe.getFinalResult(getEquipment()); + } + + public Item getEquipment() { + return getItem(EQUIPMENT); + } + + public void setEquipment(Item equipment) { + setItem(EQUIPMENT, equipment); + } + + public Item getIngredient() { + return getItem(INGREDIENT); + } + + public void setIngredient(Item ingredient) { + setItem(INGREDIENT, ingredient); + } + + @Override + public void onOpen(Player who) { + super.onOpen(who); + who.craftingType = Player.CRAFTING_SMITHING; + } + + public Item getCurrentResult() { + return currentResult; + } + + @Override + public boolean allowedToAdd(Item item) { + return ITEMS.contains(item.getId()); + } +} diff --git a/src/main/java/cn/nukkit/inventory/SmithingRecipe.java b/src/main/java/cn/nukkit/inventory/SmithingRecipe.java new file mode 100644 index 00000000000..1e9b9d2050a --- /dev/null +++ b/src/main/java/cn/nukkit/inventory/SmithingRecipe.java @@ -0,0 +1,150 @@ +package cn.nukkit.inventory; + +import cn.nukkit.item.Item; +import lombok.ToString; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +/** + * @author joserobjr + */ +@ToString +public class SmithingRecipe extends ShapelessRecipe { + private final Item equipment; + private final Item ingredient; + private final Item result; + + private final List ingredientsAggregate; + + public SmithingRecipe(String recipeId, int priority, Collection ingredients, Item result) { + super(recipeId, priority, result, ingredients); + this.equipment = (Item) ingredients.toArray()[0]; + this.ingredient = (Item) ingredients.toArray()[1]; + this.result = result; + + ArrayList aggregation = new ArrayList<>(2); + + for (Item item : new Item[]{equipment, ingredient}) { + if (item.getCount() < 1) { + throw new IllegalArgumentException("Recipe Ingredient amount was not 1 (value: " + item.getCount() + ")"); + } + boolean found = false; + for (Item existingIngredient : aggregation) { + if (existingIngredient.equals(item, item.hasMeta(), item.hasCompoundTag())) { + existingIngredient.setCount(existingIngredient.getCount() + item.getCount()); + found = true; + break; + } + } + if (!found) { + aggregation.add(item.clone()); + } + } + + aggregation.trimToSize(); + aggregation.sort(CraftingManager.recipeComparator); + this.ingredientsAggregate = Collections.unmodifiableList(aggregation); + } + + @Override + public Item getResult() { + return result; + } + + public Item getFinalResult(Item equip) { + Item finalResult = getResult().clone(); + + if (equip.hasCompoundTag()) { + finalResult.setCompoundTag(equip.getCompoundTag()); + } + + int maxDurability = finalResult.getMaxDurability(); + if (maxDurability <= 0 || equip.getMaxDurability() <= 0) { + return finalResult; + } + + int damage = equip.getDamage(); + if (damage <= 0) { + return finalResult; + } + + finalResult.setDamage(Math.min(maxDurability, damage)); + return finalResult; + } + + @Override + public void registerToCraftingManager(CraftingManager manager) { + manager.registerSmithingRecipe(this); + } + + @Override + public RecipeType getType() { + return RecipeType.SMITHING_TRANSFORM; + } + + public Item getEquipment() { + return equipment; + } + + public Item getIngredient() { + return ingredient; + } + + public List getIngredientsAggregate() { + return ingredientsAggregate; + } + + public boolean matchItems(List inputList) { + return matchItems(inputList, 1); + } + + public boolean matchItems(List inputList, int multiplier) { + List haveInputs = new ArrayList<>(); + for (Item item : inputList) { + if (item.isNull()) + continue; + haveInputs.add(item.clone()); + } + List needInputs = new ArrayList<>(); + if (multiplier != 1) { + for (Item item : ingredientsAggregate) { + if (item.isNull()) + continue; + Item itemClone = item.clone(); + itemClone.setCount(itemClone.getCount() * multiplier); + needInputs.add(itemClone); + } + } else { + for (Item item : ingredientsAggregate) { + if (item.isNull()) + continue; + needInputs.add(item.clone()); + } + } + + return matchItemList(haveInputs, needInputs); + } + + private static boolean matchItemList(List haveItems, List needItems) { + for (Item needItem : new ArrayList<>(needItems)) { + for (Item haveItem : new ArrayList<>(haveItems)) { + if (needItem.equals(haveItem, needItem.hasMeta(), needItem.hasCompoundTag())) { + int amount = Math.min(haveItem.getCount(), needItem.getCount()); + needItem.setCount(needItem.getCount() - amount); + haveItem.setCount(haveItem.getCount() - amount); + if (haveItem.getCount() == 0) { + haveItems.remove(haveItem); + } + if (needItem.getCount() == 0) { + needItems.remove(needItem); + break; + } + } + } + } + return haveItems.isEmpty() && needItems.isEmpty(); + } +} diff --git a/src/main/java/cn/nukkit/inventory/SmokerInventory.java b/src/main/java/cn/nukkit/inventory/SmokerInventory.java new file mode 100644 index 00000000000..1994b88810e --- /dev/null +++ b/src/main/java/cn/nukkit/inventory/SmokerInventory.java @@ -0,0 +1,15 @@ +package cn.nukkit.inventory; + +import cn.nukkit.blockentity.BlockEntitySmoker; + +public class SmokerInventory extends FurnaceInventory { + + public SmokerInventory(BlockEntitySmoker smoker) { + super(smoker, InventoryType.SMOKER); + } + + @Override + public BlockEntitySmoker getHolder() { + return (BlockEntitySmoker) this.holder; + } +} diff --git a/src/main/java/cn/nukkit/inventory/TradeInventory.java b/src/main/java/cn/nukkit/inventory/TradeInventory.java new file mode 100644 index 00000000000..7f184d49ae7 --- /dev/null +++ b/src/main/java/cn/nukkit/inventory/TradeInventory.java @@ -0,0 +1,53 @@ +package cn.nukkit.inventory; + +import cn.nukkit.Player; +import cn.nukkit.entity.passive.EntityVillagerV1; +import cn.nukkit.item.Item; +import cn.nukkit.nbt.NBTIO; +import cn.nukkit.network.protocol.UpdateTradePacket; + +import java.io.IOException; +import java.nio.ByteOrder; + +public class TradeInventory extends BaseInventory { + + public TradeInventory(InventoryHolder holder) { + super(holder, InventoryType.TRADING); + } + + public void onOpen(Player who) { + super.onOpen(who); + + UpdateTradePacket pk = new UpdateTradePacket(); + pk.windowId = (byte) who.getWindowId(this); + pk.windowType = (byte) InventoryType.TRADING.getNetworkType(); + pk.isWilling = this.getHolder().isWilling(); + pk.screen2 = false; // use old trade screen + pk.trader = this.getHolder().getId(); + pk.tradeTier = this.getHolder().getTradeTier(); + pk.player = who.getId(); + try { + pk.offers = NBTIO.write(this.getHolder().getOffers(),ByteOrder.LITTLE_ENDIAN, true); + } catch (IOException ignored) {} + + who.dataPacket(pk); + } + + public void onClose(Player who) { + for (int i = 0; i <= 1; i++) { + Item item = getItem(i); + this.clear(i); + if (who.getInventory().canAddItem(item)) { + who.getInventory().addItem(item); + } else { + who.level.dropItem(who, item); + } + } + + super.onClose(who); + } + + public EntityVillagerV1 getHolder() { + return (EntityVillagerV1) this.holder; + } +} diff --git a/src/main/java/cn/nukkit/inventory/TradeInventoryRecipe.java b/src/main/java/cn/nukkit/inventory/TradeInventoryRecipe.java new file mode 100644 index 00000000000..0e042cd5202 --- /dev/null +++ b/src/main/java/cn/nukkit/inventory/TradeInventoryRecipe.java @@ -0,0 +1,114 @@ +package cn.nukkit.inventory; + +import cn.nukkit.item.Item; +import cn.nukkit.nbt.NBTIO; +import cn.nukkit.nbt.tag.CompoundTag; +import lombok.Getter; + +public class TradeInventoryRecipe { + + public static final int A_ITEM = 0; + public static final int B_ITEM = 1; + @Getter + private final Item sellItem; + @Getter + private final Item buyItem; + @Getter + private final Item secondBuyItem; + + private int tier = -1; + private int maxUses = 999; + private int buyCountA = 0; + private int buyCountB = 0; + private final int uses = 0; + private int demand = 0; + private int rewardsExp = 0; + private final int traderExp = 0; + private float priceMultiplierA = 0F; + private float priceMultiplierB = 0F; + + public TradeInventoryRecipe(Item sellItem, Item buyItem) { + this(sellItem, buyItem, Item.get(0)); + } + + public TradeInventoryRecipe(Item sellItem, Item buyItem, Item secondBuyItem) { + this.sellItem = sellItem; + this.buyItem = buyItem; + this.secondBuyItem = secondBuyItem; + } + + public TradeInventoryRecipe setTier(int tier) { + this.tier = tier; + return this; + } + + public TradeInventoryRecipe setMaxUses(int maxUses) { + this.maxUses = maxUses; + return this; + } + + public TradeInventoryRecipe setBuyCount(int count, int type) { + switch (type) { + case 0: + this.buyCountA = count; + break; + case 1: + this.buyCountB = count; + break; + } + this.buyCountA = count; + return this; + } + + public TradeInventoryRecipe setDemand(int demand) { + this.demand = demand; + return this; + } + + public TradeInventoryRecipe setMultiplier(float multiplier, int type) { + switch (type) { + case 0: + this.priceMultiplierA = multiplier; + break; + case 1: + this.priceMultiplierB = multiplier; + break; + } + return this; + } + + public TradeInventoryRecipe setRewardExp(int reward) { + this.rewardsExp = reward; + return this; + } + + public CompoundTag toNBT() { + CompoundTag nbt = new CompoundTag(); + nbt.putCompound("buyA", NBTIO.putItemHelper(buyItem, -1)); + nbt.putCompound("buyB", NBTIO.putItemHelper(secondBuyItem,-1)); + nbt.putCompound("sell", NBTIO.putItemHelper(sellItem, -1)); + nbt.putInt("tier", tier); + nbt.putInt("buyCountA", buyCountA); + nbt.putInt("buyCountB", buyCountB); + nbt.putInt("uses", uses); + nbt.putInt("maxUses", maxUses); + nbt.putInt("rewardExp", rewardsExp); + nbt.putInt("demand", demand); + nbt.putInt("traderExp", traderExp); + nbt.putFloat("priceMultiplierA", priceMultiplierA); + nbt.putFloat("priceMultiplierB", priceMultiplierB); + return nbt; + } + + public static TradeInventoryRecipe toNBT(CompoundTag nbt) { + return new TradeInventoryRecipe(NBTIO.getItemHelper(nbt.getCompound("sell")), NBTIO.getItemHelper(nbt.getCompound("buyA")), NBTIO.getItemHelper(nbt.getCompound("buyB"))) + .setTier(nbt.getInt("tier")) + .setBuyCount(nbt.getInt("buyCountA"), A_ITEM) + .setBuyCount(nbt.getInt("buyCountB"), B_ITEM) + .setMaxUses(nbt.getInt("maxUses")) + .setMultiplier(nbt.getInt("priceMultiplierA"), A_ITEM) + .setMultiplier(nbt.getInt("priceMultiplierB"), B_ITEM) + .setDemand(nbt.getInt("demand")) + .setRewardExp(nbt.getInt("rewardExp")); + } +} diff --git a/src/main/java/cn/nukkit/inventory/transaction/CraftingTransaction.java b/src/main/java/cn/nukkit/inventory/transaction/CraftingTransaction.java index 910c9cc33cc..a603bbf24dc 100644 --- a/src/main/java/cn/nukkit/inventory/transaction/CraftingTransaction.java +++ b/src/main/java/cn/nukkit/inventory/transaction/CraftingTransaction.java @@ -1,10 +1,9 @@ package cn.nukkit.inventory.transaction; import cn.nukkit.Player; +import cn.nukkit.Server; import cn.nukkit.event.inventory.CraftItemEvent; -import cn.nukkit.inventory.BigCraftingGrid; -import cn.nukkit.inventory.CraftingRecipe; -import cn.nukkit.inventory.InventoryType; +import cn.nukkit.inventory.*; import cn.nukkit.inventory.transaction.action.InventoryAction; import cn.nukkit.inventory.transaction.action.SlotChangeAction; import cn.nukkit.item.Item; @@ -76,7 +75,7 @@ public void setPrimaryOutput(Item item) { if (primaryOutput == null) { primaryOutput = item.clone(); } else if (!primaryOutput.equals(item)) { - throw new RuntimeException("Primary result item has already been set and does not match the current item (expected " + primaryOutput + ", got " + item + ")"); + throw new RuntimeException("Primary result item has already been set and does not match the current item (expected " + primaryOutput + ", got " + item + ')'); } } @@ -85,7 +84,26 @@ public CraftingRecipe getRecipe() { } public boolean canExecute() { - recipe = source.getServer().getCraftingManager().matchRecipe(inputs, this.primaryOutput, this.secondaryOutputs); + if (source.craftingType == Player.CRAFTING_LOOM) { + Inventory inventory = source.getWindowById(Player.LOOM_WINDOW_ID); + if (inventory instanceof LoomInventory) { + addInventory(inventory); + } + } else if (source.craftingType == Player.CRAFTING_SMITHING) { + Inventory inventory = source.getWindowById(Player.SMITHING_WINDOW_ID); + if (inventory instanceof SmithingInventory) { + addInventory(inventory); + + SmithingInventory smithingInventory = (SmithingInventory) inventory; + SmithingRecipe smithingRecipe = smithingInventory.matchRecipe(); + if (smithingRecipe != null && this.primaryOutput.equals(smithingRecipe.getFinalResult(smithingInventory.getEquipment()), true, true)) { + return super.canExecute(); + } + return false; + } + } else { + recipe = source.getServer().getCraftingManager().matchRecipe(inputs, this.primaryOutput, this.secondaryOutputs); + } return this.recipe != null && super.canExecute(); } @@ -103,12 +121,12 @@ protected void sendInventories() { return; // Already closed } - /* + /* * TODO: HACK! - * we can't resend the contents of the crafting window, so we force the client to close it instead. - * So people don't whine about messy desync issues when someone cancels CraftItemEvent, or when a crafting - * transaction goes wrong. - */ + * we can't resend the contents of the crafting window, so we force the client to close it instead. + * So people don't whine about messy desync issues when someone cancels CraftItemEvent, or when a crafting + * transaction goes wrong. + */ source.getServer().getScheduler().scheduleDelayedTask(new Task() { @Override public void onRun(int currentTick) { @@ -119,7 +137,7 @@ public void onRun(int currentTick) { source.dataPacket(pk); } } - }, 20); + }, 10); this.source.resetCraftingGridType(); } @@ -149,13 +167,22 @@ public boolean execute() { case Item.GOLDEN_PICKAXE: case Item.IRON_PICKAXE: case Item.DIAMOND_PICKAXE: + case Item.NETHERITE_PICKAXE: source.awardAchievement("buildBetterPickaxe"); break; case Item.WOODEN_SWORD: + case Item.STONE_SWORD: + case Item.GOLDEN_SWORD: + case Item.IRON_SWORD: + case Item.DIAMOND_SWORD: + case Item.NETHERITE_SWORD: source.awardAchievement("buildSword"); break; - case Item.DIAMOND: - source.awardAchievement("diamond"); + case Item.ENCHANT_TABLE: + source.awardAchievement("enchantments"); + break; + case Item.BOOKSHELF: + source.awardAchievement("bookcase"); break; } @@ -169,12 +196,28 @@ public boolean checkForCraftingPart(List actions) { for (InventoryAction action : actions) { if (action instanceof SlotChangeAction) { SlotChangeAction slotChangeAction = (SlotChangeAction) action; - if (slotChangeAction.getInventory().getType() == InventoryType.UI && slotChangeAction.getSlot() == 50 && - !slotChangeAction.getSourceItem().equals(slotChangeAction.getTargetItem())) { - return true; + if (slotChangeAction.getInventory().getType() == InventoryType.UI) { + if (slotChangeAction.getSlot() == 50) { + if (!slotChangeAction.getSourceItem().equals(slotChangeAction.getTargetItem())) { + return true; + } else { + Server.getInstance().getLogger().debug("Source equals target"); + return false; + } + } else { + Server.getInstance().getLogger().debug("Invalid slot: " + slotChangeAction.getSlot()); + return false; + } + } else { + Server.getInstance().getLogger().debug("Invalid action type: " + slotChangeAction.getInventory().getType()); + return false; } + } else { + Server.getInstance().getLogger().debug("SlotChangeAction expected, got " + action); + return false; } } + Server.getInstance().getLogger().debug("No actions on the list"); return false; } } diff --git a/src/main/java/cn/nukkit/inventory/transaction/EnchantTransaction.java b/src/main/java/cn/nukkit/inventory/transaction/EnchantTransaction.java index 8b828d17ebe..a9959c68424 100644 --- a/src/main/java/cn/nukkit/inventory/transaction/EnchantTransaction.java +++ b/src/main/java/cn/nukkit/inventory/transaction/EnchantTransaction.java @@ -6,6 +6,7 @@ import cn.nukkit.inventory.Inventory; import cn.nukkit.inventory.transaction.action.EnchantingAction; import cn.nukkit.inventory.transaction.action.InventoryAction; +import cn.nukkit.inventory.transaction.action.SlotChangeAction; import cn.nukkit.item.Item; import cn.nukkit.network.protocol.types.NetworkInventoryAction; import lombok.Getter; @@ -16,24 +17,49 @@ @Getter @Setter public class EnchantTransaction extends InventoryTransaction { + private Item inputItem; private Item outputItem; + private Item outputItemCheck; + private int cost = -1; public EnchantTransaction(Player source, List actions) { super(source, actions); + + for (InventoryAction action : actions) { + if (action instanceof SlotChangeAction) { + SlotChangeAction slotChangeAction = (SlotChangeAction) action; + if (slotChangeAction.getInventory() instanceof EnchantInventory && slotChangeAction.getSlot() == 0) { + this.outputItemCheck = slotChangeAction.getTargetItem(); + } + } + } } @Override public boolean canExecute() { Inventory inv = getSource().getWindowById(Player.ENCHANT_WINDOW_ID); - if (inv == null) return false; + if (!(inv instanceof EnchantInventory)) { + return false; + } EnchantInventory eInv = (EnchantInventory) inv; if (!getSource().isCreative()) { - if (cost == -1 || !eInv.getReagentSlot().equals(Item.get(Item.DYE, 4), true, false) || eInv.getReagentSlot().count < cost) + if (this.cost < 1) { return false; + } else { + Item reagent = eInv.getReagentSlot(); + if (reagent.count < this.cost || !reagent.equals(Item.get(Item.DYE, 4), true, false)) { + return false; + } + } } - return (inputItem != null && outputItem != null && inputItem.equals(eInv.getInputSlot(), true, true)); + return this.inputItem != null && this.outputItem != null + && this.inputItem.equals(eInv.getInputSlot(), true, true) + && (this.outputItemCheck == null || this.inputItem.getId() == this.outputItemCheck.getId() || + (this.inputItem.getId() == Item.BOOK && this.outputItemCheck.getId() == Item.ENCHANTED_BOOK)) + && (this.outputItemCheck == null || this.inputItem.getCount() == this.outputItemCheck.getCount() || + (this.outputItemCheck.getId() == Item.ENCHANTED_BOOK && this.outputItemCheck.getCount() == 1)); } @Override @@ -50,7 +76,6 @@ public boolean execute() { if (ev.isCancelled()) { source.removeAllWindows(false); this.sendInventories(); - // Cancelled by plugin, means handled OK return true; } @@ -87,10 +112,10 @@ public void addAction(InventoryAction action) { this.outputItem = action.getSourceItem(); // Output sent as oldItem break; case NetworkInventoryAction.SOURCE_TYPE_ENCHANT_MATERIAL: - if (action.getTargetItem().equals(Item.get(Item.AIR), false, false)) { - this.cost = action.getSourceItem().count; + if (action.getTargetItemUnsafe().getId() == Item.AIR) { + this.cost = action.getSourceItemUnsafe().count; } else { - this.cost = action.getSourceItem().count - action.getTargetItem().count; + this.cost = action.getSourceItemUnsafe().count - action.getTargetItemUnsafe().count; } break; } diff --git a/src/main/java/cn/nukkit/inventory/transaction/InventoryTransaction.java b/src/main/java/cn/nukkit/inventory/transaction/InventoryTransaction.java index 1e4dda97451..634599db43b 100644 --- a/src/main/java/cn/nukkit/inventory/transaction/InventoryTransaction.java +++ b/src/main/java/cn/nukkit/inventory/transaction/InventoryTransaction.java @@ -1,12 +1,14 @@ package cn.nukkit.inventory.transaction; import cn.nukkit.Player; +import cn.nukkit.Server; import cn.nukkit.event.inventory.InventoryClickEvent; import cn.nukkit.event.inventory.InventoryTransactionEvent; import cn.nukkit.inventory.Inventory; import cn.nukkit.inventory.transaction.action.InventoryAction; import cn.nukkit.inventory.transaction.action.SlotChangeAction; import cn.nukkit.item.Item; +import cn.nukkit.item.enchantment.Enchantment; import java.util.*; @@ -15,7 +17,7 @@ */ public class InventoryTransaction { - private long creationTime; + private boolean invalid; protected boolean hasExecuted; protected Player source; @@ -35,7 +37,7 @@ public InventoryTransaction(Player source, List actions, boolea } protected void init(Player source, List actions) { - creationTime = System.currentTimeMillis(); + //creationTime = System.currentTimeMillis(); this.source = source; for (InventoryAction action : actions) { @@ -48,7 +50,7 @@ public Player getSource() { } public long getCreationTime() { - return creationTime; + return 0; // unused } public Set getInventories() { @@ -64,8 +66,38 @@ public Set getActions() { } public void addAction(InventoryAction action) { + if (invalid) { + Server.getInstance().getLogger().debug("Failed to add InventoryAction for " + source.getName() + ": previous run was marked as invalid"); + return; + } + if (action instanceof SlotChangeAction) { - SlotChangeAction slotChangeAction = (SlotChangeAction) action; + SlotChangeAction slotChangeAction = (SlotChangeAction)action; + + Item targetItem = slotChangeAction.getTargetItemUnsafe(); + Item sourceItem = slotChangeAction.getSourceItemUnsafe(); + if (targetItem.getCount() > targetItem.getMaxStackSize() || sourceItem.getCount() > sourceItem.getMaxStackSize()) { + invalid = true; + Server.getInstance().getLogger().debug("Failed to add SlotChangeAction for " + source.getName() + ": illegal item stack size"); + return; + } + + if (!slotChangeAction.getInventory().allowedToAdd(targetItem)) { + invalid = true; + Server.getInstance().getLogger().debug("Failed to add SlotChangeAction for " + source.getName() + ": " + slotChangeAction.getInventory().getName() + " inventory doesn't allow item " + targetItem.getId()); + return; + } + + if (!source.isCreative()) { + int slot = slotChangeAction.getSlot(); + if (slot == 36 || slot == 37 || slot == 38 || slot == 39) { + if (sourceItem.hasEnchantment(Enchantment.ID_BINDING_CURSE)) { + invalid = true; + Server.getInstance().getLogger().debug("Failed to add SlotChangeAction for " + source.getName() + ": armor has binding curse"); + return; + } + } + } ListIterator iterator = this.actions.listIterator(); @@ -77,22 +109,22 @@ public void addAction(InventoryAction action) { continue; Item existingSource = existingSlotChangeAction.getSourceItem(); Item existingTarget = existingSlotChangeAction.getTargetItem(); - if (existingSlotChangeAction.getSlot() == slotChangeAction.getSlot() - && slotChangeAction.getSourceItem().equals(existingTarget, existingTarget.hasMeta(), existingTarget.hasCompoundTag())) { + if (existingSlotChangeAction.getSlot() == slotChangeAction.getSlot() && slotChangeAction.getSourceItem().equals(existingTarget, existingTarget.hasMeta(), existingTarget.hasCompoundTag())) { iterator.set(new SlotChangeAction(existingSlotChangeAction.getInventory(), existingSlotChangeAction.getSlot(), existingSlotChangeAction.getSourceItem(), slotChangeAction.getTargetItem())); action.onAddToTransaction(this); return; } else if (existingSlotChangeAction.getSlot() == slotChangeAction.getSlot() && slotChangeAction.getSourceItem().equals(existingSource, existingSource.hasMeta(), existingSource.hasCompoundTag()) && slotChangeAction.getTargetItem().equals(existingTarget, existingTarget.hasMeta(), existingTarget.hasCompoundTag())) { - existingSource.setCount(existingSource.getCount() + slotChangeAction.getSourceItem().getCount()); - existingTarget.setCount(existingTarget.getCount() + slotChangeAction.getTargetItem().getCount()); + existingSource.setCount(existingSource.getCount() + slotChangeAction.getSourceItemUnsafe().getCount()); + existingTarget.setCount(existingTarget.getCount() + slotChangeAction.getTargetItemUnsafe().getCount()); iterator.set(new SlotChangeAction(existingSlotChangeAction.getInventory(), existingSlotChangeAction.getSlot(), existingSource, existingTarget)); return; } } } } + this.actions.add(action); action.onAddToTransaction(this); } @@ -109,15 +141,16 @@ public void addInventory(Inventory inventory) { protected boolean matchItems(List needItems, List haveItems) { for (InventoryAction action : this.actions) { - if (action.getTargetItem().getId() != Item.AIR) { + if (action.getTargetItemUnsafe().getId() != Item.AIR) { needItems.add(action.getTargetItem()); } if (!action.isValid(this.source)) { + invalid = true; return false; } - if (action.getSourceItem().getId() != Item.AIR) { + if (action.getSourceItemUnsafe().getId() != Item.AIR) { haveItems.add(action.getSourceItem()); } } @@ -146,7 +179,6 @@ protected void sendInventories() { for (InventoryAction action : this.actions) { if (action instanceof SlotChangeAction) { SlotChangeAction sca = (SlotChangeAction) action; - sca.getInventory().sendSlot(sca.getSlot(), this.source); } } @@ -155,7 +187,7 @@ protected void sendInventories() { public boolean canExecute() { List haveItems = new ArrayList<>(); List needItems = new ArrayList<>(); - return matchItems(needItems, haveItems) && this.actions.size() > 0 && haveItems.size() == 0 && needItems.size() == 0; + return matchItems(needItems, haveItems) && !invalid && !this.actions.isEmpty() && haveItems.isEmpty() && needItems.isEmpty(); } protected boolean callExecuteEvent() { @@ -184,7 +216,7 @@ protected boolean callExecuteEvent() { } if (who != null && to != null) { - if (from.getTargetItem().getCount() > from.getSourceItem().getCount()) { + if (from.getTargetItemUnsafe().getCount() > from.getSourceItemUnsafe().getCount()) { from = to; } @@ -200,12 +232,11 @@ protected boolean callExecuteEvent() { } public boolean execute() { - if (this.hasExecuted() || !this.canExecute()) { + if (invalid || this.hasExecuted() || !this.canExecute()) { this.sendInventories(); return false; } - if (!callExecuteEvent()) { this.sendInventories(); return true; diff --git a/src/main/java/cn/nukkit/inventory/transaction/LoomTransaction.java b/src/main/java/cn/nukkit/inventory/transaction/LoomTransaction.java new file mode 100644 index 00000000000..2b5073499e2 --- /dev/null +++ b/src/main/java/cn/nukkit/inventory/transaction/LoomTransaction.java @@ -0,0 +1,100 @@ +package cn.nukkit.inventory.transaction; + +import cn.nukkit.Player; +import cn.nukkit.event.inventory.LoomItemEvent; +import cn.nukkit.inventory.Inventory; +import cn.nukkit.inventory.LoomInventory; +import cn.nukkit.inventory.transaction.action.InventoryAction; +import cn.nukkit.inventory.transaction.action.LoomItemAction; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; + +import java.util.List; + +public class LoomTransaction extends InventoryTransaction { + + private Item outputItem; + + public LoomTransaction(Player source, List actions) { + super(source, actions); + } + + @Override + public void addAction(InventoryAction action) { + super.addAction(action); + + if (action instanceof LoomItemAction) { + outputItem = action.getSourceItem(); + } + } + + @Override + public boolean canExecute() { + if (!super.canExecute()) { + return false; + } + + Inventory inventory = getSource().getWindowById(Player.LOOM_WINDOW_ID); + if (!(inventory instanceof LoomInventory)) { + return false; + } + + if (outputItem == null) { + return false; + } + + LoomInventory loomInventory = (LoomInventory) inventory; + Item banner = loomInventory.getBanner(); + Item dye = loomInventory.getDye(); + if (banner.getId() != Item.BANNER || dye.getId() != Item.DYE || banner.getDamage() != outputItem.getDamage()) { + return false; + } + + if (!outputItem.hasCompoundTag()) { + return false; + } + + int patternCount = outputItem.getNamedTag().getList("Patterns").size(); + if (banner.getNamedTag() == null) { + return patternCount == 1; + } + + if (patternCount > 6) { + return false; + } + + Item pattern = loomInventory.getPattern(); + if (pattern.getId() != 0 && pattern.getId() != ItemID.BANNER_PATTERN) { + return false; + } + + return banner.getNamedTag().getList("Patterns").size() + 1 == patternCount; + } + + @Override + protected boolean callExecuteEvent() { + LoomInventory inventory = (LoomInventory) getSource().getWindowById(Player.LOOM_WINDOW_ID); + LoomItemEvent event = new LoomItemEvent(inventory, this.outputItem, this.source); + this.source.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + this.source.removeAllWindows(false); + this.sendInventories(); + return false; + } + return true; + } + + @Override + protected void sendInventories() { + this.source.removeAllWindows(false); + super.sendInventories(); + } + + public Item getOutputItem() { + return this.outputItem; + } + + public static boolean checkForItemPart(List actions) { + return actions.stream().anyMatch(it-> it instanceof LoomItemAction); + } +} diff --git a/src/main/java/cn/nukkit/inventory/transaction/RepairItemTransaction.java b/src/main/java/cn/nukkit/inventory/transaction/RepairItemTransaction.java index c6c5cd0e9f1..9ef9c0e96f0 100644 --- a/src/main/java/cn/nukkit/inventory/transaction/RepairItemTransaction.java +++ b/src/main/java/cn/nukkit/inventory/transaction/RepairItemTransaction.java @@ -8,8 +8,10 @@ import cn.nukkit.inventory.AnvilInventory; import cn.nukkit.inventory.FakeBlockMenu; import cn.nukkit.inventory.Inventory; -import cn.nukkit.inventory.transaction.action.RepairItemAction; +import cn.nukkit.inventory.PlayerInventory; import cn.nukkit.inventory.transaction.action.InventoryAction; +import cn.nukkit.inventory.transaction.action.RepairItemAction; +import cn.nukkit.inventory.transaction.action.SlotChangeAction; import cn.nukkit.item.Item; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.network.protocol.LevelEventPacket; @@ -25,22 +27,38 @@ public class RepairItemTransaction extends InventoryTransaction { private Item inputItem; private Item materialItem; private Item outputItem; + private Item outputItemCheck; private int cost; public RepairItemTransaction(Player source, List actions) { super(source, actions); + + for (InventoryAction action : actions) { + if (action instanceof SlotChangeAction) { + SlotChangeAction slotChangeAction = (SlotChangeAction) action; + if (slotChangeAction.getInventory() instanceof PlayerInventory) { + this.outputItemCheck = slotChangeAction.getTargetItem(); + } + } + } } @Override public boolean canExecute() { + if (!super.canExecute()) { + return false; + } + Inventory inventory = getSource().getWindowById(Player.ANVIL_WINDOW_ID); - if (inventory == null) { + if (!(inventory instanceof AnvilInventory)) { return false; } AnvilInventory anvilInventory = (AnvilInventory) inventory; return this.inputItem != null && this.outputItem != null && this.inputItem.equals(anvilInventory.getInputSlot(), true, true) && (!this.hasMaterial() || this.materialItem.equals(anvilInventory.getMaterialSlot(), true, true)) + && (this.outputItemCheck == null || this.inputItem.getId() == this.outputItemCheck.getId()) + && (this.outputItemCheck == null || this.inputItem.getCount() == this.outputItemCheck.getCount()) && this.checkRecipeValid(); } @@ -54,7 +72,7 @@ public boolean execute() { AnvilInventory inventory = (AnvilInventory) getSource().getWindowById(Player.ANVIL_WINDOW_ID); if (inventory.getCost() != this.cost && !this.source.isCreative()) { - this.source.getServer().getLogger().debug("Got unexpected cost " + inventory.getCost() + " from " + this.source.getName() + "(expected " + this.cost + ")"); + this.source.getServer().getLogger().debug("Got unexpected cost " + inventory.getCost() + " from " + this.source.getName() + "(expected " + this.cost + ')'); } RepairItemEvent event = new RepairItemEvent(inventory, this.inputItem, this.outputItem, this.materialItem, this.cost, this.source); @@ -272,7 +290,7 @@ private boolean checkRecipeValid() { } } if (this.outputItem.getRepairCost() != nextBaseRepairCost) { - this.source.getServer().getLogger().debug("Got unexpected base cost " + this.outputItem.getRepairCost() + " from " + this.source.getName() + "(expected " + nextBaseRepairCost + ")"); + this.source.getServer().getLogger().debug("Got unexpected base cost " + this.outputItem.getRepairCost() + " from " + this.source.getName() + "(expected " + nextBaseRepairCost + ')'); return false; } diff --git a/src/main/java/cn/nukkit/inventory/transaction/SmithingTransaction.java b/src/main/java/cn/nukkit/inventory/transaction/SmithingTransaction.java new file mode 100644 index 00000000000..e3f25b56d52 --- /dev/null +++ b/src/main/java/cn/nukkit/inventory/transaction/SmithingTransaction.java @@ -0,0 +1,120 @@ +package cn.nukkit.inventory.transaction; + +import cn.nukkit.Player; +import cn.nukkit.event.inventory.SmithItemEvent; +import cn.nukkit.inventory.Inventory; +import cn.nukkit.inventory.SmithingInventory; +import cn.nukkit.inventory.transaction.action.CreativeInventoryAction; +import cn.nukkit.inventory.transaction.action.InventoryAction; +import cn.nukkit.inventory.transaction.action.SmithingItemAction; +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; + +import java.util.List; + +/** + * @author joserobjr + */ +public class SmithingTransaction extends InventoryTransaction { + + private Item equipmentItem; + private Item ingredientItem; + private Item outputItem; + + public SmithingTransaction(Player source, List actions) { + super(source, actions); + } + + @Override + public void addAction(InventoryAction action) { + super.addAction(action); + if (action instanceof SmithingItemAction) { + switch (((SmithingItemAction) action).getType()) { + case 0: // input + this.equipmentItem = action.getTargetItem(); + break; + case 1: // ingredient + this.ingredientItem = action.getTargetItem(); + break; + case 2: // result + this.outputItem = action.getSourceItem(); + break; + } + } else if (action instanceof CreativeInventoryAction) { + CreativeInventoryAction creativeAction = (CreativeInventoryAction) action; + if (creativeAction.getActionType() == 0 + && creativeAction.getSourceItemUnsafe().isNull() + && !creativeAction.getTargetItemUnsafe().isNull() && creativeAction.getTargetItemUnsafe().getId() == ItemID.NETHERITE_INGOT) { + this.ingredientItem = action.getTargetItem(); + } + } + } + + @Override + public boolean canExecute() { + Inventory inventory = getSource().getWindowById(Player.SMITHING_WINDOW_ID); + if (!(inventory instanceof SmithingInventory)) { + return false; + } + SmithingInventory smithingInventory = (SmithingInventory) inventory; + if (outputItem == null || outputItem.isNull() || + ((equipmentItem == null || equipmentItem.isNull()) && (ingredientItem == null || ingredientItem.isNull()))) { + return false; + } + + Item air = Item.get(0); + Item equipment = equipmentItem != null ? equipmentItem : air; + Item ingredient = ingredientItem != null ? ingredientItem : air; + + return equipment.equals(smithingInventory.getEquipment(), true, true) + && ingredient.equals(smithingInventory.getIngredient(), true, true) + && outputItem.equals(smithingInventory.getResult(), true, true); + } + + @Override + public boolean execute() { + if (this.hasExecuted() || !this.canExecute()) { + this.source.removeAllWindows(false); + this.sendInventories(); + return false; + } + + SmithingInventory inventory = (SmithingInventory) getSource().getWindowById(Player.SMITHING_WINDOW_ID); + SmithItemEvent event = new SmithItemEvent(inventory, this.equipmentItem, this.outputItem, this.ingredientItem, this.source); + this.source.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + this.source.removeAllWindows(false); + this.sendInventories(); + return true; + } + + for (InventoryAction action : this.actions) { + if (action.execute(this.source)) { + action.onExecuteSuccess(this.source); + } else { + action.onExecuteFail(this.source); + } + } + + if (inventory != null) { + inventory.sendContents(source); + } + return true; + } + + public Item getInputItem() { + return this.equipmentItem; + } + + public Item getMaterialItem() { + return this.ingredientItem; + } + + public Item getOutputItem() { + return this.outputItem; + } + + public static boolean checkForItemPart(List actions) { + return actions.stream().anyMatch(it-> it instanceof SmithingItemAction); + } +} diff --git a/src/main/java/cn/nukkit/inventory/transaction/action/CraftingTakeResultAction.java b/src/main/java/cn/nukkit/inventory/transaction/action/CraftingTakeResultAction.java index bee879d4230..b1484827cdc 100644 --- a/src/main/java/cn/nukkit/inventory/transaction/action/CraftingTakeResultAction.java +++ b/src/main/java/cn/nukkit/inventory/transaction/action/CraftingTakeResultAction.java @@ -34,11 +34,9 @@ public boolean execute(Player source) { @Override public void onExecuteSuccess(Player $source) { - } @Override public void onExecuteFail(Player source) { - } } diff --git a/src/main/java/cn/nukkit/inventory/transaction/action/CraftingTransferMaterialAction.java b/src/main/java/cn/nukkit/inventory/transaction/action/CraftingTransferMaterialAction.java index aa872ec9d32..137b86839ea 100644 --- a/src/main/java/cn/nukkit/inventory/transaction/action/CraftingTransferMaterialAction.java +++ b/src/main/java/cn/nukkit/inventory/transaction/action/CraftingTransferMaterialAction.java @@ -10,12 +10,8 @@ */ public class CraftingTransferMaterialAction extends InventoryAction { - private int slot; - public CraftingTransferMaterialAction(Item sourceItem, Item targetItem, int slot) { super(sourceItem, targetItem); - - this.slot = slot; } @Override @@ -45,11 +41,9 @@ public boolean execute(Player source) { @Override public void onExecuteSuccess(Player $source) { - } @Override public void onExecuteFail(Player source) { - } } diff --git a/src/main/java/cn/nukkit/inventory/transaction/action/CreativeInventoryAction.java b/src/main/java/cn/nukkit/inventory/transaction/action/CreativeInventoryAction.java index d92948d8e8b..804923111dd 100644 --- a/src/main/java/cn/nukkit/inventory/transaction/action/CreativeInventoryAction.java +++ b/src/main/java/cn/nukkit/inventory/transaction/action/CreativeInventoryAction.java @@ -53,10 +53,8 @@ public boolean execute(Player source) { } public void onExecuteSuccess(Player source) { - } public void onExecuteFail(Player source) { - } } diff --git a/src/main/java/cn/nukkit/inventory/transaction/action/DropItemAction.java b/src/main/java/cn/nukkit/inventory/transaction/action/DropItemAction.java index 9f2aa207296..b46f97c5cf8 100644 --- a/src/main/java/cn/nukkit/inventory/transaction/action/DropItemAction.java +++ b/src/main/java/cn/nukkit/inventory/transaction/action/DropItemAction.java @@ -25,11 +25,9 @@ public boolean isValid(Player source) { public boolean onPreExecute(Player source) { PlayerDropItemEvent ev; source.getServer().getPluginManager().callEvent(ev = new PlayerDropItemEvent(source, this.targetItem)); - - if(ev.isCancelled()) { + if (ev.isCancelled()) { source.stopAction(); } - return !ev.isCancelled(); } @@ -41,10 +39,8 @@ public boolean execute(Player source) { } public void onExecuteSuccess(Player source) { - } public void onExecuteFail(Player source) { - } } diff --git a/src/main/java/cn/nukkit/inventory/transaction/action/EnchantingAction.java b/src/main/java/cn/nukkit/inventory/transaction/action/EnchantingAction.java index c035bad751c..5cb41a737c4 100644 --- a/src/main/java/cn/nukkit/inventory/transaction/action/EnchantingAction.java +++ b/src/main/java/cn/nukkit/inventory/transaction/action/EnchantingAction.java @@ -1,12 +1,14 @@ package cn.nukkit.inventory.transaction.action; import cn.nukkit.Player; +import cn.nukkit.inventory.EnchantInventory; import cn.nukkit.item.Item; import lombok.Getter; public class EnchantingAction extends InventoryAction { + @Getter - private int type; + private final int type; public EnchantingAction(Item source, Item target, int type) { super(source, target); @@ -15,7 +17,7 @@ public EnchantingAction(Item source, Item target, int type) { @Override public boolean isValid(Player source) { - return source.getWindowById(Player.ENCHANT_WINDOW_ID) != null; + return source.getWindowById(Player.ENCHANT_WINDOW_ID) instanceof EnchantInventory; } @Override diff --git a/src/main/java/cn/nukkit/inventory/transaction/action/InventoryAction.java b/src/main/java/cn/nukkit/inventory/transaction/action/InventoryAction.java index b1559b5dc1b..266c3400f15 100644 --- a/src/main/java/cn/nukkit/inventory/transaction/action/InventoryAction.java +++ b/src/main/java/cn/nukkit/inventory/transaction/action/InventoryAction.java @@ -9,8 +9,7 @@ */ public abstract class InventoryAction { - - private long creationTime; + //private long creationTime; protected Item sourceItem; @@ -20,31 +19,50 @@ public InventoryAction(Item sourceItem, Item targetItem) { this.sourceItem = sourceItem; this.targetItem = targetItem; - this.creationTime = System.currentTimeMillis(); + //this.creationTime = System.currentTimeMillis(); } + @Deprecated public long getCreationTime() { - return creationTime; + return 0; //creationTime; } /** - * Returns the item that was present before the action took place. + * Returns a clone of the item that was present before the action took place. * - * @return source item + * @return clone of the source item */ public Item getSourceItem() { return sourceItem.clone(); } /** - * Returns the item that the action attempted to replace the source item with. + * Returns the item that was present before the action took place. * - * @return target item + * @return source item + */ + public Item getSourceItemUnsafe() { + return sourceItem; + } + + /** + * Returns a clone of the item that the action attempted to replace the source item with. + * + * @return clone of the target item */ public Item getTargetItem() { return targetItem.clone(); } + /** + * Returns the item that the action attempted to replace the source item with. + * + * @return target item + */ + public Item getTargetItemUnsafe() { + return targetItem; + } + /** * Called by inventory transactions before any actions are processed. If this returns false, the transaction will * be cancelled. @@ -70,7 +88,6 @@ public boolean onPreExecute(Player source) { * @param transaction to add */ public void onAddToTransaction(InventoryTransaction transaction) { - } /** diff --git a/src/main/java/cn/nukkit/inventory/transaction/action/LoomItemAction.java b/src/main/java/cn/nukkit/inventory/transaction/action/LoomItemAction.java new file mode 100644 index 00000000000..8a433b0baad --- /dev/null +++ b/src/main/java/cn/nukkit/inventory/transaction/action/LoomItemAction.java @@ -0,0 +1,45 @@ +package cn.nukkit.inventory.transaction.action; + +import cn.nukkit.Player; +import cn.nukkit.inventory.LoomInventory; +import cn.nukkit.item.Item; + +public class LoomItemAction extends InventoryAction { + + private final LoomInventory inventory; + + public LoomItemAction(Item sourceItem, Item targetItem, LoomInventory inventory) { + super(sourceItem, targetItem); + this.inventory = inventory; + } + + @Override + public boolean isValid(Player source) { + return source.getWindowById(Player.LOOM_WINDOW_ID) instanceof LoomInventory; + } + + @Override + public boolean execute(Player source) { + return true; + } + + @Override + public void onExecuteSuccess(Player source) { + Item banner = inventory.getBanner(); + Item dye = inventory.getDye(); + if (banner != null && !banner.isNull()) { + banner.count -= sourceItem.getCount(); + inventory.setBanner(banner); + } + if (dye != null && !dye.isNull()) { + dye.count -= sourceItem.getCount(); + inventory.setDye(dye); + } + // Pattern not consumed + } + + @Override + public void onExecuteFail(Player source) { + inventory.sendContents(source); + } +} diff --git a/src/main/java/cn/nukkit/inventory/transaction/action/RepairItemAction.java b/src/main/java/cn/nukkit/inventory/transaction/action/RepairItemAction.java index b126b2b2552..8b1fceb1193 100644 --- a/src/main/java/cn/nukkit/inventory/transaction/action/RepairItemAction.java +++ b/src/main/java/cn/nukkit/inventory/transaction/action/RepairItemAction.java @@ -1,11 +1,12 @@ package cn.nukkit.inventory.transaction.action; import cn.nukkit.Player; +import cn.nukkit.inventory.AnvilInventory; import cn.nukkit.item.Item; public class RepairItemAction extends InventoryAction { - private int type; + private final int type; public RepairItemAction(Item sourceItem, Item targetItem, int type) { super(sourceItem, targetItem); @@ -14,7 +15,7 @@ public RepairItemAction(Item sourceItem, Item targetItem, int type) { @Override public boolean isValid(Player source) { - return source.getWindowById(Player.ANVIL_WINDOW_ID) != null; + return source.getWindowById(Player.ANVIL_WINDOW_ID) instanceof AnvilInventory; } @Override diff --git a/src/main/java/cn/nukkit/inventory/transaction/action/SlotChangeAction.java b/src/main/java/cn/nukkit/inventory/transaction/action/SlotChangeAction.java index 227eb1afda0..67ac336eb4a 100644 --- a/src/main/java/cn/nukkit/inventory/transaction/action/SlotChangeAction.java +++ b/src/main/java/cn/nukkit/inventory/transaction/action/SlotChangeAction.java @@ -1,7 +1,11 @@ package cn.nukkit.inventory.transaction.action; import cn.nukkit.Player; -import cn.nukkit.inventory.Inventory; +import cn.nukkit.blockentity.BlockEntity; +import cn.nukkit.blockentity.BlockEntityContainer; +import cn.nukkit.blockentity.BlockEntityFurnace; +import cn.nukkit.entity.Entity; +import cn.nukkit.inventory.*; import cn.nukkit.inventory.transaction.InventoryTransaction; import cn.nukkit.item.Item; @@ -14,7 +18,7 @@ public class SlotChangeAction extends InventoryAction { protected Inventory inventory; - private int inventorySlot; + private final int inventorySlot; public SlotChangeAction(Inventory inventory, int inventorySlot, Item sourceItem, Item targetItem) { super(sourceItem, targetItem); @@ -47,6 +51,30 @@ public int getSlot() { * @return valid */ public boolean isValid(Player source) { + if (inventory == null || source == null || source.closed) { + return false; + } + + if (!source.isCreative() && !(inventory instanceof PlayerUIComponent) && !(inventory instanceof PlayerUIInventory) && !inventory.getViewers().contains(source)) { + source.getServer().getLogger().debug(source.getName() + ": got SlotChangeAction but player is not a viewer of " + inventory); + return false; + } + + if (inventory instanceof PlayerOffhandInventory && !source.isInventoryOpen()) { + source.getServer().getLogger().debug(source.getName() + ": got SlotChangeAction but player has no visible inventory window"); + return false; + } + + if (inventory.getHolder() instanceof BlockEntityContainer && !((BlockEntity) inventory.getHolder()).closed && (source.distanceSquared((BlockEntity) inventory.getHolder()) > 4096 || !source.getLevel().equals(((BlockEntity) inventory.getHolder()).getLevel()))) { + source.getServer().getLogger().debug(source.getName() + ": got SlotChangeAction but player is too far away from the holder of " + inventory); + return false; + } + + if (inventory.getHolder() != source && inventory.getHolder() instanceof Entity && !((Entity) inventory.getHolder()).closed && (source.distanceSquared((Entity) inventory.getHolder()) > 4096 || !source.getLevel().equals(((Entity) inventory.getHolder()).getLevel()))) { + source.getServer().getLogger().debug(source.getName() + ": got SlotChangeAction but player is too far away from the holder of " + inventory); + return false; + } + Item check = inventory.getItem(this.inventorySlot); return check.equalsExact(this.sourceItem); @@ -72,6 +100,28 @@ public void onExecuteSuccess(Player source) { viewers.remove(source); this.inventory.sendSlot(this.inventorySlot, viewers); + + if (this.inventory instanceof FurnaceInventory && this.inventorySlot == 2) { + BlockEntityFurnace blockEntityFurnace = ((FurnaceInventory) this.inventory).getHolder(); + if (blockEntityFurnace != null && !blockEntityFurnace.closed) { + blockEntityFurnace.releaseExperience(); + } + switch (this.getSourceItemUnsafe().getId()) { + case Item.IRON_INGOT: + source.awardAchievement("acquireIron"); + break; + case Item.COOKED_FISH: + source.awardAchievement("cookFish"); + break; + } + } else if (this.inventory instanceof BrewingInventory && this.inventorySlot >= 1 && this.inventorySlot <= 3) { + int itemId = this.getSourceItemUnsafe().getId(); + if (itemId == Item.POTION || itemId == Item.SPLASH_POTION || itemId == Item.LINGERING_POTION) { + if (this.getSourceItemUnsafe().getDamage() != 0) { + source.awardAchievement("potion"); + } + } + } } /** diff --git a/src/main/java/cn/nukkit/inventory/transaction/action/SmithingItemAction.java b/src/main/java/cn/nukkit/inventory/transaction/action/SmithingItemAction.java new file mode 100644 index 00000000000..40f97cd4d8c --- /dev/null +++ b/src/main/java/cn/nukkit/inventory/transaction/action/SmithingItemAction.java @@ -0,0 +1,42 @@ +package cn.nukkit.inventory.transaction.action; + +import cn.nukkit.Player; +import cn.nukkit.inventory.SmithingInventory; +import cn.nukkit.item.Item; + +/** + * @author joserobjr + */ +public class SmithingItemAction extends InventoryAction { + + private final int type; + + public SmithingItemAction(Item sourceItem, Item targetItem, int type) { + super(sourceItem, targetItem); + this.type = type; + } + + @Override + public boolean isValid(Player source) { + return source.getWindowById(Player.SMITHING_WINDOW_ID) instanceof SmithingInventory; + } + + @Override + public boolean execute(Player source) { + return true; + } + + @Override + public void onExecuteSuccess(Player source) { + // Does nothing + } + + @Override + public void onExecuteFail(Player source) { + // Does nothing + } + + public int getType() { + return type; + } +} diff --git a/src/main/java/cn/nukkit/inventory/transaction/data/UseItemOnEntityData.java b/src/main/java/cn/nukkit/inventory/transaction/data/UseItemOnEntityData.java index 354ac0e60e7..ff959c679f2 100644 --- a/src/main/java/cn/nukkit/inventory/transaction/data/UseItemOnEntityData.java +++ b/src/main/java/cn/nukkit/inventory/transaction/data/UseItemOnEntityData.java @@ -14,5 +14,4 @@ public class UseItemOnEntityData implements TransactionData { public Item itemInHand; public Vector3 playerPos; public Vector3 clickPos; - } diff --git a/src/main/java/cn/nukkit/item/Item.java b/src/main/java/cn/nukkit/item/Item.java index d4968a333ba..0baa105638b 100644 --- a/src/main/java/cn/nukkit/item/Item.java +++ b/src/main/java/cn/nukkit/item/Item.java @@ -1,5 +1,6 @@ package cn.nukkit.item; +import cn.nukkit.Nukkit; import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.block.Block; @@ -9,48 +10,45 @@ import cn.nukkit.item.RuntimeItemMapping.RuntimeEntry; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.level.Level; +import cn.nukkit.level.persistence.PersistentItemDataContainer; +import cn.nukkit.level.persistence.impl.PersistentDataContainerItemWrapper; import cn.nukkit.math.BlockFace; import cn.nukkit.math.Vector3; import cn.nukkit.nbt.NBTIO; -import cn.nukkit.nbt.tag.ByteTag; -import cn.nukkit.nbt.tag.CompoundTag; -import cn.nukkit.nbt.tag.IntTag; -import cn.nukkit.nbt.tag.ListTag; -import cn.nukkit.nbt.tag.StringTag; -import cn.nukkit.nbt.tag.Tag; -import cn.nukkit.utils.Binary; +import cn.nukkit.nbt.tag.*; +import cn.nukkit.network.protocol.ProtocolInfo; import cn.nukkit.utils.Utils; +import cn.nukkit.utils.material.BlockType; +import cn.nukkit.utils.material.MaterialType; import com.google.gson.JsonArray; import com.google.gson.JsonElement; -import com.google.gson.JsonParser; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; import java.nio.ByteOrder; -import java.nio.charset.StandardCharsets; import java.util.*; import java.util.regex.Pattern; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ -public class Item implements Cloneable, BlockID, ItemID { - //Normal Item IDs +public class Item implements Cloneable, BlockID, ItemID, ProtocolInfo { - protected static String UNKNOWN_STR = "Unknown"; - public static Class[] list = null; - - protected Block block = null; + @SuppressWarnings("rawtypes") + public static Class[] list; + protected Block block; + protected MaterialType materialType; protected final int id; protected int meta; protected boolean hasMeta = true; private byte[] tags = new byte[0]; - private CompoundTag cachedNBT = null; + private CompoundTag cachedNBT; public int count; - protected int durability = 0; protected String name; + protected static final String UNKNOWN_STR = "Unknown"; + + private PersistentItemDataContainer persistentContainer; public Item(int id) { this(id, 0, 1, UNKNOWN_STR); @@ -65,7 +63,7 @@ public Item(int id, Integer meta, int count) { } public Item(int id, Integer meta, int count, String name) { - this.id = id & 0xffff; + this.id = id; if (meta != null && meta >= 0) { this.meta = meta & 0xffff; } else { @@ -73,10 +71,6 @@ public Item(int id, Integer meta, int count, String name) { } this.count = count; this.name = name; - /*f (this.block != null && this.id <= 0xff && Block.list[id] != null) { //probably useless - this.block = Block.get(this.id, this.meta); - this.name = this.block.getName(); - }*/ } public boolean hasMeta() { @@ -167,6 +161,7 @@ public static void init() { list[SNOWBALL] = ItemSnowball.class; //332 list[BOAT] = ItemBoat.class; //333 list[LEATHER] = ItemLeather.class; //334 + list[KELP] = ItemKelp.class; //335 list[BRICK] = ItemBrick.class; //336 list[CLAY] = ItemClay.class; //337 list[SUGARCANE] = ItemSugarcane.class; //338 @@ -289,6 +284,11 @@ public static void init() { list[TURTLE_SHELL] = ItemTurtleShell.class; //469 list[PHANTOM_MEMBRANE] = ItemPhantomMembrane.class; //470 list[CROSSBOW] = ItemCrossbow.class; //471 + list[SPRUCE_SIGN] = ItemSignSpruce.class; //472 + list[BIRCH_SIGN] = ItemSignBirch.class; //473 + list[JUNGLE_SIGN] = ItemSignJungle.class; //474 + list[ACACIA_SIGN] = ItemSignAcacia.class; //475 + list[DARKOAK_SIGN] = ItemSignDarkOak.class; //476 list[SWEET_BERRIES] = ItemSweetBerries.class; //477 list[RECORD_11] = ItemRecord11.class; //510 list[RECORD_CAT] = ItemRecordCat.class; //501 @@ -303,11 +303,28 @@ public static void init() { list[RECORD_STRAD] = ItemRecordStrad.class; //508 list[RECORD_WAIT] = ItemRecordWait.class; //511 list[SHIELD] = ItemShield.class; //513 - list[RECORD_5] = ItemRecord5.class; //643 + list[COPPER_INGOT] = ItemIngotCopper.class; // 519 + list[RAW_IRON] = ItemIronRaw.class; //520 + list[RAW_GOLD] = ItemGoldRaw.class; //521 + list[RAW_COPPER] = ItemCopperRaw.class; //522 + list[RECORD_5] = ItemRecord5.class; //636 list[RECORD_RELIC] = ItemRecordRelic.class; //701 + list[DISC_FRAGMENT_5] = ItemDiscFragment5.class; //637 + list[OAK_CHEST_BOAT] = ItemChestBoatOak.class; //638 + list[BIRCH_CHEST_BOAT] = ItemChestBoatBirch.class; //639 + list[JUNGLE_CHEST_BOAT] = ItemChestBoatJungle.class; //640 + list[SPRUCE_CHEST_BOAT] = ItemChestBoatSpruce.class; //641 + list[ACACIA_CHEST_BOAT] = ItemChestBoatAcacia.class; //642 + list[DARK_OAK_CHEST_BOAT] = ItemChestBoatDarkOak.class; //643 + list[MANGROVE_CHEST_BOAT] = ItemChestBoatMangrove.class; //644 + list[ECHO_SHARD] = ItemEchoShard.class; //647 + list[RECOVERY_COMPASS] = ItemRecoveryCompass.class; //648 + list[GLOW_BERRIES] = ItemGlowBerries.class; //654 + list[CAMPFIRE] = ItemCampfire.class; //720 list[SUSPICIOUS_STEW] = ItemSuspiciousStew.class; //734 list[HONEYCOMB] = ItemHoneycomb.class; //736 list[HONEY_BOTTLE] = ItemHoneyBottle.class; //737 + list[LODESTONE_COMPASS] = ItemLodestoneCompass.class; //741 list[NETHERITE_INGOT] = ItemIngotNetherite.class; //742 list[NETHERITE_SWORD] = ItemSwordNetherite.class; //743 list[NETHERITE_SHOVEL] = ItemShovelNetherite.class; //744 @@ -319,10 +336,20 @@ public static void init() { list[NETHERITE_LEGGINGS] = ItemLeggingsNetherite.class; //750 list[NETHERITE_BOOTS] = ItemBootsNetherite.class; //751 list[NETHERITE_SCRAP] = ItemScrapNetherite.class; //752 + list[CRIMSON_SIGN] = ItemSignCrimson.class; //753 + list[WARPED_SIGN] = ItemSignWarped.class; //754 + list[CRIMSON_DOOR] = ItemDoorCrimson.class; //755 + list[WARPED_DOOR] = ItemDoorWarped.class; //756 list[WARPED_FUNGUS_ON_A_STICK] = ItemWarpedFungusOnAStick.class; //757 + list[CHAIN] = ItemChain.class; //758 list[RECORD_PIGSTEP] = ItemRecordPigstep.class; //759 + list[NETHER_SPROUTS] = ItemNetherSprouts.class; //760 + list[GOAT_HORN] = ItemGoatHorn.class; //761 + list[AMETHYST_SHARD] = ItemAmethystShard.class; //771 list[SPYGLASS] = ItemSpyglass.class; //772 list[RECORD_OTHERSIDE] = ItemRecordOtherside.class; //773 + list[SOUL_CAMPFIRE] = ItemCampfireSoul.class; //801 + list[GLOW_ITEM_FRAME] = ItemItemFrameGlow.class; //850 for (int i = 0; i < 256; ++i) { if (Block.list[i] != null) { @@ -331,51 +358,53 @@ public static void init() { } } - initCreativeItems(); + clearCreativeItems(); } - private static final ArrayList creative = new ArrayList<>(); + private static final List CREATIVE_ITEMS = new ObjectArrayList<>(); - private static void initCreativeItems() { - clearCreativeItems(); + public static void initCreativeItems() { + Server.getInstance().getLogger().debug("Loading creative items..."); - JsonArray itemsArray; - try (InputStream stream = Server.class.getClassLoader().getResourceAsStream("creative_items.json")) { - itemsArray = JsonParser.parseReader(new InputStreamReader(stream, StandardCharsets.UTF_8)).getAsJsonObject().getAsJsonArray("items"); - } catch (Exception e) { - throw new AssertionError("Error loading required block states!"); + if (!CREATIVE_ITEMS.isEmpty()) { + throw new IllegalStateException("CREATIVE_ITEMS is not empty"); + } + + JsonArray itemsArray = Utils.loadJsonResource("creative_items.json").getAsJsonObject().getAsJsonArray("items"); + if (itemsArray.isEmpty()) { + throw new IllegalStateException("Empty array"); } for (JsonElement element : itemsArray) { - Item item = RuntimeItems.parseCreativeItem(element.getAsJsonObject(), true); + Item item = RuntimeItems.getMapping().parseCreativeItem(element.getAsJsonObject(), true); if (item != null && !item.getName().equals(UNKNOWN_STR)) { // Add only implemented items - addCreativeItem(item); + CREATIVE_ITEMS.add(item); } } } public static void clearCreativeItems() { - Item.creative.clear(); + Item.CREATIVE_ITEMS.clear(); } public static ArrayList getCreativeItems() { - return new ArrayList<>(Item.creative); + return new ArrayList<>(Item.CREATIVE_ITEMS); } public static void addCreativeItem(Item item) { - Item.creative.add(item.clone()); + Item.CREATIVE_ITEMS.add(item.clone()); } public static void removeCreativeItem(Item item) { int index = getCreativeItemIndex(item); if (index != -1) { - Item.creative.remove(index); + Item.CREATIVE_ITEMS.remove(index); } } public static boolean isCreativeItem(Item item) { - for (Item aCreative : Item.creative) { + for (Item aCreative : Item.CREATIVE_ITEMS) { if (item.equals(aCreative, !item.isTool())) { return true; } @@ -384,18 +413,36 @@ public static boolean isCreativeItem(Item item) { } public static Item getCreativeItem(int index) { - return (index >= 0 && index < Item.creative.size()) ? Item.creative.get(index) : null; + List items = Item.CREATIVE_ITEMS; + return (index >= 0 && index < items.size()) ? items.get(index) : null; } public static int getCreativeItemIndex(Item item) { - for (int i = 0; i < Item.creative.size(); i++) { - if (item.equals(Item.creative.get(i), !item.isTool())) { + List items = Item.CREATIVE_ITEMS; + for (int i = 0; i < items.size(); i++) { + if (item.equals(items.get(i), !item.isTool())) { return i; } } return -1; } + public static Item get(MaterialType type) { + return get(type, 0); + } + + public static Item get(MaterialType type, Integer meta) { + return get(type, meta, 1); + } + + public static Item get(MaterialType type, Integer meta, int count) { + int legacyId = type.getLegacyId(); + if (type instanceof BlockType && legacyId > 255) { + legacyId = 255 - legacyId; + } + return get(legacyId, meta, count); + } + public static Item get(int id) { return get(id, 0); } @@ -410,7 +457,13 @@ public static Item get(int id, Integer meta, int count) { public static Item get(int id, Integer meta, int count, byte[] tags) { try { - Class c = list[id]; + Class c; + if (id < 0) { + int blockId = 255 - id; + c = Block.list[blockId]; + } else { + c = list[id]; + } Item item; if (c == null) { @@ -429,44 +482,92 @@ public static Item get(int id, Integer meta, int count, byte[] tags) { item.setCompoundTag(tags); } - return item; + return item.initItem(); } catch (Exception e) { - return new Item(id, meta, count).setCompoundTag(tags); + return new Item(id, meta, count).setCompoundTag(tags).initItem(); } } + public static Item get(int id, Integer meta, int count, Tag tags) { + try { + Class c; + if (id < 0) { + int blockId = 255 - id; + c = Block.list[blockId]; + } else { + c = list[id]; + } + Item item; + + if (c == null) { + item = new Item(id, meta, count); + } else if (id < 256 && id != 166) { + if (meta >= 0) { + item = new ItemBlock(Block.get(id, meta), meta, count); + } else { + item = new ItemBlock(Block.get(id), meta, count); + } + } else { + item = ((Item) c.getConstructor(Integer.class, int.class).newInstance(meta, count)); + } + + if (tags instanceof CompoundTag) { + item.setCompoundTag((CompoundTag) tags); + } + + return item.initItem(); + } catch (Exception e) { + Item item = new Item(id, meta, count); + if (tags instanceof CompoundTag) { + item.setCompoundTag((CompoundTag) tags); + } + return item.initItem(); + } + } + + private static final Pattern INTEGER_PATTERN = Pattern.compile("^[-1-9]\\d*$"); + public static Item fromString(String str) { String[] b = str.trim().replace(' ', '_').replace("minecraft:", "").split(":"); int id = 0; int meta = 0; - Pattern integerPattern = Pattern.compile("^[1-9]\\d*$"); - if (integerPattern.matcher(b[0]).matches()) { - id = Integer.parseInt(b[0]); + String idStr = b[0]; + if (INTEGER_PATTERN.matcher(idStr).matches()) { + id = Integer.parseInt(idStr); } else { + String idStrUp = idStr.toUpperCase(); try { - id = Item.class.getField(b[0].toUpperCase()).getInt(null); + id = BlockID.class.getField(idStrUp).getInt(null); + if (id > 255) { + id = 255 - id; + } } catch (Exception ignore) { + try { + id = ItemID.class.getField(idStrUp).getInt(null); + } catch (Exception ignore1) { + } } } - id = id & 0xFFFF; - if (b.length != 1) meta = Integer.parseInt(b[1]) & 0xFFFF; + if (b.length != 1) { + try { + meta = Integer.parseInt(b[1]) & 0xFFFF; + } catch (NumberFormatException customItem) { + return Item.get(AIR); + } + } return get(id, meta); } public static Item fromJson(Map data) { - return fromJson(data, false); - } - - public static Item fromJson(Map data, boolean ignoreUnsupported) { String nbt = (String) data.get("nbt_b64"); byte[] nbtBytes; if (nbt != null) { nbtBytes = Base64.getDecoder().decode(nbt); - } else { // Support old format for backwards compat + } else { // Support old format for backwards compatibility nbt = (String) data.getOrDefault("nbt_hex", null); if (nbt == null) { nbtBytes = new byte[0]; @@ -475,10 +576,7 @@ public static Item fromJson(Map data, boolean ignoreUnsupported) } } - int id = Utils.toInt(data.get("id")); - if (ignoreUnsupported && id < 0) return null; - - return get(id, Utils.toInt(data.getOrDefault("damage", 0)), Utils.toInt(data.getOrDefault("count", 1)), nbtBytes); + return get(Utils.toInt(data.get("id")), Utils.toInt(data.getOrDefault("damage", 0)), Utils.toInt(data.getOrDefault("count", 1)), nbtBytes); } public static Item[] fromStringMultiple(String str) { @@ -595,7 +693,7 @@ public Enchantment getEnchantment(short id) { if (entry.getShort("id") == id) { Enchantment e = Enchantment.getEnchantment(entry.getShort("id")); if (e != null) { - e.setLevel(entry.getShort("lvl"), false); + e.setLevel(entry.getShort("lvl")); return e; } } @@ -657,7 +755,7 @@ public Enchantment[] getEnchantments() { for (CompoundTag entry : ench.getAll()) { Enchantment e = Enchantment.getEnchantment(entry.getShort("id")); if (e != null) { - e.setLevel(entry.getShort("lvl"), false); + e.setLevel(entry.getShort("lvl")); enchantments.add(e); } } @@ -666,34 +764,17 @@ public Enchantment[] getEnchantments() { } public boolean hasEnchantment(int id) { - return this.getEnchantment(id) != null; + Enchantment e = this.getEnchantment(id); + return e != null && e.getLevel() > 0; } - public int getRepairCost() { - if (this.hasCompoundTag()) { - CompoundTag tag = this.getNamedTag(); - if (tag.contains("RepairCost")) { - Tag repairCost = tag.get("RepairCost"); - if (repairCost instanceof IntTag) { - return ((IntTag) repairCost).data; - } - } - } - return 0; + public boolean hasEnchantment(short id) { + return this.getEnchantment(id) != null; } - public Item setRepairCost(int cost) { - if (cost <= 0 && this.hasCompoundTag()) { - return this.setNamedTag(this.getNamedTag().remove("RepairCost")); - } - - CompoundTag tag; - if (!this.hasCompoundTag()) { - tag = new CompoundTag(); - } else { - tag = this.getNamedTag(); - } - return this.setNamedTag(tag.putInt("RepairCost", cost)); + public int getEnchantmentLevel(int id) { + Enchantment e = this.getEnchantment(id); + return e == null ? 0 : e.getLevel(); } public boolean hasCustomName() { @@ -727,8 +808,13 @@ public String getCustomName() { } public Item setCustomName(String name) { - if (name == null || name.equals("")) { + if (name == null || name.isEmpty()) { this.clearCustomName(); + return this; + } + + if (name.length() > 100) { + name = name.substring(0, 100); } CompoundTag tag; @@ -811,7 +897,7 @@ public Item setLore(String... lines) { public Tag getNamedTagEntry(String name) { CompoundTag tag = this.getNamedTag(); if (tag != null) { - return tag.contains(name) ? tag.get(name) : null; + return tag.get(name); } return null; @@ -826,9 +912,7 @@ public CompoundTag getNamedTag() { this.cachedNBT = parseCompoundTag(this.tags); } - if (this.cachedNBT != null) { - this.cachedNBT.setName(""); - } + this.cachedNBT.setName(""); return this.cachedNBT; } @@ -878,7 +962,7 @@ public boolean isNull() { return this.count <= 0 || this.id == AIR; } - final public String getName() { + public String getName() { return this.hasCustomName() ? this.getCustomName() : this.name; } @@ -898,12 +982,23 @@ public Block getBlockUnsafe() { return this.block; } + public int getBlockId() { + return block == null ? 0 : block.getId(); + } + public int getId() { return id; } + public MaterialType getItemType() { + if (this.materialType == null) { + this.materialType = ItemTypes.getFromLegacy(this.id); + } + return this.materialType; + } + public int getDamage() { - return meta; + return meta == 0xffff ? 0 : meta; } public void setDamage(Integer meta) { @@ -980,6 +1075,10 @@ public boolean isHelmet() { return false; } + public boolean canBePutInHelmetSlot() { + return false; + } + public boolean isChestplate() { return false; } @@ -1042,12 +1141,13 @@ public boolean onRelease(Player player, int ticksUsed) { } @Override - final public String toString() { - return "Item " + this.name + " (" + this.id + ":" + (!this.hasMeta ? "?" : this.meta) + ")x" + this.count + (this.hasCompoundTag() ? " tags:0x" + Binary.bytesToHexString(this.getCompoundTag()) : ""); - } - - public int getDestroySpeed(Block block, Player player) { - return 1; + public String toString() { + String out = "Item " + this.name + " (" + this.id + ':' + (!this.hasMeta ? "?" : this.meta) + ")x" + this.count; + CompoundTag tag; + if (Nukkit.DEBUG > 1 && (tag = this.getNamedTag()) != null) { + out += '\n' + tag.toString(); + } + return out; } public boolean onActivate(Level level, Player player, Block block, Block target, BlockFace face, double fx, double fy, double fz) { @@ -1076,7 +1176,7 @@ public final boolean equals(Item item, boolean checkDamage) { } public final boolean equals(Item item, boolean checkDamage, boolean checkCompound) { - if (this.getId() == item.getId() && (!checkDamage || this.getDamage() == item.getDamage())) { + if (this.id == item.id && (!checkDamage || this.meta == item.meta)) { if (checkCompound) { if (Arrays.equals(this.getCompoundTag(), item.getCompoundTag())) { return true; @@ -1116,6 +1216,33 @@ public final boolean deepEquals(Item item, boolean checkDamage, boolean checkCom return equals(item, checkDamage, checkCompound); } + public int getRepairCost() { + if (this.hasCompoundTag()) { + CompoundTag tag = this.getNamedTag(); + if (tag.contains("RepairCost")) { + Tag repairCost = tag.get("RepairCost"); + if (repairCost instanceof IntTag) { + return ((IntTag) repairCost).data; + } + } + } + return 0; + } + + public Item setRepairCost(int cost) { + if (cost <= 0 && this.hasCompoundTag()) { + return this.setNamedTag(this.getNamedTag().remove("RepairCost")); + } + + CompoundTag tag; + if (!this.hasCompoundTag()) { + tag = new CompoundTag(); + } else { + tag = this.getNamedTag(); + } + return this.setNamedTag(tag.putInt("RepairCost", cost)); + } + @Override public Item clone() { try { @@ -1134,4 +1261,49 @@ public final RuntimeEntry getRuntimeEntry() { public final int getNetworkId() { return this.getRuntimeEntry().getRuntimeId(); } + + /** + * This code runs when the item is initialized and can be overridden to for example check the item for missing nbt + * @return current item + */ + public Item initItem() { + return this; + } + + public PersistentItemDataContainer getPersistentDataContainer() { + if (this.persistentContainer == null) { + this.persistentContainer = new PersistentDataContainerItemWrapper(this); + } + return this.persistentContainer; + } + + public boolean hasPersistentDataContainer() { + return this.hasCompoundTag() && !this.getPersistentDataContainer().isEmpty(); + } + + /** + * Returns a new item instance with count decreased by amount or air if new count is less or equal to 0 + */ + public final Item decrement(int amount) { + return increment(-amount); + } + + /** + * Returns a new item instance with count increased by amount or air if new count is less or equal to 0 + */ + public final Item increment(int amount) { + if (this.count + amount <= 0) { + return get(0); + } + Item cloned = this.clone(); + cloned.count += amount; + return cloned; + } + + /** + * Whether item can be placed in player offhand inventory + */ + public boolean allowOffhand() { + return this.id == AIR; + } } diff --git a/src/main/java/cn/nukkit/item/ItemAmethystShard.java b/src/main/java/cn/nukkit/item/ItemAmethystShard.java new file mode 100644 index 00000000000..c0da083d82b --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemAmethystShard.java @@ -0,0 +1,16 @@ +package cn.nukkit.item; + +public class ItemAmethystShard extends Item { + + public ItemAmethystShard() { + this(0, 1); + } + + public ItemAmethystShard(Integer meta) { + this(meta, 1); + } + + public ItemAmethystShard(Integer meta, int count) { + super(AMETHYST_SHARD, meta, count, "Amethyst Shard"); + } +} diff --git a/src/main/java/cn/nukkit/item/ItemApple.java b/src/main/java/cn/nukkit/item/ItemApple.java index 62d321f8ae9..0823f6159e4 100644 --- a/src/main/java/cn/nukkit/item/ItemApple.java +++ b/src/main/java/cn/nukkit/item/ItemApple.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemApple extends ItemEdible { diff --git a/src/main/java/cn/nukkit/item/ItemAppleGold.java b/src/main/java/cn/nukkit/item/ItemAppleGold.java index 4abaf316937..873ba33e92e 100644 --- a/src/main/java/cn/nukkit/item/ItemAppleGold.java +++ b/src/main/java/cn/nukkit/item/ItemAppleGold.java @@ -1,10 +1,7 @@ package cn.nukkit.item; -import cn.nukkit.Player; -import cn.nukkit.math.Vector3; - /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemAppleGold extends ItemEdible { @@ -22,7 +19,7 @@ public ItemAppleGold(Integer meta, int count) { } @Override - public boolean onClickAir(Player player, Vector3 directionVector) { + public boolean canAlwaysEat() { return true; } } diff --git a/src/main/java/cn/nukkit/item/ItemAppleGoldEnchanted.java b/src/main/java/cn/nukkit/item/ItemAppleGoldEnchanted.java index 3196050edc1..3686f4716c8 100644 --- a/src/main/java/cn/nukkit/item/ItemAppleGoldEnchanted.java +++ b/src/main/java/cn/nukkit/item/ItemAppleGoldEnchanted.java @@ -1,13 +1,11 @@ package cn.nukkit.item; -import cn.nukkit.Player; -import cn.nukkit.math.Vector3; - /** * Created by Snake1999 on 2016/1/14. * Package cn.nukkit.item in project nukkit. */ public class ItemAppleGoldEnchanted extends ItemEdible { + public ItemAppleGoldEnchanted() { this(0, 1); } @@ -17,11 +15,11 @@ public ItemAppleGoldEnchanted(Integer meta) { } public ItemAppleGoldEnchanted(Integer meta, int count) { - super(GOLDEN_APPLE_ENCHANTED, meta, count, "Enchanted Golden Apple"); + super(GOLDEN_APPLE_ENCHANTED, meta, count, "Enchanted Apple"); } @Override - public boolean onClickAir(Player player, Vector3 directionVector) { + public boolean canAlwaysEat() { return true; } } diff --git a/src/main/java/cn/nukkit/item/ItemArmor.java b/src/main/java/cn/nukkit/item/ItemArmor.java index 910b1bfedea..d1873ae8874 100644 --- a/src/main/java/cn/nukkit/item/ItemArmor.java +++ b/src/main/java/cn/nukkit/item/ItemArmor.java @@ -2,12 +2,10 @@ import cn.nukkit.Player; import cn.nukkit.math.Vector3; -import cn.nukkit.nbt.tag.ByteTag; -import cn.nukkit.nbt.tag.Tag; import cn.nukkit.network.protocol.LevelSoundEventPacket; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ abstract public class ItemArmor extends Item implements ItemDurable { @@ -98,7 +96,7 @@ public boolean onClickAir(Player player, Vector3 directionVector) { } } - return this.getCount() == 0; + return false; // We already use setItem & clear here } @Override @@ -114,14 +112,15 @@ public int getEnchantAbility() { return 25; case TIER_IRON: return 9; + case TIER_NETHERITE: + return 10; //TODO } return 0; } @Override - public boolean isUnbreakable() { - Tag tag = this.getNamedTagEntry("Unbreakable"); - return tag instanceof ByteTag && ((ByteTag) tag).data > 0; + public boolean canBePutInHelmetSlot() { + return this.isHelmet(); } } diff --git a/src/main/java/cn/nukkit/item/ItemArmorStand.java b/src/main/java/cn/nukkit/item/ItemArmorStand.java index 845a794cbe8..c7c1d9f74ae 100644 --- a/src/main/java/cn/nukkit/item/ItemArmorStand.java +++ b/src/main/java/cn/nukkit/item/ItemArmorStand.java @@ -1,5 +1,18 @@ package cn.nukkit.item; +import cn.nukkit.Player; +import cn.nukkit.block.Block; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityArmorStand; +import cn.nukkit.level.Level; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.math.BlockFace; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.DoubleTag; +import cn.nukkit.nbt.tag.FloatTag; +import cn.nukkit.nbt.tag.ListTag; +import cn.nukkit.network.protocol.LevelEventPacket; + public class ItemArmorStand extends Item { public ItemArmorStand() { @@ -13,4 +26,63 @@ public ItemArmorStand(Integer meta) { public ItemArmorStand(Integer meta, int count) { super(ARMOR_STAND, meta, count, "Armor Stand"); } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Level level, Player player, Block block, Block target, BlockFace face, double fx, double fy, double fz) { + FullChunk chunk = level.getChunk((int) block.getX() >> 4, (int) block.getZ() >> 4); + + if (chunk == null) { + return false; + } + + for (Entity e : chunk.getEntities().values()) { + if (e instanceof EntityArmorStand) { + if (e.getY() == block.getY() && e.getX() == (block.getX() + 0.5) && e.getZ() == (block.getZ() + 0.5)) { + return false; + } + } + } + + CompoundTag nbt = new CompoundTag() + .putList(new ListTag("Pos") + .add(new DoubleTag("", block.getX() + 0.5)) + .add(new DoubleTag("", block.getY())) + .add(new DoubleTag("", block.getZ() + 0.5))) + .putList(new ListTag("Motion") + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0))) + .putList(new ListTag("Rotation") + .add(new FloatTag("", getDirection((float) player.getYaw()))) + .add(new FloatTag("", 0))); + + if (this.hasCustomName()) { + nbt.putString("CustomName", this.getCustomName()); + } + + Entity entity = Entity.createEntity("ArmorStand", chunk, nbt); + + if (!player.isCreative()) { + this.count--; + } + + if (entity != null) { + entity.spawnToAll(); + player.getLevel().addLevelEvent(entity, LevelEventPacket.EVENT_SOUND_ARMOR_STAND_PLACE); + } + return true; + } + + private static float getDirection(float yaw) { + float rot = (Math.round(yaw / 22.5f / 2f) * 45f) - 180f; + if (rot < 0) { + rot += 360f; + } + return rot; + } } diff --git a/src/main/java/cn/nukkit/item/ItemArrow.java b/src/main/java/cn/nukkit/item/ItemArrow.java index 1a4107c64b5..883d75aceef 100644 --- a/src/main/java/cn/nukkit/item/ItemArrow.java +++ b/src/main/java/cn/nukkit/item/ItemArrow.java @@ -1,7 +1,9 @@ package cn.nukkit.item; +import cn.nukkit.potion.Effect; + /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemArrow extends Item { @@ -18,4 +20,94 @@ public ItemArrow(Integer meta, int count) { super(ARROW, meta, count, "Arrow"); } + public static Effect getEffect(int meta) { + switch (meta) { + case 6: + return Effect.getEffect(Effect.NIGHT_VISION).setDuration(440); + case 7: + return Effect.getEffect(Effect.NIGHT_VISION).setDuration(1200); + case 8: + return Effect.getEffect(Effect.INVISIBILITY).setDuration(440); + case 9: + return Effect.getEffect(Effect.INVISIBILITY).setDuration(1200); + case 10: + return Effect.getEffect(Effect.JUMP).setDuration(440); + case 11: + return Effect.getEffect(Effect.JUMP).setDuration(1200); + case 12: + return Effect.getEffect(Effect.JUMP).setAmplifier(1).setDuration(220); + case 13: + return Effect.getEffect(Effect.FIRE_RESISTANCE).setDuration(440); + case 14: + return Effect.getEffect(Effect.FIRE_RESISTANCE).setDuration(1200); + case 15: + return Effect.getEffect(Effect.SPEED).setDuration(440); + case 16: + return Effect.getEffect(Effect.SPEED).setDuration(1200); + case 17: + return Effect.getEffect(Effect.SPEED).setAmplifier(1).setDuration(220); + case 18: + return Effect.getEffect(Effect.SLOWNESS).setDuration(220); + case 19: + return Effect.getEffect(Effect.SLOWNESS).setDuration(600); + case 20: + return Effect.getEffect(Effect.WATER_BREATHING).setDuration(440); + case 21: + return Effect.getEffect(Effect.WATER_BREATHING).setDuration(1200); + case 22: + return Effect.getEffect(Effect.HEALING).setDuration(1); + case 23: + return Effect.getEffect(Effect.HEALING).setAmplifier(1).setDuration(1); + case 24: + return Effect.getEffect(Effect.HARMING).setDuration(1); + case 25: + return Effect.getEffect(Effect.HARMING).setAmplifier(1).setDuration(1); + case 26: + return Effect.getEffect(Effect.POISON).setDuration(100); + case 27: + return Effect.getEffect(Effect.POISON).setDuration(300); + case 28: + return Effect.getEffect(Effect.POISON).setAmplifier(1).setDuration(40); + case 29: + return Effect.getEffect(Effect.REGENERATION).setDuration(100); + case 30: + return Effect.getEffect(Effect.REGENERATION).setDuration(300); + case 31: + return Effect.getEffect(Effect.REGENERATION).setAmplifier(1).setDuration(40); + case 32: + return Effect.getEffect(Effect.STRENGTH).setDuration(440); + case 33: + return Effect.getEffect(Effect.STRENGTH).setDuration(1200); + case 34: + return Effect.getEffect(Effect.STRENGTH).setAmplifier(1).setDuration(220); + case 35: + return Effect.getEffect(Effect.WEAKNESS).setDuration(220); + case 36: + return Effect.getEffect(Effect.WEAKNESS).setDuration(600); + case 37: + return Effect.getEffect(Effect.WITHER).setAmplifier(1).setDuration(100); + case 38: + return Effect.getEffect(Effect.SLOWNESS).setAmplifier(3).setDuration(40); + //return Effect.getEffect(Effect.DAMAGE_RESISTANCE).setAmplifier(2).setDuration(40); + case 39: + return Effect.getEffect(Effect.SLOWNESS).setAmplifier(3).setDuration(100); + //return Effect.getEffect(Effect.DAMAGE_RESISTANCE).setAmplifier(2).setDuration(100); + case 40: + return Effect.getEffect(Effect.SLOWNESS).setAmplifier(5).setDuration(40); + //return Effect.getEffect(Effect.DAMAGE_RESISTANCE).setAmplifier(3).setDuration(40); + case 41: + return Effect.getEffect(Effect.SLOW_FALLING).setDuration(220); + case 42: + return Effect.getEffect(Effect.SLOW_FALLING).setDuration(600); + case 43: + return Effect.getEffect(Effect.SLOWNESS).setAmplifier(3).setDuration(40); + default: + return null; + } + } + + @Override + public boolean allowOffhand() { + return true; + } } diff --git a/src/main/java/cn/nukkit/item/ItemAxeDiamond.java b/src/main/java/cn/nukkit/item/ItemAxeDiamond.java index 5d0d2a6972d..cbe1bdfa9a1 100644 --- a/src/main/java/cn/nukkit/item/ItemAxeDiamond.java +++ b/src/main/java/cn/nukkit/item/ItemAxeDiamond.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemAxeDiamond extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemAxeGold.java b/src/main/java/cn/nukkit/item/ItemAxeGold.java index c0bf7f0f997..0007ac16ca5 100644 --- a/src/main/java/cn/nukkit/item/ItemAxeGold.java +++ b/src/main/java/cn/nukkit/item/ItemAxeGold.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemAxeGold extends ItemTool { @@ -15,7 +15,7 @@ public ItemAxeGold(Integer meta) { } public ItemAxeGold(Integer meta, int count) { - super(GOLD_AXE, meta, count, "Gold Axe"); + super(GOLD_AXE, meta, count, "Golden Axe"); } @Override diff --git a/src/main/java/cn/nukkit/item/ItemAxeIron.java b/src/main/java/cn/nukkit/item/ItemAxeIron.java index c1157ed953b..8e60ab2d1cb 100644 --- a/src/main/java/cn/nukkit/item/ItemAxeIron.java +++ b/src/main/java/cn/nukkit/item/ItemAxeIron.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemAxeIron extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemAxeStone.java b/src/main/java/cn/nukkit/item/ItemAxeStone.java index e3c24b2c959..7275ebdf025 100644 --- a/src/main/java/cn/nukkit/item/ItemAxeStone.java +++ b/src/main/java/cn/nukkit/item/ItemAxeStone.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemAxeStone extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemAxeWood.java b/src/main/java/cn/nukkit/item/ItemAxeWood.java index 78380960555..1225cafc5c1 100644 --- a/src/main/java/cn/nukkit/item/ItemAxeWood.java +++ b/src/main/java/cn/nukkit/item/ItemAxeWood.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemAxeWood extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemBanner.java b/src/main/java/cn/nukkit/item/ItemBanner.java index d44e43c49da..1c2cc561951 100644 --- a/src/main/java/cn/nukkit/item/ItemBanner.java +++ b/src/main/java/cn/nukkit/item/ItemBanner.java @@ -6,9 +6,6 @@ import cn.nukkit.utils.BannerPattern; import cn.nukkit.utils.DyeColor; -/** - * Created by PetteriM1 - */ public class ItemBanner extends Item { public ItemBanner() { @@ -65,7 +62,7 @@ public BannerPattern getPattern(int index) { public void removePattern(int index) { CompoundTag tag = this.hasCompoundTag() ? this.getNamedTag() : new CompoundTag(); ListTag patterns = tag.getList("Patterns", CompoundTag.class); - if(patterns.size() > index && index >= 0) { + if (patterns.size() > index && index >= 0) { patterns.remove(index); } this.setNamedTag(tag); @@ -75,7 +72,7 @@ public int getPatternsSize() { return (this.hasCompoundTag() ? this.getNamedTag() : new CompoundTag()).getList("Patterns").size(); } - public void correctNBT() { - + public boolean hasPattern() { + return (this.hasCompoundTag() ? this.getNamedTag() : new CompoundTag()).contains("Patterns"); } } diff --git a/src/main/java/cn/nukkit/item/ItemBed.java b/src/main/java/cn/nukkit/item/ItemBed.java index f2103b0942b..eb41df272b4 100644 --- a/src/main/java/cn/nukkit/item/ItemBed.java +++ b/src/main/java/cn/nukkit/item/ItemBed.java @@ -1,11 +1,10 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; import cn.nukkit.utils.DyeColor; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemBed extends Item { @@ -20,7 +19,7 @@ public ItemBed(Integer meta) { public ItemBed(Integer meta, int count) { super(BED, meta, count, DyeColor.getByWoolData(meta).getName() + " Bed"); - this.block = Block.get(BlockID.BED_BLOCK); + this.block = Block.get(BED_BLOCK); } @Override diff --git a/src/main/java/cn/nukkit/item/ItemBeefRaw.java b/src/main/java/cn/nukkit/item/ItemBeefRaw.java index 346d1777cea..435e8c3d06f 100644 --- a/src/main/java/cn/nukkit/item/ItemBeefRaw.java +++ b/src/main/java/cn/nukkit/item/ItemBeefRaw.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemBeefRaw extends ItemEdible { diff --git a/src/main/java/cn/nukkit/item/ItemBeetroot.java b/src/main/java/cn/nukkit/item/ItemBeetroot.java index f2387e2acf4..92ffd89c60d 100644 --- a/src/main/java/cn/nukkit/item/ItemBeetroot.java +++ b/src/main/java/cn/nukkit/item/ItemBeetroot.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemBeetroot extends ItemEdible { @@ -17,5 +17,4 @@ public ItemBeetroot(Integer meta) { public ItemBeetroot(Integer meta, int count) { super(BEETROOT, meta, count, "Beetroot"); } - } diff --git a/src/main/java/cn/nukkit/item/ItemBeetrootSoup.java b/src/main/java/cn/nukkit/item/ItemBeetrootSoup.java index a835e8f22db..44f13c52bd8 100644 --- a/src/main/java/cn/nukkit/item/ItemBeetrootSoup.java +++ b/src/main/java/cn/nukkit/item/ItemBeetrootSoup.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemBeetrootSoup extends ItemEdible { diff --git a/src/main/java/cn/nukkit/item/ItemBlazePowder.java b/src/main/java/cn/nukkit/item/ItemBlazePowder.java index a233d4fc8ad..348d3e1aa70 100644 --- a/src/main/java/cn/nukkit/item/ItemBlazePowder.java +++ b/src/main/java/cn/nukkit/item/ItemBlazePowder.java @@ -1,12 +1,9 @@ package cn.nukkit.item; -/** - * Created by Leonidius20 on 18.08.18. - */ public class ItemBlazePowder extends Item { public ItemBlazePowder() { - this(0); + this(0, 1); } public ItemBlazePowder(Integer meta) { @@ -14,6 +11,6 @@ public ItemBlazePowder(Integer meta) { } public ItemBlazePowder(Integer meta, int count) { - super(BLAZE_POWDER, meta, count, "Blaze Powder"); + super(BLAZE_POWDER, 0, count, "Blaze Powder"); } } diff --git a/src/main/java/cn/nukkit/item/ItemBlazeRod.java b/src/main/java/cn/nukkit/item/ItemBlazeRod.java index e02ad9ab4cc..2e50243b1b8 100644 --- a/src/main/java/cn/nukkit/item/ItemBlazeRod.java +++ b/src/main/java/cn/nukkit/item/ItemBlazeRod.java @@ -16,5 +16,4 @@ public ItemBlazeRod(Integer meta) { public ItemBlazeRod(Integer meta, int count) { super(BLAZE_ROD, meta, count, "Blaze Rod"); } - } diff --git a/src/main/java/cn/nukkit/item/ItemBlock.java b/src/main/java/cn/nukkit/item/ItemBlock.java index f27338237a6..5bd56783b6f 100644 --- a/src/main/java/cn/nukkit/item/ItemBlock.java +++ b/src/main/java/cn/nukkit/item/ItemBlock.java @@ -1,12 +1,17 @@ package cn.nukkit.item; +import cn.nukkit.Nukkit; import cn.nukkit.block.Block; +import cn.nukkit.block.custom.container.BlockStorageContainer; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.utils.material.MaterialType; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemBlock extends Item { + public ItemBlock(Block block) { this(block, 0, 1); } @@ -15,8 +20,17 @@ public ItemBlock(Block block, Integer meta) { this(block, meta, 1); } + public ItemBlock(Block block, int meta) { + this(block, meta, 1); + } + public ItemBlock(Block block, Integer meta, int count) { - super(block.getId(), meta, count, block.getName()); + super(block.getItemId(), meta, count, block.getName()); + this.block = block; + } + + public ItemBlock(Block block, int meta, int count) { + super(block.getItemId(), meta, count, block.getName()); this.block = block; } @@ -26,7 +40,12 @@ public void setDamage(Integer meta) { } else { this.hasMeta = false; } - this.block.setDamage(meta); + + if (this.block instanceof BlockStorageContainer) { + ((BlockStorageContainer) this.block).setStorageFromItem(meta == null ? 0 : meta); + } else { + this.block.setDamage(meta); + } } @Override @@ -40,9 +59,13 @@ public Block getBlock() { return this.block.clone(); } + @Override + public MaterialType getItemType() { + return this.block.getBlockType(); + } + @Override public int getMaxStackSize() { - //Shulker boxes don't stack! if (this.block.getId() == Block.SHULKER_BOX || this.block.getId() == Block.UNDYED_SHULKER_BOX) { return 1; } @@ -50,4 +73,18 @@ public int getMaxStackSize() { return super.getMaxStackSize(); } + @Override + final public String getName() { + return this.hasCustomName() ? this.getCustomName() : this.block.getName(); + } + + @Override + final public String toString() { + String out = "ItemBlock " + this.block.getName() + " (" + this.id + ':' + (!this.hasMeta ? "?" : this.meta) + ")x" + this.count; + CompoundTag tag; + if (Nukkit.DEBUG > 1 && (tag = this.getNamedTag()) != null) { + out += '\n' + tag.toString(); + } + return out; + } } diff --git a/src/main/java/cn/nukkit/item/ItemBoat.java b/src/main/java/cn/nukkit/item/ItemBoat.java index 06bade567d4..feb8be8efc2 100644 --- a/src/main/java/cn/nukkit/item/ItemBoat.java +++ b/src/main/java/cn/nukkit/item/ItemBoat.java @@ -37,11 +37,11 @@ public boolean canBeActivated() { @Override public boolean onActivate(Level level, Player player, Block block, Block target, BlockFace face, double fx, double fy, double fz) { if (face != BlockFace.UP || block instanceof BlockWater) return false; - EntityBoat boat = (EntityBoat) Entity.createEntity("Boat", - level.getChunk(block.getFloorX() >> 4, block.getFloorZ() >> 4), new CompoundTag("") + Entity.createEntity(EntityBoat.NETWORK_ID, + level.getChunk(block.getChunkX(), block.getChunkZ()), new CompoundTag("") .putList(new ListTag("Pos") .add(new DoubleTag("", block.getX() + 0.5)) - .add(new DoubleTag("", block.getY() - (target instanceof BlockWater ? 0.0625 : 0))) + .add(new DoubleTag("", block.getY() - (target instanceof BlockWater ? 0.1 : 0))) .add(new DoubleTag("", block.getZ() + 0.5))) .putList(new ListTag("Motion") .add(new DoubleTag("", 0)) @@ -50,20 +50,13 @@ public boolean onActivate(Level level, Player player, Block block, Block target, .putList(new ListTag("Rotation") .add(new FloatTag("", (float) ((player.yaw + 90f) % 360))) .add(new FloatTag("", 0))) - .putByte("woodID", this.getDamage()) - ); + .putInt("Variant", this.getDamage()) + ).spawnToAll(); - if (boat == null) { - return false; + if (!player.isCreative()) { + this.count--; } - if (player.isAdventure() || player.isSurvival()) { - Item item = player.getInventory().getItemInHand(); - item.setCount(item.getCount() - 1); - player.getInventory().setItemInHand(item); - } - - boat.spawnToAll(); return true; } diff --git a/src/main/java/cn/nukkit/item/ItemBone.java b/src/main/java/cn/nukkit/item/ItemBone.java index 2cb1d4775f8..2786ab21e7a 100644 --- a/src/main/java/cn/nukkit/item/ItemBone.java +++ b/src/main/java/cn/nukkit/item/ItemBone.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemBone extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemBook.java b/src/main/java/cn/nukkit/item/ItemBook.java index 83edef9fa44..3c9eb643dbd 100644 --- a/src/main/java/cn/nukkit/item/ItemBook.java +++ b/src/main/java/cn/nukkit/item/ItemBook.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemBook extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemBookEnchanted.java b/src/main/java/cn/nukkit/item/ItemBookEnchanted.java index 726c95b56b1..fb5279aa823 100644 --- a/src/main/java/cn/nukkit/item/ItemBookEnchanted.java +++ b/src/main/java/cn/nukkit/item/ItemBookEnchanted.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemBookEnchanted extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemBookWritable.java b/src/main/java/cn/nukkit/item/ItemBookWritable.java index 383aa5f753f..6c9ea824a47 100644 --- a/src/main/java/cn/nukkit/item/ItemBookWritable.java +++ b/src/main/java/cn/nukkit/item/ItemBookWritable.java @@ -164,7 +164,7 @@ public boolean insertPage(int pageId, String pageText) { return true; } - /** + /** * Switches the text of two pages with each other. * @return boolean indicating success */ diff --git a/src/main/java/cn/nukkit/item/ItemBookWritten.java b/src/main/java/cn/nukkit/item/ItemBookWritten.java index 9d09f1a5852..1bca8290785 100644 --- a/src/main/java/cn/nukkit/item/ItemBookWritten.java +++ b/src/main/java/cn/nukkit/item/ItemBookWritten.java @@ -36,7 +36,7 @@ public Item writeBook(String author, String title, String[] pages) { } public Item writeBook(String author, String title, ListTag pages) { - if (pages.size() > 50 || pages.size() <= 0) return this; //Minecraft does not support more than 50 pages + if (pages.size() > 50 || pages.size() <= 0) return this; // Minecraft does not support more than 50 pages CompoundTag tag = this.hasCompoundTag() ? this.getNamedTag() : new CompoundTag(); tag.putString("author", author); diff --git a/src/main/java/cn/nukkit/item/ItemBootsChain.java b/src/main/java/cn/nukkit/item/ItemBootsChain.java index dd713eacdf3..82048caccef 100644 --- a/src/main/java/cn/nukkit/item/ItemBootsChain.java +++ b/src/main/java/cn/nukkit/item/ItemBootsChain.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemBootsChain extends ItemArmor { diff --git a/src/main/java/cn/nukkit/item/ItemBootsDiamond.java b/src/main/java/cn/nukkit/item/ItemBootsDiamond.java index d1283d0a868..6a16233c5cf 100644 --- a/src/main/java/cn/nukkit/item/ItemBootsDiamond.java +++ b/src/main/java/cn/nukkit/item/ItemBootsDiamond.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemBootsDiamond extends ItemArmor { diff --git a/src/main/java/cn/nukkit/item/ItemBootsGold.java b/src/main/java/cn/nukkit/item/ItemBootsGold.java index 1cd689442bb..9df6d08c631 100644 --- a/src/main/java/cn/nukkit/item/ItemBootsGold.java +++ b/src/main/java/cn/nukkit/item/ItemBootsGold.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemBootsGold extends ItemArmor { @@ -15,7 +15,7 @@ public ItemBootsGold(Integer meta) { } public ItemBootsGold(Integer meta, int count) { - super(GOLD_BOOTS, meta, count, "Gold Boots"); + super(GOLD_BOOTS, meta, count, "Golden Boots"); } @Override diff --git a/src/main/java/cn/nukkit/item/ItemBootsIron.java b/src/main/java/cn/nukkit/item/ItemBootsIron.java index 0f6fed366d5..4d00db5a2f5 100644 --- a/src/main/java/cn/nukkit/item/ItemBootsIron.java +++ b/src/main/java/cn/nukkit/item/ItemBootsIron.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemBootsIron extends ItemArmor { diff --git a/src/main/java/cn/nukkit/item/ItemBootsLeather.java b/src/main/java/cn/nukkit/item/ItemBootsLeather.java index f8409136edf..3c33510fc66 100644 --- a/src/main/java/cn/nukkit/item/ItemBootsLeather.java +++ b/src/main/java/cn/nukkit/item/ItemBootsLeather.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemBootsLeather extends ItemColorArmor { diff --git a/src/main/java/cn/nukkit/item/ItemBootsNetherite.java b/src/main/java/cn/nukkit/item/ItemBootsNetherite.java index 6761c3a26bb..961279e0256 100644 --- a/src/main/java/cn/nukkit/item/ItemBootsNetherite.java +++ b/src/main/java/cn/nukkit/item/ItemBootsNetherite.java @@ -36,6 +36,6 @@ public int getArmorPoints() { @Override public int getToughness() { - return 2; + return 3; } } diff --git a/src/main/java/cn/nukkit/item/ItemBow.java b/src/main/java/cn/nukkit/item/ItemBow.java index 019c3cf063e..00600a9514d 100644 --- a/src/main/java/cn/nukkit/item/ItemBow.java +++ b/src/main/java/cn/nukkit/item/ItemBow.java @@ -7,7 +7,6 @@ import cn.nukkit.entity.projectile.EntityProjectile; import cn.nukkit.event.entity.EntityShootBowEvent; import cn.nukkit.event.entity.ProjectileLaunchEvent; -import cn.nukkit.inventory.Inventory; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.math.Vector3; import cn.nukkit.nbt.tag.CompoundTag; @@ -15,11 +14,10 @@ import cn.nukkit.nbt.tag.FloatTag; import cn.nukkit.nbt.tag.ListTag; import cn.nukkit.network.protocol.LevelSoundEventPacket; - -import java.util.Random; +import cn.nukkit.utils.Utils; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemBow extends ItemTool { @@ -33,7 +31,11 @@ public ItemBow(Integer meta) { } public ItemBow(Integer meta, int count) { - super(BOW, meta, count, "Bow"); + this(BOW, meta, count, "Bow"); + } + + public ItemBow(int id, Integer meta, int count, String name) { + super(id, meta, count, name); } @Override @@ -48,23 +50,44 @@ public int getEnchantAbility() { @Override public boolean onClickAir(Player player, Vector3 directionVector) { - return player.getInventory().contains(Item.get(ItemID.ARROW)) || player.isCreative(); + return playerHasArrow(player) || player.isCreative(); + } + + private boolean playerHasArrow(Player p) { + if (p.getOffhandInventory().getItemFast(0).getId() == ItemID.ARROW) return true; + for (Item i : p.getInventory().getContents().values()) { + if (i.getId() == ItemID.ARROW) return true; + } + return false; } @Override public boolean onRelease(Player player, int ticksUsed) { - Item itemArrow = Item.get(Item.ARROW, 0, 1); - - Inventory inventory = player.getOffhandInventory(); + Item itemArrow = null; + boolean offhand = false; + if (player.getOffhandInventory().getItemFast(0).getId() == ItemID.ARROW) { + itemArrow = player.getOffhandInventory().getItemFast(0).clone(); + itemArrow.setCount(1); + offhand = true; + } else { + for (Item i : player.getInventory().getContents().values()) { + if (i.getId() == ItemID.ARROW) { + itemArrow = i.clone(); + itemArrow.setCount(1); + break; + } + } + } - if (!inventory.contains(itemArrow) && !(inventory = player.getInventory()).contains(itemArrow) && (player.isAdventure() || player.isSurvival())) { - player.getOffhandInventory().sendContents(player); - inventory.sendContents(player); - return false; + if (itemArrow == null) { + if (player.isCreative()) { + itemArrow = Item.get(Item.ARROW, 0, 1); + } else { + return false; + } } double damage = 2; - Enchantment bowDamage = this.getEnchantment(Enchantment.ID_BOW_POWER); if (bowDamage != null && bowDamage.getLevel() > 0) { damage += (double) bowDamage.getLevel() * 0.5 + 0.5; @@ -73,6 +96,12 @@ public boolean onRelease(Player player, int ticksUsed) { Enchantment flameEnchant = this.getEnchantment(Enchantment.ID_BOW_FLAME); boolean flame = flameEnchant != null && flameEnchant.getLevel() > 0; + float knockBack = 0.3f; + Enchantment knockBackEnchantment = this.getEnchantment(Enchantment.ID_BOW_KNOCKBACK); + if (knockBackEnchantment != null) { + knockBack += knockBackEnchantment.getLevel() * 0.1f; + } + CompoundTag nbt = new CompoundTag() .putList(new ListTag("Pos") .add(new DoubleTag("", player.x)) @@ -85,18 +114,17 @@ public boolean onRelease(Player player, int ticksUsed) { .putList(new ListTag("Rotation") .add(new FloatTag("", (player.yaw > 180 ? 360 : 0) - (float) player.yaw)) .add(new FloatTag("", (float) -player.pitch))) - .putShort("Fire", flame ? 45 * 60 : 0) - .putDouble("damage", damage); + .putShort("Fire", flame ? 2700 : 0) + .putDouble("damage", damage) + .putFloat("knockback", knockBack); double p = (double) ticksUsed / 20; - double f = Math.min((p * p + p * 2) / 3, 1) * 2; - - EntityArrow arrow = (EntityArrow) Entity.createEntity("Arrow", player.chunk, nbt, player, f == 2); + double f = Math.min((p * p + p * 2) / 3, 1) * 2.8; - if (arrow == null) { - return false; + EntityArrow arrow = (EntityArrow) Entity.createEntity(EntityArrow.NETWORK_ID, player.chunk, nbt, player, f > 2.3, false); + if (itemArrow.getDamage() > 0) { + arrow.setData(itemArrow.getDamage()); } - EntityShootBowEvent entityShootBowEvent = new EntityShootBowEvent(player, this, arrow, f); if (f < 0.1 || ticksUsed < 3) { @@ -105,25 +133,29 @@ public boolean onRelease(Player player, int ticksUsed) { Server.getInstance().getPluginManager().callEvent(entityShootBowEvent); if (entityShootBowEvent.isCancelled()) { - entityShootBowEvent.getProjectile().kill(); - player.getInventory().sendContents(player); - player.getOffhandInventory().sendContents(player); + entityShootBowEvent.getProjectile().close(); + return false; } else { entityShootBowEvent.getProjectile().setMotion(entityShootBowEvent.getProjectile().getMotion().multiply(entityShootBowEvent.getForce())); Enchantment infinityEnchant = this.getEnchantment(Enchantment.ID_BOW_INFINITY); boolean infinity = infinityEnchant != null && infinityEnchant.getLevel() > 0; EntityProjectile projectile; - if (infinity && (projectile = entityShootBowEvent.getProjectile()) instanceof EntityArrow) { + if (infinity && itemArrow.getDamage() == 0 && (projectile = entityShootBowEvent.getProjectile()) instanceof EntityArrow) { ((EntityArrow) projectile).setPickupMode(EntityArrow.PICKUP_CREATIVE); } - if (player.isAdventure() || player.isSurvival()) { - if (!infinity) { - inventory.removeItem(itemArrow); + if (!player.isCreative()) { + if (!infinity || itemArrow.getDamage() != 0) { + if (offhand) { + player.getOffhandInventory().removeItem(itemArrow); + } else { + player.getInventory().removeItem(itemArrow); + } } + if (!this.isUnbreakable()) { Enchantment durability = this.getEnchantment(Enchantment.ID_DURABILITY); - if (!(durability != null && durability.getLevel() > 0 && (100 / (durability.getLevel() + 1)) <= new Random().nextInt(100))) { - this.setDamage(this.getDamage() + 1); + if (!(durability != null && durability.getLevel() > 0 && (100 / (durability.getLevel() + 1)) <= Utils.random.nextInt(100))) { + this.setDamage(this.getDamage() + 2); if (this.getDamage() >= getMaxDurability()) { this.count--; } @@ -131,13 +163,15 @@ public boolean onRelease(Player player, int ticksUsed) { } } } + if (entityShootBowEvent.getProjectile() != null) { - ProjectileLaunchEvent projectev = new ProjectileLaunchEvent(entityShootBowEvent.getProjectile()); + EntityProjectile proj = entityShootBowEvent.getProjectile(); + ProjectileLaunchEvent projectev = new ProjectileLaunchEvent(proj); Server.getInstance().getPluginManager().callEvent(projectev); if (projectev.isCancelled()) { - entityShootBowEvent.getProjectile().kill(); + proj.close(); } else { - entityShootBowEvent.getProjectile().spawnToAll(); + proj.spawnToAll(); player.getLevel().addLevelSoundEvent(player, LevelSoundEventPacket.SOUND_BOW); } } diff --git a/src/main/java/cn/nukkit/item/ItemBowl.java b/src/main/java/cn/nukkit/item/ItemBowl.java index 886fd824cee..ea866c81cac 100644 --- a/src/main/java/cn/nukkit/item/ItemBowl.java +++ b/src/main/java/cn/nukkit/item/ItemBowl.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemBowl extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemBread.java b/src/main/java/cn/nukkit/item/ItemBread.java index 49f52fc0bf7..1334d450348 100644 --- a/src/main/java/cn/nukkit/item/ItemBread.java +++ b/src/main/java/cn/nukkit/item/ItemBread.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemBread extends ItemEdible { diff --git a/src/main/java/cn/nukkit/item/ItemBrewingStand.java b/src/main/java/cn/nukkit/item/ItemBrewingStand.java index 6a70de3d858..aeadd0ca451 100644 --- a/src/main/java/cn/nukkit/item/ItemBrewingStand.java +++ b/src/main/java/cn/nukkit/item/ItemBrewingStand.java @@ -1,7 +1,6 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; public class ItemBrewingStand extends Item { @@ -15,7 +14,6 @@ public ItemBrewingStand(Integer meta) { public ItemBrewingStand(Integer meta, int count) { super(BREWING_STAND, 0, count, "Brewing Stand"); - this.block = Block.get(BlockID.BREWING_STAND_BLOCK); + this.block = Block.get(BREWING_STAND_BLOCK); } - } \ No newline at end of file diff --git a/src/main/java/cn/nukkit/item/ItemBrick.java b/src/main/java/cn/nukkit/item/ItemBrick.java index 0f1414b7271..0339d287d41 100644 --- a/src/main/java/cn/nukkit/item/ItemBrick.java +++ b/src/main/java/cn/nukkit/item/ItemBrick.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemBrick extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemBucket.java b/src/main/java/cn/nukkit/item/ItemBucket.java index 8b8740ef62c..976cdf99bc2 100644 --- a/src/main/java/cn/nukkit/item/ItemBucket.java +++ b/src/main/java/cn/nukkit/item/ItemBucket.java @@ -8,6 +8,7 @@ import cn.nukkit.event.player.PlayerBucketFillEvent; import cn.nukkit.event.player.PlayerItemConsumeEvent; import cn.nukkit.level.Level; +import cn.nukkit.level.format.anvil.Anvil; import cn.nukkit.level.particle.ExplodeParticle; import cn.nukkit.math.BlockFace; import cn.nukkit.math.BlockFace.Plane; @@ -16,7 +17,7 @@ import cn.nukkit.network.protocol.UpdateBlockPacket; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemBucket extends Item { @@ -49,6 +50,8 @@ protected static String getName(int meta) { return "Water Bucket"; case 10: return "Lava Bucket"; + case 11: + return "Powder Snow Bucket"; case 12: return "Bucket of Axolotl"; case 13: @@ -65,15 +68,34 @@ public static int getDamageByTarget(int target) { case 4: case 5: case 8: - case 9: + case 9: // still water case 12: case 13: - return 8; + return WATER; case 10: + case 11: // still lava + return LAVA; + default: + return AIR; + } + } + + public static int getBlockByDamage(int target) { + switch (target) { + case 2: + case 3: + case 4: + case 5: + case 8: + case 12: + case 13: + return WATER; + case 10: + return LAVA; case 11: - return 10; + return POWDER_SNOW; default: - return 0; + return AIR; } } @@ -84,7 +106,7 @@ public int getMaxStackSize() { @Override public boolean canBeActivated() { - return true; + return this.getDamage() != 1; // Not milk } @Override @@ -93,32 +115,65 @@ public boolean onActivate(Level level, Player player, Block block, Block target, return false; } - Block targetBlock = Block.get(getDamageByTarget(this.meta)); + Block targetBlock; + if (target instanceof BlockPowderSnow && this.getDamage() == 0) { + PlayerBucketFillEvent ev = new PlayerBucketFillEvent(player, block, face, this, Item.get(BUCKET, 11, 1)); + player.getServer().getPluginManager().callEvent(ev); + + if (!ev.isCancelled()) { + player.getLevel().setBlock(target, BlockLayer.NORMAL, Block.get(BlockID.AIR), true, true); + + if (!player.isCreative()) { + if (this.getCount() - 1 <= 0) { + player.getInventory().setItemInHand(ev.getItem()); + } else { + player.getInventory().setItemInHand(this.decrement(1)); + if (player.getInventory().canAddItem(ev.getItem())) { + player.getInventory().addItem(ev.getItem()); + } else { + player.dropItem(ev.getItem()); + } + } + } + + level.addLevelSoundEvent(block, LevelSoundEventPacket.SOUND_BUCKET_FILL_POWDER_SNOW); + return true; + } else { + player.setNeedSendInventory(true); + } + } else if ((targetBlock = Block.get(getBlockByDamage(this.meta))) instanceof BlockAir) { + if (!(target instanceof BlockLiquid) || target.getDamage() != 0) { + target = target.getLevelBlock(BlockLayer.WATERLOGGED); + } + if (!(target instanceof BlockLiquid) || target.getDamage() != 0) { + target = block; + } + if (!(target instanceof BlockLiquid) || target.getDamage() != 0) { + target = block.getLevelBlock(BlockLayer.WATERLOGGED); + } - if (targetBlock instanceof BlockAir) { if (target instanceof BlockLiquid && target.getDamage() == 0) { Item result = Item.get(BUCKET, getDamageByTarget(target.getId()), 1); PlayerBucketFillEvent ev; player.getServer().getPluginManager().callEvent(ev = new PlayerBucketFillEvent(player, block, face, this, result)); + if (!ev.isCancelled()) { - player.getLevel().setBlock(target, Block.get(BlockID.AIR), true, true); + player.getLevel().setBlock(target, target.getLayer(), Block.get(BlockID.AIR), true, true); // When water is removed ensure any adjacent still water is // replaced with water that can flow. for (BlockFace side : Plane.HORIZONTAL) { - Block b = target.getSide(side); + Block b = target.getSide(Block.LAYER_NORMAL, side); if (b.getId() == STILL_WATER) { level.setBlock(b, Block.get(BlockID.WATER)); } } - if (player.isSurvival()) { + if (!player.isCreative()) { if (this.getCount() - 1 <= 0) { player.getInventory().setItemInHand(ev.getItem()); } else { - Item clone = this.clone(); - clone.setCount(this.getCount() - 1); - player.getInventory().setItemInHand(clone); + player.getInventory().setItemInHand(this.decrement(1)); if (player.getInventory().canAddItem(ev.getItem())) { player.getInventory().addItem(ev.getItem()); } else { @@ -135,13 +190,34 @@ public boolean onActivate(Level level, Player player, Block block, Block target, return true; } else { - player.getInventory().sendContents(player); + player.setNeedSendInventory(true); } } } else if (targetBlock instanceof BlockLiquid) { Item result = Item.get(BUCKET, 0, 1); + boolean usesWaterlogging = ((BlockLiquid) targetBlock).usesWaterLogging(); + Block placementBlock; + if (usesWaterlogging) { + if (block.getId() == BlockID.BAMBOO) { + placementBlock = block; + } else if (target.getWaterloggingType() != Block.WaterloggingType.NO_WATERLOGGING) { + placementBlock = target.getLevelBlock(BlockLayer.WATERLOGGED); + } else if (block.getWaterloggingType() != Block.WaterloggingType.NO_WATERLOGGING) { + placementBlock = block.getLevelBlock(BlockLayer.WATERLOGGED); + } else { + placementBlock = block; + } + } else { + placementBlock = block; + } PlayerBucketEmptyEvent ev = new PlayerBucketEmptyEvent(player, block, face, this, result, true); - if (!block.canBeFlowedInto()) { + boolean canBeFlowedInto = placementBlock.canBeFlowedInto() || placementBlock.getId() == BlockID.BAMBOO; + if (usesWaterlogging) { + ev.setCancelled(placementBlock.getWaterloggingType() == Block.WaterloggingType.NO_WATERLOGGING && !canBeFlowedInto); + } else { + ev.setCancelled(!canBeFlowedInto); + } + if (!block.canBeFlowedInto() && !(block instanceof BlockTrapdoor)) { ev.setCancelled(true); } @@ -154,14 +230,12 @@ public boolean onActivate(Level level, Player player, Block block, Block target, player.getServer().getPluginManager().callEvent(ev); if (!ev.isCancelled()) { - player.getLevel().setBlock(block, targetBlock, true, true); - if (player.isSurvival()) { + player.getLevel().setBlock(placementBlock, placementBlock.getLayer(), targetBlock, true, true); + if (!player.isCreative()) { if (this.getCount() - 1 <= 0) { player.getInventory().setItemInHand(ev.getItem()); } else { - Item clone = this.clone(); - clone.setCount(this.getCount() - 1); - player.getInventory().setItemInHand(clone); + player.getInventory().setItemInHand(this.decrement(1)); if (player.getInventory().canAddItem(ev.getItem())) { player.getInventory().addItem(ev.getItem()); } else { @@ -214,8 +288,36 @@ public boolean onActivate(Level level, Player player, Block block, Block target, player.getLevel().addLevelSoundEvent(target, LevelSoundEventPacket.SOUND_FIZZ); player.getLevel().addParticle(new ExplodeParticle(target.add(0.5, 1, 0.5))); } else { - player.getLevel().sendBlocks(new Player[]{player}, new Block[]{Block.get(Block.AIR, 0, block)}, UpdateBlockPacket.FLAG_ALL_PRIORITY, 1); - player.getInventory().sendContents(player); + player.getLevel().sendBlocks(new Player[] {player}, new Block[] {block.getLevelBlock(Block.LAYER_WATERLOGGED)}, UpdateBlockPacket.FLAG_ALL_PRIORITY, BlockLayer.WATERLOGGED); + player.setNeedSendInventory(true); + } + } else if (targetBlock instanceof BlockPowderSnow) { + if (player.getLevel().getProvider() instanceof Anvil || !block.canBeReplaced()) { + return false; + } + + PlayerBucketEmptyEvent ev = new PlayerBucketEmptyEvent(player, block, face, this, Item.get(BUCKET, 0, 1), true); + player.getServer().getPluginManager().callEvent(ev); + + if (!ev.isCancelled()) { + player.getLevel().setBlock(block, BlockLayer.NORMAL, targetBlock, true, true); + if (!player.isCreative()) { + if (this.getCount() - 1 <= 0) { + player.getInventory().setItemInHand(ev.getItem()); + } else { + player.getInventory().setItemInHand(this.decrement(1)); + if (player.getInventory().canAddItem(ev.getItem())) { + player.getInventory().addItem(ev.getItem()); + } else { + player.dropItem(ev.getItem()); + } + } + } + + level.addLevelSoundEvent(block, LevelSoundEventPacket.SOUND_BUCKET_EMPTY_POWDER_SNOW); + return true; + } else { + player.setNeedSendInventory(true); } } @@ -237,7 +339,7 @@ public boolean onUse(Player player, int ticksUsed) { player.getServer().getPluginManager().callEvent(consumeEvent); if (consumeEvent.isCancelled()) { - player.getInventory().sendContents(player); + player.setNeedSendInventory(true); return false; } diff --git a/src/main/java/cn/nukkit/item/ItemCake.java b/src/main/java/cn/nukkit/item/ItemCake.java index d3f0021ed00..0d7037c3b38 100644 --- a/src/main/java/cn/nukkit/item/ItemCake.java +++ b/src/main/java/cn/nukkit/item/ItemCake.java @@ -1,10 +1,9 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemCake extends Item { @@ -19,7 +18,7 @@ public ItemCake(Integer meta) { public ItemCake(Integer meta, int count) { super(CAKE, 0, count, "Cake"); - this.block = Block.get(BlockID.CAKE_BLOCK); + this.block = Block.get(CAKE_BLOCK); } @Override diff --git a/src/main/java/cn/nukkit/item/ItemCampfire.java b/src/main/java/cn/nukkit/item/ItemCampfire.java new file mode 100644 index 00000000000..c7ba1b41579 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemCampfire.java @@ -0,0 +1,19 @@ +package cn.nukkit.item; + +import cn.nukkit.block.Block; + +public class ItemCampfire extends Item { + + public ItemCampfire() { + this(0, 1); + } + + public ItemCampfire(Integer meta) { + this(meta, 1); + } + + public ItemCampfire(Integer meta, int count) { + super(CAMPFIRE, meta, count, "Campfire"); + this.block = Block.get(CAMPFIRE_BLOCK); + } +} diff --git a/src/main/java/cn/nukkit/item/ItemCampfireSoul.java b/src/main/java/cn/nukkit/item/ItemCampfireSoul.java new file mode 100644 index 00000000000..5a5abd82a42 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemCampfireSoul.java @@ -0,0 +1,19 @@ +package cn.nukkit.item; + +import cn.nukkit.block.Block; + +public class ItemCampfireSoul extends Item { + + public ItemCampfireSoul() { + this(0, 1); + } + + public ItemCampfireSoul(Integer meta) { + this(meta, 1); + } + + public ItemCampfireSoul(Integer meta, int count) { + super(SOUL_CAMPFIRE, meta, count, "Soul Campfire"); + this.block = Block.get(Block.SOUL_CAMPFIRE_BLOCK); + } +} diff --git a/src/main/java/cn/nukkit/item/ItemCarrot.java b/src/main/java/cn/nukkit/item/ItemCarrot.java index 3aeba7409be..19ceefcd61a 100644 --- a/src/main/java/cn/nukkit/item/ItemCarrot.java +++ b/src/main/java/cn/nukkit/item/ItemCarrot.java @@ -1,10 +1,9 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemCarrot extends ItemEdible { @@ -19,7 +18,6 @@ public ItemCarrot(Integer meta) { public ItemCarrot(Integer meta, int count) { super(CARROT, 0, count, "Carrot"); - this.block = Block.get(BlockID.CARROT_BLOCK); + this.block = Block.get(CARROT_BLOCK); } - } diff --git a/src/main/java/cn/nukkit/item/ItemCarrotGolden.java b/src/main/java/cn/nukkit/item/ItemCarrotGolden.java index d11c1a3e1b5..176e1b3af85 100644 --- a/src/main/java/cn/nukkit/item/ItemCarrotGolden.java +++ b/src/main/java/cn/nukkit/item/ItemCarrotGolden.java @@ -1,6 +1,7 @@ package cn.nukkit.item; public class ItemCarrotGolden extends ItemEdible { + public ItemCarrotGolden() { this(0, 1); } diff --git a/src/main/java/cn/nukkit/item/ItemCauldron.java b/src/main/java/cn/nukkit/item/ItemCauldron.java index 59b306e9684..e53d4163393 100644 --- a/src/main/java/cn/nukkit/item/ItemCauldron.java +++ b/src/main/java/cn/nukkit/item/ItemCauldron.java @@ -1,10 +1,9 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; /** - * author: CreeperFace + * @author CreeperFace * Nukkit Project */ public class ItemCauldron extends Item { @@ -19,6 +18,6 @@ public ItemCauldron(Integer meta) { public ItemCauldron(Integer meta, int count) { super(CAULDRON, meta, count, "Cauldron"); - this.block = Block.get(BlockID.CAULDRON_BLOCK); + this.block = Block.get(CAULDRON_BLOCK); } } \ No newline at end of file diff --git a/src/main/java/cn/nukkit/item/ItemChain.java b/src/main/java/cn/nukkit/item/ItemChain.java new file mode 100644 index 00000000000..e5fcae87a78 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemChain.java @@ -0,0 +1,20 @@ +package cn.nukkit.item; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; + +public class ItemChain extends Item { + + public ItemChain() { + this(0, 1); + } + + public ItemChain(Integer meta) { + this(meta, 1); + } + + public ItemChain(Integer meta, int count) { + super(CHAIN, meta, count, "Chain"); + this.block = Block.get(BlockID.CHAIN_BLOCK); + } +} diff --git a/src/main/java/cn/nukkit/item/ItemChestBoatAcacia.java b/src/main/java/cn/nukkit/item/ItemChestBoatAcacia.java new file mode 100644 index 00000000000..c21b4f447ed --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemChestBoatAcacia.java @@ -0,0 +1,65 @@ +package cn.nukkit.item; + +import cn.nukkit.Player; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockWater; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityChestBoat; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.DoubleTag; +import cn.nukkit.nbt.tag.FloatTag; +import cn.nukkit.nbt.tag.ListTag; + +public class ItemChestBoatAcacia extends Item { + + public ItemChestBoatAcacia() { + this(0, 1); + } + + public ItemChestBoatAcacia(Integer meta) { + this(meta, 1); + } + + public ItemChestBoatAcacia(Integer meta, int count) { + super(ACACIA_CHEST_BOAT, meta, count, "Oak Boat with Chest"); + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Level level, Player player, Block block, Block target, BlockFace face, double fx, double fy, double fz) { + if (face != BlockFace.UP) return false; + EntityChestBoat boat = (EntityChestBoat) Entity.createEntity(EntityChestBoat.NETWORK_ID, + level.getChunk(block.getChunkX(), block.getChunkZ()), new CompoundTag("") + .putList(new ListTag("Pos") + .add(new DoubleTag("", block.getX() + 0.5)) + .add(new DoubleTag("", block.getY() - (target instanceof BlockWater ? 0.1 : 0))) + .add(new DoubleTag("", block.getZ() + 0.5))) + .putList(new ListTag("Motion") + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0))) + .putList(new ListTag("Rotation") + .add(new FloatTag("", (float) ((player.yaw + 90f) % 360))) + .add(new FloatTag("", 0))) + .putInt("Variant", 4) + ); + + if (!player.isCreative()) { + this.count--; + } + + boat.spawnToAll(); + return true; + } + + @Override + public int getMaxStackSize() { + return 1; + } +} diff --git a/src/main/java/cn/nukkit/item/ItemChestBoatBirch.java b/src/main/java/cn/nukkit/item/ItemChestBoatBirch.java new file mode 100644 index 00000000000..f4a69f78282 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemChestBoatBirch.java @@ -0,0 +1,65 @@ +package cn.nukkit.item; + +import cn.nukkit.Player; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockWater; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityChestBoat; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.DoubleTag; +import cn.nukkit.nbt.tag.FloatTag; +import cn.nukkit.nbt.tag.ListTag; + +public class ItemChestBoatBirch extends Item { + + public ItemChestBoatBirch() { + this(0, 1); + } + + public ItemChestBoatBirch(Integer meta) { + this(meta, 1); + } + + public ItemChestBoatBirch(Integer meta, int count) { + super(BIRCH_CHEST_BOAT, meta, count, "Birch Boat with Chest"); + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Level level, Player player, Block block, Block target, BlockFace face, double fx, double fy, double fz) { + if (face != BlockFace.UP) return false; + EntityChestBoat boat = (EntityChestBoat) Entity.createEntity(EntityChestBoat.NETWORK_ID, + level.getChunk(block.getChunkX(), block.getChunkZ()), new CompoundTag("") + .putList(new ListTag("Pos") + .add(new DoubleTag("", block.getX() + 0.5)) + .add(new DoubleTag("", block.getY() - (target instanceof BlockWater ? 0.1 : 0))) + .add(new DoubleTag("", block.getZ() + 0.5))) + .putList(new ListTag("Motion") + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0))) + .putList(new ListTag("Rotation") + .add(new FloatTag("", (float) ((player.yaw + 90f) % 360))) + .add(new FloatTag("", 0))) + .putInt("Variant", 2) + ); + + if (!player.isCreative()) { + this.count--; + } + + boat.spawnToAll(); + return true; + } + + @Override + public int getMaxStackSize() { + return 1; + } +} diff --git a/src/main/java/cn/nukkit/item/ItemChestBoatDarkOak.java b/src/main/java/cn/nukkit/item/ItemChestBoatDarkOak.java new file mode 100644 index 00000000000..0bcb3ade8ed --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemChestBoatDarkOak.java @@ -0,0 +1,64 @@ +package cn.nukkit.item; + +import cn.nukkit.Player; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockWater; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityChestBoat; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.DoubleTag; +import cn.nukkit.nbt.tag.FloatTag; +import cn.nukkit.nbt.tag.ListTag; + +public class ItemChestBoatDarkOak extends Item { + + public ItemChestBoatDarkOak() { + this(0, 1); + } + + public ItemChestBoatDarkOak(Integer meta) { + this(meta, 1); + } + + public ItemChestBoatDarkOak(Integer meta, int count) { + super(DARK_OAK_CHEST_BOAT, meta, count, "Oak Boat with Chest"); + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Level level, Player player, Block block, Block target, BlockFace face, double fx, double fy, double fz) { + if (face != BlockFace.UP) return false; + Entity.createEntity(EntityChestBoat.NETWORK_ID, + level.getChunk(block.getChunkX(), block.getChunkZ()), new CompoundTag("") + .putList(new ListTag("Pos") + .add(new DoubleTag("", block.getX() + 0.5)) + .add(new DoubleTag("", block.getY() - (target instanceof BlockWater ? 0.1 : 0))) + .add(new DoubleTag("", block.getZ() + 0.5))) + .putList(new ListTag("Motion") + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0))) + .putList(new ListTag("Rotation") + .add(new FloatTag("", (float) ((player.yaw + 90f) % 360))) + .add(new FloatTag("", 0))) + .putInt("Variant", 5) + ).spawnToAll(); + + if (!player.isCreative()) { + this.count--; + } + + return true; + } + + @Override + public int getMaxStackSize() { + return 1; + } +} diff --git a/src/main/java/cn/nukkit/item/ItemChestBoatJungle.java b/src/main/java/cn/nukkit/item/ItemChestBoatJungle.java new file mode 100644 index 00000000000..001f4306e08 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemChestBoatJungle.java @@ -0,0 +1,65 @@ +package cn.nukkit.item; + +import cn.nukkit.Player; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockWater; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityChestBoat; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.DoubleTag; +import cn.nukkit.nbt.tag.FloatTag; +import cn.nukkit.nbt.tag.ListTag; + +public class ItemChestBoatJungle extends Item { + + public ItemChestBoatJungle() { + this(0, 1); + } + + public ItemChestBoatJungle(Integer meta) { + this(meta, 1); + } + + public ItemChestBoatJungle(Integer meta, int count) { + super(JUNGLE_CHEST_BOAT, meta, count, "Oak Boat with Chest"); + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Level level, Player player, Block block, Block target, BlockFace face, double fx, double fy, double fz) { + if (face != BlockFace.UP) return false; + EntityChestBoat boat = (EntityChestBoat) Entity.createEntity(EntityChestBoat.NETWORK_ID, + level.getChunk(block.getChunkX(), block.getChunkZ()), new CompoundTag("") + .putList(new ListTag("Pos") + .add(new DoubleTag("", block.getX() + 0.5)) + .add(new DoubleTag("", block.getY() - (target instanceof BlockWater ? 0.1 : 0))) + .add(new DoubleTag("", block.getZ() + 0.5))) + .putList(new ListTag("Motion") + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0))) + .putList(new ListTag("Rotation") + .add(new FloatTag("", (float) ((player.yaw + 90f) % 360))) + .add(new FloatTag("", 0))) + .putInt("Variant", 3) + ); + + if (!player.isCreative()) { + this.count--; + } + + boat.spawnToAll(); + return true; + } + + @Override + public int getMaxStackSize() { + return 1; + } +} diff --git a/src/main/java/cn/nukkit/item/ItemChestBoatMangrove.java b/src/main/java/cn/nukkit/item/ItemChestBoatMangrove.java new file mode 100644 index 00000000000..ac07a051823 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemChestBoatMangrove.java @@ -0,0 +1,65 @@ +package cn.nukkit.item; + +import cn.nukkit.Player; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockWater; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityChestBoat; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.DoubleTag; +import cn.nukkit.nbt.tag.FloatTag; +import cn.nukkit.nbt.tag.ListTag; + +public class ItemChestBoatMangrove extends Item { + + public ItemChestBoatMangrove() { + this(0, 1); + } + + public ItemChestBoatMangrove(Integer meta) { + this(meta, 1); + } + + public ItemChestBoatMangrove(Integer meta, int count) { + super(MANGROVE_CHEST_BOAT, meta, count, "Oak Boat with Chest"); + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Level level, Player player, Block block, Block target, BlockFace face, double fx, double fy, double fz) { + if (face != BlockFace.UP) return false; + EntityChestBoat boat = (EntityChestBoat) Entity.createEntity(EntityChestBoat.NETWORK_ID, + level.getChunk(block.getChunkX(), block.getChunkZ()), new CompoundTag("") + .putList(new ListTag("Pos") + .add(new DoubleTag("", block.getX() + 0.5)) + .add(new DoubleTag("", block.getY() - (target instanceof BlockWater ? 0.1 : 0))) + .add(new DoubleTag("", block.getZ() + 0.5))) + .putList(new ListTag("Motion") + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0))) + .putList(new ListTag("Rotation") + .add(new FloatTag("", (float) ((player.yaw + 90f) % 360))) + .add(new FloatTag("", 0))) + .putInt("Variant", 6) + ); + + if (!player.isCreative()) { + this.count--; + } + + boat.spawnToAll(); + return true; + } + + @Override + public int getMaxStackSize() { + return 1; + } +} diff --git a/src/main/java/cn/nukkit/item/ItemChestBoatOak.java b/src/main/java/cn/nukkit/item/ItemChestBoatOak.java new file mode 100644 index 00000000000..9ffdb662cde --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemChestBoatOak.java @@ -0,0 +1,65 @@ +package cn.nukkit.item; + +import cn.nukkit.Player; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockWater; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityChestBoat; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.DoubleTag; +import cn.nukkit.nbt.tag.FloatTag; +import cn.nukkit.nbt.tag.ListTag; + +public class ItemChestBoatOak extends Item { + + public ItemChestBoatOak() { + this(0, 1); + } + + public ItemChestBoatOak(Integer meta) { + this(meta, 1); + } + + public ItemChestBoatOak(Integer meta, int count) { + super(OAK_CHEST_BOAT, meta, count, "Oak Boat with Chest"); + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Level level, Player player, Block block, Block target, BlockFace face, double fx, double fy, double fz) { + if (face != BlockFace.UP) return false; + EntityChestBoat boat = (EntityChestBoat) Entity.createEntity(EntityChestBoat.NETWORK_ID, + level.getChunk(block.getChunkX(), block.getChunkZ()), new CompoundTag("") + .putList(new ListTag("Pos") + .add(new DoubleTag("", block.getX() + 0.5)) + .add(new DoubleTag("", block.getY() - (target instanceof BlockWater ? 0.1 : 0))) + .add(new DoubleTag("", block.getZ() + 0.5))) + .putList(new ListTag("Motion") + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0))) + .putList(new ListTag("Rotation") + .add(new FloatTag("", (float) ((player.yaw + 90f) % 360))) + .add(new FloatTag("", 0))) + .putInt("Variant", 0) + ); + + if (!player.isCreative()) { + this.count--; + } + + boat.spawnToAll(); + return true; + } + + @Override + public int getMaxStackSize() { + return 1; + } +} diff --git a/src/main/java/cn/nukkit/item/ItemChestBoatSpruce.java b/src/main/java/cn/nukkit/item/ItemChestBoatSpruce.java new file mode 100644 index 00000000000..12681499349 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemChestBoatSpruce.java @@ -0,0 +1,64 @@ +package cn.nukkit.item; + +import cn.nukkit.Player; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockWater; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.item.EntityChestBoat; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.DoubleTag; +import cn.nukkit.nbt.tag.FloatTag; +import cn.nukkit.nbt.tag.ListTag; + +public class ItemChestBoatSpruce extends Item { + + public ItemChestBoatSpruce() { + this(0, 1); + } + + public ItemChestBoatSpruce(Integer meta) { + this(meta, 1); + } + + public ItemChestBoatSpruce(Integer meta, int count) { + super(SPRUCE_CHEST_BOAT, meta, count, "Oak Boat with Chest"); + } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Level level, Player player, Block block, Block target, BlockFace face, double fx, double fy, double fz) { + if (face != BlockFace.UP) return false; + Entity.createEntity(EntityChestBoat.NETWORK_ID, + level.getChunk(block.getChunkX(), block.getChunkZ()), new CompoundTag("") + .putList(new ListTag("Pos") + .add(new DoubleTag("", block.getX() + 0.5)) + .add(new DoubleTag("", block.getY() - (target instanceof BlockWater ? 0.1 : 0))) + .add(new DoubleTag("", block.getZ() + 0.5))) + .putList(new ListTag("Motion") + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0))) + .putList(new ListTag("Rotation") + .add(new FloatTag("", (float) ((player.yaw + 90f) % 360))) + .add(new FloatTag("", 0))) + .putInt("Variant", 1) + ).spawnToAll(); + + if (!player.isCreative()) { + this.count--; + } + + return true; + } + + @Override + public int getMaxStackSize() { + return 1; + } +} diff --git a/src/main/java/cn/nukkit/item/ItemChestplateChain.java b/src/main/java/cn/nukkit/item/ItemChestplateChain.java index b19082e7554..609a364ec9a 100644 --- a/src/main/java/cn/nukkit/item/ItemChestplateChain.java +++ b/src/main/java/cn/nukkit/item/ItemChestplateChain.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemChestplateChain extends ItemArmor { diff --git a/src/main/java/cn/nukkit/item/ItemChestplateDiamond.java b/src/main/java/cn/nukkit/item/ItemChestplateDiamond.java index cae253764e7..55e0fe9f9cb 100644 --- a/src/main/java/cn/nukkit/item/ItemChestplateDiamond.java +++ b/src/main/java/cn/nukkit/item/ItemChestplateDiamond.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemChestplateDiamond extends ItemArmor { diff --git a/src/main/java/cn/nukkit/item/ItemChestplateGold.java b/src/main/java/cn/nukkit/item/ItemChestplateGold.java index 60856b738be..cc91d7af651 100644 --- a/src/main/java/cn/nukkit/item/ItemChestplateGold.java +++ b/src/main/java/cn/nukkit/item/ItemChestplateGold.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemChestplateGold extends ItemArmor { @@ -15,7 +15,7 @@ public ItemChestplateGold(Integer meta) { } public ItemChestplateGold(Integer meta, int count) { - super(GOLD_CHESTPLATE, meta, count, "Gold Chestplate"); + super(GOLD_CHESTPLATE, meta, count, "Golden Chestplate"); } @Override diff --git a/src/main/java/cn/nukkit/item/ItemChestplateIron.java b/src/main/java/cn/nukkit/item/ItemChestplateIron.java index 69c12764628..3aefbe3f0aa 100644 --- a/src/main/java/cn/nukkit/item/ItemChestplateIron.java +++ b/src/main/java/cn/nukkit/item/ItemChestplateIron.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemChestplateIron extends ItemArmor { diff --git a/src/main/java/cn/nukkit/item/ItemChestplateLeather.java b/src/main/java/cn/nukkit/item/ItemChestplateLeather.java index c6496a7af1a..561c221f116 100644 --- a/src/main/java/cn/nukkit/item/ItemChestplateLeather.java +++ b/src/main/java/cn/nukkit/item/ItemChestplateLeather.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemChestplateLeather extends ItemColorArmor { diff --git a/src/main/java/cn/nukkit/item/ItemChestplateNetherite.java b/src/main/java/cn/nukkit/item/ItemChestplateNetherite.java index 09674778ac9..3007fa3b36c 100644 --- a/src/main/java/cn/nukkit/item/ItemChestplateNetherite.java +++ b/src/main/java/cn/nukkit/item/ItemChestplateNetherite.java @@ -36,6 +36,6 @@ public int getArmorPoints() { @Override public int getToughness() { - return 2; + return 3; } } diff --git a/src/main/java/cn/nukkit/item/ItemChickenCooked.java b/src/main/java/cn/nukkit/item/ItemChickenCooked.java index 32771b663de..7571fa9474b 100644 --- a/src/main/java/cn/nukkit/item/ItemChickenCooked.java +++ b/src/main/java/cn/nukkit/item/ItemChickenCooked.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemChickenCooked extends ItemEdible { diff --git a/src/main/java/cn/nukkit/item/ItemChickenRaw.java b/src/main/java/cn/nukkit/item/ItemChickenRaw.java index fc510835eb4..685565db5b8 100644 --- a/src/main/java/cn/nukkit/item/ItemChickenRaw.java +++ b/src/main/java/cn/nukkit/item/ItemChickenRaw.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemChickenRaw extends ItemEdible { diff --git a/src/main/java/cn/nukkit/item/ItemChorusFruit.java b/src/main/java/cn/nukkit/item/ItemChorusFruit.java index da98bdf478f..3481763650d 100644 --- a/src/main/java/cn/nukkit/item/ItemChorusFruit.java +++ b/src/main/java/cn/nukkit/item/ItemChorusFruit.java @@ -3,9 +3,6 @@ import cn.nukkit.Player; import cn.nukkit.math.Vector3; -/** - * Created by Leonidius20 on 20.08.18. - */ public class ItemChorusFruit extends ItemEdible { public ItemChorusFruit() { @@ -17,7 +14,7 @@ public ItemChorusFruit(Integer meta) { } public ItemChorusFruit(Integer meta, int count) { - super(CHORUS_FRUIT, meta, count, "Chorus Fruit"); + super(CHORUS_FRUIT, 0, count, "Chorus Fruit"); } @Override @@ -27,10 +24,9 @@ public boolean onClickAir(Player player, Vector3 directionVector) { @Override public boolean onUse(Player player, int ticksUsed) { - boolean successful = super.onUse(player, ticksUsed); - if (successful) { + if (super.onUse(player, ticksUsed)) { player.onChorusFruitTeleport(); } - return successful; + return true; } -} \ No newline at end of file +} diff --git a/src/main/java/cn/nukkit/item/ItemClay.java b/src/main/java/cn/nukkit/item/ItemClay.java index 864a4bc392b..a2d3763a308 100644 --- a/src/main/java/cn/nukkit/item/ItemClay.java +++ b/src/main/java/cn/nukkit/item/ItemClay.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemClay extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemClock.java b/src/main/java/cn/nukkit/item/ItemClock.java index 193e26930a4..5234e5bc8e2 100644 --- a/src/main/java/cn/nukkit/item/ItemClock.java +++ b/src/main/java/cn/nukkit/item/ItemClock.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemClock extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemClownfish.java b/src/main/java/cn/nukkit/item/ItemClownfish.java index c512ab8f090..55aa9d88011 100644 --- a/src/main/java/cn/nukkit/item/ItemClownfish.java +++ b/src/main/java/cn/nukkit/item/ItemClownfish.java @@ -15,6 +15,6 @@ public ItemClownfish(Integer meta) { } public ItemClownfish(Integer meta, int count) { - super(CLOWNFISH, meta, count, "Clownfish"); + super(CLOWNFISH, meta, count, "Tropical Fish"); } } diff --git a/src/main/java/cn/nukkit/item/ItemCoal.java b/src/main/java/cn/nukkit/item/ItemCoal.java index c4fa1c67665..7bd76f1bf17 100644 --- a/src/main/java/cn/nukkit/item/ItemCoal.java +++ b/src/main/java/cn/nukkit/item/ItemCoal.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemCoal extends Item { @@ -15,9 +15,6 @@ public ItemCoal(Integer meta) { } public ItemCoal(Integer meta, int count) { - super(COAL, meta, count, "Coal"); - if (this.meta == 1) { - this.name = "Charcoal"; - } + super(COAL, meta, count, meta != null && meta == 1 ? "Charcoal" : "Coal"); } } diff --git a/src/main/java/cn/nukkit/item/ItemCompass.java b/src/main/java/cn/nukkit/item/ItemCompass.java index 97b0798fb04..626935709b9 100644 --- a/src/main/java/cn/nukkit/item/ItemCompass.java +++ b/src/main/java/cn/nukkit/item/ItemCompass.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemCompass extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemCookie.java b/src/main/java/cn/nukkit/item/ItemCookie.java index a7bdf28e7e8..5088dacedf4 100644 --- a/src/main/java/cn/nukkit/item/ItemCookie.java +++ b/src/main/java/cn/nukkit/item/ItemCookie.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemCookie extends ItemEdible { diff --git a/src/main/java/cn/nukkit/item/ItemCopperRaw.java b/src/main/java/cn/nukkit/item/ItemCopperRaw.java new file mode 100644 index 00000000000..8cdce147bf6 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemCopperRaw.java @@ -0,0 +1,16 @@ +package cn.nukkit.item; + +public class ItemCopperRaw extends Item { + + public ItemCopperRaw() { + this(0, 1); + } + + public ItemCopperRaw(Integer meta) { + this(meta, 1); + } + + public ItemCopperRaw(Integer meta, int count) { + super(RAW_COPPER, meta, count, "Raw Copper"); + } +} diff --git a/src/main/java/cn/nukkit/item/ItemCrossbow.java b/src/main/java/cn/nukkit/item/ItemCrossbow.java index 6abd3526271..8533e982df6 100644 --- a/src/main/java/cn/nukkit/item/ItemCrossbow.java +++ b/src/main/java/cn/nukkit/item/ItemCrossbow.java @@ -1,6 +1,19 @@ package cn.nukkit.item; -public class ItemCrossbow extends ItemTool { +import cn.nukkit.Player; +import cn.nukkit.Server; +import cn.nukkit.entity.Entity; +import cn.nukkit.entity.projectile.EntityArrow; +import cn.nukkit.entity.projectile.EntityProjectile; +import cn.nukkit.event.entity.EntityShootBowEvent; +import cn.nukkit.event.entity.ProjectileLaunchEvent; +import cn.nukkit.item.enchantment.Enchantment; +import cn.nukkit.math.Vector3; +import cn.nukkit.nbt.tag.*; +import cn.nukkit.network.protocol.LevelSoundEventPacket; +import cn.nukkit.utils.Utils; + +public class ItemCrossbow extends ItemBow { public ItemCrossbow() { this(0, 1); @@ -19,6 +32,214 @@ public int getMaxDurability() { return ItemTool.DURABILITY_CROSSBOW; } + @Override + public boolean onUse(Player player, int ticksUsed) { + int needTickUsed = 25; + Enchantment enchantment = this.getEnchantment(Enchantment.ID_CROSSBOW_QUICK_CHARGE); + if (enchantment != null) { + needTickUsed -= enchantment.getLevel() * 5; //0.25s + } + + if (ticksUsed < needTickUsed) { + return true; + } + + Item itemArrow = null; + boolean offhand = false; + Item offhandItem = player.getOffhandInventory().getItemFast(0); + if (offhandItem.getId() == ItemID.ARROW) { + itemArrow = offhandItem.clone(); + itemArrow.setCount(1); + offhand = true; + } else { + for (Item i : player.getInventory().getContents().values()) { + if (i.getId() == ItemID.ARROW) { + itemArrow = i.clone(); + itemArrow.setCount(1); + break; + } + } + } + + if (itemArrow == null) { + if (player.isCreative()) { + itemArrow = Item.get(Item.ARROW, 0, 1); + } else { + return true; + } + } + + if (!this.isLoaded()) { + if (!player.isCreative()) { + if (!this.isUnbreakable()) { + Enchantment durability = this.getEnchantment(Enchantment.ID_DURABILITY); + if (!(durability != null && durability.getLevel() > 0 && (100 / (durability.getLevel() + 1)) <= Utils.random.nextInt(100))) { + this.setDamage(this.getDamage() + 2); + if (this.getDamage() >= DURABILITY_CROSSBOW) { + this.count--; + } + } + } + + if (offhand) { + player.getOffhandInventory().removeItem(itemArrow); + } else { + player.getInventory().removeItem(itemArrow); + } + } + + player.getInventory().setItemInHand(this.loadArrow(itemArrow)); + player.getLevel().addLevelSoundEvent(player, LevelSoundEventPacket.SOUND_CROSSBOW_LOADING_END); + } + + return true; + } + + @Override + public boolean onClickAir(Player player, Vector3 directionVector) { + return false; // Handled directly from Player + } + + @Override + public boolean onRelease(Player player, int ticksUsed) { + return true; + } + + public Item loadArrow(Item arrow) { + if (arrow == null) { + throw new IllegalArgumentException("null cannot be loaded into a crossbow!"); + } + if (arrow.getId() != Item.ARROW) { + throw new IllegalArgumentException(arrow + " cannot be loaded into a crossbow!"); + } + if (arrow.getCount() != 1) { + throw new IllegalArgumentException("Only one arrow per crossbow is supported!"); + } + CompoundTag tag = this.getNamedTag() == null ? new CompoundTag() : this.getNamedTag(); + CompoundTag chargedItem = new CompoundTag("chargedItem") + .putByte("Count", arrow.getCount()) + .putShort("Damage", arrow.getDamage()) + .putString("Name", "minecraft:arrow"); + CompoundTag cTag; + tag.putBoolean("Charged", true).putCompound("chargedItem", chargedItem); + this.setCompoundTag(tag); + return this; + } + + public boolean isLoaded() { + Tag itemInfo = this.getNamedTagEntry("chargedItem"); + if (itemInfo != null) { + CompoundTag tag = (CompoundTag) itemInfo; + return tag.getByte("Count") > 0 && !tag.getString("Name").isEmpty(); + } + + return false; + } + + /** + * Launch the crossbow. Assumes that isLoaded() == true. + * @param player player + * @return launched successfully + */ + public boolean launchArrow(Player player) { + CompoundTag chargedItem = ((CompoundTag) this.getNamedTagEntry("chargedItem")); + if (chargedItem == null) { + throw new IllegalArgumentException("A crossbow without charged item cannot be launched!"); + } + int arrowData = chargedItem.getShort("Damage"); + CompoundTag nbt = new CompoundTag() + .putList(new ListTag("Pos") + .add(new DoubleTag("", player.x)) + .add(new DoubleTag("", player.y + player.getEyeHeight())) + .add(new DoubleTag("", player.z))) + .putList(new ListTag("Motion") + .add(new DoubleTag("", -Math.sin(player.yaw / 180 * Math.PI) * Math.cos(player.pitch / 180 * Math.PI))) + .add(new DoubleTag("", -Math.sin(player.pitch / 180 * Math.PI))) + .add(new DoubleTag("", Math.cos(player.yaw / 180 * Math.PI) * Math.cos(player.pitch / 180 * Math.PI)))) + .putList(new ListTag("Rotation") + .add(new FloatTag("", (player.yaw > 180 ? 360 : 0) - (float) player.yaw)) + .add(new FloatTag("", (float) -player.pitch))); + EntityProjectile arrow; + { + arrow = (EntityArrow) Entity.createEntity(EntityArrow.NETWORK_ID, player.chunk, nbt, player, false, true); + if (arrowData > 0) { + ((EntityArrow) arrow).setData(arrowData); + } + if (this.hasEnchantment(Enchantment.ID_CROSSBOW_PIERCING)) { + arrow.piercing = 1; + } + } + EntityShootBowEvent entityShootBowEvent = new EntityShootBowEvent(player, this, arrow, 3.5); + Server.getInstance().getPluginManager().callEvent(entityShootBowEvent); + if (entityShootBowEvent.isCancelled()) { + entityShootBowEvent.getProjectile().close(); + return false; + } else { + entityShootBowEvent.getProjectile().setMotion(entityShootBowEvent.getProjectile().getMotion().multiply(entityShootBowEvent.getForce())); + if (entityShootBowEvent.getProjectile() != null) { + EntityProjectile proj = entityShootBowEvent.getProjectile(); + ProjectileLaunchEvent projectev = new ProjectileLaunchEvent(proj); + Server.getInstance().getPluginManager().callEvent(projectev); + if (projectev.isCancelled()) { + proj.close(); + return false; + } else { + proj.spawnToAll(); + if (this.hasEnchantment(Enchantment.ID_CROSSBOW_MULTISHOT)) { + CompoundTag nbt1 = new CompoundTag() + .putList(new ListTag("Pos") + .add(new DoubleTag("", player.x)) + .add(new DoubleTag("", player.y + player.getEyeHeight())) + .add(new DoubleTag("", player.z))) + .putList(new ListTag("Motion") + .add(new DoubleTag("", -Math.sin(player.yaw / 180 * Math.PI) * Math.cos(player.pitch / 180 * Math.PI))) + .add(new DoubleTag("", -Math.sin(player.pitch / 180 * Math.PI))) + .add(new DoubleTag("", Math.cos(player.yaw / 180 * Math.PI) * Math.cos(player.pitch / 180 * Math.PI)))) + .putList(new ListTag("Rotation") + .add(new FloatTag("", (player.yaw > 180 ? 360 : 0) - (float) player.yaw - 10)) + .add(new FloatTag("", (float) -player.pitch))); + EntityArrow arrow1 = (EntityArrow) Entity.createEntity(EntityArrow.NETWORK_ID, player.chunk, nbt1, player, false, true); + arrow1.setPickupMode(EntityProjectile.PICKUP_NONE_REMOVE); + if (arrowData > 0) { + arrow1.setData(arrowData); + } + if (this.hasEnchantment(Enchantment.ID_CROSSBOW_PIERCING)) { // Illegal enchantment + arrow1.piercing = 1; + } + arrow1.setMotion(arrow1.getMotion().multiply(entityShootBowEvent.getForce()).add(-0.3, 0, 0.3)); + arrow1.spawnToAll(); + CompoundTag nbt2 = new CompoundTag() + .putList(new ListTag("Pos") + .add(new DoubleTag("", player.x)) + .add(new DoubleTag("", player.y + player.getEyeHeight())) + .add(new DoubleTag("", player.z))) + .putList(new ListTag("Motion") + .add(new DoubleTag("", -Math.sin(player.yaw / 180 * Math.PI) * Math.cos(player.pitch / 180 * Math.PI))) + .add(new DoubleTag("", -Math.sin(player.pitch / 180 * Math.PI))) + .add(new DoubleTag("", Math.cos(player.yaw / 180 * Math.PI) * Math.cos(player.pitch / 180 * Math.PI)))) + .putList(new ListTag("Rotation") + .add(new FloatTag("", (player.yaw > 180 ? 360 : 0) - (float) player.yaw + 10)) + .add(new FloatTag("", (float) -player.pitch))); + EntityArrow arrow2 = (EntityArrow) Entity.createEntity(EntityArrow.NETWORK_ID, player.chunk, nbt2, player, false, true); + arrow2.setPickupMode(EntityProjectile.PICKUP_NONE_REMOVE); + if (arrowData > 0) { + arrow2.setData(arrowData); + } + if (this.hasEnchantment(Enchantment.ID_CROSSBOW_PIERCING)) { // Illegal enchantment + arrow2.piercing = 1; + } + arrow2.setMotion(arrow2.getMotion().multiply(entityShootBowEvent.getForce()).add(0.3, 0, -0.3)); + arrow2.spawnToAll(); + } + player.getLevel().addLevelSoundEvent(player, LevelSoundEventPacket.SOUND_CROSSBOW_SHOOT); + this.setCompoundTag(this.getNamedTag().putBoolean("Charged", false).remove("chargedItem")); + player.getInventory().setItemInHand(this); + } + } + } + return true; + } + @Override public int getEnchantAbility() { return 1; diff --git a/src/main/java/cn/nukkit/item/ItemDiamond.java b/src/main/java/cn/nukkit/item/ItemDiamond.java index b3ef6a5eedd..aa6c1e4a54c 100644 --- a/src/main/java/cn/nukkit/item/ItemDiamond.java +++ b/src/main/java/cn/nukkit/item/ItemDiamond.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemDiamond extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemDiscFragment5.java b/src/main/java/cn/nukkit/item/ItemDiscFragment5.java new file mode 100644 index 00000000000..96a623a47df --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemDiscFragment5.java @@ -0,0 +1,16 @@ +package cn.nukkit.item; + +public class ItemDiscFragment5 extends Item { + + public ItemDiscFragment5() { + this(0, 1); + } + + public ItemDiscFragment5(Integer meta) { + this(meta, 1); + } + + public ItemDiscFragment5(Integer meta, int count) { + super(DISC_FRAGMENT_5, meta, count, "Disc Fragment"); + } +} diff --git a/src/main/java/cn/nukkit/item/ItemDoorAcacia.java b/src/main/java/cn/nukkit/item/ItemDoorAcacia.java index a94538a271a..69175e8b063 100644 --- a/src/main/java/cn/nukkit/item/ItemDoorAcacia.java +++ b/src/main/java/cn/nukkit/item/ItemDoorAcacia.java @@ -1,9 +1,9 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; public class ItemDoorAcacia extends Item { + public ItemDoorAcacia() { this(0, 1); } @@ -14,7 +14,6 @@ public ItemDoorAcacia(Integer meta) { public ItemDoorAcacia(Integer meta, int count) { super(ACACIA_DOOR, 0, count, "Acacia Door"); - this.block = Block.get(BlockID.ACACIA_DOOR_BLOCK); + this.block = Block.get(ACACIA_DOOR_BLOCK); } - } diff --git a/src/main/java/cn/nukkit/item/ItemDoorBirch.java b/src/main/java/cn/nukkit/item/ItemDoorBirch.java index 1da599a503a..9e0f5d5225a 100644 --- a/src/main/java/cn/nukkit/item/ItemDoorBirch.java +++ b/src/main/java/cn/nukkit/item/ItemDoorBirch.java @@ -1,9 +1,9 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; public class ItemDoorBirch extends Item { + public ItemDoorBirch() { this(0, 1); } @@ -14,7 +14,6 @@ public ItemDoorBirch(Integer meta) { public ItemDoorBirch(Integer meta, int count) { super(BIRCH_DOOR, 0, count, "Birch Door"); - this.block = Block.get(BlockID.BIRCH_DOOR_BLOCK); + this.block = Block.get(BIRCH_DOOR_BLOCK); } - } diff --git a/src/main/java/cn/nukkit/item/ItemDoorCrimson.java b/src/main/java/cn/nukkit/item/ItemDoorCrimson.java new file mode 100644 index 00000000000..768b54a8693 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemDoorCrimson.java @@ -0,0 +1,19 @@ +package cn.nukkit.item; + +import cn.nukkit.block.Block; + +public class ItemDoorCrimson extends Item { + + public ItemDoorCrimson() { + this(0, 1); + } + + public ItemDoorCrimson(Integer meta) { + this(meta, 1); + } + + public ItemDoorCrimson(Integer meta, int count) { + super(CRIMSON_DOOR, 0, count, "Crimson Door"); + this.block = Block.get(CRIMSON_DOOR_BLOCK); + } +} diff --git a/src/main/java/cn/nukkit/item/ItemDoorDarkOak.java b/src/main/java/cn/nukkit/item/ItemDoorDarkOak.java index f3259b573d9..a89a23be13b 100644 --- a/src/main/java/cn/nukkit/item/ItemDoorDarkOak.java +++ b/src/main/java/cn/nukkit/item/ItemDoorDarkOak.java @@ -1,9 +1,9 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; public class ItemDoorDarkOak extends Item { + public ItemDoorDarkOak() { this(0, 1); } @@ -14,7 +14,6 @@ public ItemDoorDarkOak(Integer meta) { public ItemDoorDarkOak(Integer meta, int count) { super(DARK_OAK_DOOR, 0, count, "Dark Oak Door"); - this.block = Block.get(BlockID.DARK_OAK_DOOR_BLOCK); + this.block = Block.get(DARK_OAK_DOOR_BLOCK); } - } diff --git a/src/main/java/cn/nukkit/item/ItemDoorIron.java b/src/main/java/cn/nukkit/item/ItemDoorIron.java index a10ed1b10dd..a8af1ee0ff9 100644 --- a/src/main/java/cn/nukkit/item/ItemDoorIron.java +++ b/src/main/java/cn/nukkit/item/ItemDoorIron.java @@ -1,10 +1,9 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemDoorIron extends Item { @@ -19,7 +18,6 @@ public ItemDoorIron(Integer meta) { public ItemDoorIron(Integer meta, int count) { super(IRON_DOOR, 0, count, "Iron Door"); - this.block = Block.get(BlockID.IRON_DOOR_BLOCK); + this.block = Block.get(IRON_DOOR_BLOCK); } - } diff --git a/src/main/java/cn/nukkit/item/ItemDoorJungle.java b/src/main/java/cn/nukkit/item/ItemDoorJungle.java index f5a4aba4bca..1e6bdeb7f81 100644 --- a/src/main/java/cn/nukkit/item/ItemDoorJungle.java +++ b/src/main/java/cn/nukkit/item/ItemDoorJungle.java @@ -1,9 +1,9 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; public class ItemDoorJungle extends Item { + public ItemDoorJungle() { this(0, 1); } @@ -14,7 +14,6 @@ public ItemDoorJungle(Integer meta) { public ItemDoorJungle(Integer meta, int count) { super(JUNGLE_DOOR, 0, count, "Jungle Door"); - this.block = Block.get(BlockID.JUNGLE_DOOR_BLOCK); + this.block = Block.get(JUNGLE_DOOR_BLOCK); } - } diff --git a/src/main/java/cn/nukkit/item/ItemDoorSpruce.java b/src/main/java/cn/nukkit/item/ItemDoorSpruce.java index 74b4c46c259..541ed4aed10 100644 --- a/src/main/java/cn/nukkit/item/ItemDoorSpruce.java +++ b/src/main/java/cn/nukkit/item/ItemDoorSpruce.java @@ -1,9 +1,9 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; public class ItemDoorSpruce extends Item { + public ItemDoorSpruce() { this(0, 1); } @@ -14,7 +14,6 @@ public ItemDoorSpruce(Integer meta) { public ItemDoorSpruce(Integer meta, int count) { super(SPRUCE_DOOR, 0, count, "Spruce Door"); - this.block = Block.get(BlockID.SPRUCE_DOOR_BLOCK); + this.block = Block.get(SPRUCE_DOOR_BLOCK); } - } diff --git a/src/main/java/cn/nukkit/item/ItemDoorWarped.java b/src/main/java/cn/nukkit/item/ItemDoorWarped.java new file mode 100644 index 00000000000..6d0e3d7bfa6 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemDoorWarped.java @@ -0,0 +1,19 @@ +package cn.nukkit.item; + +import cn.nukkit.block.Block; + +public class ItemDoorWarped extends Item { + + public ItemDoorWarped() { + this(0, 1); + } + + public ItemDoorWarped(Integer meta) { + this(meta, 1); + } + + public ItemDoorWarped(Integer meta, int count) { + super(WARPED_DOOR, 0, count, "Warped Door"); + this.block = Block.get(WARPED_DOOR_BLOCK); + } +} diff --git a/src/main/java/cn/nukkit/item/ItemDoorWood.java b/src/main/java/cn/nukkit/item/ItemDoorWood.java index e1818c39a25..0ff0bd09f7c 100644 --- a/src/main/java/cn/nukkit/item/ItemDoorWood.java +++ b/src/main/java/cn/nukkit/item/ItemDoorWood.java @@ -1,10 +1,9 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemDoorWood extends Item { @@ -19,7 +18,6 @@ public ItemDoorWood(Integer meta) { public ItemDoorWood(Integer meta, int count) { super(WOODEN_DOOR, 0, count, "Oak Door"); - this.block = Block.get(BlockID.WOODEN_DOOR_BLOCK); + this.block = Block.get(WOODEN_DOOR_BLOCK); } - } diff --git a/src/main/java/cn/nukkit/item/ItemDriedKelp.java b/src/main/java/cn/nukkit/item/ItemDriedKelp.java index d31f7cc76d6..b176ebf2071 100644 --- a/src/main/java/cn/nukkit/item/ItemDriedKelp.java +++ b/src/main/java/cn/nukkit/item/ItemDriedKelp.java @@ -1,8 +1,5 @@ package cn.nukkit.item; -/** - * Created by PetteriM1 - */ public class ItemDriedKelp extends ItemEdible { public ItemDriedKelp() { @@ -16,4 +13,9 @@ public ItemDriedKelp(Integer meta) { public ItemDriedKelp(Integer meta, int count) { super(DRIED_KELP, 0, count, "Dried Kelp"); } + + @Override + public int getUseTicks() { + return 15; + } } diff --git a/src/main/java/cn/nukkit/item/ItemDye.java b/src/main/java/cn/nukkit/item/ItemDye.java index 1fe86b73df7..55eb1a18dab 100644 --- a/src/main/java/cn/nukkit/item/ItemDye.java +++ b/src/main/java/cn/nukkit/item/ItemDye.java @@ -6,7 +6,7 @@ import cn.nukkit.utils.DyeColor; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemDye extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemEchoShard.java b/src/main/java/cn/nukkit/item/ItemEchoShard.java new file mode 100644 index 00000000000..4168541258a --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemEchoShard.java @@ -0,0 +1,16 @@ +package cn.nukkit.item; + +public class ItemEchoShard extends Item { + + public ItemEchoShard() { + this(0, 1); + } + + public ItemEchoShard(Integer meta) { + this(meta, 1); + } + + public ItemEchoShard(Integer meta, int count) { + super(ECHO_SHARD, meta, count, "Echo Shard"); + } +} diff --git a/src/main/java/cn/nukkit/item/ItemEdible.java b/src/main/java/cn/nukkit/item/ItemEdible.java index c85f579e4b7..ea6690449c5 100644 --- a/src/main/java/cn/nukkit/item/ItemEdible.java +++ b/src/main/java/cn/nukkit/item/ItemEdible.java @@ -4,12 +4,14 @@ import cn.nukkit.event.player.PlayerItemConsumeEvent; import cn.nukkit.item.food.Food; import cn.nukkit.math.Vector3; +import cn.nukkit.network.protocol.LevelSoundEventPacket; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class ItemEdible extends Item { + public ItemEdible(int id, Integer meta, int count, String name) { super(id, meta, count, name); } @@ -28,28 +30,51 @@ public ItemEdible(int id, Integer meta, int count) { @Override public boolean onClickAir(Player player, Vector3 directionVector) { - if (player.getFoodData().getLevel() < player.getFoodData().getMaxLevel() || player.isCreative() || player.getServer().getDifficulty() == 0) { - return true; - } - player.getFoodData().sendFoodLevel(); - return false; + return this.canAlwaysEat() || player.canEat(true); + } + + /** + * How many ticks player must eat the food before it can be consumed + */ + public int getUseTicks() { + return 30; } @Override public boolean onUse(Player player, int ticksUsed) { + if (ticksUsed < this.getUseTicks()) { + player.getServer().getLogger().debug(player.getName() + ": food ticksUsed=" + ticksUsed); + return false; + } PlayerItemConsumeEvent consumeEvent = new PlayerItemConsumeEvent(player, this); player.getServer().getPluginManager().callEvent(consumeEvent); if (consumeEvent.isCancelled()) { - player.getInventory().sendContents(player); - return false; + return false; // Inventory#sendContents is called in Player } Food food = Food.getByRelative(this); - if ((player.isAdventure() || player.isSurvival()) && food != null && food.eatenBy(player)) { - --this.count; - player.getInventory().setItemInHand(this); + if (food != null && food.eatenBy(player)) { + player.getLevel().addLevelSoundEvent(player, LevelSoundEventPacket.SOUND_BURP); + if (!player.isCreative() && !player.isSpectator()) { + --this.count; + player.getInventory().setItemInHand(this); + } } return true; } + + /** + * Whether food is a drink (mainly used for custom food item sounds) + */ + public boolean isDrink() { + return false; + } + + /** + * Whether food can be eaten even if food bar is full + */ + public boolean canAlwaysEat() { + return false; + } } diff --git a/src/main/java/cn/nukkit/item/ItemEgg.java b/src/main/java/cn/nukkit/item/ItemEgg.java index 419dd087c7f..52c180674f2 100644 --- a/src/main/java/cn/nukkit/item/ItemEgg.java +++ b/src/main/java/cn/nukkit/item/ItemEgg.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemEgg extends ProjectileItem { @@ -27,7 +27,9 @@ public String getProjectileEntityType() { public float getThrowForce() { return 1.5f; } - + @Override - public int getMaxStackSize() { return 16; } + public int getMaxStackSize() { + return 16; + } } diff --git a/src/main/java/cn/nukkit/item/ItemElytra.java b/src/main/java/cn/nukkit/item/ItemElytra.java index 21d525515da..1c10b3b5468 100644 --- a/src/main/java/cn/nukkit/item/ItemElytra.java +++ b/src/main/java/cn/nukkit/item/ItemElytra.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemElytra extends ItemArmor { @@ -32,5 +32,4 @@ public boolean isArmor() { public boolean isChestplate() { return true; } - } diff --git a/src/main/java/cn/nukkit/item/ItemEmerald.java b/src/main/java/cn/nukkit/item/ItemEmerald.java index 6e82a21c3a0..204ffcc767d 100644 --- a/src/main/java/cn/nukkit/item/ItemEmerald.java +++ b/src/main/java/cn/nukkit/item/ItemEmerald.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemEmerald extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemEmptyMap.java b/src/main/java/cn/nukkit/item/ItemEmptyMap.java index 41622b635c3..5fd8314bb02 100644 --- a/src/main/java/cn/nukkit/item/ItemEmptyMap.java +++ b/src/main/java/cn/nukkit/item/ItemEmptyMap.java @@ -1,5 +1,11 @@ package cn.nukkit.item; +import cn.nukkit.Player; +import cn.nukkit.block.Block; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; +import cn.nukkit.math.Vector3; + public class ItemEmptyMap extends Item { public ItemEmptyMap() { @@ -13,4 +19,27 @@ public ItemEmptyMap(Integer meta) { public ItemEmptyMap(Integer meta, int count) { super(EMPTY_MAP, meta, count, "Empty Map"); } + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public boolean onActivate(Level level, Player player, Block block, Block target, BlockFace face, double fx, double fy, double fz) { + if (!player.isCreative()) { + this.count--; + } + player.getInventory().addItem(Item.get(Item.MAP)); + return true; + } + + @Override + public boolean onClickAir(Player player, Vector3 directionVector) { + if (!player.isCreative()) { + this.count--; + } + player.getInventory().addItem(Item.get(Item.MAP)); + return true; + } } diff --git a/src/main/java/cn/nukkit/item/ItemEndCrystal.java b/src/main/java/cn/nukkit/item/ItemEndCrystal.java index 97a6984ab7e..382fe6a30b4 100644 --- a/src/main/java/cn/nukkit/item/ItemEndCrystal.java +++ b/src/main/java/cn/nukkit/item/ItemEndCrystal.java @@ -15,7 +15,7 @@ import cn.nukkit.nbt.tag.FloatTag; import cn.nukkit.nbt.tag.ListTag; -import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; public class ItemEndCrystal extends Item { @@ -40,24 +40,33 @@ public boolean canBeActivated() { public boolean onActivate(Level level, Player player, Block block, Block target, BlockFace face, double fx, double fy, double fz) { if (!(target instanceof BlockBedrock) && !(target instanceof BlockObsidian)) return false; FullChunk chunk = level.getChunk((int) block.getX() >> 4, (int) block.getZ() >> 4); - Entity[] entities = level.getNearbyEntities(new SimpleAxisAlignedBB(target.x, target.y, target.z, target.x + 1, target.y + 2, target.z + 1)); - Block up = target.up(); + if (chunk == null) { + return false; + } + + int tx = (int) target.x; + int ty = (int) target.y; + int tz = (int) target.z; + if (level.getBlockIdAt(chunk, tx, ty + 1, tz) != BlockID.AIR || level.getBlockIdAt(chunk, tx, ty + 2, tz) != BlockID.AIR) { + return false; + } - if (chunk == null || up.getId() != BlockID.AIR || up.up().getId() != BlockID.AIR || entities.length != 0) { + Entity[] entities = level.getCollidingEntities(new SimpleAxisAlignedBB(target.x, target.y, target.z, target.x + 1, target.y + 2, target.z + 1)); + if (entities.length != 0) { return false; } CompoundTag nbt = new CompoundTag() .putList(new ListTag("Pos") .add(new DoubleTag("", target.x + 0.5)) - .add(new DoubleTag("", up.y)) + .add(new DoubleTag("", ty + 1)) .add(new DoubleTag("", target.z + 0.5))) .putList(new ListTag("Motion") .add(new DoubleTag("", 0)) .add(new DoubleTag("", 0)) .add(new DoubleTag("", 0))) .putList(new ListTag("Rotation") - .add(new FloatTag("", new Random().nextFloat() * 360)) + .add(new FloatTag("", ThreadLocalRandom.current().nextFloat() * 360)) .add(new FloatTag("", 0))); if (this.hasCustomName()) { @@ -67,11 +76,10 @@ public boolean onActivate(Level level, Player player, Block block, Block target, Entity entity = Entity.createEntity("EndCrystal", chunk, nbt); if (entity != null) { - if (player.isAdventure() || player.isSurvival()) { - Item item = player.getInventory().getItemInHand(); - item.setCount(item.getCount() - 1); - player.getInventory().setItemInHand(item); + if (!player.isCreative()) { + this.count--; } + entity.spawnToAll(); return true; } diff --git a/src/main/java/cn/nukkit/item/ItemEnderEye.java b/src/main/java/cn/nukkit/item/ItemEnderEye.java index 0c1e55cc9d7..91262e43907 100644 --- a/src/main/java/cn/nukkit/item/ItemEnderEye.java +++ b/src/main/java/cn/nukkit/item/ItemEnderEye.java @@ -1,6 +1,6 @@ package cn.nukkit.item; -public class ItemEnderEye extends Item { +public class ItemEnderEye extends ProjectileItem { public ItemEnderEye() { this(0, 1); @@ -13,4 +13,14 @@ public ItemEnderEye(Integer meta) { public ItemEnderEye(Integer meta, int count) { super(ENDER_EYE, meta, count, "Ender Eye"); } + + @Override + public String getProjectileEntityType() { + return "EnderEye"; + } + + @Override + public float getThrowForce() { + return 1.5f; + } } diff --git a/src/main/java/cn/nukkit/item/ItemExpBottle.java b/src/main/java/cn/nukkit/item/ItemExpBottle.java index 247e2824319..6957e9162d8 100644 --- a/src/main/java/cn/nukkit/item/ItemExpBottle.java +++ b/src/main/java/cn/nukkit/item/ItemExpBottle.java @@ -27,5 +27,4 @@ public String getProjectileEntityType() { public float getThrowForce() { return 1f; } - } diff --git a/src/main/java/cn/nukkit/item/ItemFeather.java b/src/main/java/cn/nukkit/item/ItemFeather.java index b6e50659c79..d63b4187d1e 100644 --- a/src/main/java/cn/nukkit/item/ItemFeather.java +++ b/src/main/java/cn/nukkit/item/ItemFeather.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemFeather extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemFireCharge.java b/src/main/java/cn/nukkit/item/ItemFireCharge.java index 8182b666398..4ef3be088d2 100644 --- a/src/main/java/cn/nukkit/item/ItemFireCharge.java +++ b/src/main/java/cn/nukkit/item/ItemFireCharge.java @@ -1,17 +1,13 @@ package cn.nukkit.item; -import cn.nukkit.block.*; -import cn.nukkit.math.BlockFace; -import cn.nukkit.level.Level; import cn.nukkit.Player; - -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.block.*; import cn.nukkit.event.block.BlockIgniteEvent; -import cn.nukkit.network.protocol.LevelEventPacket; +import cn.nukkit.level.Level; +import cn.nukkit.level.Sound; +import cn.nukkit.math.BlockFace; +import cn.nukkit.utils.Utils; -/** - * Created by PetteriM1 - */ public class ItemFireCharge extends Item { public ItemFireCharge() { @@ -37,32 +33,33 @@ public boolean onActivate(Level level, Player player, Block block, Block target, return false; } - if (block.getId() == AIR && (target instanceof BlockSolid || target instanceof BlockSolidMeta)) { + if (block.getId() == AIR && (target instanceof BlockSolid || target instanceof BlockSolidMeta || target instanceof BlockLeaves)) { if (target.getId() == OBSIDIAN) { if (level.createPortal(target)) { + level.addSound(target, Sound.MOB_GHAST_FIREBALL); return true; } } - BlockFire fire = (BlockFire) Block.get(BlockID.FIRE); + int did; + BlockFire fire = (BlockFire) Block.get(((did = block.down().getId()) == SOUL_SAND || did == SOUL_SOIL) ? BlockID.SOUL_FIRE : BlockID.FIRE); fire.x = block.x; fire.y = block.y; fire.z = block.z; fire.level = level; if (fire.isBlockTopFacingSurfaceSolid(fire.down()) || fire.canNeighborBurn()) { - BlockIgniteEvent e = new BlockIgniteEvent(block, null, player, BlockIgniteEvent.BlockIgniteCause.FLINT_AND_STEEL); + BlockIgniteEvent e = new BlockIgniteEvent(block, null, player, BlockIgniteEvent.BlockIgniteCause.FIREBALL); block.getLevel().getServer().getPluginManager().callEvent(e); if (!e.isCancelled()) { level.setBlock(fire, fire, true); - level.addLevelEvent(block, LevelEventPacket.EVENT_SOUND_GHAST_SHOOT, 78642); - level.scheduleUpdate(fire, fire.tickRate() + ThreadLocalRandom.current().nextInt(10)); - } - if (player.isSurvival()) { - Item item = player.getInventory().getItemInHand(); - item.setCount(item.getCount() - 1); - player.getInventory().setItemInHand(item); + level.scheduleUpdate(fire, (fire.tickRate() + Utils.random.nextInt(10))); + level.addSound(block, Sound.MOB_GHAST_FIREBALL); + + if (!player.isCreative()) { + this.count--; + } } return true; } diff --git a/src/main/java/cn/nukkit/item/ItemFirework.java b/src/main/java/cn/nukkit/item/ItemFirework.java index 2bc7e4ca8f5..b65259c2e36 100644 --- a/src/main/java/cn/nukkit/item/ItemFirework.java +++ b/src/main/java/cn/nukkit/item/ItemFirework.java @@ -8,10 +8,7 @@ import cn.nukkit.math.BlockFace; import cn.nukkit.math.Vector3; import cn.nukkit.nbt.NBTIO; -import cn.nukkit.nbt.tag.CompoundTag; -import cn.nukkit.nbt.tag.DoubleTag; -import cn.nukkit.nbt.tag.FloatTag; -import cn.nukkit.nbt.tag.ListTag; +import cn.nukkit.nbt.tag.*; import cn.nukkit.utils.DyeColor; import java.util.ArrayList; @@ -70,7 +67,7 @@ public boolean onActivate(Level level, Player player, Block block, Block target, this.spawnFirework(level, block); if (!player.isCreative()) { - player.getInventory().decreaseCount(player.getInventory().getHeldItemIndex()); + this.count--; } return true; @@ -81,18 +78,14 @@ public boolean onActivate(Level level, Player player, Block block, Block target, @Override public boolean onClickAir(Player player, Vector3 directionVector) { - if (player.getInventory().getChestplate() instanceof ItemElytra && player.isGliding()) { + if (player.isGliding() && player.getInventory().getChestplateFast() instanceof ItemElytra) { this.spawnFirework(player.getLevel(), player); - player.setMotion(new Vector3( - -Math.sin(Math.toRadians(player.yaw)) * Math.cos(Math.toRadians(player.pitch)) * 2, - -Math.sin(Math.toRadians(player.pitch)) * 2, - Math.cos(Math.toRadians(player.yaw)) * Math.cos(Math.toRadians(player.pitch)) * 2)); - if (!player.isCreative()) { this.count--; } + player.onFireworkBoost(this.getFlight()); return true; } @@ -146,16 +139,31 @@ private void spawnFirework(Level level, Vector3 pos) { .add(new FloatTag("", 0))) .putCompound("FireworkItem", NBTIO.putItemHelper(this)); - EntityFirework entity = (EntityFirework) Entity.createEntity("Firework", level.getChunk(pos.getFloorX() >> 4, pos.getFloorZ() >> 4), nbt); - if (entity != null) { - entity.spawnToAll(); + Entity.createEntity(EntityFirework.NETWORK_ID, level.getChunk(pos.getChunkX(), pos.getChunkZ()), nbt).spawnToAll(); + } + + public int getFlight() { + int level = 0; + Tag nbt = this.getNamedTag(); + if (nbt != null) { + nbt = ((CompoundTag) nbt).get("Fireworks"); + if (nbt instanceof CompoundTag) { + level = ((CompoundTag) nbt).getByte("Flight"); + } } + return level; + } + + public void setFlight(int flight) { + CompoundTag tag = this.getNamedTag(); + tag.putCompound("Fireworks", tag.getCompound("Fireworks").putByte("Flight", flight)); + this.setNamedTag(tag); } public static class FireworkExplosion { - private List colors = new ArrayList<>(); - private List fades = new ArrayList<>(); + private final List colors = new ArrayList<>(); + private final List fades = new ArrayList<>(); private boolean flicker = false; private boolean trail = false; private ExplosionType type = ExplosionType.CREEPER_SHAPED; @@ -213,4 +221,9 @@ public enum ExplosionType { BURST } } -} + + @Override + public boolean allowOffhand() { + return true; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/item/ItemFish.java b/src/main/java/cn/nukkit/item/ItemFish.java index ad874c5d565..f9c7c380a94 100644 --- a/src/main/java/cn/nukkit/item/ItemFish.java +++ b/src/main/java/cn/nukkit/item/ItemFish.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemFish extends ItemEdible { @@ -21,5 +21,4 @@ public ItemFish(Integer meta, int count) { protected ItemFish(int id, Integer meta, int count, String name) { super(id, meta, count, name); } - } diff --git a/src/main/java/cn/nukkit/item/ItemFishCooked.java b/src/main/java/cn/nukkit/item/ItemFishCooked.java index aef3dd90548..fe4a29c3f50 100644 --- a/src/main/java/cn/nukkit/item/ItemFishCooked.java +++ b/src/main/java/cn/nukkit/item/ItemFishCooked.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemFishCooked extends ItemFish { @@ -17,5 +17,4 @@ public ItemFishCooked(Integer meta) { public ItemFishCooked(Integer meta, int count) { super(COOKED_FISH, meta, count, "Cooked Fish"); } - } diff --git a/src/main/java/cn/nukkit/item/ItemFishingRod.java b/src/main/java/cn/nukkit/item/ItemFishingRod.java index 431a1e11289..c6fea5d8dd9 100644 --- a/src/main/java/cn/nukkit/item/ItemFishingRod.java +++ b/src/main/java/cn/nukkit/item/ItemFishingRod.java @@ -3,10 +3,6 @@ import cn.nukkit.Player; import cn.nukkit.math.Vector3; -/** - * Created by Snake1999 on 2016/1/14. - * Package cn.nukkit.item in project nukkit. - */ public class ItemFishingRod extends ItemTool { public ItemFishingRod() { @@ -29,11 +25,17 @@ public int getEnchantAbility() { @Override public boolean onClickAir(Player player, Vector3 directionVector) { if (player.fishing != null) { + if (player.fishing.getTarget() > 0) { + this.meta = this.meta + 2; + } else { + this.meta++; + } + player.stopFishing(true); - } else { - player.startFishing(this); - this.meta++; + } else { + player.startFishing(this); } + return true; } @@ -51,4 +53,9 @@ public boolean noDamageOnAttack() { public boolean noDamageOnBreak() { return true; } + + @Override + public boolean onUse(Player player, int ticksUsed) { + return true; + } } diff --git a/src/main/java/cn/nukkit/item/ItemFlint.java b/src/main/java/cn/nukkit/item/ItemFlint.java index 9bd87411660..c78a7444dd3 100644 --- a/src/main/java/cn/nukkit/item/ItemFlint.java +++ b/src/main/java/cn/nukkit/item/ItemFlint.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemFlint extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemFlintSteel.java b/src/main/java/cn/nukkit/item/ItemFlintSteel.java index 0a55252fb28..e3170f6a6ce 100644 --- a/src/main/java/cn/nukkit/item/ItemFlintSteel.java +++ b/src/main/java/cn/nukkit/item/ItemFlintSteel.java @@ -4,17 +4,18 @@ import cn.nukkit.block.*; import cn.nukkit.event.block.BlockIgniteEvent; import cn.nukkit.level.Level; +import cn.nukkit.level.Sound; +import cn.nukkit.level.particle.ItemBreakParticle; import cn.nukkit.math.BlockFace; import cn.nukkit.network.protocol.LevelSoundEventPacket; - -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemFlintSteel extends ItemTool { - + public ItemFlintSteel() { this(0, 1); } @@ -38,14 +39,17 @@ public boolean onActivate(Level level, Player player, Block block, Block target, return false; } - if (block.getId() == AIR && (target instanceof BlockSolid || target instanceof BlockSolidMeta)) { + // 1.18 vanilla allows flint & steel to be used even if fire exists + if ((block.getId() == AIR || block.getId() == FIRE || block.getId() == SOUL_FIRE) && (target instanceof BlockSolid || target instanceof BlockSolidMeta || target instanceof BlockLeaves)) { if (target.getId() == OBSIDIAN) { if (level.createPortal(target)) { + level.addLevelSoundEvent(target, LevelSoundEventPacket.SOUND_IGNITE); return true; } } - BlockFire fire = (BlockFire) Block.get(BlockID.FIRE); + int did; + BlockFire fire = (BlockFire) Block.get(((did = block.down().getId()) == SOUL_SAND || did == SOUL_SOIL) ? BlockID.SOUL_FIRE : BlockID.FIRE); fire.x = block.x; fire.y = block.y; fire.z = block.z; @@ -57,18 +61,23 @@ public boolean onActivate(Level level, Player player, Block block, Block target, if (!e.isCancelled()) { level.setBlock(fire, fire, true); + level.scheduleUpdate(fire, fire.tickRate() + Utils.random.nextInt(10)); level.addLevelSoundEvent(block, LevelSoundEventPacket.SOUND_IGNITE); - level.scheduleUpdate(fire, fire.tickRate() + ThreadLocalRandom.current().nextInt(10)); - if ((player.gamemode & 0x01) == 0 && this.useOn(block)) { - if (this.getDamage() >= this.getMaxDurability()) { + if (!player.isCreative()) { + this.useOn(block); + if (this.getDamage() >= DURABILITY_FLINT_STEEL) { this.count = 0; + + player.level.addSound(player, Sound.RANDOM_BREAK); + player.level.addParticle(new ItemBreakParticle(player, this)); } + player.getInventory().setItemInHand(this); } } - return true; } + return true; } return false; } diff --git a/src/main/java/cn/nukkit/item/ItemFlowerPot.java b/src/main/java/cn/nukkit/item/ItemFlowerPot.java index 99c9f7ea4e8..7e84f8186c3 100644 --- a/src/main/java/cn/nukkit/item/ItemFlowerPot.java +++ b/src/main/java/cn/nukkit/item/ItemFlowerPot.java @@ -20,5 +20,4 @@ public ItemFlowerPot(Integer meta, int count) { super(FLOWER_POT, meta, count, "Flower Pot"); this.block = Block.get(Block.FLOWER_POT_BLOCK); } - } diff --git a/src/main/java/cn/nukkit/item/ItemGhastTear.java b/src/main/java/cn/nukkit/item/ItemGhastTear.java index 4a12bf08316..b754438ca60 100644 --- a/src/main/java/cn/nukkit/item/ItemGhastTear.java +++ b/src/main/java/cn/nukkit/item/ItemGhastTear.java @@ -1,8 +1,5 @@ package cn.nukkit.item; -/** - * Created by Leonidius20 on 18.08.18. - */ public class ItemGhastTear extends Item { public ItemGhastTear() { @@ -14,7 +11,6 @@ public ItemGhastTear(Integer meta) { } public ItemGhastTear(Integer meta, int count) { - super(GHAST_TEAR, meta, count, "Ghast Tear"); + super(GHAST_TEAR, 0, count, "Ghast Tear"); } - } diff --git a/src/main/java/cn/nukkit/item/ItemGlassBottle.java b/src/main/java/cn/nukkit/item/ItemGlassBottle.java index d73db93b83d..4ae5c973407 100644 --- a/src/main/java/cn/nukkit/item/ItemGlassBottle.java +++ b/src/main/java/cn/nukkit/item/ItemGlassBottle.java @@ -27,8 +27,8 @@ public boolean canBeActivated() { @Override public boolean onActivate(Level level, Player player, Block block, Block target, BlockFace face, double fx, double fy, double fz) { - if (target.getId() == WATER || target.getId() == STILL_WATER) { - Item potion = new ItemPotion(); + if (Block.isWater(target.getId())) { + Item potion = Item.get(Item.POTION); if (this.count == 1) { player.getInventory().setItemInHand(potion); diff --git a/src/main/java/cn/nukkit/item/ItemGlowBerries.java b/src/main/java/cn/nukkit/item/ItemGlowBerries.java new file mode 100644 index 00000000000..3c1a0bc2902 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemGlowBerries.java @@ -0,0 +1,19 @@ +package cn.nukkit.item; + +import cn.nukkit.block.Block; + +public class ItemGlowBerries extends ItemEdible { + + public ItemGlowBerries() { + this(0, 1); + } + + public ItemGlowBerries(Integer meta) { + this(meta, 1); + } + + public ItemGlowBerries(Integer meta, int count) { + super(GLOW_BERRIES, meta, count, "Glow Berries"); + this.block = Block.get(CAVE_VINES); + } +} diff --git a/src/main/java/cn/nukkit/item/ItemGlowstoneDust.java b/src/main/java/cn/nukkit/item/ItemGlowstoneDust.java index 9eee2a76096..ae23ef5023c 100644 --- a/src/main/java/cn/nukkit/item/ItemGlowstoneDust.java +++ b/src/main/java/cn/nukkit/item/ItemGlowstoneDust.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemGlowstoneDust extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemGoatHorn.java b/src/main/java/cn/nukkit/item/ItemGoatHorn.java new file mode 100644 index 00000000000..f1effaf1ab3 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemGoatHorn.java @@ -0,0 +1,63 @@ +package cn.nukkit.item; + +import cn.nukkit.Player; +import cn.nukkit.Server; +import cn.nukkit.level.Sound; +import cn.nukkit.math.Vector3; + +import java.util.concurrent.atomic.AtomicBoolean; + +public class ItemGoatHorn extends Item { + + private final AtomicBoolean cooldown = new AtomicBoolean(false); + + public ItemGoatHorn() { + this(0, 1); + } + + public ItemGoatHorn(Integer meta) { + this(meta, 1); + } + + public ItemGoatHorn(Integer meta, int count) { + super(GOAT_HORN, meta, count, "Goat Horn"); + } + + @Override + public int getMaxStackSize() { + return 1; + } + + @Override + public boolean onClickAir(Player player, Vector3 directionVector) { + if (!cooldown.getAndSet(true)) { + this.playSound(player); + Server.getInstance().getScheduler().scheduleDelayedTask(null, () -> cooldown.set(false), 140); + player.startItemCooldown(140, "goat_horn"); + return true; + } else { + return false; + } + } + + public void playSound(Player player) { + switch (this.getDamage()) { + case 0: player.getLevel().addSound(player, Sound.HORN_CALL_0); + break; + case 1: player.getLevel().addSound(player, Sound.HORN_CALL_1); + break; + case 2: player.getLevel().addSound(player, Sound.HORN_CALL_2); + break; + case 3: player.getLevel().addSound(player, Sound.HORN_CALL_3); + break; + case 4: player.getLevel().addSound(player, Sound.HORN_CALL_4); + break; + case 5: player.getLevel().addSound(player, Sound.HORN_CALL_5); + break; + case 6: player.getLevel().addSound(player, Sound.HORN_CALL_6); + break; + case 7: player.getLevel().addSound(player, Sound.HORN_CALL_7); + break; + } + } +} diff --git a/src/main/java/cn/nukkit/item/ItemGoldRaw.java b/src/main/java/cn/nukkit/item/ItemGoldRaw.java new file mode 100644 index 00000000000..b5d86ecf927 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemGoldRaw.java @@ -0,0 +1,16 @@ +package cn.nukkit.item; + +public class ItemGoldRaw extends Item { + + public ItemGoldRaw() { + this(0, 1); + } + + public ItemGoldRaw(Integer meta) { + this(meta, 1); + } + + public ItemGoldRaw(Integer meta, int count) { + super(RAW_GOLD, meta, count, "Raw Gold"); + } +} diff --git a/src/main/java/cn/nukkit/item/ItemGunpowder.java b/src/main/java/cn/nukkit/item/ItemGunpowder.java index b02786db0e9..a2225cfc3e2 100644 --- a/src/main/java/cn/nukkit/item/ItemGunpowder.java +++ b/src/main/java/cn/nukkit/item/ItemGunpowder.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemGunpowder extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemHelmetChain.java b/src/main/java/cn/nukkit/item/ItemHelmetChain.java index 1cc3d1dec74..c1b5abdcb59 100644 --- a/src/main/java/cn/nukkit/item/ItemHelmetChain.java +++ b/src/main/java/cn/nukkit/item/ItemHelmetChain.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemHelmetChain extends ItemArmor { @@ -15,7 +15,7 @@ public ItemHelmetChain(Integer meta) { } public ItemHelmetChain(Integer meta, int count) { - super(CHAIN_HELMET, meta, count, "Chainmail Helmet"); + super(CHAIN_HELMET, meta, count, "Chain Helmet"); } @Override diff --git a/src/main/java/cn/nukkit/item/ItemHelmetDiamond.java b/src/main/java/cn/nukkit/item/ItemHelmetDiamond.java index a9e2fe52d06..ba759c055ea 100644 --- a/src/main/java/cn/nukkit/item/ItemHelmetDiamond.java +++ b/src/main/java/cn/nukkit/item/ItemHelmetDiamond.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemHelmetDiamond extends ItemArmor { diff --git a/src/main/java/cn/nukkit/item/ItemHelmetGold.java b/src/main/java/cn/nukkit/item/ItemHelmetGold.java index d68866c19fc..b08e69e4d19 100644 --- a/src/main/java/cn/nukkit/item/ItemHelmetGold.java +++ b/src/main/java/cn/nukkit/item/ItemHelmetGold.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemHelmetGold extends ItemArmor { @@ -15,7 +15,7 @@ public ItemHelmetGold(Integer meta) { } public ItemHelmetGold(Integer meta, int count) { - super(GOLD_HELMET, meta, count, "Gold Helmet"); + super(GOLD_HELMET, meta, count, "Golden Helmet"); } @Override diff --git a/src/main/java/cn/nukkit/item/ItemHelmetIron.java b/src/main/java/cn/nukkit/item/ItemHelmetIron.java index d31f0b3eac0..aad54957f6a 100644 --- a/src/main/java/cn/nukkit/item/ItemHelmetIron.java +++ b/src/main/java/cn/nukkit/item/ItemHelmetIron.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemHelmetIron extends ItemArmor { diff --git a/src/main/java/cn/nukkit/item/ItemHelmetLeather.java b/src/main/java/cn/nukkit/item/ItemHelmetLeather.java index fb4403479da..e3ed24f71cb 100644 --- a/src/main/java/cn/nukkit/item/ItemHelmetLeather.java +++ b/src/main/java/cn/nukkit/item/ItemHelmetLeather.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemHelmetLeather extends ItemColorArmor { diff --git a/src/main/java/cn/nukkit/item/ItemHelmetNetherite.java b/src/main/java/cn/nukkit/item/ItemHelmetNetherite.java index 4f6b45146fb..29340e46f8e 100644 --- a/src/main/java/cn/nukkit/item/ItemHelmetNetherite.java +++ b/src/main/java/cn/nukkit/item/ItemHelmetNetherite.java @@ -36,6 +36,6 @@ public int getArmorPoints() { @Override public int getToughness() { - return 2; + return 3; } } diff --git a/src/main/java/cn/nukkit/item/ItemHoeDiamond.java b/src/main/java/cn/nukkit/item/ItemHoeDiamond.java index 02a97921238..0f117442ef8 100644 --- a/src/main/java/cn/nukkit/item/ItemHoeDiamond.java +++ b/src/main/java/cn/nukkit/item/ItemHoeDiamond.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemHoeDiamond extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemHoeGold.java b/src/main/java/cn/nukkit/item/ItemHoeGold.java index 8d08a946737..ade2b243e4e 100644 --- a/src/main/java/cn/nukkit/item/ItemHoeGold.java +++ b/src/main/java/cn/nukkit/item/ItemHoeGold.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemHoeGold extends ItemTool { @@ -15,7 +15,7 @@ public ItemHoeGold(Integer meta) { } public ItemHoeGold(Integer meta, int count) { - super(GOLD_HOE, meta, count, "Gold Hoe"); + super(GOLD_HOE, meta, count, "Golden Hoe"); } @Override diff --git a/src/main/java/cn/nukkit/item/ItemHoeIron.java b/src/main/java/cn/nukkit/item/ItemHoeIron.java index e0beeb7d1b2..0411990f0a0 100644 --- a/src/main/java/cn/nukkit/item/ItemHoeIron.java +++ b/src/main/java/cn/nukkit/item/ItemHoeIron.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemHoeIron extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemHoeNetherite.java b/src/main/java/cn/nukkit/item/ItemHoeNetherite.java index a808c6c80b5..69de33522e2 100644 --- a/src/main/java/cn/nukkit/item/ItemHoeNetherite.java +++ b/src/main/java/cn/nukkit/item/ItemHoeNetherite.java @@ -19,11 +19,6 @@ public boolean isHoe() { return true; } - @Override - public int getAttackDamage() { - return 6; - } - @Override public int getTier() { return ItemTool.TIER_NETHERITE; diff --git a/src/main/java/cn/nukkit/item/ItemHoeStone.java b/src/main/java/cn/nukkit/item/ItemHoeStone.java index 747d9fc030c..ea195ed0dfb 100644 --- a/src/main/java/cn/nukkit/item/ItemHoeStone.java +++ b/src/main/java/cn/nukkit/item/ItemHoeStone.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemHoeStone extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemHoeWood.java b/src/main/java/cn/nukkit/item/ItemHoeWood.java index edeaa4a1c18..98c30e01a32 100644 --- a/src/main/java/cn/nukkit/item/ItemHoeWood.java +++ b/src/main/java/cn/nukkit/item/ItemHoeWood.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemHoeWood extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemHoneyBottle.java b/src/main/java/cn/nukkit/item/ItemHoneyBottle.java index d365970b83e..7ff6c2e145e 100644 --- a/src/main/java/cn/nukkit/item/ItemHoneyBottle.java +++ b/src/main/java/cn/nukkit/item/ItemHoneyBottle.java @@ -6,22 +6,21 @@ /** * @author Kaooot - * @version 1.0 */ public class ItemHoneyBottle extends ItemEdible { - + public ItemHoneyBottle() { this(0, 1); } - + public ItemHoneyBottle(Integer meta) { this(meta, 1); } - + public ItemHoneyBottle(Integer meta, int count) { super(HONEY_BOTTLE, meta, count, "Honey Bottle"); } - + @Override public int getMaxStackSize() { return 16; @@ -29,17 +28,19 @@ public int getMaxStackSize() { @Override public boolean onUse(Player player, int ticksUsed) { - super.onUse(player, ticksUsed); - - if (player.hasEffect(Effect.POISON)) { + if (super.onUse(player, ticksUsed)) { player.removeEffect(Effect.POISON, EntityPotionEffectEvent.Cause.FOOD); - } - player.getInventory().setItemInHand(this); - - if (!player.isCreative()) { - player.getInventory().addItem(new Item(ItemID.BOTTLE, 0, 1)); + if (!player.isCreative()) { + this.count--; + player.getInventory().addItem(Item.get(Item.BOTTLE, 0, 1)); + } } return true; } -} \ No newline at end of file + + @Override + public boolean isDrink() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/item/ItemHoneycomb.java b/src/main/java/cn/nukkit/item/ItemHoneycomb.java index 69cc77f3640..9566c7cc891 100644 --- a/src/main/java/cn/nukkit/item/ItemHoneycomb.java +++ b/src/main/java/cn/nukkit/item/ItemHoneycomb.java @@ -2,7 +2,6 @@ /** * @author Kaooot - * @version 1.0 */ public class ItemHoneycomb extends Item { @@ -17,4 +16,4 @@ public ItemHoneycomb(Integer meta) { public ItemHoneycomb(Integer meta, int count) { super(HONEYCOMB, meta, count, "Honeycomb"); } -} \ No newline at end of file +} diff --git a/src/main/java/cn/nukkit/item/ItemHopper.java b/src/main/java/cn/nukkit/item/ItemHopper.java index 74127f79843..95c76cbc787 100644 --- a/src/main/java/cn/nukkit/item/ItemHopper.java +++ b/src/main/java/cn/nukkit/item/ItemHopper.java @@ -1,7 +1,6 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; /** * Created by CreeperFace on 13.5.2017. @@ -18,6 +17,6 @@ public ItemHopper(Integer meta) { public ItemHopper(Integer meta, int count) { super(HOPPER, 0, count, "Hopper"); - this.block = Block.get(BlockID.HOPPER_BLOCK); + this.block = Block.get(HOPPER_BLOCK); } } diff --git a/src/main/java/cn/nukkit/item/ItemHorseArmorDiamond.java b/src/main/java/cn/nukkit/item/ItemHorseArmorDiamond.java index d59da4e4429..adc81255ef9 100644 --- a/src/main/java/cn/nukkit/item/ItemHorseArmorDiamond.java +++ b/src/main/java/cn/nukkit/item/ItemHorseArmorDiamond.java @@ -1,6 +1,7 @@ package cn.nukkit.item; public class ItemHorseArmorDiamond extends Item { + public ItemHorseArmorDiamond() { this(0, 0); } diff --git a/src/main/java/cn/nukkit/item/ItemHorseArmorGold.java b/src/main/java/cn/nukkit/item/ItemHorseArmorGold.java index d88c44db6f1..dfbf503964f 100644 --- a/src/main/java/cn/nukkit/item/ItemHorseArmorGold.java +++ b/src/main/java/cn/nukkit/item/ItemHorseArmorGold.java @@ -1,6 +1,7 @@ package cn.nukkit.item; public class ItemHorseArmorGold extends Item { + public ItemHorseArmorGold() { this(0, 0); } @@ -10,7 +11,7 @@ public ItemHorseArmorGold(Integer meta) { } public ItemHorseArmorGold(Integer meta, int count) { - super(GOLD_HORSE_ARMOR, meta, count, "Gold Horse Armor"); + super(GOLD_HORSE_ARMOR, meta, count, "Golden Horse Armor"); } @Override diff --git a/src/main/java/cn/nukkit/item/ItemHorseArmorIron.java b/src/main/java/cn/nukkit/item/ItemHorseArmorIron.java index dc9cec7da05..90d31071a7f 100644 --- a/src/main/java/cn/nukkit/item/ItemHorseArmorIron.java +++ b/src/main/java/cn/nukkit/item/ItemHorseArmorIron.java @@ -1,6 +1,7 @@ package cn.nukkit.item; public class ItemHorseArmorIron extends Item { + public ItemHorseArmorIron() { this(0, 0); } diff --git a/src/main/java/cn/nukkit/item/ItemHorseArmorLeather.java b/src/main/java/cn/nukkit/item/ItemHorseArmorLeather.java index 47d5a4ee7de..99c0437f3ce 100644 --- a/src/main/java/cn/nukkit/item/ItemHorseArmorLeather.java +++ b/src/main/java/cn/nukkit/item/ItemHorseArmorLeather.java @@ -1,6 +1,7 @@ package cn.nukkit.item; public class ItemHorseArmorLeather extends Item { + public ItemHorseArmorLeather() { this(0, 1); } diff --git a/src/main/java/cn/nukkit/item/ItemID.java b/src/main/java/cn/nukkit/item/ItemID.java index 28a0b52808f..97d5b1c5ff2 100644 --- a/src/main/java/cn/nukkit/item/ItemID.java +++ b/src/main/java/cn/nukkit/item/ItemID.java @@ -1,6 +1,10 @@ package cn.nukkit.item; +/** + * List of item IDs + */ public interface ItemID { + int IRON_SHOVEL = 256; int IRON_PICKAXE = 257; int IRON_AXE = 258; @@ -59,9 +63,13 @@ public interface ItemID { int LEATHER_LEGGINGS = 300; int LEATHER_BOOTS = 301; int CHAIN_HELMET = 302; + int CHAINMAIL_HELMET = 302; int CHAIN_CHESTPLATE = 303; + int CHAINMAIL_CHESTPLATE = 303; int CHAIN_LEGGINGS = 304; + int CHAINMAIL_LEGGINGS = 304; int CHAIN_BOOTS = 305; + int CHAINMAIL_BOOTS = 305; int IRON_HELMET = 306; int IRON_CHESTPLATE = 307; int IRON_LEGGINGS = 308; @@ -86,6 +94,7 @@ public interface ItemID { int SIGN = 323; int WOODEN_DOOR = 324; int BUCKET = 325; + // int MINECART = 328; int SADDLE = 329; int IRON_DOOR = 330; @@ -107,6 +116,7 @@ public interface ItemID { int SLIME_BALL = 341; int CHEST_MINECART = 342; int MINECART_WITH_CHEST = 342; + // int EGG = 344; int COMPASS = 345; int FISHING_ROD = 346; @@ -220,16 +230,26 @@ public interface ItemID { int CHORUS_FRUIT = 432; int POPPED_CHORUS_FRUIT = 433; int BANNER_PATTERN = 434; + // int DRAGON_BREATH = 437; int SPLASH_POTION = 438; + // int LINGERING_POTION = 441; + int SPARKLER = 442; int COMMAND_BLOCK_MINECART = 443; int ELYTRA = 444; int SHULKER_SHELL = 445; int BANNER = 446; + int EYE_DROP = 447; + int BALLOON = 448; + int SUPER_FERTILIZER = 449; int TOTEM = 450; + int BLEACH = 451; int IRON_NUGGET = 452; + int ICE_BOMB = 453; + // int TRIDENT = 455; + // int BEETROOT = 457; int BEETROOT_SEEDS = 458; int BEETROOT_SEED = 458; @@ -250,7 +270,15 @@ public interface ItemID { int TURTLE_HELMET = 469; int PHANTOM_MEMBRANE = 470; int CROSSBOW = 471; + int SPRUCE_SIGN = 472; + int BIRCH_SIGN = 473; + int JUNGLE_SIGN = 474; + int ACACIA_SIGN = 475; + int DARKOAK_SIGN = 476; int SWEET_BERRIES = 477; + // + int CAMERA = 498; + int COMPOUND = 499; int RECORD_13 = 500; int RECORD_CAT = 501; int RECORD_BLOCKS = 502; @@ -263,12 +291,39 @@ public interface ItemID { int RECORD_WARD = 509; int RECORD_11 = 510; int RECORD_WAIT = 511; + // int SHIELD = 513; - int RECORD_5 = 643; + // + int COPPER_INGOT = 519; + int RAW_IRON = 520; + int RAW_GOLD = 521; + int RAW_COPPER = 522; + // + int RECORD_5 = 636; //TODO: 643 + int DISC_FRAGMENT_5 = 637; + // + int OAK_CHEST_BOAT = 638; + int BIRCH_CHEST_BOAT = 639; + int JUNGLE_CHEST_BOAT = 640; + int SPRUCE_CHEST_BOAT = 641; + int ACACIA_CHEST_BOAT = 642; + int DARK_OAK_CHEST_BOAT = 643; + int MANGROVE_CHEST_BOAT = 644; + // + int ECHO_SHARD = 647; + int RECOVERY_COMPASS = 648; + // + int GLOW_BERRIES = 654; + // int RECORD_RELIC = 701; + // + int CAMPFIRE = 720; + // int SUSPICIOUS_STEW = 734; + // int HONEYCOMB = 736; int HONEY_BOTTLE = 737; + // int LODESTONECOMPASS = 741; int LODESTONE_COMPASS = 741; int NETHERITE_INGOT = 742; @@ -282,8 +337,23 @@ public interface ItemID { int NETHERITE_LEGGINGS = 750; int NETHERITE_BOOTS = 751; int NETHERITE_SCRAP = 752; + int CRIMSON_SIGN = 753; + int WARPED_SIGN = 754; + int CRIMSON_DOOR = 755; + int WARPED_DOOR = 756; + // int WARPED_FUNGUS_ON_A_STICK = 757; + // + int CHAIN = 758; int RECORD_PIGSTEP = 759; + int NETHER_SPROUTS = 760; + int GOAT_HORN = 761; + // + int AMETHYST_SHARD = 771; int SPYGLASS = 772; int RECORD_OTHERSIDE = 773; + // + int SOUL_CAMPFIRE = 801; + // + int GLOW_ITEM_FRAME = 850; } diff --git a/src/main/java/cn/nukkit/item/ItemIngotCopper.java b/src/main/java/cn/nukkit/item/ItemIngotCopper.java new file mode 100644 index 00000000000..07378d6fe03 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemIngotCopper.java @@ -0,0 +1,16 @@ +package cn.nukkit.item; + +public class ItemIngotCopper extends Item { + + public ItemIngotCopper() { + this(0, 1); + } + + public ItemIngotCopper(Integer meta) { + this(meta, 1); + } + + public ItemIngotCopper(Integer meta, int count) { + super(COPPER_INGOT, 0, count, "Copper Ingot"); + } +} diff --git a/src/main/java/cn/nukkit/item/ItemIngotGold.java b/src/main/java/cn/nukkit/item/ItemIngotGold.java index cd3150f599c..bb0ade3ab95 100644 --- a/src/main/java/cn/nukkit/item/ItemIngotGold.java +++ b/src/main/java/cn/nukkit/item/ItemIngotGold.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemIngotGold extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemIngotIron.java b/src/main/java/cn/nukkit/item/ItemIngotIron.java index ec6306afd54..f1fc33a7769 100644 --- a/src/main/java/cn/nukkit/item/ItemIngotIron.java +++ b/src/main/java/cn/nukkit/item/ItemIngotIron.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemIngotIron extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemIronRaw.java b/src/main/java/cn/nukkit/item/ItemIronRaw.java new file mode 100644 index 00000000000..c6fca03c650 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemIronRaw.java @@ -0,0 +1,16 @@ +package cn.nukkit.item; + +public class ItemIronRaw extends Item { + + public ItemIronRaw() { + this(0, 1); + } + + public ItemIronRaw(Integer meta) { + this(meta, 1); + } + + public ItemIronRaw(Integer meta, int count) { + super(RAW_IRON, meta, count, "Raw Iron"); + } +} diff --git a/src/main/java/cn/nukkit/item/ItemItemFrame.java b/src/main/java/cn/nukkit/item/ItemItemFrame.java index b8e5eb1935b..b32df67479a 100644 --- a/src/main/java/cn/nukkit/item/ItemItemFrame.java +++ b/src/main/java/cn/nukkit/item/ItemItemFrame.java @@ -1,7 +1,6 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; /** * Created by Pub4Game on 03.07.2016. @@ -18,6 +17,6 @@ public ItemItemFrame(Integer meta) { public ItemItemFrame(Integer meta, int count) { super(ITEM_FRAME, meta, count, "Item Frame"); - this.block = Block.get(BlockID.ITEM_FRAME_BLOCK); + this.block = Block.get(ITEM_FRAME_BLOCK); } } diff --git a/src/main/java/cn/nukkit/item/ItemItemFrameGlow.java b/src/main/java/cn/nukkit/item/ItemItemFrameGlow.java new file mode 100644 index 00000000000..826f625ffb4 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemItemFrameGlow.java @@ -0,0 +1,20 @@ +package cn.nukkit.item; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; + +public class ItemItemFrameGlow extends Item { + + public ItemItemFrameGlow() { + this(0, 1); + } + + public ItemItemFrameGlow(Integer meta) { + this(meta, 1); + } + + public ItemItemFrameGlow(Integer meta, int count) { + super(GLOW_ITEM_FRAME, meta, count, "Glow Item Frame"); + this.block = Block.get(BlockID.GLOW_FRAME); + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/item/ItemKelp.java b/src/main/java/cn/nukkit/item/ItemKelp.java new file mode 100644 index 00000000000..96b36b205d4 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemKelp.java @@ -0,0 +1,19 @@ +package cn.nukkit.item; + +import cn.nukkit.block.Block; + +public class ItemKelp extends Item { + + public ItemKelp() { + this(0, 1); + } + + public ItemKelp(Integer meta) { + this(meta, 1); + } + + public ItemKelp(Integer meta, int count) { + super(KELP, meta, count, "Kelp"); + this.block = Block.get(Block.BLOCK_KELP); + } +} diff --git a/src/main/java/cn/nukkit/item/ItemLeather.java b/src/main/java/cn/nukkit/item/ItemLeather.java index d676ed64700..8addfb1ad5f 100644 --- a/src/main/java/cn/nukkit/item/ItemLeather.java +++ b/src/main/java/cn/nukkit/item/ItemLeather.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemLeather extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemLeggingsChain.java b/src/main/java/cn/nukkit/item/ItemLeggingsChain.java index 687ad8c764e..7ba7910719a 100644 --- a/src/main/java/cn/nukkit/item/ItemLeggingsChain.java +++ b/src/main/java/cn/nukkit/item/ItemLeggingsChain.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemLeggingsChain extends ItemArmor { diff --git a/src/main/java/cn/nukkit/item/ItemLeggingsDiamond.java b/src/main/java/cn/nukkit/item/ItemLeggingsDiamond.java index 82f3f995fb2..d7648af679c 100644 --- a/src/main/java/cn/nukkit/item/ItemLeggingsDiamond.java +++ b/src/main/java/cn/nukkit/item/ItemLeggingsDiamond.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemLeggingsDiamond extends ItemArmor { diff --git a/src/main/java/cn/nukkit/item/ItemLeggingsGold.java b/src/main/java/cn/nukkit/item/ItemLeggingsGold.java index a34e2dd6e83..b653688be19 100644 --- a/src/main/java/cn/nukkit/item/ItemLeggingsGold.java +++ b/src/main/java/cn/nukkit/item/ItemLeggingsGold.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemLeggingsGold extends ItemArmor { @@ -15,7 +15,7 @@ public ItemLeggingsGold(Integer meta) { } public ItemLeggingsGold(Integer meta, int count) { - super(GOLD_LEGGINGS, meta, count, "Gold Leggings"); + super(GOLD_LEGGINGS, meta, count, "Golden Leggings"); } @Override diff --git a/src/main/java/cn/nukkit/item/ItemLeggingsIron.java b/src/main/java/cn/nukkit/item/ItemLeggingsIron.java index 58b83d0a589..3c591e629d7 100644 --- a/src/main/java/cn/nukkit/item/ItemLeggingsIron.java +++ b/src/main/java/cn/nukkit/item/ItemLeggingsIron.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemLeggingsIron extends ItemArmor { diff --git a/src/main/java/cn/nukkit/item/ItemLeggingsLeather.java b/src/main/java/cn/nukkit/item/ItemLeggingsLeather.java index fd25d1f6d31..d107fb1b5b9 100644 --- a/src/main/java/cn/nukkit/item/ItemLeggingsLeather.java +++ b/src/main/java/cn/nukkit/item/ItemLeggingsLeather.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemLeggingsLeather extends ItemColorArmor { diff --git a/src/main/java/cn/nukkit/item/ItemLeggingsNetherite.java b/src/main/java/cn/nukkit/item/ItemLeggingsNetherite.java index a7e0298fec9..77ced531669 100644 --- a/src/main/java/cn/nukkit/item/ItemLeggingsNetherite.java +++ b/src/main/java/cn/nukkit/item/ItemLeggingsNetherite.java @@ -36,6 +36,6 @@ public int getArmorPoints() { @Override public int getToughness() { - return 2; + return 3; } } diff --git a/src/main/java/cn/nukkit/item/ItemLodestoneCompass.java b/src/main/java/cn/nukkit/item/ItemLodestoneCompass.java new file mode 100644 index 00000000000..1c12d9880b9 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemLodestoneCompass.java @@ -0,0 +1,16 @@ +package cn.nukkit.item; + +public class ItemLodestoneCompass extends Item { + + public ItemLodestoneCompass() { + this(0, 1); + } + + public ItemLodestoneCompass(Integer meta) { + this(meta, 1); + } + + public ItemLodestoneCompass(Integer meta, int count) { + super(LODESTONE_COMPASS, meta, count, "Lodestone Compass"); + } +} diff --git a/src/main/java/cn/nukkit/item/ItemMagmaCream.java b/src/main/java/cn/nukkit/item/ItemMagmaCream.java index 0cf5fdcbd9a..1010904d179 100644 --- a/src/main/java/cn/nukkit/item/ItemMagmaCream.java +++ b/src/main/java/cn/nukkit/item/ItemMagmaCream.java @@ -6,14 +6,14 @@ public class ItemMagmaCream extends Item { public ItemMagmaCream() { - this(0); + this(0, 1); } public ItemMagmaCream(Integer meta) { - this(0, 1); + this(meta, 1); } public ItemMagmaCream(Integer meta, int count) { - super(MAGMA_CREAM, meta, count, "Magma Cream"); + super(MAGMA_CREAM, 0, count, "Magma Cream"); } } diff --git a/src/main/java/cn/nukkit/item/ItemMap.java b/src/main/java/cn/nukkit/item/ItemMap.java index 5ed327ea55b..c411fb67b1d 100644 --- a/src/main/java/cn/nukkit/item/ItemMap.java +++ b/src/main/java/cn/nukkit/item/ItemMap.java @@ -1,12 +1,13 @@ package cn.nukkit.item; import cn.nukkit.Player; +import cn.nukkit.Server; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.network.protocol.ClientboundMapItemDataPacket; import cn.nukkit.utils.MainLogger; import javax.imageio.ImageIO; -import java.awt.Graphics2D; +import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -18,9 +19,8 @@ */ public class ItemMap extends Item { - public static int mapCount = 0; + public static long mapCount = 0; - // not very pretty but definitely better than before. private BufferedImage image; public ItemMap() { @@ -33,12 +33,6 @@ public ItemMap(Integer meta) { public ItemMap(Integer meta, int count) { super(MAP, meta, count, "Map"); - - if (!hasCompoundTag() || !getNamedTag().contains("map_uuid")) { - CompoundTag tag = new CompoundTag(); - tag.putLong("map_uuid", mapCount++); - this.setNamedTag(tag); - } } public void setImage(File file) throws IOException { @@ -47,7 +41,12 @@ public void setImage(File file) throws IOException { public void setImage(BufferedImage image) { try { - if (image.getHeight() != 128 || image.getWidth() != 128) { //resize + if (this.getMapId() == 0) { + Server.getInstance().getLogger().debug("Uninitialized map", new Throwable("")); + this.initItem(); + } + + if (image.getHeight() != 128 || image.getWidth() != 128) { this.image = new BufferedImage(128, 128, image.getType()); Graphics2D g = this.image.createGraphics(); g.drawImage(image, 0, 0, 128, 128, null); @@ -59,7 +58,8 @@ public void setImage(BufferedImage image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(this.image, "png", baos); - this.getNamedTag().putByteArray("Colors", baos.toByteArray()); + this.setNamedTag(this.getNamedTag().putByteArray("Colors", baos.toByteArray())); + baos.close(); } catch (IOException e) { MainLogger.getLogger().logException(e); } @@ -78,24 +78,49 @@ protected BufferedImage loadImageFromNBT() { } public long getMapId() { - return getNamedTag().getLong("map_uuid"); + CompoundTag tag = this.getNamedTag(); + if (tag == null) return 0; + return tag.getLong("map_uuid"); } public void sendImage(Player p) { - // don't load the image from NBT if it has been done before. + // Don't load the image from NBT if it has been done before + BufferedImage image = this.image != null ? this.image : loadImageFromNBT(); + + ClientboundMapItemDataPacket pk = new ClientboundMapItemDataPacket(); + pk.mapId = getMapId(); + pk.update = ClientboundMapItemDataPacket.TEXTURE_UPDATE; + pk.scale = 0; + pk.width = 128; + pk.height = 128; + pk.offsetX = 0; + pk.offsetZ = 0; + pk.image = image; + pk.eids = new long[]{pk.mapId}; + + p.dataPacket(pk); + } + + public boolean trySendImage(Player p) { + // Don't load the image from NBT if it has been done before BufferedImage image = this.image != null ? this.image : loadImageFromNBT(); + if (image == null) { + return false; + } ClientboundMapItemDataPacket pk = new ClientboundMapItemDataPacket(); pk.mapId = getMapId(); - pk.update = 2; + pk.update = ClientboundMapItemDataPacket.TEXTURE_UPDATE; pk.scale = 0; pk.width = 128; pk.height = 128; pk.offsetX = 0; pk.offsetZ = 0; pk.image = image; + pk.eids = new long[]{pk.mapId}; p.dataPacket(pk); + return true; } @Override @@ -105,6 +130,33 @@ public boolean canBeActivated() { @Override public int getMaxStackSize() { - return 1; + return 1; // TODO: 64 when map copying is implemented + } + + @Override + public Item initItem() { + CompoundTag compoundTag = this.getNamedTag(); + if (compoundTag == null || !compoundTag.contains("map_uuid")) { + CompoundTag tag = new CompoundTag(); + mapCount++; + tag.putLong("map_uuid", mapCount); + tag.putInt("map_name_index", (int) mapCount); + this.setNamedTag(tag); + } else { + long id; + if ((id = getMapId()) > mapCount) { + mapCount = id; + } + if (!(compoundTag = this.getNamedTag()).contains("map_name_index")) { + compoundTag.putInt("map_name_index", (int) id); + this.setNamedTag(compoundTag); + } + } + return super.initItem(); + } + + @Override + public boolean allowOffhand() { + return true; } } diff --git a/src/main/java/cn/nukkit/item/ItemMelon.java b/src/main/java/cn/nukkit/item/ItemMelon.java index 64dae4da6ad..cfcc63bad8f 100644 --- a/src/main/java/cn/nukkit/item/ItemMelon.java +++ b/src/main/java/cn/nukkit/item/ItemMelon.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemMelon extends ItemEdible { diff --git a/src/main/java/cn/nukkit/item/ItemMelonGlistering.java b/src/main/java/cn/nukkit/item/ItemMelonGlistering.java index ad1ef673539..235b7ae0bb5 100644 --- a/src/main/java/cn/nukkit/item/ItemMelonGlistering.java +++ b/src/main/java/cn/nukkit/item/ItemMelonGlistering.java @@ -6,7 +6,7 @@ public class ItemMelonGlistering extends Item { public ItemMelonGlistering() { - this(0); + this(0, 1); } public ItemMelonGlistering(Integer meta) { @@ -14,6 +14,6 @@ public ItemMelonGlistering(Integer meta) { } public ItemMelonGlistering(Integer meta, int count) { - super(GLISTERING_MELON, meta, count, "Glistering Melon"); + super(GLISTERING_MELON, 0, count, "Glistering Melon"); } } diff --git a/src/main/java/cn/nukkit/item/ItemMinecart.java b/src/main/java/cn/nukkit/item/ItemMinecart.java index 5a523cd88cd..5544d76f348 100644 --- a/src/main/java/cn/nukkit/item/ItemMinecart.java +++ b/src/main/java/cn/nukkit/item/ItemMinecart.java @@ -14,7 +14,7 @@ import cn.nukkit.utils.Rail; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemMinecart extends Item { @@ -44,8 +44,8 @@ public boolean onActivate(Level level, Player player, Block block, Block target, if (type.isAscending()) { adjacent = 0.5D; } - EntityMinecartEmpty minecart = (EntityMinecartEmpty) Entity.createEntity("MinecartRideable", - level.getChunk(target.getFloorX() >> 4, target.getFloorZ() >> 4), new CompoundTag("") + Entity.createEntity(EntityMinecartEmpty.NETWORK_ID, + level.getChunk(target.getChunkX(), target.getChunkZ()), new CompoundTag("") .putList(new ListTag<>("Pos") .add(new DoubleTag("", target.getX() + 0.5)) .add(new DoubleTag("", target.getY() + 0.0625D + adjacent)) @@ -57,19 +57,8 @@ public boolean onActivate(Level level, Player player, Block block, Block target, .putList(new ListTag<>("Rotation") .add(new FloatTag("", 0)) .add(new FloatTag("", 0))) - ); - - if(minecart == null) { - return false; - } - - if (player.isAdventure() || player.isSurvival()) { - Item item = player.getInventory().getItemInHand(); - item.setCount(item.getCount() - 1); - player.getInventory().setItemInHand(item); - } - - minecart.spawnToAll(); + ).spawnToAll(); + count -= 1; return true; } return false; diff --git a/src/main/java/cn/nukkit/item/ItemMinecartChest.java b/src/main/java/cn/nukkit/item/ItemMinecartChest.java index 847a0feb6d6..9ff14ba538e 100644 --- a/src/main/java/cn/nukkit/item/ItemMinecartChest.java +++ b/src/main/java/cn/nukkit/item/ItemMinecartChest.java @@ -40,32 +40,21 @@ public boolean onActivate(Level level, Player player, Block block, Block target, if (type.isAscending()) { adjacent = 0.5D; } - EntityMinecartChest minecart = (EntityMinecartChest) Entity.createEntity("MinecartChest", - level.getChunk(target.getFloorX() >> 4, target.getFloorZ() >> 4), new CompoundTag("") - .putList(new ListTag<>("Pos") - .add(new DoubleTag("", target.getX() + 0.5)) - .add(new DoubleTag("", target.getY() + 0.0625D + adjacent)) - .add(new DoubleTag("", target.getZ() + 0.5))) - .putList(new ListTag<>("Motion") - .add(new DoubleTag("", 0)) - .add(new DoubleTag("", 0)) - .add(new DoubleTag("", 0))) - .putList(new ListTag<>("Rotation") - .add(new FloatTag("", 0)) - .add(new FloatTag("", 0))) - ); - - if(minecart == null) { - return false; - } - - if (player.isAdventure() || player.isSurvival()) { - Item item = player.getInventory().getItemInHand(); - item.setCount(item.getCount() - 1); - player.getInventory().setItemInHand(item); - } - - minecart.spawnToAll(); + Entity.createEntity(EntityMinecartChest.NETWORK_ID, + level.getChunk(target.getChunkX(), target.getChunkZ()), new CompoundTag("") + .putList(new ListTag<>("Pos") + .add(new DoubleTag("", target.getX() + 0.5)) + .add(new DoubleTag("", target.getY() + 0.0625D + adjacent)) + .add(new DoubleTag("", target.getZ() + 0.5))) + .putList(new ListTag<>("Motion") + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0))) + .putList(new ListTag<>("Rotation") + .add(new FloatTag("", 0)) + .add(new FloatTag("", 0))) + ).spawnToAll(); + count -= 1; return true; } return false; diff --git a/src/main/java/cn/nukkit/item/ItemMinecartHopper.java b/src/main/java/cn/nukkit/item/ItemMinecartHopper.java index 84c052b3376..761ddf291d4 100644 --- a/src/main/java/cn/nukkit/item/ItemMinecartHopper.java +++ b/src/main/java/cn/nukkit/item/ItemMinecartHopper.java @@ -40,32 +40,21 @@ public boolean onActivate(Level level, Player player, Block block, Block target, if (type.isAscending()) { adjacent = 0.5D; } - EntityMinecartHopper minecart = (EntityMinecartHopper) Entity.createEntity("MinecartHopper", - level.getChunk(target.getFloorX() >> 4, target.getFloorZ() >> 4), new CompoundTag("") - .putList(new ListTag<>("Pos") - .add(new DoubleTag("", target.getX() + 0.5)) - .add(new DoubleTag("", target.getY() + 0.0625D + adjacent)) - .add(new DoubleTag("", target.getZ() + 0.5))) - .putList(new ListTag<>("Motion") - .add(new DoubleTag("", 0)) - .add(new DoubleTag("", 0)) - .add(new DoubleTag("", 0))) - .putList(new ListTag<>("Rotation") - .add(new FloatTag("", 0)) - .add(new FloatTag("", 0))) - ); - - if(minecart == null) { - return false; - } - - if (player.isAdventure() || player.isSurvival()) { - Item item = player.getInventory().getItemInHand(); - item.setCount(item.getCount() - 1); - player.getInventory().setItemInHand(item); - } - - minecart.spawnToAll(); + Entity.createEntity(EntityMinecartHopper.NETWORK_ID, + level.getChunk(target.getChunkX(), target.getChunkZ()), new CompoundTag("") + .putList(new ListTag<>("Pos") + .add(new DoubleTag("", target.getX() + 0.5)) + .add(new DoubleTag("", target.getY() + 0.0625D + adjacent)) + .add(new DoubleTag("", target.getZ() + 0.5))) + .putList(new ListTag<>("Motion") + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0)) + .add(new DoubleTag("", 0))) + .putList(new ListTag<>("Rotation") + .add(new FloatTag("", 0)) + .add(new FloatTag("", 0))) + ).spawnToAll(); + count -= 1; return true; } return false; diff --git a/src/main/java/cn/nukkit/item/ItemMinecartTNT.java b/src/main/java/cn/nukkit/item/ItemMinecartTNT.java index 20f0e6eb2fe..7f12ce35c45 100644 --- a/src/main/java/cn/nukkit/item/ItemMinecartTNT.java +++ b/src/main/java/cn/nukkit/item/ItemMinecartTNT.java @@ -40,8 +40,8 @@ public boolean onActivate(Level level, Player player, Block block, Block target, if (type.isAscending()) { adjacent = 0.5D; } - EntityMinecartTNT minecart = (EntityMinecartTNT) Entity.createEntity("MinecartTnt", - level.getChunk(target.getFloorX() >> 4, target.getFloorZ() >> 4), new CompoundTag("") + Entity.createEntity(EntityMinecartTNT.NETWORK_ID, + level.getChunk(target.getChunkX(), target.getChunkZ()), new CompoundTag("") .putList(new ListTag<>("Pos") .add(new DoubleTag("", target.getX() + 0.5)) .add(new DoubleTag("", target.getY() + 0.0625D + adjacent)) @@ -53,19 +53,8 @@ public boolean onActivate(Level level, Player player, Block block, Block target, .putList(new ListTag<>("Rotation") .add(new FloatTag("", 0)) .add(new FloatTag("", 0))) - ); - - if(minecart == null) { - return false; - } - - if (player.isAdventure() || player.isSurvival()) { - Item item = player.getInventory().getItemInHand(); - item.setCount(item.getCount() - 1); - player.getInventory().setItemInHand(item); - } - - minecart.spawnToAll(); + ).spawnToAll(); + count -= 1; return true; } return false; diff --git a/src/main/java/cn/nukkit/item/ItemMushroomStew.java b/src/main/java/cn/nukkit/item/ItemMushroomStew.java index 808f68f81d1..579c190ba88 100644 --- a/src/main/java/cn/nukkit/item/ItemMushroomStew.java +++ b/src/main/java/cn/nukkit/item/ItemMushroomStew.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemMushroomStew extends ItemEdible { diff --git a/src/main/java/cn/nukkit/item/ItemNameTag.java b/src/main/java/cn/nukkit/item/ItemNameTag.java index ef898d71a5c..917cfff3c33 100644 --- a/src/main/java/cn/nukkit/item/ItemNameTag.java +++ b/src/main/java/cn/nukkit/item/ItemNameTag.java @@ -11,7 +11,6 @@ public ItemNameTag(Integer meta) { } public ItemNameTag(Integer meta, int count) { - super(NAME_TAG, meta, count, "Name Tag"); + super(NAME_TAG, 0, count, "Name Tag"); } - } diff --git a/src/main/java/cn/nukkit/item/ItemNautilusShell.java b/src/main/java/cn/nukkit/item/ItemNautilusShell.java index b3163e13b30..f1c029b2e40 100644 --- a/src/main/java/cn/nukkit/item/ItemNautilusShell.java +++ b/src/main/java/cn/nukkit/item/ItemNautilusShell.java @@ -13,4 +13,9 @@ public ItemNautilusShell(Integer meta) { public ItemNautilusShell(Integer meta, int count) { super(NAUTILUS_SHELL, meta, count, "Nautilus Shell"); } + + @Override + public boolean allowOffhand() { + return true; + } } diff --git a/src/main/java/cn/nukkit/item/ItemNetherBrick.java b/src/main/java/cn/nukkit/item/ItemNetherBrick.java index c354c8a194f..b3facadd8eb 100644 --- a/src/main/java/cn/nukkit/item/ItemNetherBrick.java +++ b/src/main/java/cn/nukkit/item/ItemNetherBrick.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemNetherBrick extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemNetherSprouts.java b/src/main/java/cn/nukkit/item/ItemNetherSprouts.java new file mode 100644 index 00000000000..a3205c2b91d --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemNetherSprouts.java @@ -0,0 +1,20 @@ +package cn.nukkit.item; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; + +public class ItemNetherSprouts extends Item { + + public ItemNetherSprouts() { + this(0, 1); + } + + public ItemNetherSprouts(Integer meta) { + this(meta, 1); + } + + public ItemNetherSprouts(Integer meta, int count) { + super(NETHER_SPROUTS, 0, count, "Nether Sprouts"); + this.block = Block.get(BlockID.NETHER_SPROUTS_BLOCK); + } +} diff --git a/src/main/java/cn/nukkit/item/ItemNetherWart.java b/src/main/java/cn/nukkit/item/ItemNetherWart.java index d0221314b12..fecf4d918ef 100644 --- a/src/main/java/cn/nukkit/item/ItemNetherWart.java +++ b/src/main/java/cn/nukkit/item/ItemNetherWart.java @@ -1,7 +1,6 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; /** * Created by Leonidius20 on 22.03.17. @@ -18,7 +17,6 @@ public ItemNetherWart(Integer meta) { public ItemNetherWart(Integer meta, int count) { super(NETHER_WART, meta, count, "Nether Wart"); - this.block = Block.get(BlockID.NETHER_WART_BLOCK, meta); + this.block = Block.get(NETHER_WART_BLOCK, meta); } - } diff --git a/src/main/java/cn/nukkit/item/ItemNuggetGold.java b/src/main/java/cn/nukkit/item/ItemNuggetGold.java index 2d82ea9857e..ec7819572aa 100644 --- a/src/main/java/cn/nukkit/item/ItemNuggetGold.java +++ b/src/main/java/cn/nukkit/item/ItemNuggetGold.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemNuggetGold extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemPainting.java b/src/main/java/cn/nukkit/item/ItemPainting.java index 3419bfc2086..992815d8beb 100644 --- a/src/main/java/cn/nukkit/item/ItemPainting.java +++ b/src/main/java/cn/nukkit/item/ItemPainting.java @@ -12,16 +12,18 @@ import cn.nukkit.nbt.tag.DoubleTag; import cn.nukkit.nbt.tag.FloatTag; import cn.nukkit.nbt.tag.ListTag; +import cn.nukkit.network.protocol.LevelEventPacket; +import cn.nukkit.utils.Utils; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.ThreadLocalRandom; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemPainting extends Item { + private static final int[] DIRECTION = {2, 3, 4, 5}; private static final int[] RIGHT = {4, 5, 3, 2}; private static final double OFFSET = 0.53125; @@ -45,13 +47,12 @@ public boolean canBeActivated() { @Override public boolean onActivate(Level level, Player player, Block block, Block target, BlockFace face, double fx, double fy, double fz) { - if (player.isAdventure()) { + if (player.isAdventure() || target.isTransparent() || face.getHorizontalIndex() == -1 || block.isSolid()) { return false; } FullChunk chunk = level.getChunk((int) block.getX() >> 4, (int) block.getZ() >> 4); - - if (chunk == null || target.isTransparent() || face.getHorizontalIndex() == -1 || block.isSolid()) { + if (chunk == null) { return false; } @@ -74,7 +75,7 @@ public boolean onActivate(Level level, Player player, Block block, Block target, } } int direction = DIRECTION[face.getIndex() - 2]; - EntityPainting.Motive motive = validMotives.get(ThreadLocalRandom.current().nextInt(validMotives.size())); + EntityPainting.Motive motive = validMotives.get(Utils.random.nextInt(validMotives.size())); Vector3 position = new Vector3(target.x + 0.5, target.y + 0.5, target.z + 0.5); double widthOffset = offset(motive.width); @@ -114,19 +115,13 @@ public boolean onActivate(Level level, Player player, Block block, Block target, .add(new FloatTag("0", direction * 90)) .add(new FloatTag("1", 0))); - EntityPainting entity = (EntityPainting) Entity.createEntity("Painting", chunk, nbt); - - if (entity == null) { - return false; - } + Entity.createEntity(EntityPainting.NETWORK_ID, chunk, nbt).spawnToAll(); - if (player.isSurvival()) { - Item item = player.getInventory().getItemInHand(); - item.setCount(item.getCount() - 1); - player.getInventory().setItemInHand(item); + if (!player.isCreative()) { + this.count--; } - entity.spawnToAll(); + level.addLevelEvent(block, LevelEventPacket.EVENT_SOUND_ITEM_FRAME_PLACED); return true; } diff --git a/src/main/java/cn/nukkit/item/ItemPaper.java b/src/main/java/cn/nukkit/item/ItemPaper.java index 59185957fc3..5d420125307 100644 --- a/src/main/java/cn/nukkit/item/ItemPaper.java +++ b/src/main/java/cn/nukkit/item/ItemPaper.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemPaper extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemPickaxeDiamond.java b/src/main/java/cn/nukkit/item/ItemPickaxeDiamond.java index ac7cecf769b..e0072afea74 100644 --- a/src/main/java/cn/nukkit/item/ItemPickaxeDiamond.java +++ b/src/main/java/cn/nukkit/item/ItemPickaxeDiamond.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemPickaxeDiamond extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemPickaxeGold.java b/src/main/java/cn/nukkit/item/ItemPickaxeGold.java index 993ff1b3272..654c3f18e61 100644 --- a/src/main/java/cn/nukkit/item/ItemPickaxeGold.java +++ b/src/main/java/cn/nukkit/item/ItemPickaxeGold.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemPickaxeGold extends ItemTool { @@ -15,7 +15,7 @@ public ItemPickaxeGold(Integer meta) { } public ItemPickaxeGold(Integer meta, int count) { - super(GOLD_PICKAXE, meta, count, "Gold Pickaxe"); + super(GOLD_PICKAXE, meta, count, "Golden Pickaxe"); } @Override diff --git a/src/main/java/cn/nukkit/item/ItemPickaxeIron.java b/src/main/java/cn/nukkit/item/ItemPickaxeIron.java index 62a01a72c06..77d636a29ea 100644 --- a/src/main/java/cn/nukkit/item/ItemPickaxeIron.java +++ b/src/main/java/cn/nukkit/item/ItemPickaxeIron.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemPickaxeIron extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemPickaxeStone.java b/src/main/java/cn/nukkit/item/ItemPickaxeStone.java index 8bfa75ef14d..72ad598e481 100644 --- a/src/main/java/cn/nukkit/item/ItemPickaxeStone.java +++ b/src/main/java/cn/nukkit/item/ItemPickaxeStone.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemPickaxeStone extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemPickaxeWood.java b/src/main/java/cn/nukkit/item/ItemPickaxeWood.java index 97fe4125d69..ab4e339b8fd 100644 --- a/src/main/java/cn/nukkit/item/ItemPickaxeWood.java +++ b/src/main/java/cn/nukkit/item/ItemPickaxeWood.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemPickaxeWood extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemPorkchopCooked.java b/src/main/java/cn/nukkit/item/ItemPorkchopCooked.java index 46df30e00cc..09004762524 100644 --- a/src/main/java/cn/nukkit/item/ItemPorkchopCooked.java +++ b/src/main/java/cn/nukkit/item/ItemPorkchopCooked.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemPorkchopCooked extends ItemEdible { diff --git a/src/main/java/cn/nukkit/item/ItemPorkchopRaw.java b/src/main/java/cn/nukkit/item/ItemPorkchopRaw.java index 93797753e01..c40c2bb5aba 100644 --- a/src/main/java/cn/nukkit/item/ItemPorkchopRaw.java +++ b/src/main/java/cn/nukkit/item/ItemPorkchopRaw.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemPorkchopRaw extends ItemEdible { diff --git a/src/main/java/cn/nukkit/item/ItemPotato.java b/src/main/java/cn/nukkit/item/ItemPotato.java index bde98e930d6..915f32e0511 100644 --- a/src/main/java/cn/nukkit/item/ItemPotato.java +++ b/src/main/java/cn/nukkit/item/ItemPotato.java @@ -1,10 +1,9 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemPotato extends ItemEdible { @@ -19,7 +18,7 @@ public ItemPotato(Integer meta) { public ItemPotato(Integer meta, int count) { super(POTATO, meta, count, "Potato"); - this.block = Block.get(BlockID.POTATO_BLOCK); + this.block = Block.get(POTATO_BLOCK); } protected ItemPotato(int id, Integer meta, int count, String name) { diff --git a/src/main/java/cn/nukkit/item/ItemPotatoBaked.java b/src/main/java/cn/nukkit/item/ItemPotatoBaked.java index b4f23bac68c..6c0d9f1fc96 100644 --- a/src/main/java/cn/nukkit/item/ItemPotatoBaked.java +++ b/src/main/java/cn/nukkit/item/ItemPotatoBaked.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemPotatoBaked extends ItemEdible { @@ -17,5 +17,4 @@ public ItemPotatoBaked(Integer meta) { public ItemPotatoBaked(Integer meta, int count) { super(BAKED_POTATO, meta, count, "Baked Potato"); } - } diff --git a/src/main/java/cn/nukkit/item/ItemPotion.java b/src/main/java/cn/nukkit/item/ItemPotion.java index ffa3dbfd435..d48caa4450c 100644 --- a/src/main/java/cn/nukkit/item/ItemPotion.java +++ b/src/main/java/cn/nukkit/item/ItemPotion.java @@ -69,6 +69,10 @@ public boolean onClickAir(Player player, Vector3 directionVector) { @Override public boolean onUse(Player player, int ticksUsed) { + if (ticksUsed < 30) { + player.getServer().getLogger().debug(player.getName() + ": potion ticksUsed=" + ticksUsed); + return false; + } PlayerItemConsumeEvent consumeEvent = new PlayerItemConsumeEvent(player, this); player.getServer().getPluginManager().callEvent(consumeEvent); if (consumeEvent.isCancelled()) { @@ -76,10 +80,10 @@ public boolean onUse(Player player, int ticksUsed) { } Potion potion = Potion.getPotion(this.getDamage()); - if (player.isAdventure() || player.isSurvival()) { + if (!player.isCreative()) { --this.count; player.getInventory().setItemInHand(this); - player.getInventory().addItem(new ItemGlassBottle()); + player.getInventory().addItem(Item.get(Item.GLASS_BOTTLE)); } if (potion != null) { diff --git a/src/main/java/cn/nukkit/item/ItemPotionLingering.java b/src/main/java/cn/nukkit/item/ItemPotionLingering.java index d2df4441ed7..e3ab5a8a902 100644 --- a/src/main/java/cn/nukkit/item/ItemPotionLingering.java +++ b/src/main/java/cn/nukkit/item/ItemPotionLingering.java @@ -1,6 +1,8 @@ package cn.nukkit.item; -public class ItemPotionLingering extends Item { +import cn.nukkit.nbt.tag.CompoundTag; + +public class ItemPotionLingering extends ProjectileItem { public ItemPotionLingering() { this(0, 1); @@ -11,11 +13,31 @@ public ItemPotionLingering(Integer meta) { } public ItemPotionLingering(Integer meta, int count) { - super(POTION, meta, count, "Lingering Potion"); + super(LINGERING_POTION, meta, count, "Lingering Potion"); } @Override public int getMaxStackSize() { return 1; } -} \ No newline at end of file + + @Override + public boolean canBeActivated() { + return true; + } + + @Override + public String getProjectileEntityType() { + return "ThrownLingeringPotion"; + } + + @Override + public float getThrowForce() { + return 0.50f; + } + + @Override + protected void correctNBT(CompoundTag nbt) { + nbt.putInt("PotionId", this.meta); + } +} diff --git a/src/main/java/cn/nukkit/item/ItemPotionSplash.java b/src/main/java/cn/nukkit/item/ItemPotionSplash.java index 96373bd1e16..4e463b72d9b 100644 --- a/src/main/java/cn/nukkit/item/ItemPotionSplash.java +++ b/src/main/java/cn/nukkit/item/ItemPotionSplash.java @@ -33,7 +33,7 @@ public String getProjectileEntityType() { @Override public float getThrowForce() { - return 0.5f; + return 0.50f; } @Override diff --git a/src/main/java/cn/nukkit/item/ItemPufferfish.java b/src/main/java/cn/nukkit/item/ItemPufferfish.java index 1b275409814..1d76a6d1c46 100644 --- a/src/main/java/cn/nukkit/item/ItemPufferfish.java +++ b/src/main/java/cn/nukkit/item/ItemPufferfish.java @@ -17,5 +17,4 @@ public ItemPufferfish(Integer meta) { public ItemPufferfish(Integer meta, int count) { super(PUFFERFISH, meta, count, "Pufferfish"); } - } diff --git a/src/main/java/cn/nukkit/item/ItemPumpkinPie.java b/src/main/java/cn/nukkit/item/ItemPumpkinPie.java index 4ae92c2d21c..8919b54fcaf 100644 --- a/src/main/java/cn/nukkit/item/ItemPumpkinPie.java +++ b/src/main/java/cn/nukkit/item/ItemPumpkinPie.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemPumpkinPie extends ItemEdible { diff --git a/src/main/java/cn/nukkit/item/ItemQuartz.java b/src/main/java/cn/nukkit/item/ItemQuartz.java index 18850835eab..ae8722ef3a8 100644 --- a/src/main/java/cn/nukkit/item/ItemQuartz.java +++ b/src/main/java/cn/nukkit/item/ItemQuartz.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemQuartz extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemRabbitRaw.java b/src/main/java/cn/nukkit/item/ItemRabbitRaw.java index 18e3ba2fe5a..395c9864ecb 100644 --- a/src/main/java/cn/nukkit/item/ItemRabbitRaw.java +++ b/src/main/java/cn/nukkit/item/ItemRabbitRaw.java @@ -5,6 +5,7 @@ * Package cn.nukkit.item in project nukkit. */ public class ItemRabbitRaw extends ItemEdible { + public ItemRabbitRaw() { this(0, 1); } @@ -16,5 +17,4 @@ public ItemRabbitRaw(Integer meta) { public ItemRabbitRaw(Integer meta, int count) { super(RAW_RABBIT, meta, count, "Raw Rabbit"); } - } diff --git a/src/main/java/cn/nukkit/item/ItemRecord.java b/src/main/java/cn/nukkit/item/ItemRecord.java index 5bf652e4105..b15f7487056 100644 --- a/src/main/java/cn/nukkit/item/ItemRecord.java +++ b/src/main/java/cn/nukkit/item/ItemRecord.java @@ -15,4 +15,8 @@ public int getMaxStackSize() { } public abstract String getSoundId(); + + public String getDiscName() { + return "Unknown"; + } } diff --git a/src/main/java/cn/nukkit/item/ItemRecord11.java b/src/main/java/cn/nukkit/item/ItemRecord11.java index 56f3b8f7a50..f2732c3f100 100644 --- a/src/main/java/cn/nukkit/item/ItemRecord11.java +++ b/src/main/java/cn/nukkit/item/ItemRecord11.java @@ -21,4 +21,9 @@ public ItemRecord11(Integer meta, int count) { public String getSoundId() { return "record.11"; } + + @Override + public String getDiscName() { + return "C418 - 11"; + } } diff --git a/src/main/java/cn/nukkit/item/ItemRecord13.java b/src/main/java/cn/nukkit/item/ItemRecord13.java index 173e8b029fb..bb90dbb5c43 100644 --- a/src/main/java/cn/nukkit/item/ItemRecord13.java +++ b/src/main/java/cn/nukkit/item/ItemRecord13.java @@ -21,4 +21,9 @@ public ItemRecord13(Integer meta, int count) { public String getSoundId() { return "record.13"; } + + @Override + public String getDiscName() { + return "C418 - 13"; + } } diff --git a/src/main/java/cn/nukkit/item/ItemRecord5.java b/src/main/java/cn/nukkit/item/ItemRecord5.java index 7d85876f1f4..b143ceaea05 100644 --- a/src/main/java/cn/nukkit/item/ItemRecord5.java +++ b/src/main/java/cn/nukkit/item/ItemRecord5.java @@ -18,4 +18,9 @@ public ItemRecord5(Integer meta, int count) { public String getSoundId() { return "record.5"; } + + @Override + public String getDiscName() { + return "Samuel Åberg - 5"; + } } diff --git a/src/main/java/cn/nukkit/item/ItemRecordBlocks.java b/src/main/java/cn/nukkit/item/ItemRecordBlocks.java index 00be58db636..4fa73c559c1 100644 --- a/src/main/java/cn/nukkit/item/ItemRecordBlocks.java +++ b/src/main/java/cn/nukkit/item/ItemRecordBlocks.java @@ -21,4 +21,9 @@ public ItemRecordBlocks(Integer meta, int count) { public String getSoundId() { return "record.blocks"; } + + @Override + public String getDiscName() { + return "C418 - blocks"; + } } diff --git a/src/main/java/cn/nukkit/item/ItemRecordCat.java b/src/main/java/cn/nukkit/item/ItemRecordCat.java index 8f4eef89fb9..dd680a4adf1 100644 --- a/src/main/java/cn/nukkit/item/ItemRecordCat.java +++ b/src/main/java/cn/nukkit/item/ItemRecordCat.java @@ -21,4 +21,9 @@ public ItemRecordCat(Integer meta, int count) { public String getSoundId() { return "record.cat"; } + + @Override + public String getDiscName() { + return "C418 - cat"; + } } diff --git a/src/main/java/cn/nukkit/item/ItemRecordChirp.java b/src/main/java/cn/nukkit/item/ItemRecordChirp.java index 82bd15366a9..6d97c5955d1 100644 --- a/src/main/java/cn/nukkit/item/ItemRecordChirp.java +++ b/src/main/java/cn/nukkit/item/ItemRecordChirp.java @@ -21,4 +21,9 @@ public ItemRecordChirp(Integer meta, int count) { public String getSoundId() { return "record.chirp"; } + + @Override + public String getDiscName() { + return "C418 - chirp"; + } } diff --git a/src/main/java/cn/nukkit/item/ItemRecordFar.java b/src/main/java/cn/nukkit/item/ItemRecordFar.java index 9f8d1a29c1c..51b975b2cb5 100644 --- a/src/main/java/cn/nukkit/item/ItemRecordFar.java +++ b/src/main/java/cn/nukkit/item/ItemRecordFar.java @@ -21,4 +21,9 @@ public ItemRecordFar(Integer meta, int count) { public String getSoundId() { return "record.far"; } + + @Override + public String getDiscName() { + return "C418 - far"; + } } diff --git a/src/main/java/cn/nukkit/item/ItemRecordMall.java b/src/main/java/cn/nukkit/item/ItemRecordMall.java index aa49939e6b6..589bcb266fa 100644 --- a/src/main/java/cn/nukkit/item/ItemRecordMall.java +++ b/src/main/java/cn/nukkit/item/ItemRecordMall.java @@ -21,4 +21,9 @@ public ItemRecordMall(Integer meta, int count) { public String getSoundId() { return "record.mall"; } + + @Override + public String getDiscName() { + return "C418 - mall"; + } } diff --git a/src/main/java/cn/nukkit/item/ItemRecordMellohi.java b/src/main/java/cn/nukkit/item/ItemRecordMellohi.java index 9c5119d950b..1875bdce0e5 100644 --- a/src/main/java/cn/nukkit/item/ItemRecordMellohi.java +++ b/src/main/java/cn/nukkit/item/ItemRecordMellohi.java @@ -21,4 +21,9 @@ public ItemRecordMellohi(Integer meta, int count) { public String getSoundId() { return "record.mellohi"; } + + @Override + public String getDiscName() { + return "C418 - mellohi"; + } } diff --git a/src/main/java/cn/nukkit/item/ItemRecordOtherside.java b/src/main/java/cn/nukkit/item/ItemRecordOtherside.java index b662b60b51b..6c8dd7fa922 100644 --- a/src/main/java/cn/nukkit/item/ItemRecordOtherside.java +++ b/src/main/java/cn/nukkit/item/ItemRecordOtherside.java @@ -18,4 +18,9 @@ public ItemRecordOtherside(Integer meta, int count) { public String getSoundId() { return "record.otherside"; } + + @Override + public String getDiscName() { + return "Lena Raine - otherside"; + } } diff --git a/src/main/java/cn/nukkit/item/ItemRecordPigstep.java b/src/main/java/cn/nukkit/item/ItemRecordPigstep.java index 2fb3c523b7e..eb3dc3574c8 100644 --- a/src/main/java/cn/nukkit/item/ItemRecordPigstep.java +++ b/src/main/java/cn/nukkit/item/ItemRecordPigstep.java @@ -1,8 +1,5 @@ package cn.nukkit.item; -/** - * @author PetteriM1 - */ public class ItemRecordPigstep extends ItemRecord { public ItemRecordPigstep() { @@ -21,4 +18,9 @@ public ItemRecordPigstep(Integer meta, int count) { public String getSoundId() { return "record.pigstep"; } + + @Override + public String getDiscName() { + return "Lena Raine - Pigstep"; + } } diff --git a/src/main/java/cn/nukkit/item/ItemRecordRelic.java b/src/main/java/cn/nukkit/item/ItemRecordRelic.java index 2cfede0867c..135610678df 100644 --- a/src/main/java/cn/nukkit/item/ItemRecordRelic.java +++ b/src/main/java/cn/nukkit/item/ItemRecordRelic.java @@ -18,4 +18,9 @@ public ItemRecordRelic(Integer meta, int count) { public String getSoundId() { return "record.relic"; } + + @Override + public String getDiscName() { + return "Aaron Cherof - Relic"; + } } diff --git a/src/main/java/cn/nukkit/item/ItemRecordStal.java b/src/main/java/cn/nukkit/item/ItemRecordStal.java index ec3b623f8d2..0bcdac73cb4 100644 --- a/src/main/java/cn/nukkit/item/ItemRecordStal.java +++ b/src/main/java/cn/nukkit/item/ItemRecordStal.java @@ -21,4 +21,9 @@ public ItemRecordStal(Integer meta, int count) { public String getSoundId() { return "record.stal"; } + + @Override + public String getDiscName() { + return "C418 - stal"; + } } diff --git a/src/main/java/cn/nukkit/item/ItemRecordStrad.java b/src/main/java/cn/nukkit/item/ItemRecordStrad.java index 2edf6eb9b6c..d5f3b879ee2 100644 --- a/src/main/java/cn/nukkit/item/ItemRecordStrad.java +++ b/src/main/java/cn/nukkit/item/ItemRecordStrad.java @@ -21,4 +21,9 @@ public ItemRecordStrad(Integer meta, int count) { public String getSoundId() { return "record.strad"; } + + @Override + public String getDiscName() { + return "C418 - strad"; + } } diff --git a/src/main/java/cn/nukkit/item/ItemRecordWait.java b/src/main/java/cn/nukkit/item/ItemRecordWait.java index 8816d6d8e2e..f1460bc10ad 100644 --- a/src/main/java/cn/nukkit/item/ItemRecordWait.java +++ b/src/main/java/cn/nukkit/item/ItemRecordWait.java @@ -21,4 +21,9 @@ public ItemRecordWait(Integer meta, int count) { public String getSoundId() { return "record.wait"; } + + @Override + public String getDiscName() { + return "C418 - wait"; + } } diff --git a/src/main/java/cn/nukkit/item/ItemRecordWard.java b/src/main/java/cn/nukkit/item/ItemRecordWard.java index 0d65d8fb8df..20cfc64d1f7 100644 --- a/src/main/java/cn/nukkit/item/ItemRecordWard.java +++ b/src/main/java/cn/nukkit/item/ItemRecordWard.java @@ -21,4 +21,9 @@ public ItemRecordWard(Integer meta, int count) { public String getSoundId() { return "record.ward"; } + + @Override + public String getDiscName() { + return "C418 - ward"; + } } diff --git a/src/main/java/cn/nukkit/item/ItemRecoveryCompass.java b/src/main/java/cn/nukkit/item/ItemRecoveryCompass.java new file mode 100644 index 00000000000..1908f883f5c --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemRecoveryCompass.java @@ -0,0 +1,16 @@ +package cn.nukkit.item; + +public class ItemRecoveryCompass extends Item { + + public ItemRecoveryCompass() { + this(0, 1); + } + + public ItemRecoveryCompass(Integer meta) { + this(meta, 1); + } + + public ItemRecoveryCompass(Integer meta, int count) { + super(RECOVERY_COMPASS, meta, count, "Recovery Compass"); + } +} diff --git a/src/main/java/cn/nukkit/item/ItemRedstone.java b/src/main/java/cn/nukkit/item/ItemRedstone.java index 50269f92933..4aae1c8f4a1 100644 --- a/src/main/java/cn/nukkit/item/ItemRedstone.java +++ b/src/main/java/cn/nukkit/item/ItemRedstone.java @@ -1,10 +1,9 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemRedstone extends Item { @@ -19,7 +18,6 @@ public ItemRedstone(Integer meta) { public ItemRedstone(Integer meta, int count) { super(REDSTONE, meta, count, "Redstone Dust"); - this.block = Block.get(BlockID.REDSTONE_WIRE); + this.block = Block.get(REDSTONE_WIRE); } - } diff --git a/src/main/java/cn/nukkit/item/ItemRedstoneComparator.java b/src/main/java/cn/nukkit/item/ItemRedstoneComparator.java index 93e97f24fd4..a6fa2b69f45 100644 --- a/src/main/java/cn/nukkit/item/ItemRedstoneComparator.java +++ b/src/main/java/cn/nukkit/item/ItemRedstoneComparator.java @@ -1,7 +1,6 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; /** * @author CreeperFace @@ -18,6 +17,6 @@ public ItemRedstoneComparator(Integer meta) { public ItemRedstoneComparator(Integer meta, int count) { super(COMPARATOR, meta, count, "Redstone Comparator"); - this.block = Block.get(BlockID.UNPOWERED_COMPARATOR); + this.block = Block.get(UNPOWERED_COMPARATOR); } } \ No newline at end of file diff --git a/src/main/java/cn/nukkit/item/ItemRedstoneRepeater.java b/src/main/java/cn/nukkit/item/ItemRedstoneRepeater.java index 43edb2dcb55..2f3b3bec0de 100644 --- a/src/main/java/cn/nukkit/item/ItemRedstoneRepeater.java +++ b/src/main/java/cn/nukkit/item/ItemRedstoneRepeater.java @@ -1,7 +1,6 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; /** * @author CreeperFace @@ -18,6 +17,6 @@ public ItemRedstoneRepeater(Integer meta) { public ItemRedstoneRepeater(Integer meta, int count) { super(REPEATER, meta, count, "Redstone Repeater"); - this.block = Block.get(BlockID.UNPOWERED_REPEATER); + this.block = Block.get(UNPOWERED_REPEATER); } } diff --git a/src/main/java/cn/nukkit/item/ItemRottenFlesh.java b/src/main/java/cn/nukkit/item/ItemRottenFlesh.java index 58cbc7f2aad..cf8a3cdfdf9 100644 --- a/src/main/java/cn/nukkit/item/ItemRottenFlesh.java +++ b/src/main/java/cn/nukkit/item/ItemRottenFlesh.java @@ -17,5 +17,4 @@ public ItemRottenFlesh(Integer meta) { public ItemRottenFlesh(Integer meta, int count) { super(ROTTEN_FLESH, meta, count, "Rotten Flesh"); } - } diff --git a/src/main/java/cn/nukkit/item/ItemSaddle.java b/src/main/java/cn/nukkit/item/ItemSaddle.java index 7251554acb4..e83635e1635 100644 --- a/src/main/java/cn/nukkit/item/ItemSaddle.java +++ b/src/main/java/cn/nukkit/item/ItemSaddle.java @@ -1,12 +1,13 @@ package cn.nukkit.item; public class ItemSaddle extends Item { + public ItemSaddle() { - this(0, 0); + this(0, 1); } public ItemSaddle(Integer meta) { - this(meta, 0); + this(meta, 1); } public ItemSaddle(Integer meta, int count) { diff --git a/src/main/java/cn/nukkit/item/ItemSalmon.java b/src/main/java/cn/nukkit/item/ItemSalmon.java index 59a1a7a0488..6a58bf85b6b 100644 --- a/src/main/java/cn/nukkit/item/ItemSalmon.java +++ b/src/main/java/cn/nukkit/item/ItemSalmon.java @@ -17,5 +17,4 @@ public ItemSalmon(Integer meta) { public ItemSalmon(Integer meta, int count) { super(RAW_SALMON, meta, count, "Raw Salmon"); } - } diff --git a/src/main/java/cn/nukkit/item/ItemSalmonCooked.java b/src/main/java/cn/nukkit/item/ItemSalmonCooked.java index e1277102226..c9a4509dae8 100644 --- a/src/main/java/cn/nukkit/item/ItemSalmonCooked.java +++ b/src/main/java/cn/nukkit/item/ItemSalmonCooked.java @@ -17,5 +17,4 @@ public ItemSalmonCooked(Integer meta) { public ItemSalmonCooked(Integer meta, int count) { super(COOKED_SALMON, meta, count, "Cooked Salmon"); } - } diff --git a/src/main/java/cn/nukkit/item/ItemSeedsBeetroot.java b/src/main/java/cn/nukkit/item/ItemSeedsBeetroot.java index ef6d9d9c51c..94f91a3cc00 100644 --- a/src/main/java/cn/nukkit/item/ItemSeedsBeetroot.java +++ b/src/main/java/cn/nukkit/item/ItemSeedsBeetroot.java @@ -1,10 +1,9 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemSeedsBeetroot extends Item { @@ -19,6 +18,6 @@ public ItemSeedsBeetroot(Integer meta) { public ItemSeedsBeetroot(Integer meta, int count) { super(BEETROOT_SEEDS, 0, count, "Beetroot Seeds"); - this.block = Block.get(BlockID.BEETROOT_BLOCK); + this.block = Block.get(BEETROOT_BLOCK); } } diff --git a/src/main/java/cn/nukkit/item/ItemSeedsMelon.java b/src/main/java/cn/nukkit/item/ItemSeedsMelon.java index 44b2fa2f8d4..773f93e0a8e 100644 --- a/src/main/java/cn/nukkit/item/ItemSeedsMelon.java +++ b/src/main/java/cn/nukkit/item/ItemSeedsMelon.java @@ -1,10 +1,9 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemSeedsMelon extends Item { @@ -19,6 +18,6 @@ public ItemSeedsMelon(Integer meta) { public ItemSeedsMelon(Integer meta, int count) { super(MELON_SEEDS, 0, count, "Melon Seeds"); - this.block = Block.get(BlockID.MELON_STEM); + this.block = Block.get(MELON_STEM); } } diff --git a/src/main/java/cn/nukkit/item/ItemSeedsPumpkin.java b/src/main/java/cn/nukkit/item/ItemSeedsPumpkin.java index 8f3452b5419..416c89a7f73 100644 --- a/src/main/java/cn/nukkit/item/ItemSeedsPumpkin.java +++ b/src/main/java/cn/nukkit/item/ItemSeedsPumpkin.java @@ -1,10 +1,9 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemSeedsPumpkin extends Item { @@ -19,6 +18,6 @@ public ItemSeedsPumpkin(Integer meta) { public ItemSeedsPumpkin(Integer meta, int count) { super(PUMPKIN_SEEDS, 0, count, "Pumpkin Seeds"); - this.block = Block.get(BlockID.PUMPKIN_STEM); + this.block = Block.get(PUMPKIN_STEM); } } diff --git a/src/main/java/cn/nukkit/item/ItemSeedsWheat.java b/src/main/java/cn/nukkit/item/ItemSeedsWheat.java index cf37b8b46a1..d4f18ede800 100644 --- a/src/main/java/cn/nukkit/item/ItemSeedsWheat.java +++ b/src/main/java/cn/nukkit/item/ItemSeedsWheat.java @@ -1,10 +1,9 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemSeedsWheat extends Item { @@ -18,7 +17,7 @@ public ItemSeedsWheat(Integer meta) { } public ItemSeedsWheat(Integer meta, int count) { - super(WHEAT_SEEDS, 0, count, "Wheat Seeds"); - this.block = Block.get(BlockID.WHEAT_BLOCK); + super(WHEAT_SEEDS, 0, count, "Seeds"); + this.block = Block.get(WHEAT_BLOCK); } } diff --git a/src/main/java/cn/nukkit/item/ItemShears.java b/src/main/java/cn/nukkit/item/ItemShears.java index f09a5b9b6d6..708874a8cf0 100644 --- a/src/main/java/cn/nukkit/item/ItemShears.java +++ b/src/main/java/cn/nukkit/item/ItemShears.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemShears extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemShield.java b/src/main/java/cn/nukkit/item/ItemShield.java index 621d18d3906..f573d30d16b 100644 --- a/src/main/java/cn/nukkit/item/ItemShield.java +++ b/src/main/java/cn/nukkit/item/ItemShield.java @@ -1,6 +1,6 @@ package cn.nukkit.item; -public class ItemShield extends Item { +public class ItemShield extends ItemTool { public ItemShield() { this(0, 1); @@ -15,7 +15,17 @@ public ItemShield(Integer meta, int count) { } @Override - public int getMaxStackSize() { - return 1; + public int getMaxDurability() { + return 337; + } + + @Override + public boolean noDamageOnAttack() { + return true; + } + + @Override + public boolean allowOffhand() { + return true; } } diff --git a/src/main/java/cn/nukkit/item/ItemShovelDiamond.java b/src/main/java/cn/nukkit/item/ItemShovelDiamond.java index d4b35b25bcb..cc44d0f0519 100644 --- a/src/main/java/cn/nukkit/item/ItemShovelDiamond.java +++ b/src/main/java/cn/nukkit/item/ItemShovelDiamond.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemShovelDiamond extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemShovelGold.java b/src/main/java/cn/nukkit/item/ItemShovelGold.java index 1b4f3e351b7..e31d0ae2c40 100644 --- a/src/main/java/cn/nukkit/item/ItemShovelGold.java +++ b/src/main/java/cn/nukkit/item/ItemShovelGold.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemShovelGold extends ItemTool { @@ -15,7 +15,7 @@ public ItemShovelGold(Integer meta) { } public ItemShovelGold(Integer meta, int count) { - super(GOLD_SHOVEL, meta, count, "Gold Shovel"); + super(GOLD_SHOVEL, meta, count, "Golden Shovel"); } @Override @@ -32,9 +32,4 @@ public boolean isShovel() { public int getTier() { return ItemTool.TIER_GOLD; } - - @Override - public int getAttackDamage() { - return 1; - } } diff --git a/src/main/java/cn/nukkit/item/ItemShovelIron.java b/src/main/java/cn/nukkit/item/ItemShovelIron.java index d0ae0b630d8..a3b7c327db7 100644 --- a/src/main/java/cn/nukkit/item/ItemShovelIron.java +++ b/src/main/java/cn/nukkit/item/ItemShovelIron.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemShovelIron extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemShovelStone.java b/src/main/java/cn/nukkit/item/ItemShovelStone.java index f7465c1803d..b331669309e 100644 --- a/src/main/java/cn/nukkit/item/ItemShovelStone.java +++ b/src/main/java/cn/nukkit/item/ItemShovelStone.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemShovelStone extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemShovelWood.java b/src/main/java/cn/nukkit/item/ItemShovelWood.java index e202dfd4f32..01676b54310 100644 --- a/src/main/java/cn/nukkit/item/ItemShovelWood.java +++ b/src/main/java/cn/nukkit/item/ItemShovelWood.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemShovelWood extends ItemTool { @@ -32,9 +32,4 @@ public boolean isShovel() { public int getTier() { return ItemTool.TIER_WOODEN; } - - @Override - public int getAttackDamage() { - return 1; - } } diff --git a/src/main/java/cn/nukkit/item/ItemSign.java b/src/main/java/cn/nukkit/item/ItemSign.java index 7063c55b055..ef4f3189426 100644 --- a/src/main/java/cn/nukkit/item/ItemSign.java +++ b/src/main/java/cn/nukkit/item/ItemSign.java @@ -1,10 +1,9 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemSign extends Item { @@ -18,8 +17,8 @@ public ItemSign(Integer meta) { } public ItemSign(Integer meta, int count) { - super(SIGN, 0, count, "Sign"); - this.block = Block.get(BlockID.SIGN_POST); + super(SIGN, 0, count, "Oak Sign"); + this.block = Block.get(SIGN_POST); } @Override diff --git a/src/main/java/cn/nukkit/item/ItemSignAcacia.java b/src/main/java/cn/nukkit/item/ItemSignAcacia.java new file mode 100644 index 00000000000..39cccde814e --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemSignAcacia.java @@ -0,0 +1,29 @@ +package cn.nukkit.item; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; + +/** + * @author MagicDroidX + * Nukkit Project + */ +public class ItemSignAcacia extends Item { + + public ItemSignAcacia() { + this(0, 1); + } + + public ItemSignAcacia(Integer meta) { + this(meta, 1); + } + + public ItemSignAcacia(Integer meta, int count) { + super(ACACIA_SIGN, 0, count, "Acacia Sign"); + this.block = Block.get(BlockID.ACACIA_STANDING_SIGN); + } + + @Override + public int getMaxStackSize() { + return 16; + } +} diff --git a/src/main/java/cn/nukkit/item/ItemSignBirch.java b/src/main/java/cn/nukkit/item/ItemSignBirch.java new file mode 100644 index 00000000000..17899100e35 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemSignBirch.java @@ -0,0 +1,29 @@ +package cn.nukkit.item; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; + +/** + * @author MagicDroidX + * Nukkit Project + */ +public class ItemSignBirch extends Item { + + public ItemSignBirch() { + this(0, 1); + } + + public ItemSignBirch(Integer meta) { + this(meta, 1); + } + + public ItemSignBirch(Integer meta, int count) { + super(BIRCH_SIGN, 0, count, "BirchSign"); + this.block = Block.get(BlockID.BIRCH_STANDING_SIGN); + } + + @Override + public int getMaxStackSize() { + return 16; + } +} diff --git a/src/main/java/cn/nukkit/item/ItemSignCrimson.java b/src/main/java/cn/nukkit/item/ItemSignCrimson.java new file mode 100644 index 00000000000..5e9eb1eab69 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemSignCrimson.java @@ -0,0 +1,25 @@ +package cn.nukkit.item; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; + +public class ItemSignCrimson extends Item { + + public ItemSignCrimson() { + this(0, 1); + } + + public ItemSignCrimson(Integer meta) { + this(meta, 1); + } + + public ItemSignCrimson(Integer meta, int count) { + super(CRIMSON_SIGN, 0, count, "Crimson Sign"); + this.block = Block.get(BlockID.CRIMSON_STANDING_SIGN); + } + + @Override + public int getMaxStackSize() { + return 16; + } +} diff --git a/src/main/java/cn/nukkit/item/ItemSignDarkOak.java b/src/main/java/cn/nukkit/item/ItemSignDarkOak.java new file mode 100644 index 00000000000..9315e2f962f --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemSignDarkOak.java @@ -0,0 +1,28 @@ +package cn.nukkit.item; + +import cn.nukkit.block.Block; + +/** + * @author MagicDroidX + * Nukkit Project + */ +public class ItemSignDarkOak extends Item { + + public ItemSignDarkOak() { + this(0, 1); + } + + public ItemSignDarkOak(Integer meta) { + this(meta, 1); + } + + public ItemSignDarkOak(Integer meta, int count) { + super(DARKOAK_SIGN, 0, count, "Dark Oak Sign"); + this.block = Block.get(DARK_OAK_STANDING_SIGN); + } + + @Override + public int getMaxStackSize() { + return 16; + } +} diff --git a/src/main/java/cn/nukkit/item/ItemSignJungle.java b/src/main/java/cn/nukkit/item/ItemSignJungle.java new file mode 100644 index 00000000000..a9ee4116b30 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemSignJungle.java @@ -0,0 +1,29 @@ +package cn.nukkit.item; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; + +/** + * @author MagicDroidX + * Nukkit Project + */ +public class ItemSignJungle extends Item { + + public ItemSignJungle() { + this(0, 1); + } + + public ItemSignJungle(Integer meta) { + this(meta, 1); + } + + public ItemSignJungle(Integer meta, int count) { + super(JUNGLE_SIGN, 0, count, "Jungle Sign"); + this.block = Block.get(BlockID.JUNGLE_STANDING_SIGN); + } + + @Override + public int getMaxStackSize() { + return 16; + } +} diff --git a/src/main/java/cn/nukkit/item/ItemSignSpruce.java b/src/main/java/cn/nukkit/item/ItemSignSpruce.java new file mode 100644 index 00000000000..b622e0a0572 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemSignSpruce.java @@ -0,0 +1,29 @@ +package cn.nukkit.item; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; + +/** + * @author MagicDroidX + * Nukkit Project + */ +public class ItemSignSpruce extends Item { + + public ItemSignSpruce() { + this(0, 1); + } + + public ItemSignSpruce(Integer meta) { + this(meta, 1); + } + + public ItemSignSpruce(Integer meta, int count) { + super(SPRUCE_SIGN, 0, count, "Spruce Sign"); + this.block = Block.get(BlockID.SPRUCE_STANDING_SIGN); + } + + @Override + public int getMaxStackSize() { + return 16; + } +} diff --git a/src/main/java/cn/nukkit/item/ItemSignWarped.java b/src/main/java/cn/nukkit/item/ItemSignWarped.java new file mode 100644 index 00000000000..4cc018025d1 --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemSignWarped.java @@ -0,0 +1,25 @@ +package cn.nukkit.item; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; + +public class ItemSignWarped extends Item { + + public ItemSignWarped() { + this(0, 1); + } + + public ItemSignWarped(Integer meta) { + this(meta, 1); + } + + public ItemSignWarped(Integer meta, int count) { + super(WARPED_SIGN, 0, count, "Warped Sign"); + this.block = Block.get(BlockID.WARPED_STANDING_SIGN); + } + + @Override + public int getMaxStackSize() { + return 16; + } +} diff --git a/src/main/java/cn/nukkit/item/ItemSkull.java b/src/main/java/cn/nukkit/item/ItemSkull.java index ee79602f8d5..982e23cee9f 100644 --- a/src/main/java/cn/nukkit/item/ItemSkull.java +++ b/src/main/java/cn/nukkit/item/ItemSkull.java @@ -1,6 +1,10 @@ package cn.nukkit.item; import cn.nukkit.block.Block; +import cn.nukkit.entity.mob.EntityCreeper; +import cn.nukkit.entity.mob.EntitySkeleton; +import cn.nukkit.entity.mob.EntityWitherSkeleton; +import cn.nukkit.entity.mob.EntityZombie; /** * Created by Snake1999 on 2016/2/3. @@ -48,4 +52,24 @@ public static String getItemSkullName(int meta) { return "Skeleton Skull"; } } + + @Override + public boolean canBePutInHelmetSlot() { + return true; + } + + public static Item getMobHead(int networkId) { + switch (networkId) { + case EntitySkeleton.NETWORK_ID: + return Item.get(SKULL, SKELETON_SKULL, 1); + case EntityWitherSkeleton.NETWORK_ID: + return Item.get(SKULL, WITHER_SKELETON_SKULL, 1); + case EntityZombie.NETWORK_ID: + return Item.get(SKULL, ZOMBIE_HEAD, 1); + case EntityCreeper.NETWORK_ID: + return Item.get(SKULL, CREEPER_HEAD, 1); + default: + return null; + } + } } diff --git a/src/main/java/cn/nukkit/item/ItemSlimeball.java b/src/main/java/cn/nukkit/item/ItemSlimeball.java index 1bfd0969261..1546ed99ebd 100644 --- a/src/main/java/cn/nukkit/item/ItemSlimeball.java +++ b/src/main/java/cn/nukkit/item/ItemSlimeball.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemSlimeball extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemSnowball.java b/src/main/java/cn/nukkit/item/ItemSnowball.java index ae6a5a2740e..83023ee88bb 100644 --- a/src/main/java/cn/nukkit/item/ItemSnowball.java +++ b/src/main/java/cn/nukkit/item/ItemSnowball.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemSnowball extends ProjectileItem { diff --git a/src/main/java/cn/nukkit/item/ItemSpawnEgg.java b/src/main/java/cn/nukkit/item/ItemSpawnEgg.java index 3afd9eb6440..f02e4f7ef67 100644 --- a/src/main/java/cn/nukkit/item/ItemSpawnEgg.java +++ b/src/main/java/cn/nukkit/item/ItemSpawnEgg.java @@ -2,9 +2,15 @@ import cn.nukkit.Player; import cn.nukkit.block.Block; +import cn.nukkit.block.BlockMobSpawner; +import cn.nukkit.entity.BaseEntity; import cn.nukkit.entity.Entity; +import cn.nukkit.entity.mob.EntityZombie; +import cn.nukkit.entity.passive.EntityChicken; +import cn.nukkit.entity.passive.EntityCow; +import cn.nukkit.entity.passive.EntityPig; +import cn.nukkit.entity.passive.EntitySheep; import cn.nukkit.event.entity.CreatureSpawnEvent; -import cn.nukkit.event.entity.CreatureSpawnEvent.SpawnReason; import cn.nukkit.level.Level; import cn.nukkit.level.format.FullChunk; import cn.nukkit.math.BlockFace; @@ -12,11 +18,12 @@ import cn.nukkit.nbt.tag.DoubleTag; import cn.nukkit.nbt.tag.FloatTag; import cn.nukkit.nbt.tag.ListTag; +import cn.nukkit.utils.Utils; -import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemSpawnEgg extends Item { @@ -30,7 +37,7 @@ public ItemSpawnEgg(Integer meta) { } public ItemSpawnEgg(Integer meta, int count) { - super(SPAWN_EGG, meta, count, "Spawn EntityEgg"); + super(SPAWN_EGG, meta, count, "Spawn Entity Egg"); } @Override @@ -44,6 +51,10 @@ public boolean onActivate(Level level, Player player, Block block, Block target, return false; } + if (target instanceof BlockMobSpawner) { + return false; + } + FullChunk chunk = level.getChunk((int) block.getX() >> 4, (int) block.getZ() >> 4); if (chunk == null) { @@ -60,14 +71,14 @@ public boolean onActivate(Level level, Player player, Block block, Block target, .add(new DoubleTag("", 0)) .add(new DoubleTag("", 0))) .putList(new ListTag("Rotation") - .add(new FloatTag("", new Random().nextFloat() * 360)) + .add(new FloatTag("", ThreadLocalRandom.current().nextFloat() * 360)) .add(new FloatTag("", 0))); if (this.hasCustomName()) { nbt.putString("CustomName", this.getCustomName()); } - CreatureSpawnEvent ev = new CreatureSpawnEvent(this.meta, block, nbt, SpawnReason.SPAWN_EGG); + CreatureSpawnEvent ev = new CreatureSpawnEvent(this.meta, block, nbt, CreatureSpawnEvent.SpawnReason.SPAWN_EGG); level.getServer().getPluginManager().callEvent(ev); if (ev.isCancelled()) { @@ -77,13 +88,24 @@ public boolean onActivate(Level level, Player player, Block block, Block target, Entity entity = Entity.createEntity(this.meta, chunk, nbt); if (entity != null) { - if (player.isSurvival()) { - player.getInventory().decreaseCount(player.getInventory().getHeldItemIndex()); + if (!player.isCreative()) { + this.count--; } + entity.spawnToAll(); + + if (Utils.rand(1, 20) == 1 && + (entity instanceof EntityCow || + entity instanceof EntityChicken || + entity instanceof EntityPig || + entity instanceof EntitySheep || + entity instanceof EntityZombie)) { + + ((BaseEntity) entity).setBaby(true); + } + return true; } - return false; } } diff --git a/src/main/java/cn/nukkit/item/ItemSpiderEye.java b/src/main/java/cn/nukkit/item/ItemSpiderEye.java index 470087ddbdf..df40c18ecbb 100644 --- a/src/main/java/cn/nukkit/item/ItemSpiderEye.java +++ b/src/main/java/cn/nukkit/item/ItemSpiderEye.java @@ -1,4 +1,5 @@ package cn.nukkit.item; + /** * Created by Snake1999 on 2016/1/14. * Package cn.nukkit.item in project nukkit. diff --git a/src/main/java/cn/nukkit/item/ItemSpiderEyeFermented.java b/src/main/java/cn/nukkit/item/ItemSpiderEyeFermented.java index 0c28ea55c30..56b6cfd2f76 100644 --- a/src/main/java/cn/nukkit/item/ItemSpiderEyeFermented.java +++ b/src/main/java/cn/nukkit/item/ItemSpiderEyeFermented.java @@ -6,14 +6,14 @@ public class ItemSpiderEyeFermented extends Item { public ItemSpiderEyeFermented() { - this(0); + this(0, 1); } public ItemSpiderEyeFermented(Integer meta) { - this(0, 1); + this(meta, 1); } public ItemSpiderEyeFermented(Integer meta, int count) { - super(FERMENTED_SPIDER_EYE, meta, count, "Fermented Spider Eye"); + super(FERMENTED_SPIDER_EYE, 0, count, "Fermented Spider Eye"); } } diff --git a/src/main/java/cn/nukkit/item/ItemSteak.java b/src/main/java/cn/nukkit/item/ItemSteak.java index d35dc202976..295804dfe1a 100644 --- a/src/main/java/cn/nukkit/item/ItemSteak.java +++ b/src/main/java/cn/nukkit/item/ItemSteak.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemSteak extends ItemEdible { diff --git a/src/main/java/cn/nukkit/item/ItemStick.java b/src/main/java/cn/nukkit/item/ItemStick.java index da3ffd88286..6b667805f47 100644 --- a/src/main/java/cn/nukkit/item/ItemStick.java +++ b/src/main/java/cn/nukkit/item/ItemStick.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemStick extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemString.java b/src/main/java/cn/nukkit/item/ItemString.java index b619a255d18..7d57b8c4612 100644 --- a/src/main/java/cn/nukkit/item/ItemString.java +++ b/src/main/java/cn/nukkit/item/ItemString.java @@ -1,10 +1,9 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemString extends Item { @@ -19,6 +18,6 @@ public ItemString(Integer meta) { public ItemString(Integer meta, int count) { super(STRING, meta, count, "String"); - this.block = Block.get(BlockID.TRIPWIRE); + this.block = Block.get(TRIPWIRE); } } diff --git a/src/main/java/cn/nukkit/item/ItemSugar.java b/src/main/java/cn/nukkit/item/ItemSugar.java index d3476eb47d2..e9f8866e17f 100644 --- a/src/main/java/cn/nukkit/item/ItemSugar.java +++ b/src/main/java/cn/nukkit/item/ItemSugar.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemSugar extends Item { diff --git a/src/main/java/cn/nukkit/item/ItemSugarcane.java b/src/main/java/cn/nukkit/item/ItemSugarcane.java index f87632ea105..9111f9ea44a 100644 --- a/src/main/java/cn/nukkit/item/ItemSugarcane.java +++ b/src/main/java/cn/nukkit/item/ItemSugarcane.java @@ -1,10 +1,9 @@ package cn.nukkit.item; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemSugarcane extends Item { @@ -18,7 +17,7 @@ public ItemSugarcane(Integer meta) { } public ItemSugarcane(Integer meta, int count) { - super(SUGARCANE, 0, count, "Sugar Cane"); - this.block = Block.get(BlockID.SUGARCANE_BLOCK); + super(SUGARCANE, 0, count, "Sugar Canes"); + this.block = Block.get(SUGARCANE_BLOCK); } } diff --git a/src/main/java/cn/nukkit/item/ItemSweetBerries.java b/src/main/java/cn/nukkit/item/ItemSweetBerries.java index 181322bc64f..80510fe301e 100644 --- a/src/main/java/cn/nukkit/item/ItemSweetBerries.java +++ b/src/main/java/cn/nukkit/item/ItemSweetBerries.java @@ -1,5 +1,7 @@ package cn.nukkit.item; +import cn.nukkit.block.Block; + public class ItemSweetBerries extends ItemEdible { public ItemSweetBerries() { @@ -12,5 +14,6 @@ public ItemSweetBerries(Integer meta) { public ItemSweetBerries(Integer meta, int count) { super(SWEET_BERRIES, meta, count, "Sweet Berries"); + this.block = Block.get(SWEET_BERRY_BUSH); } } diff --git a/src/main/java/cn/nukkit/item/ItemSwordDiamond.java b/src/main/java/cn/nukkit/item/ItemSwordDiamond.java index fab4b7c33bc..9ed70071dda 100644 --- a/src/main/java/cn/nukkit/item/ItemSwordDiamond.java +++ b/src/main/java/cn/nukkit/item/ItemSwordDiamond.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemSwordDiamond extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemSwordGold.java b/src/main/java/cn/nukkit/item/ItemSwordGold.java index 5c39ec59b41..d9248c2a764 100644 --- a/src/main/java/cn/nukkit/item/ItemSwordGold.java +++ b/src/main/java/cn/nukkit/item/ItemSwordGold.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemSwordGold extends ItemTool { @@ -15,7 +15,7 @@ public ItemSwordGold(Integer meta) { } public ItemSwordGold(Integer meta, int count) { - super(GOLD_SWORD, meta, count, "Gold Sword"); + super(GOLD_SWORD, meta, count, "Golden Sword"); } @Override diff --git a/src/main/java/cn/nukkit/item/ItemSwordIron.java b/src/main/java/cn/nukkit/item/ItemSwordIron.java index 508a206f2bc..282e7eaee07 100644 --- a/src/main/java/cn/nukkit/item/ItemSwordIron.java +++ b/src/main/java/cn/nukkit/item/ItemSwordIron.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemSwordIron extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemSwordStone.java b/src/main/java/cn/nukkit/item/ItemSwordStone.java index cbe9d85f7ec..34c1fa0146e 100644 --- a/src/main/java/cn/nukkit/item/ItemSwordStone.java +++ b/src/main/java/cn/nukkit/item/ItemSwordStone.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemSwordStone extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemSwordWood.java b/src/main/java/cn/nukkit/item/ItemSwordWood.java index 8dba4ad4c09..7725fe6d5c3 100644 --- a/src/main/java/cn/nukkit/item/ItemSwordWood.java +++ b/src/main/java/cn/nukkit/item/ItemSwordWood.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemSwordWood extends ItemTool { diff --git a/src/main/java/cn/nukkit/item/ItemTool.java b/src/main/java/cn/nukkit/item/ItemTool.java index 8e8602857d1..afbb283eafd 100644 --- a/src/main/java/cn/nukkit/item/ItemTool.java +++ b/src/main/java/cn/nukkit/item/ItemTool.java @@ -3,16 +3,14 @@ import cn.nukkit.block.Block; import cn.nukkit.entity.Entity; import cn.nukkit.item.enchantment.Enchantment; -import cn.nukkit.nbt.tag.ByteTag; -import cn.nukkit.nbt.tag.Tag; - -import java.util.Random; +import cn.nukkit.utils.Utils; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class ItemTool extends Item implements ItemDurable { + public static final int TIER_WOODEN = 1; public static final int TIER_GOLD = 2; public static final int TIER_STONE = 3; @@ -28,6 +26,7 @@ public abstract class ItemTool extends Item implements ItemDurable { public static final int TYPE_SHEARS = 5; public static final int TYPE_HOE = 6; + // Using vanilla durability + 1 here public static final int DURABILITY_WOODEN = 60; public static final int DURABILITY_GOLD = 33; public static final int DURABILITY_STONE = 132; @@ -37,10 +36,10 @@ public abstract class ItemTool extends Item implements ItemDurable { public static final int DURABILITY_FLINT_STEEL = 65; public static final int DURABILITY_SHEARS = 239; public static final int DURABILITY_BOW = 385; - public static final int DURABILITY_TRIDENT = 251; - public static final int DURABILITY_FISHING_ROD = 65; public static final int DURABILITY_CROSSBOW = 465; - public static final int DURABILITY_CARROT_ON_A_STICK = 25; + public static final int DURABILITY_TRIDENT = 251; + public static final int DURABILITY_FISHING_ROD = 385; + public static final int DURABILITY_CARROT_ON_A_STICK = 26; public static final int DURABILITY_WARPED_FUNGUS_ON_A_STICK = 100; public ItemTool(int id) { @@ -66,7 +65,7 @@ public int getMaxStackSize() { @Override public boolean useOn(Block block) { - if (this.isUnbreakable() || isDurable() || noDamageOnBreak()) { + if (this.noDamageOnBreak() || this.isUnbreakable() || this.isDurable()) { return true; } @@ -78,7 +77,7 @@ public boolean useOn(Block block) { block.getToolType() == ItemTool.TYPE_SHEARS && this.isShears() ) { this.meta++; - } else if (!this.isShears() && block.getBreakTime(this) > 0) { + } else if (this.isSword() && block.getHardness() > 0) { this.meta += 2; } else if (this.isHoe()) { if (block.getId() == GRASS || block.getId() == DIRT) { @@ -92,7 +91,7 @@ public boolean useOn(Block block) { @Override public boolean useOn(Entity entity) { - if (this.isUnbreakable() || isDurable() || noDamageOnAttack()) { + if (this.noDamageOnAttack() || this.isUnbreakable() || this.isDurable()) { return true; } @@ -106,48 +105,8 @@ public boolean useOn(Entity entity) { } private boolean isDurable() { - if (!hasEnchantments()) { - return false; - } - Enchantment durability = getEnchantment(Enchantment.ID_DURABILITY); - return durability != null && durability.getLevel() > 0 && (100 / (durability.getLevel() + 1)) <= new Random().nextInt(100); - } - - @Override - public boolean isUnbreakable() { - Tag tag = this.getNamedTagEntry("Unbreakable"); - return tag instanceof ByteTag && ((ByteTag) tag).data > 0; - } - - @Override - public boolean isPickaxe() { - return false; - } - - @Override - public boolean isAxe() { - return false; - } - - @Override - public boolean isSword() { - return false; - } - - @Override - public boolean isShovel() { - return false; - } - - @Override - public boolean isHoe() { - return false; - } - - @Override - public boolean isShears() { - return (this.id == SHEARS); + return durability != null && durability.getLevel() > 0 && (100 / (durability.getLevel() + 1)) <= Utils.random.nextInt(100); } @Override @@ -168,6 +127,8 @@ public int getEnchantAbility() { return 22; case TIER_IRON: return 14; + case TIER_NETHERITE: + return 10; //TODO } return 0; diff --git a/src/main/java/cn/nukkit/item/ItemTotem.java b/src/main/java/cn/nukkit/item/ItemTotem.java index e7330a41bd9..142de7a3192 100644 --- a/src/main/java/cn/nukkit/item/ItemTotem.java +++ b/src/main/java/cn/nukkit/item/ItemTotem.java @@ -1,7 +1,7 @@ package cn.nukkit.item; public class ItemTotem extends Item { - + public ItemTotem(Integer meta) { this(meta, 1); } @@ -14,4 +14,9 @@ public ItemTotem(Integer meta, int count) { public int getMaxStackSize() { return 1; } + + @Override + public boolean allowOffhand() { + return true; + } } diff --git a/src/main/java/cn/nukkit/item/ItemTrident.java b/src/main/java/cn/nukkit/item/ItemTrident.java index 99b23ca2862..5af7c72fcef 100644 --- a/src/main/java/cn/nukkit/item/ItemTrident.java +++ b/src/main/java/cn/nukkit/item/ItemTrident.java @@ -2,9 +2,13 @@ import cn.nukkit.Player; import cn.nukkit.Server; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockWater; +import cn.nukkit.entity.projectile.EntityProjectile; import cn.nukkit.entity.projectile.EntityThrownTrident; import cn.nukkit.event.entity.EntityShootBowEvent; import cn.nukkit.event.entity.ProjectileLaunchEvent; +import cn.nukkit.event.player.PlayerToggleSpinAttackEvent; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.math.Vector3; import cn.nukkit.nbt.tag.CompoundTag; @@ -13,9 +17,6 @@ import cn.nukkit.nbt.tag.ListTag; import cn.nukkit.network.protocol.LevelSoundEventPacket; -/** - * Created by PetteriM1 - */ public class ItemTrident extends ItemTool { public ItemTrident() { @@ -52,7 +53,46 @@ public boolean onClickAir(Player player, Vector3 directionVector) { @Override public boolean onRelease(Player player, int ticksUsed) { - if (this.hasEnchantment(Enchantment.ID_TRIDENT_RIPTIDE)) { + Enchantment riptide = this.getEnchantment(Enchantment.ID_TRIDENT_RIPTIDE); + if (riptide != null) { + PlayerToggleSpinAttackEvent playerToggleSpinAttackEvent = new PlayerToggleSpinAttackEvent(player, true); + + int riptideLevel = riptide.getLevel(); + if (riptideLevel < 1) { + playerToggleSpinAttackEvent.setCancelled(true); + } else { + boolean inWater = false; + for (Block block : player.getCollisionBlocks()) { + if (block instanceof BlockWater || block.level.isBlockWaterloggedAt(player.chunk, (int) block.x, (int) block.y, (int) block.z)) { + inWater = true; + break; + } + } + if (!(inWater || (player.getLevel().isRaining() && player.canSeeSky()))) { + playerToggleSpinAttackEvent.setCancelled(true); + } + } + + player.getServer().getPluginManager().callEvent(playerToggleSpinAttackEvent); + + if (playerToggleSpinAttackEvent.isCancelled()) { + player.setNeedSendData(true); + } else { + player.onSpinAttack(riptideLevel); + player.setSpinAttack(true); + player.resetFallDistance(); + + int riptideSound; + if (riptideLevel >= 3) { + riptideSound = LevelSoundEventPacket.SOUND_ITEM_TRIDENT_RIPTIDE_3; + } else if (riptideLevel == 2) { + riptideSound = LevelSoundEventPacket.SOUND_ITEM_TRIDENT_RIPTIDE_2; + } else { + riptideSound = LevelSoundEventPacket.SOUND_ITEM_TRIDENT_RIPTIDE_1; + } + + player.getLevel().addLevelSoundEvent(player, riptideSound); + } return true; } @@ -71,9 +111,17 @@ public boolean onRelease(Player player, int ticksUsed) { .add(new FloatTag("", (player.yaw > 180 ? 360 : 0) - (float) player.yaw)) .add(new FloatTag("", (float) -player.pitch))); - EntityThrownTrident trident = new EntityThrownTrident(player.chunk, nbt, player); + EntityThrownTrident trident = (EntityThrownTrident) EntityThrownTrident.createEntity(EntityThrownTrident.NETWORK_ID, player.chunk, nbt, player); trident.setItem(this); + if (player.isCreative()) { + trident.setPickupMode(EntityProjectile.PICKUP_CREATIVE); + } + + if (this.hasEnchantment(Enchantment.ID_TRIDENT_LOYALTY)) { + trident.setFavoredSlot(player.getInventory().getHeldItemIndex()); + } + double p = (double) ticksUsed / 20; double f = Math.min((p * p + p * 2) / 3, 1) * 2.5; diff --git a/src/main/java/cn/nukkit/item/ItemTurtleShell.java b/src/main/java/cn/nukkit/item/ItemTurtleShell.java index d2c2d1c9cd8..5d4fd03b0df 100644 --- a/src/main/java/cn/nukkit/item/ItemTurtleShell.java +++ b/src/main/java/cn/nukkit/item/ItemTurtleShell.java @@ -1,8 +1,5 @@ package cn.nukkit.item; -/** - * Created by PetteriM1 - */ public class ItemTurtleShell extends ItemArmor { public ItemTurtleShell() { @@ -36,9 +33,4 @@ public int getArmorPoints() { public int getMaxDurability() { return 276; } - - @Override - public int getToughness() { - return 2; - } } diff --git a/src/main/java/cn/nukkit/item/ItemTypes.java b/src/main/java/cn/nukkit/item/ItemTypes.java new file mode 100644 index 00000000000..53bce9e96da --- /dev/null +++ b/src/main/java/cn/nukkit/item/ItemTypes.java @@ -0,0 +1,371 @@ +package cn.nukkit.item; + +import cn.nukkit.utils.material.ItemType; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import lombok.Data; + + +public class ItemTypes { + + private static final Int2ObjectMap types = new Int2ObjectOpenHashMap<>(); + private static final Object2ObjectMap identifiers = new Object2ObjectOpenHashMap<>(); + + public static final ItemType IRON_SHOVEL = register("minecraft:iron_shovel", ItemID.IRON_SHOVEL); + public static final ItemType IRON_PICKAXE = register("minecraft:iron_pickaxe", ItemID.IRON_PICKAXE); + public static final ItemType IRON_AXE = register("minecraft:iron_axe", ItemID.IRON_AXE); + public static final ItemType FLINT_STEEL = register("minecraft:flint_and_steel", ItemID.FLINT_STEEL); + public static final ItemType FLINT_AND_STEEL = register("minecraft:flint_and_steel", ItemID.FLINT_AND_STEEL); + public static final ItemType APPLE = register("minecraft:apple", ItemID.APPLE); + public static final ItemType BOW = register("minecraft:bow", ItemID.BOW); + public static final ItemType ARROW = register("minecraft:arrow", ItemID.ARROW); + public static final ItemType COAL = register("minecraft:coal", ItemID.COAL); + public static final ItemType DIAMOND = register("minecraft:diamond", ItemID.DIAMOND); + public static final ItemType IRON_INGOT = register("minecraft:iron_ingot", ItemID.IRON_INGOT); + public static final ItemType GOLD_INGOT = register("minecraft:gold_ingot", ItemID.GOLD_INGOT); + public static final ItemType IRON_SWORD = register("minecraft:iron_sword", ItemID.IRON_SWORD); + public static final ItemType WOODEN_SWORD = register("minecraft:wooden_sword", ItemID.WOODEN_SWORD); + public static final ItemType WOODEN_SHOVEL = register("minecraft:wooden_shovel", ItemID.WOODEN_SHOVEL); + public static final ItemType WOODEN_PICKAXE = register("minecraft:wooden_pickaxe", ItemID.WOODEN_PICKAXE); + public static final ItemType WOODEN_AXE = register("minecraft:wooden_axe", ItemID.WOODEN_AXE); + public static final ItemType STONE_SWORD = register("minecraft:stone_sword", ItemID.STONE_SWORD); + public static final ItemType STONE_SHOVEL = register("minecraft:stone_shovel", ItemID.STONE_SHOVEL); + public static final ItemType STONE_PICKAXE = register("minecraft:stone_pickaxe", ItemID.STONE_PICKAXE); + public static final ItemType STONE_AXE = register("minecraft:stone_axe", ItemID.STONE_AXE); + public static final ItemType DIAMOND_SWORD = register("minecraft:diamond_sword", ItemID.DIAMOND_SWORD); + public static final ItemType DIAMOND_SHOVEL = register("minecraft:diamond_shovel", ItemID.DIAMOND_SHOVEL); + public static final ItemType DIAMOND_PICKAXE = register("minecraft:diamond_pickaxe", ItemID.DIAMOND_PICKAXE); + public static final ItemType DIAMOND_AXE = register("minecraft:diamond_axe", ItemID.DIAMOND_AXE); + public static final ItemType STICK = register("minecraft:stick", ItemID.STICK); + public static final ItemType STICKS = register("minecraft:stick", ItemID.STICKS); + public static final ItemType BOWL = register("minecraft:bowl", ItemID.BOWL); + public static final ItemType MUSHROOM_STEW = register("minecraft:mushroom_stew", ItemID.MUSHROOM_STEW); + public static final ItemType GOLD_SWORD = register("minecraft:golden_sword", ItemID.GOLD_SWORD); + public static final ItemType GOLDEN_SWORD = register("minecraft:golden_sword", ItemID.GOLDEN_SWORD); + public static final ItemType GOLD_SHOVEL = register("minecraft:golden_shovel", ItemID.GOLD_SHOVEL); + public static final ItemType GOLDEN_SHOVEL = register("minecraft:golden_shovel", ItemID.GOLDEN_SHOVEL); + public static final ItemType GOLD_PICKAXE = register("minecraft:golden_pickaxe", ItemID.GOLD_PICKAXE); + public static final ItemType GOLDEN_PICKAXE = register("minecraft:golden_pickaxe", ItemID.GOLDEN_PICKAXE); + public static final ItemType GOLD_AXE = register("minecraft:golden_axe", ItemID.GOLD_AXE); + public static final ItemType GOLDEN_AXE = register("minecraft:golden_axe", ItemID.GOLDEN_AXE); + public static final ItemType STRING = register("minecraft:string", ItemID.STRING); + public static final ItemType FEATHER = register("minecraft:feather", ItemID.FEATHER); + public static final ItemType GUNPOWDER = register("minecraft:gunpowder", ItemID.GUNPOWDER); + public static final ItemType WOODEN_HOE = register("minecraft:wooden_hoe", ItemID.WOODEN_HOE); + public static final ItemType STONE_HOE = register("minecraft:stone_hoe", ItemID.STONE_HOE); + public static final ItemType IRON_HOE = register("minecraft:iron_hoe", ItemID.IRON_HOE); + public static final ItemType DIAMOND_HOE = register("minecraft:diamond_hoe", ItemID.DIAMOND_HOE); + public static final ItemType GOLD_HOE = register("minecraft:golden_hoe", ItemID.GOLD_HOE); + public static final ItemType GOLDEN_HOE = register("minecraft:golden_hoe", ItemID.GOLDEN_HOE); + public static final ItemType SEEDS = register("minecraft:wheat_seeds", ItemID.SEEDS); + public static final ItemType WHEAT_SEEDS = register("minecraft:wheat_seeds", ItemID.WHEAT_SEEDS); + public static final ItemType WHEAT = register("minecraft:wheat", ItemID.WHEAT); + public static final ItemType BREAD = register("minecraft:bread", ItemID.BREAD); + public static final ItemType LEATHER_CAP = register("minecraft:leather_helmet", ItemID.LEATHER_CAP); + public static final ItemType LEATHER_HELMET = register("minecraft:leather_helmet", ItemID.LEATHER_HELMET); + public static final ItemType LEATHER_TUNIC = register("minecraft:leather_chestplate", ItemID.LEATHER_TUNIC); + public static final ItemType LEATHER_CHESTPLATE = register("minecraft:leather_chestplate", ItemID.LEATHER_CHESTPLATE); + public static final ItemType LEATHER_PANTS = register("minecraft:leather_leggings", ItemID.LEATHER_PANTS); + public static final ItemType LEATHER_LEGGINGS = register("minecraft:leather_leggings", ItemID.LEATHER_LEGGINGS); + public static final ItemType LEATHER_BOOTS = register("minecraft:leather_boots", ItemID.LEATHER_BOOTS); + public static final ItemType CHAIN_HELMET = register("minecraft:chainmail_helmet", ItemID.CHAIN_HELMET); + public static final ItemType CHAINMAIL_HELMET = register("minecraft:chainmail_helmet", ItemID.CHAINMAIL_HELMET); + public static final ItemType CHAIN_CHESTPLATE = register("minecraft:chainmail_chestplate", ItemID.CHAIN_CHESTPLATE); + public static final ItemType CHAINMAIL_CHESTPLATE = register("minecraft:chainmail_chestplate", ItemID.CHAINMAIL_CHESTPLATE); + public static final ItemType CHAIN_LEGGINGS = register("minecraft:chainmail_leggings", ItemID.CHAIN_LEGGINGS); + public static final ItemType CHAINMAIL_LEGGINGS = register("minecraft:chainmail_leggings", ItemID.CHAINMAIL_LEGGINGS); + public static final ItemType CHAIN_BOOTS = register("minecraft:chainmail_boots", ItemID.CHAIN_BOOTS); + public static final ItemType CHAINMAIL_BOOTS = register("minecraft:chainmail_boots", ItemID.CHAINMAIL_BOOTS); + public static final ItemType IRON_HELMET = register("minecraft:iron_helmet", ItemID.IRON_HELMET); + public static final ItemType IRON_CHESTPLATE = register("minecraft:iron_chestplate", ItemID.IRON_CHESTPLATE); + public static final ItemType IRON_LEGGINGS = register("minecraft:iron_leggings", ItemID.IRON_LEGGINGS); + public static final ItemType IRON_BOOTS = register("minecraft:iron_boots", ItemID.IRON_BOOTS); + public static final ItemType DIAMOND_HELMET = register("minecraft:diamond_helmet", ItemID.DIAMOND_HELMET); + public static final ItemType DIAMOND_CHESTPLATE = register("minecraft:diamond_chestplate", ItemID.DIAMOND_CHESTPLATE); + public static final ItemType DIAMOND_LEGGINGS = register("minecraft:diamond_leggings", ItemID.DIAMOND_LEGGINGS); + public static final ItemType DIAMOND_BOOTS = register("minecraft:diamond_boots", ItemID.DIAMOND_BOOTS); + public static final ItemType GOLD_HELMET = register("minecraft:golden_helmet", ItemID.GOLD_HELMET); + public static final ItemType GOLDEN_HELMET = register("minecraft:golden_helmet", ItemID.GOLDEN_HELMET); + public static final ItemType GOLD_CHESTPLATE = register("minecraft:golden_chestplate", ItemID.GOLD_CHESTPLATE); + public static final ItemType GOLDEN_CHESTPLATE = register("minecraft:golden_chestplate", ItemID.GOLDEN_CHESTPLATE); + public static final ItemType GOLD_LEGGINGS = register("minecraft:golden_leggings", ItemID.GOLD_LEGGINGS); + public static final ItemType GOLDEN_LEGGINGS = register("minecraft:golden_leggings", ItemID.GOLDEN_LEGGINGS); + public static final ItemType GOLD_BOOTS = register("minecraft:golden_boots", ItemID.GOLD_BOOTS); + public static final ItemType GOLDEN_BOOTS = register("minecraft:golden_boots", ItemID.GOLDEN_BOOTS); + public static final ItemType FLINT = register("minecraft:flint", ItemID.FLINT); + public static final ItemType RAW_PORKCHOP = register("minecraft:porkchop", ItemID.RAW_PORKCHOP); + public static final ItemType COOKED_PORKCHOP = register("minecraft:cooked_porkchop", ItemID.COOKED_PORKCHOP); + public static final ItemType PAINTING = register("minecraft:painting", ItemID.PAINTING); + public static final ItemType GOLDEN_APPLE = register("minecraft:golden_apple", ItemID.GOLDEN_APPLE); + public static final ItemType SIGN = register("minecraft:oak_sign", ItemID.SIGN); + public static final ItemType WOODEN_DOOR = register("minecraft:wooden_door", ItemID.WOODEN_DOOR); + public static final ItemType BUCKET = register("minecraft:bucket", ItemID.BUCKET); + public static final ItemType MINECART = register("minecraft:minecart", ItemID.MINECART); + public static final ItemType SADDLE = register("minecraft:saddle", ItemID.SADDLE); + public static final ItemType IRON_DOOR = register("minecraft:iron_door", ItemID.IRON_DOOR); + public static final ItemType REDSTONE = register("minecraft:redstone", ItemID.REDSTONE); + public static final ItemType REDSTONE_DUST = register("minecraft:redstone", ItemID.REDSTONE_DUST); + public static final ItemType SNOWBALL = register("minecraft:snowball", ItemID.SNOWBALL); + public static final ItemType BOAT = register("minecraft:boat", ItemID.BOAT); + public static final ItemType LEATHER = register("minecraft:leather", ItemID.LEATHER); + public static final ItemType KELP = register("minecraft:kelp", ItemID.KELP); + public static final ItemType BRICK = register("minecraft:brick", ItemID.BRICK); + public static final ItemType CLAY = register("minecraft:clay_ball", ItemID.CLAY); + public static final ItemType CLAY_BALL = register("minecraft:clay_ball", ItemID.CLAY_BALL); + public static final ItemType SUGARCANE = register("minecraft:sugar_cane", ItemID.SUGARCANE); + public static final ItemType SUGAR_CANE = register("minecraft:sugar_cane", ItemID.SUGAR_CANE); + public static final ItemType SUGAR_CANES = register("minecraft:sugar_cane", ItemID.SUGAR_CANES); + public static final ItemType PAPER = register("minecraft:paper", ItemID.PAPER); + public static final ItemType BOOK = register("minecraft:book", ItemID.BOOK); + public static final ItemType SLIMEBALL = register("minecraft:slime_ball", ItemID.SLIMEBALL); + public static final ItemType SLIME_BALL = register("minecraft:slime_ball", ItemID.SLIME_BALL); + public static final ItemType CHEST_MINECART = register("minecraft:chest_minecart", ItemID.CHEST_MINECART); + public static final ItemType MINECART_WITH_CHEST = register("minecraft:chest_minecart", ItemID.MINECART_WITH_CHEST); + public static final ItemType EGG = register("minecraft:egg", ItemID.EGG); + public static final ItemType COMPASS = register("minecraft:compass", ItemID.COMPASS); + public static final ItemType FISHING_ROD = register("minecraft:fishing_rod", ItemID.FISHING_ROD); + public static final ItemType CLOCK = register("minecraft:clock", ItemID.CLOCK); + public static final ItemType GLOWSTONE_DUST = register("minecraft:glowstone_dust", ItemID.GLOWSTONE_DUST); + public static final ItemType RAW_FISH = register("minecraft:cod", ItemID.RAW_FISH); + public static final ItemType COOKED_FISH = register("minecraft:cooked_cod", ItemID.COOKED_FISH); + public static final ItemType DYE = register("minecraft:dye", ItemID.DYE); + public static final ItemType BONE = register("minecraft:bone", ItemID.BONE); + public static final ItemType SUGAR = register("minecraft:sugar", ItemID.SUGAR); + public static final ItemType CAKE = register("minecraft:cake", ItemID.CAKE); + public static final ItemType BED = register("minecraft:bed", ItemID.BED); + public static final ItemType REPEATER = register("minecraft:repeater", ItemID.REPEATER); + public static final ItemType COOKIE = register("minecraft:cookie", ItemID.COOKIE); + public static final ItemType MAP = register("minecraft:filled_map", ItemID.MAP); + public static final ItemType SHEARS = register("minecraft:shears", ItemID.SHEARS); + public static final ItemType MELON = register("minecraft:melon_slice", ItemID.MELON); + public static final ItemType MELON_SLICE = register("minecraft:melon_slice", ItemID.MELON_SLICE); + public static final ItemType PUMPKIN_SEEDS = register("minecraft:pumpkin_seeds", ItemID.PUMPKIN_SEEDS); + public static final ItemType MELON_SEEDS = register("minecraft:melon_seeds", ItemID.MELON_SEEDS); + public static final ItemType BEEF = register("minecraft:beef", ItemID.BEEF); + public static final ItemType RAW_BEEF = register("minecraft:beef", ItemID.RAW_BEEF); + public static final ItemType STEAK = register("minecraft:cooked_beef", ItemID.STEAK); + public static final ItemType COOKED_BEEF = register("minecraft:cooked_beef", ItemID.COOKED_BEEF); + public static final ItemType RAW_CHICKEN = register("minecraft:chicken", ItemID.RAW_CHICKEN); + public static final ItemType CHICKEN = register("minecraft:chicken", ItemID.CHICKEN); + public static final ItemType COOKED_CHICKEN = register("minecraft:cooked_chicken", ItemID.COOKED_CHICKEN); + public static final ItemType ROTTEN_FLESH = register("minecraft:rotten_flesh", ItemID.ROTTEN_FLESH); + public static final ItemType ENDER_PEARL = register("minecraft:ender_pearl", ItemID.ENDER_PEARL); + public static final ItemType BLAZE_ROD = register("minecraft:blaze_rod", ItemID.BLAZE_ROD); + public static final ItemType GHAST_TEAR = register("minecraft:ghast_tear", ItemID.GHAST_TEAR); + public static final ItemType GOLD_NUGGET = register("minecraft:gold_nugget", ItemID.GOLD_NUGGET); + public static final ItemType GOLDEN_NUGGET = register("minecraft:gold_nugget", ItemID.GOLDEN_NUGGET); + public static final ItemType NETHER_WART = register("minecraft:nether_wart", ItemID.NETHER_WART); + public static final ItemType POTION = register("minecraft:potion", ItemID.POTION); + public static final ItemType GLASS_BOTTLE = register("minecraft:glass_bottle", ItemID.GLASS_BOTTLE); + public static final ItemType BOTTLE = register("minecraft:glass_bottle", ItemID.BOTTLE); + public static final ItemType SPIDER_EYE = register("minecraft:spider_eye", ItemID.SPIDER_EYE); + public static final ItemType FERMENTED_SPIDER_EYE = register("minecraft:fermented_spider_eye", ItemID.FERMENTED_SPIDER_EYE); + public static final ItemType BLAZE_POWDER = register("minecraft:blaze_powder", ItemID.BLAZE_POWDER); + public static final ItemType MAGMA_CREAM = register("minecraft:magma_cream", ItemID.MAGMA_CREAM); + public static final ItemType BREWING_STAND = register("minecraft:brewing_stand", ItemID.BREWING_STAND); + public static final ItemType BREWING = register("minecraft:brewing_stand", ItemID.BREWING); + public static final ItemType CAULDRON = register("minecraft:cauldron", ItemID.CAULDRON); + public static final ItemType ENDER_EYE = register("minecraft:ender_eye", ItemID.ENDER_EYE); + public static final ItemType GLISTERING_MELON = register("minecraft:glistering_melon_slice", ItemID.GLISTERING_MELON); + public static final ItemType GLISTERING_MELON_SLICE = register("minecraft:glistering_melon_slice", ItemID.GLISTERING_MELON_SLICE); + public static final ItemType SPAWN_EGG = register("minecraft:spawn_egg", ItemID.SPAWN_EGG); + public static final ItemType EXPERIENCE_BOTTLE = register("minecraft:experience_bottle", ItemID.EXPERIENCE_BOTTLE); + public static final ItemType FIRE_CHARGE = register("minecraft:fire_charge", ItemID.FIRE_CHARGE); + public static final ItemType BOOK_AND_QUILL = register("minecraft:writable_book", ItemID.BOOK_AND_QUILL); + public static final ItemType WRITTEN_BOOK = register("minecraft:written_book", ItemID.WRITTEN_BOOK); + public static final ItemType EMERALD = register("minecraft:emerald", ItemID.EMERALD); + public static final ItemType ITEM_FRAME = register("minecraft:frame", ItemID.ITEM_FRAME); + public static final ItemType FRAME = register("minecraft:frame", ItemID.FRAME); + public static final ItemType FLOWER_POT = register("minecraft:flower_pot", ItemID.FLOWER_POT); + public static final ItemType CARROT = register("minecraft:carrot", ItemID.CARROT); + public static final ItemType CARROTS = register("minecraft:carrot", ItemID.CARROTS); + public static final ItemType POTATO = register("minecraft:potato", ItemID.POTATO); + public static final ItemType POTATOES = register("minecraft:potato", ItemID.POTATOES); + public static final ItemType BAKED_POTATO = register("minecraft:baked_potato", ItemID.BAKED_POTATO); + public static final ItemType BAKED_POTATOES = register("minecraft:baked_potato", ItemID.BAKED_POTATOES); + public static final ItemType POISONOUS_POTATO = register("minecraft:poisonous_potato", ItemID.POISONOUS_POTATO); + public static final ItemType EMPTY_MAP = register("minecraft:empty_map", ItemID.EMPTY_MAP); + public static final ItemType EMPTYMAP = register("minecraft:empty_map", ItemID.EMPTYMAP); + public static final ItemType GOLDEN_CARROT = register("minecraft:golden_carrot", ItemID.GOLDEN_CARROT); + public static final ItemType SKULL = register("minecraft:skull", ItemID.SKULL); + public static final ItemType CARROTONASTICK = register("minecraft:carrot_on_a_stick", ItemID.CARROTONASTICK); + public static final ItemType CARROT_ON_A_STICK = register("minecraft:carrot_on_a_stick", ItemID.CARROT_ON_A_STICK); + public static final ItemType NETHER_STAR = register("minecraft:nether_star", ItemID.NETHER_STAR); + public static final ItemType PUMPKIN_PIE = register("minecraft:pumpkin_pie", ItemID.PUMPKIN_PIE); + public static final ItemType FIREWORKS = register("minecraft:firework_rocket", ItemID.FIREWORKS); + public static final ItemType FIREWORKSCHARGE = register("minecraft:firework_star", ItemID.FIREWORKSCHARGE); + public static final ItemType ENCHANTED_BOOK = register("minecraft:enchanted_book", ItemID.ENCHANTED_BOOK); + public static final ItemType ENCHANT_BOOK = register("minecraft:enchanted_book", ItemID.ENCHANT_BOOK); + public static final ItemType COMPARATOR = register("minecraft:comparator", ItemID.COMPARATOR); + public static final ItemType NETHER_BRICK = register("minecraft:netherbrick", ItemID.NETHER_BRICK); + public static final ItemType QUARTZ = register("minecraft:quartz", ItemID.QUARTZ); + public static final ItemType NETHER_QUARTZ = register("minecraft:quartz", ItemID.NETHER_QUARTZ); + public static final ItemType TNT_MINECART = register("minecraft:tnt_minecart", ItemID.TNT_MINECART); + public static final ItemType MINECART_WITH_TNT = register("minecraft:tnt_minecart", ItemID.MINECART_WITH_TNT); + public static final ItemType HOPPER_MINECART = register("minecraft:hopper_minecart", ItemID.HOPPER_MINECART); + public static final ItemType MINECART_WITH_HOPPER = register("minecraft:hopper_minecart", ItemID.MINECART_WITH_HOPPER); + public static final ItemType PRISMARINE_SHARD = register("minecraft:prismarine_shard", ItemID.PRISMARINE_SHARD); + public static final ItemType HOPPER = register("minecraft:hopper", ItemID.HOPPER); + public static final ItemType RAW_RABBIT = register("minecraft:rabbit", ItemID.RAW_RABBIT); + public static final ItemType RABBIT = register("minecraft:rabbit", ItemID.RABBIT); + public static final ItemType COOKED_RABBIT = register("minecraft:cooked_rabbit", ItemID.COOKED_RABBIT); + public static final ItemType RABBIT_STEW = register("minecraft:rabbit_stew", ItemID.RABBIT_STEW); + public static final ItemType RABBIT_FOOT = register("minecraft:rabbit_foot", ItemID.RABBIT_FOOT); + public static final ItemType RABBIT_HIDE = register("minecraft:rabbit_hide", ItemID.RABBIT_HIDE); + public static final ItemType LEATHER_HORSE_ARMOR = register("minecraft:leather_horse_armor", ItemID.LEATHER_HORSE_ARMOR); + public static final ItemType IRON_HORSE_ARMOR = register("minecraft:iron_horse_armor", ItemID.IRON_HORSE_ARMOR); + public static final ItemType GOLD_HORSE_ARMOR = register("minecraft:golden_horse_armor", ItemID.GOLD_HORSE_ARMOR); + public static final ItemType GOLDEN_HORSE_ARMOR = register("minecraft:golden_horse_armor", ItemID.GOLDEN_HORSE_ARMOR); + public static final ItemType DIAMOND_HORSE_ARMOR = register("minecraft:diamond_horse_armor", ItemID.DIAMOND_HORSE_ARMOR); + public static final ItemType LEAD = register("minecraft:lead", ItemID.LEAD); + public static final ItemType NAME_TAG = register("minecraft:name_tag", ItemID.NAME_TAG); + public static final ItemType NAMETAG = register("minecraft:name_tag", ItemID.NAMETAG); + public static final ItemType PRISMARINE_CRYSTALS = register("minecraft:prismarine_crystals", ItemID.PRISMARINE_CRYSTALS); + public static final ItemType RAW_MUTTON = register("minecraft:mutton", ItemID.RAW_MUTTON); + public static final ItemType MUTTONRAW = register("minecraft:mutton", ItemID.MUTTONRAW); + public static final ItemType COOKED_MUTTON = register("minecraft:cooked_mutton", ItemID.COOKED_MUTTON); + public static final ItemType ARMOR_STAND = register("minecraft:armor_stand", ItemID.ARMOR_STAND); + public static final ItemType END_CRYSTAL = register("minecraft:end_crystal", ItemID.END_CRYSTAL); + public static final ItemType SPRUCE_DOOR = register("minecraft:spruce_door", ItemID.SPRUCE_DOOR); + public static final ItemType BIRCH_DOOR = register("minecraft:birch_door", ItemID.BIRCH_DOOR); + public static final ItemType JUNGLE_DOOR = register("minecraft:jungle_door", ItemID.JUNGLE_DOOR); + public static final ItemType ACACIA_DOOR = register("minecraft:acacia_door", ItemID.ACACIA_DOOR); + public static final ItemType DARK_OAK_DOOR = register("minecraft:dark_oak_door", ItemID.DARK_OAK_DOOR); + public static final ItemType CHORUS_FRUIT = register("minecraft:chorus_fruit", ItemID.CHORUS_FRUIT); + public static final ItemType POPPED_CHORUS_FRUIT = register("minecraft:popped_chorus_fruit", ItemID.POPPED_CHORUS_FRUIT); + public static final ItemType BANNER_PATTERN = register("minecraft:banner_pattern", ItemID.BANNER_PATTERN); + public static final ItemType DRAGON_BREATH = register("minecraft:dragon_breath", ItemID.DRAGON_BREATH); + public static final ItemType SPLASH_POTION = register("minecraft:splash_potion", ItemID.SPLASH_POTION); + public static final ItemType LINGERING_POTION = register("minecraft:lingering_potion", ItemID.LINGERING_POTION); + public static final ItemType SPARKLER = register("minecraft:sparkler", ItemID.SPARKLER); + public static final ItemType COMMAND_BLOCK_MINECART = register("minecraft:command_block_minecart", ItemID.COMMAND_BLOCK_MINECART); + public static final ItemType ELYTRA = register("minecraft:elytra", ItemID.ELYTRA); + public static final ItemType SHULKER_SHELL = register("minecraft:shulker_shell", ItemID.SHULKER_SHELL); + public static final ItemType BANNER = register("minecraft:banner", ItemID.BANNER); + public static final ItemType EYE_DROP = register("minecraft:medicine", ItemID.EYE_DROP); + public static final ItemType BALLOON = register("minecraft:balloon", ItemID.BALLOON); + public static final ItemType SUPER_FERTILIZER = register("minecraft:rapid_fertilizer", ItemID.SUPER_FERTILIZER); + public static final ItemType TOTEM = register("minecraft:totem_of_undying", ItemID.TOTEM); + public static final ItemType BLEACH = register("minecraft:bleach", ItemID.BLEACH); + public static final ItemType IRON_NUGGET = register("minecraft:iron_nugget", ItemID.IRON_NUGGET); + public static final ItemType ICE_BOMB = register("minecraft:ice_bomb", ItemID.ICE_BOMB); + public static final ItemType TRIDENT = register("minecraft:trident", ItemID.TRIDENT); + public static final ItemType BEETROOT = register("minecraft:beetroot", ItemID.BEETROOT); + public static final ItemType BEETROOT_SEEDS = register("minecraft:beetroot_seeds", ItemID.BEETROOT_SEEDS); + public static final ItemType BEETROOT_SEED = register("minecraft:beetroot_seeds", ItemID.BEETROOT_SEED); + public static final ItemType BEETROOT_SOUP = register("minecraft:beetroot_soup", ItemID.BEETROOT_SOUP); + public static final ItemType RAW_SALMON = register("minecraft:salmon", ItemID.RAW_SALMON); + public static final ItemType CLOWNFISH = register("minecraft:tropical_fish", ItemID.CLOWNFISH); + public static final ItemType PUFFERFISH = register("minecraft:pufferfish", ItemID.PUFFERFISH); + public static final ItemType COOKED_SALMON = register("minecraft:cooked_salmon", ItemID.COOKED_SALMON); + public static final ItemType DRIED_KELP = register("minecraft:dried_kelp", ItemID.DRIED_KELP); + public static final ItemType NAUTILUS_SHELL = register("minecraft:nautilus_shell", ItemID.NAUTILUS_SHELL); + public static final ItemType GOLDEN_APPLE_ENCHANTED = register("minecraft:enchanted_golden_apple", ItemID.GOLDEN_APPLE_ENCHANTED); + public static final ItemType ENCHANTED_GOLDEN_APPLE = register("minecraft:enchanted_golden_apple", ItemID.ENCHANTED_GOLDEN_APPLE); + public static final ItemType APPLEENCHANTED = register("minecraft:enchanted_golden_apple", ItemID.APPLEENCHANTED); + public static final ItemType HEART_OF_THE_SEA = register("minecraft:heart_of_the_sea", ItemID.HEART_OF_THE_SEA); + public static final ItemType SCUTE = register("minecraft:turtle_scute", ItemID.SCUTE); + public static final ItemType TURTLE_SCUTE = register("minecraft:turtle_scute", ItemID.TURTLE_SCUTE); + public static final ItemType TURTLE_SHELL = register("minecraft:turtle_helmet", ItemID.TURTLE_SHELL); + public static final ItemType TURTLE_HELMET = register("minecraft:turtle_helmet", ItemID.TURTLE_HELMET); + public static final ItemType PHANTOM_MEMBRANE = register("minecraft:phantom_membrane", ItemID.PHANTOM_MEMBRANE); + public static final ItemType CROSSBOW = register("minecraft:crossbow", ItemID.CROSSBOW); + public static final ItemType SPRUCE_SIGN = register("minecraft:spruce_sign", ItemID.SPRUCE_SIGN); + public static final ItemType BIRCH_SIGN = register("minecraft:birch_sign", ItemID.BIRCH_SIGN); + public static final ItemType JUNGLE_SIGN = register("minecraft:jungle_sign", ItemID.JUNGLE_SIGN); + public static final ItemType ACACIA_SIGN = register("minecraft:acacia_sign", ItemID.ACACIA_SIGN); + public static final ItemType DARKOAK_SIGN = register("minecraft:dark_oak_sign", ItemID.DARKOAK_SIGN); + public static final ItemType SWEET_BERRIES = register("minecraft:sweet_berries", ItemID.SWEET_BERRIES); + public static final ItemType CAMERA = register("minecraft:camera", ItemID.CAMERA); + public static final ItemType COMPOUND = register("minecraft:compound", ItemID.COMPOUND); + public static final ItemType RECORD_13 = register("minecraft:music_disc_13", ItemID.RECORD_13); + public static final ItemType RECORD_CAT = register("minecraft:music_disc_cat", ItemID.RECORD_CAT); + public static final ItemType RECORD_BLOCKS = register("minecraft:music_disc_blocks", ItemID.RECORD_BLOCKS); + public static final ItemType RECORD_CHIRP = register("minecraft:music_disc_chirp", ItemID.RECORD_CHIRP); + public static final ItemType RECORD_FAR = register("minecraft:music_disc_far", ItemID.RECORD_FAR); + public static final ItemType RECORD_MALL = register("minecraft:music_disc_mall", ItemID.RECORD_MALL); + public static final ItemType RECORD_MELLOHI = register("minecraft:music_disc_mellohi", ItemID.RECORD_MELLOHI); + public static final ItemType RECORD_STAL = register("minecraft:music_disc_stal", ItemID.RECORD_STAL); + public static final ItemType RECORD_STRAD = register("minecraft:music_disc_strad", ItemID.RECORD_STRAD); + public static final ItemType RECORD_WARD = register("minecraft:music_disc_ward", ItemID.RECORD_WARD); + public static final ItemType RECORD_11 = register("minecraft:music_disc_11", ItemID.RECORD_11); + public static final ItemType RECORD_WAIT = register("minecraft:music_disc_wait", ItemID.RECORD_WAIT); + public static final ItemType SHIELD = register("minecraft:shield", ItemID.SHIELD); + public static final ItemType COPPER_INGOT = register("minecraft:copper_ingot", ItemID.COPPER_INGOT); + public static final ItemType RAW_IRON = register("minecraft:raw_iron", ItemID.RAW_IRON); + public static final ItemType RAW_GOLD = register("minecraft:raw_gold", ItemID.RAW_GOLD); + public static final ItemType RAW_COPPER = register("minecraft:raw_copper", ItemID.RAW_COPPER); + public static final ItemType RECORD_5 = register("minecraft:music_disc_5", ItemID.RECORD_5); + public static final ItemType DISC_FRAGMENT_5 = register("minecraft:disc_fragment_5", ItemID.DISC_FRAGMENT_5); + public static final ItemType OAK_CHEST_BOAT = register("minecraft:oak_chest_boat", ItemID.OAK_CHEST_BOAT); + public static final ItemType BIRCH_CHEST_BOAT = register("minecraft:birch_chest_boat", ItemID.BIRCH_CHEST_BOAT); + public static final ItemType JUNGLE_CHEST_BOAT = register("minecraft:jungle_chest_boat", ItemID.JUNGLE_CHEST_BOAT); + public static final ItemType SPRUCE_CHEST_BOAT = register("minecraft:spruce_chest_boat", ItemID.SPRUCE_CHEST_BOAT); + public static final ItemType ACACIA_CHEST_BOAT = register("minecraft:acacia_chest_boat", ItemID.ACACIA_CHEST_BOAT); + public static final ItemType DARK_OAK_CHEST_BOAT = register("minecraft:dark_oak_chest_boat", ItemID.DARK_OAK_CHEST_BOAT); + public static final ItemType MANGROVE_CHEST_BOAT = register("minecraft:mangrove_chest_boat", ItemID.MANGROVE_CHEST_BOAT); + public static final ItemType ECHO_SHARD = register("minecraft:echo_shard", ItemID.ECHO_SHARD); + public static final ItemType RECOVERY_COMPASS = register("minecraft:recovery_compass", ItemID.RECOVERY_COMPASS); + public static final ItemType GLOW_BERRIES = register("minecraft:glow_berries", ItemID.GLOW_BERRIES); + public static final ItemType RECORD_RELIC = register("minecraft:music_disc_relic", ItemID.RECORD_RELIC); + public static final ItemType CAMPFIRE = register("minecraft:campfire", ItemID.CAMPFIRE); + public static final ItemType SUSPICIOUS_STEW = register("minecraft:suspicious_stew", ItemID.SUSPICIOUS_STEW); + public static final ItemType HONEYCOMB = register("minecraft:honeycomb", ItemID.HONEYCOMB); + public static final ItemType HONEY_BOTTLE = register("minecraft:honey_bottle", ItemID.HONEY_BOTTLE); + public static final ItemType LODESTONECOMPASS = register("minecraft:lodestone_compass", ItemID.LODESTONECOMPASS); + public static final ItemType LODESTONE_COMPASS = register("minecraft:lodestone_compass", ItemID.LODESTONE_COMPASS); + public static final ItemType NETHERITE_INGOT = register("minecraft:netherite_ingot", ItemID.NETHERITE_INGOT); + public static final ItemType NETHERITE_SWORD = register("minecraft:netherite_sword", ItemID.NETHERITE_SWORD); + public static final ItemType NETHERITE_SHOVEL = register("minecraft:netherite_shovel", ItemID.NETHERITE_SHOVEL); + public static final ItemType NETHERITE_PICKAXE = register("minecraft:netherite_pickaxe", ItemID.NETHERITE_PICKAXE); + public static final ItemType NETHERITE_AXE = register("minecraft:netherite_axe", ItemID.NETHERITE_AXE); + public static final ItemType NETHERITE_HOE = register("minecraft:netherite_hoe", ItemID.NETHERITE_HOE); + public static final ItemType NETHERITE_HELMET = register("minecraft:netherite_helmet", ItemID.NETHERITE_HELMET); + public static final ItemType NETHERITE_CHESTPLATE = register("minecraft:netherite_chestplate", ItemID.NETHERITE_CHESTPLATE); + public static final ItemType NETHERITE_LEGGINGS = register("minecraft:netherite_leggings", ItemID.NETHERITE_LEGGINGS); + public static final ItemType NETHERITE_BOOTS = register("minecraft:netherite_boots", ItemID.NETHERITE_BOOTS); + public static final ItemType NETHERITE_SCRAP = register("minecraft:netherite_scrap", ItemID.NETHERITE_SCRAP); + public static final ItemType CRIMSON_SIGN = register("minecraft:crimson_sign", ItemID.CRIMSON_SIGN); + public static final ItemType WARPED_SIGN = register("minecraft:warped_sign", ItemID.WARPED_SIGN); + public static final ItemType CRIMSON_DOOR = register("minecraft:crimson_door", ItemID.CRIMSON_DOOR); + public static final ItemType WARPED_DOOR = register("minecraft:warped_door", ItemID.WARPED_DOOR); + public static final ItemType WARPED_FUNGUS_ON_A_STICK = register("minecraft:warped_fungus_on_a_stick", ItemID.WARPED_FUNGUS_ON_A_STICK); + public static final ItemType CHAIN = register("minecraft:chain", ItemID.CHAIN); + public static final ItemType RECORD_PIGSTEP = register("minecraft:music_disc_pigstep", ItemID.RECORD_PIGSTEP); + public static final ItemType NETHER_SPROUTS = register("minecraft:nether_sprouts", ItemID.NETHER_SPROUTS); + public static final ItemType GOAT_HORN = register("minecraft:goat_horn", ItemID.GOAT_HORN); + public static final ItemType AMETHYST_SHARD = register("minecraft:amethyst_shard", ItemID.AMETHYST_SHARD); + public static final ItemType SPYGLASS = register("minecraft:spyglass", ItemID.SPYGLASS); + public static final ItemType RECORD_OTHERSIDE = register("minecraft:music_disc_otherside", ItemID.RECORD_OTHERSIDE); + public static final ItemType SOUL_CAMPFIRE = register("minecraft:soul_campfire", ItemID.SOUL_CAMPFIRE); + public static final ItemType GLOW_ITEM_FRAME = register("minecraft:glow_frame", ItemID.GLOW_ITEM_FRAME); + + private static ItemType register(String identifier, int legacyId) { + return register(new ItemTypeImpl(identifier, legacyId)); + } + + private static ItemType register(ItemType itemType) { + ItemType old = types.putIfAbsent(itemType.getLegacyId(), itemType); + /*if (old != null) { // TODO: there are alternate names for some items + throw new IllegalArgumentException("Item type with id " + itemType.getLegacyId() + " already exists: " + old); + }*/ + identifiers.putIfAbsent(itemType.getIdentifier(), itemType); // TODO: using identifiers.put() would be better + return old == null ? itemType : old; + } + + public static ItemType getFromLegacy(int legacyId) { + return types.get(legacyId); + } + + public static ItemType get(String identifier) { + return identifiers.get(identifier); + } + + @Data + private static class ItemTypeImpl implements ItemType { + private final String identifier; + private final int legacyId; + } +} diff --git a/src/main/java/cn/nukkit/item/ItemWarpedFungusOnAStick.java b/src/main/java/cn/nukkit/item/ItemWarpedFungusOnAStick.java index e8c0378c113..dae721c19f0 100644 --- a/src/main/java/cn/nukkit/item/ItemWarpedFungusOnAStick.java +++ b/src/main/java/cn/nukkit/item/ItemWarpedFungusOnAStick.java @@ -1,8 +1,5 @@ package cn.nukkit.item; -/** - * @author PetteriM1 - */ public class ItemWarpedFungusOnAStick extends ItemTool { public ItemWarpedFungusOnAStick() { diff --git a/src/main/java/cn/nukkit/item/ItemWheat.java b/src/main/java/cn/nukkit/item/ItemWheat.java index d04bcb6ab12..d46ed0ddfef 100644 --- a/src/main/java/cn/nukkit/item/ItemWheat.java +++ b/src/main/java/cn/nukkit/item/ItemWheat.java @@ -1,7 +1,7 @@ package cn.nukkit.item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ItemWheat extends Item { diff --git a/src/main/java/cn/nukkit/item/ProjectileItem.java b/src/main/java/cn/nukkit/item/ProjectileItem.java index 5daac1d2756..bdcc4a30090 100644 --- a/src/main/java/cn/nukkit/item/ProjectileItem.java +++ b/src/main/java/cn/nukkit/item/ProjectileItem.java @@ -2,10 +2,14 @@ import cn.nukkit.Player; import cn.nukkit.entity.Entity; +import cn.nukkit.entity.projectile.EntityEnderEye; import cn.nukkit.entity.projectile.EntityEnderPearl; import cn.nukkit.entity.projectile.EntityProjectile; import cn.nukkit.event.entity.ProjectileLaunchEvent; +import cn.nukkit.level.Level; +import cn.nukkit.level.Position; import cn.nukkit.math.Vector3; +import cn.nukkit.math.Vector3f; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.DoubleTag; import cn.nukkit.nbt.tag.FloatTag; @@ -26,10 +30,14 @@ public ProjectileItem(int id, Integer meta, int count, String name) { abstract public float getThrowForce(); public boolean onClickAir(Player player, Vector3 directionVector) { + if (this instanceof ItemEnderEye && player.getLevel().getDimension() != Level.DIMENSION_OVERWORLD) { + return false; + } + CompoundTag nbt = new CompoundTag() .putList(new ListTag("Pos") .add(new DoubleTag("", player.x)) - .add(new DoubleTag("", player.y + player.getEyeHeight() - 0.30000000149011612)) + .add(new DoubleTag("", player.y + player.getEyeHeight())) .add(new DoubleTag("", player.z))) .putList(new ListTag("Motion") .add(new DoubleTag("", directionVector.x)) @@ -41,41 +49,67 @@ public boolean onClickAir(Player player, Vector3 directionVector) { this.correctNBT(nbt); - Entity projectile = Entity.createEntity(this.getProjectileEntityType(), player.getLevel().getChunk(player.getFloorX() >> 4, player.getFloorZ() >> 4), nbt, player); + Entity projectile = Entity.createEntity(this.getProjectileEntityType(), player.getLevel().getChunk(player.getChunkX(), player.getChunkZ()), nbt, player); if (projectile != null) { - if (projectile instanceof EntityEnderPearl) { + if (projectile instanceof EntityEnderPearl || projectile instanceof EntityEnderEye) { if (player.getServer().getTick() - player.getLastEnderPearlThrowingTick() < 20) { - projectile.kill(); + projectile.close(); return false; } } - projectile.setMotion(projectile.getMotion().multiply(this.getThrowForce())); + if (projectile instanceof EntityEnderEye) { + if (player.getServer().getTick() - player.getLastEnderPearlThrowingTick() < 20) { + projectile.close(); + return false; + } + + Position strongholdPosition = this.getStrongholdPosition(player); + if (strongholdPosition == null) { + projectile.close(); + return false; + } + + Vector3f vector = strongholdPosition + .subtract(player.getPosition()) + .asVector3f() + .normalize() + .multiply(1f); + + vector.y = 0.55f; + + projectile.setMotion(vector.asVector3().divide(this.getThrowForce())); + } else { + projectile.setMotion(projectile.getMotion().multiply(this.getThrowForce())); + } if (projectile instanceof EntityProjectile) { ProjectileLaunchEvent ev = new ProjectileLaunchEvent((EntityProjectile) projectile); player.getServer().getPluginManager().callEvent(ev); + if (ev.isCancelled()) { - projectile.kill(); + projectile.close(); } else { if (!player.isCreative()) { this.count--; } - if (projectile instanceof EntityEnderPearl) { + if (projectile instanceof EntityEnderPearl || projectile instanceof EntityEnderEye) { player.onThrowEnderPearl(); } projectile.spawnToAll(); player.getLevel().addLevelSoundEvent(player, LevelSoundEventPacket.SOUND_BOW); } } - } else { - return false; } + return true; } protected void correctNBT(CompoundTag nbt) { + } + private Position getStrongholdPosition(Player p) { + return p.level.getDimension() == Level.DIMENSION_OVERWORLD ? p : null; // TODO } } diff --git a/src/main/java/cn/nukkit/item/RuntimeItemMapping.java b/src/main/java/cn/nukkit/item/RuntimeItemMapping.java index 6b7e4f3cf01..b71b8adf90c 100644 --- a/src/main/java/cn/nukkit/item/RuntimeItemMapping.java +++ b/src/main/java/cn/nukkit/item/RuntimeItemMapping.java @@ -1,19 +1,20 @@ package cn.nukkit.item; +import cn.nukkit.Nukkit; +import cn.nukkit.block.Block; import cn.nukkit.item.RuntimeItems.MappingEntry; -import cn.nukkit.Server; +import cn.nukkit.level.GlobalBlockPalette; import cn.nukkit.utils.BinaryStream; +import cn.nukkit.utils.Utils; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import com.google.gson.JsonParser; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import lombok.Data; import lombok.extern.log4j.Log4j2; -import java.io.InputStream; -import java.io.InputStreamReader; +import java.util.Base64; import java.util.HashMap; import java.util.Map; @@ -27,11 +28,10 @@ public class RuntimeItemMapping { private byte[] itemPalette; public RuntimeItemMapping(Map mappings) { - InputStream stream = Server.class.getClassLoader().getResourceAsStream("runtime_item_states.json"); - if (stream == null) { - throw new AssertionError("Unable to load runtime_item_states.json"); + JsonArray json = Utils.loadJsonResource("runtime_item_states.json").getAsJsonArray(); + if (json.isEmpty()) { + throw new IllegalStateException("Empty array"); } - JsonArray json = JsonParser.parseReader(new InputStreamReader(stream)).getAsJsonArray(); for (JsonElement element : json) { if (!element.isJsonObject()) { @@ -49,7 +49,7 @@ public RuntimeItemMapping(Map mappings) { MappingEntry mapping = mappings.get(identifier); legacyId = RuntimeItems.getLegacyIdFromLegacyString(mapping.getLegacyName()); if (legacyId == -1) { - throw new IllegalStateException("Unable to match " + mapping + " with legacyId"); + throw new IllegalStateException("Unable to match " + mapping + " with legacyId"); } damage = mapping.getDamage(); hasDamage = true; @@ -61,28 +61,42 @@ public RuntimeItemMapping(Map mappings) { } } - int fullId = this.getFullId(legacyId, damage); - LegacyEntry legacyEntry = new LegacyEntry(legacyId, hasDamage, damage); + this.registerItem(identifier, runtimeId, legacyId, damage, hasDamage); + } - this.runtime2Legacy.put(runtimeId, legacyEntry); - this.identifier2Legacy.put(identifier, legacyEntry); - if (!hasDamage && this.legacy2Runtime.containsKey(fullId)) { - Server.getInstance().getLogger().debug("RuntimeItemMapping contains duplicated legacy item state runtimeId=" + runtimeId + " identifier=" + identifier); - } else { - this.legacy2Runtime.put(fullId, new RuntimeEntry(identifier, runtimeId, hasDamage)); + this.generatePalette(); + } + + public void registerItem(String identifier, int runtimeId, int legacyId, int damage) { + this.registerItem(identifier, runtimeId, legacyId, damage, false); + } + + public void registerItem(String identifier, int runtimeId, int legacyId, int damage, boolean hasDamage) { + int fullId = this.getFullId(legacyId, damage); + LegacyEntry legacyEntry = new LegacyEntry(legacyId, hasDamage, damage); + + if (Nukkit.DEBUG > 1) { + if (this.runtime2Legacy.containsKey(runtimeId)) { + log.warn("RuntimeItemMapping: Registering " + identifier + " but runtime id " + runtimeId + " is already used"); } } - this.generatePalette(); + this.runtime2Legacy.put(runtimeId, legacyEntry); + this.identifier2Legacy.put(identifier, legacyEntry); + if (!hasDamage && this.legacy2Runtime.containsKey(fullId)) { + log.debug("RuntimeItemMapping contains duplicated legacy item state runtimeId=" + runtimeId + " identifier=" + identifier); + } else { + this.legacy2Runtime.put(fullId, new RuntimeEntry(identifier, runtimeId, hasDamage)); + } } - private void generatePalette() { + public void generatePalette() { BinaryStream paletteBuffer = new BinaryStream(); paletteBuffer.putUnsignedVarInt(this.legacy2Runtime.size()); for (RuntimeEntry entry : this.legacy2Runtime.values()) { paletteBuffer.putString(entry.getIdentifier()); paletteBuffer.putLShort(entry.getRuntimeId()); - paletteBuffer.putBoolean(false); // Component item + paletteBuffer.putBoolean(!entry.getIdentifier().startsWith("minecraft:")); // TODO: Component item without bc break } this.itemPalette = paletteBuffer.getBuffer(); } @@ -90,7 +104,9 @@ private void generatePalette() { public LegacyEntry fromRuntime(int runtimeId) { LegacyEntry legacyEntry = this.runtime2Legacy.get(runtimeId); if (legacyEntry == null) { - throw new IllegalArgumentException("Unknown runtime2Legacy mapping: " + runtimeId); + //throw new IllegalArgumentException("Unknown runtime2Legacy mapping: " + runtimeId); + log.warn("Unknown runtime2Legacy mapping: " + runtimeId); + return new LegacyEntry(0, false, 0); } return legacyEntry; } @@ -102,11 +118,59 @@ public RuntimeEntry toRuntime(int id, int meta) { } if (runtimeEntry == null) { - throw new IllegalArgumentException("Unknown legacy2Runtime mapping: id=" + id + " meta=" + meta); + log.warn("Unknown legacy2Runtime mapping: id=" + id + " meta=" + meta); + runtimeEntry = this.legacy2Runtime.get(this.getFullId(Item.INFO_UPDATE, 0)); + if (runtimeEntry == null) throw new RuntimeException("Runtime ID for Item.INFO_UPDATE must exist!"); + //throw new IllegalArgumentException("Unknown legacy2Runtime mapping: id=" + id + " meta=" + meta); } return runtimeEntry; } + public Item parseCreativeItem(JsonObject json, boolean ignoreUnknown) { + String identifier = json.get("id").getAsString(); + LegacyEntry legacyEntry = this.fromIdentifier(identifier); + if (legacyEntry == null) { + log.trace("Can not find legacyEntry for " + identifier); + if (!ignoreUnknown) { + throw new IllegalStateException("Can not find legacyEntry for " + identifier); + } + return null; + } + + byte[] nbtBytes; + if (json.has("nbt_b64")) { + nbtBytes = Base64.getDecoder().decode(json.get("nbt_b64").getAsString()); + } else if (json.has("nbt_hex")) { + nbtBytes = Utils.parseHexBinary(json.get("nbt_hex").getAsString()); + } else { + nbtBytes = new byte[0]; + } + + int legacyId = legacyEntry.getLegacyId(); + int damage = 0; + if (json.has("damage")) { + damage = json.get("damage").getAsInt(); + } else if (legacyEntry.isHasDamage()) { + damage = legacyEntry.getDamage(); + } else if (json.has("blockRuntimeId")) { + int runtimeId = json.get("blockRuntimeId").getAsInt(); + int fullId = GlobalBlockPalette.getLegacyFullId(runtimeId); + if (fullId == -1) { + if (ignoreUnknown) { + return null; + } else { + throw new IllegalStateException("Can not find blockRuntimeId for " + identifier + " (" + runtimeId + ")"); + } + } + + damage = fullId & Block.DATA_MASK; + } + + int count = json.has("count") ? json.get("count").getAsInt() : 1; + return Item.get(legacyId, damage, count, nbtBytes); + } + + public LegacyEntry fromIdentifier(String identifier) { return this.identifier2Legacy.get(identifier); } diff --git a/src/main/java/cn/nukkit/item/RuntimeItems.java b/src/main/java/cn/nukkit/item/RuntimeItems.java index 5e09049b3c0..944ba5cea0b 100644 --- a/src/main/java/cn/nukkit/item/RuntimeItems.java +++ b/src/main/java/cn/nukkit/item/RuntimeItems.java @@ -1,17 +1,12 @@ package cn.nukkit.item; -import cn.nukkit.item.RuntimeItemMapping.LegacyEntry; -import cn.nukkit.Server; -import cn.nukkit.level.GlobalBlockPalette; +import cn.nukkit.utils.Utils; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import com.google.gson.JsonParser; import lombok.Data; import lombok.experimental.UtilityClass; import lombok.extern.log4j.Log4j2; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Base64; import java.util.HashMap; import java.util.Map; @@ -20,7 +15,11 @@ public class RuntimeItems { private static final Map legacyString2LegacyInt = new HashMap<>(); - private static RuntimeItemMapping itemPalette; + private static final Map legacyInt2LegacyString = new HashMap<>(); + private static final Map latestIdentifierMapping = new HashMap<>(); + + private static RuntimeItemMapping mapping; + private static boolean initialized; public static void init() { @@ -28,89 +27,76 @@ public static void init() { throw new IllegalStateException("RuntimeItems were already generated!"); } initialized = true; - log.info("Loading runtime items..."); - - InputStream itemIdsStream = Server.class.getClassLoader().getResourceAsStream("legacy_item_ids.json"); - if (itemIdsStream == null) { - throw new AssertionError("Unable to load legacy_item_ids.json"); - } + log.debug("Loading runtime items..."); - JsonObject json = JsonParser.parseReader(new InputStreamReader(itemIdsStream)).getAsJsonObject(); - for (String identifier : json.keySet()) { - legacyString2LegacyInt.put(identifier, json.get(identifier).getAsInt()); + JsonObject json = Utils.loadJsonResource("legacy_item_ids.json").getAsJsonObject(); + for (Map.Entry identifierToId : json.entrySet()) { + int legacyId = identifierToId.getValue().getAsInt(); + legacyString2LegacyInt.put(identifierToId.getKey(), legacyId); + legacyInt2LegacyString.put(legacyId, identifierToId.getKey()); } - InputStream mappingStream = Server.class.getClassLoader().getResourceAsStream("item_mappings.json"); - if (mappingStream == null) { - throw new AssertionError("Unable to load item_mappings.json"); - } - JsonObject itemMapping = JsonParser.parseReader(new InputStreamReader(mappingStream)).getAsJsonObject(); - - Map mappingEntries = new HashMap<>(); + JsonObject itemMapping = Utils.loadJsonResource("item_mappings.json").getAsJsonObject(); + Map mappingEntries = latestIdentifierMapping; // keep it same with master + Map mappingEntriesLegacy = new HashMap<>(); for (String legacyName : itemMapping.keySet()) { JsonObject convertData = itemMapping.getAsJsonObject(legacyName); + boolean isLegacyStone = "minecraft:stone".equals(legacyName); + for (String damageStr : convertData.keySet()) { String identifier = convertData.get(damageStr).getAsString(); int damage = Integer.parseInt(damageStr); mappingEntries.put(identifier, new MappingEntry(legacyName, damage)); - } - } - itemPalette = new RuntimeItemMapping(mappingEntries); - } - - public static Item parseCreativeItem(JsonObject json, boolean ignoreUnknown) { - String identifier = json.get("id").getAsString(); - LegacyEntry legacyEntry = itemPalette.fromIdentifier(identifier); - if (legacyEntry == null) { - if (!ignoreUnknown) { - throw new IllegalStateException("Can not find legacyEntry for " + identifier); - } - log.debug("Can not find legacyEntry for " + identifier); - return null; - } - - byte[] nbtBytes; - if (json.has("nbt_b64")) { - nbtBytes = Base64.getDecoder().decode(json.get("nbt_b64").getAsString()); - } else { - nbtBytes = new byte[0]; - } - int legacyId = legacyEntry.getLegacyId(); - int damage = 0; - if (json.has("damage")) { - damage = json.get("damage").getAsInt(); - } else if (legacyEntry.isHasDamage()) { - damage = legacyEntry.getDamage(); - } else if (json.has("blockRuntimeId")) { - int runtimeId = json.get("blockRuntimeId").getAsInt(); - int fullId = GlobalBlockPalette.getLegacyFullId(runtimeId); - if (fullId == -1) { - if (ignoreUnknown) { - return null; - } else { - throw new IllegalStateException("Can not find blockRuntimeId for " + runtimeId); + if (!isLegacyStone) { + mappingEntriesLegacy.put(identifier, new MappingEntry(legacyName, damage)); } } - - damage = fullId & 0xf; } - int count = json.has("count") ? json.get("count").getAsInt() : 1; - return Item.get(legacyId, damage, count, nbtBytes); + mapping = new RuntimeItemMapping(mappingEntries); } public static RuntimeItemMapping getMapping() { - return itemPalette; + return mapping; } public static int getLegacyIdFromLegacyString(String identifier) { return legacyString2LegacyInt.getOrDefault(identifier, -1); } + public static String getLegacyStringFromLegacyId(int legacyId) { + return legacyInt2LegacyString.getOrDefault(legacyId, "minecraft:info_update"); + } + + public static String getLegacyStringFromNew(String identifier) { + MappingEntry entry = latestIdentifierMapping.get(identifier); + return entry == null ? identifier : entry.getLegacyName(); + } + @Data public static class MappingEntry { private final String legacyName; private final int damage; } + + public static int getId(int fullId) { + return (short) (fullId >> 16); + } + + public static int getData(int fullId) { + return ((fullId >> 1) & 0x7fff); + } + + public static int getFullId(int id, int data) { + return (((short) id) << 16) | ((data & 0x7fff) << 1); + } + + public static int getNetworkId(int networkFullId) { + return networkFullId >> 1; + } + + public static boolean hasData(int id) { + return (id & 0x1) != 0; + } } diff --git a/src/main/java/cn/nukkit/item/custom/CustomItem.java b/src/main/java/cn/nukkit/item/custom/CustomItem.java new file mode 100644 index 00000000000..b083ad0e040 --- /dev/null +++ b/src/main/java/cn/nukkit/item/custom/CustomItem.java @@ -0,0 +1,10 @@ +package cn.nukkit.item.custom; + +public interface CustomItem { + + ItemDefinition getItemDefinition(); + + default String getIdentifier() { + return this.getItemDefinition().getIdentifier(); + } +} diff --git a/src/main/java/cn/nukkit/item/custom/CustomItemManager.java b/src/main/java/cn/nukkit/item/custom/CustomItemManager.java new file mode 100644 index 00000000000..39fca831871 --- /dev/null +++ b/src/main/java/cn/nukkit/item/custom/CustomItemManager.java @@ -0,0 +1,138 @@ +package cn.nukkit.item.custom; + +import cn.nukkit.item.Item; +import cn.nukkit.item.RuntimeItems; +import cn.nukkit.network.protocol.BatchPacket; +import cn.nukkit.network.protocol.ItemComponentPacket; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.zip.Deflater; + +/** + * Handles custom item registry. + *

+ * See CustomItemExample for example usage + */ +public class CustomItemManager { + + /** + * Lowest allowed Nukkit save id for custom items + */ + public static final int LOWEST_CUSTOM_ITEM_ID = 5000; + + private static final CustomItemManager INSTANCE = new CustomItemManager(); + + /** + * Get CustomItemManager instance + */ + public static CustomItemManager get() { + return INSTANCE; + } + + private final Map itemDefinitions = new HashMap<>(); + private final Int2ObjectMap legacyDefinitions = new Int2ObjectOpenHashMap<>(); + + private volatile boolean closed; + + private BatchPacket cachedPacket; + + private CustomItemManager() { + + } + + public BatchPacket getCachedPacket() { + if (this.cachedPacket == null) { + ItemComponentPacket pk = new ItemComponentPacket(); + pk.itemDefinitions = new ArrayList<>(this.itemDefinitions.values()); + pk.tryEncode(); + this.cachedPacket = pk.compress(Deflater.BEST_COMPRESSION); + } + return this.cachedPacket; + } + + @SuppressWarnings("unused") + public void registerDefinition(ItemDefinition definition) { + if (this.closed) { + throw new IllegalStateException("Item registry was already closed"); + } + + if (definition.getLegacyId() < LOWEST_CUSTOM_ITEM_ID) { + throw new IllegalArgumentException("Custom item ID can not be lower than " + LOWEST_CUSTOM_ITEM_ID); + } + + if (definition.getLegacyId() > 65534) { + throw new IllegalArgumentException("Custom item ID can not be higher than 65534"); + } + + if (this.legacyDefinitions.containsKey(definition.getLegacyId())) { + throw new IllegalArgumentException("Custom item " + definition.getIdentifier() + " cannot be registered because legacy ID " + + definition.getLegacyId() +" is already used by " + this.getDefinition(definition.getLegacyId()).getIdentifier()); + } + + if (this.itemDefinitions.containsKey(definition.getIdentifier())) { + throw new IllegalArgumentException("Custom item " + definition.getIdentifier() + " was already registered"); + } + + this.itemDefinitions.put(definition.getIdentifier(), definition); + this.legacyDefinitions.put(definition.getLegacyId(), definition); + + Item.list[definition.getLegacyId()] = definition.getImplementation(); + + RuntimeItems.getMapping().registerItem(definition.getIdentifier(), definition.getLegacyId(), definition.getLegacyId(), 0); + + if (definition.getCreativeCategory() != null && definition.getCreativeCategory() != ItemDefinition.CreativeCategory.NONE) { + try { + Item item = definition.getImplementation().getConstructor(Integer.class, int.class).newInstance(0, 1); + if (!(item instanceof CustomItem)) { + throw new IllegalStateException("Implementation of " + definition.getIdentifier() + " does not implement CustomItem"); + } + Item.addCreativeItem(item); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + + public ItemDefinition getDefinition(String identifier) { + return this.itemDefinitions.get(identifier); + } + + public ItemDefinition getDefinition(int legacyId) { + return this.legacyDefinitions.get(legacyId); + } + + public int getLegacyId(String identifier) { + ItemDefinition definition = this.itemDefinitions.get(identifier); + if (definition == null) { + return -1; + } + return definition.getLegacyId(); + } + + public boolean hasCustomItems() { + return !this.itemDefinitions.isEmpty(); + } + + /** + * Internal: close registry to prepare for data generation + */ + public boolean closeRegistry() { + if (this.closed) { + throw new IllegalStateException("Item registry was already closed"); + } + + this.closed = true; + + boolean hasItems = this.hasCustomItems(); + + if (hasItems) { + this.getCachedPacket(); + } + + return hasItems; + } +} diff --git a/src/main/java/cn/nukkit/item/custom/ItemDefinition.java b/src/main/java/cn/nukkit/item/custom/ItemDefinition.java new file mode 100644 index 00000000000..88cb8ae7b06 --- /dev/null +++ b/src/main/java/cn/nukkit/item/custom/ItemDefinition.java @@ -0,0 +1,183 @@ +package cn.nukkit.item.custom; + +import cn.nukkit.item.Item; +import cn.nukkit.item.ItemEdible; +import cn.nukkit.nbt.tag.CompoundTag; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; + +import java.util.List; + +@Builder +@Data +public class ItemDefinition { + + // Prefer having properties related to server side behavior in implementation class + + /** + * Item identifier + */ + private final String identifier; + + /** + * Nukkit save ID for the item + */ + private final int legacyId; + + /** + * Class which implements the item behavior + */ + private final Class implementation; + + /** + * Item default texture name + */ + private final String texture; + + /** + * Override item name given in implementation class constructor + */ + private final String overrideDisplayName; + + /** + * Creative inventory page where the item is put into + */ + private final CreativeCategory creativeCategory; + + /** + * Group items in creative inventory + */ + private final String creativeGroup; + + /** + * Whether item is displayed with enchantment glint even when not enchanted (like enchanted golden apple) + */ + private final boolean foil; + + /** + * Whether item can be used to destroy blocks on creative (disable to match sword behavior) + */ + @Builder.Default private final boolean canDestroyInCreative = true; + + /** + * Allow plugins to provide properties we haven't implemented yet + */ + private final List customProperties; + + /** + * Allow plugins to provide components we haven't implemented yet + */ + private final List customComponents; + + /** + * Get the nbt tag that is sent to client + */ + public CompoundTag getNetworkData() { + try { + Item item = this.implementation.getConstructor(Integer.class, int.class).newInstance(0, 1); + if (!(item instanceof CustomItem)) { + throw new IllegalStateException("Implementation of " + this.identifier + " does not implement CustomItem"); + } + + CompoundTag properties = new CompoundTag() + .putInt("max_stack_size", item.getMaxStackSize()) + .putBoolean("hand_equipped", item.isTool()) + .putBoolean("allow_off_hand", item.allowOffhand()) + .putBoolean("can_destroy_in_creative", this.canDestroyInCreative); + + properties.putCompound("minecraft:icon", new CompoundTag() + .putCompound("textures", new CompoundTag() + .putString("default", this.texture) + ) + ); + + if (this.creativeCategory != null) { + properties.putInt("creative_category", this.creativeCategory.id); + + if (this.creativeCategory != CreativeCategory.NONE && this.creativeGroup != null) { + properties.putString("creative_group", this.creativeGroup); + } + } + + if (this.foil) { + properties.putBoolean("foil", true); + } + + CompoundTag components = new CompoundTag() + .putCompound("item_properties", properties) + .putCompound("minecraft:display_name", new CompoundTag() + .putString("value", this.overrideDisplayName == null ? item.getName() : this.overrideDisplayName) + ); + + if (item.getMaxDurability() > 0) { + components.putCompound("minecraft:durability", new CompoundTag().putInt("max_durability", item.getMaxDurability())); + } + + if (item.isArmor()) { + components.putCompound("minecraft:armor", new CompoundTag().putInt("protection", item.getArmorPoints())); + + if (item.isHelmet()) { + properties.putString("wearable_slot", "slot.armor.head"); + components.putCompound("minecraft:wearable", new CompoundTag().putString("slot", "slot.armor.head")); + } else if (item.isChestplate()) { + properties.putString("wearable_slot", "slot.armor.chest"); + components.putCompound("minecraft:wearable", new CompoundTag().putString("slot", "slot.armor.chest")); + } else if (item.isLeggings()) { + properties.putString("wearable_slot", "slot.armor.legs"); + components.putCompound("minecraft:wearable", new CompoundTag().putString("slot", "slot.armor.legs")); + } else if (item.isBoots()) { + properties.putString("wearable_slot", "slot.armor.feet"); + components.putCompound("minecraft:wearable", new CompoundTag().putString("slot", "slot.armor.feet")); + } + } + + if (item instanceof ItemEdible) { + components.putCompound("minecraft:food", new CompoundTag() + .putBoolean("can_always_eat", ((ItemEdible) item).canAlwaysEat()) + ); + + properties.putInt("use_duration", ((ItemEdible) item).getUseTicks()).putInt("use_animation", ((ItemEdible) item).isDrink() ? 2 : 1); + } + + if (item.isTool()) { + properties.putInt("damage", item.getAttackDamage()); + + /*if (item.isPickaxe()) { + components.putCompound("minecraft:digger", getPickaxeDiggerNBT(item)); + } else if (item.isAxe()) { + components.putCompound("minecraft:digger", getAxeDiggerNBT(item)); + } else if (item.isShovel()) { + components.putCompound("minecraft:digger", getShovelDiggerNBT(item)); + }*/ + } + + if (this.customProperties != null) { + for (CompoundTag property : this.customProperties) { + components.putCompound(property.getName(), property); + } + } + + if (this.customComponents != null) { + for (CompoundTag component : this.customComponents) { + components.putCompound(component.getName(), component); + } + } + + return new CompoundTag().putCompound("components", components); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @AllArgsConstructor + public enum CreativeCategory { + CONSTRUCTION(1), + NATURE(2), + EQUIPMENT(3), + ITEMS(4), + NONE(6); + + private final int id; + } +} diff --git a/src/main/java/cn/nukkit/item/enchantment/Enchantment.java b/src/main/java/cn/nukkit/item/enchantment/Enchantment.java index 5f5753ff7b5..dda16e1c1c2 100644 --- a/src/main/java/cn/nukkit/item/enchantment/Enchantment.java +++ b/src/main/java/cn/nukkit/item/enchantment/Enchantment.java @@ -21,21 +21,18 @@ import cn.nukkit.item.enchantment.trident.EnchantmentTridentImpaling; import cn.nukkit.item.enchantment.trident.EnchantmentTridentLoyalty; import cn.nukkit.item.enchantment.trident.EnchantmentTridentRiptide; -import cn.nukkit.math.NukkitMath; +import cn.nukkit.utils.Utils; import java.util.ArrayList; import java.util.HashSet; -import java.util.concurrent.ThreadLocalRandom; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class Enchantment implements Cloneable { - protected static Enchantment[] enchantments; - - //http://minecraft.gamepedia.com/Enchanting#Aqua_Affinity + public static Enchantment[] enchantments = new Enchantment[256]; public static final int ID_PROTECTION_ALL = 0; public static final int ID_PROTECTION_FIRE = 1; @@ -77,8 +74,6 @@ public abstract class Enchantment implements Cloneable { public static final int ID_SWIFT_SNEAK = 37; public static void init() { - enchantments = new Enchantment[256]; - enchantments[ID_PROTECTION_ALL] = new EnchantmentProtectionAll(); enchantments[ID_PROTECTION_FIRE] = new EnchantmentProtectionFire(); enchantments[ID_PROTECTION_FALL] = new EnchantmentProtectionFall(); @@ -109,8 +104,8 @@ public static void init() { enchantments[ID_BINDING_CURSE] = new EnchantmentBindingCurse(); enchantments[ID_VANISHING_CURSE] = new EnchantmentVanishingCurse(); enchantments[ID_TRIDENT_IMPALING] = new EnchantmentTridentImpaling(); - enchantments[ID_TRIDENT_RIPTIDE] = new EnchantmentTridentRiptide(); enchantments[ID_TRIDENT_LOYALTY] = new EnchantmentTridentLoyalty(); + enchantments[ID_TRIDENT_RIPTIDE] = new EnchantmentTridentRiptide(); enchantments[ID_TRIDENT_CHANNELING] = new EnchantmentTridentChanneling(); enchantments[ID_CROSSBOW_MULTISHOT] = new EnchantmentCrossbowMultishot(); enchantments[ID_CROSSBOW_PIERCING] = new EnchantmentCrossbowPiercing(); @@ -177,7 +172,9 @@ public Enchantment setLevel(int level, boolean safe) { return this; } - this.level = NukkitMath.clamp(level, this.getMinLevel(), this.getMaxLevel()); + if (level > this.getMaxLevel()) { + this.level = this.getMaxLevel(); + } else this.level = Math.max(level, this.getMinLevel()); return this; } @@ -258,6 +255,10 @@ public boolean isMajor() { return false; } + public boolean isTreasure() { + return false; + } + @Override protected Enchantment clone() { try { @@ -270,10 +271,9 @@ protected Enchantment clone() { public static final String[] words = {"the", "elder", "scrolls", "klaatu", "berata", "niktu", "xyzzy", "bless", "curse", "light", "darkness", "fire", "air", "earth", "water", "hot", "dry", "cold", "wet", "ignite", "snuff", "embiggen", "twist", "shorten", "stretch", "fiddle", "destroy", "imbue", "galvanize", "enchant", "free", "limited", "range", "of", "towards", "inside", "sphere", "cube", "self", "other", "ball", "mental", "physical", "grow", "shrink", "demon", "elemental", "spirit", "animal", "creature", "beast", "humanoid", "undead", "fresh", "stale"}; public static String getRandomName() { - int count = ThreadLocalRandom.current().nextInt(3, 6); HashSet set = new HashSet<>(); - while (set.size() < count) { - set.add(Enchantment.words[ThreadLocalRandom.current().nextInt(0, Enchantment.words.length)]); + while (set.size() < Utils.random.nextInt(3, 6)) { + set.add(Enchantment.words[Utils.random.nextInt(0, Enchantment.words.length)]); } String[] words = set.toArray(new String[0]); diff --git a/src/main/java/cn/nukkit/item/enchantment/EnchantmentBindingCurse.java b/src/main/java/cn/nukkit/item/enchantment/EnchantmentBindingCurse.java index 7d511415002..e2d0b1876be 100644 --- a/src/main/java/cn/nukkit/item/enchantment/EnchantmentBindingCurse.java +++ b/src/main/java/cn/nukkit/item/enchantment/EnchantmentBindingCurse.java @@ -1,17 +1,23 @@ -package cn.nukkit.item.enchantment; - -public class EnchantmentBindingCurse extends Enchantment { - protected EnchantmentBindingCurse() { - super(ID_BINDING_CURSE, "curse.binding", Rarity.VERY_RARE, EnchantmentType.WEARABLE); - } - - @Override - public int getMinEnchantAbility(int level) { - return 25; - } - - @Override - public int getMaxEnchantAbility(int level) { - return 30; - } -} +package cn.nukkit.item.enchantment; + +public class EnchantmentBindingCurse extends Enchantment { + + protected EnchantmentBindingCurse() { + super(ID_BINDING_CURSE, "curse.binding", Rarity.VERY_RARE, EnchantmentType.WEARABLE); + } + + @Override + public int getMinEnchantAbility(int level) { + return 25; + } + + @Override + public int getMaxEnchantAbility(int level) { + return 30; + } + + @Override + public boolean isTreasure() { + return true; + } +} diff --git a/src/main/java/cn/nukkit/item/enchantment/EnchantmentDurability.java b/src/main/java/cn/nukkit/item/enchantment/EnchantmentDurability.java index 8cd4140069a..1f3e533e306 100644 --- a/src/main/java/cn/nukkit/item/enchantment/EnchantmentDurability.java +++ b/src/main/java/cn/nukkit/item/enchantment/EnchantmentDurability.java @@ -5,17 +5,18 @@ import java.util.Random; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentDurability extends Enchantment { + protected EnchantmentDurability() { super(ID_DURABILITY, "durability", Rarity.UNCOMMON, EnchantmentType.BREAKABLE); } @Override public int getMinEnchantAbility(int level) { - return 5 + (level - 1) * 8; + return 5 + ((level - 1) << 3); } @Override @@ -28,11 +29,6 @@ public int getMaxLevel() { return 3; } - @Override - public boolean checkCompatibility(Enchantment enchantment) { - return super.checkCompatibility(enchantment) && enchantment.id != ID_FORTUNE_DIGGING; - } - @Override public boolean canEnchant(Item item) { return item.getMaxDurability() >= 0 || super.canEnchant(item); diff --git a/src/main/java/cn/nukkit/item/enchantment/EnchantmentEfficiency.java b/src/main/java/cn/nukkit/item/enchantment/EnchantmentEfficiency.java index 35581c0cf3f..289c601d9ed 100644 --- a/src/main/java/cn/nukkit/item/enchantment/EnchantmentEfficiency.java +++ b/src/main/java/cn/nukkit/item/enchantment/EnchantmentEfficiency.java @@ -3,10 +3,11 @@ import cn.nukkit.item.Item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentEfficiency extends Enchantment { + protected EnchantmentEfficiency() { super(ID_EFFICIENCY, "digging", Rarity.COMMON, EnchantmentType.DIGGER); } diff --git a/src/main/java/cn/nukkit/item/enchantment/EnchantmentEntry.java b/src/main/java/cn/nukkit/item/enchantment/EnchantmentEntry.java index 1ff6fb9d8d4..52ca6b7c2b6 100644 --- a/src/main/java/cn/nukkit/item/enchantment/EnchantmentEntry.java +++ b/src/main/java/cn/nukkit/item/enchantment/EnchantmentEntry.java @@ -26,5 +26,4 @@ public int getCost() { public String getRandomName() { return randomName; } - } diff --git a/src/main/java/cn/nukkit/item/enchantment/EnchantmentFireAspect.java b/src/main/java/cn/nukkit/item/enchantment/EnchantmentFireAspect.java index 4ebb94500cc..e76d5ed56d6 100644 --- a/src/main/java/cn/nukkit/item/enchantment/EnchantmentFireAspect.java +++ b/src/main/java/cn/nukkit/item/enchantment/EnchantmentFireAspect.java @@ -6,10 +6,11 @@ import cn.nukkit.event.entity.EntityCombustByEntityEvent; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentFireAspect extends Enchantment { + protected EnchantmentFireAspect() { super(ID_FIRE_ASPECT, "fire", Rarity.RARE, EnchantmentType.SWORD); } diff --git a/src/main/java/cn/nukkit/item/enchantment/EnchantmentFrostWalker.java b/src/main/java/cn/nukkit/item/enchantment/EnchantmentFrostWalker.java index 7f75d0e2d35..8bd9fac1487 100644 --- a/src/main/java/cn/nukkit/item/enchantment/EnchantmentFrostWalker.java +++ b/src/main/java/cn/nukkit/item/enchantment/EnchantmentFrostWalker.java @@ -1,17 +1,28 @@ -package cn.nukkit.item.enchantment; - -public class EnchantmentFrostWalker extends Enchantment { - protected EnchantmentFrostWalker() { - super(ID_FROST_WALKER, "frostwalker", Rarity.RARE, EnchantmentType.ARMOR_FEET); - } - - @Override - public int getMaxEnchantAbility(int level) { - return this.getMinEnchantAbility(level) + 15; - } - - @Override - public int getMaxLevel() { - return 2; - } -} +package cn.nukkit.item.enchantment; + +public class EnchantmentFrostWalker extends Enchantment { + + protected EnchantmentFrostWalker() { + super(ID_FROST_WALKER, "frostwalker", Rarity.RARE, EnchantmentType.ARMOR_FEET); + } + + @Override + public int getMaxEnchantAbility(int level) { + return this.getMinEnchantAbility(level) + 15; + } + + @Override + public int getMaxLevel() { + return 2; + } + + @Override + public boolean isTreasure() { + return true; + } + + @Override + public boolean checkCompatibility(Enchantment enchantment) { + return super.checkCompatibility(enchantment) && enchantment.id != ID_WATER_WALKER; + } +} diff --git a/src/main/java/cn/nukkit/item/enchantment/EnchantmentKnockback.java b/src/main/java/cn/nukkit/item/enchantment/EnchantmentKnockback.java index e920eb91f67..bd4d47e0174 100644 --- a/src/main/java/cn/nukkit/item/enchantment/EnchantmentKnockback.java +++ b/src/main/java/cn/nukkit/item/enchantment/EnchantmentKnockback.java @@ -1,10 +1,11 @@ package cn.nukkit.item.enchantment; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentKnockback extends Enchantment { + protected EnchantmentKnockback() { super(ID_KNOCKBACK, "knockback", Rarity.UNCOMMON, EnchantmentType.SWORD); } diff --git a/src/main/java/cn/nukkit/item/enchantment/EnchantmentList.java b/src/main/java/cn/nukkit/item/enchantment/EnchantmentList.java index 5723e969d28..e890348087b 100644 --- a/src/main/java/cn/nukkit/item/enchantment/EnchantmentList.java +++ b/src/main/java/cn/nukkit/item/enchantment/EnchantmentList.java @@ -28,5 +28,4 @@ public EnchantmentEntry getSlot(int slot) { public int getSize() { return enchantments.length; } - } diff --git a/src/main/java/cn/nukkit/item/enchantment/EnchantmentLure.java b/src/main/java/cn/nukkit/item/enchantment/EnchantmentLure.java index d8890a6e053..51cd8fa3ef6 100644 --- a/src/main/java/cn/nukkit/item/enchantment/EnchantmentLure.java +++ b/src/main/java/cn/nukkit/item/enchantment/EnchantmentLure.java @@ -1,10 +1,11 @@ package cn.nukkit.item.enchantment; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentLure extends Enchantment { + protected EnchantmentLure() { super(ID_LURE, "fishingSpeed", Rarity.RARE, EnchantmentType.FISHING_ROD); } diff --git a/src/main/java/cn/nukkit/item/enchantment/EnchantmentMending.java b/src/main/java/cn/nukkit/item/enchantment/EnchantmentMending.java index 2b9e9fc3b48..c07de608377 100644 --- a/src/main/java/cn/nukkit/item/enchantment/EnchantmentMending.java +++ b/src/main/java/cn/nukkit/item/enchantment/EnchantmentMending.java @@ -4,6 +4,7 @@ * @author Rover656 */ public class EnchantmentMending extends Enchantment { + protected EnchantmentMending() { super(ID_MENDING, "mending", Rarity.RARE, EnchantmentType.BREAKABLE); } @@ -18,6 +19,11 @@ public int getMaxEnchantAbility(int level) { return this.getMinEnchantAbility(level) + 50; } + @Override + public boolean isTreasure() { + return true; + } + @Override public boolean checkCompatibility(Enchantment enchantment) { return super.checkCompatibility(enchantment) && enchantment.id != ID_BOW_INFINITY; diff --git a/src/main/java/cn/nukkit/item/enchantment/EnchantmentSilkTouch.java b/src/main/java/cn/nukkit/item/enchantment/EnchantmentSilkTouch.java index 550dea32eba..740ee115f0a 100644 --- a/src/main/java/cn/nukkit/item/enchantment/EnchantmentSilkTouch.java +++ b/src/main/java/cn/nukkit/item/enchantment/EnchantmentSilkTouch.java @@ -3,10 +3,11 @@ import cn.nukkit.item.Item; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentSilkTouch extends Enchantment { + protected EnchantmentSilkTouch() { super(ID_SILK_TOUCH, "untouching", Rarity.VERY_RARE, EnchantmentType.DIGGER); } diff --git a/src/main/java/cn/nukkit/item/enchantment/EnchantmentSoulSpeed.java b/src/main/java/cn/nukkit/item/enchantment/EnchantmentSoulSpeed.java index e5d8e1356b2..0fbfa0a3837 100644 --- a/src/main/java/cn/nukkit/item/enchantment/EnchantmentSoulSpeed.java +++ b/src/main/java/cn/nukkit/item/enchantment/EnchantmentSoulSpeed.java @@ -15,4 +15,9 @@ public int getMinEnchantAbility(int level) { public int getMaxLevel() { return 3; } + + @Override + public boolean isTreasure() { + return true; + } } diff --git a/src/main/java/cn/nukkit/item/enchantment/EnchantmentThorns.java b/src/main/java/cn/nukkit/item/enchantment/EnchantmentThorns.java index cf85ed2cb97..14b0d90e5ab 100644 --- a/src/main/java/cn/nukkit/item/enchantment/EnchantmentThorns.java +++ b/src/main/java/cn/nukkit/item/enchantment/EnchantmentThorns.java @@ -9,10 +9,11 @@ import java.util.concurrent.ThreadLocalRandom; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentThorns extends Enchantment { + protected EnchantmentThorns() { super(ID_THORNS, "thorns", Rarity.RARE, EnchantmentType.ARMOR); } @@ -34,7 +35,7 @@ public int getMaxLevel() { @Override public void doPostAttack(Entity attacker, Entity entity) { - if (!(entity instanceof EntityHumanType)) { + if (!(entity instanceof EntityHumanType) || attacker == entity) { return; } @@ -52,7 +53,7 @@ public void doPostAttack(Entity attacker, Entity entity) { ThreadLocalRandom random = ThreadLocalRandom.current(); if (shouldHit(random, thornsLevel)) { - attacker.attack(new EntityDamageByEntityEvent(entity, attacker, EntityDamageEvent.DamageCause.ENTITY_ATTACK, getDamage(random, level), 0f)); + attacker.attack(new EntityDamageByEntityEvent(entity, attacker, EntityDamageEvent.DamageCause.THORNS, getDamage(random, level), 0f)); } } @@ -63,4 +64,4 @@ private static boolean shouldHit(ThreadLocalRandom random, int level) { private static int getDamage(ThreadLocalRandom random, int level) { return level > 10 ? level - 10 : random.nextInt(1, 5); } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/item/enchantment/EnchantmentType.java b/src/main/java/cn/nukkit/item/enchantment/EnchantmentType.java index 676a15cb08f..037c4c8865e 100644 --- a/src/main/java/cn/nukkit/item/enchantment/EnchantmentType.java +++ b/src/main/java/cn/nukkit/item/enchantment/EnchantmentType.java @@ -1,15 +1,10 @@ package cn.nukkit.item.enchantment; -import cn.nukkit.item.Item; -import cn.nukkit.item.ItemArmor; -import cn.nukkit.item.ItemBow; -import cn.nukkit.item.ItemCrossbow; -import cn.nukkit.item.ItemFishingRod; -import cn.nukkit.item.ItemSkull; -import cn.nukkit.item.ItemTrident; +import cn.nukkit.block.BlockID; +import cn.nukkit.item.*; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public enum EnchantmentType { @@ -52,11 +47,10 @@ public boolean canEnchantItem(Item item) { default: return false; } - } else { switch (this) { case SWORD: - return item.isSword(); + return item.isSword() && item.getId() != ItemID.TRIDENT; case DIGGER: return item.isPickaxe() || item.isShovel() || item.isAxe() || item.isHoe(); case BOW: @@ -64,7 +58,7 @@ public boolean canEnchantItem(Item item) { case FISHING_ROD: return item instanceof ItemFishingRod; case WEARABLE: - return item instanceof ItemSkull; + return item instanceof ItemSkull || item.getId() == (255 - BlockID.CARVED_PUMPKIN); case TRIDENT: return item instanceof ItemTrident; case CROSSBOW: diff --git a/src/main/java/cn/nukkit/item/enchantment/EnchantmentVanishingCurse.java b/src/main/java/cn/nukkit/item/enchantment/EnchantmentVanishingCurse.java index 928398ee5fb..40ad778af19 100644 --- a/src/main/java/cn/nukkit/item/enchantment/EnchantmentVanishingCurse.java +++ b/src/main/java/cn/nukkit/item/enchantment/EnchantmentVanishingCurse.java @@ -1,14 +1,19 @@ -package cn.nukkit.item.enchantment; - -import cn.nukkit.item.Item; - -public class EnchantmentVanishingCurse extends Enchantment { - protected EnchantmentVanishingCurse() { - super(ID_VANISHING_CURSE, "curse.vanishing", Rarity.VERY_RARE, EnchantmentType.BREAKABLE); - } - - @Override - public boolean canEnchant(Item item) { - return item.getId() == Item.SKULL || item.getId() == Item.COMPASS || super.canEnchant(item); - } -} +package cn.nukkit.item.enchantment; + +import cn.nukkit.item.Item; + +public class EnchantmentVanishingCurse extends Enchantment { + + protected EnchantmentVanishingCurse() { + super(ID_VANISHING_CURSE, "curse.vanishing", Rarity.VERY_RARE, EnchantmentType.BREAKABLE); + } + + @Override + public boolean isTreasure() { + return true; + } + + public boolean canEnchant(Item item) { + return item.getId() == Item.SKULL || item.getId() == Item.COMPASS || super.canEnchant(item); + } +} diff --git a/src/main/java/cn/nukkit/item/enchantment/EnchantmentWaterBreath.java b/src/main/java/cn/nukkit/item/enchantment/EnchantmentWaterBreath.java index 694b59ee54d..7e1fd5e3f61 100644 --- a/src/main/java/cn/nukkit/item/enchantment/EnchantmentWaterBreath.java +++ b/src/main/java/cn/nukkit/item/enchantment/EnchantmentWaterBreath.java @@ -1,10 +1,11 @@ package cn.nukkit.item.enchantment; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentWaterBreath extends Enchantment { + protected EnchantmentWaterBreath() { super(ID_WATER_BREATHING, "oxygen", Rarity.RARE, EnchantmentType.ARMOR_HEAD); } diff --git a/src/main/java/cn/nukkit/item/enchantment/EnchantmentWaterWalker.java b/src/main/java/cn/nukkit/item/enchantment/EnchantmentWaterWalker.java index 4a6afdba2fd..36a0b4f79da 100644 --- a/src/main/java/cn/nukkit/item/enchantment/EnchantmentWaterWalker.java +++ b/src/main/java/cn/nukkit/item/enchantment/EnchantmentWaterWalker.java @@ -1,10 +1,11 @@ package cn.nukkit.item.enchantment; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentWaterWalker extends Enchantment { + protected EnchantmentWaterWalker() { super(ID_WATER_WALKER, "waterWalker", Rarity.RARE, EnchantmentType.ARMOR_FEET); } diff --git a/src/main/java/cn/nukkit/item/enchantment/EnchantmentWaterWorker.java b/src/main/java/cn/nukkit/item/enchantment/EnchantmentWaterWorker.java index baa9e4542c0..b8e45b52a95 100644 --- a/src/main/java/cn/nukkit/item/enchantment/EnchantmentWaterWorker.java +++ b/src/main/java/cn/nukkit/item/enchantment/EnchantmentWaterWorker.java @@ -1,10 +1,11 @@ package cn.nukkit.item.enchantment; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentWaterWorker extends Enchantment { + protected EnchantmentWaterWorker() { super(ID_WATER_WORKER, "waterWorker", Rarity.RARE, EnchantmentType.ARMOR_HEAD); } diff --git a/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBow.java b/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBow.java index 062eaf35df2..30581eab182 100644 --- a/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBow.java +++ b/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBow.java @@ -4,10 +4,11 @@ import cn.nukkit.item.enchantment.EnchantmentType; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class EnchantmentBow extends Enchantment { + protected EnchantmentBow(int id, String name, Rarity rarity) { super(id, name, rarity, EnchantmentType.BOW); } diff --git a/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBowFlame.java b/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBowFlame.java index 62b9f48d54a..6bb109edc3d 100644 --- a/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBowFlame.java +++ b/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBowFlame.java @@ -3,7 +3,7 @@ import cn.nukkit.item.enchantment.Enchantment; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentBowFlame extends EnchantmentBow { diff --git a/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBowInfinity.java b/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBowInfinity.java index f630c80af95..7848e7b75b0 100644 --- a/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBowInfinity.java +++ b/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBowInfinity.java @@ -3,10 +3,11 @@ import cn.nukkit.item.enchantment.Enchantment; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentBowInfinity extends EnchantmentBow { + public EnchantmentBowInfinity() { super(Enchantment.ID_BOW_INFINITY, "arrowInfinite", Rarity.VERY_RARE); } diff --git a/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBowKnockback.java b/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBowKnockback.java index 457e14715f3..51cf980f9aa 100644 --- a/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBowKnockback.java +++ b/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBowKnockback.java @@ -3,7 +3,7 @@ import cn.nukkit.item.enchantment.Enchantment; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentBowKnockback extends EnchantmentBow { @@ -13,7 +13,7 @@ public EnchantmentBowKnockback() { @Override public int getMinEnchantAbility(int level) { - return 12 + (level - 1) * 20; + return this.getMinEnchantAbility(level) + 25; } @Override diff --git a/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBowPower.java b/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBowPower.java index 77b25b7172b..3c832fffcab 100644 --- a/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBowPower.java +++ b/src/main/java/cn/nukkit/item/enchantment/bow/EnchantmentBowPower.java @@ -3,10 +3,11 @@ import cn.nukkit.item.enchantment.Enchantment; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentBowPower extends EnchantmentBow { + public EnchantmentBowPower() { super(Enchantment.ID_BOW_POWER, "arrowDamage", Rarity.COMMON); } diff --git a/src/main/java/cn/nukkit/item/enchantment/damage/EnchantmentDamage.java b/src/main/java/cn/nukkit/item/enchantment/damage/EnchantmentDamage.java index a2a1e5a612b..9f864befdcf 100644 --- a/src/main/java/cn/nukkit/item/enchantment/damage/EnchantmentDamage.java +++ b/src/main/java/cn/nukkit/item/enchantment/damage/EnchantmentDamage.java @@ -5,7 +5,7 @@ import cn.nukkit.item.enchantment.EnchantmentType; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class EnchantmentDamage extends Enchantment { @@ -16,11 +16,8 @@ public enum TYPE { ARTHROPODS } - protected final TYPE damageType; - protected EnchantmentDamage(int id, String name, Rarity rarity, TYPE type) { super(id, name, rarity, EnchantmentType.SWORD); - this.damageType = type; } @Override diff --git a/src/main/java/cn/nukkit/item/enchantment/damage/EnchantmentDamageAll.java b/src/main/java/cn/nukkit/item/enchantment/damage/EnchantmentDamageAll.java index 0cf32eb95c9..7121b211e54 100644 --- a/src/main/java/cn/nukkit/item/enchantment/damage/EnchantmentDamageAll.java +++ b/src/main/java/cn/nukkit/item/enchantment/damage/EnchantmentDamageAll.java @@ -3,7 +3,7 @@ import cn.nukkit.entity.Entity; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentDamageAll extends EnchantmentDamage { @@ -29,6 +29,6 @@ public int getMaxEnchantableLevel() { @Override public double getDamageBonus(Entity entity) { - return this.getLevel() * 1.25; //https://minecraft.fandom.com/wiki/Sharpness#Usage + return this.getLevel() * 1.25; } } diff --git a/src/main/java/cn/nukkit/item/enchantment/damage/EnchantmentDamageArthropods.java b/src/main/java/cn/nukkit/item/enchantment/damage/EnchantmentDamageArthropods.java index 57d08fa2a5d..90a84a0f594 100644 --- a/src/main/java/cn/nukkit/item/enchantment/damage/EnchantmentDamageArthropods.java +++ b/src/main/java/cn/nukkit/item/enchantment/damage/EnchantmentDamageArthropods.java @@ -4,11 +4,10 @@ import cn.nukkit.entity.EntityArthropod; import cn.nukkit.event.entity.EntityPotionEffectEvent; import cn.nukkit.potion.Effect; - -import java.util.concurrent.ThreadLocalRandom; +import cn.nukkit.utils.Utils; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentDamageArthropods extends EnchantmentDamage { @@ -19,7 +18,7 @@ public EnchantmentDamageArthropods() { @Override public int getMinEnchantAbility(int level) { - return 5 + (level - 1) * 8; + return 5 + ((level - 1) << 3); } @Override @@ -39,9 +38,8 @@ public double getDamageBonus(Entity entity) { @Override public void doPostAttack(Entity attacker, Entity entity) { if (entity instanceof EntityArthropod) { - int duration = 20 + ThreadLocalRandom.current().nextInt(10 * this.level); entity.addEffect( - Effect.getEffect(Effect.SLOWNESS).setDuration(duration).setAmplifier(3), + Effect.getEffect(Effect.SLOWNESS).setDuration(20 + Utils.random.nextInt(10 * this.level)).setAmplifier(3), EntityPotionEffectEvent.Cause.ATTACK); } } diff --git a/src/main/java/cn/nukkit/item/enchantment/damage/EnchantmentDamageSmite.java b/src/main/java/cn/nukkit/item/enchantment/damage/EnchantmentDamageSmite.java index ec45ba265ec..de0ed9e9ad4 100644 --- a/src/main/java/cn/nukkit/item/enchantment/damage/EnchantmentDamageSmite.java +++ b/src/main/java/cn/nukkit/item/enchantment/damage/EnchantmentDamageSmite.java @@ -4,7 +4,7 @@ import cn.nukkit.entity.EntitySmite; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentDamageSmite extends EnchantmentDamage { @@ -15,7 +15,7 @@ public EnchantmentDamageSmite() { @Override public int getMinEnchantAbility(int level) { - return 5 + (level - 1) * 8; + return 5 + ((level - 1) << 3); } @Override @@ -25,7 +25,7 @@ public int getMaxEnchantAbility(int level) { @Override public double getDamageBonus(Entity entity) { - if(entity instanceof EntitySmite) { + if (entity instanceof EntitySmite) { return getLevel() * 2.5; } diff --git a/src/main/java/cn/nukkit/item/enchantment/loot/EnchantmentLoot.java b/src/main/java/cn/nukkit/item/enchantment/loot/EnchantmentLoot.java index 3be23fe9686..3c002d52086 100644 --- a/src/main/java/cn/nukkit/item/enchantment/loot/EnchantmentLoot.java +++ b/src/main/java/cn/nukkit/item/enchantment/loot/EnchantmentLoot.java @@ -4,7 +4,7 @@ import cn.nukkit.item.enchantment.EnchantmentType; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class EnchantmentLoot extends Enchantment { diff --git a/src/main/java/cn/nukkit/item/enchantment/loot/EnchantmentLootDigging.java b/src/main/java/cn/nukkit/item/enchantment/loot/EnchantmentLootDigging.java index 83d116a69e0..6e5fa3da8a4 100644 --- a/src/main/java/cn/nukkit/item/enchantment/loot/EnchantmentLootDigging.java +++ b/src/main/java/cn/nukkit/item/enchantment/loot/EnchantmentLootDigging.java @@ -4,10 +4,11 @@ import cn.nukkit.item.enchantment.EnchantmentType; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentLootDigging extends EnchantmentLoot { + public EnchantmentLootDigging() { super(Enchantment.ID_FORTUNE_DIGGING, "lootBonusDigger", Rarity.RARE, EnchantmentType.DIGGER); } diff --git a/src/main/java/cn/nukkit/item/enchantment/loot/EnchantmentLootFishing.java b/src/main/java/cn/nukkit/item/enchantment/loot/EnchantmentLootFishing.java index 1016b6f3137..077bad043ef 100644 --- a/src/main/java/cn/nukkit/item/enchantment/loot/EnchantmentLootFishing.java +++ b/src/main/java/cn/nukkit/item/enchantment/loot/EnchantmentLootFishing.java @@ -4,10 +4,11 @@ import cn.nukkit.item.enchantment.EnchantmentType; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentLootFishing extends EnchantmentLoot { + public EnchantmentLootFishing() { super(Enchantment.ID_FORTUNE_FISHING, "lootBonusFishing", Rarity.RARE, EnchantmentType.FISHING_ROD); } diff --git a/src/main/java/cn/nukkit/item/enchantment/loot/EnchantmentLootWeapon.java b/src/main/java/cn/nukkit/item/enchantment/loot/EnchantmentLootWeapon.java index d0f438b2794..8bb5a1834b4 100644 --- a/src/main/java/cn/nukkit/item/enchantment/loot/EnchantmentLootWeapon.java +++ b/src/main/java/cn/nukkit/item/enchantment/loot/EnchantmentLootWeapon.java @@ -4,10 +4,11 @@ import cn.nukkit.item.enchantment.EnchantmentType; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentLootWeapon extends EnchantmentLoot { + public EnchantmentLootWeapon() { super(Enchantment.ID_LOOTING, "lootBonus", Rarity.RARE, EnchantmentType.SWORD); } diff --git a/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtection.java b/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtection.java index 57949b75d1c..7096d26894f 100644 --- a/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtection.java +++ b/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtection.java @@ -4,7 +4,7 @@ import cn.nukkit.item.enchantment.EnchantmentType; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class EnchantmentProtection extends Enchantment { diff --git a/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionAll.java b/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionAll.java index 4db1e0f9616..bb1ad5d21f6 100644 --- a/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionAll.java +++ b/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionAll.java @@ -5,7 +5,7 @@ import cn.nukkit.item.enchantment.Enchantment; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentProtectionAll extends EnchantmentProtection { @@ -33,7 +33,7 @@ public double getTypeModifier() { public float getProtectionFactor(EntityDamageEvent e) { DamageCause cause = e.getCause(); - if (level <= 0 || cause == DamageCause.VOID || cause == DamageCause.CUSTOM || cause == DamageCause.MAGIC || cause == DamageCause.HUNGER) { + if (level <= 0 || cause == DamageCause.VOID || cause == DamageCause.SUICIDE || cause == DamageCause.CUSTOM || cause == DamageCause.HUNGER) { // Apparently protection reduces potion damage now return 0; } diff --git a/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionExplosion.java b/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionExplosion.java index ca2d74693e2..d9e54c2dd28 100644 --- a/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionExplosion.java +++ b/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionExplosion.java @@ -4,7 +4,7 @@ import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentProtectionExplosion extends EnchantmentProtection { @@ -15,7 +15,7 @@ public EnchantmentProtectionExplosion() { @Override public int getMinEnchantAbility(int level) { - return 5 + (level - 1) * 8; + return 5 + ((level - 1) << 3); } @Override diff --git a/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionFall.java b/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionFall.java index 2fc1d91803d..d8cac97d0f5 100644 --- a/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionFall.java +++ b/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionFall.java @@ -4,7 +4,7 @@ import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentProtectionFall extends EnchantmentProtection { diff --git a/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionFire.java b/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionFire.java index f5aeac6a93b..378a4db250e 100644 --- a/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionFire.java +++ b/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionFire.java @@ -4,7 +4,7 @@ import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentProtectionFire extends EnchantmentProtection { @@ -15,7 +15,7 @@ public EnchantmentProtectionFire() { @Override public int getMinEnchantAbility(int level) { - return 10 + (level - 1) * 8; + return 10 + ((level - 1) << 3); } @Override diff --git a/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionProjectile.java b/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionProjectile.java index 5a05696bd7e..9674dd98ce1 100644 --- a/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionProjectile.java +++ b/src/main/java/cn/nukkit/item/enchantment/protection/EnchantmentProtectionProjectile.java @@ -4,7 +4,7 @@ import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EnchantmentProtectionProjectile extends EnchantmentProtection { diff --git a/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTrident.java b/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTrident.java index 4e9b8e066a4..78d3d667f96 100644 --- a/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTrident.java +++ b/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTrident.java @@ -4,6 +4,7 @@ import cn.nukkit.item.enchantment.EnchantmentType; public abstract class EnchantmentTrident extends Enchantment { + protected EnchantmentTrident(int id, String name, Rarity rarity) { super(id, name, rarity, EnchantmentType.TRIDENT); } diff --git a/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTridentChanneling.java b/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTridentChanneling.java index 61956f8db4f..f95939a5afb 100644 --- a/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTridentChanneling.java +++ b/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTridentChanneling.java @@ -1,9 +1,10 @@ -package cn.nukkit.item.enchantment.trident; - -import cn.nukkit.item.enchantment.Enchantment; - -public class EnchantmentTridentChanneling extends EnchantmentTrident { - public EnchantmentTridentChanneling() { - super(Enchantment.ID_TRIDENT_CHANNELING, "tridentChanneling", Rarity.VERY_RARE); - } -} +package cn.nukkit.item.enchantment.trident; + +import cn.nukkit.item.enchantment.Enchantment; + +public class EnchantmentTridentChanneling extends EnchantmentTrident { + + public EnchantmentTridentChanneling() { + super(Enchantment.ID_TRIDENT_CHANNELING, "tridentChanneling", Rarity.VERY_RARE); + } +} diff --git a/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTridentImpaling.java b/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTridentImpaling.java index 384ed212cd2..488217a98b1 100644 --- a/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTridentImpaling.java +++ b/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTridentImpaling.java @@ -1,34 +1,35 @@ -package cn.nukkit.item.enchantment.trident; - -import cn.nukkit.entity.Entity; -import cn.nukkit.item.enchantment.Enchantment; - -public class EnchantmentTridentImpaling extends EnchantmentTrident { - public EnchantmentTridentImpaling() { - super(Enchantment.ID_TRIDENT_IMPALING, "tridentImpaling", Rarity.RARE); - } - - @Override - public int getMinEnchantAbility(int level) { - return 8 * level - 7; - } - - @Override - public int getMaxEnchantAbility(int level) { - return this.getMinEnchantAbility(level) + 20; - } - - @Override - public int getMaxLevel() { - return 5; - } - - @Override - public double getDamageBonus(Entity entity) { - if (entity.isInsideOfWater() || (entity.getLevel().isRaining() && entity.getLevel().canBlockSeeSky(entity))) { - return 2.5 * getLevel(); - } - - return 0; - } -} +package cn.nukkit.item.enchantment.trident; + +import cn.nukkit.entity.Entity; +import cn.nukkit.item.enchantment.Enchantment; + +public class EnchantmentTridentImpaling extends EnchantmentTrident { + + public EnchantmentTridentImpaling() { + super(Enchantment.ID_TRIDENT_IMPALING, "tridentImpaling", Rarity.RARE); + } + + @Override + public int getMinEnchantAbility(int level) { + return 8 * level - 7; + } + + @Override + public int getMaxEnchantAbility(int level) { + return this.getMinEnchantAbility(level) + 20; + } + + @Override + public int getMaxLevel() { + return 5; + } + + @Override + public double getDamageBonus(Entity entity) { + if (entity.isInsideOfWater() || (entity.getLevel().isRaining() && entity.canSeeSky())) { + return 2.5 * getLevel(); + } + + return 0; + } +} diff --git a/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTridentLoyalty.java b/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTridentLoyalty.java index be37f596a15..ee61f5d2b52 100644 --- a/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTridentLoyalty.java +++ b/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTridentLoyalty.java @@ -1,19 +1,20 @@ -package cn.nukkit.item.enchantment.trident; - -import cn.nukkit.item.enchantment.Enchantment; - -public class EnchantmentTridentLoyalty extends EnchantmentTrident { - public EnchantmentTridentLoyalty() { - super(Enchantment.ID_TRIDENT_LOYALTY, "tridentLoyalty", Rarity.UNCOMMON); - } - - @Override - public int getMinEnchantAbility(int level) { - return 7 * level + 5; - } - - @Override - public int getMaxLevel() { - return 3; - } -} +package cn.nukkit.item.enchantment.trident; + +import cn.nukkit.item.enchantment.Enchantment; + +public class EnchantmentTridentLoyalty extends EnchantmentTrident { + + public EnchantmentTridentLoyalty() { + super(Enchantment.ID_TRIDENT_LOYALTY, "tridentLoyalty", Rarity.UNCOMMON); + } + + @Override + public int getMinEnchantAbility(int level) { + return 7 * level + 5; + } + + @Override + public int getMaxLevel() { + return 3; + } +} diff --git a/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTridentRiptide.java b/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTridentRiptide.java index e226fb7d766..65c2bf161a4 100644 --- a/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTridentRiptide.java +++ b/src/main/java/cn/nukkit/item/enchantment/trident/EnchantmentTridentRiptide.java @@ -1,19 +1,20 @@ -package cn.nukkit.item.enchantment.trident; - -import cn.nukkit.item.enchantment.Enchantment; - -public class EnchantmentTridentRiptide extends EnchantmentTrident { - public EnchantmentTridentRiptide() { - super(Enchantment.ID_TRIDENT_RIPTIDE, "tridentRiptide", Rarity.RARE); - } - - @Override - public int getMinEnchantAbility(int level) { - return 7 * level + 10; - } - - @Override - public int getMaxLevel() { - return 3; - } -} +package cn.nukkit.item.enchantment.trident; + +import cn.nukkit.item.enchantment.Enchantment; + +public class EnchantmentTridentRiptide extends EnchantmentTrident { + + public EnchantmentTridentRiptide() { + super(Enchantment.ID_TRIDENT_RIPTIDE, "tridentRiptide", Rarity.RARE); + } + + @Override + public int getMinEnchantAbility(int level) { + return 7 * level + 10; + } + + @Override + public int getMaxLevel() { + return 3; + } +} diff --git a/src/main/java/cn/nukkit/item/food/Food.java b/src/main/java/cn/nukkit/item/food/Food.java index a52aa5b0151..55f03256b6c 100644 --- a/src/main/java/cn/nukkit/item/food/Food.java +++ b/src/main/java/cn/nukkit/item/food/Food.java @@ -20,14 +20,14 @@ public abstract class Food { public static final Food apple = registerDefaultFood(new FoodNormal(4, 2.4F).addRelative(Item.APPLE)); public static final Food apple_golden = registerDefaultFood(new FoodEffective(4, 9.6F) - .addEffect(Effect.getEffect(Effect.REGENERATION).setAmplifier(1).setDuration(5 * 20)) - .addEffect(Effect.getEffect(Effect.ABSORPTION).setDuration(2 * 60 * 20)) + .addEffect(Effect.getEffect(Effect.REGENERATION).setAmplifier(1).setDuration(100)) + .addEffect(Effect.getEffect(Effect.ABSORPTION).setDuration(2400)) .addRelative(Item.GOLDEN_APPLE)); public static final Food apple_golden_enchanted = registerDefaultFood(new FoodEffective(4, 9.6F) - .addEffect(Effect.getEffect(Effect.REGENERATION).setAmplifier(4).setDuration(30 * 20)) - .addEffect(Effect.getEffect(Effect.ABSORPTION).setDuration(2 * 60 * 20).setAmplifier(3)) - .addEffect(Effect.getEffect(Effect.DAMAGE_RESISTANCE).setDuration(5 * 60 * 20)) - .addEffect(Effect.getEffect(Effect.FIRE_RESISTANCE).setDuration(5 * 60 * 20)) + .addEffect(Effect.getEffect(Effect.REGENERATION).setAmplifier(4).setDuration(600)) + .addEffect(Effect.getEffect(Effect.ABSORPTION).setDuration(2400).setAmplifier(3)) + .addEffect(Effect.getEffect(Effect.DAMAGE_RESISTANCE).setDuration(6000)) + .addEffect(Effect.getEffect(Effect.FIRE_RESISTANCE).setDuration(6000)) .addRelative(Item.GOLDEN_APPLE_ENCHANTED)); public static final Food beef_raw = registerDefaultFood(new FoodNormal(3, 1.8F).addRelative(Item.RAW_BEEF)); public static final Food beetroot = registerDefaultFood(new FoodNormal(1, 1.2F).addRelative(Item.BEETROOT)); @@ -40,7 +40,7 @@ public abstract class Food { public static final Food carrot = registerDefaultFood(new FoodNormal(3, 4.8F).addRelative(Item.CARROT)); public static final Food carrot_golden = registerDefaultFood(new FoodNormal(6, 14.4F).addRelative(Item.GOLDEN_CARROT)); public static final Food chicken_raw = registerDefaultFood(new FoodEffective(2, 1.2F) - .addChanceEffect(0.3F, Effect.getEffect(Effect.HUNGER).setDuration(30 * 20)) + .addChanceEffect(0.3F, Effect.getEffect(Effect.HUNGER).setDuration(600)) .addRelative(Item.RAW_CHICKEN)); public static final Food chicken_cooked = registerDefaultFood(new FoodNormal(6, 7.2F).addRelative(Item.COOKED_CHICKEN)); public static final Food chorus_fruit = registerDefaultFood(new FoodChorusFruit()); @@ -55,35 +55,52 @@ public abstract class Food { public static final Food potato_raw = registerDefaultFood(new FoodNormal(1, 0.6F).addRelative(Item.POTATO)); public static final Food potato_baked = registerDefaultFood(new FoodNormal(5, 7.2F).addRelative(Item.BAKED_POTATO)); public static final Food potato_poisonous = registerDefaultFood(new FoodEffective(2, 1.2F) - .addChanceEffect(0.6F, Effect.getEffect(Effect.POISON).setDuration(4 * 20)) + .addChanceEffect(0.6F, Effect.getEffect(Effect.POISON).setDuration(80)) .addRelative(Item.POISONOUS_POTATO)); public static final Food pumpkin_pie = registerDefaultFood(new FoodNormal(8, 4.8F).addRelative(Item.PUMPKIN_PIE)); public static final Food rabbit_cooked = registerDefaultFood(new FoodNormal(5, 6F).addRelative(Item.COOKED_RABBIT)); public static final Food rabbit_raw = registerDefaultFood(new FoodNormal(3, 1.8F).addRelative(Item.RAW_RABBIT)); public static final Food rabbit_stew = registerDefaultFood(new FoodInBowl(10, 12F).addRelative(Item.RABBIT_STEW)); public static final Food rotten_flesh = registerDefaultFood(new FoodEffective(4, 0.8F) - .addChanceEffect(0.8F, Effect.getEffect(Effect.HUNGER).setDuration(30 * 20)) + .addChanceEffect(0.8F, Effect.getEffect(Effect.HUNGER).setDuration(600)) .addRelative(Item.ROTTEN_FLESH)); public static final Food spider_eye = registerDefaultFood(new FoodEffective(2, 3.2F) - .addEffect(Effect.getEffect(Effect.POISON).setDuration(4 * 20)) + .addEffect(Effect.getEffect(Effect.POISON).setDuration(80)) .addRelative(Item.SPIDER_EYE)); public static final Food steak = registerDefaultFood(new FoodNormal(8, 12.8F).addRelative(Item.COOKED_BEEF)); - //different kinds of fishes public static final Food clownfish = registerDefaultFood(new FoodNormal(1, 0.2F).addRelative(Item.CLOWNFISH)); public static final Food fish_cooked = registerDefaultFood(new FoodNormal(5, 6F).addRelative(Item.COOKED_FISH)); public static final Food fish_raw = registerDefaultFood(new FoodNormal(2, 0.4F).addRelative(Item.RAW_FISH)); public static final Food salmon_cooked = registerDefaultFood(new FoodNormal(6, 9.6F).addRelative(Item.COOKED_SALMON)); public static final Food salmon_raw = registerDefaultFood(new FoodNormal(2, 0.4F).addRelative(Item.RAW_SALMON)); public static final Food pufferfish = registerDefaultFood(new FoodEffective(1, 0.2F) - .addEffect(Effect.getEffect(Effect.HUNGER).setAmplifier(2).setDuration(15 * 20)) - .addEffect(Effect.getEffect(Effect.NAUSEA).setAmplifier(1).setDuration(15 * 20)) - .addEffect(Effect.getEffect(Effect.POISON).setAmplifier(3).setDuration(60 * 20)) + .addEffect(Effect.getEffect(Effect.HUNGER).setAmplifier(2).setDuration(300)) + .addEffect(Effect.getEffect(Effect.NAUSEA).setAmplifier(1).setDuration(300)) + .addEffect(Effect.getEffect(Effect.POISON).setAmplifier(3).setDuration(1200)) .addRelative(Item.PUFFERFISH)); public static final Food dried_kelp = registerDefaultFood(new FoodNormal(1, 0.6F).addRelative(Item.DRIED_KELP)); public static final Food sweet_berries = registerDefaultFood(new FoodNormal(2, 0.4F).addRelative(Item.SWEET_BERRIES)); + public static final Food glow_berries = registerDefaultFood(new FoodNormal(2, 0.4F).addRelative(Item.GLOW_BERRIES)); + public static final Food suspicious_stew_night_vision = registerDefaultFood(new FoodEffectiveInBow(6, 7.2F) + .addEffect(Effect.getEffect(Effect.NIGHT_VISION).setAmplifier(1).setDuration(80)).addRelative(Item.SUSPICIOUS_STEW, 0)); + public static final Food suspicious_stew_jump = registerDefaultFood(new FoodEffectiveInBow(6, 7.2F) + .addEffect(Effect.getEffect(Effect.JUMP).setAmplifier(1).setDuration(80)).addRelative(Item.SUSPICIOUS_STEW, 1)); + public static final Food suspicious_stew_weakness = registerDefaultFood(new FoodEffectiveInBow(6, 7.2F) + .addEffect(Effect.getEffect(Effect.WEAKNESS).setAmplifier(1).setDuration(140)).addRelative(Item.SUSPICIOUS_STEW, 2)); + public static final Food suspicious_stew_blindness = registerDefaultFood(new FoodEffectiveInBow(6, 7.2F) + .addEffect(Effect.getEffect(Effect.BLINDNESS).setAmplifier(1).setDuration(120)).addRelative(Item.SUSPICIOUS_STEW, 3)); + public static final Food suspicious_stew_poison = registerDefaultFood(new FoodEffectiveInBow(6, 7.2F) + .addEffect(Effect.getEffect(Effect.POISON).setAmplifier(1).setDuration(220)).addRelative(Item.SUSPICIOUS_STEW, 4)); + public static final Food suspicious_stew_saturation = registerDefaultFood(new FoodEffectiveInBow(6, 7.2F) + .addEffect(Effect.getEffect(Effect.SATURATION).setAmplifier(1).setDuration(7)).addRelative(Item.SUSPICIOUS_STEW, 6)); + public static final Food suspicious_stew_fire_resistance = registerDefaultFood(new FoodEffectiveInBow(6, 7.2F) + .addEffect(Effect.getEffect(Effect.FIRE_RESISTANCE).setAmplifier(1).setDuration(40)).addRelative(Item.SUSPICIOUS_STEW, 7)); + public static final Food suspicious_stew_regeneration = registerDefaultFood(new FoodEffectiveInBow(6, 7.2F) + .addEffect(Effect.getEffect(Effect.REGENERATION).setAmplifier(1).setDuration(120)).addRelative(Item.SUSPICIOUS_STEW, 8)); + public static final Food suspicious_stew_wither = registerDefaultFood(new FoodEffectiveInBow(6, 7.2F) + .addEffect(Effect.getEffect(Effect.WITHER).setAmplifier(1).setDuration(120)).addRelative(Item.SUSPICIOUS_STEW, 9)); public static final Food honey_bottle = registerDefaultFood(new FoodNormal(6, 1.2F).addRelative(Item.HONEY_BOTTLE)); - //Opened API for plugins public static Food registerFood(Food food, Plugin plugin) { Objects.requireNonNull(food); Objects.requireNonNull(plugin); @@ -119,8 +136,8 @@ public static Food getByRelative(int relativeID, int meta) { return result[0]; } - protected int restoreFood = 0; - protected float restoreSaturation = 0; + protected int restoreFood; + protected float restoreSaturation; protected final List relativeIDs = new ArrayList<>(); public final boolean eatenBy(Player player) { @@ -185,5 +202,4 @@ static class NodeIDMetaPlugin extends NodeIDMeta { this.plugin = plugin; } } - } diff --git a/src/main/java/cn/nukkit/item/food/FoodChorusFruit.java b/src/main/java/cn/nukkit/item/food/FoodChorusFruit.java index 44f9ec0866a..2b60e655f5c 100644 --- a/src/main/java/cn/nukkit/item/food/FoodChorusFruit.java +++ b/src/main/java/cn/nukkit/item/food/FoodChorusFruit.java @@ -6,9 +6,10 @@ import cn.nukkit.event.player.PlayerTeleportEvent; import cn.nukkit.item.Item; import cn.nukkit.level.Level; -import cn.nukkit.math.NukkitRandom; +import cn.nukkit.level.format.FullChunk; import cn.nukkit.math.Vector3; import cn.nukkit.network.protocol.LevelSoundEventPacket; +import cn.nukkit.utils.Utils; /** * Created by Leonidius20 on 20.08.18. @@ -23,47 +24,61 @@ public FoodChorusFruit() { @Override protected boolean onEatenBy(Player player) { super.onEatenBy(player); - // Teleportation int minX = player.getFloorX() - 8; int minY = player.getFloorY() - 8; int minZ = player.getFloorZ() - 8; + int maxX = minX + 16; - int maxY = minY + 16; + int maxY; int maxZ = minZ + 16; + if (player.getLevel().getDimension() == Level.DIMENSION_NETHER) { + maxY = Math.min(minY + 16, 125); + + if (minY > maxY) { + minY = maxY; + } + } else { + maxY = minY + 16; + } + + int minBlockY = player.getLevel().getMinBlockY(); + Level level = player.getLevel(); if (level == null) return false; - NukkitRandom random = new NukkitRandom(); - for (int attempts = 0; attempts < 128; attempts++) { - int x = random.nextRange(minX, maxX); - int y = random.nextRange(minY, maxY); - int z = random.nextRange(minZ, maxZ); + for (int attempts = 0; attempts < 16; attempts++) { + int x = Utils.rand(minX, maxX); + int y = Utils.rand(minY, maxY); + int z = Utils.rand(minZ, maxZ); + + if (y < minBlockY) continue; - if (y < 0) continue; + FullChunk chunk = level.getChunkIfLoaded(x >> 4, z >> 4); + if (chunk == null) { + continue; + } - while (y >= 0 && !level.getBlock(new Vector3(x, y + 1, z)).isSolid()) { + while (y >= minBlockY && !level.getBlock(chunk, x, y + 1, z, true).isSolid()) { y--; } - y++; // Back up to non solid - Block blockUp = level.getBlock(new Vector3(x, y + 1, z)); - Block blockUp2 = level.getBlock(new Vector3(x, y + 2, z)); + y++; - if (blockUp.isSolid() || blockUp instanceof BlockLiquid || - blockUp2.isSolid() || blockUp2 instanceof BlockLiquid) { + Block blockUp = level.getBlock(chunk, x, y + 1, z, true); + Block blockUp2 = level.getBlock(chunk, x, y + 2, z, true); + + if (blockUp.isSolid() || blockUp instanceof BlockLiquid || blockUp2.isSolid() || blockUp2 instanceof BlockLiquid) { continue; } - // Sounds are broadcast at both source and destination - level.addLevelSoundEvent(player, LevelSoundEventPacket.SOUND_TELEPORT); - player.teleport(new Vector3(x + 0.5, y + 1, z + 0.5), PlayerTeleportEvent.TeleportCause.CHORUS_FRUIT); level.addLevelSoundEvent(player, LevelSoundEventPacket.SOUND_TELEPORT); - + if (player.teleport(new Vector3(x + 0.5, y + 1, z + 0.5), PlayerTeleportEvent.TeleportCause.CHORUS_FRUIT)) { + level.addLevelSoundEvent(player, LevelSoundEventPacket.SOUND_TELEPORT); + } break; } return true; } - -} \ No newline at end of file +} diff --git a/src/main/java/cn/nukkit/item/food/FoodEffective.java b/src/main/java/cn/nukkit/item/food/FoodEffective.java index 0f655a8c718..96f0da18fa7 100644 --- a/src/main/java/cn/nukkit/item/food/FoodEffective.java +++ b/src/main/java/cn/nukkit/item/food/FoodEffective.java @@ -2,6 +2,7 @@ import cn.nukkit.Player; import cn.nukkit.event.entity.EntityPotionEffectEvent; +import cn.nukkit.item.Item; import cn.nukkit.potion.Effect; import java.util.LinkedHashMap; @@ -34,11 +35,17 @@ public FoodEffective addChanceEffect(float chance, Effect effect) { @Override protected boolean onEatenBy(Player player) { super.onEatenBy(player); + effects.forEach((effect, chance) -> { if (chance >= Math.random()) { player.addEffect(effect.clone(), EntityPotionEffectEvent.Cause.FOOD); } }); + + NodeIDMeta id = relativeIDs.get(0); + if (id != null && id.id == Item.GOLDEN_APPLE_ENCHANTED) { + player.awardAchievement("overpowered"); + } return true; } } diff --git a/src/main/java/cn/nukkit/item/food/FoodEffectiveInBow.java b/src/main/java/cn/nukkit/item/food/FoodEffectiveInBow.java new file mode 100644 index 00000000000..a5c17ee7e44 --- /dev/null +++ b/src/main/java/cn/nukkit/item/food/FoodEffectiveInBow.java @@ -0,0 +1,18 @@ +package cn.nukkit.item.food; + +import cn.nukkit.Player; +import cn.nukkit.item.Item; + +public class FoodEffectiveInBow extends FoodEffective { + + public FoodEffectiveInBow(int restoreFood, float restoreSaturation) { + super(restoreFood, restoreSaturation); + } + + @Override + protected boolean onEatenBy(Player player) { + super.onEatenBy(player); + player.getInventory().addItem(Item.get(Item.BOWL));; // TODO: set to same slot but don't have it replaced + return true; + } +} diff --git a/src/main/java/cn/nukkit/item/food/FoodInBowl.java b/src/main/java/cn/nukkit/item/food/FoodInBowl.java index 81427500e55..a3850e02e78 100644 --- a/src/main/java/cn/nukkit/item/food/FoodInBowl.java +++ b/src/main/java/cn/nukkit/item/food/FoodInBowl.java @@ -1,7 +1,7 @@ package cn.nukkit.item.food; import cn.nukkit.Player; -import cn.nukkit.item.ItemBowl; +import cn.nukkit.item.Item; /** * Created by Snake1999 on 2016/1/14. @@ -17,8 +17,7 @@ public FoodInBowl(int restoreFood, float restoreSaturation) { @Override protected boolean onEatenBy(Player player) { super.onEatenBy(player); - player.getInventory().addItem(new ItemBowl()); + player.getInventory().addItem(Item.get(Item.BOWL)); // TODO: set to same slot but don't have it replaced return true; } - } diff --git a/src/main/java/cn/nukkit/item/food/FoodMilk.java b/src/main/java/cn/nukkit/item/food/FoodMilk.java index 3c1e765a9b1..c84ccbe5d17 100644 --- a/src/main/java/cn/nukkit/item/food/FoodMilk.java +++ b/src/main/java/cn/nukkit/item/food/FoodMilk.java @@ -2,17 +2,18 @@ import cn.nukkit.Player; import cn.nukkit.event.entity.EntityPotionEffectEvent; -import cn.nukkit.item.ItemBucket; +import cn.nukkit.item.Item; /** * Created by Snake1999 on 2016/1/21. * Package cn.nukkit.item.food in project nukkit. */ public class FoodMilk extends Food { + @Override protected boolean onEatenBy(Player player) { super.onEatenBy(player); - player.getInventory().addItem(new ItemBucket()); + player.getInventory().addItem(Item.get(Item.BUCKET)); player.removeAllEffects(EntityPotionEffectEvent.Cause.MILK); return true; } diff --git a/src/main/java/cn/nukkit/item/randomitem/ConstantItemSelector.java b/src/main/java/cn/nukkit/item/randomitem/ConstantItemSelector.java index 950981b19da..51cf91411e9 100644 --- a/src/main/java/cn/nukkit/item/randomitem/ConstantItemSelector.java +++ b/src/main/java/cn/nukkit/item/randomitem/ConstantItemSelector.java @@ -18,10 +18,18 @@ public ConstantItemSelector(int id, Integer meta, Selector parent) { this(id, meta, 1, parent); } + public ConstantItemSelector(int id, int meta, Selector parent) { + this(id, meta, 1, parent); + } + public ConstantItemSelector(int id, Integer meta, int count, Selector parent) { this(Item.get(id, meta, count), parent); } + public ConstantItemSelector(int id, int meta, int count, Selector parent) { + this(Item.get(id, meta, count), parent); + } + public ConstantItemSelector(Item item, Selector parent) { super(parent); this.item = item; @@ -32,6 +40,6 @@ public Item getItem() { } public Object select() { - return getItem(); + return item; } } diff --git a/src/main/java/cn/nukkit/item/randomitem/Fishing.java b/src/main/java/cn/nukkit/item/randomitem/Fishing.java index f328a0e3d6e..f1cadaac1fd 100644 --- a/src/main/java/cn/nukkit/item/randomitem/Fishing.java +++ b/src/main/java/cn/nukkit/item/randomitem/Fishing.java @@ -2,7 +2,6 @@ import cn.nukkit.item.Item; import cn.nukkit.item.enchantment.Enchantment; -import cn.nukkit.math.NukkitMath; import cn.nukkit.potion.Potion; import cn.nukkit.utils.DyeColor; @@ -45,19 +44,20 @@ public static Item getFishingResult(Item rod) { int fortuneLevel = 0; int lureLevel = 0; if (rod != null) { - if (rod.getEnchantment(Enchantment.ID_FORTUNE_FISHING) != null) { - fortuneLevel = rod.getEnchantment(Enchantment.ID_FORTUNE_FISHING).getLevel(); - } else if (rod.getEnchantment(Enchantment.ID_LURE) != null) { - lureLevel = rod.getEnchantment(Enchantment.ID_LURE).getLevel(); + Enchantment ench; + if ((ench = rod.getEnchantment(Enchantment.ID_FORTUNE_FISHING)) != null) { + fortuneLevel = ench.getLevel(); + } else if ((ench = rod.getEnchantment(Enchantment.ID_LURE)) != null) { + lureLevel = ench.getLevel(); } } return getFishingResult(fortuneLevel, lureLevel); } public static Item getFishingResult(int fortuneLevel, int lureLevel) { - float treasureChance = NukkitMath.clamp(0.05f + 0.01f * fortuneLevel - 0.01f * lureLevel, 0, 1); - float junkChance = NukkitMath.clamp(0.05f - 0.025f * fortuneLevel - 0.01f * lureLevel, 0, 1); - float fishChance = NukkitMath.clamp(1 - treasureChance - junkChance, 0, 1); + float treasureChance = limitRange(0.05f + 0.01f * fortuneLevel - 0.01f * lureLevel); + float junkChance = limitRange(0.05f - 0.025f * fortuneLevel - 0.01f * lureLevel); + float fishChance = limitRange(1 - treasureChance - junkChance); putSelector(FISHES, fishChance); putSelector(TREASURES, treasureChance); putSelector(JUNKS, junkChance); @@ -65,4 +65,9 @@ public static Item getFishingResult(int fortuneLevel, int lureLevel) { if (result instanceof Item) return (Item) result; return null; } + + private static float limitRange(float value) { + if (value >= 1f) return 1f; + return Math.max(value, 0f); + } } diff --git a/src/main/java/cn/nukkit/item/randomitem/RandomItem.java b/src/main/java/cn/nukkit/item/randomitem/RandomItem.java index 93ab7933810..598d707edd9 100644 --- a/src/main/java/cn/nukkit/item/randomitem/RandomItem.java +++ b/src/main/java/cn/nukkit/item/randomitem/RandomItem.java @@ -9,6 +9,7 @@ * Package cn.nukkit.item.randomitem in project nukkit. */ public final class RandomItem { + private static final Map selectors = new HashMap<>(); public static final Selector ROOT = new Selector(null); @@ -29,8 +30,7 @@ static Object selectFrom(Selector selector) { selectors.forEach((s, f) -> { if (s.getParent() == selector) child.put(s, f); }); - if (child.size() == 0) return selector.select(); + if (child.isEmpty()) return selector.select(); return selectFrom(Selector.selectRandom(child)); } - } diff --git a/src/main/java/cn/nukkit/lang/BaseLang.java b/src/main/java/cn/nukkit/lang/BaseLang.java index b8b31948285..4fd70c646c1 100644 --- a/src/main/java/cn/nukkit/lang/BaseLang.java +++ b/src/main/java/cn/nukkit/lang/BaseLang.java @@ -10,10 +10,11 @@ import java.util.Objects; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BaseLang { + public static final String FALLBACK_LANGUAGE = "eng"; protected final String langName; @@ -21,7 +22,6 @@ public class BaseLang { protected Map lang = new HashMap<>(); protected Map fallbackLang = new HashMap<>(); - public BaseLang(String lang) { this(lang, null); } @@ -43,8 +43,6 @@ public BaseLang(String lang, String path, String fallback) { if (useFallback) this.fallbackLang = this.loadLang(path + fallback + "/lang.ini"); } if (this.fallbackLang == null) this.fallbackLang = this.lang; - - } public Map getLangMap() { @@ -69,7 +67,7 @@ protected Map loadLang(String path) { Map d = new HashMap<>(); for (String line : content.split("\n")) { line = line.trim(); - if (line.equals("") || line.charAt(0) == '#') { + if (line.isEmpty() || line.charAt(0) == '#') { continue; } String[] t = line.split("="); @@ -77,15 +75,15 @@ protected Map loadLang(String path) { continue; } String key = t[0]; - String value = ""; + StringBuilder value = new StringBuilder(); for (int i = 1; i < t.length - 1; i++) { - value += t[i] + "="; + value.append(t[i]).append("="); } - value += t[t.length - 1]; - if (value.equals("")) { + value.append(t[t.length - 1]); + if (value.length() == 0) { continue; } - d.put(key, value); + d.put(key, value.toString()); } return d; } catch (IOException e) { @@ -100,7 +98,7 @@ protected Map loadLang(InputStream stream) { Map d = new HashMap<>(); for (String line : content.split("\n")) { line = line.trim(); - if (line.equals("") || line.charAt(0) == '#') { + if (line.isEmpty() || line.charAt(0) == '#') { continue; } String[] t = line.split("="); @@ -108,15 +106,15 @@ protected Map loadLang(InputStream stream) { continue; } String key = t[0]; - String value = ""; + StringBuilder value = new StringBuilder(); for (int i = 1; i < t.length - 1; i++) { - value += t[i] + "="; + value.append(t[i]).append("="); } - value += t[t.length - 1]; - if (value.equals("")) { + value.append(t[t.length - 1]); + if (value.length() == 0) { continue; } - d.put(key, value); + d.put(key, value.toString()); } return d; } catch (IOException e) { @@ -174,21 +172,19 @@ public String translate(TextContainer c) { } public String internalGet(String id) { - if (this.lang.containsKey(id)) { - return this.lang.get(id); - } else if (this.fallbackLang.containsKey(id)) { - return this.fallbackLang.get(id); + String translation = this.lang.get(id); + if (translation == null) { + translation = this.fallbackLang.get(id); } - return null; + return translation; } public String get(String id) { - if (this.lang.containsKey(id)) { - return this.lang.get(id); - } else if (this.fallbackLang.containsKey(id)) { - return this.fallbackLang.get(id); + String translation = this.lang.get(id); + if (translation == null) { + translation = this.fallbackLang.get(id); } - return id; + return translation == null ? id : translation; } protected String parseTranslation(String text) { @@ -199,19 +195,18 @@ protected String parseTranslation(String text, String onlyPrefix) { StringBuilder newString = new StringBuilder(); text = String.valueOf(text); - String replaceString = null; + StringBuilder replaceString = null; int len = text.length(); for (int i = 0; i < len; ++i) { char c = text.charAt(i); if (replaceString != null) { - int ord = c; - if ((ord >= 0x30 && ord <= 0x39) // 0-9 - || (ord >= 0x41 && ord <= 0x5a) // A-Z - || (ord >= 0x61 && ord <= 0x7a) || // a-z + if (((int) c >= 0x30 && (int) c <= 0x39) // 0-9 + || ((int) c >= 0x41 && (int) c <= 0x5a) // A-Z + || ((int) c >= 0x61 && (int) c <= 0x7a) || // a-z c == '.' || c == '-') { - replaceString += String.valueOf(c); + replaceString.append(c); } else { String t = this.internalGet(replaceString.substring(1)); if (t != null && (onlyPrefix == null || replaceString.indexOf(onlyPrefix) == 1)) { @@ -221,13 +216,13 @@ protected String parseTranslation(String text, String onlyPrefix) { } replaceString = null; if (c == '%') { - replaceString = String.valueOf(c); + replaceString = new StringBuilder(String.valueOf(c)); } else { newString.append(c); } } } else if (c == '%') { - replaceString = String.valueOf(c); + replaceString = new StringBuilder(String.valueOf(c)); } else { newString.append(c); } diff --git a/src/main/java/cn/nukkit/lang/TextContainer.java b/src/main/java/cn/nukkit/lang/TextContainer.java index a6051907985..61d47814361 100644 --- a/src/main/java/cn/nukkit/lang/TextContainer.java +++ b/src/main/java/cn/nukkit/lang/TextContainer.java @@ -3,10 +3,11 @@ import cn.nukkit.Server; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class TextContainer implements Cloneable { + protected String text; public TextContainer(String text) { @@ -23,7 +24,7 @@ public String getText() { @Override public String toString() { - return this.getText(); + return this.text; } @Override diff --git a/src/main/java/cn/nukkit/lang/TranslationContainer.java b/src/main/java/cn/nukkit/lang/TranslationContainer.java index 5bf0f089b15..e938edb1b46 100644 --- a/src/main/java/cn/nukkit/lang/TranslationContainer.java +++ b/src/main/java/cn/nukkit/lang/TranslationContainer.java @@ -1,7 +1,7 @@ package cn.nukkit.lang; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class TranslationContainer extends TextContainer implements Cloneable { diff --git a/src/main/java/cn/nukkit/level/AsyncChunkData.java b/src/main/java/cn/nukkit/level/AsyncChunkData.java new file mode 100644 index 00000000000..0451510b6f1 --- /dev/null +++ b/src/main/java/cn/nukkit/level/AsyncChunkData.java @@ -0,0 +1,20 @@ +package cn.nukkit.level; + +class AsyncChunkData { + + final long timestamp; + final int x; + final int z; + final long hash; + final byte[] data; + final int count; + + AsyncChunkData(long timestamp, int x, int z, long hash, byte[] data, int count) { + this.timestamp = timestamp; + this.x = x; + this.z = z; + this.hash = hash; + this.data = data; + this.count = count; + } +} diff --git a/src/main/java/cn/nukkit/level/AsyncChunkThread.java b/src/main/java/cn/nukkit/level/AsyncChunkThread.java new file mode 100644 index 00000000000..f95d96a523c --- /dev/null +++ b/src/main/java/cn/nukkit/level/AsyncChunkThread.java @@ -0,0 +1,41 @@ +package cn.nukkit.level; + +import cn.nukkit.level.format.generic.BaseChunk; +import cn.nukkit.Server; +import cn.nukkit.level.format.generic.serializer.NetworkChunkData; +import cn.nukkit.level.format.generic.serializer.NetworkChunkSerializer; +import cn.nukkit.utils.BinaryStream; +import com.google.common.util.concurrent.ThreadFactoryBuilder; + +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.BiConsumer; + +class AsyncChunkThread { + + private final ExecutorService threadedExecutor; + final Queue out = new ConcurrentLinkedQueue<>(); + + AsyncChunkThread(String levelName) { + ThreadFactoryBuilder builder = new ThreadFactoryBuilder(); + builder.setNameFormat("AsyncChunkThread for " + levelName); + builder.setUncaughtExceptionHandler((thread, ex) -> Server.getInstance().getLogger().error("Exception in " + thread.getName(), ex)); + this.threadedExecutor = Executors.newFixedThreadPool(2, builder.build()); + } + + void queue(BaseChunk chunk, long timestamp, int x, int z, DimensionData dimensionData) { + this.threadedExecutor.execute(() -> this.run(chunk, timestamp, x, z, dimensionData)); + } + + private void run(BaseChunk chunk, long timestamp, int x, int z, DimensionData dimensionData) { + BiConsumer callback = (stream, data) -> + this.out.add(new AsyncChunkData(timestamp, x, z, Level.chunkHash(x, z), stream.getBuffer(), data.getChunkSections())); + NetworkChunkSerializer.serialize(chunk, callback, dimensionData); + } + + void shutdown() { + this.threadedExecutor.shutdownNow(); + } +} diff --git a/src/main/java/cn/nukkit/level/BlockPalette.java b/src/main/java/cn/nukkit/level/BlockPalette.java new file mode 100644 index 00000000000..19feea03d92 --- /dev/null +++ b/src/main/java/cn/nukkit/level/BlockPalette.java @@ -0,0 +1,85 @@ +package cn.nukkit.level; + +import cn.nukkit.block.BlockID; +import cn.nukkit.nbt.tag.CompoundTag; +import it.unimi.dsi.fastutil.ints.Int2IntMap; +import it.unimi.dsi.fastutil.ints.Int2IntMaps; +import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; +import lombok.Data; +import lombok.extern.log4j.Log4j2; + +import java.util.HashMap; +import java.util.Map; + +@Data +@Log4j2 +public class BlockPalette { + + private final int protocol; + private final Int2IntMap legacyToRuntimeId = new Int2IntOpenHashMap(); + private final Int2IntMap runtimeIdToLegacy = new Int2IntOpenHashMap(); + private final Map stateToLegacy = new HashMap<>(); + private volatile boolean locked; + + public BlockPalette(int protocol) { + this.protocol = protocol; + this.legacyToRuntimeId.defaultReturnValue(-1); + this.runtimeIdToLegacy.defaultReturnValue(-1); + } + + public void clearStates() { + this.locked = false; + this.legacyToRuntimeId.clear(); + this.runtimeIdToLegacy.clear(); + this.stateToLegacy.clear(); + } + + public void registerState(int blockId, int data, int runtimeId, CompoundTag blockState) { + if (this.locked) { + throw new IllegalStateException("Block palette is already locked!"); + } + + int legacyId = blockId << 6 | data; + this.legacyToRuntimeId.put(legacyId, runtimeId); + this.runtimeIdToLegacy.putIfAbsent(runtimeId, legacyId); + this.stateToLegacy.putIfAbsent(blockState, legacyId); + } + + public void lock() { + this.locked = true; + } + + public int getRuntimeId(int id, int meta) { + int legacyId = id << 6 | meta; + int runtimeId = this.legacyToRuntimeId.get(legacyId); + if (runtimeId == -1) { + runtimeId = legacyToRuntimeId.get(id << 6); + if (runtimeId == -1) { + runtimeId = legacyToRuntimeId.get(BlockID.INFO_UPDATE << 6); + log.info("Missing block runtime id mappings for {}:{}", id, meta); + } + } + return runtimeId; + } + + public int getRuntimeId(int legacyId) { + int runtimeId = this.legacyToRuntimeId.get(legacyId); + if (runtimeId == -1) { + log.info("Missing block runtime id mappings for {}", legacyId); + return legacyToRuntimeId.get(BlockID.INFO_UPDATE << 6); + } + return runtimeId; + } + + public int getLegacyFullId(int runtimeId) { + return this.runtimeIdToLegacy.get(runtimeId); + } + + public int getLegacyFullId(CompoundTag state) { + return this.stateToLegacy.getOrDefault(state, -1); + } + + public Int2IntMap getLegacyToRuntimeIdMap() { + return Int2IntMaps.unmodifiable(this.legacyToRuntimeId); + } +} diff --git a/src/main/java/cn/nukkit/level/ChunkLoader.java b/src/main/java/cn/nukkit/level/ChunkLoader.java index dd46de977a9..1e1d8fd273c 100644 --- a/src/main/java/cn/nukkit/level/ChunkLoader.java +++ b/src/main/java/cn/nukkit/level/ChunkLoader.java @@ -4,7 +4,7 @@ import cn.nukkit.math.Vector3; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface ChunkLoader { diff --git a/src/main/java/cn/nukkit/level/ChunkManager.java b/src/main/java/cn/nukkit/level/ChunkManager.java index a7edf2b897e..503b43390cc 100644 --- a/src/main/java/cn/nukkit/level/ChunkManager.java +++ b/src/main/java/cn/nukkit/level/ChunkManager.java @@ -1,18 +1,32 @@ package cn.nukkit.level; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockLayer; import cn.nukkit.level.format.generic.BaseFullChunk; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface ChunkManager { - int getBlockIdAt(int x, int y, int z); + default int getBlockIdAt(int x, int y, int z) { + return this.getBlockIdAt(x, y, z, Block.LAYER_NORMAL); + } + + int getBlockIdAt(int x, int y, int z, BlockLayer layer); + + default void setBlockFullIdAt(int x, int y, int z, int fullId) { + this.setBlockFullIdAt(x, y, z, Block.LAYER_NORMAL, fullId); + } + + void setBlockFullIdAt(int x, int y, int z, BlockLayer layer, int fullId); - void setBlockFullIdAt(int x, int y, int z, int fullId); + default void setBlockIdAt(int x, int y, int z, int id) { + this.setBlockIdAt(x, y, z, Block.LAYER_NORMAL, id); + } - void setBlockIdAt(int x, int y, int z, int id); + void setBlockIdAt(int x, int y, int z, BlockLayer layer, int id); default void setBlockAt(int x, int y, int z, int id) { setBlockAt(x, y, z, id, 0); @@ -20,9 +34,20 @@ default void setBlockAt(int x, int y, int z, int id) { void setBlockAt(int x, int y, int z, int id, int data); - int getBlockDataAt(int x, int y, int z); + boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int id); + boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int id, int data); + + default int getBlockDataAt(int x, int y, int z) { + return this.getBlockDataAt(x, y, z, Block.LAYER_NORMAL); + } + + int getBlockDataAt(int x, int y, int z, BlockLayer layer); + + default void setBlockDataAt(int x, int y, int z, int data) { + this.setBlockDataAt(x, y, z, Block.LAYER_NORMAL, data); + } - void setBlockDataAt(int x, int y, int z, int data); + void setBlockDataAt(int x, int y, int z, BlockLayer layer, int data); BaseFullChunk getChunk(int chunkX, int chunkZ); @@ -31,4 +56,4 @@ default void setBlockAt(int x, int y, int z, int id) { void setChunk(int chunkX, int chunkZ, BaseFullChunk chunk); long getSeed(); -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/ChunkPosition.java b/src/main/java/cn/nukkit/level/ChunkPosition.java index 4a8282dc54c..6f1e43c9eec 100644 --- a/src/main/java/cn/nukkit/level/ChunkPosition.java +++ b/src/main/java/cn/nukkit/level/ChunkPosition.java @@ -4,8 +4,8 @@ import cn.nukkit.math.Vector3; /** - * Author: Adam Matthew - *

+ * @author Adam Matthew + * * Nukkit Project */ public class ChunkPosition { diff --git a/src/main/java/cn/nukkit/level/DimensionData.java b/src/main/java/cn/nukkit/level/DimensionData.java index c25ab2ed65e..3c3c02205d0 100644 --- a/src/main/java/cn/nukkit/level/DimensionData.java +++ b/src/main/java/cn/nukkit/level/DimensionData.java @@ -4,6 +4,9 @@ @Data public class DimensionData { + + public static final DimensionData LEGACY_DIMENSION = new LegacyDimensionData(); + private final int dimensionId; private final int minHeight; private final int maxHeight; @@ -20,4 +23,19 @@ public DimensionData(int dimensionId, int minHeight, int maxHeight) { } this.height = height; } + + public int getSectionOffset() { + return (-this.minHeight) >> 4; + } + + private static class LegacyDimensionData extends DimensionData { + public LegacyDimensionData() { + super(0, 0, 255); + } + + @Override + public int getHeight() { + return DimensionEnum.OVERWORLD.getDimensionData().getHeight(); + } + } } diff --git a/src/main/java/cn/nukkit/level/DimensionEnum.java b/src/main/java/cn/nukkit/level/DimensionEnum.java index 52bcd8cabc8..5f8f902bb67 100644 --- a/src/main/java/cn/nukkit/level/DimensionEnum.java +++ b/src/main/java/cn/nukkit/level/DimensionEnum.java @@ -1,6 +1,7 @@ package cn.nukkit.level; public enum DimensionEnum { + OVERWORLD(new DimensionData(Level.DIMENSION_OVERWORLD, -64, 319)), NETHER(new DimensionData(Level.DIMENSION_NETHER, 0, 127)), END(new DimensionData(Level.DIMENSION_THE_END, 0, 255)); diff --git a/src/main/java/cn/nukkit/level/EnumLevel.java b/src/main/java/cn/nukkit/level/EnumLevel.java index 3423d84c9bd..4b6d183a0af 100644 --- a/src/main/java/cn/nukkit/level/EnumLevel.java +++ b/src/main/java/cn/nukkit/level/EnumLevel.java @@ -2,76 +2,50 @@ import cn.nukkit.Server; import cn.nukkit.level.generator.Generator; -import cn.nukkit.math.NukkitMath; +/** + * Default dimensions and their Levels + */ public enum EnumLevel { + OVERWORLD, NETHER, - //THE_END - ; + THE_END; - Level level; + private Level level; + /** + * Get Level + * + * @return Level or null if the dimension is not enabled + */ public Level getLevel() { return level; } + /** + * Internal: Initialize default overworld, nether and the end Levels + */ public static void initLevels() { - OVERWORLD.level = Server.getInstance().getDefaultLevel(); - - // attempt to load the nether world if it is allowed in server properties - if (Server.getInstance().isNetherAllowed() && !Server.getInstance().loadLevel("nether")) { - - // Nether is allowed, and not found, create the default nether world - Server.getInstance().getLogger().info("No level called \"nether\" found, creating default nether level."); - - // Generate seed for nether and get nether generator - long seed = System.currentTimeMillis(); - Class generator = Generator.getGenerator("nether"); - - // Generate the nether world - Server.getInstance().generateLevel("nether", seed, generator); - - // Finally, load the level if not already loaded and set the level - if (!Server.getInstance().isLevelLoaded("nether")) { - Server.getInstance().loadLevel("nether"); + Server server = Server.getInstance(); + OVERWORLD.level = server.getDefaultLevel(); + if (server.getPropertyBoolean("allow-nether", true)) { + if (server.getLevelByName("nether") == null) { + server.generateLevel("nether", System.currentTimeMillis(), Generator.getGenerator(Generator.TYPE_NETHER)); + server.loadLevel("nether"); } - + NETHER.level = server.getLevelByName("nether"); } - - NETHER.level = Server.getInstance().getLevelByName("nether"); - - if (NETHER.level == null) { - // Nether is not found or disabled - Server.getInstance().getLogger().alert("No level called \"nether\" found or nether is disabled in server properties! Nether functionality will be disabled."); - } - } - - public static Level getOtherNetherPair(Level current) { - if (current == OVERWORLD.level) { - return NETHER.level; - } else if (current == NETHER.level) { - return OVERWORLD.level; - } else { - throw new IllegalArgumentException("Neither overworld nor nether given!"); - } - } - - public static Position moveToNether(Position current) { - if (NETHER.level == null) { - return null; - } else { - if (current.level == OVERWORLD.level) { - return new Position(mRound(current.getFloorX() >> 3, 128), NukkitMath.clamp(mRound(current.getFloorY(), 32), 70, 128 - 10), mRound(current.getFloorZ() >> 3, 128), NETHER.level); - } else if (current.level == NETHER.level) { - return new Position(mRound(current.getFloorX() << 3, 1024), NukkitMath.clamp(mRound(current.getFloorY(), 32), 70, 256 - 10), mRound(current.getFloorZ() << 3, 1024), OVERWORLD.level); - } else { - throw new IllegalArgumentException("Neither overworld nor nether given!"); + if (server.getPropertyBoolean("allow-the-end", true)) { + if (server.getLevelByName("the_end") == null) { + server.generateLevel("the_end", System.currentTimeMillis(), Generator.getGenerator(Generator.TYPE_THE_END)); + server.loadLevel("the_end"); } + THE_END.level = server.getLevelByName("the_end"); } } - private static final int mRound(int value, int factor) { - return Math.round((float) value / factor) * factor; + static int mRound32(int value) { + return Math.round((float) value / 32) * 32; } } diff --git a/src/main/java/cn/nukkit/level/Explosion.java b/src/main/java/cn/nukkit/level/Explosion.java index 8155dcb806b..b27a2844d89 100644 --- a/src/main/java/cn/nukkit/level/Explosion.java +++ b/src/main/java/cn/nukkit/level/Explosion.java @@ -1,50 +1,54 @@ package cn.nukkit.level; +import cn.nukkit.Player; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; import cn.nukkit.block.BlockTNT; -import cn.nukkit.block.BlockWater; import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.blockentity.BlockEntityShulkerBox; import cn.nukkit.entity.Entity; import cn.nukkit.entity.EntityExplosive; +import cn.nukkit.entity.EntityLiving; import cn.nukkit.entity.item.EntityItem; import cn.nukkit.entity.item.EntityXPOrb; +import cn.nukkit.entity.mob.EntityEnderDragon; +import cn.nukkit.event.block.BlockExplodeEvent; import cn.nukkit.event.block.BlockUpdateEvent; import cn.nukkit.event.entity.EntityDamageByBlockEvent; import cn.nukkit.event.entity.EntityDamageByEntityEvent; import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; import cn.nukkit.event.entity.EntityExplodeEvent; +import cn.nukkit.inventory.Inventory; import cn.nukkit.inventory.InventoryHolder; import cn.nukkit.item.Item; -import cn.nukkit.item.ItemBlock; +import cn.nukkit.item.ItemArmor; import cn.nukkit.level.particle.HugeExplodeSeedParticle; import cn.nukkit.math.*; import cn.nukkit.network.protocol.LevelSoundEventPacket; import cn.nukkit.utils.Hash; +import cn.nukkit.utils.Utils; import it.unimi.dsi.fastutil.longs.LongArraySet; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.ThreadLocalRandom; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class Explosion { - private final int rays = 16; //Rays + private static final int rays = 16; private final Level level; private final Position source; private final double size; private List affectedBlocks = new ArrayList<>(); - private final double stepLen = 0.3d; + private static final double stepLen = 0.3d; private final Object what; private boolean doesDamage = true; + private double minHeight = Integer.MIN_VALUE; public Explosion(Position center, double size, Entity what) { this.level = center.getLevel(); @@ -53,10 +57,17 @@ public Explosion(Position center, double size, Entity what) { this.what = what; } + public Explosion(Position center, double size, Object what) { + this.level = center.getLevel(); + this.source = center; + this.size = Math.max(size, 0); + this.what = what; + } + /** * @return bool - * @deprecated */ + @Deprecated public boolean explode() { if (explodeA()) { return explodeB(); @@ -68,48 +79,42 @@ public boolean explode() { * @return bool */ public boolean explodeA() { - if (what instanceof EntityExplosive) { - Entity entity = (Entity) what; - if (entity.getLevelBlock() instanceof BlockWater) { - this.doesDamage = false; - return true; - } - } - - if (this.size < 0.1) { - return false; + if (what instanceof EntityExplosive && ((Entity) what).isInsideOfWater()) { + this.doesDamage = false; + return true; } + if (this.size < 0.1) return false; Vector3 vector = new Vector3(0, 0, 0); Vector3 vBlock = new Vector3(0, 0, 0); - int mRays = this.rays - 1; - for (int i = 0; i < this.rays; ++i) { - for (int j = 0; j < this.rays; ++j) { - for (int k = 0; k < this.rays; ++k) { + int mRays = 15; + for (int i = 0; i < rays; ++i) { + for (int j = 0; j < rays; ++j) { + for (int k = 0; k < rays; ++k) { if (i == 0 || i == mRays || j == 0 || j == mRays || k == 0 || k == mRays) { vector.setComponents((double) i / (double) mRays * 2d - 1, (double) j / (double) mRays * 2d - 1, (double) k / (double) mRays * 2d - 1); double len = vector.length(); - vector.setComponents((vector.x / len) * this.stepLen, (vector.y / len) * this.stepLen, (vector.z / len) * this.stepLen); + vector.setComponents((vector.x / len) * stepLen, (vector.y / len) * stepLen, (vector.z / len) * stepLen); double pointerX = this.source.x; double pointerY = this.source.y; double pointerZ = this.source.z; - for (double blastForce = this.size * (ThreadLocalRandom.current().nextInt(700, 1301)) / 1000d; blastForce > 0; blastForce -= this.stepLen * 0.75d) { + for (double blastForce = this.size * (Utils.random.nextInt(700, 1301)) / 1000d; blastForce > 0; blastForce -= 0.22499999999999998) { int x = (int) pointerX; int y = (int) pointerY; int z = (int) pointerZ; vBlock.x = pointerX >= x ? x : x - 1; vBlock.y = pointerY >= y ? y : y - 1; vBlock.z = pointerZ >= z ? z : z - 1; - if (vBlock.y < 0 || vBlock.y > 255) { + if (vBlock.y < this.level.getMinBlockY() || vBlock.y > this.level.getMaxBlockY()) { break; } - Block block = this.level.getBlock(vBlock); - if (block.getId() != 0) { - blastForce -= (block.getResistance() / 5 + 0.3d) * this.stepLen; - if (blastForce > 0) { + Block block = this.level.getBlock(vBlock); + if (block.getId() != Block.AIR) { + blastForce -= (block.getResistance() / 5 + 0.3d) * stepLen; + if (blastForce > 0 && block.y >= this.minHeight) { if (!this.affectedBlocks.contains(block)) { this.affectedBlocks.add(block); } @@ -128,11 +133,6 @@ public boolean explodeA() { } public boolean explodeB() { - - LongArraySet updateBlocks = new LongArraySet(); - List send = new ArrayList<>(); - - Vector3 source = (new Vector3(this.source.x, this.source.y, this.source.z)).floor(); double yield = (1d / this.size) * 100d; if (this.what instanceof Entity) { @@ -144,8 +144,18 @@ public boolean explodeB() { yield = ev.getYield(); this.affectedBlocks = ev.getBlockList(); } + } else if (this.what instanceof Block) { + BlockExplodeEvent ev = new BlockExplodeEvent((Block) this.what, this.source, this.affectedBlocks, yield); + this.level.getServer().getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + return false; + } else { + yield = ev.getYield(); + this.affectedBlocks = ev.getBlockList(); + } } + LongArraySet updateBlocks = new LongArraySet(); double explosionSize = this.size * 2d; double minX = NukkitMath.floorDouble(this.source.x - explosionSize - 1); double maxX = NukkitMath.ceilDouble(this.source.x + explosionSize + 1); @@ -161,10 +171,10 @@ public boolean explodeB() { if (distance <= 1) { Vector3 motion = entity.subtract(this.source).normalize(); - int exposure = 1; + double exposure = this.getSeenPercent(this.source, entity); double impact = (1 - distance) * exposure; - int damage = this.doesDamage ? (int) (((impact * impact + impact) / 2) * 8 * explosionSize + 1) : 0; + int damage = this.doesDamage ? Math.max((int) (((impact * impact + impact) / 2) * 8 * explosionSize + 1), 0) : 0; if (this.what instanceof Entity) { entity.attack(new EntityDamageByEntityEvent((Entity) this.what, entity, DamageCause.ENTITY_EXPLOSION, damage)); @@ -175,43 +185,67 @@ public boolean explodeB() { } if (!(entity instanceof EntityItem || entity instanceof EntityXPOrb)) { - entity.setMotion(motion.multiply(impact)); + if (entity instanceof Player) { + int netheritePieces = 0; + for (Item armor : ((Player) entity).getInventory().getArmorContents()) { + if (armor.getTier() == ItemArmor.TIER_NETHERITE) { + netheritePieces++; + } + } + if (netheritePieces > 0) { + impact *= 1 - 0.1 * netheritePieces; + } + } + entity.setMotion(entity.getMotion().add(motion.multiply(impact))); } } } - ItemBlock air = new ItemBlock(Block.get(BlockID.AIR)); + Item air = Item.get(Item.AIR); BlockEntity container; - - //Iterator iter = this.affectedBlocks.entrySet().iterator(); for (Block block : this.affectedBlocks) { - //Block block = (Block) ((HashMap.Entry) iter.next()).getValue(); if (block.getId() == Block.TNT) { - ((BlockTNT) block).prime(new NukkitRandom().nextRange(10, 30), this.what instanceof Entity ? (Entity) this.what : null); - } else if ((container = block.getLevel().getBlockEntity(block)) instanceof InventoryHolder) { - if (container instanceof BlockEntityShulkerBox) { - this.level.dropItem(block.add(0.5, 0.5, 0.5), block.toItem()); - ((InventoryHolder) container).getInventory().clearAll(); - } else { - for (Item drop : ((InventoryHolder) container).getInventory().getContents().values()) { - this.level.dropItem(block.add(0.5, 0.5, 0.5), drop); + ((BlockTNT) block).prime(Utils.rand(10, 30), this.what instanceof Entity ? (Entity) this.what : null); + } else if (block.getId() == Block.BED_BLOCK && (block.getDamage() & 0x08) == 0x08) { + this.level.setBlockAt((int) block.x, (int) block.y, (int) block.z, Block.AIR); + continue; // We don't want drops from both bed parts + } else if ((container = this.level.getBlockEntity(block)) instanceof InventoryHolder && !container.closed) { + if (this.level.getGameRules().getBoolean(GameRule.DO_TILE_DROPS)) { + Inventory inv = ((InventoryHolder) container).getInventory(); + if (inv != null) { + inv.getViewers().clear(); } - ((InventoryHolder) container).getInventory().clearAll(); + if (container instanceof BlockEntityShulkerBox) { + this.level.dropItem(block.add(0.5, 0.5, 0.5), block.toItem()); + ((BlockEntityShulkerBox) container).getInventory().clearAll(); + } else { + container.onBreak(); + } + } + container.close(); + } else if (block.alwaysDropsOnExplosion() || Math.random() * 100 < yield) { + if (this.level.getBlockIdAt((int) block.x, (int) block.y, (int) block.z) == Block.AIR) { + continue; // Block broken by another explosion (end crystals) } - } else if (Math.random() * 100 < yield) { for (Item drop : block.getDrops(air)) { this.level.dropItem(block.add(0.5, 0.5, 0.5), drop); } } - this.level.setBlockAt((int) block.x, (int) block.y, (int) block.z, BlockID.AIR); + this.level.setBlockAt((int) block.x, (int) block.y, (int) block.z, Block.AIR); Vector3 pos = new Vector3(block.x, block.y, block.z); + sideBlocks: for (BlockFace side : BlockFace.values()) { Vector3 sideBlock = pos.getSide(side); long index = Hash.hashBlock((int) sideBlock.x, (int) sideBlock.y, (int) sideBlock.z); - if (!this.affectedBlocks.contains(sideBlock) && !updateBlocks.contains(index)) { + if (!updateBlocks.contains(index)) { + for (Block affected : this.affectedBlocks) { + if (affected.x == sideBlock.x && affected.y == sideBlock.y && affected.z == sideBlock.z) { + continue sideBlocks; + } + } BlockUpdateEvent ev = new BlockUpdateEvent(this.level.getBlock(sideBlock)); this.level.getServer().getPluginManager().callEvent(ev); if (!ev.isCancelled()) { @@ -220,13 +254,195 @@ public boolean explodeB() { updateBlocks.add(index); } } - send.add(new Vector3(block.x - source.x, block.y - source.y, block.z - source.z)); } this.level.addParticle(new HugeExplodeSeedParticle(this.source)); this.level.addLevelSoundEvent(source, LevelSoundEventPacket.SOUND_EXPLODE); - return true; } + public void explodeEntity() { + if (this.what instanceof Entity) { + EntityExplodeEvent ev = new EntityExplodeEvent((Entity) this.what, this.source, this.affectedBlocks, 0); + this.level.getServer().getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + return; + } + } + + double explosionSize = this.size * 2d; + double minX = NukkitMath.floorDouble(this.source.x - explosionSize - 1); + double maxX = NukkitMath.ceilDouble(this.source.x + explosionSize + 1); + double minY = NukkitMath.floorDouble(this.source.y - explosionSize - 1); + double maxY = NukkitMath.ceilDouble(this.source.y + explosionSize + 1); + double minZ = NukkitMath.floorDouble(this.source.z - explosionSize - 1); + double maxZ = NukkitMath.ceilDouble(this.source.z + explosionSize + 1); + + AxisAlignedBB explosionBB = new SimpleAxisAlignedBB(minX, minY, minZ, maxX, maxY, maxZ); + Entity[] list = this.level.getNearbyEntities(explosionBB, this.what instanceof Entity ? (Entity) this.what : null); + for (Entity entity : list) { + if (!(entity instanceof EntityLiving) || (entity instanceof EntityEnderDragon)) { + continue; + } + + double distance = entity.distance(this.source) / explosionSize; + + if (distance <= 1) { + Vector3 motion = entity.subtract(this.source).normalize(); + double exposure = this.getSeenPercent(this.source, entity); + double impact = (1 - distance) * exposure; + + int damage = this.doesDamage ? Math.max((int) (((impact * impact + impact) / 2) * 5 * this.size + 1), 0) : 0; // * 8 * explosionSize + + if (this.what instanceof Entity) { + entity.attack(new EntityDamageByEntityEvent((Entity) this.what, entity, DamageCause.ENTITY_EXPLOSION, damage)); + } else if (this.what instanceof Block) { + entity.attack(new EntityDamageByBlockEvent((Block) this.what, entity, DamageCause.BLOCK_EXPLOSION, damage)); + } else { + entity.attack(new EntityDamageEvent(entity, DamageCause.BLOCK_EXPLOSION, damage)); + } + + if (entity instanceof Player) { + int netheritePieces = 0; + for (Item armor : ((Player) entity).getInventory().getArmorContents()) { + if (armor.getTier() == ItemArmor.TIER_NETHERITE) { + netheritePieces++; + } + } + if (netheritePieces > 0) { + impact *= 1 - 0.1 * netheritePieces; + } + } + entity.setMotion(entity.getMotion().add(motion.multiply(impact))); + } + } + } + + private double getSeenPercent(Vector3 source, Entity entity) { + AxisAlignedBB bb = entity.getBoundingBox(); + + if (bb.isVectorInside(source)) { + return 1; + } + + double x = 1 / ((bb.getMaxX() - bb.getMinX()) * 2 + 1); + double y = 1 / ((bb.getMaxY() - bb.getMinY()) * 2 + 1); + double z = 1 / ((bb.getMaxZ() - bb.getMinZ()) * 2 + 1); + + double xOffset = (1 - Math.floor(1 / x) * x) / 2; + double yOffset = (1 - Math.floor(1 / y) * y) / 2; + double zOffset = (1 - Math.floor(1 / z) * z) / 2; + + int misses = 0; + int total = 0; + + for (double i = 0; i <= 1; i += x) { + for (double j = 0; j <= 1; j += y) { + for (double k = 0; k <= 1; k += z) { + Vector3 target = new Vector3( + bb.getMinX() + i * (bb.getMaxX() - bb.getMinX()) + xOffset, + bb.getMinY() + j * (bb.getMaxY() - bb.getMinY()) + yOffset, + bb.getMinZ() + k * (bb.getMaxZ() - bb.getMinZ()) + zOffset + ); + + if (!this.raycast(source, target)) { + ++misses; + } + + total++; + } + } + } + + return total != 0 ? (double) misses / (double) total : 0; + } + + private boolean raycast(Vector3 start, Vector3 end) { + Vector3 current = new Vector3(start.x, start.y, start.z); + Vector3 direction = end.subtract(start).normalize(); + + double stepX = sign(direction.getX()); + double stepY = sign(direction.getY()); + double stepZ = sign(direction.getZ()); + + double tMaxX = boundary(start.getX(), direction.getX()); + double tMaxY = boundary(start.getY(), direction.getY()); + double tMaxZ = boundary(start.getZ(), direction.getZ()); + + double tDeltaX = direction.getX() == 0 ? 0 : stepX / direction.getX(); + double tDeltaY = direction.getY() == 0 ? 0 : stepY / direction.getY(); + double tDeltaZ = direction.getZ() == 0 ? 0 : stepZ / direction.getZ(); + + double radius = start.distance(end); + + while (true) { + Block block = level.getBlock(current); + + if (block.isSolid() && block.calculateIntercept(current, end) != null) { + return true; + } + + if (tMaxX < tMaxY && tMaxX < tMaxZ) { + if (tMaxX > radius) { + break; + } + + current.x += stepX; + tMaxX += tDeltaX; + } else if (tMaxY < tMaxZ) { + if (tMaxY > radius) { + break; + } + + current.y += stepY; + tMaxY += tDeltaY; + } else { + if (tMaxZ > radius) { + break; + } + + current.z += stepZ; + tMaxZ += tDeltaZ; + } + } + + return false; + } + + private static double sign(double d) { + if (d > 0) { + return 1; + } + + if (d < 0) { + return -1; + } + + return 0; + } + + private static double boundary(double start, double distance) { + if (distance == 0) { + return Double.POSITIVE_INFINITY; + } + + if (distance < 0) { + start = -start; + distance = -distance; + + if (Math.floor(start) == start) { + return 0; + } + } + + return (1 - (start - Math.floor(start))) / distance; + } + + /** + * Set minimum height at which the explosion can break blocks + * @param minHeight min y coordinate + */ + public void setMinHeight(double minHeight) { + this.minHeight = minHeight; + } } diff --git a/src/main/java/cn/nukkit/level/GameRule.java b/src/main/java/cn/nukkit/level/GameRule.java index e66454ed125..7c4b93574ea 100644 --- a/src/main/java/cn/nukkit/level/GameRule.java +++ b/src/main/java/cn/nukkit/level/GameRule.java @@ -50,7 +50,7 @@ public enum GameRule { public static Optional parseString(String gameRuleString) { for (GameRule gameRule: values()) { - if (gameRule.getName().equalsIgnoreCase(gameRuleString)) { + if (gameRule.name.equalsIgnoreCase(gameRuleString)) { return Optional.of(gameRule); } } @@ -59,9 +59,16 @@ public static Optional parseString(String gameRuleString) { public static String[] getNames() { String[] stringValues = new String[values().length]; + for (int i = 0; i < values().length; i++) { + stringValues[i] = values()[i].name; + } + return stringValues; + } + public static String[] getNamesLowerCase() { + String[] stringValues = new String[values().length]; for (int i = 0; i < values().length; i++) { - stringValues[i] = values()[i].getName(); + stringValues[i] = values()[i].name.toLowerCase(); } return stringValues; } diff --git a/src/main/java/cn/nukkit/level/GameRules.java b/src/main/java/cn/nukkit/level/GameRules.java index 1890cd271f6..43017168ba0 100644 --- a/src/main/java/cn/nukkit/level/GameRules.java +++ b/src/main/java/cn/nukkit/level/GameRules.java @@ -12,15 +12,12 @@ import static cn.nukkit.level.GameRule.*; -@SuppressWarnings({"unchecked"}) +@SuppressWarnings("unchecked") public class GameRules { + private final EnumMap gameRules = new EnumMap<>(GameRule.class); private boolean stale; - private GameRules() { - } - - public static GameRules getDefault() { GameRules gameRules = new GameRules(); @@ -107,9 +104,9 @@ public void setGameRules(GameRule gameRule, String value) throws IllegalArgument switch (getGameRuleType(gameRule)) { case BOOLEAN: - if (value.equalsIgnoreCase("true")) { + if (value.equalsIgnoreCase("true") || value.equals("1")) { setGameRule(gameRule, true); - } else if (value.equalsIgnoreCase("false")) { + } else if (value.equalsIgnoreCase("false") || value.equals("0")) { setGameRule(gameRule, false); } else { throw new IllegalArgumentException("Was not a boolean"); @@ -128,22 +125,18 @@ public boolean getBoolean(GameRule gameRule) { } public int getInteger(GameRule gameRule) { - Preconditions.checkNotNull(gameRule, "gameRule"); return gameRules.get(gameRule).getValueAsInteger(); } public float getFloat(GameRule gameRule) { - Preconditions.checkNotNull(gameRule, "gameRule"); return gameRules.get(gameRule).getValueAsFloat(); } public String getString(GameRule gameRule) { - Preconditions.checkNotNull(gameRule, "gameRule"); return gameRules.get(gameRule).value.toString(); } public Type getGameRuleType(GameRule gameRule) { - Preconditions.checkNotNull(gameRule, "gameRule"); return gameRules.get(gameRule).getType(); } @@ -155,7 +148,6 @@ public GameRule[] getRules() { return gameRules.keySet().toArray(new GameRule[0]); } - // TODO: This needs to be moved out since there is not a separate compound tag in the LevelDB format for Game Rules. public CompoundTag writeNBT() { CompoundTag nbt = new CompoundTag(); @@ -167,7 +159,7 @@ public CompoundTag writeNBT() { } public void readNBT(CompoundTag nbt) { - Preconditions.checkNotNull(nbt); + Preconditions.checkNotNull(nbt, "nbt"); for (String key : nbt.getTags().keySet()) { Optional gameRule = GameRule.parseString(key); if (!gameRule.isPresent()) { @@ -256,10 +248,10 @@ private float getValueAsFloat() { return (Float) value; } - public void write(BinaryStream stream) { - stream.putBoolean(this.canBeChanged); - stream.putUnsignedVarInt(type.ordinal()); - type.write(stream, this); + public void write(BinaryStream pk) { + pk.putBoolean(this.canBeChanged); + pk.putUnsignedVarInt(type.ordinal()); + type.write(pk, this); } } } diff --git a/src/main/java/cn/nukkit/level/GlobalBlockPalette.java b/src/main/java/cn/nukkit/level/GlobalBlockPalette.java index 8adedce836e..34f41090171 100644 --- a/src/main/java/cn/nukkit/level/GlobalBlockPalette.java +++ b/src/main/java/cn/nukkit/level/GlobalBlockPalette.java @@ -1,97 +1,84 @@ package cn.nukkit.level; -import cn.nukkit.Server; -import cn.nukkit.block.BlockID; -import cn.nukkit.nbt.NBTIO; +import cn.nukkit.level.format.leveldb.LevelDBConstants; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.ListTag; -import it.unimi.dsi.fastutil.ints.Int2IntMap; -import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; +import cn.nukkit.network.protocol.ProtocolInfo; +import cn.nukkit.utils.Utils; import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import lombok.Getter; import lombok.extern.log4j.Log4j2; -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteOrder; import java.util.List; import java.util.NoSuchElementException; -import java.util.zip.GZIPInputStream; @Log4j2 public class GlobalBlockPalette { - private static final Int2IntMap legacyToRuntimeId = new Int2IntOpenHashMap(); - private static final Int2IntMap runtimeIdToLegacy = new Int2IntOpenHashMap(); - static { - legacyToRuntimeId.defaultReturnValue(-1); - runtimeIdToLegacy.defaultReturnValue(-1); + private static boolean initialized; - ListTag tag; - try (InputStream stream = Server.class.getClassLoader().getResourceAsStream("runtime_block_states.dat")) { - if (stream == null) { - throw new AssertionError("Unable to locate block state nbt"); - } - //noinspection unchecked - tag = (ListTag) NBTIO.readTag(new BufferedInputStream(new GZIPInputStream(stream)), ByteOrder.BIG_ENDIAN, false); - } catch (IOException e) { - throw new AssertionError("Unable to load block palette", e); + @Getter + private static final BlockPalette currentBlockPalette = new BlockPalette(ProtocolInfo.CURRENT_PROTOCOL); + @Getter + private static final BlockPalette leveldbBlockPalette = new BlockPalette(LevelDBConstants.PALETTE_VERSION); + + public static void init() { + if (initialized) { + throw new IllegalStateException("GlobalBlockPalette was already generated!"); } + initialized = true; + log.debug("Loading block palette..."); + + //noinspection unchecked + loadBlockStates((ListTag) Utils.loadTagResource("runtime_block_states.dat"), getCurrentBlockPalette()); + //noinspection unchecked + loadBlockStates((ListTag) Utils.loadTagResource("runtime_block_states_" + LevelDBConstants.PALETTE_VERSION + ".dat"), getLeveldbBlockPalette()); + } + private static void loadBlockStates(ListTag blockStates, BlockPalette blockPalette) { List stateOverloads = new ObjectArrayList<>(); - for (CompoundTag state : tag.getAll()) { - if (!registerBlockState(state, false)) { + for (CompoundTag state : blockStates.getAll()) { + if (!registerBlockState(blockPalette, state, false)) { stateOverloads.add(state); } } for (CompoundTag state : stateOverloads) { - log.debug("Registering block palette overload: {}", state.getString("name")); - registerBlockState(state, true); + log.debug("[{}] Registering block palette overload: {}", blockPalette.getProtocol(), state.getString("name")); + registerBlockState(blockPalette, state, true); } + + blockPalette.lock(); // prevent adding new states } - private static boolean registerBlockState(CompoundTag state, boolean force) { - int blockId = state.getInt("id"); - int meta = state.getShort("data"); + private static boolean registerBlockState(BlockPalette blockPalette, CompoundTag state, boolean force) { + int id = state.getInt("id"); + int data = state.getShort("data"); int runtimeId = state.getInt("runtimeId"); boolean stateOverload = state.getBoolean("stateOverload"); - // DO NOT MERGE! - if (meta > 15) { // Not supported here - return true; // Not an overload - } - if (stateOverload && !force) { return false; } - int legacyId = blockId << 6 | meta; - legacyToRuntimeId.put(legacyId, runtimeId); - runtimeIdToLegacy.putIfAbsent(runtimeId, legacyId); + CompoundTag vanillaState = state + .remove("id") + .remove("data") + .remove("runtimeId") + .remove("stateOverload"); + blockPalette.registerState(id, data, runtimeId, vanillaState); return true; } public static int getOrCreateRuntimeId(int id, int meta) { - int legacyId = id << 6 | meta; - int runtimeId = legacyToRuntimeId.get(legacyId); - if (runtimeId == -1) { - runtimeId = legacyToRuntimeId.get(id << 6); - if (runtimeId == -1 && id != BlockID.INFO_UPDATE) { - log.info("Unable to find runtime id for {}", id); - return getOrCreateRuntimeId(BlockID.INFO_UPDATE, 0); - } else if (id == BlockID.INFO_UPDATE){ - throw new IllegalStateException("InfoUpdate state is missing!"); - } - } - return runtimeId; + return getCurrentBlockPalette().getRuntimeId(id, meta); } public static int getOrCreateRuntimeId(int legacyId) throws NoSuchElementException { - return getOrCreateRuntimeId(legacyId >> 4, legacyId & 0xf); + return getCurrentBlockPalette().getRuntimeId(legacyId); } public static int getLegacyFullId(int runtimeId) { - return runtimeIdToLegacy.get(runtimeId); + return getCurrentBlockPalette().getLegacyFullId(runtimeId); } } diff --git a/src/main/java/cn/nukkit/level/Level.java b/src/main/java/cn/nukkit/level/Level.java index a625279ded7..c3d9250cf60 100644 --- a/src/main/java/cn/nukkit/level/Level.java +++ b/src/main/java/cn/nukkit/level/Level.java @@ -2,14 +2,14 @@ import cn.nukkit.Player; import cn.nukkit.Server; -import cn.nukkit.block.Block; -import cn.nukkit.block.BlockID; -import cn.nukkit.block.BlockRedstoneDiode; +import cn.nukkit.block.*; import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.entity.Entity; +import cn.nukkit.entity.custom.EntityDefinition; +import cn.nukkit.entity.custom.EntityManager; import cn.nukkit.entity.item.EntityItem; import cn.nukkit.entity.item.EntityXPOrb; -import cn.nukkit.entity.projectile.EntityArrow; +import cn.nukkit.entity.projectile.EntityProjectile; import cn.nukkit.entity.weather.EntityLightning; import cn.nukkit.event.block.BlockBreakEvent; import cn.nukkit.event.block.BlockPlaceEvent; @@ -18,6 +18,8 @@ import cn.nukkit.event.player.PlayerInteractEvent; import cn.nukkit.event.player.PlayerInteractEvent.Action; import cn.nukkit.event.weather.LightningStrikeEvent; +import cn.nukkit.inventory.Inventory; +import cn.nukkit.inventory.InventoryHolder; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemBucket; @@ -29,18 +31,19 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.format.LevelProvider; import cn.nukkit.level.format.anvil.Anvil; +import cn.nukkit.level.format.generic.BaseChunk; import cn.nukkit.level.format.generic.BaseFullChunk; -import cn.nukkit.level.format.generic.BaseLevelProvider; import cn.nukkit.level.format.generic.EmptyChunkSection; -import cn.nukkit.level.format.leveldb.LevelDB; -import cn.nukkit.level.format.mcregion.McRegion; import cn.nukkit.level.generator.Generator; +import cn.nukkit.level.generator.GeneratorTaskFactory; import cn.nukkit.level.generator.PopChunkManager; import cn.nukkit.level.generator.task.GenerationTask; -import cn.nukkit.level.generator.task.LightPopulationTask; import cn.nukkit.level.generator.task.PopulationTask; import cn.nukkit.level.particle.DestroyBlockParticle; +import cn.nukkit.level.particle.ItemBreakParticle; import cn.nukkit.level.particle.Particle; +import cn.nukkit.level.persistence.PersistentDataContainer; +import cn.nukkit.level.persistence.impl.DelegatePersistentDataContainer; import cn.nukkit.math.*; import cn.nukkit.math.BlockFace.Plane; import cn.nukkit.metadata.BlockMetadataStore; @@ -53,32 +56,25 @@ import cn.nukkit.potion.Effect; import cn.nukkit.scheduler.AsyncTask; import cn.nukkit.scheduler.BlockUpdateScheduler; -import cn.nukkit.timings.LevelTimings; import cn.nukkit.utils.*; -import co.aikar.timings.Timings; -import co.aikar.timings.TimingsHistory; -import com.google.common.base.Preconditions; -import it.unimi.dsi.fastutil.ints.Int2IntMap; -import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; -import it.unimi.dsi.fastutil.ints.Int2ObjectMap; -import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.ints.*; import it.unimi.dsi.fastutil.longs.*; import it.unimi.dsi.fastutil.objects.ObjectIterator; +import lombok.Getter; +import lombok.Setter; -import java.io.File; -import java.io.IOException; import java.lang.ref.SoftReference; import java.util.*; import java.util.concurrent.*; + /** - * author: MagicDroidX Nukkit Project + * @author MagicDroidX Nukkit Project */ -public class Level implements ChunkManager, Metadatable { +public class Level implements ChunkManager, Metadatable, GeneratorTaskFactory { private static int levelIdCounter = 1; private static int chunkLoaderCounter = 1; - public static int COMPRESSION_LEVEL = 8; public static final int BLOCK_UPDATE_NORMAL = 1; public static final int BLOCK_UPDATE_RANDOM = 2; @@ -101,11 +97,14 @@ public class Level implements ChunkManager, Metadatable { public static final int DIMENSION_NETHER = 1; public static final int DIMENSION_THE_END = 2; - // Lower values use less memory - public static final int MAX_BLOCK_CACHE = 512; + public static final int MAX_BLOCK_CACHE = 1024; + + private static final int LCG_CONSTANT = 1013904223; - // The blocks that can randomly tick - private static final boolean[] randomTickBlocks = new boolean[256]; + /** + * The blocks that can be randomly ticked + */ + private static final boolean[] randomTickBlocks = new boolean[Block.MAX_BLOCK_ID]; static { randomTickBlocks[Block.GRASS] = true; @@ -126,34 +125,63 @@ public class Level implements ChunkManager, Metadatable { randomTickBlocks[Block.PUMPKIN_STEM] = true; randomTickBlocks[Block.WHEAT_BLOCK] = true; randomTickBlocks[Block.SUGARCANE_BLOCK] = true; - randomTickBlocks[Block.RED_MUSHROOM] = true; - randomTickBlocks[Block.BROWN_MUSHROOM] = true; randomTickBlocks[Block.NETHER_WART_BLOCK] = true; randomTickBlocks[Block.FIRE] = true; randomTickBlocks[Block.GLOWING_REDSTONE_ORE] = true; randomTickBlocks[Block.COCOA_BLOCK] = true; + randomTickBlocks[Block.ICE_FROSTED] = true; randomTickBlocks[Block.VINE] = true; + randomTickBlocks[Block.WATER] = true; + randomTickBlocks[Block.CAULDRON_BLOCK] = true; + randomTickBlocks[Block.CHORUS_FLOWER] = true; + randomTickBlocks[Block.SWEET_BERRY_BUSH] = true; + randomTickBlocks[Block.BAMBOO_SAPLING] = true; + randomTickBlocks[Block.BAMBOO] = true; + randomTickBlocks[Block.CORAL_FAN] = true; + randomTickBlocks[Block.CORAL_FAN_DEAD] = true; + randomTickBlocks[Block.BLOCK_KELP] = true; + randomTickBlocks[BlockID.COPPER_BLOCK] = true; + randomTickBlocks[BlockID.EXPOSED_COPPER] = true; + randomTickBlocks[BlockID.WEATHERED_COPPER] = true; + randomTickBlocks[BlockID.WAXED_COPPER] = true; + randomTickBlocks[BlockID.CUT_COPPER] = true; + randomTickBlocks[BlockID.EXPOSED_CUT_COPPER] = true; + randomTickBlocks[BlockID.WEATHERED_CUT_COPPER] = true; + randomTickBlocks[BlockID.CUT_COPPER_STAIRS] = true; + randomTickBlocks[BlockID.EXPOSED_CUT_COPPER_STAIRS] = true; + randomTickBlocks[BlockID.WEATHERED_CUT_COPPER_STAIRS] = true; + randomTickBlocks[BlockID.CUT_COPPER_SLAB] = true; + randomTickBlocks[BlockID.EXPOSED_CUT_COPPER_SLAB] = true; + randomTickBlocks[BlockID.WEATHERED_CUT_COPPER_SLAB] = true; + randomTickBlocks[BlockID.DOUBLE_CUT_COPPER_SLAB] = true; + randomTickBlocks[BlockID.EXPOSED_DOUBLE_CUT_COPPER_SLAB] = true; + randomTickBlocks[BlockID.WEATHERED_DOUBLE_CUT_COPPER_SLAB] = true; + randomTickBlocks[BlockID.BUDDING_AMETHYST] = true; + randomTickBlocks[BlockID.CAVE_VINES] = true; + randomTickBlocks[BlockID.CAVE_VINES_BODY_WITH_BERRIES] = true; + randomTickBlocks[BlockID.CAVE_VINES_HEAD_WITH_BERRIES] = true; + randomTickBlocks[BlockID.AZALEA_LEAVES] = true; + randomTickBlocks[BlockID.AZALEA_LEAVES_FLOWERED] = true; + randomTickBlocks[BlockID.POINTED_DRIPSTONE] = true; } private final Long2ObjectOpenHashMap blockEntities = new Long2ObjectOpenHashMap<>(); private final Long2ObjectOpenHashMap players = new Long2ObjectOpenHashMap<>(); - private final Long2ObjectOpenHashMap entities = new Long2ObjectOpenHashMap<>(); + public final Long2ObjectOpenHashMap entities = new Long2ObjectOpenHashMap<>(); public final Long2ObjectOpenHashMap updateEntities = new Long2ObjectOpenHashMap<>(); private final ConcurrentLinkedQueue updateBlockEntities = new ConcurrentLinkedQueue<>(); - private boolean cacheChunks = false; - private final Server server; - + private final int levelId; private LevelProvider provider; - private final Int2ObjectOpenHashMap loaders = new Int2ObjectOpenHashMap<>(); + private final Int2ObjectMap loaders = new Int2ObjectOpenHashMap<>(); private final Int2IntMap loaderCounter = new Int2IntOpenHashMap(); @@ -165,140 +193,117 @@ public class Level implements ChunkManager, Metadatable { private final Long2LongMap unloadQueue = Long2LongMaps.synchronize(new Long2LongOpenHashMap()); - private float time; + private int time; public boolean stopTime; - + public int sleepTicks; public float skyLightSubtracted; + @Getter + @Setter + public boolean lightUpdatesEnabled = true; - private String folderName; - - private Vector3 mutableBlock; + private final String folderName; // Avoid OOM, gc'd references result in whole chunk being sent (possibly higher cpu) - private final Long2ObjectOpenHashMap>> changedBlocks = new Long2ObjectOpenHashMap<>(); + private final Long2ObjectOpenHashMap>> changedBlocks = new Long2ObjectOpenHashMap<>(); // Storing the vector is redundant private final Object changeBlocksPresent = new Object(); // Storing extra blocks past 512 is redundant - private final Map changeBlocksFullMap = new HashMap() { - @Override - public int size() { - return Character.MAX_VALUE; - } - }; - + private final Int2ObjectOpenHashMap changeBlocksFullMap = new Int2ObjectOpenHashMap<>(); private final BlockUpdateScheduler updateQueue; private final Queue normalUpdateQueue = new ConcurrentLinkedDeque<>(); -// private final TreeSet updateQueue = new TreeSet<>(); -// private final List nextTickUpdates = Lists.newArrayList(); - //private final Map updateQueueIndex = new HashMap<>(); + private final Map> lightQueue = new ConcurrentHashMap<>(8, 0.9f, 1); private final ConcurrentMap> chunkSendQueue = new ConcurrentHashMap<>(); private final LongSet chunkSendTasks = new LongOpenHashSet(); - private final Long2ObjectOpenHashMap chunkPopulationQueue = new Long2ObjectOpenHashMap<>(); - private final Long2ObjectOpenHashMap chunkPopulationLock = new Long2ObjectOpenHashMap<>(); - private final Long2ObjectOpenHashMap chunkGenerationQueue = new Long2ObjectOpenHashMap<>(); - private int chunkGenerationQueueSize = 8; - private int chunkPopulationQueueSize = 2; + private final LongOpenHashSet chunkPopulationQueue = new LongOpenHashSet(); + private final LongOpenHashSet chunkPopulationLock = new LongOpenHashSet(); + private final LongOpenHashSet chunkGenerationQueue = new LongOpenHashSet(); + private final int chunkGenerationQueueSize; + private final int chunkPopulationQueueSize; private boolean autoSave; + @Getter + @Setter + private boolean saveOnUnloadEnabled = true; + public boolean isBeingConverted; private BlockMetadataStore blockMetadata; - private boolean useSections; - - private Position temporalPosition; - private Vector3 temporalVector; + private final boolean useSections; - public int sleepTicks = 0; - - private int chunkTickRadius; + private boolean useChunkLoaderApi; + private final Vector3 temporalVector = new Vector3(0, 0, 0); + private final int chunkTickRadius; private final Long2IntMap chunkTickList = new Long2IntOpenHashMap(); - private int chunksPerTicks; - private boolean clearChunksOnTick; + private final int chunksPerTicks; + private final boolean clearChunksOnTick; private int updateLCG = ThreadLocalRandom.current().nextInt(); - private static final int LCG_CONSTANT = 1013904223; + private int tickRate = 1; + public int tickRateTime; + public int tickRateCounter; + private long levelCurrentTick; - public LevelTimings timings; + private boolean raining; + private int rainTime; + private boolean thundering; + private int thunderTime; - private int tickRate; - public int tickRateTime = 0; - public int tickRateCounter = 0; + @SuppressWarnings("FieldMayBeFinal") private Class generatorClass; + @SuppressWarnings("FieldMayBeFinal") private ThreadLocal generators = new ThreadLocal() { - private Class generatorClass; - private ThreadLocal generators = new ThreadLocal() { @Override public Generator initialValue() { try { Generator generator = generatorClass.getConstructor(Map.class).newInstance(provider.getGeneratorOptions()); NukkitRandom rand = new NukkitRandom(getSeed()); - ChunkManager manager; if (Server.getInstance().isPrimaryThread()) { generator.init(Level.this, rand); } - generator.init(new PopChunkManager(getSeed()), rand); + generator.init(new PopChunkManager(getSeed(), Level.this::getDimensionData), rand); return generator; } catch (Throwable e) { - e.printStackTrace(); + Server.getInstance().getLogger().logException(e); return null; } } }; - private boolean raining = false; - private int rainTime = 0; - private boolean thundering = false; - private int thunderTime = 0; - - private long levelCurrentTick = 0; - + @Getter + @Setter private DimensionData dimensionData; public GameRules gameRules; + private final AsyncChunkThread asyncChunkThread; + + private GeneratorTaskFactory generatorTaskFactory = this; + public Level(Server server, String name, String path, Class provider) { this.levelId = levelIdCounter++; - this.blockMetadata = new BlockMetadataStore(this); this.server = server; + this.folderName = name; this.autoSave = server.getAutoSave(); - boolean convert = provider == McRegion.class || provider == LevelDB.class; + this.blockMetadata = new BlockMetadataStore(this); + try { - if (convert) { - String newPath = new File(path).getParent() + "/" + name + ".old/"; - new File(path).renameTo(new File(newPath)); - this.provider = provider.getConstructor(Level.class, String.class).newInstance(this, newPath); - } else { - this.provider = provider.getConstructor(Level.class, String.class).newInstance(this, path); - } + this.provider = provider.getConstructor(Level.class, String.class).newInstance(this, path); } catch (Exception e) { throw new LevelException("Caused by " + Utils.getExceptionMessage(e)); } - this.timings = new LevelTimings(this); - - if (convert) { - this.server.getLogger().info(this.server.getLanguage().translateString("nukkit.level.updating", - TextFormat.GREEN + this.provider.getName() + TextFormat.WHITE)); - LevelProvider old = this.provider; - try { - this.provider = new LevelProviderConverter(this, path) - .from(old) - .to(Anvil.class) - .perform(); - } catch (IOException e) { - throw new RuntimeException(e); - } - old.close(); - } - this.provider.updateLevelName(name); this.server.getLogger().info(this.server.getLanguage().translateString("nukkit.level.preparing", - TextFormat.GREEN + this.provider.getName() + TextFormat.WHITE)); + TextFormat.GREEN + name + TextFormat.WHITE)); + + if (this.provider instanceof Anvil) { + this.server.getLogger().warning("Level \"" + name + "\" is in old format. Convert it to enable new features. Type 'convert " + name + "' to get started."); + } this.generatorClass = Generator.getGenerator(this.provider.getGenerator()); @@ -308,8 +313,7 @@ public Level(Server server, String name, String path, Class= 256) { - throw new IllegalArgumentException("Y coordinate y is out of range!"); - } - return (((long) x & (long) 0xFFFFFFF) << 36) | (((long) y & (long) 0xFF) << 28) | ((long) z & (long) 0xFFFFFFF); + public static long blockHash(int x, int y, int z, DimensionData dimensionData) { + return (((long) x & (long) 0xFFFFFFF) << 36) | ((long) (capWorldY(y, dimensionData) - dimensionData.getMinHeight()) << 28) | ((long) z & (long) 0xFFFFFFF); } - public static char localBlockHash(double x, double y, double z) { + public static int localBlockHash(double x, double y, double z, DimensionData dimensionData) { byte hi = (byte) (((int) x & 15) + (((int) z & 15) << 4)); - byte lo = (byte) y; - return (char) (((hi & 0xFF) << 8) | (lo & 0xFF)); + short lo = (short) (capWorldY((int) y, dimensionData) - dimensionData.getMinHeight()); + return (hi & 0xFF) << 16 | lo; } - public static Vector3 getBlockXYZ(long chunkHash, char blockHash) { - int hi = (byte) (blockHash >>> 8); - int lo = (byte) blockHash; - int y = lo & 0xFF; + public static Vector3 getBlockXYZ(long chunkHash, int blockHash, DimensionData dimensionData) { + int hi = (byte) (blockHash >>> 16); + int lo = (short) blockHash; + int y = capWorldY(lo + dimensionData.getMinHeight(), dimensionData); int x = (hi & 0xF) + (getHashX(chunkHash) << 4); int z = ((hi >> 4) & 0xF) + (getHashZ(chunkHash) << 4); return new Vector3(x, y, z); } + public static BlockVector3 blockHash(double x, double y, double z) { + return new BlockVector3((int) x, (int) y, (int) z); + } + public static int chunkBlockHash(int x, int y, int z) { - return (x << 12) | (z << 8) | y; + return (x << 13) | (z << 9) | (y + 64); } public static int getHashX(long hash) { @@ -387,6 +388,10 @@ public static Chunk.Entry getChunkXZ(long hash) { return new Chunk.Entry(getHashX(hash), getHashZ(hash)); } + private static int capWorldY(int y, DimensionData dimensionData) { + return Math.max(Math.min(y, dimensionData.getMaxHeight()), dimensionData.getMinHeight()); + } + public static int generateChunkLoaderId(ChunkLoader loader) { if (loader.getLoaderId() == 0) { return chunkLoaderCounter++; @@ -410,11 +415,12 @@ public void setTickRate(int tickRate) { public void initLevel() { Generator generator = generators.get(); this.dimensionData = generator.getDimensionData(); - this.gameRules = this.provider.getGamerules(); + if (this.dimensionData.getDimensionId() == DIMENSION_OVERWORLD && + this.provider instanceof Anvil) { + this.dimensionData = DimensionData.LEGACY_DIMENSION; + } - this.server.getLogger().info("Preparing start region for level \"" + this.getFolderName() + "\""); - Position spawn = this.getSpawnLocation(); - this.populateChunk(spawn.getChunkX(), spawn.getChunkZ(), true); + this.gameRules = this.provider.getGamerules(); } public Generator getGenerator() { @@ -438,14 +444,14 @@ final public int getId() { } public void close() { - if (this.getAutoSave()) { - this.save(true); + if (this.asyncChunkThread != null) { + this.asyncChunkThread.shutdown(); } - this.provider.close(); + this.saveLevelData(); + this.provider.close(); // Also saves chunks on unload this.provider = null; this.blockMetadata = null; - this.temporalPosition = null; this.server.getLevels().remove(this.levelId); } @@ -462,8 +468,8 @@ public void addSound(Vector3 pos, Sound sound, float volume, float pitch, Collec } public void addSound(Vector3 pos, Sound sound, float volume, float pitch, Player... players) { - Preconditions.checkArgument(volume >= 0 && volume <= 1, "Sound volume must be between 0 and 1"); - Preconditions.checkArgument(pitch >= 0, "Sound pitch must be higher than 0"); + if (volume < 0 || volume > 1) throw new IllegalArgumentException("Sound volume must be between 0 and 1"); + if (pitch < 0) throw new IllegalArgumentException("Sound pitch must be higher than 0"); PlaySoundPacket packet = new PlaySoundPacket(); packet.name = sound.getSound(); @@ -474,7 +480,7 @@ public void addSound(Vector3 pos, Sound sound, float volume, float pitch, Player packet.z = pos.getFloorZ(); if (players == null || players.length == 0) { - addChunkPacket(pos.getFloorX() >> 4, pos.getFloorZ() >> 4, packet); + this.addChunkPacket(pos.getChunkX(), pos.getChunkZ(), packet); } else { Server.broadcastPacket(players, packet); } @@ -491,17 +497,24 @@ public void addLevelEvent(Vector3 pos, int event, int data) { pk.y = (float) pos.y; pk.z = (float) pos.z; pk.data = data; - - addChunkPacket(pos.getFloorX() >> 4, pos.getFloorZ() >> 4, pk); + this.addChunkPacket(pos.getChunkX(), pos.getChunkZ(), pk); } public void addLevelSoundEvent(Vector3 pos, int type, int data, int entityType) { - addLevelSoundEvent(pos, type, data, entityType, false, false); + this.addLevelSoundEvent(pos, type, data, entityType, false, false); } public void addLevelSoundEvent(Vector3 pos, int type, int data, int entityType, boolean isBaby, boolean isGlobal) { - String identifier = AddEntityPacket.LEGACY_IDS.getOrDefault(entityType, ":"); - addLevelSoundEvent(pos, type, data, identifier, isBaby, isGlobal); + String identifier = AddEntityPacket.LEGACY_IDS.get(entityType); + if (identifier == null) { + EntityDefinition definition = EntityManager.get().getDefinition(entityType); + if (definition == null) { + identifier = ":"; + } else { + identifier = definition.getIdentifier(); + } + } + this.addLevelSoundEvent(pos, type, data, identifier, isBaby, isGlobal); } public void addLevelSoundEvent(Vector3 pos, int type) { @@ -516,7 +529,7 @@ public void addLevelSoundEvent(Vector3 pos, int type) { * @param data generic data that can affect sound */ public void addLevelSoundEvent(Vector3 pos, int type, int data) { - this.addLevelSoundEvent(pos, type, data, ":", false, false); + this.addLevelSoundEvent(pos, type, data, "", false, false); } public void addLevelSoundEvent(Vector3 pos, int type, int data, String identifier, boolean isBaby, boolean isGlobal) { @@ -530,7 +543,7 @@ public void addLevelSoundEvent(Vector3 pos, int type, int data, String identifie pk.isGlobal = isGlobal; pk.isBabyMob = isBaby; - this.addChunkPacket(pos.getFloorX() >> 4, pos.getFloorZ() >> 4, pk); + this.addChunkPacket(pos.getChunkX(), pos.getChunkZ(), pk); } public void addParticle(Particle particle) { @@ -542,18 +555,19 @@ public void addParticle(Particle particle, Player player) { } public void addParticle(Particle particle, Player[] players) { - DataPacket[] packets = particle.encode(); + this.addParticle(particle, players, 1); + } + public void addParticle(Particle particle, Player[] players, int count) { if (players == null) { - if (packets != null) { - for (DataPacket packet : packets) { - this.addChunkPacket((int) particle.x >> 4, (int) particle.z >> 4, packet); - } - } - } else { - if (packets != null) { - for (DataPacket packet : packets) { - Server.broadcastPacket(players, packet); + players = this.getChunkPlayers(particle.getChunkX(), particle.getChunkZ()).values().toArray(new Player[0]); + } + + DataPacket[] packets = particle.encode(); + if (packets != null) { + for (int i = 0; i < count; i++) { + for (DataPacket pk : packets) { + Server.broadcastPacket(players, pk); } } } @@ -613,7 +627,7 @@ public boolean unload(boolean force) { LevelUnloadEvent ev = new LevelUnloadEvent(this); if (this == this.server.getDefaultLevel() && !force) { - ev.setCancelled(); + ev.setCancelled(true); } this.server.getPluginManager().callEvent(ev); @@ -645,8 +659,9 @@ public boolean unload(boolean force) { public Map getChunkPlayers(int chunkX, int chunkZ) { long index = Level.chunkHash(chunkX, chunkZ); - if (this.playerLoaders.containsKey(index)) { - return new HashMap<>(this.playerLoaders.get(index)); + Map map = this.playerLoaders.get(index); + if (map != null) { + return new HashMap<>(map); } else { return new HashMap<>(); } @@ -654,8 +669,9 @@ public Map getChunkPlayers(int chunkX, int chunkZ) { public ChunkLoader[] getChunkLoaders(int chunkX, int chunkZ) { long index = Level.chunkHash(chunkX, chunkZ); - if (this.chunkLoaders.containsKey(index)) { - return this.chunkLoaders.get(index).values().toArray(new ChunkLoader[0]); + Map map = this.chunkLoaders.get(index); + if (map != null) { + return map.values().toArray(new ChunkLoader[0]); } else { return new ChunkLoader[0]; } @@ -674,18 +690,31 @@ public void registerChunkLoader(ChunkLoader loader, int chunkX, int chunkZ) { } public void registerChunkLoader(ChunkLoader loader, int chunkX, int chunkZ, boolean autoLoad) { + if (!(loader instanceof Player) && !this.useChunkLoaderApi) { + this.server.getLogger().debug("registerChunkLoader: full ChunkLoader API enabled"); + this.useChunkLoaderApi = true; + } + int hash = loader.getLoaderId(); long index = Level.chunkHash(chunkX, chunkZ); - if (!this.chunkLoaders.containsKey(index)) { - this.chunkLoaders.put(index, new HashMap<>()); - this.playerLoaders.put(index, new HashMap<>()); - } else if (this.chunkLoaders.get(index).containsKey(hash)) { - return; - } - this.chunkLoaders.get(index).put(hash, loader); - if (loader instanceof Player) { - this.playerLoaders.get(index).put(hash, (Player) loader); + Map map = this.chunkLoaders.get(index); + if (map == null) { + Map newChunkLoader = new HashMap<>(); + newChunkLoader.put(hash, loader); + this.chunkLoaders.put(index, newChunkLoader); + Map newPlayerLoader = new HashMap<>(); + if (loader instanceof Player) { + newPlayerLoader.put(hash, (Player) loader); + } + this.playerLoaders.put(index, newPlayerLoader); + } else if (map.containsKey(hash)) { + return; + } else { + map.put(hash, loader); + if (loader instanceof Player) { + this.playerLoaders.get(index).put(hash, (Player) loader); + } } if (!this.loaders.containsKey(hash)) { @@ -719,7 +748,7 @@ public void unregisterChunkLoader(ChunkLoader loader, int chunkX, int chunkZ) { } int count = this.loaderCounter.get(hash); - if (--count == 0) { + if (--count <= 0) { this.loaderCounter.remove(hash); this.loaders.remove(hash); } else { @@ -731,13 +760,14 @@ public void unregisterChunkLoader(ChunkLoader loader, int chunkX, int chunkZ) { public void checkTime() { if (!this.stopTime && this.gameRules.getBoolean(GameRule.DO_DAYLIGHT_CYCLE)) { - this.time += tickRate; + this.time = this.time + tickRate; + if (this.time < 0) this.time = 0; } } public void sendTime(Player... players) { SetTimePacket pk = new SetTimePacket(); - pk.time = (int) this.time; + pk.time = this.time; Server.broadcastPacket(players, pk); } @@ -751,17 +781,24 @@ public GameRules getGameRules() { } public void doTick(int currentTick) { - this.timings.doTick.startTiming(); + int sendCount = (this.players.size() + 1) * server.chunksPerTick; + for (int i = 0; i < sendCount; i++) { + AsyncChunkData data = this.asyncChunkThread.out.poll(); + if (data == null) { + break; + } + this.chunkRequestCallback(data.timestamp, data.x, data.z, data.count, data.data, data.hash); + } - updateBlockLight(lightQueue); + this.updateBlockLight(this.lightQueue); this.checkTime(); - if (currentTick % 1200 == 0) { // Send time to client every 60 seconds to make sure it stay in sync + if (currentTick % 6000 == 0) { // Keep the time in sync this.sendTime(); } // Tick Weather - if (this.getDimension() != DIMENSION_NETHER && this.getDimension() != DIMENSION_THE_END && gameRules.getBoolean(GameRule.DO_WEATHER_CYCLE)) { + if (this.getDimension() != DIMENSION_NETHER && this.getDimension() != DIMENSION_THE_END && this.gameRules.getBoolean(GameRule.DO_WEATHER_CYCLE)) { this.rainTime--; if (this.rainTime <= 0) { if (!this.setRaining(!this.raining)) { @@ -794,7 +831,7 @@ public void doTick(int currentTick) { performThunder(entry.getLongKey(), entry.getValue()); } } else { - for (Map.Entry entry : getChunks().entrySet()) { + for (Map.Entry entry : chunks.entrySet()) { performThunder(entry.getKey(), entry.getValue()); } } @@ -806,20 +843,14 @@ public void doTick(int currentTick) { this.levelCurrentTick++; this.unloadChunks(); - this.timings.doTickPending.startTiming(); - int polled = 0; - - this.updateQueue.tick(this.getCurrentTick()); - this.timings.doTickPending.stopTiming(); + this.updateQueue.tick(this.levelCurrentTick); Block block; while ((block = this.normalUpdateQueue.poll()) != null) { block.onUpdate(BLOCK_UPDATE_NORMAL); } - TimingsHistory.entityTicks += this.updateEntities.size(); - this.timings.entityTick.startTiming(); if (!this.updateEntities.isEmpty()) { for (long id : new ArrayList<>(this.updateEntities.keySet())) { @@ -833,46 +864,41 @@ public void doTick(int currentTick) { } } } - this.timings.entityTick.stopTiming(); - TimingsHistory.tileEntityTicks += this.updateBlockEntities.size(); - this.timings.blockEntityTick.startTiming(); this.updateBlockEntities.removeIf(blockEntity -> !blockEntity.isValid() || !blockEntity.onUpdate()); - this.timings.blockEntityTick.stopTiming(); - this.timings.tickChunks.startTiming(); this.tickChunks(); - this.timings.tickChunks.stopTiming(); synchronized (changedBlocks) { if (!this.changedBlocks.isEmpty()) { if (!this.players.isEmpty()) { - ObjectIterator>>> iter = changedBlocks.long2ObjectEntrySet().fastIterator(); + ObjectIterator>>> iter = changedBlocks.long2ObjectEntrySet().fastIterator(); while (iter.hasNext()) { - Long2ObjectMap.Entry>> entry = iter.next(); + Long2ObjectMap.Entry>> entry = iter.next(); long index = entry.getLongKey(); - Map blocks = entry.getValue().get(); + Map blocks = entry.getValue().get(); int chunkX = Level.getHashX(index); int chunkZ = Level.getHashZ(index); if (blocks == null || blocks.size() > MAX_BLOCK_CACHE) { - FullChunk chunk = this.getChunk(chunkX, chunkZ); + FullChunk chunk = this.getChunkIfLoaded(chunkX, chunkZ); + if (chunk == null) { + continue; + } for (Player p : this.getChunkPlayers(chunkX, chunkZ).values()) { p.onChunkChanged(chunk); } } else { - Collection toSend = this.getChunkPlayers(chunkX, chunkZ).values(); - Player[] playerArray = toSend.toArray(new Player[0]); + Player[] playerArray = this.getChunkPlayers(chunkX, chunkZ).values().toArray(new Player[0]); Vector3[] blocksArray = new Vector3[blocks.size()]; int i = 0; - for (char blockHash : blocks.keySet()) { - Vector3 hash = getBlockXYZ(index, blockHash); + for (int blockHash : blocks.keySet()) { + Vector3 hash = getBlockXYZ(index, blockHash, this.getDimensionData()); blocksArray[i++] = hash; } this.sendBlocks(playerArray, blocksArray, UpdateBlockPacket.FLAG_ALL); } } } - this.changedBlocks.clear(); } } @@ -887,8 +913,9 @@ public void doTick(int currentTick) { for (long index : this.chunkPackets.keySet()) { int chunkX = Level.getHashX(index); int chunkZ = Level.getHashZ(index); - Player[] chunkPlayers = this.getChunkPlayers(chunkX, chunkZ).values().toArray(new Player[0]); - if (chunkPlayers.length > 0) { + Map map = this.getChunkPlayers(chunkX, chunkZ); + if (!map.isEmpty()) { + Player[] chunkPlayers = map.values().toArray(new Player[0]); for (DataPacket pk : this.chunkPackets.get(index)) { Server.broadcastPacket(chunkPlayers, pk); } @@ -899,20 +926,22 @@ public void doTick(int currentTick) { if (gameRules.isStale()) { GameRulesChangedPacket packet = new GameRulesChangedPacket(); - packet.gameRules = gameRules; - Server.broadcastPacket(players.values().toArray(new Player[0]), packet); + packet.gameRulesMap = gameRules.getGameRules(); + Server.broadcastPacket(this.players.values(), packet); gameRules.refresh(); } - - this.timings.doTick.stopTiming(); } private void performThunder(long index, FullChunk chunk) { - if (ThreadLocalRandom.current().nextInt(10000) == 0 && !areNeighboringChunksLoaded(index)) { + if (Utils.random.nextInt(100000) < 1) { + if (areNeighboringChunksLoaded(index)) { + return; + } + int LCG = this.getUpdateLCG() >> 2; - int chunkX = chunk.getX() * 16; - int chunkZ = chunk.getZ() * 16; + int chunkX = chunk.getX() << 4; + int chunkZ = chunk.getZ() << 4; Vector3 vector = this.adjustPosToNearbyEntity(new Vector3(chunkX + (LCG & 0xf), 0, chunkZ + (LCG >> 8 & 0xf))); Biome biome = Biome.getBiome(this.getBiomeId(vector.getFloorX(), vector.getFloorZ())); @@ -931,34 +960,30 @@ private void performThunder(long index, FullChunk chunk) { .putList(new ListTag("Rotation").add(new FloatTag("", 0)) .add(new FloatTag("", 0))); - EntityLightning bolt = (EntityLightning) Entity.createEntity("Lightning", chunk, nbt); - if(bolt == null) return; + EntityLightning bolt = (EntityLightning) Entity.createEntity(EntityLightning.NETWORK_ID, chunk, nbt); LightningStrikeEvent ev = new LightningStrikeEvent(this, bolt); - getServer().getPluginManager().callEvent(ev); + server.getPluginManager().callEvent(ev); if (!ev.isCancelled()) { bolt.spawnToAll(); } else { bolt.setEffect(false); } - - this.addLevelSoundEvent(vector, LevelSoundEventPacket.SOUND_THUNDER, -1, EntityLightning.NETWORK_ID); - this.addLevelSoundEvent(vector, LevelSoundEventPacket.SOUND_EXPLODE, -1, EntityLightning.NETWORK_ID); } } public Vector3 adjustPosToNearbyEntity(Vector3 pos) { pos.y = this.getHighestBlockAt(pos.getFloorX(), pos.getFloorZ()); - AxisAlignedBB axisalignedbb = new SimpleAxisAlignedBB(pos.x, pos.y, pos.z, pos.getX(), 255, pos.getZ()).expand(3, 3, 3); + AxisAlignedBB axisalignedbb = new SimpleAxisAlignedBB(pos.x, pos.y, pos.z, pos.getX(), this.getMaxBlockY(), pos.getZ()).expand(3, 3, 3); List list = new ArrayList<>(); for (Entity entity : this.getCollidingEntities(axisalignedbb)) { - if (entity.isAlive() && canBlockSeeSky(entity)) { + if (entity.isAlive() && entity.canSeeSky()) { list.add(entity); } } if (!list.isEmpty()) { - return list.get(ThreadLocalRandom.current().nextInt(list.size())).getPosition(); + return list.get(Utils.random.nextInt(list.size())).getPosition(); } else { if (pos.getY() == -1) { pos = pos.up(2); @@ -975,14 +1000,17 @@ public void checkSleep() { int playerCount = 0; int sleepingPlayerCount = 0; - for (Player p : this.getPlayers().values()) { + for (Player p : this.players.values()) { + if (p.isSpectator()) { + continue; + } playerCount++; if (p.isSleeping()) { sleepingPlayerCount++; } } - if (playerCount > 0 && sleepingPlayerCount / playerCount * 100 >= this.gameRules.getInteger(GameRule.PLAYERS_SLEEPING_PERCENTAGE)) { + if (playerCount > 0 && sleepingPlayerCount / playerCount * 100 >= gameRules.getInteger(GameRule.PLAYERS_SLEEPING_PERCENTAGE)) { int time = this.getTime() % Level.TIME_FULL; if ((time >= Level.TIME_NIGHT && time < Level.TIME_SUNRISE) || this.isThundering()) { @@ -1005,7 +1033,7 @@ public void sendBlockExtraData(int x, int y, int z, int id, int data) { } public void sendBlockExtraData(int x, int y, int z, int id, int data, Collection players) { - sendBlockExtraData(x, y, z, id, data, players.toArray(new Player[0])); + this.sendBlockExtraData(x, y, z, id, data, players.toArray(new Player[0])); } public void sendBlockExtraData(int x, int y, int z, int id, int data, Player[] players) { @@ -1024,22 +1052,25 @@ public void sendBlocks(Player[] target, Vector3[] blocks) { } public void sendBlocks(Player[] target, Vector3[] blocks, int flags) { - this.sendBlocks(target, blocks, flags, 0); + this.sendBlocks(target, blocks, flags, false, Block.LAYER_NORMAL); + this.sendBlocks(target, blocks, flags, false, Block.LAYER_WATERLOGGED); } public void sendBlocks(Player[] target, Vector3[] blocks, int flags, boolean optimizeRebuilds) { - this.sendBlocks(target, blocks, flags, 0, optimizeRebuilds); + this.sendBlocks(target, blocks, flags, optimizeRebuilds, Block.LAYER_NORMAL); + this.sendBlocks(target, blocks, flags, optimizeRebuilds, Block.LAYER_WATERLOGGED); } - public void sendBlocks(Player[] target, Vector3[] blocks, int flags, int dataLayer) { - this.sendBlocks(target, blocks, flags, dataLayer, false); + public void sendBlocks(Player[] target, Vector3[] blocks, int flags, BlockLayer blockLayer) { + this.sendBlocks(target, blocks, flags, false, blockLayer); } - public void sendBlocks(Player[] target, Vector3[] blocks, int flags, int dataLayer, boolean optimizeRebuilds) { + public void sendBlocks(Player[] target, Vector3[] blocks, int flags, boolean optimizeRebuilds, BlockLayer layer) { LongSet chunks = null; if (optimizeRebuilds) { chunks = new LongOpenHashSet(); } + for (Vector3 b : blocks) { if (b == null) { continue; @@ -1053,27 +1084,49 @@ public void sendBlocks(Player[] target, Vector3[] blocks, int flags, int dataLay first = true; } } - UpdateBlockPacket updateBlockPacket = new UpdateBlockPacket(); updateBlockPacket.x = (int) b.x; updateBlockPacket.y = (int) b.y; updateBlockPacket.z = (int) b.z; updateBlockPacket.flags = first ? flags : UpdateBlockPacket.FLAG_NONE; - updateBlockPacket.dataLayer = dataLayer; - int fullId; - if (b instanceof Block) { - fullId = ((Block) b).getFullId(); - } else { - fullId = getFullBlock((int) b.x, (int) b.y, (int) b.z); + updateBlockPacket.dataLayer = layer.ordinal(); + + Block block = (b instanceof Block && ((Block) b).getLayer() == layer) ? (Block) b : this.getBlockAsyncIfLoaded(null, (int) b.x, (int) b.y, (int) b.z, layer); + + UpdateBlockPacket packet = (UpdateBlockPacket) updateBlockPacket.clone(); + + try { + int fullBlock = block.getFullId(); + packet.blockRuntimeId = GlobalBlockPalette.getOrCreateRuntimeId(fullBlock); + } catch (NoSuchElementException e) { + throw new IllegalStateException("Unable to create BlockUpdatePacket at (" + b.x + ", " + b.y + ", " + b.z + ") in " + getName()); + } + + Server.broadcastPacket(target, packet); + } + } + + public void sendBlocks(Player target, Vector3[] blocks, int flags) { + for (Vector3 b : blocks) { + if (b == null) { + continue; } + + UpdateBlockPacket updateBlockPacket = new UpdateBlockPacket(); + updateBlockPacket.x = (int) b.x; + updateBlockPacket.y = (int) b.y; + updateBlockPacket.z = (int) b.z; + updateBlockPacket.flags = flags; + + Block block = b instanceof Block ? (Block) b : this.getBlockAsyncIfLoaded(target.chunk, (int) b.x, (int) b.y, (int) b.z, BlockLayer.NORMAL); + try { - updateBlockPacket.blockRuntimeId = GlobalBlockPalette.getOrCreateRuntimeId(fullId); + updateBlockPacket.blockRuntimeId = GlobalBlockPalette.getOrCreateRuntimeId(block.getFullId()); } catch (NoSuchElementException e) { - throw new IllegalStateException("Unable to create BlockUpdatePacket at (" + - b.x + ", " + b.y + ", " + b.z + ") in " + getName(), e); + throw new IllegalStateException("Unable to create BlockUpdatePacket at (" + b.x + ", " + b.y + ", " + b.z + ") in " + getName() + " for player " + target.getName()); } - Server.broadcastPacket(target, updateBlockPacket); + target.dataPacket(updateBlockPacket); } } @@ -1087,22 +1140,19 @@ private void tickChunks() { int randRange = 3 + chunksPerLoader / 30; randRange = Math.min(randRange, this.chunkTickRadius); - ThreadLocalRandom random = ThreadLocalRandom.current(); - if (!this.loaders.isEmpty()) { - for (ChunkLoader loader : this.loaders.values()) { - int chunkX = (int) loader.getX() >> 4; - int chunkZ = (int) loader.getZ() >> 4; - - long index = Level.chunkHash(chunkX, chunkZ); - int existingLoaders = Math.max(0, this.chunkTickList.getOrDefault(index, 0)); - this.chunkTickList.put(index, existingLoaders + 1); - for (int chunk = 0; chunk < chunksPerLoader; ++chunk) { - int dx = random.nextInt(2 * randRange) - randRange; - int dz = random.nextInt(2 * randRange) - randRange; - long hash = Level.chunkHash(dx + chunkX, dz + chunkZ); - if (!this.chunkTickList.containsKey(hash) && provider.isChunkLoaded(hash)) { - this.chunkTickList.put(hash, -1); - } + for (ChunkLoader loader : this.loaders.values()) { + int chunkX = NukkitMath.floorDouble(loader.getX()) >> 4; + int chunkZ = NukkitMath.floorDouble(loader.getZ()) >> 4; + + long index = Level.chunkHash(chunkX, chunkZ); + int existingLoaders = Math.max(0, this.chunkTickList.getOrDefault(index, 0)); + this.chunkTickList.put(index, existingLoaders + 1); + for (int chunk = 0; chunk < chunksPerLoader; ++chunk) { + int dx = Utils.random.nextInt(randRange << 1) - randRange; + int dz = Utils.random.nextInt(randRange << 1) - randRange; + long hash = Level.chunkHash(dx + chunkX, dz + chunkZ); + if (!this.chunkTickList.containsKey(hash) && provider.isChunkLoaded(hash)) { + this.chunkTickList.put(hash, -1); } } } @@ -1125,7 +1175,7 @@ private void tickChunks() { int chunkZ = getHashZ(index); FullChunk chunk; - if ((chunk = this.getChunk(chunkX, chunkZ, false)) == null) { + if ((chunk = this.getChunkIfLoaded(chunkX, chunkZ)) == null) { iter.remove(); continue; } else if (loaders <= 0) { @@ -1133,46 +1183,48 @@ private void tickChunks() { } for (Entity entity : chunk.getEntities().values()) { - entity.scheduleUpdate(); + if (entity.updateMode < 1 || (entity.updateMode % 3 == 2 && server.getTick() - entity.lastUpdate > 300)) { // Force an update every 15 seconds to check age for despawning + if (entity.updateMode % 2 == 1) { + entity.updateMode = 1; + } + entity.scheduleUpdate(); + } } - int tickSpeed = gameRules.getInteger(GameRule.RANDOM_TICK_SPEED); - - if (tickSpeed > 0) { - if (this.useSections) { - for (ChunkSection section : ((Chunk) chunk).getSections()) { - if (!(section instanceof EmptyChunkSection)) { - int Y = section.getY(); - for (int i = 0; i < tickSpeed; ++i) { - int lcg = this.getUpdateLCG(); - int x = lcg & 0x0f; - int y = lcg >>> 8 & 0x0f; - int z = lcg >>> 16 & 0x0f; - - int fullId = section.getFullBlock(x, y, z); - int blockId = fullId >> 4; - if (randomTickBlocks[blockId]) { - Block block = Block.get(fullId, this, chunkX * 16 + x, (Y << 4) + y, chunkZ * 16 + z); - block.onUpdate(BLOCK_UPDATE_RANDOM); - } + + if (this.useSections) { + for (ChunkSection section : ((Chunk) chunk).getSections()) { + if (!(section instanceof EmptyChunkSection)) { + int Y = section.getY(); + for (int i = 0; i < gameRules.getInteger(GameRule.RANDOM_TICK_SPEED); ++i) { + int n = ThreadLocalRandom.current().nextInt(); + int x = n & 0xF; + int z = n >> 8 & 0xF; + int y = n >> 16 & 0xF; + + int fullId = section.getFullBlock(x, y, z); + int blockId = fullId >> Block.DATA_BITS; + if (blockId < randomTickBlocks.length && randomTickBlocks[blockId]) { + Block block = Block.get(fullId, this, (chunkX << 4) + x, (Y << 4) + y, (chunkZ << 4) + z); + block.onUpdate(BLOCK_UPDATE_RANDOM); } } } - } else { - for (int Y = 0; Y < 8 && (Y < 3 || blockTest != 0); ++Y) { - blockTest = 0; - for (int i = 0; i < tickSpeed; ++i) { - int lcg = this.getUpdateLCG(); - int x = lcg & 0x0f; - int y = lcg >>> 8 & 0x0f; - int z = lcg >>> 16 & 0x0f; - - int fullId = chunk.getFullBlock(x, y + (Y << 4), z); - int blockId = fullId >> 4; - blockTest |= fullId; - if (Level.randomTickBlocks[blockId]) { - Block block = Block.get(fullId, this, x, y + (Y << 4), z); - block.onUpdate(BLOCK_UPDATE_RANDOM); - } + } + } else { + for (int Y = 0; Y < 8 && (Y < 3 || blockTest != 0); ++Y) { + blockTest = 0; + for (int i = 0; i < gameRules.getInteger(GameRule.RANDOM_TICK_SPEED); ++i) { + int n = ThreadLocalRandom.current().nextInt(); + int x = n & 0xF; + int z = n >> 8 & 0xF; + int y = n >> 16 & 0xF; + + int fullId = chunk.getFullBlock(x, y + (Y << 4), z); + int blockId = fullId >> Block.DATA_BITS; + blockTest |= fullId; + if (blockId < randomTickBlocks.length && randomTickBlocks[blockId]) { + Block block = Block.get(fullId, this, x, y + (Y << 4), z); + block.onUpdate(BLOCK_UPDATE_RANDOM); } } } @@ -1190,38 +1242,44 @@ public boolean save() { } public boolean save(boolean force) { - if (!this.getAutoSave() && !force) { + if ((!this.autoSave || server.holdWorldSave) && !force) { return false; } this.server.getPluginManager().callEvent(new LevelSaveEvent(this)); - this.provider.setTime((int) this.time); - this.provider.setRaining(this.raining); - this.provider.setRainTime(this.rainTime); - this.provider.setThundering(this.thundering); - this.provider.setThunderTime(this.thunderTime); - this.provider.setCurrentTick(this.levelCurrentTick); - this.provider.setGameRules(this.gameRules); + this.saveLevelData(); this.saveChunks(); - if (this.provider instanceof BaseLevelProvider) { + return true; + } + + private void saveLevelData() { + try { + this.provider.setTime(this.time); + this.provider.setRaining(this.raining); + this.provider.setRainTime(this.rainTime); + this.provider.setThundering(this.thundering); + this.provider.setThunderTime(this.thunderTime); + this.provider.setCurrentTick(this.levelCurrentTick); + this.provider.setGameRules(this.gameRules); this.provider.saveLevelData(); + } catch (Exception ex) { + Server.getInstance().getLogger().error("Failed to save level data for " + this.getFolderName(), ex); } - - return true; } public void saveChunks() { provider.saveChunks(); } - public void updateAroundRedstone(Vector3 pos, BlockFace face) { + public void updateAroundRedstone(Vector3 pos, BlockFace ignoredFace) { for (BlockFace side : BlockFace.values()) { - if (face != null && side == face) { + if (ignoredFace != null && side == ignoredFace) { continue; } - this.getBlock(pos.getSideVec(side)).onUpdate(BLOCK_UPDATE_REDSTONE); + Vector3 sideVec = pos.getSideVec(side); + this.getBlock(sideVec).onUpdate(BLOCK_UPDATE_REDSTONE); } } @@ -1247,43 +1305,50 @@ public void updateComparatorOutputLevel(Vector3 v) { } public void updateAround(Vector3 pos) { - updateAround((int) pos.x, (int) pos.y, (int) pos.z); + this.updateAround((int) pos.x, (int) pos.y, (int) pos.z, Block.LAYER_NORMAL); + this.updateAround((int) pos.x, (int) pos.y, (int) pos.z, Block.LAYER_WATERLOGGED); } public void updateAround(int x, int y, int z) { + this.updateAround(x, y, z, Block.LAYER_NORMAL); + this.updateAround(x, y, z, Block.LAYER_WATERLOGGED); + } + + public void updateAround(int x, int y, int z, BlockLayer layer) { + Vector3 updatePos = new Vector3(x, y, z); BlockUpdateEvent ev; this.server.getPluginManager().callEvent( - ev = new BlockUpdateEvent(this.getBlock(x, y - 1, z))); + ev = new BlockUpdateEvent(this.getBlock(null, x, y - 1, z, layer, true).setUpdatePos(updatePos))); if (!ev.isCancelled()) { normalUpdateQueue.add(ev.getBlock()); } this.server.getPluginManager().callEvent( - ev = new BlockUpdateEvent(this.getBlock(x, y + 1, z))); + ev = new BlockUpdateEvent(this.getBlock(null, x, y + 1, z, layer, true).setUpdatePos(updatePos))); if (!ev.isCancelled()) { normalUpdateQueue.add(ev.getBlock()); } this.server.getPluginManager().callEvent( - ev = new BlockUpdateEvent(this.getBlock(x - 1, y, z))); + ev = new BlockUpdateEvent(this.getBlock(null, x - 1, y, z, layer, true).setUpdatePos(updatePos))); if (!ev.isCancelled()) { normalUpdateQueue.add(ev.getBlock()); } this.server.getPluginManager().callEvent( - ev = new BlockUpdateEvent(this.getBlock(x + 1, y, z))); + ev = new BlockUpdateEvent(this.getBlock(null, x + 1, y, z, layer, true).setUpdatePos(updatePos))); if (!ev.isCancelled()) { normalUpdateQueue.add(ev.getBlock()); } this.server.getPluginManager().callEvent( - ev = new BlockUpdateEvent(this.getBlock(x, y, z - 1))); + ev = new BlockUpdateEvent(this.getBlock(null, x, y, z - 1, layer, true).setUpdatePos(updatePos))); if (!ev.isCancelled()) { normalUpdateQueue.add(ev.getBlock()); } this.server.getPluginManager().callEvent( - ev = new BlockUpdateEvent(this.getBlock(x, y, z + 1))); + ev = new BlockUpdateEvent(this.getBlock(null, x, y, z + 1, layer, true).setUpdatePos(updatePos))); if (!ev.isCancelled()) { normalUpdateQueue.add(ev.getBlock()); } @@ -1302,11 +1367,11 @@ public void scheduleUpdate(Block block, Vector3 pos, int delay, int priority) { } public void scheduleUpdate(Block block, Vector3 pos, int delay, int priority, boolean checkArea) { - if (block.getId() == 0 || (checkArea && !this.isChunkLoaded(block.getFloorX() >> 4, block.getFloorZ() >> 4))) { + if (block.getId() == 0 || (checkArea && !this.isChunkLoaded(block.getChunkX(), block.getChunkZ()))) { return; } - BlockUpdateEntry entry = new BlockUpdateEntry(pos.floor(), block, ((long) delay) + getCurrentTick(), priority); + BlockUpdateEntry entry = new BlockUpdateEntry(pos.floor(), block, ((long) delay) + levelCurrentTick, priority); if (!this.updateQueue.contains(entry)) { this.updateQueue.add(entry); @@ -1327,11 +1392,11 @@ public boolean isBlockTickPending(Vector3 pos, Block block) { public Set getPendingBlockUpdates(FullChunk chunk) { int minX = (chunk.getX() << 4) - 2; - int maxX = minX + 16 + 2; + int maxX = minX + 18; int minZ = (chunk.getZ() << 4) - 2; - int maxZ = minZ + 16 + 2; + int maxZ = minZ + 18; - return this.getPendingBlockUpdates(new SimpleAxisAlignedBB(minX, 0, minZ, maxX, 256, maxZ)); + return this.getPendingBlockUpdates(new SimpleAxisAlignedBB(minX, this.getMinBlockY(), minZ, maxX, this.getMaxBlockY(), maxZ)); } public Set getPendingBlockUpdates(AxisAlignedBB boundingBox) { @@ -1343,6 +1408,10 @@ public Block[] getCollisionBlocks(AxisAlignedBB bb) { } public Block[] getCollisionBlocks(AxisAlignedBB bb, boolean targetFirst) { + return getCollisionBlocks(null, bb, targetFirst); + } + + public Block[] getCollisionBlocks(Entity entity, AxisAlignedBB bb, boolean targetFirst) { int minX = NukkitMath.floorDouble(bb.getMinX()); int minY = NukkitMath.floorDouble(bb.getMinY()); int minZ = NukkitMath.floorDouble(bb.getMinZ()); @@ -1356,7 +1425,7 @@ public Block[] getCollisionBlocks(AxisAlignedBB bb, boolean targetFirst) { for (int z = minZ; z <= maxZ; ++z) { for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { - Block block = this.getBlock(this.temporalVector.setComponents(x, y, z), false); + Block block = this.getBlock(entity == null ? null : entity.chunk, x, y, z, false); if (block != null && block.getId() != 0 && block.collidesWithBB(bb)) { return new Block[]{block}; } @@ -1367,7 +1436,7 @@ public Block[] getCollisionBlocks(AxisAlignedBB bb, boolean targetFirst) { for (int z = minZ; z <= maxZ; ++z) { for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { - Block block = this.getBlock(this.temporalVector.setComponents(x, y, z), false); + Block block = this.getBlock(entity == null ? null : entity.chunk, x, y, z, false); if (block != null && block.getId() != 0 && block.collidesWithBB(bb)) { collides.add(block); } @@ -1379,6 +1448,28 @@ public Block[] getCollisionBlocks(AxisAlignedBB bb, boolean targetFirst) { return collides.toArray(new Block[0]); } + public boolean hasCollisionBlocks(Entity entity, AxisAlignedBB bb) { + int minX = NukkitMath.floorDouble(bb.getMinX()); + int minY = NukkitMath.floorDouble(bb.getMinY()); + int minZ = NukkitMath.floorDouble(bb.getMinZ()); + int maxX = NukkitMath.ceilDouble(bb.getMaxX()); + int maxY = NukkitMath.ceilDouble(bb.getMaxY()); + int maxZ = NukkitMath.ceilDouble(bb.getMaxZ()); + + for (int z = minZ; z <= maxZ; ++z) { + for (int x = minX; x <= maxX; ++x) { + for (int y = minY; y <= maxY; ++y) { + Block block = this.getBlock(entity.chunk, x, y, z, false); + if (block != null && block.getId() != 0 && block.collidesWithBB(bb)) { + return true; + } + } + } + } + + return false; + } + public boolean isFullBlock(Vector3 pos) { AxisAlignedBB bb; if (pos instanceof Block) { @@ -1402,6 +1493,8 @@ public AxisAlignedBB[] getCollisionCubes(Entity entity, AxisAlignedBB bb, boolea } public AxisAlignedBB[] getCollisionCubes(Entity entity, AxisAlignedBB bb, boolean entities, boolean solidEntities) { + if (entity.noClip) return new AxisAlignedBB[0]; + int minX = NukkitMath.floorDouble(bb.getMinX()); int minY = NukkitMath.floorDouble(bb.getMinY()); int minZ = NukkitMath.floorDouble(bb.getMinZ()); @@ -1414,7 +1507,7 @@ public AxisAlignedBB[] getCollisionCubes(Entity entity, AxisAlignedBB bb, boolea for (int z = minZ; z <= maxZ; ++z) { for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { - Block block = this.getBlock(this.temporalVector.setComponents(x, y, z), false); + Block block = this.getBlock(entity.chunk, x, y, z, false); if (!block.canPassThrough() && block.collidesWithBB(bb)) { collides.add(block.getBoundingBox()); } @@ -1444,7 +1537,7 @@ public boolean hasCollision(Entity entity, AxisAlignedBB bb, boolean entities) { for (int z = minZ; z <= maxZ; ++z) { for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { - Block block = this.getBlock(this.temporalVector.setComponents(x, y, z)); + Block block = this.getBlock(entity.chunk, x, y, z, false); if (!block.canPassThrough() && block.collidesWithBB(bb)) { return true; } @@ -1459,15 +1552,18 @@ public boolean hasCollision(Entity entity, AxisAlignedBB bb, boolean entities) { } public int getFullLight(Vector3 pos) { - FullChunk chunk = this.getChunk((int) pos.x >> 4, (int) pos.z >> 4, false); + if (pos.y < this.getMinBlockY() || pos.y > this.getMaxBlockY()) { + return 0; + } + + FullChunk chunk = this.getChunk(pos.getChunkX(), pos.getChunkZ(), false); int level = 0; if (chunk != null) { - level = chunk.getBlockSkyLight((int) pos.x & 0x0f, (int) pos.y & 0xff, (int) pos.z & 0x0f); + level = chunk.getBlockSkyLight((int) pos.x & 0x0f, (int) pos.y, (int) pos.z & 0x0f); level -= this.skyLightSubtracted; if (level < 15) { - level = Math.max(chunk.getBlockLight((int) pos.x & 0x0f, (int) pos.y & 0xff, (int) pos.z & 0x0f), - level); + level = Math.max(chunk.getBlockLight((int) pos.x & 0x0f, (int) pos.y, (int) pos.z & 0x0f), level); } } @@ -1475,12 +1571,11 @@ public int getFullLight(Vector3 pos) { } public int calculateSkylightSubtracted(float tickDiff) { - float angle = this.calculateCelestialAngle(getTime(), tickDiff); - float light = 1 - (MathHelper.cos(angle * ((float) Math.PI * 2F)) * 2 + 0.5f); + float light = 1 - (MathHelper.cos(this.calculateCelestialAngle(getTime(), tickDiff) * (6.2831855f)) * 2 + 0.5f); light = light < 0 ? 0 : light > 1 ? 1 : light; light = 1 - light; - light = (float) ((double) light * ((isRaining() ? 1 : 0) - (double) 5f / 16d)); - light = (float) ((double) light * ((isThundering() ? 1 : 0) - (double) 5f / 16d)); + light = (float) ((double) light * ((raining ? 1 : 0) - 0.3125)); + light = (float) ((double) light * ((isThundering() ? 1 : 0) - 0.3125)); light = 1 - light; return (int) (light * 11f); } @@ -1506,97 +1601,151 @@ public int getMoonPhase(long worldTime) { } public int getFullBlock(int x, int y, int z) { - return this.getChunk(x >> 4, z >> 4, false).getFullBlock(x & 0x0f, y & 0xff, z & 0x0f); + return this.getFullBlock(null, x, y, z); + } + + public int getFullBlock(FullChunk chunk, int x, int y, int z) { + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) return 0; + int cx = x >> 4; + int cz = z >> 4; + if (chunk == null || cx != chunk.getX() || cz != chunk.getZ()) { + chunk = this.getChunk(cx, cz, false); + } + if (chunk == null) { + return 0; + } + return chunk.getFullBlock(x & 0x0f, y, z & 0x0f, Block.LAYER_NORMAL); + } + + public synchronized Block getBlock(Vector3 pos) { // Original API + return this.getBlock(null, pos.getFloorX(), pos.getFloorY(), pos.getFloorZ(), Block.LAYER_NORMAL, true); } - public synchronized Block getBlock(Vector3 pos) { - return this.getBlock(pos.getFloorX(), pos.getFloorY(), pos.getFloorZ()); + public synchronized Block getBlock(Vector3 pos, boolean load) { // Original API + return this.getBlock(null, pos.getFloorX(), pos.getFloorY(), pos.getFloorZ(), Block.LAYER_NORMAL, load); } - public synchronized Block getBlock(Vector3 pos, boolean load) { - return this.getBlock(pos.getFloorX(), pos.getFloorY(), pos.getFloorZ(), load); + public synchronized Block getBlock(Vector3 pos, BlockLayer layer, boolean load) { + return this.getBlock(null, pos.getFloorX(), pos.getFloorY(), pos.getFloorZ(), layer, load); } - public synchronized Block getBlock(int x, int y, int z) { - return getBlock(x, y, z, true); + public synchronized Block getBlock(int x, int y, int z) { // Original API + return getBlock(null, x, y, z, Block.LAYER_NORMAL, true); } - public synchronized Block getBlock(int x, int y, int z, boolean load) { + public synchronized Block getBlock(int x, int y, int z, boolean load) { // Original API + return this.getBlock(null, x, y, z, Block.LAYER_NORMAL, load); + } + + public synchronized Block getBlock(FullChunk chunk, int x, int y, int z, boolean load) { + return this.getBlock(chunk, x, y, z, Block.LAYER_NORMAL, load); + } + + // The chunk doesn't have to be correct, give the most likely one + public synchronized Block getBlock(FullChunk chunk, int x, int y, int z, BlockLayer layer, boolean load) { int fullState; - if (y >= 0 && y < 256) { + if (y >= this.getMinBlockY() && y <= this.getMaxBlockY()) { int cx = x >> 4; int cz = z >> 4; - BaseFullChunk chunk; - if (load) { - chunk = getChunk(cx, cz); + if (chunk == null || cx != chunk.getX() || cz != chunk.getZ()) { + if (load) { + chunk = getChunk(cx, cz); + } else { + chunk = getChunkIfLoaded(cx, cz); + } + } + if (chunk == null) { + fullState = 0; } else { + fullState = chunk.getFullBlock(x & 0xF, y, z & 0xF, layer); + } + } else { + fullState = 0; + } + + Block block = Block.fullList[fullState].clone(); + + block.x = x; + block.y = y; + block.z = z; + block.level = this; + block.setLayer(layer); + return block; + } + + // Use only if getting correct block is not critical + private Block getBlockAsyncIfLoaded(FullChunk chunk, int x, int y, int z, BlockLayer layer) { + int fullState; + if (y >= this.getMinBlockY() && y <= this.getMaxBlockY()) { + int cx = x >> 4; + int cz = z >> 4; + if (chunk == null || cx != chunk.getX() || cz != chunk.getZ()) { chunk = getChunkIfLoaded(cx, cz); } - if (chunk != null) { - fullState = chunk.getFullBlock(x & 0xF, y, z & 0xF); - } else { + if (chunk == null) { fullState = 0; + } else { + fullState = chunk.getFullBlock(x & 0xF, y, z & 0xF, layer); } } else { fullState = 0; } - Block block = Block.fullList[fullState & 0xFFF].clone(); + + Block block = Block.fullList[fullState].clone(); + block.x = x; block.y = y; block.z = z; block.level = this; + block.setLayer(layer); return block; } + public void updateAllLight(Vector3 pos) { this.updateBlockSkyLight((int) pos.x, (int) pos.y, (int) pos.z); this.addLightUpdate((int) pos.x, (int) pos.y, (int) pos.z); } public void updateBlockSkyLight(int x, int y, int z) { - // todo } - public void updateBlockLight(Map> map) { + private void updateBlockLight(Map> map) { int size = map.size(); if (size == 0) { return; } Queue lightPropagationQueue = new ConcurrentLinkedQueue<>(); Queue lightRemovalQueue = new ConcurrentLinkedQueue<>(); - Long2ObjectOpenHashMap visited = new Long2ObjectOpenHashMap<>(); - Long2ObjectOpenHashMap removalVisited = new Long2ObjectOpenHashMap<>(); + LongOpenHashSet visited = new LongOpenHashSet(); + LongOpenHashSet removalVisited = new LongOpenHashSet(); - Iterator>> iter = map.entrySet().iterator(); + Iterator>> iter = map.entrySet().iterator(); while (iter.hasNext() && size-- > 0) { - Map.Entry> entry = iter.next(); + Map.Entry> entry = iter.next(); iter.remove(); long index = entry.getKey(); - Map blocks = entry.getValue(); - int chunkX = Level.getHashX(index); - int chunkZ = Level.getHashZ(index); - int bx = chunkX << 4; - int bz = chunkZ << 4; - for (char blockHash : blocks.keySet()) { - int hi = (byte) (blockHash >>> 8); - int lo = (byte) blockHash; - int y = lo & 0xFF; - int x = (hi & 0xF) + bx; - int z = ((hi >> 4) & 0xF) + bz; - BaseFullChunk chunk = getChunk(x >> 4, z >> 4, false); + Set blocks = entry.getValue(); + + for (int blockHash : blocks) { + Vector3 pos = getBlockXYZ(index, blockHash, this.getDimensionData()); + BaseFullChunk chunk = getChunk(((int) pos.x) >> 4, ((int) pos.z) >> 4, false); + if (chunk != null) { - int lcx = x & 0xF; - int lcz = z & 0xF; - int oldLevel = chunk.getBlockLight(lcx, y, lcz); - int newLevel = Block.light[chunk.getBlockId(lcx, y, lcz)]; + int lcx = ((int) pos.x) & 0xF; + int lcz = ((int) pos.z) & 0xF; + int oldLevel = chunk.getBlockLight(lcx, ((int) pos.y), lcz); + int newLevel = Block.getBlockLight(chunk.getBlockId(lcx, ((int) pos.y), lcz)); if (oldLevel != newLevel) { - this.setBlockLightAt(x, y, z, newLevel); + this.setBlockLightAt(((int) pos.x), ((int) pos.y), ((int) pos.z), newLevel); + + long hash = Hash.hashBlock(((int) pos.x), ((int) pos.y), ((int) pos.z)); if (newLevel < oldLevel) { - removalVisited.put(Hash.hashBlock(x, y, z), changeBlocksPresent); - lightRemovalQueue.add(new Object[]{Hash.hashBlock(x, y, z), oldLevel}); + removalVisited.add(hash); + lightRemovalQueue.add(new Object[]{hash, oldLevel}); } else { - visited.put(Hash.hashBlock(x, y, z), changeBlocksPresent); - lightPropagationQueue.add(Hash.hashBlock(x, y, z)); + visited.add(hash); + lightPropagationQueue.add(hash); } } } @@ -1612,18 +1761,12 @@ public void updateBlockLight(Map> map) { int lightLevel = (int) val[1]; - this.computeRemoveBlockLight(x - 1, y, z, lightLevel, lightRemovalQueue, lightPropagationQueue, - removalVisited, visited); - this.computeRemoveBlockLight(x + 1, y, z, lightLevel, lightRemovalQueue, lightPropagationQueue, - removalVisited, visited); - this.computeRemoveBlockLight(x, y - 1, z, lightLevel, lightRemovalQueue, lightPropagationQueue, - removalVisited, visited); - this.computeRemoveBlockLight(x, y + 1, z, lightLevel, lightRemovalQueue, lightPropagationQueue, - removalVisited, visited); - this.computeRemoveBlockLight(x, y, z - 1, lightLevel, lightRemovalQueue, lightPropagationQueue, - removalVisited, visited); - this.computeRemoveBlockLight(x, y, z + 1, lightLevel, lightRemovalQueue, lightPropagationQueue, - removalVisited, visited); + this.computeRemoveBlockLight(x - 1, y, z, lightLevel, lightRemovalQueue, lightPropagationQueue, removalVisited, visited); + this.computeRemoveBlockLight(x + 1, y, z, lightLevel, lightRemovalQueue, lightPropagationQueue, removalVisited, visited); + this.computeRemoveBlockLight(x, y - 1, z, lightLevel, lightRemovalQueue, lightPropagationQueue, removalVisited, visited); + this.computeRemoveBlockLight(x, y + 1, z, lightLevel, lightRemovalQueue, lightPropagationQueue, removalVisited, visited); + this.computeRemoveBlockLight(x, y, z - 1, lightLevel, lightRemovalQueue, lightPropagationQueue, removalVisited, visited); + this.computeRemoveBlockLight(x, y, z + 1, lightLevel, lightRemovalQueue, lightPropagationQueue, removalVisited, visited); } while (!lightPropagationQueue.isEmpty()) { @@ -1634,7 +1777,7 @@ public void updateBlockLight(Map> map) { int z = Hash.hashBlockZ(node); int lightLevel = this.getBlockLightAt(x, y, z) - - Block.lightFilter[this.getBlockIdAt(x, y, z)]; + - Block.getBlockLightFilter(this.getBlockIdAt(x, y, z)); if (lightLevel >= 1) { this.computeSpreadBlockLight(x - 1, y, z, lightLevel, lightPropagationQueue, visited); @@ -1648,112 +1791,136 @@ public void updateBlockLight(Map> map) { } private void computeRemoveBlockLight(int x, int y, int z, int currentLight, Queue queue, - Queue spreadQueue, Map visited, Map spreadVisited) { + Queue spreadQueue, Set visited, Set spreadVisited) { int current = this.getBlockLightAt(x, y, z); - long index = Hash.hashBlock(x, y, z); if (current != 0 && current < currentLight) { this.setBlockLightAt(x, y, z, 0); if (current > 1) { - if (!visited.containsKey(index)) { - visited.put(index, changeBlocksPresent); - queue.add(new Object[]{Hash.hashBlock(x, y, z), current}); + long index = Hash.hashBlock(x, y, z); + if (!visited.contains(index)) { + visited.add(index); + queue.add(new Object[]{index, current}); } } } else if (current >= currentLight) { - if (!spreadVisited.containsKey(index)) { - spreadVisited.put(index, changeBlocksPresent); - spreadQueue.add(Hash.hashBlock(x, y, z)); + long index = Hash.hashBlock(x, y, z); + if (!spreadVisited.contains(index)) { + spreadVisited.add(index); + spreadQueue.add(index); } } } - private void computeSpreadBlockLight(int x, int y, int z, int currentLight, Queue queue, - Map visited) { + private void computeSpreadBlockLight(int x, int y, int z, int currentLight, Queue queue, Set visited) { int current = this.getBlockLightAt(x, y, z); - long index = Hash.hashBlock(x, y, z); - if (current < currentLight - 1) { this.setBlockLightAt(x, y, z, currentLight); - if (!visited.containsKey(index)) { - visited.put(index, changeBlocksPresent); + long index = Hash.hashBlock(x, y, z); + if (!visited.contains(index)) { + visited.add(index); if (currentLight > 1) { - queue.add(Hash.hashBlock(x, y, z)); + queue.add(index); } } } } - private Map> lightQueue = new ConcurrentHashMap<>(8, 0.9f, 1); - public void addLightUpdate(int x, int y, int z) { long index = chunkHash(x >> 4, z >> 4); - Map currentMap = lightQueue.get(index); - if (currentMap == null) { - currentMap = new ConcurrentHashMap<>(8, 0.9f, 1); - this.lightQueue.put(index, currentMap); - } - currentMap.put(Level.localBlockHash(x, y, z), changeBlocksPresent); + Set currentMap = this.lightQueue.computeIfAbsent(index, k -> ConcurrentHashMap.newKeySet(8)); + currentMap.add(Level.localBlockHash(x, y, z, this.getDimensionData())); } @Override public synchronized void setBlockFullIdAt(int x, int y, int z, int fullId) { - setBlock(x, y, z, Block.fullList[fullId], false, false); + this.setBlockFullIdAt(x, y, z, Block.LAYER_NORMAL, fullId); + } + + @Override + public synchronized void setBlockFullIdAt(int x, int y, int z, BlockLayer layer, int fullId) { + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return; + } + + Block block = Block.fullList[fullId]; + + this.setBlock(x, y, z, layer, block, false, false); + } + + public synchronized boolean setBlock(Vector3 pos, Block block) { // Original API + return this.setBlock(pos, Block.LAYER_NORMAL, block, false, true); + } + + public synchronized boolean setBlock(Vector3 pos, Block block, boolean direct) { // Original API + return this.setBlock(pos, Block.LAYER_NORMAL, block, direct, true); + } + + public synchronized boolean setBlock(Vector3 pos, Block block, boolean direct, boolean update) { // Original API + return this.setBlock(pos, Block.LAYER_NORMAL, block, direct, update); } - public synchronized boolean setBlock(Vector3 pos, Block block) { - return this.setBlock(pos, block, false); + public synchronized boolean setBlock(Vector3 pos, BlockLayer layer, Block block, boolean direct, boolean update) { + return this.setBlock(pos.getFloorX(), pos.getFloorY(), pos.getFloorZ(), layer, block, direct, update); } - public synchronized boolean setBlock(Vector3 pos, Block block, boolean direct) { - return this.setBlock(pos, block, direct, true); + public synchronized boolean setBlock(int x, int y, int z, Block block, boolean direct, boolean update) { // Original API + return this.setBlock(x, y, z, Block.LAYER_NORMAL, block, direct, update); } - public synchronized boolean setBlock(Vector3 pos, Block block, boolean direct, boolean update) { - return setBlock(pos.getFloorX(), pos.getFloorY(), pos.getFloorZ(), block, direct, update); + public synchronized boolean setBlock(int x, int y, int z, BlockLayer layer, Block block, boolean direct, boolean update) { + return this.setBlock(x, y, z, layer, block, direct, update, true); } - public synchronized boolean setBlock(int x, int y, int z, Block block, boolean direct, boolean update) { - if (y < 0 || y >= 256) { + public synchronized boolean setBlock(int x, int y, int z, BlockLayer layer, Block block, boolean direct, boolean update, boolean send) { + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { return false; } - BaseFullChunk chunk = this.getChunk(x >> 4, z >> 4, true); + + int cx = x >> 4; + int cz = z >> 4; + BaseFullChunk chunk = this.getChunk(cx, cz, true); Block blockPrevious; -// synchronized (chunk) { - blockPrevious = chunk.getAndSetBlock(x & 0xF, y, z & 0xF, block); + blockPrevious = chunk.getAndSetBlock(x & 0xF, y, z & 0xF, layer, block); if (blockPrevious.getFullId() == block.getFullId()) { return false; } -// } + block.x = x; block.y = y; block.z = z; block.level = this; - int cx = x >> 4; - int cz = z >> 4; - long index = Level.chunkHash(cx, cz); - if (direct) { - this.sendBlocks(this.getChunkPlayers(cx, cz).values().toArray(new Player[0]), new Block[]{block}, UpdateBlockPacket.FLAG_ALL_PRIORITY); - this.sendBlocks(this.getChunkPlayers(cx, cz).values().toArray(new Player[0]), new Block[]{Block.get(Block.AIR, 0, block)}, UpdateBlockPacket.FLAG_ALL_PRIORITY, 1); - } else { - addBlockChange(index, x, y, z); + block.setLayer(layer); + + if (send) { + if (direct) { + this.sendBlocks(this.getChunkPlayers(cx, cz).values().toArray(new Player[0]), new Block[]{block}, UpdateBlockPacket.FLAG_ALL_PRIORITY, layer); + } else { + addBlockChange(Level.chunkHash(cx, cz), x, y, z); + } } - for (ChunkLoader loader : this.getChunkLoaders(cx, cz)) { - loader.onBlockChanged(block); + if (this.useChunkLoaderApi) { + for (ChunkLoader loader : this.getChunkLoaders(cx, cz)) { + loader.onBlockChanged(block); + } } + if (update) { - if (blockPrevious.isTransparent() != block.isTransparent() || blockPrevious.getLightLevel() != block.getLightLevel()) { + if (this.lightUpdatesEnabled && (blockPrevious.isTransparent() != block.isTransparent() || blockPrevious.getLightLevel() != block.getLightLevel())) { addLightUpdate(x, y, z); } BlockUpdateEvent ev = new BlockUpdateEvent(block); this.server.getPluginManager().callEvent(ev); if (!ev.isCancelled()) { - for (Entity entity : this.getNearbyEntities(new SimpleAxisAlignedBB(x - 1, y - 1, z - 1, x + 1, y + 1, z + 1))) { + for (Entity entity : this.getNearbyEntities(new SimpleAxisAlignedBB(x - 1, y - 1, z - 1, x + 1.1, y + 1.1, z + 1.1))) { + if (entity.updateMode % 2 == 1) { + entity.updateMode = 1; + } entity.scheduleUpdate(); } block = ev.getBlock(); - block.onUpdate(BLOCK_UPDATE_NORMAL); + if (!(block instanceof BlockObserver)) block.onUpdate(BLOCK_UPDATE_NORMAL); this.updateAround(x, y, z); } } @@ -1767,54 +1934,35 @@ private void addBlockChange(int x, int y, int z) { private void addBlockChange(long index, int x, int y, int z) { synchronized (changedBlocks) { - SoftReference> current = changedBlocks.computeIfAbsent(index, k -> new SoftReference<>(new HashMap<>())); - Map currentMap = current.get(); + SoftReference> current = changedBlocks.computeIfAbsent(index, k -> new SoftReference<>(new HashMap<>())); + Map currentMap = current.get(); if (currentMap != changeBlocksFullMap && currentMap != null) { if (currentMap.size() > MAX_BLOCK_CACHE) { this.changedBlocks.put(index, new SoftReference<>(changeBlocksFullMap)); } else { - currentMap.put(Level.localBlockHash(x, y, z), changeBlocksPresent); + currentMap.put(Level.localBlockHash(x, y, z, this.getDimensionData()), changeBlocksPresent); } } } } public void dropItem(Vector3 source, Item item) { - this.dropItem(source, item, null); + this.dropAndGetItem(source, item); } public void dropItem(Vector3 source, Item item, Vector3 motion) { - this.dropItem(source, item, motion, 10); + this.dropAndGetItem(source, item, motion); } public void dropItem(Vector3 source, Item item, Vector3 motion, int delay) { - this.dropItem(source, item, motion, false, delay); + this.dropAndGetItem(source, item, motion, delay); } public void dropItem(Vector3 source, Item item, Vector3 motion, boolean dropAround, int delay) { - if (motion == null) { - if (dropAround) { - float f = ThreadLocalRandom.current().nextFloat() * 0.5f; - float f1 = ThreadLocalRandom.current().nextFloat() * ((float) Math.PI * 2); - - motion = new Vector3(-MathHelper.sin(f1) * f, 0.20000000298023224, MathHelper.cos(f1) * f); - } else { - motion = new Vector3(new java.util.Random().nextDouble() * 0.2 - 0.1, 0.2, - new java.util.Random().nextDouble() * 0.2 - 0.1); - } - } - - if (item.getId() > 0 && item.getCount() > 0) { - EntityItem itemEntity = (EntityItem) Entity.createEntity("Item", - this.getChunk((int) source.getX() >> 4, (int) source.getZ() >> 4, true), - Entity.getDefaultNBT(source, motion, new Random().nextFloat() * 360, 0).putShort("Health", 5).putCompound("Item", NBTIO.putItemHelper(item)).putShort("PickupDelay", delay)); - - if (itemEntity != null) { - itemEntity.spawnToAll(); - } - } + this.dropAndGetItem(source, item, motion, dropAround, delay); } + @SuppressWarnings("UnusedReturnValue") public EntityItem dropAndGetItem(Vector3 source, Item item) { return this.dropAndGetItem(source, item, null); } @@ -1828,44 +1976,40 @@ public EntityItem dropAndGetItem(Vector3 source, Item item, Vector3 motion, int } public EntityItem dropAndGetItem(Vector3 source, Item item, Vector3 motion, boolean dropAround, int delay) { - EntityItem itemEntity = null; - - if (motion == null) { - if (dropAround) { - float f = ThreadLocalRandom.current().nextFloat() * 0.5f; - float f1 = ThreadLocalRandom.current().nextFloat() * ((float) Math.PI * 2); + if (item.getId() != 0 && item.getCount() > 0) { + if (motion == null) { + if (dropAround) { + float f = ThreadLocalRandom.current().nextFloat() * 0.5f; + float f1 = ThreadLocalRandom.current().nextFloat() * 6.2831855f; - motion = new Vector3(-MathHelper.sin(f1) * f, 0.20000000298023224, MathHelper.cos(f1) * f); - } else { - motion = new Vector3(new java.util.Random().nextDouble() * 0.2 - 0.1, 0.2, - new java.util.Random().nextDouble() * 0.2 - 0.1); + motion = new Vector3(-MathHelper.sin(f1) * f, 0.20000000298023224, MathHelper.cos(f1) * f); + } else { + motion = new Vector3(Utils.random.nextDouble() * 0.2 - 0.1, 0.2, Utils.random.nextDouble() * 0.2 - 0.1); + } } - } - CompoundTag itemTag = NBTIO.putItemHelper(item); - itemTag.setName("Item"); + CompoundTag itemTag = NBTIO.putItemHelper(item); + itemTag.setName("Item"); - if (item.getId() > 0 && item.getCount() > 0) { - itemEntity = (EntityItem) Entity.createEntity("Item", - this.getChunk((int) source.getX() >> 4, (int) source.getZ() >> 4, true), + EntityItem itemEntity = (EntityItem) Entity.createEntity(EntityItem.NETWORK_ID, + this.getChunk(source.getChunkX(), source.getChunkZ(), true), new CompoundTag().putList(new ListTag("Pos").add(new DoubleTag("", source.getX())) - .add(new DoubleTag("", source.getY())).add(new DoubleTag("", source.getZ()))) + .add(new DoubleTag("", source.getY())).add(new DoubleTag("", source.getZ()))) .putList(new ListTag("Motion").add(new DoubleTag("", motion.x)) .add(new DoubleTag("", motion.y)).add(new DoubleTag("", motion.z))) .putList(new ListTag("Rotation") - .add(new FloatTag("", new Random().nextFloat() * 360)) + .add(new FloatTag("", ThreadLocalRandom.current().nextFloat() * 360)) .add(new FloatTag("", 0))) .putShort("Health", 5).putCompound("Item", itemTag).putShort("PickupDelay", delay)); - if (itemEntity != null) { - itemEntity.spawnToAll(); - } + itemEntity.spawnToAll(); + return itemEntity; } - return itemEntity; + return null; } public Item useBreakOn(Vector3 vector) { @@ -1885,7 +2029,7 @@ public Item useBreakOn(Vector3 vector, Item item, Player player, boolean createP } public Item useBreakOn(Vector3 vector, BlockFace face, Item item, Player player, boolean createParticles) { - if (player != null && player.getGamemode() > 2) { + if (player != null && player.getGamemode() > Player.ADVENTURE) { return null; } Block target = this.getBlock(vector); @@ -1896,17 +2040,18 @@ public Item useBreakOn(Vector3 vector, BlockFace face, Item item, Player player, item = new ItemBlock(Block.get(BlockID.AIR), 0, 0); } - boolean isSilkTouch = item.getEnchantment(Enchantment.ID_SILK_TOUCH) != null; + Vector3 dropPosition = vector; + boolean isSilkTouch = item.isTool() && item.hasEnchantment(Enchantment.ID_SILK_TOUCH); if (player != null) { - if (player.getGamemode() == 2) { + if (player.getGamemode() == Player.ADVENTURE) { Tag tag = item.getNamedTagEntry("CanDestroy"); boolean canBreak = false; if (tag instanceof ListTag) { for (Tag v : ((ListTag) tag).getAll()) { if (v instanceof StringTag) { Item entry = Item.fromString(((StringTag) v).data); - if (entry.getId() > 0 && entry.getBlockUnsafe() != null && entry.getBlockUnsafe().getId() == target.getId()) { + if (entry.getId() != 0 && entry.getBlockUnsafe() != null && entry.getBlockUnsafe().getId() == target.getId()) { canBreak = true; break; } @@ -1918,10 +2063,24 @@ public Item useBreakOn(Vector3 vector, BlockFace face, Item item, Player player, } } + Item[] eventDrops; + if (!player.isSurvival()) { + if (target instanceof BlockShulkerBox && this.gameRules.getBoolean(GameRule.DO_TILE_DROPS)) { + eventDrops = target.getDrops(item); + + if (eventDrops.length != 0 && !eventDrops[0].hasCompoundTag()) { + eventDrops = new Item[0]; + } + } else { + eventDrops = new Item[0]; + } + } else if (isSilkTouch && target.canSilkTouch()) { + eventDrops = new Item[]{target.toItem()}; + } else { + eventDrops = target.getDrops(item); + } + double breakTime = target.getBreakTime(item, player); - // this in - // block - // class if (player.isCreative() && breakTime > 0.15) { breakTime = 0.15; @@ -1943,85 +2102,109 @@ public Item useBreakOn(Vector3 vector, BlockFace face, Item item, Player player, breakTime -= 0.15; - Item[] eventDrops; - if (!player.isSurvival()) { - eventDrops = new Item[0]; - } else if (isSilkTouch && target.canSilkTouch()) { - eventDrops = new Item[]{target.toItem()}; - } else { - eventDrops = target.getDrops(item); - } + long now = System.currentTimeMillis(); BlockBreakEvent ev = new BlockBreakEvent(player, target, face, item, eventDrops, player.isCreative(), - (player.lastBreak + breakTime * 1000) > System.currentTimeMillis()); - - if (player.isSurvival() && !target.isBreakable(item)) { - ev.setCancelled(); - } else if(!player.isOp() && isInSpawnRadius(target)) { - ev.setCancelled(); + (player.lastBreak + breakTime * 1000) > now, vector); + + if (!player.isCreative() && (!player.isBreakingBlock() || !target.equals(player.breakingBlock))) { + ev.setCancelled(true); + } else if ((player.isSurvival() || player.isAdventure()) && !target.isBreakable(item)) { + ev.setCancelled(true); + } else if (!player.isOp() && isInSpawnRadius(target)) { + ev.setCancelled(true); } else if (!ev.getInstaBreak() && ev.isFastBreak()) { - ev.setCancelled(); + ev.setCancelled(true); } + player.lastBreak = now; + this.server.getPluginManager().callEvent(ev); if (ev.isCancelled()) { return null; } - player.lastBreak = System.currentTimeMillis(); + if (target instanceof BlockBed) { + // Drops only from the top part, prevent a dupe + if ((target.getDamage() & 0x08) == 0x08) { + drops = ev.getDrops(); + } else { + drops = new Item[0]; + } + // Make sure no item is dropped if drops are cleared in BlockBreakEvent + ((BlockBed) target).canDropItem = ev.getDrops().length != 0; + } else { + drops = ev.getDrops(); + } - drops = ev.getDrops(); dropExp = ev.getDropExp(); + + if (ev.getDropPosition() != null) { + dropPosition = ev.getDropPosition(); + } } else if (!target.isBreakable(item)) { return null; - } else if (item.getEnchantment(Enchantment.ID_SILK_TOUCH) != null) { + } else if (item.hasEnchantment(Enchantment.ID_SILK_TOUCH)) { drops = new Item[]{target.toItem()}; } else { drops = target.getDrops(item); } - Block above = this.getBlock(new Vector3(target.x, target.y + 1, target.z)); - if (above != null) { - if (above.getId() == Item.FIRE) { - this.setBlock(above, Block.get(BlockID.AIR), true); - } + Vector3 above = new Vector3(target.x, target.y + 1, target.z); + int bid = this.getBlockIdAt((int) above.x, (int) above.y, (int) above.z); + if (bid == Item.FIRE || bid == Item.SOUL_FIRE) { + this.setBlock(above, Block.get(BlockID.AIR), true); } if (createParticles) { this.addParticle(new DestroyBlockParticle(target.add(0.5), target)); - - if (player != null) { - players.remove(player.getLoaderId()); - } } - // Close BlockEntity before we check onBreak BlockEntity blockEntity = this.getBlockEntity(target); if (blockEntity != null) { + // Let client close the inventory for viewers, fixes refusing to open inventories afterward + if (blockEntity instanceof InventoryHolder) { + Inventory inventory = ((InventoryHolder) blockEntity).getInventory(); + if (inventory != null && !inventory.getViewers().isEmpty()) { + inventory.getViewers().clear(); + } + } + blockEntity.onBreak(); blockEntity.close(); this.updateComparatorOutputLevel(target); } - target.onBreak(item); + Block waterlogged = target.getWaterloggingType() != Block.WaterloggingType.NO_WATERLOGGING ? target.getLevelBlock(Block.LAYER_WATERLOGGED) : null; + + target.onBreak(item, player); + + if (waterlogged instanceof BlockLiquid) { + this.setBlock(target, Block.LAYER_WATERLOGGED, Block.get(Block.AIR), false, true); + this.setBlock(target, Block.LAYER_NORMAL, waterlogged, false, true); + this.scheduleUpdate(waterlogged, 1); + } item.useOn(target); if (item.isTool() && item.getDamage() >= item.getMaxDurability()) { + this.addSound(target, cn.nukkit.level.Sound.RANDOM_BREAK); + this.addParticle(new ItemBreakParticle(target, item)); item = new ItemBlock(Block.get(BlockID.AIR), 0, 0); } if (this.gameRules.getBoolean(GameRule.DO_TILE_DROPS)) { - - if (!isSilkTouch && player != null && player.isSurvival() && dropExp > 0 && drops.length != 0) { - this.dropExpOrb(vector.add(0.5, 0.5, 0.5), dropExp); + // For example no xp from redstone if it's mined with stone pickaxe + // Spawners drop xp only when mined with a pickaxe and don't drop anything (to prevent xp dupe with plugins) + if (!isSilkTouch && player != null && ((drops.length != 0 && target.getId() != Block.MONSTER_SPAWNER) || (drops.length == 0 && target.getId() == Block.MONSTER_SPAWNER && item.isPickaxe()))) { + if (player.isSurvival() || player.isAdventure()) { + this.dropExpOrb(dropPosition.add(0.5, 0.5, 0.5), dropExp); + } } - if (player == null || player.isSurvival()) { - for (Item drop : drops) { - if (drop.getCount() > 0) { - this.dropItem(vector.add(0.5, 0.5, 0.5), drop); - } + for (Item drop : drops) { + if (drop.getCount() > 0) { + this.dropItem(dropPosition.add(0.5, 0.5, 0.5), drop); } } } @@ -2038,20 +2221,17 @@ public void dropExpOrb(Vector3 source, int exp, Vector3 motion) { } public void dropExpOrb(Vector3 source, int exp, Vector3 motion, int delay) { - Random rand = ThreadLocalRandom.current(); - for (int split : EntityXPOrb.splitIntoOrbSizes(exp)) { - CompoundTag nbt = Entity.getDefaultNBT(source, motion == null ? new Vector3( - (rand.nextDouble() * 0.2 - 0.1) * 2, - rand.nextDouble() * 0.4, - (rand.nextDouble() * 0.2 - 0.1) * 2) : motion, - rand.nextFloat() * 360f, 0); - - nbt.putShort("Value", split); - nbt.putShort("PickupDelay", delay); - - Entity entity = Entity.createEntity("XpOrb", this.getChunk(source.getChunkX(), source.getChunkZ()), nbt); - if (entity != null) { - entity.spawnToAll(); + if (exp > 0) { + Random rand = ThreadLocalRandom.current(); + for (int split : EntityXPOrb.splitIntoOrbSizes(exp)) { + CompoundTag nbt = Entity.getDefaultNBT(source, motion == null ? new Vector3( + (rand.nextDouble() * 0.2 - 0.1) * 2, + rand.nextDouble() * 0.4, + (rand.nextDouble() * 0.2 - 0.1) * 2) : motion, + rand.nextFloat() * 360f, 0); + nbt.putShort("Value", split); + nbt.putShort("PickupDelay", delay); + Entity.createEntity("XpOrb", this.getChunk(source.getChunkX(), source.getChunkZ()), nbt).spawnToAll(); } } } @@ -2064,68 +2244,86 @@ public Item useItemOn(Vector3 vector, Item item, BlockFace face, float fx, float return this.useItemOn(vector, item, face, fx, fy, fz, player, true); } - + @SuppressWarnings("unchecked") public Item useItemOn(Vector3 vector, Item item, BlockFace face, float fx, float fy, float fz, Player player, boolean playSound) { Block target = this.getBlock(vector); Block block = target.getSide(face); - if (block.y > 255 || block.y < 0) { + if (block.y > this.getMaxBlockY() || block.y < this.getMinBlockY()) { return null; } - if (block.y > 127 && this.getDimension() == DIMENSION_NETHER) { - return null; - } - if (target.getId() == Item.AIR) { return null; } + if (face == BlockFace.UP && item.getBlockId() == BlockID.SCAFFOLDING && block.getId() == BlockID.SCAFFOLDING) { + while (block instanceof BlockScaffolding) { + block = block.up(); + } + } + if (player != null) { - PlayerInteractEvent ev = new PlayerInteractEvent(player, item, target, face, - target.getId() == 0 ? Action.RIGHT_CLICK_AIR : Action.RIGHT_CLICK_BLOCK); + PlayerInteractEvent ev = new PlayerInteractEvent(player, item, target, face, Action.RIGHT_CLICK_BLOCK); - if (player.getGamemode() > 2) { - ev.setCancelled(); + if (player.getGamemode() > Player.ADVENTURE) { + ev.setCancelled(true); } - if(!player.isOp() && isInSpawnRadius(target)) { - ev.setCancelled(); + if (!player.isOp() && isInSpawnRadius(target)) { + ev.setCancelled(true); } this.server.getPluginManager().callEvent(ev); + if (!ev.isCancelled()) { target.onUpdate(BLOCK_UPDATE_TOUCH); - if ((!player.isSneaking() || player.getInventory().getItemInHand().isNull()) && target.canBeActivated() && target.onActivate(item, player)) { + + if ((!player.sneakToBlockInteract() || item.isNull()) && target.canBeActivated() && target.onActivate(item, player)) { if (item.isTool() && item.getDamage() >= item.getMaxDurability()) { + this.addSound(target, cn.nukkit.level.Sound.RANDOM_BREAK); + this.addParticle(new ItemBreakParticle(target, item)); item = new ItemBlock(Block.get(BlockID.AIR), 0, 0); } + return item; } - if (item.canBeActivated() && item.onActivate(this, player, block, target, face, fx, fy, fz)) { - if (item.getCount() <= 0) { - item = new ItemBlock(Block.get(BlockID.AIR), 0, 0); - return item; + if (item.canBeActivated()) { + int oldCount = item.getCount(); + if (item.onActivate(this, player, block, target, face, fx, fy, fz)) { + if (oldCount != item.getCount()) { + if (item.getCount() <= 0) { + item = new ItemBlock(Block.get(BlockID.AIR), 0, 0); + } + return item; + } } } } else { - if(item.getId() == ItemID.BUCKET && ItemBucket.getDamageByTarget(item.getDamage()) == BlockID.WATER) { - player.getLevel().sendBlocks(new Player[]{player}, new Block[]{Block.get(Block.AIR, 0, target)}, UpdateBlockPacket.FLAG_ALL_PRIORITY, 1); + if (item.getId() == ItemID.BUCKET && ItemBucket.getDamageByTarget(item.getDamage()) == BlockID.WATER) { + player.getLevel().sendBlocks(new Player[]{player}, new Block[]{Block.get(Block.AIR, 0, target.getLevelBlock(BlockLayer.WATERLOGGED))}, UpdateBlockPacket.FLAG_ALL_PRIORITY, Block.LAYER_WATERLOGGED); } return null; } - if(item.getId() == ItemID.BUCKET && ItemBucket.getDamageByTarget(item.getDamage()) == BlockID.WATER) { - player.getLevel().sendBlocks(new Player[] {player}, new Block[] {Block.get(Block.AIR, 0, target)}, UpdateBlockPacket.FLAG_ALL_PRIORITY, 1); + if (item.getId() == ItemID.BUCKET && ItemBucket.getDamageByTarget(item.getDamage()) == BlockID.WATER) { + player.getLevel().sendBlocks(new Player[] {player}, new Block[] {target.getLevelBlock(BlockLayer.WATERLOGGED)}, UpdateBlockPacket.FLAG_ALL_PRIORITY, Block.LAYER_WATERLOGGED); } - } else if (target.canBeActivated() && target.onActivate(item, player)) { + } else if (target.canBeActivated() && target.onActivate(item, null)) { if (item.isTool() && item.getDamage() >= item.getMaxDurability()) { item = new ItemBlock(Block.get(BlockID.AIR), 0, 0); } return item; } + + int blockID = item.getBlockId(); + if (blockID > 255 && provider instanceof Anvil) { + return null; + } + Block hand; + if (item.canBePlaced()) { hand = item.getBlock(); hand.position(block); @@ -2133,50 +2331,48 @@ public Item useItemOn(Vector3 vector, Item item, BlockFace face, float fx, float return null; } - if (!(block.canBeReplaced() || (hand.getId() == Item.SLAB && block.getId() == Item.SLAB))) { + if (!(block.canBeReplaced() || (hand instanceof BlockSlab && block instanceof BlockSlab && hand.getId() == block.getId()))) { return null; } if (target.canBeReplaced()) { Block b = item.getBlockUnsafe(); if (b != null && target.getId() == b.getId() && target.getDamage() == b.getDamage()) { - return item; + return item; // No need to sync item } block = target; hand.position(block); } - if (!hand.canPassThrough() && hand.getBoundingBox() != null) { + if (!hand.canPassThrough() && hand.getBoundingBox() != null && !(hand instanceof BlockBed)) { Entity[] entities = this.getCollidingEntities(hand.getBoundingBox()); for (Entity e : entities) { - if (e instanceof EntityArrow || e instanceof EntityItem || (e instanceof Player && ((Player) e).isSpectator())) { + if (player == e || e instanceof EntityProjectile || e instanceof EntityItem || (e instanceof Player && ((Player) e).isSpectator() || !e.canCollide())) { continue; } - return null; + this.sendBlocks(player, new Block[]{block, target}, UpdateBlockPacket.FLAG_NONE); // Prevent ghost blocks + return null; // Entity in block } if (player != null) { - Vector3 diff = player.getNextPosition().subtract(player.getPosition()); - if (diff.lengthSquared() > 0.00001) { - AxisAlignedBB bb = player.getBoundingBox().getOffsetBoundingBox(diff.x, diff.y, diff.z); - if (hand.getBoundingBox().intersectsWith(bb)) { - return null; - } + if (hand.getBoundingBox().intersectsWith(player.getNextPositionBB())) { + this.sendBlocks(player, new Block[]{block, target}, UpdateBlockPacket.FLAG_NONE); // Prevent ghost blocks + return null; // Player in block } } } if (player != null) { BlockPlaceEvent event = new BlockPlaceEvent(player, hand, block, target, item); - if (player.getGamemode() == 2) { + if (player.getGamemode() == Player.ADVENTURE) { Tag tag = item.getNamedTagEntry("CanPlaceOn"); boolean canPlace = false; if (tag instanceof ListTag) { for (Tag v : ((ListTag) tag).getAll()) { if (v instanceof StringTag) { Item entry = Item.fromString(((StringTag) v).data); - if (entry.getId() > 0 && entry.getBlockUnsafe() != null && entry.getBlockUnsafe().getId() == target.getId()) { + if (entry.getId() != 0 && entry.getBlockUnsafe() != null && entry.getBlockUnsafe().getId() == target.getId()) { canPlace = true; break; } @@ -2184,11 +2380,12 @@ public Item useItemOn(Vector3 vector, Item item, BlockFace face, float fx, float } } if (!canPlace) { - event.setCancelled(); + event.setCancelled(true); } } - if(!player.isOp() && isInSpawnRadius(target)) { - event.setCancelled(); + + if (!player.isOp() && isInSpawnRadius(target)) { + event.setCancelled(true); } this.server.getPluginManager().callEvent(event); @@ -2197,10 +2394,31 @@ public Item useItemOn(Vector3 vector, Item item, BlockFace face, float fx, float } } + boolean liquidMoved = false; + if (hand.getWaterloggingType() != Block.WaterloggingType.NO_WATERLOGGING || !hand.canBeFlowedInto() || !(block instanceof BlockLiquid || block.getLevelBlock(BlockLayer.WATERLOGGED) instanceof BlockLiquid)) { + if ((block instanceof BlockLiquid) && ((BlockLiquid) block).usesWaterLogging() && hand.getWaterloggingType() != Block.WaterloggingType.NO_WATERLOGGING) { + liquidMoved = true; + this.setBlock(block, Block.LAYER_NORMAL, Block.get(BlockID.AIR), false, false); + this.setBlock(block, Block.LAYER_WATERLOGGED, block, false, false); + } + } + if (!hand.place(item, block, target, face, fx, fy, fz, player)) { + if (liquidMoved) { + this.setBlock(block, Block.LAYER_NORMAL, block, false, false); + this.setBlock(block, Block.LAYER_WATERLOGGED, Block.get(BlockID.AIR), false, false); + } return null; } + if (item.hasPersistentDataContainer() && item.getPersistentDataContainer().convertsToBlock()) { + block.getPersistentDataContainer().setStorage(item.getPersistentDataContainer().getStorage().clone()); + } + + if (liquidMoved) { + this.scheduleUpdate(block, 1); + } + if (player != null) { if (!player.isCreative()) { item.setCount(item.getCount() - 1); @@ -2208,7 +2426,17 @@ public Item useItemOn(Vector3 vector, Item item, BlockFace face, float fx, float } if (playSound) { - this.addLevelSoundEvent(hand, LevelSoundEventPacket.SOUND_PLACE, GlobalBlockPalette.getOrCreateRuntimeId(hand.getId(), hand.getDamage())); + int soundData = GlobalBlockPalette.getOrCreateRuntimeId(hand.getId(), hand.getDamage()); + + LevelSoundEventPacket pk = new LevelSoundEventPacket(); + pk.sound = LevelSoundEventPacket.SOUND_PLACE; + pk.extraData = soundData; + pk.entityIdentifier = ""; + pk.x = (float) hand.x; + pk.y = (float) hand.y; + pk.z = (float) hand.z; + + Server.broadcastPacket(this.getChunkPlayers(hand.getChunkX(), hand.getChunkZ()).values(), pk); } if (item.getCount() <= 0) { @@ -2218,17 +2446,12 @@ public Item useItemOn(Vector3 vector, Item item, BlockFace face, float fx, float } public boolean isInSpawnRadius(Vector3 vector3) { - int distance = this.server.getSpawnRadius(); - if (distance > -1) { - Vector2 t = new Vector2(vector3.x, vector3.z); - Vector2 s = new Vector2(this.getSpawnLocation().x, this.getSpawnLocation().z); - return t.distance(s) <= distance; - } - return false; + Vector3 spawn; + return server.getSpawnRadius() > -1 && new Vector2(vector3.x, vector3.z).distance(new Vector2((spawn = this.provider.getSpawn()).x, spawn.z)) <= server.getSpawnRadius(); } public Entity getEntity(long entityId) { - return this.entities.containsKey(entityId) ? this.entities.get(entityId) : null; + return this.entities.get(entityId); } public Entity[] getEntities() { @@ -2251,8 +2474,7 @@ public Entity[] getCollidingEntities(AxisAlignedBB bb, Entity entity) { for (int x = minX; x <= maxX; ++x) { for (int z = minZ; z <= maxZ; ++z) { for (Entity ent : this.getChunkEntities(x, z, false).values()) { - if ((entity == null || (ent != entity && entity.canCollideWith(ent))) - && ent.boundingBox.intersectsWith(bb)) { + if ((entity == null || (ent != entity && entity.canCollideWith(ent))) && ent.boundingBox.intersectsWith(bb)) { nearby.add(ent); } } @@ -2264,55 +2486,32 @@ public Entity[] getCollidingEntities(AxisAlignedBB bb, Entity entity) { } public Entity[] getNearbyEntities(AxisAlignedBB bb) { - return this.getNearbyEntities(bb, null); + return this.getNearbyEntities(bb, null, false); } - private static Entity[] EMPTY_ENTITY_ARR = new Entity[0]; - private static Entity[] ENTITY_BUFFER = new Entity[512]; - public Entity[] getNearbyEntities(AxisAlignedBB bb, Entity entity) { return getNearbyEntities(bb, entity, false); } public Entity[] getNearbyEntities(AxisAlignedBB bb, Entity entity, boolean loadChunks) { - int index = 0; + List nearby = new ArrayList<>(); int minX = NukkitMath.floorDouble((bb.getMinX() - 2) * 0.0625); int maxX = NukkitMath.ceilDouble((bb.getMaxX() + 2) * 0.0625); int minZ = NukkitMath.floorDouble((bb.getMinZ() - 2) * 0.0625); int maxZ = NukkitMath.ceilDouble((bb.getMaxZ() + 2) * 0.0625); - ArrayList overflow = null; - for (int x = minX; x <= maxX; ++x) { for (int z = minZ; z <= maxZ; ++z) { for (Entity ent : this.getChunkEntities(x, z, loadChunks).values()) { if (ent != entity && ent.boundingBox.intersectsWith(bb)) { - if (index < ENTITY_BUFFER.length) { - ENTITY_BUFFER[index] = ent; - } else { - if (overflow == null) overflow = new ArrayList<>(1024); - overflow.add(ent); - } - index++; + nearby.add(ent); } } } } - if (index == 0) return EMPTY_ENTITY_ARR; - Entity[] copy; - if (overflow == null) { - copy = Arrays.copyOfRange(ENTITY_BUFFER, 0, index); - Arrays.fill(ENTITY_BUFFER, 0, index, null); - } else { - copy = new Entity[ENTITY_BUFFER.length + overflow.size()]; - System.arraycopy(ENTITY_BUFFER, 0, copy, 0, ENTITY_BUFFER.length); - for (int i = 0; i < overflow.size(); i++) { - copy[ENTITY_BUFFER.length + i] = overflow.get(i); - } - } - return copy; + return nearby.toArray(new Entity[0]); } public Map getBlockEntities() { @@ -2320,7 +2519,7 @@ public Map getBlockEntities() { } public BlockEntity getBlockEntityById(long blockEntityId) { - return this.blockEntities.containsKey(blockEntityId) ? this.blockEntities.get(blockEntityId) : null; + return this.blockEntities.get(blockEntityId); } public Map getPlayers() { @@ -2332,20 +2531,42 @@ public Map getLoaders() { } public BlockEntity getBlockEntity(Vector3 pos) { - FullChunk chunk = this.getChunk((int) pos.x >> 4, (int) pos.z >> 4, false); + return getBlockEntity(null, pos); + } + + public BlockEntity getBlockEntity(FullChunk chunk, Vector3 pos) { + int by = pos.getFloorY(); + if (by < this.getMinBlockY() || by > this.getMaxBlockY()) return null; + + int cx = (int) pos.x >> 4; + int cz = (int) pos.z >> 4; + if (chunk == null || cx != chunk.getX() || cz != chunk.getZ()) { + chunk = this.getChunk(cx, cz, false); + } if (chunk != null) { - return chunk.getTile((int) pos.x & 0x0f, (int) pos.y & 0xff, (int) pos.z & 0x0f); + return chunk.getTile((int) pos.x & 0x0f, by, (int) pos.z & 0x0f); } return null; } public BlockEntity getBlockEntityIfLoaded(Vector3 pos) { - FullChunk chunk = this.getChunkIfLoaded((int) pos.x >> 4, (int) pos.z >> 4); + return getBlockEntityIfLoaded(null, pos); + } + + public BlockEntity getBlockEntityIfLoaded(FullChunk chunk, Vector3 pos) { + int by = pos.getFloorY(); + if (by < this.getMinBlockY() || by > this.getMaxBlockY()) return null; + + int cx = (int) pos.x >> 4; + int cz = (int) pos.z >> 4; + if (chunk == null || cx != chunk.getX() || cz != chunk.getZ()) { + chunk = this.getChunkIfLoaded(cx, cz); + } if (chunk != null) { - return chunk.getTile((int) pos.x & 0x0f, (int) pos.y & 0xff, (int) pos.z & 0x0f); + return chunk.getTile((int) pos.x & 0x0f, by, (int) pos.z & 0x0f); } return null; @@ -2366,78 +2587,213 @@ public Map getChunkBlockEntities(int X, int Z) { } @Override - public synchronized int getBlockIdAt(int x, int y, int z) { - return this.getChunk(x >> 4, z >> 4, true).getBlockId(x & 0x0f, y & 0xff, z & 0x0f); + public int getBlockIdAt(int x, int y, int z) { + return getBlockIdAt(x, y, z, Block.LAYER_NORMAL); + } + + @Override + public synchronized int getBlockIdAt(int x, int y, int z, BlockLayer layer) { + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return 0; + } + + int cx = x >> 4; + int cz = z >> 4; + FullChunk chunk = this.getChunk(cx, cz, true); + return chunk.getBlockId(x & 0x0f, y, z & 0x0f, layer); + } + + public synchronized int getBlockIdAt(FullChunk chunk, int x, int y, int z) { + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return 0; + } + + int cx = x >> 4; + int cz = z >> 4; + if (chunk == null || cx != chunk.getX() || cz != chunk.getZ()) { + chunk = this.getChunk(cx, cz, true); + } + return chunk.getBlockId(x & 0x0f, y, z & 0x0f, Block.LAYER_NORMAL); } @Override public synchronized void setBlockIdAt(int x, int y, int z, int id) { - this.getChunk(x >> 4, z >> 4, true).setBlockId(x & 0x0f, y & 0xff, z & 0x0f, id & 0xff); + this.setBlockIdAt(x, y, z, Block.LAYER_NORMAL, id); + } + + @Override + public synchronized void setBlockIdAt(int x, int y, int z, BlockLayer layer, int id) { + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return; + } + + FullChunk chunk = this.getChunk(x >> 4, z >> 4, true); + chunk.setBlockId(x & 0x0f, y, z & 0x0f, layer, id); addBlockChange(x, y, z); - temporalVector.setComponents(x, y, z); - for (ChunkLoader loader : this.getChunkLoaders(x >> 4, z >> 4)) { - loader.onBlockChanged(temporalVector); + + if (this.useChunkLoaderApi) { + temporalVector.setComponents(x, y, z); + for (ChunkLoader loader : this.getChunkLoaders(x >> 4, z >> 4)) { + loader.onBlockChanged(temporalVector); + } + } + + if (id == 0) { + updateEntitiesOnBlockChange(chunk); } } + @Override public synchronized void setBlockAt(int x, int y, int z, int id, int data) { + this.setBlockAtLayer(x, y, z, Block.LAYER_NORMAL, id, data); + } + + @Override + public boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int id) { + return this.setBlockAtLayer(x, y, z, layer, id, 0); + } + + @Override + public synchronized boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int id, int data) { + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return false; + } + BaseFullChunk chunk = this.getChunk(x >> 4, z >> 4, true); - chunk.setBlockId(x & 0x0f, y & 0xff, z & 0x0f, id & 0xff); - chunk.setBlockData(x & 0x0f, y & 0xff, z & 0x0f, data & 0xf); + boolean changed = chunk.setBlockAtLayer(x & 0x0f, y, z & 0x0f, layer, id, data & Block.DATA_MASK); + if (!changed) { + return false; + } + addBlockChange(x, y, z); - temporalVector.setComponents(x, y, z); - for (ChunkLoader loader : this.getChunkLoaders(x >> 4, z >> 4)) { - loader.onBlockChanged(temporalVector); + + if (this.useChunkLoaderApi) { + temporalVector.setComponents(x, y, z); + for (ChunkLoader loader : this.getChunkLoaders(x >> 4, z >> 4)) { + loader.onBlockChanged(temporalVector); + } + } + + if (id == 0) { + updateEntitiesOnBlockChange(chunk); + } + return true; + } + + private void updateEntitiesOnBlockChange(FullChunk chunk) { + if (chunk == null) { + return; + } + for (Entity entity : chunk.getEntities().values()) { + if (entity.updateMode % 2 == 1) { + entity.updateMode = 1; + } } } public synchronized int getBlockExtraDataAt(int x, int y, int z) { - return this.getChunk(x >> 4, z >> 4, true).getBlockExtraData(x & 0x0f, y & 0xff, z & 0x0f); + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return 0; + } + return this.getChunk(x >> 4, z >> 4, true).getBlockExtraData(x & 0x0f, y, z & 0x0f); } public synchronized void setBlockExtraDataAt(int x, int y, int z, int id, int data) { - this.getChunk(x >> 4, z >> 4, true).setBlockExtraData(x & 0x0f, y & 0xff, z & 0x0f, (data << 8) | id); + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return; + } + this.getChunk(x >> 4, z >> 4, true).setBlockExtraData(x & 0x0f, y, z & 0x0f, (data << 8) | id); this.sendBlockExtraData(x, y, z, id, data); } @Override public synchronized int getBlockDataAt(int x, int y, int z) { - return this.getChunk(x >> 4, z >> 4, true).getBlockData(x & 0x0f, y & 0xff, z & 0x0f); + return this.getBlockDataAt(null, x, y, z, Block.LAYER_NORMAL); + } + + @Override + public synchronized int getBlockDataAt(int x, int y, int z, BlockLayer layer) { + return this.getBlockDataAt(null, x, y, z, layer); + } + + public synchronized int getBlockDataAt(FullChunk chunk, int x, int y, int z, BlockLayer layer) { + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return 0; + } + int cx = x >> 4; + int cz = z >> 4; + if (chunk == null || cx != chunk.getX() || cz != chunk.getZ()) { + chunk = this.getChunk(cx, cz, true); + } + return chunk.getBlockData(x & 0x0f, y, z & 0x0f, layer); } @Override public synchronized void setBlockDataAt(int x, int y, int z, int data) { - this.getChunk(x >> 4, z >> 4, true).setBlockData(x & 0x0f, y & 0xff, z & 0x0f, data & 0x0f); + this.setBlockDataAt(x, y, z, Block.LAYER_NORMAL, data); + } + + @Override + public synchronized void setBlockDataAt(int x, int y, int z, BlockLayer layer, int data) { + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return; + } + + this.getChunk(x >> 4, z >> 4, true).setBlockData(x & 0x0f, y, z & 0x0f, layer, data & Block.DATA_MASK); addBlockChange(x, y, z); - temporalVector.setComponents(x, y, z); - for (ChunkLoader loader : this.getChunkLoaders(x >> 4, z >> 4)) { - loader.onBlockChanged(temporalVector); + + if (this.useChunkLoaderApi) { + temporalVector.setComponents(x, y, z); + for (ChunkLoader loader : this.getChunkLoaders(x >> 4, z >> 4)) { + loader.onBlockChanged(temporalVector); + } } } public synchronized int getBlockSkyLightAt(int x, int y, int z) { - return this.getChunk(x >> 4, z >> 4, true).getBlockSkyLight(x & 0x0f, y & 0xff, z & 0x0f); + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return 0; + } + return this.getChunk(x >> 4, z >> 4, true).getBlockSkyLight(x & 0x0f, y, z & 0x0f); } public synchronized void setBlockSkyLightAt(int x, int y, int z, int level) { - this.getChunk(x >> 4, z >> 4, true).setBlockSkyLight(x & 0x0f, y & 0xff, z & 0x0f, level & 0x0f); + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return; + } + this.getChunk(x >> 4, z >> 4, true).setBlockSkyLight(x & 0x0f, y, z & 0x0f, level & 0x0f); } public synchronized int getBlockLightAt(int x, int y, int z) { - return this.getChunk(x >> 4, z >> 4, true).getBlockLight(x & 0x0f, y & 0xff, z & 0x0f); + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return 0; + } + BaseFullChunk chunk = this.getChunkIfLoaded(x >> 4, z >> 4); + return chunk == null ? 0 : chunk.getBlockLight(x & 0x0f, y, z & 0x0f); } public synchronized void setBlockLightAt(int x, int y, int z, int level) { - this.getChunk(x >> 4, z >> 4, true).setBlockLight(x & 0x0f, y & 0xff, z & 0x0f, level & 0x0f); + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return; + } + + BaseFullChunk c = this.getChunkIfLoaded(x >> 4, z >> 4); + if (null != c) { + c.setBlockLight(x & 0x0f, y, z & 0x0f, level & 0x0f); + } } public int getBiomeId(int x, int z) { return this.getChunk(x >> 4, z >> 4, true).getBiomeId(x & 0x0f, z & 0x0f); } + public void setBiomeId(int x, int z, int biomeId) { + this.getChunk(x >> 4, z >> 4, true).setBiomeId(x & 0x0f, z & 0x0f, biomeId & 0x0f); + } + public void setBiomeId(int x, int z, byte biomeId) { - this.getChunk(x >> 4, z >> 4, true).setBiomeId(x & 0x0f, z & 0x0f, biomeId); + this.getChunk(x >> 4, z >> 4, true).setBiomeId(x & 0x0f, z & 0x0f, biomeId & 0x0f); } public int getHeightMap(int x, int z) { @@ -2467,8 +2823,7 @@ public BaseFullChunk getChunk(int chunkX, int chunkZ, boolean create) { } public BaseFullChunk getChunkIfLoaded(int chunkX, int chunkZ) { - long index = Level.chunkHash(chunkX, chunkZ); - return this.provider.getLoadedChunk(index); + return this.provider.getLoadedChunk(Level.chunkHash(chunkX, chunkZ)); } public void generateChunkCallback(int x, int z, BaseFullChunk chunk) { @@ -2476,9 +2831,8 @@ public void generateChunkCallback(int x, int z, BaseFullChunk chunk) { } public void generateChunkCallback(int x, int z, BaseFullChunk chunk, boolean isPopulated) { - Timings.generationCallbackTimer.startTiming(); long index = Level.chunkHash(x, z); - if (this.chunkPopulationQueue.containsKey(index)) { + if (this.chunkPopulationQueue.contains(index)) { FullChunk oldChunk = this.getChunk(x, z, false); for (int xx = -1; xx <= 1; ++xx) { for (int zz = -1; zz <= 1; ++zz) { @@ -2493,11 +2847,13 @@ public void generateChunkCallback(int x, int z, BaseFullChunk chunk, boolean isP && chunk.getProvider() != null) { this.server.getPluginManager().callEvent(new ChunkPopulateEvent(chunk)); - for (ChunkLoader loader : this.getChunkLoaders(x, z)) { - loader.onChunkPopulated(chunk); + if (this.useChunkLoaderApi) { + for (ChunkLoader loader : this.getChunkLoaders(x, z)) { + loader.onChunkPopulated(chunk); + } } } - } else if (this.chunkGenerationQueue.containsKey(index) || this.chunkPopulationLock.containsKey(index)) { + } else if (this.chunkGenerationQueue.contains(index) || this.chunkPopulationLock.contains(index)) { this.chunkGenerationQueue.remove(index); this.chunkPopulationLock.remove(index); chunk.setProvider(this.provider); @@ -2506,7 +2862,6 @@ public void generateChunkCallback(int x, int z, BaseFullChunk chunk, boolean isP chunk.setProvider(this.provider); this.setChunk(x, z, chunk, false); } - Timings.generationCallbackTimer.stopTiming(); } @Override @@ -2530,8 +2885,6 @@ public void setChunk(int chunkX, int chunkZ, BaseFullChunk chunk, boolean unload if (oldChunk != chunk) { if (unload && oldChunk != null) { this.unloadChunk(chunkX, chunkZ, false, false); - - this.provider.setChunk(chunkX, chunkZ, chunk); } else { Map oldEntities = oldChunk != null ? oldChunk.getEntities() : Collections.emptyMap(); @@ -2565,8 +2918,8 @@ public void setChunk(int chunkX, int chunkZ, BaseFullChunk chunk, boolean unload } } - this.provider.setChunk(chunkX, chunkZ, chunk); } + this.provider.setChunk(chunkX, chunkZ, chunk); } chunk.setChanged(); @@ -2581,32 +2934,134 @@ public void setChunk(int chunkX, int chunkZ, BaseFullChunk chunk, boolean unload } public int getHighestBlockAt(int x, int z) { - return this.getChunk(x >> 4, z >> 4, true).getHighestBlockAt(x & 0x0f, z & 0x0f); + return this.getHighestBlockAt(x, z, true); + } + + public int getHighestBlockAt(int x, int z, boolean cache) { + return this.getChunk(x >> 4, z >> 4, true).getHighestBlockAt(x & 0x0f, z & 0x0f, cache); } public BlockColor getMapColorAt(int x, int z) { - int y = getHighestBlockAt(x, z); - while (y > 1) { - Block block = getBlock(new Vector3(x, y, z)); - BlockColor blockColor = block.getColor(); - if (blockColor.getAlpha() == 0x00) { - y--; + return getMapColorAt(x, getHighestBlockAt(x, z, false), z); + } + + public BlockColor getMapColorAt(int x, int y, int z) { + int minY = this.getMinBlockY(); + if (y < minY || y > this.getMaxBlockY()) return BlockColor.VOID_BLOCK_COLOR; + + int checkY = y; + FullChunk chunk = this.getChunk(x >> 4, z >> 4); + while (checkY > minY) { + Block block = this.getBlock(chunk, x, checkY, z, BlockLayer.NORMAL, false); + if (block instanceof BlockGrass) { + return getGrassColorAt(chunk, x, z); + //} else if (block instanceof BlockWater) { + // return getWaterColorAt(chunk, x, z); } else { - return blockColor; + BlockColor blockColor = block.getColor(); + if (blockColor.getAlpha() == 0x00) { + checkY--; + } else { + return blockColor; + } } } + return BlockColor.VOID_BLOCK_COLOR; } + private BlockColor getGrassColorAt(FullChunk chunk, int x, int z) { + int biome = chunk.getBiomeId(x & 0x0f, z & 0x0f); + + switch (biome) { + case 0: //ocean + case 7: //river + case 9: //end + case 24: //deep ocean + return new BlockColor("#8eb971"); + case 1: //plains + case 16: //beach + case 129: //sunflower plains + return new BlockColor("#91bd59"); + case 2: //desert + case 8: //hell + case 17: //desert hills + case 35: //savanna + case 36: //savanna plateau + case 130: //desert m + case 163: //savanna m + case 164: //savanna plateau m + return new BlockColor("#bfb755"); + case 3: //extreme hills + case 20: //extreme hills edge + case 25: //stone beach + case 34: //extreme hills + case 131: //extreme hills m + case 162: //extreme hills plus m + return new BlockColor("#8ab689"); + case 4: //forest + case 132: //flower forest + return new BlockColor("#79c05a"); + case 5: //taiga + case 19: //taiga hills + case 32: //mega taiga + case 33: //mega taiga hills + case 133: //taiga m + case 160: //mega spruce taiga + return new BlockColor("#86b783"); + case 6: //swamp + case 134: //swampland m + return new BlockColor("#6A7039"); + case 10: //frozen ocean + case 11: //frozen river + case 12: //ice plains + case 30: //cold taiga + case 31: //cold taiga hills + case 140: //ice plains spikes + case 158: //cold taiga m + return new BlockColor("#80b497"); + case 14: //mushroom island + case 15: //mushroom island shore + return new BlockColor("#55c93f"); + case 18: //forest hills + case 27: //birch forest + case 28: //birch forest hills + case 155: //birch forest m + case 156: //birch forest hills m + return new BlockColor("#88bb67"); + case 21: //jungle + case 22: //jungle hills + case 149: //jungle m + return new BlockColor("#59c93c"); + case 23: //jungle edge + case 151: //jungle edge m + return new BlockColor("#64c73f"); + case 26: //cold beach + return new BlockColor("#83b593"); + case 29: //roofed forest + case 157: //roofed forest m + return new BlockColor("#507a32"); + case 37: //mesa + case 38: //mesa plateau f + case 39: //mesa plateau + case 165: //mesa bryce + case 166: //mesa plateau f m + case 167: //mesa plateau m + return new BlockColor("#90814d"); + default: + return BlockColor.GRASS_BLOCK_COLOR; + } + } + public boolean isChunkLoaded(int x, int z) { return this.provider.isChunkLoaded(x, z); } private boolean areNeighboringChunksLoaded(long hash) { return this.provider.isChunkLoaded(hash + 1) && - this.provider.isChunkLoaded(hash - 1) && - this.provider.isChunkLoaded(hash + (1L << 32)) && - this.provider.isChunkLoaded(hash - (1L << 32)); + this.provider.isChunkLoaded(hash - 1) && + this.provider.isChunkLoaded(hash + (4294967296L)) && + this.provider.isChunkLoaded(hash - (4294967296L)); } public boolean isChunkGenerated(int x, int z) { @@ -2625,22 +3080,25 @@ public Position getSpawnLocation() { public void setSpawnLocation(Vector3 pos) { Position previousSpawn = this.getSpawnLocation(); - this.provider.setSpawn(pos); + this.provider.setSpawn(new Vector3(pos.x, pos.y, pos.z)); this.server.getPluginManager().callEvent(new SpawnChangeEvent(this, previousSpawn)); SetSpawnPositionPacket pk = new SetSpawnPositionPacket(); pk.spawnType = SetSpawnPositionPacket.TYPE_WORLD_SPAWN; pk.x = pos.getFloorX(); pk.y = pos.getFloorY(); pk.z = pos.getFloorZ(); + pk.dimension = this.getDimension(); for (Player p : getPlayers().values()) p.dataPacket(pk); } public void requestChunk(int x, int z, Player player) { - Preconditions.checkState(player.getLoaderId() > 0, player.getName() + " has no chunk loader"); + if (player.getLoaderId() <= 0) { + throw new IllegalStateException(player.getName() + " has no chunk loader"); + } + long index = Level.chunkHash(x, z); this.chunkSendQueue.putIfAbsent(index, new Int2ObjectOpenHashMap<>()); - this.chunkSendQueue.get(index).put(player.getLoaderId(), player); } @@ -2658,7 +3116,6 @@ private void sendChunk(int x, int z, long index, DataPacket packet) { } private void processChunkRequest() { - this.timings.syncChunkSendTimer.startTiming(); for (long index : this.chunkSendQueue.keySet()) { if (this.chunkSendTasks.contains(index)) { continue; @@ -2674,42 +3131,31 @@ private void processChunkRequest() { continue; } } - this.timings.syncChunkSendPrepareTimer.startTiming(); - AsyncTask task = this.provider.requestChunkTask(x, z); - if (task != null) { - this.server.getScheduler().scheduleAsyncTask(task); - } - this.timings.syncChunkSendPrepareTimer.stopTiming(); + this.provider.requestChunkTask(x, z); } - this.timings.syncChunkSendTimer.stopTiming(); } - public void chunkRequestCallback(long timestamp, int x, int z, int subChunkCount, byte[] payload) { - this.timings.syncChunkSendTimer.startTiming(); - long index = Level.chunkHash(x, z); - - if (this.cacheChunks) { - BatchPacket data = Player.getChunkCacheFromData(x, z, subChunkCount, payload); - BaseFullChunk chunk = getChunk(x, z, false); + public void chunkRequestCallback(long timestamp, int x, int z, int subChunkCount, byte[] payload, long index) { + if (server.cacheChunks) { + BatchPacket data = Player.getChunkCacheFromData(x, z, subChunkCount, payload, this.getDimension()); + BaseFullChunk chunk = this.getChunkIfLoaded(x, z); if (chunk != null && chunk.getChanges() <= timestamp) { chunk.setChunkPacket(data); } this.sendChunk(x, z, index, data); - this.timings.syncChunkSendTimer.stopTiming(); return; } if (this.chunkSendTasks.contains(index)) { for (Player player : this.chunkSendQueue.get(index).values()) { if (player.isConnected() && player.usedChunks.containsKey(index)) { - player.sendChunk(x, z, subChunkCount, payload); + player.sendChunk(x, z, subChunkCount, payload, this.getDimension()); } } this.chunkSendQueue.remove(index); this.chunkSendTasks.remove(index); } - this.timings.syncChunkSendTimer.stopTiming(); } public void removeEntity(Entity entity) { @@ -2741,22 +3187,24 @@ public void addEntity(Entity entity) { public void addBlockEntity(BlockEntity blockEntity) { if (blockEntity.getLevel() != this) { - throw new LevelException("Invalid Block Entity level"); + throw new LevelException("BlockEntity is not in this level"); } blockEntities.put(blockEntity.getId(), blockEntity); } public void scheduleBlockEntityUpdate(BlockEntity entity) { - Preconditions.checkNotNull(entity, "entity"); - Preconditions.checkArgument(entity.getLevel() == this, "BlockEntity is not in this level"); + if (entity.getLevel() != this) { + throw new LevelException("BlockEntity is not in this level"); + } if (!updateBlockEntities.contains(entity)) { updateBlockEntities.add(entity); } } public void removeBlockEntity(BlockEntity entity) { - Preconditions.checkNotNull(entity, "entity"); - Preconditions.checkArgument(entity.getLevel() == this, "BlockEntity is not in this level"); + if (entity.getLevel() != this) { + throw new LevelException("BlockEntity is not in this level"); + } blockEntities.remove(entity.getId()); updateBlockEntities.remove(entity); } @@ -2766,7 +3214,8 @@ public boolean isChunkInUse(int x, int z) { } public boolean isChunkInUse(long hash) { - return this.chunkLoaders.containsKey(hash) && !this.chunkLoaders.get(hash).isEmpty(); + Map map = this.chunkLoaders.get(hash); + return map != null && !map.isEmpty(); } public boolean loadChunk(int x, int z) { @@ -2782,40 +3231,39 @@ public boolean loadChunk(int x, int z, boolean generate) { } private synchronized BaseFullChunk forceLoadChunk(long index, int x, int z, boolean generate) { - this.timings.syncChunkLoadTimer.startTiming(); BaseFullChunk chunk = this.provider.getChunk(x, z, generate); + if (chunk == null) { if (generate) { - throw new IllegalStateException("Could not create new Chunk"); + throw new IllegalStateException("Could not create new chunk"); } - this.timings.syncChunkLoadTimer.stopTiming(); - return chunk; + return null; } if (chunk.getProvider() != null) { this.server.getPluginManager().callEvent(new ChunkLoadEvent(chunk, !chunk.isGenerated())); } else { this.unloadChunk(x, z, false); - this.timings.syncChunkLoadTimer.stopTiming(); return chunk; } chunk.initChunk(); - if (!chunk.isLightPopulated() && chunk.isPopulated() - && this.getServer().getConfig("chunk-ticking.light-updates", false)) { - this.getServer().getScheduler().scheduleAsyncTask(new LightPopulationTask(this, chunk)); - } + /*if (!chunk.isLightPopulated() && chunk.isPopulated()) { + this.server.getScheduler().scheduleAsyncTask(new LightPopulationTask(this, chunk)); + }*/ if (this.isChunkInUse(index)) { this.unloadQueue.remove(index); - for (ChunkLoader loader : this.getChunkLoaders(x, z)) { - loader.onChunkLoaded(chunk); + + if (this.useChunkLoaderApi) { + for (ChunkLoader loader : this.getChunkLoaders(x, z)) { + loader.onChunkLoaded(chunk); + } } } else { this.unloadQueue.put(index, System.currentTimeMillis()); } - this.timings.syncChunkLoadTimer.stopTiming(); return chunk; } @@ -2863,54 +3311,55 @@ public synchronized boolean unloadChunk(int x, int z, boolean safe, boolean tryS return true; } - this.timings.doChunkUnload.startTiming(); - BaseFullChunk chunk = this.getChunk(x, z); if (chunk != null && chunk.getProvider() != null) { ChunkUnloadEvent ev = new ChunkUnloadEvent(chunk); this.server.getPluginManager().callEvent(ev); if (ev.isCancelled()) { - this.timings.doChunkUnload.stopTiming(); return false; } } try { if (chunk != null) { - if (trySave && this.getAutoSave()) { - int entities = 0; - for (Entity e : chunk.getEntities().values()) { - if (e instanceof Player) { - continue; + if (trySave && this.saveOnUnloadEnabled) { + boolean needSave = chunk.hasChanged(); + + if (!needSave) { + for (Entity e : chunk.getEntities().values()) { + if (e.canSaveToStorage() && !e.ignoredAsSaveReason()) { + needSave = true; + break; + } } - ++entities; } - if (chunk.hasChanged() || !chunk.getBlockEntities().isEmpty() || entities > 0) { + if (needSave) { this.provider.setChunk(x, z, chunk); - this.provider.saveChunk(x, z); + this.provider.saveChunk(x, z, chunk); } } - for (ChunkLoader loader : this.getChunkLoaders(x, z)) { - loader.onChunkUnloaded(chunk); + + if (this.useChunkLoaderApi) { + for (ChunkLoader loader : this.getChunkLoaders(x, z)) { + loader.onChunkUnloaded(chunk); + } } } this.provider.unloadChunk(x, z, safe); } catch (Exception e) { MainLogger logger = this.server.getLogger(); - logger.error(this.server.getLanguage().translateString("nukkit.level.chunkUnloadError", e.toString())); - logger.logException(e); + logger.error(this.server.getLanguage().translateString("nukkit.level.chunkUnloadError", e.toString()), e); } - this.timings.doChunkUnload.stopTiming(); - return true; } public boolean isSpawnChunk(int X, int Z) { - Vector3 spawn = this.provider.getSpawn(); - return Math.abs(X - (spawn.getFloorX() >> 4)) <= 1 && Math.abs(Z - (spawn.getFloorZ() >> 4)) <= 1; + Vector3 cachedSpawnPos = this.provider.getSpawn(); + + return Math.abs(X - (cachedSpawnPos.getChunkX())) <= 1 && Math.abs(Z - (cachedSpawnPos.getChunkZ())) <= 1; } public Position getSafeSpawn() { @@ -2918,56 +3367,52 @@ public Position getSafeSpawn() { } public Position getSafeSpawn(Vector3 spawn) { - if (spawn == null || spawn.y < 1) { + if (spawn == null /*|| spawn.y < 1*/) { spawn = this.getSpawnLocation(); } - if (spawn != null) { - Vector3 v = spawn.floor(); - FullChunk chunk = this.getChunk((int) v.x >> 4, (int) v.z >> 4, false); - int x = (int) v.x & 0x0f; - int z = (int) v.z & 0x0f; - if (chunk != null && chunk.isGenerated()) { - int y = (int) NukkitMath.clamp(v.y, 1, 254); - boolean wasAir = chunk.getBlockId(x, y - 1, z) == 0; - for (; y > 0; --y) { - int b = chunk.getFullBlock(x, y, z); - Block block = Block.get(b >> 4, b & 0x0f); - if (this.isFullBlock(block)) { - if (wasAir) { - y++; - break; - } - } else { - wasAir = true; + Vector3 pos = spawn.floor(); + FullChunk chunk = this.getChunk((int) pos.x >> 4, (int) pos.z >> 4, false); + int x = (int) pos.x & 0x0f; + int z = (int) pos.z & 0x0f; + if (chunk != null && chunk.isGenerated()) { + int y = NukkitMath.clamp((int) pos.y, this.getMinBlockY() + 1, this.getMaxBlockY() - 1); + boolean wasAir = chunk.getBlockId(x, y - 1, z) == 0; + for (; y > this.getMinBlockY(); --y) { + int fullId = chunk.getFullBlock(x, y, z); + Block block = Block.get(fullId >> Block.DATA_BITS, fullId & Block.DATA_MASK); + if (this.isFullBlock(block)) { + if (wasAir) { + y++; } + break; + } else { + wasAir = true; } + } - for (; y >= 0 && y < 255; y++) { - int b = chunk.getFullBlock(x, y + 1, z); - Block block = Block.get(b >> 4, b & 0x0f); + for (; y >= this.getMinBlockY() && y < this.getMaxBlockY(); y++) { + int fullId = chunk.getFullBlock(x, y + 1, z); + Block block = Block.get(fullId >> Block.DATA_BITS, fullId & Block.DATA_MASK); + if (!this.isFullBlock(block)) { + fullId = chunk.getFullBlock(x, y, z); + block = Block.get(fullId >> Block.DATA_BITS, fullId & Block.DATA_MASK); if (!this.isFullBlock(block)) { - b = chunk.getFullBlock(x, y, z); - block = Block.get(b >> 4, b & 0x0f); - if (!this.isFullBlock(block)) { - return new Position(spawn.x, y == (int) spawn.y ? spawn.y : y, spawn.z, this); - } - } else { - ++y; + return new Position(pos.x + 0.5, y + 0.51, pos.z + 0.5, this); // Hack: + 0.51 for slabs } + } else { + ++y; } - - v.y = y; } - return new Position(spawn.x, v.y, spawn.z, this); + pos.y = y; } - return null; + return new Position(pos.x + 0.5, pos.y + 0.1, pos.z + 0.5, this); } public int getTime() { - return (int) time; + return time; } public boolean isDaytime() { @@ -2979,7 +3424,8 @@ public long getCurrentTick() { } public String getName() { - return this.provider.getName(); + return this.folderName; + //return this.provider.getName(); } public String getFolderName() { @@ -3016,45 +3462,47 @@ public boolean populateChunk(int x, int z) { public boolean populateChunk(int x, int z, boolean force) { long index = Level.chunkHash(x, z); - if (this.chunkPopulationQueue.containsKey(index) || this.chunkPopulationQueue.size() >= this.chunkPopulationQueueSize && !force) { + if (this.chunkPopulationQueue.contains(index) || this.chunkPopulationQueue.size() >= this.chunkPopulationQueueSize && !force) { return false; } BaseFullChunk chunk = this.getChunk(x, z, true); - boolean populate; if (!chunk.isPopulated()) { - Timings.populationTimer.startTiming(); - populate = true; + boolean populate = true; + + top: for (int xx = -1; xx <= 1; ++xx) { for (int zz = -1; zz <= 1; ++zz) { - if (this.chunkPopulationLock.containsKey(Level.chunkHash(x + xx, z + zz))) { - + if (this.chunkPopulationLock.contains(Level.chunkHash(x + xx, z + zz))) { populate = false; - break; + break top; } } } if (populate) { - if (!this.chunkPopulationQueue.containsKey(index)) { - this.chunkPopulationQueue.put(index, Boolean.TRUE); + if (!this.chunkPopulationQueue.contains(index)) { + this.chunkPopulationQueue.add(index); for (int xx = -1; xx <= 1; ++xx) { for (int zz = -1; zz <= 1; ++zz) { - this.chunkPopulationLock.put(Level.chunkHash(x + xx, z + zz), Boolean.TRUE); + this.chunkPopulationLock.add(Level.chunkHash(x + xx, z + zz)); } } - PopulationTask task = new PopulationTask(this, chunk); - this.server.getScheduler().scheduleAsyncTask(task); + this.server.getScheduler().scheduleAsyncTask(null, this.generatorTaskFactory.populateChunkTask(chunk, this)); } } - Timings.populationTimer.stopTiming(); return false; } return true; } + @Override + public AsyncTask populateChunkTask(BaseFullChunk chunk, Level level) { + return new PopulationTask(this, chunk); + } + public void generateChunk(int x, int z) { this.generateChunk(x, z, false); } @@ -3065,29 +3513,26 @@ public void generateChunk(int x, int z, boolean force) { } long index = Level.chunkHash(x, z); - if (!this.chunkGenerationQueue.containsKey(index)) { - Timings.generationTimer.startTiming(); - this.chunkGenerationQueue.put(index, Boolean.TRUE); - GenerationTask task = new GenerationTask(this, this.getChunk(x, z, true)); - this.server.getScheduler().scheduleAsyncTask(task); - Timings.generationTimer.stopTiming(); + if (!this.chunkGenerationQueue.contains(index)) { + this.chunkGenerationQueue.add(index); + this.server.getScheduler().scheduleAsyncTask(null, this.generatorTaskFactory.generateChunkTask(this.getChunk(x, z, true), this)); } } + @Override + public AsyncTask generateChunkTask(BaseFullChunk chunk, Level level) { + return new GenerationTask(level, chunk); + } + public void regenerateChunk(int x, int z) { this.unloadChunk(x, z, false, false); - this.cancelUnloadChunkRequest(x, z); - - BaseFullChunk chunk = provider.getEmptyChunk(x, z); - provider.setChunk(x, z, chunk); - + provider.setChunk(x, z, provider.getEmptyChunk(x, z)); this.generateChunk(x, z, true); } public void doChunkGarbageCollection() { - this.timings.doChunkGC.startTiming(); - // remove all invaild block entities. + // Remove all invalid block entities if (!blockEntities.isEmpty()) { ObjectIterator iter = blockEntities.values().iterator(); while (iter.hasNext()) { @@ -3116,13 +3561,13 @@ public void doChunkGarbageCollection() { } this.provider.doGarbageCollection(); - this.timings.doChunkGC.stopTiming(); } + public void doGarbageCollection(long allocatedTime) { long start = System.currentTimeMillis(); if (unloadChunks(start, allocatedTime, false)) { - allocatedTime = allocatedTime - (System.currentTimeMillis() - start); + allocatedTime -= (System.currentTimeMillis() - start); provider.doGarbageCollection(allocatedTime); } } @@ -3132,32 +3577,37 @@ public void unloadChunks() { } public void unloadChunks(boolean force) { - unloadChunks(96, force); + this.unloadChunks(50, force); } public void unloadChunks(int maxUnload, boolean force) { + if (server.holdWorldSave && !force && this.saveOnUnloadEnabled) { + return; + } + if (!this.unloadQueue.isEmpty()) { long now = System.currentTimeMillis(); + int unloaded = 0; LongList toRemove = null; for (Long2LongMap.Entry entry : unloadQueue.long2LongEntrySet()) { - long index = entry.getLongKey(); - - if (isChunkInUse(index)) { - continue; - } - if (!force) { long time = entry.getLongValue(); - if (maxUnload <= 0) { + if (unloaded > maxUnload) { break; } else if (time > (now - 30000)) { continue; } } + long index = entry.getLongKey(); + if (isChunkInUse(index)) { + continue; + } + if (toRemove == null) toRemove = new LongArrayList(); toRemove.add(index); + unloaded++; } if (toRemove != null) { @@ -3169,7 +3619,6 @@ public void unloadChunks(int maxUnload, boolean force) { if (this.unloadChunk(X, Z, true)) { this.unloadQueue.remove(index); - --maxUnload; } } } @@ -3179,12 +3628,16 @@ public void unloadChunks(int maxUnload, boolean force) { private int lastUnloadIndex; /** - * @param now - * @param allocatedTime - * @param force + * @param now current time + * @param allocatedTime allocated time + * @param force force * @return true if there is allocated time remaining */ private boolean unloadChunks(long now, long allocatedTime, boolean force) { + if (server.holdWorldSave && !force && this.saveOnUnloadEnabled) { + return false; + } + if (!this.unloadQueue.isEmpty()) { boolean result = true; int maxIterations = this.unloadQueue.size(); @@ -3201,12 +3654,6 @@ private boolean unloadChunks(long now, long allocatedTime, boolean force) { } Long2LongMap.Entry entry = iter.next(); - long index = entry.getLongKey(); - - if (isChunkInUse(index)) { - continue; - } - if (!force) { long time = entry.getLongValue(); if (time > (now - 30000)) { @@ -3214,13 +3661,18 @@ private boolean unloadChunks(long now, long allocatedTime, boolean force) { } } + long index = entry.getLongKey(); + if (isChunkInUse(index)) { + continue; + } + if (toUnload == null) toUnload = new LongArrayList(); toUnload.add(index); } if (toUnload != null) { - long[] arr = toUnload.toLongArray(); - for (long index : arr) { + //long[] arr = toUnload.toLongArray(); + for (long index : toUnload) { int X = getHashX(index); int Z = getHashZ(index); if (this.unloadChunk(X, Z, true)) { @@ -3267,6 +3719,8 @@ public void addPlayerMovement(Entity entity, double x, double y, double z, doubl pk.yaw = (float) yaw; pk.headYaw = (float) headYaw; pk.pitch = (float) pitch; + pk.onGround = entity.onGround; + if (entity.riding != null) { pk.ridingEid = entity.riding.getId(); pk.mode = MovePlayerPacket.MODE_PITCH; @@ -3295,7 +3749,7 @@ public boolean isRaining() { public boolean setRaining(boolean raining) { WeatherChangeEvent ev = new WeatherChangeEvent(this, raining); - this.getServer().getPluginManager().callEvent(ev); + this.server.getPluginManager().callEvent(ev); if (ev.isCancelled()) { return false; @@ -3308,7 +3762,7 @@ public boolean setRaining(boolean raining) { if (raining) { pk.evid = LevelEventPacket.EVENT_START_RAIN; - int time = ThreadLocalRandom.current().nextInt(12000) + 12000; + int time = Utils.random.nextInt(12000) + 12000; pk.data = time; setRainTime(time); } else { @@ -3330,18 +3784,18 @@ public void setRainTime(int rainTime) { } public boolean isThundering() { - return isRaining() && this.thundering; + return raining && this.thundering; } public boolean setThundering(boolean thundering) { ThunderChangeEvent ev = new ThunderChangeEvent(this, thundering); - this.getServer().getPluginManager().callEvent(ev); + this.server.getPluginManager().callEvent(ev); if (ev.isCancelled()) { return false; } - if (thundering && !isRaining()) { + if (thundering && !raining) { setRaining(true); } @@ -3351,7 +3805,7 @@ public boolean setThundering(boolean thundering) { // These numbers are from Minecraft if (thundering) { pk.evid = LevelEventPacket.EVENT_START_THUNDER; - int time = ThreadLocalRandom.current().nextInt(12000) + 3600; + int time = Utils.random.nextInt(12000) + 3600; pk.data = time; setThunderTime(time); } else { @@ -3378,8 +3832,7 @@ public void sendWeather(Player[] players) { } LevelEventPacket pk = new LevelEventPacket(); - - if (this.isRaining()) { + if (this.raining) { pk.evid = LevelEventPacket.EVENT_START_RAIN; pk.data = this.rainTime; } else { @@ -3388,6 +3841,7 @@ public void sendWeather(Player[] players) { Server.broadcastPacket(players, pk); + pk = new LevelEventPacket(); if (this.isThundering()) { pk.evid = LevelEventPacket.EVENT_START_THUNDER; pk.data = this.thunderTime; @@ -3411,35 +3865,43 @@ public void sendWeather(Collection players) { this.sendWeather(players.toArray(new Player[0])); } - public DimensionData getDimensionData() { - return this.dimensionData; - } - public int getDimension() { return this.dimensionData.getDimensionId(); } public int getMinBlockY() { - return 0; //this.dimensionData.getMinHeight(); + return this.dimensionData.getMinHeight(); } public int getMaxBlockY() { - return this.getDimension() == DIMENSION_NETHER ? 127 : 255; //this.dimensionData.getMaxHeight(); + return this.dimensionData.getMaxHeight(); } public boolean canBlockSeeSky(Vector3 pos) { return this.getHighestBlockAt(pos.getFloorX(), pos.getFloorZ()) < pos.getY(); } + public boolean canBlockSeeSky(Block block) { + return this.getHighestBlockAt((int) block.getX(), (int) block.getZ()) < block.getY(); + } + public int getStrongPower(Vector3 pos, BlockFace direction) { - return this.getBlock(pos).getStrongPower(direction); + return getStrongPower(null, pos, direction); + } + + private int getStrongPower(FullChunk cachedChunk, Vector3 pos, BlockFace direction) { + return this.getBlock(cachedChunk, pos.getFloorX(), pos.getFloorY(), pos.getFloorZ(), true).getStrongPower(direction); } public int getStrongPower(Vector3 pos) { + return getStrongPower(null, pos); + } + + private int getStrongPower(FullChunk cachedChunk, Vector3 pos) { int i = 0; for (BlockFace face : BlockFace.values()) { - i = Math.max(i, this.getStrongPower(pos.getSideVec(face), face)); + i = Math.max(i, this.getStrongPower(cachedChunk, pos.getSideVec(face), face)); if (i >= 15) { return i; @@ -3447,38 +3909,6 @@ public int getStrongPower(Vector3 pos) { } return i; -// i = Math.max(i, this.getStrongPower(pos.down(), BlockFace.DOWN)); -// -// if (i >= 15) { -// return i; -// } else { -// i = Math.max(i, this.getStrongPower(pos.up(), BlockFace.UP)); -// -// if (i >= 15) { -// return i; -// } else { -// i = Math.max(i, this.getStrongPower(pos.north(), BlockFace.NORTH)); -// -// if (i >= 15) { -// return i; -// } else { -// i = Math.max(i, this.getStrongPower(pos.south(), BlockFace.SOUTH)); -// -// if (i >= 15) { -// return i; -// } else { -// i = Math.max(i, this.getStrongPower(pos.west(), BlockFace.WEST)); -// -// if (i >= 15) { -// return i; -// } else { -// i = Math.max(i, this.getStrongPower(pos.east(), BlockFace.EAST)); -// return i >= 15 ? i : i; -// } -// } -// } -// } -// } } public boolean isSidePowered(Vector3 pos, BlockFace face) { @@ -3486,17 +3916,24 @@ public boolean isSidePowered(Vector3 pos, BlockFace face) { } public int getRedstonePower(Vector3 pos, BlockFace face) { - Block block = this.getBlock(pos); - return block.isNormalBlock() ? this.getStrongPower(pos) : block.getWeakPower(face); + return getRedstonePower(null, pos, face); + } + + private int getRedstonePower(FullChunk cachedChunk, Vector3 pos, BlockFace face) { + Block block = this.getBlock(cachedChunk, pos.getFloorX(), pos.getFloorY(), pos.getFloorZ(), true); + return block.isNormalBlock() ? this.getStrongPower(cachedChunk, pos) : block.getWeakPower(face); } public boolean isBlockPowered(Vector3 pos) { + return isBlockPowered(null, pos); + } + + public boolean isBlockPowered(FullChunk cachedChunk, Vector3 pos) { for (BlockFace face : BlockFace.values()) { - if (this.getRedstonePower(pos.getSideVec(face), face) > 0) { + if (this.getRedstonePower(cachedChunk, pos.getSideVec(face), face) > 0) { return true; } } - return false; } @@ -3519,9 +3956,6 @@ public int isBlockIndirectlyGettingPowered(Vector3 pos) { } public boolean isAreaLoaded(AxisAlignedBB bb) { - if (bb.getMaxY() < 0 || bb.getMinY() >= 256) { - return false; - } int minX = NukkitMath.floorDouble(bb.getMinX()) >> 4; int minZ = NukkitMath.floorDouble(bb.getMinZ()) >> 4; int maxX = NukkitMath.floorDouble(bb.getMaxX()) >> 4; @@ -3538,13 +3972,13 @@ public boolean isAreaLoaded(AxisAlignedBB bb) { return true; } - public int getUpdateLCG() { + private int getUpdateLCG() { return (this.updateLCG = (this.updateLCG * 3) ^ LCG_CONSTANT); } public boolean createPortal(Block target) { if (this.getDimension() == DIMENSION_THE_END) return false; - int maxPortalSize = 23; + final int maxPortalSize = 23; final int targX = target.getFloorX(); final int targY = target.getFloorY(); final int targZ = target.getFloorZ(); @@ -3594,25 +4028,24 @@ public boolean createPortal(Block target) { //find pillar or end of portal to start scan int scanX = targX; int scanY = targY + 1; - int scanZ = targZ; for (int i = 0; i < sizePosX + 1; i++) { //this must be air - if (this.getBlockIdAt(scanX + i, scanY, scanZ) != BlockID.AIR) { + if (this.getBlockIdAt(scanX + i, scanY, targZ) != BlockID.AIR) { return false; } - if (this.getBlockIdAt(scanX + i + 1, scanY, scanZ) == BlockID.OBSIDIAN) { + if (this.getBlockIdAt(scanX + i + 1, scanY, targZ) == BlockID.OBSIDIAN) { scanX += i; break; } } //make sure that the above loop finished - if (this.getBlockIdAt(scanX + 1, scanY, scanZ) != BlockID.OBSIDIAN) { + if (this.getBlockIdAt(scanX + 1, scanY, targZ) != BlockID.OBSIDIAN) { return false; } int innerWidth = 0; - LOOP: for (int i = 0; i < maxPortalSize - 2; i++) { - int id = this.getBlockIdAt(scanX - i, scanY, scanZ); + LOOP: for (int i = 0; i < 21; i++) { + int id = this.getBlockIdAt(scanX - i, scanY, targZ); switch (id) { case BlockID.AIR: innerWidth++; @@ -3624,8 +4057,8 @@ public boolean createPortal(Block target) { } } int innerHeight = 0; - LOOP: for (int i = 0; i < maxPortalSize - 2; i++) { - int id = this.getBlockIdAt(scanX, scanY + i, scanZ); + LOOP: for (int i = 0; i < 21; i++) { + int id = this.getBlockIdAt(scanX, scanY + i, targZ); switch (id) { case BlockID.AIR: innerHeight++; @@ -3636,9 +4069,9 @@ public boolean createPortal(Block target) { return false; } } - if (!(innerWidth <= maxPortalSize - 2 + if (!(innerWidth <= 21 && innerWidth >= 2 - && innerHeight <= maxPortalSize - 2 + && innerHeight <= 21 && innerHeight >= 3)) { return false; } @@ -3646,18 +4079,18 @@ public boolean createPortal(Block target) { for (int height = 0; height < innerHeight + 1; height++) { if (height == innerHeight) { for (int width = 0; width < innerWidth; width++) { - if (this.getBlockIdAt(scanX - width, scanY + height, scanZ) != BlockID.OBSIDIAN) { + if (this.getBlockIdAt(scanX - width, scanY + height, targZ) != BlockID.OBSIDIAN) { return false; } } } else { - if (this.getBlockIdAt(scanX + 1, scanY + height, scanZ) != BlockID.OBSIDIAN - || this.getBlockIdAt(scanX - innerWidth, scanY + height, scanZ) != BlockID.OBSIDIAN) { + if (this.getBlockIdAt(scanX + 1, scanY + height, targZ) != BlockID.OBSIDIAN + || this.getBlockIdAt(scanX - innerWidth, scanY + height, targZ) != BlockID.OBSIDIAN) { return false; } for (int width = 0; width < innerWidth; width++) { - if (this.getBlockIdAt(scanX - width, scanY + height, scanZ) != BlockID.AIR) { + if (this.getBlockIdAt(scanX - width, scanY + height, targZ) != BlockID.AIR) { return false; } } @@ -3666,36 +4099,34 @@ public boolean createPortal(Block target) { for (int height = 0; height < innerHeight; height++) { for (int width = 0; width < innerWidth; width++) { - this.setBlock(new Vector3(scanX - width, scanY + height, scanZ), Block.get(BlockID.NETHER_PORTAL)); + this.setBlock(new Vector3(scanX - width, scanY + height, targZ), Block.get(BlockID.NETHER_PORTAL)); } } - this.addLevelSoundEvent(target, LevelSoundEventPacket.SOUND_IGNITE); return true; } else if (sizeZ >= 2 && sizeZ <= maxPortalSize) { //start scan from 1 block above base //find pillar or end of portal to start scan - int scanX = targX; int scanY = targY + 1; int scanZ = targZ; for (int i = 0; i < sizePosZ + 1; i++) { //this must be air - if (this.getBlockIdAt(scanX, scanY, scanZ + i) != BlockID.AIR) { + if (this.getBlockIdAt(targX, scanY, scanZ + i) != BlockID.AIR) { return false; } - if (this.getBlockIdAt(scanX, scanY, scanZ + i + 1) == BlockID.OBSIDIAN) { + if (this.getBlockIdAt(targX, scanY, scanZ + i + 1) == BlockID.OBSIDIAN) { scanZ += i; break; } } //make sure that the above loop finished - if (this.getBlockIdAt(scanX, scanY, scanZ + 1) != BlockID.OBSIDIAN) { + if (this.getBlockIdAt(targX, scanY, scanZ + 1) != BlockID.OBSIDIAN) { return false; } int innerWidth = 0; - LOOP: for (int i = 0; i < maxPortalSize - 2; i++) { - int id = this.getBlockIdAt(scanX, scanY, scanZ - i); + LOOP: for (int i = 0; i < 21; i++) { + int id = this.getBlockIdAt(targX, scanY, scanZ - i); switch (id) { case BlockID.AIR: innerWidth++; @@ -3707,8 +4138,8 @@ public boolean createPortal(Block target) { } } int innerHeight = 0; - LOOP: for (int i = 0; i < maxPortalSize - 2; i++) { - int id = this.getBlockIdAt(scanX, scanY + i, scanZ); + LOOP: for (int i = 0; i < 21; i++) { + int id = this.getBlockIdAt(targX, scanY + i, scanZ); switch (id) { case BlockID.AIR: innerHeight++; @@ -3719,9 +4150,9 @@ public boolean createPortal(Block target) { return false; } } - if (!(innerWidth <= maxPortalSize - 2 + if (!(innerWidth <= 21 && innerWidth >= 2 - && innerHeight <= maxPortalSize - 2 + && innerHeight <= 21 && innerHeight >= 3)) { return false; } @@ -3729,18 +4160,18 @@ public boolean createPortal(Block target) { for (int height = 0; height < innerHeight + 1; height++) { if (height == innerHeight) { for (int width = 0; width < innerWidth; width++) { - if (this.getBlockIdAt(scanX, scanY + height, scanZ - width) != BlockID.OBSIDIAN) { + if (this.getBlockIdAt(targX, scanY + height, scanZ - width) != BlockID.OBSIDIAN) { return false; } } } else { - if (this.getBlockIdAt(scanX, scanY + height, scanZ + 1) != BlockID.OBSIDIAN - || this.getBlockIdAt(scanX, scanY + height, scanZ - innerWidth) != BlockID.OBSIDIAN) { + if (this.getBlockIdAt(targX, scanY + height, scanZ + 1) != BlockID.OBSIDIAN + || this.getBlockIdAt(targX, scanY + height, scanZ - innerWidth) != BlockID.OBSIDIAN) { return false; } for (int width = 0; width < innerWidth; width++) { - if (this.getBlockIdAt(scanX, scanY + height, scanZ - width) != BlockID.AIR) { + if (this.getBlockIdAt(targX, scanY + height, scanZ - width) != BlockID.AIR) { return false; } } @@ -3749,64 +4180,95 @@ public boolean createPortal(Block target) { for (int height = 0; height < innerHeight; height++) { for (int width = 0; width < innerWidth; width++) { - this.setBlock(new Vector3(scanX, scanY + height, scanZ - width), Block.get(BlockID.NETHER_PORTAL)); + this.setBlock(new Vector3(targX, scanY + height, scanZ - width), Block.get(BlockID.NETHER_PORTAL)); } } - this.addLevelSoundEvent(target, LevelSoundEventPacket.SOUND_IGNITE); return true; } return false; } -// private static void orderGetRidings(Entity entity, LongSet set) { -// if (entity.riding != null) { -// if(!set.add(entity.riding.getId())) { -// throw new RuntimeException("Circular entity link detected (id = "+entity.riding.getId()+")"); -// } -// orderGetRidings(entity.riding, set); -// } -// } -// -// public List orderChunkEntitiesForSpawn(int chunkX, int chunkZ) { -// return orderChunkEntitiesForSpawn(getChunk(chunkX, chunkZ, false)); -// } -// -// public List orderChunkEntitiesForSpawn(BaseFullChunk chunk) { -// Comparator comparator = (o1, o2) -> { -// if (o1.riding == null) { -// if(o2 == null) { -// return 0; -// } -// -// return -1; -// } -// -// if (o2.riding == null) { -// return 1; -// } -// -// LongSet ridings = new LongOpenHashSet(); -// orderGetRidings(o1, ridings); -// -// if(ridings.contains(o2.getId())) { -// return 1; -// } -// -// ridings.clear(); -// orderGetRidings(o2, ridings); -// -// if(ridings.contains(o1.getId())) { -// return -1; -// } -// -// return 0; -// }; -// -// List sorted = new ArrayList<>(chunk.getEntities().values()); -// sorted.sort(comparator); -// -// return sorted; -// } + public Position calculatePortalMirror(Vector3 portal) { + double x; + double y; + double z; + + if (this.getDimension() == DIMENSION_NETHER) { + x = Math.floor(portal.getFloorX() << 3); + y = NukkitMath.clamp(EnumLevel.mRound32(portal.getFloorY()), 70, 256 - 10); + z = Math.floor(portal.getFloorZ() << 3); + + return new Position(x, y, z, Server.getInstance().getDefaultLevel()); + } else { + Level nether = Server.getInstance().getLevelByName("nether"); + if (nether == null) { + return null; + } + + x = Math.floor(portal.getFloorX() >> 3); + y = NukkitMath.clamp(EnumLevel.mRound32(portal.getFloorY()), 70, 128 - 10); + z = Math.floor(portal.getFloorZ() >> 3); + + return new Position(x, y, z, nether); + } + } + + public void setGeneratorTaskFactory(GeneratorTaskFactory factory) { + if (factory == null) { + throw new NullPointerException("GeneratorTaskFactory can not be null!"); + } + this.generatorTaskFactory = factory; + } + + public boolean isBlockWaterloggedAt(FullChunk chunk, int x, int y, int z) { + if (chunk == null || y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return false; + } + int block = chunk.getBlockId(x & 0x0f, y, z & 0x0f, Block.LAYER_WATERLOGGED); + return Block.isWater(block); + } + + @Override + public String toString() { + return "Level@" + Integer.toHexString(hashCode()) + "[" + this.folderName + ']'; + } + + public void asyncChunk(BaseChunk chunk, long timestamp, int x, int z) { + this.asyncChunkThread.queue(chunk, timestamp, x, z, this.dimensionData); + } + + public PersistentDataContainer getPersistentDataContainer(Vector3 position) { + return this.getPersistentDataContainer(position, false); + } + + public PersistentDataContainer getPersistentDataContainer(Vector3 position, boolean create) { + BlockEntity blockEntity = this.getBlockEntity(position); + if (blockEntity != null) { + return blockEntity.getPersistentDataContainer(); + } + + if (create) { + CompoundTag compound = BlockEntity.getDefaultCompound(position, BlockEntity.PERSISTENT_CONTAINER); + blockEntity = BlockEntity.createBlockEntity(BlockEntity.PERSISTENT_CONTAINER, this.getChunk(position.getChunkX(), position.getChunkZ()), compound); + + if (blockEntity == null) { + throw new IllegalStateException("Failed to create persistent container block entity at " + position); + } + return blockEntity.getPersistentDataContainer(); + } + + return new DelegatePersistentDataContainer() { + @Override + protected PersistentDataContainer createDelegate() { + return getPersistentDataContainer(position, true); + } + }; + } + + public boolean hasPersistentDataContainer(Vector3 position) { + BlockEntity blockEntity = this.getBlockEntity(position); + return blockEntity != null && blockEntity.hasPersistentDataContainer(); + } } diff --git a/src/main/java/cn/nukkit/level/LevelProviderConverter.java b/src/main/java/cn/nukkit/level/LevelProviderConverter.java deleted file mode 100644 index 51e78cefe7a..00000000000 --- a/src/main/java/cn/nukkit/level/LevelProviderConverter.java +++ /dev/null @@ -1,141 +0,0 @@ -package cn.nukkit.level; - -import cn.nukkit.level.format.FullChunk; -import cn.nukkit.level.format.LevelProvider; -import cn.nukkit.level.format.anvil.Anvil; -import cn.nukkit.level.format.anvil.Chunk; -import cn.nukkit.level.format.generic.BaseFullChunk; -import cn.nukkit.level.format.generic.ChunkConverter; -import cn.nukkit.level.format.leveldb.LevelDB; -import cn.nukkit.level.format.mcregion.McRegion; -import cn.nukkit.level.format.mcregion.RegionLoader; -import cn.nukkit.nbt.NBTIO; -import cn.nukkit.nbt.tag.CompoundTag; -import cn.nukkit.utils.LevelException; -import cn.nukkit.utils.Utils; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.ByteOrder; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -class LevelProviderConverter { - - private LevelProvider provider; - private Class toClass; - private Level level; - private String path; - - LevelProviderConverter(Level level, String path) { - this.level = level; - this.path = path; - } - - LevelProviderConverter from(LevelProvider provider) { - if (!(provider instanceof McRegion) && !(provider instanceof LevelDB)) { - throw new IllegalArgumentException("From type can be only McRegion or LevelDB"); - } - this.provider = provider; - return this; - } - - LevelProviderConverter to(Class toClass) { - if (toClass != Anvil.class) { - throw new IllegalArgumentException("To type can be only Anvil"); - } - this.toClass = toClass; - return this; - } - - LevelProvider perform() throws IOException { - new File(path).mkdir(); - File dat = new File(provider.getPath(), "level.dat.old"); - new File(provider.getPath(), "level.dat").renameTo(dat); - Utils.copyFile(dat, new File(path, "level.dat")); - LevelProvider result; - try { - if (provider instanceof LevelDB) { - try (FileInputStream stream = new FileInputStream(path + "level.dat")) { - stream.skip(8); - CompoundTag levelData = NBTIO.read(stream, ByteOrder.LITTLE_ENDIAN); - if (levelData != null) { - NBTIO.writeGZIPCompressed(new CompoundTag().putCompound("Data", levelData), new FileOutputStream(path + "level.dat")); - } else { - throw new IOException("LevelData can not be null"); - } - } catch (IOException e) { - throw new LevelException("Invalid level.dat"); - } - } - result = toClass.getConstructor(Level.class, String.class).newInstance(level, path); - } catch (Exception e) { - throw new RuntimeException(e); - } - if (toClass == Anvil.class) { - if (provider instanceof McRegion) { - new File(path, "region").mkdir(); - for (File file : new File(provider.getPath() + "region/").listFiles()) { - Matcher m = Pattern.compile("-?\\d+").matcher(file.getName()); - int regionX, regionZ; - try { - if (m.find()) { - regionX = Integer.parseInt(m.group()); - } else continue; - if (m.find()) { - regionZ = Integer.parseInt(m.group()); - } else continue; - } catch (NumberFormatException e) { - continue; - } - RegionLoader region = new RegionLoader(provider, regionX, regionZ); - for (Integer index : region.getLocationIndexes()) { - int chunkX = index & 0x1f; - int chunkZ = index >> 5; - BaseFullChunk old = region.readChunk(chunkX, chunkZ); - if (old == null) continue; - int x = (regionX << 5) | chunkX; - int z = (regionZ << 5) | chunkZ; - FullChunk chunk = new ChunkConverter(result) - .from(old) - .to(Chunk.class) - .perform(); - result.saveChunk(x, z, chunk); - } - region.close(); - } - } - if (provider instanceof LevelDB) { - new File(path, "region").mkdir(); - for (byte[] key : ((LevelDB) provider).getTerrainKeys()) { - int x = getChunkX(key); - int z = getChunkZ(key); - BaseFullChunk old = ((LevelDB) provider).readChunk(x, z); - FullChunk chunk = new ChunkConverter(result) - .from(old) - .to(Chunk.class) - .perform(); - result.saveChunk(x, z, chunk); - } - } - result.doGarbageCollection(); - } - return result; - } - - private static int getChunkX(byte[] key) { - return (key[3] << 24) | - (key[2] << 16) | - (key[1] << 8) | - key[0]; - } - - private static int getChunkZ(byte[] key) { - return (key[7] << 24) | - (key[6] << 16) | - (key[5] << 8) | - key[4]; - } -} diff --git a/src/main/java/cn/nukkit/level/ListChunkManager.java b/src/main/java/cn/nukkit/level/ListChunkManager.java index 1df86a9a595..8c2c1310443 100644 --- a/src/main/java/cn/nukkit/level/ListChunkManager.java +++ b/src/main/java/cn/nukkit/level/ListChunkManager.java @@ -1,6 +1,7 @@ package cn.nukkit.level; import cn.nukkit.block.Block; +import cn.nukkit.block.BlockLayer; import cn.nukkit.level.format.generic.BaseFullChunk; import java.util.ArrayList; @@ -9,8 +10,8 @@ public class ListChunkManager implements ChunkManager { - private ChunkManager parent; - private List blocks; + private final ChunkManager parent; + private final List blocks; public ListChunkManager(ChunkManager parent) { this.parent = parent; @@ -18,23 +19,17 @@ public ListChunkManager(ChunkManager parent) { } @Override - public int getBlockIdAt(int x, int y, int z) { - Optional optionalBlock = this.blocks.stream().filter(block -> block.getFloorX() == x && block.getFloorY() == y && block.getFloorZ() == z).findAny(); - return optionalBlock.map(Block::getId).orElseGet(() -> this.parent.getBlockIdAt(x, y, z)); + public int getBlockIdAt(int x, int y, int z, BlockLayer layer) { + Optional optionalBlock = this.blocks.stream().filter(block -> block.getFloorX() == x && block.getFloorY() == y && block.getFloorZ() == z && block.getLayer() == layer).findAny(); + return optionalBlock.map(Block::getId).orElseGet(() -> this.parent.getBlockIdAt(x, y, z, layer)); } @Override - public void setBlockFullIdAt(int x, int y, int z, int fullId) { - this.blocks.removeIf(block -> block.getFloorX() == x && block.getFloorY() == y && block.getFloorZ() == z); - this.blocks.add(Block.get(fullId, null, x, y, z)); - } - - @Override - public void setBlockIdAt(int x, int y, int z, int id) { - Optional optionalBlock = this.blocks.stream().filter(block -> block.getFloorX() == x && block.getFloorY() == y && block.getFloorZ() == z).findAny(); - Block block = optionalBlock.orElse(Block.get(this.getBlockIdAt(x, y, z), this.getBlockDataAt(x, y, z), new Position(x, y, z))); + public void setBlockIdAt(int x, int y, int z, BlockLayer layer, int id) { + Optional optionalBlock = this.blocks.stream().filter(block -> block.getFloorX() == x && block.getFloorY() == y && block.getFloorZ() == z && block.getLayer() == layer).findAny(); + Block block = optionalBlock.orElse(Block.get(this.getBlockIdAt(x, y, z, layer), this.getBlockDataAt(x, y, z, layer), new Position(x, y, z), layer)); this.blocks.remove(block); - this.blocks.add(Block.get(this.getBlockIdAt(x, y, z), this.getBlockDataAt(x, y, z), new Position(x, y, z))); + this.blocks.add(Block.get(this.getBlockIdAt(x, y, z, layer), this.getBlockDataAt(x, y, z, layer), new Position(x, y, z), layer)); } @Override @@ -44,20 +39,38 @@ public void setBlockAt(int x, int y, int z, int id, int data) { } @Override - public int getBlockDataAt(int x, int y, int z) { - Optional optionalBlock = this.blocks.stream().filter(block -> block.getFloorX() == x && block.getFloorY() == y && block.getFloorZ() == z).findAny(); - return optionalBlock.map(Block::getDamage).orElseGet(() -> this.parent.getBlockDataAt(x, y, z)); + public void setBlockFullIdAt(int x, int y, int z, BlockLayer layer, int fullId) { + this.blocks.removeIf(block -> block.getFloorX() == x && block.getFloorY() == y && block.getFloorZ() == z && block.getLayer() == layer); + this.blocks.add(Block.get(fullId, null, x, y, z, layer)); + } + + @Override + public int getBlockDataAt(int x, int y, int z, BlockLayer layer) { + Optional optionalBlock = this.blocks.stream().filter(block -> block.getFloorX() == x && block.getFloorY() == y && block.getFloorZ() == z && block.getLayer() == layer).findAny(); + return optionalBlock.map(Block::getDamage).orElseGet(() -> this.parent.getBlockDataAt(x, y, z, layer)); } @Override - public void setBlockDataAt(int x, int y, int z, int data) { - Optional optionalBlock = this.blocks.stream().filter(block -> block.getFloorX() == x && block.getFloorY() == y && block.getFloorZ() == z).findAny(); - Block block = optionalBlock.orElse(Block.get(this.getBlockIdAt(x, y, z), this.getBlockDataAt(x, y, z), new Position(x, y, z))); + public void setBlockDataAt(int x, int y, int z, BlockLayer layer, int data) { + Optional optionalBlock = this.blocks.stream().filter(block -> block.getFloorX() == x && block.getFloorY() == y && block.getFloorZ() == z && block.getLayer() == layer).findAny(); + Block block = optionalBlock.orElse(Block.get(this.getBlockIdAt(x, y, z, layer), this.getBlockDataAt(x, y, z, layer), new Position(x, y, z), layer)); this.blocks.remove(block); block.setDamage(data); this.blocks.add(block); } + @Override + public boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int id) { + return this.setBlockAtLayer(x, y, z, layer, id, 0); + } + + @Override + public boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int id, int data) { + this.blocks.removeIf(block -> block.getFloorX() == x && block.getFloorY() == y && block.getFloorZ() == z && block.getLayer() == layer); + this.blocks.add(Block.get(id, data, new Position(x, y, z), layer)); + return true; + } + @Override public BaseFullChunk getChunk(int chunkX, int chunkZ) { return this.parent.getChunk(chunkX, chunkZ); @@ -81,5 +94,4 @@ public long getSeed() { public List getBlocks() { return this.blocks; } - } diff --git a/src/main/java/cn/nukkit/level/Location.java b/src/main/java/cn/nukkit/level/Location.java index baa119cc08d..d473c0fba79 100644 --- a/src/main/java/cn/nukkit/level/Location.java +++ b/src/main/java/cn/nukkit/level/Location.java @@ -4,7 +4,7 @@ import cn.nukkit.utils.LevelException; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class Location extends Position { @@ -26,19 +26,19 @@ public Location(double x, double y) { } public Location(double x, double y, double z) { - this(x, y, z, 0); + this(x, y, z, 0, 0, 0, null); } public Location(double x, double y, double z, Level level) { - this(x, y, z, 0, 0, level); + this(x, y, z, 0, 0, 0, level); } public Location(double x, double y, double z, double yaw) { - this(x, y, z, yaw, 0); + this(x, y, z, yaw, 0, 0, null); } public Location(double x, double y, double z, double yaw, double pitch) { - this(x, y, z, yaw, pitch, null); + this(x, y, z, yaw, pitch, 0, null); } public Location(double x, double y, double z, double yaw, double pitch, Level level) { @@ -60,19 +60,19 @@ public Location(double x, double y, double z, double yaw, double pitch, double h } public static Location fromObject(Vector3 pos) { - return fromObject(pos, null, 0.0f, 0.0f); + return fromObject(pos, null, 0.0f, 0.0f, 0.0f); } public static Location fromObject(Vector3 pos, Level level) { - return fromObject(pos, level, 0.0f, 0.0f); + return fromObject(pos, level, 0.0f, 0.0f, 0.0f); } public static Location fromObject(Vector3 pos, Level level, double yaw) { - return fromObject(pos, level, yaw, 0.0f); + return fromObject(pos, level, yaw, 0.0f, 0.0f); } public static Location fromObject(Vector3 pos, Level level, double yaw, double pitch) { - return new Location(pos.x, pos.y, pos.z, yaw, pitch, (level == null) ? ((pos instanceof Position) ? ((Position) pos).level : null) : level); + return fromObject(pos, level, yaw, pitch, 0.0f); } public static Location fromObject(Vector3 pos, Level level, double yaw, double pitch, double headYaw) { @@ -91,9 +91,30 @@ public double getHeadYaw() { return this.headYaw; } + public Location setYaw(double yaw) { + this.yaw = yaw; + return this; + } + + public Location setBothYaw(double yaw) { + this.yaw = yaw; + this.headYaw = yaw; + return this; + } + + public Location setPitch(double pitch) { + this.pitch = pitch; + return this; + } + + public Location setHeadYaw(double headYaw) { + this.headYaw = headYaw; + return this; + } + @Override public String toString() { - return "Location (level=" + (this.isValid() ? this.getLevel().getName() : "null") + ", x=" + this.x + ", y=" + this.y + ", z=" + this.z + ", yaw=" + this.yaw + ", pitch=" + this.pitch + ", headYaw=" + this.headYaw + ")"; + return "Location(level=" + (this.isValid() ? this.getLevel().getName() : "null") + ", x=" + this.x + ", y=" + this.y + ", z=" + this.z + ", yaw=" + this.yaw + ", pitch=" + this.pitch + ", headYaw=" + this.headYaw + ')'; } @Override @@ -178,8 +199,8 @@ public Location abs() { } public Vector3 getDirectionVector() { - double pitch = ((getPitch() + 90) * Math.PI) / 180; - double yaw = ((getYaw() + 90) * Math.PI) / 180; + double pitch = ((this.pitch + 90) * Math.PI) / 180; + double yaw = ((this.yaw + 90) * Math.PI) / 180; double x = Math.sin(pitch) * Math.cos(yaw); double z = Math.sin(pitch) * Math.sin(yaw); double y = Math.cos(pitch); diff --git a/src/main/java/cn/nukkit/level/MovingObjectPosition.java b/src/main/java/cn/nukkit/level/MovingObjectPosition.java index b65ad226e6d..8f1cc5a47ab 100644 --- a/src/main/java/cn/nukkit/level/MovingObjectPosition.java +++ b/src/main/java/cn/nukkit/level/MovingObjectPosition.java @@ -4,7 +4,7 @@ import cn.nukkit.math.Vector3; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class MovingObjectPosition { diff --git a/src/main/java/cn/nukkit/level/ParticleEffect.java b/src/main/java/cn/nukkit/level/ParticleEffect.java index dde4da6509a..5f08c259d53 100644 --- a/src/main/java/cn/nukkit/level/ParticleEffect.java +++ b/src/main/java/cn/nukkit/level/ParticleEffect.java @@ -1,6 +1,7 @@ package cn.nukkit.level; public enum ParticleEffect { + ARROWSPELL("minecraft:arrow_spell_emitter"), BALLOON_GAS("minecraft:balloon_gas_particle"), BASIC_BUBBLE("minecraft:basic_bubble_particle"), diff --git a/src/main/java/cn/nukkit/level/Position.java b/src/main/java/cn/nukkit/level/Position.java index f128d93155f..5ee0e5a17a5 100644 --- a/src/main/java/cn/nukkit/level/Position.java +++ b/src/main/java/cn/nukkit/level/Position.java @@ -1,16 +1,18 @@ package cn.nukkit.level; import cn.nukkit.block.Block; +import cn.nukkit.block.BlockLayer; import cn.nukkit.level.format.FullChunk; import cn.nukkit.math.BlockFace; import cn.nukkit.math.Vector3; import cn.nukkit.utils.LevelException; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class Position extends Vector3 { + public Level level; public Position() { @@ -78,7 +80,7 @@ public Position getSide(BlockFace face, int step) { @Override public String toString() { - return "Position(level=" + (this.isValid() ? this.getLevel().getName() : "null") + ",x=" + this.x + ",y=" + this.y + ",z=" + this.z + ")"; + return "Position(level=" + (this.isValid() ? this.level.getName() : "null") + ",x=" + this.x + ",y=" + this.y + ",z=" + this.z + ')'; } @Override @@ -90,7 +92,12 @@ public Position setComponents(double x, double y, double z) { } public Block getLevelBlock() { - if (this.isValid()) return this.level.getBlock(this); + if (this.isValid()) return this.level.getBlock(this, BlockLayer.NORMAL, true); + else throw new LevelException("Undefined Level reference"); + } + + public Block getLevelBlock(BlockLayer layer) { + if (this.isValid()) return this.level.getBlock(this, layer, true); else throw new LevelException("Undefined Level reference"); } diff --git a/src/main/java/cn/nukkit/level/Sound.java b/src/main/java/cn/nukkit/level/Sound.java index 0ed349b41f0..2328552a3cf 100644 --- a/src/main/java/cn/nukkit/level/Sound.java +++ b/src/main/java/cn/nukkit/level/Sound.java @@ -4,6 +4,7 @@ * @author CreeperFace */ public enum Sound { + AMBIENT_BASALT_DELTAS_ADDITIONS("ambient.basalt_deltas.additions"), AMBIENT_BASALT_DELTAS_LOOP("ambient.basalt_deltas.loop"), AMBIENT_BASALT_DELTAS_MOOD("ambient.basalt_deltas.mood"), diff --git a/src/main/java/cn/nukkit/level/biome/Biome.java b/src/main/java/cn/nukkit/level/biome/Biome.java index c6b4dce2b16..84d45482b37 100644 --- a/src/main/java/cn/nukkit/level/biome/Biome.java +++ b/src/main/java/cn/nukkit/level/biome/Biome.java @@ -5,26 +5,22 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.generator.populator.type.Populator; import cn.nukkit.math.NukkitRandom; +import cn.nukkit.utils.Utils; import com.google.gson.JsonObject; -import com.google.gson.JsonParser; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class Biome implements BlockID { - public static final int MAX_BIOMES = 256; - public static final Biome[] biomes = new Biome[MAX_BIOMES]; + public static final Biome[] biomes = new Biome[256]; public static final List unorderedBiomes = new ObjectArrayList<>(); private static final Int2ObjectMap runtimeId2Identifier = new Int2ObjectOpenHashMap<>(); @@ -34,14 +30,10 @@ public abstract class Biome implements BlockID { private float heightVariation = 0.3f; static { - try (InputStream stream = Biome.class.getClassLoader().getResourceAsStream("biome_id_map.json")) { - JsonObject json = JsonParser.parseReader(new InputStreamReader(stream)).getAsJsonObject(); - for (String identifier : json.keySet()) { - int biomeId = json.get(identifier).getAsInt(); - runtimeId2Identifier.put(biomeId, identifier); - } - } catch (NullPointerException | IOException e) { - throw new AssertionError("Unable to load biome mapping from biome_id_map.json", e); + JsonObject json = Utils.loadJsonResource("biome_id_map.json").getAsJsonObject(); + for (String identifier : json.keySet()) { + int biomeId = json.get(identifier).getAsInt(); + runtimeId2Identifier.put(biomeId, identifier); } } @@ -129,7 +121,7 @@ public float getHeightVariation() { @Override public int hashCode() { - return getId(); + return id; } @Override @@ -137,14 +129,18 @@ public boolean equals(Object obj) { return hashCode() == obj.hashCode(); } - //whether or not water should freeze into ice on generation + /** + * Whether or not water should freeze into ice on generation + * + * @return overhang + */ public boolean isFreezing() { return false; } /** * Whether or not overhangs should generate in this biome (places where solid blocks generate over air) - * + *

* This should probably be used with a custom max elevation or things can look stupid * * @return overhang diff --git a/src/main/java/cn/nukkit/level/biome/BiomeSelector.java b/src/main/java/cn/nukkit/level/biome/BiomeSelector.java index d4fbf007e7e..86ba2c9708a 100644 --- a/src/main/java/cn/nukkit/level/biome/BiomeSelector.java +++ b/src/main/java/cn/nukkit/level/biome/BiomeSelector.java @@ -4,12 +4,11 @@ import cn.nukkit.math.NukkitRandom; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ -//WIP -//do not touch lol public class BiomeSelector { + private final SimplexF temperature; private final SimplexF rainfall; private final SimplexF river; @@ -25,225 +24,387 @@ public BiomeSelector(NukkitRandom random) { } public Biome pickBiome(int x, int z) { - /*double noiseOcean = ocean.noise2D(x, z, true); - double noiseTemp = temperature.noise2D(x, z, true); - double noiseRain = rainfall.noise2D(x, z, true); - if (noiseOcean < -0.15) { - if (noiseOcean < -0.9) { - return EnumBiome.MUSHROOM_ISLAND.biome; - } else { - return EnumBiome.OCEAN.biome; - } - } - double noiseRiver = Math.abs(river.noise2D(x, z, true)); - if (noiseRiver < 0.04) { - return EnumBiome.RIVER.biome; - } - return EnumBiome.OCEAN.biome;*/ - - // > using actual biome selectors in 2018 - //x >>= 6; - //z >>= 6; - - //here's a test for just every biome, for making sure there's no crashes: - //return Biome.unorderedBiomes.get(Math.abs(((int) x >> 5) ^ 6457109 * ((int) z >> 5) ^ 9800471) % Biome.unorderedBiomes.size()); - - //a couple random high primes: 6457109 9800471 7003231 - - //here's a test for mesas - /*boolean doPlateau = ocean.noise2D(x, z, true) < 0f; - boolean doF = rainfall.noise2D(x, z, true) < -0.5f; - if (doPlateau) { - boolean doM = temperature.noise2D(x, z, true) < 0f; - if (doM && doF) { - return EnumBiome.MESA_PLATEAU_F_M.biome; - } else if (doM) { - return EnumBiome.MESA_PLATEAU_M.biome; - } else if (doF) { - return EnumBiome.MESA_PLATEAU_F.biome; - } else { - return EnumBiome.MESA_PLATEAU.biome; - } - } else { - return doF ? EnumBiome.MESA_BRYCE.biome : EnumBiome.MESA.biome; - }*/ - - //here's a test for extreme hills + oceans - /*double noiseOcean = ocean.noise2D(x, z, true); - if (noiseOcean < -0.15f) { - return EnumBiome.OCEAN.biome; - } else if (noiseOcean < -0.19f) { - return EnumBiome.STONE_BEACH.biome; - } else { - boolean plus = temperature.noise2D(x, z, true) < 0f; - boolean m = rainfall.noise2D(x, z, true) < 0f; - if (plus && m) { - return EnumBiome.EXTREME_HILLS_PLUS_M.biome; - } else if (m) { - return EnumBiome.EXTREME_HILLS_M.biome; - } else if (plus) { - return EnumBiome.EXTREME_HILLS_PLUS.biome; - } else { - return EnumBiome.EXTREME_HILLS.biome; - } - }*/ + return this.pickBiome(x, z, 0); + } + public Biome pickBiome(int x, int z, int version) { float noiseOcean = ocean.noise2D(x, z, true); float noiseRiver = river.noise2D(x, z, true); float temperature = this.temperature.noise2D(x, z, true); float rainfall = this.rainfall.noise2D(x, z, true); + EnumBiome biome; - if (noiseOcean < -0.15f) { - if (noiseOcean < -0.91f) { - if (noiseOcean < -0.92f) { - biome = EnumBiome.MUSHROOM_ISLAND; - } else { + + if (version < 2) { + if (noiseOcean < -0.15f) { + if (noiseOcean < -0.65f) { biome = EnumBiome.MUSHROOM_ISLAND_SHORE; + } else { + if (rainfall < 0f) { + if (temperature < -0.4f) { + biome = EnumBiome.FROZEN_OCEAN; + } else if (temperature < 0.5f) { + biome = EnumBiome.OCEAN; + } else { + biome = EnumBiome.WARM_OCEAN; + } + } else { + biome = EnumBiome.DEEP_OCEAN; + } } - } else { - if (rainfall < 0f) { - biome = EnumBiome.OCEAN; + } else if (Math.abs(noiseRiver) < 0.04f) { + if (temperature < -0.4f) { + biome = EnumBiome.FROZEN_RIVER; } else { - biome = EnumBiome.DEEP_OCEAN; + biome = EnumBiome.RIVER; } - } - } else if (Math.abs(noiseRiver) < 0.04f) { - if (temperature < -0.3f) { - biome = EnumBiome.FROZEN_RIVER; } else { - biome = EnumBiome.RIVER; - } - } else { - float hills = this.hills.noise2D(x, z, true); - if (temperature < -0.379f) { - //freezing - if (noiseOcean < -0.12f) { - biome = EnumBiome.COLD_BEACH; - } else if (rainfall < 0f) { - if (hills < -0.1f) { - biome = EnumBiome.COLD_TAIGA; - } else if (hills < 0.5f) { - biome = EnumBiome.COLD_TAIGA_HILLS; + float hills = this.hills.noise2D(x, z, true); + if (temperature < -0.379f) { + // freezing + if (noiseOcean < -0.12f) { + biome = EnumBiome.COLD_BEACH; + } else if (rainfall < 0f) { + if (hills < -0.1f) { + biome = EnumBiome.COLD_TAIGA; + } else if (hills < 0.5f) { + biome = EnumBiome.COLD_TAIGA_HILLS; + } else { + biome = EnumBiome.COLD_TAIGA_M; + } } else { - biome = EnumBiome.COLD_TAIGA_M; + if (hills < 0.7f) { + biome = EnumBiome.ICE_PLAINS; + } else { + biome = EnumBiome.ICE_PLAINS_SPIKES; + } } - } else { - if (hills < 0.7f) { - biome = EnumBiome.ICE_PLAINS; + } else if (noiseOcean < -0.12f) { + biome = EnumBiome.BEACH; + } else if (temperature < 0f) { + // cold + if (hills < 0.2f) { + if (rainfall < -0.5f) { + biome = EnumBiome.EXTREME_HILLS_M; + } else if (rainfall > 0.5f) { + biome = EnumBiome.EXTREME_HILLS_PLUS_M; + } else if (rainfall < 0f) { + biome = EnumBiome.EXTREME_HILLS; + } else { + biome = EnumBiome.EXTREME_HILLS_PLUS; + } } else { - biome = EnumBiome.ICE_PLAINS_SPIKES; + if (rainfall < -0.6) { + biome = EnumBiome.MEGA_TAIGA; + } else if (rainfall > 0.6) { + biome = EnumBiome.MEGA_SPRUCE_TAIGA; + } else if (rainfall < 0.2f) { + biome = EnumBiome.TAIGA; + } else { + biome = EnumBiome.TAIGA_M; + } } - } - } else if (noiseOcean < -0.12f) { - biome = EnumBiome.BEACH; - } else if (temperature < 0f) { - //cold - if (hills < 0.2f) { - if (rainfall < -0.5f) { - biome = EnumBiome.EXTREME_HILLS_M; - } else if (rainfall > 0.5f) { - biome = EnumBiome.EXTREME_HILLS_PLUS_M; - } else if (rainfall < 0f) { - biome = EnumBiome.EXTREME_HILLS; + } else if (temperature < 0.5f) { + // normal + if (temperature < 0.25f) { + if (rainfall < 0f) { + if (noiseOcean < 0f) { + biome = EnumBiome.SUNFLOWER_PLAINS; + } else { + biome = EnumBiome.PLAINS; + } + } else if (rainfall < 0.25f) { + if (noiseOcean < 0f) { + biome = EnumBiome.FLOWER_FOREST; + } else { + biome = EnumBiome.FOREST; + } + } else { + if (noiseOcean < 0f) { + biome = EnumBiome.BIRCH_FOREST_M; + } else { + biome = EnumBiome.BIRCH_FOREST; + } + } } else { - biome = EnumBiome.EXTREME_HILLS_PLUS; + if (rainfall < -0.2f) { + if (noiseOcean < 0f) { + biome = EnumBiome.SWAMPLAND_M; + } else { + biome = EnumBiome.SWAMP; + } + } else if (rainfall > 0.1f) { + if (noiseOcean < 0.155f) { + biome = EnumBiome.JUNGLE_M; + } else { + biome = EnumBiome.JUNGLE; + } + } else { + if (noiseOcean < 0f) { + biome = EnumBiome.ROOFED_FOREST_M; + } else { + biome = EnumBiome.ROOFED_FOREST; + } + } } } else { - if (rainfall < -0.6) { - biome = EnumBiome.MEGA_TAIGA; - } else if (rainfall > 0.6) { - biome = EnumBiome.MEGA_SPRUCE_TAIGA; - } else if (rainfall < 0.2f) { - biome = EnumBiome.TAIGA; - } else { - biome = EnumBiome.TAIGA_M; - } - } - } else if (temperature < 0.5f) { - //normal - if (temperature < 0.25f) { - if (rainfall < 0f) { - if (noiseOcean < 0f){ - biome = EnumBiome.SUNFLOWER_PLAINS; + // hot + if (rainfall < 0f) { + if (noiseOcean < 0f) { + biome = EnumBiome.DESERT_M; + } else if (hills < 0f) { + biome = EnumBiome.DESERT_HILLS; } else { - biome = EnumBiome.PLAINS; + biome = EnumBiome.DESERT; } - } else if (rainfall < 0.25f) { - if (noiseOcean < 0f) { - biome = EnumBiome.FLOWER_FOREST; + } else if (rainfall > 0.4f) { + if (noiseOcean < 0.155f) { + if (hills < 0f) { + biome = EnumBiome.SAVANNA_PLATEAU_M; + } else { + biome = EnumBiome.SAVANNA_M; + } } else { - biome = EnumBiome.FOREST; + if (hills < 0f) { + biome = EnumBiome.SAVANNA_PLATEAU; + } else { + biome = EnumBiome.SAVANNA; + } } } else { - if (noiseOcean < 0f) { - biome = EnumBiome.BIRCH_FOREST_M; + if (noiseOcean < 0f) { + if (hills < 0f) { + biome = EnumBiome.MESA_PLATEAU_F; + } else { + biome = EnumBiome.MESA_PLATEAU_F_M; + } + } else if (hills < 0f) { + if (noiseOcean < 0.2f) { + biome = EnumBiome.MESA_PLATEAU_M; + } else { + biome = EnumBiome.MESA_PLATEAU; + } } else { - biome = EnumBiome.BIRCH_FOREST; + if (noiseOcean < 0.1f) { + biome = EnumBiome.MESA_BRYCE; + } else { + biome = EnumBiome.MESA; + } } } + } + } + } else { + if (noiseOcean < -0.15f) { + if (noiseOcean < -0.65f) { + biome = EnumBiome.MUSHROOM_ISLAND_SHORE; } else { - if (rainfall < -0.2f) { - if (noiseOcean < 0f) { - biome = EnumBiome.SWAMPLAND_M; - } else { - biome = EnumBiome.SWAMP; - } - } else if (rainfall > 0.1f) { - if (noiseOcean < 0.155f) { - biome = EnumBiome.JUNGLE_M; + if (rainfall < 0f) { + if (temperature < -0.45f) { + biome = EnumBiome.FROZEN_OCEAN; + } else if (temperature < -0.15f) { + biome = EnumBiome.COLD_OCEAN; + } else if (temperature < 0.2f) { + biome = EnumBiome.OCEAN; + } else if (temperature < 0.55f) { + biome = EnumBiome.LUKEWARM_OCEAN; } else { - biome = EnumBiome.JUNGLE; + biome = EnumBiome.WARM_OCEAN; } } else { - if (noiseOcean < 0f) { - biome = EnumBiome.ROOFED_FOREST_M; + if (temperature < -0.45f) { + biome = EnumBiome.DEEP_FROZEN_OCEAN; + } else if (temperature < -0.15f) { + biome = EnumBiome.DEEP_COLD_OCEAN; + } else if (temperature < 0.2f) { + biome = EnumBiome.DEEP_OCEAN; + } else if (temperature < 0.55f) { + biome = EnumBiome.DEEP_LUKEWARM_OCEAN; } else { - biome = EnumBiome.ROOFED_FOREST; + biome = EnumBiome.WARM_OCEAN; } } } + } else if (Math.abs(noiseRiver) < 0.04f) { + if (temperature < -0.379f) { + biome = EnumBiome.FROZEN_RIVER; + } else { + biome = EnumBiome.RIVER; + } } else { - //hot - if (rainfall < 0f) { - if (noiseOcean < 0f) { - biome = EnumBiome.DESERT_M; - } else if (hills < 0f) { - biome = EnumBiome.DESERT_HILLS; + float hills = this.hills.noise2D(x, z, true); + if (temperature < -0.379f) { + //freezing + if (noiseOcean < -0.12f) { + biome = EnumBiome.COLD_BEACH; + } else if (rainfall < 0f) { + if (hills < -0.1f) { + biome = EnumBiome.COLD_TAIGA; + } else if (hills < 0.5f) { + biome = EnumBiome.COLD_TAIGA_HILLS; + } else { + biome = EnumBiome.COLD_TAIGA_M; + } } else { - biome = EnumBiome.DESERT; + if (hills < 0) { + biome = EnumBiome.ICE_MOUNTAINS; + } else if (hills < 0.7f) { + biome = EnumBiome.ICE_PLAINS; + } else { + biome = EnumBiome.ICE_PLAINS_SPIKES; + } + } + } else if (noiseOcean < -0.12f) { + //if (hills < -0.2225f) { + // biome = EnumBiome.STONE_BEACH; + //} else { + biome = EnumBiome.BEACH; + //} + } else if (temperature < 0f) { + //cold + if (hills < 0.2f) { + if (rainfall < -0.5f) { + biome = EnumBiome.EXTREME_HILLS_M; + } else if (rainfall > 0.5f) { + biome = EnumBiome.EXTREME_HILLS_PLUS_M; + } else if (rainfall < 0f) { + biome = EnumBiome.EXTREME_HILLS; + } else { + biome = EnumBiome.EXTREME_HILLS_PLUS; + } + } else { + if (rainfall < -0.6f) { + if (hills < 0.6f) { + biome = EnumBiome.MEGA_TAIGA_HILLS; + } else { + biome = EnumBiome.MEGA_TAIGA; + } + } else if (rainfall > 0.6f) { + if (hills < 0.6f) { + biome = EnumBiome.MEGA_SPRUCE_TAIGA_HILLS; + } else { + biome = EnumBiome.MEGA_SPRUCE_TAIGA; + } + } else if (rainfall < 0.2f) { + if (hills < 0.6f) { + biome = EnumBiome.TAIGA_HILLS; + } else { + biome = EnumBiome.TAIGA; + } + } else { + biome = EnumBiome.TAIGA_M; + } } - } else if (rainfall > 0.4f) { - if (noiseOcean < 0.155f) { - if (hills < 0f) { - biome = EnumBiome.SAVANNA_PLATEAU_M; + } else if (temperature < 0.5f) { + //normal + if (temperature < 0.25f) { + if (rainfall < 0f) { + if (noiseOcean < 0f) { + biome = EnumBiome.SUNFLOWER_PLAINS; + } else { + biome = EnumBiome.PLAINS; + } + } else if (rainfall < 0.25f) { + if (noiseOcean < 0f) { + biome = EnumBiome.FLOWER_FOREST; + } else { + if (hills < 0) { + biome = EnumBiome.FOREST_HILLS; + } else { + biome = EnumBiome.FOREST; + } + } } else { - biome = EnumBiome.SAVANNA_M; + if (noiseOcean < 0f) { + if (hills < 0) { + biome = EnumBiome.BIRCH_FOREST_HILLS_M; + } else { + biome = EnumBiome.BIRCH_FOREST_M; + } + } else { + if (hills < 0) { + biome = EnumBiome.BIRCH_FOREST_HILLS; + } else { + biome = EnumBiome.BIRCH_FOREST; + } + } } } else { - if (hills < 0f) { - biome = EnumBiome.SAVANNA_PLATEAU; + if (rainfall < -0.2f) { + if (noiseOcean < 0f) { + biome = EnumBiome.SWAMPLAND_M; + } else { + biome = EnumBiome.SWAMP; + } + } else if (rainfall > 0.1f) { + if (noiseOcean < 0.155f) { + biome = EnumBiome.JUNGLE_M; + } else { + if (hills < 0) { + if (rainfall < 0.2f) { + biome = EnumBiome.BAMBOO_JUNGLE_HILLS; + } else { + biome = EnumBiome.JUNGLE_HILLS; + } + } else { + if (rainfall < 0.2f) { + biome = EnumBiome.BAMBOO_JUNGLE; + } else { + biome = EnumBiome.JUNGLE; + } + } + } } else { - biome = EnumBiome.SAVANNA; + if (noiseOcean < 0f) { + biome = EnumBiome.ROOFED_FOREST_M; + } else { + biome = EnumBiome.ROOFED_FOREST; + } } } } else { - if (noiseOcean < 0f) { - if (hills < 0f) { - biome = EnumBiome.MESA_PLATEAU_F; + //hot + if (rainfall < 0f) { + if (noiseOcean < 0f) { + biome = EnumBiome.DESERT_M; + } else if (hills < 0f) { + biome = EnumBiome.DESERT_HILLS; } else { - biome = EnumBiome.MESA_PLATEAU_F_M; + biome = EnumBiome.DESERT; } - } else if (hills < 0f) { - if (noiseOcean < 0.2f) { - biome = EnumBiome.MESA_PLATEAU_M; + } else if (rainfall > 0.4f) { + if (noiseOcean < 0.155f) { + if (hills < 0f) { + biome = EnumBiome.SAVANNA_PLATEAU_M; + } else { + biome = EnumBiome.SAVANNA_M; + } } else { - biome = EnumBiome.MESA_PLATEAU; + if (hills < 0f) { + biome = EnumBiome.SAVANNA_PLATEAU; + } else { + biome = EnumBiome.SAVANNA; + } } } else { - if (noiseOcean < 0.1f) { - biome = EnumBiome.MESA_BRYCE; + if (noiseOcean < 0f) { + if (hills < 0f) { + biome = EnumBiome.MESA_PLATEAU_F; + } else { + biome = EnumBiome.MESA_PLATEAU_F_M; + } + } else if (hills < 0f) { + if (noiseOcean < 0.2f) { + biome = EnumBiome.MESA_PLATEAU_M; + } else { + biome = EnumBiome.MESA_PLATEAU; + } } else { - biome = EnumBiome.MESA; + if (noiseOcean < 0.1f) { + biome = EnumBiome.MESA_BRYCE; + } else { + biome = EnumBiome.MESA; + } } } } diff --git a/src/main/java/cn/nukkit/level/biome/EnumBiome.java b/src/main/java/cn/nukkit/level/biome/EnumBiome.java index 751aa13a98e..df74740ae60 100644 --- a/src/main/java/cn/nukkit/level/biome/EnumBiome.java +++ b/src/main/java/cn/nukkit/level/biome/EnumBiome.java @@ -1,5 +1,6 @@ package cn.nukkit.level.biome; +import cn.nukkit.level.biome.impl.EndBiome; import cn.nukkit.level.biome.impl.HellBiome; import cn.nukkit.level.biome.impl.beach.BeachBiome; import cn.nukkit.level.biome.impl.beach.ColdBeachBiome; @@ -11,14 +12,17 @@ import cn.nukkit.level.biome.impl.forest.ForestBiome; import cn.nukkit.level.biome.impl.forest.ForestHillsBiome; import cn.nukkit.level.biome.impl.iceplains.IcePlainsBiome; +import cn.nukkit.level.biome.impl.iceplains.IcePlainsHillsBiome; import cn.nukkit.level.biome.impl.iceplains.IcePlainsSpikesBiome; import cn.nukkit.level.biome.impl.jungle.*; import cn.nukkit.level.biome.impl.mesa.*; import cn.nukkit.level.biome.impl.mushroom.MushroomIslandBiome; import cn.nukkit.level.biome.impl.mushroom.MushroomIslandShoreBiome; -import cn.nukkit.level.biome.impl.ocean.DeepOceanBiome; -import cn.nukkit.level.biome.impl.ocean.FrozenOceanBiome; -import cn.nukkit.level.biome.impl.ocean.OceanBiome; +import cn.nukkit.level.biome.impl.nether.BasaltDeltasBiome; +import cn.nukkit.level.biome.impl.nether.CrimsonForestBiome; +import cn.nukkit.level.biome.impl.nether.SoulSandValleyBiome; +import cn.nukkit.level.biome.impl.nether.WarpedForestBiome; +import cn.nukkit.level.biome.impl.ocean.*; import cn.nukkit.level.biome.impl.plains.PlainsBiome; import cn.nukkit.level.biome.impl.plains.SunflowerPlainsBiome; import cn.nukkit.level.biome.impl.river.FrozenRiverBiome; @@ -41,25 +45,28 @@ *

*/ public enum EnumBiome { - OCEAN(0, new OceanBiome()),// + + OCEAN(0, new OceanBiome()), PLAINS(1, new PlainsBiome()), DESERT(2, new DesertBiome()), EXTREME_HILLS(3, new ExtremeHillsBiome()), FOREST(4, new ForestBiome()), TAIGA(5, new TaigaBiome()), SWAMP(6, new SwampBiome()), - RIVER(7, new RiverBiome()),// + RIVER(7, new RiverBiome()), HELL(8, new HellBiome()), - FROZEN_OCEAN(10, new FrozenOceanBiome()), //DOES NOT GENERATE NATUALLY + END(9, new EndBiome()), + FROZEN_OCEAN(10, new FrozenOceanBiome()), FROZEN_RIVER(11, new FrozenRiverBiome()), ICE_PLAINS(12, new IcePlainsBiome()), - MUSHROOM_ISLAND(14, new MushroomIslandBiome()),// + ICE_MOUNTAINS(13, new IcePlainsHillsBiome()), + MUSHROOM_ISLAND(14, new MushroomIslandBiome()), MUSHROOM_ISLAND_SHORE(15, new MushroomIslandShoreBiome()), BEACH(16, new BeachBiome()), DESERT_HILLS(17, new DesertHillsBiome()), FOREST_HILLS(18, new ForestHillsBiome()), TAIGA_HILLS(19, new TaigaHillsBiome()), - EXTREME_HILLS_EDGE(20, new ExtremeHillsEdgeBiome()), //DOES NOT GENERATE NATUALLY + EXTREME_HILLS_EDGE(20, new ExtremeHillsEdgeBiome()), JUNGLE(21, new JungleBiome()), JUNGLE_HILLS(22, new JungleHillsBiome()), JUNGLE_EDGE(23, new JungleEdgeBiome()), @@ -79,14 +86,24 @@ public enum EnumBiome { MESA(37, new MesaBiome()), MESA_PLATEAU_F(38, new MesaPlateauFBiome()), MESA_PLATEAU(39, new MesaPlateauBiome()), - // All biomes below this comment are mutated variants of existing biomes + WARM_OCEAN(40, new WarmOceanBiome()), + DEEP_WARM_OCEAN(41, new WarmDeepOceanBiome()), + LUKEWARM_OCEAN(42, new LukewarmOceanBiome()), + DEEP_LUKEWARM_OCEAN(43, new LukewarmDeepOceanBiome()), + COLD_OCEAN(44, new ColdOceanBiome()), + DEEP_COLD_OCEAN(45, new ColdDeepOceanBiome()), + NEW_FROZEN_OCEAN(46, new NewFrozenOceanBiome()), + DEEP_FROZEN_OCEAN(47, new FrozenDeepOceanBiome()), + BAMBOO_JUNGLE(48, new BambooJungleBiome()), + BAMBOO_JUNGLE_HILLS(49, new BambooJungleHillsBiome()), + // All biomes below this comment are mutated variants of existing biomes SUNFLOWER_PLAINS(129, new SunflowerPlainsBiome()), DESERT_M(130, new DesertMBiome()), EXTREME_HILLS_M(131, new ExtremeHillsMBiome()), FLOWER_FOREST(132, new FlowerForestBiome()), TAIGA_M(133, new TaigaMBiome()), SWAMPLAND_M(134, new SwamplandMBiome()), - //no, the following jumps in IDs are NOT mistakes + // No, the following jumps in IDs are NOT mistakes ICE_PLAINS_SPIKES(140, new IcePlainsSpikesBiome()), JUNGLE_M(149, new JungleMBiome()), JUNGLE_EDGE_M(151, new JungleEdgeMBiome()), @@ -95,12 +112,18 @@ public enum EnumBiome { ROOFED_FOREST_M(157, new RoofedForestMBiome()), COLD_TAIGA_M(158, new ColdTaigaMBiome()), MEGA_SPRUCE_TAIGA(160, new MegaSpruceTaigaBiome()), + MEGA_SPRUCE_TAIGA_HILLS(161, new MegaSpruceTaigaHillsBiome()), EXTREME_HILLS_PLUS_M(162, new ExtremeHillsPlusMBiome()), SAVANNA_M(163, new SavannaMBiome()), SAVANNA_PLATEAU_M(164, new SavannaPlateauMBiome()), MESA_BRYCE(165, new MesaBryceBiome()), MESA_PLATEAU_F_M(166, new MesaPlateauFMBiome()), - MESA_PLATEAU_M(167, new MesaPlateauMBiome()); + MESA_PLATEAU_M(167, new MesaPlateauMBiome()), + + SOULSAND_VALLEY(178, new SoulSandValleyBiome()), + CRIMSON_FOREST(179, new CrimsonForestBiome()), + WARPED_FOREST(180, new WarpedForestBiome()), + BASALT_DELTAS(181, new BasaltDeltasBiome()); public final int id; public final Biome biome; diff --git a/src/main/java/cn/nukkit/level/biome/impl/EndBiome.java b/src/main/java/cn/nukkit/level/biome/impl/EndBiome.java new file mode 100644 index 00000000000..4eb1c6e6bf7 --- /dev/null +++ b/src/main/java/cn/nukkit/level/biome/impl/EndBiome.java @@ -0,0 +1,20 @@ +package cn.nukkit.level.biome.impl; + +import cn.nukkit.level.biome.Biome; + +public class EndBiome extends Biome { + + public EndBiome() { + + } + + @Override + public String getName() { + return "The End"; + } + + @Override + public boolean canRain() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/level/biome/impl/HellBiome.java b/src/main/java/cn/nukkit/level/biome/impl/HellBiome.java index 02eab20af32..9ba7ad4cc01 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/HellBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/HellBiome.java @@ -1,13 +1,29 @@ package cn.nukkit.level.biome.impl; -import cn.nukkit.level.biome.Biome; +import cn.nukkit.block.Block; +import cn.nukkit.level.biome.type.CoveredBiome; + +public class HellBiome extends CoveredBiome { + + public HellBiome() { + + } -public class HellBiome extends Biome { @Override public String getName() { return "Hell"; } + @Override + public int getSurfaceId(int x, int y, int z) { + return Block.NETHERRACK << Block.DATA_BITS; + } + + @Override + public int getGroundId(int x, int y, int z) { + return Block.NETHERRACK << Block.DATA_BITS; + } + @Override public boolean canRain() { return false; diff --git a/src/main/java/cn/nukkit/level/biome/impl/beach/BeachBiome.java b/src/main/java/cn/nukkit/level/biome/impl/beach/BeachBiome.java index c12b0d9273f..096177c8ff5 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/beach/BeachBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/beach/BeachBiome.java @@ -2,18 +2,22 @@ import cn.nukkit.level.biome.type.SandyBiome; import cn.nukkit.level.generator.populator.impl.PopulatorSugarcane; +import cn.nukkit.level.generator.populator.impl.PopulatorTallSugarcane; /** - * Author: PeratX + * @author PeratX * Nukkit Project */ public class BeachBiome extends SandyBiome { public BeachBiome() { PopulatorSugarcane sugarcane = new PopulatorSugarcane(); - sugarcane.setBaseAmount(0); sugarcane.setRandomAmount(3); this.addPopulator(sugarcane); + PopulatorTallSugarcane tallSugarcane = new PopulatorTallSugarcane(); + tallSugarcane.setRandomAmount(1); + this.addPopulator(tallSugarcane); + this.setBaseHeight(0f); this.setHeightVariation(0.025f); } diff --git a/src/main/java/cn/nukkit/level/biome/impl/beach/ColdBeachBiome.java b/src/main/java/cn/nukkit/level/biome/impl/beach/ColdBeachBiome.java index bd0aa74e941..ed295ac0ed0 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/beach/ColdBeachBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/beach/ColdBeachBiome.java @@ -1,12 +1,10 @@ package cn.nukkit.level.biome.impl.beach; +import cn.nukkit.block.Block; import cn.nukkit.level.biome.type.SandyBiome; -import cn.nukkit.level.generator.populator.impl.WaterIcePopulator; public class ColdBeachBiome extends SandyBiome { public ColdBeachBiome() { - WaterIcePopulator ice = new WaterIcePopulator(); - this.addPopulator(ice); this.setBaseHeight(0f); this.setHeightVariation(0.025f); @@ -14,7 +12,7 @@ public ColdBeachBiome() { @Override public int getCoverId(int x, int z) { - return SNOW_LAYER << 4; + return Block.SNOW_LAYER << Block.DATA_BITS; } @Override diff --git a/src/main/java/cn/nukkit/level/biome/impl/desert/DesertBiome.java b/src/main/java/cn/nukkit/level/biome/impl/desert/DesertBiome.java index a031e538186..85e66256f27 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/desert/DesertBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/desert/DesertBiome.java @@ -5,7 +5,7 @@ import cn.nukkit.level.generator.populator.impl.PopulatorDeadBush; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class DesertBiome extends SandyBiome { diff --git a/src/main/java/cn/nukkit/level/biome/impl/desert/DesertMBiome.java b/src/main/java/cn/nukkit/level/biome/impl/desert/DesertMBiome.java index 0eba5e38ac4..869082be994 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/desert/DesertMBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/desert/DesertMBiome.java @@ -1,7 +1,7 @@ package cn.nukkit.level.biome.impl.desert; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class DesertMBiome extends DesertBiome { diff --git a/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsBiome.java b/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsBiome.java index d54292f9306..4d224e4959f 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsBiome.java @@ -9,7 +9,7 @@ import cn.nukkit.level.generator.populator.impl.PopulatorTree; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project *

* make sure this is touching another extreme hills type or it'll look dumb diff --git a/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsEdgeBiome.java b/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsEdgeBiome.java index 063136fbf1e..aeffaa73288 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsEdgeBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsEdgeBiome.java @@ -1,7 +1,7 @@ package cn.nukkit.level.biome.impl.extremehills; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class ExtremeHillsEdgeBiome extends ExtremeHillsBiome { diff --git a/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsMBiome.java b/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsMBiome.java index df49bc00fc1..6f510a6bb02 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsMBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsMBiome.java @@ -1,10 +1,11 @@ package cn.nukkit.level.biome.impl.extremehills; +import cn.nukkit.block.Block; import cn.nukkit.level.generator.noise.nukkit.f.SimplexF; import cn.nukkit.math.NukkitRandom; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project *

* make sure this is touching another extreme hills type or it'll look dumb @@ -12,8 +13,8 @@ * very smooth hills with flat areas between */ public class ExtremeHillsMBiome extends ExtremeHillsPlusBiome { - private static final SimplexF gravelNoise = new SimplexF(new NukkitRandom(0), 1f, 1 / 4f, 1 / 64f); - private boolean isGravel = false; + + private static final SimplexF gravelNoise = new SimplexF(new NukkitRandom(), 1f, 1 / 4f, 1 / 64f); public ExtremeHillsMBiome() { this(true); @@ -33,7 +34,7 @@ public String getName() { @Override public int getSurfaceId(int x, int y, int z) { - return gravelNoise.noise2D(x, z, true) < -0.75f ? GRAVEL << 4 : super.getSurfaceId(x, y, z); + return gravelNoise.noise2D(x, z, true) < -0.75f ? GRAVEL << Block.DATA_BITS : super.getSurfaceId(x, y, z); } @Override diff --git a/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsPlusBiome.java b/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsPlusBiome.java index 3243a9dd5c7..b93b2e89d2c 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsPlusBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsPlusBiome.java @@ -1,7 +1,7 @@ package cn.nukkit.level.biome.impl.extremehills; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project *

* make sure this is touching another extreme hills type or it'll look dumb diff --git a/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsPlusMBiome.java b/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsPlusMBiome.java index c439866165f..dfb7e190368 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsPlusMBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/extremehills/ExtremeHillsPlusMBiome.java @@ -1,7 +1,7 @@ package cn.nukkit.level.biome.impl.extremehills; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project *

* make sure this is touching another extreme hills type or it'll look dumb @@ -21,9 +21,4 @@ public ExtremeHillsPlusMBiome() { public String getName() { return "Extreme Hills+ M"; } - - @Override - public boolean doesOverhang() { - return false; - } } diff --git a/src/main/java/cn/nukkit/level/biome/impl/extremehills/StoneBeachBiome.java b/src/main/java/cn/nukkit/level/biome/impl/extremehills/StoneBeachBiome.java index f5b192bf217..de7615193e7 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/extremehills/StoneBeachBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/extremehills/StoneBeachBiome.java @@ -10,6 +10,7 @@ * Nearly ertical cliffs, but no overhangs. Height difference is 2-7 near ocean, and pretty much flat everywhere else */ public class StoneBeachBiome extends CoveredBiome { + public StoneBeachBiome() { this.setBaseHeight(0.1f); this.setHeightVariation(0.8f); diff --git a/src/main/java/cn/nukkit/level/biome/impl/forest/FlowerForestBiome.java b/src/main/java/cn/nukkit/level/biome/impl/forest/FlowerForestBiome.java index 714ab73fd31..3fc819f38eb 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/forest/FlowerForestBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/forest/FlowerForestBiome.java @@ -5,7 +5,7 @@ import cn.nukkit.level.generator.populator.impl.PopulatorFlower; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class FlowerForestBiome extends ForestBiome { @@ -19,6 +19,7 @@ public FlowerForestBiome(int type) { //see https://minecraft.gamepedia.com/Flower#Flower_biomes PopulatorFlower flower = new PopulatorFlower(); flower.setBaseAmount(10); + flower.setRandomAmount(10); flower.addType(DANDELION, 0); flower.addType(RED_FLOWER, BlockFlower.TYPE_POPPY); flower.addType(RED_FLOWER, BlockFlower.TYPE_ALLIUM); @@ -40,6 +41,6 @@ public FlowerForestBiome(int type) { @Override public String getName() { - return this.type == TYPE_BIRCH ? "Birch Forest" : "Forest"; + return this.type == TYPE_BIRCH ? "Birch Flower Forest" : "Flower Forest"; } } diff --git a/src/main/java/cn/nukkit/level/biome/impl/forest/ForestBiome.java b/src/main/java/cn/nukkit/level/biome/impl/forest/ForestBiome.java index 8ea91c8c37c..6336c315532 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/forest/ForestBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/forest/ForestBiome.java @@ -2,10 +2,11 @@ import cn.nukkit.block.BlockSapling; import cn.nukkit.level.biome.type.GrassyBiome; +import cn.nukkit.level.generator.populator.impl.PopulatorFallenTree; import cn.nukkit.level.generator.populator.impl.PopulatorTree; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ForestBiome extends GrassyBiome { @@ -25,15 +26,21 @@ public ForestBiome(int type) { this.type = type; PopulatorTree trees = new PopulatorTree(type == TYPE_BIRCH_TALL ? BlockSapling.BIRCH_TALL : BlockSapling.BIRCH); - trees.setBaseAmount(type == TYPE_NORMAL ? 3 : 6); + trees.setBaseAmount(type == TYPE_NORMAL ? 3 : 10); + trees.setRandomAmount(3); this.addPopulator(trees); if (type == TYPE_NORMAL) { - //normal forest biomes have both oak and birch trees + // Normal forest biomes have both oak and birch trees trees = new PopulatorTree(BlockSapling.OAK); - trees.setBaseAmount(3); + trees.setBaseAmount(4); + trees.setRandomAmount(3); this.addPopulator(trees); } + + PopulatorFallenTree fallenTree = new PopulatorFallenTree(); + fallenTree.setType(type); + this.addPopulator(fallenTree); } @Override diff --git a/src/main/java/cn/nukkit/level/biome/impl/forest/ForestHillsBiome.java b/src/main/java/cn/nukkit/level/biome/impl/forest/ForestHillsBiome.java index 90fd136a2ff..658cea5d315 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/forest/ForestHillsBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/forest/ForestHillsBiome.java @@ -1,7 +1,7 @@ package cn.nukkit.level.biome.impl.forest; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class ForestHillsBiome extends ForestBiome { diff --git a/src/main/java/cn/nukkit/level/biome/impl/iceplains/IcePlainsBiome.java b/src/main/java/cn/nukkit/level/biome/impl/iceplains/IcePlainsBiome.java index dbf0754d78a..3ef10332b65 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/iceplains/IcePlainsBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/iceplains/IcePlainsBiome.java @@ -2,10 +2,11 @@ import cn.nukkit.block.BlockSapling; import cn.nukkit.level.biome.type.SnowyBiome; +import cn.nukkit.level.generator.object.tree.ObjectTree; import cn.nukkit.level.generator.populator.impl.PopulatorTree; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class IcePlainsBiome extends SnowyBiome { @@ -13,13 +14,10 @@ public class IcePlainsBiome extends SnowyBiome { public IcePlainsBiome() { super(); - PopulatorTree trees = new PopulatorTree(BlockSapling.SPRUCE); - trees.setBaseAmount(0); + PopulatorTree trees = new PopulatorTree(BlockSapling.SPRUCE + ObjectTree.SNOWY_TREE); trees.setRandomAmount(1); this.addPopulator(trees); - - this.setBaseHeight(0.125f); this.setHeightVariation(0.05f); } diff --git a/src/main/java/cn/nukkit/level/biome/impl/iceplains/IcePlainsHillsBiome.java b/src/main/java/cn/nukkit/level/biome/impl/iceplains/IcePlainsHillsBiome.java new file mode 100644 index 00000000000..f2847500ded --- /dev/null +++ b/src/main/java/cn/nukkit/level/biome/impl/iceplains/IcePlainsHillsBiome.java @@ -0,0 +1,15 @@ +package cn.nukkit.level.biome.impl.iceplains; + +public class IcePlainsHillsBiome extends IcePlainsBiome { + + public IcePlainsHillsBiome() { + super(); + + this.setBaseHeight(0.45f); + this.setHeightVariation(0.3f); + } + + public String getName() { + return "Snowy Mountains"; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/biome/impl/iceplains/IcePlainsSpikesBiome.java b/src/main/java/cn/nukkit/level/biome/impl/iceplains/IcePlainsSpikesBiome.java index a28ced2405d..57cedf2e0af 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/iceplains/IcePlainsSpikesBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/iceplains/IcePlainsSpikesBiome.java @@ -1,12 +1,13 @@ package cn.nukkit.level.biome.impl.iceplains; +import cn.nukkit.block.Block; import cn.nukkit.level.ChunkManager; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.generator.populator.type.Populator; import cn.nukkit.math.NukkitRandom; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class IcePlainsSpikesBiome extends IcePlainsBiome { @@ -20,17 +21,13 @@ public IcePlainsSpikesBiome() { @Override public int getSurfaceId(int x, int y, int z) { - return SNOW_BLOCK << 4; + return Block.SNOW_BLOCK << Block.DATA_BITS; } public String getName() { return "Ice Plains Spikes"; } - @Override - public boolean isFreezing() { - return true; - } /** * @author DaPorkchop_ diff --git a/src/main/java/cn/nukkit/level/biome/impl/jungle/BambooJungleBiome.java b/src/main/java/cn/nukkit/level/biome/impl/jungle/BambooJungleBiome.java new file mode 100644 index 00000000000..4e246d235c1 --- /dev/null +++ b/src/main/java/cn/nukkit/level/biome/impl/jungle/BambooJungleBiome.java @@ -0,0 +1,42 @@ +package cn.nukkit.level.biome.impl.jungle; + +import cn.nukkit.block.Block; +import cn.nukkit.level.biome.type.GrassyBiome; +import cn.nukkit.level.generator.noise.nukkit.f.SimplexF; +import cn.nukkit.level.generator.populator.impl.PopulatorBamboo; +import cn.nukkit.level.generator.populator.impl.PopulatorMelon; +import cn.nukkit.level.generator.populator.impl.tree.JungleTreePopulator; +import cn.nukkit.math.NukkitRandom; + +public class BambooJungleBiome extends GrassyBiome { + + private static final SimplexF podzolNoise = new SimplexF(new NukkitRandom(), 2f, 1 / 4f, 1 / 32f); + + public BambooJungleBiome() { + super(); + + JungleTreePopulator trees = new JungleTreePopulator(); + trees.setBaseAmount(10); + this.addPopulator(trees); + + PopulatorMelon melon = new PopulatorMelon(); + melon.setBaseAmount(-65); + melon.setRandomAmount(70); + this.addPopulator(melon); + + PopulatorBamboo bamboo = new PopulatorBamboo(); + bamboo.setBaseAmount(64); + bamboo.setRandomAmount(64); + this.addPopulator(bamboo); + } + + @Override + public String getName() { + return "Bamboo Jungle"; + } + + @Override + public int getSurfaceId(int x, int y, int z) { + return podzolNoise.noise2D(x, z, true) < 0f ? PODZOL << Block.DATA_BITS : Block.GRASS << Block.DATA_BITS; + } +} diff --git a/src/main/java/cn/nukkit/level/biome/impl/jungle/BambooJungleHillsBiome.java b/src/main/java/cn/nukkit/level/biome/impl/jungle/BambooJungleHillsBiome.java new file mode 100644 index 00000000000..0f8e068f7e1 --- /dev/null +++ b/src/main/java/cn/nukkit/level/biome/impl/jungle/BambooJungleHillsBiome.java @@ -0,0 +1,16 @@ +package cn.nukkit.level.biome.impl.jungle; + +public class BambooJungleHillsBiome extends BambooJungleBiome { + + public BambooJungleHillsBiome() { + super(); + + this.setBaseHeight(0.45f); + this.setHeightVariation(0.3f); + } + + @Override + public String getName() { + return "Bamboo Jungle Hills"; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/biome/impl/jungle/JungleBiome.java b/src/main/java/cn/nukkit/level/biome/impl/jungle/JungleBiome.java index 67f08a40f4a..40ebee75dfd 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/jungle/JungleBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/jungle/JungleBiome.java @@ -1,6 +1,7 @@ package cn.nukkit.level.biome.impl.jungle; import cn.nukkit.level.biome.type.GrassyBiome; +import cn.nukkit.level.generator.populator.impl.PopulatorBamboo; import cn.nukkit.level.generator.populator.impl.PopulatorMelon; import cn.nukkit.level.generator.populator.impl.tree.JungleBigTreePopulator; import cn.nukkit.level.generator.populator.impl.tree.JungleTreePopulator; @@ -14,16 +15,21 @@ public JungleBiome() { JungleTreePopulator trees = new JungleTreePopulator(); trees.setBaseAmount(10); + trees.setRandomAmount(10); this.addPopulator(trees); JungleBigTreePopulator bigTrees = new JungleBigTreePopulator(); - bigTrees.setBaseAmount(6); + bigTrees.setBaseAmount(8); + bigTrees.setRandomAmount(8); this.addPopulator(bigTrees); PopulatorMelon melon = new PopulatorMelon(); - melon.setBaseAmount(-65); - melon.setRandomAmount(70); + melon.setRandomAmount(2); this.addPopulator(melon); + + PopulatorBamboo bamboo = new PopulatorBamboo(); + bamboo.setRandomAmount(2); + this.addPopulator(bamboo); } @Override diff --git a/src/main/java/cn/nukkit/level/biome/impl/jungle/JungleEdgeBiome.java b/src/main/java/cn/nukkit/level/biome/impl/jungle/JungleEdgeBiome.java index 88faf8753ca..620936c8d50 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/jungle/JungleEdgeBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/jungle/JungleEdgeBiome.java @@ -4,9 +4,6 @@ * @author DaPorkchpo_ */ public class JungleEdgeBiome extends JungleBiome { - public JungleEdgeBiome() { - super(); - } @Override public String getName() { diff --git a/src/main/java/cn/nukkit/level/biome/impl/jungle/JungleEdgeMBiome.java b/src/main/java/cn/nukkit/level/biome/impl/jungle/JungleEdgeMBiome.java index e0397a0bfb0..2a53b8cd788 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/jungle/JungleEdgeMBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/jungle/JungleEdgeMBiome.java @@ -3,11 +3,7 @@ /** * @author DaPorkchpo_ */ -//porktodo: this biome has steep cliffs and flat plains public class JungleEdgeMBiome extends JungleEdgeBiome { - public JungleEdgeMBiome() { - super(); - } @Override public String getName() { diff --git a/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaBiome.java b/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaBiome.java index db5ce288e48..a5db08432a3 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaBiome.java @@ -1,5 +1,6 @@ package cn.nukkit.level.biome.impl.mesa; +import cn.nukkit.block.Block; import cn.nukkit.block.BlockSand; import cn.nukkit.level.biome.type.CoveredBiome; import cn.nukkit.level.generator.noise.nukkit.f.SimplexF; @@ -8,7 +9,7 @@ import cn.nukkit.math.NukkitRandom; import java.util.Arrays; -import java.util.Random; +import java.util.SplittableRandom; /** * @author DaPorkchop_ @@ -16,12 +17,13 @@ * Handles the placement of stained clay for all mesa variants */ public class MesaBiome extends CoveredBiome { - static final int[] colorLayer = new int[64]; + + static final int[] colorLayer = new int[64]; static final SimplexF redSandNoise = new SimplexF(new NukkitRandom(937478913), 2f, 1 / 4f, 1 / 4f); - static final SimplexF colorNoise = new SimplexF(new NukkitRandom(193759875), 2f, 1 / 4f, 1 / 32f); + static final SimplexF colorNoise = new SimplexF(new NukkitRandom(193759875), 2f, 1 / 4f, 1 / 32f); static { - Random random = new Random(29864); + SplittableRandom random = new SplittableRandom(29864); Arrays.fill(colorLayer, -1); // hard clay, other values are stained clay setRandomLayerColor(random, 14, 1); // orange @@ -41,20 +43,8 @@ public class MesaBiome extends CoveredBiome { } } - private static void setRandomLayerColor(Random random, int sliceCount, int color) { - for (int i = 0; i < random.nextInt(4) + sliceCount; i++) { - int j = random.nextInt(colorLayer.length); - int k = 0; - while (k < random.nextInt(2) + 1 && j < colorLayer.length) { - colorLayer[j++] = color; - k++; - } - } - } - - private SimplexF moundNoise = new SimplexF(new NukkitRandom(347228794), 2f, 1 / 4f, getMoundFrequency()); protected int moundHeight; - + private final SimplexF moundNoise = new SimplexF(new NukkitRandom(347228794), 2f, 1 / 4f, getMoundFrequency()); public MesaBiome() { PopulatorCactus cactus = new PopulatorCactus(); cactus.setBaseAmount(1); @@ -69,6 +59,17 @@ public MesaBiome() { this.setMoundHeight(17); } + private static void setRandomLayerColor(SplittableRandom random, int sliceCount, int color) { + for (int i = 0; i < random.nextInt(4) + sliceCount; i++) { + int j = random.nextInt(colorLayer.length); + int k = 0; + while (k < random.nextInt(2) + 1 && j < colorLayer.length) { + colorLayer[j++] = color; + k++; + } + } + } + public void setMoundHeight(int height) { this.moundHeight = height; } @@ -81,10 +82,10 @@ public int getSurfaceDepth(int x, int y, int z) { @Override public int getSurfaceId(int x, int y, int z) { if (y < (71 + Math.round((redSandNoise.noise2D(x, z, true) + 1) * 1.5f))) { - return (SAND << 4) | BlockSand.RED; + return (SAND << Block.DATA_BITS) | BlockSand.RED; } else { int meta = colorLayer[(y + Math.round((colorNoise.noise2D(x, z, true) + 1) * 1.5f)) & 0x3F]; - return (meta == -1 ? TERRACOTTA << 4 : STAINED_TERRACOTTA << 4) | Math.max(0, meta); + return (meta == -1 ? TERRACOTTA << Block.DATA_BITS : STAINED_TERRACOTTA << Block.DATA_BITS) | Math.max(0, meta); } } @@ -95,7 +96,7 @@ public int getGroundDepth(int x, int y, int z) { @Override public int getGroundId(int x, int y, int z) { - return RED_SANDSTONE << 4; + return Block.RED_SANDSTONE << Block.DATA_BITS; } @Override @@ -104,7 +105,7 @@ public String getName() { } protected float getMoundFrequency() { - return 1 / 128f; + return 0.0078125f; } @Override diff --git a/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaBryceBiome.java b/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaBryceBiome.java index c3f15c0d46f..2251a2f6fb0 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaBryceBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaBryceBiome.java @@ -4,9 +4,6 @@ * @author DaPorkchop_ */ public class MesaBryceBiome extends MesaBiome { - public MesaBryceBiome() { - super(); - } @Override public String getName() { @@ -15,7 +12,7 @@ public String getName() { @Override protected float getMoundFrequency() { - return 1 / 16f; + return 0.0625f; } @Override diff --git a/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaPlateauFBiome.java b/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaPlateauFBiome.java index 3a5433c70af..716dcefb533 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaPlateauFBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaPlateauFBiome.java @@ -1,5 +1,6 @@ package cn.nukkit.level.biome.impl.mesa; +import cn.nukkit.block.Block; import cn.nukkit.block.BlockSapling; import cn.nukkit.level.generator.populator.impl.PopulatorTree; @@ -18,7 +19,7 @@ public MesaPlateauFBiome() { @Override public int getCoverId(int x, int z) { - return GRASS << 4; + return GRASS << Block.DATA_BITS; } @Override diff --git a/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaPlateauFMBiome.java b/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaPlateauFMBiome.java index 26a8afadab5..e9c46c7454f 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaPlateauFMBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaPlateauFMBiome.java @@ -3,11 +3,7 @@ /** * @author DaPorkchop_ */ -//porktodo: this biome has much smaller and more frequent plateaus than the normal mesa plateau (which is all one giant one) public class MesaPlateauFMBiome extends MesaPlateauFBiome { - public MesaPlateauFMBiome() { - super(); - } @Override public String getName() { diff --git a/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaPlateauMBiome.java b/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaPlateauMBiome.java index dea211ea421..d77a1c92b9d 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaPlateauMBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/mesa/MesaPlateauMBiome.java @@ -3,7 +3,6 @@ /** * @author DaPorkchop_ */ -//porktodo: the plateaus here are smaller and less frequent than in the normal counterpart (which is one giant plateau) public class MesaPlateauMBiome extends MesaBiome { public MesaPlateauMBiome() { super(); @@ -16,11 +15,9 @@ public String getName() { return "Mesa Plateau M"; } - - @Override protected float getMoundFrequency() { - return 1 / 50f; + return 0.02f; } @Override diff --git a/src/main/java/cn/nukkit/level/biome/impl/mushroom/MushroomIslandBiome.java b/src/main/java/cn/nukkit/level/biome/impl/mushroom/MushroomIslandBiome.java index a859e7414eb..284c22463aa 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/mushroom/MushroomIslandBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/mushroom/MushroomIslandBiome.java @@ -1,5 +1,6 @@ package cn.nukkit.level.biome.impl.mushroom; +import cn.nukkit.block.Block; import cn.nukkit.level.biome.type.GrassyBiome; import cn.nukkit.level.generator.populator.impl.MushroomPopulator; @@ -20,6 +21,6 @@ public String getName() { @Override public int getSurfaceId(int x, int y, int z) { - return MYCELIUM << 4; + return Block.MYCELIUM << Block.DATA_BITS; } } diff --git a/src/main/java/cn/nukkit/level/biome/impl/nether/BasaltDeltasBiome.java b/src/main/java/cn/nukkit/level/biome/impl/nether/BasaltDeltasBiome.java new file mode 100644 index 00000000000..19a6fb73b1c --- /dev/null +++ b/src/main/java/cn/nukkit/level/biome/impl/nether/BasaltDeltasBiome.java @@ -0,0 +1,43 @@ +package cn.nukkit.level.biome.impl.nether; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; +import cn.nukkit.level.biome.type.CoveredBiome; +import cn.nukkit.level.generator.object.ore.OreType; +import cn.nukkit.level.generator.populator.impl.PopulatorBasaltDeltaLava; +import cn.nukkit.level.generator.populator.impl.PopulatorBasaltDeltaMagma; +import cn.nukkit.level.generator.populator.impl.PopulatorBasaltDeltaPillar; +import cn.nukkit.level.generator.populator.impl.PopulatorOre; + +public class BasaltDeltasBiome extends CoveredBiome { + + public BasaltDeltasBiome() { + this.addPopulator(new PopulatorOre(BlockID.BASALT, new OreType[]{ + new OreType(Block.get(BlockID.BLACKSTONE), 4, 128, 0, 128, BASALT) + })); + + this.addPopulator(new PopulatorBasaltDeltaLava()); + this.addPopulator(new PopulatorBasaltDeltaMagma()); + this.addPopulator(new PopulatorBasaltDeltaPillar()); + } + + @Override + public String getName() { + return "Basalt Deltas"; + } + + @Override + public int getSurfaceId(int x, int y, int z) { + return Block.BASALT << Block.DATA_BITS; + } + + @Override + public int getGroundId(int x, int y, int z) { + return Block.BASALT << Block.DATA_BITS; + } + + @Override + public boolean canRain() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/level/biome/impl/nether/CrimsonForestBiome.java b/src/main/java/cn/nukkit/level/biome/impl/nether/CrimsonForestBiome.java new file mode 100644 index 00000000000..70fb4b97ea0 --- /dev/null +++ b/src/main/java/cn/nukkit/level/biome/impl/nether/CrimsonForestBiome.java @@ -0,0 +1,36 @@ +package cn.nukkit.level.biome.impl.nether; + +import cn.nukkit.block.Block; +import cn.nukkit.level.biome.type.CoveredBiome; +import cn.nukkit.level.generator.populator.impl.PopulatorCrimsonFungus; +import cn.nukkit.level.generator.populator.impl.PopulatorCrimsonForestGround; +import cn.nukkit.level.generator.populator.impl.PopulatorWeepingVines; + +public class CrimsonForestBiome extends CoveredBiome { + + public CrimsonForestBiome() { + this.addPopulator(new PopulatorCrimsonFungus()); + this.addPopulator(new PopulatorCrimsonForestGround()); + this.addPopulator(new PopulatorWeepingVines()); + } + + @Override + public String getName() { + return "Crimson Forest"; + } + + @Override + public int getSurfaceId(int x, int y, int z) { + return Block.CRIMSON_NYLIUM << Block.DATA_BITS; + } + + @Override + public int getGroundId(int x, int y, int z) { + return Block.NETHERRACK << Block.DATA_BITS; + } + + @Override + public boolean canRain() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/level/biome/impl/nether/SoulSandValleyBiome.java b/src/main/java/cn/nukkit/level/biome/impl/nether/SoulSandValleyBiome.java new file mode 100644 index 00000000000..7604223a781 --- /dev/null +++ b/src/main/java/cn/nukkit/level/biome/impl/nether/SoulSandValleyBiome.java @@ -0,0 +1,39 @@ +package cn.nukkit.level.biome.impl.nether; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; +import cn.nukkit.level.biome.type.CoveredBiome; +import cn.nukkit.level.generator.object.ore.OreType; +import cn.nukkit.level.generator.populator.impl.*; + +public class SoulSandValleyBiome extends CoveredBiome { + + public SoulSandValleyBiome() { + this.addPopulator(new PopulatorOre(BlockID.SOUL_SAND, new OreType[]{ + new OreType(Block.get(SOUL_SOIL), 3, 128, 0, 128, SOUL_SAND) + })); + + this.addPopulator(new PopulatorNetherFire(SOUL_FIRE, SOUL_SOIL)); + this.addPopulator(new PopulatorSoulSandValleyGround()); + } + + @Override + public String getName() { + return "Soul Sand Valley"; + } + + @Override + public int getSurfaceId(int x, int y, int z) { + return Block.SOUL_SAND << Block.DATA_BITS; + } + + @Override + public int getGroundId(int x, int y, int z) { + return Block.SOUL_SAND << Block.DATA_BITS; + } + + @Override + public boolean canRain() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/level/biome/impl/nether/WarpedForestBiome.java b/src/main/java/cn/nukkit/level/biome/impl/nether/WarpedForestBiome.java new file mode 100644 index 00000000000..456be94005f --- /dev/null +++ b/src/main/java/cn/nukkit/level/biome/impl/nether/WarpedForestBiome.java @@ -0,0 +1,36 @@ +package cn.nukkit.level.biome.impl.nether; + +import cn.nukkit.block.Block; +import cn.nukkit.level.biome.type.CoveredBiome; +import cn.nukkit.level.generator.populator.impl.PopulatorTwistingVines; +import cn.nukkit.level.generator.populator.impl.PopulatorWarpedFungus; +import cn.nukkit.level.generator.populator.impl.PopulatorWarpedForestGround; + +public class WarpedForestBiome extends CoveredBiome { + + public WarpedForestBiome() { + this.addPopulator(new PopulatorWarpedFungus()); + this.addPopulator(new PopulatorWarpedForestGround()); + this.addPopulator(new PopulatorTwistingVines()); + } + + @Override + public String getName() { + return "Warped Forest"; + } + + @Override + public int getSurfaceId(int x, int y, int z) { + return Block.WARPED_NYLIUM << Block.DATA_BITS; + } + + @Override + public int getGroundId(int x, int y, int z) { + return Block.NETHERRACK << Block.DATA_BITS; + } + + @Override + public boolean canRain() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/level/biome/impl/ocean/ColdDeepOceanBiome.java b/src/main/java/cn/nukkit/level/biome/impl/ocean/ColdDeepOceanBiome.java new file mode 100644 index 00000000000..24d52b96f3d --- /dev/null +++ b/src/main/java/cn/nukkit/level/biome/impl/ocean/ColdDeepOceanBiome.java @@ -0,0 +1,16 @@ +package cn.nukkit.level.biome.impl.ocean; + +public class ColdDeepOceanBiome extends ColdOceanBiome { + + public ColdDeepOceanBiome() { + super(); + + this.setBaseHeight(-1.8f); + this.setHeightVariation(0.1f); + } + + @Override + public String getName() { + return "Deep Cold Ocean"; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/biome/impl/ocean/ColdOceanBiome.java b/src/main/java/cn/nukkit/level/biome/impl/ocean/ColdOceanBiome.java new file mode 100644 index 00000000000..3a41c4f55a1 --- /dev/null +++ b/src/main/java/cn/nukkit/level/biome/impl/ocean/ColdOceanBiome.java @@ -0,0 +1,13 @@ +package cn.nukkit.level.biome.impl.ocean; + +public class ColdOceanBiome extends OceanBiome { + + public ColdOceanBiome() { + super(); + } + + @Override + public String getName() { + return "Cold Ocean"; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/biome/impl/ocean/DeepOceanBiome.java b/src/main/java/cn/nukkit/level/biome/impl/ocean/DeepOceanBiome.java index d86bbab4146..13c3866d75f 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/ocean/DeepOceanBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/ocean/DeepOceanBiome.java @@ -1,7 +1,7 @@ package cn.nukkit.level.biome.impl.ocean; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class DeepOceanBiome extends OceanBiome { diff --git a/src/main/java/cn/nukkit/level/biome/impl/ocean/FrozenDeepOceanBiome.java b/src/main/java/cn/nukkit/level/biome/impl/ocean/FrozenDeepOceanBiome.java new file mode 100644 index 00000000000..3e0ab866675 --- /dev/null +++ b/src/main/java/cn/nukkit/level/biome/impl/ocean/FrozenDeepOceanBiome.java @@ -0,0 +1,16 @@ +package cn.nukkit.level.biome.impl.ocean; + +public class FrozenDeepOceanBiome extends NewFrozenOceanBiome { + + public FrozenDeepOceanBiome() { + super(); + + this.setBaseHeight(-1.8f); + this.setHeightVariation(0.1f); + } + + @Override + public String getName() { + return "Deep Frozen Ocean"; + } +} diff --git a/src/main/java/cn/nukkit/level/biome/impl/ocean/FrozenOceanBiome.java b/src/main/java/cn/nukkit/level/biome/impl/ocean/FrozenOceanBiome.java index 242dd35c2b4..ee82f379da4 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/ocean/FrozenOceanBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/ocean/FrozenOceanBiome.java @@ -1,9 +1,9 @@ package cn.nukkit.level.biome.impl.ocean; -import cn.nukkit.level.generator.populator.impl.WaterIcePopulator; +import cn.nukkit.block.Block; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project *

* This biome does not generate naturally @@ -11,9 +11,6 @@ public class FrozenOceanBiome extends OceanBiome { public FrozenOceanBiome() { super(); - - WaterIcePopulator ice = new WaterIcePopulator(); - this.addPopulator(ice); } @Override @@ -30,4 +27,9 @@ public boolean isFreezing() { public boolean canRain() { return false; } + + @Override + public int getCoverId(int x, int z) { + return SNOW_LAYER << Block.DATA_BITS; + } } diff --git a/src/main/java/cn/nukkit/level/biome/impl/ocean/LukewarmDeepOceanBiome.java b/src/main/java/cn/nukkit/level/biome/impl/ocean/LukewarmDeepOceanBiome.java new file mode 100644 index 00000000000..a0834fdc252 --- /dev/null +++ b/src/main/java/cn/nukkit/level/biome/impl/ocean/LukewarmDeepOceanBiome.java @@ -0,0 +1,16 @@ +package cn.nukkit.level.biome.impl.ocean; + +public class LukewarmDeepOceanBiome extends LukewarmOceanBiome { + + public LukewarmDeepOceanBiome() { + super(); + + this.setBaseHeight(-1.8f); + this.setHeightVariation(0.1f); + } + + @Override + public String getName() { + return "Deep Lukewarm Ocean"; + } +} diff --git a/src/main/java/cn/nukkit/level/biome/impl/ocean/LukewarmOceanBiome.java b/src/main/java/cn/nukkit/level/biome/impl/ocean/LukewarmOceanBiome.java new file mode 100644 index 00000000000..8eadb71823f --- /dev/null +++ b/src/main/java/cn/nukkit/level/biome/impl/ocean/LukewarmOceanBiome.java @@ -0,0 +1,20 @@ +package cn.nukkit.level.biome.impl.ocean; + +import cn.nukkit.block.Block; + +public class LukewarmOceanBiome extends OceanBiome { + + public LukewarmOceanBiome() { + super(); + } + + @Override + public String getName() { + return "Lukewarm Ocean"; + } + + @Override + public int getGroundId(int x, int y, int z) { + return Block.SAND << Block.DATA_BITS; + } +} diff --git a/src/main/java/cn/nukkit/level/biome/impl/ocean/NewFrozenOceanBiome.java b/src/main/java/cn/nukkit/level/biome/impl/ocean/NewFrozenOceanBiome.java new file mode 100644 index 00000000000..268d17f0678 --- /dev/null +++ b/src/main/java/cn/nukkit/level/biome/impl/ocean/NewFrozenOceanBiome.java @@ -0,0 +1,23 @@ +package cn.nukkit.level.biome.impl.ocean; + +public class NewFrozenOceanBiome extends OceanBiome { + + public NewFrozenOceanBiome() { + super(); + } + + @Override + public String getName() { + return "Frozen Ocean"; + } + + @Override + public boolean isFreezing() { + return true; + } + + @Override + public boolean canRain() { + return false; + } +} diff --git a/src/main/java/cn/nukkit/level/biome/impl/ocean/OceanBiome.java b/src/main/java/cn/nukkit/level/biome/impl/ocean/OceanBiome.java index cda7e9df1ea..12dc994b0a5 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/ocean/OceanBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/ocean/OceanBiome.java @@ -1,15 +1,45 @@ package cn.nukkit.level.biome.impl.ocean; +import cn.nukkit.block.Block; import cn.nukkit.level.biome.type.WateryBiome; +import cn.nukkit.level.generator.populator.impl.PopulatorKelp; +import cn.nukkit.level.generator.populator.impl.PopulatorSeagrass; +import cn.nukkit.level.generator.populator.impl.PopulatorUnderwaterFloor; + +import java.util.Arrays; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class OceanBiome extends WateryBiome { public OceanBiome() { - this.setBaseHeight(-1f); + PopulatorUnderwaterFloor underwaterFloor = new PopulatorUnderwaterFloor(1.0, SAND, 2, 4, 2, Arrays.asList(GRASS, DIRT)); + underwaterFloor.setBaseAmount(3); + this.addPopulator(underwaterFloor); + + PopulatorUnderwaterFloor underwaterFloorClay = new PopulatorUnderwaterFloor(1.0, CLAY_BLOCK, 1, 2, 1, Arrays.asList(DIRT, CLAY_BLOCK)); + underwaterFloorClay.setBaseAmount(1); + this.addPopulator(underwaterFloorClay); + + PopulatorUnderwaterFloor underwaterFloorGravel = new PopulatorUnderwaterFloor(1.0, GRAVEL, 2, 3, 2, Arrays.asList(GRASS, DIRT)); + underwaterFloorGravel.setBaseAmount(1); + this.addPopulator(underwaterFloorGravel); + + if (!(this instanceof FrozenOceanBiome)) { + PopulatorKelp populatorKelp = new PopulatorKelp(); + populatorKelp.setBaseAmount(-135); + populatorKelp.setRandomAmount(180); + this.addPopulator(populatorKelp); + } + + PopulatorSeagrass populatorSeagrass = new PopulatorSeagrass(); + populatorSeagrass.setBaseAmount(24); + populatorSeagrass.setRandomAmount(24); + this.addPopulator(populatorSeagrass); + + this.setBaseHeight(-1.0f); this.setHeightVariation(0.1f); } @@ -18,7 +48,18 @@ public String getName() { return "Ocean"; } - public int getGroundId(int y) { - return GRAVEL << 4; + @Override + public int getGroundId(int x, int y, int z) { + return Block.GRAVEL << Block.DATA_BITS; + } + + @Override + public int getSurfaceDepth(int x, int y, int z) { + return 1; + } + + @Override + public int getSurfaceId(int x, int y, int z) { + return SAND << Block.DATA_BITS; } } diff --git a/src/main/java/cn/nukkit/level/biome/impl/ocean/WarmDeepOceanBiome.java b/src/main/java/cn/nukkit/level/biome/impl/ocean/WarmDeepOceanBiome.java new file mode 100644 index 00000000000..cf88925814d --- /dev/null +++ b/src/main/java/cn/nukkit/level/biome/impl/ocean/WarmDeepOceanBiome.java @@ -0,0 +1,16 @@ +package cn.nukkit.level.biome.impl.ocean; + +public class WarmDeepOceanBiome extends WarmOceanBiome { + + public WarmDeepOceanBiome() { + super(); + + this.setBaseHeight(-1.8f); + this.setHeightVariation(0.1f); + } + + @Override + public String getName() { + return "Deep Warm Ocean"; + } +} diff --git a/src/main/java/cn/nukkit/level/biome/impl/ocean/WarmOceanBiome.java b/src/main/java/cn/nukkit/level/biome/impl/ocean/WarmOceanBiome.java new file mode 100644 index 00000000000..0dc5f08515e --- /dev/null +++ b/src/main/java/cn/nukkit/level/biome/impl/ocean/WarmOceanBiome.java @@ -0,0 +1,27 @@ +package cn.nukkit.level.biome.impl.ocean; + +import cn.nukkit.block.Block; +import cn.nukkit.level.generator.populator.impl.PopulatorSeagrass; + +public class WarmOceanBiome extends OceanBiome { + + public WarmOceanBiome() { + PopulatorSeagrass populatorSeagrass = new PopulatorSeagrass(); + populatorSeagrass.setBaseAmount(24); + populatorSeagrass.setRandomAmount(24); + this.addPopulator(populatorSeagrass); + + this.setBaseHeight(-1.0f); + this.setHeightVariation(0.1f); + } + + @Override + public String getName() { + return "Warm Ocean"; + } + + @Override + public int getGroundId(int x, int y, int z) { + return Block.SAND << Block.DATA_BITS; + } +} diff --git a/src/main/java/cn/nukkit/level/biome/impl/plains/PlainsBiome.java b/src/main/java/cn/nukkit/level/biome/impl/plains/PlainsBiome.java index 9b727eaea6f..ecfca50ae9b 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/plains/PlainsBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/plains/PlainsBiome.java @@ -1,9 +1,12 @@ package cn.nukkit.level.biome.impl.plains; +import cn.nukkit.block.BlockSapling; import cn.nukkit.level.biome.type.GrassyBiome; +import cn.nukkit.level.generator.populator.impl.PopulatorPumpkin; +import cn.nukkit.level.generator.populator.impl.PopulatorTree; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class PlainsBiome extends GrassyBiome { @@ -11,6 +14,12 @@ public class PlainsBiome extends GrassyBiome { public PlainsBiome() { super(); + PopulatorTree trees = new PopulatorTree(BlockSapling.OAK); + trees.setRandomAmount(1); + this.addPopulator(trees); + + this.addPopulator(new PopulatorPumpkin()); + this.setBaseHeight(0.125f); this.setHeightVariation(0.05f); } diff --git a/src/main/java/cn/nukkit/level/biome/impl/plains/SunflowerPlainsBiome.java b/src/main/java/cn/nukkit/level/biome/impl/plains/SunflowerPlainsBiome.java index 3896b80b460..73e0c3d26f8 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/plains/SunflowerPlainsBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/plains/SunflowerPlainsBiome.java @@ -1,21 +1,31 @@ package cn.nukkit.level.biome.impl.plains; import cn.nukkit.block.BlockDoublePlant; +import cn.nukkit.block.BlockSapling; +import cn.nukkit.level.biome.type.GrassyBiome; import cn.nukkit.level.generator.populator.impl.PopulatorDoublePlant; +import cn.nukkit.level.generator.populator.impl.PopulatorTree; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ -public class SunflowerPlainsBiome extends PlainsBiome { +public class SunflowerPlainsBiome extends GrassyBiome { public SunflowerPlainsBiome() { super(); + PopulatorTree trees = new PopulatorTree(BlockSapling.OAK); + trees.setRandomAmount(1); + this.addPopulator(trees); + PopulatorDoublePlant sunflower = new PopulatorDoublePlant(BlockDoublePlant.SUNFLOWER); sunflower.setBaseAmount(8); sunflower.setRandomAmount(5); this.addPopulator(sunflower); + + this.setBaseHeight(0.125f); + this.setHeightVariation(0.05f); } @Override diff --git a/src/main/java/cn/nukkit/level/biome/impl/river/FrozenRiverBiome.java b/src/main/java/cn/nukkit/level/biome/impl/river/FrozenRiverBiome.java index 0ad727df48e..79b9647fd47 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/river/FrozenRiverBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/river/FrozenRiverBiome.java @@ -1,17 +1,14 @@ package cn.nukkit.level.biome.impl.river; -import cn.nukkit.level.generator.populator.impl.WaterIcePopulator; +import cn.nukkit.block.Block; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class FrozenRiverBiome extends RiverBiome { public FrozenRiverBiome() { super(); - - WaterIcePopulator ice = new WaterIcePopulator(); - this.addPopulator(ice); } @Override @@ -28,4 +25,9 @@ public boolean isFreezing() { public boolean canRain() { return false; } + + @Override + public int getCoverId(int x, int z) { + return SNOW_LAYER << Block.DATA_BITS; + } } diff --git a/src/main/java/cn/nukkit/level/biome/impl/river/RiverBiome.java b/src/main/java/cn/nukkit/level/biome/impl/river/RiverBiome.java index 1b5db752e81..6719e6f4d25 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/river/RiverBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/river/RiverBiome.java @@ -1,14 +1,46 @@ package cn.nukkit.level.biome.impl.river; +import cn.nukkit.block.Block; import cn.nukkit.level.biome.type.WateryBiome; +import cn.nukkit.level.generator.populator.impl.PopulatorSeagrass; +import cn.nukkit.level.generator.populator.impl.PopulatorSugarcane; +import cn.nukkit.level.generator.populator.impl.PopulatorTallSugarcane; +import cn.nukkit.level.generator.populator.impl.PopulatorUnderwaterFloor; + +import java.util.Arrays; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class RiverBiome extends WateryBiome { public RiverBiome() { + PopulatorUnderwaterFloor underwaterFloorSand = new PopulatorUnderwaterFloor(1.0, SAND, 2, 4, 2, Arrays.asList(GRASS, DIRT)); + underwaterFloorSand.setBaseAmount(3); + addPopulator(underwaterFloorSand); + + PopulatorUnderwaterFloor underwaterFloorClay = new PopulatorUnderwaterFloor(1.0, CLAY_BLOCK, 1, 2, 1, Arrays.asList(DIRT, CLAY_BLOCK)); + underwaterFloorClay.setBaseAmount(1); + addPopulator(underwaterFloorClay); + + PopulatorUnderwaterFloor underwaterFloorGravel = new PopulatorUnderwaterFloor(1.0, GRAVEL, 2, 3, 2, Arrays.asList(GRASS, DIRT)); + underwaterFloorGravel.setBaseAmount(1); + addPopulator(underwaterFloorGravel); + + PopulatorSeagrass populatorSeagrass = new PopulatorSeagrass(); + populatorSeagrass.setBaseAmount(24); + populatorSeagrass.setRandomAmount(24); + addPopulator(populatorSeagrass); + + PopulatorSugarcane sugarcane = new PopulatorSugarcane(); + sugarcane.setRandomAmount(3); + this.addPopulator(sugarcane); + + PopulatorTallSugarcane tallSugarcane = new PopulatorTallSugarcane(); + tallSugarcane.setRandomAmount(1); + this.addPopulator(tallSugarcane); + this.setBaseHeight(-0.5f); this.setHeightVariation(0f); } @@ -17,4 +49,14 @@ public RiverBiome() { public String getName() { return "River"; } + + @Override + public int getSurfaceDepth(int x, int y, int z) { + return 1; + } + + @Override + public int getSurfaceId(int x, int y, int z) { + return GRASS << Block.DATA_BITS; + } } diff --git a/src/main/java/cn/nukkit/level/biome/impl/roofedforest/RoofedForestBiome.java b/src/main/java/cn/nukkit/level/biome/impl/roofedforest/RoofedForestBiome.java index 2bcd2061d7f..17986f5dd8c 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/roofedforest/RoofedForestBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/roofedforest/RoofedForestBiome.java @@ -1,5 +1,7 @@ package cn.nukkit.level.biome.impl.roofedforest; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockFlower; import cn.nukkit.level.biome.type.GrassyBiome; import cn.nukkit.level.generator.populator.impl.MushroomPopulator; import cn.nukkit.level.generator.populator.impl.PopulatorFlower; @@ -11,17 +13,18 @@ public RoofedForestBiome() { super(); DarkOakTreePopulator tree = new DarkOakTreePopulator(); - tree.setBaseAmount(20); - tree.setRandomAmount(10); + tree.setBaseAmount(24); + tree.setRandomAmount(24); this.addPopulator(tree); PopulatorFlower flower = new PopulatorFlower(); - flower.setBaseAmount(2); - this.addPopulator(flower); + flower.setBaseAmount(3); + flower.addType(Block.DANDELION, 0); + flower.addType(Block.RED_FLOWER, BlockFlower.TYPE_POPPY); MushroomPopulator mushroom = new MushroomPopulator(); - mushroom.setBaseAmount(0); - mushroom.setRandomAmount(1); + mushroom.setBaseAmount(1); + mushroom.setRandomAmount(2); this.addPopulator(mushroom); } @@ -29,5 +32,4 @@ public RoofedForestBiome() { public String getName() { return "Roofed Forest"; } - } diff --git a/src/main/java/cn/nukkit/level/biome/impl/savanna/SavannaBiome.java b/src/main/java/cn/nukkit/level/biome/impl/savanna/SavannaBiome.java index 980a0838728..8edf451c168 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/savanna/SavannaBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/savanna/SavannaBiome.java @@ -2,6 +2,7 @@ import cn.nukkit.block.BlockSapling; import cn.nukkit.level.biome.type.GrassyBiome; +import cn.nukkit.level.generator.populator.impl.PopulatorFlower; import cn.nukkit.level.generator.populator.impl.tree.SavannaTreePopulator; /** @@ -16,6 +17,10 @@ public SavannaBiome() { tree.setBaseAmount(1); this.addPopulator(tree); + PopulatorFlower flower = new PopulatorFlower(); + flower.setBaseAmount(2); + this.addPopulator(flower); + this.setBaseHeight(0.125f); this.setHeightVariation(0.05f); } diff --git a/src/main/java/cn/nukkit/level/biome/impl/savanna/SavannaMBiome.java b/src/main/java/cn/nukkit/level/biome/impl/savanna/SavannaMBiome.java index e84f090344f..ae81f3ed647 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/savanna/SavannaMBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/savanna/SavannaMBiome.java @@ -35,4 +35,9 @@ public String getName() { public boolean doesOverhang() { return true; } + + @Override + public boolean canRain() { + return true; + } } diff --git a/src/main/java/cn/nukkit/level/biome/impl/savanna/SavannaPlateauBiome.java b/src/main/java/cn/nukkit/level/biome/impl/savanna/SavannaPlateauBiome.java index 2a59464411e..98a4df34ccb 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/savanna/SavannaPlateauBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/savanna/SavannaPlateauBiome.java @@ -16,4 +16,9 @@ public SavannaPlateauBiome() { public String getName() { return "Savanna Plateau"; } + + @Override + public boolean canRain() { + return true; + } } diff --git a/src/main/java/cn/nukkit/level/biome/impl/savanna/SavannaPlateauMBiome.java b/src/main/java/cn/nukkit/level/biome/impl/savanna/SavannaPlateauMBiome.java index 26f221e3f66..c5e89e58fd0 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/savanna/SavannaPlateauMBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/savanna/SavannaPlateauMBiome.java @@ -3,8 +3,6 @@ /** * @author DaPorkchop_ */ -//porktodo: this is just like savanna plateau with individual spikes -//see https://minecraft.gamepedia.com/Biome#Plateau_M public class SavannaPlateauMBiome extends SavannaPlateauBiome { public SavannaPlateauMBiome() { diff --git a/src/main/java/cn/nukkit/level/biome/impl/swamp/SwampBiome.java b/src/main/java/cn/nukkit/level/biome/impl/swamp/SwampBiome.java index fef542a9725..73ac22e70aa 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/swamp/SwampBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/swamp/SwampBiome.java @@ -3,14 +3,13 @@ import cn.nukkit.block.Block; import cn.nukkit.block.BlockFlower; import cn.nukkit.level.biome.type.GrassyBiome; -import cn.nukkit.level.generator.populator.impl.MushroomPopulator; -import cn.nukkit.level.generator.populator.impl.PopulatorFlower; -import cn.nukkit.level.generator.populator.impl.PopulatorLilyPad; -import cn.nukkit.level.generator.populator.impl.PopulatorSmallMushroom; +import cn.nukkit.level.generator.populator.impl.*; import cn.nukkit.level.generator.populator.impl.tree.SwampTreePopulator; +import java.util.Arrays; + /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class SwampBiome extends GrassyBiome { @@ -18,6 +17,15 @@ public class SwampBiome extends GrassyBiome { public SwampBiome() { super(); + PopulatorUnderwaterFloor underwaterFloorClay = new PopulatorUnderwaterFloor(1.0, CLAY_BLOCK, 1, 2, 1, Arrays.asList(DIRT, CLAY_BLOCK)); + underwaterFloorClay.setBaseAmount(1); + addPopulator(underwaterFloorClay); + + PopulatorSeagrass populatorSeagrass = new PopulatorSeagrass(); + populatorSeagrass.setBaseAmount(24); + populatorSeagrass.setRandomAmount(24); + addPopulator(populatorSeagrass); + PopulatorLilyPad lilypad = new PopulatorLilyPad(); lilypad.setBaseAmount(4); lilypad.setRandomAmount(2); @@ -38,7 +46,6 @@ public SwampBiome() { this.addPopulator(mushroom); PopulatorSmallMushroom smallMushroom = new PopulatorSmallMushroom(); - smallMushroom.setBaseAmount(0); smallMushroom.setRandomAmount(2); this.addPopulator(smallMushroom); diff --git a/src/main/java/cn/nukkit/level/biome/impl/swamp/SwamplandMBiome.java b/src/main/java/cn/nukkit/level/biome/impl/swamp/SwamplandMBiome.java index 0579ceeaa45..5cf743ee270 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/swamp/SwamplandMBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/swamp/SwamplandMBiome.java @@ -1,16 +1,11 @@ package cn.nukkit.level.biome.impl.swamp; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ -//porktodo: this should be flat in most places, and only rise up in a few public class SwamplandMBiome extends SwampBiome { - public SwamplandMBiome() { - super(); - } - @Override public String getName() { return "Swampland M"; diff --git a/src/main/java/cn/nukkit/level/biome/impl/taiga/ColdTaigaBiome.java b/src/main/java/cn/nukkit/level/biome/impl/taiga/ColdTaigaBiome.java index d46818f7c4b..000f55bc948 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/taiga/ColdTaigaBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/taiga/ColdTaigaBiome.java @@ -1,18 +1,15 @@ package cn.nukkit.level.biome.impl.taiga; -import cn.nukkit.level.generator.populator.impl.WaterIcePopulator; +import cn.nukkit.block.Block; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class ColdTaigaBiome extends TaigaBiome { public ColdTaigaBiome() { super(); - WaterIcePopulator ice = new WaterIcePopulator(); - this.addPopulator(ice); - this.setBaseHeight(0.2f); this.setHeightVariation(0.2f); } @@ -24,7 +21,7 @@ public String getName() { @Override public int getCoverId(int x, int z) { - return SNOW_LAYER << 4; + return Block.SNOW_LAYER << Block.DATA_BITS; } @Override diff --git a/src/main/java/cn/nukkit/level/biome/impl/taiga/ColdTaigaHillsBiome.java b/src/main/java/cn/nukkit/level/biome/impl/taiga/ColdTaigaHillsBiome.java index 56413acba4e..0c693e81233 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/taiga/ColdTaigaHillsBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/taiga/ColdTaigaHillsBiome.java @@ -1,7 +1,7 @@ package cn.nukkit.level.biome.impl.taiga; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class ColdTaigaHillsBiome extends ColdTaigaBiome { diff --git a/src/main/java/cn/nukkit/level/biome/impl/taiga/ColdTaigaMBiome.java b/src/main/java/cn/nukkit/level/biome/impl/taiga/ColdTaigaMBiome.java index 56398838905..99e5a24ee79 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/taiga/ColdTaigaMBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/taiga/ColdTaigaMBiome.java @@ -1,14 +1,10 @@ package cn.nukkit.level.biome.impl.taiga; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ -//porktodo: this biome has very steep cliffs public class ColdTaigaMBiome extends ColdTaigaBiome { - public ColdTaigaMBiome() { - super(); - } @Override public String getName() { diff --git a/src/main/java/cn/nukkit/level/biome/impl/taiga/MegaSpruceTaigaBiome.java b/src/main/java/cn/nukkit/level/biome/impl/taiga/MegaSpruceTaigaBiome.java index be128a614d9..0421d431cce 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/taiga/MegaSpruceTaigaBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/taiga/MegaSpruceTaigaBiome.java @@ -1,22 +1,47 @@ package cn.nukkit.level.biome.impl.taiga; +import cn.nukkit.block.Block; +import cn.nukkit.level.generator.noise.nukkit.f.SimplexF; +import cn.nukkit.level.generator.populator.impl.PopulatorForestRock; +import cn.nukkit.level.generator.populator.impl.PopulatorSmallMushroom; import cn.nukkit.level.generator.populator.impl.tree.SpruceBigTreePopulator; +import cn.nukkit.math.NukkitRandom; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class MegaSpruceTaigaBiome extends TaigaBiome { + + private static final SimplexF podzolNoise = new SimplexF(new NukkitRandom(), 2f, 1 / 4f, 1 / 32f); + public MegaSpruceTaigaBiome() { super(); SpruceBigTreePopulator bigTrees = new SpruceBigTreePopulator(); bigTrees.setBaseAmount(6); this.addPopulator(bigTrees); + + PopulatorForestRock rock = new PopulatorForestRock(); + rock.setRandomAmount(2); + this.addPopulator(rock); + + /*PopulatorFlower flower = new PopulatorFlower(); + flower.setRandomAmount(3); + flower.addType(Block.DANDELION, 0);*/ + + PopulatorSmallMushroom smallMushroom = new PopulatorSmallMushroom(); + smallMushroom.setRandomAmount(3); + this.addPopulator(smallMushroom); } @Override public String getName() { return "Mega Spruce Taiga"; } + + @Override + public int getSurfaceId(int x, int y, int z) { + return podzolNoise.noise2D(x, z, true) < 0f ? PODZOL << Block.DATA_BITS : Block.GRASS << Block.DATA_BITS; + } } diff --git a/src/main/java/cn/nukkit/level/biome/impl/taiga/MegaSpruceTaigaHillsBiome.java b/src/main/java/cn/nukkit/level/biome/impl/taiga/MegaSpruceTaigaHillsBiome.java new file mode 100644 index 00000000000..48b4ace174a --- /dev/null +++ b/src/main/java/cn/nukkit/level/biome/impl/taiga/MegaSpruceTaigaHillsBiome.java @@ -0,0 +1,16 @@ +package cn.nukkit.level.biome.impl.taiga; + +public class MegaSpruceTaigaHillsBiome extends MegaSpruceTaigaBiome { + + public MegaSpruceTaigaHillsBiome() { + super(); + + this.setBaseHeight(0.55f); + this.setHeightVariation(0.5f); + } + + @Override + public String getName() { + return "Mega Spruce Taiga Hills"; + } +} diff --git a/src/main/java/cn/nukkit/level/biome/impl/taiga/MegaTaigaBiome.java b/src/main/java/cn/nukkit/level/biome/impl/taiga/MegaTaigaBiome.java index 52491af9839..234ba1897da 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/taiga/MegaTaigaBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/taiga/MegaTaigaBiome.java @@ -1,19 +1,39 @@ package cn.nukkit.level.biome.impl.taiga; -import cn.nukkit.level.generator.populator.impl.tree.SpruceBigTreePopulator; +import cn.nukkit.block.Block; +import cn.nukkit.level.generator.noise.nukkit.f.SimplexF; +import cn.nukkit.level.generator.populator.impl.PopulatorForestRock; +import cn.nukkit.level.generator.populator.impl.PopulatorSmallMushroom; +import cn.nukkit.level.generator.populator.impl.tree.SpruceMegaTreePopulator; +import cn.nukkit.math.NukkitRandom; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class MegaTaigaBiome extends TaigaBiome { + + private static final SimplexF podzolNoise = new SimplexF(new NukkitRandom(), 2f, 1 / 4f, 1 / 32f); + public MegaTaigaBiome() { super(); - SpruceBigTreePopulator bigTrees = new SpruceBigTreePopulator(); + SpruceMegaTreePopulator bigTrees = new SpruceMegaTreePopulator(); bigTrees.setBaseAmount(6); this.addPopulator(bigTrees); + PopulatorForestRock rock = new PopulatorForestRock(); + rock.setRandomAmount(2); + this.addPopulator(rock); + + /*PopulatorFlower flower = new PopulatorFlower(); + flower.setRandomAmount(3); + flower.addType(Block.DANDELION, 0);*/ + + PopulatorSmallMushroom smallMushroom = new PopulatorSmallMushroom(); + smallMushroom.setRandomAmount(3); + this.addPopulator(smallMushroom); + this.setBaseHeight(0.2f); this.setHeightVariation(0.2f); } @@ -22,4 +42,9 @@ public MegaTaigaBiome() { public String getName() { return "Mega Taiga"; } + + @Override + public int getSurfaceId(int x, int y, int z) { + return podzolNoise.noise2D(x, z, true) < 0f ? PODZOL << Block.DATA_BITS : Block.GRASS << Block.DATA_BITS; + } } diff --git a/src/main/java/cn/nukkit/level/biome/impl/taiga/MegaTaigaHillsBiome.java b/src/main/java/cn/nukkit/level/biome/impl/taiga/MegaTaigaHillsBiome.java index d4e31de7f1c..73f0d3fcceb 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/taiga/MegaTaigaHillsBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/taiga/MegaTaigaHillsBiome.java @@ -1,7 +1,7 @@ package cn.nukkit.level.biome.impl.taiga; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class MegaTaigaHillsBiome extends MegaTaigaBiome { diff --git a/src/main/java/cn/nukkit/level/biome/impl/taiga/TaigaBiome.java b/src/main/java/cn/nukkit/level/biome/impl/taiga/TaigaBiome.java index 79712255d49..99edf9764ac 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/taiga/TaigaBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/taiga/TaigaBiome.java @@ -1,21 +1,35 @@ package cn.nukkit.level.biome.impl.taiga; +import cn.nukkit.block.BlockDoublePlant; import cn.nukkit.block.BlockSapling; import cn.nukkit.level.biome.type.GrassyBiome; +import cn.nukkit.level.generator.object.tree.ObjectTree; +import cn.nukkit.level.generator.populator.impl.PopulatorDoublePlant; +import cn.nukkit.level.generator.populator.impl.PopulatorSweetBerryBush; import cn.nukkit.level.generator.populator.impl.PopulatorTree; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class TaigaBiome extends GrassyBiome { public TaigaBiome() { super(); - PopulatorTree trees = new PopulatorTree(BlockSapling.SPRUCE); + PopulatorTree trees = new PopulatorTree(BlockSapling.SPRUCE + ObjectTree.SNOWY_TREE); trees.setBaseAmount(10); this.addPopulator(trees); + if (!(this instanceof ColdTaigaBiome)) { + PopulatorDoublePlant tallGrass = new PopulatorDoublePlant(BlockDoublePlant.LARGE_FERN); + tallGrass.setBaseAmount(2); + this.addPopulator(tallGrass); + + PopulatorSweetBerryBush bush = new PopulatorSweetBerryBush(); + bush.setRandomAmount(3); + this.addPopulator(bush); + } + this.setBaseHeight(0.2f); this.setHeightVariation(0.2f); } diff --git a/src/main/java/cn/nukkit/level/biome/impl/taiga/TaigaMBiome.java b/src/main/java/cn/nukkit/level/biome/impl/taiga/TaigaMBiome.java index c14f067b784..4f09ee75086 100644 --- a/src/main/java/cn/nukkit/level/biome/impl/taiga/TaigaMBiome.java +++ b/src/main/java/cn/nukkit/level/biome/impl/taiga/TaigaMBiome.java @@ -1,10 +1,9 @@ package cn.nukkit.level.biome.impl.taiga; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ -//porktodo: this should be flat-ish in most places, and upheavals should be steep public class TaigaMBiome extends TaigaBiome { public TaigaMBiome() { super(); diff --git a/src/main/java/cn/nukkit/level/biome/type/CoveredBiome.java b/src/main/java/cn/nukkit/level/biome/type/CoveredBiome.java index b934cd3b1d1..b4d4a6e7f91 100644 --- a/src/main/java/cn/nukkit/level/biome/type/CoveredBiome.java +++ b/src/main/java/cn/nukkit/level/biome/type/CoveredBiome.java @@ -1,19 +1,21 @@ package cn.nukkit.level.biome.type; +import cn.nukkit.block.Block; import cn.nukkit.level.biome.Biome; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.generator.Normal; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project *

* A biome with ground covering *

*/ public abstract class CoveredBiome extends Biome { + public int getCoverId(int x, int z) { - return AIR << 4; + return 0; } public int getSurfaceDepth(int x, int y, int z) { @@ -38,7 +40,7 @@ public void doCover(int x, int z, FullChunk chunk) { int realY; //start one below build limit in case of cover blocks for (int y = 254; y > 32; y--) { - if (chunk.getFullBlock(x, y, z) == STONE << 4) { + if (chunk.getFullBlock(x, y, z) == (STONE << Block.DATA_BITS)) { COVER: if (!hasCovered) { if (y >= Normal.seaHeight) { @@ -46,7 +48,7 @@ public void doCover(int x, int z, FullChunk chunk) { int surfaceDepth = this.getSurfaceDepth(fullX, y, fullZ); for (int i = 0; i < surfaceDepth; i++) { realY = y - i; - if (chunk.getFullBlock(x, realY, z) == STONE << 4) { + if (chunk.getFullBlock(x, realY, z) == (STONE << Block.DATA_BITS)) { chunk.setFullBlockId(x, realY, z, this.getSurfaceId(fullX, realY, fullZ)); } else break COVER; } @@ -55,7 +57,7 @@ public void doCover(int x, int z, FullChunk chunk) { int groundDepth = this.getGroundDepth(fullX, y, fullZ); for (int i = 0; i < groundDepth; i++) { realY = y - i; - if (chunk.getFullBlock(x, realY, z) == STONE << 4) { + if (chunk.getFullBlock(x, realY, z) == (STONE << Block.DATA_BITS)) { chunk.setFullBlockId(x, realY, z, this.getGroundId(fullX, realY, fullZ)); } else break COVER; } diff --git a/src/main/java/cn/nukkit/level/biome/type/GrassyBiome.java b/src/main/java/cn/nukkit/level/biome/type/GrassyBiome.java index 91048cab4b7..40228f092c0 100644 --- a/src/main/java/cn/nukkit/level/biome/type/GrassyBiome.java +++ b/src/main/java/cn/nukkit/level/biome/type/GrassyBiome.java @@ -1,14 +1,16 @@ package cn.nukkit.level.biome.type; +import cn.nukkit.block.Block; import cn.nukkit.block.BlockDoublePlant; import cn.nukkit.level.generator.populator.impl.PopulatorDoublePlant; import cn.nukkit.level.generator.populator.impl.PopulatorGrass; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class GrassyBiome extends CoveredBiome { + public GrassyBiome() { PopulatorGrass grass = new PopulatorGrass(); grass.setBaseAmount(30); @@ -21,11 +23,11 @@ public GrassyBiome() { @Override public int getSurfaceId(int x, int y, int z) { - return GRASS << 4; + return Block.GRASS << Block.DATA_BITS; } @Override public int getGroundId(int x, int y, int z) { - return DIRT << 4; + return Block.DIRT << Block.DATA_BITS; } } diff --git a/src/main/java/cn/nukkit/level/biome/type/SandyBiome.java b/src/main/java/cn/nukkit/level/biome/type/SandyBiome.java index 751e5e6b99f..dca312b5194 100644 --- a/src/main/java/cn/nukkit/level/biome/type/SandyBiome.java +++ b/src/main/java/cn/nukkit/level/biome/type/SandyBiome.java @@ -1,7 +1,9 @@ package cn.nukkit.level.biome.type; +import cn.nukkit.block.Block; + /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class SandyBiome extends CoveredBiome { @@ -12,7 +14,7 @@ public int getSurfaceDepth(int x, int y, int z) { @Override public int getSurfaceId(int x, int y, int z) { - return SAND << 4; + return Block.SAND << Block.DATA_BITS; } @Override @@ -22,6 +24,6 @@ public int getGroundDepth(int x, int y, int z) { @Override public int getGroundId(int x, int y, int z) { - return SANDSTONE << 4; + return Block.SANDSTONE << Block.DATA_BITS; } } diff --git a/src/main/java/cn/nukkit/level/biome/type/SnowyBiome.java b/src/main/java/cn/nukkit/level/biome/type/SnowyBiome.java index a8fb734fb5f..33e7c0d893d 100644 --- a/src/main/java/cn/nukkit/level/biome/type/SnowyBiome.java +++ b/src/main/java/cn/nukkit/level/biome/type/SnowyBiome.java @@ -1,22 +1,24 @@ package cn.nukkit.level.biome.type; -import cn.nukkit.level.generator.populator.impl.WaterIcePopulator; +import cn.nukkit.block.Block; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public abstract class SnowyBiome extends GrassyBiome { public SnowyBiome() { super(); - - WaterIcePopulator waterIce = new WaterIcePopulator(); - this.addPopulator(waterIce); } @Override public int getCoverId(int x, int z) { - return SNOW_LAYER << 4; + return Block.SNOW_LAYER << Block.DATA_BITS; + } + + @Override + public boolean isFreezing() { + return true; } @Override diff --git a/src/main/java/cn/nukkit/level/biome/type/WateryBiome.java b/src/main/java/cn/nukkit/level/biome/type/WateryBiome.java index 17ba88e2aa4..9e9ff127b6a 100644 --- a/src/main/java/cn/nukkit/level/biome/type/WateryBiome.java +++ b/src/main/java/cn/nukkit/level/biome/type/WateryBiome.java @@ -1,10 +1,13 @@ package cn.nukkit.level.biome.type; +import cn.nukkit.block.Block; + /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public abstract class WateryBiome extends CoveredBiome { + @Override public int getSurfaceDepth(int x, int y, int z) { return 0; @@ -23,6 +26,6 @@ public int getGroundDepth(int x, int y, int z) { @Override public int getGroundId(int x, int y, int z) { - return DIRT << 4; + return Block.DIRT << Block.DATA_BITS; } } diff --git a/src/main/java/cn/nukkit/level/format/Chunk.java b/src/main/java/cn/nukkit/level/format/Chunk.java index 0862796331f..cc5b4617e4f 100644 --- a/src/main/java/cn/nukkit/level/format/Chunk.java +++ b/src/main/java/cn/nukkit/level/format/Chunk.java @@ -1,10 +1,11 @@ package cn.nukkit.level.format; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface Chunk extends FullChunk { + byte SECTION_COUNT = 16; boolean isSectionEmpty(float fY); @@ -15,6 +16,10 @@ public interface Chunk extends FullChunk { ChunkSection[] getSections(); + default int getSectionOffset() { + return 0; + } + class Entry { public final int chunkX; public final int chunkZ; diff --git a/src/main/java/cn/nukkit/level/format/ChunkSection.java b/src/main/java/cn/nukkit/level/format/ChunkSection.java index 9b08de1e62c..3c333be5ea3 100644 --- a/src/main/java/cn/nukkit/level/format/ChunkSection.java +++ b/src/main/java/cn/nukkit/level/format/ChunkSection.java @@ -1,33 +1,67 @@ package cn.nukkit.level.format; import cn.nukkit.block.Block; +import cn.nukkit.block.BlockLayer; import cn.nukkit.utils.BinaryStream; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface ChunkSection { + int getY(); - int getBlockId(int x, int y, int z); + default int getBlockId(int x, int y, int z) { + return this.getBlockId(x, y, z, Block.LAYER_NORMAL); + } + + int getBlockId(int x, int y, int z, BlockLayer layer); + + default void setBlockId(int x, int y, int z, int id) { + this.setBlockId(x, y, z, Block.LAYER_NORMAL, id); + } + + void setBlockId(int x, int y, int z, BlockLayer layer, int id); + + default int getBlockData(int x, int y, int z) { + return this.getBlockData(x, y, z, Block.LAYER_NORMAL); + } + + int getBlockData(int x, int y, int z, BlockLayer layer); - void setBlockId(int x, int y, int z, int id); + default void setBlockData(int x, int y, int z, int data) { + this.setBlockData(x, y, z, Block.LAYER_NORMAL, data); + } - int getBlockData(int x, int y, int z); + void setBlockData(int x, int y, int z, BlockLayer layer, int data); - void setBlockData(int x, int y, int z, int data); + default int getFullBlock(int x, int y, int z) { + return this.getFullBlock(x, y, z, Block.LAYER_NORMAL); + } - int getFullBlock(int x, int y, int z); + int getFullBlock(int x, int y, int z, BlockLayer layer); - Block getAndSetBlock(int x, int y, int z, Block block); + default Block getAndSetBlock(int x, int y, int z, Block block) { + return this.getAndSetBlock(x, y, z, Block.LAYER_NORMAL, block); + } - boolean setFullBlockId(int x, int y, int z, int fullId); + Block getAndSetBlock(int x, int y, int z, BlockLayer layer, Block block); + + default boolean setFullBlockId(int x, int y, int z, int fullId) { + return this.setFullBlockId(x, y, z, Block.LAYER_NORMAL, fullId); + } + + boolean setFullBlockId(int x, int y, int z, BlockLayer layer, int fullId); boolean setBlock(int x, int y, int z, int blockId); boolean setBlock(int x, int y, int z, int blockId, int meta); + boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int blockId); + + boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int blockId, int meta); + int getBlockSkyLight(int x, int y, int z); void setBlockSkyLight(int x, int y, int z, int level); @@ -49,4 +83,8 @@ public interface ChunkSection { void writeTo(BinaryStream stream); ChunkSection copy(); + + default ChunkSection copyForChunkSending() { + return copy(); + } } diff --git a/src/main/java/cn/nukkit/level/format/FullChunk.java b/src/main/java/cn/nukkit/level/format/FullChunk.java index 895f3c0b6ed..a8ed539a1b4 100644 --- a/src/main/java/cn/nukkit/level/format/FullChunk.java +++ b/src/main/java/cn/nukkit/level/format/FullChunk.java @@ -1,14 +1,16 @@ package cn.nukkit.level.format; import cn.nukkit.block.Block; +import cn.nukkit.block.BlockLayer; import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.entity.Entity; -import cn.nukkit.level.biome.Biome; +import cn.nukkit.level.util.PalettedBlockStorage; + import java.io.IOException; import java.util.Map; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface FullChunk extends Cloneable { @@ -32,25 +34,57 @@ default void setPosition(int x, int z) { void setProvider(LevelProvider provider); - int getFullBlock(int x, int y, int z); + default int getFullBlock(int x, int y, int z) { + return this.getFullBlock(x, y, z, Block.LAYER_NORMAL); + } + + int getFullBlock(int x, int y, int z, BlockLayer layer); + + default Block getAndSetBlock(int x, int y, int z, Block block) { + return this.getAndSetBlock(x, y, z, Block.LAYER_NORMAL, block); + } - Block getAndSetBlock(int x, int y, int z, Block block); + Block getAndSetBlock(int x, int y, int z, BlockLayer layer, Block block); default boolean setFullBlockId(int x, int y, int z, int fullId) { - return setBlock(x, y, z, fullId >> 4, fullId & 0xF); + return setFullBlockId(x, y, z, Block.LAYER_NORMAL, fullId); + } + + default boolean setFullBlockId(int x, int y, int z, BlockLayer layer, int fullId) { + return setBlockAtLayer(x, y, z, layer, fullId >> Block.DATA_BITS, fullId & Block.DATA_MASK); } - boolean setBlock(int x, int y, int z, int blockId); + boolean setBlock(int x, int y, int z, int blockId); + + boolean setBlock(int x, int y, int z, int blockId, int meta); - boolean setBlock(int x, int y, int z, int blockId, int meta); + boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int id); - int getBlockId(int x, int y, int z); + boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int id, int data); - void setBlockId(int x, int y, int z, int id); + default int getBlockId(int x, int y, int z) { + return this.getBlockId(x, y, z, Block.LAYER_NORMAL); + } - int getBlockData(int x, int y, int z); + int getBlockId(int x, int y, int z, BlockLayer layer); - void setBlockData(int x, int y, int z, int data); + default void setBlockId(int x, int y, int z, int id) { + this.setBlockId(x, y, z, Block.LAYER_NORMAL, id); + } + + void setBlockId(int x, int y, int z, BlockLayer layer, int id); + + default int getBlockData(int x, int y, int z) { + return this.getBlockData(x, y, z, Block.LAYER_NORMAL); + } + + int getBlockData(int x, int y, int z, BlockLayer layer); + + default void setBlockData(int x, int y, int z, int data) { + this.setBlockData(x, y, z, Block.LAYER_NORMAL, data); + } + + void setBlockData(int x, int y, int z, BlockLayer layer, int data); int getBlockExtraData(int x, int y, int z); @@ -76,16 +110,36 @@ default boolean setFullBlockId(int x, int y, int z, int fullId) { void populateSkyLight(); + default boolean has3dBiomes() { + return false; + } + + default PalettedBlockStorage getBiomeStorage(int y) { + return null; + } + int getBiomeId(int x, int z); - void setBiomeId(int x, int z, byte biomeId); + default int getBiomeId(int x, int y, int z) { + return this.getBiomeId(x, z); + } + + default void setBiomeId(int x, int y, int z, int biomeId) { + this.setBiomeId(x, y, z, (byte) biomeId); + } default void setBiomeId(int x, int z, int biomeId) { setBiomeId(x, z, (byte) biomeId); } - default void setBiome(int x, int z, Biome biome) { - setBiomeId(x, z, (byte) biome.getId()); + default void setBiomeId(int x, int y, int z, byte biomeId) { + this.setBiomeId(x, z, biomeId); + } + + void setBiomeId(int x, int z, byte biomeId); + + default void setBiome(int x, int z, cn.nukkit.level.biome.Biome biome) { + setBiomeId(x, z, biome.getId()); } boolean isLightPopulated(); @@ -136,20 +190,27 @@ default void setBiome(int x, int z, Biome biome) { byte[] getBiomeIdArray(); + void setBiomeIdArray(byte[] biomeIdArray); + byte[] getHeightMapArray(); + @Deprecated byte[] getBlockIdArray(); + @Deprecated byte[] getBlockDataArray(); Map getBlockExtraDataArray(); + @Deprecated byte[] getBlockSkyLightArray(); + @Deprecated byte[] getBlockLightArray(); byte[] toBinary(); + @Deprecated byte[] toFastBinary(); boolean hasChanged(); @@ -157,4 +218,4 @@ default void setBiome(int x, int z, Biome biome) { void setChanged(); void setChanged(boolean changed); -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/format/LevelProvider.java b/src/main/java/cn/nukkit/level/format/LevelProvider.java index 9f7de6c674f..92f78b5b678 100644 --- a/src/main/java/cn/nukkit/level/format/LevelProvider.java +++ b/src/main/java/cn/nukkit/level/format/LevelProvider.java @@ -4,19 +4,19 @@ import cn.nukkit.level.Level; import cn.nukkit.level.format.generic.BaseFullChunk; import cn.nukkit.math.Vector3; -import cn.nukkit.scheduler.AsyncTask; import java.util.Map; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface LevelProvider { + byte ORDER_YZX = 0; byte ORDER_ZXY = 1; - AsyncTask requestChunkTask(int X, int Z); + void requestChunkTask(int X, int Z); String getPath(); diff --git a/src/main/java/cn/nukkit/level/format/LevelProviderManager.java b/src/main/java/cn/nukkit/level/format/LevelProviderManager.java index e8c8aba9339..89a4753b2f4 100644 --- a/src/main/java/cn/nukkit/level/format/LevelProviderManager.java +++ b/src/main/java/cn/nukkit/level/format/LevelProviderManager.java @@ -6,10 +6,11 @@ import java.util.Map; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class LevelProviderManager { + protected static final Map> providers = new HashMap<>(); public static void addProvider(Server server, Class clazz) { @@ -34,8 +35,6 @@ public static Class getProvider(String path) { } public static Class getProviderByName(String name) { - name = name.trim().toLowerCase(); - return providers.getOrDefault(name, null); + return providers.getOrDefault(name.trim().toLowerCase(), null); } - } diff --git a/src/main/java/cn/nukkit/level/format/anvil/Anvil.java b/src/main/java/cn/nukkit/level/format/anvil/Anvil.java index cffd7a2e89a..396e6a8d57b 100644 --- a/src/main/java/cn/nukkit/level/format/anvil/Anvil.java +++ b/src/main/java/cn/nukkit/level/format/anvil/Anvil.java @@ -1,49 +1,42 @@ package cn.nukkit.level.format.anvil; +import cn.nukkit.Server; import cn.nukkit.level.Level; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.format.generic.BaseFullChunk; import cn.nukkit.level.format.generic.BaseLevelProvider; import cn.nukkit.level.format.generic.BaseRegionLoader; -import cn.nukkit.level.format.generic.serializer.NetworkChunkSerializer; import cn.nukkit.level.generator.Generator; import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.CompoundTag; -import cn.nukkit.scheduler.AsyncTask; -import cn.nukkit.utils.BinaryStream; import cn.nukkit.utils.ChunkException; import it.unimi.dsi.fastutil.objects.ObjectIterator; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteOrder; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; -import java.util.function.BiConsumer; import java.util.regex.Pattern; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class Anvil extends BaseLevelProvider { - public static final int VERSION = 19133; - private static final byte[] PAD_256 = new byte[256]; - public static final int EXTENDED_NEGATIVE_SUB_CHUNKS = 4; public Anvil(Level level, String path) throws IOException { super(level, path); } + @SuppressWarnings("unused") public static String getProviderName() { return "anvil"; } - public static byte getProviderOrder() { - return ORDER_YZX; - } - + @SuppressWarnings("unused") public static boolean usesChunkSection() { return true; } @@ -72,7 +65,6 @@ public static void generate(String path, String name, long seed, Class callback = (stream, subchunks) -> - this.getLevel().chunkRequestCallback(timestamp, x, z, subchunks, stream.getBuffer()); - NetworkChunkSerializer.serialize(chunk, callback, this.level.getDimensionData()); - return null; + + level.asyncChunk(chunk.cloneForChunkSending(), timestamp, x, z); } private int lastPosition = 0; @@ -135,7 +125,6 @@ public void doGarbageCollection(long time) { BaseFullChunk chunk = iter.next(); if (chunk == null) continue; if (chunk.isGenerated() && chunk.isPopulated() && chunk instanceof Chunk) { - Chunk anvilChunk = (Chunk) chunk; chunk.compress(); if (System.currentTimeMillis() - start >= time) break; } @@ -149,13 +138,13 @@ public synchronized BaseFullChunk loadChunk(long index, int chunkX, int chunkZ, int regionX = getRegionIndexX(chunkX); int regionZ = getRegionIndexZ(chunkZ); BaseRegionLoader region = this.loadRegion(regionX, regionZ); - this.level.timings.syncChunkLoadDataTimer.startTiming(); - BaseFullChunk chunk; - try { - chunk = region.readChunk(chunkX - regionX * 32, chunkZ - regionZ * 32); - } catch (IOException e) { - throw new RuntimeException(e); + BaseFullChunk chunk = null; + try { // Note: We don't want to ignore corrupted regions here as those would eventually cause problems when chunks are saved + chunk = region.readChunk(chunkX - (regionX << 5), chunkZ - (regionZ << 5)); + } catch (IOException ex) { + Server.getInstance().getLogger().error("Failed to read chunk " + chunkX + ", " + chunkZ, ex); } + if (chunk == null) { if (create) { chunk = this.getEmptyChunk(chunkX, chunkZ); @@ -164,7 +153,6 @@ public synchronized BaseFullChunk loadChunk(long index, int chunkX, int chunkZ, } else { putChunk(index, chunk); } - this.level.timings.syncChunkLoadDataTimer.stopTiming(); return chunk; } @@ -175,16 +163,15 @@ public synchronized void saveChunk(int X, int Z) { try { this.loadRegion(X >> 5, Z >> 5).writeChunk(chunk); } catch (Exception e) { - throw new ChunkException("Error saving chunk (" + X + ", " + Z + ")", e); + throw new ChunkException("Error saving chunk (" + X + ", " + Z + ')', e); } } } - @Override public synchronized void saveChunk(int x, int z, FullChunk chunk) { if (!(chunk instanceof Chunk)) { - throw new ChunkException("Invalid Chunk class"); + throw new ChunkException("Invalid chunk class (" + x + ", " + z + ')'); } int regionX = x >> 5; int regionZ = z >> 5; @@ -198,10 +185,9 @@ public synchronized void saveChunk(int x, int z, FullChunk chunk) { } } + @SuppressWarnings("unused") public static ChunkSection createChunkSection(int y) { - ChunkSection cs = new ChunkSection(y); - cs.hasSkyLight = true; - return cs; + return new ChunkSection(y); } protected synchronized BaseRegionLoader loadRegion(int x, int z) { diff --git a/src/main/java/cn/nukkit/level/format/anvil/Chunk.java b/src/main/java/cn/nukkit/level/format/anvil/Chunk.java index 4f0d6dec7a2..fe90ce3dc8d 100644 --- a/src/main/java/cn/nukkit/level/format/anvil/Chunk.java +++ b/src/main/java/cn/nukkit/level/format/anvil/Chunk.java @@ -1,6 +1,5 @@ package cn.nukkit.level.format.anvil; -import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.block.Block; import cn.nukkit.blockentity.BlockEntity; @@ -11,10 +10,7 @@ import cn.nukkit.level.format.generic.EmptyChunkSection; import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.*; -import cn.nukkit.utils.BinaryStream; -import cn.nukkit.utils.BlockUpdateEntry; -import cn.nukkit.utils.ChunkException; -import cn.nukkit.utils.Zlib; +import cn.nukkit.utils.*; import java.io.ByteArrayInputStream; import java.io.DataInputStream; @@ -24,7 +20,7 @@ import java.util.*; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class Chunk extends BaseChunk { @@ -38,6 +34,11 @@ public Chunk clone() { return (Chunk) super.clone(); } + @Override + public Chunk cloneForChunkSending() { + return (Chunk) super.cloneForChunkSending(); + } + public Chunk(LevelProvider level) { this(level, null); } @@ -59,9 +60,9 @@ public Chunk(LevelProvider level, CompoundTag nbt) { } if (nbt == null) { - this.biomes = new byte[16 * 16]; + this.biomes = new byte[256]; this.sections = new cn.nukkit.level.format.ChunkSection[16]; - if (16 >= 0) System.arraycopy(EmptyChunkSection.EMPTY, 0, this.sections, 0, 16); + System.arraycopy(EmptyChunkSection.EMPTY, 0, this.sections, 0, 16); return; } @@ -94,11 +95,11 @@ public Chunk(LevelProvider level, CompoundTag nbt) { this.setPosition(nbt.getInt("xPos"), nbt.getInt("zPos")); if (sections.length > SECTION_COUNT) { - throw new ChunkException("Invalid amount of chunks"); + throw new ChunkException("Invalid amount of chunks: " + sections.length); } if (nbt.contains("BiomeColors")) { - this.biomes = new byte[16 * 16]; + this.biomes = new byte[256]; int[] biomeColors = nbt.getIntArray("BiomeColors"); if (biomeColors != null && biomeColors.length == 256) { BiomePalette palette = new BiomePalette(biomeColors); @@ -213,7 +214,7 @@ public CompoundTag getNBT() { tag.put("V", new ByteTag("V", (byte) 1)); tag.put("TerrainGenerated", new ByteTag("TerrainGenerated", (byte) (isGenerated() ? 1 : 0))); - tag.put("TerrainPopulated", new ByteTag("TerrainPopulated", (byte) (isPopulated() ? 1 : 0))); + tag.put("TerrainPopulated", new ByteTag("TerrainPopulated", (byte) (terrainPopulated ? 1 : 0))); return tag; } @@ -226,11 +227,12 @@ public static Chunk fromBinary(byte[] data, LevelProvider provider) { try { CompoundTag chunk = NBTIO.read(new ByteArrayInputStream(Zlib.inflate(data)), ByteOrder.BIG_ENDIAN); - if (!chunk.contains("Level") || !(chunk.get("Level") instanceof CompoundTag)) { + Tag levelTag = chunk.get("Level"); + if (!(levelTag instanceof CompoundTag)) { return null; } - return new Chunk(provider, chunk.getCompound("Level")); + return new Chunk(provider, (CompoundTag) levelTag); } catch (Exception e) { Server.getInstance().getLogger().logException(e); return null; @@ -245,11 +247,13 @@ public static Chunk fromFastBinary(byte[] data) { public static Chunk fromFastBinary(byte[] data, LevelProvider provider) { try { CompoundTag chunk = NBTIO.read(new DataInputStream(new ByteArrayInputStream(data)), ByteOrder.BIG_ENDIAN); - if (!chunk.contains("Level") || !(chunk.get("Level") instanceof CompoundTag)) { + + Tag levelTag = chunk.get("Level"); + if (!(levelTag instanceof CompoundTag)) { return null; } - return new Chunk(provider, chunk.getCompound("Level")); + return new Chunk(provider, (CompoundTag) levelTag); } catch (Exception e) { return null; } @@ -258,97 +262,28 @@ public static Chunk fromFastBinary(byte[] data, LevelProvider provider) { @Override public byte[] toFastBinary() { - CompoundTag nbt = this.getNBT().copy(); - nbt.remove("BiomeColors"); - - nbt.putInt("xPos", this.getX()); - nbt.putInt("zPos", this.getZ()); - - nbt.putByteArray("Biomes", this.getBiomeIdArray()); - int[] heightInts = new int[256]; - byte[] heightBytes = this.getHeightMapArray(); - for (int i = 0; i < heightInts.length; i++) { - heightInts[i] = heightBytes[i] & 0xFF; - } - - for (cn.nukkit.level.format.ChunkSection section : this.getSections()) { - if (section instanceof EmptyChunkSection) { - continue; - } - CompoundTag s = new CompoundTag(null); - s.putByte("Y", section.getY()); - s.putByteArray("Blocks", section.getIdArray()); - s.putByteArray("Data", section.getDataArray()); - s.putByteArray("BlockLight", section.getLightArray()); - s.putByteArray("SkyLight", section.getSkyLightArray()); - nbt.getList("Sections", CompoundTag.class).add(s); - } - - ArrayList entities = new ArrayList<>(); - for (Entity entity : this.getEntities().values()) { - if (!(entity instanceof Player) && !entity.closed) { - entity.saveNBT(); - entities.add(entity.namedTag); - } - } - ListTag entityListTag = new ListTag<>("Entities"); - entityListTag.setAll(entities); - nbt.putList(entityListTag); - - ArrayList tiles = new ArrayList<>(); - for (BlockEntity blockEntity : this.getBlockEntities().values()) { - blockEntity.saveNBT(); - tiles.add(blockEntity.namedTag); - } - ListTag tileListTag = new ListTag<>("TileEntities"); - tileListTag.setAll(tiles); - nbt.putList(tileListTag); - - Set entries = this.provider.getLevel().getPendingBlockUpdates(this); - - if (entries != null) { - ListTag tileTickTag = new ListTag<>("TileTicks"); - long totalTime = this.provider.getLevel().getCurrentTick(); - - for (BlockUpdateEntry entry : entries) { - CompoundTag entryNBT = new CompoundTag() - .putString("i", entry.block.getSaveId()) - .putInt("x", entry.pos.getFloorX()) - .putInt("y", entry.pos.getFloorY()) - .putInt("z", entry.pos.getFloorZ()) - .putInt("t", (int) (entry.delay - totalTime)) - .putInt("p", entry.priority); - tileTickTag.add(entryNBT); - } - - nbt.putList(tileTickTag); - } - - BinaryStream extraData = new BinaryStream(); - Map extraDataArray = this.getBlockExtraDataArray(); - extraData.putInt(extraDataArray.size()); - for (Integer key : extraDataArray.keySet()) { - extraData.putInt(key); - extraData.putShort(extraDataArray.get(key)); - } - - nbt.putByteArray("ExtraData", extraData.getBuffer()); - - CompoundTag chunk = new CompoundTag(""); - chunk.putCompound("Level", nbt); + CompoundTag chunk = chunkNBT(); try { return NBTIO.write(chunk, ByteOrder.BIG_ENDIAN); } catch (IOException e) { throw new RuntimeException(e); } - } @Override public byte[] toBinary() { - CompoundTag nbt = this.getNBT().copy(); - nbt.remove("BiomeColors"); + CompoundTag chunk = chunkNBT(); + + try { + return Zlib.deflate(NBTIO.write(chunk, ByteOrder.BIG_ENDIAN), 7); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private CompoundTag chunkNBT() { + CompoundTag nbt = this.getNBT(); nbt.putInt("xPos", this.getX()); nbt.putInt("zPos", this.getZ()); @@ -358,7 +293,7 @@ public byte[] toBinary() { if (section instanceof EmptyChunkSection) { continue; } - CompoundTag s = new CompoundTag(null); + CompoundTag s = new CompoundTag(); s.putByte("Y", (section.getY())); s.putByteArray("Blocks", section.getIdArray()); s.putByteArray("Data", section.getDataArray()); @@ -369,6 +304,7 @@ public byte[] toBinary() { nbt.putList(sectionList); nbt.putByteArray("Biomes", this.getBiomeIdArray()); + int[] heightInts = new int[256]; byte[] heightBytes = this.getHeightMapArray(); for (int i = 0; i < heightInts.length; i++) { @@ -378,26 +314,28 @@ public byte[] toBinary() { ArrayList entities = new ArrayList<>(); for (Entity entity : this.getEntities().values()) { - if (!(entity instanceof Player) && !entity.closed) { + if (entity.canSaveToStorage() && !entity.closed) { entity.saveNBT(); entities.add(entity.namedTag); } } + ListTag entityListTag = new ListTag<>("Entities"); entityListTag.setAll(entities); nbt.putList(entityListTag); ArrayList tiles = new ArrayList<>(); for (BlockEntity blockEntity : this.getBlockEntities().values()) { - blockEntity.saveNBT(); - tiles.add(blockEntity.namedTag); + if (blockEntity.canSaveToStorage()) { + blockEntity.saveNBT(); + tiles.add(blockEntity.namedTag); + } } ListTag tileListTag = new ListTag<>("TileEntities"); tileListTag.setAll(tiles); nbt.putList(tileListTag); Set entries = this.provider.getLevel().getPendingBlockUpdates(this); - if (entries != null) { ListTag tileTickTag = new ListTag<>("TileTicks"); long totalTime = this.provider.getLevel().getCurrentTick(); @@ -419,21 +357,15 @@ public byte[] toBinary() { BinaryStream extraData = new BinaryStream(); Map extraDataArray = this.getBlockExtraDataArray(); extraData.putInt(extraDataArray.size()); - for (Integer key : extraDataArray.keySet()) { - extraData.putInt(key); - extraData.putShort(extraDataArray.get(key)); + for (Map.Entry entry : extraDataArray.entrySet()) { + extraData.putInt(entry.getKey()); + extraData.putShort(entry.getValue()); } - nbt.putByteArray("ExtraData", extraData.getBuffer()); CompoundTag chunk = new CompoundTag(""); chunk.putCompound("Level", nbt); - - try { - return Zlib.deflate(NBTIO.write(chunk, ByteOrder.BIG_ENDIAN), RegionLoader.COMPRESSION_LEVEL); - } catch (Exception e) { - throw new RuntimeException(e); - } + return chunk; } @Override @@ -450,7 +382,7 @@ public int getBlockSkyLight(int x, int y, int z) { if (height < y) { return 15; } else if (height == y) { - return Block.transparent[getBlockId(x, y, z)] ? 15 : 0; + return Block.isBlockTransparentById(getBlockId(x, y, z)) ? 15 : 0; } else { return section.getBlockSkyLight(x, y & 0x0f, z); } @@ -496,7 +428,6 @@ public static Chunk getEmptyChunk(int chunkX, int chunkZ, LevelProvider provider chunk.inhabitedTime = 0; chunk.terrainGenerated = false; chunk.terrainPopulated = false; -// chunk.lightPopulated = false; return chunk; } catch (Exception e) { return null; @@ -517,4 +448,9 @@ public boolean compress() { } return result; } + + @Override + public String toString() { + return "(Anvil) Chunk[" + getX() + "," + getZ() + "] (inhabitedTime=" + inhabitedTime + " terrainPopulated=" + terrainPopulated + " terrainGenerated=" + terrainGenerated + ')'; + } } diff --git a/src/main/java/cn/nukkit/level/format/anvil/ChunkSection.java b/src/main/java/cn/nukkit/level/format/anvil/ChunkSection.java index ffc3ae7ac7e..03fc1b321f2 100644 --- a/src/main/java/cn/nukkit/level/format/anvil/ChunkSection.java +++ b/src/main/java/cn/nukkit/level/format/anvil/ChunkSection.java @@ -1,24 +1,26 @@ package cn.nukkit.level.format.anvil; +import cn.nukkit.Server; import cn.nukkit.block.Block; +import cn.nukkit.block.BlockLayer; import cn.nukkit.level.format.anvil.util.BlockStorage; import cn.nukkit.level.format.anvil.util.NibbleArray; import cn.nukkit.level.format.generic.EmptyChunkSection; -import cn.nukkit.level.util.PalettedBlockStorage; import cn.nukkit.nbt.tag.CompoundTag; -import cn.nukkit.utils.*; +import cn.nukkit.utils.Binary; +import cn.nukkit.utils.BinaryStream; +import cn.nukkit.utils.Utils; +import cn.nukkit.utils.Zlib; import java.io.IOException; import java.util.Arrays; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ChunkSection implements cn.nukkit.level.format.ChunkSection { - private static final PalettedBlockStorage EMPTY_STORAGE = PalettedBlockStorage.createFromBlockPalette(); - private final int y; private final BlockStorage storage; @@ -29,10 +31,10 @@ public class ChunkSection implements cn.nukkit.level.format.ChunkSection { protected boolean hasBlockLight; protected boolean hasSkyLight; - private ChunkSection(int y, BlockStorage storage, byte[] blockLight, byte[] skyLight, byte[] compressedLight, - boolean hasBlockLight, boolean hasSkyLight) { + public ChunkSection(int y, BlockStorage storage, byte[] blockLight, byte[] skyLight, byte[] compressedLight, boolean hasBlockLight, boolean hasSkyLight) { this.y = y; this.storage = storage; + this.blockLight = blockLight; this.skyLight = skyLight; this.compressedLight = compressedLight; this.hasBlockLight = hasBlockLight; @@ -40,12 +42,7 @@ private ChunkSection(int y, BlockStorage storage, byte[] blockLight, byte[] skyL } public ChunkSection(int y) { - this.y = y; - - hasBlockLight = false; - hasSkyLight = false; - - storage = new BlockStorage(); + this(y, new BlockStorage(), null, null, null, false, true); } public ChunkSection(CompoundTag nbt) { @@ -61,8 +58,10 @@ public ChunkSection(CompoundTag nbt) { for (int z = 0; z < 16; z++) { for (int y = 0; y < 16; y++) { int index = getAnvilIndex(x, y, z); - storage.setBlockId(x, y, z, blocks[index]); + // Set block data first so we can overwrite it when removing data values from air in setBlockId storage.setBlockData(x, y, z, data.get(index)); + int b = blocks[index] & 0xff; + storage.setBlockId(x, y, z, b); } } } @@ -81,43 +80,66 @@ public int getY() { } @Override - public int getBlockId(int x, int y, int z) { + public int getBlockId(int x, int y, int z, BlockLayer layer) { + if (layer != BlockLayer.NORMAL) { + return 0; + } synchronized (storage) { return storage.getBlockId(x, y, z); } } @Override - public void setBlockId(int x, int y, int z, int id) { + public void setBlockId(int x, int y, int z, BlockLayer layer, int id) { + if (layer != BlockLayer.NORMAL) { + return; + } + synchronized (storage) { storage.setBlockId(x, y, z, id); } } @Override - public boolean setFullBlockId(int x, int y, int z, int fullId) { + public boolean setFullBlockId(int x, int y, int z, BlockLayer layer, int fullId) { + if (layer != BlockLayer.NORMAL) { + return true; + } + synchronized (storage) { - storage.setFullBlock(x, y, z, (char) fullId); + storage.setFullBlock(x, y, z, fullId); } return true; } @Override - public int getBlockData(int x, int y, int z) { + public int getBlockData(int x, int y, int z, BlockLayer layer) { + if (layer != BlockLayer.NORMAL) { + return 0; + } + synchronized (storage) { return storage.getBlockData(x, y, z); } } @Override - public void setBlockData(int x, int y, int z, int data) { + public void setBlockData(int x, int y, int z, BlockLayer layer, int data) { + if (layer != BlockLayer.NORMAL) { + return; + } + synchronized (storage) { storage.setBlockData(x, y, z, data); } } @Override - public int getFullBlock(int x, int y, int z) { + public int getFullBlock(int x, int y, int z, BlockLayer layer) { + if (layer != BlockLayer.NORMAL) { + return 0; + } + synchronized (storage) { return storage.getFullBlock(x, y, z); } @@ -130,19 +152,36 @@ public boolean setBlock(int x, int y, int z, int blockId) { } } - public Block getAndSetBlock(int x, int y, int z, Block block) { + public Block getAndSetBlock(int x, int y, int z, BlockLayer layer, Block block) { + if (layer != BlockLayer.NORMAL) { + return Block.get(Block.AIR); + } + synchronized (storage) { int fullId = storage.getAndSetFullBlock(x, y, z, block.getFullId()); - return Block.fullList[fullId].clone(); + return Block.get(fullId, null, x, y, z, layer); } } @Override public boolean setBlock(int x, int y, int z, int blockId, int meta) { - int newFullId = (blockId << 4) + meta; + return this.setBlockAtLayer(x, y, z, Block.LAYER_NORMAL, blockId, meta); + } + + @Override + public boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int blockId) { + return this.setBlockAtLayer(x, y, z, layer, blockId, 0); + } + + @Override + public boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int blockId, int meta) { + if (layer != BlockLayer.NORMAL) { + return true; + } + synchronized (storage) { - int previousFullId = storage.getAndSetFullBlock(x, y, z, newFullId); - return (newFullId != previousFullId); + int fullId = (blockId << Block.DATA_BITS) | meta; + return storage.getAndSetFullBlock(x, y, z, fullId) != fullId; } } @@ -251,16 +290,14 @@ public byte[] getDataArray() { @Override public byte[] getSkyLightArray() { - if (this.skyLight != null) return skyLight; - if (hasSkyLight) { - if (compressedLight != null) { - inflate(); - return this.skyLight; + if (this.skyLight != null) return this.skyLight; + if (this.hasSkyLight) { + if (this.compressedLight != null) { + this.inflate(); + if (this.skyLight != null) return this.skyLight; } - return EmptyChunkSection.EMPTY_SKY_LIGHT_ARR; - } else { - return EmptyChunkSection.EMPTY_LIGHT_ARR; } + return EmptyChunkSection.EMPTY_SKY_LIGHT_ARR; } private void inflate() { @@ -278,26 +315,27 @@ private void inflate() { } compressedLight = null; } else { - blockLight = new byte[2048]; + if (blockLight == null) { + blockLight = new byte[2048]; + } skyLight = new byte[2048]; if (hasSkyLight) { Arrays.fill(skyLight, (byte) 0xFF); } } } catch (IOException e) { - e.printStackTrace(); + Server.getInstance().getLogger().logException(e); } } @Override public byte[] getLightArray() { - if (this.blockLight != null) return blockLight; - if (hasBlockLight) { - inflate(); - return this.blockLight; - } else { - return EmptyChunkSection.EMPTY_LIGHT_ARR; + if (this.blockLight != null) return this.blockLight; + if (this.hasBlockLight) { + this.inflate(); + if (this.blockLight != null) return this.blockLight; } + return EmptyChunkSection.EMPTY_LIGHT_ARR; } @Override @@ -305,24 +343,10 @@ public boolean isEmpty() { return false; } - private byte[] toXZY(char[] raw) { - byte[] buffer = ThreadCache.byteCache6144.get(); - for (int i = 0; i < 4096; i++) { - buffer[i] = (byte) (raw[i] >> 4); - } - for (int i = 0, j = 4096; i < 4096; i += 2, j++) { - buffer[j] = (byte) (((raw[i + 1] & 0xF) << 4) | (raw[i] & 0xF)); - } - return buffer; - } - @Override public void writeTo(BinaryStream stream) { synchronized (storage) { - stream.putByte((byte) 8); // Paletted chunk because Mojang messed up the old one - stream.putByte((byte) 2); this.storage.writeTo(stream); - EMPTY_STORAGE.writeTo(stream); } } @@ -352,7 +376,7 @@ public boolean compress() { try { compressedLight = Zlib.deflate(toDeflate, 1); } catch (Exception e) { - e.printStackTrace(); + Server.getInstance().getLogger().logException(e); } } return true; @@ -360,6 +384,7 @@ public boolean compress() { return false; } + @Override public ChunkSection copy() { return new ChunkSection( this.y, @@ -371,4 +396,17 @@ public ChunkSection copy() { this.hasSkyLight ); } + + @Override + public ChunkSection copyForChunkSending() { + return new ChunkSection( + this.y, + this.storage.copy(), + null, + null, + null, + false, + false + ); + } } diff --git a/src/main/java/cn/nukkit/level/format/anvil/RegionLoader.java b/src/main/java/cn/nukkit/level/format/anvil/RegionLoader.java index ffdbd8c4ba9..c6fb0969cf5 100644 --- a/src/main/java/cn/nukkit/level/format/anvil/RegionLoader.java +++ b/src/main/java/cn/nukkit/level/format/anvil/RegionLoader.java @@ -14,10 +14,11 @@ import java.util.TreeMap; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class RegionLoader extends BaseRegionLoader { + public RegionLoader(LevelProvider level, int regionX, int regionZ) throws IOException { super(level, regionX, regionZ, "mca"); } @@ -42,42 +43,42 @@ public Chunk readChunk(int x, int z) throws IOException { } try { - Integer[] table = this.locationTable.get(index); - RandomAccessFile raf = this.getRandomAccessFile(); - raf.seek(table[0] << 12); - int length = raf.readInt(); - byte compression = raf.readByte(); - if (length <= 0 || length >= MAX_SECTOR_LENGTH) { - if (length >= MAX_SECTOR_LENGTH) { - table[0] = ++this.lastSector; - table[1] = 1; - this.locationTable.put(index, table); - MainLogger.getLogger().error("Corrupted chunk header detected"); + Integer[] table = this.locationTable.get(index); + RandomAccessFile raf = this.getRandomAccessFile(); + raf.seek(table[0] << 12); + int length = raf.readInt(); + byte compression = raf.readByte(); + if (length <= 0 || length >= MAX_SECTOR_LENGTH) { + if (length >= MAX_SECTOR_LENGTH) { + table[0] = ++this.lastSector; + table[1] = 1; + this.locationTable.put(index, table); + MainLogger.getLogger().error("Corrupted chunk header detected (" + x + ", " + z + ") (" + this.levelProvider.getName() + "/r." + this.x + "." + this.z + ".mca)"); + } + return null; } - return null; - } - if (length > (table[1] << 12)) { - MainLogger.getLogger().error("Corrupted bigger chunk detected"); - table[1] = length >> 12; - this.locationTable.put(index, table); - this.writeLocationIndex(index); - } else if (compression != COMPRESSION_ZLIB && compression != COMPRESSION_GZIP) { - MainLogger.getLogger().error("Invalid compression type"); - return null; - } + if (length > (table[1] << 12)) { + MainLogger.getLogger().error("Corrupted bigger chunk detected (" + x + ", " + z + ") (" + this.levelProvider.getName() + "/r." + this.x + "." + this.z + ".mca)"); + table[1] = length >> 12; + this.locationTable.put(index, table); + this.writeLocationIndex(index); + } else if (compression != COMPRESSION_ZLIB && compression != COMPRESSION_GZIP) { + MainLogger.getLogger().error("Invalid compression type (" + x + ", " + z + ") (" + this.levelProvider.getName() + "/r." + this.x + "." + this.z + ".mca)"); + return null; + } - byte[] data = new byte[length - 1]; - raf.readFully(data); - Chunk chunk = this.unserializeChunk(data); - if (chunk != null) { - return chunk; - } else { - MainLogger.getLogger().error("Corrupted chunk detected at (" + x + ", " + z + ") in " + levelProvider.getName()); - return null; - } - } catch (EOFException e) { - MainLogger.getLogger().error("Your world is corrupt, because some code is bad and corrupted it. oops. "); + byte[] data = new byte[length - 1]; + raf.readFully(data); + Chunk chunk = this.unserializeChunk(data); + if (chunk != null) { + return chunk; + } else { + MainLogger.getLogger().error("Corrupted chunk detected (" + x + ", " + z + ") (" + this.levelProvider.getName() + "/r." + this.x + "." + this.z + ".mca)"); + return null; + } + } catch (EOFException e) { + MainLogger.getLogger().error("World corruption occurred (" + x + ", " + z + ") (" + this.levelProvider.getName() + "/r." + this.x + "." + this.z + ".mca)"); return null; } } @@ -96,7 +97,7 @@ public boolean chunkExists(int x, int z) { protected void saveChunk(int x, int z, byte[] chunkData) throws IOException { int length = chunkData.length + 1; if (length + 4 > MAX_SECTOR_LENGTH) { - throw new ChunkException("Chunk is too big! " + (length + 4) + " > " + MAX_SECTOR_LENGTH); + throw new ChunkException("Chunk [" + x + ", " + z + "] is too big! " + (length + 4) + " > " + MAX_SECTOR_LENGTH); } int sectors = (int) Math.ceil((length + 4) / 4096d); int index = getChunkOffset(x, z); @@ -119,7 +120,7 @@ protected void saveChunk(int x, int z, byte[] chunkData) throws IOException { RandomAccessFile raf = this.getRandomAccessFile(); raf.seek(table[0] << 12); - BinaryStream stream = new BinaryStream(); + BinaryStream stream = new BinaryStream(new byte[5 + chunkData.length]).reset(); stream.put(Binary.writeInt(length)); stream.putByte(COMPRESSION_ZLIB); stream.put(chunkData); @@ -214,8 +215,8 @@ protected void loadLocationTable() throws IOException { RandomAccessFile raf = this.getRandomAccessFile(); raf.seek(0); this.lastSector = 1; - int[] data = new int[1024 * 2]; //1024 records * 2 times - for (int i = 0; i < 1024 * 2; i++) { + int[] data = new int[2048]; //1024 records * 2 times + for (int i = 0; i < 2048; i++) { data[i] = raf.readInt(); } for (int i = 0; i < 1024; ++i) { @@ -244,15 +245,14 @@ private void writeLocationTable() throws IOException { private int cleanGarbage() throws IOException { RandomAccessFile raf = this.getRandomAccessFile(); Map sectors = new TreeMap<>(); - for (Map.Entry entry : this.locationTable.entrySet()) { - Integer index = (Integer) entry.getKey(); - Integer[] data = (Integer[]) entry.getValue(); - if (data[0] == 0 || data[1] == 0) { + this.locationTable.forEach((key, value) -> { + int index = key; + if (value[0] == 0 || value[1] == 0) { this.locationTable.put(index, new Integer[]{0, 0, 0}); - continue; + return; } - sectors.put(data[0], index); - } + sectors.put(value[0], index); + }); if (sectors.size() == (this.lastSector - 2)) { return 0; diff --git a/src/main/java/cn/nukkit/level/format/anvil/palette/BiomePalette.java b/src/main/java/cn/nukkit/level/format/anvil/palette/BiomePalette.java index 0aa025eb075..b67aba1f8f9 100644 --- a/src/main/java/cn/nukkit/level/format/anvil/palette/BiomePalette.java +++ b/src/main/java/cn/nukkit/level/format/anvil/palette/BiomePalette.java @@ -6,6 +6,7 @@ @Deprecated public final class BiomePalette { + private int biome; private BitArray256 encodedData; private IntPalette palette; @@ -77,15 +78,12 @@ public synchronized void set(int index, int value) { raw[i] = palette.getKey(raw[i]); } - int oldRaw = raw[4]; - raw[index] = value; palette.add(value); - int oldBits = MathHelper.log2(palette.length() - 2); int newBits = MathHelper.log2(palette.length() - 1); - if (oldBits != newBits) { + if (MathHelper.log2(palette.length() - 2) != newBits) { encodedData = new BitArray256(newBits); } @@ -96,7 +94,6 @@ public synchronized void set(int index, int value) { encodedData.fromRaw(raw); } } - } public synchronized int[] toRaw() { diff --git a/src/main/java/cn/nukkit/level/format/anvil/palette/BitArray256.java b/src/main/java/cn/nukkit/level/format/anvil/palette/BitArray256.java index 4a60bbfadb1..97198a4e5b4 100644 --- a/src/main/java/cn/nukkit/level/format/anvil/palette/BitArray256.java +++ b/src/main/java/cn/nukkit/level/format/anvil/palette/BitArray256.java @@ -3,15 +3,16 @@ import cn.nukkit.utils.ThreadCache; /** - * @author https://github.com/boy0001/ + * @author ... */ public final class BitArray256 { + private final int bitsPerEntry; protected final long[] data; public BitArray256(int bitsPerEntry) { this.bitsPerEntry = bitsPerEntry; - int longLen = (this.bitsPerEntry * 256) >> 6; + int longLen = (this.bitsPerEntry << 8) >> 6; this.data = new long[longLen]; } @@ -26,7 +27,7 @@ public final void setAt(int index, int value) { int localBitIndexStart = bitIndexStart & 63; this.data[longIndexStart] = this.data[longIndexStart] & ~((long) ((1 << bitsPerEntry) - 1) << localBitIndexStart) | ((long) value) << localBitIndexStart; - if(localBitIndexStart > 64 - bitsPerEntry) { + if (localBitIndexStart > 64 - bitsPerEntry) { int longIndexEnd = longIndexStart + 1; int localShiftStart = 64 - localBitIndexStart; int localShiftEnd = bitsPerEntry - localShiftStart; @@ -40,11 +41,10 @@ public final int getAt(int index) { int longIndexStart = bitIndexStart >> 6; int localBitIndexStart = bitIndexStart & 63; - if(localBitIndexStart <= 64 - bitsPerEntry) { + if (localBitIndexStart <= 64 - bitsPerEntry) { return (int)(this.data[longIndexStart] >>> localBitIndexStart & ((1 << bitsPerEntry) - 1)); } else { - int localShift = 64 - localBitIndexStart; - return (int) ((this.data[longIndexStart] >>> localBitIndexStart | this.data[longIndexStart + 1] << localShift) & ((1 << bitsPerEntry) - 1)); + return (int) ((this.data[longIndexStart] >>> localBitIndexStart | this.data[longIndexStart + 1] << (64 - localBitIndexStart)) & ((1 << bitsPerEntry) - 1)); } } @@ -55,8 +55,7 @@ public final void fromRaw(int[] arr) { } public BitArray256 grow(int newBitsPerEntry) { - int amtGrow = newBitsPerEntry - this.bitsPerEntry; - if (amtGrow <= 0) return this; + if (newBitsPerEntry - this.bitsPerEntry <= 0) return this; BitArray256 newBitArray = new BitArray256(newBitsPerEntry); int[] buffer = ThreadCache.intCache256.get(); diff --git a/src/main/java/cn/nukkit/level/format/anvil/palette/BitArray4096.java b/src/main/java/cn/nukkit/level/format/anvil/palette/BitArray4096.java deleted file mode 100644 index e4891e8ffc7..00000000000 --- a/src/main/java/cn/nukkit/level/format/anvil/palette/BitArray4096.java +++ /dev/null @@ -1,163 +0,0 @@ -package cn.nukkit.level.format.anvil.palette; - -import cn.nukkit.utils.ThreadCache; - -/** - * @author https://github.com/boy0001/ - */ -public final class BitArray4096 { - - private final int bitsPerEntry; - private final int maxSeqLocIndex; - private final int maxEntryValue; - private final long[] data; - - public BitArray4096(int bitsPerEntry) { - this.bitsPerEntry = bitsPerEntry; - this.maxSeqLocIndex = 64 - bitsPerEntry; - maxEntryValue = (1 << bitsPerEntry) - 1; - int longLen = (this.bitsPerEntry * 4096) >> 6; - this.data = new long[longLen]; - } - - public final void setAt(int index, int value) { - if (data.length == 0) return; - int bitIndexStart = index * bitsPerEntry; - int longIndexStart = bitIndexStart >> 6; - int localBitIndexStart = bitIndexStart & 63; - this.data[longIndexStart] = this.data[longIndexStart] & ~((long) maxEntryValue << localBitIndexStart) | ((long) value) << localBitIndexStart; - - if(localBitIndexStart > maxSeqLocIndex) { - int longIndexEnd = longIndexStart + 1; - int localShiftStart = 64 - localBitIndexStart; - int localShiftEnd = bitsPerEntry - localShiftStart; - this.data[longIndexEnd] = this.data[longIndexEnd] >>> localShiftEnd << localShiftEnd | (((long) value) >> localShiftStart); - } - } - - public final int getAt(int index) { - if (data.length == 0) return 0; - int bitIndexStart = index * bitsPerEntry; - - int longIndexStart = bitIndexStart >> 6; - - int localBitIndexStart = bitIndexStart & 63; - if(localBitIndexStart <= maxSeqLocIndex) { - return (int)(this.data[longIndexStart] >>> localBitIndexStart & maxEntryValue); - } else { - int localShift = 64 - localBitIndexStart; - return (int) ((this.data[longIndexStart] >>> localBitIndexStart | this.data[longIndexStart + 1] << localShift) & maxEntryValue); - } - } - - public final void fromRawSlow(char[] arr) { - for (int i = 0; i < arr.length; i++) { - setAt(i, arr[i]); - } - } - - public final void fromRaw(char[] arr) { - final long[] data = this.data; - final int dataLength = data.length; - final int bitsPerEntry = this.bitsPerEntry; - final int maxEntryValue = this.maxEntryValue; - final int maxSeqLocIndex = this.maxSeqLocIndex; - - int localStart = 0; - char lastVal; - int arrI = 0; - long l = 0; - long nextVal; - for (int i = 0; i < dataLength; i++) { - for (; localStart <= maxSeqLocIndex; localStart += bitsPerEntry) { - lastVal = arr[arrI++]; - l |= ((long) lastVal << localStart); - } - if (localStart < 64) { - if (i != dataLength - 1) { - lastVal = arr[arrI++]; - int shift = 64 - localStart; - - nextVal = lastVal >> shift; - - l |= ((lastVal - (nextVal << shift)) << localStart); - - data[i] = l; - data[i + 1] = l = nextVal; - - localStart -= maxSeqLocIndex; - } - } else { - localStart = 0; - data[i] = l; - l = 0; - } - } - } - - public BitArray4096 grow(int newBitsPerEntry) { - int amtGrow = newBitsPerEntry - this.bitsPerEntry; - if (amtGrow <= 0) return this; - BitArray4096 newBitArray = new BitArray4096(newBitsPerEntry); - - char[] buffer = ThreadCache.charCache4096.get(); - toRaw(buffer); - newBitArray.fromRaw(buffer); - - return newBitArray; - } - - public BitArray4096 growSlow(int bitsPerEntry) { - BitArray4096 newBitArray = new BitArray4096(bitsPerEntry); - for (int i = 0; i < 4096; i++) { - newBitArray.setAt(i, getAt(i)); - } - return newBitArray; - } - - public final char[] toRawSlow() { - char[] arr = new char[4096]; - for (int i = 0; i < arr.length; i++) { - arr[i] = (char) getAt(i); - } - return arr; - } - - public final char[] toRaw() { - return toRaw(new char[4096]); - } - - protected final char[] toRaw(char[] buffer) { - final long[] data = this.data; - final int dataLength = data.length; - final int bitsPerEntry = this.bitsPerEntry; - final int maxEntryValue = this.maxEntryValue; - final int maxSeqLocIndex = this.maxSeqLocIndex; - - int localStart = 0; - char lastVal; - int arrI = 0; - long l; - for (int i = 0; i < dataLength; i++) { - l = data[i]; - for (; localStart <= maxSeqLocIndex; localStart += bitsPerEntry) { - lastVal = (char) (l >>> localStart & maxEntryValue); - buffer[arrI++] = lastVal; - } - if (localStart < 64) { - if (i != dataLength - 1) { - lastVal = (char) (l >>> localStart); - localStart -= maxSeqLocIndex; - l = data[i + 1]; - int localShift = bitsPerEntry - localStart; - lastVal |= l << localShift; - lastVal &= maxEntryValue; - buffer[arrI++] = lastVal; - } - } else { - localStart = 0; - } - } - return buffer; - } -} diff --git a/src/main/java/cn/nukkit/level/format/anvil/palette/BlockDataPalette.java b/src/main/java/cn/nukkit/level/format/anvil/palette/BlockDataPalette.java deleted file mode 100644 index 1ca87183028..00000000000 --- a/src/main/java/cn/nukkit/level/format/anvil/palette/BlockDataPalette.java +++ /dev/null @@ -1,221 +0,0 @@ -package cn.nukkit.level.format.anvil.palette; - -import cn.nukkit.Server; -import cn.nukkit.math.MathHelper; -import cn.nukkit.utils.ThreadCache; -import com.google.common.base.Preconditions; - -import java.util.Arrays; -import java.util.BitSet; - -/** - * @author https://github.com/boy0001/ - */ -public final class BlockDataPalette implements Cloneable { - private static final int BLOCK_SIZE = 4096; - private volatile char[] rawData; - - private volatile BitArray4096 encodedData; - private volatile CharPalette palette; - - // TODO compress unused sections - // private byte[] compressedData; - - public BlockDataPalette() { - this(new char[BLOCK_SIZE]); - } - - public BlockDataPalette(char[] rawData) { - Preconditions.checkArgument(rawData.length == BLOCK_SIZE, "Data is not 4096"); - this.rawData = rawData; - } - - private char[] getCachedRaw() { - char[] raw = rawData; - if (raw != null) { - return raw; - } else if (!Server.getInstance().isPrimaryThread()) { - return getRaw(); - } - return rawData; - } - - public synchronized char[] getRaw() { - CharPalette palette = this.palette; - BitArray4096 encodedData = this.encodedData; - this.encodedData = null; - this.palette = null; - - char[] raw = rawData; - if (raw == null && palette != null) { - if (encodedData != null) { - raw = encodedData.toRaw(); - } else { - raw = new char[BLOCK_SIZE]; - } - for (int i = 0; i < BLOCK_SIZE; i++) { - raw[i] = palette.getKey(raw[i]); - } - } else { - raw = new char[BLOCK_SIZE]; - } - rawData = raw; - return rawData; - } - - private int getIndex(int x, int y, int z) { - return (x << 8) + (z << 4) + y; // XZY = Bedrock format - } - - public int getBlockData(int x, int y, int z) { - return getFullBlock(x, y, z) & 0xF; - } - - public int getBlockId(int x, int y, int z) { - return getFullBlock(x, y, z) >> 4; - } - - public void setBlockId(int x, int y, int z, int id) { - setFullBlock(x, y, z, (char) (id << 4)); - } - - public synchronized void setBlockData(int x, int y, int z, int data) { - int index = getIndex(x, y, z); - char[] raw = getCachedRaw(); - - if (raw != null) { - int fullId = raw[index]; - raw[index] = (char) ((fullId & 0xFFF0) | data); - } if (palette != null && encodedData != null) { - char fullId = palette.getKey(encodedData.getAt(index)); - if ((fullId & 0xF) != data) { - setPaletteFullBlock(index, (char) ((fullId & 0xFFF0) | data)); - } - } else { - throw new IllegalStateException("Raw data and pallete was null"); - } - } - - public int getFullBlock(int x, int y, int z) { - return getFullBlock(getIndex(x, y, z)); - } - - public void setFullBlock(int x, int y, int z, int value) { - this.setFullBlock(getIndex(x, y, z), (char) value); - } - - public int getAndSetFullBlock(int x, int y, int z, int value) { - return getAndSetFullBlock(getIndex(x, y, z), (char) value); - } - - private int getAndSetFullBlock(int index, char value) { - char[] raw = getCachedRaw(); - if (raw != null) { - char result = raw[index]; - raw[index] = value; - return result; - } else if (palette != null && encodedData != null) { - char result = palette.getKey(encodedData.getAt(index)); - if (result != value) { - setPaletteFullBlock(index, value); - } - return result; - } else { - throw new IllegalStateException("Raw data and pallete was null"); - } - } - - private int getFullBlock(int index) { - char[] raw = getCachedRaw(); - if (raw != null) { - return raw[index]; - } else if (palette != null && encodedData != null) { - return palette.getKey(encodedData.getAt(index)); - } else { - throw new IllegalStateException("Raw data and pallete was null"); - } - } - - private void setFullBlock(int index, char value) { - char[] raw = getCachedRaw(); - if (raw != null) { - raw[index] = value; - } else if (!setPaletteFullBlock(index, value)) { - throw new IllegalStateException("Raw data and pallete was null"); - } - } - - private synchronized boolean setPaletteFullBlock(int index, char value) { - CharPalette palette = this.palette; - BitArray4096 encodedData = this.encodedData; - if (palette != null && encodedData != null) { - char encodedValue = palette.getValue(value); - if (encodedValue != Character.MAX_VALUE) { - encodedData.setAt(index, encodedValue); - } else { - char[] raw = encodedData.toRaw(); - for (int i = 0; i < BLOCK_SIZE; i++) { - raw[i] = palette.getKey(raw[i]); - } - raw[index] = value; - this.rawData = raw; - this.encodedData = null; - this.palette = null; - } - return true; - } - return false; - } - - public synchronized boolean compress() { - char[] raw = rawData; - if (raw != null) { - char unique = 0; - - BitSet countTable = ThreadCache.boolCache4096.get(); - char[] mapFullTable = ThreadCache.charCache4096.get(); - char[] mapBitTable = ThreadCache.charCache4096v2.get(); - countTable.clear(); - for (char c : raw) { - if (!countTable.get(c)) { - mapBitTable[unique] = c; - countTable.set(c); - unique++; - } - } - - char[] keys = Arrays.copyOfRange(mapBitTable, 0, unique); - if (keys.length > 1) { - Arrays.sort(keys); - for (char c = 0; c < keys.length; c++) { - mapFullTable[keys[c]] = c; - } - } else { - mapFullTable[keys[0]] = 0; - } - - CharPalette palette = new CharPalette(); - palette.set(keys); - - int bits = MathHelper.log2(unique - 1); - BitArray4096 encodedData = new BitArray4096(bits); - - for (int i = 0; i < raw.length; i++) { - mapBitTable[i] = mapFullTable[raw[i]]; - } - - encodedData.fromRaw(mapBitTable); - - this.palette = palette; - this.encodedData = encodedData; - rawData = null; - return true; - } - return false; - } - - public synchronized BlockDataPalette clone() { - char[] raw = getRaw(); - return new BlockDataPalette(raw.clone()); - } -} diff --git a/src/main/java/cn/nukkit/level/format/anvil/palette/BytePalette.java b/src/main/java/cn/nukkit/level/format/anvil/palette/BytePalette.java deleted file mode 100644 index 0d75eae5d5f..00000000000 --- a/src/main/java/cn/nukkit/level/format/anvil/palette/BytePalette.java +++ /dev/null @@ -1,93 +0,0 @@ -package cn.nukkit.level.format.anvil.palette; - -import java.util.Arrays; - -/** - * @author https://github.com/boy0001/ - */ -public class BytePalette { - private static byte[] BYTE0 = new byte[0]; - private byte[] keys = BYTE0; - private byte lastIndex = Byte.MIN_VALUE; - - public void add(byte key) { - keys = insert(key); - lastIndex = Byte.MIN_VALUE; - } - - protected void set(byte[] keys) { - this.keys = keys; - lastIndex = Byte.MIN_VALUE; - } - - private byte[] insert(byte val) { - lastIndex = Byte.MIN_VALUE; - if (keys.length == 0) { - return new byte[] { val }; - } - else if (val < keys[0]) { - byte[] s = new byte[keys.length + 1]; - System.arraycopy(keys, 0, s, 1, keys.length); - s[0] = val; - return s; - } else if (val > keys[keys.length - 1]) { - byte[] s = Arrays.copyOf(keys, keys.length + 1); - s[keys.length] = val; - return s; - } - byte[] s = Arrays.copyOf(keys, keys.length + 1); - for (int i = 0; i < s.length; i++) { - if (keys[i] < val) { - continue; - } - System.arraycopy(keys, i, s, i + 1, s.length - i - 1); - s[i] = val; - break; - } - return s; - } - - public byte getKey(int index) { - return keys[index]; - } - - public byte getValue(byte key) { - byte lastTmp = lastIndex; - boolean hasLast = lastTmp != Byte.MIN_VALUE; - int index; - if (hasLast) { - byte lastKey = keys[lastTmp]; - if (lastKey == key) return lastTmp; - if (lastKey > key) { - index = binarySearch0(0, lastTmp, key); - } else { - index = binarySearch0(lastTmp + 1, keys.length, key); - } - } else { - index = binarySearch0(0, keys.length, key); - } - if (index >= keys.length || index < 0) { - return lastIndex = Byte.MIN_VALUE; - } else { - return lastIndex = (byte) index; - } - } - - private int binarySearch0(int fromIndex, int toIndex, byte key) { - int low = fromIndex; - int high = toIndex - 1; - - while (low <= high) { - int mid = (low + high) >>> 1; - byte midVal = keys[mid]; - - if (midVal < key) - low = mid + 1; - else if (midVal > key) - high = mid - 1; - else - return mid; // key found - } - return -(low + 1); // key not found. - } -} diff --git a/src/main/java/cn/nukkit/level/format/anvil/palette/CharPalette.java b/src/main/java/cn/nukkit/level/format/anvil/palette/CharPalette.java deleted file mode 100644 index 4e18cde54b5..00000000000 --- a/src/main/java/cn/nukkit/level/format/anvil/palette/CharPalette.java +++ /dev/null @@ -1,93 +0,0 @@ -package cn.nukkit.level.format.anvil.palette; - -import java.util.Arrays; - -/** - * @author https://github.com/boy0001/ - */ -public class CharPalette { - private static char[] CHAR0 = new char[0]; - private char[] keys = CHAR0; - private char lastIndex = Character.MAX_VALUE; - - public void add(char key) { - keys = insert(key); - lastIndex = Character.MAX_VALUE; - } - - protected void set(char[] keys) { - this.keys = keys; - lastIndex = Character.MAX_VALUE; - } - - private char[] insert(char val) { - lastIndex = Character.MAX_VALUE; - if (keys.length == 0) { - return new char[] { val }; - } - else if (val < keys[0]) { - char[] s = new char[keys.length + 1]; - System.arraycopy(keys, 0, s, 1, keys.length); - s[0] = val; - return s; - } else if (val > keys[keys.length - 1]) { - char[] s = Arrays.copyOf(keys, keys.length + 1); - s[keys.length] = val; - return s; - } - char[] s = Arrays.copyOf(keys, keys.length + 1); - for (int i = 0; i < s.length; i++) { - if (keys[i] < val) { - continue; - } - System.arraycopy(keys, i, s, i + 1, s.length - i - 1); - s[i] = val; - break; - } - return s; - } - - public char getKey(int index) { - return keys[index]; - } - - public char getValue(char key) { - char lastTmp = lastIndex; - boolean hasLast = lastTmp != Character.MAX_VALUE; - int index; - if (hasLast) { - char lastKey = keys[lastTmp]; - if (lastKey == key) return lastTmp; - if (lastKey > key) { - index = binarySearch0(0, lastTmp, key); - } else { - index = binarySearch0(lastTmp + 1, keys.length, key); - } - } else { - index = binarySearch0(0, keys.length, key); - } - if (index >= keys.length || index < 0) { - return lastIndex = Character.MAX_VALUE; - } else { - return lastIndex = (char) index; - } - } - - private int binarySearch0(int fromIndex, int toIndex, char key) { - int low = fromIndex; - int high = toIndex - 1; - - while (low <= high) { - int mid = (low + high) >>> 1; - char midVal = keys[mid]; - - if (midVal < key) - low = mid + 1; - else if (midVal > key) - high = mid - 1; - else - return mid; // key found - } - return -(low + 1); // key not found. - } -} diff --git a/src/main/java/cn/nukkit/level/format/anvil/palette/IntPalette.java b/src/main/java/cn/nukkit/level/format/anvil/palette/IntPalette.java index 86a65209361..3f17f124a8f 100644 --- a/src/main/java/cn/nukkit/level/format/anvil/palette/IntPalette.java +++ b/src/main/java/cn/nukkit/level/format/anvil/palette/IntPalette.java @@ -3,10 +3,11 @@ import java.util.Arrays; /** - * @author https://github.com/boy0001/ + * @author ... */ public class IntPalette { - private static int[] INT0 = new int[0]; + + private static final int[] INT0 = new int[0]; private int[] keys = INT0; private int lastIndex = Integer.MIN_VALUE; @@ -15,11 +16,6 @@ public void add(int key) { lastIndex = Integer.MIN_VALUE; } - protected void set(int[] keys) { - this.keys = keys; - lastIndex = Integer.MIN_VALUE; - } - private int[] insert(int val) { lastIndex = Integer.MIN_VALUE; if (keys.length == 0) { diff --git a/src/main/java/cn/nukkit/level/format/anvil/util/BlockStorage.java b/src/main/java/cn/nukkit/level/format/anvil/util/BlockStorage.java index fbeb28121da..c1ad91559a3 100644 --- a/src/main/java/cn/nukkit/level/format/anvil/util/BlockStorage.java +++ b/src/main/java/cn/nukkit/level/format/anvil/util/BlockStorage.java @@ -1,13 +1,12 @@ package cn.nukkit.level.format.anvil.util; +import cn.nukkit.block.Block; import cn.nukkit.level.GlobalBlockPalette; import cn.nukkit.level.util.PalettedBlockStorage; import cn.nukkit.utils.BinaryStream; -import com.google.common.base.Preconditions; - -import java.util.Arrays; public class BlockStorage { + private static final int SECTION_SIZE = 4096; private final byte[] blockIds; private final NibbleArray blockData; @@ -24,7 +23,7 @@ private BlockStorage(byte[] blockIds, NibbleArray blockData) { private static int getIndex(int x, int y, int z) { int index = (x << 8) + (z << 4) + y; // XZY = Bedrock format - Preconditions.checkArgument(index >= 0 && index < SECTION_SIZE, "Invalid index"); + if (index < 0 || index >= SECTION_SIZE) throw new IllegalArgumentException("Invalid index"); return index; } @@ -49,60 +48,66 @@ public int getFullBlock(int x, int y, int z) { } public void setFullBlock(int x, int y, int z, int value) { - this.setFullBlock(getIndex(x, y, z), (short) value); + this.setFullBlock(getIndex(x, y, z), value); } public int getAndSetFullBlock(int x, int y, int z, int value) { - return getAndSetFullBlock(getIndex(x, y, z), (short) value); + return getAndSetFullBlock(getIndex(x, y, z), value); } - private int getAndSetFullBlock(int index, short value) { - Preconditions.checkArgument(value < 0xfff, "Invalid full block"); - byte oldBlock = blockIds[index]; + private int getAndSetFullBlock(int index, int value) { + // Convert to old data bits + int block = value >> Block.DATA_BITS; + int meta = value & Block.DATA_MASK; + value = (block << 4) + Math.min(meta, 15); + + if (value >= 0x1fff) throw new IllegalArgumentException("Invalid full block " + value); + int oldBlock = blockIds[index] & 0xff; byte oldData = blockData.get(index); - byte newBlock = (byte) ((value & 0xff0) >> 4); byte newData = (byte) (value & 0xf); - if (oldBlock != newBlock) { - blockIds[index] = newBlock; + if (oldBlock != block) { + blockIds[index] = (byte) (block & 0xff); } if (oldData != newData) { blockData.set(index, newData); } - return ((oldBlock & 0xff) << 4) | oldData; - } - private int getFullBlock(int index) { - byte block = blockIds[index]; - byte data = blockData.get(index); - return ((block & 0xff) << 4) | data; + // Convert to new data bits + return (oldBlock << Block.DATA_BITS) | oldData; } - private void setFullBlock(int index, short value) { - Preconditions.checkArgument(value < 0xfff, "Invalid full block"); - byte block = (byte) ((value & 0xff0) >> 4); - byte data = (byte) (value & 0xf); + private int getFullBlock(int index) { + int b = blockIds[index] & 0xff; - blockIds[index] = block; - blockData.set(index, data); + // Convert to new data bits + return (b << Block.DATA_BITS) | blockData.get(index); } - public byte[] getBlockIds() { - return Arrays.copyOf(blockIds, blockIds.length); - } + private void setFullBlock(int index, int value) { + // Convert to old data bits + int block = value >> Block.DATA_BITS; + int meta = value & Block.DATA_MASK; + value = (block << 4) + Math.min(meta, 15); - public byte[] getBlockData() { - return blockData.getData(); + if (value >= 0x1fff) throw new IllegalArgumentException("Invalid full block " + value); + blockIds[index] = (byte) (block & 0xff); + blockData.set(index, (byte) (value & 0xf)); } public void writeTo(BinaryStream stream) { - PalettedBlockStorage storage = PalettedBlockStorage.createFromBlockPalette(); + stream.putByte((byte) 8); // paletted + + PalettedBlockStorage layer = PalettedBlockStorage.createFromBlockPalette(); for (int i = 0; i < SECTION_SIZE; i++) { - storage.setBlock(i, GlobalBlockPalette.getOrCreateRuntimeId(blockIds[i] & 0xff, blockData.get(i))); + layer.setBlock(i, GlobalBlockPalette.getOrCreateRuntimeId(blockIds[i] & 0xff, blockData.get(i))); } - storage.writeTo(stream); + + stream.putByte((byte) 1); // layers + + layer.writeTo(stream); } public BlockStorage copy() { return new BlockStorage(blockIds.clone(), blockData.copy()); } -} \ No newline at end of file +} diff --git a/src/main/java/cn/nukkit/level/format/anvil/util/NibbleArray.java b/src/main/java/cn/nukkit/level/format/anvil/util/NibbleArray.java index 45ebe670cc8..a8bf00db46e 100644 --- a/src/main/java/cn/nukkit/level/format/anvil/util/NibbleArray.java +++ b/src/main/java/cn/nukkit/level/format/anvil/util/NibbleArray.java @@ -3,11 +3,14 @@ import com.google.common.base.Preconditions; +import java.util.Arrays; + public class NibbleArray implements Cloneable { + private final byte[] data; public NibbleArray(int length) { - data = new byte[length / 2]; + data = new byte[(length >> 1)]; } public NibbleArray(byte[] array) { @@ -15,8 +18,8 @@ public NibbleArray(byte[] array) { } public byte get(int index) { - Preconditions.checkElementIndex(index, data.length * 2); - byte val = data[index / 2]; + if (index >= data.length << 1) throw new IndexOutOfBoundsException("index=" + index + ", data.length=" + data.length); + byte val = data[index >> 1]; if ((index & 1) == 0) { return (byte) (val & 0x0f); } else { @@ -25,10 +28,13 @@ public byte get(int index) { } public void set(int index, byte value) { - Preconditions.checkArgument(value >= 0 && value < 16, "Nibbles must have a value between 0 and 15."); - Preconditions.checkElementIndex(index, data.length * 2); + if (value != (value & 15)) { + throw new IllegalArgumentException("Nibbles must have a value between 0 and 15."); + } else if (index >= data.length << 1 || index < 0) { + throw new IndexOutOfBoundsException("index=" + index + ", data.length=" + data.length); + } value &= 0xf; - int half = index / 2; + int half = index >> 1; byte previous = data[half]; if ((index & 1) == 0) { data[half] = (byte) (previous & 0xf0 | value); @@ -37,12 +43,23 @@ public void set(int index, byte value) { } } + public void remove(int index) { + if (index >= data.length << 1 || index < 0) { + throw new IndexOutOfBoundsException("index=" + index + ", data.length=" + data.length); + } + int half = index >> 1; + byte previous = data[half]; + if ((index & 1) == 0) { + data[half] = (byte) (previous & 0xf0); + } else { + data[half] = (byte) (previous & 0x0f); + } + } + public void fill(byte value) { Preconditions.checkArgument(value >= 0 && value < 16, "Nibbles must have a value between 0 and 15."); value &= 0xf; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) ((value << 4) | value); - } + Arrays.fill(data, (byte) ((value << 4) | value)); } public void copyFrom(byte[] bytes) { diff --git a/src/main/java/cn/nukkit/level/format/generic/Anvil2LevelDBConverter.java b/src/main/java/cn/nukkit/level/format/generic/Anvil2LevelDBConverter.java new file mode 100644 index 00000000000..74273d01f0b --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/generic/Anvil2LevelDBConverter.java @@ -0,0 +1,239 @@ +package cn.nukkit.level.format.generic; + +import cn.nukkit.Server; +import cn.nukkit.level.DimensionData; +import cn.nukkit.level.DimensionEnum; +import cn.nukkit.level.Level; +import cn.nukkit.level.format.anvil.Anvil; +import cn.nukkit.level.format.anvil.RegionLoader; +import cn.nukkit.level.format.leveldb.LevelDBProvider; +import cn.nukkit.level.format.leveldb.structure.LevelDBChunk; +import cn.nukkit.level.generator.Generator; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.scheduler.TaskHandler; +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import lombok.RequiredArgsConstructor; +import lombok.ToString; + +import java.io.IOException; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.IntConsumer; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Anvil2LevelDBConverter { + + private final Level sourceLevel; + private final Level targetLevel; + private final ExecutorService executor; + + public Anvil2LevelDBConverter(Level sourceLevel) { + this.sourceLevel = sourceLevel; + + Server server = sourceLevel.getServer(); + String levelName = sourceLevel.getFolderName() + "-convert"; + + if (!server.generateLevel(levelName, 0, Generator.getGenerator("void"))) { + throw new IllegalStateException("Failed to generate target level, make sure it doesn't exist: " + levelName); + } + + this.targetLevel = server.getLevelByName(levelName); + if (this.targetLevel == null) { + throw new IllegalStateException("Failed to load target level: " + levelName); + } + + this.sourceLevel.setAutoSave(false); + this.sourceLevel.isBeingConverted = true; + + this.targetLevel.setAutoSave(false); + this.targetLevel.isBeingConverted = true; + + // DO NOT INCREASE THREAD COUNT + this.executor = Executors.newFixedThreadPool(1, new ThreadFactoryBuilder() + .setNameFormat("Converted Thread " + sourceLevel.getFolderName() + " - %s") + .build()); + } + + public CompletableFuture convert() { + try { + return this.convertUnsafe(); + } catch (Exception e) { + throw new RuntimeException("Failed to convert level " + this.sourceLevel.getFolderName(), e); + } finally { + this.executor.shutdown(); + } + } + + private CompletableFuture convertUnsafe() throws IOException { + Anvil anvil = (Anvil) this.sourceLevel.getProvider(); + LevelDBProvider levelDBProvider = (LevelDBProvider) this.targetLevel.getProvider(); + + Server server = this.sourceLevel.getServer(); + server.getLogger().info("Converting level " + this.targetLevel.getFolderName()); + + // Clone level data + CompoundTag levelData = anvil.getLevelData().clone(); + levelData.putString("generatorName", this.sourceLevel.getGenerator().getName()); + levelData.remove("GameRules"); + levelDBProvider.setLevelData(levelData, this.sourceLevel.getGameRules()); + levelDBProvider.saveLevelData(); + + boolean nether = this.sourceLevel.getDimension() == Level.DIMENSION_NETHER; + DimensionData dimensionData = DimensionEnum.getDataFromId(this.sourceLevel.getDimension()); + if (dimensionData == null) { + server.getLogger().warning("Invalid DimensionData, using OVERWORLD"); + dimensionData = DimensionEnum.OVERWORLD.getDimensionData(); + } + this.targetLevel.setDimensionData(dimensionData); + + List regions = new ObjectArrayList<>(); + Path regionFolder = Paths.get("worlds/" + this.sourceLevel.getFolderName() + "/region"); + try (DirectoryStream stream = Files.newDirectoryStream(regionFolder, "**.mca")) { + for (Path path : stream) { + regions.add(path); + } + } + + AtomicInteger regionCounter = new AtomicInteger(); + AtomicInteger chunksConverted = new AtomicInteger(); + AtomicInteger chunksConvertedPerSecond = new AtomicInteger(); + + TaskHandler tickFuture = server.getScheduler().scheduleRepeatingTask(null, () -> + chunksConvertedPerSecond.set(0), 20); + + IntConsumer callback = chunksCount -> { + chunksConverted.addAndGet(chunksCount); + int regionNumber = regionCounter.incrementAndGet(); + + int chps = chunksConvertedPerSecond.addAndGet(chunksCount); + String message = "[Convert-%s] [%s/%s] [%s chps] Converted %s chunks"; + server.getLogger().info(String.format(message, this.sourceLevel.getFolderName(), regionNumber, regions.size(), chps, chunksCount)); + }; + + List> futures = new ObjectArrayList<>(); + for (Path regionPath : regions) { + CompletableFuture future = new CompletableFuture<>(); + this.executor.execute(() -> { + convertRegion(regionPath, anvil, levelDBProvider, callback, nether ? 128 : 256); + future.complete(null); + }); + futures.add(future); + } + + return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).whenCompleteAsync((v, error) -> { + server.getScheduler().cancelTask(tickFuture.getTaskId()); + if (error != null) { + server.getLogger().error("Failed to convert level " + this.sourceLevel.getFolderName(), error); + } else { + this.convertFinished(); + } + }, task -> server.getScheduler().scheduleTask(null, task)); + } + + private void convertFinished() { + Server server = this.sourceLevel.getServer(); + + server.unloadLevel(this.targetLevel); + + if (sourceLevel.equals(server.getDefaultLevel())) { + server.getLogger().warning("Couldn't unload original level due to it being loaded as the default level. Please restart the server."); + } else { + server.unloadLevel(this.sourceLevel); + } + + server.getLogger().info("[Convert-" + this.sourceLevel.getFolderName() + "] All done! Converted level is saved under worlds/" + this.targetLevel.getFolderName() + "/"); + } + + private static void convertRegion(Path regionFile, Anvil anvil, LevelDBProvider levelDBProvider, IntConsumer callback, int maxY) { + RegionPosition regionPos = RegionPosition.fromPath(regionFile); + assert regionPos != null; + + try { + BaseRegionLoader regionLoader = new RegionLoader(anvil, regionPos.x, regionPos.z); + int chunks = 0; + for (int x = 0; x < 32; x++) { + for (int z = 0; z < 32; z++) { + int chunkX = regionPos.x << 5 | x; + int chunkZ = regionPos.z << 5 | z; + + BaseFullChunk oldChunk = regionLoader.readChunk(chunkX - (getRegionIndexX(chunkX) << 5), chunkZ - (getRegionIndexZ(chunkZ) << 5)); // anvil.getChunk(chunkX, chunkZ, false); + if (oldChunk == null || (!oldChunk.isPopulated() && !oldChunk.isGenerated())) { + continue; + } + + chunks++; + BaseFullChunk newChunk = levelDBProvider.getChunk(chunkX, chunkZ, true); + convertChunk(oldChunk, (LevelDBChunk) newChunk, levelDBProvider, anvil, maxY); + } + } + + callback.accept(chunks); + } catch (IOException e) { + throw new IllegalStateException("Failed to convert region " + regionPos, e); + } + } + + private static void convertChunk(BaseFullChunk oldChunk, LevelDBChunk newChunk, LevelDBProvider levelDBProvider, Anvil anvil, int maxY) { + oldChunk.initChunk(); + newChunk.setGenerated(true); + newChunk.setPopulated(oldChunk.isPopulated()); + + newChunk.setBiomeIdArray(oldChunk.getBiomeIdArray()); + + newChunk.heightMap = Arrays.copyOf(oldChunk.getHeightMapArray(), oldChunk.getHeightMapArray().length); + newChunk.tiles = oldChunk.getBlockEntities(); + newChunk.entities = oldChunk.getEntities(); + newChunk.tileList = oldChunk.tileList; + + for (int blockX = 0; blockX < 16; blockX++) { + for (int blockY = 0; blockY < maxY; blockY++) { + for (int blockZ = 0; blockZ < 16; blockZ++) { + int fullId = oldChunk.getFullBlock(blockX, blockY, blockZ); + newChunk.setFullBlockId(blockX, blockY, blockZ, fullId); + newChunk.setBlockLight(blockX, blockY, blockZ, oldChunk.getBlockSkyLight(blockX, blockY, blockZ)); + } + } + } + + levelDBProvider.saveChunkSync(newChunk.getX(), newChunk.getZ(), newChunk); + levelDBProvider.unloadChunk(newChunk.getX(), newChunk.getZ(), false); + anvil.unloadChunk(oldChunk.getX(), oldChunk.getZ(), false); + } + + protected static int getRegionIndexX(int chunkX) { + return chunkX >> 5; + } + + protected static int getRegionIndexZ(int chunkZ) { + return chunkZ >> 5; + } + + @ToString + @RequiredArgsConstructor + private static class RegionPosition { + private static final Pattern PATTERN = Pattern.compile("^r\\.(-?[0-9]+)\\.(-?[0-9]+)\\.mca$"); + + private final int x; + private final int z; + + static RegionPosition fromPath(Path regionPath) { + Matcher matcher = PATTERN.matcher(regionPath.getFileName().toString()); + if (!matcher.matches()) { + return null; + } + int x = Integer.parseInt(matcher.group(1)); + int z = Integer.parseInt(matcher.group(2)); + return new RegionPosition(x, z); + } + } +} diff --git a/src/main/java/cn/nukkit/level/format/generic/BaseChunk.java b/src/main/java/cn/nukkit/level/format/generic/BaseChunk.java index 4dd5d53ec7c..527e2bdc748 100644 --- a/src/main/java/cn/nukkit/level/format/generic/BaseChunk.java +++ b/src/main/java/cn/nukkit/level/format/generic/BaseChunk.java @@ -2,10 +2,10 @@ import cn.nukkit.Server; import cn.nukkit.block.Block; +import cn.nukkit.block.BlockLayer; import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.level.format.Chunk; import cn.nukkit.level.format.ChunkSection; -import cn.nukkit.level.format.LevelProvider; import cn.nukkit.utils.ChunkException; import java.io.IOException; @@ -14,7 +14,7 @@ import java.util.Arrays; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @@ -22,11 +22,26 @@ public abstract class BaseChunk extends BaseFullChunk implements Chunk { protected ChunkSection[] sections; + @SuppressWarnings("MismatchedReadAndWriteOfArray") + private static final byte[] emptyIdArray = new byte[4096]; + @SuppressWarnings("MismatchedReadAndWriteOfArray") + private static final byte[] emptyDataArray = new byte[2048]; + @Override public BaseChunk clone() { BaseChunk chunk = (BaseChunk) super.clone(); - if (this.biomes != null) chunk.biomes = this.biomes.clone(); - chunk.heightMap = this.getHeightMapArray().clone(); + if (sections != null && sections[0] != null) { + chunk.sections = new ChunkSection[sections.length]; + for (int i = 0; i < sections.length; i++) { + chunk.sections[i] = sections[i].copy(); + } + } + return chunk; + } + + @Override + public BaseChunk cloneForChunkSending() { + BaseChunk chunk = (BaseChunk) super.cloneForChunkSending(); if (sections != null && sections[0] != null) { chunk.sections = new ChunkSection[sections.length]; for (int i = 0; i < sections.length; i++) { @@ -39,13 +54,20 @@ public BaseChunk clone() { private void removeInvalidTile(int x, int y, int z) { BlockEntity entity = getTile(x, y, z); if (entity != null && !entity.isBlockEntityValid()) { - removeBlockEntity(entity); + this.removeBlockEntity(entity); + if (!entity.closed) { + entity.closed = true; + if (entity.level != null) { + entity.level.removeBlockEntity(entity); + entity.level = null; + } + } } } @Override - public int getFullBlock(int x, int y, int z) { - return this.sections[y >> 4].getFullBlock(x, y & 0x0f, z); + public int getFullBlock(int x, int y, int z, BlockLayer layer) { + return this.getSection(y >> 4).getFullBlock(x, y & 0x0f, z, layer); } @Override @@ -54,36 +76,36 @@ public boolean setBlock(int x, int y, int z, int blockId) { } @Override - public Block getAndSetBlock(int x, int y, int z, Block block) { + public Block getAndSetBlock(int x, int y, int z, BlockLayer layer, Block block) { int Y = y >> 4; try { setChanged(); - return this.sections[Y].getAndSetBlock(x, y & 0x0f, z, block); + return this.getSection(Y).getAndSetBlock(x, y & 0x0f, z, layer, block); } catch (ChunkException e) { try { this.setInternalSection(Y, (ChunkSection) this.providerClass.getMethod("createChunkSection", int.class).invoke(this.providerClass, Y)); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) { Server.getInstance().getLogger().logException(e1); } - return this.sections[Y].getAndSetBlock(x, y & 0x0f, z, block); + return this.getSection(Y).getAndSetBlock(x, y & 0x0f, z, layer, block); } finally { removeInvalidTile(x, y, z); } } @Override - public boolean setFullBlockId(int x, int y, int z, int fullId) { + public boolean setFullBlockId(int x, int y, int z, BlockLayer layer, int fullId) { int Y = y >> 4; try { setChanged(); - return this.sections[Y].setFullBlockId(x, y & 0x0f, z, fullId); + return this.getSection(Y).setFullBlockId(x, y & 0x0f, z, layer, fullId); } catch (ChunkException e) { try { this.setInternalSection(Y, (ChunkSection) this.providerClass.getMethod("createChunkSection", int.class).invoke(this.providerClass, Y)); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) { Server.getInstance().getLogger().logException(e1); } - return this.sections[Y].setFullBlockId(x, y & 0x0f, z, fullId); + return this.getSection(Y).setFullBlockId(x, y & 0x0f, z, layer, fullId); } finally { removeInvalidTile(x, y, z); } @@ -91,27 +113,37 @@ public boolean setFullBlockId(int x, int y, int z, int fullId) { @Override public boolean setBlock(int x, int y, int z, int blockId, int meta) { + return this.setBlockAtLayer(x, y, z, BlockLayer.NORMAL, blockId, meta); + } + + @Override + public boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int id) { + return this.setBlockAtLayer(x, y, z, layer, id, 0); + } + + @Override + public boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int blockId, int meta) { int Y = y >> 4; try { setChanged(); - return this.sections[Y].setBlock(x, y & 0x0f, z, blockId, meta); + return this.getSection(Y).setBlockAtLayer(x, y & 0x0f, z, layer, blockId, meta); } catch (ChunkException e) { try { this.setInternalSection(Y, (ChunkSection) this.providerClass.getMethod("createChunkSection", int.class).invoke(this.providerClass, Y)); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) { Server.getInstance().getLogger().logException(e1); } - return this.sections[Y].setBlock(x, y & 0x0f, z, blockId, meta); + return this.getSection(Y).setBlockAtLayer(x, y & 0x0f, z, layer, blockId, meta); } finally { removeInvalidTile(x, y, z); } } @Override - public void setBlockId(int x, int y, int z, int id) { + public void setBlockId(int x, int y, int z, BlockLayer layer, int id) { int Y = y >> 4; try { - this.sections[Y].setBlockId(x, y & 0x0f, z, id); + this.getSection(Y).setBlockId(x, y & 0x0f, z, layer, id); setChanged(); } catch (ChunkException e) { try { @@ -119,27 +151,26 @@ public void setBlockId(int x, int y, int z, int id) { } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) { Server.getInstance().getLogger().logException(e1); } - this.sections[Y].setBlockId(x, y & 0x0f, z, id); + this.getSection(Y).setBlockId(x, y & 0x0f, z, layer, id); } finally { removeInvalidTile(x, y, z); } } - @Override - public int getBlockId(int x, int y, int z) { - return this.sections[y >> 4].getBlockId(x, y & 0x0f, z); + public int getBlockId(int x, int y, int z, BlockLayer layer) { + return this.getSection(y >> 4).getBlockId(x, y & 0x0f, z, layer); } @Override - public int getBlockData(int x, int y, int z) { - return this.sections[y >> 4].getBlockData(x, y & 0x0f, z); + public int getBlockData(int x, int y, int z, BlockLayer layer) { + return this.getSection(y >> 4).getBlockData(x, y & 0x0f, z, layer); } @Override - public void setBlockData(int x, int y, int z, int data) { + public void setBlockData(int x, int y, int z, BlockLayer layer, int data) { int Y = y >> 4; try { - this.sections[Y].setBlockData(x, y & 0x0f, z, data); + this.getSection(Y).setBlockData(x, y & 0x0f, z, layer, data); setChanged(); } catch (ChunkException e) { try { @@ -147,7 +178,7 @@ public void setBlockData(int x, int y, int z, int data) { } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) { Server.getInstance().getLogger().logException(e1); } - this.sections[Y].setBlockData(x, y & 0x0f, z, data); + this.getSection(Y).setBlockData(x, y & 0x0f, z, layer, data); } finally { removeInvalidTile(x, y, z); } @@ -155,14 +186,14 @@ public void setBlockData(int x, int y, int z, int data) { @Override public int getBlockSkyLight(int x, int y, int z) { - return this.sections[y >> 4].getBlockSkyLight(x, y & 0x0f, z); + return this.getSection(y >> 4).getBlockSkyLight(x, y & 0x0f, z); } @Override public void setBlockSkyLight(int x, int y, int z, int level) { int Y = y >> 4; try { - this.sections[Y].setBlockSkyLight(x, y & 0x0f, z, level); + this.getSection(Y).setBlockSkyLight(x, y & 0x0f, z, level); setChanged(); } catch (ChunkException e) { try { @@ -170,20 +201,20 @@ public void setBlockSkyLight(int x, int y, int z, int level) { } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) { Server.getInstance().getLogger().logException(e1); } - this.sections[Y].setBlockSkyLight(x, y & 0x0f, z, level); + this.getSection(Y).setBlockSkyLight(x, y & 0x0f, z, level); } } @Override public int getBlockLight(int x, int y, int z) { - return this.sections[y >> 4].getBlockLight(x, y & 0x0f, z); + return this.getSection(y >> 4).getBlockLight(x, y & 0x0f, z); } @Override public void setBlockLight(int x, int y, int z, int level) { int Y = y >> 4; try { - this.sections[Y].setBlockLight(x, y & 0x0f, z, level); + this.getSection(Y).setBlockLight(x, y & 0x0f, z, level); setChanged(); } catch (ChunkException e) { try { @@ -191,35 +222,39 @@ public void setBlockLight(int x, int y, int z, int level) { } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) { Server.getInstance().getLogger().logException(e1); } - this.sections[Y].setBlockLight(x, y & 0x0f, z, level); + this.getSection(Y).setBlockLight(x, y & 0x0f, z, level); } } @Override public boolean isSectionEmpty(float fY) { - return this.sections[(int) fY] instanceof EmptyChunkSection; + return this.getSection(fY) instanceof EmptyChunkSection; } @Override public ChunkSection getSection(float fY) { - return this.sections[(int) fY]; + int index = (this.getSectionOffset() + (int) fY); + if (index >= this.sections.length) { + Throwable t = new Throwable("Tried to get chunk section " + index + ", but chunk has only " + this.sections.length + " sections!"); + this.getProvider().getLevel().getServer().getLogger().logException(t); + index = this.sections.length - 1; + } + return this.sections[index]; } @Override public boolean setSection(float fY, ChunkSection section) { - byte[] emptyIdArray = new byte[4096]; - byte[] emptyDataArray = new byte[2048]; if (Arrays.equals(emptyIdArray, section.getIdArray()) && Arrays.equals(emptyDataArray, section.getDataArray())) { - this.sections[(int) fY] = EmptyChunkSection.EMPTY[(int) fY]; + this.sections[this.getSectionOffset() + (int) fY] = EmptyChunkSection.EMPTY[(int) fY]; } else { - this.sections[(int) fY] = section; + this.sections[this.getSectionOffset() + (int) fY] = section; } setChanged(); return true; } private void setInternalSection(float fY, ChunkSection section) { - this.sections[(int) fY] = section; + this.sections[this.getSectionOffset() + (int) fY] = section; setChanged(); } @@ -230,41 +265,41 @@ public boolean load() throws IOException { @Override public boolean load(boolean generate) throws IOException { - return this.getProvider() != null && this.getProvider().getChunk(this.getX(), this.getZ(), true) != null; + return this.provider != null && this.provider.getChunk(this.getX(), this.getZ(), true) != null; } @Override public byte[] getBlockIdArray() { - ByteBuffer buffer = ByteBuffer.allocate(4096 * SECTION_COUNT); + ByteBuffer buffer = ByteBuffer.allocate(65536); for (int y = 0; y < SECTION_COUNT; y++) { - buffer.put(this.sections[y].getIdArray()); + buffer.put(this.getSection(y).getIdArray()); } return buffer.array(); } @Override public byte[] getBlockDataArray() { - ByteBuffer buffer = ByteBuffer.allocate(2048 * SECTION_COUNT); + ByteBuffer buffer = ByteBuffer.allocate(32768); for (int y = 0; y < SECTION_COUNT; y++) { - buffer.put(this.sections[y].getDataArray()); + buffer.put(this.getSection(y).getDataArray()); } return buffer.array(); } @Override public byte[] getBlockSkyLightArray() { - ByteBuffer buffer = ByteBuffer.allocate(2048 * SECTION_COUNT); + ByteBuffer buffer = ByteBuffer.allocate(32768); for (int y = 0; y < SECTION_COUNT; y++) { - buffer.put(this.sections[y].getSkyLightArray()); + buffer.put(this.getSection(y).getSkyLightArray()); } return buffer.array(); } @Override public byte[] getBlockLightArray() { - ByteBuffer buffer = ByteBuffer.allocate(2048 * SECTION_COUNT); + ByteBuffer buffer = ByteBuffer.allocate(32768); for (int y = 0; y < SECTION_COUNT; y++) { - buffer.put(this.sections[y].getLightArray()); + buffer.put(this.getSection(y).getLightArray()); } return buffer.array(); } @@ -273,14 +308,4 @@ public byte[] getBlockLightArray() { public ChunkSection[] getSections() { return sections; } - - @Override - public byte[] getHeightMapArray() { - return this.heightMap; - } - - @Override - public LevelProvider getProvider() { - return this.provider; - } } diff --git a/src/main/java/cn/nukkit/level/format/generic/BaseFullChunk.java b/src/main/java/cn/nukkit/level/format/generic/BaseFullChunk.java index 0b9127a2ba7..0a2e4864c14 100644 --- a/src/main/java/cn/nukkit/level/format/generic/BaseFullChunk.java +++ b/src/main/java/cn/nukkit/level/format/generic/BaseFullChunk.java @@ -1,13 +1,16 @@ package cn.nukkit.level.format.generic; import cn.nukkit.Player; -import cn.nukkit.block.Block; +import cn.nukkit.block.BlockLayer; import cn.nukkit.blockentity.BlockEntity; +import cn.nukkit.blockentity.PersistentDataContainerBlockEntity; import cn.nukkit.entity.Entity; import cn.nukkit.level.ChunkManager; import cn.nukkit.level.Level; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.format.LevelProvider; +import cn.nukkit.level.persistence.PersistentDataContainer; +import cn.nukkit.math.Vector3; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.ListTag; import cn.nukkit.nbt.tag.NumberTag; @@ -22,10 +25,11 @@ import java.util.Map; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class BaseFullChunk implements FullChunk, ChunkManager { + protected Map entities; protected Map tiles; @@ -34,19 +38,11 @@ public abstract class BaseFullChunk implements FullChunk, ChunkManager { /** * encoded as: - * + *

* (x << 4) | z */ protected byte[] biomes; - protected byte[] blocks; - - protected byte[] data; - - protected byte[] skyLight; - - protected byte[] blockLight; - protected byte[] heightMap; protected List NBTtiles; @@ -76,59 +72,67 @@ public BaseFullChunk clone() { } catch (CloneNotSupportedException e) { return null; } + if (this.biomes != null) { chunk.biomes = this.biomes.clone(); } - if (this.blocks != null) { - chunk.blocks = this.blocks.clone(); + if (this.heightMap != null) { + chunk.heightMap = this.heightMap.clone(); } + return chunk; + } - if (this.data != null) { - chunk.data = this.data.clone(); + protected BaseFullChunk cloneForChunkSending() { + BaseFullChunk chunk; + try { + chunk = (BaseFullChunk) super.clone(); + } catch (CloneNotSupportedException e) { + return null; } - if (this.skyLight != null) { - chunk.skyLight = this.skyLight.clone(); + if (this.tiles != null) { + chunk.tiles = new Long2ObjectOpenHashMap<>(this.tiles); } - if (this.blockLight != null) { - chunk.blockLight = this.blockLight.clone(); - } + // No need to deep clone biome data as we don't modify them - if (this.heightMap != null) { - chunk.heightMap = this.getHeightMapArray().clone(); - } + // Not needed for chunk sending + chunk.entities = null; + chunk.tileList = null; + chunk.NBTentities = null; + chunk.NBTtiles = null; + chunk.extraData = null; + chunk.heightMap = null; return chunk; } public void setChunkPacket(BatchPacket packet) { if (packet != null) { packet.trim(); + this.chunkPacket = packet; } - this.chunkPacket = packet; } public BatchPacket getChunkPacket() { - BatchPacket pk = chunkPacket; + BatchPacket pk = this.chunkPacket; if (pk != null) { pk.trim(); } - return chunkPacket; + return pk; } public void initChunk() { if (this.getProvider() != null && !this.isInit) { boolean changed = false; if (this.NBTentities != null) { - this.getProvider().getLevel().timings.syncChunkLoadEntitiesTimer.startTiming(); for (CompoundTag nbt : NBTentities) { if (!nbt.contains("id")) { this.setChanged(); continue; } ListTag pos = nbt.getList("Pos"); - if ((((NumberTag) pos.get(0)).getData().intValue() >> 4) != this.getX() || ((((NumberTag) pos.get(2)).getData().intValue() >> 4) != this.getZ())) { + if ((((NumberTag) pos.get(0)).getData().intValue() >> 4) != this.x || ((((NumberTag) pos.get(2)).getData().intValue() >> 4) != this.z)) { changed = true; continue; } @@ -137,29 +141,26 @@ public void initChunk() { changed = true; } } - this.getProvider().getLevel().timings.syncChunkLoadEntitiesTimer.stopTiming(); this.NBTentities = null; } if (this.NBTtiles != null) { - this.getProvider().getLevel().timings.syncChunkLoadBlockEntitiesTimer.startTiming(); for (CompoundTag nbt : NBTtiles) { if (nbt != null) { if (!nbt.contains("id")) { changed = true; continue; } - if ((nbt.getInt("x") >> 4) != this.getX() || ((nbt.getInt("z") >> 4) != this.getZ())) { + if ((nbt.getInt("x") >> 4) != this.x || ((nbt.getInt("z") >> 4) != this.z)) { changed = true; continue; } - BlockEntity blockEntity = BlockEntity.createBlockEntity(nbt.getString("id"), this, nbt); + BlockEntity blockEntity = BlockEntity.createBlockEntity(nbt.getString("id").replaceFirst("BlockEntity", ""), this, nbt); if (blockEntity == null) { changed = true; } } } - this.getProvider().getLevel().timings.syncChunkLoadBlockEntitiesTimer.stopTiming(); this.NBTtiles = null; } @@ -193,12 +194,12 @@ public void setPosition(int x, int z) { public final void setX(int x) { this.x = x; - this.hash = Level.chunkHash(x, getZ()); + this.hash = Level.chunkHash(x, z); } public final void setZ(int z) { this.z = z; - this.hash = Level.chunkHash(getX(), z); + this.hash = Level.chunkHash(x, z); } @Override @@ -210,7 +211,7 @@ public LevelProvider getProvider() { public void setProvider(LevelProvider provider) { this.provider = provider; - if(provider != null) { + if (provider != null) { this.providerClass = provider.getClass(); } } @@ -222,10 +223,14 @@ public int getBiomeId(int x, int z) { @Override public void setBiomeId(int x, int z, byte biomeId) { - this.setChanged(); this.biomes[(x << 4) | z] = biomeId; } + @Override + public void setBiomeId(int x, int z, int biomeId) { + this.biomes[(x << 4) | z] = (byte) biomeId; + } + @Override public int getHeightMap(int x, int z) { return this.heightMap[(z << 4) | x] & 0xFF; @@ -266,12 +271,12 @@ public void setBlockExtraData(int x, int y, int z, int data) { this.extraData.put(Level.chunkBlockHash(x, y, z), data); } - this.setChanged(true); + this.setChanged(); } @Override public void populateSkyLight() { - for (int z = 0; z < 16; ++z) { + /*for (int z = 0; z < 16; ++z) { for (int x = 0; x < 16; ++x) { int top = this.getHeightMap(x, z); for (int y = 255; y > top; --y) { @@ -285,7 +290,7 @@ public void populateSkyLight() { } this.setHeightMap(x, z, this.getHighestBlockAt(x, z, false)); } - } + }*/ } @Override @@ -301,9 +306,11 @@ public int getHighestBlockAt(int x, int z, boolean cache) { return h; } } - for (int y = 255; y >= 0; --y) { + for (int y = this.provider.getLevel().getMaxBlockY(); y >= this.provider.getLevel().getMinBlockY(); --y) { if (getBlockId(x, y, z) != 0x00) { - this.setHeightMap(x, z, y); + if (cache) { + this.setHeightMap(x, z, y); + } return y; } } @@ -338,10 +345,13 @@ public void addBlockEntity(BlockEntity blockEntity) { this.tileList = new Int2ObjectOpenHashMap<>(); } this.tiles.put(blockEntity.getId(), blockEntity); - int index = ((blockEntity.getFloorZ() & 0x0f) << 12) | ((blockEntity.getFloorX() & 0x0f) << 8) | (blockEntity.getFloorY() & 0xff); + + int y = blockEntity.getFloorY() - this.getProvider().getLevel().getMinBlockY(); + int index = ((blockEntity.getFloorZ() & 0x0f) << 16) | ((blockEntity.getFloorX() & 0x0f) << 12) | y; if (this.tileList.containsKey(index) && !this.tileList.get(index).equals(blockEntity)) { BlockEntity entity = this.tileList.get(index); this.tiles.remove(entity.getId()); + entity.onReplacedWith(blockEntity); entity.close(); } this.tileList.put(index, blockEntity); @@ -354,14 +364,25 @@ public void addBlockEntity(BlockEntity blockEntity) { public void removeBlockEntity(BlockEntity blockEntity) { if (this.tiles != null) { this.tiles.remove(blockEntity.getId()); - int index = ((blockEntity.getFloorZ() & 0x0f) << 12) | ((blockEntity.getFloorX() & 0x0f) << 8) | (blockEntity.getFloorY() & 0xff); - this.tileList.remove(index); + int y = blockEntity.getFloorY() - this.getProvider().getLevel().getMinBlockY(); + this.tileList.remove(((blockEntity.getFloorZ() & 0x0f) << 16) | ((blockEntity.getFloorX() & 0x0f) << 12) | y); + + if (!(blockEntity instanceof PersistentDataContainerBlockEntity) && blockEntity.hasPersistentDataContainer()) { + this.createPersistentBlockContainer(blockEntity, blockEntity.getPersistentDataContainer().getStorage()); + } + if (this.isInit) { this.setChanged(); } } } + private BlockEntity createPersistentBlockContainer(Vector3 pos, CompoundTag storage) { + CompoundTag tag = BlockEntity.getDefaultCompound(pos, BlockEntity.PERSISTENT_CONTAINER); + tag.putCompound(PersistentDataContainer.STORAGE_TAG, storage); + return BlockEntity.createBlockEntity(BlockEntity.PERSISTENT_CONTAINER, this, tag); + } + @Override public Map getEntities() { return entities == null ? Collections.emptyMap() : entities; @@ -379,12 +400,13 @@ public Map getBlockExtraDataArray() { @Override public BlockEntity getTile(int x, int y, int z) { - return this.tileList != null ? this.tileList.get((z << 12) | (x << 8) | y) : null; + int capY = this.getProvider() == null ? y : y - this.getProvider().getLevel().getMinBlockY(); //TODO: better fix + return this.tileList != null ? this.tileList.get((z << 16) | (x << 12) | capY) : null; } @Override public boolean isLoaded() { - return this.getProvider() != null && this.getProvider().isChunkLoaded(this.getX(), this.getZ()); + return this.getProvider() != null && this.getProvider().isChunkLoaded(this.x, this.z); } @Override @@ -394,12 +416,12 @@ public boolean load() throws IOException { @Override public boolean load(boolean generate) throws IOException { - return this.getProvider() != null && this.getProvider().getChunk(this.getX(), this.getZ(), true) != null; + return this.getProvider() != null && this.getProvider().getChunk(this.x, this.z, true) != null; } @Override public boolean unload() throws Exception { - return this.unload(true, true); + return this.unload(provider.getLevel().isSaveOnUnloadEnabled(), true); } @Override @@ -413,8 +435,21 @@ public boolean unload(boolean save, boolean safe) { if (provider == null) { return true; } - if (save && this.changes != 0) { - provider.saveChunk(this.getX(), this.getZ()); + if (save) { + boolean needSave = this.hasChanged(); + + if (!needSave) { + for (Entity e : this.getEntities().values()) { + if (e.canSaveToStorage() && !e.ignoredAsSaveReason()) { + needSave = true; + break; + } + } + } + + if (needSave) { + provider.saveChunk(this.x, this.z, this); + } } if (safe) { for (Entity entity : this.getEntities().values()) { @@ -439,22 +474,22 @@ public boolean unload(boolean save, boolean safe) { @Override public byte[] getBlockIdArray() { - return this.blocks; + return new byte[0]; } @Override public byte[] getBlockDataArray() { - return this.data; + return new byte[0]; } @Override public byte[] getBlockSkyLightArray() { - return this.skyLight; + return new byte[0]; } @Override public byte[] getBlockLightArray() { - return this.blockLight; + return new byte[0]; } @Override @@ -462,6 +497,11 @@ public byte[] getBiomeIdArray() { return this.biomes; } + @Override + public void setBiomeIdArray(byte[] biomeIdArray) { + this.biomes = biomeIdArray; + } + @Override public byte[] getHeightMapArray() { return this.heightMap; @@ -479,7 +519,7 @@ public boolean hasChanged() { @Override public void setChanged() { this.changes++; - chunkPacket = null; + this.chunkPacket = null; } @Override @@ -511,54 +551,66 @@ public void setLightPopulated(boolean value) { } - @Override - public int getBlockIdAt(int x, int y, int z) { - if (x >> 4 == getX() && z >> 4 == getZ()) { - return getBlockId(x & 15, y, z & 15); + public int getBlockIdAt(int x, int y, int z, BlockLayer layer) { + if (x >> 4 == this.x && z >> 4 == this.z) { + return getBlockId(x & 15, y, z & 15, layer); } return 0; } @Override - public void setBlockFullIdAt(int x, int y, int z, int fullId) { - if (x >> 4 == getX() && z >> 4 == getZ()) { - setFullBlockId(x & 15, y, z & 15, fullId); + public void setBlockFullIdAt(int x, int y, int z, BlockLayer layer, int fullId) { + if (x >> 4 == this.x && z >> 4 == this.z) { + setFullBlockId(x & 15, y, z & 15, layer, fullId); } } @Override - public void setBlockIdAt(int x, int y, int z, int id) { - if (x >> 4 == getX() && z >> 4 == getZ()) { - setBlockId(x & 15, y, z & 15, id); + public void setBlockIdAt(int x, int y, int z, BlockLayer layer, int id) { + if (x >> 4 == this.x && z >> 4 == this.z) { + setBlockId(x & 15, y, z & 15, layer, id); } } @Override public void setBlockAt(int x, int y, int z, int id, int data) { - if (x >> 4 == getX() && z >> 4 == getZ()) { + if (x >> 4 == this.x && z >> 4 == this.z) { setBlock(x & 15, y, z & 15, id, data); } } @Override - public int getBlockDataAt(int x, int y, int z) { - if (x >> 4 == getX() && z >> 4 == getZ()) { - return getBlockIdAt(x & 15, y, z & 15); + public boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int blockId, int meta) { + int oldId = this.getBlockId(x, y, z, layer); + int oldData = this.getBlockData(x, y, z, layer); + if (oldId != blockId || oldData != meta) { + this.setBlockAtLayer(x, y, z, layer, blockId); + this.setBlockData(x, y, z, layer, meta); + return true; + } else { + return false; + } + } + + @Override + public int getBlockDataAt(int x, int y, int z, BlockLayer layer) { + if (x >> 4 == this.x && z >> 4 == this.z) { + return getBlockIdAt(x & 15, y, z & 15, layer); } return 0; } @Override - public void setBlockDataAt(int x, int y, int z, int data) { - if (x >> 4 == getX() && z >> 4 == getZ()) { - setBlockData(x & 15, y, z & 15, data); + public void setBlockDataAt(int x, int y, int z, BlockLayer layer, int data) { + if (x >> 4 == this.x && z >> 4 == this.z) { + setBlockData(x & 15, y, z & 15, layer, data); } } @Override public BaseFullChunk getChunk(int chunkX, int chunkZ) { - if (chunkX == getX() && chunkZ == getZ()) return this; + if (chunkX == x && chunkZ == z) return this; return null; } @@ -578,9 +630,8 @@ public long getSeed() { } public boolean compress() { - BatchPacket pk = chunkPacket; - if (pk != null) { - pk.trim(); + if (this.chunkPacket != null) { + this.chunkPacket.trim(); return true; } return false; diff --git a/src/main/java/cn/nukkit/level/format/generic/BaseLevelProvider.java b/src/main/java/cn/nukkit/level/format/generic/BaseLevelProvider.java index d95f47bd189..996c6975744 100644 --- a/src/main/java/cn/nukkit/level/format/generic/BaseLevelProvider.java +++ b/src/main/java/cn/nukkit/level/format/generic/BaseLevelProvider.java @@ -17,19 +17,20 @@ import it.unimi.dsi.fastutil.objects.ObjectIterator; import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteOrder; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class BaseLevelProvider implements LevelProvider { + protected Level level; protected final String path; @@ -49,12 +50,40 @@ public abstract class BaseLevelProvider implements LevelProvider { public BaseLevelProvider(Level level, String path) throws IOException { this.level = level; this.path = path; + File file_path = new File(this.path); if (!file_path.exists()) { file_path.mkdirs(); } - CompoundTag levelData = NBTIO.readCompressed(new FileInputStream(new File(this.getPath() + "level.dat")), ByteOrder.BIG_ENDIAN); - if (levelData.get("Data") instanceof CompoundTag) { + + CompoundTag levelData = null; + File levelDat = new File(this.path + "level.dat"); + + try { + levelData = NBTIO.readCompressed(Files.newInputStream(levelDat.toPath()), ByteOrder.BIG_ENDIAN); + } catch (Exception ex1) { + Server.getInstance().getLogger().error("Failed to load level.dat in " + file_path.getPath(), ex1); + + try { + File backup = new File(this.path + "level.dat_old"); + + if (backup.exists()) { + Server.getInstance().getLogger().warning("Attempting to load level.dat_old in " + file_path.getPath()); + + // Save a copy of the corrupted one + com.google.common.io.Files.copy(levelDat, new File(this.path + "level.dat_invalid")); + + // Replace the corrupted one with a backup + com.google.common.io.Files.copy(backup, levelDat); + + levelData = NBTIO.readCompressed(Files.newInputStream(levelDat.toPath()), ByteOrder.BIG_ENDIAN); + } + } catch (Exception ex2) { + Server.getInstance().getLogger().error("Failed to load level.dat_old in " + file_path.getPath(), ex2); + } + } + + if (levelData != null && levelData.get("Data") instanceof CompoundTag) { this.levelData = levelData.getCompound("Data"); } else { throw new LevelException("Invalid level.dat"); @@ -83,7 +112,7 @@ public int size() { public void unloadChunks() { ObjectIterator iter = chunks.values().iterator(); while (iter.hasNext()) { - iter.next().unload(true, false); + iter.next().unload(level.isSaveOnUnloadEnabled(), false); iter.remove(); } } @@ -280,7 +309,6 @@ public void doGarbageCollection() { lastRegion.set(null); iter.remove(); } - } } } @@ -289,9 +317,9 @@ public void doGarbageCollection() { public void saveChunks() { synchronized (chunks) { for (BaseFullChunk chunk : this.chunks.values()) { - if (chunk.getChanges() != 0) { + if (chunk.hasChanged()) { chunk.setChanged(false); - this.saveChunk(chunk.getX(), chunk.getZ()); + this.saveChunk(chunk.getX(), chunk.getZ(), chunk); } } } @@ -303,17 +331,24 @@ public CompoundTag getLevelData() { @Override public void saveLevelData() { + String file = this.path + "level.dat"; + File old = new File(file); + if (old.exists()) { + try { + com.google.common.io.Files.copy(old, new File(file + ".bak")); + } catch (IOException e) { + Server.getInstance().getLogger().logException(e); + } + } try { - NBTIO.writeGZIPCompressed(new CompoundTag().putCompound("Data", this.levelData), new FileOutputStream(this.getPath() + "level.dat")); + NBTIO.writeGZIPCompressed(new CompoundTag().putCompound("Data", this.levelData), Files.newOutputStream(Paths.get(file))); } catch (IOException e) { throw new RuntimeException(e); } } public void updateLevelName(String name) { - if (!this.getName().equals(name)) { - this.levelData.putString("LevelName", name); - } + this.levelData.putString("LevelName", name); } @Override @@ -391,25 +426,24 @@ public BaseFullChunk getChunk(int chunkX, int chunkZ, boolean create) { synchronized (chunks) { lastChunk.set(tmp = chunks.get(index)); } - if (tmp != null) { - return tmp; - } else { + if (tmp == null) { tmp = this.loadChunk(index, chunkX, chunkZ, create); lastChunk.set(tmp); - return tmp; } + return tmp; } @Override public void setChunk(int chunkX, int chunkZ, FullChunk chunk) { if (!(chunk instanceof BaseFullChunk)) { - throw new ChunkException("Invalid Chunk class"); + throw new ChunkException("Invalid chunk class (" + chunkX + ", " + chunkZ + ')'); } chunk.setProvider(this); chunk.setPosition(chunkX, chunkZ); long index = Level.chunkHash(chunkX, chunkZ); synchronized (chunks) { - if (this.chunks.containsKey(index) && !this.chunks.get(index).equals(chunk)) { + FullChunk oldChunk = this.chunks.get(index); + if (oldChunk != null && !oldChunk.equals(chunk)) { this.unloadChunk(chunkX, chunkZ, false); } this.chunks.put(index, (BaseFullChunk) chunk); @@ -444,6 +478,8 @@ public synchronized void close() { @Override public boolean isChunkGenerated(int chunkX, int chunkZ) { BaseRegionLoader region = this.getRegion(chunkX >> 5, chunkZ >> 5); - return region != null && region.chunkExists(chunkX - region.getX() * 32, chunkZ - region.getZ() * 32) && this.getChunk(chunkX - region.getX() * 32, chunkZ - region.getZ() * 32, true).isGenerated(); + BaseFullChunk chunk; + return region != null && region.chunkExists(chunkX - (region.getX() << 5), chunkZ - (region.getZ() << 5)) && + (chunk = this.getChunk(chunkX - (region.getX() << 5), chunkZ - (region.getZ() << 5))) != null && chunk.isGenerated(); } } diff --git a/src/main/java/cn/nukkit/level/format/generic/BaseRegionLoader.java b/src/main/java/cn/nukkit/level/format/generic/BaseRegionLoader.java index c75848c3235..ba09a371818 100644 --- a/src/main/java/cn/nukkit/level/format/generic/BaseRegionLoader.java +++ b/src/main/java/cn/nukkit/level/format/generic/BaseRegionLoader.java @@ -2,33 +2,32 @@ import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.format.LevelProvider; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; -import java.util.HashMap; -import java.util.Map; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ abstract public class BaseRegionLoader { - public static final int VERSION = 1; + public static final byte COMPRESSION_GZIP = 1; public static final byte COMPRESSION_ZLIB = 2; public static final int MAX_SECTOR_LENGTH = 256 << 12; - public static final int COMPRESSION_LEVEL = 7; protected int x; protected int z; protected int lastSector; protected LevelProvider levelProvider; - private RandomAccessFile randomAccessFile; + private final RandomAccessFile randomAccessFile; // TODO: A simple array will perform better and use less memory - protected final Map locationTable = new HashMap<>(); + protected final Int2ObjectMap locationTable = new Int2ObjectOpenHashMap<>(); public long lastUsed; @@ -37,7 +36,7 @@ public BaseRegionLoader(LevelProvider level, int regionX, int regionZ, String ex this.x = regionX; this.z = regionZ; this.levelProvider = level; - String filePath = this.levelProvider.getPath() + "region/r." + regionX + "." + regionZ + "." + ext; + String filePath = this.levelProvider.getPath() + "region/r." + regionX + '.' + regionZ + '.' + ext; File file = new File(filePath); boolean exists = file.exists(); if (!exists) { @@ -54,14 +53,10 @@ public BaseRegionLoader(LevelProvider level, int regionX, int regionZ, String ex this.lastUsed = System.currentTimeMillis(); } catch (IOException e) { - throw new RuntimeException(e); + throw new RuntimeException("Unable to load r." + regionX + '.' + regionZ + '.' + ext, e); } } - public void compress() { - // TODO - } - public RandomAccessFile getRandomAccessFile() { return randomAccessFile; } @@ -99,5 +94,4 @@ public void close() throws IOException { public Integer[] getLocationIndexes() { return this.locationTable.keySet().toArray(new Integer[0]); } - } diff --git a/src/main/java/cn/nukkit/level/format/generic/ChunkConverter.java b/src/main/java/cn/nukkit/level/format/generic/ChunkConverter.java deleted file mode 100644 index 35d12f84c36..00000000000 --- a/src/main/java/cn/nukkit/level/format/generic/ChunkConverter.java +++ /dev/null @@ -1,91 +0,0 @@ -package cn.nukkit.level.format.generic; - -import cn.nukkit.level.format.FullChunk; -import cn.nukkit.level.format.LevelProvider; -import cn.nukkit.level.format.anvil.Chunk; -import cn.nukkit.level.format.anvil.ChunkSection; - -import java.util.ArrayList; - -public class ChunkConverter { - - private BaseFullChunk chunk; - private Class toClass; - private LevelProvider provider; - - public ChunkConverter(LevelProvider provider) { - this.provider = provider; - } - - public ChunkConverter from(BaseFullChunk chunk) { - if (!(chunk instanceof cn.nukkit.level.format.mcregion.Chunk) && !(chunk instanceof cn.nukkit.level.format.leveldb.Chunk)) { - throw new IllegalArgumentException("From type can be only McRegion or LevelDB"); - } - this.chunk = chunk; - return this; - } - - public ChunkConverter to(Class toClass) { - if (toClass != Chunk.class) { - throw new IllegalArgumentException("To type can be only Anvil"); - } - this.toClass = toClass; - return this; - } - - public FullChunk perform() { - BaseFullChunk result; - try { - result = (BaseFullChunk) toClass.getMethod("getEmptyChunk", int.class, int.class, LevelProvider.class).invoke(null, chunk.getX(), chunk.getZ(), provider); - } catch (Exception e) { - throw new RuntimeException(e); - } - if (toClass == Chunk.class) { - for (int Y = 0; Y < 8; Y++) { - boolean empty = true; - for (int x = 0; x < 16; x++) { - for (int y = 0; y < 16; y++) { - for (int z = 0; z < 16; z++) { - if (chunk.getBlockId(x, (Y << 4) | y, z) != 0) { - empty = false; - break; - } - } - if (!empty) break; - } - if (!empty) break; - } - if (!empty) { - ChunkSection section = new ChunkSection(Y); - for (int x = 0; x < 16; x++) { - for (int y = 0; y < 16; y++) { - for (int z = 0; z < 16; z++) { - section.setBlockId(x, y, z, chunk.getBlockId(x, (Y << 4) | y, z)); - section.setBlockData(x, y, z, chunk.getBlockData(x, (Y << 4) | y, z)); - section.setBlockLight(x, y, z, chunk.getBlockLight(x, (Y << 4) | y, z)); - section.setBlockSkyLight(x, y, z, chunk.getBlockSkyLight(x, (Y << 4) | y, z)); - } - } - } - ((BaseChunk) result).sections[Y] = section; - } - } - } - System.arraycopy(chunk.biomes, 0, result.biomes, 0, 256); - System.arraycopy(chunk.getHeightMapArray(), 0, result.heightMap, 0, 256); - if (chunk.NBTentities != null && !chunk.NBTentities.isEmpty()) { - result.NBTentities = new ArrayList<>(chunk.NBTentities.size()); - chunk.NBTentities.forEach((nbt) -> result.NBTentities.add(nbt.copy())); - } - - if (chunk.NBTtiles != null && !chunk.NBTtiles.isEmpty()) { - result.NBTtiles = new ArrayList<>(chunk.NBTtiles.size()); - chunk.NBTtiles.forEach((nbt) -> result.NBTtiles.add(nbt.copy())); - } - result.setGenerated(); - result.setPopulated(); - result.setLightPopulated(); - result.initChunk(); - return result; - } -} diff --git a/src/main/java/cn/nukkit/level/format/generic/EmptyChunkSection.java b/src/main/java/cn/nukkit/level/format/generic/EmptyChunkSection.java index adcb277931e..4506c87d8e9 100644 --- a/src/main/java/cn/nukkit/level/format/generic/EmptyChunkSection.java +++ b/src/main/java/cn/nukkit/level/format/generic/EmptyChunkSection.java @@ -1,30 +1,30 @@ package cn.nukkit.level.format.generic; import cn.nukkit.block.Block; +import cn.nukkit.block.BlockLayer; import cn.nukkit.level.format.ChunkSection; -import cn.nukkit.level.util.BitArrayVersion; -import cn.nukkit.level.util.PalettedBlockStorage; import cn.nukkit.utils.BinaryStream; import cn.nukkit.utils.ChunkException; import java.util.Arrays; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EmptyChunkSection implements ChunkSection { + public static final EmptyChunkSection[] EMPTY = new EmptyChunkSection[16]; - private static final PalettedBlockStorage EMPTY_STORAGE = PalettedBlockStorage.createFromBlockPalette(BitArrayVersion.V1); + + public static final byte[] EMPTY_LIGHT_ARR = new byte[2048]; + public static final byte[] EMPTY_SKY_LIGHT_ARR = new byte[2048]; + private static final byte[] EMPTY_ID_ARR = new byte[4096]; static { for (int y = 0; y < EMPTY.length; y++) { EMPTY[y] = new EmptyChunkSection(y); } - } - public static byte[] EMPTY_LIGHT_ARR = new byte[2048]; - public static byte[] EMPTY_SKY_LIGHT_ARR = new byte[2048]; - static { + Arrays.fill(EMPTY_SKY_LIGHT_ARR, (byte) 255); } @@ -40,17 +40,17 @@ public int getY() { } @Override - final public int getBlockId(int x, int y, int z) { + public int getBlockId(int x, int y, int z, BlockLayer layer) { return 0; } @Override - public int getFullBlock(int x, int y, int z) throws ChunkException { + public int getFullBlock(int x, int y, int z, BlockLayer layer) { return 0; } @Override - public Block getAndSetBlock(int x, int y, int z, Block block) { + public Block getAndSetBlock(int x, int y, int z, BlockLayer layer, Block block) { if (block.getId() != 0) throw new ChunkException("Tried to modify an empty Chunk"); return Block.get(0); } @@ -67,14 +67,26 @@ public boolean setBlock(int x, int y, int z, int blockId, int meta) throws Chunk return false; } + @Override + public boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int blockId) { + if (blockId != 0) throw new ChunkException("Tried to modify an empty Chunk"); + return false; + } + + @Override + public boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int blockId, int meta) { + if (blockId != 0) throw new ChunkException("Tried to modify an empty Chunk"); + return false; + } + @Override public byte[] getIdArray() { - return new byte[4096]; + return EMPTY_ID_ARR; } @Override public byte[] getDataArray() { - return new byte[2048]; + return EMPTY_LIGHT_ARR; // empty 2048 } @Override @@ -88,22 +100,22 @@ public byte[] getLightArray() { } @Override - final public void setBlockId(int x, int y, int z, int id) throws ChunkException { + public void setBlockId(int x, int y, int z, BlockLayer layer, int id) { if (id != 0) throw new ChunkException("Tried to modify an empty Chunk"); } @Override - final public int getBlockData(int x, int y, int z) { + public int getBlockData(int x, int y, int z, BlockLayer layer) { return 0; } @Override - public void setBlockData(int x, int y, int z, int data) throws ChunkException { + public void setBlockData(int x, int y, int z, BlockLayer layer, int data) { if (data != 0) throw new ChunkException("Tried to modify an empty Chunk"); } @Override - public boolean setFullBlockId(int x, int y, int z, int fullId) { + public boolean setFullBlockId(int x, int y, int z, BlockLayer layer, int fullId) { if (fullId != 0) throw new ChunkException("Tried to modify an empty Chunk"); return false; } @@ -135,14 +147,17 @@ public boolean isEmpty() { @Override public void writeTo(BinaryStream stream) { - stream.putByte((byte) 8); - stream.putByte((byte) 2); - EMPTY_STORAGE.writeTo(stream); - EMPTY_STORAGE.writeTo(stream); + stream.putByte((byte) 8); // paletted + stream.putByte((byte) 0); // layers } @Override public EmptyChunkSection copy() { return this; } + + @Override + public EmptyChunkSection copyForChunkSending() { + return this; + } } diff --git a/src/main/java/cn/nukkit/level/format/generic/serializer/NetworkChunkData.java b/src/main/java/cn/nukkit/level/format/generic/serializer/NetworkChunkData.java new file mode 100644 index 00000000000..5ad70eedb7f --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/generic/serializer/NetworkChunkData.java @@ -0,0 +1,13 @@ +package cn.nukkit.level.format.generic.serializer; + +import cn.nukkit.level.DimensionData; +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class NetworkChunkData { + + private int chunkSections; + private final DimensionData dimensionData; +} diff --git a/src/main/java/cn/nukkit/level/format/generic/serializer/NetworkChunkSerializer.java b/src/main/java/cn/nukkit/level/format/generic/serializer/NetworkChunkSerializer.java index 37f948d19ad..41fd12f6f34 100644 --- a/src/main/java/cn/nukkit/level/format/generic/serializer/NetworkChunkSerializer.java +++ b/src/main/java/cn/nukkit/level/format/generic/serializer/NetworkChunkSerializer.java @@ -3,6 +3,7 @@ import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.blockentity.BlockEntitySpawnable; import cn.nukkit.level.DimensionData; +import cn.nukkit.level.Level; import cn.nukkit.level.biome.Biome; import cn.nukkit.level.format.ChunkSection; import cn.nukkit.level.format.generic.BaseChunk; @@ -26,8 +27,8 @@ public class NetworkChunkSerializer { private static final byte[] negativeSubChunks; static { - // Build up 4 SubChunks for the extended negative height BinaryStream stream = new BinaryStream(); + // Build up 4 SubChunks for the extended negative height for (int i = 0; i < EXTENDED_NEGATIVE_SUB_CHUNKS; i++) { stream.putByte((byte) 8); // SubChunk version stream.putByte((byte) 0); // 0 layers @@ -35,14 +36,7 @@ public class NetworkChunkSerializer { negativeSubChunks = stream.getBuffer(); } - public static void serialize(BaseChunk chunk, BiConsumer callback, DimensionData dimensionData) { - byte[] blockEntities; - if (chunk.getBlockEntities().isEmpty()) { - blockEntities = new byte[0]; - } else { - blockEntities = serializeEntities(chunk); - } - + public static void serialize(BaseChunk chunk, BiConsumer callback, DimensionData dimensionData) { int subChunkCount = 0; ChunkSection[] sections = chunk.getSections(); for (int i = sections.length - 1; i >= 0; i--) { @@ -52,17 +46,32 @@ public static void serialize(BaseChunk chunk, BiConsumer } } + BinaryStream stream = ThreadCache.binaryStream.get().reset(); + NetworkChunkData chunkData = new NetworkChunkData(subChunkCount, dimensionData); + serialize1_18_30(stream, chunk, sections, chunkData); + + byte[] blockEntities; + if (chunk.getBlockEntities().isEmpty()) { + blockEntities = new byte[0]; + } else { + blockEntities = serializeEntities(chunk); + } + stream.put(blockEntities); + + callback.accept(stream, chunkData); + } + + private static void serialize1_18_30(BinaryStream stream, BaseFullChunk chunk, ChunkSection[] sections, NetworkChunkData chunkData) { + DimensionData dimensionData = chunkData.getDimensionData(); int maxDimensionSections = dimensionData.getHeight() >> 4; - subChunkCount = Math.min(maxDimensionSections, subChunkCount); + int subChunkCount = Math.min(maxDimensionSections, chunkData.getChunkSections()); - // In 1.18 3D biome palettes were introduced. However, current world format - // used internally doesn't support them, so we need to convert from legacy 2D - byte[] biomePalettes = convert2DBiomesTo3D(chunk, maxDimensionSections); - BinaryStream stream = ThreadCache.binaryStream.get().reset(); + byte[] biomePalettes = serialize3DBiomes(chunk, maxDimensionSections); + stream.reset(); // Overworld has negative coordinates, but we currently do not support them int writtenSections = subChunkCount; - if (/*dimensionData.getDimensionId() == Level.DIMENSION_OVERWORLD && subChunkCount < maxDimensionSections*/true) { //TODO: change client dimension + if (dimensionData.getDimensionId() == Level.DIMENSION_OVERWORLD && subChunkCount < maxDimensionSections) { stream.put(negativeSubChunks); writtenSections += EXTENDED_NEGATIVE_SUB_CHUNKS; } @@ -73,8 +82,8 @@ public static void serialize(BaseChunk chunk, BiConsumer stream.put(biomePalettes); stream.putByte((byte) 0); // Border blocks - stream.put(blockEntities); - callback.accept(stream, writtenSections); + + chunkData.setChunkSections(writtenSections); } private static byte[] serializeEntities(BaseChunk chunk) { @@ -92,24 +101,34 @@ private static byte[] serializeEntities(BaseChunk chunk) { } } - private static byte[] convert2DBiomesTo3D(BaseFullChunk chunk, int sections) { - PalettedBlockStorage palette = PalettedBlockStorage.createWithDefaultState(Biome.getBiomeIdOrCorrect(chunk.getBiomeId(0, 0))); - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - int biomeId = Biome.getBiomeIdOrCorrect(chunk.getBiomeId(x, z)); - for (int y = 0; y < 16; y++) { - palette.setBlock(x, y, z, biomeId); + private static byte[] serialize3DBiomes(BaseFullChunk chunk, int sections) { + if (!chunk.has3dBiomes()) { // Convert 2D biomes to 3D + PalettedBlockStorage palette = PalettedBlockStorage.createWithDefaultState(Biome.getBiomeIdOrCorrect(chunk.getBiomeId(0, 0))); + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + int biomeId = chunk.getBiomeId(x, z); + for (int y = 0; y < 16; y++) { + palette.setBlock(x, y, z, biomeId); + } } } + + BinaryStream stream = ThreadCache.binaryStream.get().reset(); + palette.writeTo(stream, Biome::getBiomeIdOrCorrect); + byte[] bytes = stream.getBuffer(); + stream.reset(); + + for (int i = 0; i < sections; i++) { + stream.put(bytes); + } + return stream.getBuffer(); } BinaryStream stream = ThreadCache.binaryStream.get().reset(); - palette.writeTo(stream); - byte[] bytes = stream.getBuffer(); - stream.reset(); - for (int i = 0; i < sections; i++) { - stream.put(bytes); + PalettedBlockStorage storage = chunk.getBiomeStorage(i); + storage.writeTo(stream, Biome::getBiomeIdOrCorrect); + } return stream.getBuffer(); } diff --git a/src/main/java/cn/nukkit/level/format/leveldb/BlockStateMapping.java b/src/main/java/cn/nukkit/level/format/leveldb/BlockStateMapping.java new file mode 100644 index 00000000000..e3d07f7d849 --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/BlockStateMapping.java @@ -0,0 +1,295 @@ +package cn.nukkit.level.format.leveldb; + +import cn.nukkit.block.BlockID; +import cn.nukkit.level.format.leveldb.structure.BlockStateSnapshot; +import cn.nukkit.level.format.leveldb.updater.BlockStateUpdaterChunker; +import cn.nukkit.level.format.leveldb.updater.BlockStateUpdaterVanilla; +import cn.nukkit.utils.MainLogger; +import com.google.common.base.Preconditions; +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import it.unimi.dsi.fastutil.Hash; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.cloudburstmc.blockstateupdater.*; +import org.cloudburstmc.blockstateupdater.util.tagupdater.CompoundTagUpdaterContext; +import org.cloudburstmc.nbt.NbtMap; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import static cn.nukkit.level.format.leveldb.LevelDBConstants.PALETTE_VERSION; + +public class BlockStateMapping { + private static final Logger log = LogManager.getLogger("LevelDB-Logger"); + private static final Logger serverLog = LogManager.getLogger(MainLogger.class); + + private static final CompoundTagUpdaterContext CONTEXT; + private static final int LATEST_UPDATER_VERSION; + private static final BlockStateMapping INSTANCE = new BlockStateMapping(PALETTE_VERSION); + + private static final Cache BLOCK_UPDATE_CACHE = CacheBuilder.newBuilder() + .maximumSize(1024) + .expireAfterAccess(2, TimeUnit.MINUTES) + .build(); + + static { + INSTANCE.setLegacyMapper(new NukkitLegacyMapper()); + NukkitLegacyMapper.registerStates(INSTANCE); + + List updaters = new ArrayList<>(); + updaters.add(BlockStateUpdaterBase.INSTANCE); + updaters.add(BlockStateUpdater_1_10_0.INSTANCE); + updaters.add(BlockStateUpdater_1_12_0.INSTANCE); + updaters.add(BlockStateUpdater_1_13_0.INSTANCE); + updaters.add(BlockStateUpdater_1_14_0.INSTANCE); + updaters.add(BlockStateUpdater_1_15_0.INSTANCE); + updaters.add(BlockStateUpdater_1_16_0.INSTANCE); + updaters.add(BlockStateUpdater_1_16_210.INSTANCE); + updaters.add(BlockStateUpdater_1_17_30.INSTANCE); + updaters.add(BlockStateUpdater_1_17_40.INSTANCE); + updaters.add(BlockStateUpdater_1_18_10.INSTANCE); + updaters.add(BlockStateUpdater_1_18_30.INSTANCE); + updaters.add(BlockStateUpdater_1_19_0.INSTANCE); + updaters.add(BlockStateUpdater_1_19_20.INSTANCE); + updaters.add(BlockStateUpdater_1_19_70.INSTANCE); + updaters.add(BlockStateUpdater_1_19_80.INSTANCE); + updaters.add(BlockStateUpdater_1_20_0.INSTANCE); + updaters.add(BlockStateUpdater_1_20_10.INSTANCE); + updaters.add(BlockStateUpdater_1_20_30.INSTANCE); + updaters.add(BlockStateUpdater_1_20_40.INSTANCE); + updaters.add(BlockStateUpdater_1_20_50.INSTANCE); + updaters.add(BlockStateUpdater_1_20_60.INSTANCE); + updaters.add(BlockStateUpdater_1_20_70.INSTANCE); + updaters.add(BlockStateUpdater_1_20_80.INSTANCE); + updaters.add(BlockStateUpdater_1_21_0.INSTANCE); + updaters.add(BlockStateUpdater_1_21_10.INSTANCE); + updaters.add(BlockStateUpdater_1_21_20.INSTANCE); + updaters.add(BlockStateUpdater_1_21_30.INSTANCE); + updaters.add(BlockStateUpdaterVanilla.INSTANCE); + + boolean chunkerSupport = Boolean.parseBoolean(System.getProperty("leveldb-chunker")); + if (chunkerSupport) { + updaters.add(BlockStateUpdaterChunker.INSTANCE); + serverLog.warn("Enabled chunker.app LevelDB updater. This may impact chunk loading performance!"); + } + + CompoundTagUpdaterContext context = new CompoundTagUpdaterContext(); + updaters.forEach(updater -> updater.registerUpdaters(context)); + + CONTEXT = context; + LATEST_UPDATER_VERSION = context.getLatestVersion(); + log.info("Latest block state updater version {}", context.getLatestVersion()); + } + + public static BlockStateMapping get() { + return INSTANCE; + } + + private final Int2ObjectMap runtime2State = new Int2ObjectOpenHashMap<>(); + private final Object2ObjectMap paletteMap = new Object2ObjectOpenCustomHashMap<>(new Hash.Strategy() { + @Override + public int hashCode(NbtMap nbtMap) { + return nbtMap.hashCode(); + } + + @Override + public boolean equals(NbtMap nbtMap1, NbtMap nbtMap2) { + return Objects.equals(nbtMap1, nbtMap2); + } + }); + private final int version; + + private LegacyStateMapper legacyMapper; + + private int defaultRuntimeId = -1; + private BlockStateSnapshot defaultState; + + public BlockStateMapping(int version) { + this(version, null); + } + + public BlockStateMapping(int version, LegacyStateMapper legacyMapper) { + this.version = version; + this.legacyMapper = legacyMapper; + } + + public void registerState(int runtimeId, NbtMap state) { + Preconditions.checkArgument(!this.runtime2State.containsKey(runtimeId), + "Mapping for runtimeId " + runtimeId + " is already created!"); + Preconditions.checkArgument(!this.paletteMap.containsKey(state), + "Mapping for state is already created: " + state); + + BlockStateSnapshot blockState = BlockStateSnapshot.builder() + .version(this.version) + .vanillaState(state) + .runtimeId(runtimeId) + .build(); + this.runtime2State.put(runtimeId, blockState); + this.paletteMap.put(state, blockState); + } + + public void clearMapping() { + this.runtime2State.clear(); + this.paletteMap.clear(); + } + + public BlockStateSnapshot getState(int legacyId, int data) { + int runtimeId = this.legacyMapper.legacyToRuntime(legacyId, data); + if (runtimeId == -1) { + log.warn("Can not find state! No legacy2runtime mapping for " + legacyId + ":" + data); + return this.getDefaultState(); + } + return this.getState(runtimeId); + } + + public BlockStateSnapshot getState(int runtimeId) { + BlockStateSnapshot state = this.runtime2State.get(runtimeId); + if (state == null) { + log.warn("Can not find state! No runtime2State mapping for " + runtimeId); + return this.getDefaultState(); + } + return state; + } + + public BlockStateSnapshot getState(NbtMap vanillaState) { + BlockStateSnapshot state = this.paletteMap.get(vanillaState); + if (state == null) { + log.warn("Can not find block state! " + vanillaState); + return this.getDefaultState(); + } + return state; + } + + public BlockStateSnapshot getStateUnsafe(NbtMap vanillaState) { + return this.paletteMap.get(vanillaState); + } + + public int getRuntimeId(int legacyId, int data) { + int runtimeId = this.legacyMapper.legacyToRuntime(legacyId, data); + if (runtimeId == -1) { + log.warn("Can not find runtimeId! No legacy2runtime mapping for " + legacyId + ":" + data); + return this.getDefaultRuntimeId(); + } + return runtimeId; + } + + public int getFullId(int runtimeId) { + int fullId = this.legacyMapper.runtimeToFullId(runtimeId); + if (fullId == -1) { + log.warn("Can not find legacyId! No runtime2FullId mapping for " + runtimeId); + fullId = this.legacyMapper.runtimeToFullId(this.getDefaultRuntimeId()); + Preconditions.checkArgument(fullId != -1, "Can not find fullId for default runtimeId: " + this.getDefaultRuntimeId()); + } + return fullId; + } + + public int getLegacyId(int runtimeId) { + int legacyId = this.legacyMapper.runtimeToLegacyId(runtimeId); + if (legacyId == -1) { + log.warn("Can not find legacyId! No runtime2legacy mapping for " + runtimeId); + legacyId = this.legacyMapper.runtimeToLegacyId(this.getDefaultRuntimeId()); + Preconditions.checkArgument(legacyId != -1, "Can not find legacyId for default runtimeId: " + this.getDefaultRuntimeId()); + } + return legacyId; + } + + public int getLegacyData(int runtimeId) { + int data = this.legacyMapper.runtimeToLegacyData(runtimeId); + if (data == -1) { + log.warn("Can not find legacyId! No runtime2legacy mapping for " + runtimeId); + data = this.legacyMapper.runtimeToLegacyData(this.getDefaultRuntimeId()); + Preconditions.checkArgument(data != -1, "Can not find legacyData for default runtimeId: " + this.getDefaultRuntimeId()); + } + return data; + } + + public void setDefaultBlock(int legacyId, int legacyData) { + int runtimeId = this.legacyMapper.legacyToRuntime(legacyId, legacyData); + Preconditions.checkArgument(runtimeId != -1, "Can not find runtimeId mapping for default block: " + legacyId + ":" + legacyData); + this.defaultRuntimeId = runtimeId; + + BlockStateSnapshot state = this.runtime2State.get(runtimeId); + Preconditions.checkNotNull(state, "Can not find state for default block: " + legacyId + ":" + legacyData); + this.defaultState = state; + } + + public int getDefaultRuntimeId() { + if (this.defaultRuntimeId == -1) { + this.setDefaultBlock(BlockID.INFO_UPDATE, 0); + } + return this.defaultRuntimeId; + } + + public BlockStateSnapshot getDefaultState() { + if (this.defaultState == null) { + this.setDefaultBlock(BlockID.INFO_UPDATE, 0); + } + return this.defaultState; + } + + public BlockStateSnapshot updateState(NbtMap state) { + BlockStateSnapshot blockState = this.paletteMap.get(state); + if (blockState == null) { + blockState = this.updateStateUnsafe(state); + } + return blockState; + } + + public BlockStateSnapshot updateStateUnsafe(NbtMap state) { + return this.getState(this.updateVanillaState(state)); + } + + public BlockStateSnapshot getUpdatedState(NbtMap state) { + if (this.paletteMap.get(state) == null) { + return this.getState(this.updateVanillaState(state)); + } + return null; + } + + public NbtMap updateVanillaState(NbtMap state) { + NbtMap cached = BLOCK_UPDATE_CACHE.getIfPresent(state); + if (cached == null) { + int version = state.getInt("version"); // TODO: validate this when updating next time + cached = CONTEXT.update(state, LATEST_UPDATER_VERSION == version ? version - 1 : version); + BLOCK_UPDATE_CACHE.put(state, cached); + } + return cached; + } + + public BlockStateSnapshot getUpdatedOrCustom(NbtMap state) { + return this.getUpdatedOrCustom(state, this.updateVanillaState(state)); + } + + public BlockStateSnapshot getUpdatedOrCustom(NbtMap state, NbtMap updated) { + BlockStateSnapshot blockState = this.getStateUnsafe(updated); + if (blockState != null) { + return blockState; + } + + return BlockStateSnapshot.builder() + .vanillaState(state) + .runtimeId(this.getDefaultState().getRuntimeId()) + .version(this.version) + .custom(true) + .build(); + } + + public void setLegacyMapper(LegacyStateMapper legacyMapper) { + this.legacyMapper = legacyMapper; + } + + public LegacyStateMapper getLegacyMapper() { + return this.legacyMapper; + } + + public int getVersion() { + return this.version; + } +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/Chunk.java b/src/main/java/cn/nukkit/level/format/leveldb/Chunk.java deleted file mode 100644 index 6ee2c7de042..00000000000 --- a/src/main/java/cn/nukkit/level/format/leveldb/Chunk.java +++ /dev/null @@ -1,537 +0,0 @@ -package cn.nukkit.level.format.leveldb; - -import cn.nukkit.Player; -import cn.nukkit.Server; -import cn.nukkit.block.Block; -import cn.nukkit.blockentity.BlockEntity; -import cn.nukkit.entity.Entity; -import cn.nukkit.level.format.LevelProvider; -import cn.nukkit.level.format.anvil.palette.BiomePalette; -import cn.nukkit.level.format.generic.BaseFullChunk; -import cn.nukkit.level.format.leveldb.key.EntitiesKey; -import cn.nukkit.level.format.leveldb.key.ExtraDataKey; -import cn.nukkit.level.format.leveldb.key.TilesKey; -import cn.nukkit.nbt.NBTIO; -import cn.nukkit.nbt.stream.NBTInputStream; -import cn.nukkit.nbt.tag.CompoundTag; -import cn.nukkit.nbt.tag.Tag; -import cn.nukkit.utils.Binary; -import cn.nukkit.utils.BinaryStream; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.*; - -/** - * author: MagicDroidX - * Nukkit Project - */ -public class Chunk extends BaseFullChunk { - - public static final int DATA_LENGTH = 16384 * (2 + 1 + 1 + 1) + 256 + 1024; - - protected boolean isLightPopulated = false; - protected boolean isPopulated = false; - protected boolean isGenerated = false; - - public Chunk(LevelProvider level, int chunkX, int chunkZ, byte[] terrain) { - this(level, chunkX, chunkZ, terrain, null); - } - - public Chunk(Class providerClass, int chunkX, int chunkZ, byte[] terrain) { - this(null, chunkX, chunkZ, terrain, null); - this.providerClass = providerClass; - } - - public Chunk(LevelProvider level, int chunkX, int chunkZ, byte[] terrain, List entityData) { - this(level, chunkX, chunkZ, terrain, entityData, null); - } - - public Chunk(LevelProvider level, int chunkX, int chunkZ, byte[] terrain, List entityData, List tileData) { - this(level, chunkX, chunkZ, terrain, entityData, tileData, null); - } - - public Chunk(LevelProvider level, int chunkX, int chunkZ, byte[] terrain, List entityData, List tileData, Map extraData) { - ByteBuffer buffer = ByteBuffer.wrap(terrain).order(ByteOrder.BIG_ENDIAN); - - byte[] blocks = new byte[32768]; - buffer.get(blocks); - - byte[] data = new byte[16384]; - buffer.get(data); - - byte[] skyLight = new byte[16384]; - buffer.get(skyLight); - - byte[] blockLight = new byte[16384]; - buffer.get(blockLight); - - byte[] heightMap = new byte[256]; - for (int i = 0; i < 256; i++) { - heightMap[i] = buffer.get(); - } - - int[] biomeColors = new int[256]; - for (int i = 0; i < 256; i++) { - biomeColors[i] = buffer.getInt(); - } - - this.provider = level; - if (level != null) { - this.providerClass = level.getClass(); - } - - this.setPosition(chunkX, chunkZ); - - this.blocks = blocks; - this.data = data; - this.skyLight = skyLight; - this.blockLight = blockLight; - - this.biomes = new byte[16 * 16]; - if (biomeColors.length == 256) { - BiomePalette palette = new BiomePalette(biomeColors); - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - biomes[(x << 4) | z] = (byte) (palette.get(x, z) >> 24); - } - } - } - - if (heightMap.length == 256) { - this.heightMap = heightMap; - } else { - byte[] bytes = new byte[256]; - Arrays.fill(bytes, (byte) 256); - this.heightMap = bytes; - } - - this.NBTentities = entityData; - this.NBTtiles = tileData; - this.extraData = extraData; - } - - @Override - public int getBlockId(int x, int y, int z) { - return this.blocks[(x << 11) | (z << 7) | y] & 0xff; - } - - @Override - public void setBlockId(int x, int y, int z, int id) { - this.blocks[(x << 11) | (z << 7) | y] = (byte) id; - setChanged(); - } - - @Override - public int getBlockData(int x, int y, int z) { - int b = this.data[(x << 10) | (z << 6) | (y >> 1)] & 0xff; - if ((y & 1) == 0) { - return b & 0x0f; - } else { - return b >> 4; - } - } - - @Override - public void setBlockData(int x, int y, int z, int data) { - int i = (x << 10) | (z << 6) | (y >> 1); - int old = this.data[i] & 0xff; - if ((y & 1) == 0) { - this.data[i] = (byte) ((old & 0xf0) | (data & 0x0f)); - } else { - this.data[i] = (byte) (((data & 0x0f) << 4) | (old & 0x0f)); - } - setChanged(); - } - - @Override - public int getFullBlock(int x, int y, int z) { - int i = (x << 11) | (z << 7) | y; - int block = this.blocks[i] & 0xff; - int data = this.data[i >> 1] & 0xff; - if ((y & 1) == 0) { - return (block << 4) | (data & 0x0f); - } else { - return (block << 4) | (data >> 4); - } - } - - @Override - public Block getAndSetBlock(int x, int y, int z, Block block) { - int i = (x << 11) | (z << 7) | y; - boolean changed = false; - byte id = (byte) block.getId(); - - byte previousId = this.blocks[i]; - - if (previousId != id) { - this.blocks[i] = id; - changed = true; - } - - int previousData; - i >>= 1; - int old = this.data[i] & 0xff; - if ((y & 1) == 0) { - previousData = old & 0x0f; - if (Block.hasMeta[block.getId()]) { - this.data[i] = (byte) ((old & 0xf0) | (block.getDamage() & 0x0f)); - if (block.getDamage() != previousData) { - changed = true; - } - } - } else { - previousData = old >> 4; - if (Block.hasMeta[block.getId()]) { - this.data[i] = (byte) (((block.getDamage() & 0x0f) << 4) | (old & 0x0f)); - if (block.getDamage() != previousData) { - changed = true; - } - } - } - - if (changed) { - setChanged(); - } - return Block.get(previousId, previousData); - } - - @Override - public boolean setBlock(int x, int y, int z, int blockId) { - return setBlock(x, y, z, blockId, 0); - } - - @Override - public boolean setBlock(int x, int y, int z, int blockId, int meta) { - int i = (x << 11) | (z << 7) | y; - boolean changed = false; - byte id = (byte) blockId; - if (this.blocks[i] != id) { - this.blocks[i] = id; - changed = true; - } - - if (Block.hasMeta[blockId]) { - i >>= 1; - int old = this.data[i] & 0xff; - if ((y & 1) == 0) { - this.data[i] = (byte) ((old & 0xf0) | (meta & 0x0f)); - if ((old & 0x0f) != meta) { - changed = true; - } - } else { - this.data[i] = (byte) (((meta & 0x0f) << 4) | (old & 0x0f)); - if (meta != (old >> 4)) { - changed = true; - } - } - } - - if (changed) { - setChanged(); - } - return changed; - } - - @Override - public int getBlockSkyLight(int x, int y, int z) { - int sl = this.skyLight[(x << 10) | (z << 6) | (y >> 1)] & 0xff; - if ((y & 1) == 0) { - return sl & 0x0f; - } else { - return sl >> 4; - } - } - - @Override - public void setBlockSkyLight(int x, int y, int z, int level) { - int i = (x << 10) | (z << 6) | (y >> 1); - int old = this.skyLight[i] & 0xff; - if ((y & 1) == 0) { - this.skyLight[i] = (byte) ((old & 0xf0) | (level & 0x0f)); - } else { - this.skyLight[i] = (byte) (((level & 0x0f) << 4) | (old & 0x0f)); - } - setChanged(); - } - - @Override - public int getBlockLight(int x, int y, int z) { - int b = this.blockLight[(x << 10) | (z << 6) | (y >> 1)] & 0xff; - if ((y & 1) == 0) { - return b & 0x0f; - } else { - return b >> 4; - } - } - - @Override - public void setBlockLight(int x, int y, int z, int level) { - int i = (x << 10) | (z << 6) | (y >> 1); - int old = this.blockLight[i] & 0xff; - if ((y & 1) == 0) { - this.blockLight[i] = (byte) ((old & 0xf0) | (level & 0x0f)); - } else { - this.blockLight[i] = (byte) (((level & 0x0f) << 4) | (old & 0x0f)); - } - setChanged(); - } - - @Override - public boolean isLightPopulated() { - return this.isLightPopulated; - } - - @Override - public void setLightPopulated() { - this.setLightPopulated(true); - } - - @Override - public void setLightPopulated(boolean value) { - this.isLightPopulated = value; - } - - @Override - public boolean isPopulated() { - return this.isPopulated; - } - - @Override - public void setPopulated() { - this.setPopulated(true); - } - - @Override - public void setPopulated(boolean value) { - this.isPopulated = true; - } - - @Override - public boolean isGenerated() { - return this.isGenerated; - } - - @Override - public void setGenerated() { - this.setGenerated(true); - } - - @Override - public void setGenerated(boolean value) { - this.isGenerated = true; - } - - public static Chunk fromBinary(byte[] data) { - return fromBinary(data, null); - } - - public static Chunk fromBinary(byte[] data, LevelProvider provider) { - try { - - int chunkX = Binary.readLInt(new byte[]{data[0], data[1], data[2], data[3]}); - int chunkZ = Binary.readLInt(new byte[]{data[4], data[5], data[6], data[7]}); - byte[] chunkData = Binary.subBytes(data, 8, data.length - 1); - - int flags = data[data.length - 1]; - - List entities = new ArrayList<>(); - List tiles = new ArrayList<>(); - - Map extraDataMap = new HashMap<>(); - - if (provider instanceof LevelDB) { - byte[] entityData = ((LevelDB) provider).getDatabase().get(EntitiesKey.create(chunkX, chunkZ).toArray()); - if (entityData != null && entityData.length > 0) { - try (NBTInputStream nbtInputStream = new NBTInputStream(new ByteArrayInputStream(entityData), ByteOrder.LITTLE_ENDIAN)) { - while (nbtInputStream.available() > 0) { - Tag tag = Tag.readNamedTag(nbtInputStream); - if (!(tag instanceof CompoundTag)) { - throw new IOException("Root tag must be a named compound tag"); - } - entities.add((CompoundTag) tag); - } - } - } - - byte[] tileData = ((LevelDB) provider).getDatabase().get(TilesKey.create(chunkX, chunkZ).toArray()); - if (tileData != null && tileData.length > 0) { - try (NBTInputStream nbtInputStream = new NBTInputStream(new ByteArrayInputStream(tileData), ByteOrder.LITTLE_ENDIAN)) { - while (nbtInputStream.available() > 0) { - Tag tag = Tag.readNamedTag(nbtInputStream); - if (!(tag instanceof CompoundTag)) { - throw new IOException("Root tag must be a named compound tag"); - } - tiles.add((CompoundTag) tag); - } - } - } - - byte[] extraData = ((LevelDB) provider).getDatabase().get(ExtraDataKey.create(chunkX, chunkZ).toArray()); - if (extraData != null && extraData.length > 0) { - BinaryStream stream = new BinaryStream(tileData); - int count = stream.getInt(); - for (int i = 0; i < count; ++i) { - int key = stream.getInt(); - int value = stream.getShort(); - extraDataMap.put(key, value); - } - } - - /*if (!entities.isEmpty() || !blockEntities.isEmpty()) { - CompoundTag ct = new CompoundTag(); - ListTag entityList = new ListTag<>("entities"); - ListTag tileList = new ListTag<>("blockEntities"); - - entityList.list = entities; - tileList.list = blockEntities; - ct.putList(entityList); - ct.putList(tileList); - NBTIO.write(ct, new File(Nukkit.DATA_PATH + chunkX + "_" + chunkZ + ".dat")); - }*/ - - - Chunk chunk = new Chunk(provider, chunkX, chunkZ, chunkData, entities, tiles, extraDataMap); - - if ((flags & 0x01) > 0) { - chunk.setGenerated(); - } - - if ((flags & 0x02) > 0) { - chunk.setPopulated(); - } - - if ((flags & 0x04) > 0) { - chunk.setLightPopulated(); - } - return chunk; - } - } catch (Exception e) { - Server.getInstance().getLogger().logException(e); - } - return null; - } - - public static Chunk fromFastBinary(byte[] data) { - return fromFastBinary(data, null); - } - - public static Chunk fromFastBinary(byte[] data, LevelProvider provider) { - return fromBinary(data, provider); - } - - @Override - public byte[] toFastBinary() { - return this.toBinary(false); - } - - @Override - public byte[] toBinary() { - return this.toBinary(false); - } - - public byte[] toBinary(boolean saveExtra) { - try { - LevelProvider provider = this.getProvider(); - - if (saveExtra && provider instanceof LevelDB) { - - List entities = new ArrayList<>(); - - for (Entity entity : this.getEntities().values()) { - if (!(entity instanceof Player) && !entity.closed) { - entity.saveNBT(); - entities.add(entity.namedTag); - } - } - - EntitiesKey entitiesKey = EntitiesKey.create(this.getX(), this.getZ()); - if (!entities.isEmpty()) { - ((LevelDB) provider).getDatabase().put(entitiesKey.toArray(), NBTIO.write(entities)); - } else { - ((LevelDB) provider).getDatabase().delete(entitiesKey.toArray()); - } - - List tiles = new ArrayList<>(); - - for (BlockEntity blockEntity : this.getBlockEntities().values()) { - if (!blockEntity.closed) { - blockEntity.saveNBT(); - tiles.add(blockEntity.namedTag); - } - } - - TilesKey tilesKey = TilesKey.create(this.getX(), this.getZ()); - if (!tiles.isEmpty()) { - ((LevelDB) provider).getDatabase().put(tilesKey.toArray(), NBTIO.write(tiles)); - } else { - ((LevelDB) provider).getDatabase().delete(tilesKey.toArray()); - } - - ExtraDataKey extraDataKey = ExtraDataKey.create(this.getX(), this.getZ()); - if (!this.getBlockExtraDataArray().isEmpty()) { - BinaryStream extraData = new BinaryStream(); - Map extraDataArray = this.getBlockExtraDataArray(); - extraData.putInt(extraDataArray.size()); - for (Integer key : extraDataArray.keySet()) { - extraData.putInt(key); - extraData.putShort(extraDataArray.get(key)); - } - ((LevelDB) provider).getDatabase().put(extraDataKey.toArray(), extraData.getBuffer()); - } else { - ((LevelDB) provider).getDatabase().delete(extraDataKey.toArray()); - } - - } - - byte[] heightMap = this.getHeightMapArray(); - - byte[] biomeColors = new byte[this.biomes.length * 4]; - for (int i = 0; i < this.biomes.length; i++) { - byte[] bytes = Binary.writeInt(this.biomes[i] << 24); - biomeColors[i * 4] = bytes[0]; - biomeColors[i * 4 + 1] = bytes[1]; - biomeColors[i * 4 + 2] = bytes[2]; - biomeColors[i * 4 + 3] = bytes[3]; - } - - return Binary.appendBytes( - Binary.writeLInt(this.getX()), - Binary.writeLInt(this.getZ()), - this.getBlockIdArray(), - this.getBlockDataArray(), - this.getBlockSkyLightArray(), - this.getBlockLightArray(), - heightMap, - biomeColors, - new byte[]{(byte) (((this.isLightPopulated ? 0x04 : 0) | (this.isPopulated() ? 0x02 : 0) | (this.isGenerated() ? 0x01 : 0)) & 0xff)} - ); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - public static Chunk getEmptyChunk(int chunkX, int chunkZ) { - return getEmptyChunk(chunkX, chunkZ, null); - } - - public static Chunk getEmptyChunk(int chunkX, int chunkZ, LevelProvider provider) { - try { - Chunk chunk; - if (provider != null) { - chunk = new Chunk(provider, chunkX, chunkZ, new byte[DATA_LENGTH]); - } else { - chunk = new Chunk(LevelDB.class, chunkX, chunkZ, new byte[DATA_LENGTH]); - } - - byte[] skyLight = new byte[16384]; - Arrays.fill(skyLight, (byte) 0xff); - chunk.skyLight = skyLight; - return chunk; - } catch (Exception e) { - throw new RuntimeException(e); - } - } -} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/LegacyStateMapper.java b/src/main/java/cn/nukkit/level/format/leveldb/LegacyStateMapper.java new file mode 100644 index 00000000000..fc3bd55c298 --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/LegacyStateMapper.java @@ -0,0 +1,11 @@ +package cn.nukkit.level.format.leveldb; + +public interface LegacyStateMapper { + int legacyToRuntime(int legacyId, int meta); + + int runtimeToLegacyId(int runtimeId); + + int runtimeToLegacyData(int runtimeId); + + int runtimeToFullId(int runtimeId); +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/LevelDB.java b/src/main/java/cn/nukkit/level/format/leveldb/LevelDB.java deleted file mode 100644 index 5ad5bae06d6..00000000000 --- a/src/main/java/cn/nukkit/level/format/leveldb/LevelDB.java +++ /dev/null @@ -1,560 +0,0 @@ -package cn.nukkit.level.format.leveldb; - -import cn.nukkit.Server; -import cn.nukkit.blockentity.BlockEntity; -import cn.nukkit.blockentity.BlockEntitySpawnable; -import cn.nukkit.level.GameRules; -import cn.nukkit.level.Level; -import cn.nukkit.level.format.ChunkSection; -import cn.nukkit.level.format.FullChunk; -import cn.nukkit.level.format.LevelProvider; -import cn.nukkit.level.format.generic.BaseFullChunk; -import cn.nukkit.level.format.leveldb.key.BaseKey; -import cn.nukkit.level.format.leveldb.key.FlagsKey; -import cn.nukkit.level.format.leveldb.key.TerrainKey; -import cn.nukkit.level.format.leveldb.key.VersionKey; -import cn.nukkit.level.generator.Generator; -import cn.nukkit.math.Vector3; -import cn.nukkit.nbt.NBTIO; -import cn.nukkit.nbt.tag.CompoundTag; -import cn.nukkit.scheduler.AsyncTask; -import cn.nukkit.utils.*; -import org.iq80.leveldb.DB; -import org.iq80.leveldb.Options; -import org.iq80.leveldb.impl.Iq80DBFactory; - -import java.io.*; -import java.nio.ByteOrder; -import java.util.*; - -/** - * author: MagicDroidX - * Nukkit Project - */ -public class LevelDB implements LevelProvider { - - protected Map chunks = new HashMap<>(); - - protected DB db; - - protected Level level; - - protected final String path; - - protected CompoundTag levelData; - - public LevelDB(Level level, String path) { - this.level = level; - this.path = path; - File file_path = new File(this.path); - if (!file_path.exists()) { - file_path.mkdirs(); - } - - try (FileInputStream stream = new FileInputStream(this.getPath() + "level.dat")) { - stream.skip(8); - CompoundTag levelData = NBTIO.read(stream, ByteOrder.LITTLE_ENDIAN); - if (levelData != null) { - this.levelData = levelData; - } else { - throw new IOException("LevelData can not be null"); - } - } catch (IOException e) { - throw new LevelException("Invalid level.dat"); - } - - if (!this.levelData.contains("generatorName")) { - this.levelData.putString("generatorName", Generator.getGenerator("DEFAULT").getSimpleName().toLowerCase()); - } - - if (!this.levelData.contains("generatorOptions")) { - this.levelData.putString("generatorOptions", ""); - } - - try { - this.db = Iq80DBFactory.factory.open(new File(this.getPath() + "/db"), new Options().createIfMissing(true)); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static String getProviderName() { - return "leveldb"; - } - - public static byte getProviderOrder() { - return ORDER_ZXY; - } - - public static boolean usesChunkSection() { - return false; - } - - public static boolean isValid(String path) { - return new File(path + "/level.dat").exists() && new File(path + "/db").isDirectory(); - } - - public static void generate(String path, String name, long seed, Class generator) throws IOException { - generate(path, name, seed, generator, new HashMap<>()); - } - - public static void generate(String path, String name, long seed, Class generator, Map options) throws IOException { - if (!new File(path + "/db").exists()) { - new File(path + "/db").mkdirs(); - } - - CompoundTag levelData = new CompoundTag("") - .putLong("currentTick", 0) - .putInt("DayCycleStopTime", -1) - .putInt("GameType", 0) - .putInt("Generator", Generator.getGeneratorType(generator)) - .putBoolean("hasBeenLoadedInCreative", false) - .putLong("LastPlayed", System.currentTimeMillis() / 1000) - .putString("LevelName", name) - .putFloat("lightningLevel", 0) - .putInt("lightningTime", new Random().nextInt()) - .putInt("limitedWorldOriginX", 128) - .putInt("limitedWorldOriginY", 70) - .putInt("limitedWorldOriginZ", 128) - .putInt("Platform", 0) - .putFloat("rainLevel", 0) - .putInt("rainTime", new Random().nextInt()) - .putLong("RandomSeed", seed) - .putByte("spawnMobs", 0) - .putInt("SpawnX", 128) - .putInt("SpawnY", 70) - .putInt("SpawnZ", 128) - .putInt("storageVersion", 4) - .putLong("Time", 0) - .putLong("worldStartCount", ((long) Integer.MAX_VALUE) & 0xffffffffL); - - byte[] data = NBTIO.write(levelData, ByteOrder.LITTLE_ENDIAN); - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - outputStream.write(Binary.writeLInt(3)); - outputStream.write(Binary.writeLInt(data.length)); - outputStream.write(data); - - Utils.writeFile(path + "level.dat", new ByteArrayInputStream(outputStream.toByteArray())); - - DB db = Iq80DBFactory.factory.open(new File(path + "/db"), new Options().createIfMissing(true)); - db.close(); - } - - @Override - public void saveLevelData() { - try { - byte[] data = NBTIO.write(levelData, ByteOrder.LITTLE_ENDIAN); - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - outputStream.write(Binary.writeLInt(3)); - outputStream.write(Binary.writeLInt(data.length)); - outputStream.write(data); - - Utils.writeFile(path + "level.dat", new ByteArrayInputStream(outputStream.toByteArray())); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - - @Override - public Chunk getEmptyChunk(int chunkX, int chunkZ) { - return Chunk.getEmptyChunk(chunkX, chunkZ, this); - } - - @Override - public AsyncTask requestChunkTask(int x, int z) { - Chunk chunk = this.getChunk(x, z, false); - if (chunk == null) { - throw new ChunkException("Invalid Chunk sent"); - } - - long timestamp = chunk.getChanges(); - - BinaryStream stream = new BinaryStream(); - stream.putByte((byte) 0); // subchunk version - - stream.put(chunk.getBlockIdArray()); - stream.put(chunk.getBlockDataArray()); - stream.put(chunk.getBlockSkyLightArray()); - stream.put(chunk.getBlockLightArray()); - stream.put(chunk.getHeightMapArray()); - stream.put(chunk.getBiomeIdArray()); - - Map extra = chunk.getBlockExtraDataArray(); - stream.putLInt(extra.size()); - if (!extra.isEmpty()) { - for (Integer key : extra.values()) { - stream.putLInt(key); - stream.putLShort(extra.get(key)); - } - } - - if (!chunk.getBlockEntities().isEmpty()) { - List tagList = new ArrayList<>(); - - for (BlockEntity blockEntity : chunk.getBlockEntities().values()) { - if (blockEntity instanceof BlockEntitySpawnable) { - tagList.add(((BlockEntitySpawnable) blockEntity).getSpawnCompound()); - } - } - - try { - stream.put(NBTIO.write(tagList, ByteOrder.LITTLE_ENDIAN)); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - this.getLevel().chunkRequestCallback(timestamp, x, z, 16, stream.getBuffer()); - - return null; - } - - @Override - public void unloadChunks() { - for (Chunk chunk : new ArrayList<>(this.chunks.values())) { - this.unloadChunk(chunk.getX(), chunk.getZ(), false); - } - this.chunks = new HashMap<>(); - } - - @Override - public String getGenerator() { - return this.levelData.getString("generatorName"); - } - - @Override - public Map getGeneratorOptions() { - return new HashMap() { - { - put("preset", levelData.getString("generatorOptions")); - } - }; - } - - @Override - public BaseFullChunk getLoadedChunk(int X, int Z) { - return this.getLoadedChunk(Level.chunkHash(X, Z)); - } - - @Override - public BaseFullChunk getLoadedChunk(long hash) { - return this.chunks.get(hash); - } - - @Override - public Map getLoadedChunks() { - return this.chunks; - } - - @Override - public boolean isChunkLoaded(int x, int z) { - return this.isChunkLoaded(Level.chunkHash(x, z)); - } - - @Override - public boolean isChunkLoaded(long hash) { - return this.chunks.containsKey(hash); - } - - @Override - public void saveChunks() { - for (Chunk chunk : this.chunks.values()) { - this.saveChunk(chunk.getX(), chunk.getZ()); - } - } - - @Override - public boolean loadChunk(int x, int z) { - return this.loadChunk(x, z, false); - } - - @Override - public boolean loadChunk(int x, int z, boolean create) { - long index = Level.chunkHash(x, z); - if (this.chunks.containsKey(index)) { - return true; - } - - this.level.timings.syncChunkLoadDataTimer.startTiming(); - Chunk chunk = this.readChunk(x, z); - if (chunk == null && create) { - chunk = Chunk.getEmptyChunk(x, z, this); - } - this.level.timings.syncChunkLoadDataTimer.stopTiming(); - if (chunk != null) { - this.chunks.put(index, chunk); - return true; - } - - return false; - } - - public Chunk readChunk(int chunkX, int chunkZ) { - byte[] data; - if (!this.chunkExists(chunkX, chunkZ) || (data = this.db.get(TerrainKey.create(chunkX, chunkZ).toArray())) == null) { - return null; - } - - byte[] flags = this.db.get(FlagsKey.create(chunkX, chunkZ).toArray()); - if (flags == null) { - flags = new byte[]{0x03}; - } - - return Chunk.fromBinary( - Binary.appendBytes( - Binary.writeLInt(chunkX), - Binary.writeLInt(chunkZ), - data, - flags) - , this); - } - - private void writeChunk(Chunk chunk) { - byte[] binary = chunk.toBinary(true); - this.db.put(TerrainKey.create(chunk.getX(), chunk.getZ()).toArray(), Binary.subBytes(binary, 8, binary.length - 1)); - this.db.put(FlagsKey.create(chunk.getX(), chunk.getZ()).toArray(), Binary.subBytes(binary, binary.length - 1)); - this.db.put(VersionKey.create(chunk.getX(), chunk.getZ()).toArray(), new byte[]{0x02}); - } - - @Override - public boolean unloadChunk(int x, int z) { - return this.unloadChunk(x, z, true); - } - - @Override - public boolean unloadChunk(int x, int z, boolean safe) { - long index = Level.chunkHash(x, z); - Chunk chunk = this.chunks.getOrDefault(index, null); - if (chunk != null && chunk.unload(false, safe)) { - this.chunks.remove(index); - return true; - } - - return false; - } - - @Override - public void saveChunk(int x, int z) { - if (this.isChunkLoaded(x, z)) { - this.writeChunk(this.getChunk(x, z)); - } - } - - @Override - public void saveChunk(int x, int z, FullChunk chunk) { - if (!(chunk instanceof Chunk)) { - throw new ChunkException("Invalid Chunk class"); - } - this.writeChunk((Chunk) chunk); - } - - @Override - public Chunk getChunk(int x, int z) { - return this.getChunk(x, z, false); - } - - @Override - public Chunk getChunk(int x, int z, boolean create) { - long index = Level.chunkHash(x, z); - if (this.chunks.containsKey(index)) { - return this.chunks.get(index); - } else { - this.loadChunk(x, z, create); - return this.chunks.getOrDefault(index, null); - } - } - - public DB getDatabase() { - return db; - } - - @Override - public void setChunk(int chunkX, int chunkZ, FullChunk chunk) { - if (!(chunk instanceof Chunk)) { - throw new ChunkException("Invalid Chunk class"); - } - chunk.setProvider(this); - - chunk.setPosition(chunkX, chunkZ); - long index = Level.chunkHash(chunkX, chunkZ); - - if (this.chunks.containsKey(index) && !this.chunks.get(index).equals(chunk)) { - this.unloadChunk(chunkX, chunkZ, false); - } - - this.chunks.put(index, (Chunk) chunk); - } - - public static ChunkSection createChunkSection(int y) { - return null; - } - - private boolean chunkExists(int chunkX, int chunkZ) { - return this.db.get(VersionKey.create(chunkX, chunkZ).toArray()) != null; - } - - @Override - public boolean isChunkGenerated(int x, int z) { - return this.chunkExists(x, z) && this.getChunk(x, z, false) != null; - - } - - @Override - public boolean isChunkPopulated(int x, int z) { - return this.getChunk(x, z) != null; - } - - @Override - public void close() { - this.unloadChunks(); - try { - this.db.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - this.level = null; - } - - @Override - public String getPath() { - return path; - } - - public Server getServer() { - return this.level.getServer(); - } - - @Override - public Level getLevel() { - return level; - } - - @Override - public String getName() { - return this.levelData.getString("LevelName"); - } - - @Override - public boolean isRaining() { - return this.levelData.getFloat("rainLevel") > 0; - } - - @Override - public void setRaining(boolean raining) { - this.levelData.putFloat("rainLevel", raining ? 1.0f : 0); - } - - @Override - public int getRainTime() { - return this.levelData.getInt("rainTime"); - } - - @Override - public void setRainTime(int rainTime) { - this.levelData.putInt("rainTime", rainTime); - } - - @Override - public boolean isThundering() { - return this.levelData.getFloat("lightningLevel") > 0; - } - - @Override - public void setThundering(boolean thundering) { - this.levelData.putFloat("lightningLevel", thundering ? 1.0f : 0); - } - - @Override - public int getThunderTime() { - return this.levelData.getInt("lightningTime"); - } - - @Override - public void setThunderTime(int thunderTime) { - this.levelData.putInt("lightningTime", thunderTime); - } - - @Override - public long getCurrentTick() { - return this.levelData.getLong("currentTick"); - } - - @Override - public void setCurrentTick(long currentTick) { - this.levelData.putLong("currentTick", currentTick); - } - - @Override - public long getTime() { - return this.levelData.getLong("Time"); - } - - @Override - public void setTime(long value) { - this.levelData.putLong("Time", value); - } - - @Override - public long getSeed() { - return this.levelData.getLong("RandomSeed"); - } - - @Override - public void setSeed(long value) { - this.levelData.putLong("RandomSeed", value); - } - - @Override - public Vector3 getSpawn() { - return new Vector3(this.levelData.getInt("SpawnX"), this.levelData.getInt("SpawnY"), this.levelData.getInt("SpawnZ")); - } - - @Override - public void setSpawn(Vector3 pos) { - this.levelData.putInt("SpawnX", (int) pos.x); - this.levelData.putInt("SpawnY", (int) pos.y); - this.levelData.putInt("SpawnZ", (int) pos.z); - } - - @Override - public GameRules getGamerules() { - GameRules rules = GameRules.getDefault(); - - if (this.levelData.contains("GameRules")) - rules.readNBT(this.levelData.getCompound("GameRules")); - - return rules; - } - - @Override - public void setGameRules(GameRules rules) { - this.levelData.putCompound("GameRules", rules.writeNBT()); - } - - @Override - public void doGarbageCollection() { - - } - - public CompoundTag getLevelData() { - return levelData; - } - - public void updateLevelName(String name) { - if (!this.getName().equals(name)) { - this.levelData.putString("LevelName", name); - } - } - - public byte[][] getTerrainKeys() { - List result = new ArrayList<>(); - this.db.forEach((entry) -> { - byte[] key = entry.getKey(); - if (key.length > 8 && key[8] == BaseKey.DATA_TERRAIN) { - result.add(key); - } - }); - return result.toArray(new byte[0][]); - } -} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/LevelDBConstants.java b/src/main/java/cn/nukkit/level/format/leveldb/LevelDBConstants.java new file mode 100644 index 00000000000..ab6f091e15f --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/LevelDBConstants.java @@ -0,0 +1,23 @@ +package cn.nukkit.level.format.leveldb; + +public class LevelDBConstants { + // This is protocol version if block palette used in storage + public static final int PALETTE_VERSION = 729; + // By combining this versions we can get block state version + public static final int STATE_MAYOR_VERSION = 1; + public static final int STATE_MINOR_VERSION = 21; + public static final int STATE_PATCH_VERSION = 30; + public static final int STATE_VERSION = 18161159; + // Chunk version that will be currently used as default + // NOTE: This is not necessary bumped everytime with PALETTE_VERSION + // Last time this was bumped in 1.18.10 (TODO: 41 for 1.21.40+) + public static final int LATEST_CHUNK_VERSION = 40; + // SubChunk version used for serializing chunks into storage + public static final int LATEST_SUBCHUNK_VERSION = 8; + // Lowest SubChunk index + public static final int MIN_SUBCHUNK_INDEX = -4; + // Highest SubChunk index + public static final int MAX_SUBCHUNK_INDEX = 19; + // SubChunks count + public static final int MAX_SUBCHUNK_COUNT = MAX_SUBCHUNK_INDEX - MIN_SUBCHUNK_INDEX + 1; +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/LevelDBKey.java b/src/main/java/cn/nukkit/level/format/leveldb/LevelDBKey.java new file mode 100644 index 00000000000..e7fa4e387e7 --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/LevelDBKey.java @@ -0,0 +1,92 @@ +package cn.nukkit.level.format.leveldb; + +public enum LevelDBKey { + DATA_3D('+'), + VERSION(','), + DATA_2D('-'), + DATA_2D_LEGACY('.'), + SUB_CHUNK_PREFIX('/'), + LEGACY_TERRAIN('0'), + BLOCK_ENTITIES('1'), + ENTITIES('2'), + PENDING_TICKS('3'), + BLOCK_EXTRA_DATA('4'), + BIOME_STATE('5'), + STATE_FINALIZATION('6'), + CONVERSION_DATA('7'), + BORDER_BLOCKS('8'), + HARDCODED_SPAWNERS('9'), + RANDOM_TICKS(':'), + CHECKSUMS(';'), + GENERATION_SEED('<'), + META_DATA_HASH('='), + GENERATED_PRE_CAVES_AND_CLIFFS_BLENDING('='), + BLENDING_BIOME_HEIGHT('>'), + METADATA_HASH('?'), + BLENDING_DATA('@'), + ACTOR_DIGEST_VERSION('A'), + FLAGS('f'), + VERSION_OLD('v'), + NUKKIT_BLOCK_LIGHT((char) 1000), + NUKKIT_SKY_LIGHT((char) 1001); + + private final byte encoded; + + LevelDBKey(char encoded) { + this.encoded = (byte) encoded; + } + + public byte[] getKey(int chunkX, int chunkZ, int dimension) { + if (dimension == 0) { + return this.getKey(chunkX, chunkZ, false, 0); + } else { + return this.getKey(chunkX, chunkZ, dimension, false, 0); + } + } + + public byte[] getKey(int chunkX, int chunkZ, int y, int dimension) { + if (dimension == 0) { + return this.getKey(chunkX, chunkZ, true, y); + } else { + return this.getKey(chunkX, chunkZ, dimension, true, y); + } + } + + private byte[] getKey(int chunkX, int chunkZ, boolean extend, int y) { + byte[] bytes = new byte[extend ? 10 : 9]; + bytes[0] = (byte) (chunkX & 0xff); + bytes[1] = (byte) ((chunkX >>> 8) & 0xff); + bytes[2] = (byte) ((chunkX >>> 16) & 0xff); + bytes[3] = (byte) ((chunkX >>> 24) & 0xff); + bytes[4] = (byte) (chunkZ & 0xff); + bytes[5] = (byte) ((chunkZ >>> 8) & 0xff); + bytes[6] = (byte) ((chunkZ >>> 16) & 0xff); + bytes[7] = (byte) ((chunkZ >>> 24) & 0xff); + bytes[8] = this.encoded; + if (extend) { + bytes[9] = (byte) y; + } + return bytes; + } + + private byte[] getKey(int chunkX, int chunkZ, int dimension, boolean extend, int y) { + byte[] bytes = new byte[extend ? 14 : 13]; + bytes[0] = (byte) (chunkX & 0xff); + bytes[1] = (byte) ((chunkX >>> 8) & 0xff); + bytes[2] = (byte) ((chunkX >>> 16) & 0xff); + bytes[3] = (byte) ((chunkX >>> 24) & 0xff); + bytes[4] = (byte) (chunkZ & 0xff); + bytes[5] = (byte) ((chunkZ >>> 8) & 0xff); + bytes[6] = (byte) ((chunkZ >>> 16) & 0xff); + bytes[7] = (byte) ((chunkZ >>> 24) & 0xff); + bytes[8] = (byte) (dimension & 0xff); + bytes[9] = (byte) ((dimension >>> 8) & 0xff); + bytes[10] = (byte) ((dimension >>> 16) & 0xff); + bytes[11] = (byte) ((dimension >>> 24) & 0xff); + bytes[12] = this.encoded; + if (extend) { + bytes[13] = (byte) y; + } + return bytes; + } +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/LevelDBProvider.java b/src/main/java/cn/nukkit/level/format/leveldb/LevelDBProvider.java new file mode 100644 index 00000000000..c205daeec87 --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/LevelDBProvider.java @@ -0,0 +1,860 @@ +package cn.nukkit.level.format.leveldb; + +import cn.nukkit.Nukkit; +import cn.nukkit.Server; +import cn.nukkit.block.Block; +import cn.nukkit.level.GameRule; +import cn.nukkit.level.GameRules; +import cn.nukkit.level.Level; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.format.LevelProvider; +import cn.nukkit.level.format.generic.BaseFullChunk; +import cn.nukkit.level.format.leveldb.serializer.*; +import cn.nukkit.level.format.leveldb.structure.BlockStateSnapshot; +import cn.nukkit.level.format.leveldb.structure.ChunkBuilder; +import cn.nukkit.level.format.leveldb.structure.LevelDBChunk; +import cn.nukkit.level.format.leveldb.structure.LevelDBChunkSection; +import cn.nukkit.level.generator.Generator; +import cn.nukkit.math.Vector3; +import cn.nukkit.nbt.stream.NBTInputStream; +import cn.nukkit.nbt.stream.NBTOutputStream; +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.Tag; +import cn.nukkit.utils.BlockUpdateEntry; +import cn.nukkit.utils.ChunkException; +import cn.nukkit.utils.LevelException; +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableMap; +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import io.netty.buffer.*; +import it.unimi.dsi.fastutil.longs.Long2ObjectMap; +import it.unimi.dsi.fastutil.longs.Long2ObjectMaps; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.ObjectIterator; +import net.daporkchop.ldbjni.DBProvider; +import net.daporkchop.ldbjni.LevelDB; +import net.daporkchop.lib.natives.FeatureBuilder; +import org.cloudburstmc.nbt.NbtMap; +import org.cloudburstmc.nbt.NbtMapBuilder; +import org.cloudburstmc.nbt.NbtType; +import org.cloudburstmc.nbt.NbtUtils; +import org.iq80.leveldb.CompressionType; +import org.iq80.leveldb.DB; +import org.iq80.leveldb.Options; +import org.iq80.leveldb.WriteBatch; + +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.nio.ByteOrder; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static cn.nukkit.level.format.leveldb.LevelDBConstants.*; + +public class LevelDBProvider implements LevelProvider { + + private Level level; + private final Path path; + private final DB db; + + private final Long2ObjectMap chunks = Long2ObjectMaps.synchronize(new Long2ObjectOpenHashMap<>()); + + private CompoundTag levelData; + private Vector3 spawn; + private int lastGcPosition = 0; + + private final ExecutorService executor; + + private volatile boolean closed; + + private static final DBProvider JAVA_LDB_PROVIDER = (DBProvider) FeatureBuilder.create(LevelDBProvider.class).addJava("net.daporkchop.ldbjni.java.JavaDBProvider").build(); + + public LevelDBProvider(Level level, String path) throws IOException { + this.level = level; + this.path = Paths.get(path); + + Path dbPath = this.path.resolve("db"); + Files.createDirectories(dbPath); + Preconditions.checkArgument(Files.isDirectory(dbPath), "db is not a directory"); + + Options options = new Options() + .createIfMissing(true) + .compressionType(CompressionType.ZLIB_RAW) + .cacheSize(1024L * 1024L * level.getServer().getConfig("leveldb.cache-size-mb", 80)) + .blockSize(64 * 1024); + + this.db = level.getServer().getConfig("leveldb.use-native", false) ? + LevelDB.PROVIDER.open(dbPath.toFile(), options) : JAVA_LDB_PROVIDER.open(dbPath.toFile(), options); + + this.levelData = loadLevelData(this.path); + + if (!this.levelData.contains("generatorName")) { + Class generator = null; + if (this.levelData.contains("Generator")) { + generator = Generator.getGenerator(this.levelData.getInt("Generator")); + } + + if (generator == null) { + generator = Generator.getGenerator("DEFAULT"); + } + this.levelData.putString("generatorName", generator.getSimpleName().toLowerCase()); + } + + if (!this.levelData.contains("generatorOptions")) { + this.levelData.putString("generatorOptions", ""); + } + + this.spawn = new Vector3(this.levelData.getInt("SpawnX"), this.levelData.getInt("SpawnY"), this.levelData.getInt("SpawnZ")); + + ThreadFactoryBuilder builder = new ThreadFactoryBuilder(); + builder.setNameFormat("LevelDB Executor-" + this.getName() + " #%s"); + builder.setUncaughtExceptionHandler((thread, ex) -> { + Server.getInstance().getLogger().error("Exception in " + thread.getName(), ex); + }); + this.executor = Executors.newFixedThreadPool(3, builder.build()); + } + + @SuppressWarnings("unused") + public static String getProviderName() { + return "leveldb"; + } + + @SuppressWarnings("unused") + public static boolean usesChunkSection() { + return true; + } + + public static boolean isValid(String path) { + Path worldPath = Paths.get(path); + return Files.exists(worldPath.resolve("level.dat")) && Files.exists(worldPath.resolve("db")); + } + + public static void generate(String path, String name, long seed, Class generator) throws IOException { + generate(path, name, seed, generator, new HashMap<>()); + } + + public static void generate(String path, String name, long seed, Class generator, Map options) throws IOException { + Path worldPath = Paths.get(path); + Path dbPath = worldPath.resolve("db"); + + if (!Files.isDirectory(dbPath)) { + Files.createDirectories(dbPath); + } + + CompoundTag levelData = new CompoundTag() + .putInt("PM1EGen", (generator == cn.nukkit.level.generator.Void.class ? 0 : 2)) // Don't set for converted worlds + .putLong("DayTime", 0) + .putInt("GameType", 0) + .putInt("Generator", Generator.getGeneratorType(generator)) + .putString("generatorName", Generator.getGeneratorName(generator)) + .putString("generatorOptions", options.getOrDefault("preset", "")) + .putString("LevelName", name) + .putBoolean("raining", false) + .putInt("rainTime", 0) + .putLong("RandomSeed", seed) + .putInt("SpawnX", 128) + .putInt("SpawnY", 70) + .putInt("SpawnZ", 128) + .putBoolean("thundering", false) + .putInt("thunderTime", 0) + .putLong("Time", 0); + + saveLevelData(levelData, worldPath); + } + + @Override + public BaseFullChunk getChunk(int chunkX, int chunkZ) { + return this.getChunk(chunkX, chunkZ, false); + } + + @Override + public BaseFullChunk getChunk(int chunkX, int chunkZ, boolean create) { + // BaseFullChunk tmp = lastChunk.get(); + // if (tmp != null && tmp.getX() == chunkX && tmp.getZ() == chunkZ) { + // return tmp; + // } + long index = Level.chunkHash(chunkX, chunkZ); + BaseFullChunk chunk = this.chunks.get(index); + if (chunk == null) { + chunk = this.readOrCreateChunk(chunkX, chunkZ, create); + } + return chunk; + } + + @Override + public void setChunk(int chunkX, int chunkZ, FullChunk chunk) { + if (!(chunk instanceof LevelDBChunk)) throw new IllegalArgumentException("Only LevelDB chunks are supported"); + chunk.setProvider(this); + chunk.setPosition(chunkX, chunkZ); + long index = Level.chunkHash(chunkX, chunkZ); + + FullChunk oldChunk = this.chunks.get(index); + if (oldChunk != null && !oldChunk.equals(chunk)) { + this.unloadChunk(chunkX, chunkZ, false); + } + this.chunks.put(index, (BaseFullChunk) chunk); + } + + @Override + public boolean loadChunk(int chunkX, int chunkZ) { + return this.loadChunk(chunkX, chunkZ, false); + } + + @Override + public boolean loadChunk(int chunkX, int chunkZ, boolean create) { + long index = Level.chunkHash(chunkX, chunkZ); + if (this.chunks.containsKey(index)) { + return true; + } + + return this.readOrCreateChunk(chunkX, chunkZ, create) != null; + } + + @Override + public boolean unloadChunk(int chunkX, int chunkZ) { + return this.unloadChunk(chunkX, chunkZ, true); + } + + @Override + public boolean unloadChunk(int chunkX, int chunkZ, boolean safe) { + long index = Level.chunkHash(chunkX, chunkZ); + BaseFullChunk chunk = this.chunks.get(index); + if (chunk == null || !chunk.unload(false, safe)) { + return false; + } + // TODO: this.lastChunk.set(null); + this.chunks.remove(index, chunk); // TODO: Do this after saveChunkFuture to prevent loading of old copy + return true; + } + + @Override + public BaseFullChunk getLoadedChunk(int chunkX, int chunkZ) { + // BaseFullChunk tmp = lastChunk.get(); + // if (tmp != null && tmp.getX() == chunkX && tmp.getZ() == chunkZ) { + // return tmp; + // } + long index = Level.chunkHash(chunkX, chunkZ); + return this.chunks.get(index); + } + + @Override + public BaseFullChunk getLoadedChunk(long hash) { + // BaseFullChunk tmp = lastChunk.get(); + // if (tmp != null && tmp.getX() == chunkX && tmp.getZ() == chunkZ) { + // return tmp; + // } + return this.chunks.get(hash); + } + + @Override + public boolean isChunkLoaded(int X, int Z) { + return this.isChunkLoaded(Level.chunkHash(X, Z)); + } + + @Override + public boolean isChunkLoaded(long hash) { + return this.chunks.containsKey(hash); + } + + private synchronized BaseFullChunk readOrCreateChunk(int chunkX, int chunkZ, boolean create) { + BaseFullChunk chunk = null; + try { + chunk = this.readChunk(chunkX, chunkZ); + } catch (Exception ex) { + Server.getInstance().getLogger().error("Failed to read chunk " + chunkX + ", " + chunkZ, ex); + } + + if (chunk == null && create) { + chunk = this.getEmptyChunk(chunkX, chunkZ); + } else if (chunk == null) { + return null; + } + + this.chunks.put(Level.chunkHash(chunkX, chunkZ), chunk); + return chunk; + } + + private BaseFullChunk readChunk(int chunkX, int chunkZ) { + byte[] versionValue = this.db.get(LevelDBKey.VERSION.getKey(chunkX, chunkZ, this.level.getDimension())); + if (versionValue == null || versionValue.length != 1) { + versionValue = this.db.get(LevelDBKey.VERSION_OLD.getKey(chunkX, chunkZ, this.level.getDimension())); + if (versionValue == null || versionValue.length != 1) { + return null; + } + } + + ChunkBuilder chunkBuilder = new ChunkBuilder(chunkX, chunkZ, this); + byte[] finalizationState = this.db.get(LevelDBKey.STATE_FINALIZATION.getKey(chunkX, chunkZ, this.level.getDimension())); + if (finalizationState == null) { + chunkBuilder.state(ChunkBuilder.STATE_FINISHED); + } else { + chunkBuilder.state(Unpooled.wrappedBuffer(finalizationState).readIntLE() + 1); + } + + byte chunkVersion = versionValue[0]; + if (chunkVersion < 7) { + chunkBuilder.dirty(); + } + + ChunkSerializers.deserializeChunk(this.db, chunkBuilder, chunkVersion); + + Data3dSerializer.deserialize(this.db, chunkBuilder); + if (!chunkBuilder.has3dBiomes()) { + Data2dSerializer.deserialize(this.db, chunkBuilder); + } + + BlockEntitySerializer.loadBlockEntities(this.db, chunkBuilder); + EntitySerializer.loadEntities(this.db, chunkBuilder); + + byte[] pendingBlockUpdates = this.db.get(LevelDBKey.PENDING_TICKS.getKey(chunkX, chunkZ, this.level.getDimension())); + if (pendingBlockUpdates != null && pendingBlockUpdates.length > 0) { + loadPendingBlockUpdates(pendingBlockUpdates); + } + + return chunkBuilder.build(); + } + + private void loadPendingBlockUpdates(byte[] data) { + NbtMap ticks; + try (ByteBufInputStream stream = new ByteBufInputStream(Unpooled.wrappedBuffer(data))) { + ticks = (NbtMap) NbtUtils.createReaderLE(stream).readTag(); + } catch (IOException ex) { + throw new ChunkException("Corrupted block ticking data", ex); + } + + int currentTick = ticks.getInt("currentTick"); + + for (NbtMap nbtMap : ticks.getList("tickList", NbtType.COMPOUND)) { + Block block = null; + + NbtMap state = nbtMap.getCompound("blockState"); + //noinspection ResultOfMethodCallIgnored + state.hashCode(); + + if (state.containsKey("name")) { + BlockStateSnapshot blockState = BlockStateMapping.get().getStateUnsafe(state); + if (blockState == null) { + NbtMap updatedState = BlockStateMapping.get().updateVanillaState(state); + blockState = BlockStateMapping.get().getUpdatedOrCustom(state, updatedState); + } + block = Block.get(blockState.getLegacyId(), blockState.getLegacyData()); + } else if (nbtMap.containsKey("tileID")) { + block = Block.get(nbtMap.getByte("tileID") & 0xff); + } + + if (block == null) { + if (Nukkit.DEBUG > 1) { + Server.getInstance().getLogger().debug("Invalid block ticking entry: " + nbtMap); + } + continue; + } + + block.x = nbtMap.getInt("x"); + block.y = nbtMap.getInt("y"); + block.z = nbtMap.getInt("z"); + block.level = level; + + int delay = (int) (nbtMap.getLong("time") - currentTick); + int priority = nbtMap.getInt("p"); + + level.scheduleUpdate(block, block, delay, priority, false); + } + } + + @Override + public void saveChunk(int chunkX, int chunkZ) { + BaseFullChunk chunk = this.getChunk(chunkX, chunkZ); + if (chunk != null) { + this.saveChunk(chunkX, chunkZ, chunk); + } + } + + @Override + public void saveChunk(int chunkX, int chunkZ, FullChunk chunk0) { + this.saveChunkFuture(chunkX, chunkZ, chunk0); + } + + public CompletableFuture saveChunkFuture(int chunkX, int chunkZ, FullChunk chunk0) { + if (!(chunk0 instanceof LevelDBChunk)) throw new IllegalArgumentException("Only LevelDB chunks are supported"); + LevelDBChunk chunk = (LevelDBChunk) chunk0; + chunk.setX(chunkX); + chunk.setZ(chunkZ); + if (!chunk.isGenerated()) { + return CompletableFuture.completedFuture(null); + } + chunk.setChanged(false); + + WriteBatch batch = save0(chunkX, chunkZ, chunk); + return CompletableFuture.runAsync(() -> this.saveChunkCallback(batch, chunk), this.executor); + } + + public void saveChunkSync(int chunkX, int chunkZ, FullChunk chunk0) { + if (!(chunk0 instanceof LevelDBChunk)) throw new IllegalArgumentException("Only LevelDB chunks are supported"); + LevelDBChunk chunk = (LevelDBChunk) chunk0; + chunk.setX(chunkX); + chunk.setZ(chunkZ); + if (!chunk.isGenerated()) { + return; + } + chunk.setChanged(false); + + WriteBatch batch = save0(chunkX, chunkZ, chunk); + this.saveChunkCallback(batch, chunk); + } + + private WriteBatch save0(int chunkX, int chunkZ, LevelDBChunk chunk) { + WriteBatch batch = this.db.createWriteBatch(); + ChunkSerializers.serializeChunk(batch, chunk, LATEST_CHUNK_VERSION); + if (chunk.has3dBiomes()) { + Data3dSerializer.serialize(batch, chunk); + } else { + Data2dSerializer.serialize(batch, chunk); + } + + batch.put(LevelDBKey.VERSION.getKey(chunkX, chunkZ, this.level.getDimension()), new byte[]{LATEST_CHUNK_VERSION}); + batch.put(LevelDBKey.STATE_FINALIZATION.getKey(chunkX, chunkZ, this.level.getDimension()), + Unpooled.buffer(4).writeIntLE(chunk.getState() - 1).array()); + + BlockEntitySerializer.saveBlockEntities(batch, chunk); + EntitySerializer.saveEntities(batch, chunk); + + long currentTick = 0; + Set pendingBlockUpdates = null; + + LevelProvider provider; + if ((provider = chunk.getProvider()) != null) { + Level level = provider.getLevel(); + currentTick = level.getCurrentTick(); + pendingBlockUpdates = level.getPendingBlockUpdates(chunk); + } + + byte[] pendingBlockUpdatesKey = LevelDBKey.PENDING_TICKS.getKey(chunkX, chunkZ, this.level.getDimension()); + if (pendingBlockUpdates != null && !pendingBlockUpdates.isEmpty()) { + NbtMap ticks = savePendingBlockUpdates(pendingBlockUpdates, currentTick); + + if (ticks != null) { + ByteBuf byteBuf = ByteBufAllocator.DEFAULT.ioBuffer(); + try (org.cloudburstmc.nbt.NBTOutputStream outputStream = NbtUtils.createWriterLE(new ByteBufOutputStream(byteBuf))) { + outputStream.writeTag(ticks); + } catch (IOException ex) { + throw new RuntimeException(ex); + } + byte[] bytes = new byte[byteBuf.readableBytes()]; + byteBuf.readBytes(bytes); + byteBuf.release(); + batch.put(pendingBlockUpdatesKey, bytes); + } else { + batch.delete(pendingBlockUpdatesKey); + } + } else { + batch.delete(pendingBlockUpdatesKey); + } + + return batch; + } + + private NbtMap savePendingBlockUpdates(Set entries, long currentTick) { + ObjectArrayList list = new ObjectArrayList<>(); + + for (BlockUpdateEntry entry : entries) { + NbtMap blockTag = BlockStateMapping.get().getState(entry.block.getId(), entry.block.getDamage()).getVanillaState(); + + NbtMapBuilder tag = NbtMap.builder() + .putInt("x", entry.pos.getFloorX()) + .putInt("y", entry.pos.getFloorY()) + .putInt("z", entry.pos.getFloorZ()) + .putCompound("blockState", blockTag) + .putLong("time", entry.delay - currentTick); + + if (entry.priority != 0) { + tag.putInt("p", entry.priority); + } + + list.add(tag.build()); + } + + return list.isEmpty() ? null : NbtMap.builder() + .putInt("currentTick", 0) + .putList("tickList", NbtType.COMPOUND, list).build(); + } + + private void saveChunkCallback(WriteBatch batch, LevelDBChunk chunk) { + if (this.closed) { + return; + } + + chunk.writeLock().lock(); + try { + this.db.write(batch); + batch.close(); + } catch (IOException e) { + throw new RuntimeException("Failed to close WriteBatch for " + this.getName(), e); + } finally { + chunk.writeLock().unlock(); + } + } + + @Override + public void saveChunks() { + for (BaseFullChunk chunk : this.chunks.values()) { + if (chunk.hasChanged()) { + chunk.setChanged(false); + this.saveChunk(chunk.getX(), chunk.getZ(), chunk); + } + } + } + + @Override + public void unloadChunks() { + this.unloadChunksUnsafe(false); + } + + private void unloadChunksUnsafe(boolean wait) { + Iterator iterator = this.chunks.values().iterator(); + while (iterator.hasNext()) { + LevelDBChunk chunk = (LevelDBChunk) iterator.next(); + chunk.unload(level.isSaveOnUnloadEnabled(), false); + if (wait) { + if (!chunk.writeLock().tryLock()) { + chunk.writeLock().lock(); + } + chunk.writeLock().unlock(); + } + iterator.remove(); + } + } + + @Override + public boolean isChunkGenerated(int chunkX, int chunkZ) { + BaseFullChunk chunk = this.getChunk(chunkX, chunkZ); + return chunk != null && chunk.isGenerated(); + } + + @Override + public boolean isChunkPopulated(int chunkX, int chunkZ) { + BaseFullChunk chunk = this.getChunk(chunkX, chunkZ); + return chunk != null && chunk.isPopulated(); + } + + @Override + public LevelDBChunk getEmptyChunk(int x, int z) { + LevelDBChunk chunk = new LevelDBChunk(this, new LevelDBChunkSection[0]); + chunk.setPosition(x, z); + return chunk; + } + + @SuppressWarnings("unused") + public static LevelDBChunkSection createChunkSection(int y) { + return new LevelDBChunkSection(y); + } + + @Override + public Map getLoadedChunks() { + return ImmutableMap.copyOf(this.chunks); + } + + @Override + public void requestChunkTask(int chunkX, int chunkZ) { + LevelDBChunk chunk = (LevelDBChunk) this.getChunk(chunkX, chunkZ, false); + if (chunk == null) { + throw new ChunkException("Invalid chunk"); + } + + long timestamp = chunk.getChanges(); + + level.asyncChunk(chunk.cloneForChunkSending(), timestamp, chunkX, chunkZ); + } + + @Override + public String getPath() { + return this.path.toString(); + } + + @Override + public String getGenerator() { + return this.levelData.getString("generatorName"); + } + + @Override + public Map getGeneratorOptions() { + Map options = new HashMap<>(); + options.put("preset", this.levelData.getString("generatorOptions")); + options.put("__LevelDB", true); + options.put("__Version", this.levelData.getInt("PM1EGen")); + return options; + } + + @Override + public String getName() { + return this.levelData.getString("LevelName"); + } + + @Override + public boolean isRaining() { + return this.levelData.getBoolean("raining"); + } + + @Override + public void setRaining(boolean raining) { + this.levelData.putBoolean("raining", raining); + } + + @Override + public int getRainTime() { + return this.levelData.getInt("rainTime"); + } + + @Override + public void setRainTime(int rainTime) { + this.levelData.putInt("rainTime", rainTime); + } + + @Override + public boolean isThundering() { + return this.levelData.getBoolean("thundering"); + } + + @Override + public void setThundering(boolean thundering) { + this.levelData.putBoolean("thundering", thundering); + } + + @Override + public int getThunderTime() { + return this.levelData.getInt("thunderTime"); + } + + @Override + public void setThunderTime(int thunderTime) { + this.levelData.putInt("thunderTime", thunderTime); + } + + @Override + public long getCurrentTick() { + return this.levelData.getLong("Time"); + } + + @Override + public void setCurrentTick(long currentTick) { + this.levelData.putLong("Time", currentTick); + } + + @Override + public long getTime() { + return this.levelData.getLong("DayTime"); + } + + @Override + public void setTime(long value) { + this.levelData.putLong("DayTime", value); + } + + @Override + public long getSeed() { + return this.levelData.getLong("RandomSeed"); + } + + @Override + public void setSeed(long value) { + this.levelData.putLong("RandomSeed", value); + } + + @Override + public Vector3 getSpawn() { + return this.spawn; + } + + @Override + public void setSpawn(Vector3 spawn) { + this.levelData.putInt("SpawnX", (int) spawn.getX()); + this.levelData.putInt("SpawnY", (int) spawn.getY()); + this.levelData.putInt("SpawnZ", (int) spawn.getZ()); + this.spawn = spawn; + } + + @Override + public Level getLevel() { + return this.level; + } + + @Override + public void updateLevelName(String name) { + this.levelData.putString("LevelName", name); + } + + @Override + public GameRules getGamerules() { + GameRules rules = GameRules.getDefault(); + rules.readNBT(this.levelData); + return rules; + } + + public void setLevelData(CompoundTag levelData, GameRules gameRules) { + this.levelData = levelData; + + this.setGameRules(gameRules); + } + + @Override + public void setGameRules(GameRules rules) { + //noinspection rawtypes + for (Map.Entry entry : rules.getGameRules().entrySet()) { + String name = entry.getKey().getName().toLowerCase(); + + if (entry.getValue().getType() == GameRules.Type.BOOLEAN) { + this.levelData.putBoolean(name, rules.getBoolean(entry.getKey())); + } else if (entry.getValue().getType() == GameRules.Type.INTEGER) { + this.levelData.putInt(name, rules.getInteger(entry.getKey())); + } else if (entry.getValue().getType() == GameRules.Type.FLOAT) { + this.levelData.putFloat(name, rules.getFloat(entry.getKey())); + } + } + } + + private static CompoundTag loadLevelData(Path path) { + Path levelDat = path.resolve("level.dat"); + + try (NBTInputStream stream = new NBTInputStream(new DataInputStream(Files.newInputStream(levelDat)), ByteOrder.LITTLE_ENDIAN)) { + int version = stream.readInt(); + if (version != 8 && version != 9 && version != 10) { + throw new LevelException("Incompatible level.dat version: " + version); + } + + stream.readInt(); + return (CompoundTag) Tag.readNamedTag(stream); + } catch (Exception ex1) { + Server.getInstance().getLogger().error("Failed to load level.dat in " + path, ex1); + + Path backup = path.resolve("level.dat_old"); + if (Files.exists(backup)) { + Server.getInstance().getLogger().warning("Attempting to load level.dat_old in " + path); + + try { + // Save a copy of the corrupted one + Files.copy(levelDat, path.resolve("level.dat_invalid"), StandardCopyOption.REPLACE_EXISTING); + + // Replace the corrupted one with a backup + Files.copy(backup, levelDat, StandardCopyOption.REPLACE_EXISTING); + + try (NBTInputStream stream = new NBTInputStream(new DataInputStream(Files.newInputStream(levelDat)), ByteOrder.LITTLE_ENDIAN)) { + int version = stream.readInt(); + if (version != 8 && version != 9 && version != 10) { + throw new LevelException("Incompatible level.dat_old version: " + version); + } + + stream.readInt(); + return (CompoundTag) Tag.readNamedTag(stream); + } + } catch (Exception ex2) { + Server.getInstance().getLogger().error("Failed to load level.dat_old in " + path, ex1); + } + } + } + + throw new LevelException("Invalid level.dat"); + } + + private static void saveLevelData(CompoundTag levelData, Path path) { + // Update storage version values to latest supported + levelData.putInt("NetworkVersion", PALETTE_VERSION); + levelData.putInt("StorageVersion", LATEST_SUBCHUNK_VERSION); + + Path savePath = path.resolve("level.dat"); + try { + if (Files.exists(savePath)) { + Files.copy(savePath, path.resolve("level.dat_old"), StandardCopyOption.REPLACE_EXISTING); + } + + byte[] tagBytes; + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + NBTOutputStream stream = new NBTOutputStream(outputStream, ByteOrder.LITTLE_ENDIAN)) { + Tag.writeNamedTag(levelData, stream); + tagBytes = outputStream.toByteArray(); + } + + try (NBTOutputStream stream = new NBTOutputStream(Files.newOutputStream(savePath), ByteOrder.LITTLE_ENDIAN)) { + stream.writeInt(8); + stream.writeInt(tagBytes.length); + stream.write(tagBytes); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void saveLevelData() { + saveLevelData(this.levelData, this.path); + } + + @Override + public void close() { + if (this.closed) { + return; + } + + this.unloadChunksUnsafe(true); + this.closed = true; + this.level = null; + this.executor.shutdown(); + try { + this.executor.awaitTermination(1, TimeUnit.DAYS); + } catch (InterruptedException e) { + Server.getInstance().getLogger().error("Stopping LevelDB Executor interrupted", e); + } + + try { + this.db.close(); + } catch (IOException e) { + Server.getInstance().getLogger().error("Can not close LevelDB database", e); + } + } + + @Override + public void doGarbageCollection() { + // Noop + } + + @Override + public void doGarbageCollection(long time) { + long start = System.currentTimeMillis(); + int maxIterations = this.chunks.size(); + if (this.lastGcPosition > maxIterations) { + this.lastGcPosition = 0; + } + + ObjectIterator iterator = chunks.values().iterator(); + if (this.lastGcPosition != 0) { + iterator.skip(lastGcPosition); + } + + int iterations; + for (iterations = 0; iterations < maxIterations; iterations++) { + if (!iterator.hasNext()) { + iterator = this.chunks.values().iterator(); + } + + if (!iterator.hasNext()) { + break; + } + + BaseFullChunk chunk = iterator.next(); + if (chunk instanceof LevelDBChunk && chunk.isGenerated() && chunk.isPopulated()) { + chunk.compress(); + if (System.currentTimeMillis() - start >= time) { + break; + } + } + } + this.lastGcPosition += iterations; + } +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/NukkitLegacyMapper.java b/src/main/java/cn/nukkit/level/format/leveldb/NukkitLegacyMapper.java new file mode 100644 index 00000000000..fe7063219d2 --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/NukkitLegacyMapper.java @@ -0,0 +1,61 @@ +package cn.nukkit.level.format.leveldb; + +import cn.nukkit.block.Block; +import cn.nukkit.level.GlobalBlockPalette; +import org.cloudburstmc.nbt.NbtMap; +import org.cloudburstmc.nbt.NbtMapBuilder; +import org.cloudburstmc.nbt.NbtType; +import org.cloudburstmc.nbt.NbtUtils; + +import java.io.InputStream; +import java.util.List; + +public class NukkitLegacyMapper implements LegacyStateMapper { + + public static void registerStates(BlockStateMapping mapping) { + List states = loadBlockPalette(); + for (int i = 0; i < states.size(); i++) { + NbtMap state = states.get(i); + if (state.containsKey("name_hash") || state.containsKey("network_id") || state.containsKey("block_id")) { + NbtMapBuilder builder = NbtMapBuilder.from(state); + builder.remove("name_hash"); + builder.remove("network_id"); + builder.remove("block_id"); + state = builder.build(); + } + //noinspection ResultOfMethodCallIgnored + state.hashCode(); // cache hashCode + mapping.registerState(i, state); + } + } + + public static List loadBlockPalette() { + try (InputStream stream = NukkitLegacyMapper.class.getClassLoader().getResourceAsStream("block_palette_" + LevelDBConstants.PALETTE_VERSION + ".nbt")) { + return ((NbtMap) NbtUtils.createGZIPReader(stream).readTag()).getList("blocks", NbtType.COMPOUND); + } catch (Exception e) { + throw new AssertionError("Error while loading leveldb block palette", e); + } + } + + @Override + public int legacyToRuntime(int legacyId, int meta) { + return GlobalBlockPalette.getLeveldbBlockPalette().getRuntimeId(legacyId, meta); + } + + @Override + public int runtimeToFullId(int runtimeId) { + return GlobalBlockPalette.getLeveldbBlockPalette().getLegacyFullId(runtimeId); + } + + @Override + public int runtimeToLegacyId(int runtimeId) { + int fullId = this.runtimeToFullId(runtimeId); + return fullId == -1 ? -1 : fullId >> Block.DATA_BITS; + } + + @Override + public int runtimeToLegacyData(int runtimeId) { + int fullId = this.runtimeToFullId(runtimeId); + return fullId == -1 ? -1 : (fullId & Block.DATA_MASK); + } +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/key/BaseKey.java b/src/main/java/cn/nukkit/level/format/leveldb/key/BaseKey.java deleted file mode 100644 index 660674497e2..00000000000 --- a/src/main/java/cn/nukkit/level/format/leveldb/key/BaseKey.java +++ /dev/null @@ -1,39 +0,0 @@ -package cn.nukkit.level.format.leveldb.key; - -/** - * author: MagicDroidX - * Nukkit Project - */ -public class BaseKey { - private final int chunkX; - private final int chunkZ; - private final byte type; - - public static final byte DATA_VERSION = 0x76; - public static final byte DATA_FLAGS = 0x66; - public static final byte DATA_EXTRA_DATA = 0x34; - public static final byte DATA_TICKS = 0x33; - public static final byte DATA_ENTITIES = 0x32; - public static final byte DATA_TILES = 0x31; - public static final byte DATA_TERRAIN = 0x30; - - protected BaseKey(int chunkX, int chunkZ, byte type) { - this.chunkX = chunkX; - this.chunkZ = chunkZ; - this.type = type; - } - - public byte[] toArray() { - return new byte[]{ - (byte) (this.chunkX & 0xff), - (byte) ((this.chunkX >>> 8) & 0xff), - (byte) ((this.chunkX >>> 16) & 0xff), - (byte) ((this.chunkX >>> 24) & 0xff), - (byte) (this.chunkZ & 0xff), - (byte) ((this.chunkZ >>> 8) & 0xff), - (byte) ((this.chunkZ >>> 16) & 0xff), - (byte) ((this.chunkZ >>> 24) & 0xff), - this.type - }; - } -} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/key/EntitiesKey.java b/src/main/java/cn/nukkit/level/format/leveldb/key/EntitiesKey.java deleted file mode 100644 index 7ea9a9cd029..00000000000 --- a/src/main/java/cn/nukkit/level/format/leveldb/key/EntitiesKey.java +++ /dev/null @@ -1,15 +0,0 @@ -package cn.nukkit.level.format.leveldb.key; - -/** - * author: MagicDroidX - * Nukkit Project - */ -public class EntitiesKey extends BaseKey { - protected EntitiesKey(int chunkX, int chunkZ) { - super(chunkX, chunkZ, DATA_ENTITIES); - } - - public static EntitiesKey create(int chunkX, int chunkZ) { - return new EntitiesKey(chunkX, chunkZ); - } -} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/key/ExtraDataKey.java b/src/main/java/cn/nukkit/level/format/leveldb/key/ExtraDataKey.java deleted file mode 100644 index 8632826bf6c..00000000000 --- a/src/main/java/cn/nukkit/level/format/leveldb/key/ExtraDataKey.java +++ /dev/null @@ -1,15 +0,0 @@ -package cn.nukkit.level.format.leveldb.key; - -/** - * author: MagicDroidX - * Nukkit Project - */ -public class ExtraDataKey extends BaseKey { - protected ExtraDataKey(int chunkX, int chunkZ) { - super(chunkX, chunkZ, DATA_EXTRA_DATA); - } - - public static ExtraDataKey create(int chunkX, int chunkZ) { - return new ExtraDataKey(chunkX, chunkZ); - } -} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/key/FlagsKey.java b/src/main/java/cn/nukkit/level/format/leveldb/key/FlagsKey.java deleted file mode 100644 index 800442642e9..00000000000 --- a/src/main/java/cn/nukkit/level/format/leveldb/key/FlagsKey.java +++ /dev/null @@ -1,15 +0,0 @@ -package cn.nukkit.level.format.leveldb.key; - -/** - * author: MagicDroidX - * Nukkit Project - */ -public class FlagsKey extends BaseKey { - protected FlagsKey(int chunkX, int chunkZ) { - super(chunkX, chunkZ, DATA_FLAGS); - } - - public static FlagsKey create(int chunkX, int chunkZ) { - return new FlagsKey(chunkX, chunkZ); - } -} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/key/TerrainKey.java b/src/main/java/cn/nukkit/level/format/leveldb/key/TerrainKey.java deleted file mode 100644 index 6536483313f..00000000000 --- a/src/main/java/cn/nukkit/level/format/leveldb/key/TerrainKey.java +++ /dev/null @@ -1,15 +0,0 @@ -package cn.nukkit.level.format.leveldb.key; - -/** - * author: MagicDroidX - * Nukkit Project - */ -public class TerrainKey extends BaseKey { - protected TerrainKey(int chunkX, int chunkZ) { - super(chunkX, chunkZ, DATA_TERRAIN); - } - - public static TerrainKey create(int chunkX, int chunkZ) { - return new TerrainKey(chunkX, chunkZ); - } -} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/key/TicksKey.java b/src/main/java/cn/nukkit/level/format/leveldb/key/TicksKey.java deleted file mode 100644 index aa9bf1da317..00000000000 --- a/src/main/java/cn/nukkit/level/format/leveldb/key/TicksKey.java +++ /dev/null @@ -1,15 +0,0 @@ -package cn.nukkit.level.format.leveldb.key; - -/** - * author: MagicDroidX - * Nukkit Project - */ -public class TicksKey extends BaseKey { - protected TicksKey(int chunkX, int chunkZ) { - super(chunkX, chunkZ, DATA_TICKS); - } - - public static TicksKey create(int chunkX, int chunkZ) { - return new TicksKey(chunkX, chunkZ); - } -} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/key/TilesKey.java b/src/main/java/cn/nukkit/level/format/leveldb/key/TilesKey.java deleted file mode 100644 index 8c1e4fa3218..00000000000 --- a/src/main/java/cn/nukkit/level/format/leveldb/key/TilesKey.java +++ /dev/null @@ -1,15 +0,0 @@ -package cn.nukkit.level.format.leveldb.key; - -/** - * author: MagicDroidX - * Nukkit Project - */ -public class TilesKey extends BaseKey { - protected TilesKey(int chunkX, int chunkZ) { - super(chunkX, chunkZ, DATA_TILES); - } - - public static TilesKey create(int chunkX, int chunkZ) { - return new TilesKey(chunkX, chunkZ); - } -} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/key/VersionKey.java b/src/main/java/cn/nukkit/level/format/leveldb/key/VersionKey.java deleted file mode 100644 index 617989fcc45..00000000000 --- a/src/main/java/cn/nukkit/level/format/leveldb/key/VersionKey.java +++ /dev/null @@ -1,15 +0,0 @@ -package cn.nukkit.level.format.leveldb.key; - -/** - * author: MagicDroidX - * Nukkit Project - */ -public class VersionKey extends BaseKey { - protected VersionKey(int chunkX, int chunkZ) { - super(chunkX, chunkZ, DATA_VERSION); - } - - public static VersionKey create(int chunkX, int chunkZ) { - return new VersionKey(chunkX, chunkZ); - } -} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/serializer/BlockEntitySerializer.java b/src/main/java/cn/nukkit/level/format/leveldb/serializer/BlockEntitySerializer.java new file mode 100644 index 00000000000..c18fa402791 --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/serializer/BlockEntitySerializer.java @@ -0,0 +1,64 @@ +package cn.nukkit.level.format.leveldb.serializer; + +import cn.nukkit.blockentity.BlockEntity; +import cn.nukkit.level.format.leveldb.LevelDBKey; +import cn.nukkit.level.format.leveldb.structure.ChunkBuilder; +import cn.nukkit.level.format.leveldb.structure.LevelDBChunk; +import cn.nukkit.nbt.NBTIO; +import cn.nukkit.nbt.tag.CompoundTag; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.iq80.leveldb.DB; +import org.iq80.leveldb.WriteBatch; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteOrder; +import java.util.Collection; +import java.util.List; + +public class BlockEntitySerializer { + + public static void loadBlockEntities(DB db, ChunkBuilder builder) { + byte[] key = LevelDBKey.BLOCK_ENTITIES.getKey(builder.getX(), builder.getZ(), builder.getProvider().getLevel().getDimension()); + + byte[] value = db.get(key); + if (value == null) { + return; + } + + List blockEntities = new ObjectArrayList<>(); + try (ByteArrayInputStream stream = new ByteArrayInputStream(value)) { + while (stream.available() > 0) { + blockEntities.add(NBTIO.read(stream, ByteOrder.LITTLE_ENDIAN)); + } + builder.dataLoader((chunk, provider) -> chunk.setNbtBlockEntities(blockEntities)); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static void saveBlockEntities(WriteBatch db, LevelDBChunk chunk) { + byte[] key = LevelDBKey.BLOCK_ENTITIES.getKey(chunk.getX(), chunk.getZ(), chunk.getProvider().getLevel().getDimension()); + if (chunk.getBlockEntities().isEmpty()) { + db.delete(key); + return; + } + + Collection entities = chunk.getBlockEntities().values(); + + byte[] value; + try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { + for (BlockEntity blockEntity : entities) { + if (blockEntity.canSaveToStorage()) { + blockEntity.saveNBT(); + NBTIO.write(blockEntity.namedTag, stream, ByteOrder.LITTLE_ENDIAN); + } + } + value = stream.toByteArray(); + } catch (IOException e) { + throw new RuntimeException(e); + } + db.put(key, value); + } +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkDataLoader.java b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkDataLoader.java new file mode 100644 index 00000000000..2bcfa57f019 --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkDataLoader.java @@ -0,0 +1,9 @@ +package cn.nukkit.level.format.leveldb.serializer; + +import cn.nukkit.level.format.leveldb.LevelDBProvider; +import cn.nukkit.level.format.leveldb.structure.LevelDBChunk; + +public interface ChunkDataLoader { + + void initChunk(LevelDBChunk chunk, LevelDBProvider provider); +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSectionSerializer.java b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSectionSerializer.java new file mode 100644 index 00000000000..438b97beda4 --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSectionSerializer.java @@ -0,0 +1,12 @@ +package cn.nukkit.level.format.leveldb.serializer; + +import cn.nukkit.level.format.leveldb.structure.ChunkBuilder; +import cn.nukkit.level.format.leveldb.structure.StateBlockStorage; +import io.netty.buffer.ByteBuf; + +interface ChunkSectionSerializer { + + void serialize(ByteBuf buf, StateBlockStorage[] storage, int ySection); + + StateBlockStorage[] deserialize(ByteBuf buf, ChunkBuilder builder); +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSectionSerializerV1.java b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSectionSerializerV1.java new file mode 100644 index 00000000000..5a4cc784f36 --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSectionSerializerV1.java @@ -0,0 +1,23 @@ +package cn.nukkit.level.format.leveldb.serializer; + +import cn.nukkit.level.format.leveldb.structure.ChunkBuilder; +import cn.nukkit.level.format.leveldb.structure.StateBlockStorage; +import io.netty.buffer.ByteBuf; + +public class ChunkSectionSerializerV1 implements ChunkSectionSerializer { + + public static final ChunkSectionSerializer INSTANCE = new ChunkSectionSerializerV1(); + + @Override + public void serialize(ByteBuf buf, StateBlockStorage[] storage, int ySection) { + throw new UnsupportedOperationException(); + } + + @Override + public StateBlockStorage[] deserialize(ByteBuf buf, ChunkBuilder builder) { + StateBlockStorage[] storage = new StateBlockStorage[2]; + storage[0] = new StateBlockStorage(); + storage[0].readFromStorage(buf, builder); + return storage; + } +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSectionSerializerV7.java b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSectionSerializerV7.java new file mode 100644 index 00000000000..e153beff7ef --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSectionSerializerV7.java @@ -0,0 +1,41 @@ +package cn.nukkit.level.format.leveldb.serializer; + +import cn.nukkit.level.format.anvil.util.NibbleArray; +import cn.nukkit.level.format.leveldb.BlockStateMapping; +import cn.nukkit.level.format.leveldb.structure.ChunkBuilder; +import cn.nukkit.level.format.leveldb.structure.StateBlockStorage; +import io.netty.buffer.ByteBuf; + +public class ChunkSectionSerializerV7 implements ChunkSectionSerializer { + + public static final ChunkSectionSerializer INSTANCE = new ChunkSectionSerializerV7(); + + @Override + public void serialize(ByteBuf buf, StateBlockStorage[] storage, int ySection) { + throw new UnsupportedOperationException(); + } + + @Override + public StateBlockStorage[] deserialize(ByteBuf buf, ChunkBuilder builder) { + byte[] blockIds = new byte[4096]; + buf.readBytes(blockIds); + byte[] blockData = new byte[2048]; + buf.readBytes(blockData); + if (buf.isReadable(4096)) { + buf.skipBytes(4096); // light + } + + StateBlockStorage[] blockStorage = new StateBlockStorage[2]; + blockStorage[0] = fromXZY(blockIds, blockData); + return blockStorage; + } + + private static StateBlockStorage fromXZY(byte[] blockIds, byte[] blockData) { + NibbleArray data = new NibbleArray(blockData); + StateBlockStorage storage = new StateBlockStorage(); + for (int i = 0; i < 4096; i++) { + storage.setBlockStateUnsafe(i, BlockStateMapping.get().getState(blockIds[i], data.get(i))); + } + return storage; + } +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSectionSerializerV8.java b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSectionSerializerV8.java new file mode 100644 index 00000000000..4e5c34b6097 --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSectionSerializerV8.java @@ -0,0 +1,30 @@ +package cn.nukkit.level.format.leveldb.serializer; + +import cn.nukkit.level.format.leveldb.structure.ChunkBuilder; +import cn.nukkit.level.format.leveldb.structure.StateBlockStorage; +import io.netty.buffer.ByteBuf; + +public class ChunkSectionSerializerV8 implements ChunkSectionSerializer { + + public static final ChunkSectionSerializer INSTANCE = new ChunkSectionSerializerV8(); + + @Override + public void serialize(ByteBuf buf, StateBlockStorage[] storage, int ySection) { + buf.writeByte(storage.length); + for (StateBlockStorage blockStorage : storage) { + blockStorage.writeToStorage(buf); + } + } + + @Override + public StateBlockStorage[] deserialize(ByteBuf buf, ChunkBuilder builder) { + int storageCount = buf.readUnsignedByte(); + + StateBlockStorage[] storage = new StateBlockStorage[Math.max(storageCount, 2)]; + for (int i = 0; i < storageCount; i++) { + storage[i] = new StateBlockStorage(); + storage[i].readFromStorage(buf, builder); + } + return storage; + } +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSectionSerializerV9.java b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSectionSerializerV9.java new file mode 100644 index 00000000000..a8adcc3a3ee --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSectionSerializerV9.java @@ -0,0 +1,32 @@ +package cn.nukkit.level.format.leveldb.serializer; + +import cn.nukkit.level.format.leveldb.structure.ChunkBuilder; +import cn.nukkit.level.format.leveldb.structure.StateBlockStorage; +import io.netty.buffer.ByteBuf; + +public class ChunkSectionSerializerV9 implements ChunkSectionSerializer { + + public static final ChunkSectionSerializer INSTANCE = new ChunkSectionSerializerV9(); + + @Override + public void serialize(ByteBuf buf, StateBlockStorage[] storage, int ySection) { + buf.writeByte(storage.length); + buf.writeByte(ySection); + for (StateBlockStorage blockStorage : storage) { + blockStorage.writeToStorage(buf); + } + } + + @Override + public StateBlockStorage[] deserialize(ByteBuf buf, ChunkBuilder builder) { + int storageCount = buf.readUnsignedByte(); + buf.readUnsignedByte(); // ySection + + StateBlockStorage[] storage = new StateBlockStorage[Math.max(storageCount, 2)]; + for (int i = 0; i < storageCount; i++) { + storage[i] = new StateBlockStorage(); + storage[i].readFromStorage(buf, builder); + } + return storage; + } +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSectionSerializers.java b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSectionSerializers.java new file mode 100644 index 00000000000..7e1a3fb7c87 --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSectionSerializers.java @@ -0,0 +1,38 @@ +package cn.nukkit.level.format.leveldb.serializer; + +import cn.nukkit.level.format.leveldb.structure.ChunkBuilder; +import cn.nukkit.level.format.leveldb.structure.StateBlockStorage; +import com.google.common.base.Preconditions; +import io.netty.buffer.ByteBuf; + +public class ChunkSectionSerializers { + private static final ChunkSectionSerializer[] SERIALIZERS = new ChunkSectionSerializer[10]; + + static { + SERIALIZERS[0] = ChunkSectionSerializerV7.INSTANCE; + SERIALIZERS[1] = ChunkSectionSerializerV1.INSTANCE; + SERIALIZERS[2] = ChunkSectionSerializerV7.INSTANCE; + SERIALIZERS[3] = ChunkSectionSerializerV7.INSTANCE; + SERIALIZERS[4] = ChunkSectionSerializerV7.INSTANCE; + SERIALIZERS[5] = ChunkSectionSerializerV7.INSTANCE; + SERIALIZERS[6] = ChunkSectionSerializerV7.INSTANCE; + SERIALIZERS[7] = ChunkSectionSerializerV7.INSTANCE; + SERIALIZERS[8] = ChunkSectionSerializerV8.INSTANCE; + SERIALIZERS[9] = ChunkSectionSerializerV9.INSTANCE; + } + + public static void serialize(ByteBuf buf, StateBlockStorage[] storage, int ySection, int version) { + getSerializer(version).serialize(buf, storage, ySection); + } + + public static StateBlockStorage[] deserialize(ByteBuf buf, ChunkBuilder builder, int version) { + return getSerializer(version).deserialize(buf, builder); + } + + public static ChunkSectionSerializer getSerializer(int version) { + Preconditions.checkElementIndex(version, SERIALIZERS.length, "Invalid sub-chunk version " + version); + ChunkSectionSerializer serializer = SERIALIZERS[version]; + if (serializer == null) throw new NullPointerException("No ChunkSectionSerializer for version " + version); + return serializer; + } +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSerializer.java b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSerializer.java new file mode 100644 index 00000000000..81c8848ee9b --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSerializer.java @@ -0,0 +1,13 @@ +package cn.nukkit.level.format.leveldb.serializer; + +import cn.nukkit.level.format.Chunk; +import cn.nukkit.level.format.leveldb.structure.ChunkBuilder; +import org.iq80.leveldb.DB; +import org.iq80.leveldb.WriteBatch; + +public interface ChunkSerializer { + + void serialize(WriteBatch db, Chunk chunk); + + void deserialize(DB db, ChunkBuilder chunkBuilder); +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSerializerV3.java b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSerializerV3.java new file mode 100644 index 00000000000..06d2d48ef0b --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSerializerV3.java @@ -0,0 +1,128 @@ +package cn.nukkit.level.format.leveldb.serializer; + +import cn.nukkit.level.DimensionData; +import cn.nukkit.level.format.Chunk; +import cn.nukkit.level.format.generic.EmptyChunkSection; +import cn.nukkit.level.format.leveldb.BlockStateMapping; +import cn.nukkit.level.format.leveldb.LevelDBKey; +import cn.nukkit.level.format.leveldb.structure.ChunkBuilder; +import cn.nukkit.level.format.leveldb.structure.LevelDBChunkSection; +import cn.nukkit.level.format.leveldb.structure.StateBlockStorage; +import cn.nukkit.utils.ChunkException; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import io.netty.buffer.Unpooled; +import it.unimi.dsi.fastutil.ints.Int2ShortMap; +import it.unimi.dsi.fastutil.ints.Int2ShortOpenHashMap; +import org.iq80.leveldb.DB; +import org.iq80.leveldb.WriteBatch; + +import static cn.nukkit.level.format.leveldb.LevelDBConstants.*; + +public class ChunkSerializerV3 implements ChunkSerializer { + public static final ChunkSerializer INSTANCE = new ChunkSerializerV3(); + + @Override + public void serialize(WriteBatch db, Chunk chunk) { + // Write chunk sections + DimensionData dimensionData = chunk.getProvider().getLevel().getDimensionData(); + int lowestSection = dimensionData.getMinHeight() >> 4; + int highestSection = dimensionData.getMaxHeight() >> 4; + + for (int ySection = lowestSection; ySection <= highestSection; ySection++) { + LevelDBChunkSection section = (LevelDBChunkSection) chunk.getSection(ySection); + if (section == null) { + continue; + } + + ByteBuf buffer = ByteBufAllocator.DEFAULT.ioBuffer(); + try { + buffer.writeByte(LATEST_SUBCHUNK_VERSION); + ChunkSectionSerializers.serialize(buffer, section.getStorages(), ySection, LATEST_SUBCHUNK_VERSION); + + byte[] payload = new byte[buffer.readableBytes()]; + buffer.readBytes(payload); + db.put(LevelDBKey.SUB_CHUNK_PREFIX.getKey(chunk.getX(), chunk.getZ(), ySection, chunk.getProvider().getLevel().getDimension()), payload); + } finally { + buffer.release(); + } + + buffer = ByteBufAllocator.DEFAULT.ioBuffer(); + try { + byte[] blockLight = section.getLightArray(); + if (blockLight != EmptyChunkSection.EMPTY_LIGHT_ARR) { + db.put(LevelDBKey.NUKKIT_BLOCK_LIGHT.getKey(chunk.getX(), chunk.getZ(), ySection, chunk.getProvider().getLevel().getDimension()), blockLight); + } + } finally { + buffer.release(); + } + } + } + + @Override + public void deserialize(DB db, ChunkBuilder chunkBuilder) { + int chunkX = chunkBuilder.getX(); + int chunkZ = chunkBuilder.getZ(); + + Int2ShortMap extraDataMap = null; + + byte[] extraData = db.get(LevelDBKey.BLOCK_EXTRA_DATA.getKey(chunkX, chunkZ, chunkBuilder.getProvider().getLevel().getDimension())); + if (extraData != null) { + extraDataMap = new Int2ShortOpenHashMap(); + ByteBuf extraDataBuf = Unpooled.wrappedBuffer(extraData); + + int count = extraDataBuf.readIntLE(); + for (int i = 0; i < count; i++) { + int key = extraDataBuf.readIntLE(); + short value = extraDataBuf.readShortLE(); + extraDataMap.put(key, value); + } + } + + DimensionData dimensionData = chunkBuilder.getProvider().getLevel().getDimensionData(); + int offset = dimensionData.getSectionOffset(); + int lowestSection = dimensionData.getMinHeight() >> 4; + int highestSection = dimensionData.getMaxHeight() >> 4; + + LevelDBChunkSection[] sections = new LevelDBChunkSection[dimensionData.getHeight() >> 4]; + + for (int ySection = lowestSection; ySection <= highestSection; ySection++) { + byte[] sectionData = db.get(LevelDBKey.SUB_CHUNK_PREFIX.getKey(chunkX, chunkZ, ySection, chunkBuilder.getProvider().getLevel().getDimension())); + if (sectionData == null) { + continue; + } + ByteBuf buf = Unpooled.wrappedBuffer(sectionData); + if (!buf.isReadable()) { + throw new ChunkException("Empty sub-chunk " + ySection); + } + + int subChunkVersion = buf.readUnsignedByte(); + StateBlockStorage[] blockStorage = ChunkSectionSerializers.deserialize(buf, chunkBuilder, subChunkVersion); + + if (blockStorage[1] == null) { + blockStorage[1] = new StateBlockStorage(); + if (extraDataMap != null) { + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + for (int y = ySection << 4, lim = y + 16; y < lim; y++) { + int key = ChunkBuilder.blockKey(x, y, z); + if (extraDataMap.containsKey(key)) { + short value = extraDataMap.get(ChunkBuilder.blockKey(x, y, z)); + int blockId = value & 0xff; + int blockData = (value >> 8) & 0xf; + blockStorage[1].setBlockStateUnsafe(ChunkBuilder.getSectionIndex(x, y, z), BlockStateMapping.get().getState(blockId, blockData)); + } + } + } + } + } + } + + byte[] blockLight = db.get(LevelDBKey.NUKKIT_BLOCK_LIGHT.getKey(chunkX, chunkZ, ySection, chunkBuilder.getProvider().getLevel().getDimension())); + + sections[ySection + offset] = new LevelDBChunkSection(ySection, blockStorage, blockLight, null, null, false, false); + } + + chunkBuilder.sections(sections); + } +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSerializers.java b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSerializers.java new file mode 100644 index 00000000000..08647e19272 --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/serializer/ChunkSerializers.java @@ -0,0 +1,57 @@ +package cn.nukkit.level.format.leveldb.serializer; + +import cn.nukkit.level.format.leveldb.structure.ChunkBuilder; +import cn.nukkit.level.format.leveldb.structure.LevelDBChunk; +import io.netty.util.collection.IntObjectHashMap; +import io.netty.util.collection.IntObjectMap; +import org.iq80.leveldb.DB; +import org.iq80.leveldb.WriteBatch; + +public class ChunkSerializers { + private static final IntObjectMap SERIALIZERS = new IntObjectHashMap<>(); + + static { + // SERIALIZERS.put(0, ChunkSerializerV1.INSTANCE); + // SERIALIZERS.put(1, ChunkSerializerV1.INSTANCE); + // SERIALIZERS.put(2, ChunkSerializerV1.INSTANCE); + SERIALIZERS.put(3, ChunkSerializerV3.INSTANCE); // v1_0_0 + SERIALIZERS.put(4, ChunkSerializerV3.INSTANCE); // v1_1_0 + SERIALIZERS.put(6, ChunkSerializerV3.INSTANCE); // v1_2_0_2_beta + SERIALIZERS.put(7, ChunkSerializerV3.INSTANCE); // v1_2_0 + SERIALIZERS.put(9, ChunkSerializerV3.INSTANCE); // v1_8_0 + SERIALIZERS.put(10, ChunkSerializerV3.INSTANCE); // v1_9_0 + SERIALIZERS.put(11, ChunkSerializerV3.INSTANCE); // v1_11_0_1_beta + SERIALIZERS.put(12, ChunkSerializerV3.INSTANCE); // v1_11_0_3_beta + SERIALIZERS.put(13, ChunkSerializerV3.INSTANCE); // v1_11_0_4_beta + SERIALIZERS.put(14, ChunkSerializerV3.INSTANCE); // v1_11_1 + SERIALIZERS.put(15, ChunkSerializerV3.INSTANCE); // v1_12_0_4_beta + SERIALIZERS.put(16, ChunkSerializerV3.INSTANCE); // v1_12_0_unused1 + SERIALIZERS.put(17, ChunkSerializerV3.INSTANCE); // v1_12_0_unused2 + SERIALIZERS.put(18, ChunkSerializerV3.INSTANCE); // v1_16_0_51_beta + SERIALIZERS.put(19, ChunkSerializerV3.INSTANCE); // v1_16_0 + SERIALIZERS.put(22, ChunkSerializerV3.INSTANCE); // v1_16_210 + // Here are some experimental Caves & Cliffs versions from 1.16 betas + SERIALIZERS.put(32, ChunkSerializerV3.INSTANCE); // v1_17_40_unused + SERIALIZERS.put(33, ChunkSerializerV3.INSTANCE); // v1_18_0_20_beta + SERIALIZERS.put(35, ChunkSerializerV3.INSTANCE); // v1_18_0_22_beta + SERIALIZERS.put(37, ChunkSerializerV3.INSTANCE); // v1_18_0_24_beta + SERIALIZERS.put(39, ChunkSerializerV3.INSTANCE); // v1_18_0_25_beta + SERIALIZERS.put(40, ChunkSerializerV3.INSTANCE); // v1_18_30 + } + + private static ChunkSerializer getChunkSerializer(int version) { + ChunkSerializer chunkSerializer = SERIALIZERS.get(version); + if (chunkSerializer == null) { + throw new IllegalArgumentException("Invalid chunk serializer version " + version + "! Serializers up to 1.21.30 (version 40) are supported"); + } + return chunkSerializer; + } + + public static void serializeChunk(WriteBatch db, LevelDBChunk chunk, int version) { + getChunkSerializer(version).serialize(db, chunk); + } + + public static void deserializeChunk(DB db, ChunkBuilder chunkBuilder, int version) { + getChunkSerializer(version).deserialize(db, chunkBuilder); + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/format/leveldb/serializer/Data2dSerializer.java b/src/main/java/cn/nukkit/level/format/leveldb/serializer/Data2dSerializer.java new file mode 100644 index 00000000000..b1505db8335 --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/serializer/Data2dSerializer.java @@ -0,0 +1,45 @@ +package cn.nukkit.level.format.leveldb.serializer; + +import cn.nukkit.level.format.leveldb.LevelDBKey; +import cn.nukkit.level.format.leveldb.structure.ChunkBuilder; +import cn.nukkit.level.format.leveldb.structure.LevelDBChunk; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import org.iq80.leveldb.DB; +import org.iq80.leveldb.WriteBatch; + +public class Data2dSerializer { + + public static void serialize(WriteBatch db, LevelDBChunk chunk) { + // Write height map and biomes. + byte[] data2d = new byte[768]; + ByteBuf buffer = Unpooled.wrappedBuffer(data2d); + buffer.writerIndex(0); + byte[] heightMap = chunk.getHeightMapArray(); + byte[] biomes = chunk.getBiomeIdArray(); + for (int height : heightMap) { + buffer.writeShortLE(height); + } + buffer.writeBytes(biomes); + + db.put(LevelDBKey.DATA_2D.getKey(chunk.getX(), chunk.getZ(), chunk.getProvider().getLevel().getDimension()), data2d); + } + + public static void deserialize(DB db, ChunkBuilder builder) { + byte[] data2d = db.get(LevelDBKey.DATA_2D.getKey(builder.getX(), builder.getZ(), builder.getProvider().getLevel().getDimension())); + int[] heightMap = new int[512]; + byte[] biomes = new byte[256]; + + if (data2d != null) { + ByteBuf buffer = Unpooled.wrappedBuffer(data2d); + + for (int i = 0; i < 256; i++) { + heightMap[i] = buffer.readUnsignedShortLE(); + } + buffer.readBytes(biomes); + } + + builder.heightMap(heightMap); + builder.biomes(biomes); + } +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/serializer/Data3dSerializer.java b/src/main/java/cn/nukkit/level/format/leveldb/serializer/Data3dSerializer.java new file mode 100644 index 00000000000..94dcdd243f3 --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/serializer/Data3dSerializer.java @@ -0,0 +1,90 @@ +package cn.nukkit.level.format.leveldb.serializer; + +import cn.nukkit.level.DimensionData; +import cn.nukkit.level.format.leveldb.LevelDBKey; +import cn.nukkit.level.format.leveldb.structure.ChunkBuilder; +import cn.nukkit.level.format.leveldb.structure.LevelDBChunk; +import cn.nukkit.level.util.BitArrayVersion; +import cn.nukkit.level.util.PalettedBlockStorage; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import org.iq80.leveldb.DB; +import org.iq80.leveldb.WriteBatch; + +public class Data3dSerializer { + + public static void serialize(WriteBatch db, LevelDBChunk chunk) { + DimensionData dimensionData = chunk.getProvider().getLevel().getDimensionData(); + + ByteBuf buffer = ByteBufAllocator.DEFAULT.ioBuffer(); + try { + byte[] heightMap = chunk.getHeightMapArray(); + for (int height : heightMap) { + buffer.writeShortLE(height); + } + + for (int i = 0; i < dimensionData.getHeight() >> 4; i++) { + PalettedBlockStorage storage = chunk.getBiomeStorage(i); + storage.writeToStorage(buffer); + } + + byte[] data = new byte[buffer.readableBytes()]; + buffer.readBytes(data); + db.put(LevelDBKey.DATA_3D.getKey(chunk.getX(), chunk.getZ(), chunk.getProvider().getLevel().getDimension()), data); + } finally { + buffer.release(); + } + } + + public static void deserialize(DB db, ChunkBuilder builder) { + DimensionData dimensionData = builder.getProvider().getLevel().getDimensionData(); + + byte[] data3d = db.get(LevelDBKey.DATA_3D.getKey(builder.getX(), builder.getZ(), dimensionData.getDimensionId())); + if (data3d == null || data3d.length < 1) { + return; + } + + + int[] heightMap = new int[512]; + PalettedBlockStorage[] biomes = new PalettedBlockStorage[dimensionData.getHeight() >> 4]; + + ByteBuf buffer = ByteBufAllocator.DEFAULT.ioBuffer(data3d.length); + try { + buffer.writeBytes(data3d); + for (int i = 0; i < 256; i++) { + heightMap[i] = buffer.readUnsignedShortLE(); + } + + for (int i = 0; i < biomes.length; i++) { + PalettedBlockStorage storage = readPalettedBiomes(buffer); + if (storage == null && i == 0) { + throw new IllegalStateException("First biome palette can not point to previous!"); + } + + if (storage == null) { + storage = biomes[i - 1].copy(); + } + biomes[i] = storage; + } + } finally { + buffer.release(); + } + + builder.heightMap(heightMap); + builder.biomes3d(biomes); + } + + public static PalettedBlockStorage readPalettedBiomes(ByteBuf buffer) { + int index = buffer.readerIndex(); + int size = buffer.readUnsignedByte() >> 1; + if (size == 127) { + // This means this paletted storage had the flag pointing to the previous one + return null; + } + + buffer.readerIndex(index); + PalettedBlockStorage storage = PalettedBlockStorage.createWithDefaultState(BitArrayVersion.V0, 0); + storage.readFromStorage(buffer); + return storage; + } +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/serializer/EntitySerializer.java b/src/main/java/cn/nukkit/level/format/leveldb/serializer/EntitySerializer.java new file mode 100644 index 00000000000..f1289100c07 --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/serializer/EntitySerializer.java @@ -0,0 +1,88 @@ +package cn.nukkit.level.format.leveldb.serializer; + +import cn.nukkit.entity.Entity; +import cn.nukkit.level.format.leveldb.LevelDBKey; +import cn.nukkit.level.format.leveldb.structure.ChunkBuilder; +import cn.nukkit.level.format.leveldb.structure.LevelDBChunk; +import cn.nukkit.nbt.NBTIO; +import cn.nukkit.nbt.tag.CompoundTag; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.iq80.leveldb.DB; +import org.iq80.leveldb.WriteBatch; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.ByteOrder; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; + +public class EntitySerializer { + + public static void loadEntities(DB db, ChunkBuilder builder) { + byte[] key = LevelDBKey.ENTITIES.getKey(builder.getX(), builder.getZ(), builder.getProvider().getLevel().getDimension()); + + byte[] value = db.get(key); + if (value == null) { + return; + } + + List entityTags = new ObjectArrayList<>(); + try (ByteArrayInputStream stream = new ByteArrayInputStream(value)) { + while (stream.available() > 0) { + deserializeNbt(NBTIO.read(stream, ByteOrder.LITTLE_ENDIAN), entityTags::add); + } + builder.dataLoader((chunk, provider) -> chunk.setNbtEntities(entityTags)); + } catch (IOException e) { + throw new RuntimeException("Unable to deserialize entity NBT", e); + } + } + + public static void saveEntities(WriteBatch db, LevelDBChunk chunk) { + byte[] key = LevelDBKey.ENTITIES.getKey(chunk.getX(), chunk.getZ(), chunk.getProvider().getLevel().getDimension()); + Collection entities = chunk.getEntities().values(); + if (entities.isEmpty()) { + db.delete(key); + return; + } + + byte[] value; + try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { + for (Entity entity : entities) { + if (entity.canSaveToStorage() && !entity.closed) { + // Player data are still saved externally + entity.saveNBT(); + serializeNbt(entity.namedTag, nbt -> writeSilently(nbt, stream)); + } + } + value = stream.toByteArray(); + } catch (IOException e) { + throw new RuntimeException("Can not create out stream", e); + } + db.put(key, value); + } + + private static void deserializeNbt(CompoundTag nbt, Consumer handle) { + // TODO: convert LevelDB format to our legacy + if (!nbt.contains("id") || !nbt.contains("Pos")) { + return; + } + handle.accept(nbt); + } + + private static void serializeNbt(CompoundTag nbt, Consumer handle) { + // TODO: use identifiers instead of class names here + // might do some validation here too + handle.accept(nbt); + } + + private static void writeSilently(CompoundTag nbt, OutputStream stream) { + try { + NBTIO.write(nbt, stream, ByteOrder.LITTLE_ENDIAN); + } catch (IOException e) { + throw new RuntimeException("Unable to write entity NBT", e); + } + } +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/structure/BlockStateSnapshot.java b/src/main/java/cn/nukkit/level/format/leveldb/structure/BlockStateSnapshot.java new file mode 100644 index 00000000000..5c66838ccc2 --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/structure/BlockStateSnapshot.java @@ -0,0 +1,63 @@ +package cn.nukkit.level.format.leveldb.structure; + +import cn.nukkit.level.GlobalBlockPalette; +import cn.nukkit.level.format.leveldb.BlockStateMapping; +import org.cloudburstmc.nbt.NbtMap; +import lombok.Builder; +import lombok.Getter; +import lombok.ToString; + +@Getter +@Builder +@ToString +public class BlockStateSnapshot { + private final NbtMap vanillaState; + private final int runtimeId; + private final int version; + + @Builder.Default + private boolean custom = false; + + @Builder.Default + private int legacyId = -1; + @Builder.Default + private int legacyData = -1; + + @Builder.Default + private int runtimeIdNetworkProtocol = -1; + + public int getLegacyId() { + if (this.legacyId != -1) { + return this.legacyId; + } + + int id = BlockStateMapping.get().getLegacyId(this.runtimeId); + if (this.version == BlockStateMapping.get().getVersion()) { + // Cache legacyId only if the mapping is same version, + // plugins might be passing custom states + // with unknown legacyId to vanilla mapping + this.legacyId = id; + } + return id; + } + + public int getLegacyData() { + if (this.legacyData != -1) { + return this.legacyData; + } + + int data = BlockStateMapping.get().getLegacyData(this.runtimeId); + if (this.version == BlockStateMapping.get().getVersion()) { + this.legacyData = data; + } + return data; + } + + int getRuntimeIdNetworkProtocol() { + if (this.runtimeIdNetworkProtocol == -1) { + this.runtimeIdNetworkProtocol = GlobalBlockPalette.getOrCreateRuntimeId(this.getLegacyId(), this.getLegacyData()); + } + + return this.runtimeIdNetworkProtocol; + } +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/structure/ChunkBuilder.java b/src/main/java/cn/nukkit/level/format/leveldb/structure/ChunkBuilder.java new file mode 100644 index 00000000000..3e2f0a82457 --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/structure/ChunkBuilder.java @@ -0,0 +1,171 @@ +package cn.nukkit.level.format.leveldb.structure; + +import cn.nukkit.level.format.leveldb.LevelDBConstants; +import cn.nukkit.level.format.leveldb.LevelDBProvider; +import cn.nukkit.level.format.leveldb.serializer.ChunkDataLoader; +import cn.nukkit.level.util.PalettedBlockStorage; +import cn.nukkit.math.Vector3; +import it.unimi.dsi.fastutil.ints.Int2IntMap; +import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + +import java.util.List; + +public class ChunkBuilder { + + public static final int STATE_NEW = 0; + public static final int STATE_GENERATED = 1; + public static final int STATE_POPULATED = 2; + public static final int STATE_FINISHED = 3; + + private final int x; + private final int z; + private final LevelDBProvider provider; + + private Int2IntMap extraData; + private final List chunkDataLoaders = new ObjectArrayList<>(); + private LevelDBChunkSection[] sections; + private byte[] biomes; + private PalettedBlockStorage[] biomes3d; + private boolean has3dBiomes; + private int[] heightMap; + private int state = STATE_NEW; + private int chunkVersion = LevelDBConstants.LATEST_CHUNK_VERSION; + + private boolean dirty; + + public ChunkBuilder(int x, int z, LevelDBProvider provider) { + this.x = x; + this.z = z; + if (provider == null) throw new NullPointerException(); + this.provider = provider; + } + + public static short blockKey(Vector3 vector) { + return blockKey((int) vector.getX(), (int) vector.getY(), (int) vector.getZ()); + } + + public static short blockKey(int x, int y, int z) { + return (short) ((x & 0xf) | ((z & 0xf) << 4) | ((y & 0xff) << 9)); + } + + public static Vector3 fromKey(long chunkKey, short blockKey) { + int x = (blockKey & 0xf) | (fromKeyX(chunkKey) << 4); + int z = ((blockKey >>> 4) & 0xf) | (fromKeyZ(chunkKey) << 4); + int y = (blockKey >>> 8) & 0xff; + return new Vector3(x, y, z); + } + + public static long key(int x, int z) { + return (((long) x) << 32) | (z & 0xffffffffL); + } + + public static int fromKeyX(long key) { + return (int) (key >> 32); + } + + public static int fromKeyZ(long key) { + return (int) key; + } + + public static int getSectionIndex(int x, int y, int z) { + return (x << 8) + (z << 4) + y; + } + + public int getX() { + return x; + } + + public int getZ() { + return z; + } + + public ChunkBuilder sections(LevelDBChunkSection[] sections) { + if (sections == null) throw new NullPointerException(); + this.sections = sections; + return this; + } + + public ChunkBuilder extraData(int key, short value) { + if (this.extraData == null) { + this.extraData = new Int2IntOpenHashMap(); + } + this.extraData.put(key, value); + return this; + } + + public ChunkBuilder biomes(byte[] biomes) { + if (biomes == null) throw new NullPointerException(); + this.biomes = biomes; + return this; + } + + public ChunkBuilder biomes3d(PalettedBlockStorage[] biomes) { + if (biomes == null) throw new NullPointerException(); + this.biomes3d = biomes; + this.has3dBiomes = true; + return this; + } + + public ChunkBuilder heightMap(int[] heightMap) { + if (heightMap == null) throw new NullPointerException(); + this.heightMap = heightMap; + return this; + } + + public ChunkBuilder dataLoader(ChunkDataLoader chunkDataLoader) { + if (chunkDataLoader == null) throw new NullPointerException(); + this.chunkDataLoaders.add(chunkDataLoader); + return this; + } + + public ChunkBuilder state(int state) { + this.state = state; + return this; + } + + public ChunkBuilder dirty() { + this.dirty = true; + return this; + } + + public ChunkBuilder chunkVersion(int chunkVersion) { + this.chunkVersion = chunkVersion; + return this; + } + + public LevelDBChunk build() { + if (this.sections == null) throw new NullPointerException("sections"); + if (this.biomes == null && this.biomes3d == null) throw new NullPointerException("biomes"); + if (this.heightMap == null) throw new NullPointerException("sections"); + + LevelDBChunk chunk = new LevelDBChunk(this.provider, this.sections, this.extraData, this.biomes, this.heightMap); + chunk.setPosition(this.x, this.z); + chunk.setState(this.state); + if (this.has3dBiomes) { + chunk.setBiomes3d(this.biomes3d); + } + + this.chunkDataLoaders.forEach(loader -> loader.initChunk(chunk, this.provider)); + if (this.dirty) { + chunk.setChanged(); + } + return chunk; + } + + public LevelDBProvider getProvider() { + return this.provider; + } + + public boolean has3dBiomes() { + return this.has3dBiomes; + } + + public int getChunkVersion() { + return this.chunkVersion; + } + + public String debugString() { + return this.provider.getName() + "(x=" + this.x + ", z=" + this.z + ")"; + } +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/structure/LevelDBChunk.java b/src/main/java/cn/nukkit/level/format/leveldb/structure/LevelDBChunk.java new file mode 100644 index 00000000000..4dd3106b10e --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/structure/LevelDBChunk.java @@ -0,0 +1,362 @@ +package cn.nukkit.level.format.leveldb.structure; + +import cn.nukkit.block.Block; +import cn.nukkit.level.DimensionData; +import cn.nukkit.level.biome.Biome; +import cn.nukkit.level.format.ChunkSection; +import cn.nukkit.level.format.LevelProvider; +import cn.nukkit.level.format.generic.BaseChunk; +import cn.nukkit.level.util.BitArrayVersion; +import cn.nukkit.level.util.PalettedBlockStorage; +import cn.nukkit.nbt.tag.CompoundTag; +import it.unimi.dsi.fastutil.ints.Int2IntMap; +import lombok.Getter; +import lombok.Setter; + +import java.util.*; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +public class LevelDBChunk extends BaseChunk { + + @Getter + @Setter + private int state = ChunkBuilder.STATE_NEW; + + private PalettedBlockStorage[] biomes3d; + + private final Lock writeLock = new ReentrantLock(); + + private final DimensionData dimensionData; + + public LevelDBChunk(Class providerClass) { + this(null, new LevelDBChunkSection[0], null, null, null); + this.providerClass = providerClass; + } + + public LevelDBChunk(LevelProvider provider, LevelDBChunkSection[] sections) { + this(provider, sections, null, null, null); + } + + public LevelDBChunk(LevelProvider provider, LevelDBChunkSection[] sections, Int2IntMap extraData, byte[] biomes, int[] heightMap) { + this.provider = provider; + if (provider != null) { + this.providerClass = provider.getClass(); + } + + this.dimensionData = provider == null ? DimensionData.LEGACY_DIMENSION : provider.getLevel().getDimensionData(); + int offset = dimensionData.getSectionOffset(); + int lowestSection = dimensionData.getMinHeight() >> 4; + int highestSection = dimensionData.getMaxHeight() >> 4; + + this.sections = new ChunkSection[dimensionData.getHeight() >> 4]; + for (int y = lowestSection; y <= highestSection; y++) { + int index = y + offset; + if (index < sections.length && sections[index] != null) { + this.sections[index] = sections[index]; + } else { + this.sections[index] = new LevelDBChunkSection(y); + } + } + + if (extraData != null && !extraData.isEmpty()) { + this.extraData = extraData; + } + + if (biomes == null) { + int biomePalettes = this.provider == null ? this.sections.length : dimensionData.getHeight() >> 4; + this.biomes3d = new PalettedBlockStorage[biomePalettes]; + this.biomes = new byte[256]; + } else { + this.biomes = biomes; + } + + this.heightMap = new byte[256]; + if (heightMap == null || heightMap.length != 256) { + Arrays.fill(this.heightMap, (byte) 255); + } else { + for (int i = 0; i < heightMap.length; i++) { + this.heightMap[i] = (byte) heightMap[i]; + } + } + } + + public void setNbtBlockEntities(List blockEntities) { + this.NBTtiles = blockEntities; + } + + public void setNbtEntities(List entities) { + this.NBTentities = entities; + } + + public void setBiomes3d(PalettedBlockStorage[] biomes3d) { + this.biomes3d = biomes3d; + } + + public void setBiomes3d(int y, PalettedBlockStorage biomes3d) { + if (!this.has3dBiomes()) { + this.convertBiomesTo3d(this.biomes); + } + + int index = y + this.getSectionOffset(); + if (index >= this.biomes3d.length) { + index = 0; + } + + this.biomes3d[index] = biomes3d; + } + + @Override + public void setBiomeIdArray(byte[] biomeIdArray) { + super.setBiomeIdArray(biomeIdArray); + if (this.has3dBiomes()) { + this.convertBiomesTo3d(biomeIdArray); + } + } + + @Override + public boolean has3dBiomes() { + return this.biomes3d != null && this.biomes3d.length > 0; + } + + @Override + public PalettedBlockStorage getBiomeStorage(int y) { + if (!this.has3dBiomes()) { + throw new IllegalStateException("Chunk does not have 3D biomes"); + } + + int index = y + this.getSectionOffset(); + if (index >= this.biomes3d.length) { + index = 0; // TODO: log + } + + if (this.biomes3d[index] == null) { + for (int i = index; i >= 0 ; i--) { + if (this.biomes3d[i] != null) { + this.biomes3d[index] = this.biomes3d[i].copy(); + break; + } + } + + if (this.biomes3d[index] == null) { + this.biomes3d[index] = PalettedBlockStorage.createWithDefaultState(BitArrayVersion.V0, 0); + } + } + return this.biomes3d[index]; + } + + private void convertBiomesTo3d(byte[] biomeIdArray) { + PalettedBlockStorage biomesStorage = PalettedBlockStorage.createWithDefaultState(BitArrayVersion.V0, Biome.getBiomeIdOrCorrect(biomeIdArray[0] & 0xFF)); + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + int biomeId = biomeIdArray[(x << 4) | z] & 0xFF; + for (int y = 0; y < 16; y++) { + biomesStorage.setBlock(x, y, z, biomeId); + } + } + } + + int biomePalettes = this.provider == null ? this.sections.length : provider.getLevel().getDimensionData().getHeight() >> 4; + PalettedBlockStorage[] biomes = new PalettedBlockStorage[biomePalettes]; + + for (int i = 0; i < biomePalettes; i++) { + biomes[i] = biomesStorage.copy(); + } + this.biomes3d = biomes; + this.setChanged(); + } + + @Override + public int getSectionOffset() { + return this.dimensionData.getSectionOffset(); + } + + @Override + public boolean isGenerated() { + return this.getState() >= ChunkBuilder.STATE_GENERATED; + } + + @Override + public void setGenerated() { + this.setGenerated(true); + } + + @Override + public void setGenerated(boolean value) { + if (this.isGenerated() == value) { + return; + } + this.setChanged(); + + if (value) { + this.setState(Math.max(this.getState(), ChunkBuilder.STATE_GENERATED)); + } else { + this.setState(ChunkBuilder.STATE_NEW); + } + } + + @Override + public boolean isPopulated() { + return this.state >= ChunkBuilder.STATE_POPULATED; + } + + @Override + public void setPopulated() { + this.setPopulated(true); + } + + @Override + public void setPopulated(boolean value) { + if (this.isPopulated() == value) { + return; + } + this.setChanged(); + + if (value) { + this.setState(Math.max(this.getState(), ChunkBuilder.STATE_POPULATED)); + } else { + this.setState(Math.max(this.getState(), ChunkBuilder.STATE_NEW)); + } + } + + @Override + public int getBlockSkyLight(int x, int y, int z) { + ChunkSection section0 = this.getSection(y >> 4); + if (!(section0 instanceof LevelDBChunkSection)) { + return section0.getBlockSkyLight(x, y & 0x0f, z); + } + + LevelDBChunkSection section = (LevelDBChunkSection) section0; + if (section.skyLight != null) { + return section.getBlockSkyLight(x, y & 0x0f, z); + } else if (!section.hasSkyLight) { + return 0; + } else { + int height = this.getHighestBlockAt(x, z); + if (height < y) { + return 15; + } else if (height == y) { + return Block.isBlockTransparentById(this.getBlockId(x, y, z)) ? 15 : 0; + } else { + return section.getBlockSkyLight(x, y & 0x0f, z); + } + } + } + + @Override + public int getBlockLight(int x, int y, int z) { + ChunkSection section0 = this.getSection(y >> 4); + if (!(section0 instanceof LevelDBChunkSection)) { + return section0.getBlockLight(x, y & 0x0f, z); + } + + LevelDBChunkSection section = (LevelDBChunkSection) section0; + if (section.blockLight != null) { + return section.getBlockLight(x, y & 0x0f, z); + } else if (!section.hasBlockLight) { + return 0; + } else { + return section.getBlockLight(x, y & 0x0f, z); + } + } + + @Override + public boolean compress() { + boolean result = super.compress(); + for (ChunkSection section : this.getSections()) { + if (section instanceof LevelDBChunkSection && !section.isEmpty()) { + result |= ((LevelDBChunkSection) section).compress(); + } + } + return result; + } + + @Override + @Deprecated + public byte[] toFastBinary() { + return new byte[0]; + } + + @Override + @Deprecated + public byte[] toBinary() { + return new byte[0]; + } + + @Override + public LevelDBChunk clone() { + LevelDBChunk chunk = (LevelDBChunk) super.clone(); + if (this.has3dBiomes()) { + PalettedBlockStorage[] biomes = new PalettedBlockStorage[this.biomes3d.length]; + for (int i = 0; i < this.biomes3d.length; i++) { + biomes[i] = this.biomes3d[i].copy(); + } + chunk.setBiomes3d(biomes); + } + return chunk; + } + + @Override + public LevelDBChunk cloneForChunkSending() { + LevelDBChunk chunk = (LevelDBChunk) super.cloneForChunkSending(); + if (this.has3dBiomes()) { + PalettedBlockStorage[] biomes = new PalettedBlockStorage[this.biomes3d.length]; + for (int i = 0; i < this.biomes3d.length; i++) { + PalettedBlockStorage storage = this.biomes3d[i]; + if (storage != null) { + biomes[i] = storage.copy(); + } + } + chunk.setBiomes3d(biomes); + } + return chunk; + } + + @Override + public int getBiomeId(int x, int z) { + return this.getBiomeId(x, 0, z); + } + + @Override + public int getBiomeId(int x, int y, int z) { + if (this.has3dBiomes()) { + return this.getBiomeStorage(y >> 4).getBlock(x, y & 0x0f, z); + } else { + return super.getBiomeId(x, z); + } + } + + @Override + public void setBiomeId(int x, int z, byte biomeId) { + this.setBiomeId(x, z, (int) biomeId); + } + + @Override + public void setBiomeId(int x, int y, int z, byte biomeId) { + this.setBiomeId(x, y, z, ((int) biomeId) & 0xff); + } + + @Override + public void setBiomeId(int x, int z, int biomeId) { + for (int i = 0; i < this.sections.length; i++) { + int y = (i - this.getSectionOffset()) << 4; + for (int yy = 0; yy < 16; yy++) { + this.setBiomeId(x, y + yy, z, biomeId); + } + } + } + + @Override + public void setBiomeId(int x, int y, int z, int biomeId) { + if (!this.has3dBiomes()) { + this.convertBiomesTo3d(this.biomes); + } + + this.getBiomeStorage(y >> 4).setBlock(x, y & 0x0f, z, biomeId); + this.setChanged(); + } + + public Lock writeLock() { + return this.writeLock; + } +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/structure/LevelDBChunkSection.java b/src/main/java/cn/nukkit/level/format/leveldb/structure/LevelDBChunkSection.java new file mode 100644 index 00000000000..cf25efda0ec --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/structure/LevelDBChunkSection.java @@ -0,0 +1,370 @@ +package cn.nukkit.level.format.leveldb.structure; + +import cn.nukkit.Server; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockLayer; +import cn.nukkit.level.format.ChunkSection; +import cn.nukkit.level.format.generic.EmptyChunkSection; +import cn.nukkit.utils.Binary; +import cn.nukkit.utils.BinaryStream; +import cn.nukkit.utils.Utils; +import cn.nukkit.utils.Zlib; +import lombok.Getter; + +import java.io.IOException; +import java.util.Arrays; + +public class LevelDBChunkSection implements ChunkSection { + + @Getter + private final int y; + @Getter + private final StateBlockStorage[] storages; + + protected byte[] blockLight; + protected byte[] skyLight; + private byte[] compressedLight; + protected boolean hasBlockLight; + protected boolean hasSkyLight; + + public LevelDBChunkSection(int y, StateBlockStorage[] storages, byte[] blockLight, byte[] skyLight, byte[] compressedLight, boolean hasBlockLight, boolean hasSkyLight) { + this.y = y; + this.storages = storages; + this.blockLight = blockLight; + this.skyLight = skyLight; + this.compressedLight = compressedLight; + this.hasBlockLight = hasBlockLight; + this.hasSkyLight = hasSkyLight; + } + + public LevelDBChunkSection(int y) { + this(y, new StateBlockStorage[]{new StateBlockStorage(), new StateBlockStorage()}, null, null, null, false, true); + } + + private StateBlockStorage computeStorage(BlockLayer layer) { + if (this.storages.length <= layer.ordinal()) { + throw new IllegalArgumentException("Tried to get layer " + layer + " but LevelDBChunkSection has only " + this.storages.length); + } + + StateBlockStorage storage = this.storages[layer.ordinal()]; + if (storage == null) { + return this.storages[layer.ordinal()] = new StateBlockStorage(); + } + return storage; + } + + @Override + public int getBlockId(int x, int y, int z, BlockLayer layer) { + synchronized (this.storages) { + return this.computeStorage(layer).getBlockId(x, y, z); + } + } + + @Override + public void setBlockId(int x, int y, int z, BlockLayer layer, int id) { + synchronized (this.storages) { + this.computeStorage(layer).setBlockId(x, y, z, id); + if (layer != Block.LAYER_WATERLOGGED && id == 0 && this.hasSecondLayer()) { + this.computeStorage(Block.LAYER_WATERLOGGED).setBlockId(x, y, z, 0); + } + } + } + + @Override + public boolean setFullBlockId(int x, int y, int z, BlockLayer layer, int fullId) { + synchronized (this.storages) { + this.computeStorage(layer).setFullBlock(x, y, z, fullId); + if (layer != Block.LAYER_WATERLOGGED && fullId == 0 && this.hasSecondLayer()) { + this.computeStorage(Block.LAYER_WATERLOGGED).setFullBlock(x, y, z, 0); + } + } + return true; + } + + @Override + public int getBlockData(int x, int y, int z, BlockLayer layer) { + synchronized (this.storages) { + return this.computeStorage(layer).getBlockData(x, y, z); + } + } + + @Override + public void setBlockData(int x, int y, int z, BlockLayer layer, int data) { + synchronized (this.storages) { + this.computeStorage(layer).setBlockData(x, y, z, data); + } + } + + @Override + public int getFullBlock(int x, int y, int z, BlockLayer layer) { + synchronized (this.storages) { + return this.computeStorage(layer).getFullBlock(x, y, z); + } + } + + public Block getAndSetBlock(int x, int y, int z, BlockLayer layer, Block block) { + synchronized (this.storages) { + int fullId = this.computeStorage(layer).getAndSetFullBlock(x, y, z, block.getFullId()); + if (layer != Block.LAYER_WATERLOGGED && block.getId() == 0 && fullId != block.getFullId() && this.hasSecondLayer()) { + this.computeStorage(Block.LAYER_WATERLOGGED).setFullBlock(x, y, z, 0); + } + return Block.get(fullId, null, x, y, z, layer); + } + } + + @Override + public boolean setBlock(int x, int y, int z, int blockId) { + return this.setBlock(x, y, z, blockId, 0); + } + + @Override + public boolean setBlock(int x, int y, int z, int blockId, int meta) { + return this.setBlockAtLayer(x, y, z, Block.LAYER_NORMAL, blockId, meta); + } + + @Override + public boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int blockId) { + return this.setBlockAtLayer(x, y, z, layer, blockId, 0); + } + + @Override + public boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int blockId, int meta) { + synchronized (this.storages) { + int fullId = (blockId << Block.DATA_BITS) | meta; + boolean success = this.computeStorage(layer).getAndSetFullBlock(x, y, z, fullId) != fullId; + if (layer != Block.LAYER_WATERLOGGED && blockId == 0 && this.hasSecondLayer()) { + this.computeStorage(Block.LAYER_WATERLOGGED).setFullBlock(x, y, z, 0); + } + return success; + } + } + + @Override + public int getBlockSkyLight(int x, int y, int z) { + if (this.skyLight == null) { + if (!hasSkyLight) { + return 0; + } else if (compressedLight == null) { + return 15; + } + } + this.skyLight = getSkyLightArray(); + int sl = this.skyLight[(y << 7) | (z << 3) | (x >> 1)] & 0xff; + if ((x & 1) == 0) { + return sl & 0x0f; + } + return sl >> 4; + } + + @Override + public void setBlockSkyLight(int x, int y, int z, int level) { + if (this.skyLight == null) { + if (hasSkyLight && compressedLight != null) { + this.skyLight = getSkyLightArray(); + } else if (level == (hasSkyLight ? 15 : 0)) { + return; + } else { + this.skyLight = new byte[2048]; + if (hasSkyLight) { + Arrays.fill(this.skyLight, (byte) 0xFF); + } + } + } + int i = (y << 7) | (z << 3) | (x >> 1); + int old = this.skyLight[i] & 0xff; + if ((x & 1) == 0) { + this.skyLight[i] = (byte) ((old & 0xf0) | (level & 0x0f)); + } else { + this.skyLight[i] = (byte) (((level & 0x0f) << 4) | (old & 0x0f)); + } + } + + @Override + public int getBlockLight(int x, int y, int z) { + if (blockLight == null && !hasBlockLight) return 0; + this.blockLight = getLightArray(); + int l = blockLight[(y << 7) | (z << 3) | (x >> 1)] & 0xff; + if ((x & 1) == 0) { + return l & 0x0f; + } + return l >> 4; + } + + @Override + public void setBlockLight(int x, int y, int z, int level) { + if (this.blockLight == null) { + if (hasBlockLight) { + this.blockLight = getLightArray(); + } else if (level == 0) { + return; + } else { + this.blockLight = new byte[2048]; + } + } + int i = (y << 7) | (z << 3) | (x >> 1); + int old = this.blockLight[i] & 0xff; + if ((x & 1) == 0) { + this.blockLight[i] = (byte) ((old & 0xf0) | (level & 0x0f)); + } else { + this.blockLight[i] = (byte) (((level & 0x0f) << 4) | (old & 0x0f)); + } + } + + @Override + public byte[] getIdArray() { + // We don't support old byte format + return new byte[0]; + } + + @Override + public byte[] getDataArray() { + // We don't support old byte format + return new byte[0]; + } + + @Override + public void writeTo(BinaryStream stream) { + synchronized (this.storages) { + boolean waterLogging = this.hasSecondLayer(); + stream.putByte((byte) 8); // Paletted chunk because Mojang messed up the old one + stream.putByte((byte) (waterLogging ? 2 : 1)); + this.storages[0].writeTo(stream); + if (waterLogging) { + this.storages[1].writeTo(stream); + } + } + } + + private boolean hasSecondLayer() { + return this.storages.length > 1 && this.storages[1] != null; + } + + @Override + public byte[] getSkyLightArray() { + if (this.skyLight != null) return this.skyLight; + if (this.hasSkyLight) { + if (this.compressedLight != null) { + this.inflate(); + if (this.skyLight != null) return this.skyLight; + } + } + return EmptyChunkSection.EMPTY_SKY_LIGHT_ARR; + } + + private void inflate() { + try { + if (compressedLight != null && compressedLight.length != 0) { + byte[] inflated = Zlib.inflate(compressedLight); + blockLight = Arrays.copyOfRange(inflated, 0, 2048); + if (inflated.length > 2048) { + skyLight = Arrays.copyOfRange(inflated, 2048, 4096); + } else { + skyLight = new byte[2048]; + if (hasSkyLight) { + Arrays.fill(skyLight, (byte) 0xFF); + } + } + compressedLight = null; + } else { + if (blockLight == null) { + blockLight = new byte[2048]; + } + skyLight = new byte[2048]; + if (hasSkyLight) { + Arrays.fill(skyLight, (byte) 0xFF); + } + } + } catch (IOException e) { + Server.getInstance().getLogger().logException(e); + } + } + + @Override + public byte[] getLightArray() { + if (this.blockLight != null) return this.blockLight; + if (this.hasBlockLight) { + this.inflate(); + if (this.blockLight != null) return this.blockLight; + } + return EmptyChunkSection.EMPTY_LIGHT_ARR; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public ChunkSection copy() { + StateBlockStorage[] storages = new StateBlockStorage[this.storages.length]; + for (int i = 0; i < this.storages.length; i++) { + if (this.storages[i] != null) { + storages[i] = this.storages[i].copy(); + } + } + + return new LevelDBChunkSection( + this.y, + storages, + this.blockLight == null ? null : this.blockLight.clone(), + this.skyLight == null ? null : this.skyLight.clone(), + this.compressedLight == null ? null : this.compressedLight.clone(), + this.hasBlockLight, + this.hasSkyLight + ); + } + + @Override + public ChunkSection copyForChunkSending() { + StateBlockStorage[] storages = new StateBlockStorage[this.storages.length]; + for (int i = 0; i < this.storages.length; i++) { + if (this.storages[i] != null) { + storages[i] = this.storages[i].copy(); + } + } + + return new LevelDBChunkSection( + this.y, + storages, + null, + null, + null, + false, + false + ); + } + + public boolean compress() { + if (blockLight != null) { + byte[] arr1 = blockLight; + hasBlockLight = !Utils.isByteArrayEmpty(arr1); + byte[] arr2; + if (skyLight != null) { + arr2 = skyLight; + hasSkyLight = !Utils.isByteArrayEmpty(arr2); + } else if (hasSkyLight) { + arr2 = EmptyChunkSection.EMPTY_SKY_LIGHT_ARR; + } else { + arr2 = EmptyChunkSection.EMPTY_LIGHT_ARR; + hasSkyLight = false; + } + blockLight = null; + skyLight = null; + byte[] toDeflate = null; + if (hasBlockLight && hasSkyLight && arr2 != EmptyChunkSection.EMPTY_SKY_LIGHT_ARR) { + toDeflate = Binary.appendBytes(arr1, arr2); + } else if (hasBlockLight) { + toDeflate = arr1; + } + if (toDeflate != null) { + try { + compressedLight = Zlib.deflate(toDeflate, 1); + } catch (Exception e) { + Server.getInstance().getLogger().logException(e); + } + } + return true; + } + return false; + } +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/structure/StateBlockStorage.java b/src/main/java/cn/nukkit/level/format/leveldb/structure/StateBlockStorage.java new file mode 100644 index 00000000000..d42dfd033af --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/structure/StateBlockStorage.java @@ -0,0 +1,272 @@ +package cn.nukkit.level.format.leveldb.structure; + +import cn.nukkit.Nukkit; +import cn.nukkit.block.Block; +import cn.nukkit.level.format.leveldb.BlockStateMapping; +import cn.nukkit.level.util.BitArray; +import cn.nukkit.level.util.BitArrayVersion; +import cn.nukkit.utils.BinaryStream; +import cn.nukkit.utils.MainLogger; +import org.cloudburstmc.nbt.NBTInputStream; +import org.cloudburstmc.nbt.NBTOutputStream; +import org.cloudburstmc.nbt.NbtMap; +import org.cloudburstmc.nbt.NbtUtils; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufInputStream; +import io.netty.buffer.ByteBufOutputStream; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.IOException; +import java.util.List; + +public class StateBlockStorage { + private static final Logger log = LogManager.getLogger("LevelDB-Logger"); + + private static final int SECTION_SIZE = 4096; + + private final List palette; + private BitArray bitArray; + + public StateBlockStorage() { + this(BitArrayVersion.V2); + } + + public StateBlockStorage(BitArrayVersion version) { + this.bitArray = version.createPalette(); + this.palette = new ObjectArrayList<>(16); + // Air is at the beginning of each palette + this.palette.add(BlockStateMapping.get().getState(0, 0)); + } + + public StateBlockStorage(BitArray bitArray, List palette) { + this.palette = palette; + this.bitArray = bitArray; + } + + private int getPaletteHeader(BitArrayVersion version, boolean runtime) { + return (version.getId() << 1) | (runtime ? 1 : 0); + } + + private static BitArrayVersion getVersionFromHeader(byte header) { + return BitArrayVersion.get(header >> 1, true); + } + + public void writeToStorage(ByteBuf buffer) { + int paletteSize = this.palette.size(); + BitArrayVersion version = paletteSize <= 1 ? BitArrayVersion.V0 : this.bitArray.getVersion(); + buffer.writeByte(getPaletteHeader(version, false)); + + if (version != BitArrayVersion.V0) { + for (int word : this.bitArray.getWords()) { + buffer.writeIntLE(word); + } + buffer.writeIntLE(paletteSize); + } + + try (ByteBufOutputStream stream = new ByteBufOutputStream(buffer); + NBTOutputStream nbtOutputStream = NbtUtils.createWriterLE(stream)) { + for (BlockStateSnapshot state : this.palette) { + nbtOutputStream.writeTag(state.getVanillaState()); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public void readFromStorage(ByteBuf buffer, ChunkBuilder chunkBuilder) { + BitArrayVersion version = getVersionFromHeader(buffer.readByte()); + this.palette.clear(); + int paletteSize = 1; + + if (version == BitArrayVersion.V0) { + this.bitArray = version.createPalette(SECTION_SIZE, null); + } else { + int expectedWordCount = version.getWordsForSize(SECTION_SIZE); + int[] words = new int[expectedWordCount]; + for (int i = 0; i < expectedWordCount; i++) { + words[i] = buffer.readIntLE(); + } + paletteSize = buffer.readIntLE(); + this.bitArray = version.createPalette(SECTION_SIZE, words); + } + + if (version.getMaxEntryValue() < paletteSize - 1) { + throw new IllegalArgumentException( + chunkBuilder.debugString() + " Palette (version " + version.name() + ") is too large. Max size " + version.getMaxEntryValue() + ". Actual size " + paletteSize + ); + } + + try (ByteBufInputStream stream = new ByteBufInputStream(buffer); + NBTInputStream nbtInputStream = NbtUtils.createReaderLE(stream)) { + for (int i = 0; i < paletteSize; i++) { + try { + NbtMap state = (NbtMap) nbtInputStream.readTag(); + //noinspection ResultOfMethodCallIgnored + state.hashCode(); // cache hashCode + + BlockStateSnapshot blockState = BlockStateMapping.get().getStateUnsafe(state); + if (blockState == null) { + NbtMap updatedState = BlockStateMapping.get().updateVanillaState(state); + blockState = BlockStateMapping.get().getUpdatedOrCustom(state, updatedState); + if (!blockState.isCustom()) { + if (Nukkit.DEBUG > 1) log.info("[{}] Updated unmapped block state: {} => {}", chunkBuilder.debugString(), state, blockState.getVanillaState()); + chunkBuilder.dirty(); + } + + if (Nukkit.DEBUG > 1 && blockState.getRuntimeId() == BlockStateMapping.get().getDefaultRuntimeId()) { + log.info("[{}] Chunk contains unknown block {} => {}", chunkBuilder.debugString(), state, updatedState); + } + } + + if (Nukkit.DEBUG > 1 && this.palette.contains(blockState)) { + log.info("[{}] Palette contains block state twice: {}", chunkBuilder.debugString(), state); + } + this.palette.add(blockState); + } catch (Exception e) { + MainLogger.getLogger().error("[" + chunkBuilder.debugString() + "] Unable to deserialize chunk block state", e); + } + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public void setBlockState(int index, NbtMap state) { + BlockStateSnapshot blockState = BlockStateMapping.get().getStateUnsafe(state); + if (blockState == null) { + blockState = BlockStateMapping.get().updateStateUnsafe(state); + } + this.setBlockStateUnsafe(index, blockState); + } + + public void setBlockStateUnsafe(int index, BlockStateSnapshot state) { + try { + int id = this.idFor(state); + this.bitArray.set(index, id); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("Unable to set block state: " + state + ", palette: " + palette, e); + } + } + + public BlockStateSnapshot getBlockState(int x, int y, int z) { + int index = ChunkBuilder.getSectionIndex(x, y, z); + return this.stateFor(this.bitArray.get(index)); + } + + public BlockStateSnapshot getBlockState(int index) { + return this.stateFor(this.bitArray.get(index)); + } + + public int getBlockData(int x, int y, int z) { + return this.getBlockState(x, y, z).getLegacyData(); + } + + public int getBlockId(int x, int y, int z) { + return this.getBlockState(x, y, z).getLegacyId(); + } + + public void setBlockId(int x, int y, int z, int id) { + int index = ChunkBuilder.getSectionIndex(x, y, z); + this.setBlockStateUnsafe(index, BlockStateMapping.get().getState(id, 0)); + } + + public void setBlockData(int x, int y, int z, int data) { + int index = ChunkBuilder.getSectionIndex(x, y, z); + this.setBlockStateUnsafe(index, BlockStateMapping.get().getState(this.getBlockId(x, y, z), data)); + } + + public int getFullBlock(int x, int y, int z) { + return getFullBlock(ChunkBuilder.getSectionIndex(x, y, z)); + } + + public void setFullBlock(int x, int y, int z, int value) { + this.setFullBlock(ChunkBuilder.getSectionIndex(x, y, z), value); + } + + public int getAndSetFullBlock(int x, int y, int z, int value) { + return getAndSetFullBlock(ChunkBuilder.getSectionIndex(x, y, z), value); + } + + private int getAndSetFullBlock(int index, int value) { + BlockStateSnapshot state = this.getBlockState(index); + int newBlock = value >> Block.DATA_BITS; + int newData = value & Block.DATA_MASK; + this.setBlockStateUnsafe(index, BlockStateMapping.get().getState(newBlock, newData)); + return (state.getLegacyId() << Block.DATA_BITS) | state.getLegacyData(); + } + + private int getFullBlock(int index) { + BlockStateSnapshot state = this.getBlockState(index); + return (state.getLegacyId() << Block.DATA_BITS) | state.getLegacyData(); + } + + public void setFullBlock(int index, int value) { + int block = value >> Block.DATA_BITS; + int data = value & Block.DATA_MASK; + this.setBlockStateUnsafe(index, BlockStateMapping.get().getState(block, data)); + } + + public void writeTo(BinaryStream stream) { + BitArray bitArray = this.bitArray; + + stream.putByte((byte) this.getPaletteHeader(bitArray.getVersion(), true)); + if (bitArray.getVersion() != BitArrayVersion.V0) { + for (int word : bitArray.getWords()) { + stream.putLInt(word); + } + stream.putVarInt(this.palette.size()); + } + + for (BlockStateSnapshot state : this.palette) { + stream.putVarInt(state.getRuntimeIdNetworkProtocol()); + } + } + + private void onResize(BitArrayVersion version) { + BitArray newBitArray = version.createPalette(); + for (int i = 0; i < SECTION_SIZE; i++) { + newBitArray.set(i, this.bitArray.get(i)); + } + this.bitArray = newBitArray; + } + + private int idFor(BlockStateSnapshot state) { + int index = this.palette.indexOf(state); + if (index != -1) { + return index; + } + + index = this.palette.size(); + BitArrayVersion version = this.bitArray.getVersion(); + if (index > version.getMaxEntryValue()) { + BitArrayVersion next = version.next(); + if (next != null) { + this.onResize(next); + } + } + this.palette.add(state); + return index; + } + + private BlockStateSnapshot stateFor(int index) { + return this.palette.get(index); + } + + public boolean isEmpty() { + if (this.palette.size() == 1) { + return true; + } + for (int word : this.bitArray.getWords()) { + if (Integer.toUnsignedLong(word) != 0L) { + return false; + } + } + return true; + } + + public StateBlockStorage copy() { + return new StateBlockStorage(this.bitArray.copy(), new ObjectArrayList<>(this.palette)); + } +} diff --git a/src/main/java/cn/nukkit/level/format/leveldb/updater/BlockStateUpdaterChunker.java b/src/main/java/cn/nukkit/level/format/leveldb/updater/BlockStateUpdaterChunker.java new file mode 100644 index 00000000000..26a331f69ff --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/updater/BlockStateUpdaterChunker.java @@ -0,0 +1,86 @@ +package cn.nukkit.level.format.leveldb.updater; + +import org.cloudburstmc.blockstateupdater.BlockStateUpdater; +import org.cloudburstmc.blockstateupdater.util.tagupdater.CompoundTagUpdaterContext; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +import static cn.nukkit.level.format.leveldb.LevelDBConstants.*; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class BlockStateUpdaterChunker implements BlockStateUpdater { + + // This is updater for worlds converted using chunker.app + public static final BlockStateUpdater INSTANCE = new BlockStateUpdaterChunker(); + + @Override + public void registerUpdaters(CompoundTagUpdaterContext ctx) { + this.addProperty(ctx, "minecraft:anvil", "damage", "undamaged"); + this.addProperty(ctx, "minecraft:azalea_leaves", "update_bit", (byte) 0); + this.addProperty(ctx, "minecraft:azalea_leaves_flowered", "update_bit", (byte) 0); + this.addProperty(ctx, "minecraft:bamboo_sapling", "age_bit", (byte) 0); + this.addProperty(ctx, "minecraft:bedrock", "infiniburn_bit", (byte) 0); + this.addProperty(ctx, "minecraft:big_dripleaf", "big_dripleaf_tilt", "none"); + this.addProperty(ctx, "minecraft:blackstone_double_slab", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:cauldron", "cauldron_liquid", "water"); + this.addProperty(ctx, "minecraft:cobbled_deepslate_double_slab", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:coral", "dead_bit", (byte) 0); + this.addProperty(ctx, "minecraft:coral_block", "dead_bit", (byte) 0); + this.addProperty(ctx, "minecraft:coral_fan", "coral_fan_direction", (int) 0); + this.addProperty(ctx, "minecraft:coral_fan_dead", "coral_fan_direction", (int) 0); + this.addProperty(ctx, "minecraft:coral_fan_hang", "dead_bit", (byte) 0); + this.addProperty(ctx, "minecraft:coral_fan_hang2", "dead_bit", (byte) 0); + this.addProperty(ctx, "minecraft:coral_fan_hang3", "dead_bit", (byte) 0); + this.addProperty(ctx, "minecraft:crimson_double_slab", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:double_wooden_slab", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:deepslate_brick_double_slab", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:deepslate_tile_double_slab", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:dirt", "dirt_type", "normal"); + this.addProperty(ctx, "minecraft:double_cut_copper_slab", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:double_wooden_slab", "wood_type", "oak"); + this.addProperty(ctx, "minecraft:double_stone_block_slab", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:double_stone_block_slab2", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:double_stone_block_slab3", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:double_stone_block_slab4", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:exposed_double_cut_copper_slab", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:flower_pot", "update_bit", (byte) 0); + this.addProperty(ctx, "minecraft:frame", "item_frame_photo_bit", (byte) 0); + this.addProperty(ctx, "minecraft:frame", "item_frame_map_bit", (byte) 0); + this.addProperty(ctx, "minecraft:kelp", "kelp_age", (int) 0); + this.addProperty(ctx, "minecraft:lava_cauldron", "cauldron_liquid", "lava"); + this.addProperty(ctx, "minecraft:leaves", "update_bit", (byte) 0); + this.addProperty(ctx, "minecraft:leaves2", "update_bit", (byte) 0); + this.addProperty(ctx, "minecraft:oxidized_double_cut_copper_slab", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:polished_blackstone_brick_double_slab", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:polished_blackstone_double_slab", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:polished_deepslate_double_slab", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:prismarine", "prismarine_block_type", "default"); + this.addProperty(ctx, "minecraft:purpur_block", "chisel_type", "default"); + this.addProperty(ctx, "minecraft:red_sandstone", "sand_stone_type", "default"); + this.addProperty(ctx, "minecraft:sand", "sand_type", "normal"); + this.addProperty(ctx, "minecraft:sandstone", "sand_stone_type", "default"); + this.addProperty(ctx, "minecraft:sea_pickle", "dead_bit", (byte) 0); + this.addProperty(ctx, "minecraft:soul_fire", "age", (int) 0); + this.addProperty(ctx, "minecraft:sponge", "sponge_type", "dry"); + this.addProperty(ctx, "minecraft:structure_void", "structure_void_type", "void"); + this.addProperty(ctx, "minecraft:tnt", "allow_underwater_bit", (byte) 0); + this.addProperty(ctx, "minecraft:trip_wire", "suspended_bit", (byte) 0); + this.addProperty(ctx, "minecraft:warped_double_slab", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:water", "liquid_depth", (int) 0); + this.addProperty(ctx, "minecraft:waxed_double_cut_copper_slab", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:waxed_exposed_double_cut_copper_slab", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:waxed_oxidized_double_cut_copper_slab", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:waxed_weathered_double_cut_copper_slab", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:weathered_double_cut_copper_slab", "top_slot_bit", (byte) 0); + this.addProperty(ctx, "minecraft:wooden_slab", "wood_type", "oak"); + this.addProperty(ctx, "minecraft:quartz_block", "chisel_type", "default"); + this.addProperty(ctx, "minecraft:quartz_block", "pillar_axis", "y"); + } + + private void addProperty(CompoundTagUpdaterContext ctx, String identifier, String propertyName, Object value) { + ctx.addUpdater(STATE_MAYOR_VERSION, STATE_MINOR_VERSION, STATE_PATCH_VERSION, true) + .match("name", identifier) + .visit("states") + .tryAdd(propertyName, value); + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/format/leveldb/updater/BlockStateUpdaterVanilla.java b/src/main/java/cn/nukkit/level/format/leveldb/updater/BlockStateUpdaterVanilla.java new file mode 100644 index 00000000000..6b2d2512b2b --- /dev/null +++ b/src/main/java/cn/nukkit/level/format/leveldb/updater/BlockStateUpdaterVanilla.java @@ -0,0 +1,55 @@ +package cn.nukkit.level.format.leveldb.updater; + +import org.cloudburstmc.blockstateupdater.BlockStateUpdater; +import org.cloudburstmc.blockstateupdater.util.tagupdater.CompoundTagUpdaterContext; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +import static cn.nukkit.level.format.leveldb.LevelDBConstants.*; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class BlockStateUpdaterVanilla implements BlockStateUpdater { + + public static final BlockStateUpdater INSTANCE = new BlockStateUpdaterVanilla(); + + @Override + public void registerUpdaters(CompoundTagUpdaterContext ctx) { + ctx.addUpdater(STATE_MAYOR_VERSION, STATE_MINOR_VERSION, STATE_PATCH_VERSION, true) + .match("name", "minecraft:water") + .visit("states") + .tryAdd("liquid_depth", (int) 0); + + ctx.addUpdater(STATE_MAYOR_VERSION, STATE_MINOR_VERSION, STATE_PATCH_VERSION, true) + .match("name", "minecraft:polished_blackstone_double_slab") + .visit("states") + .tryAdd("top_slot_bit", (byte) 0); + + this.replaceState(ctx, "minecraft:wood", "pillar_axis", "y"); + this.removeConnections(ctx, "minecraft:cobblestone_wall"); + } + + private void replaceState(CompoundTagUpdaterContext ctx, String identifier, String propertyName, Object value) { + ctx.addUpdater(STATE_MAYOR_VERSION, STATE_MINOR_VERSION, STATE_PATCH_VERSION, true) + .match("name", identifier) + .visit("states") + .edit(propertyName, helper -> helper.replaceWith(propertyName, value)); + } + + private void removeConnections(CompoundTagUpdaterContext ctx, String identifier) { + ctx.addUpdater(STATE_MAYOR_VERSION, STATE_MINOR_VERSION, STATE_PATCH_VERSION, true) + .match("name", identifier) + .visit("states") + .edit("wall_connection_type_east", helper -> helper.replaceWith("wall_connection_type_east", "none")) + .edit("wall_connection_type_north", helper -> helper.replaceWith("wall_connection_type_north", "none")) + .edit("wall_connection_type_south", helper -> helper.replaceWith("wall_connection_type_south", "none")) + .edit("wall_connection_type_west", helper -> helper.replaceWith("wall_connection_type_west", "none")) + .edit("wall_post_bit", helper -> helper.replaceWith("wall_post_bit", (byte) 0)); + } + + private void addProperty(CompoundTagUpdaterContext ctx, String identifier, String propertyName, Object value) { + ctx.addUpdater(STATE_MAYOR_VERSION, STATE_MINOR_VERSION, STATE_PATCH_VERSION, true) + .match("name", identifier) + .visit("states") + .tryAdd(propertyName, value); + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/format/mcregion/Chunk.java b/src/main/java/cn/nukkit/level/format/mcregion/Chunk.java deleted file mode 100644 index b738ee83b12..00000000000 --- a/src/main/java/cn/nukkit/level/format/mcregion/Chunk.java +++ /dev/null @@ -1,538 +0,0 @@ -package cn.nukkit.level.format.mcregion; - -import cn.nukkit.Player; -import cn.nukkit.block.Block; -import cn.nukkit.blockentity.BlockEntity; -import cn.nukkit.entity.Entity; -import cn.nukkit.level.format.LevelProvider; -import cn.nukkit.level.format.anvil.palette.BiomePalette; -import cn.nukkit.level.format.generic.BaseFullChunk; -import cn.nukkit.nbt.NBTIO; -import cn.nukkit.nbt.tag.ByteArrayTag; -import cn.nukkit.nbt.tag.CompoundTag; -import cn.nukkit.nbt.tag.IntArrayTag; -import cn.nukkit.nbt.tag.ListTag; -import cn.nukkit.utils.Binary; -import cn.nukkit.utils.BinaryStream; -import cn.nukkit.utils.Zlib; - -import java.io.ByteArrayInputStream; -import java.nio.ByteOrder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -/** - * author: MagicDroidX - * Nukkit Project - */ -public class Chunk extends BaseFullChunk { - - private CompoundTag nbt; - - public Chunk(LevelProvider level) { - this(level, null); - } - - public Chunk(Class providerClass) { - this((LevelProvider) null, null); - this.providerClass = providerClass; - } - - public Chunk(Class providerClass, CompoundTag nbt) { - this((LevelProvider) null, nbt); - this.providerClass = providerClass; - } - - public Chunk(LevelProvider level, CompoundTag nbt) { - this.provider = level; - if (level != null) { - this.providerClass = level.getClass(); - } - - if (nbt == null) { - return; - } - - this.nbt = nbt; - - if (!(this.nbt.contains("Entities") && (this.nbt.get("Entities") instanceof ListTag))) { - this.nbt.putList(new ListTag("Entities")); - } - - if (!(this.nbt.contains("TileEntities") && (this.nbt.get("TileEntities") instanceof ListTag))) { - this.nbt.putList(new ListTag("TileEntities")); - } - - if (!(this.nbt.contains("TileTicks") && (this.nbt.get("TileTicks") instanceof ListTag))) { - this.nbt.putList(new ListTag("TileTicks")); - } - - if (!(this.nbt.contains("Biomes") && (this.nbt.get("Biomes") instanceof ByteArrayTag))) { - this.nbt.putByteArray("Biomes", new byte[256]); - } - - if (!(this.nbt.contains("HeightMap") && (this.nbt.get("HeightMap") instanceof IntArrayTag))) { - this.nbt.putIntArray("HeightMap", new int[256]); - } - - if (!(this.nbt.contains("Blocks"))) { - this.nbt.putByteArray("Blocks", new byte[32768]); - } - - if (!(this.nbt.contains("Data"))) { - this.nbt.putByteArray("Data", new byte[16384]); - this.nbt.putByteArray("SkyLight", new byte[16384]); - this.nbt.putByteArray("BlockLight", new byte[16384]); - } - - Map extraData = new HashMap<>(); - - if (!this.nbt.contains("ExtraData") || !(this.nbt.get("ExtraData") instanceof ByteArrayTag)) { - this.nbt.putByteArray("ExtraData", Binary.writeInt(0)); - } else { - BinaryStream stream = new BinaryStream(this.nbt.getByteArray("ExtraData")); - for (int i = 0; i < stream.getInt(); i++) { - int key = stream.getInt(); - extraData.put(key, stream.getShort()); - } - } - - this.setPosition(this.nbt.getInt("xPos"), this.nbt.getInt("zPos")); - this.blocks = this.nbt.getByteArray("Blocks"); - this.data = this.nbt.getByteArray("Data"); - this.skyLight = this.nbt.getByteArray("SkyLight"); - this.blockLight = this.nbt.getByteArray("BlockLight"); - - if (this.nbt.contains("BiomeColors")) { - this.biomes = new byte[16 * 16]; - int[] biomeColors = this.nbt.getIntArray("BiomeColors"); - if (biomeColors.length == 256) { - BiomePalette palette = new BiomePalette(biomeColors); - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - this.biomes[(x << 4) | z] = (byte) (palette.get(x, z) >> 24); - } - } - } - } else { - this.biomes = this.nbt.getByteArray("Biomes"); - } - - int[] heightMap = this.nbt.getIntArray("HeightMap"); - this.heightMap = new byte[256]; - if (heightMap.length != 256) { - Arrays.fill(this.heightMap, (byte) 255); - } else { - for (int i = 0; i < heightMap.length; i++) { - this.heightMap[i] = (byte) heightMap[i]; - } - } - - if (!extraData.isEmpty()) this.extraData = extraData; - - this.NBTentities = ((ListTag) this.nbt.getList("Entities")).getAll(); - this.NBTtiles = ((ListTag) this.nbt.getList("TileEntities")).getAll(); - - this.nbt.remove("Blocks"); - this.nbt.remove("Data"); - this.nbt.remove("SkyLight"); - this.nbt.remove("BlockLight"); - this.nbt.remove("BiomeColors"); - this.nbt.remove("HeightMap"); - this.nbt.remove("Biomes"); - } - - @Override - public int getBlockId(int x, int y, int z) { - return this.blocks[(x << 11) | (z << 7) | y] & 0xff; - } - - @Override - public void setBlockId(int x, int y, int z, int id) { - this.blocks[(x << 11) | (z << 7) | y] = (byte) id; - setChanged(); - } - - @Override - public int getBlockData(int x, int y, int z) { - int b = this.data[(x << 10) | (z << 6) | (y >> 1)] & 0xff; - if ((y & 1) == 0) { - return b & 0x0f; - } else { - return b >> 4; - } - } - - @Override - public void setBlockData(int x, int y, int z, int data) { - int i = (x << 10) | (z << 6) | (y >> 1); - int old = this.data[i] & 0xff; - if ((y & 1) == 0) { - this.data[i] = (byte) ((old & 0xf0) | (data & 0x0f)); - } else { - this.data[i] = (byte) (((data & 0x0f) << 4) | (old & 0x0f)); - } - setChanged(); - } - - @Override - public int getFullBlock(int x, int y, int z) { - int i = (x << 11) | (z << 7) | y; - int block = this.blocks[i] & 0xff; - int data = this.data[i >> 1] & 0xff; - if ((y & 1) == 0) { - return (block << 4) | (data & 0x0f); - } else { - return (block << 4) | (data >> 4); - } - } - - @Override - public boolean setBlock(int x, int y, int z, int blockId) { - return setBlock(x, y, z, blockId, 0); - } - - @Override - public boolean setBlock(int x, int y, int z, int blockId, int meta) { - int i = (x << 11) | (z << 7) | y; - boolean changed = false; - byte id = (byte) blockId; - if (this.blocks[i] != id) { - this.blocks[i] = id; - changed = true; - } - - if (Block.hasMeta[blockId]) { - i >>= 1; - int old = this.data[i] & 0xff; - if ((y & 1) == 0) { - this.data[i] = (byte) ((old & 0xf0) | (meta & 0x0f)); - if ((old & 0x0f) != meta) { - changed = true; - } - } else { - this.data[i] = (byte) (((meta & 0x0f) << 4) | (old & 0x0f)); - if (meta != (old >> 4)) { - changed = true; - } - } - } - - if (changed) { - setChanged(); - } - return changed; - } - - @Override - public Block getAndSetBlock(int x, int y, int z, Block block) { - int i = (x << 11) | (z << 7) | y; - boolean changed = false; - byte id = (byte) block.getId(); - - byte previousId = this.blocks[i]; - - if (previousId != id) { - this.blocks[i] = id; - changed = true; - } - - int previousData; - i >>= 1; - int old = this.data[i] & 0xff; - if ((y & 1) == 0) { - previousData = old & 0x0f; - if (Block.hasMeta[block.getId()]) { - this.data[i] = (byte) ((old & 0xf0) | (block.getDamage() & 0x0f)); - if (block.getDamage() != previousData) { - changed = true; - } - } - } else { - previousData = old >> 4; - if (Block.hasMeta[block.getId()]) { - this.data[i] = (byte) (((block.getDamage() & 0x0f) << 4) | (old & 0x0f)); - if (block.getDamage() != previousData) { - changed = true; - } - } - } - - if (changed) { - setChanged(); - } - return Block.get(previousId, previousData); - } - - @Override - public int getBlockSkyLight(int x, int y, int z) { - int sl = this.skyLight[(x << 10) | (z << 6) | (y >> 1)] & 0xff; - if ((y & 1) == 0) { - return sl & 0x0f; - } else { - return sl >> 4; - } - } - - @Override - public void setBlockSkyLight(int x, int y, int z, int level) { - int i = (x << 10) | (z << 6) | (y >> 1); - int old = this.skyLight[i] & 0xff; - if ((y & 1) == 0) { - this.skyLight[i] = (byte) ((old & 0xf0) | (level & 0x0f)); - } else { - this.skyLight[i] = (byte) (((level & 0x0f) << 4) | (old & 0x0f)); - } - setChanged(); - } - - @Override - public int getBlockLight(int x, int y, int z) { - int b = this.blockLight[(x << 10) | (z << 6) | (y >> 1)] & 0xff; - if ((y & 1) == 0) { - return b & 0x0f; - } else { - return b >> 4; - } - } - - @Override - public void setBlockLight(int x, int y, int z, int level) { - int i = (x << 10) | (z << 6) | (y >> 1); - int old = this.blockLight[i] & 0xff; - if ((y & 1) == 0) { - this.blockLight[i] = (byte) ((old & 0xf0) | (level & 0x0f)); - } else { - this.blockLight[i] = (byte) (((level & 0x0f) << 4) | (old & 0x0f)); - } - setChanged(); - } - - @Override - public boolean isLightPopulated() { - return this.nbt.getBoolean("LightPopulated"); - } - - @Override - public void setLightPopulated() { - this.setLightPopulated(true); - } - - @Override - public void setLightPopulated(boolean value) { - this.nbt.putBoolean("LightPopulated", value); - setChanged(); - } - - @Override - public boolean isPopulated() { - return this.nbt.contains("TerrainPopulated") && this.nbt.getBoolean("TerrainPopulated"); - } - - @Override - public void setPopulated() { - this.setPopulated(true); - } - - @Override - public void setPopulated(boolean value) { - this.nbt.putBoolean("TerrainPopulated", value); - setChanged(); - } - - @Override - public boolean isGenerated() { - if (this.nbt.contains("TerrainGenerated")) { - return this.nbt.getBoolean("TerrainGenerated"); - } else if (this.nbt.contains("TerrainPopulated")) { - return this.nbt.getBoolean("TerrainPopulated"); - } - return false; - } - - @Override - public void setGenerated() { - this.setGenerated(true); - } - - @Override - public void setGenerated(boolean value) { - this.nbt.putBoolean("TerrainGenerated", value); - setChanged(); - } - - public static Chunk fromBinary(byte[] data) { - return fromBinary(data, null); - } - - public static Chunk fromBinary(byte[] data, LevelProvider provider) { - try { - CompoundTag chunk = NBTIO.read(new ByteArrayInputStream(Zlib.inflate(data)), ByteOrder.BIG_ENDIAN); - - if (!chunk.contains("Level") || !(chunk.get("Level") instanceof CompoundTag)) { - return null; - } - return new Chunk(provider != null ? provider : McRegion.class.newInstance(), chunk.getCompound("Level")); - } catch (Exception e) { - return null; - } - } - - public static Chunk fromFastBinary(byte[] data) { - return fromFastBinary(data, null); - } - - public static Chunk fromFastBinary(byte[] data, LevelProvider provider) { - try { - int offset = 0; - Chunk chunk = new Chunk(provider != null ? provider : McRegion.class.newInstance(), null); - chunk.provider = provider; - int chunkX = (Binary.readInt(Arrays.copyOfRange(data, offset, offset + 3))); - offset += 4; - int chunkZ = (Binary.readInt(Arrays.copyOfRange(data, offset, offset + 3))); - chunk.setPosition(chunkX, chunkZ); - offset += 4; - chunk.blocks = Arrays.copyOfRange(data, offset, offset + 32767); - offset += 32768; - chunk.data = Arrays.copyOfRange(data, offset, offset + 16383); - offset += 16384; - chunk.skyLight = Arrays.copyOfRange(data, offset, offset + 16383); - offset += 16384; - chunk.blockLight = Arrays.copyOfRange(data, offset, offset + 16383); - offset += 16384; - chunk.heightMap = Arrays.copyOfRange(data, offset, offset + 256); - offset += 256; - chunk.biomes = Arrays.copyOfRange(data, offset, offset + 256); - offset += 256; - byte flags = data[offset++]; - chunk.nbt.putByte("TerrainGenerated", (flags & 0b1)); - chunk.nbt.putByte("TerrainPopulated", ((flags >> 1) & 0b1)); - chunk.nbt.putByte("LightPopulated", ((flags >> 2) & 0b1)); - return chunk; - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - - @Override - public byte[] toFastBinary() { - BinaryStream stream = new BinaryStream(new byte[65536]); - stream.put(Binary.writeInt(this.getX())); - stream.put(Binary.writeInt(this.getZ())); - stream.put(this.getBlockIdArray()); - stream.put(this.getBlockDataArray()); - stream.put(this.getBlockSkyLightArray()); - stream.put(this.getBlockLightArray()); - stream.put(this.getHeightMapArray()); - stream.put(this.getBiomeIdArray()); - stream.putByte((byte) ((this.isLightPopulated() ? 1 << 2 : 0) + (this.isPopulated() ? 1 << 2 : 0) + (this.isGenerated() ? 1 : 0))); - return stream.getBuffer(); - } - - @Override - public byte[] toBinary() { - CompoundTag nbt = this.getNBT().copy(); - nbt.remove("BiomeColors"); - - nbt.putInt("xPos", this.getX()); - nbt.putInt("zPos", this.getZ()); - - if (this.isGenerated()) { - nbt.putByteArray("Blocks", this.getBlockIdArray()); - nbt.putByteArray("Data", this.getBlockDataArray()); - nbt.putByteArray("SkyLight", this.getBlockSkyLightArray()); - nbt.putByteArray("BlockLight", this.getBlockLightArray()); - nbt.putByteArray("Biomes", this.getBiomeIdArray()); - - int[] heightInts = new int[256]; - byte[] heightBytes = this.getHeightMapArray(); - for (int i = 0; i < heightInts.length; i++) { - heightInts[i] = heightBytes[i] & 0xFF; - } - nbt.putIntArray("HeightMap", heightInts); - } - - - ArrayList entities = new ArrayList<>(); - for (Entity entity : this.getEntities().values()) { - if (!(entity instanceof Player) && !entity.closed) { - entity.saveNBT(); - entities.add(entity.namedTag); - } - } - ListTag entityListTag = new ListTag<>("Entities"); - entityListTag.setAll(entities); - nbt.putList(entityListTag); - - ArrayList tiles = new ArrayList<>(); - for (BlockEntity blockEntity : this.getBlockEntities().values()) { - blockEntity.saveNBT(); - tiles.add(blockEntity.namedTag); - } - ListTag tileListTag = new ListTag<>("TileEntities"); - tileListTag.setAll(tiles); - nbt.putList(tileListTag); - - BinaryStream extraData = new BinaryStream(); - Map extraDataArray = this.getBlockExtraDataArray(); - extraData.putInt(extraDataArray.size()); - for (Integer key : extraDataArray.keySet()) { - extraData.putInt(key); - extraData.putShort(extraDataArray.get(key)); - } - - nbt.putByteArray("ExtraData", extraData.getBuffer()); - - CompoundTag chunk = new CompoundTag(""); - chunk.putCompound("Level", nbt); - - try { - return Zlib.deflate(NBTIO.write(chunk, ByteOrder.BIG_ENDIAN), RegionLoader.COMPRESSION_LEVEL); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - public CompoundTag getNBT() { - return nbt; - } - - public static Chunk getEmptyChunk(int chunkX, int chunkZ) { - return getEmptyChunk(chunkX, chunkZ, null); - } - - public static Chunk getEmptyChunk(int chunkX, int chunkZ, LevelProvider provider) { - try { - Chunk chunk; - if (provider != null) { - chunk = new Chunk(provider, null); - } else { - chunk = new Chunk(McRegion.class, null); - } - - chunk.setPosition(chunkX, chunkZ); - chunk.data = new byte[16384]; - chunk.blocks = new byte[32768]; - byte[] skyLight = new byte[16384]; - Arrays.fill(skyLight, (byte) 0xff); - chunk.skyLight = skyLight; - chunk.blockLight = chunk.data; - - chunk.heightMap = new byte[256]; - chunk.biomes = new byte[16 * 16]; - - chunk.nbt.putByte("V", 1); - chunk.nbt.putLong("InhabitedTime", 0); - chunk.nbt.putBoolean("TerrainGenerated", false); - chunk.nbt.putBoolean("TerrainPopulated", false); - chunk.nbt.putBoolean("LightPopulated", false); - - return chunk; - } catch (Exception e) { - throw new RuntimeException(e); - } - } -} diff --git a/src/main/java/cn/nukkit/level/format/mcregion/McRegion.java b/src/main/java/cn/nukkit/level/format/mcregion/McRegion.java deleted file mode 100644 index ae9f0ad5366..00000000000 --- a/src/main/java/cn/nukkit/level/format/mcregion/McRegion.java +++ /dev/null @@ -1,220 +0,0 @@ -package cn.nukkit.level.format.mcregion; - -import cn.nukkit.blockentity.BlockEntity; -import cn.nukkit.blockentity.BlockEntitySpawnable; -import cn.nukkit.level.Level; -import cn.nukkit.level.format.ChunkSection; -import cn.nukkit.level.format.FullChunk; -import cn.nukkit.level.format.generic.BaseFullChunk; -import cn.nukkit.level.format.generic.BaseLevelProvider; -import cn.nukkit.level.format.generic.BaseRegionLoader; -import cn.nukkit.level.generator.Generator; -import cn.nukkit.nbt.NBTIO; -import cn.nukkit.nbt.tag.CompoundTag; -import cn.nukkit.scheduler.AsyncTask; -import cn.nukkit.utils.BinaryStream; -import cn.nukkit.utils.ChunkException; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.ByteOrder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; - -/** - * author: MagicDroidX - * Nukkit Project - */ -public class McRegion extends BaseLevelProvider { - - public McRegion(Level level, String path) throws IOException { - super(level, path); - } - - public static String getProviderName() { - return "mcregion"; - } - - public static byte getProviderOrder() { - return ORDER_ZXY; - } - - public static boolean usesChunkSection() { - return false; - } - - public static boolean isValid(String path) { - boolean isValid = (new File(path + "/level.dat").exists()) && new File(path + "/region/").isDirectory(); - if (isValid) { - for (File file : new File(path + "/region/").listFiles((dir, name) -> Pattern.matches("^.+\\.mc[r|a]$", name))) { - if (!file.getName().endsWith(".mcr")) { - isValid = false; - break; - } - } - } - return isValid; - } - - public static void generate(String path, String name, long seed, Class generator) throws IOException { - generate(path, name, seed, generator, new HashMap<>()); - } - - public static void generate(String path, String name, long seed, Class generator, Map options) throws IOException { - if (!new File(path + "/region").exists()) { - new File(path + "/region").mkdirs(); - } - - CompoundTag levelData = new CompoundTag("Data") - .putCompound("GameRules", new CompoundTag()) - - .putLong("DayTime", 0) - .putInt("GameType", 0) - .putString("generatorName", Generator.getGeneratorName(generator)) - .putString("generatorOptions", options.getOrDefault("preset", "")) - .putInt("generatorVersion", 1) - .putBoolean("hardcore", false) - .putBoolean("initialized", true) - .putLong("LastPlayed", System.currentTimeMillis() / 1000) - .putString("LevelName", name) - .putBoolean("raining", false) - .putInt("rainTime", 0) - .putLong("RandomSeed", seed) - .putInt("SpawnX", 128) - .putInt("SpawnY", 70) - .putInt("SpawnZ", 128) - .putBoolean("thundering", false) - .putInt("thunderTime", 0) - .putInt("version", 19133) - .putLong("Time", 0) - .putLong("SizeOnDisk", 0); - - NBTIO.writeGZIPCompressed(new CompoundTag().putCompound("Data", levelData), new FileOutputStream(path + "level.dat"), ByteOrder.BIG_ENDIAN); - } - - @Override - public AsyncTask requestChunkTask(int x, int z) throws ChunkException { - BaseFullChunk chunk = this.getChunk(x, z, false); - if (chunk == null) { - throw new ChunkException("Invalid Chunk Sent"); - } - - long timestamp = chunk.getChanges(); - - BinaryStream stream = new BinaryStream(); - stream.putByte((byte) 0); // subchunk version - - stream.put(chunk.getBlockIdArray()); - stream.put(chunk.getBlockDataArray()); - stream.put(chunk.getBlockSkyLightArray()); - stream.put(chunk.getBlockLightArray()); - stream.put(chunk.getHeightMapArray()); - stream.put(chunk.getBiomeIdArray()); - - Map extra = chunk.getBlockExtraDataArray(); - stream.putLInt(extra.size()); - if (!extra.isEmpty()) { - for (Integer key : extra.values()) { - stream.putLInt(key); - stream.putLShort(extra.get(key)); - } - } - - if (!chunk.getBlockEntities().isEmpty()) { - List tagList = new ArrayList<>(); - - for (BlockEntity blockEntity : chunk.getBlockEntities().values()) { - if (blockEntity instanceof BlockEntitySpawnable) { - tagList.add(((BlockEntitySpawnable) blockEntity).getSpawnCompound()); - } - } - - try { - stream.put(NBTIO.write(tagList, ByteOrder.LITTLE_ENDIAN)); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - return null; - } - - @Override - public BaseFullChunk loadChunk(long index, int chunkX, int chunkZ, boolean create) { - int regionX = getRegionIndexX(chunkX); - int regionZ = getRegionIndexZ(chunkZ); - BaseRegionLoader region = this.loadRegion(regionX, regionZ); - this.level.timings.syncChunkLoadDataTimer.startTiming(); - BaseFullChunk chunk; - try { - chunk = region.readChunk(chunkX - regionX * 32, chunkZ - regionZ * 32); - } catch (IOException e) { - throw new RuntimeException(e); - } - if (chunk == null) { - if (create) { - chunk = this.getEmptyChunk(chunkX, chunkZ); - putChunk(index, chunk); - } - } else { - putChunk(index, chunk); - } - this.level.timings.syncChunkLoadDataTimer.stopTiming(); - return chunk; - } - - @Override - public Chunk getEmptyChunk(int chunkX, int chunkZ) { - return Chunk.getEmptyChunk(chunkX, chunkZ, this); - } - - @Override - public void saveChunk(int x, int z) { - if (this.isChunkLoaded(x, z)) { - try { - this.getRegion(x >> 5, z >> 5).writeChunk(this.getChunk(x, z)); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } - - @Override - public void saveChunk(int x, int z, FullChunk chunk) { - if (!(chunk instanceof Chunk)) { - throw new ChunkException("Invalid Chunk class"); - } - this.loadRegion(x >> 5, z >> 5); - chunk.setPosition(x, z); - try { - this.getRegion(x >> 5, z >> 5).writeChunk(chunk); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - public static ChunkSection createChunkSection(int y) { - return null; - } - - protected BaseRegionLoader loadRegion(int x, int z) { - BaseRegionLoader tmp = lastRegion.get(); - if (tmp != null && x == tmp.getX() && z == tmp.getZ()) { - return tmp; - } - long index = Level.chunkHash(x, z); - synchronized (regions) { - BaseRegionLoader region = this.regions.get(index); - if (region == null) { - region = new RegionLoader(this, x, z); - this.regions.put(index, region); - } - lastRegion.set(region); - return region; - } - } -} diff --git a/src/main/java/cn/nukkit/level/format/mcregion/RegionLoader.java b/src/main/java/cn/nukkit/level/format/mcregion/RegionLoader.java deleted file mode 100644 index 4963f942c72..00000000000 --- a/src/main/java/cn/nukkit/level/format/mcregion/RegionLoader.java +++ /dev/null @@ -1,322 +0,0 @@ -package cn.nukkit.level.format.mcregion; - -import cn.nukkit.level.format.FullChunk; -import cn.nukkit.level.format.LevelProvider; -import cn.nukkit.level.format.generic.BaseRegionLoader; -import cn.nukkit.utils.*; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Map; -import java.util.TreeMap; - -/** - * author: MagicDroidX - * Nukkit Project - */ - -public class RegionLoader extends BaseRegionLoader { - - public RegionLoader(LevelProvider level, int regionX, int regionZ) { - super(level, regionX, regionZ, "mcr"); - } - - @Override - protected boolean isChunkGenerated(int index) { - Integer[] array = this.locationTable.get(index); - return !(array[0] == 0 || array[1] == 0); - } - - public Chunk readChunk(int x, int z) throws IOException { - int index = getChunkOffset(x, z); - if (index < 0 || index >= 4096) { - return null; - } - - this.lastUsed = System.currentTimeMillis(); - - if (!this.isChunkGenerated(index)) { - return null; - } - - Integer[] table = this.locationTable.get(index); - RandomAccessFile raf = this.getRandomAccessFile(); - raf.seek(table[0] << 12); - int length = raf.readInt(); - if (length <= 0 || length >= MAX_SECTOR_LENGTH) { - if (length >= MAX_SECTOR_LENGTH) { - table[0] = ++this.lastSector; - table[1] = 1; - this.locationTable.put(index, table); - MainLogger.getLogger().error("Corrupted chunk header detected"); - } - return null; - } - - byte compression = raf.readByte(); - if (length > (table[1] << 12)) { - MainLogger.getLogger().error("Corrupted bigger chunk detected"); - table[1] = length >> 12; - this.locationTable.put(index, table); - this.writeLocationIndex(index); - } else if (compression != COMPRESSION_ZLIB && compression != COMPRESSION_GZIP) { - MainLogger.getLogger().error("Invalid compression type"); - return null; - } - - byte[] data = new byte[length - 1]; - raf.readFully(data); - Chunk chunk = this.unserializeChunk(data); - if (chunk != null) { - return chunk; - } else { - MainLogger.getLogger().error("Corrupted chunk detected"); - return null; - } - } - - @Override - protected Chunk unserializeChunk(byte[] data) { - return Chunk.fromBinary(data, this.levelProvider); - } - - @Override - public boolean chunkExists(int x, int z) { - return this.isChunkGenerated(getChunkOffset(x, z)); - } - - @Override - protected void saveChunk(int x, int z, byte[] chunkData) throws IOException { - int length = chunkData.length + 1; - if (length + 4 > MAX_SECTOR_LENGTH) { - throw new ChunkException("Chunk is too big! " + (length + 4) + " > " + MAX_SECTOR_LENGTH); - } - int sectors = (int) Math.ceil((length + 4) / 4096d); - int index = getChunkOffset(x, z); - boolean indexChanged = false; - Integer[] table = this.locationTable.get(index); - - if (table[1] < sectors) { - table[0] = this.lastSector + 1; - this.locationTable.put(index, table); - this.lastSector += sectors; - indexChanged = true; - } else if (table[1] != sectors) { - indexChanged = true; - } - - table[1] = sectors; - table[2] = (int) (System.currentTimeMillis() / 1000d); - - this.locationTable.put(index, table); - - RandomAccessFile raf = this.getRandomAccessFile(); - raf.seek(table[0] << 12); - - BinaryStream stream = new BinaryStream(); - stream.put(Binary.writeInt(length)); - stream.putByte(COMPRESSION_ZLIB); - stream.put(chunkData); - byte[] data = stream.getBuffer(); - if (data.length < sectors << 12) { - byte[] newData = new byte[sectors << 12]; - System.arraycopy(data, 0, newData, 0, data.length); - data = newData; - } - - raf.write(data); - - if (indexChanged) { - this.writeLocationIndex(index); - } - - } - - @Override - public void removeChunk(int x, int z) { - int index = getChunkOffset(x, z); - Integer[] table = this.locationTable.get(0); - table[0] = 0; - table[1] = 0; - this.locationTable.put(index, table); - } - - @Override - public void writeChunk(FullChunk chunk) throws Exception { - this.lastUsed = System.currentTimeMillis(); - byte[] chunkData = chunk.toBinary(); - this.saveChunk(chunk.getX() & 0x1f, chunk.getZ() & 0x1f, chunkData); - } - - protected static int getChunkOffset(int x, int z) { - return x | (z << 5); - } - - @Override - public void close() throws IOException { - this.writeLocationTable(); - this.levelProvider = null; - super.close(); - } - - @Override - public int doSlowCleanUp() throws Exception { - RandomAccessFile raf = this.getRandomAccessFile(); - for (int i = 0; i < 1024; i++) { - Integer[] table = this.locationTable.get(i); - if (table[0] == 0 || table[1] == 0) { - continue; - } - raf.seek(table[0] << 12); - byte[] chunk = new byte[table[1] << 12]; - raf.readFully(chunk); - int length = Binary.readInt(Arrays.copyOfRange(chunk, 0, 3)); - if (length <= 1) { - this.locationTable.put(i, (table = new Integer[]{0, 0, 0})); - } - try { - chunk = Zlib.inflate(Arrays.copyOf(chunk, 5)); - } catch (Exception e) { - this.locationTable.put(i, new Integer[]{0, 0, 0}); - continue; - } - chunk = Zlib.deflate(chunk, 9); - ByteBuffer buffer = ByteBuffer.allocate(4 + 1 + chunk.length); - buffer.put(Binary.writeInt(chunk.length + 1)); - buffer.put(COMPRESSION_ZLIB); - buffer.put(chunk); - chunk = buffer.array(); - int sectors = (int) Math.ceil(chunk.length / 4096d); - if (sectors > table[1]) { - table[0] = this.lastSector + 1; - this.lastSector += sectors; - this.locationTable.put(i, table); - } - raf.seek(table[0] << 12); - byte[] bytes = new byte[sectors << 12]; - ByteBuffer buffer1 = ByteBuffer.wrap(bytes); - buffer1.put(chunk); - raf.write(buffer1.array()); - } - this.writeLocationTable(); - int n = this.cleanGarbage(); - this.writeLocationTable(); - return n; - } - - @Override - protected void loadLocationTable() throws IOException { - RandomAccessFile raf = this.getRandomAccessFile(); - raf.seek(0); - this.lastSector = 1; - int[] data = new int[1024 * 2]; //1024 records * 2 times - for (int i = 0; i < 1024 * 2; i++) { - data[i] = raf.readInt(); - } - for (int i = 0; i < 1024; ++i) { - int index = data[i]; - this.locationTable.put(i, new Integer[]{index >> 8, index & 0xff, data[1024 + i]}); - int value = this.locationTable.get(i)[0] + this.locationTable.get(i)[1] - 1; - if (value > this.lastSector) { - this.lastSector = value; - } - } - } - - private void writeLocationTable() throws IOException { - RandomAccessFile raf = this.getRandomAccessFile(); - raf.seek(0); - for (int i = 0; i < 1024; ++i) { - Integer[] array = this.locationTable.get(i); - raf.writeInt((array[0] << 8) | array[1]); - } - for (int i = 0; i < 1024; ++i) { - Integer[] array = this.locationTable.get(i); - raf.writeInt(array[2]); - } - } - - private int cleanGarbage() throws IOException { - Map sectors = new TreeMap<>(); - for (int index : new ArrayList<>(this.locationTable.keySet())) { - Integer[] data = this.locationTable.get(index); - if (data[0] == 0 || data[1] == 0) { - this.locationTable.put(index, new Integer[]{0, 0, 0}); - continue; - } - sectors.put(data[0], index); - } - - if (sectors.size() == (this.lastSector - 2)) { - return 0; - } - - int shift = 0; - int lastSector = 1; - - RandomAccessFile raf = this.getRandomAccessFile(); - raf.seek(8192); - int s = 2; - for (int sector : sectors.keySet()) { - s = sector; - int index = sectors.get(sector); - if ((sector - lastSector) > 1) { - shift += sector - lastSector - 1; - } - if (shift > 0) { - raf.seek(sector << 12); - byte[] old = new byte[4096]; - raf.readFully(old); - raf.seek((sector - shift) << 12); - raf.write(old); - } - Integer[] v = this.locationTable.get(index); - v[0] -= shift; - this.locationTable.put(index, v); - this.lastSector = sector; - } - raf.setLength((s + 1) << 12); - return shift; - } - - @Override - protected void writeLocationIndex(int index) throws IOException { - Integer[] array = this.locationTable.get(index); - RandomAccessFile raf = this.getRandomAccessFile(); - - raf.seek(index << 2); - raf.writeInt((array[0] << 8) | array[1]); - raf.seek(4096 + (index << 2)); - raf.writeInt(array[2]); - } - - @Override - protected void createBlank() throws IOException { - RandomAccessFile raf = this.getRandomAccessFile(); - - raf.seek(0); - raf.setLength(0); - this.lastSector = 1; - int time = (int) (System.currentTimeMillis() / 1000d); - for (int i = 0; i < 1024; ++i) { - this.locationTable.put(i, new Integer[]{0, 0, time}); - raf.writeInt(0); - } - for (int i = 0; i < 1024; ++i) { - raf.writeInt(time); - } - } - - @Override - public int getX() { - return x; - } - - @Override - public int getZ() { - return z; - } - -} diff --git a/src/main/java/cn/nukkit/level/generator/Flat.java b/src/main/java/cn/nukkit/level/generator/Flat.java index dd963702f07..57ffd7def1e 100644 --- a/src/main/java/cn/nukkit/level/generator/Flat.java +++ b/src/main/java/cn/nukkit/level/generator/Flat.java @@ -1,7 +1,8 @@ package cn.nukkit.level.generator; import cn.nukkit.Server; -import cn.nukkit.block.*; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; import cn.nukkit.level.ChunkManager; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.format.generic.BaseFullChunk; @@ -11,14 +12,11 @@ import cn.nukkit.math.NukkitRandom; import cn.nukkit.math.Vector3; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.regex.Pattern; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class Flat extends Generator { @@ -62,7 +60,7 @@ public String getName() { } public Flat() { - this(new HashMap<>()); + this(Collections.emptyMap()); } public Flat(Map options) { @@ -70,25 +68,24 @@ public Flat(Map options) { this.options = options; if (this.options.containsKey("decoration")) { - PopulatorOre ores = new PopulatorOre(BlockID.STONE, new OreType[]{ - new OreType(Block.get(BlockID.COAL_ORE), 20, 16, 0, 128), - new OreType(Block.get(BlockID.IRON_ORE), 20, 8, 0, 64), - new OreType(Block.get(BlockID.REDSTONE_ORE), 8, 7, 0, 16), - new OreType(Block.get(BlockID.LAPIS_ORE), 1, 6, 0, 32), - new OreType(Block.get(BlockID.GOLD_ORE), 2, 8, 0, 32), - new OreType(Block.get(BlockID.DIAMOND_ORE), 1, 7, 0, 16), - new OreType(Block.get(BlockID.DIRT), 20, 32, 0, 128), - new OreType(Block.get(BlockID.GRAVEL), 20, 16, 0, 128), + PopulatorOre ores = new PopulatorOre(STONE, new OreType[]{ + new OreType(Block.get(BlockID.COAL_ORE), 20, 17, 0, 128), + new OreType(Block.get(BlockID.IRON_ORE), 20, 9, 0, 64), + new OreType(Block.get(BlockID.REDSTONE_ORE), 8, 8, 0, 16), + new OreType(Block.get(BlockID.LAPIS_ORE), 1, 7, 0, 30), + new OreType(Block.get(BlockID.GOLD_ORE), 2, 9, 0, 32), + new OreType(Block.get(BlockID.DIAMOND_ORE), 1, 8, 0, 16), + new OreType(Block.get(BlockID.DIRT), 10, 33, 0, 128), + new OreType(Block.get(BlockID.GRAVEL), 8, 33, 0, 128) }); this.populators.add(ores); } } - protected void parsePreset(String preset, int chunkX, int chunkZ) { + protected void parsePreset(String preset) { try { this.preset = preset; String[] presetArray = preset.split(";"); - int version = Integer.parseInt(presetArray[0]); String blocks = presetArray.length > 1 ? presetArray[1] : ""; this.biome = presetArray.length > 2 ? Integer.parseInt(presetArray[2]) : 1; String options = presetArray.length > 3 ? presetArray[1] : ""; @@ -129,8 +126,8 @@ protected void parsePreset(String preset, int chunkX, int chunkZ) { if (Pattern.matches("^[0-9a-z_]+$", option)) { this.options.put(option, true); } else if (Pattern.matches("^[0-9a-z_]+\\([0-9a-z_ =]+\\)$", option)) { - String name = option.substring(0, option.indexOf("(")); - String extra = option.substring(option.indexOf("(") + 1, option.indexOf(")")); + String name = option.substring(0, option.indexOf('(')); + String extra = option.substring(option.indexOf('(') + 1, option.indexOf(')')); Map map = new HashMap<>(); for (String kv : extra.split(" ")) { String[] data = kv.split("="); @@ -140,7 +137,7 @@ protected void parsePreset(String preset, int chunkX, int chunkZ) { } } } catch (Exception e) { - Server.getInstance().getLogger().error("error while parsing the preset", e); + Server.getInstance().getLogger().error("Error while parsing the preset", e); throw new RuntimeException(e); } } @@ -156,9 +153,9 @@ public void generateChunk(int chunkX, int chunkZ) { if (!this.init) { init = true; if (this.options.containsKey("preset") && !"".equals(this.options.get("preset"))) { - this.parsePreset((String) this.options.get("preset"), chunkX, chunkZ); + this.parsePreset((String) this.options.get("preset")); } else { - this.parsePreset(this.preset, chunkX, chunkZ); + this.parsePreset(this.preset); } } this.generateChunk(level.getChunk(chunkX, chunkZ)); @@ -172,8 +169,6 @@ private void generateChunk(FullChunk chunk) { chunk.setBiomeId(X, Z, biome); for (int y = 0; y < 256; ++y) { - int k = this.structure[y][0]; - int l = this.structure[y][1]; chunk.setBlock(X, y, Z, this.structure[y][0], this.structure[y][1]); } } @@ -191,6 +186,6 @@ public void populateChunk(int chunkX, int chunkZ) { @Override public Vector3 getSpawn() { - return new Vector3(128, this.floorLevel, 128); + return new Vector3(0.5, this.floorLevel, 0.5); } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/generator/Generator.java b/src/main/java/cn/nukkit/level/generator/Generator.java index ea53d7eef79..6a9976a03ef 100644 --- a/src/main/java/cn/nukkit/level/generator/Generator.java +++ b/src/main/java/cn/nukkit/level/generator/Generator.java @@ -1,5 +1,6 @@ package cn.nukkit.level.generator; +import cn.nukkit.Server; import cn.nukkit.block.BlockID; import cn.nukkit.level.ChunkManager; import cn.nukkit.level.DimensionData; @@ -7,30 +8,34 @@ import cn.nukkit.level.Level; import cn.nukkit.math.NukkitRandom; import cn.nukkit.math.Vector3; + import java.util.HashMap; import java.util.Map; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class Generator implements BlockID { + public static final int TYPE_OLD = 0; public static final int TYPE_INFINITE = 1; public static final int TYPE_FLAT = 2; public static final int TYPE_NETHER = 3; + public static final int TYPE_THE_END = 4; + public static final int TYPE_VOID = 5; public abstract int getId(); public DimensionData getDimensionData() { DimensionData dimensionData = DimensionEnum.getDataFromId(this.getDimension()); if (dimensionData == null) { + Server.getInstance().getLogger().warning("Invalid DimensionData for Generator " + this.getClass().getName()); dimensionData = DimensionEnum.OVERWORLD.getDimensionData(); } return dimensionData; } - @Deprecated public int getDimension() { return Level.DIMENSION_OVERWORLD; } @@ -72,18 +77,18 @@ public static Class getGenerator(int type) { } public static String getGeneratorName(Class c) { - for (String key : Generator.nameList.keySet()) { - if (Generator.nameList.get(key).equals(c)) { - return key; + for (Map.Entry> entry : Generator.nameList.entrySet()) { + if (entry.getValue() == c) { + return entry.getKey(); } } return "unknown"; } public static int getGeneratorType(Class c) { - for (int key : Generator.typeList.keySet()) { - if (Generator.typeList.get(key).equals(c)) { - return key; + for (Map.Entry> entry : Generator.typeList.entrySet()) { + if (entry.getValue() == c) { + return entry.getKey(); } } return Generator.TYPE_INFINITE; diff --git a/src/main/java/cn/nukkit/level/generator/GeneratorTaskFactory.java b/src/main/java/cn/nukkit/level/generator/GeneratorTaskFactory.java new file mode 100644 index 00000000000..54518d46f4a --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/GeneratorTaskFactory.java @@ -0,0 +1,11 @@ +package cn.nukkit.level.generator; + +import cn.nukkit.level.Level; +import cn.nukkit.level.format.generic.BaseFullChunk; +import cn.nukkit.scheduler.AsyncTask; + +public interface GeneratorTaskFactory { + + AsyncTask populateChunkTask(BaseFullChunk chunk, Level level); + AsyncTask generateChunkTask(BaseFullChunk chunk, Level level); +} diff --git a/src/main/java/cn/nukkit/level/generator/Nether.java b/src/main/java/cn/nukkit/level/generator/Nether.java index 64d7a9b08cd..763ac530603 100644 --- a/src/main/java/cn/nukkit/level/generator/Nether.java +++ b/src/main/java/cn/nukkit/level/generator/Nether.java @@ -1,45 +1,72 @@ package cn.nukkit.level.generator; -import cn.nukkit.block.*; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; import cn.nukkit.level.ChunkManager; import cn.nukkit.level.Level; import cn.nukkit.level.biome.Biome; import cn.nukkit.level.biome.EnumBiome; +import cn.nukkit.level.biome.type.CoveredBiome; import cn.nukkit.level.format.generic.BaseFullChunk; +import cn.nukkit.level.format.leveldb.structure.LevelDBChunk; import cn.nukkit.level.generator.noise.nukkit.f.SimplexF; import cn.nukkit.level.generator.object.ore.OreType; -import cn.nukkit.level.generator.populator.impl.PopulatorGlowStone; -import cn.nukkit.level.generator.populator.impl.PopulatorGroundFire; -import cn.nukkit.level.generator.populator.impl.PopulatorLava; -import cn.nukkit.level.generator.populator.impl.PopulatorOre; +import cn.nukkit.level.generator.populator.impl.*; import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitMath; import cn.nukkit.math.NukkitRandom; import cn.nukkit.math.Vector3; +import net.daporkchop.lib.common.ref.Ref; +import net.daporkchop.lib.common.ref.ThreadRef; +import net.daporkchop.lib.common.util.PValidation; +import net.daporkchop.lib.noise.engine.PerlinNoiseEngine; +import net.daporkchop.lib.noise.filter.ScaleOctavesOffsetFilter; +import net.daporkchop.lib.random.PRandom; import java.util.*; +import java.util.concurrent.ThreadLocalRandom; public class Nether extends Generator { + + private final boolean legacy; + private final int version; + private ChunkManager level; - /** - * @var Random - */ private NukkitRandom nukkitRandom; - private Random random; - private double lavaHeight = 32; - private double bedrockDepth = 5; - private SimplexF[] noiseGen = new SimplexF[3]; + private static final int lavaHeight = 32; // should be 31 + private final SimplexF[] noiseGen = new SimplexF[3]; private final List populators = new ArrayList<>(); - private List generationPopulators = new ArrayList<>(); + private final List generationPopulators = new ArrayList<>(); private long localSeed1; private long localSeed2; + private SimplexF biomeNoise; + + private static final int STEP_X = 4; + private static final int STEP_Y = 8; + private static final int STEP_Z = STEP_X; + private static final int SAMPLES_X = 16 / STEP_X; + private static final int SAMPLES_Y = 256 / STEP_Y; + private static final int SAMPLES_Z = 16 / STEP_Z; + private static final int CACHE_X = SAMPLES_X + 1; + private static final int CACHE_Y = SAMPLES_Y + 1; + private static final int CACHE_Z = SAMPLES_Z + 1; + private static final double SCALE_X = 1.0d / STEP_X; + private static final double SCALE_Y = 1.0d / STEP_Y; + private static final double SCALE_Z = 1.0d / STEP_Z; + private static final double NOISE_SCALE_FACTOR = ((1 << 16) - 1.0d) / 512.0d; + private static final Ref THREAD_DATA_CACHE = ThreadRef.soft(ThreadData::new); + private ScaleOctavesOffsetFilter selector; + private ScaleOctavesOffsetFilter low; + private ScaleOctavesOffsetFilter high; public Nether() { - this(new HashMap<>()); + this(Collections.emptyMap()); } public Nether(Map options) { - //Nothing here. Just used for future update. + this.legacy = !options.containsKey("__LevelDB"); + this.version = (int) options.getOrDefault("__Version", 0); } @Override @@ -59,7 +86,7 @@ public String getName() { @Override public Map getSettings() { - return new HashMap<>(); + return Collections.emptyMap(); } @Override @@ -70,43 +97,59 @@ public ChunkManager getChunkManager() { @Override public void init(ChunkManager level, NukkitRandom random) { this.level = level; + this.nukkitRandom = random; - this.random = new Random(); this.nukkitRandom.setSeed(this.level.getSeed()); - for (int i = 0; i < noiseGen.length; i++) { - noiseGen[i] = new SimplexF(nukkitRandom, 4, 1 / 4f, 1 / 64f); + if (this.legacy || this.version < 2) { + for (int i = 0; i < noiseGen.length; i++) { + noiseGen[i] = new SimplexF(this.nukkitRandom, 4, 1 / 4f, 1 / 64f); + } + } else { + this.selector = new ScaleOctavesOffsetFilter(new PerlinNoiseEngine(PRandom.wrap(new Random(this.level.getSeed()))), 0.01670927734375, 0.0334185546875, 0.01670927734375, 8, 12.75, 0.5); + this.low = new ScaleOctavesOffsetFilter(new PerlinNoiseEngine(PRandom.wrap(new Random(this.level.getSeed()))), 0.005221649169921875, 0.0078324737548828125, 0.005221649169921875, 16, 1.0, 0); + this.high = new ScaleOctavesOffsetFilter(new PerlinNoiseEngine(PRandom.wrap(new Random(this.level.getSeed()))), 0.005221649169921875, 0.0078324737548828125, 0.005221649169921875, 16, 1.0, 0); } this.nukkitRandom.setSeed(this.level.getSeed()); - this.localSeed1 = this.random.nextLong(); - this.localSeed2 = this.random.nextLong(); - - PopulatorOre ores = new PopulatorOre(Block.NETHERRACK, new OreType[]{ - new OreType(Block.get(BlockID.QUARTZ_ORE), 20, 16, 0, 128), - new OreType(Block.get(BlockID.SOUL_SAND), 5, 64, 0, 128), - new OreType(Block.get(BlockID.GRAVEL), 5, 64, 0, 128), - new OreType(Block.get(BlockID.LAVA), 1, 16, 0, (int) this.lavaHeight), - }); + this.localSeed1 = ThreadLocalRandom.current().nextLong(); + this.localSeed2 = ThreadLocalRandom.current().nextLong(); + + this.biomeNoise = new SimplexF(this.nukkitRandom, 2F, 1F / 8F, 1F / 2048f); + + PopulatorBedrock bedrock = new PopulatorBedrock(true); + this.generationPopulators.add(bedrock); + + PopulatorOre ores; + if (this.legacy) { + ores = new PopulatorOre(NETHERRACK, new OreType[]{ + new OreType(Block.get(BlockID.QUARTZ_ORE), 16, 24, 10, 117, NETHERRACK), + new OreType(Block.get(BlockID.SOUL_SAND), 12, 23, 0, /*31*/ 105, NETHERRACK), + new OreType(Block.get(BlockID.GRAVEL), 2, 64, 5, /*41*/ 105, NETHERRACK), + new OreType(Block.get(BlockID.MAGMA), 4, 64, 26, /*37*/ lavaHeight + 1, NETHERRACK), + new OreType(Block.get(BlockID.LAVA), 1, 16, 0, lavaHeight, NETHERRACK), + }); + } else { + ores = new PopulatorOre(NETHERRACK, new OreType[]{ + new OreType(Block.get(BlockID.QUARTZ_ORE), 16, 24, 10, 117, NETHERRACK), + new OreType(Block.get(BlockID.SOUL_SAND), 12, 23, 0, /*31*/ 105, NETHERRACK), + new OreType(Block.get(BlockID.GRAVEL), 2, 64, 5, /*41*/ 105, NETHERRACK), + new OreType(Block.get(BlockID.MAGMA), 4, 64, 26, /*37*/ lavaHeight + 1, NETHERRACK), + new OreType(Block.get(BlockID.LAVA), 1, 16, 0, lavaHeight, NETHERRACK), + new OreType(Block.get(BlockID.NETHER_GOLD_ORE), 10, 16, 10, 117, NETHERRACK), + new OreType(Block.get(BlockID.ANCIENT_DEBRIS), 2, 3, 8, 23, NETHERRACK), + new OreType(Block.get(BlockID.ANCIENT_DEBRIS), 3, 2, 8, 119, NETHERRACK), + }); + } this.populators.add(ores); - PopulatorGroundFire groundFire = new PopulatorGroundFire(); - groundFire.setBaseAmount(1); - groundFire.setRandomAmount(1); - this.populators.add(groundFire); + this.populators.add(new PopulatorNetherFire(FIRE, NETHERRACK)); PopulatorLava lava = new PopulatorLava(); - lava.setBaseAmount(1); lava.setRandomAmount(2); this.populators.add(lava); + this.populators.add(new PopulatorGlowStone()); - PopulatorOre ore = new PopulatorOre(Block.NETHERRACK, new OreType[]{ - new OreType(Block.get(BlockID.QUARTZ_ORE), 40, 16, 0, 128, NETHERRACK), - new OreType(Block.get(BlockID.SOUL_SAND), 1, 64, 30, 35, NETHERRACK), - new OreType(Block.get(BlockID.LAVA), 32, 1, 0, 32, NETHERRACK), - new OreType(Block.get(BlockID.MAGMA), 32, 16, 26, 37, NETHERRACK), - }); - this.populators.add(ore); } @Override @@ -117,45 +160,205 @@ public void generateChunk(int chunkX, int chunkZ) { BaseFullChunk chunk = level.getChunk(chunkX, chunkZ); - for (int x = 0; x < 16; ++x) { - for (int z = 0; z < 16; ++z) { - Biome biome = EnumBiome.HELL.biome; - chunk.setBiomeId(x, z, biome.getId()); + if (this.version < 2 || !(chunk instanceof LevelDBChunk)) { + for (int x = 0; x < 16; ++x) { + for (int z = 0; z < 16; ++z) { + chunk.setBiomeId(x, z, EnumBiome.HELL.biome.getId()); - chunk.setBlockId(x, 0, z, Block.BEDROCK); - for (int y = 115; y < 127; ++y) { - chunk.setBlockId(x, y, z, Block.NETHERRACK); - } - chunk.setBlockId(x, 127, z, Block.BEDROCK); - for (int y = 1; y < 127; ++y) { - if (getNoise(baseX | x, y, baseZ | z) > 0) { + for (int y = 115; y < 127; ++y) { chunk.setBlockId(x, y, z, Block.NETHERRACK); - } else if (y <= this.lavaHeight) { - chunk.setBlockId(x, y, z, Block.STILL_LAVA); - chunk.setBlockLight(x, y + 1, z, 15); + } + + for (int y = 1; y < 127; ++y) { + if (getNoise(baseX | x, y, baseZ | z) > 0) { + chunk.setBlockId(x, y, z, Block.NETHERRACK); + } else if (y <= lavaHeight) { + chunk.setBlockId(x, y, z, Block.STILL_LAVA); + chunk.setBlockLight(x, y + 1, z, 15); + } + } + } + } + } else { // use generator from Cloudburst + CoveredBiome[][] biomes = new CoveredBiome[16][16]; + + for (int x = 0; x < 16; ++x) { + for (int z = 0; z < 16; ++z) { + CoveredBiome biome = (CoveredBiome) pickBiome(baseX + x, baseZ + z); + chunk.setBiomeId(x, z, biome.getId()); + biomes[x][z] = biome; + } + } + + final ThreadData threadData = THREAD_DATA_CACHE.get(); + final double[] densityCache = threadData.densityCache = densityGet(threadData.densityCache, baseX, 0, baseZ); + + for (int i = 0, sectionX = 0; sectionX < SAMPLES_X; sectionX++) { + for (int sectionZ = 0; sectionZ < SAMPLES_Z; sectionZ++) { + for (int sectionY = 0; sectionY < SAMPLES_Y; sectionY++, i++) { + double dxyz = densityCache[i]; + double dxYz = densityCache[i + 1]; + double dxyZ = densityCache[i + CACHE_Y]; + double dxYZ = densityCache[i + CACHE_Y + 1]; + double dXyz = densityCache[i + CACHE_Y * CACHE_Z]; + double dXYz = densityCache[i + CACHE_Y * CACHE_Z + 1]; + double dXyZ = densityCache[i + CACHE_Y * CACHE_Z + CACHE_Y]; + double dXYZ = densityCache[i + CACHE_Y * CACHE_Z + CACHE_Y + 1]; + + double bx00 = dxyz; + double bx01 = dxyZ; + double bx10 = dxYz; + double bx11 = dxYZ; + double gx00 = (dXyz - dxyz) * SCALE_X; + double gx01 = (dXyZ - dxyZ) * SCALE_X; + double gx10 = (dXYz - dxYz) * SCALE_X; + double gx11 = (dXYZ - dxYZ) * SCALE_X; + + for (int stepX = 0; stepX < STEP_X; stepX++) { + double ix00 = bx00 + gx00 * stepX; + double ix01 = bx01 + gx01 * stepX; + double ix10 = bx10 + gx10 * stepX; + double ix11 = bx11 + gx11 * stepX; + + double by0 = ix00; + double by1 = ix01; + double gy0 = (ix10 - ix00) * SCALE_Y; + double gy1 = (ix11 - ix01) * SCALE_Y; + + for (int stepY = 0; stepY < STEP_Y; stepY++) { + double iy0 = by0 + gy0 * stepY; + double iy1 = by1 + gy1 * stepY; + + double bz = iy0; + double gz = (iy1 - iy0) * SCALE_Z; + + for (int stepZ = 0; stepZ < STEP_Z; stepZ++) { + double iz = bz + gz * stepZ; + + int blockX = sectionX * STEP_X | stepX; + int blockY = sectionY * STEP_Y | stepY; + int blockZ = sectionZ * STEP_Z | stepZ; + + if (blockY < 127 && iz > 0.0d) { + CoveredBiome biome = biomes[blockX][blockZ]; + chunk.setFullBlockId(blockX, blockY, blockZ, biome.getGroundId(blockX, 0, blockZ)); + } else if (blockY <= lavaHeight) { + chunk.setBlockId(blockX, blockY, blockZ, Block.STILL_LAVA); + chunk.setBlockLight(blockX, blockY + 1, blockZ, 15); + } + } + } + } + } + + i++; + } + + i += CACHE_Y; + } + + // Populate ground cover + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + CoveredBiome biome = biomes[x][z]; + + int ground = biome.getGroundId(x, 0, z); + int surface = biome.getSurfaceId(x, 0, z); + + if (ground != surface) { + int previous = chunk.getBlockId(x, 126, z); + for (int y = 125; y > 1; --y) { + int id = chunk.getFullBlock(x, y, z); + if (id == ground && previous == AIR) { + chunk.setFullBlockId(x, y, z, surface); + } + previous = id; + } } } } } + + // Populate bedrock for (Populator populator : this.generationPopulators) { populator.populate(this.level, chunkX, chunkZ, this.nukkitRandom, chunk); } } + private double densityGet(int x, int y, int z) { + if (y >= 128) { + return 0.0d; + } + + double selector = NukkitMath.clamp(this.selector.get(x, y, (double) z), 0.0d, 1.0d); + double low = this.low.get(x, y, (double) z) * NOISE_SCALE_FACTOR; + double high = this.high.get(x, y, (double) z) * NOISE_SCALE_FACTOR; + + double outputNoise = NukkitMath.lerp(low, high, selector); + + double threshold = y * 0.125d; + double offset = Math.cos(threshold * Math.PI * 6.0d / 17.0d) * 2.0d; + + if (threshold > 8.0d) { + threshold = 16.0d - threshold; + } + if (threshold < 4.0d) { + threshold = 4.0d - threshold; + offset -= threshold * threshold * threshold * 10.0d; + } + + return outputNoise - offset; + } + + private double[] densityGet(double[] arr, int x, int y, int z) { + int totalSize = PValidation.positive(Nether.CACHE_X) * PValidation.positive(Nether.CACHE_Y) * PValidation.positive(Nether.CACHE_Z) + PValidation.notNegative(0); + if (arr == null || arr.length < totalSize) { + arr = new double[totalSize]; + } + + for (int i = 0, dx = 0; dx < Nether.CACHE_X; dx++) { + for (int dz = 0; dz < Nether.CACHE_Z; dz++) { + for (int dy = 0; dy < Nether.CACHE_Y; dy++) { + arr[i++] = densityGet(x + dx * Nether.STEP_X, y + dy * Nether.STEP_Y, z + dz * Nether.STEP_Z); + } + } + } + return arr; + } + + private Biome pickBiome(int x, int z) { + float value = this.biomeNoise.noise2D(x, z, true); + float secondaryValue = this.biomeNoise.noise2D(z, x, true); // Reversed x & z is intentional here + + if (value >= 1 / 3f) { + return secondaryValue >= 0 ? EnumBiome.WARPED_FOREST.biome : EnumBiome.CRIMSON_FOREST.biome; + } else if (value >= -1 / 3f) { + return EnumBiome.HELL.biome; + } else { + return secondaryValue >= 0 ? EnumBiome.BASALT_DELTAS.biome : EnumBiome.SOULSAND_VALLEY.biome; + } + } + @Override public void populateChunk(int chunkX, int chunkZ) { BaseFullChunk chunk = level.getChunk(chunkX, chunkZ); + this.nukkitRandom.setSeed(0xdeadbeef ^ (chunkX << 8) ^ chunkZ ^ this.level.getSeed()); + for (Populator populator : this.populators) { populator.populate(this.level, chunkX, chunkZ, this.nukkitRandom, chunk); } - Biome biome = EnumBiome.getBiome(chunk.getBiomeId(7, 7)); - biome.populateChunk(this.level, chunkX, chunkZ, this.nukkitRandom); + if (!(chunk instanceof LevelDBChunk)) { + EnumBiome.HELL.biome.populateChunk(this.level, chunkX, chunkZ, this.nukkitRandom); + } else { + Biome biome = Biome.getBiome(chunk.getBiomeId(7, 7)); + biome.populateChunk(this.level, chunkX, chunkZ, this.nukkitRandom); + } } public Vector3 getSpawn() { - return new Vector3(0, 64, 0); + return new Vector3(0.5, 64, 0.5); } public float getNoise(int x, int y, int z) { @@ -165,4 +368,8 @@ public float getNoise(int x, int y, int z) { } return val; } -} + + private static final class ThreadData { + private double[] densityCache; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/generator/Normal.java b/src/main/java/cn/nukkit/level/generator/Normal.java index 61ced5c4966..56f45e0ac25 100644 --- a/src/main/java/cn/nukkit/level/generator/Normal.java +++ b/src/main/java/cn/nukkit/level/generator/Normal.java @@ -1,13 +1,18 @@ package cn.nukkit.level.generator; -import cn.nukkit.block.*; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; +import cn.nukkit.block.BlockStone; import cn.nukkit.level.ChunkManager; import cn.nukkit.level.biome.Biome; import cn.nukkit.level.biome.BiomeSelector; import cn.nukkit.level.biome.EnumBiome; +import cn.nukkit.level.biome.impl.beach.BeachBiome; +import cn.nukkit.level.biome.impl.mushroom.MushroomIslandBiome; +import cn.nukkit.level.biome.impl.swamp.SwampBiome; +import cn.nukkit.level.biome.type.WateryBiome; import cn.nukkit.level.format.generic.BaseFullChunk; import cn.nukkit.level.generator.noise.vanilla.f.NoiseGeneratorOctavesF; -import cn.nukkit.level.generator.noise.vanilla.f.NoiseGeneratorPerlinF; import cn.nukkit.level.generator.object.ore.OreType; import cn.nukkit.level.generator.populator.impl.*; import cn.nukkit.level.generator.populator.type.Populator; @@ -16,91 +21,18 @@ import cn.nukkit.math.Vector3; import com.google.common.collect.ImmutableList; -import java.util.*; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.SplittableRandom; /** * Nukkit's terrain generator * Originally adapted from the PocketMine-MP generator by NycuRO and CreeperFace * Mostly rewritten by DaPorkchop_ - *

- * The following classes, and others related to terrain generation are theirs and are intended for NUKKIT USAGE and should not be copied/translated to other server software - * such as BukkitPE, ClearSky, Genisys, PocketMine-MP, or others - *

- * Normal.java - * MushroomPopulator.java - * DarkOakTreePopulator.java - * JungleBigTreePopulator.java - * JungleTreePopulaotr.java - * SavannaTreePopulator.java - * SwampTreePopulator.java - * BasicPopulator.java - * TreeGenerator.java - * HugeTreesGenerator.java - * BeachBiome.java - * ColdBeachBiome.java - * DesertBiome.java - * DesertHillsBiome.java - * DesertMBiome.java - * ExtremeHillsBiome.java - * ExtremeHillsEdgeBiome.java - * ExtremeHillsMBiome.java - * ExtremeHillsPlusBiome.java - * ExtremeHillsPlusMBiome.java - * StoneBeachBiome.java - * FlowerForestBiome.java - * ForestBiome.java - * ForestHillsBiome.java - * IcePlainsBiome.java - * IcePlainsSpikesBiome.java - * JungleBiome.java - * JungleEdgeBiome.java - * JungleEdgeMBiome.java - * JungleHillsBiome.java - * JungleMBiome.java - * MesaBiome.java - * MesaBryceBiome.java - * MesaPlateauBiome.java - * MesaPlateauFBiome.java - * MesaPlateauFMBiome.java - * MesaPlateauMBiome.java - * MushroomIslandBiome.java - * MushroomIslandShoreBiome.java - * DeepOceanBiome.java - * FrozenOceanBiome.java - * OceanBiome.java - * PlainsBiome.java - * SunflowerPlainsBiome.java - * FrozenRiverBiome.java - * RiverBiome.java - * RoofedForestBiome.java - * RoofedForestMBiome.java - * SavannaBiome.java - * SavannaMBiome.java - * SavannaPlateauBiome.java - * SavannaPlateauMBiome.java - * SwampBiome.java - * SwamplandMBiome.java - * ColdTaigaBiome.java - * ColdTaigaHillsBiome.java - * ColdTaigaMBiome.java - * MegaSpruceTaigaBiome.java - * MegaTaigaBiome.java - * MegaTagaHillsBiome.java - * TaigaBiome.java - * TaigaHillsBiome.java - * TaigaMBiome.java - * CoveredBiome.java - * GrassyBiome.java - * SandyBiome.java - * WateryBiome.java - * EnumBiomeBiome.java - * PopulatorCount.java - * PopulatorSurfaceBlock.java - * Normal.java - * Nether.java - * End.java */ public class Normal extends Generator { + private static final float[] biomeWeights = new float[25]; static { @@ -111,34 +43,31 @@ public class Normal extends Generator { } } + private final int version; private List populators = Collections.emptyList(); private List generationPopulators = Collections.emptyList(); - public static final int seaHeight = 64; - public NoiseGeneratorOctavesF scaleNoise; + public static int seaHeight = 64; // should be 62 public NoiseGeneratorOctavesF depthNoise; private ChunkManager level; - private Random random; private NukkitRandom nukkitRandom; private long localSeed1; private long localSeed2; private BiomeSelector selector; - private ThreadLocal biomes = ThreadLocal.withInitial(() -> new Biome[10 * 10]); - private ThreadLocal depthRegion = ThreadLocal.withInitial(() -> null); - private ThreadLocal mainNoiseRegion = ThreadLocal.withInitial(() -> null); - private ThreadLocal minLimitRegion = ThreadLocal.withInitial(() -> null); - private ThreadLocal maxLimitRegion = ThreadLocal.withInitial(() -> null); - private ThreadLocal heightMap = ThreadLocal.withInitial(() -> new float[825]); + private final ThreadLocal depthRegion = ThreadLocal.withInitial(() -> null); + private final ThreadLocal mainNoiseRegion = ThreadLocal.withInitial(() -> null); + private final ThreadLocal minLimitRegion = ThreadLocal.withInitial(() -> null); + private final ThreadLocal maxLimitRegion = ThreadLocal.withInitial(() -> null); + private final ThreadLocal heightMap = ThreadLocal.withInitial(() -> new float[825]); private NoiseGeneratorOctavesF minLimitPerlinNoise; private NoiseGeneratorOctavesF maxLimitPerlinNoise; private NoiseGeneratorOctavesF mainPerlinNoise; - private NoiseGeneratorPerlinF surfaceNoise; public Normal() { this(Collections.emptyMap()); } public Normal(Map options) { - //Nothing here. Just used for future update. + this.version = (int) options.getOrDefault("__Version", 0); } @Override @@ -148,7 +77,7 @@ public int getId() { @Override public ChunkManager getChunkManager() { - return this.level; + return level; } @Override @@ -162,25 +91,23 @@ public Map getSettings() { } public Biome pickBiome(int x, int z) { - return this.selector.pickBiome(x, z); + return this.selector.pickBiome(x, z, this.version); } @Override public void init(ChunkManager level, NukkitRandom random) { this.level = level; this.nukkitRandom = random; - this.random = new Random(); + SplittableRandom random1 = new SplittableRandom(); this.nukkitRandom.setSeed(this.level.getSeed()); - this.localSeed1 = this.random.nextLong(); - this.localSeed2 = this.random.nextLong(); + this.localSeed1 = random1.nextLong(); + this.localSeed2 = random1.nextLong(); this.nukkitRandom.setSeed(this.level.getSeed()); this.selector = new BiomeSelector(this.nukkitRandom); this.minLimitPerlinNoise = new NoiseGeneratorOctavesF(random, 16); this.maxLimitPerlinNoise = new NoiseGeneratorOctavesF(random, 16); this.mainPerlinNoise = new NoiseGeneratorOctavesF(random, 8); - this.surfaceNoise = new NoiseGeneratorPerlinF(random, 4); - this.scaleNoise = new NoiseGeneratorOctavesF(random, 10); this.depthNoise = new NoiseGeneratorOctavesF(random, 16); //this should run before all other populators so that we don't do things like generate ground cover on bedrock or something @@ -194,7 +121,7 @@ public void init(ChunkManager level, NukkitRandom random) { new OreType(Block.get(BlockID.COAL_ORE), 20, 17, 0, 128), new OreType(Block.get(BlockID.IRON_ORE), 20, 9, 0, 64), new OreType(Block.get(BlockID.REDSTONE_ORE), 8, 8, 0, 16), - new OreType(Block.get(BlockID.LAPIS_ORE), 1, 7, 0, 16), + new OreType(Block.get(BlockID.LAPIS_ORE), 1, 7, 0, 30), new OreType(Block.get(BlockID.GOLD_ORE), 2, 9, 0, 32), new OreType(Block.get(BlockID.DIAMOND_ORE), 1, 8, 0, 16), new OreType(Block.get(BlockID.DIRT), 10, 33, 0, 128), @@ -203,8 +130,10 @@ public void init(ChunkManager level, NukkitRandom random) { new OreType(Block.get(BlockID.STONE, BlockStone.DIORITE), 10, 33, 0, 80), new OreType(Block.get(BlockID.STONE, BlockStone.ANDESITE), 10, 33, 0, 80) }), - new PopulatorCaves()//, - //new PopulatorRavines() + new PopulatorCaves(), + new WaterIcePopulator(), // Populate water ice here to avoid sharp corners when the chunk is not fully on a freezing biome + new PopulatorSpring(BlockID.WATER, BlockID.STONE, 15, 8, 255), + new PopulatorSpring(BlockID.LAVA, BlockID.STONE, 10, 16, 255) ); } @@ -212,18 +141,18 @@ public void init(ChunkManager level, NukkitRandom random) { public void generateChunk(final int chunkX, final int chunkZ) { int baseX = chunkX << 4; int baseZ = chunkZ << 4; - this.nukkitRandom.setSeed(chunkX * this.localSeed1 ^ chunkZ * this.localSeed2 ^ this.level.getSeed()); + this.nukkitRandom.setSeed(chunkX * localSeed1 ^ chunkZ * localSeed2 ^ this.level.getSeed()); - BaseFullChunk chunk = this.level.getChunk(chunkX, chunkZ); + BaseFullChunk chunk = level.getChunk(chunkX, chunkZ); //generate base noise values - float[] depthRegion = this.depthNoise.generateNoiseOctaves(this.depthRegion.get(), chunkX * 4, chunkZ * 4, 5, 5, 200f, 200f, 0.5f); + float[] depthRegion = this.depthNoise.generateNoiseOctaves(this.depthRegion.get(), chunkX << 2, chunkZ << 2, 5, 5, 200f, 200f, 0.5f); this.depthRegion.set(depthRegion); - float[] mainNoiseRegion = this.mainPerlinNoise.generateNoiseOctaves(this.mainNoiseRegion.get(), chunkX * 4, 0, chunkZ * 4, 5, 33, 5, 684.412f / 60f, 684.412f / 160f, 684.412f / 60f); + float[] mainNoiseRegion = this.mainPerlinNoise.generateNoiseOctaves(this.mainNoiseRegion.get(), chunkX << 2, 0, chunkZ << 2, 5, 33, 5, 11.406866f, 4.277575f, 11.406866f); this.mainNoiseRegion.set(mainNoiseRegion); - float[] minLimitRegion = this.minLimitPerlinNoise.generateNoiseOctaves(this.minLimitRegion.get(), chunkX * 4, 0, chunkZ * 4, 5, 33, 5, 684.412f, 684.412f, 684.412f); + float[] minLimitRegion = this.minLimitPerlinNoise.generateNoiseOctaves(this.minLimitRegion.get(), chunkX << 2, 0, chunkZ << 2, 5, 33, 5, 684.412f, 684.412f, 684.412f); this.minLimitRegion.set(minLimitRegion); - float[] maxLimitRegion = this.maxLimitPerlinNoise.generateNoiseOctaves(this.maxLimitRegion.get(), chunkX * 4, 0, chunkZ * 4, 5, 33, 5, 684.412f, 684.412f, 684.412f); + float[] maxLimitRegion = this.maxLimitPerlinNoise.generateNoiseOctaves(this.maxLimitRegion.get(), chunkX << 2, 0, chunkZ << 2, 5, 33, 5, 684.412f, 684.412f, 684.412f); this.maxLimitRegion.set(maxLimitRegion); float[] heightMap = this.heightMap.get(); @@ -235,11 +164,11 @@ public void generateChunk(final int chunkX, final int chunkZ) { float heightVariationSum = 0.0F; float baseHeightSum = 0.0F; float biomeWeightSum = 0.0F; - Biome biome = this.pickBiome(baseX + (xSeg * 4), baseZ + (zSeg * 4)); + Biome biome = pickBiome(baseX + (xSeg << 2), baseZ + (zSeg << 2)); for (int xSmooth = -2; xSmooth <= 2; ++xSmooth) { for (int zSmooth = -2; zSmooth <= 2; ++zSmooth) { - Biome biome1 = this.pickBiome(baseX + (xSeg * 4) + xSmooth, baseZ + (zSeg * 4) + zSmooth); + Biome biome1 = pickBiome(baseX + (xSeg << 2) + xSmooth, baseZ + (zSeg << 2) + zSmooth); float baseHeight = biome1.getBaseHeight(); float heightVariation = biome1.getHeightVariation(); @@ -314,6 +243,12 @@ public void generateChunk(final int chunkX, final int chunkZ) { } } + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + chunk.setBiome(x, z, selector.pickBiome(baseX | x, baseZ | z, this.version)); + } + } + //place blocks for (int xSeg = 0; xSeg < 4; ++xSeg) { int xScale = xSeg * 5; @@ -346,10 +281,21 @@ public void generateChunk(final int chunkX, final int chunkZ) { double scaleZ2 = baseIncr - scaleZ; for (int xIn = 0; xIn < 4; ++xIn) { - if ((scaleZ2 += scaleZ) > 0.0f) { - chunk.setBlockId(xSeg * 4 + zIn, ySeg * 8 + yIn, zSeg * 4 + xIn, STONE); - } else if (ySeg * 8 + yIn <= seaHeight) { - chunk.setBlockId(xSeg * 4 + zIn, ySeg * 8 + yIn, zSeg * 4 + xIn, STILL_WATER); + int xxx = (xSeg << 2) + zIn; + int yyy = (ySeg << 3) + yIn; + int zzz = (zSeg << 2) + xIn; + + if ((scaleZ2 += scaleZ) > 0.0) { + chunk.setBlockId(xxx, yyy, zzz, STONE); + } else if (yyy <= seaHeight) { + chunk.setBlockId(xxx, yyy, zzz, STILL_WATER); + + if (yyy < seaHeight) { + Biome biome = Biome.getBiome(chunk.getBiomeId(xxx, zzz)); + if (!(biome instanceof WateryBiome) && !(biome instanceof BeachBiome) && !(biome instanceof SwampBiome) && !(biome instanceof MushroomIslandBiome)) { // don't replace shore + chunk.setBiome(xxx, zzz, biome.isFreezing() ? EnumBiome.FROZEN_RIVER.biome : EnumBiome.RIVER.biome); + } + } } } @@ -366,14 +312,6 @@ public void generateChunk(final int chunkX, final int chunkZ) { } } - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - Biome biome = this.selector.pickBiome(baseX | x, baseZ | z); - - chunk.setBiome(x, z, biome); - } - } - //populate chunk for (Populator populator : this.generationPopulators) { populator.populate(this.level, chunkX, chunkZ, this.nukkitRandom, chunk); @@ -382,14 +320,15 @@ public void generateChunk(final int chunkX, final int chunkZ) { @Override public void populateChunk(int chunkX, int chunkZ) { - BaseFullChunk chunk = this.level.getChunk(chunkX, chunkZ); + BaseFullChunk chunk = level.getChunk(chunkX, chunkZ); + this.nukkitRandom.setSeed(0xdeadbeef ^ (chunkX << 8) ^ chunkZ ^ this.level.getSeed()); + for (Populator populator : this.populators) { populator.populate(this.level, chunkX, chunkZ, this.nukkitRandom, chunk); } - @SuppressWarnings("deprecation") - Biome biome = EnumBiome.getBiome(chunk.getBiomeId(7, 7)); + Biome biome = Biome.getBiome(chunk.getBiomeId(7, 7)); biome.populateChunk(this.level, chunkX, chunkZ, this.nukkitRandom); } diff --git a/src/main/java/cn/nukkit/level/generator/PopChunkManager.java b/src/main/java/cn/nukkit/level/generator/PopChunkManager.java index d879c2fcf73..db8f3a556ee 100644 --- a/src/main/java/cn/nukkit/level/generator/PopChunkManager.java +++ b/src/main/java/cn/nukkit/level/generator/PopChunkManager.java @@ -1,16 +1,26 @@ package cn.nukkit.level.generator; +import cn.nukkit.level.DimensionData; import cn.nukkit.level.format.generic.BaseFullChunk; import java.util.Arrays; +import java.util.function.Supplier; public class PopChunkManager extends SimpleChunkManager { + private boolean clean = true; private final BaseFullChunk[] chunks = new BaseFullChunk[9]; private int CX = Integer.MAX_VALUE; private int CZ = Integer.MAX_VALUE; + private final Supplier dimensionDataSupplier; + public PopChunkManager(long seed) { + this(seed, () -> DimensionData.LEGACY_DIMENSION); + } + + public PopChunkManager(long seed, Supplier dimensionDataSupplier) { super(seed); + this.dimensionDataSupplier = dimensionDataSupplier; } @Override @@ -90,4 +100,14 @@ public void setChunk(int chunkX, int chunkZ, BaseFullChunk chunk) { clean = false; chunks[index] = chunk; } + + @Override + public int getMaxBlockY() { + return this.dimensionDataSupplier.get().getMaxHeight(); + } + + @Override + public int getMinBlockY() { + return this.dimensionDataSupplier.get().getMinHeight(); + } } diff --git a/src/main/java/cn/nukkit/level/generator/SimpleChunkManager.java b/src/main/java/cn/nukkit/level/generator/SimpleChunkManager.java index 5ff6692c8a3..2eff112ffdd 100644 --- a/src/main/java/cn/nukkit/level/generator/SimpleChunkManager.java +++ b/src/main/java/cn/nukkit/level/generator/SimpleChunkManager.java @@ -1,10 +1,11 @@ package cn.nukkit.level.generator; +import cn.nukkit.block.BlockLayer; import cn.nukkit.level.ChunkManager; import cn.nukkit.level.format.FullChunk; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class SimpleChunkManager implements ChunkManager { @@ -16,54 +17,86 @@ public SimpleChunkManager(long seed) { } @Override - public int getBlockIdAt(int x, int y, int z) { + public int getBlockIdAt(int x, int y, int z, BlockLayer layer) { + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return 0; + } FullChunk chunk = this.getChunk(x >> 4, z >> 4); if (chunk != null) { - return chunk.getBlockId(x & 0xf, y & 0xff, z & 0xf); + return chunk.getBlockId(x & 0xf, y, z & 0xf, layer); } return 0; } @Override - public void setBlockIdAt(int x, int y, int z, int id) { + public void setBlockIdAt(int x, int y, int z, BlockLayer layer, int id) { + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return; + } FullChunk chunk = this.getChunk(x >> 4, z >> 4); if (chunk != null) { - chunk.setBlockId(x & 0xf, y & 0xff, z & 0xf, id); + chunk.setBlockId(x & 0xf, y, z & 0xf, layer, id); } } @Override public void setBlockAt(int x, int y, int z, int id, int data) { + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return; + } + FullChunk chunk = this.getChunk(x >> 4, z >> 4); if (chunk != null) { - chunk.setBlock(x & 0xf, y & 0xff, z & 0xf, id, data); + chunk.setBlock(x & 0xf, y, z & 0xf, id, data); } } - @Override - public void setBlockFullIdAt(int x, int y, int z, int fullId) { + public void setBlockFullIdAt(int x, int y, int z, BlockLayer layer, int fullId) { + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return; + } FullChunk chunk = this.getChunk(x >> 4, z >> 4); if (chunk != null) { - chunk.setFullBlockId(x & 0xf, y & 0xff, z & 0xf, fullId); + chunk.setFullBlockId(x & 0xf, y, z & 0xf, layer, fullId); } } @Override - public int getBlockDataAt(int x, int y, int z) { + public int getBlockDataAt(int x, int y, int z, BlockLayer layer) { + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return 0; + } FullChunk chunk = this.getChunk(x >> 4, z >> 4); if (chunk != null) { - return chunk.getBlockData(x & 0xf, y & 0xff, z & 0xf); + return chunk.getBlockData(x & 0xf, y, z & 0xf, layer); } return 0; } @Override - public void setBlockDataAt(int x, int y, int z, int data) { + public void setBlockDataAt(int x, int y, int z, BlockLayer layer, int data) { + FullChunk chunk = this.getChunk(x >> 4, z >> 4); + if (chunk != null) { + chunk.setBlockData(x & 0xf, y, z & 0xf, layer, data); + } + } + + @Override + public boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int id) { + return this.setBlockAtLayer(x, y, z, layer, id, 0); + } + + @Override + public boolean setBlockAtLayer(int x, int y, int z, BlockLayer layer, int id, int data) { + if (y < this.getMinBlockY() || y > this.getMaxBlockY()) { + return false; + } FullChunk chunk = this.getChunk(x >> 4, z >> 4); if (chunk != null) { - chunk.setBlockData(x & 0xf, y & 0xff, z & 0xf, data); + return chunk.setBlockAtLayer(x, y, z, layer, id, data); } + return true; } @Override @@ -83,4 +116,7 @@ public void setSeed(long seed) { public void cleanChunks(long seed) { this.seed = seed; } + + public abstract int getMinBlockY(); + public abstract int getMaxBlockY(); } diff --git a/src/main/java/cn/nukkit/level/generator/SingleChunkManager.java b/src/main/java/cn/nukkit/level/generator/SingleChunkManager.java index 3567dd5a4ee..69eacf94acd 100644 --- a/src/main/java/cn/nukkit/level/generator/SingleChunkManager.java +++ b/src/main/java/cn/nukkit/level/generator/SingleChunkManager.java @@ -3,6 +3,7 @@ import cn.nukkit.level.format.generic.BaseFullChunk; public class SingleChunkManager extends SimpleChunkManager { + private int CX = Integer.MAX_VALUE; private int CZ = Integer.MAX_VALUE; private BaseFullChunk chunk; @@ -41,4 +42,14 @@ public void cleanChunks(long seed) { CX = Integer.MAX_VALUE; CZ = Integer.MAX_VALUE; } + + @Override + public int getMinBlockY() { + return 0; + } + + @Override + public int getMaxBlockY() { + return 255; + } } diff --git a/src/main/java/cn/nukkit/level/generator/TheEnd.java b/src/main/java/cn/nukkit/level/generator/TheEnd.java new file mode 100644 index 00000000000..4b34327ee78 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/TheEnd.java @@ -0,0 +1,276 @@ +package cn.nukkit.level.generator; + +import cn.nukkit.block.Block; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.Level; +import cn.nukkit.level.biome.EnumBiome; +import cn.nukkit.level.format.generic.BaseFullChunk; +import cn.nukkit.math.NukkitMath; +import cn.nukkit.math.NukkitRandom; +import cn.nukkit.math.Vector3; +import it.unimi.dsi.fastutil.longs.Long2LongLinkedOpenHashMap; +import net.daporkchop.lib.common.ref.Ref; +import net.daporkchop.lib.common.ref.ThreadRef; +import net.daporkchop.lib.common.util.PValidation; +import net.daporkchop.lib.noise.NoiseSource; +import net.daporkchop.lib.noise.engine.PerlinNoiseEngine; +import net.daporkchop.lib.noise.engine.SimplexNoiseEngine; +import net.daporkchop.lib.noise.filter.ScaleOctavesOffsetFilter; +import net.daporkchop.lib.random.PRandom; + +import java.util.Collections; +import java.util.Map; +import java.util.Random; + +public class TheEnd extends Generator { + + private static final int STEP_X = 4; + private static final int STEP_Y = 8; + private static final int STEP_Z = STEP_X; + private static final int SAMPLES_X = 16 / STEP_X; + private static final int SAMPLES_Y = 256 / STEP_Y; + private static final int SAMPLES_Z = 16 / STEP_Z; + private static final int CACHE_X = SAMPLES_X + 1; + private static final int CACHE_Y = SAMPLES_Y + 1; + private static final int CACHE_Z = SAMPLES_Z + 1; + private static final double SCALE_X = 1.0d / STEP_X; + private static final double SCALE_Y = 1.0d / STEP_Y; + private static final double SCALE_Z = 1.0d / STEP_Z; + private static final double NOISE_SCALE_FACTOR = ((1 << 16) - 1.0d) / 512.0d; + private static final Ref THREAD_DATA_CACHE = ThreadRef.soft(ThreadData::new); + private static final double maxHeightCutoff = 56.0; + private static final double minHeightCutoff = 32.0; + + private ChunkManager level; + private ScaleOctavesOffsetFilter selector; + private ScaleOctavesOffsetFilter low; + private ScaleOctavesOffsetFilter high; + private IslandCache islands; + + public TheEnd() { + } + + public TheEnd(Map options) { + } + + @Override + public int getId() { + return Generator.TYPE_THE_END; + } + + @Override + public int getDimension() { + return Level.DIMENSION_THE_END; + } + + @Override + public ChunkManager getChunkManager() { + return level; + } + + @Override + public Map getSettings() { + return Collections.emptyMap(); + } + + @Override + public String getName() { + return "the_end"; + } + + @Override + public void init(ChunkManager level, NukkitRandom random) { + this.level = level; + this.selector = new ScaleOctavesOffsetFilter(new PerlinNoiseEngine(PRandom.wrap(new Random(this.level.getSeed()))), 0.008354638671875, 0.008354638671875, 0.008354638671875, 8, 12.75, 0.5); + this.low = new ScaleOctavesOffsetFilter(new PerlinNoiseEngine(PRandom.wrap(new Random(this.level.getSeed()))), 0.005221649169921875, 0.005221649169921875, 0.005221649169921875, 16, 1.0, 0); + this.high = new ScaleOctavesOffsetFilter(new PerlinNoiseEngine(PRandom.wrap(new Random(this.level.getSeed()))), 0.005221649169921875, 0.005221649169921875, 0.005221649169921875, 16, 1.0, 0); + + this.islands = new IslandCache(); + this.islands.init(PRandom.wrap(new Random(this.level.getSeed()))); + } + + @Override + public void generateChunk(int chunkX, int chunkZ) { + int baseX = chunkX << 4; + int baseZ = chunkZ << 4; + + BaseFullChunk chunk = level.getChunk(chunkX, chunkZ); + + for (int x = 0; x < 16; ++x) { + for (int z = 0; z < 16; ++z) { + chunk.setBiomeId(x, z, EnumBiome.END.biome.getId()); + } + } + + final ThreadData threadData = THREAD_DATA_CACHE.get(); + final double[] densityCache = threadData.densityCache = densityGet(threadData.densityCache, baseX, baseZ); + + for (int i = 0, sectionX = 0; sectionX < SAMPLES_X; sectionX++) { + for (int sectionZ = 0; sectionZ < SAMPLES_Z; sectionZ++) { + for (int sectionY = 0; sectionY < SAMPLES_Y; sectionY++, i++) { + double dxyz = densityCache[i]; + double dxYz = densityCache[i + 1]; + double dxyZ = densityCache[i + CACHE_Y]; + double dxYZ = densityCache[i + CACHE_Y + 1]; + double dXyz = densityCache[i + CACHE_Y * CACHE_Z]; + double dXYz = densityCache[i + CACHE_Y * CACHE_Z + 1]; + double dXyZ = densityCache[i + CACHE_Y * CACHE_Z + CACHE_Y]; + double dXYZ = densityCache[i + CACHE_Y * CACHE_Z + CACHE_Y + 1]; + + double bx00 = dxyz; + double bx01 = dxyZ; + double bx10 = dxYz; + double bx11 = dxYZ; + double gx00 = (dXyz - dxyz) * SCALE_X; + double gx01 = (dXyZ - dxyZ) * SCALE_X; + double gx10 = (dXYz - dxYz) * SCALE_X; + double gx11 = (dXYZ - dxYZ) * SCALE_X; + + for (int stepX = 0; stepX < STEP_X; stepX++) { + double ix00 = bx00 + gx00 * stepX; + double ix01 = bx01 + gx01 * stepX; + double ix10 = bx10 + gx10 * stepX; + double ix11 = bx11 + gx11 * stepX; + + double by0 = ix00; + double by1 = ix01; + double gy0 = (ix10 - ix00) * SCALE_Y; + double gy1 = (ix11 - ix01) * SCALE_Y; + + for (int stepY = 0; stepY < STEP_Y; stepY++) { + double iy0 = by0 + gy0 * stepY; + double iy1 = by1 + gy1 * stepY; + + double bz = iy0; + double gz = (iy1 - iy0) * SCALE_Z; + + for (int stepZ = 0; stepZ < STEP_Z; stepZ++) { + double iz = bz + gz * stepZ; + + int blockX = sectionX * STEP_X | stepX; + int blockY = sectionY * STEP_Y | stepY; + int blockZ = sectionZ * STEP_Z | stepZ; + + if (iz > 0.0d && blockY > 16) { // TODO: fix + chunk.setBlockId(blockX, blockY, blockZ, Block.END_STONE); + } + } + } + } + } + + i++; + } + + i += CACHE_Y; + } + } + + private double[] densityGet(double[] arr, int x, int z) { + int totalSize = PValidation.positive(CACHE_X) * PValidation.positive(CACHE_Y) * PValidation.positive(CACHE_Z) + PValidation.notNegative(0); + if (arr == null || arr.length < totalSize) { + arr = new double[totalSize]; + } + + for (int i = 0, dx = 0, xx = x; dx < CACHE_X; dx++, xx += STEP_X) { + for (int dz = 0, zz = z; dz < CACHE_Z; dz++, zz += STEP_Z) { + double islandNoise = this.islands.get(xx, zz) - 8.0d; + + for (int dy = 0, yy = 0; dy < CACHE_Y; dy++, yy += STEP_Y) { + double selector = NukkitMath.clamp(this.selector.get(xx, yy, (double) zz), 0.0d, 1.0d); + double low = this.low.get(xx, yy, (double) zz) * NOISE_SCALE_FACTOR; + double high = this.high.get(xx, yy, (double) zz) * NOISE_SCALE_FACTOR; + + arr[i++] = this.cutOff(yy, NukkitMath.lerp(low, high, selector) + islandNoise); + } + } + } + return arr; + } + + private double cutOff(double y, double noise) { + if (y > maxHeightCutoff) { + double factor = NukkitMath.clamp(((y * 0.125d) - (minHeightCutoff * 0.125d)) * 0.015625d, 0.0d, 1.0d); + return noise * (1.0d - factor) - 3000.0d * factor; + } else if (y < minHeightCutoff) { + if (y < 16) { + return 0.0d; + } + double factor = ((minHeightCutoff * 0.125d) - (y * 0.125d)) / ((minHeightCutoff * 0.125d) - 1.0d); + return noise * (1.0d - factor) - 30.0d * factor; + } else { + return noise; + } + } + + @Override + public void populateChunk(int chunkX, int chunkZ) { + } + + public Vector3 getSpawn() { + return new Vector3(100.5, 49, 0.5); + } + + private static final class ThreadData { + private double[] densityCache; + } + + private static class IslandCache { + + private static final long NaN = Double.doubleToRawLongBits(Double.NaN); + + private final Ref cacheCache = ThreadRef.soft(Long2LongLinkedOpenHashMap::new); + + private double get(int x, int z) { + Long2LongLinkedOpenHashMap cache = this.cacheCache.get(); + long val = cache.getOrDefault(Level.chunkHash(x, z), NaN); + if (val == NaN) { + if (cache.size() >= 1024) { + cache.removeFirstLong(); + } + + cache.put(Level.chunkHash(x, z), val = Double.doubleToRawLongBits(this.computeValue(x, z))); + } + return Double.longBitsToDouble(val); + } + + private NoiseSource island; + private NoiseSource weight; + + private void init(PRandom random) { + this.island = new ScaleOctavesOffsetFilter(new SimplexNoiseEngine(PRandom.wrap(new Random(random.nextLong()))), 1, 1, 1, 1, 1, 0); + this.weight = new ScaleOctavesOffsetFilter(new SimplexNoiseEngine(PRandom.wrap(new Random(random.nextLong()))), 1, 1, 1, 1, 6.5, 15.5); + } + + private double computeValue(int x, int z) { + final double islandRadius = 100.0; + final double outerIslandStartRadiusSq = (1024.0 / 16.0d) * (1024.0 / 16.0d); + final double outerIslandSeedThreshold = -0.8; + + final double chunkX = x >> 4; + final double chunkZ = z >> 4; + final double tileX = (x & 0xF) * 0.125d; + final double tileZ = (z & 0xF) * 0.125d; + + double val = islandRadius - Math.sqrt((x * 0.125d) * (x * 0.125d) + (z * 0.125d) * (z * 0.125d)) * 8.0d; + + for (int dx = -12; dx <= 12; dx++) { + for (int dz = -12; dz <= 12; dz++) { + double islandX = chunkX + dx; + double islandZ = chunkZ + dz; + + if (islandX * islandX + islandZ * islandZ > outerIslandStartRadiusSq && this.island.get(islandX, islandZ) < outerIslandSeedThreshold) { + double weight = this.weight.get(islandX, islandZ); + + double offsetX = tileX - dx * 2.0d; + double offsetZ = tileZ - dz * 2.0d; + + val = Math.max(val, islandRadius - Math.sqrt(offsetX * offsetX + offsetZ * offsetZ) * weight); + } + } + } + + return NukkitMath.clamp(val, -100.0d, 80.0d); + } + } +} diff --git a/src/main/java/cn/nukkit/level/generator/Void.java b/src/main/java/cn/nukkit/level/generator/Void.java new file mode 100644 index 00000000000..8a0979c476a --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/Void.java @@ -0,0 +1,57 @@ +package cn.nukkit.level.generator; + +import cn.nukkit.level.ChunkManager; +import cn.nukkit.math.NukkitRandom; +import cn.nukkit.math.Vector3; + +import java.util.Map; + +public class Void extends Generator { + + private ChunkManager level; + + public Void() { + //this(Collections.emptyMap()); + } + + public Void(Map options) { + } + + @Override + public int getId() { + return TYPE_VOID; + } + + @Override + public ChunkManager getChunkManager() { + return level; + } + + @Override + public void init(ChunkManager level, NukkitRandom random) { + this.level = level; + } + + @Override + public void generateChunk(int chX, int chZ) { + } + + @Override + public void populateChunk(int i, int i1) { + } + + @Override + public Map getSettings() { + return null; + } + + @Override + public String getName() { + return "void"; + } + + @Override + public Vector3 getSpawn() { + return new Vector3(0.5, 64, 0.5); + } +} diff --git a/src/main/java/cn/nukkit/level/generator/noise/nukkit/d/NoiseD.java b/src/main/java/cn/nukkit/level/generator/noise/Noise.java similarity index 97% rename from src/main/java/cn/nukkit/level/generator/noise/nukkit/d/NoiseD.java rename to src/main/java/cn/nukkit/level/generator/noise/Noise.java index 04b2c400c46..88ee18a49ff 100644 --- a/src/main/java/cn/nukkit/level/generator/noise/nukkit/d/NoiseD.java +++ b/src/main/java/cn/nukkit/level/generator/noise/Noise.java @@ -1,10 +1,10 @@ -package cn.nukkit.level.generator.noise.nukkit.d; +package cn.nukkit.level.generator.noise; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ -public abstract class NoiseD { +public abstract class Noise { protected int[] perm; protected double offsetX = 0; protected double offsetY = 0; diff --git a/src/main/java/cn/nukkit/level/generator/noise/nukkit/d/PerlinD.java b/src/main/java/cn/nukkit/level/generator/noise/Perlin.java similarity index 83% rename from src/main/java/cn/nukkit/level/generator/noise/nukkit/d/PerlinD.java rename to src/main/java/cn/nukkit/level/generator/noise/Perlin.java index 6989ea5bf3d..dbf8ad919f2 100644 --- a/src/main/java/cn/nukkit/level/generator/noise/nukkit/d/PerlinD.java +++ b/src/main/java/cn/nukkit/level/generator/noise/Perlin.java @@ -1,17 +1,23 @@ -package cn.nukkit.level.generator.noise.nukkit.d; +package cn.nukkit.level.generator.noise; import cn.nukkit.math.NukkitRandom; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ -public class PerlinD extends NoiseD { - public PerlinD(NukkitRandom random, double octaves, double persistence) { +public class Perlin extends Noise { + public static final int[][] grad3 = { + {1, 1, 0}, {-1, 1, 0}, {1, -1, 0}, {-1, -1, 0}, + {1, 0, 1}, {-1, 0, 1}, {1, 0, -1}, {-1, 0, -1}, + {0, 1, 1}, {0, -1, 1}, {0, 1, -1}, {0, -1, -1} + }; + + public Perlin(NukkitRandom random, double octaves, double persistence) { this(random, octaves, persistence, 1); } - public PerlinD(NukkitRandom random, double octaves, double persistence, double expansion) { + public Perlin(NukkitRandom random, double octaves, double persistence, double expansion) { this.octaves = octaves; this.persistence = persistence; this.expansion = expansion; diff --git a/src/main/java/cn/nukkit/level/generator/noise/nukkit/d/SimplexD.java b/src/main/java/cn/nukkit/level/generator/noise/Simplex.java similarity index 80% rename from src/main/java/cn/nukkit/level/generator/noise/nukkit/d/SimplexD.java rename to src/main/java/cn/nukkit/level/generator/noise/Simplex.java index 34f20ecddee..b2b8c73679f 100644 --- a/src/main/java/cn/nukkit/level/generator/noise/nukkit/d/SimplexD.java +++ b/src/main/java/cn/nukkit/level/generator/noise/Simplex.java @@ -1,12 +1,12 @@ -package cn.nukkit.level.generator.noise.nukkit.d; +package cn.nukkit.level.generator.noise; import cn.nukkit.math.NukkitRandom; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ -public class SimplexD extends PerlinD { +public class Simplex extends Perlin { protected static double SQRT_3; protected static double SQRT_5; protected static double F2; @@ -19,14 +19,26 @@ public class SimplexD extends PerlinD { protected static double G42; protected static double G43; protected static double G44; - public static final int[][] grad3 = { - {1, 1, 0}, {-1, 1, 0}, {1, -1, 0}, {-1, -1, 0}, - {1, 0, 1}, {-1, 0, 1}, {1, 0, -1}, {-1, 0, -1}, - {0, 1, 1}, {0, -1, 1}, {0, 1, -1}, {0, -1, -1} - }; + protected static final int[][] grad4 = {{0, 1, 1, 1}, {0, 1, 1, -1}, {0, 1, -1, 1}, {0, 1, -1, -1}, + {0, -1, 1, 1}, {0, -1, 1, -1}, {0, -1, -1, 1}, {0, -1, -1, -1}, + {1, 0, 1, 1}, {1, 0, 1, -1}, {1, 0, -1, 1}, {1, 0, -1, -1}, + {-1, 0, 1, 1}, {-1, 0, 1, -1}, {-1, 0, -1, 1}, {-1, 0, -1, -1}, + {1, 1, 0, 1}, {1, 1, 0, -1}, {1, -1, 0, 1}, {1, -1, 0, -1}, + {-1, 1, 0, 1}, {-1, 1, 0, -1}, {-1, -1, 0, 1}, {-1, -1, 0, -1}, + {1, 1, 1, 0}, {1, 1, -1, 0}, {1, -1, 1, 0}, {1, -1, -1, 0}, + {-1, 1, 1, 0}, {-1, 1, -1, 0}, {-1, -1, 1, 0}, {-1, -1, -1, 0}}; + protected static final int[][] simplex = { + {0, 1, 2, 3}, {0, 1, 3, 2}, {0, 0, 0, 0}, {0, 2, 3, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {1, 2, 3, 0}, + {0, 2, 1, 3}, {0, 0, 0, 0}, {0, 3, 1, 2}, {0, 3, 2, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {1, 3, 2, 0}, + {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, + {1, 2, 0, 3}, {0, 0, 0, 0}, {1, 3, 0, 2}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {2, 3, 0, 1}, {2, 3, 1, 0}, + {1, 0, 2, 3}, {1, 0, 3, 2}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {2, 0, 3, 1}, {0, 0, 0, 0}, {2, 1, 3, 0}, + {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, + {2, 0, 1, 3}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {3, 0, 1, 2}, {3, 0, 2, 1}, {0, 0, 0, 0}, {3, 1, 2, 0}, + {2, 1, 0, 3}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {3, 1, 0, 2}, {0, 0, 0, 0}, {3, 2, 0, 1}, {3, 2, 1, 0}}; protected final double offsetW; - public SimplexD(NukkitRandom random, double octaves, double persistence) { + public Simplex(NukkitRandom random, double octaves, double persistence) { super(random, octaves, persistence); this.offsetW = random.nextDouble() * 256; SQRT_3 = Math.sqrt(3); @@ -34,8 +46,8 @@ public SimplexD(NukkitRandom random, double octaves, double persistence) { F2 = 0.5 * (SQRT_3 - 1); G2 = (3 - SQRT_3) / 6; G22 = G2 * 2.0 - 1; - F3 = 1.0 / 3.0; - G3 = 1.0 / 6.0; + F3 = 0.3333333333333333; + G3 = 0.16666666666666666; F4 = (SQRT_5 - 1.0) / 4.0; G4 = (5.0 - SQRT_5) / 20.0; G42 = G4 * 2.0; @@ -43,7 +55,7 @@ public SimplexD(NukkitRandom random, double octaves, double persistence) { G44 = G4 * 4.0 - 1.0; } - public SimplexD(NukkitRandom random, double octaves, double persistence, double expansion) { + public Simplex(NukkitRandom random, double octaves, double persistence, double expansion) { super(random, octaves, persistence, expansion); this.offsetW = random.nextDouble() * 256; SQRT_3 = Math.sqrt(3); @@ -51,8 +63,8 @@ public SimplexD(NukkitRandom random, double octaves, double persistence, double F2 = 0.5 * (SQRT_3 - 1); G2 = (3 - SQRT_3) / 6; G22 = G2 * 2.0 - 1; - F3 = 1.0 / 3.0; - G3 = 1.0 / 6.0; + F3 = 0.3333333333333333; + G3 = 0.16666666666666666; F4 = (SQRT_5 - 1.0) / 4.0; G4 = (5.0 - SQRT_5) / 20.0; G42 = G4 * 2.0; diff --git a/src/main/java/cn/nukkit/level/generator/noise/nukkit/f/NoiseF.java b/src/main/java/cn/nukkit/level/generator/noise/nukkit/f/NoiseF.java index ff0cc7146c1..5fe0f025c00 100644 --- a/src/main/java/cn/nukkit/level/generator/noise/nukkit/f/NoiseF.java +++ b/src/main/java/cn/nukkit/level/generator/noise/nukkit/f/NoiseF.java @@ -1,7 +1,7 @@ package cn.nukkit.level.generator.noise.nukkit.f; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public abstract class NoiseF { diff --git a/src/main/java/cn/nukkit/level/generator/noise/nukkit/f/PerlinF.java b/src/main/java/cn/nukkit/level/generator/noise/nukkit/f/PerlinF.java index 491778ffd06..50c09297935 100644 --- a/src/main/java/cn/nukkit/level/generator/noise/nukkit/f/PerlinF.java +++ b/src/main/java/cn/nukkit/level/generator/noise/nukkit/f/PerlinF.java @@ -3,7 +3,7 @@ import cn.nukkit.math.NukkitRandom; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class PerlinF extends NoiseF { diff --git a/src/main/java/cn/nukkit/level/generator/noise/nukkit/f/SimplexF.java b/src/main/java/cn/nukkit/level/generator/noise/nukkit/f/SimplexF.java index bfb15848cc0..960e82d553b 100644 --- a/src/main/java/cn/nukkit/level/generator/noise/nukkit/f/SimplexF.java +++ b/src/main/java/cn/nukkit/level/generator/noise/nukkit/f/SimplexF.java @@ -3,7 +3,7 @@ import cn.nukkit.math.NukkitRandom; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class SimplexF extends PerlinF { diff --git a/src/main/java/cn/nukkit/level/generator/noise/vanilla/d/NoiseGeneratorImprovedD.java b/src/main/java/cn/nukkit/level/generator/noise/vanilla/d/NoiseGeneratorImprovedD.java deleted file mode 100644 index 6ac9aa097c3..00000000000 --- a/src/main/java/cn/nukkit/level/generator/noise/vanilla/d/NoiseGeneratorImprovedD.java +++ /dev/null @@ -1,177 +0,0 @@ -package cn.nukkit.level.generator.noise.vanilla.d; - -import cn.nukkit.math.NukkitRandom; - -public class NoiseGeneratorImprovedD { - private static final double[] GRAD_X = new double[]{1.0D, -1.0D, 1.0D, -1.0D, 1.0D, -1.0D, 1.0D, -1.0D, 0.0D, 0.0D, 0.0D, 0.0D, 1.0D, 0.0D, -1.0D, 0.0D}; - private static final double[] GRAD_Y = new double[]{1.0D, 1.0D, -1.0D, -1.0D, 0.0D, 0.0D, 0.0D, 0.0D, 1.0D, -1.0D, 1.0D, -1.0D, 1.0D, -1.0D, 1.0D, -1.0D}; - private static final double[] GRAD_Z = new double[]{0.0D, 0.0D, 0.0D, 0.0D, 1.0D, 1.0D, -1.0D, -1.0D, 1.0D, 1.0D, -1.0D, -1.0D, 0.0D, 1.0D, 0.0D, -1.0D}; - private static final double[] GRAD_2X = new double[]{1.0D, -1.0D, 1.0D, -1.0D, 1.0D, -1.0D, 1.0D, -1.0D, 0.0D, 0.0D, 0.0D, 0.0D, 1.0D, 0.0D, -1.0D, 0.0D}; - private static final double[] GRAD_2Z = new double[]{0.0D, 0.0D, 0.0D, 0.0D, 1.0D, 1.0D, -1.0D, -1.0D, 1.0D, 1.0D, -1.0D, -1.0D, 0.0D, 1.0D, 0.0D, -1.0D}; - private final int[] permutations; - public double xCoord; - public double yCoord; - public double zCoord; - - public NoiseGeneratorImprovedD() { - this(new NukkitRandom(System.currentTimeMillis())); - } - - public NoiseGeneratorImprovedD(NukkitRandom random) { - this.permutations = new int[512]; - this.xCoord = random.nextDouble() * 256.0D; - this.yCoord = random.nextDouble() * 256.0D; - this.zCoord = random.nextDouble() * 256.0D; - - int i = 0; - while (i < 256) { - this.permutations[i] = i++; - } - - for (int l = 0; l < 256; ++l) { - int j = random.nextBoundedInt(256 - l) + l; - int k = this.permutations[l]; - this.permutations[l] = this.permutations[j]; - this.permutations[j] = k; - this.permutations[l + 256] = this.permutations[l]; - } - } - - public final double lerp(double p_76311_1_, double p_76311_3_, double p_76311_5_) { - return p_76311_3_ + p_76311_1_ * (p_76311_5_ - p_76311_3_); - } - - public final double grad2(int p_76309_1_, double p_76309_2_, double p_76309_4_) { - int i = p_76309_1_ & 15; - return GRAD_2X[i] * p_76309_2_ + GRAD_2Z[i] * p_76309_4_; - } - - public final double grad(int p_76310_1_, double p_76310_2_, double p_76310_4_, double p_76310_6_) { - int i = p_76310_1_ & 15; - return GRAD_X[i] * p_76310_2_ + GRAD_Y[i] * p_76310_4_ + GRAD_Z[i] * p_76310_6_; - } - - /* - * noiseArray should be xSize*ySize*zSize in size - */ - public void populateNoiseArray(double[] noiseArray, double xOffset, double yOffset, double zOffset, int xSize, int ySize, int zSize, double xScale, double yScale, double zScale, double noiseScale) { - if (ySize == 1) { - int i5 = 0; - int j5 = 0; - int j = 0; - int k5 = 0; - double d14 = 0.0D; - double d15 = 0.0D; - int l5 = 0; - double d16 = 1.0D / noiseScale; - - for (int j2 = 0; j2 < xSize; ++j2) { - double d17 = xOffset + (double) j2 * xScale + this.xCoord; - int i6 = (int) d17; - - if (d17 < (double) i6) { - --i6; - } - - int k2 = i6 & 255; - d17 = d17 - (double) i6; - double d18 = d17 * d17 * d17 * (d17 * (d17 * 6.0D - 15.0D) + 10.0D); - - for (int j6 = 0; j6 < zSize; ++j6) { - double d19 = zOffset + (double) j6 * zScale + this.zCoord; - int k6 = (int) d19; - - if (d19 < (double) k6) { - --k6; - } - - int l6 = k6 & 255; - d19 = d19 - (double) k6; - double d20 = d19 * d19 * d19 * (d19 * (d19 * 6.0D - 15.0D) + 10.0D); - i5 = this.permutations[k2]; - j5 = this.permutations[i5] + l6; - j = this.permutations[k2 + 1]; - k5 = this.permutations[j] + l6; - d14 = this.lerp(d18, this.grad2(this.permutations[j5], d17, d19), this.grad(this.permutations[k5], d17 - 1.0D, 0.0D, d19)); - d15 = this.lerp(d18, this.grad(this.permutations[j5 + 1], d17, 0.0D, d19 - 1.0D), this.grad(this.permutations[k5 + 1], d17 - 1.0D, 0.0D, d19 - 1.0D)); - double d21 = this.lerp(d20, d14, d15); - int i7 = l5++; - noiseArray[i7] += d21 * d16; - } - } - } else { - int i = 0; - double d0 = 1.0D / noiseScale; - int k = -1; - int l = 0; - int i1 = 0; - int j1 = 0; - int k1 = 0; - int l1 = 0; - int i2 = 0; - double d1 = 0.0D; - double d2 = 0.0D; - double d3 = 0.0D; - double d4 = 0.0D; - - for (int l2 = 0; l2 < xSize; ++l2) { - double d5 = xOffset + (double) l2 * xScale + this.xCoord; - int i3 = (int) d5; - - if (d5 < (double) i3) { - --i3; - } - - int j3 = i3 & 255; - d5 = d5 - (double) i3; - double d6 = d5 * d5 * d5 * (d5 * (d5 * 6.0D - 15.0D) + 10.0D); - - for (int k3 = 0; k3 < zSize; ++k3) { - double d7 = zOffset + (double) k3 * zScale + this.zCoord; - int l3 = (int) d7; - - if (d7 < (double) l3) { - --l3; - } - - int i4 = l3 & 255; - d7 = d7 - (double) l3; - double d8 = d7 * d7 * d7 * (d7 * (d7 * 6.0D - 15.0D) + 10.0D); - - for (int j4 = 0; j4 < ySize; ++j4) { - double d9 = yOffset + (double) j4 * yScale + this.yCoord; - int k4 = (int) d9; - - if (d9 < (double) k4) { - --k4; - } - - int l4 = k4 & 255; - d9 = d9 - (double) k4; - double d10 = d9 * d9 * d9 * (d9 * (d9 * 6.0D - 15.0D) + 10.0D); - - if (j4 == 0 || l4 != k) { - k = l4; - l = this.permutations[j3] + l4; - i1 = this.permutations[l] + i4; - j1 = this.permutations[l + 1] + i4; - k1 = this.permutations[j3 + 1] + l4; - l1 = this.permutations[k1] + i4; - i2 = this.permutations[k1 + 1] + i4; - d1 = this.lerp(d6, this.grad(this.permutations[i1], d5, d9, d7), this.grad(this.permutations[l1], d5 - 1.0D, d9, d7)); - d2 = this.lerp(d6, this.grad(this.permutations[j1], d5, d9 - 1.0D, d7), this.grad(this.permutations[i2], d5 - 1.0D, d9 - 1.0D, d7)); - d3 = this.lerp(d6, this.grad(this.permutations[i1 + 1], d5, d9, d7 - 1.0D), this.grad(this.permutations[l1 + 1], d5 - 1.0D, d9, d7 - 1.0D)); - d4 = this.lerp(d6, this.grad(this.permutations[j1 + 1], d5, d9 - 1.0D, d7 - 1.0D), this.grad(this.permutations[i2 + 1], d5 - 1.0D, d9 - 1.0D, d7 - 1.0D)); - } - - double d11 = this.lerp(d10, d1, d2); - double d12 = this.lerp(d10, d3, d4); - double d13 = this.lerp(d8, d11, d12); - int j7 = i++; - noiseArray[j7] += d13 * d0; - } - } - } - } - } -} diff --git a/src/main/java/cn/nukkit/level/generator/noise/vanilla/d/NoiseGeneratorOctavesD.java b/src/main/java/cn/nukkit/level/generator/noise/vanilla/d/NoiseGeneratorOctavesD.java deleted file mode 100644 index 76d10f240c6..00000000000 --- a/src/main/java/cn/nukkit/level/generator/noise/vanilla/d/NoiseGeneratorOctavesD.java +++ /dev/null @@ -1,62 +0,0 @@ -package cn.nukkit.level.generator.noise.vanilla.d; - -import cn.nukkit.math.MathHelper; -import cn.nukkit.math.NukkitRandom; - -public class NoiseGeneratorOctavesD { - /** - * Collection of noise generation functions. Output is combined to produce different octaves of noise. - */ - private final NoiseGeneratorImprovedD[] generatorCollection; - private final int octaves; - - public NoiseGeneratorOctavesD(NukkitRandom seed, int octavesIn) { - this.octaves = octavesIn; - this.generatorCollection = new NoiseGeneratorImprovedD[octavesIn]; - - for (int i = 0; i < octavesIn; ++i) { - this.generatorCollection[i] = new NoiseGeneratorImprovedD(seed); - } - } - - /* - * pars:(par2,3,4=noiseOffset ; so that adjacent noise segments connect) (pars5,6,7=x,y,zArraySize),(pars8,10,12 = - * x,y,z noiseScale) - */ - public double[] generateNoiseOctaves(double[] noiseArray, int xOffset, int yOffset, int zOffset, int xSize, int ySize, int zSize, double xScale, double yScale, double zScale) { - if (noiseArray == null) { - noiseArray = new double[xSize * ySize * zSize]; - } else { - for (int i = 0; i < noiseArray.length; ++i) { - noiseArray[i] = 0.0D; - } - } - - double d3 = 1.0D; - - for (int j = 0; j < this.octaves; ++j) { - double d0 = (double) xOffset * d3 * xScale; - double d1 = (double) yOffset * d3 * yScale; - double d2 = (double) zOffset * d3 * zScale; - long k = MathHelper.floor_double_long(d0); - long l = MathHelper.floor_double_long(d2); - d0 = d0 - (double) k; - d2 = d2 - (double) l; - k = k % 16777216L; - l = l % 16777216L; - d0 = d0 + (double) k; - d2 = d2 + (double) l; - this.generatorCollection[j].populateNoiseArray(noiseArray, d0, d1, d2, xSize, ySize, zSize, xScale * d3, yScale * d3, zScale * d3, d3); - d3 /= 2.0D; - } - - return noiseArray; - } - - /* - * Bouncer function to the main one with some default arguments. - */ - public double[] generateNoiseOctaves(double[] noiseArray, int xOffset, int zOffset, int xSize, int zSize, double xScale, double zScale, double p_76305_10_) { - return this.generateNoiseOctaves(noiseArray, xOffset, 10, zOffset, xSize, 1, zSize, xScale, 1.0D, zScale); - } -} diff --git a/src/main/java/cn/nukkit/level/generator/noise/vanilla/d/NoiseGeneratorPerlinD.java b/src/main/java/cn/nukkit/level/generator/noise/vanilla/d/NoiseGeneratorPerlinD.java deleted file mode 100644 index 6bf2f310f57..00000000000 --- a/src/main/java/cn/nukkit/level/generator/noise/vanilla/d/NoiseGeneratorPerlinD.java +++ /dev/null @@ -1,54 +0,0 @@ -package cn.nukkit.level.generator.noise.vanilla.d; - -import cn.nukkit.math.NukkitRandom; - -public class NoiseGeneratorPerlinD { - private final NoiseGeneratorSimplexD[] noiseLevels; - private final int levels; - - public NoiseGeneratorPerlinD(NukkitRandom p_i45470_1_, int p_i45470_2_) { - this.levels = p_i45470_2_; - this.noiseLevels = new NoiseGeneratorSimplexD[p_i45470_2_]; - - for (int i = 0; i < p_i45470_2_; ++i) { - this.noiseLevels[i] = new NoiseGeneratorSimplexD(p_i45470_1_); - } - } - - public double getValue(double p_151601_1_, double p_151601_3_) { - double d0 = 0.0D; - double d1 = 1.0D; - - for (int i = 0; i < this.levels; ++i) { - d0 += this.noiseLevels[i].getValue(p_151601_1_ * d1, p_151601_3_ * d1) / d1; - d1 /= 2.0D; - } - - return d0; - } - - public double[] getRegion(double[] p_151599_1_, double p_151599_2_, double p_151599_4_, int p_151599_6_, int p_151599_7_, double p_151599_8_, double p_151599_10_, double p_151599_12_) { - return this.getRegion(p_151599_1_, p_151599_2_, p_151599_4_, p_151599_6_, p_151599_7_, p_151599_8_, p_151599_10_, p_151599_12_, 0.5D); - } - - public double[] getRegion(double[] p_151600_1_, double p_151600_2_, double p_151600_4_, int p_151600_6_, int p_151600_7_, double p_151600_8_, double p_151600_10_, double p_151600_12_, double p_151600_14_) { - if (p_151600_1_ != null && p_151600_1_.length >= p_151600_6_ * p_151600_7_) { - for (int i = 0; i < p_151600_1_.length; ++i) { - p_151600_1_[i] = 0.0D; - } - } else { - p_151600_1_ = new double[p_151600_6_ * p_151600_7_]; - } - - double d1 = 1.0D; - double d0 = 1.0D; - - for (int j = 0; j < this.levels; ++j) { - this.noiseLevels[j].add(p_151600_1_, p_151600_2_, p_151600_4_, p_151600_6_, p_151600_7_, p_151600_8_ * d0 * d1, p_151600_10_ * d0 * d1, 0.55D / d1); - d0 *= p_151600_12_; - d1 *= p_151600_14_; - } - - return p_151600_1_; - } -} diff --git a/src/main/java/cn/nukkit/level/generator/noise/vanilla/d/NoiseGeneratorSimplexD.java b/src/main/java/cn/nukkit/level/generator/noise/vanilla/d/NoiseGeneratorSimplexD.java deleted file mode 100644 index 78ca1ecbf1d..00000000000 --- a/src/main/java/cn/nukkit/level/generator/noise/vanilla/d/NoiseGeneratorSimplexD.java +++ /dev/null @@ -1,182 +0,0 @@ -package cn.nukkit.level.generator.noise.vanilla.d; - -import cn.nukkit.math.NukkitRandom; - -public class NoiseGeneratorSimplexD { - public static final double SQRT_3 = Math.sqrt(3.0D); - private static final int[][] grad3 = new int[][]{{1, 1, 0}, {-1, 1, 0}, {1, -1, 0}, {-1, -1, 0}, {1, 0, 1}, {-1, 0, 1}, {1, 0, -1}, {-1, 0, -1}, {0, 1, 1}, {0, -1, 1}, {0, 1, -1}, {0, -1, -1}}; - private static final double F2 = 0.5D * (SQRT_3 - 1.0D); - private static final double G2 = (3.0D - SQRT_3) / 6.0D; - private final int[] p; - public double xo; - public double yo; - public double zo; - - public NoiseGeneratorSimplexD() { - this(new NukkitRandom(System.currentTimeMillis())); - } - - public NoiseGeneratorSimplexD(NukkitRandom p_i45471_1_) { - this.p = new int[512]; - this.xo = p_i45471_1_.nextDouble() * 256.0D; - this.yo = p_i45471_1_.nextDouble() * 256.0D; - this.zo = p_i45471_1_.nextDouble() * 256.0D; - - int i = 0; - while (i < 256) { - this.p[i] = i++; - } - - for (int l = 0; l < 256; ++l) { - int j = p_i45471_1_.nextBoundedInt(256 - l) + l; - int k = this.p[l]; - this.p[l] = this.p[j]; - this.p[j] = k; - this.p[l + 256] = this.p[l]; - } - } - - private static int fastFloor(double value) { - return value > 0.0D ? (int) value : (int) value - 1; - } - - private static double dot(int[] p_151604_0_, double p_151604_1_, double p_151604_3_) { - return (double) p_151604_0_[0] * p_151604_1_ + (double) p_151604_0_[1] * p_151604_3_; - } - - public double getValue(double p_151605_1_, double p_151605_3_) { - double d3 = 0.5D * (SQRT_3 - 1.0D); - double d4 = (p_151605_1_ + p_151605_3_) * d3; - int i = fastFloor(p_151605_1_ + d4); - int j = fastFloor(p_151605_3_ + d4); - double d5 = (3.0D - SQRT_3) / 6.0D; - double d6 = (double) (i + j) * d5; - double d7 = (double) i - d6; - double d8 = (double) j - d6; - double d9 = p_151605_1_ - d7; - double d10 = p_151605_3_ - d8; - int k; - int l; - - if (d9 > d10) { - k = 1; - l = 0; - } else { - k = 0; - l = 1; - } - - double d11 = d9 - (double) k + d5; - double d12 = d10 - (double) l + d5; - double d13 = d9 - 1.0D + 2.0D * d5; - double d14 = d10 - 1.0D + 2.0D * d5; - int i1 = i & 255; - int j1 = j & 255; - int k1 = this.p[i1 + this.p[j1]] % 12; - int l1 = this.p[i1 + k + this.p[j1 + l]] % 12; - int i2 = this.p[i1 + 1 + this.p[j1 + 1]] % 12; - double d15 = 0.5D - d9 * d9 - d10 * d10; - double d0; - - if (d15 < 0.0D) { - d0 = 0.0D; - } else { - d15 = d15 * d15; - d0 = d15 * d15 * dot(grad3[k1], d9, d10); - } - - double d16 = 0.5D - d11 * d11 - d12 * d12; - double d1; - - if (d16 < 0.0D) { - d1 = 0.0D; - } else { - d16 = d16 * d16; - d1 = d16 * d16 * dot(grad3[l1], d11, d12); - } - - double d17 = 0.5D - d13 * d13 - d14 * d14; - double d2; - - if (d17 < 0.0D) { - d2 = 0.0D; - } else { - d17 = d17 * d17; - d2 = d17 * d17 * dot(grad3[i2], d13, d14); - } - - return 70.0D * (d0 + d1 + d2); - } - - public void add(double[] p_151606_1_, double p_151606_2_, double p_151606_4_, int p_151606_6_, int p_151606_7_, double p_151606_8_, double p_151606_10_, double p_151606_12_) { - int i = 0; - - for (int j = 0; j < p_151606_7_; ++j) { - double d0 = (p_151606_4_ + (double) j) * p_151606_10_ + this.yo; - - for (int k = 0; k < p_151606_6_; ++k) { - double d1 = (p_151606_2_ + (double) k) * p_151606_8_ + this.xo; - double d5 = (d1 + d0) * F2; - int l = fastFloor(d1 + d5); - int i1 = fastFloor(d0 + d5); - double d6 = (double) (l + i1) * G2; - double d7 = (double) l - d6; - double d8 = (double) i1 - d6; - double d9 = d1 - d7; - double d10 = d0 - d8; - int j1; - int k1; - - if (d9 > d10) { - j1 = 1; - k1 = 0; - } else { - j1 = 0; - k1 = 1; - } - - double d11 = d9 - (double) j1 + G2; - double d12 = d10 - (double) k1 + G2; - double d13 = d9 - 1.0D + 2.0D * G2; - double d14 = d10 - 1.0D + 2.0D * G2; - int l1 = l & 255; - int i2 = i1 & 255; - int j2 = this.p[l1 + this.p[i2]] % 12; - int k2 = this.p[l1 + j1 + this.p[i2 + k1]] % 12; - int l2 = this.p[l1 + 1 + this.p[i2 + 1]] % 12; - double d15 = 0.5D - d9 * d9 - d10 * d10; - double d2; - - if (d15 < 0.0D) { - d2 = 0.0D; - } else { - d15 = d15 * d15; - d2 = d15 * d15 * dot(grad3[j2], d9, d10); - } - - double d16 = 0.5D - d11 * d11 - d12 * d12; - double d3; - - if (d16 < 0.0D) { - d3 = 0.0D; - } else { - d16 = d16 * d16; - d3 = d16 * d16 * dot(grad3[k2], d11, d12); - } - - double d17 = 0.5D - d13 * d13 - d14 * d14; - double d4; - - if (d17 < 0.0D) { - d4 = 0.0D; - } else { - d17 = d17 * d17; - d4 = d17 * d17 * dot(grad3[l2], d13, d14); - } - - int i3 = i++; - p_151606_1_[i3] += 70.0D * (d2 + d3 + d4) * p_151606_12_; - } - } - } -} diff --git a/src/main/java/cn/nukkit/level/generator/noise/vanilla/f/NoiseGeneratorImprovedF.java b/src/main/java/cn/nukkit/level/generator/noise/vanilla/f/NoiseGeneratorImprovedF.java index 954a3da6d12..10cd733a8ba 100644 --- a/src/main/java/cn/nukkit/level/generator/noise/vanilla/f/NoiseGeneratorImprovedF.java +++ b/src/main/java/cn/nukkit/level/generator/noise/vanilla/f/NoiseGeneratorImprovedF.java @@ -3,11 +3,11 @@ import cn.nukkit.math.NukkitRandom; public class NoiseGeneratorImprovedF { - private static final float[] GRAD_X = new float[]{1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f}; - private static final float[] GRAD_Y = new float[]{1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f}; - private static final float[] GRAD_Z = new float[]{0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 1.0f, 0.0f, -1.0f}; - private static final float[] GRAD_2X = new float[]{1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f}; - private static final float[] GRAD_2Z = new float[]{0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 1.0f, 0.0f, -1.0f}; + private static final float[] GRAD_X = {1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f}; + private static final float[] GRAD_Y = {1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f}; + private static final float[] GRAD_Z = {0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 1.0f, 0.0f, -1.0f}; + private static final float[] GRAD_2X = {1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f}; + private static final float[] GRAD_2Z = {0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 1.0f, 0.0f, -1.0f}; private final int[] permutations; public float xCoord; public float yCoord; diff --git a/src/main/java/cn/nukkit/level/generator/noise/vanilla/f/NoiseGeneratorOctavesF.java b/src/main/java/cn/nukkit/level/generator/noise/vanilla/f/NoiseGeneratorOctavesF.java index 605fc378dfb..d01b0f256e3 100644 --- a/src/main/java/cn/nukkit/level/generator/noise/vanilla/f/NoiseGeneratorOctavesF.java +++ b/src/main/java/cn/nukkit/level/generator/noise/vanilla/f/NoiseGeneratorOctavesF.java @@ -3,6 +3,8 @@ import cn.nukkit.math.MathHelper; import cn.nukkit.math.NukkitRandom; +import java.util.Arrays; + public class NoiseGeneratorOctavesF { /** * Collection of noise generation functions. Output is combined to produce different octaves of noise. @@ -27,9 +29,7 @@ public float[] generateNoiseOctaves(float[] noiseArray, int xOffset, int yOffset if (noiseArray == null) { noiseArray = new float[xSize * ySize * zSize]; } else { - for (int i = 0; i < noiseArray.length; ++i) { - noiseArray[i] = 0.0f; - } + Arrays.fill(noiseArray, 0.0f); } float d3 = 1.0f; diff --git a/src/main/java/cn/nukkit/level/generator/noise/vanilla/f/NoiseGeneratorPerlinF.java b/src/main/java/cn/nukkit/level/generator/noise/vanilla/f/NoiseGeneratorPerlinF.java deleted file mode 100644 index 947bf5b6533..00000000000 --- a/src/main/java/cn/nukkit/level/generator/noise/vanilla/f/NoiseGeneratorPerlinF.java +++ /dev/null @@ -1,54 +0,0 @@ -package cn.nukkit.level.generator.noise.vanilla.f; - -import cn.nukkit.math.NukkitRandom; - -public class NoiseGeneratorPerlinF { - private final NoiseGeneratorSimplexF[] noiseLevels; - private final int levels; - - public NoiseGeneratorPerlinF(NukkitRandom p_i45470_1_, int p_i45470_2_) { - this.levels = p_i45470_2_; - this.noiseLevels = new NoiseGeneratorSimplexF[p_i45470_2_]; - - for (int i = 0; i < p_i45470_2_; ++i) { - this.noiseLevels[i] = new NoiseGeneratorSimplexF(p_i45470_1_); - } - } - - public float getValue(float p_151601_1_, float p_151601_3_) { - float d0 = 0.0f; - float d1 = 1.0f; - - for (int i = 0; i < this.levels; ++i) { - d0 += this.noiseLevels[i].getValue(p_151601_1_ * d1, p_151601_3_ * d1) / d1; - d1 /= 2.0f; - } - - return d0; - } - - public float[] getRegion(float[] p_151599_1_, float p_151599_2_, float p_151599_4_, int p_151599_6_, int p_151599_7_, float p_151599_8_, float p_151599_10_, float p_151599_12_) { - return this.getRegion(p_151599_1_, p_151599_2_, p_151599_4_, p_151599_6_, p_151599_7_, p_151599_8_, p_151599_10_, p_151599_12_, 0.5f); - } - - public float[] getRegion(float[] p_151600_1_, float p_151600_2_, float p_151600_4_, int p_151600_6_, int p_151600_7_, float p_151600_8_, float p_151600_10_, float p_151600_12_, float p_151600_14_) { - if (p_151600_1_ != null && p_151600_1_.length >= p_151600_6_ * p_151600_7_) { - for (int i = 0; i < p_151600_1_.length; ++i) { - p_151600_1_[i] = 0.0f; - } - } else { - p_151600_1_ = new float[p_151600_6_ * p_151600_7_]; - } - - float d1 = 1.0f; - float d0 = 1.0f; - - for (int j = 0; j < this.levels; ++j) { - this.noiseLevels[j].add(p_151600_1_, p_151600_2_, p_151600_4_, p_151600_6_, p_151600_7_, p_151600_8_ * d0 * d1, p_151600_10_ * d0 * d1, 0.55f / d1); - d0 *= p_151600_12_; - d1 *= p_151600_14_; - } - - return p_151600_1_; - } -} diff --git a/src/main/java/cn/nukkit/level/generator/noise/vanilla/f/NoiseGeneratorSimplexF.java b/src/main/java/cn/nukkit/level/generator/noise/vanilla/f/NoiseGeneratorSimplexF.java deleted file mode 100644 index d55d59e4105..00000000000 --- a/src/main/java/cn/nukkit/level/generator/noise/vanilla/f/NoiseGeneratorSimplexF.java +++ /dev/null @@ -1,182 +0,0 @@ -package cn.nukkit.level.generator.noise.vanilla.f; - -import cn.nukkit.math.NukkitRandom; - -public class NoiseGeneratorSimplexF { - public static final float SQRT_3 = (float) Math.sqrt(3.0f); - private static final int[][] grad3 = new int[][]{{1, 1, 0}, {-1, 1, 0}, {1, -1, 0}, {-1, -1, 0}, {1, 0, 1}, {-1, 0, 1}, {1, 0, -1}, {-1, 0, -1}, {0, 1, 1}, {0, -1, 1}, {0, 1, -1}, {0, -1, -1}}; - private static final float F2 = 0.5f * (SQRT_3 - 1.0f); - private static final float G2 = (3.0f - SQRT_3) / 6.0f; - private final int[] p; - public float xo; - public float yo; - public float zo; - - public NoiseGeneratorSimplexF() { - this(new NukkitRandom(System.currentTimeMillis())); - } - - public NoiseGeneratorSimplexF(NukkitRandom p_i45471_1_) { - this.p = new int[512]; - this.xo = p_i45471_1_.nextFloat() * 256.0f; - this.yo = p_i45471_1_.nextFloat() * 256.0f; - this.zo = p_i45471_1_.nextFloat() * 256.0f; - - int i = 0; - while (i < 256) { - this.p[i] = i++; - } - - for (int l = 0; l < 256; ++l) { - int j = p_i45471_1_.nextBoundedInt(256 - l) + l; - int k = this.p[l]; - this.p[l] = this.p[j]; - this.p[j] = k; - this.p[l + 256] = this.p[l]; - } - } - - private static int fastFloor(float value) { - return value > 0.0f ? (int) value : (int) value - 1; - } - - private static float dot(int[] p_151604_0_, float p_151604_1_, float p_151604_3_) { - return (float) p_151604_0_[0] * p_151604_1_ + (float) p_151604_0_[1] * p_151604_3_; - } - - public float getValue(float p_151605_1_, float p_151605_3_) { - float d3 = 0.5f * (SQRT_3 - 1.0f); - float d4 = (p_151605_1_ + p_151605_3_) * d3; - int i = fastFloor(p_151605_1_ + d4); - int j = fastFloor(p_151605_3_ + d4); - float d5 = (3.0f - SQRT_3) / 6.0f; - float d6 = (float) (i + j) * d5; - float d7 = (float) i - d6; - float d8 = (float) j - d6; - float d9 = p_151605_1_ - d7; - float d10 = p_151605_3_ - d8; - int k; - int l; - - if (d9 > d10) { - k = 1; - l = 0; - } else { - k = 0; - l = 1; - } - - float d11 = d9 - (float) k + d5; - float d12 = d10 - (float) l + d5; - float d13 = d9 - 1.0f + 2.0f * d5; - float d14 = d10 - 1.0f + 2.0f * d5; - int i1 = i & 255; - int j1 = j & 255; - int k1 = this.p[i1 + this.p[j1]] % 12; - int l1 = this.p[i1 + k + this.p[j1 + l]] % 12; - int i2 = this.p[i1 + 1 + this.p[j1 + 1]] % 12; - float d15 = 0.5f - d9 * d9 - d10 * d10; - float d0; - - if (d15 < 0.0f) { - d0 = 0.0f; - } else { - d15 = d15 * d15; - d0 = d15 * d15 * dot(grad3[k1], d9, d10); - } - - float d16 = 0.5f - d11 * d11 - d12 * d12; - float d1; - - if (d16 < 0.0f) { - d1 = 0.0f; - } else { - d16 = d16 * d16; - d1 = d16 * d16 * dot(grad3[l1], d11, d12); - } - - float d17 = 0.5f - d13 * d13 - d14 * d14; - float d2; - - if (d17 < 0.0f) { - d2 = 0.0f; - } else { - d17 = d17 * d17; - d2 = d17 * d17 * dot(grad3[i2], d13, d14); - } - - return 70.0f * (d0 + d1 + d2); - } - - public void add(float[] p_151606_1_, float p_151606_2_, float p_151606_4_, int p_151606_6_, int p_151606_7_, float p_151606_8_, float p_151606_10_, float p_151606_12_) { - int i = 0; - - for (int j = 0; j < p_151606_7_; ++j) { - float d0 = (p_151606_4_ + (float) j) * p_151606_10_ + this.yo; - - for (int k = 0; k < p_151606_6_; ++k) { - float d1 = (p_151606_2_ + (float) k) * p_151606_8_ + this.xo; - float d5 = (d1 + d0) * F2; - int l = fastFloor(d1 + d5); - int i1 = fastFloor(d0 + d5); - float d6 = (float) (l + i1) * G2; - float d7 = (float) l - d6; - float d8 = (float) i1 - d6; - float d9 = d1 - d7; - float d10 = d0 - d8; - int j1; - int k1; - - if (d9 > d10) { - j1 = 1; - k1 = 0; - } else { - j1 = 0; - k1 = 1; - } - - float d11 = d9 - (float) j1 + G2; - float d12 = d10 - (float) k1 + G2; - float d13 = d9 - 1.0f + 2.0f * G2; - float d14 = d10 - 1.0f + 2.0f * G2; - int l1 = l & 255; - int i2 = i1 & 255; - int j2 = this.p[l1 + this.p[i2]] % 12; - int k2 = this.p[l1 + j1 + this.p[i2 + k1]] % 12; - int l2 = this.p[l1 + 1 + this.p[i2 + 1]] % 12; - float d15 = 0.5f - d9 * d9 - d10 * d10; - float d2; - - if (d15 < 0.0f) { - d2 = 0.0f; - } else { - d15 = d15 * d15; - d2 = d15 * d15 * dot(grad3[j2], d9, d10); - } - - float d16 = 0.5f - d11 * d11 - d12 * d12; - float d3; - - if (d16 < 0.0f) { - d3 = 0.0f; - } else { - d16 = d16 * d16; - d3 = d16 * d16 * dot(grad3[k2], d11, d12); - } - - float d17 = 0.5f - d13 * d13 - d14 * d14; - float d4; - - if (d17 < 0.0f) { - d4 = 0.0f; - } else { - d17 = d17 * d17; - d4 = d17 * d17 * dot(grad3[l2], d13, d14); - } - - int i3 = i++; - p_151606_1_[i3] += 70.0f * (d2 + d3 + d4) * p_151606_12_; - } - } - } -} diff --git a/src/main/java/cn/nukkit/level/generator/object/BasicGenerator.java b/src/main/java/cn/nukkit/level/generator/object/BasicGenerator.java index 840f3f9b276..b81c85b3204 100644 --- a/src/main/java/cn/nukkit/level/generator/object/BasicGenerator.java +++ b/src/main/java/cn/nukkit/level/generator/object/BasicGenerator.java @@ -11,19 +11,16 @@ public abstract class BasicGenerator { //also autism, see below public abstract boolean generate(ChunkManager level, NukkitRandom rand, Vector3 position); - public void setDecorationDefaults() { - } - protected void setBlockAndNotifyAdequately(ChunkManager level, BlockVector3 pos, Block state) { - setBlock(level, new Vector3(pos.x, pos.y, pos.z), state); + level.setBlockAt(pos.x, pos.y, pos.z, state.getId(), state.getDamage()); } protected void setBlockAndNotifyAdequately(ChunkManager level, Vector3 pos, Block state) { - setBlock(level, pos, state); + level.setBlockAt((int) pos.x, (int) pos.y, (int) pos.z, state.getId(), state.getDamage()); } //what autism is this? why are we using floating-point vectors for setting block IDs? protected void setBlock(ChunkManager level, Vector3 v, Block b) { level.setBlockAt((int) v.x, (int) v.y, (int) v.z, b.getId(), b.getDamage()); } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/generator/object/ObjectTallGrass.java b/src/main/java/cn/nukkit/level/generator/object/ObjectTallGrass.java index 1d96514f673..9c432741e02 100644 --- a/src/main/java/cn/nukkit/level/generator/object/ObjectTallGrass.java +++ b/src/main/java/cn/nukkit/level/generator/object/ObjectTallGrass.java @@ -1,16 +1,28 @@ package cn.nukkit.level.generator.object; import cn.nukkit.block.Block; +import cn.nukkit.block.BlockLayer; import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.Level; import cn.nukkit.math.NukkitRandom; import cn.nukkit.math.Vector3; +import cn.nukkit.utils.Utils; /** - * author: ItsLucas + * @author ItsLucas * Nukkit Project */ public class ObjectTallGrass { + + @SuppressWarnings("unused") // Backwards compatibility public static void growGrass(ChunkManager level, Vector3 pos, NukkitRandom random) { + growGrass(level, pos); + } + + public static void growGrass(ChunkManager level, Vector3 pos) { + int maxBlockY = level instanceof Level ? ((Level) level).getMaxBlockY() : 255; + int minBlockY = level instanceof Level ? ((Level) level).getMinBlockY() : 0; + for (int i = 0; i < 128; ++i) { int num = 0; @@ -19,12 +31,14 @@ public static void growGrass(ChunkManager level, Vector3 pos, NukkitRandom rando int z = pos.getFloorZ(); while (true) { - if (num >= i / 16) { + if (num >= i >> 4) { if (level.getBlockIdAt(x, y, z) == Block.AIR) { - if (random.nextBoundedInt(8) == 0) { - //porktodo: biomes have specific flower types that can grow in them - if (random.nextBoolean()) { + if (Utils.random.nextInt(8) == 0) { + //TODO: biomes have specific flower types that can grow in them + if (Utils.rand()) { level.setBlockAt(x, y, z, Block.DANDELION); + } else if (Utils.rand()) { + level.setBlockAt(x, y, z, Block.TALL_GRASS, 2); // fern } else { level.setBlockAt(x, y, z, Block.POPPY); } @@ -36,11 +50,51 @@ public static void growGrass(ChunkManager level, Vector3 pos, NukkitRandom rando break; } - x += random.nextRange(-1, 1); - y += random.nextRange(-1, 1) * random.nextBoundedInt(3) / 2; - z += random.nextRange(-1, 1); + x += Utils.rand(-1, 1); + y += Utils.rand(-1, 1) * Utils.random.nextInt(3) >> 1; + z += Utils.rand(-1, 1); + + if (y > maxBlockY || y < minBlockY || level.getBlockIdAt(x, y - 1, z) != Block.GRASS) { + break; + } + + ++num; + } + } + } + + public static void growSeagrass(ChunkManager level, Vector3 pos) { + int maxBlockY = level instanceof Level ? ((Level) level).getMaxBlockY() : 255; + int minBlockY = level instanceof Level ? ((Level) level).getMinBlockY() : 0; + + for (int i = 0; i < 48; ++i) { + int num = 0; + + int x = pos.getFloorX(); + int y = pos.getFloorY() + 1; + int z = pos.getFloorZ(); + + while (true) { + if (num >= i >> 4) { + int block = level.getBlockIdAt(x, y, z); + if (block == Block.WATER || block == Block.STILL_WATER) { + //if (Utils.random.nextInt(8) == 0) { + // TODO: coral & tall seagrass + //} else { + level.setBlockAt(x, y, z, Block.SEAGRASS, 0); + level.setBlockAtLayer(x, y, z, BlockLayer.WATERLOGGED, Block.WATER, 0); + //} + } + + break; + } + + x += Utils.rand(-1, 1); + y += Utils.rand(-1, 1) * Utils.random.nextInt(3) >> 1; + z += Utils.rand(-1, 1); - if (level.getBlockIdAt(x, y - 1, z) != Block.GRASS || y > 255 || y < 0) { + int block; + if (y > maxBlockY || y < minBlockY || ((block = level.getBlockIdAt(x, y - 1, z)) != Block.DIRT && block != Block.SAND && block != Block.GRAVEL)) { break; } diff --git a/src/main/java/cn/nukkit/level/generator/object/mushroom/BigMushroom.java b/src/main/java/cn/nukkit/level/generator/object/mushroom/BigMushroom.java index 19d261ef173..5a16fea86c3 100644 --- a/src/main/java/cn/nukkit/level/generator/object/mushroom/BigMushroom.java +++ b/src/main/java/cn/nukkit/level/generator/object/mushroom/BigMushroom.java @@ -3,6 +3,7 @@ import cn.nukkit.block.Block; import cn.nukkit.block.BlockID; import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.Level; import cn.nukkit.level.generator.object.BasicGenerator; import cn.nukkit.math.NukkitRandom; import cn.nukkit.math.Vector3; @@ -27,7 +28,7 @@ public class BigMushroom extends BasicGenerator { /** * The mushroom type. 0 for brown, 1 for red. */ - private int mushroomType; + private final int mushroomType; public BigMushroom(int mushroomType) { this.mushroomType = mushroomType; @@ -48,12 +49,15 @@ public boolean generate(ChunkManager level, NukkitRandom rand, Vector3 position) int i = rand.nextBoundedInt(3) + 4; if (rand.nextBoundedInt(12) == 0) { - i *= 2; + i <<= 1; } boolean flag = true; - if (position.getY() >= 1 && position.getY() + i + 1 < 256) { + int maxY = level instanceof Level ? ((Level) level).getMaxBlockY() + 1 : 256; + int minBlockY = level instanceof Level ? ((Level) level).getMinBlockY() : 0; + + if (position.getY() > minBlockY && position.getY() + i + 1 < maxY) { for (int j = position.getFloorY(); j <= position.getY() + 1 + i; ++j) { int k = 3; @@ -65,7 +69,7 @@ public boolean generate(ChunkManager level, NukkitRandom rand, Vector3 position) for (int l = position.getFloorX() - k; l <= position.getX() + k && flag; ++l) { for (int i1 = position.getFloorZ() - k; i1 <= position.getZ() + k && flag; ++i1) { - if (j >= 0 && j < 256) { + if (j >= 0 && j < maxY) { pos.setComponents(l, j, i1); int material = level.getBlockIdAt(pos.getFloorX(), pos.getFloorY(), pos.getFloorZ()); @@ -173,7 +177,7 @@ public boolean generate(ChunkManager level, NukkitRandom rand, Vector3 position) if (position.getY() >= position.getY() + i - 1 || meta != ALL_INSIDE) { Vector3 blockPos = new Vector3(l1, l2, i2); - if (!Block.solid[level.getBlockIdAt(blockPos.getFloorX(), blockPos.getFloorY(), blockPos.getFloorZ())]) { + if (!Block.isBlockSolidById(level.getBlockIdAt(blockPos.getFloorX(), blockPos.getFloorY(), blockPos.getFloorZ()))) { mushroom.setDamage(meta); this.setBlockAndNotifyAdequately(level, blockPos, mushroom); } @@ -186,7 +190,7 @@ public boolean generate(ChunkManager level, NukkitRandom rand, Vector3 position) Vector3 pos = position.up(i3); int id = level.getBlockIdAt(pos.getFloorX(), pos.getFloorY(), pos.getFloorZ()); - if (!Block.solid[id]) { + if (!Block.isBlockSolidById(id)) { mushroom.setDamage(STEM); this.setBlockAndNotifyAdequately(level, pos, mushroom); } diff --git a/src/main/java/cn/nukkit/level/generator/object/ore/OreType.java b/src/main/java/cn/nukkit/level/generator/object/ore/OreType.java index ce318bae2c3..2e06274aa6f 100644 --- a/src/main/java/cn/nukkit/level/generator/object/ore/OreType.java +++ b/src/main/java/cn/nukkit/level/generator/object/ore/OreType.java @@ -8,11 +8,11 @@ import static cn.nukkit.block.BlockID.STONE; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ -//porktodo: rewrite this, the whole class is terrible and generated ores look stupid public class OreType { + public final int fullId; public final int clusterCount; public final int clusterSize; @@ -79,7 +79,7 @@ public boolean spawn(ChunkManager level, NukkitRandom rand, int replaceId, int x } } } - + return true; } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/generator/object/tree/HugeTreesGenerator.java b/src/main/java/cn/nukkit/level/generator/object/tree/HugeTreesGenerator.java index ab582cf98e9..8d545217409 100644 --- a/src/main/java/cn/nukkit/level/generator/object/tree/HugeTreesGenerator.java +++ b/src/main/java/cn/nukkit/level/generator/object/tree/HugeTreesGenerator.java @@ -2,6 +2,8 @@ import cn.nukkit.block.Block; import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.Level; +import cn.nukkit.math.BlockFace; import cn.nukkit.math.NukkitRandom; import cn.nukkit.math.Vector3; @@ -29,7 +31,7 @@ public HugeTreesGenerator(int baseHeightIn, int extraRandomHeightIn, Block woodM this.leavesMetadata = leavesMetadataIn; } - /* + /** * Calculates the height based on this trees base height and its extra random height */ protected int getHeight(NukkitRandom rand) { @@ -42,13 +44,16 @@ protected int getHeight(NukkitRandom rand) { return i; } - /* + /** * returns whether or not there is space for a tree to grow at a certain position */ private boolean isSpaceAt(ChunkManager worldIn, Vector3 leavesPos, int height) { boolean flag = true; - if (leavesPos.getY() >= 1 && leavesPos.getY() + height + 1 <= 256) { + int maxY = worldIn instanceof Level ? ((Level) worldIn).getMaxBlockY() + 1 : 256; + int minBlockY = worldIn instanceof Level ? ((Level) worldIn).getMinBlockY() : 0; + + if (leavesPos.getY() > minBlockY && leavesPos.getY() + height + 1 <= maxY) { for (int i = 0; i <= 1 + height; ++i) { int j = 2; @@ -61,7 +66,7 @@ private boolean isSpaceAt(ChunkManager worldIn, Vector3 leavesPos, int height) { for (int k = -j; k <= j && flag; ++k) { for (int l = -j; l <= j && flag; ++l) { Vector3 blockPos = leavesPos.add(k, i, l); - if (leavesPos.getY() + i < 0 || leavesPos.getY() + i >= 256 || !this.canGrowInto(worldIn.getBlockIdAt((int) blockPos.x, (int) blockPos.y, (int) blockPos.z))) { + if (leavesPos.getY() + i < 0 || leavesPos.getY() + i >= maxY || !this.canGrowInto(worldIn.getBlockIdAt((int) blockPos.x, (int) blockPos.y, (int) blockPos.z))) { flag = false; } } @@ -74,12 +79,12 @@ private boolean isSpaceAt(ChunkManager worldIn, Vector3 leavesPos, int height) { } } - /* + /** * returns whether or not there is dirt underneath the block where the tree will be grown. * It also generates dirt around the block in a 2x2 square if there is dirt underneath the blockpos. */ private boolean ensureDirtsUnderneath(Vector3 pos, ChunkManager worldIn) { - Vector3 blockpos = pos.down(); + Vector3 blockpos = pos.getSideVec(BlockFace.DOWN); int block = worldIn.getBlockIdAt((int) blockpos.x, (int) blockpos.y, (int) blockpos.z); if ((block == Block.GRASS || block == Block.DIRT) && pos.getY() >= 2) { @@ -93,15 +98,15 @@ private boolean ensureDirtsUnderneath(Vector3 pos, ChunkManager worldIn) { } } - /* + /** * returns whether or not a tree can grow at a specific position. * If it can, it generates surrounding dirt underneath. */ - protected boolean ensureGrowable(ChunkManager worldIn, NukkitRandom rand, Vector3 treePos, int p_175929_4_) { - return this.isSpaceAt(worldIn, treePos, p_175929_4_) && this.ensureDirtsUnderneath(treePos, worldIn); + protected boolean ensureGrowable(ChunkManager worldIn, Vector3 treePos, int height) { + return this.isSpaceAt(worldIn, treePos, height) && this.ensureDirtsUnderneath(treePos, worldIn); } - /* + /** * grow leaves in a circle with the outsides being within the circle */ protected void growLeavesLayerStrict(ChunkManager worldIn, Vector3 layerCenter, int width) { @@ -124,7 +129,7 @@ protected void growLeavesLayerStrict(ChunkManager worldIn, Vector3 layerCenter, } } - /* + /** * grow leaves in a circle */ protected void growLeavesLayer(ChunkManager worldIn, Vector3 layerCenter, int width) { diff --git a/src/main/java/cn/nukkit/level/generator/object/tree/NewJungleTree.java b/src/main/java/cn/nukkit/level/generator/object/tree/NewJungleTree.java index f9b1cfc579e..8b3ebd20e06 100644 --- a/src/main/java/cn/nukkit/level/generator/object/tree/NewJungleTree.java +++ b/src/main/java/cn/nukkit/level/generator/object/tree/NewJungleTree.java @@ -1,7 +1,11 @@ package cn.nukkit.level.generator.object.tree; -import cn.nukkit.block.*; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; +import cn.nukkit.block.BlockLeaves; +import cn.nukkit.block.BlockWood; import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; import cn.nukkit.math.BlockVector3; import cn.nukkit.math.NukkitRandom; @@ -17,6 +21,9 @@ public class NewJungleTree extends TreeGenerator { */ private final int minTreeHeight; + /** + * The maxium height of a generated tree. + */ private final int maxTreeHeight; /** @@ -29,6 +36,10 @@ public class NewJungleTree extends TreeGenerator { */ private final Block metaLeaves = Block.get(BlockID.LEAVES, BlockLeaves.JUNGLE); + public NewJungleTree(int minTreeHeight) { + this(minTreeHeight, 3); + } + public NewJungleTree(int minTreeHeight, int maxTreeHeight) { this.minTreeHeight = minTreeHeight; this.maxTreeHeight = maxTreeHeight; @@ -41,7 +52,10 @@ public boolean generate(ChunkManager worldIn, NukkitRandom rand, Vector3 vectorP int i = rand.nextBoundedInt(maxTreeHeight) + this.minTreeHeight; boolean flag = true; - if (position.getY() >= 1 && position.getY() + i + 1 <= 256) { + int maxY = worldIn instanceof Level ? ((Level) worldIn).getMaxBlockY() + 1 : 256; + int minBlockY = worldIn instanceof Level ? ((Level) worldIn).getMinBlockY() : 0; + + if (position.getY() > minBlockY && position.getY() + i + 1 <= maxY) { for (int j = position.getY(); j <= position.getY() + 1 + i; ++j) { int k = 1; @@ -57,7 +71,7 @@ public boolean generate(ChunkManager worldIn, NukkitRandom rand, Vector3 vectorP for (int l = position.getX() - k; l <= position.getX() + k && flag; ++l) { for (int i1 = position.getZ() - k; i1 <= position.getZ() + k && flag; ++i1) { - if (j >= 0 && j < 256) { + if (j >= 0 && j < maxY) { pos2.setComponents(l, j, i1); if (!this.canGrowInto(worldIn.getBlockIdAt(pos2.x, pos2.y, pos2.z))) { flag = false; @@ -75,14 +89,12 @@ public boolean generate(ChunkManager worldIn, NukkitRandom rand, Vector3 vectorP BlockVector3 down = position.down(); int block = worldIn.getBlockIdAt(down.x, down.y, down.z); - if ((block == Block.GRASS || block == Block.DIRT || block == Block.FARMLAND) && position.getY() < 256 - i - 1) { + if ((block == Block.GRASS || block == Block.DIRT || block == Block.FARMLAND) && position.getY() < maxY - i - 1) { this.setDirtAt(worldIn, down); - int k2 = 3; - int l2 = 0; for (int i3 = position.getY() - 3 + i; i3 <= position.getY() + i; ++i3) { int i4 = i3 - (position.getY() + i); - int j1 = 1 - i4 / 2; + int j1 = 1 - (i4 >> 1); for (int k1 = position.getX() - j1; k1 <= position.getX() + j1; ++k1) { int l1 = k1 - position.getX(); @@ -131,7 +143,7 @@ public boolean generate(ChunkManager worldIn, NukkitRandom rand, Vector3 vectorP for (int k3 = position.getY() - 3 + i; k3 <= position.getY() + i; ++k3) { int j4 = k3 - (position.getY() + i); - int k4 = 2 - j4 / 2; + int k4 = 2 - (j4 >> 1); BlockVector3 pos2 = new BlockVector3(); for (int l4 = position.getX() - k4; l4 <= position.getX() + k4; ++l4) { @@ -169,7 +181,7 @@ public boolean generate(ChunkManager worldIn, NukkitRandom rand, Vector3 vectorP for (BlockFace enumfacing : BlockFace.Plane.HORIZONTAL) { if (rand.nextBoundedInt(4 - l3) == 0) { BlockFace enumfacing1 = enumfacing.getOpposite(); - this.placeCocoa(worldIn, rand.nextBoundedInt(3), position.add(enumfacing1.getXOffset(), i - 5 + l3, enumfacing1.getZOffset()), enumfacing); + this.placeCocoa(worldIn, /*rand.nextBoundedInt(3),*/ position.add(enumfacing1.getXOffset(), i - 5 + l3, enumfacing1.getZOffset()), enumfacing); } } } @@ -185,10 +197,8 @@ public boolean generate(ChunkManager worldIn, NukkitRandom rand, Vector3 vectorP } } - private void placeCocoa(ChunkManager worldIn, int age, BlockVector3 pos, BlockFace side) { - int meta = getCocoaMeta(age, side.getIndex()); - - this.setBlockAndNotifyAdequately(worldIn, pos, new BlockUnknown(127, meta)); + private void placeCocoa(ChunkManager worldIn, /*int age,*/ BlockVector3 pos, BlockFace side) { + this.setBlockAndNotifyAdequately(worldIn, pos, Block.get(BlockID.COCOA_BLOCK, getCocoaMeta(side.getIndex()))); } private void addVine(ChunkManager worldIn, BlockVector3 pos, int meta) { @@ -205,12 +215,12 @@ private void addHangingVine(ChunkManager worldIn, BlockVector3 pos, int meta) { } } - private boolean isAirBlock(ChunkManager level, BlockVector3 v) { + private static boolean isAirBlock(ChunkManager level, BlockVector3 v) { return level.getBlockIdAt(v.x, v.y, v.z) == 0; } - private int getCocoaMeta(int age, int side) { - int meta = age * 4; + private static int getCocoaMeta(int side) { + int meta = 0; //3 4 2 5 switch (side) { diff --git a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectBigSpruceTree.java b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectBigSpruceTree.java index 890bf1c8db2..e918f9db0af 100644 --- a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectBigSpruceTree.java +++ b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectBigSpruceTree.java @@ -5,10 +5,11 @@ import cn.nukkit.math.NukkitRandom; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class ObjectBigSpruceTree extends ObjectSpruceTree { + private final float leafStartHeightMultiplier; private final int baseLeafRadius; @@ -19,14 +20,13 @@ public ObjectBigSpruceTree(float leafStartHeightMultiplier, int baseLeafRadius) @Override public void placeObject(ChunkManager level, int x, int y, int z, NukkitRandom random) { - this.treeHeight = random.nextBoundedInt(15) + 20; + this.treeHeight = random.nextBoundedInt(15) + 15; int topSize = this.treeHeight - (int) (this.treeHeight * leafStartHeightMultiplier); - int lRadius = baseLeafRadius + random.nextBoundedInt(2); this.placeTrunk(level, x, y, z, random, this.getTreeHeight() - random.nextBoundedInt(3)); - this.placeLeaves(level, topSize, lRadius, x, y, z, random); + this.placeLeaves(level, topSize, baseLeafRadius, x, y, z, random); } @Override @@ -46,4 +46,51 @@ protected void placeTrunk(ChunkManager level, int x, int y, int z, NukkitRandom } } } + + @Override + public void placeLeaves(ChunkManager level, int topSize, int lRadius, int x, int y, int z, NukkitRandom random) { + int radius = random.nextBoundedInt(2); + int maxR = 1; + int minR = 0; + + for (int yy = 0; yy <= topSize; ++yy) { + int yyy = y + this.treeHeight - yy; + + for (int xx = x - radius; xx <= x + radius + 1; ++xx) { + for (int zz = z - radius; zz <= z + radius + 1; ++zz) { + if (topSize - yy > 1 && radius > 0) { + if (Math.abs(xx - x) > radius && Math.abs(zz - z) > radius) { + continue; + } + + if (xx - x <= -radius && zz - z <= -radius) { + continue; + } + + if (Math.abs(xx - x) > radius && zz - z <= -radius) { + continue; + } + + if (xx - x <= -radius && Math.abs(zz - z) > radius) { + continue; + } + } + + if (!Block.isBlockSolidById(level.getBlockIdAt(xx, yyy, zz))) { + level.setBlockAt(xx, yyy, zz, this.getLeafBlock(), this.getType()); + } + } + } + + if (radius >= maxR) { + radius = minR; + minR = 1; + if (++maxR > lRadius) { + maxR = lRadius; + } + } else { + ++radius; + } + } + } } diff --git a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectBirchTree.java b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectBirchTree.java index 6b6ed4a7d16..81701139e80 100644 --- a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectBirchTree.java +++ b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectBirchTree.java @@ -1,26 +1,16 @@ package cn.nukkit.level.generator.object.tree; -import cn.nukkit.block.Block; import cn.nukkit.block.BlockWood; import cn.nukkit.level.ChunkManager; import cn.nukkit.math.NukkitRandom; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ObjectBirchTree extends ObjectTree { - protected int treeHeight = 7; - - @Override - public int getTrunkBlock() { - return Block.LOG; - } - @Override - public int getLeafBlock() { - return Block.LEAVES; - } + protected int treeHeight = 7; @Override public int getType() { diff --git a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectCrimsonTree.java b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectCrimsonTree.java new file mode 100644 index 00000000000..77cf2a1f4e1 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectCrimsonTree.java @@ -0,0 +1,19 @@ +package cn.nukkit.level.generator.object.tree; + +import cn.nukkit.block.Block; + +/** + * @author FlamingKnight + */ +public class ObjectCrimsonTree extends ObjectNetherTree { + + @Override + public int getTrunkBlock() { + return Block.CRIMSON_STEM; + } + + @Override + public int getLeafBlock() { + return Block.BLOCK_NETHER_WART_BLOCK; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectDarkOakTree.java b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectDarkOakTree.java index e4fa570ba13..1994a3f7530 100644 --- a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectDarkOakTree.java +++ b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectDarkOakTree.java @@ -5,6 +5,7 @@ import cn.nukkit.block.BlockLeaves2; import cn.nukkit.block.BlockWood2; import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; import cn.nukkit.math.NukkitRandom; import cn.nukkit.math.Vector3; @@ -13,6 +14,7 @@ * Created by CreeperFace on 23. 10. 2016. */ public class ObjectDarkOakTree extends TreeGenerator { + private static final Block DARK_OAK_LOG = Block.get(BlockID.WOOD2, BlockWood2.DARK_OAK); private static final Block DARK_OAK_LEAVES = Block.get(BlockID.LEAVES2, BlockLeaves2.DARK_OAK); @@ -23,7 +25,8 @@ public boolean generate(ChunkManager level, NukkitRandom rand, Vector3 position) int k = position.getFloorY(); int l = position.getFloorZ(); - if (k >= 1 && k + i + 1 < 256) { + int maxY = level instanceof Level ? ((Level) level).getMaxBlockY() + 1 : 256; + if (k >= 1 && k + i + 1 < maxY) { Vector3 blockpos = position.down(); int block = level.getBlockIdAt(blockpos.getFloorX(), blockpos.getFloorY(), blockpos.getFloorZ()); diff --git a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectFallenTree.java b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectFallenTree.java new file mode 100644 index 00000000000..e57bd6ff840 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectFallenTree.java @@ -0,0 +1,61 @@ +package cn.nukkit.level.generator.object.tree; + +import cn.nukkit.block.Block; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.math.NukkitRandom; + +public class ObjectFallenTree { + + public ObjectFallenTree(ChunkManager level, int x, int y, int z, int type, NukkitRandom random) { + placeObject(level, x, y, z, type, random); + } + + public void placeObject(ChunkManager level, int x, int y, int z, int type, NukkitRandom random) { + int direction = random.nextRange(1, 2); + if (direction == 1 && type == 0) { //oak tree + //tree + level.setBlockAt(x - 1, y, z, Block.WOOD); + level.setBlockAt(x + 1, y, z, Block.WOOD, 12); + level.setBlockAt(x + 2, y, z, Block.WOOD, 12); + //vines + level.setBlockAt(x - 2, y, z, Block.VINES, 8); + level.setBlockAt(x - 1, y, z + 1, Block.VINES, 4); + level.setBlockAt(x - 1, y, z - 1, Block.VINES, 1); + } else if (direction == 1 && type == 1) { //birch + //tree + level.setBlockAt(x - 1, y, z, Block.WOOD, 2); + level.setBlockAt(x + 1, y, z, Block.WOOD, 14); + level.setBlockAt(x + 2, y, z, Block.WOOD, 14); + level.setBlockAt(x + 3, y, z, Block.WOOD, 14); + //vines + level.setBlockAt(x - 2, y, z, Block.VINES, 8); + level.setBlockAt(x - 1, y, z + 1, Block.VINES, 4); + level.setBlockAt(x - 1, y, z - 1, Block.VINES, 1); + //mushrooms + level.setBlockAt(x + 1, y + 1, z, Block.BROWN_MUSHROOM); + level.setBlockAt(x + 3, y + 1, z, Block.RED_MUSHROOM); + } else if (direction == 2 && type == 0) { //oak tree + //tree + level.setBlockAt(x, y, z - 1, Block.WOOD); + level.setBlockAt(x, y, z + 1, Block.WOOD, 12); + level.setBlockAt(x, y, z + 2, Block.WOOD, 12); + //vines + level.setBlockAt(x, y, z - 2, Block.VINES, 1); + level.setBlockAt(x + 1, y, z - 1, Block.VINES, 2); + level.setBlockAt(x - 1, y, z - 1, Block.VINES, 8); + } else if (direction == 2 && type == 1) { //birch + //tree + level.setBlockAt(x, y, z - 1, Block.WOOD, 2); + level.setBlockAt(x, y, z + 1, Block.WOOD, 14); + level.setBlockAt(x, y, z + 2, Block.WOOD, 14); + level.setBlockAt(x, y, z + 3, Block.WOOD, 14); + //vines + level.setBlockAt(x, y, z - 2, Block.VINES, 1); + level.setBlockAt(x + 1, y, z - 1, Block.VINES, 2); + level.setBlockAt(x - 1, y, z - 1, Block.VINES, 8); + //mushrooms + level.setBlockAt(x, y + 1, z + 1, Block.BROWN_MUSHROOM); + level.setBlockAt(x, y + 1, z + 3, Block.RED_MUSHROOM); + } + } +} diff --git a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectJungleBigTree.java b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectJungleBigTree.java index 4a4d7727c79..7457447e27f 100644 --- a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectJungleBigTree.java +++ b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectJungleBigTree.java @@ -3,7 +3,6 @@ import cn.nukkit.block.Block; import cn.nukkit.block.BlockID; import cn.nukkit.level.ChunkManager; -import cn.nukkit.math.BlockVector3; import cn.nukkit.math.MathHelper; import cn.nukkit.math.NukkitRandom; import cn.nukkit.math.Vector3; @@ -16,27 +15,27 @@ public ObjectJungleBigTree(int baseHeightIn, int extraRandomHeight, Block woodMe public boolean generate(ChunkManager level, NukkitRandom rand, Vector3 position) { int height = this.getHeight(rand); - if (!this.ensureGrowable(level, rand, position, height)) { + if (!this.ensureGrowable(level, position, height)) { return false; } else { this.createCrown(level, position.up(height), 2); - for (int j = (int) position.getY() + height - 2 - rand.nextBoundedInt(4); j > position.getY() + height / 2; j -= 2 + rand.nextBoundedInt(4)) { - float f = rand.nextFloat() * ((float) Math.PI * 2F); + for (int j = (int) position.getY() + height - 2 - rand.nextBoundedInt(4); j > position.getY() + (height >> 1); j -= 2 + rand.nextBoundedInt(4)) { + float f = rand.nextFloat() * (6.2831855f); int k = (int) (position.getX() + (0.5F + MathHelper.cos(f) * 4.0F)); int l = (int) (position.getZ() + (0.5F + MathHelper.sin(f) * 4.0F)); for (int i1 = 0; i1 < 5; ++i1) { k = (int) (position.getX() + (1.5F + MathHelper.cos(f) * (float) i1)); l = (int) (position.getZ() + (1.5F + MathHelper.sin(f) * (float) i1)); - this.setBlockAndNotifyAdequately(level, new BlockVector3(k, j - 3 + i1 / 2, l), this.woodMetadata); + this.setBlockAndNotifyAdequately(level, new Vector3(k, j - 3 + (i1 >> 1), l - 1), this.woodMetadata); } int j2 = 1 + rand.nextBoundedInt(2); for (int k1 = j - j2; k1 <= j; ++k1) { int l1 = k1 - j; - this.growLeavesLayer(level, new Vector3(k, k1, l), 1 - l1); + this.growLeavesLayer(level, new Vector3(k, k1, l - 1), 1 - l1); } } @@ -94,7 +93,7 @@ public boolean generate(ChunkManager level, NukkitRandom rand, Vector3 position) private void placeVine(ChunkManager level, NukkitRandom random, Vector3 pos, int meta) { if (random.nextBoundedInt(3) > 0 && level.getBlockIdAt((int) pos.x, (int) pos.y, (int) pos.z) == 0) { - this.setBlockAndNotifyAdequately(level, pos, Block.get(BlockID.VINE, meta)); + this.setBlockAndNotifyAdequately(level, pos, Block.get(BlockID.VINES, meta)); } } diff --git a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectJungleTree.java b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectJungleTree.java index c50f8fe2905..e3a0e4e6735 100644 --- a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectJungleTree.java +++ b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectJungleTree.java @@ -1,27 +1,16 @@ package cn.nukkit.level.generator.object.tree; -import cn.nukkit.block.Block; import cn.nukkit.block.BlockWood; import cn.nukkit.level.ChunkManager; import cn.nukkit.math.NukkitRandom; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ObjectJungleTree extends ObjectTree { private int treeHeight = 8; - @Override - public int getTrunkBlock() { - return Block.LOG; - } - - @Override - public int getLeafBlock() { - return Block.LEAVES; - } - @Override public int getType() { return BlockWood.JUNGLE; diff --git a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectNetherTree.java b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectNetherTree.java new file mode 100644 index 00000000000..e0f93b3a047 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectNetherTree.java @@ -0,0 +1,131 @@ +package cn.nukkit.level.generator.object.tree; + +import cn.nukkit.block.Block; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.Level; +import cn.nukkit.math.NukkitRandom; + +import java.util.concurrent.ThreadLocalRandom; + +/** + * @author FlamingKnight + */ +public abstract class ObjectNetherTree extends ObjectTree { + + private final int treeHeight; + + public ObjectNetherTree() { + this(ThreadLocalRandom.current().nextInt(9) + 4); + } + + public ObjectNetherTree(int treeHeight) { + this.treeHeight = treeHeight; + } + + @Override + public int getTreeHeight() { + return treeHeight; + } + + @Override + public void placeObject(ChunkManager level, int x, int y, int z, NukkitRandom random) { + int maxBlockY = level instanceof Level ? ((Level) level).getMaxBlockY() : 255; + + if (y >= maxBlockY) { + return; + } + + this.placeTrunk(level, x, y, z, random, this.getTreeHeight()); + + int mid = 2; + for (int yy = y - 3 + treeHeight; yy <= y + this.treeHeight - 1; ++yy) { + if (yy >= maxBlockY) { + continue; + } + + for (int xx = x - mid; xx <= x + mid; xx++) { + int xOff = Math.abs(xx - x); + for (int zz = z - mid; zz <= z + mid; zz += mid * 2) { + int zOff = Math.abs(zz - z); + if (xOff == mid && zOff == mid && random.nextBoundedInt(2) == 0) { + continue; + } + if (!Block.isBlockSolidById(level.getBlockIdAt(xx, yy, zz))) { + if (random.nextBoundedInt(20) == 0) level.setBlockAt(xx, yy, zz, Block.SHROOMLIGHT); + else level.setBlockAt(xx, yy, zz, this.getLeafBlock()); + } + } + } + + for (int zz = z - mid; zz <= z + mid; zz++) { + int zOff = Math.abs(zz - z); + for (int xx = x - mid; xx <= x + mid; xx += mid * 2) { + int xOff = Math.abs(xx - x); + if (xOff == mid && zOff == mid && (random.nextBoundedInt(2) == 0)) { + continue; + } + if (!Block.isBlockSolidById(level.getBlockIdAt(xx, yy, zz))) { + if (random.nextBoundedInt(20) == 0) level.setBlockAt(xx, yy, zz, Block.SHROOMLIGHT); + else level.setBlockAt(xx, yy, zz, this.getLeafBlock()); + } + } + } + } + + for (int yy = y - 4 + treeHeight; yy <= y + this.treeHeight - 3; ++yy) { + if (yy >= maxBlockY) { + continue; + } + + for (int xx = x - mid; xx <= x + mid; xx++) { + for (int zz = z - mid; zz <= z + mid; zz += mid * 2) { + if (!Block.isBlockSolidById(level.getBlockIdAt(xx, yy, zz))) { + if (random.nextBoundedInt(3) == 0) { + for (int i = 0; i < random.nextBoundedInt(5); i++) { + if (!Block.isBlockSolidById(level.getBlockIdAt(xx, yy - i, zz))) + level.setBlockAt(xx, yy - i, zz, getLeafBlock()); + } + } + } + } + } + + for (int zz = z - mid; zz <= z + mid; zz++) { + for (int xx = x - mid; xx <= x + mid; xx += mid * 2) { + if (!Block.isBlockSolidById(level.getBlockIdAt(xx, yy, zz))) { + if (random.nextBoundedInt(3) == 0) { + for (int i = 0; i < random.nextBoundedInt(4); i++) { + if (!Block.isBlockSolidById(level.getBlockIdAt(xx, yy - i, zz))) + level.setBlockAt(xx, yy - i, zz, getLeafBlock()); + } + } + } + } + } + } + + for (int xCanopy = x - mid + 1; xCanopy <= x + mid - 1; xCanopy++) { + for (int zCanopy = z - mid + 1; zCanopy <= z + mid - 1; zCanopy++) { + if (!Block.isBlockSolidById(level.getBlockIdAt(xCanopy, y + treeHeight, zCanopy))) + level.setBlockAt(xCanopy, y + treeHeight, zCanopy, getLeafBlock()); + } + } + } + + @Override + protected void placeTrunk(ChunkManager level, int x, int y, int z, NukkitRandom random, int trunkHeight) { + int maxBlockY = level instanceof Level ? ((Level) level).getMaxBlockY() : 255; + + level.setBlockAt(x, y, z, getTrunkBlock()); + + for (int yy = 0; yy < trunkHeight; ++yy) { + if (y + yy >= maxBlockY) { + continue; + } + int blockId = level.getBlockIdAt(x, y + yy, z); + if (this.overridable(blockId)) { + level.setBlockAt(x, y + yy, z, this.getTrunkBlock()); + } + } + } +} diff --git a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectOakTree.java b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectOakTree.java index 66127162d52..35592f7ee4e 100644 --- a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectOakTree.java +++ b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectOakTree.java @@ -1,26 +1,16 @@ package cn.nukkit.level.generator.object.tree; -import cn.nukkit.block.Block; import cn.nukkit.block.BlockWood; import cn.nukkit.level.ChunkManager; import cn.nukkit.math.NukkitRandom; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ObjectOakTree extends ObjectTree { - private int treeHeight = 7; - - @Override - public int getTrunkBlock() { - return Block.LOG; - } - @Override - public int getLeafBlock() { - return Block.LEAVES; - } + private int treeHeight = 7; @Override public int getType() { diff --git a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectSavannaTree.java b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectSavannaTree.java index 71226eb541f..5490f2d6fa4 100644 --- a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectSavannaTree.java +++ b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectSavannaTree.java @@ -5,11 +5,13 @@ import cn.nukkit.block.BlockLeaves2; import cn.nukkit.block.BlockWood2; import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; import cn.nukkit.math.NukkitRandom; import cn.nukkit.math.Vector3; public class ObjectSavannaTree extends TreeGenerator { + private static final Block TRUNK = Block.get(BlockID.WOOD2, BlockWood2.ACACIA); private static final Block LEAF = Block.get(BlockID.LEAVES2, BlockLeaves2.ACACIA); @@ -17,7 +19,10 @@ public boolean generate(ChunkManager level, NukkitRandom rand, Vector3 position) int i = rand.nextBoundedInt(3) + rand.nextBoundedInt(3) + 5; boolean flag = true; - if (position.getY() >= 1 && position.getY() + i + 1 <= 256) { + int maxY = level instanceof Level ? ((Level) level).getMaxBlockY() + 1 : 256; + int minBlockY = level instanceof Level ? ((Level) level).getMinBlockY() : 0; + + if (position.getY() > minBlockY && position.getY() + i + 1 <= maxY) { for (int j = (int) position.getY(); j <= position.getY() + 1 + i; ++j) { int k = 1; @@ -33,7 +38,7 @@ public boolean generate(ChunkManager level, NukkitRandom rand, Vector3 position) for (int l = (int) position.getX() - k; l <= position.getX() + k && flag; ++l) { for (int i1 = (int) position.getZ() - k; i1 <= position.getZ() + k && flag; ++i1) { - if (j >= 0 && j < 256) { + if (j >= 0 && j < maxY) { vector3.setComponents(l, j, i1); if (!this.canGrowInto(level.getBlockIdAt((int) vector3.x, (int) vector3.y, (int) vector3.z))) { @@ -52,7 +57,7 @@ public boolean generate(ChunkManager level, NukkitRandom rand, Vector3 position) Vector3 down = position.down(); int block = level.getBlockIdAt(down.getFloorX(), down.getFloorY(), down.getFloorZ()); - if ((block == Block.GRASS || block == Block.DIRT) && position.getY() < 256 - i - 1) { + if ((block == Block.GRASS || block == Block.DIRT) && position.getY() < maxY - i - 1) { this.setDirtAt(level, position.down()); BlockFace face = BlockFace.Plane.HORIZONTAL.random(rand); int k2 = i - rand.nextBoundedInt(4) - 1; diff --git a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectSpruceTree.java b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectSpruceTree.java index 89c4f7792ef..0c8d490b394 100644 --- a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectSpruceTree.java +++ b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectSpruceTree.java @@ -3,23 +3,25 @@ import cn.nukkit.block.Block; import cn.nukkit.block.BlockWood; import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.biome.Biome; +import cn.nukkit.level.format.FullChunk; import cn.nukkit.math.NukkitRandom; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ObjectSpruceTree extends ObjectTree { - protected int treeHeight; - @Override - public int getTrunkBlock() { - return Block.LOG; + protected int treeHeight = 15; + private final boolean canCreateSnow; + + public ObjectSpruceTree() { + this(false); } - @Override - public int getLeafBlock() { - return Block.LEAVES; + public ObjectSpruceTree(boolean canCreateSnow) { + this.canCreateSnow = canCreateSnow; } @Override @@ -36,10 +38,10 @@ public int getTreeHeight() { public void placeObject(ChunkManager level, int x, int y, int z, NukkitRandom random) { this.treeHeight = random.nextBoundedInt(4) + 6; - int topSize = this.getTreeHeight() - (1 + random.nextBoundedInt(2)); + int topSize = this.treeHeight - (1 + random.nextBoundedInt(2)); int lRadius = 2 + random.nextBoundedInt(2); - this.placeTrunk(level, x, y, z, random, this.getTreeHeight() - random.nextBoundedInt(3)); + this.placeTrunk(level, x, y, z, random, this.treeHeight); this.placeLeaves(level, topSize, lRadius, x, y, z, random); } @@ -49,6 +51,12 @@ public void placeLeaves(ChunkManager level, int topSize, int lRadius, int x, int int maxR = 1; int minR = 0; + boolean createSnow = false; + if (this.canCreateSnow) { + FullChunk chunk = level.getChunk(x >> 4, z >> 4); + createSnow = chunk == null || Biome.getBiome(chunk.getBiomeId(x & 0x0f, z & 0x0f)).isFreezing(); + } + for (int yy = 0; yy <= topSize; ++yy) { int yyy = y + this.treeHeight - yy; @@ -60,8 +68,14 @@ public void placeLeaves(ChunkManager level, int topSize, int lRadius, int x, int continue; } - if (!Block.solid[level.getBlockIdAt(xx, yyy, zz)]) { + if (!Block.isBlockSolidById(level.getBlockIdAt(xx, yyy, zz))) { level.setBlockAt(xx, yyy, zz, this.getLeafBlock(), this.getType()); + + if (createSnow) { + if (level.getBlockIdAt(xx, yyy + 1, zz) == Block.AIR && level.getBlockIdAt(xx, yyy + 2, zz) == Block.AIR) { + level.setBlockAt(xx, yyy + 1, zz, Block.SNOW_LAYER, 0); + } + } } } } diff --git a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectSwampTree.java b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectSwampTree.java index bdc871c38d7..813b31224b6 100644 --- a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectSwampTree.java +++ b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectSwampTree.java @@ -1,7 +1,11 @@ package cn.nukkit.level.generator.object.tree; -import cn.nukkit.block.*; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; +import cn.nukkit.block.BlockLeaves; +import cn.nukkit.block.BlockWood; import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.Level; import cn.nukkit.math.BlockVector3; import cn.nukkit.math.NukkitRandom; import cn.nukkit.math.Vector3; @@ -25,7 +29,10 @@ public boolean generate(ChunkManager worldIn, NukkitRandom rand, Vector3 vectorP int i = rand.nextBoundedInt(4) + 5; boolean flag = true; - if (position.getY() >= 1 && position.getY() + i + 1 <= 256) { + int maxY = worldIn instanceof Level ? ((Level) worldIn).getMaxBlockY() + 1 : 256; + int minBlockY = worldIn instanceof Level ? ((Level) worldIn).getMinBlockY() : 0; + + if (position.getY() > minBlockY && position.getY() + i + 1 <= maxY) { for (int j = position.getY(); j <= position.getY() + 1 + i; ++j) { int k = 1; @@ -41,7 +48,7 @@ public boolean generate(ChunkManager worldIn, NukkitRandom rand, Vector3 vectorP for (int l = position.getX() - k; l <= position.getX() + k && flag; ++l) { for (int i1 = position.getZ() - k; i1 <= position.getZ() + k && flag; ++i1) { - if (j >= 0 && j < 256) { + if (j >= 0 && j < maxY) { pos2.setComponents(l, j, i1); if (!this.canGrowInto(worldIn.getBlockIdAt(pos2.x, pos2.y, pos2.z))) { flag = false; @@ -59,12 +66,12 @@ public boolean generate(ChunkManager worldIn, NukkitRandom rand, Vector3 vectorP BlockVector3 down = position.down(); int block = worldIn.getBlockIdAt(down.x, down.y, down.z); - if ((block == Block.GRASS || block == Block.DIRT) && position.getY() < 256 - i - 1) { + if ((block == Block.GRASS || block == Block.DIRT) && position.getY() < maxY - i - 1) { this.setDirtAt(worldIn, down); for (int k1 = position.getY() - 3 + i; k1 <= position.getY() + i; ++k1) { int j2 = k1 - (position.getY() + i); - int l2 = 2 - j2 / 2; + int l2 = 2 - (j2 >> 1); for (int j3 = position.getX() - l2; j3 <= position.getX() + l2; ++j3) { int k3 = j3 - position.getX(); @@ -95,7 +102,7 @@ public boolean generate(ChunkManager worldIn, NukkitRandom rand, Vector3 vectorP for (int i2 = position.getY() - 3 + i; i2 <= position.getY() + i; ++i2) { int k2 = i2 - (position.getY() + i); - int i3 = 2 - k2 / 2; + int i3 = 2 - (k2 >> 1); BlockVector3 pos2 = new BlockVector3(); for (int l3 = position.getX() - i3; l3 <= position.getX() + i3; ++l3) { diff --git a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectTallBirchTree.java b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectTallBirchTree.java index 72759ea56b7..72741d1218a 100644 --- a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectTallBirchTree.java +++ b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectTallBirchTree.java @@ -4,7 +4,7 @@ import cn.nukkit.math.NukkitRandom; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class ObjectTallBirchTree extends ObjectBirchTree { diff --git a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectTree.java b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectTree.java index 49da3dfc6b6..2902d9dccd8 100644 --- a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectTree.java +++ b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectTree.java @@ -6,10 +6,13 @@ import cn.nukkit.math.NukkitRandom; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class ObjectTree { + + public static final int SNOWY_TREE = 100; + protected boolean overridable(int id) { switch (id) { case Block.AIR: @@ -51,6 +54,9 @@ public static void growTree(ChunkManager level, int x, int y, int z, NukkitRando case BlockSapling.SPRUCE: tree = new ObjectSpruceTree(); break; + case BlockSapling.SPRUCE + SNOWY_TREE: + tree = new ObjectSpruceTree(true); + break; case BlockSapling.BIRCH: tree = new ObjectBirchTree(); break; @@ -78,6 +84,7 @@ public boolean canPlaceObject(ChunkManager level, int x, int y, int z, NukkitRan for (int yy = 0; yy < this.getTreeHeight() + 3; ++yy) { if (yy == 1 || yy == this.getTreeHeight()) { ++radiusToCheck; + continue; } for (int xx = -radiusToCheck; xx < (radiusToCheck + 1); ++xx) { for (int zz = -radiusToCheck; zz < (radiusToCheck + 1); ++zz) { @@ -105,7 +112,7 @@ public void placeObject(ChunkManager level, int x, int y, int z, NukkitRandom ra if (xOff == mid && zOff == mid && (yOff == 0 || random.nextBoundedInt(2) == 0)) { continue; } - if (!Block.solid[level.getBlockIdAt(xx, yy, zz)]) { + if (!Block.isBlockSolidById(level.getBlockIdAt(xx, yy, zz))) { level.setBlockAt(xx, yy, zz, this.getLeafBlock(), this.getType()); } } @@ -124,4 +131,4 @@ protected void placeTrunk(ChunkManager level, int x, int y, int z, NukkitRandom } } } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/generator/object/tree/ObjectWarpedTree.java b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectWarpedTree.java new file mode 100644 index 00000000000..4456e840884 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/object/tree/ObjectWarpedTree.java @@ -0,0 +1,19 @@ +package cn.nukkit.level.generator.object.tree; + +import cn.nukkit.block.Block; + +/** + * @author FlamingKnight + */ +public class ObjectWarpedTree extends ObjectNetherTree { + + @Override + public int getTrunkBlock() { + return Block.WARPED_STEM; + } + + @Override + public int getLeafBlock() { + return Block.WARPED_WART_BLOCK; + } +} diff --git a/src/main/java/cn/nukkit/level/generator/object/tree/TreeGenerator.java b/src/main/java/cn/nukkit/level/generator/object/tree/TreeGenerator.java index 06e2314e990..603b289a45b 100644 --- a/src/main/java/cn/nukkit/level/generator/object/tree/TreeGenerator.java +++ b/src/main/java/cn/nukkit/level/generator/object/tree/TreeGenerator.java @@ -4,15 +4,12 @@ import cn.nukkit.block.BlockID; import cn.nukkit.item.Item; import cn.nukkit.level.ChunkManager; -import cn.nukkit.level.Level; import cn.nukkit.math.BlockVector3; import cn.nukkit.math.Vector3; -import java.util.Random; - public abstract class TreeGenerator extends cn.nukkit.level.generator.object.BasicGenerator { - /* + /** * returns whether or not a tree can grow into a block * For example, a tree will not grow into stone */ @@ -20,14 +17,13 @@ protected boolean canGrowInto(int id) { return id == Item.AIR || id == Item.LEAVES || id == Item.GRASS || id == Item.DIRT || id == Item.LOG || id == Item.LOG2 || id == Item.SAPLING || id == Item.VINE; } - public void generateSaplings(Level level, Random random, Vector3 pos) { - } - protected void setDirtAt(ChunkManager level, BlockVector3 pos) { - setDirtAt(level, new Vector3(pos.x, pos.y, pos.z)); + if (level.getBlockIdAt(pos.x, pos.y, pos.z) != Item.DIRT) { + this.setBlockAndNotifyAdequately(level, pos, Block.get(BlockID.DIRT)); + } } - /* + /** * sets dirt at a specific location if it isn't already dirt */ protected void setDirtAt(ChunkManager level, Vector3 pos) { diff --git a/src/main/java/cn/nukkit/level/generator/populator/helper/EnsureBelow.java b/src/main/java/cn/nukkit/level/generator/populator/helper/EnsureBelow.java index 710b26a7d56..661ea75a8c5 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/helper/EnsureBelow.java +++ b/src/main/java/cn/nukkit/level/generator/populator/helper/EnsureBelow.java @@ -6,7 +6,8 @@ * @author DaPorkchop_ */ public interface EnsureBelow { - static boolean ensureBelow(int x, int y, int z, int id, FullChunk chunk) { + + static boolean ensureBelow(int x, int y, int z, int id, FullChunk chunk) { return chunk.getBlockId(x, y - 1, z) == id; } } diff --git a/src/main/java/cn/nukkit/level/generator/populator/helper/EnsureCover.java b/src/main/java/cn/nukkit/level/generator/populator/helper/EnsureCover.java index 3bf11d72ef8..071e29934ff 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/helper/EnsureCover.java +++ b/src/main/java/cn/nukkit/level/generator/populator/helper/EnsureCover.java @@ -2,15 +2,21 @@ import cn.nukkit.level.format.FullChunk; -import static cn.nukkit.block.BlockID.AIR; -import static cn.nukkit.block.BlockID.SNOW_LAYER; +import static cn.nukkit.block.BlockID.*; /** * @author DaPorkchop_ */ public interface EnsureCover { - static boolean ensureCover(int x, int y, int z, FullChunk chunk) { + + static boolean ensureCover(int x, int y, int z, FullChunk chunk) { + if (y > 255) return false; int id = chunk.getBlockId(x, y, z); return id == AIR || id == SNOW_LAYER; } + + static boolean ensureWaterCover(int x, int y, int z, FullChunk chunk) { + if (y > 255) return false; + return chunk.getBlockId(x, y, z) == STILL_WATER; + } } diff --git a/src/main/java/cn/nukkit/level/generator/populator/helper/EnsureGrassBelow.java b/src/main/java/cn/nukkit/level/generator/populator/helper/EnsureGrassBelow.java index 773ea9f794a..fdfc11c4fd8 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/helper/EnsureGrassBelow.java +++ b/src/main/java/cn/nukkit/level/generator/populator/helper/EnsureGrassBelow.java @@ -2,13 +2,20 @@ import cn.nukkit.level.format.FullChunk; -import static cn.nukkit.block.BlockID.GRASS; +import static cn.nukkit.block.BlockID.*; /** * @author DaPorkchop_ */ public interface EnsureGrassBelow { - static boolean ensureGrassBelow(int x, int y, int z, FullChunk chunk) { - return EnsureBelow.ensureBelow(x, y, z, GRASS, chunk); + + static boolean ensureGrassBelow(int x, int y, int z, FullChunk chunk) { + int bid = chunk.getBlockId(x, y - 1, z); + return bid == GRASS || bid == PODZOL; + } + + static boolean ensureGrassOrSandBelow(int x, int y, int z, FullChunk chunk) { + int bid = chunk.getBlockId(x, y - 1, z); + return bid == GRASS || bid == PODZOL || bid == SAND; } } diff --git a/src/main/java/cn/nukkit/level/generator/populator/helper/PopulatorHelpers.java b/src/main/java/cn/nukkit/level/generator/populator/helper/PopulatorHelpers.java index 7cad9dfdb41..e8fd53ca12e 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/helper/PopulatorHelpers.java +++ b/src/main/java/cn/nukkit/level/generator/populator/helper/PopulatorHelpers.java @@ -9,13 +9,23 @@ * @author DaPorkchop_ */ public final class PopulatorHelpers implements BlockID { + private static final IntSet nonSolidBlocks = new IntOpenHashSet(); + private static final IntSet nonOceanSolidBlocks = new IntOpenHashSet(); static { nonSolidBlocks.add(AIR); nonSolidBlocks.add(LEAVES); nonSolidBlocks.add(LEAVES2); nonSolidBlocks.add(SNOW_LAYER); + nonSolidBlocks.add(TALL_GRASS); + + nonOceanSolidBlocks.add(AIR); + nonOceanSolidBlocks.add(WATER); + nonOceanSolidBlocks.add(STILL_WATER); + nonOceanSolidBlocks.add(ICE); + nonOceanSolidBlocks.add(PACKED_ICE); + nonOceanSolidBlocks.add(BLUE_ICE); } private PopulatorHelpers() { @@ -28,4 +38,8 @@ public static boolean canGrassStay(int x, int y, int z, FullChunk chunk) { public static boolean isNonSolid(int id) { return nonSolidBlocks.contains(id); } + + public static boolean isNonOceanSolid(int id) { + return nonOceanSolidBlocks.contains(id); + } } diff --git a/src/main/java/cn/nukkit/level/generator/populator/helper/package-info.java b/src/main/java/cn/nukkit/level/generator/populator/helper/package-info.java deleted file mode 100644 index 45d449289ec..00000000000 --- a/src/main/java/cn/nukkit/level/generator/populator/helper/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * This package has lots of helper interfaces for frequently repeated methods - */ -package cn.nukkit.level.generator.populator.helper; diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/MushroomPopulator.java b/src/main/java/cn/nukkit/level/generator/populator/impl/MushroomPopulator.java index feda79d36f1..4cb0d7c6707 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/MushroomPopulator.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/MushroomPopulator.java @@ -12,6 +12,7 @@ * @author DaPorkchop_ */ public class MushroomPopulator extends PopulatorCount { + private final int type; public MushroomPopulator() { @@ -39,7 +40,7 @@ protected int getHighestWorkableBlock(ChunkManager level, int x, int z, FullChun z &= 0xF; for (y = 254; y > 0; --y) { int b = chunk.getBlockId(x, y, z); - if (b == Block.DIRT || b == Block.GRASS) { + if (b == Block.DIRT || b == Block.GRASS || b == Block.MYCELIUM) { break; } else if (b != Block.AIR && b != Block.SNOW_LAYER) { return -1; diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorBamboo.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorBamboo.java new file mode 100644 index 00000000000..3fcc0ab617a --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorBamboo.java @@ -0,0 +1,45 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.block.Block; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.populator.helper.EnsureCover; +import cn.nukkit.level.generator.populator.helper.EnsureGrassBelow; +import cn.nukkit.level.generator.populator.type.PopulatorSurfaceBlock; +import cn.nukkit.math.NukkitRandom; +import cn.nukkit.utils.Utils; + +public class PopulatorBamboo extends PopulatorSurfaceBlock { + + @Override + protected boolean canStay(int x, int y, int z, FullChunk chunk) { + if (chunk instanceof cn.nukkit.level.format.anvil.Chunk) return false; + return EnsureCover.ensureCover(x, y, z, chunk) && EnsureGrassBelow.ensureGrassBelow(x, y, z, chunk); + } + + @Override + protected int getBlockId(int x, int z, NukkitRandom random, FullChunk chunk) { + return Block.BAMBOO << Block.DATA_BITS; + } + + @Override + protected void placeBlock(int x, int y, int z, int id, FullChunk chunk, NukkitRandom random) { + int height = Utils.rand(1, 10); + int part = 0; + while (part < height) { + int yy = y + part; + if (yy < 256 && chunk.getBlockId(x, yy, z) == AIR) { + super.placeBlock(x, yy, z, id, chunk, random); + } else { + break; + } + part++; + } + // Top part + int yy = y + part; + if (yy < 256 && chunk.getBlockId(x, yy, z) == AIR) { + chunk.setBlock(x, yy, z, BAMBOO, 2); + } else { + chunk.setBlock(x, yy - 1, z, BAMBOO, 2); + } + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorBasaltDeltaLava.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorBasaltDeltaLava.java new file mode 100644 index 00000000000..9afe52df594 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorBasaltDeltaLava.java @@ -0,0 +1,45 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitRandom; +import it.unimi.dsi.fastutil.ints.IntArrayList; + +public class PopulatorBasaltDeltaLava extends Populator { + + private static IntArrayList getHighestWorkableBlocks(ChunkManager level, int x, int z) { + int y; + IntArrayList blockYs = new IntArrayList(); + for (y = 128; y > 0; --y) { + int b = level.getBlockIdAt(x, y, z); + if ((b == Block.BASALT || b == Block.BLACKSTONE) && + level.getBlockIdAt(x, y + 1, z) == 0 && + level.getBlockIdAt(x + 1, y, z) != 0 && + level.getBlockIdAt(x - 1, y, z) != 0 && + level.getBlockIdAt(x, y, z + 1) != 0 && + level.getBlockIdAt(x, y, z - 1) != 0 + ) { + blockYs.add(y); + } + } + return blockYs; + } + + @Override + public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + int amount = random.nextBoundedInt(64) + 64; + + for (int i = 0; i < amount; ++i) { + int x = random.nextRange(chunkX << 4, (chunkX << 4) + 15); + int z = random.nextRange(chunkZ << 4, (chunkZ << 4) + 15); + IntArrayList ys = getHighestWorkableBlocks(level, x, z); + for (int y : ys) { + if (y <= 1) continue; + level.setBlockAt(x, y, z, BlockID.STILL_LAVA); + } + } + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorBasaltDeltaMagma.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorBasaltDeltaMagma.java new file mode 100644 index 00000000000..a6cfe81b0e9 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorBasaltDeltaMagma.java @@ -0,0 +1,45 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitRandom; +import it.unimi.dsi.fastutil.ints.IntArrayList; + +public class PopulatorBasaltDeltaMagma extends Populator { + + private static IntArrayList getHighestWorkableBlocks(ChunkManager level, int x, int z) { + int y; + IntArrayList blockYs = new IntArrayList(); + for (y = 128; y > 0; --y) { + int b = level.getBlockIdAt(x, y, z); + if ((b == Block.BASALT || b == Block.BLACKSTONE) && + level.getBlockIdAt(x, y + 1, z) == 0 && ( + level.getBlockIdAt(x + 1, y, z) == BlockID.STILL_LAVA || + level.getBlockIdAt(x - 1, y, z) == BlockID.STILL_LAVA || + level.getBlockIdAt(x, y, z + 1) == BlockID.STILL_LAVA || + level.getBlockIdAt(x, y, z - 1) == BlockID.STILL_LAVA) + ) { + blockYs.add(y); + } + } + return blockYs; + } + + @Override + public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + int amount = random.nextBoundedInt(4) + 20; + + for (int i = 0; i < amount; ++i) { + int x = random.nextRange(chunkX << 4, (chunkX << 4) + 15); + int z = random.nextRange(chunkZ << 4, (chunkZ << 4) + 15); + IntArrayList ys = getHighestWorkableBlocks(level, x, z); + for (int y : ys) { + if (y <= 1) continue; + level.setBlockAt(x, y, z, BlockID.MAGMA); + } + } + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorBasaltDeltaPillar.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorBasaltDeltaPillar.java new file mode 100644 index 00000000000..1d9368e2637 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorBasaltDeltaPillar.java @@ -0,0 +1,47 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitRandom; +import it.unimi.dsi.fastutil.ints.IntArrayList; + +public class PopulatorBasaltDeltaPillar extends Populator { + + private static IntArrayList getHighestWorkableBlocks(ChunkManager level, int x, int z) { + int y; + IntArrayList blockYs = new IntArrayList(); + for (y = 128; y > 0; --y) { + int b = level.getBlockIdAt(x, y, z); + if ((b == Block.BASALT || b == Block.BLACKSTONE) && level.getBlockIdAt(x, y + 1, z) == 0) { + blockYs.add(y + 1); + } + } + return blockYs; + } + + @Override + public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + int amount = random.nextBoundedInt(128) + 128; + + IntArrayList visited = new IntArrayList(); + for (int i = 0; i < amount; ++i) { + int x = random.nextRange(chunkX << 4, (chunkX << 4) + 15); + int z = random.nextRange(chunkZ << 4, (chunkZ << 4) + 15); + int pos = (x >> 1) + (z << 1); + if (visited.contains(pos)) continue; + IntArrayList ys = getHighestWorkableBlocks(level, x, z); + for (int y : ys) { + if (y <= 1) continue; + if (random.nextBoundedInt(5) == 0) continue; + for (int randomHeight = 0; randomHeight < random.nextBoundedInt(5) + 1; randomHeight++) { + int placeLocation = y + randomHeight; + level.setBlockAt(x, placeLocation, z, BlockID.BASALT); + } + visited.add(pos); + } + } + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorBedrock.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorBedrock.java index 6c231cb29c4..03b22372f79 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorBedrock.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorBedrock.java @@ -5,24 +5,44 @@ import cn.nukkit.level.generator.populator.type.Populator; import cn.nukkit.math.NukkitRandom; -import static cn.nukkit.block.BlockID.BEDROCK; - /** * @author DaPorkchop_ * * Places bedrock on the bottom of the world */ public class PopulatorBedrock extends Populator { + + private final boolean nether; + + public PopulatorBedrock() { + this(false); + } + + public PopulatorBedrock(boolean nether) { + this.nether = nether; + } + @Override public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { chunk.setBlockId(x, 0, z, BEDROCK); + for (int i = 1; i < 5; i++) { - if (random.nextBoundedInt(i) == 0) { //decreasing amount + if (random.nextBoundedInt(i) == 0) { // decreasing amount chunk.setBlockId(x, i, z, BEDROCK); } } + + if (this.nether) { + chunk.setBlockId(x, 127, z, BEDROCK); + + for (int i = 126; i > 122; i--) { + if (random.nextBoundedInt(127 - i) == 0) { // decreasing amount + chunk.setBlockId(x, i, z, BEDROCK); + } + } + } } } } diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorCactus.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorCactus.java index b6057b2ec8d..4d14b3e2447 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorCactus.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorCactus.java @@ -1,24 +1,47 @@ package cn.nukkit.level.generator.populator.impl; +import cn.nukkit.block.Block; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.generator.populator.helper.EnsureBelow; import cn.nukkit.level.generator.populator.helper.EnsureCover; import cn.nukkit.level.generator.populator.type.PopulatorSurfaceBlock; +import cn.nukkit.math.BlockFace; import cn.nukkit.math.NukkitRandom; -import static cn.nukkit.block.BlockID.CACTUS; +import java.util.concurrent.ThreadLocalRandom; /** * @author DaPorkchop_ */ public class PopulatorCactus extends PopulatorSurfaceBlock { + + private boolean checkSurroundingBlocks(int x, int y, int z, FullChunk chunk) { + int b = chunk.getBlockId(x + BlockFace.NORTH.getXOffset() & 0xF, y, z + BlockFace.NORTH.getZOffset() & 0xF); + if (b != Block.AIR) return false; + b = chunk.getBlockId(x + BlockFace.EAST.getXOffset() & 0xF, y, z + BlockFace.EAST.getZOffset() & 0xF); + if (b != Block.AIR) return false; + b = chunk.getBlockId(x + BlockFace.SOUTH.getXOffset() & 0xF, y, z + BlockFace.SOUTH.getZOffset() & 0xF); + if (b != Block.AIR) return false; + b = chunk.getBlockId(x + BlockFace.WEST.getXOffset() & 0xF, y, z + BlockFace.WEST.getZOffset() & 0xF); + return b == Block.AIR; + } + @Override protected boolean canStay(int x, int y, int z, FullChunk chunk) { - return EnsureCover.ensureCover(x, y, z, chunk) && EnsureBelow.ensureBelow(x, y, z, SAND, chunk); + return EnsureCover.ensureCover(x, y, z, chunk) && EnsureBelow.ensureBelow(x, y, z, SAND, chunk) && checkSurroundingBlocks(x, y, z, chunk); } @Override protected int getBlockId(int x, int z, NukkitRandom random, FullChunk chunk) { - return (CACTUS << 4) | 1; + return (Block.CACTUS << Block.DATA_BITS) | 1; + } + + @Override + protected void placeBlock(int x, int y, int z, int id, FullChunk chunk, NukkitRandom random) { + int height = ThreadLocalRandom.current().nextInt(3) + 1; + if (y + height > 255) return; + for (int i = 0; i < height; i++) { + chunk.setFullBlockId(x, y + i, z, id); + } } } diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorCaves.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorCaves.java index 59eaed143aa..5b2b156b94c 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorCaves.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorCaves.java @@ -2,7 +2,6 @@ import cn.nukkit.block.Block; import cn.nukkit.level.ChunkManager; -import cn.nukkit.level.biome.EnumBiome; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.biome.Biome; import cn.nukkit.level.biome.type.CoveredBiome; @@ -13,7 +12,7 @@ import java.util.Random; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class PopulatorCaves extends Populator { @@ -22,11 +21,11 @@ public class PopulatorCaves extends Populator { private Random random; - public static int caveRarity = 7;//7 - public static int caveFrequency = 40;//40 + public static int caveRarity = 7; + public static int caveFrequency = 40; public static int caveMinAltitude = 8; public static int caveMaxAltitude = 67; - public static int individualCaveRarity = 25;//25 + public static int individualCaveRarity = 25; public static int caveSystemFrequency = 1; public static int caveSystemPocketChance = 0; public static int caveSystemPocketMinSize = 0; @@ -61,8 +60,8 @@ protected void generateCaveNode(long seed, FullChunk chunk, double x, double y, int chunkX = chunk.getX(); int chunkZ = chunk.getZ(); - double realX = chunkX * 16 + 8; - double realZ = chunkZ * 16 + 8; + double realX = (chunkX << 4) + 8; + double realZ = (chunkZ << 4) + 8; float f1 = 0.0F; float f2 = 0.0F; @@ -70,17 +69,17 @@ protected void generateCaveNode(long seed, FullChunk chunk, double x, double y, Random localRandom = new Random(seed); if (maxAngle <= 0) { - int checkAreaSize = this.checkAreaSize * 16 - 16; - maxAngle = checkAreaSize - localRandom.nextInt(checkAreaSize / 4); + int checkAreaSize = (this.checkAreaSize << 4) - 16; + maxAngle = checkAreaSize - localRandom.nextInt(checkAreaSize >> 2); } boolean isLargeCave = false; if (angle == -1) { - angle = maxAngle / 2; + angle = maxAngle >> 1; isLargeCave = true; } - int randomAngel = localRandom.nextInt(maxAngle / 2) + maxAngle / 4; + int randomAngel = localRandom.nextInt(maxAngle >> 1) + (maxAngle >> 2); boolean bigAngel = localRandom.nextInt(6) == 0; for (; angle < maxAngle; angle++) { @@ -129,14 +128,14 @@ protected void generateCaveNode(long seed, FullChunk chunk, double x, double y, continue; - int xFrom = MathHelper.floor(x - offsetXZ) - chunkX * 16 - 1; - int xTo = MathHelper.floor(x + offsetXZ) - chunkX * 16 + 1; + int xFrom = MathHelper.floor(x - offsetXZ) - (chunkX << 4) - 1; + int xTo = MathHelper.floor(x + offsetXZ) - (chunkX << 4) + 1; int yFrom = MathHelper.floor(y - offsetY) - 1; int yTo = MathHelper.floor(y + offsetY) + 1; - int zFrom = MathHelper.floor(z - offsetXZ) - chunkZ * 16 - 1; - int zTo = MathHelper.floor(z + offsetXZ) - chunkZ * 16 + 1; + int zFrom = MathHelper.floor(z - offsetXZ) - (chunkZ << 4) - 1; + int zTo = MathHelper.floor(z + offsetXZ) - (chunkZ << 4) + 1; if (xFrom < 0) xFrom = 0; @@ -176,22 +175,21 @@ protected void generateCaveNode(long seed, FullChunk chunk, double x, double y, // Generate cave for (int xx = xFrom; xx < xTo; xx++) { - double modX = (xx + chunkX * 16 + 0.5D - x) / offsetXZ; + double modX = (xx + (chunkX << 4) + 0.5D - x) / offsetXZ; for (int zz = zFrom; zz < zTo; zz++) { - double modZ = (zz + chunkZ * 16 + 0.5D - z) / offsetXZ; + double modZ = (zz + (chunkZ << 4) + 0.5D - z) / offsetXZ; boolean grassFound = false; if (modX * modX + modZ * modZ < 1.0D) { for (int yy = yTo; yy > yFrom; yy--) { double modY = ((yy - 1) + 0.5D - y) / offsetY; - if ((modY > -0.7D) && (modX * modX + modY * modY + modZ * modZ < 1.0D)) { - Biome biome = EnumBiome.getBiome(chunk.getBiomeId(xx, zz)); + if ((modY > -0.7) && (modX * modX + modY * modY + modZ * modZ < 1.0D)) { + Biome biome = Biome.getBiome(chunk.getBiomeId(xx, zz)); if (!(biome instanceof CoveredBiome)) { continue; } int material = chunk.getBlockId(xx, yy, zz); - int materialAbove = chunk.getBlockId(xx, yy + 1, zz); if (material == Block.GRASS || material == Block.MYCELIUM) { grassFound = true; } @@ -230,16 +228,16 @@ protected void generateChunk(int chunkX, int chunkZ, FullChunk generatingChunkBu i = 0; for (int j = 0; j < i; j++) { - double x = chunkX * 16 + this.random.nextInt(16); + double x = (chunkX << 4) + this.random.nextInt(16); double y; if (evenCaveDistribution) - y = numberInRange(random, caveMinAltitude, caveMaxAltitude); + y = MathHelper.getRandomNumberInRange(random, caveMinAltitude, caveMaxAltitude); else y = this.random.nextInt(this.random.nextInt(caveMaxAltitude - caveMinAltitude + 1) + 1) + caveMinAltitude; - double z = chunkZ * 16 + this.random.nextInt(16); + double z = (chunkZ << 4) + this.random.nextInt(16); int count = caveSystemFrequency; boolean largeCaveSpawned = false; @@ -249,11 +247,11 @@ protected void generateChunk(int chunkX, int chunkZ, FullChunk generatingChunkBu } if ((largeCaveSpawned) || (this.random.nextInt(100) <= caveSystemPocketChance - 1)) { - count += numberInRange(random, caveSystemPocketMinSize, caveSystemPocketMaxSize); + count += MathHelper.getRandomNumberInRange(random, caveSystemPocketMinSize, caveSystemPocketMaxSize); } while (count > 0) { count--; - float f1 = this.random.nextFloat() * 3.141593F * 2.0F; + float f1 = this.random.nextFloat() * 6.283186f; float f2 = (this.random.nextFloat() - 0.5F) * 2.0F / 8.0F; float f3 = this.random.nextFloat() * 2.0F + this.random.nextFloat(); @@ -261,8 +259,4 @@ protected void generateChunk(int chunkX, int chunkZ, FullChunk generatingChunkBu } } } - - public static int numberInRange(Random random, int min, int max) { - return min + random.nextInt(max - min + 1); - } } diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorCrimsonForestGround.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorCrimsonForestGround.java new file mode 100644 index 00000000000..50ad9c8f112 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorCrimsonForestGround.java @@ -0,0 +1,50 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.block.Block; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitRandom; +import it.unimi.dsi.fastutil.ints.IntArrayList; + +public class PopulatorCrimsonForestGround extends Populator { + + private static IntArrayList getHighestWorkableBlocks(ChunkManager level, int x, int z) { + int y; + IntArrayList blockYs = new IntArrayList(); + for (y = 128; y > 0; --y) { + int b = level.getBlockIdAt(x, y, z); + if ((b == Block.CRIMSON_NYLIUM) && level.getBlockIdAt(x, y + 1, z) == 0) { + blockYs.add(y + 1); + } + } + return blockYs; + } + + @Override + public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + int amount = random.nextBoundedInt(64) + 32; + + for (int i = 0; i < amount; ++i) { + int x = random.nextRange(chunkX << 4, (chunkX << 4) + 15); + int z = random.nextRange(chunkZ << 4, (chunkZ << 4) + 15); + IntArrayList ys = getHighestWorkableBlocks(level, x, z); + for (int y : ys) { + if (y <= 1) continue; + + int blockID; + if (random.nextBoundedInt(6) == 0) { + if (random.nextBoundedInt(8) == 1) { + blockID = WARPED_FUNGUS; + } else { + blockID = CRIMSON_FUNGUS; + } + } else { + blockID = CRIMSON_ROOTS; + } + + level.setBlockAt(x, y, z, blockID); + } + } + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorCrimsonFungus.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorCrimsonFungus.java new file mode 100644 index 00000000000..46d5c18aada --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorCrimsonFungus.java @@ -0,0 +1,40 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.block.Block; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.object.tree.ObjectCrimsonTree; +import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitRandom; +import it.unimi.dsi.fastutil.ints.IntArrayList; + +public class PopulatorCrimsonFungus extends Populator { + + private static IntArrayList getHighestWorkableBlocks(ChunkManager level, int x, int z) { + int y; + IntArrayList blockYs = new IntArrayList(); + for (y = 128; y > 0; --y) { + int b = level.getBlockIdAt(x, y, z); + if ((b == Block.CRIMSON_NYLIUM) && level.getBlockIdAt(x, y + 1, z) == 0) { + blockYs.add(y + 1); + } + } + return blockYs; + } + + @Override + public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + int amount = random.nextBoundedInt(6) + 3; + + for (int i = 0; i < amount; ++i) { + int x = random.nextRange(chunkX << 4, (chunkX << 4) + 15); + int z = random.nextRange(chunkZ << 4, (chunkZ << 4) + 15); + IntArrayList ys = getHighestWorkableBlocks(level, x, z); + for (int y : ys) { + if (y <= 1) continue; + if (random.nextBoundedInt(4) == 1) continue; + new ObjectCrimsonTree().placeObject(level, x, y, z, random); + } + } + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorDeadBush.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorDeadBush.java index 2b9e09e9812..5d3a97094ea 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorDeadBush.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorDeadBush.java @@ -1,5 +1,6 @@ package cn.nukkit.level.generator.populator.impl; +import cn.nukkit.block.Block; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.generator.populator.helper.EnsureBelow; import cn.nukkit.level.generator.populator.helper.EnsureCover; @@ -18,6 +19,6 @@ protected boolean canStay(int x, int y, int z, FullChunk chunk) { @Override protected int getBlockId(int x, int z, NukkitRandom random, FullChunk chunk) { - return DEAD_BUSH << 4; + return Block.DEAD_BUSH << Block.DATA_BITS; } } diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorDoublePlant.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorDoublePlant.java index 9218e54171f..9cb0aa323be 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorDoublePlant.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorDoublePlant.java @@ -1,32 +1,32 @@ package cn.nukkit.level.generator.populator.impl; +import cn.nukkit.block.Block; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.generator.populator.helper.EnsureCover; import cn.nukkit.level.generator.populator.helper.EnsureGrassBelow; import cn.nukkit.level.generator.populator.type.PopulatorSurfaceBlock; import cn.nukkit.math.NukkitRandom; -import static cn.nukkit.block.BlockID.DOUBLE_PLANT; - /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class PopulatorDoublePlant extends PopulatorSurfaceBlock { - private int type; - public PopulatorDoublePlant(int type) { + private final int type; + + public PopulatorDoublePlant(int type) { this.type = type; } @Override protected boolean canStay(int x, int y, int z, FullChunk chunk) { - return EnsureCover.ensureCover(x, y, z, chunk) && EnsureCover.ensureCover(x, y + 1, z, chunk) && EnsureGrassBelow.ensureGrassBelow(x, y, z, chunk); + return y < 255 && EnsureCover.ensureCover(x, y, z, chunk) && EnsureCover.ensureCover(x, y + 1, z, chunk) && EnsureGrassBelow.ensureGrassBelow(x, y, z, chunk); } @Override protected int getBlockId(int x, int z, NukkitRandom random, FullChunk chunk) { - return (DOUBLE_PLANT << 4) | type; + return (Block.DOUBLE_PLANT << Block.DATA_BITS) | type; } @Override diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorFallenTree.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorFallenTree.java new file mode 100644 index 00000000000..9e9ae786c69 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorFallenTree.java @@ -0,0 +1,69 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.block.Block; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.object.tree.ObjectFallenTree; +import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitMath; +import cn.nukkit.math.NukkitRandom; + +public class PopulatorFallenTree extends Populator { + + private ChunkManager level; + private int type; + + public void setType(int type) { //0 = oak, 1 = birch + this.type = type; + } + + @Override + public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + if (random.nextRange(0, 3) != 1) return; + this.level = level; + int amount = 1; + for (int i = 0; i < amount; ++i) { + int x = NukkitMath.randomRange(random, chunkX << 4, (chunkX << 4) + 15); + int z = NukkitMath.randomRange(random, chunkZ << 4, (chunkZ << 4) + 15); + int y = this.getHighestWorkableBlock(x, z); + if (y == -1) { + continue; + } + if (level.getBlockIdAt(x, y, z) != Block.AIR || + level.getBlockIdAt(x + 1, y, z) != Block.AIR || + level.getBlockIdAt(x, y, z + 1) != Block.AIR || + level.getBlockIdAt(x - 1, y, z) != Block.AIR || + level.getBlockIdAt(x, y, z - 1) != Block.AIR || + level.getBlockIdAt(x + 1, y - 1, z) != Block.GRASS || + level.getBlockIdAt(x, y - 1, z + 1) != Block.GRASS || + level.getBlockIdAt(x - 1, y - 1, z) != Block.GRASS || + level.getBlockIdAt(x, y - 1, z - 1) != Block.GRASS || + level.getBlockIdAt(x + 2, y - 1, z) != Block.GRASS || + level.getBlockIdAt(x, y - 1, z + 2) != Block.GRASS || + level.getBlockIdAt(x - 2, y - 1, z) != Block.GRASS || + level.getBlockIdAt(x, y - 1, z - 2) != Block.GRASS || + level.getBlockIdAt(x - 3, y - 1, z) != Block.GRASS || + level.getBlockIdAt(x, y - 1, z - 3) != Block.GRASS || + level.getBlockIdAt(x + 2, y, z) != Block.AIR || + level.getBlockIdAt(x, y, z + 2) != Block.AIR || + level.getBlockIdAt(x + 3, y, z) != Block.AIR || + level.getBlockIdAt(x, y, z + 3) != Block.AIR) { + continue; + } + new ObjectFallenTree(this.level, x, y, z, type, random); + } + } + + private int getHighestWorkableBlock(int x, int z) { + int y; + + for (y = 127; y > 0; --y) { + int b = this.level.getBlockIdAt(x, y, z); + if (b == Block.GRASS) { + break; + } + } + + return ++y; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorFlower.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorFlower.java index 77d3f09513e..b73700c359b 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorFlower.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorFlower.java @@ -1,14 +1,15 @@ package cn.nukkit.level.generator.populator.impl; +import cn.nukkit.block.Block; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.generator.populator.helper.EnsureCover; import cn.nukkit.level.generator.populator.helper.EnsureGrassBelow; import cn.nukkit.level.generator.populator.type.PopulatorSurfaceBlock; import cn.nukkit.math.NukkitRandom; +import cn.nukkit.utils.Utils; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.ThreadLocalRandom; /** * @author Angelic47, Niall Lindsay (Niall7459) @@ -17,6 +18,7 @@ *

*/ public class PopulatorFlower extends PopulatorSurfaceBlock { + private final List flowerTypes = new ArrayList<>(); public void addType(int a, int b) { @@ -32,11 +34,11 @@ public List getTypes() { @Override protected void placeBlock(int x, int y, int z, int id, FullChunk chunk, NukkitRandom random) { - if (flowerTypes.size() != 0) { - int[] type = flowerTypes.get(ThreadLocalRandom.current().nextInt(flowerTypes.size())); - chunk.setFullBlockId(x, y, z, (type[0] << 4) | type[1]); + if (!flowerTypes.isEmpty()) { + int[] type = flowerTypes.get(Utils.random.nextInt(flowerTypes.size())); + chunk.setFullBlockId(x, y, z, (type[0] << Block.DATA_BITS) | type[1]); if (type[0] == DOUBLE_PLANT) { - chunk.setFullBlockId(x, y + 1, z, (type[0] << 4) | (8 | type[1])); + chunk.setFullBlockId(x, y + 1, z, (type[0] << Block.DATA_BITS) | (8 | type[1])); } } } diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorForestRock.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorForestRock.java new file mode 100644 index 00000000000..eccb9249a75 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorForestRock.java @@ -0,0 +1,72 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.block.Block; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.populator.helper.EnsureCover; +import cn.nukkit.level.generator.populator.helper.EnsureGrassBelow; +import cn.nukkit.level.generator.populator.type.PopulatorSurfaceBlock; +import cn.nukkit.math.NukkitRandom; + +public class PopulatorForestRock extends PopulatorSurfaceBlock { + + @Override + protected boolean canStay(int x, int y, int z, FullChunk chunk) { + return EnsureCover.ensureCover(x, y, z, chunk) && EnsureGrassBelow.ensureGrassBelow(x, y, z, chunk); + } + + @Override + protected int getBlockId(int x, int z, NukkitRandom random, FullChunk chunk) { + return MOSSY_STONE << Block.DATA_BITS; + } + + @Override + protected void populateCount(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + int radiusX = random.nextBoundedInt(2); + int radiusZ = random.nextBoundedInt(2); + int radiusY = random.nextBoundedInt(2); + float f = (radiusX + radiusZ + radiusY) * 0.333F + 0.5F; + float fsquared = f * f; + if (fsquared <= 0.7) return; // Skip one block sized ones + + int rx = random.nextBoundedInt(16); + int rz = random.nextBoundedInt(16); + int sourceX = (chunkX << 4) + rx; + int sourceZ = (chunkZ << 4) + rz; + int sourceY = getHighestWorkableBlock(level, rx, rz, chunk); + + boolean groundReached = false; + while (sourceY > 3) { + sourceY--; + int block = level.getBlockIdAt(sourceX, sourceY, sourceZ); + if (block == 0) { + continue; + } + if (block == PODZOL || block == GRASS || block == DIRT || block == STONE) { + groundReached = true; + sourceY++; + break; + } + } + + if (!groundReached || level.getBlockIdAt(sourceX, sourceY, sourceZ) != 0) { + return; + } + + for (int x = -radiusX; x <= radiusX; x++) { + float xsquared = x * x; + for (int z = -radiusZ; z <= radiusZ; z++) { + float zsquared = z * z; + for (int y = -radiusY; y <= radiusY; y++) { + if (xsquared + zsquared + y * y > fsquared) { + continue; + } + int bid = level.getBlockIdAt(sourceX + x, sourceY + y, sourceZ + z); + if (bid == AIR || bid == PODZOL || bid == GRASS || bid == DIRT || bid == STONE) { + level.setBlockFullIdAt(sourceX + x, sourceY + y, sourceZ + z, MOSSY_STONE << Block.DATA_BITS); + } + } + } + } + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorGlowStone.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorGlowStone.java index 7d0575fb869..ab7ed3f671c 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorGlowStone.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorGlowStone.java @@ -2,28 +2,41 @@ import cn.nukkit.block.Block; import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.biome.Biome; +import cn.nukkit.level.biome.EnumBiome; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.generator.populator.type.Populator; import cn.nukkit.math.NukkitMath; import cn.nukkit.math.NukkitRandom; public class PopulatorGlowStone extends Populator { + @Override public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + if (random.nextBoundedInt(9) < 8 || Biome.getBiome(chunk.getBiomeId(7, 7)).getId() == EnumBiome.SOULSAND_VALLEY.id) return; int x = NukkitMath.randomRange(random, chunkX << 4, (chunkX << 4) + 15); int z = NukkitMath.randomRange(random, chunkZ << 4, (chunkZ << 4) + 15); - int y = this.getHighestWorkableBlock(chunk, x & 0xF, z & 0xF); - if (y != -1 && level.getBlockIdAt(x, y, z) != NETHERRACK) { - int count = NukkitMath.randomRange(random, 40, 60); + int y = getHighestWorkableBlock(chunk, x & 0xF, z & 0xF) + 1; + boolean vertical = random.nextBoolean(); + if (y != -1) { + int size = random.nextRange(3, 6); + int count = NukkitMath.randomRange(random, 20 + (size << 1), 30 + (size << 1)); + if (vertical && size > 3) size--; for (int i = 0; i < count; i++) { - level.setBlockAt(x + (random.nextBoundedInt(7) - 3), y + (random.nextBoundedInt(9) - 4), z + (random.nextBoundedInt(7) - 3), GLOWSTONE); + int yy = y + (random.nextBoundedInt(size) - random.nextRange(3, vertical ? 5 : 3)); + if (yy <= 0) continue; + int xx = x + (random.nextBoundedInt(size) - 3); + int zz = z + (random.nextBoundedInt(size) - 3); + if (chunk.getBlockId(xx & 0x0f, yy & 0x0ff, zz & 0x0f) == AIR) { + level.setBlockAt(xx, yy, zz, GLOWSTONE); + } } } } - private int getHighestWorkableBlock(FullChunk chunk, int x, int z) { + private static int getHighestWorkableBlock(FullChunk chunk, int x, int z) { int y; - //start scanning a bit lower down to allow space for placing on top + // Start scanning a bit lower down to allow space for placing on top for (y = 120; y >= 0; y--) { int b = chunk.getBlockId(x, y, z); if (b == Block.AIR) { diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorGrass.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorGrass.java index d381a3dbdb3..518a69eecaf 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorGrass.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorGrass.java @@ -1,15 +1,17 @@ package cn.nukkit.level.generator.populator.impl; +import cn.nukkit.block.Block; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.generator.populator.helper.PopulatorHelpers; import cn.nukkit.level.generator.populator.type.PopulatorSurfaceBlock; import cn.nukkit.math.NukkitRandom; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class PopulatorGrass extends PopulatorSurfaceBlock { + @Override protected boolean canStay(int x, int y, int z, FullChunk chunk) { return PopulatorHelpers.canGrassStay(x, y, z, chunk); @@ -17,6 +19,6 @@ protected boolean canStay(int x, int y, int z, FullChunk chunk) { @Override protected int getBlockId(int x, int z, NukkitRandom random, FullChunk chunk) { - return (TALL_GRASS << 4) | 1; + return (TALL_GRASS << Block.DATA_BITS) | 1; } } diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorGroundCover.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorGroundCover.java index 3feec7fa3b1..b3b9744bdbe 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorGroundCover.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorGroundCover.java @@ -1,7 +1,6 @@ package cn.nukkit.level.generator.populator.impl; import cn.nukkit.level.ChunkManager; -import cn.nukkit.level.biome.EnumBiome; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.biome.Biome; import cn.nukkit.level.biome.type.CoveredBiome; @@ -10,18 +9,19 @@ /** * @author DaPorkchop_ + * Nukkit Project */ public class PopulatorGroundCover extends Populator { + @Override public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { - //reverse iteration to 0 is faster for (int x = 15; x >= 0; x--) { for (int z = 15; z >= 0; z--) { - Biome realBiome = EnumBiome.getBiome(chunk.getBiomeId(x, z)); + Biome realBiome = Biome.getBiome(chunk.getBiomeId(x, z)); if (realBiome instanceof CoveredBiome) { ((CoveredBiome) realBiome).doCover(x, z, chunk); } } } } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorGroundFire.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorGroundFire.java index 3c93cb88e48..4da61438333 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorGroundFire.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorGroundFire.java @@ -12,6 +12,7 @@ * @author DaPorkchop_ */ public class PopulatorGroundFire extends PopulatorSurfaceBlock { + @Override protected boolean canStay(int x, int y, int z, FullChunk chunk) { return EnsureCover.ensureCover(x, y, z, chunk) && EnsureBelow.ensureBelow(x, y, z, NETHERRACK, chunk); @@ -19,24 +20,25 @@ protected boolean canStay(int x, int y, int z, FullChunk chunk) { @Override protected int getBlockId(int x, int z, NukkitRandom random, FullChunk chunk) { - return FIRE << 4; + return Block.FIRE << Block.DATA_BITS; } @Override protected void placeBlock(int x, int y, int z, int id, FullChunk chunk, NukkitRandom random) { super.placeBlock(x, y, z, id, chunk, random); - chunk.setBlockLight(x, y, z, Block.light[FIRE]); + chunk.setBlockLight(x, y, z, Block.getBlockLight(FIRE)); } @Override protected int getHighestWorkableBlock(ChunkManager level, int x, int z, FullChunk chunk) { - int y; - for (y = 0; y <= 127; ++y) { - int b = chunk.getBlockId(x, y, z); - if (b == Block.AIR) { + int height = 0; + for (int y = 0; y < 127; ++y) { + height = y; + int blockId = chunk.getBlockId(x, y, z); + if (blockId == Block.AIR) { break; } } - return y == 0 ? -1 : y; + return height == 0 ? -1 : height; } } diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorKelp.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorKelp.java new file mode 100644 index 00000000000..b5d553db6e6 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorKelp.java @@ -0,0 +1,48 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockLayer; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.format.leveldb.structure.LevelDBChunk; +import cn.nukkit.level.generator.populator.helper.EnsureBelow; +import cn.nukkit.level.generator.populator.helper.EnsureCover; +import cn.nukkit.level.generator.populator.type.PopulatorOceanFloorSurfaceBlock; +import cn.nukkit.math.NukkitRandom; +import cn.nukkit.utils.Utils; + +public class PopulatorKelp extends PopulatorOceanFloorSurfaceBlock { + + @Override + protected boolean canStay(int x, int y, int z, FullChunk chunk) { + if (chunk instanceof cn.nukkit.level.format.anvil.Chunk) return false; + return EnsureCover.ensureWaterCover(x, y, z, chunk) && EnsureBelow.ensureBelow(x, y, z, GRAVEL, chunk); + } + + @Override + protected int getBlockId(int x, int z, NukkitRandom random, FullChunk chunk) { + return Block.BLOCK_KELP << Block.DATA_BITS; + } + + @Override + protected void placeBlock(int x, int y, int z, int id, FullChunk chunk, NukkitRandom random) { + int height = Utils.rand(1, 25); + int lastTop = y; + + boolean leveldb = chunk instanceof LevelDBChunk; + + for (int part = 0; part < height; part++) { + int yy = y + part; + if (yy < 256 && chunk.getBlockId(x, yy, z) == STILL_WATER && chunk.getBlockId(x, yy + 1, z) == STILL_WATER) { + chunk.setBlock(x, yy, z, Block.BLOCK_KELP, leveldb ? part : (int) (part / 1.6)); + chunk.setFullBlockId(x, yy, z, BlockLayer.WATERLOGGED, Block.STILL_WATER << Block.DATA_BITS); + lastTop = yy; + } else { + lastTop = yy - 1; + break; + } + } + + // Stop top part growing + chunk.setBlockData(x, lastTop, z, leveldb ? 24 : 15); + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorLava.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorLava.java index c2f954a9474..73db47f2958 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorLava.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorLava.java @@ -7,6 +7,7 @@ import cn.nukkit.math.NukkitRandom; public class PopulatorLava extends Populator { + private ChunkManager level; private int randomAmount; private int baseAmount; @@ -28,15 +29,13 @@ public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom ra int amount = random.nextRange(0, this.randomAmount + 1) + this.baseAmount; int bx = chunkX << 4; int bz = chunkZ << 4; - int tx = bx + 15; - int tz = bz + 15; for (int i = 0; i < amount; ++i) { int x = random.nextRange(0, 15); int z = random.nextRange(0, 15); - int y = this.getHighestWorkableBlock(chunk, x, z); + int y = getHighestWorkableBlock(chunk, x, z); if (y != -1 && chunk.getBlockId(x, y, z) == Block.AIR) { chunk.setBlock(x, y, z, Block.LAVA); - chunk.setBlockLight(x, y, z, Block.light[Block.LAVA]); + chunk.setBlockLight(x, y, z, Block.getBlockLight(Block.LAVA)); this.lavaSpread(bx + x, y, bz + z); } } @@ -141,7 +140,6 @@ private int calculateFlowCost(int xx, int yy, int zz, int accumulatedCost, int p (j == 3 && previousDirection == 2) ) { int x = xx; - int y = yy; int z = zz; if (j == 0) { --x; @@ -152,17 +150,17 @@ private int calculateFlowCost(int xx, int yy, int zz, int accumulatedCost, int p } else if (j == 3) { ++z; } - if (!this.canFlowInto(x, y, z)) { + if (!this.canFlowInto(x, yy, z)) { continue; - } else if (this.canFlowInto(x, y, z) && this.level.getBlockDataAt(x, y, z) == 0) { + } else if (this.canFlowInto(x, yy, z) && this.level.getBlockDataAt(x, yy, z) == 0) { continue; - } else if (this.canFlowInto(x, y - 1, z)) { + } else if (this.canFlowInto(x, yy - 1, z)) { return accumulatedCost; } if (accumulatedCost >= 4) { continue; } - int realCost = this.calculateFlowCost(x, y, z, accumulatedCost + 1, j); + int realCost = this.calculateFlowCost(x, yy, z, accumulatedCost + 1, j); if (realCost < cost) { cost = realCost; } @@ -177,7 +175,6 @@ private boolean[] getOptimalFlowDirections(int xx, int yy, int zz) { for (int j = 0; j < 4; ++j) { flowCost[j] = 1000; int x = xx; - int y = yy; int z = zz; if (j == 0) { --x; @@ -188,10 +185,10 @@ private boolean[] getOptimalFlowDirections(int xx, int yy, int zz) { } else if (j == 3) { ++z; } - if (this.canFlowInto(x, y - 1, z)) { + if (this.canFlowInto(x, yy - 1, z)) { flowCost[j] = 0; } else { - flowCost[j] = this.calculateFlowCost(x, y, z, 1, j); + flowCost[j] = this.calculateFlowCost(x, yy, z, 1, j); } } int minCost = flowCost[0]; @@ -217,7 +214,7 @@ private int getSmallestFlowDecay(int x1, int y1, int z1, int x2, int y2, int z2, } - private int getHighestWorkableBlock(FullChunk chunk, int x, int z) { + private static int getHighestWorkableBlock(FullChunk chunk, int x, int z) { int y; for (y = 127; y >= 0; y--) { int b = chunk.getBlockId(x, y, z); diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorLilyPad.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorLilyPad.java index d6fd6d0ed17..fc0241ad472 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorLilyPad.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorLilyPad.java @@ -1,5 +1,6 @@ package cn.nukkit.level.generator.populator.impl; +import cn.nukkit.block.Block; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.generator.populator.helper.EnsureBelow; import cn.nukkit.level.generator.populator.helper.EnsureCover; @@ -18,6 +19,6 @@ protected boolean canStay(int x, int y, int z, FullChunk chunk) { @Override protected int getBlockId(int x, int z, NukkitRandom random, FullChunk chunk) { - return WATER_LILY << 4; + return Block.LILY_PAD << Block.DATA_BITS; } } diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorMelon.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorMelon.java index e3271cad822..ca4d65dcf47 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorMelon.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorMelon.java @@ -1,5 +1,6 @@ package cn.nukkit.level.generator.populator.impl; +import cn.nukkit.block.Block; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.generator.populator.helper.EnsureCover; import cn.nukkit.level.generator.populator.helper.EnsureGrassBelow; @@ -10,6 +11,7 @@ * @author DaPorkchop_ */ public class PopulatorMelon extends PopulatorSurfaceBlock { + @Override protected boolean canStay(int x, int y, int z, FullChunk chunk) { return EnsureCover.ensureCover(x, y, z, chunk) && EnsureGrassBelow.ensureGrassBelow(x, y, z, chunk); @@ -17,6 +19,6 @@ protected boolean canStay(int x, int y, int z, FullChunk chunk) { @Override protected int getBlockId(int x, int z, NukkitRandom random, FullChunk chunk) { - return MELON_BLOCK << 4; + return Block.MELON_BLOCK << Block.DATA_BITS; } } diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorMineshaft.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorMineshaft.java deleted file mode 100644 index f5f970201fe..00000000000 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorMineshaft.java +++ /dev/null @@ -1,25 +0,0 @@ -package cn.nukkit.level.generator.populator.impl; - -import cn.nukkit.level.ChunkManager; -import cn.nukkit.level.format.FullChunk; -import cn.nukkit.level.generator.populator.type.Populator; -import cn.nukkit.math.NukkitRandom; - -public class PopulatorMineshaft extends Populator { - - /** - * @author Niall Lindsay (Niall7459) - *

- * Nukkit Project - *

- * - * WIP - */ - - @Override - public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { - // TODO Auto-generated method stub - - } - -} diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorNetherFire.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorNetherFire.java new file mode 100644 index 00000000000..b44ee25ab66 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorNetherFire.java @@ -0,0 +1,47 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitRandom; +import it.unimi.dsi.fastutil.ints.IntArrayList; + +public class PopulatorNetherFire extends Populator { + + private final int fireBlock; + private final int replaceBlock; + + public PopulatorNetherFire(int fireBlock, int replaceBlock) { + this.fireBlock = fireBlock; + this.replaceBlock = replaceBlock; + } + + private IntArrayList getHighestWorkableBlocks(ChunkManager level, int x, int z) { + int y; + IntArrayList blockYs = new IntArrayList(); + for (y = 127; y > 0; y--) { + int b = level.getBlockIdAt(x, y, z); + if ((b == this.replaceBlock) && level.getBlockIdAt(x, y + 1, z) == AIR) { + blockYs.add(y + 1); + } + } + return blockYs; + } + + @Override + public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + if (this.replaceBlock == NETHERRACK && random.nextBoundedInt(8) < 7) return; + + int amount = random.nextBoundedInt(4) + 4; + + for (int i = 0; i < amount; ++i) { + int x = random.nextRange(chunkX << 4, (chunkX << 4) + 15); + int z = random.nextRange(chunkZ << 4, (chunkZ << 4) + 15); + IntArrayList ys = getHighestWorkableBlocks(level, x, z); + for (int y : ys) { + if (y <= 1) continue; + level.setBlockAt(x, y, z, this.fireBlock); + } + } + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorOre.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorOre.java index 56474e4870b..2fcae2710da 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorOre.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorOre.java @@ -11,6 +11,7 @@ * @author DaPorkchop_ */ public class PopulatorOre extends Populator { + private final int replaceId; private final OreType[] oreTypes; diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorPumpkin.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorPumpkin.java new file mode 100644 index 00000000000..628ffe5cfbc --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorPumpkin.java @@ -0,0 +1,39 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.block.Block; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitRandom; +import cn.nukkit.utils.Utils; + +public class PopulatorPumpkin extends Populator { + + @Override + public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + if (Utils.rand(0, 10) == 5) { + int x = random.nextRange(0, 15); + int z = random.nextRange(0, 15); + int y = getHighestWorkableBlock(chunk, x, z); + if (y != -1 && canPumpkinStay(chunk, x, y, z)) { + chunk.setBlock(x, y, z, Block.PUMPKIN); + } + } + } + + private static boolean canPumpkinStay(FullChunk chunk, int x, int y, int z) { + int b = chunk.getBlockId(x, y, z); + return (b == Block.AIR) && chunk.getBlockId(x, y - 1, z) == Block.GRASS; + } + + private static int getHighestWorkableBlock(FullChunk chunk, int x, int z) { + int y; + for (y = 0; y <= 127; ++y) { + int b = chunk.getBlockId(x, y, z); + if (b == Block.AIR) { + break; + } + } + return y == 0 ? -1 : y; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorRavines.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorRavines.java deleted file mode 100644 index f04068d7eee..00000000000 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorRavines.java +++ /dev/null @@ -1,205 +0,0 @@ -package cn.nukkit.level.generator.populator.impl; - -import cn.nukkit.block.Block; -import cn.nukkit.level.ChunkManager; -import cn.nukkit.level.format.FullChunk; -import cn.nukkit.level.generator.populator.type.Populator; -import cn.nukkit.math.MathHelper; -import cn.nukkit.math.NukkitRandom; - -import java.util.Random; - -public class PopulatorRavines extends Populator { - - protected int checkAreaSize = 8; - - private Random random; - private long worldLong1; - private long worldLong2; - - private int ravineRarity = 1;//2 - private int ravineMinAltitude = 20; - private int ravineMaxAltitude = 67; - private int ravineMinLength = 84; - private int ravineMaxLength = 111; - - private double ravineDepth = 3; - - private int worldHeightCap = 1 << 8; - - private float[] a = new float[1024]; - - @Override - public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { - this.random = new Random(); - this.random.setSeed(level.getSeed()); - worldLong1 = this.random.nextLong(); - worldLong2 = this.random.nextLong(); - - int i = this.checkAreaSize; - - for (int x = chunkX - i; x <= chunkX + i; x++) - for (int z = chunkZ - i; z <= chunkZ + i; z++) { - long l3 = x * worldLong1; - long l4 = z * worldLong2; - this.random.setSeed(l3 ^ l4 ^ level.getSeed()); - generateChunk(chunkX, chunkZ, level.getChunk(chunkX, chunkZ)); - } - } - - protected void generateChunk(int chunkX, int chunkZ, FullChunk generatingChunkBuffer) { - if (this.random.nextInt(300) >= this.ravineRarity) - return; - double d1 = (chunkX * 16) + this.random.nextInt(16); - double d2 = numberInRange(random, this.ravineMinAltitude, this.ravineMaxAltitude); - double d3 = (chunkZ * 16) + this.random.nextInt(16); - - int i = 1; - - for (int j = 0; j < i; j++) { - float f1 = this.random.nextFloat() * 3.141593F * 2.0F; - float f2 = (this.random.nextFloat() - 0.5F) * 2.0F / 8.0F; - float f3 = (this.random.nextFloat() * 2.0F + this.random.nextFloat()) * 2.0F; - - int size = numberInRange(random, this.ravineMinLength, this.ravineMaxLength); - - createRavine(this.random.nextLong(), generatingChunkBuffer, d1, d2, d3, f3, f1, f2, size, this.ravineDepth); - } - } - - protected void createRavine(long paramLong, FullChunk generatingChunkBuffer, double paramDouble1, double paramDouble2, double paramDouble3, - float paramFloat1, float paramFloat2, float paramFloat3, int size, double paramDouble4) { - Random localRandom = new Random(paramLong); - - int chunkX = generatingChunkBuffer.getX(); - int chunkZ = generatingChunkBuffer.getZ(); - - double d1 = chunkX * 16 + 8; - double d2 = chunkZ * 16 + 8; - - float f1 = 0.0F; - float f2 = 0.0F; - - int i = 0; - - float f3 = 1.0F; - for (int j = 0; ; j++) { - if (j >= worldHeightCap) - break; - if ((j == 0) || (localRandom.nextInt(3) == 0)) { - f3 = 1.0F + localRandom.nextFloat() * localRandom.nextFloat() * 1.0F; - } - this.a[j] = (f3 * f3); - } - - for (int stepCount = 0; stepCount < size; stepCount++) { - double d3 = 1.5D + MathHelper.sin(stepCount * 3.141593F / size) * paramFloat1 * 1.0F; - double d4 = d3 * paramDouble4; - - d3 *= (localRandom.nextFloat() * 0.25D + 0.75D); - d4 *= (localRandom.nextFloat() * 0.25D + 0.75D); - - float f4 = MathHelper.cos(paramFloat3); - float f5 = MathHelper.sin(paramFloat3); - paramDouble1 += MathHelper.cos(paramFloat2) * f4; - paramDouble2 += f5; - paramDouble3 += MathHelper.sin(paramFloat2) * f4; - - paramFloat3 *= 0.7F; - - paramFloat3 += f2 * 0.05F; - paramFloat2 += f1 * 0.05F; - - f2 *= 0.8F; - f1 *= 0.5F; - f2 += (localRandom.nextFloat() - localRandom.nextFloat()) * localRandom.nextFloat() * 2.0F; - f1 += (localRandom.nextFloat() - localRandom.nextFloat()) * localRandom.nextFloat() * 4.0F; - - if ((i == 0) && (localRandom.nextInt(4) == 0)) { - continue; - } - double d5 = paramDouble1 - d1; - double d6 = paramDouble3 - d2; - double d7 = size - stepCount; - double d8 = paramFloat1 + 2.0F + 16.0F; - if (d5 * d5 + d6 * d6 - d7 * d7 > d8 * d8) { - return; - } - - if ((paramDouble1 < d1 - 16.0D - d3 * 2.0D) || (paramDouble3 < d2 - 16.0D - d3 * 2.0D) || (paramDouble1 > d1 + 16.0D + d3 * 2.0D) || (paramDouble3 > d2 + 16.0D + d3 * 2.0D)) - continue; - int k = MathHelper.floor(paramDouble1 - d3) - (chunkX * 16) - 1; - int m = MathHelper.floor(paramDouble1 + d3) - (chunkZ * 16) + 1; - - int maxY = MathHelper.floor(paramDouble2 - d4) - 1; - int minY = MathHelper.floor(paramDouble2 + d4) + 1; - - int i2 = MathHelper.floor(paramDouble3 - d3) - (chunkX * 16) - 1; - int i3 = MathHelper.floor(paramDouble3 + d3) - (chunkZ * 16) + 1; - - if (k < 0) - k = 0; - if (m > 16) - m = 16; - - if (maxY < 1) - maxY = 1; - if (minY > this.worldHeightCap - 8) - minY = this.worldHeightCap - 8; - - if (i2 < 0) - i2 = 0; - if (i3 > 16) - i3 = 16; - - int i4 = 0; - for (int localX = k; (i4 == 0) && (localX < m); localX++) { - for (int localZ = i2; (i4 == 0) && (localZ < i3); localZ++) { - for (int localY = minY + 1; (i4 == 0) && (localY >= maxY - 1); localY--) { - if (localY < 0) - continue; - if (localY < this.worldHeightCap) { - int materialAtPosition = generatingChunkBuffer.getBlockId(localX, localY, localZ); - if (materialAtPosition == Block.WATER - || materialAtPosition == Block.STILL_WATER) { - i4 = 1; - } - if ((localY != maxY - 1) && (localX != k) && (localX != m - 1) && (localZ != i2) && (localZ != i3 - 1)) - localY = maxY; - } - } - } - } - if (i4 != 0) { - continue; - } - for (int localX = k; localX < m; localX++) { - double d9 = (localX + (chunkX * 16) + 0.5D - paramDouble1) / d3; - for (int localZ = i2; localZ < i3; localZ++) { - double d10 = (localZ + (chunkZ * 16) + 0.5D - paramDouble3) / d3; - if (d9 * d9 + d10 * d10 < 1.0D) { - for (int localY = minY; localY >= maxY; localY--) { - double d11 = ((localY - 1) + 0.5D - paramDouble2) / d4; - if ((d9 * d9 + d10 * d10) * this.a[localY - 1] + d11 * d11 / 6.0D < 1.0D) { - int material = generatingChunkBuffer.getBlockId(localX, localY, localZ); - if (material == Block.GRASS) { - if (localY - 1 < 10) { - generatingChunkBuffer.setBlock(localX, localY, localZ, Block.LAVA); - } else { - generatingChunkBuffer.setBlock(localX, localY, localZ, Block.AIR); - } - } - } - } - } - } - } - if (i != 0) - break; - } - } - - public static int numberInRange(Random random, int min, int max) { - return min + random.nextInt(max - min + 1); - } -} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSeagrass.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSeagrass.java new file mode 100644 index 00000000000..4f6f498f288 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSeagrass.java @@ -0,0 +1,36 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockLayer; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.populator.helper.EnsureCover; +import cn.nukkit.level.generator.populator.type.PopulatorOceanFloorSurfaceBlock; +import cn.nukkit.math.NukkitRandom; + +public class PopulatorSeagrass extends PopulatorOceanFloorSurfaceBlock { + + @Override + protected boolean canStay(int x, int y, int z, FullChunk chunk) { + if (chunk instanceof cn.nukkit.level.format.anvil.Chunk) return false; + int down; + return EnsureCover.ensureWaterCover(x, y, z, chunk) && ((down = chunk.getBlockId(x, y - 1, z)) == DIRT || down == SAND || down == GRAVEL); + } + + @Override + protected int getBlockId(int x, int z, NukkitRandom random, FullChunk chunk) { + return Block.SEAGRASS << Block.DATA_BITS; + } + + @Override + protected void placeBlock(int x, int y, int z, int id, FullChunk chunk, NukkitRandom random) { + if (y < 255 && random.nextDouble() < 0.3 && chunk.getBlockId(x, y + 1, z) == STILL_WATER) { + chunk.setBlock(x, y, z, SEAGRASS, 2); // tall seagrass bottom + chunk.setBlock(x, y + 1, z, SEAGRASS, 1); // tall seagrass top + chunk.setFullBlockId(x, y, z, BlockLayer.WATERLOGGED, Block.STILL_WATER << Block.DATA_BITS); + chunk.setFullBlockId(x, y + 1, z, BlockLayer.WATERLOGGED, Block.STILL_WATER << Block.DATA_BITS); + } else { + chunk.setFullBlockId(x, y, z, id); + chunk.setFullBlockId(x, y, z, BlockLayer.WATERLOGGED, Block.STILL_WATER << Block.DATA_BITS); + } + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSmallMushroom.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSmallMushroom.java index 4269946967a..32921198eeb 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSmallMushroom.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSmallMushroom.java @@ -1,5 +1,6 @@ package cn.nukkit.level.generator.populator.impl; +import cn.nukkit.block.Block; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.generator.populator.helper.EnsureCover; import cn.nukkit.level.generator.populator.helper.EnsureGrassBelow; @@ -18,6 +19,6 @@ protected boolean canStay(int x, int y, int z, FullChunk chunk) { @Override protected int getBlockId(int x, int z, NukkitRandom random, FullChunk chunk) { - return BROWN_MUSHROOM << 4; + return Block.BROWN_MUSHROOM << Block.DATA_BITS; } } diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSoulSandValleyGround.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSoulSandValleyGround.java new file mode 100644 index 00000000000..859370a3fc3 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSoulSandValleyGround.java @@ -0,0 +1,41 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.block.Block; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitRandom; +import it.unimi.dsi.fastutil.ints.IntArrayList; + +public class PopulatorSoulSandValleyGround extends Populator { + + private static IntArrayList getHighestWorkableBlocks(ChunkManager level, int x, int z) { + int y; + IntArrayList blockYs = new IntArrayList(); + for (y = 127; y > 0; y--) { + int b = level.getBlockIdAt(x, y, z); + if ((b == Block.SOUL_SOIL || b == Block.SOUL_SAND) && level.getBlockIdAt(x, y + 1, z) == 0) { + blockYs.add(y + 1); + } + } + return blockYs; + } + + @Override + public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + if (random.nextBoundedInt(15) != 1) return; + + int block = random.nextBoolean() ? CRIMSON_ROOTS : random.nextBoolean() ? RED_MUSHROOM : BROWN_MUSHROOM; + + int amount = random.nextBoundedInt(7) + 3; + for (int i = 0; i < amount; ++i) { + int x = random.nextRange(chunkX << 4, (chunkX << 4) + 15); + int z = random.nextRange(chunkZ << 4, (chunkZ << 4) + 15); + IntArrayList ys = getHighestWorkableBlocks(level, x, z); + for (int y : ys) { + if (y <= 1) continue; + level.setBlockAt(x, y, z, block); + } + } + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSpring.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSpring.java new file mode 100644 index 00000000000..f33de854149 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSpring.java @@ -0,0 +1,110 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.format.LevelProvider; +import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitRandom; + +public class PopulatorSpring extends Populator { + + private final int block; + private final int replaceId; + private final int attempts; + private final int minHeight; + private final int maxHeight; + + public PopulatorSpring(int block, int replaceId, int attempts, int minHeight, int maxHeight) { + this.block = block; + this.replaceId = replaceId; + this.attempts = attempts; + this.minHeight = minHeight; + this.maxHeight = maxHeight; + } + + @Override + public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + int sourceX = chunkX << 4; + int sourceZ = chunkZ << 4; + + for (int i = 0; i < attempts; i++) { + int x = sourceX + random.nextBoundedInt(16); + int z = sourceZ + random.nextBoundedInt(16); + int y = random.nextRange(minHeight, maxHeight); + + int blockXYZ = level.getBlockIdAt(x, y, z); + if (!(blockXYZ == BlockID.AIR || blockXYZ == this.replaceId)) { + continue; + } + + // We don't want to trigger block update next to a fallable block + + int blockX_1YZ = level.getBlockIdAt(x, y - 1, z); + if (blockX_1YZ == BlockID.SAND || blockX_1YZ == BlockID.GRAVEL) { + continue; + } + + int blockX1YZ = level.getBlockIdAt(x, y + 1, z); + if (blockX1YZ == BlockID.SAND || blockX1YZ == BlockID.GRAVEL) { + continue; + } + + if (!(blockX_1YZ == this.replaceId || blockX1YZ == this.replaceId)) { + continue; + } + + int block1XYZ = level.getBlockIdAt(x + 1, y, z); + if (block1XYZ == BlockID.SAND || block1XYZ == BlockID.GRAVEL) { + continue; + } + int block_1XYZ = level.getBlockIdAt(x - 1, y, z); + if (block_1XYZ == BlockID.SAND || block_1XYZ == BlockID.GRAVEL) { + continue; + } + int blockXY1Z = level.getBlockIdAt(x, y, z + 1); + if (blockXY1Z == BlockID.SAND || blockXY1Z == BlockID.GRAVEL) { + continue; + } + int blockXY_1Z = level.getBlockIdAt(x, y, z - 1); + if (blockXY_1Z == BlockID.SAND || blockXY_1Z == BlockID.GRAVEL) { + continue; + } + + int surroundCount = 0; + if (block1XYZ == this.replaceId) surroundCount++; + if (block_1XYZ == this.replaceId) surroundCount++; + if (blockXY1Z == this.replaceId) surroundCount++; + if (blockXY_1Z == this.replaceId) surroundCount++; + + if (surroundCount != 3) { + continue; + } + + int airCount = 0; + if (block1XYZ == AIR) airCount++; + if (block_1XYZ == AIR) airCount++; + if (blockXY1Z == AIR) airCount++; + if (blockXY_1Z == AIR) airCount++; + + if (airCount != 1) { + continue; + } + + level.setBlockAt(x, y, z, this.block); + + LevelProvider provider = chunk.getProvider(); + if (provider != null) { + Block state = Block.fullList[this.block << Block.DATA_BITS].clone(); + state.x = x; + state.y = y; + state.z = z; + state.level = provider.getLevel(); + if (state.level != null) { + state.level.scheduleUpdate(state, state, 1, 0, false); + } + } + } + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSugarcane.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSugarcane.java index 1b1bf160af3..851b38be8fd 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSugarcane.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSugarcane.java @@ -1,12 +1,12 @@ package cn.nukkit.level.generator.populator.impl; import cn.nukkit.block.Block; -import cn.nukkit.level.Level; import cn.nukkit.level.format.FullChunk; -import cn.nukkit.level.generator.populator.helper.EnsureBelow; import cn.nukkit.level.generator.populator.helper.EnsureCover; import cn.nukkit.level.generator.populator.helper.EnsureGrassBelow; import cn.nukkit.level.generator.populator.type.PopulatorSurfaceBlock; +import cn.nukkit.math.BlockFace; +import cn.nukkit.math.NukkitMath; import cn.nukkit.math.NukkitRandom; /** @@ -17,29 +17,26 @@ */ public class PopulatorSugarcane extends PopulatorSurfaceBlock { - private boolean findWater(int x, int y, int z, Level level) { - int count = 0; - for (int i = x - 4; i < (x + 4); i++) { - for (int j = z - 4; j < (z + 4); j++) { - int b = level.getBlockIdAt(i, y, j); - if (b == Block.WATER || b == Block.STILL_WATER) { - count++; - } - if (count > 10) { - return true; - } - } - } - return (count > 10); + private boolean findWater(int x, int y, int z, FullChunk chunk) { + int cx = x & 0xF; + int cz = z & 0xF; + int b = chunk.getBlockId(NukkitMath.clamp(cx + BlockFace.NORTH.getXOffset(), 0, 15), y, NukkitMath.clamp(cz + BlockFace.NORTH.getZOffset(), 0, 15)); + if (b == Block.WATER || b == Block.STILL_WATER) return true; + b = chunk.getBlockId(NukkitMath.clamp(cx + BlockFace.EAST.getXOffset(), 0, 15), y, NukkitMath.clamp(cz + BlockFace.EAST.getZOffset(), 0, 15)); + if (b == Block.WATER || b == Block.STILL_WATER) return true; + b = chunk.getBlockId(NukkitMath.clamp(cx + BlockFace.SOUTH.getXOffset(), 0, 15), y, NukkitMath.clamp(cz + BlockFace.SOUTH.getZOffset(), 0, 15)); + if (b == Block.WATER || b == Block.STILL_WATER) return true; + b = chunk.getBlockId(NukkitMath.clamp(cx + BlockFace.WEST.getXOffset(), 0, 15), y, NukkitMath.clamp(cz + BlockFace.WEST.getZOffset(), 0, 15)); + return b == Block.WATER || b == Block.STILL_WATER; } @Override protected boolean canStay(int x, int y, int z, FullChunk chunk) { - return EnsureCover.ensureCover(x, y, z, chunk) && (EnsureGrassBelow.ensureGrassBelow(x, y, z, chunk) || EnsureBelow.ensureBelow(x, y, z, SAND, chunk)) && findWater(x, y - 1, z, chunk.getProvider().getLevel()); + return EnsureCover.ensureCover(x, y, z, chunk) && EnsureGrassBelow.ensureGrassOrSandBelow(x, y, z, chunk) && findWater(x, y - 1, z, chunk); } @Override protected int getBlockId(int x, int z, NukkitRandom random, FullChunk chunk) { - return (SUGARCANE_BLOCK << 4) | 1; + return (Block.SUGARCANE_BLOCK << Block.DATA_BITS) | 1; } } diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSweetBerryBush.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSweetBerryBush.java new file mode 100644 index 00000000000..06370dd5b1a --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorSweetBerryBush.java @@ -0,0 +1,25 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockID; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.populator.helper.EnsureBelow; +import cn.nukkit.level.generator.populator.helper.EnsureCover; +import cn.nukkit.level.generator.populator.type.PopulatorSurfaceBlock; +import cn.nukkit.math.NukkitRandom; + +import java.util.concurrent.ThreadLocalRandom; + +public class PopulatorSweetBerryBush extends PopulatorSurfaceBlock { + + @Override + protected boolean canStay(int x, int y, int z, FullChunk chunk) { + if (chunk instanceof cn.nukkit.level.format.anvil.Chunk) return false; + return EnsureCover.ensureCover(x, y, z, chunk) && EnsureBelow.ensureBelow(x, y, z, GRASS, chunk); + } + + @Override + protected int getBlockId(int x, int z, NukkitRandom random, FullChunk chunk) { + return (BlockID.SWEET_BERRY_BUSH << Block.DATA_BITS) + ThreadLocalRandom.current().nextInt(3); + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorTallSugarcane.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorTallSugarcane.java index 84aa9a0002d..ef7382822aa 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorTallSugarcane.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorTallSugarcane.java @@ -16,6 +16,7 @@ public class PopulatorTallSugarcane extends PopulatorSugarcane { @Override protected void placeBlock(int x, int y, int z, int id, FullChunk chunk, NukkitRandom random) { int height = ThreadLocalRandom.current().nextInt(3) + 1; + if (y + height > 255) return; for (int i = 0; i < height; i++) { chunk.setFullBlockId(x, y + i, z, id); } diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorTree.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorTree.java index a68ffa676a3..681755dca95 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorTree.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorTree.java @@ -10,7 +10,7 @@ import cn.nukkit.math.NukkitRandom; /** - * author: DaPorkchop_ + * @author DaPorkchop_ * Nukkit Project */ public class PopulatorTree extends PopulatorCount { @@ -42,7 +42,7 @@ private int getHighestWorkableBlock(int x, int z) { int y; for (y = 254; y > 0; --y) { int b = this.level.getBlockIdAt(x, y, z); - if (b == Block.DIRT || b == Block.GRASS) { + if (b == Block.DIRT || b == Block.GRASS || (this.type == BlockSapling.SPRUCE && b == Block.PODZOL)) { break; } else if (b != Block.AIR && b != Block.SNOW_LAYER) { return -1; diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorTwistingVines.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorTwistingVines.java new file mode 100644 index 00000000000..bd125127e51 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorTwistingVines.java @@ -0,0 +1,62 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.block.Block; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitRandom; +import it.unimi.dsi.fastutil.ints.IntArrayList; + +public class PopulatorTwistingVines extends Populator { + + private static int getHighestEndingBlock(ChunkManager level, int x, int y, int z) { + for (; y < 128; ++y) { + int b = level.getBlockIdAt(x, y, z); + int above = level.getBlockIdAt(x, y + 1, z); + if (b == 0 && ( + above == NETHERRACK || above == WARPED_NYLIUM || above == WARPED_WART_BLOCK || + above == STILL_LAVA || above == LAVA || + above == WARPED_FUNGUS || above == WARPED_ROOTS || + above == QUARTZ_ORE || above == NETHER_GOLD_ORE || above == ANCIENT_DEBRIS)) { + break; + } + } + + return y; + } + + private static IntArrayList getHighestWorkableBlocks(ChunkManager level, int x, int z) { + int y; + IntArrayList blockYs = new IntArrayList(); + + for (y = 128; y > 0; --y) { + int b = level.getBlockIdAt(x, y, z); + if ((b == Block.WARPED_NYLIUM || b == Block.NETHERRACK) && level.getBlockIdAt(x, y + 1, z) == 0) { + blockYs.add(y + 1); + } + } + return blockYs; + } + + @Override + public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + if (random.nextBoundedInt(8) < 7) return; + + int amount = random.nextBoundedInt(5) + 2; + + for (int i = 0; i < amount; ++i) { + int x = random.nextRange(chunkX << 4, (chunkX << 4) + 15); + int z = random.nextRange(chunkZ << 4, (chunkZ << 4) + 15); + IntArrayList ys = getHighestWorkableBlocks(level, x, z); + for (int y : ys) { + if (y <= 1) continue; + if (random.nextBoundedInt(4) == 0) continue; + int endY = getHighestEndingBlock(level, x, y, z); + int amountToDecrease = Math.min(random.nextBoundedInt(endY - y), 15); + for (int yPos = y; yPos < y + (amountToDecrease / 2); yPos++) { + level.setBlockAt(x, yPos, z, TWISTING_VINES); + } + } + } + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorUnderwaterFloor.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorUnderwaterFloor.java new file mode 100644 index 00000000000..83216b5f07c --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorUnderwaterFloor.java @@ -0,0 +1,77 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.block.BlockID; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.Normal; +import cn.nukkit.level.generator.populator.helper.PopulatorHelpers; +import cn.nukkit.level.generator.populator.type.PopulatorCount; +import cn.nukkit.math.NukkitRandom; + +import java.util.List; + +public class PopulatorUnderwaterFloor extends PopulatorCount { + + private final double probability; + private final int block; + private final int radiusMin; + private final int radiusMax; + private final int radiusY; + private final List replaceBlocks; + + public PopulatorUnderwaterFloor(double probability, int block, int radiusMin, int radiusMax, int radiusY, List replaceBlocks) { + this.probability = probability; + this.block = block; + this.radiusMin = radiusMin; + this.radiusMax = radiusMax; + this.radiusY = radiusY; + this.replaceBlocks = replaceBlocks; + } + + @Override + public void populateCount(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + if (random.nextDouble() >= probability) { + return; + } + + int sourceX = (chunkX << 4) + random.nextBoundedInt(16); + int sourceZ = (chunkZ << 4) + random.nextBoundedInt(16); + int sourceY = getHighestWorkableBlock(level, sourceX, sourceZ, chunk) - 1; + if (sourceY < radiusY) { + return; + } + + if (level.getBlockIdAt(sourceX, sourceY + 1, sourceZ) != BlockID.STILL_WATER) { + return; + } + + int radius = random.nextRange(radiusMin, radiusMax); + for (int x = sourceX - radius; x <= sourceX + radius; x++) { + for (int z = sourceZ - radius; z <= sourceZ + radius; z++) { + if ((x - sourceX) * (x - sourceX) + (z - sourceZ) * (z - sourceZ) <= radius * radius) { + for (int y = sourceY - radiusY; y <= sourceY + radiusY; y++) { + for (int replaceBlockState : replaceBlocks) { + if (level.getBlockIdAt(x, y, z) == replaceBlockState) { + level.setBlockAt(x, y, z, block, 0); + } + } + } + } + } + } + } + + @Override + protected int getHighestWorkableBlock(ChunkManager level, int x, int z, FullChunk chunk) { + int y; + x &= 0xF; + z &= 0xF; + for (y = Normal.seaHeight - 1; y >= 0; --y) { + if (!PopulatorHelpers.isNonOceanSolid(chunk.getBlockId(x, y, z))) { + break; + } + } + + return y == 0 ? -1 : ++y; + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorWarpedForestGround.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorWarpedForestGround.java new file mode 100644 index 00000000000..02fd6703bfd --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorWarpedForestGround.java @@ -0,0 +1,48 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.block.Block; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitRandom; +import it.unimi.dsi.fastutil.ints.IntArrayList; + +public class PopulatorWarpedForestGround extends Populator { + + private static IntArrayList getHighestWorkableBlocks(ChunkManager level, int x, int z) { + int y; + IntArrayList blockYs = new IntArrayList(); + for (y = 128; y > 0; --y) { + int b = level.getBlockIdAt(x, y, z); + if ((b == Block.WARPED_NYLIUM) && level.getBlockIdAt(x, y + 1, z) == 0) { + blockYs.add(y + 1); + } + } + return blockYs; + } + + @Override + public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + int amount = random.nextBoundedInt(64) + 32; + + for (int i = 0; i < amount; ++i) { + int x = random.nextRange(chunkX << 4, (chunkX << 4) + 15); + int z = random.nextRange(chunkZ << 4, (chunkZ << 4) + 15); + IntArrayList ys = getHighestWorkableBlocks(level, x, z); + for (int y : ys) { + if (y <= 1) continue; + + int blockID; + if (random.nextBoundedInt(4) == 0) { + blockID = NETHER_SPROUTS_BLOCK; + } else if (random.nextBoundedInt(6) == 0) { + blockID = WARPED_FUNGUS; + } else { + blockID = WARPED_ROOTS; + } + + level.setBlockAt(x, y, z, blockID); + } + } + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorWarpedFungus.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorWarpedFungus.java new file mode 100644 index 00000000000..3b63da5dfc8 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorWarpedFungus.java @@ -0,0 +1,40 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.block.Block; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.object.tree.ObjectWarpedTree; +import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitRandom; +import it.unimi.dsi.fastutil.ints.IntArrayList; + +public class PopulatorWarpedFungus extends Populator { + + private static IntArrayList getHighestWorkableBlocks(ChunkManager level, int x, int z) { + int y; + IntArrayList blockYs = new IntArrayList(); + for (y = 128; y > 0; --y) { + int b = level.getBlockIdAt(x, y, z); + if ((b == Block.WARPED_NYLIUM) && level.getBlockIdAt(x, y + 1, z) == 0) { + blockYs.add(y + 1); + } + } + return blockYs; + } + + @Override + public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + int amount = random.nextBoundedInt(6) + 3; + + for (int i = 0; i < amount; ++i) { + int x = random.nextRange(chunkX << 4, (chunkX << 4) + 15); + int z = random.nextRange(chunkZ << 4, (chunkZ << 4) + 15); + IntArrayList ys = getHighestWorkableBlocks(level, x, z); + for (int y : ys) { + if (y <= 1) continue; + if (random.nextBoundedInt(4) == 0) continue; + new ObjectWarpedTree().placeObject(level, x, y, z, random); + } + } + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorWeepingVines.java b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorWeepingVines.java new file mode 100644 index 00000000000..88be7ce9e6b --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorWeepingVines.java @@ -0,0 +1,60 @@ +package cn.nukkit.level.generator.populator.impl; + +import cn.nukkit.block.Block; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitRandom; +import it.unimi.dsi.fastutil.ints.IntArrayList; + +public class PopulatorWeepingVines extends Populator { + + private static int getHighestEndingBlock(ChunkManager level, int x, int y, int z) { + for (; y > 0; --y) { + int b = level.getBlockIdAt(x, y, z); + int above = level.getBlockIdAt(x, y + 1, z); + if (above == 0 && ( + b == NETHERRACK || b == CRIMSON_NYLIUM || b == BLOCK_NETHER_WART_BLOCK || + b == STILL_LAVA || b == LAVA || + b == CRIMSON_FUNGUS || b == CRIMSON_ROOTS || + b == QUARTZ_ORE || b == NETHER_GOLD_ORE || b == ANCIENT_DEBRIS)) { + break; + } + } + + return ++y; + } + + private static IntArrayList getHighestWorkableBlocks(ChunkManager level, int x, int z) { + int y; + IntArrayList blockYs = new IntArrayList(); + for (y = 128; y > 0; --y) { + int b = level.getBlockIdAt(x, y, z); + if ((b == Block.CRIMSON_NYLIUM || b == Block.NETHERRACK) && level.getBlockIdAt(x, y - 1, z) == 0) { + blockYs.add(y - 1); + } + } + return blockYs; + } + + @Override + public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + if (random.nextBoundedInt(8) < 7) return; + + int amount = random.nextBoundedInt(5) + 1; + + for (int i = 0; i < amount; ++i) { + int x = random.nextRange(chunkX << 4, (chunkX << 4) + 15); + int z = random.nextRange(chunkZ << 4, (chunkZ << 4) + 15); + IntArrayList ys = getHighestWorkableBlocks(level, x, z); + for (int y : ys) { + if (y <= 1) continue; + int endY = getHighestEndingBlock(level, x, y, z); + int amountToDecrease = Math.min(random.nextBoundedInt(y - endY), 10); + for (int yPos = y; yPos > y - amountToDecrease; yPos--) { + level.setBlockAt(x, yPos, z, WEEPING_VINES); + } + } + } + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/WaterIcePopulator.java b/src/main/java/cn/nukkit/level/generator/populator/impl/WaterIcePopulator.java index dfe92b8f5b3..e3d74147726 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/WaterIcePopulator.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/WaterIcePopulator.java @@ -2,23 +2,20 @@ import cn.nukkit.level.ChunkManager; import cn.nukkit.level.biome.Biome; -import cn.nukkit.level.biome.EnumBiome; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.generator.populator.type.Populator; import cn.nukkit.math.NukkitRandom; -import static cn.nukkit.block.BlockID.ICE; -import static cn.nukkit.block.BlockID.STILL_WATER; - public class WaterIcePopulator extends Populator { + @Override public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { - Biome biome = EnumBiome.getBiome(chunk.getBiomeId(x, z)); + Biome biome = Biome.getBiome(chunk.getBiomeId(x, z)); if (biome.isFreezing()) { int topBlock = chunk.getHighestBlockAt(x, z); - if (chunk.getBlockId(x, topBlock, z) == STILL_WATER) { + if (chunk.getBlockId(x, topBlock, z) == STILL_WATER) { chunk.setBlockId(x, topBlock, z, ICE); } } diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/tree/DarkOakTreePopulator.java b/src/main/java/cn/nukkit/level/generator/populator/impl/tree/DarkOakTreePopulator.java index 0b0aa540db7..8482a7dcc66 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/tree/DarkOakTreePopulator.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/tree/DarkOakTreePopulator.java @@ -15,15 +15,11 @@ public class DarkOakTreePopulator extends Populator { private int randomAmount; private int baseAmount; - private final int type; - public DarkOakTreePopulator() { this(BlockSapling.DARK_OAK); } - public DarkOakTreePopulator(int type) { - this.type = type; - } + public DarkOakTreePopulator(int type) {} public void setRandomAmount(int randomAmount) { this.randomAmount = randomAmount; diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/tree/JungleBigTreePopulator.java b/src/main/java/cn/nukkit/level/generator/populator/impl/tree/JungleBigTreePopulator.java index 394a97c581e..05f7f1c293f 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/tree/JungleBigTreePopulator.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/tree/JungleBigTreePopulator.java @@ -1,6 +1,9 @@ package cn.nukkit.level.generator.populator.impl.tree; -import cn.nukkit.block.*; +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockLeaves; +import cn.nukkit.block.BlockSapling; +import cn.nukkit.block.BlockWood; import cn.nukkit.level.ChunkManager; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.generator.object.tree.ObjectJungleBigTree; @@ -15,15 +18,11 @@ public class JungleBigTreePopulator extends Populator { private int randomAmount; private int baseAmount; - private final int type; - public JungleBigTreePopulator() { this(BlockSapling.JUNGLE); } - public JungleBigTreePopulator(int type) { - this.type = type; - } + public JungleBigTreePopulator(int type) {} public void setRandomAmount(int randomAmount) { this.randomAmount = randomAmount; @@ -46,7 +45,7 @@ public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom ra if (y == -1) { continue; } - new ObjectJungleBigTree(10, 20, Block.get(BlockID.WOOD, BlockWood.JUNGLE), Block.get(BlockID.LEAVES, BlockLeaves.JUNGLE)).generate(this.level, random, v.setComponents(x, y, z)); + new ObjectJungleBigTree(10, 20, Block.get(WOOD, BlockWood.JUNGLE), Block.get(LEAVES, BlockLeaves.JUNGLE)).generate(this.level, random, v.setComponents(x, y, z)); } } diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/tree/JungleFloorPopulator.java b/src/main/java/cn/nukkit/level/generator/populator/impl/tree/JungleFloorPopulator.java index e886c4da580..91e2b158ed6 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/tree/JungleFloorPopulator.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/tree/JungleFloorPopulator.java @@ -20,15 +20,11 @@ public class JungleFloorPopulator extends Populator { private int randomAmount; private int baseAmount; - private final int type; - public JungleFloorPopulator() { this(BlockSapling.JUNGLE); } - public JungleFloorPopulator(int type) { - this.type = type; - } + public JungleFloorPopulator(int type) {} public void setRandomAmount(int randomAmount) { this.randomAmount = randomAmount; diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/tree/JungleTreePopulator.java b/src/main/java/cn/nukkit/level/generator/populator/impl/tree/JungleTreePopulator.java index 94f77c34461..1018a3f7073 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/tree/JungleTreePopulator.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/tree/JungleTreePopulator.java @@ -15,15 +15,11 @@ public class JungleTreePopulator extends Populator { private int randomAmount; private int baseAmount; - private final int type; - public JungleTreePopulator() { this(BlockSapling.JUNGLE); } - public JungleTreePopulator(int type) { - this.type = type; - } + public JungleTreePopulator(int type) {} public void setRandomAmount(int randomAmount) { this.randomAmount = randomAmount; diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/tree/SavannaTreePopulator.java b/src/main/java/cn/nukkit/level/generator/populator/impl/tree/SavannaTreePopulator.java index 11911087f7f..e83a8b572e7 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/tree/SavannaTreePopulator.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/tree/SavannaTreePopulator.java @@ -16,15 +16,11 @@ public class SavannaTreePopulator extends Populator { private int randomAmount; private int baseAmount; - private final int type; - public SavannaTreePopulator() { this(BlockSapling.ACACIA); } - public SavannaTreePopulator(int type) { - this.type = type; - } + public SavannaTreePopulator(int type) {} public void setRandomAmount(int randomAmount) { this.randomAmount = randomAmount; diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/tree/SpruceBigTreePopulator.java b/src/main/java/cn/nukkit/level/generator/populator/impl/tree/SpruceBigTreePopulator.java index 360f83db0e8..d626f085112 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/tree/SpruceBigTreePopulator.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/tree/SpruceBigTreePopulator.java @@ -1,7 +1,6 @@ package cn.nukkit.level.generator.populator.impl.tree; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockSapling; import cn.nukkit.level.ChunkManager; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.generator.object.tree.ObjectBigSpruceTree; @@ -16,14 +15,7 @@ public class SpruceBigTreePopulator extends Populator { private int randomAmount; private int baseAmount; - private final int type; - public SpruceBigTreePopulator() { - this(BlockSapling.SPRUCE); - } - - private SpruceBigTreePopulator(int type) { - this.type = type; } public void setRandomAmount(int randomAmount) { @@ -47,7 +39,7 @@ public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom ra if (y == -1) { continue; } - new ObjectBigSpruceTree(3 / 4f, 4).placeObject(this.level, (int) (v.x = x), (int) (v.y = y), (int) (v.z = z), random); + new ObjectBigSpruceTree(0.75f, 4).placeObject(this.level, (int) (v.x = x), (int) (v.y = y), (int) (v.z = z), random); } } @@ -55,7 +47,7 @@ private int getHighestWorkableBlock(int x, int z) { int y; for (y = 255; y > 0; --y) { int b = this.level.getBlockIdAt(x, y, z); - if (b == Block.DIRT || b == Block.GRASS) { + if (b == Block.DIRT || b == Block.GRASS || b == Block.PODZOL) { break; } else if (b != Block.AIR && b != Block.SNOW_LAYER) { return -1; diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/tree/SpruceMegaTreePopulator.java b/src/main/java/cn/nukkit/level/generator/populator/impl/tree/SpruceMegaTreePopulator.java index 9e6c67f7e38..bc10705b470 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/tree/SpruceMegaTreePopulator.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/tree/SpruceMegaTreePopulator.java @@ -1,7 +1,6 @@ package cn.nukkit.level.generator.populator.impl.tree; import cn.nukkit.block.Block; -import cn.nukkit.block.BlockSapling; import cn.nukkit.level.ChunkManager; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.generator.object.tree.ObjectBigSpruceTree; @@ -18,14 +17,7 @@ public class SpruceMegaTreePopulator extends Populator { private int randomAmount; private int baseAmount; - private final int type; - public SpruceMegaTreePopulator() { - this(BlockSapling.SPRUCE); - } - - private SpruceMegaTreePopulator(int type) { - this.type = type; } public void setRandomAmount(int randomAmount) { @@ -49,7 +41,7 @@ public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom ra if (y == -1) { continue; } - new ObjectBigSpruceTree(1 / 4f, 5).placeObject(this.level, (int) (v.x = x), (int) (v.y = y), (int) (v.z = z), random); + new ObjectBigSpruceTree(0.25f, 4).placeObject(this.level, (int) (v.x = x), (int) (v.y = y), (int) (v.z = z), random); } } @@ -57,7 +49,7 @@ private int getHighestWorkableBlock(int x, int z) { int y; for (y = 255; y > 0; --y) { int b = this.level.getBlockIdAt(x, y, z); - if (b == Block.DIRT || b == Block.GRASS) { + if (b == Block.DIRT || b == Block.GRASS || b == Block.PODZOL) { break; } else if (b != Block.AIR && b != Block.SNOW_LAYER) { return -1; diff --git a/src/main/java/cn/nukkit/level/generator/populator/impl/tree/SwampTreePopulator.java b/src/main/java/cn/nukkit/level/generator/populator/impl/tree/SwampTreePopulator.java index 631c931d514..50828a5a234 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/impl/tree/SwampTreePopulator.java +++ b/src/main/java/cn/nukkit/level/generator/populator/impl/tree/SwampTreePopulator.java @@ -15,15 +15,11 @@ public class SwampTreePopulator extends Populator { private int randomAmount; private int baseAmount; - private final int type; - public SwampTreePopulator() { this(BlockSapling.OAK); } - public SwampTreePopulator(int type) { - this.type = type; - } + public SwampTreePopulator(int type) {} public void setRandomAmount(int randomAmount) { this.randomAmount = randomAmount; diff --git a/src/main/java/cn/nukkit/level/generator/populator/tree/DarkOakTreePopulator.java b/src/main/java/cn/nukkit/level/generator/populator/tree/DarkOakTreePopulator.java new file mode 100644 index 00000000000..b85f34d20e7 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/tree/DarkOakTreePopulator.java @@ -0,0 +1,64 @@ +package cn.nukkit.level.generator.populator.tree; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockSapling; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.object.tree.ObjectDarkOakTree; +import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitMath; +import cn.nukkit.math.NukkitRandom; +import cn.nukkit.math.Vector3; + +public class DarkOakTreePopulator extends Populator { + + private ChunkManager level; + private int randomAmount; + private int baseAmount; + + public DarkOakTreePopulator() { + this(BlockSapling.DARK_OAK); + } + + public DarkOakTreePopulator(int type) {} + + public void setRandomAmount(int randomAmount) { + this.randomAmount = randomAmount; + } + + public void setBaseAmount(int baseAmount) { + this.baseAmount = baseAmount; + } + + @Override + public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + this.level = level; + int amount = random.nextBoundedInt(this.randomAmount + 1) + this.baseAmount; + Vector3 v = new Vector3(); + + for (int i = 0; i < amount; ++i) { + int x = NukkitMath.randomRange(random, chunkX << 4, (chunkX << 4) + 15); + int z = NukkitMath.randomRange(random, chunkZ << 4, (chunkZ << 4) + 15); + int y = this.getHighestWorkableBlock(x, z); + if (y == -1) { + continue; + } + + new ObjectDarkOakTree().generate(level, random, v.setComponents(x, y, z)); + } + } + + private int getHighestWorkableBlock(int x, int z) { + int y; + for (y = 127; y > 0; --y) { + int b = this.level.getBlockIdAt(x, y, z); + if (b == Block.DIRT || b == Block.GRASS) { + break; + } else if (b != Block.AIR && b != Block.SNOW_LAYER) { + return -1; + } + } + + return ++y; + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/tree/JungleBigTreePopulator.java b/src/main/java/cn/nukkit/level/generator/populator/tree/JungleBigTreePopulator.java new file mode 100644 index 00000000000..65dd8f65d16 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/tree/JungleBigTreePopulator.java @@ -0,0 +1,62 @@ +package cn.nukkit.level.generator.populator.tree; + +import cn.nukkit.block.*; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.object.tree.ObjectJungleBigTree; +import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitMath; +import cn.nukkit.math.NukkitRandom; +import cn.nukkit.math.Vector3; + +public class JungleBigTreePopulator extends Populator { + + private ChunkManager level; + private int randomAmount; + private int baseAmount; + + public JungleBigTreePopulator() { + this(BlockSapling.JUNGLE); + } + + public JungleBigTreePopulator(int type) {} + + public void setRandomAmount(int randomAmount) { + this.randomAmount = randomAmount; + } + + public void setBaseAmount(int baseAmount) { + this.baseAmount = baseAmount; + } + + @Override + public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + this.level = level; + int amount = random.nextBoundedInt(this.randomAmount + 1) + this.baseAmount; + Vector3 v = new Vector3(); + + for (int i = 0; i < amount; ++i) { + int x = NukkitMath.randomRange(random, chunkX << 4, (chunkX << 4) + 15); + int z = NukkitMath.randomRange(random, chunkZ << 4, (chunkZ << 4) + 15); + int y = this.getHighestWorkableBlock(x, z); + if (y == -1) { + continue; + } + new ObjectJungleBigTree(10, 20, Block.get(BlockID.WOOD, BlockWood.JUNGLE), Block.get(BlockID.LEAVES, BlockLeaves.JUNGLE)).generate(this.level, random, v.setComponents(x, y, z)); + } + } + + private int getHighestWorkableBlock(int x, int z) { + int y; + for (y = 127; y > 0; --y) { + int b = this.level.getBlockIdAt(x, y, z); + if (b == Block.DIRT || b == Block.GRASS) { + break; + } else if (b != Block.AIR && b != Block.SNOW_LAYER) { + return -1; + } + } + + return ++y; + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/tree/JungleTreePopulator.java b/src/main/java/cn/nukkit/level/generator/populator/tree/JungleTreePopulator.java new file mode 100644 index 00000000000..4882257ea2a --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/tree/JungleTreePopulator.java @@ -0,0 +1,63 @@ +package cn.nukkit.level.generator.populator.tree; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockSapling; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.object.tree.NewJungleTree; +import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitMath; +import cn.nukkit.math.NukkitRandom; +import cn.nukkit.math.Vector3; + +public class JungleTreePopulator extends Populator { + + private ChunkManager level; + private int randomAmount; + private int baseAmount; + + public JungleTreePopulator() { + this(BlockSapling.JUNGLE); + } + + public JungleTreePopulator(int type) {} + + public void setRandomAmount(int randomAmount) { + this.randomAmount = randomAmount; + } + + public void setBaseAmount(int baseAmount) { + this.baseAmount = baseAmount; + } + + @Override + public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + this.level = level; + int amount = random.nextBoundedInt(this.randomAmount + 1) + this.baseAmount; + Vector3 v = new Vector3(); + + for (int i = 0; i < amount; ++i) { + int x = NukkitMath.randomRange(random, chunkX << 4, (chunkX << 4) + 15); + int z = NukkitMath.randomRange(random, chunkZ << 4, (chunkZ << 4) + 15); + int y = this.getHighestWorkableBlock(x, z); + if (y == -1) { + continue; + } + new NewJungleTree(4 + random.nextBoundedInt(7)).generate(level, random, v.setComponents(x, y, z)); + } + } + + private int getHighestWorkableBlock(int x, int z) { + int y; + for (y = 127; y > 0; --y) { + int b = this.level.getBlockIdAt(x, y, z); + if (b == Block.DIRT || b == Block.GRASS) { + break; + } else if (b != Block.AIR && b != Block.SNOW_LAYER) { + return -1; + } + } + + return ++y; + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/tree/SavannaTreePopulator.java b/src/main/java/cn/nukkit/level/generator/populator/tree/SavannaTreePopulator.java new file mode 100644 index 00000000000..d4d55213d79 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/tree/SavannaTreePopulator.java @@ -0,0 +1,63 @@ +package cn.nukkit.level.generator.populator.tree; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockSapling; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.object.tree.ObjectSavannaTree; +import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitMath; +import cn.nukkit.math.NukkitRandom; +import cn.nukkit.math.Vector3; + +public class SavannaTreePopulator extends Populator { + + private ChunkManager level; + private int randomAmount; + private int baseAmount; + + public SavannaTreePopulator() { + this(BlockSapling.ACACIA); + } + + public SavannaTreePopulator(int type) {} + + public void setRandomAmount(int randomAmount) { + this.randomAmount = randomAmount; + } + + public void setBaseAmount(int baseAmount) { + this.baseAmount = baseAmount; + } + + @Override + public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + this.level = level; + int amount = random.nextBoundedInt(this.randomAmount + 1) + this.baseAmount; + Vector3 v = new Vector3(); + + for (int i = 0; i < amount; ++i) { + int x = NukkitMath.randomRange(random, chunkX << 4, (chunkX << 4) + 15); + int z = NukkitMath.randomRange(random, chunkZ << 4, (chunkZ << 4) + 15); + int y = this.getHighestWorkableBlock(x, z); + if (y == -1) { + continue; + } + new ObjectSavannaTree().generate(level, random, v.setComponents(x, y, z)); + } + } + + private int getHighestWorkableBlock(int x, int z) { + int y; + for (y = 127; y > 0; --y) { + int b = this.level.getBlockIdAt(x, y, z); + if (b == Block.DIRT || b == Block.GRASS) { + break; + } else if (b != Block.AIR && b != Block.SNOW_LAYER) { + return -1; + } + } + + return ++y; + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/tree/SwampTreePopulator.java b/src/main/java/cn/nukkit/level/generator/populator/tree/SwampTreePopulator.java new file mode 100644 index 00000000000..ab09530fe79 --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/tree/SwampTreePopulator.java @@ -0,0 +1,63 @@ +package cn.nukkit.level.generator.populator.tree; + +import cn.nukkit.block.Block; +import cn.nukkit.block.BlockSapling; +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.object.tree.ObjectSwampTree; +import cn.nukkit.level.generator.populator.type.Populator; +import cn.nukkit.math.NukkitMath; +import cn.nukkit.math.NukkitRandom; +import cn.nukkit.math.Vector3; + +public class SwampTreePopulator extends Populator { + + private ChunkManager level; + private int randomAmount; + private int baseAmount; + + public SwampTreePopulator() { + this(BlockSapling.OAK); + } + + public SwampTreePopulator(int type) {} + + public void setRandomAmount(int randomAmount) { + this.randomAmount = randomAmount; + } + + public void setBaseAmount(int baseAmount) { + this.baseAmount = baseAmount; + } + + @Override + public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { + this.level = level; + int amount = random.nextBoundedInt(this.randomAmount + 1) + this.baseAmount; + Vector3 v = new Vector3(); + + for (int i = 0; i < amount; ++i) { + int x = NukkitMath.randomRange(random, chunkX << 4, (chunkX << 4) + 15); + int z = NukkitMath.randomRange(random, chunkZ << 4, (chunkZ << 4) + 15); + int y = this.getHighestWorkableBlock(x, z); + if (y == -1) { + continue; + } + new ObjectSwampTree().generate(level, random, v.setComponents(x, y, z)); + } + } + + private int getHighestWorkableBlock(int x, int z) { + int y; + for (y = 127; y > 0; --y) { + int b = this.level.getBlockIdAt(x, y, z); + if (b == Block.DIRT || b == Block.GRASS) { + break; + } else if (b != Block.AIR && b != Block.SNOW_LAYER) { + return -1; + } + } + + return ++y; + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/type/Populator.java b/src/main/java/cn/nukkit/level/generator/populator/type/Populator.java index 481d85f7f12..16ecb4165fb 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/type/Populator.java +++ b/src/main/java/cn/nukkit/level/generator/populator/type/Populator.java @@ -6,13 +6,14 @@ import cn.nukkit.math.NukkitRandom; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class Populator implements BlockID { + public abstract void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk); - protected int getHighestWorkableBlock(ChunkManager level, int x, int z, FullChunk chunk) { + protected int getHighestWorkableBlock(ChunkManager level, int x, int z, FullChunk chunk) { return chunk.getHighestBlockAt(x & 0xF, z & 0xF); } } diff --git a/src/main/java/cn/nukkit/level/generator/populator/type/PopulatorCount.java b/src/main/java/cn/nukkit/level/generator/populator/type/PopulatorCount.java index b15bba7c42d..c537997267f 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/type/PopulatorCount.java +++ b/src/main/java/cn/nukkit/level/generator/populator/type/PopulatorCount.java @@ -11,6 +11,7 @@ * This prevents the exact same code from being repeated in nearly every single populator */ public abstract class PopulatorCount extends Populator { + private int randomAmount; private int baseAmount; diff --git a/src/main/java/cn/nukkit/level/generator/populator/type/PopulatorOceanFloorSurfaceBlock.java b/src/main/java/cn/nukkit/level/generator/populator/type/PopulatorOceanFloorSurfaceBlock.java new file mode 100644 index 00000000000..395857449cb --- /dev/null +++ b/src/main/java/cn/nukkit/level/generator/populator/type/PopulatorOceanFloorSurfaceBlock.java @@ -0,0 +1,20 @@ +package cn.nukkit.level.generator.populator.type; + +import cn.nukkit.level.ChunkManager; +import cn.nukkit.level.format.FullChunk; +import cn.nukkit.level.generator.Normal; +import cn.nukkit.level.generator.populator.helper.PopulatorHelpers; + +public abstract class PopulatorOceanFloorSurfaceBlock extends PopulatorSurfaceBlock { + + @Override + protected int getHighestWorkableBlock(ChunkManager level, int x, int z, FullChunk chunk) { + int y; + for (y = Normal.seaHeight - 1; y >= 0; --y) { + if (!PopulatorHelpers.isNonOceanSolid(chunk.getBlockId(x, y, z))) { + break; + } + } + return y == 0 ? -1 : ++y; + } +} diff --git a/src/main/java/cn/nukkit/level/generator/populator/type/PopulatorSurfaceBlock.java b/src/main/java/cn/nukkit/level/generator/populator/type/PopulatorSurfaceBlock.java index e649eb7e314..8cd56ac3245 100644 --- a/src/main/java/cn/nukkit/level/generator/populator/type/PopulatorSurfaceBlock.java +++ b/src/main/java/cn/nukkit/level/generator/populator/type/PopulatorSurfaceBlock.java @@ -11,6 +11,7 @@ * A populator that populates a single block type. */ public abstract class PopulatorSurfaceBlock extends PopulatorCount { + @Override protected void populateCount(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { int x = random.nextBoundedInt(16); @@ -28,7 +29,7 @@ protected void populateCount(ChunkManager level, int chunkX, int chunkZ, NukkitR @Override protected int getHighestWorkableBlock(ChunkManager level, int x, int z, FullChunk chunk) { int y; - //start at 254 because we add one afterwards + // Start at 254 because we add one afterwards for (y = 254; y >= 0; --y) { if (!PopulatorHelpers.isNonSolid(chunk.getBlockId(x, y, z))) { break; diff --git a/src/main/java/cn/nukkit/level/generator/task/GenerationTask.java b/src/main/java/cn/nukkit/level/generator/task/GenerationTask.java index 4d4654e227b..f9c7784e1fd 100644 --- a/src/main/java/cn/nukkit/level/generator/task/GenerationTask.java +++ b/src/main/java/cn/nukkit/level/generator/task/GenerationTask.java @@ -8,15 +8,15 @@ import cn.nukkit.scheduler.AsyncTask; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class GenerationTask extends AsyncTask { + private final Level level; public boolean state; private BaseFullChunk chunk; - public GenerationTask(Level level, BaseFullChunk chunk) { this.state = true; this.chunk = chunk; @@ -25,16 +25,17 @@ public GenerationTask(Level level, BaseFullChunk chunk) { @Override public void onRun() { - Generator generator = level.getGenerator(); this.state = false; + Generator generator = level.getGenerator(); if (generator == null) { + Server.getInstance().getLogger().debug(level.getFolderName() + "/GenerationTask: generator == null"); return; } SimpleChunkManager manager = (SimpleChunkManager) generator.getChunkManager(); if (manager == null) { - this.state = false; + Server.getInstance().getLogger().debug(level.getFolderName() + "/GenerationTask: manager == null"); return; } @@ -49,6 +50,12 @@ public void onRun() { synchronized (chunk) { if (!chunk.isGenerated()) { + if (level.getProvider() == null) { + this.state = false; + Server.getInstance().getLogger().debug(level.getFolderName() + "/GenerationTask: provider == null"); + return; + } + manager.setChunk(chunk.getX(), chunk.getZ(), chunk); generator.generateChunk(chunk.getX(), chunk.getZ()); chunk = manager.getChunk(chunk.getX(), chunk.getZ()); @@ -56,12 +63,11 @@ public void onRun() { } } this.chunk = chunk; - state = true; + this.state = true; } finally { manager.cleanChunks(level.getSeed()); } } - } @Override @@ -80,4 +86,4 @@ public void onCompletion(Server server) { level.generateChunkCallback(chunk.getX(), chunk.getZ(), chunk); } } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/generator/task/LightPopulationTask.java b/src/main/java/cn/nukkit/level/generator/task/LightPopulationTask.java index d1efa9fddd8..00700354ff8 100644 --- a/src/main/java/cn/nukkit/level/generator/task/LightPopulationTask.java +++ b/src/main/java/cn/nukkit/level/generator/task/LightPopulationTask.java @@ -6,7 +6,7 @@ import cn.nukkit.scheduler.AsyncTask; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class LightPopulationTask extends AsyncTask { @@ -37,8 +37,8 @@ public void onRun() { public void onCompletion(Server server) { Level level = server.getLevel(this.levelId); - BaseFullChunk chunk = this.chunk.clone(); if (level != null) { + BaseFullChunk chunk = this.chunk.clone(); if (chunk == null) { return; } @@ -46,4 +46,4 @@ public void onCompletion(Server server) { level.generateChunkCallback(chunk.getX(), chunk.getZ(), chunk); } } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/generator/task/PopulationTask.java b/src/main/java/cn/nukkit/level/generator/task/PopulationTask.java index 078dc8a4dbb..61c155d2c04 100644 --- a/src/main/java/cn/nukkit/level/generator/task/PopulationTask.java +++ b/src/main/java/cn/nukkit/level/generator/task/PopulationTask.java @@ -8,10 +8,11 @@ import cn.nukkit.scheduler.AsyncTask; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class PopulationTask extends AsyncTask { + private final long seed; private final Level level; private boolean state; @@ -61,13 +62,14 @@ private void generationTask() { this.state = false; Generator generator = level.getGenerator(); if (generator == null) { + Server.getInstance().getLogger().debug(level.getFolderName() + "/PopulationTask: generator == null"); return; } SimpleChunkManager manager = (SimpleChunkManager) generator.getChunkManager(); if (manager == null) { - this.state = false; + Server.getInstance().getLogger().debug(level.getFolderName() + "/PopulationTask: manager == null"); return; } @@ -85,27 +87,46 @@ private void generationTask() { for (int z = -1; z < 2; z++, index++) { BaseFullChunk ck = this.chunks[index]; if (ck == centerChunk) continue; + + if (level.getProvider() == null) { + this.state = false; + Server.getInstance().getLogger().debug(level.getFolderName() + "/PopulationTask: provider == null"); + return; + } + if (ck == null) { - try { - this.chunks[index] = (BaseFullChunk) centerChunk.getClass().getMethod("getEmptyChunk", int.class, int.class).invoke(null, centerChunk.getX() + x, centerChunk.getZ() + z); - } catch (Exception e) { - throw new RuntimeException(e); - } + //try { + //this.chunks[index] = (BaseFullChunk) centerChunk.getClass().getMethod("getEmptyChunk", int.class, int.class).invoke(null, centerChunk.getX() + x, centerChunk.getZ() + z); + this.chunks[index] = level.getProvider().getEmptyChunk(centerChunk.getX() + x, centerChunk.getZ() + z); + //} catch (Exception e) { + // throw new RuntimeException(e); + //} } else { this.chunks[index] = ck; } - } } for (BaseFullChunk chunk : this.chunks) { + if (level.getProvider() == null) { + this.state = false; + Server.getInstance().getLogger().debug(level.getFolderName() + "/PopulationTask: provider == null"); + return; + } + manager.setChunk(chunk.getX(), chunk.getZ(), chunk); if (!chunk.isGenerated()) { generator.generateChunk(chunk.getX(), chunk.getZ()); BaseFullChunk newChunk = manager.getChunk(chunk.getX(), chunk.getZ()); newChunk.setGenerated(); if (newChunk != chunk) manager.setChunk(chunk.getX(), chunk.getZ(), newChunk); - } + } + } + + if (level.getProvider() == null) { + this.state = false; + Server.getInstance().getLogger().debug(level.getFolderName() + "/PopulationTask: provider == null"); + return; } isPopulated = centerChunk.isPopulated(); @@ -131,7 +152,6 @@ private void generationTask() { chunks[index] = newChunk; } } - } } this.state = true; @@ -163,4 +183,4 @@ public void onCompletion(Server server) { level.generateChunkCallback(centerChunk.getX(), centerChunk.getZ(), centerChunk, isPopulated); } } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/particle/AngryVillagerParticle.java b/src/main/java/cn/nukkit/level/particle/AngryVillagerParticle.java index 9af7ff473a3..42506adab7e 100644 --- a/src/main/java/cn/nukkit/level/particle/AngryVillagerParticle.java +++ b/src/main/java/cn/nukkit/level/particle/AngryVillagerParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class AngryVillagerParticle extends GenericParticle { + public AngryVillagerParticle(Vector3 pos) { super(pos, Particle.TYPE_VILLAGER_ANGRY); } diff --git a/src/main/java/cn/nukkit/level/particle/BlockForceFieldParticle.java b/src/main/java/cn/nukkit/level/particle/BlockForceFieldParticle.java index 3b307c292b0..fd84ef2c69d 100644 --- a/src/main/java/cn/nukkit/level/particle/BlockForceFieldParticle.java +++ b/src/main/java/cn/nukkit/level/particle/BlockForceFieldParticle.java @@ -3,6 +3,7 @@ import cn.nukkit.math.Vector3; public class BlockForceFieldParticle extends GenericParticle { + public BlockForceFieldParticle(Vector3 pos) { this(pos, 0); } diff --git a/src/main/java/cn/nukkit/level/particle/BoneMealParticle.java b/src/main/java/cn/nukkit/level/particle/BoneMealParticle.java index 0ff4decf824..b62afd681d3 100644 --- a/src/main/java/cn/nukkit/level/particle/BoneMealParticle.java +++ b/src/main/java/cn/nukkit/level/particle/BoneMealParticle.java @@ -9,21 +9,19 @@ */ public class BoneMealParticle extends Particle { - private Vector3 position; - public BoneMealParticle(Vector3 pos) { super(pos.x, pos.y, pos.z); } @Override public DataPacket[] encode() { - LevelEventPacket pk = new LevelEventPacket(); - pk.evid = LevelEventPacket.EVENT_PARTICLE_BONEMEAL; - pk.x = (float) this.x; - pk.y = (float) this.y; - pk.z = (float) this.z; - pk.data = 0; - - return new DataPacket[]{pk}; + LevelEventPacket packet = new LevelEventPacket(); + packet.evid = LevelEventPacket.EVENT_PARTICLE_BONEMEAL; + packet.x = (float) this.x; + packet.y = (float) this.y; + packet.z = (float) this.z; + packet.data = 0; + packet.tryEncode(); + return new DataPacket[]{packet}; } } diff --git a/src/main/java/cn/nukkit/level/particle/BubbleParticle.java b/src/main/java/cn/nukkit/level/particle/BubbleParticle.java index e4013afb21a..2991032c11e 100644 --- a/src/main/java/cn/nukkit/level/particle/BubbleParticle.java +++ b/src/main/java/cn/nukkit/level/particle/BubbleParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class BubbleParticle extends GenericParticle { + public BubbleParticle(Vector3 pos) { super(pos, Particle.TYPE_BUBBLE); } diff --git a/src/main/java/cn/nukkit/level/particle/CriticalParticle.java b/src/main/java/cn/nukkit/level/particle/CriticalParticle.java index 12c670fbf88..088230e1347 100644 --- a/src/main/java/cn/nukkit/level/particle/CriticalParticle.java +++ b/src/main/java/cn/nukkit/level/particle/CriticalParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class CriticalParticle extends GenericParticle { + public CriticalParticle(Vector3 pos) { this(pos, 2); } diff --git a/src/main/java/cn/nukkit/level/particle/DestroyBlockParticle.java b/src/main/java/cn/nukkit/level/particle/DestroyBlockParticle.java index 4f81b7e4784..6436a6fef2e 100644 --- a/src/main/java/cn/nukkit/level/particle/DestroyBlockParticle.java +++ b/src/main/java/cn/nukkit/level/particle/DestroyBlockParticle.java @@ -21,13 +21,14 @@ public DestroyBlockParticle(Vector3 pos, Block block) { @Override public DataPacket[] encode() { - LevelEventPacket pk = new LevelEventPacket(); - pk.evid = LevelEventPacket.EVENT_PARTICLE_DESTROY; - pk.x = (float) this.x; - pk.y = (float) this.y; - pk.z = (float) this.z; - pk.data = this.data; + LevelEventPacket packet = new LevelEventPacket(); + packet.evid = LevelEventPacket.EVENT_PARTICLE_DESTROY; + packet.x = (float) this.x; + packet.y = (float) this.y; + packet.z = (float) this.z; - return new DataPacket[]{pk}; + packet.data = this.data; + packet.tryEncode(); + return new DataPacket[]{packet}; } } diff --git a/src/main/java/cn/nukkit/level/particle/ElectricSparkParticle.java b/src/main/java/cn/nukkit/level/particle/ElectricSparkParticle.java new file mode 100644 index 00000000000..03c0f7e6a8c --- /dev/null +++ b/src/main/java/cn/nukkit/level/particle/ElectricSparkParticle.java @@ -0,0 +1,24 @@ +package cn.nukkit.level.particle; + +import cn.nukkit.math.Vector3; +import cn.nukkit.network.protocol.DataPacket; +import cn.nukkit.network.protocol.LevelEventPacket; + +public class ElectricSparkParticle extends GenericParticle { + + public ElectricSparkParticle(Vector3 pos) { + super(pos, Particle.TYPE_WAX); + } + + @Override + public DataPacket[] encode() { + LevelEventPacket packet = new LevelEventPacket(); + packet.evid = LevelEventPacket.EVENT_PARTICLE_ELECTRIC_SPARK; + packet.x = (float) this.x; + packet.y = (float) this.y; + packet.z = (float) this.z; + packet.data = this.data; + packet.tryEncode(); + return new DataPacket[]{packet}; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/particle/EnchantParticle.java b/src/main/java/cn/nukkit/level/particle/EnchantParticle.java index dec924f536f..87d26ef2063 100644 --- a/src/main/java/cn/nukkit/level/particle/EnchantParticle.java +++ b/src/main/java/cn/nukkit/level/particle/EnchantParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class EnchantParticle extends GenericParticle { + public EnchantParticle(Vector3 pos) { super(pos, Particle.TYPE_MOB_SPELL); } diff --git a/src/main/java/cn/nukkit/level/particle/EnchantmentTableParticle.java b/src/main/java/cn/nukkit/level/particle/EnchantmentTableParticle.java index a5499a9a069..2d793706085 100644 --- a/src/main/java/cn/nukkit/level/particle/EnchantmentTableParticle.java +++ b/src/main/java/cn/nukkit/level/particle/EnchantmentTableParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class EnchantmentTableParticle extends GenericParticle { + public EnchantmentTableParticle(Vector3 pos) { super(pos, Particle.TYPE_ENCHANTMENT_TABLE); } diff --git a/src/main/java/cn/nukkit/level/particle/EntityFlameParticle.java b/src/main/java/cn/nukkit/level/particle/EntityFlameParticle.java index dbc74dd6dcb..e67c4526721 100644 --- a/src/main/java/cn/nukkit/level/particle/EntityFlameParticle.java +++ b/src/main/java/cn/nukkit/level/particle/EntityFlameParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class EntityFlameParticle extends GenericParticle { + public EntityFlameParticle(Vector3 pos) { super(pos, Particle.TYPE_MOB_FLAME); } diff --git a/src/main/java/cn/nukkit/level/particle/ExplodeParticle.java b/src/main/java/cn/nukkit/level/particle/ExplodeParticle.java index a1bb3ef92ea..a70ab352e62 100644 --- a/src/main/java/cn/nukkit/level/particle/ExplodeParticle.java +++ b/src/main/java/cn/nukkit/level/particle/ExplodeParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class ExplodeParticle extends GenericParticle { + public ExplodeParticle(Vector3 pos) { super(pos, Particle.TYPE_EXPLODE); } diff --git a/src/main/java/cn/nukkit/level/particle/FlameParticle.java b/src/main/java/cn/nukkit/level/particle/FlameParticle.java index 9ae63d42ee7..b4a4cabd3ee 100644 --- a/src/main/java/cn/nukkit/level/particle/FlameParticle.java +++ b/src/main/java/cn/nukkit/level/particle/FlameParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class FlameParticle extends GenericParticle { + public FlameParticle(Vector3 pos) { super(pos, Particle.TYPE_FLAME); } diff --git a/src/main/java/cn/nukkit/level/particle/GenericParticle.java b/src/main/java/cn/nukkit/level/particle/GenericParticle.java index 870c4f3f80c..72909bceaca 100644 --- a/src/main/java/cn/nukkit/level/particle/GenericParticle.java +++ b/src/main/java/cn/nukkit/level/particle/GenericParticle.java @@ -10,7 +10,7 @@ */ public class GenericParticle extends Particle { - protected int id = 0; + protected int id; protected final int data; @@ -26,13 +26,13 @@ public GenericParticle(Vector3 pos, int id, int data) { @Override public DataPacket[] encode() { - LevelEventPacket pk = new LevelEventPacket(); - pk.evid = (short) (LevelEventPacket.EVENT_ADD_PARTICLE_MASK | this.id); - pk.x = (float) this.x; - pk.y = (float) this.y; - pk.z = (float) this.z; - pk.data = this.data; - - return new DataPacket[]{pk}; + LevelEventPacket packet = new LevelEventPacket(); + packet.evid = (short) (LevelEventPacket.EVENT_ADD_PARTICLE_MASK | this.id); + packet.x = (float) this.x; + packet.y = (float) this.y; + packet.z = (float) this.z; + packet.data = this.data; + packet.tryEncode(); + return new DataPacket[]{packet}; } } diff --git a/src/main/java/cn/nukkit/level/particle/HappyVillagerParticle.java b/src/main/java/cn/nukkit/level/particle/HappyVillagerParticle.java index 494d38a64b4..0750ab67f62 100644 --- a/src/main/java/cn/nukkit/level/particle/HappyVillagerParticle.java +++ b/src/main/java/cn/nukkit/level/particle/HappyVillagerParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class HappyVillagerParticle extends GenericParticle { + public HappyVillagerParticle(Vector3 pos) { super(pos, Particle.TYPE_VILLAGER_HAPPY); } diff --git a/src/main/java/cn/nukkit/level/particle/HeartParticle.java b/src/main/java/cn/nukkit/level/particle/HeartParticle.java index 1d94e017c35..90640170386 100644 --- a/src/main/java/cn/nukkit/level/particle/HeartParticle.java +++ b/src/main/java/cn/nukkit/level/particle/HeartParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class HeartParticle extends GenericParticle { + public HeartParticle(Vector3 pos) { this(pos, 0); } diff --git a/src/main/java/cn/nukkit/level/particle/HugeExplodeParticle.java b/src/main/java/cn/nukkit/level/particle/HugeExplodeParticle.java index af056ffb04d..ad310911605 100644 --- a/src/main/java/cn/nukkit/level/particle/HugeExplodeParticle.java +++ b/src/main/java/cn/nukkit/level/particle/HugeExplodeParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class HugeExplodeParticle extends GenericParticle { + public HugeExplodeParticle(Vector3 pos) { super(pos, Particle.TYPE_HUGE_EXPLODE); } diff --git a/src/main/java/cn/nukkit/level/particle/HugeExplodeSeedParticle.java b/src/main/java/cn/nukkit/level/particle/HugeExplodeSeedParticle.java index a5fc23b480a..c3bd7105e61 100644 --- a/src/main/java/cn/nukkit/level/particle/HugeExplodeSeedParticle.java +++ b/src/main/java/cn/nukkit/level/particle/HugeExplodeSeedParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class HugeExplodeSeedParticle extends GenericParticle { + public HugeExplodeSeedParticle(Vector3 pos) { super(pos, Particle.TYPE_HUGE_EXPLODE_SEED); } diff --git a/src/main/java/cn/nukkit/level/particle/InstantEnchantParticle.java b/src/main/java/cn/nukkit/level/particle/InstantEnchantParticle.java index 751ee650079..d5d46cdabf1 100644 --- a/src/main/java/cn/nukkit/level/particle/InstantEnchantParticle.java +++ b/src/main/java/cn/nukkit/level/particle/InstantEnchantParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class InstantEnchantParticle extends GenericParticle { + public InstantEnchantParticle(Vector3 pos) { super(pos, Particle.TYPE_MOB_SPELL_INSTANTANEOUS); } diff --git a/src/main/java/cn/nukkit/level/particle/InstantSpellParticle.java b/src/main/java/cn/nukkit/level/particle/InstantSpellParticle.java index 80c29518eca..c8693d69533 100644 --- a/src/main/java/cn/nukkit/level/particle/InstantSpellParticle.java +++ b/src/main/java/cn/nukkit/level/particle/InstantSpellParticle.java @@ -8,7 +8,6 @@ * Package cn.nukkit.level.particle in project nukkit . */ public class InstantSpellParticle extends SpellParticle { - protected int data; public InstantSpellParticle(Vector3 pos) { this(pos, 0); @@ -27,5 +26,4 @@ public InstantSpellParticle(Vector3 pos, int r, int g, int b) { //this 0x01 is the only difference between instant spell and non-instant one super(pos, r, g, b, 0x01); } - } diff --git a/src/main/java/cn/nukkit/level/particle/ItemBreakParticle.java b/src/main/java/cn/nukkit/level/particle/ItemBreakParticle.java index b8722427d86..375c21b9998 100644 --- a/src/main/java/cn/nukkit/level/particle/ItemBreakParticle.java +++ b/src/main/java/cn/nukkit/level/particle/ItemBreakParticle.java @@ -26,6 +26,7 @@ public DataPacket[] encode() { packet.y = (float) this.y; packet.z = (float) this.z; packet.data = this.data; + packet.tryEncode(); return new DataPacket[]{packet}; } } diff --git a/src/main/java/cn/nukkit/level/particle/LavaDripParticle.java b/src/main/java/cn/nukkit/level/particle/LavaDripParticle.java index 8397fa9e43c..89b57d03b43 100644 --- a/src/main/java/cn/nukkit/level/particle/LavaDripParticle.java +++ b/src/main/java/cn/nukkit/level/particle/LavaDripParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class LavaDripParticle extends GenericParticle { + public LavaDripParticle(Vector3 pos) { super(pos, Particle.TYPE_DRIP_LAVA); } diff --git a/src/main/java/cn/nukkit/level/particle/LavaParticle.java b/src/main/java/cn/nukkit/level/particle/LavaParticle.java index d64fb7ad7ec..eb7bc8f2cc6 100644 --- a/src/main/java/cn/nukkit/level/particle/LavaParticle.java +++ b/src/main/java/cn/nukkit/level/particle/LavaParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class LavaParticle extends GenericParticle { + public LavaParticle(Vector3 pos) { super(pos, Particle.TYPE_LAVA); } diff --git a/src/main/java/cn/nukkit/level/particle/MobSpawnParticle.java b/src/main/java/cn/nukkit/level/particle/MobSpawnParticle.java index 56827e741e8..191875970d6 100644 --- a/src/main/java/cn/nukkit/level/particle/MobSpawnParticle.java +++ b/src/main/java/cn/nukkit/level/particle/MobSpawnParticle.java @@ -27,7 +27,7 @@ public DataPacket[] encode() { packet.y = (float) this.y; packet.z = (float) this.z; packet.data = (this.width & 0xff) + ((this.height & 0xff) << 8); - + packet.tryEncode(); return new DataPacket[]{packet}; } } diff --git a/src/main/java/cn/nukkit/level/particle/Particle.java b/src/main/java/cn/nukkit/level/particle/Particle.java index 6d1fd70fe9b..894f915a5e4 100644 --- a/src/main/java/cn/nukkit/level/particle/Particle.java +++ b/src/main/java/cn/nukkit/level/particle/Particle.java @@ -6,7 +6,7 @@ import java.lang.reflect.Field; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class Particle extends Vector3 { @@ -104,6 +104,24 @@ public abstract class Particle extends Vector3 { public static final int TYPE_WOLF_ARMOR_BREAK = 92; public static final int TYPE_OMINOUS_ITEM_SPAWNER = 93; + public Particle() { + super(0, 0, 0); + } + + public Particle(double x) { + super(x, 0, 0); + } + + public Particle(double x, double y) { + super(x, y, 0); + } + + public Particle(double x, double y, double z) { + super(x, y, z); + } + + public abstract DataPacket[] encode(); + public static Integer getParticleIdByName(String name) { name = name.toUpperCase(); @@ -115,31 +133,11 @@ public static Integer getParticleIdByName(String name) { if (type == int.class) { return field.getInt(null); } - } catch (NoSuchFieldException | IllegalAccessException e) { - // ignore - } + } catch (NoSuchFieldException | IllegalAccessException ignored) {} return null; } public static boolean particleExists(String name) { return getParticleIdByName(name) != null; } - - public Particle() { - super(0, 0, 0); - } - - public Particle(double x) { - super(x, 0, 0); - } - - public Particle(double x, double y) { - super(x, y, 0); - } - - public Particle(double x, double y, double z) { - super(x, y, z); - } - - abstract public DataPacket[] encode(); } diff --git a/src/main/java/cn/nukkit/level/particle/PortalParticle.java b/src/main/java/cn/nukkit/level/particle/PortalParticle.java index 282130b6486..d3a8473efd0 100644 --- a/src/main/java/cn/nukkit/level/particle/PortalParticle.java +++ b/src/main/java/cn/nukkit/level/particle/PortalParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class PortalParticle extends GenericParticle { + public PortalParticle(Vector3 pos) { super(pos, Particle.TYPE_PORTAL); } diff --git a/src/main/java/cn/nukkit/level/particle/PunchBlockParticle.java b/src/main/java/cn/nukkit/level/particle/PunchBlockParticle.java index f7ce141abcb..f4f14a5aa62 100644 --- a/src/main/java/cn/nukkit/level/particle/PunchBlockParticle.java +++ b/src/main/java/cn/nukkit/level/particle/PunchBlockParticle.java @@ -9,7 +9,10 @@ public class PunchBlockParticle extends Particle { - protected final int data; + protected final int blockId; + protected final int blockDamage; + protected final int index; + protected final int face; public PunchBlockParticle(Vector3 pos, Block block, BlockFace face) { this(pos, block.getId(), block.getDamage(), face); @@ -17,18 +20,21 @@ public PunchBlockParticle(Vector3 pos, Block block, BlockFace face) { public PunchBlockParticle(Vector3 pos, int blockId, int blockDamage, BlockFace face) { super(pos.x, pos.y, pos.z); - this.data = GlobalBlockPalette.getOrCreateRuntimeId(blockId, blockDamage) | (face.getIndex() << 24); + this.blockId = blockId; + this.blockDamage = blockDamage; + this.face = face.getIndex(); + this.index = this.face << 24; } @Override public DataPacket[] encode() { - LevelEventPacket pk = new LevelEventPacket(); - pk.evid = LevelEventPacket.EVENT_PARTICLE_PUNCH_BLOCK; - pk.x = (float) this.x; - pk.y = (float) this.y; - pk.z = (float) this.z; - pk.data = this.data; - - return new DataPacket[]{pk}; + LevelEventPacket packet = new LevelEventPacket(); + packet.evid = LevelEventPacket.EVENT_PARTICLE_PUNCH_BLOCK; + packet.x = (float) this.x; + packet.y = (float) this.y; + packet.z = (float) this.z; + packet.data = GlobalBlockPalette.getOrCreateRuntimeId(blockId, blockDamage) | index; + packet.tryEncode(); + return new DataPacket[]{packet}; } } diff --git a/src/main/java/cn/nukkit/level/particle/RainSplashParticle.java b/src/main/java/cn/nukkit/level/particle/RainSplashParticle.java index 5149c748a5d..86730109567 100644 --- a/src/main/java/cn/nukkit/level/particle/RainSplashParticle.java +++ b/src/main/java/cn/nukkit/level/particle/RainSplashParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class RainSplashParticle extends GenericParticle { + public RainSplashParticle(Vector3 pos) { super(pos, Particle.TYPE_RAIN_SPLASH); } diff --git a/src/main/java/cn/nukkit/level/particle/RedstoneParticle.java b/src/main/java/cn/nukkit/level/particle/RedstoneParticle.java index 7effbfa34b7..c815dd7f469 100644 --- a/src/main/java/cn/nukkit/level/particle/RedstoneParticle.java +++ b/src/main/java/cn/nukkit/level/particle/RedstoneParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class RedstoneParticle extends GenericParticle { + public RedstoneParticle(Vector3 pos) { this(pos, 1); } diff --git a/src/main/java/cn/nukkit/level/particle/ScrapeParticle.java b/src/main/java/cn/nukkit/level/particle/ScrapeParticle.java new file mode 100644 index 00000000000..50cb24ef19c --- /dev/null +++ b/src/main/java/cn/nukkit/level/particle/ScrapeParticle.java @@ -0,0 +1,24 @@ +package cn.nukkit.level.particle; + +import cn.nukkit.math.Vector3; +import cn.nukkit.network.protocol.DataPacket; +import cn.nukkit.network.protocol.LevelEventPacket; + +public class ScrapeParticle extends GenericParticle { + + public ScrapeParticle(Vector3 pos) { + super(pos, Particle.TYPE_WAX); + } + + @Override + public DataPacket[] encode() { + LevelEventPacket packet = new LevelEventPacket(); + packet.evid = LevelEventPacket.EVENT_PARTICLE_SCRAPE; + packet.x = (float) this.x; + packet.y = (float) this.y; + packet.z = (float) this.z; + packet.data = this.data; + packet.tryEncode(); + return new DataPacket[]{packet}; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/particle/SmokeParticle.java b/src/main/java/cn/nukkit/level/particle/SmokeParticle.java index 2544f836717..5db5fe0044e 100644 --- a/src/main/java/cn/nukkit/level/particle/SmokeParticle.java +++ b/src/main/java/cn/nukkit/level/particle/SmokeParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class SmokeParticle extends GenericParticle { + public SmokeParticle(Vector3 pos) { this(pos, 0); } diff --git a/src/main/java/cn/nukkit/level/particle/SpellParticle.java b/src/main/java/cn/nukkit/level/particle/SpellParticle.java index 038b9273dc6..629ec65a518 100644 --- a/src/main/java/cn/nukkit/level/particle/SpellParticle.java +++ b/src/main/java/cn/nukkit/level/particle/SpellParticle.java @@ -38,13 +38,13 @@ protected SpellParticle(Vector3 pos, int r, int g, int b, int a) { @Override public DataPacket[] encode() { - LevelEventPacket pk = new LevelEventPacket(); - pk.evid = LevelEventPacket.EVENT_PARTICLE_SPLASH; - pk.x = (float) this.x; - pk.y = (float) this.y; - pk.z = (float) this.z; - pk.data = this.data; - - return new DataPacket[]{pk}; + LevelEventPacket packet = new LevelEventPacket(); + packet.evid = LevelEventPacket.EVENT_PARTICLE_SPLASH; + packet.x = (float) this.x; + packet.y = (float) this.y; + packet.z = (float) this.z; + packet.data = this.data; + packet.tryEncode(); + return new DataPacket[]{packet}; } } diff --git a/src/main/java/cn/nukkit/level/particle/SplashParticle.java b/src/main/java/cn/nukkit/level/particle/SplashParticle.java index 5128cc75be5..8e8f825f042 100644 --- a/src/main/java/cn/nukkit/level/particle/SplashParticle.java +++ b/src/main/java/cn/nukkit/level/particle/SplashParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class SplashParticle extends GenericParticle { + public SplashParticle(Vector3 pos) { super(pos, Particle.TYPE_WATER_SPLASH); } diff --git a/src/main/java/cn/nukkit/level/particle/SporeParticle.java b/src/main/java/cn/nukkit/level/particle/SporeParticle.java index 78b223b8dac..3557c1d8469 100644 --- a/src/main/java/cn/nukkit/level/particle/SporeParticle.java +++ b/src/main/java/cn/nukkit/level/particle/SporeParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class SporeParticle extends GenericParticle { + public SporeParticle(Vector3 pos) { super(pos, Particle.TYPE_TOWN_AURA); } diff --git a/src/main/java/cn/nukkit/level/particle/TerrainParticle.java b/src/main/java/cn/nukkit/level/particle/TerrainParticle.java index 1041dc4d232..d55caecea6e 100644 --- a/src/main/java/cn/nukkit/level/particle/TerrainParticle.java +++ b/src/main/java/cn/nukkit/level/particle/TerrainParticle.java @@ -9,6 +9,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class TerrainParticle extends GenericParticle { + public TerrainParticle(Vector3 pos, Block block) { super(pos, Particle.TYPE_TERRAIN, GlobalBlockPalette.getOrCreateRuntimeId(block.getId(), block.getDamage())); } diff --git a/src/main/java/cn/nukkit/level/particle/WaterDripParticle.java b/src/main/java/cn/nukkit/level/particle/WaterDripParticle.java index 9c7b34536ac..b8c780387b3 100644 --- a/src/main/java/cn/nukkit/level/particle/WaterDripParticle.java +++ b/src/main/java/cn/nukkit/level/particle/WaterDripParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class WaterDripParticle extends GenericParticle { + public WaterDripParticle(Vector3 pos) { super(pos, Particle.TYPE_DRIP_WATER); } diff --git a/src/main/java/cn/nukkit/level/particle/WaterParticle.java b/src/main/java/cn/nukkit/level/particle/WaterParticle.java index 7f6a1d92393..7446fe1c86b 100644 --- a/src/main/java/cn/nukkit/level/particle/WaterParticle.java +++ b/src/main/java/cn/nukkit/level/particle/WaterParticle.java @@ -7,6 +7,7 @@ * Package cn.nukkit.level.particle in project Nukkit . */ public class WaterParticle extends GenericParticle { + public WaterParticle(Vector3 pos) { super(pos, Particle.TYPE_WATER_WAKE); } diff --git a/src/main/java/cn/nukkit/level/particle/WaxOffParticle.java b/src/main/java/cn/nukkit/level/particle/WaxOffParticle.java new file mode 100644 index 00000000000..09af7240d5f --- /dev/null +++ b/src/main/java/cn/nukkit/level/particle/WaxOffParticle.java @@ -0,0 +1,24 @@ +package cn.nukkit.level.particle; + +import cn.nukkit.math.Vector3; +import cn.nukkit.network.protocol.DataPacket; +import cn.nukkit.network.protocol.LevelEventPacket; + +public class WaxOffParticle extends GenericParticle { + + public WaxOffParticle(Vector3 pos) { + super(pos, Particle.TYPE_WAX); + } + + @Override + public DataPacket[] encode() { + LevelEventPacket packet = new LevelEventPacket(); + packet.evid = LevelEventPacket.EVENT_PARTICLE_WAX_OFF; + packet.x = (float) this.x; + packet.y = (float) this.y; + packet.z = (float) this.z; + packet.data = this.data; + packet.tryEncode(); + return new DataPacket[]{packet}; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/particle/WaxOnParticle.java b/src/main/java/cn/nukkit/level/particle/WaxOnParticle.java new file mode 100644 index 00000000000..f74e4fdc42d --- /dev/null +++ b/src/main/java/cn/nukkit/level/particle/WaxOnParticle.java @@ -0,0 +1,24 @@ +package cn.nukkit.level.particle; + +import cn.nukkit.math.Vector3; +import cn.nukkit.network.protocol.DataPacket; +import cn.nukkit.network.protocol.LevelEventPacket; + +public class WaxOnParticle extends GenericParticle { + + public WaxOnParticle(Vector3 pos) { + super(pos, Particle.TYPE_WAX); + } + + @Override + public DataPacket[] encode() { + LevelEventPacket packet = new LevelEventPacket(); + packet.evid = LevelEventPacket.EVENT_PARTICLE_WAX_ON; + packet.x = (float) this.x; + packet.y = (float) this.y; + packet.z = (float) this.z; + packet.data = this.data; + packet.tryEncode(); + return new DataPacket[]{packet}; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/level/persistence/ImmutableCompoundTag.java b/src/main/java/cn/nukkit/level/persistence/ImmutableCompoundTag.java new file mode 100644 index 00000000000..35034ef5c6a --- /dev/null +++ b/src/main/java/cn/nukkit/level/persistence/ImmutableCompoundTag.java @@ -0,0 +1,241 @@ +package cn.nukkit.level.persistence; + +import cn.nukkit.nbt.stream.NBTInputStream; +import cn.nukkit.nbt.tag.*; + +import java.io.IOException; +import java.io.PrintStream; +import java.util.Collection; +import java.util.Map; + +public class ImmutableCompoundTag extends CompoundTag { + + public static final CompoundTag EMPTY = new ImmutableCompoundTag(new CompoundTag()); + + public static CompoundTag of(CompoundTag tag) { + return new ImmutableCompoundTag(tag); + } + + private final CompoundTag delegate; + + private ImmutableCompoundTag(CompoundTag delegate) { + this.delegate = delegate; + } + + @Override + public void load(NBTInputStream dis) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public CompoundTag put(String name, Tag tag) { + throw new UnsupportedOperationException(); + } + + @Override + public CompoundTag putByte(String name, int value) { + throw new UnsupportedOperationException(); + } + + @Override + public CompoundTag putShort(String name, int value) { + throw new UnsupportedOperationException(); + } + + @Override + public CompoundTag putInt(String name, int value) { + throw new UnsupportedOperationException(); + } + + @Override + public CompoundTag putLong(String name, long value) { + throw new UnsupportedOperationException(); + } + + @Override + public CompoundTag putFloat(String name, float value) { + throw new UnsupportedOperationException(); + } + + @Override + public CompoundTag putDouble(String name, double value) { + throw new UnsupportedOperationException(); + } + + @Override + public CompoundTag putString(String name, String value) { + throw new UnsupportedOperationException(); + } + + @Override + public CompoundTag putByteArray(String name, byte[] value) { + throw new UnsupportedOperationException(); + } + + @Override + public CompoundTag putIntArray(String name, int[] value) { + throw new UnsupportedOperationException(); + } + @Override + + public CompoundTag putList(ListTag listTag) { + throw new UnsupportedOperationException(); + } + + @Override + public CompoundTag putCompound(String name, CompoundTag value) { + throw new UnsupportedOperationException(); + } + + @Override + public CompoundTag putBoolean(String string, boolean val) { + throw new UnsupportedOperationException(); + } + + @Override + public CompoundTag remove(String name) { + throw new UnsupportedOperationException(); + } + + @Override + public T removeAndGet(String name) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean contains(String name) { + return this.delegate.contains(name); + } + + @Override + public Collection getAllTags() { + return this.delegate.getAllTags(); + } + + @Override + public int getByte(String name) { + return this.delegate.getByte(name); + } + + @Override + public int getShort(String name) { + return this.delegate.getShort(name); + } + + @Override + public int getInt(String name) { + return this.delegate.getInt(name); + } + @Override + public long getLong(String name) { + return this.delegate.getLong(name); + } + + @Override + public float getFloat(String name) { + return this.delegate.getFloat(name); + } + + @Override + public double getDouble(String name) { + return this.delegate.getDouble(name); + } + + @Override + public String getString(String name) { + return this.delegate.getString(name); + } + + @Override + public byte[] getByteArray(String name) { + return this.delegate.getByteArray(name); + } + + @Override + public byte[] getByteArray(String name, int defaultSize) { + return this.delegate.getByteArray(name, defaultSize); + } + + @Override + public int[] getIntArray(String name) { + return this.delegate.getIntArray(name); + } + + @Override + public CompoundTag getCompound(String name) { + return this.delegate.getCompound(name); + } + + @Override + public ListTag getList(String name) { + return this.delegate.getList(name); + } + + @Override + public ListTag getList(String name, Class type) { + return this.delegate.getList(name, type); + } + + @Override + public Map getTags() { + return this.delegate.getTags(); + } + + @Override + public Map parseValue() { + return this.delegate.parseValue(); + } + + @Override + public boolean getBoolean(String name) { + return this.delegate.getBoolean(name); + } + + @Override + public boolean getBoolean(String name, boolean def) { + return this.delegate.getBoolean(name, def); + } + + @Override + public String toString() { + return this.delegate.toString(); + } + + @Override + public void print(PrintStream out) { + this.delegate.print(out); + } + + @Override + public void print(String prefix, PrintStream out) { + this.delegate.print(prefix, out); + } + + @Override + public boolean isEmpty() { + return this.delegate.isEmpty(); + } + + @Override + public CompoundTag copy() { + return this; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof ImmutableCompoundTag) { + return this.delegate.equals(((ImmutableCompoundTag) obj).delegate); + } + return this.delegate.equals(obj); + } + + @Override + public boolean exist(String name) { + return this.delegate.exist(name); + } + + @Override + public CompoundTag clone() { + return this; + } +} diff --git a/src/main/java/cn/nukkit/level/persistence/PersistentDataContainer.java b/src/main/java/cn/nukkit/level/persistence/PersistentDataContainer.java new file mode 100644 index 00000000000..0a4da27564c --- /dev/null +++ b/src/main/java/cn/nukkit/level/persistence/PersistentDataContainer.java @@ -0,0 +1,58 @@ +package cn.nukkit.level.persistence; + +import cn.nukkit.nbt.tag.CompoundTag; +import cn.nukkit.nbt.tag.Tag; + +public interface PersistentDataContainer { + String STORAGE_TAG = "persistent_storage"; + + CompoundTag getStorage(); + + default CompoundTag getReadStorage() { + return this.getStorage(); + } + + void setStorage(CompoundTag storage); + + default void set(String key, PersistentDataType type, T value) { + if (value == null) { + this.remove(key); + } else { + this.getStorage().put(key, type.serialize(value)); + this.write(); + } + } + + default boolean has(String key, PersistentDataType type) { + Tag tag = this.getReadStorage().get(key); + return tag != null && type.validate(tag); + } + + default T get(String key, PersistentDataType type) { + Tag tag = this.getReadStorage().get(key); + if (tag != null && type.validate(tag)) { + return type.deserialize(tag); + } if (tag != null) { + this.remove(key); + } + return null; + } + + default void write() { + } + + default void remove(String key) { + if (this.getReadStorage().contains(key)) { + this.getStorage().remove(key); + this.write(); + } + } + + default void clearStorage() { + this.setStorage(new CompoundTag()); + } + + default boolean isEmpty() { + return this.getReadStorage().isEmpty(); + } +} diff --git a/src/main/java/cn/nukkit/level/persistence/PersistentDataType.java b/src/main/java/cn/nukkit/level/persistence/PersistentDataType.java new file mode 100644 index 00000000000..6891bdf99ad --- /dev/null +++ b/src/main/java/cn/nukkit/level/persistence/PersistentDataType.java @@ -0,0 +1,49 @@ +package cn.nukkit.level.persistence; + +import cn.nukkit.nbt.tag.*; +import lombok.AllArgsConstructor; +import lombok.Getter; + +import java.util.function.Function; + +public interface PersistentDataType { + + PersistentDataType BOOLEAN = new PrimitiveDataType<>(Boolean.class, ByteTag.class, val -> new ByteTag(null, val ? 1 : 0), tag -> tag.parseValue() == 1); + PersistentDataType BYTE = new PrimitiveDataType<>(Byte.class, ByteTag.class, val -> new ByteTag(null, val), tag -> tag.parseValue().byteValue()); + PersistentDataType INT = new PrimitiveDataType<>(Integer.class, IntTag.class, val -> new IntTag(null, val), IntTag::parseValue); + PersistentDataType DOUBLE = new PrimitiveDataType<>(Double.class, DoubleTag.class, val -> new DoubleTag(null, val), DoubleTag::parseValue); + PersistentDataType FLOAT = new PrimitiveDataType<>(Float.class, FloatTag.class, val -> new FloatTag(null, val), FloatTag::parseValue); + PersistentDataType STRING = new PrimitiveDataType<>(String.class, StringTag.class, val -> new StringTag(null, val), StringTag::parseValue); + + Class getImplementation(); + + Tag serialize(T value); + + T deserialize(Tag tag); + + boolean validate(Tag tag); + + @Getter + @AllArgsConstructor + class PrimitiveDataType implements PersistentDataType { + private final Class implementation; + private final Class tagClass; + private final Function serializer; + private final Function deserializer; + + @Override + public Tag serialize(T value) { + return this.serializer.apply(value); + } + + @Override + public T deserialize(Tag tag) { + return this.deserializer.apply((I) tag); + } + + @Override + public boolean validate(Tag tag) { + return this.tagClass.isAssignableFrom(tag.getClass()); + } + } +} diff --git a/src/main/java/cn/nukkit/level/persistence/PersistentItemDataContainer.java b/src/main/java/cn/nukkit/level/persistence/PersistentItemDataContainer.java new file mode 100644 index 00000000000..23b89815c29 --- /dev/null +++ b/src/main/java/cn/nukkit/level/persistence/PersistentItemDataContainer.java @@ -0,0 +1,8 @@ +package cn.nukkit.level.persistence; + +public interface PersistentItemDataContainer extends PersistentDataContainer { + + void setConvertsToBlock(boolean value); + + boolean convertsToBlock(); +} diff --git a/src/main/java/cn/nukkit/level/persistence/impl/DelegatePersistentDataContainer.java b/src/main/java/cn/nukkit/level/persistence/impl/DelegatePersistentDataContainer.java new file mode 100644 index 00000000000..892496e5f6f --- /dev/null +++ b/src/main/java/cn/nukkit/level/persistence/impl/DelegatePersistentDataContainer.java @@ -0,0 +1,34 @@ +package cn.nukkit.level.persistence.impl; + +import cn.nukkit.level.persistence.ImmutableCompoundTag; +import cn.nukkit.level.persistence.PersistentDataContainer; +import cn.nukkit.nbt.tag.CompoundTag; + +public abstract class DelegatePersistentDataContainer implements PersistentDataContainer { + + private PersistentDataContainer delegate; + + protected abstract PersistentDataContainer createDelegate(); + + protected final PersistentDataContainer getDelegate() { + if (this.delegate == null) { + this.delegate = this.createDelegate(); + } + return this.delegate; + } + + @Override + public CompoundTag getStorage() { + return this.getDelegate().getStorage(); + } + + @Override + public void setStorage(CompoundTag storage) { + this.getDelegate().setStorage(storage); + } + + @Override + public CompoundTag getReadStorage() { + return this.delegate == null ? ImmutableCompoundTag.EMPTY : this.getStorage(); + } +} diff --git a/src/main/java/cn/nukkit/level/persistence/impl/PersistentDataContainerBlockWrapper.java b/src/main/java/cn/nukkit/level/persistence/impl/PersistentDataContainerBlockWrapper.java new file mode 100644 index 00000000000..95a1d65ea8c --- /dev/null +++ b/src/main/java/cn/nukkit/level/persistence/impl/PersistentDataContainerBlockWrapper.java @@ -0,0 +1,58 @@ +package cn.nukkit.level.persistence.impl; + +import cn.nukkit.blockentity.BlockEntity; +import cn.nukkit.level.persistence.ImmutableCompoundTag; +import cn.nukkit.level.persistence.PersistentDataContainer; +import cn.nukkit.nbt.tag.CompoundTag; + +public class PersistentDataContainerBlockWrapper implements PersistentDataContainer { + + private final BlockEntity blockEntity; + private CompoundTag storage; + + public PersistentDataContainerBlockWrapper(BlockEntity blockEntity) { + this.blockEntity = blockEntity; + } + + @Override + public CompoundTag getReadStorage() { + CompoundTag storage = this.getInternalStorage(); + if (storage == null) { + return ImmutableCompoundTag.EMPTY; + } + return storage; + } + + @Override + public CompoundTag getStorage() { + CompoundTag storage = this.getInternalStorage(); + if (storage == null) { + storage = new CompoundTag(); + this.setStorage(storage); + } + return storage; + } + + private CompoundTag getInternalStorage() { + if (this.storage != null) { + return this.storage; + } + + if (this.blockEntity.namedTag.contains(STORAGE_TAG)) { + return this.storage = this.blockEntity.namedTag.getCompound(STORAGE_TAG); + } + return null; + } + + @Override + public void setStorage(CompoundTag storage) { + this.blockEntity.namedTag.putCompound(STORAGE_TAG, storage); + this.storage = storage; + } + + @Override + public void clearStorage() { + this.blockEntity.namedTag.remove(STORAGE_TAG); + this.storage = null; + } +} diff --git a/src/main/java/cn/nukkit/level/persistence/impl/PersistentDataContainerEntityWrapper.java b/src/main/java/cn/nukkit/level/persistence/impl/PersistentDataContainerEntityWrapper.java new file mode 100644 index 00000000000..590e2e030cb --- /dev/null +++ b/src/main/java/cn/nukkit/level/persistence/impl/PersistentDataContainerEntityWrapper.java @@ -0,0 +1,63 @@ +package cn.nukkit.level.persistence.impl; + +import cn.nukkit.entity.Entity; +import cn.nukkit.level.persistence.ImmutableCompoundTag; +import cn.nukkit.level.persistence.PersistentDataContainer; +import cn.nukkit.nbt.tag.CompoundTag; + +public class PersistentDataContainerEntityWrapper implements PersistentDataContainer { + + private final Entity entity; + private CompoundTag storage; + + public PersistentDataContainerEntityWrapper(Entity entity) { + this.entity = entity; + } + + @Override + public CompoundTag getReadStorage() { + CompoundTag storage = this.getInternalStorage(); + if (storage == null) { + return ImmutableCompoundTag.EMPTY; + } + return storage; + } + + @Override + public CompoundTag getStorage() { + CompoundTag storage = this.getInternalStorage(); + if (storage == null) { + storage = new CompoundTag(); + this.setStorage(storage); + } + return storage; + } + + private CompoundTag getInternalStorage() { + if (this.storage != null) { + return this.storage; + } + + if (this.entity.namedTag.contains(STORAGE_TAG)) { + return this.storage = this.entity.namedTag.getCompound(STORAGE_TAG); + } + return null; + } + + @Override + public void setStorage(CompoundTag storage) { + this.entity.namedTag.putCompound(STORAGE_TAG, storage); + this.storage = storage; + } + + @Override + public void write() { + this.setStorage(this.getStorage()); + } + + @Override + public void clearStorage() { + this.entity.namedTag.remove(STORAGE_TAG); + this.storage = null; + } +} diff --git a/src/main/java/cn/nukkit/level/persistence/impl/PersistentDataContainerItemWrapper.java b/src/main/java/cn/nukkit/level/persistence/impl/PersistentDataContainerItemWrapper.java new file mode 100644 index 00000000000..77250f09be6 --- /dev/null +++ b/src/main/java/cn/nukkit/level/persistence/impl/PersistentDataContainerItemWrapper.java @@ -0,0 +1,84 @@ +package cn.nukkit.level.persistence.impl; + +import cn.nukkit.item.Item; +import cn.nukkit.level.persistence.ImmutableCompoundTag; +import cn.nukkit.level.persistence.PersistentItemDataContainer; +import cn.nukkit.nbt.tag.CompoundTag; + +public class PersistentDataContainerItemWrapper implements PersistentItemDataContainer { + + private final Item item; + private boolean convertsToBlock = false; + private CompoundTag storage; + + public PersistentDataContainerItemWrapper(Item item) { + this.item = item; + } + + @Override + public CompoundTag getReadStorage() { + CompoundTag storage = this.getInternalStorage(); + if (storage == null) { + return ImmutableCompoundTag.EMPTY; + } + return storage; + } + + @Override + public CompoundTag getStorage() { + CompoundTag storage = this.getInternalStorage(); + if (storage == null) { + storage = new CompoundTag(); + this.setStorage(storage); + } + return storage; + } + + private CompoundTag getInternalStorage() { + if (this.storage != null) { + return this.storage; + } + + if (this.item.hasCompoundTag() && this.item.getNamedTag().contains(STORAGE_TAG)) { + return this.storage = this.item.getNamedTag().getCompound(STORAGE_TAG); + } + return null; + } + + @Override + public void setStorage(CompoundTag storage) { + CompoundTag compoundTag = this.item.hasCompoundTag() ? this.item.getNamedTag() : new CompoundTag(); + compoundTag.putCompound(STORAGE_TAG, storage); + this.item.setCompoundTag(compoundTag); + this.storage = storage; + } + + @Override + public void write() { + if (this.getReadStorage().isEmpty()) { + this.clearStorage(); + } else { + this.setStorage(this.getStorage()); + } + } + + @Override + public void setConvertsToBlock(boolean convertsToBlock) { + this.convertsToBlock = convertsToBlock; + } + + @Override + public boolean convertsToBlock() { + return this.convertsToBlock; + } + + @Override + public void clearStorage() { + if (this.item.hasCompoundTag()) { + CompoundTag compoundTag = this.item.getNamedTag(); + compoundTag.remove(STORAGE_TAG); + this.item.setCompoundTag(compoundTag); + } + this.storage = null; + } +} diff --git a/src/main/java/cn/nukkit/level/util/BitArrayVersion.java b/src/main/java/cn/nukkit/level/util/BitArrayVersion.java index 8596bc89a34..12bfbe0653c 100644 --- a/src/main/java/cn/nukkit/level/util/BitArrayVersion.java +++ b/src/main/java/cn/nukkit/level/util/BitArrayVersion.java @@ -1,6 +1,7 @@ package cn.nukkit.level.util; public enum BitArrayVersion { + V16(16, 2, null), V8(8, 4, V16), V6(6, 5, V8), // 2 bit padding @@ -8,7 +9,10 @@ public enum BitArrayVersion { V4(4, 8, V5), V3(3, 10, V4), // 2 bit padding V2(2, 16, V3), - V1(1, 32, V2); + V1(1, 32, V2), + V0(0, 0, V1); + + private static final BitArrayVersion[] VALUES = values(); final byte bits; final byte entriesPerWord; @@ -23,7 +27,7 @@ public enum BitArrayVersion { } public static BitArrayVersion get(int version, boolean read) { - for (BitArrayVersion ver : values()) { + for (BitArrayVersion ver : VALUES) { if ((!read && ver.entriesPerWord <= version) || (read && ver.bits == version)) { return ver; } @@ -31,7 +35,14 @@ public static BitArrayVersion get(int version, boolean read) { throw new IllegalArgumentException("Invalid palette version: " + version); } + public BitArray createPalette() { + return this.createPalette(4096); + } + public BitArray createPalette(int size) { + if (this == V0) { + return SingletonBitArray.INSTANCE; + } return this.createPalette(size, new int[this.getWordsForSize(size)]); } @@ -55,6 +66,8 @@ public BitArray createPalette(int size, int[] words) { if (this == V3 || this == V5 || this == V6) { // Padded palettes aren't able to use bitwise operations due to their padding. return new PaddedBitArray(this, size, words); + } else if (this == V0) { + return SingletonBitArray.INSTANCE; } else { return new Pow2BitArray(this, size, words); } diff --git a/src/main/java/cn/nukkit/level/util/PaddedBitArray.java b/src/main/java/cn/nukkit/level/util/PaddedBitArray.java index 20a9e53b8f5..b22735866a9 100644 --- a/src/main/java/cn/nukkit/level/util/PaddedBitArray.java +++ b/src/main/java/cn/nukkit/level/util/PaddedBitArray.java @@ -36,8 +36,10 @@ public class PaddedBitArray implements BitArray { @Override public void set(int index, int value) { Preconditions.checkElementIndex(index, this.size); - Preconditions.checkArgument(value >= 0 && value <= this.version.maxEntryValue, - "Max value: %s. Received value", this.version.maxEntryValue, value); + if (value < 0 || value > this.version.maxEntryValue) { + throw new IllegalArgumentException(String.format("Max value: %s. Received value %s", this.version.maxEntryValue, value)); + } + int arrayIndex = index / this.version.entriesPerWord; int offset = (index % this.version.entriesPerWord) * this.version.bits; diff --git a/src/main/java/cn/nukkit/level/util/PalettedBlockStorage.java b/src/main/java/cn/nukkit/level/util/PalettedBlockStorage.java index 2484d8db35a..f9a5ef6d336 100644 --- a/src/main/java/cn/nukkit/level/util/PalettedBlockStorage.java +++ b/src/main/java/cn/nukkit/level/util/PalettedBlockStorage.java @@ -1,12 +1,13 @@ package cn.nukkit.level.util; +import cn.nukkit.Server; import cn.nukkit.level.GlobalBlockPalette; import cn.nukkit.utils.BinaryStream; +import io.netty.buffer.ByteBuf; +import it.unimi.dsi.fastutil.ints.Int2IntFunction; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; -import java.util.function.IntConsumer; - public class PalettedBlockStorage { private static final int SIZE = 4096; @@ -19,7 +20,7 @@ public static PalettedBlockStorage createFromBlockPalette() { } public static PalettedBlockStorage createFromBlockPalette(BitArrayVersion version) { - int runtimeId = GlobalBlockPalette.getOrCreateRuntimeId(0); // Air is first + int runtimeId = GlobalBlockPalette.getOrCreateRuntimeId(0); return new PalettedBlockStorage(version, runtimeId); } @@ -31,6 +32,10 @@ public static PalettedBlockStorage createWithDefaultState(BitArrayVersion versio return new PalettedBlockStorage(version, defaultState); } + public static PalettedBlockStorage createFromBitArray(BitArray bitArray, IntList palette) { + return new PalettedBlockStorage(bitArray, palette); + } + private PalettedBlockStorage(BitArrayVersion version, int defaultState) { this.bitArray = version.createPalette(SIZE); this.palette = new IntArrayList(16); @@ -46,6 +51,10 @@ private int getPaletteHeader(BitArrayVersion version, boolean runtime) { return (version.getId() << 1) | (runtime ? 1 : 0); } + private static BitArrayVersion getVersionFromHeader(byte header) { + return BitArrayVersion.get(header >> 1, true); + } + private int getIndex(int x, int y, int z) { return (x << 8) | (z << 4) | y; } @@ -54,6 +63,11 @@ public void setBlock(int x, int y, int z, int runtimeId) { this.setBlock(this.getIndex(x, y, z), runtimeId); } + public int getBlock(int x, int y, int z) { + int index = this.getIndex(x, y, z); + return this.palette.getInt(this.bitArray.get(index)); + } + public void setBlock(int index, int runtimeId) { try { int id = this.idFor(runtimeId); @@ -63,19 +77,73 @@ public void setBlock(int index, int runtimeId) { } } + public void readFromStorage(ByteBuf buffer) { + BitArrayVersion version = getVersionFromHeader(buffer.readByte()); + this.palette.clear(); + int paletteSize = 1; + + if (version == BitArrayVersion.V0) { + this.bitArray = version.createPalette(SIZE, null); + } else { + int expectedWordCount = version.getWordsForSize(SIZE); + int[] words = new int[expectedWordCount]; + for (int i = 0; i < expectedWordCount; i++) { + words[i] = buffer.readIntLE(); + } + paletteSize = buffer.readIntLE(); + this.bitArray = version.createPalette(SIZE, words); + } + + if (!(version.getMaxEntryValue() >= paletteSize - 1)) { + throw new IllegalArgumentException(String.format("Palette (version " + version.name() + ") is too large. Max size %s. Actual size %s", version.getMaxEntryValue(), paletteSize)); + } + + for (int i = 0; i < paletteSize; i++) { + int id = buffer.readIntLE(); + this.palette.add(id); + if (id < 0) { + Server.getInstance().getLogger().warning("Negative biome ID " + id); + } + } + } + + public void writeToStorage(ByteBuf buffer) { + int paletteSize = this.palette.size(); + BitArrayVersion version = paletteSize <= 1 ? BitArrayVersion.V0 : this.bitArray.getVersion(); + buffer.writeByte(getPaletteHeader(version, false)); + + if (version != BitArrayVersion.V0) { + for (int word : this.bitArray.getWords()) { + buffer.writeIntLE(word); + } + buffer.writeIntLE(paletteSize); + } + + for (int runtimeId : this.palette) { + buffer.writeIntLE(runtimeId); + } + } + public void writeTo(BinaryStream stream) { - stream.putByte((byte) getPaletteHeader(bitArray.getVersion(), true)); + this.writeTo(stream, i -> i); + } - for (int word : bitArray.getWords()) { - stream.putLInt(word); + public void writeTo(BinaryStream stream, Int2IntFunction mapper) { + stream.putByte((byte) getPaletteHeader(this.bitArray.getVersion(), true)); + if (this.bitArray.getVersion() != BitArrayVersion.V0) { + for (int word : this.bitArray.getWords()) { + stream.putLInt(word); + } + stream.putVarInt(this.palette.size()); } - stream.putVarInt(palette.size()); - palette.forEach((IntConsumer) stream::putVarInt); + for (int runtimeId : this.palette) { + stream.putVarInt(mapper.get(runtimeId)); + } } private void onResize(BitArrayVersion version) { - BitArray newBitArray = version.createPalette(SIZE); + BitArray newBitArray = version.createPalette(); for (int i = 0; i < SIZE; i++) { newBitArray.set(i, this.bitArray.get(i)); diff --git a/src/main/java/cn/nukkit/level/util/Pow2BitArray.java b/src/main/java/cn/nukkit/level/util/Pow2BitArray.java index 6e2c1a02965..4c830953c0a 100644 --- a/src/main/java/cn/nukkit/level/util/Pow2BitArray.java +++ b/src/main/java/cn/nukkit/level/util/Pow2BitArray.java @@ -38,8 +38,10 @@ public class Pow2BitArray implements BitArray { */ public void set(int index, int value) { Preconditions.checkElementIndex(index, this.size); - Preconditions.checkArgument(value >= 0 && value <= this.version.maxEntryValue, - "Max value: %s. Received value", this.version.maxEntryValue, value); + if (value < 0 || value > this.version.maxEntryValue) { + throw new IllegalArgumentException(String.format("Max value: %s. Received value %s", this.version.maxEntryValue, value)); + } + int bitIndex = index * this.version.bits; int arrayIndex = bitIndex >> 5; int offset = bitIndex & 31; diff --git a/src/main/java/cn/nukkit/level/util/SingletonBitArray.java b/src/main/java/cn/nukkit/level/util/SingletonBitArray.java new file mode 100644 index 00000000000..7e35bade8ef --- /dev/null +++ b/src/main/java/cn/nukkit/level/util/SingletonBitArray.java @@ -0,0 +1,39 @@ +package cn.nukkit.level.util; + +public class SingletonBitArray implements BitArray { + public static final SingletonBitArray INSTANCE = new SingletonBitArray(); + + private static final int[] EMPTY_ARRAY = new int[0]; + + public SingletonBitArray() { + } + + @Override + public void set(int index, int value) { + } + + @Override + public int get(int index) { + return 0; + } + + @Override + public int size() { + return 1; + } + + @Override + public int[] getWords() { + return EMPTY_ARRAY; + } + + @Override + public BitArrayVersion getVersion() { + return BitArrayVersion.V0; + } + + @Override + public SingletonBitArray copy() { + return new SingletonBitArray(); + } +} diff --git a/src/main/java/cn/nukkit/math/Angle.java b/src/main/java/cn/nukkit/math/Angle.java index 549284a74ab..edd19d1e375 100644 --- a/src/main/java/cn/nukkit/math/Angle.java +++ b/src/main/java/cn/nukkit/math/Angle.java @@ -148,5 +148,4 @@ private Angle(double doubleValue, boolean isDegree) { this.doubleValue = doubleValue; this.isDegree = isDegree; } - } diff --git a/src/main/java/cn/nukkit/math/BlockFace.java b/src/main/java/cn/nukkit/math/BlockFace.java index a677ce5b734..6e57e690875 100644 --- a/src/main/java/cn/nukkit/math/BlockFace.java +++ b/src/main/java/cn/nukkit/math/BlockFace.java @@ -4,9 +4,11 @@ import java.util.Iterator; import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; import java.util.function.Predicate; public enum BlockFace { + DOWN(0, 1, -1, "down", AxisDirection.NEGATIVE, new Vector3(0, -1, 0)), UP(1, 0, -1, "up", AxisDirection.POSITIVE, new Vector3(0, 1, 0)), NORTH(2, 3, 2, "north", AxisDirection.NEGATIVE, new Vector3(0, 0, -1)), @@ -25,7 +27,6 @@ public enum BlockFace { private static final BlockFace[] HORIZONTALS = new BlockFace[4]; static { - //Circular dependency DOWN.axis = Axis.Y; UP.axis = Axis.Y; NORTH.axis = Axis.Z; @@ -36,7 +37,7 @@ public enum BlockFace { for (BlockFace face : values()) { VALUES[face.index] = face; - if (face.getAxis().isHorizontal()) { + if (face.axis.isHorizontal()) { HORIZONTALS[face.horizontalIndex] = face; } } @@ -112,12 +113,12 @@ public static BlockFace fromHorizontalAngle(double angle) { public static BlockFace fromAxis(AxisDirection axisDirection, Axis axis) { for (BlockFace face : VALUES) { - if (face.getAxisDirection() == axisDirection && face.getAxis() == axis) { + if (face.axisDirection == axisDirection && face.axis == axis) { return face; } } - throw new RuntimeException("Unable to get face from axis: " + axisDirection + " " + axis); + throw new RuntimeException("Unable to get face from axis: " + axisDirection + ' ' + axis); } /** @@ -214,25 +215,25 @@ public int getYOffset() { /** * Returns an offset that addresses the block in front of this BlockFace * - * @return x offset + * @return z offset */ public int getZOffset() { return axis == Axis.Z ? axisDirection.getOffset() : 0; } /** - * Get the opposite BlockFace (e.g. DOWN ==> UP) - * - * @return block face + * Get the opposite BlockFace (e.g. DOWN ==> UP) + * + * @return block face */ public BlockFace getOpposite() { return fromIndex(opposite); } /** - * Rotate this BlockFace around the Y axis clockwise (NORTH => EAST => SOUTH => WEST => NORTH) - * - * @return block face + * Rotate this BlockFace around the Y axis clockwise (NORTH => EAST => SOUTH => WEST => NORTH) + * + * @return block face */ public BlockFace rotateY() { switch (this) { @@ -250,9 +251,9 @@ public BlockFace rotateY() { } /** - * Rotate this BlockFace around the Y axis counter-clockwise (NORTH => WEST => SOUTH => EAST => NORTH) - * - * @return block face + * Rotate this BlockFace around the Y axis counter-clockwise (NORTH => WEST => SOUTH => EAST => NORTH) + * + * @return block face */ public BlockFace rotateYCCW() { switch (this) { @@ -282,7 +283,6 @@ public enum Axis implements Predicate { private Plane plane; static { - //Circular dependency X.plane = Plane.HORIZONTAL; Y.plane = Plane.VERTICAL; Z.plane = Plane.HORIZONTAL; @@ -343,17 +343,20 @@ public enum Plane implements Predicate, Iterable { VERTICAL; static { - //Circular dependency HORIZONTAL.faces = new BlockFace[]{NORTH, EAST, SOUTH, WEST}; VERTICAL.faces = new BlockFace[]{UP, DOWN}; } private BlockFace[] faces; - public BlockFace random(NukkitRandom rand) { //todo Default Random? + public BlockFace random(NukkitRandom rand) { return faces[rand.nextBoundedInt(faces.length)]; } + public BlockFace random() { + return faces[ThreadLocalRandom.current().nextInt(faces.length)]; + } + public boolean test(BlockFace face) { return face != null && face.getAxis().getPlane() == this; } diff --git a/src/main/java/cn/nukkit/math/BlockVector3.java b/src/main/java/cn/nukkit/math/BlockVector3.java index 696419bcf8f..fbe20f72c38 100644 --- a/src/main/java/cn/nukkit/math/BlockVector3.java +++ b/src/main/java/cn/nukkit/math/BlockVector3.java @@ -1,6 +1,7 @@ package cn.nukkit.math; public class BlockVector3 implements Cloneable { + public int x; public int y; public int z; @@ -93,7 +94,7 @@ public BlockVector3 add(int x, int y, int z) { } public BlockVector3 add(BlockVector3 x) { - return new BlockVector3(this.x + x.getX(), this.y + x.getY(), this.z + x.getZ()); + return new BlockVector3(this.x + x.x, this.y + x.y, this.z + x.z); } public BlockVector3 subtract() { @@ -113,7 +114,7 @@ public BlockVector3 subtract(int x, int y, int z) { } public BlockVector3 subtract(BlockVector3 x) { - return this.add(-x.getX(), -x.getY(), -x.getZ()); + return this.add(-x.x, -x.y, -x.z); } public BlockVector3 multiply(int number) { @@ -129,7 +130,7 @@ public BlockVector3 getSide(BlockFace face) { } public BlockVector3 getSide(BlockFace face, int step) { - return new BlockVector3(this.getX() + face.getXOffset() * step, this.getY() + face.getYOffset() * step, this.getZ() + face.getZOffset() * step); + return new BlockVector3(this.x + face.getXOffset() * step, this.y + face.getYOffset() * step, this.z + face.getZOffset() * step); } public BlockVector3 up() { @@ -220,7 +221,7 @@ public final int hashCode() { @Override public String toString() { - return "BlockPosition(level=" + ",x=" + this.x + ",y=" + this.y + ",z=" + this.z + ")"; + return "BlockVector3(level=" + ",x=" + this.x + ",y=" + this.y + ",z=" + this.z + ')'; } @Override diff --git a/src/main/java/cn/nukkit/math/MathHelper.java b/src/main/java/cn/nukkit/math/MathHelper.java index ae5f214186a..bb69aef37ec 100644 --- a/src/main/java/cn/nukkit/math/MathHelper.java +++ b/src/main/java/cn/nukkit/math/MathHelper.java @@ -3,6 +3,7 @@ import java.util.Random; public class MathHelper { + private static final float[] a = new float[65536]; static { @@ -99,4 +100,4 @@ public static double denormalizeClamp(double lowerBnd, double upperBnd, double s public static float denormalizeClamp(float lowerBnd, float upperBnd, float slide) { return slide < 0.0f ? lowerBnd : (slide > 1.0f ? upperBnd : lowerBnd + (upperBnd - lowerBnd) * slide); } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/math/NukkitMath.java b/src/main/java/cn/nukkit/math/NukkitMath.java index 2a00f4abbd7..197aa73618a 100644 --- a/src/main/java/cn/nukkit/math/NukkitMath.java +++ b/src/main/java/cn/nukkit/math/NukkitMath.java @@ -1,7 +1,7 @@ package cn.nukkit.math; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class NukkitMath { @@ -65,4 +65,7 @@ public static double getDirection(double diffX, double diffZ) { return Math.max(diffX, diffZ); } + public static double lerp(double a, double b, double t) { + return a + (b - a) * t; + } } diff --git a/src/main/java/cn/nukkit/math/NukkitRandom.java b/src/main/java/cn/nukkit/math/NukkitRandom.java index 82d906d9057..917f87668e5 100644 --- a/src/main/java/cn/nukkit/math/NukkitRandom.java +++ b/src/main/java/cn/nukkit/math/NukkitRandom.java @@ -5,10 +5,11 @@ import java.util.zip.CRC32; /** - * author: Angelic47 + * @author Angelic47 * Nukkit Project */ public class NukkitRandom { + protected long seed; public NukkitRandom() { @@ -75,4 +76,4 @@ public int nextRange(int start, int end) { public int nextBoundedInt(int bound) { return bound == 0 ? 0 : this.nextInt() % bound; } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/math/SimpleAxisAlignedBB.java b/src/main/java/cn/nukkit/math/SimpleAxisAlignedBB.java index 3bd41cc1d18..30b44a7145c 100644 --- a/src/main/java/cn/nukkit/math/SimpleAxisAlignedBB.java +++ b/src/main/java/cn/nukkit/math/SimpleAxisAlignedBB.java @@ -1,7 +1,7 @@ package cn.nukkit.math; /** - * auth||: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class SimpleAxisAlignedBB implements AxisAlignedBB { diff --git a/src/main/java/cn/nukkit/math/Vector2.java b/src/main/java/cn/nukkit/math/Vector2.java index f9e197911ee..29dece471b8 100644 --- a/src/main/java/cn/nukkit/math/Vector2.java +++ b/src/main/java/cn/nukkit/math/Vector2.java @@ -1,10 +1,11 @@ package cn.nukkit.math; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class Vector2 { + public final double x; public final double y; @@ -46,7 +47,7 @@ public Vector2 add(double x, double y) { } public Vector2 add(Vector2 x) { - return this.add(x.getX(), x.getY()); + return this.add(x.x, x.y); } public Vector2 subtract(double x) { @@ -58,7 +59,7 @@ public Vector2 subtract(double x, double y) { } public Vector2 subtract(Vector2 x) { - return this.add(-x.getX(), -x.getY()); + return this.add(-x.x, -x.y); } public Vector2 ceil() { @@ -94,7 +95,7 @@ public double distance(double x, double y) { } public double distance(Vector2 vector) { - return Math.sqrt(this.distanceSquared(vector.getX(), vector.getY())); + return Math.sqrt(this.distanceSquared(vector.x, vector.y)); } public double distanceSquared(double x) { @@ -106,7 +107,7 @@ public double distanceSquared(double x, double y) { } public double distanceSquared(Vector2 vector) { - return this.distanceSquared(vector.getX(), vector.getY()); + return this.distanceSquared(vector.x, vector.y); } public double length() { @@ -131,7 +132,6 @@ public double dot(Vector2 v) { @Override public String toString() { - return "Vector2(x=" + this.x + ",y=" + this.y + ")"; + return "Vector2(x=" + this.x + ",y=" + this.y + ')'; } - } \ No newline at end of file diff --git a/src/main/java/cn/nukkit/math/Vector2f.java b/src/main/java/cn/nukkit/math/Vector2f.java index c5d17175568..8f17de8892c 100644 --- a/src/main/java/cn/nukkit/math/Vector2f.java +++ b/src/main/java/cn/nukkit/math/Vector2f.java @@ -1,10 +1,11 @@ package cn.nukkit.math; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class Vector2f { + public final float x; public final float y; @@ -46,7 +47,7 @@ public Vector2f add(float x, float y) { } public Vector2f add(Vector2f x) { - return this.add(x.getX(), x.getY()); + return this.add(x.x, x.y); } public Vector2f subtract(float x) { @@ -58,7 +59,7 @@ public Vector2f subtract(float x, float y) { } public Vector2f subtract(Vector2f x) { - return this.add(-x.getX(), -x.getY()); + return this.add(-x.x, -x.y); } public Vector2f ceil() { @@ -94,7 +95,7 @@ public double distance(float x, float y) { } public double distance(Vector2f vector) { - return Math.sqrt(this.distanceSquared(vector.getX(), vector.getY())); + return Math.sqrt(this.distanceSquared(vector.x, vector.y)); } public double distanceSquared(float x) { @@ -106,7 +107,7 @@ public double distanceSquared(float x, float y) { } public double distanceSquared(Vector2f vector) { - return this.distanceSquared(vector.getX(), vector.getY()); + return this.distanceSquared(vector.x, vector.y); } public double length() { @@ -131,7 +132,6 @@ public float dot(Vector2f v) { @Override public String toString() { - return "Vector2(x=" + this.x + ",y=" + this.y + ")"; + return "Vector2f(x=" + this.x + ",y=" + this.y + ')'; } - } \ No newline at end of file diff --git a/src/main/java/cn/nukkit/math/Vector3.java b/src/main/java/cn/nukkit/math/Vector3.java index dc2ed4b8683..cbbc2ce908f 100644 --- a/src/main/java/cn/nukkit/math/Vector3.java +++ b/src/main/java/cn/nukkit/math/Vector3.java @@ -1,7 +1,7 @@ package cn.nukkit.math; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class Vector3 implements Cloneable { @@ -109,7 +109,7 @@ public Vector3 add(double x, double y, double z) { } public Vector3 add(Vector3 x) { - return new Vector3(this.x + x.getX(), this.y + x.getY(), this.z + x.getZ()); + return new Vector3(this.x + x.x, this.y + x.y, this.z + x.z); } public Vector3 subtract() { @@ -129,7 +129,7 @@ public Vector3 subtract(double x, double y, double z) { } public Vector3 subtract(Vector3 x) { - return this.add(-x.getX(), -x.getY(), -x.getZ()); + return this.add(-x.x, -x.y, -x.z); } public Vector3 multiply(double number) { @@ -161,7 +161,7 @@ public Vector3 getSide(BlockFace face) { } public Vector3 getSide(BlockFace face, int step) { - return new Vector3(this.getX() + face.getXOffset() * step, this.getY() + face.getYOffset() * step, this.getZ() + face.getZOffset() * step); + return new Vector3(this.x + face.getXOffset() * step, this.y + face.getYOffset() * step, this.z + face.getZOffset() * step); } // Get as a Vector3 for better performance. Do not override in Block! @@ -169,6 +169,11 @@ public Vector3 getSideVec(BlockFace face) { return new Vector3(this.getX() + face.getXOffset(), this.getY() + face.getYOffset(), this.getZ() + face.getZOffset()); } + // Get as a Vector3 for better performance. Do not override in Block! + public Vector3 getSideVec(BlockFace face, int step) { + return new Vector3(this.x + face.getXOffset() * step, this.y + face.getYOffset() * step, this.z + face.getZOffset() * step); + } + public Vector3 up() { return up(1); } @@ -378,7 +383,7 @@ public Vector3 setComponents(double x, double y, double z) { @Override public String toString() { - return "Vector3(x=" + this.x + ",y=" + this.y + ",z=" + this.z + ")"; + return "Vector3(x=" + this.x + ",y=" + this.y + ",z=" + this.z + ')'; } @Override diff --git a/src/main/java/cn/nukkit/math/Vector3f.java b/src/main/java/cn/nukkit/math/Vector3f.java index ce466ce673a..dff536eef81 100644 --- a/src/main/java/cn/nukkit/math/Vector3f.java +++ b/src/main/java/cn/nukkit/math/Vector3f.java @@ -1,6 +1,7 @@ package cn.nukkit.math; public class Vector3f implements Cloneable { + public static final int SIDE_DOWN = 0; public static final int SIDE_UP = 1; public static final int SIDE_NORTH = 2; @@ -102,7 +103,7 @@ public Vector3f add(float x, float y, float z) { } public Vector3f add(Vector3f x) { - return new Vector3f(this.x + x.getX(), this.y + x.getY(), this.z + x.getZ()); + return new Vector3f(this.x + x.x, this.y + x.y, this.z + x.z); } public Vector3f subtract() { @@ -122,7 +123,7 @@ public Vector3f subtract(float x, float y, float z) { } public Vector3f subtract(Vector3f x) { - return this.add(-x.getX(), -x.getY(), -x.getZ()); + return this.add(-x.x, -x.y, -x.z); } public Vector3f multiply(float number) { @@ -352,7 +353,7 @@ public Vector3f setComponents(float x, float y, float z) { @Override public String toString() { - return "Vector3(x=" + this.x + ",y=" + this.y + ",z=" + this.z + ")"; + return "Vector3f(x=" + this.x + ",y=" + this.y + ",z=" + this.z + ')'; } @Override diff --git a/src/main/java/cn/nukkit/math/VectorMath.java b/src/main/java/cn/nukkit/math/VectorMath.java index 9c3d5fe189b..6e8d873b977 100644 --- a/src/main/java/cn/nukkit/math/VectorMath.java +++ b/src/main/java/cn/nukkit/math/VectorMath.java @@ -1,7 +1,7 @@ package cn.nukkit.math; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @@ -10,5 +10,4 @@ public abstract class VectorMath { public static Vector2 getDirection2D(double azimuth) { return new Vector2(Math.cos(azimuth), Math.sin(azimuth)); } - } diff --git a/src/main/java/cn/nukkit/metadata/BlockMetadataStore.java b/src/main/java/cn/nukkit/metadata/BlockMetadataStore.java index 92a6ac15a2b..8d19484b6a3 100644 --- a/src/main/java/cn/nukkit/metadata/BlockMetadataStore.java +++ b/src/main/java/cn/nukkit/metadata/BlockMetadataStore.java @@ -7,10 +7,11 @@ import java.util.List; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BlockMetadataStore extends MetadataStore { + private final Level owningLevel; public BlockMetadataStore(Level owningLevel) { @@ -22,7 +23,7 @@ protected String disambiguate(Metadatable block, String metadataKey) { if (!(block instanceof Block)) { throw new IllegalArgumentException("Argument must be a Block instance"); } - return ((Block) block).x + ":" + ((Block) block).y + ":" + ((Block) block).z + ":" + metadataKey; + return ((Block) block).x + ":" + ((Block) block).y + ':' + ((Block) block).z + ':' + metadataKey; } @Override diff --git a/src/main/java/cn/nukkit/metadata/EntityMetadataStore.java b/src/main/java/cn/nukkit/metadata/EntityMetadataStore.java index c51f7d31eb8..6102a9d3d47 100644 --- a/src/main/java/cn/nukkit/metadata/EntityMetadataStore.java +++ b/src/main/java/cn/nukkit/metadata/EntityMetadataStore.java @@ -3,7 +3,7 @@ import cn.nukkit.entity.Entity; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class EntityMetadataStore extends MetadataStore { diff --git a/src/main/java/cn/nukkit/metadata/LevelMetadataStore.java b/src/main/java/cn/nukkit/metadata/LevelMetadataStore.java index d45b3cd4d6e..74569d53390 100644 --- a/src/main/java/cn/nukkit/metadata/LevelMetadataStore.java +++ b/src/main/java/cn/nukkit/metadata/LevelMetadataStore.java @@ -3,7 +3,7 @@ import cn.nukkit.level.Level; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class LevelMetadataStore extends MetadataStore { @@ -13,6 +13,6 @@ protected String disambiguate(Metadatable level, String metadataKey) { if (!(level instanceof Level)) { throw new IllegalArgumentException("Argument must be a Level instance"); } - return (((Level) level).getName() + ":" + metadataKey).toLowerCase(); + return (((Level) level).getName() + ':' + metadataKey).toLowerCase(); } } diff --git a/src/main/java/cn/nukkit/metadata/MetadataStore.java b/src/main/java/cn/nukkit/metadata/MetadataStore.java index 18680a1e735..5eb412195fe 100644 --- a/src/main/java/cn/nukkit/metadata/MetadataStore.java +++ b/src/main/java/cn/nukkit/metadata/MetadataStore.java @@ -7,7 +7,7 @@ import java.util.*; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class MetadataStore { diff --git a/src/main/java/cn/nukkit/metadata/MetadataValue.java b/src/main/java/cn/nukkit/metadata/MetadataValue.java index 58ac519c244..7bf3df4f98b 100644 --- a/src/main/java/cn/nukkit/metadata/MetadataValue.java +++ b/src/main/java/cn/nukkit/metadata/MetadataValue.java @@ -5,7 +5,7 @@ import java.lang.ref.WeakReference; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class MetadataValue { @@ -23,5 +23,4 @@ public Plugin getOwningPlugin() { public abstract Object value(); public abstract void invalidate(); - } diff --git a/src/main/java/cn/nukkit/metadata/Metadatable.java b/src/main/java/cn/nukkit/metadata/Metadatable.java index e517c1796e0..63165c97c45 100644 --- a/src/main/java/cn/nukkit/metadata/Metadatable.java +++ b/src/main/java/cn/nukkit/metadata/Metadatable.java @@ -5,7 +5,7 @@ import java.util.List; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface Metadatable { diff --git a/src/main/java/cn/nukkit/metadata/PlayerMetadataStore.java b/src/main/java/cn/nukkit/metadata/PlayerMetadataStore.java index b9e53959914..c2933ee0af3 100644 --- a/src/main/java/cn/nukkit/metadata/PlayerMetadataStore.java +++ b/src/main/java/cn/nukkit/metadata/PlayerMetadataStore.java @@ -3,7 +3,7 @@ import cn.nukkit.IPlayer; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class PlayerMetadataStore extends MetadataStore { @@ -13,6 +13,6 @@ protected String disambiguate(Metadatable player, String metadataKey) { if (!(player instanceof IPlayer)) { throw new IllegalArgumentException("Argument must be an IPlayer instance"); } - return (((IPlayer) player).getName() + ":" + metadataKey).toLowerCase(); + return (((IPlayer) player).getName() + ':' + metadataKey).toLowerCase(); } } diff --git a/src/main/java/cn/nukkit/metrics/Metrics.java b/src/main/java/cn/nukkit/metrics/Metrics.java index bc710e18ff8..73eab0a8cbf 100644 --- a/src/main/java/cn/nukkit/metrics/Metrics.java +++ b/src/main/java/cn/nukkit/metrics/Metrics.java @@ -20,10 +20,11 @@ /** * bStats collects some data for plugin authors. - * - * Check out https://bStats.org/ to learn more about bStats! + *

+ * Check out ... to learn more about bStats! */ public class Metrics { + public static final int B_STATS_VERSION = 1; private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); @@ -529,5 +530,4 @@ protected JSONObject getChartData() throws Exception { } } - } \ No newline at end of file diff --git a/src/main/java/cn/nukkit/metrics/NukkitMetrics.java b/src/main/java/cn/nukkit/metrics/NukkitMetrics.java index c67ac240f5e..4428b13d31e 100644 --- a/src/main/java/cn/nukkit/metrics/NukkitMetrics.java +++ b/src/main/java/cn/nukkit/metrics/NukkitMetrics.java @@ -2,6 +2,7 @@ import cn.nukkit.Server; import cn.nukkit.utils.Config; +import cn.nukkit.utils.Utils; import java.io.BufferedWriter; import java.io.File; @@ -14,6 +15,7 @@ import java.util.regex.Pattern; public class NukkitMetrics { + private static boolean metricsStarted = false; private final Server server; @@ -31,8 +33,8 @@ public NukkitMetrics(Server server) { try { this.loadConfig(); - } catch (IOException e) { - e.printStackTrace(); + } catch (IOException ex) { + server.getLogger().logException(ex); } if (enabled) { @@ -42,13 +44,13 @@ public NukkitMetrics(Server server) { metrics.addCustomChart(new Metrics.SimplePie("codename", server::getCodename)); metrics.addCustomChart(new Metrics.SimplePie("minecraft_version", server::getVersion)); metrics.addCustomChart(new Metrics.SimplePie("nukkit_version", server::getNukkitVersion)); - metrics.addCustomChart(new Metrics.SimplePie("xbox_auth", () -> server.getPropertyBoolean("xbox-auth") ? "Required" : "Not required")); + metrics.addCustomChart(new Metrics.SimplePie("xbox_auth", () -> server.xboxAuth ? "Required" : "Not required")); metrics.addCustomChart(new Metrics.AdvancedPie("player_platform", () -> { Map valueMap = new HashMap<>(); server.getOnlinePlayers().forEach((uuid, player) -> { - String deviceOS = mapDeviceOSToString(player.getLoginChainData().getDeviceOS()); + String deviceOS = Utils.getOS(player); if (!valueMap.containsKey(deviceOS)) { valueMap.put(deviceOS, 1); } else { @@ -147,25 +149,4 @@ private void writeFile(File file, String... lines) throws IOException { } } } - - private String mapDeviceOSToString(int os) { - switch (os) { - case 1: return "Android"; - case 2: return "iOS"; - case 3: return "macOS"; - case 4: return "Fire OS"; - case 5: return "Gear VR"; - case 6: return "HoloLens"; - case 7: return "Windows 10"; - case 8: return "Windows"; - case 9: return "Dedicated"; - case 10: return "tvOS"; - case 11: return "PlayStation"; - case 12: return "Switch"; - case 13: return "Xbox"; - case 14: return "Windows Phone"; - case 15: return "Linux"; - } - return "Unknown"; - } } diff --git a/src/main/java/cn/nukkit/nbt/NBTIO.java b/src/main/java/cn/nukkit/nbt/NBTIO.java index 5ce1b2f3795..c602c60a2d9 100644 --- a/src/main/java/cn/nukkit/nbt/NBTIO.java +++ b/src/main/java/cn/nukkit/nbt/NBTIO.java @@ -1,6 +1,8 @@ package cn.nukkit.nbt; import cn.nukkit.item.Item; +import cn.nukkit.item.RuntimeItemMapping; +import cn.nukkit.item.RuntimeItems; import cn.nukkit.nbt.stream.FastByteArrayOutputStream; import cn.nukkit.nbt.stream.NBTInputStream; import cn.nukkit.nbt.stream.NBTOutputStream; @@ -43,26 +45,50 @@ public static CompoundTag putItemHelper(Item item, Integer slot) { return tag; } + public static CompoundTag putNetworkItemHelper(Item item) { + CompoundTag tag = new CompoundTag(null) + .putString("Name", RuntimeItems.getMapping().toRuntime(item.getId(), item.getDamage()).getIdentifier()) + .putByte("Count", item.getCount()) + .putShort("Damage", item.getDamage()); + + if (item.hasCompoundTag()) { + tag.putCompound("tag", item.getNamedTag()); + } + + return tag; + } + public static Item getItemHelper(CompoundTag tag) { - if (!tag.contains("id") || !tag.contains("Count")) { + if (!tag.contains("Count")) { return Item.get(0); } - Item item; - try { - item = Item.get(tag.getShort("id"), !tag.contains("Damage") ? 0 : tag.getShort("Damage"), tag.getByte("Count")); - } catch (Exception e) { - item = Item.fromString(tag.getString("id")); - item.setDamage(!tag.contains("Damage") ? 0 : tag.getShort("Damage")); - item.setCount(tag.getByte("Count")); + // Nukkit format + if (tag.contains("id")) { + return Item.get( + tag.getShort("id"), + tag.getShort("Damage"), + tag.getByte("Count"), + tag.get("tag") + ); } - Tag tagTag = tag.get("tag"); - if (tagTag instanceof CompoundTag) { - item.setNamedTag((CompoundTag) tagTag); + // Vanilla format (current version only) + if (tag.contains("Name")) { + RuntimeItemMapping.LegacyEntry legacy = RuntimeItems.getMapping().fromIdentifier(tag.getString("Name")); + if (legacy == null) { + return Item.get(0); + } + + return Item.get( + legacy.getLegacyId(), + legacy.isHasDamage() ? legacy.getDamage() : tag.getShort("Damage"), + tag.getByte("Count"), + tag.get("tag") + ); } - return item; + return Item.get(0); } public static CompoundTag read(File file) throws IOException { @@ -71,7 +97,7 @@ public static CompoundTag read(File file) throws IOException { public static CompoundTag read(File file, ByteOrder endianness) throws IOException { if (!file.exists()) return null; - return read(new FileInputStream(file), endianness); + return read(Files.newInputStream(file.toPath()), endianness); } public static CompoundTag read(InputStream inputStream) throws IOException { @@ -92,6 +118,12 @@ public static CompoundTag read(InputStream inputStream, ByteOrder endianness, bo } } + public static Tag readNetwork(InputStream inputStream) throws IOException { + try (NBTInputStream stream = new NBTInputStream(inputStream, ByteOrder.LITTLE_ENDIAN, true)) { + return Tag.readNamedTag(stream); + } + } + public static Tag readTag(InputStream inputStream, ByteOrder endianness, boolean network) throws IOException { try (NBTInputStream stream = new NBTInputStream(inputStream, endianness, network)) { return Tag.readNamedTag(stream); @@ -185,7 +217,7 @@ public static void write(CompoundTag tag, File file) throws IOException { } public static void write(CompoundTag tag, File file, ByteOrder endianness) throws IOException { - write(tag, new FileOutputStream(file), endianness); + write(tag, Files.newOutputStream(file.toPath()), endianness); } public static void write(CompoundTag tag, OutputStream outputStream) throws IOException { diff --git a/src/main/java/cn/nukkit/nbt/stream/BufferedRandomAccessFile.java b/src/main/java/cn/nukkit/nbt/stream/BufferedRandomAccessFile.java deleted file mode 100644 index 7959c4f94c0..00000000000 --- a/src/main/java/cn/nukkit/nbt/stream/BufferedRandomAccessFile.java +++ /dev/null @@ -1,467 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 - * - * http://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. - */ -package cn.nukkit.nbt.stream; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.util.Arrays; - - -/** - * A BufferedRandomAccessFile is like a - * RandomAccessFile, but it uses a private buffer so that most - * operations do not require a disk access. - *

- * - * Note: The operations on this class are unmonitored. Also, the correct - * functioning of the RandomAccessFile methods that are not - * overridden here relies on the implementation of those methods in the - * superclass. - * Author : Avinash Lakshman ( alakshman@facebook.com) & Prashant Malik ( pmalik@facebook.com ) - */ - -public class BufferedRandomAccessFile extends RandomAccessFile -{ - static final int LogBuffSz_ = 16; // 64K buffer - public static final int BuffSz_ = (1 << LogBuffSz_); - static final long BuffMask_ = -((long) BuffSz_); - - /* - * This implementation is based on the buffer implementation in Modula-3's - * "Rd", "Wr", "RdClass", and "WrClass" interfaces. - */ - private boolean dirty_; // true iff unflushed bytes exist - private boolean closed_; // true iff the file is closed - private long curr_; // current position in file - private long lo_, hi_; // bounds on characters in "buff" - private byte[] buff_; // local buffer - private long maxHi_; // this.lo + this.buff.length - private boolean hitEOF_; // buffer contains last file block? - private long diskPos_; // disk position - - /* - * To describe the above fields, we introduce the following abstractions for - * the file "f": - * - * len(f) the length of the file curr(f) the current position in the file - * c(f) the abstract contents of the file disk(f) the contents of f's - * backing disk file closed(f) true iff the file is closed - * - * "curr(f)" is an index in the closed interval [0, len(f)]. "c(f)" is a - * character sequence of length "len(f)". "c(f)" and "disk(f)" may differ if - * "c(f)" contains unflushed writes not reflected in "disk(f)". The flush - * operation has the effect of making "disk(f)" identical to "c(f)". - * - * A file is said to be *valid* if the following conditions hold: - * - * V1. The "closed" and "curr" fields are correct: - * - * f.closed == closed(f) f.curr == curr(f) - * - * V2. The current position is either contained in the buffer, or just past - * the buffer: - * - * f.lo <= f.curr <= f.hi - * - * V3. Any (possibly) unflushed characters are stored in "f.buff": - * - * (forall i in [f.lo, f.curr): c(f)[i] == f.buff[i - f.lo]) - * - * V4. For all characters not covered by V3, c(f) and disk(f) agree: - * - * (forall i in [f.lo, len(f)): i not in [f.lo, f.curr) => c(f)[i] == - * disk(f)[i]) - * - * V5. "f.dirty" is true iff the buffer contains bytes that should be - * flushed to the file; by V3 and V4, only part of the buffer can be dirty. - * - * f.dirty == (exists i in [f.lo, f.curr): c(f)[i] != f.buff[i - f.lo]) - * - * V6. this.maxHi == this.lo + this.buff.length - * - * Note that "f.buff" can be "null" in a valid file, since the range of - * characters in V3 is empty when "f.lo == f.curr". - * - * A file is said to be *ready* if the buffer contains the current position, - * i.e., when: - * - * R1. !f.closed && f.buff != null && f.lo <= f.curr && f.curr < f.hi - * - * When a file is ready, reading or writing a single byte can be performed - * by reading or writing the in-memory buffer without performing a disk - * operation. - */ - - /** - * Open a new BufferedRandomAccessFile on file - * in mode mode, which should be "r" for reading only, or - * "rw" for reading and writing. - */ - public BufferedRandomAccessFile(File file, String mode) throws IOException - { - super(file, mode); - this.init(0); - } - - public BufferedRandomAccessFile(File file, String mode, int size) throws IOException - { - super(file, mode); - this.init(size); - } - - /** - * Open a new BufferedRandomAccessFile on the file named - * name in mode mode, which should be "r" for - * reading only, or "rw" for reading and writing. - */ - public BufferedRandomAccessFile(String name, String mode) throws IOException - { - super(name, mode); - this.init(0); - } - - public BufferedRandomAccessFile(String name, String mode, int size) throws FileNotFoundException - { - super(name, mode); - this.init(size); - } - - private void init(int size) - { - this.dirty_ = this.closed_ = false; - this.lo_ = this.curr_ = this.hi_ = 0; - this.buff_ = (size > BuffSz_) ? new byte[size] : new byte[BuffSz_]; - this.maxHi_ = BuffSz_; - this.hitEOF_ = false; - this.diskPos_ = 0L; - } - - @Override - public void close() throws IOException - { - this.flush(); - this.closed_ = true; - super.close(); - } - - /** - * Flush any bytes in the file's buffer that have not yet been written to - * disk. If the file was created read-only, this method is a no-op. - */ - public void flush() throws IOException - { - this.flushBuffer(); - } - - /* Flush any dirty bytes in the buffer to disk. */ - private void flushBuffer() throws IOException - { - if (this.dirty_) - { - if (this.diskPos_ != this.lo_) - super.seek(this.lo_); - int len = (int) (this.curr_ - this.lo_); - super.write(this.buff_, 0, len); - this.diskPos_ = this.curr_; - this.dirty_ = false; - } - } - - /* - * Read at most "this.buff.length" bytes into "this.buff", returning the - * number of bytes read. If the return result is less than - * "this.buff.length", then EOF was read. - */ - private int fillBuffer() throws IOException - { - int cnt = 0; - int rem = this.buff_.length; - while (rem > 0) - { - int n = super.read(this.buff_, cnt, rem); - if (n < 0) - break; - cnt += n; - rem -= n; - } - if ( (cnt < 0) && (this.hitEOF_ = (cnt < this.buff_.length)) ) - { - // make sure buffer that wasn't read is initialized with -1 - Arrays.fill(this.buff_, cnt, this.buff_.length, (byte) 0xff); - } - this.diskPos_ += cnt; - return cnt; - } - - /* - * This method positions this.curr at position pos. - * If pos does not fall in the current buffer, it flushes the - * current buffer and loads the correct one.

- * - * On exit from this routine this.curr == this.hi iff pos - * is at or past the end-of-file, which can only happen if the file was - * opened in read-only mode. - */ - @Override - public void seek(long pos) throws IOException - { - if (pos >= this.hi_ || pos < this.lo_) - { - // seeking outside of current buffer -- flush and read - this.flushBuffer(); - this.lo_ = pos & BuffMask_; // start at BuffSz boundary - this.maxHi_ = this.lo_ + (long) this.buff_.length; - if (this.diskPos_ != this.lo_) - { - super.seek(this.lo_); - this.diskPos_ = this.lo_; - } - int n = this.fillBuffer(); - this.hi_ = this.lo_ + (long) n; - } - else - { - // seeking inside current buffer -- no read required - if (pos < this.curr_) - { - // if seeking backwards, we must flush to maintain V4 - this.flushBuffer(); - } - } - this.curr_ = pos; - } - - /* - * Does not maintain V4 (i.e. buffer differs from disk contents if previously written to) - * - Assumes no writes were made - * @param pos - * @throws IOException - */ - public void seekUnsafe(long pos) throws IOException - { - if (pos >= this.hi_ || pos < this.lo_) - { - // seeking outside of current buffer -- flush and read - this.flushBuffer(); - this.lo_ = pos & BuffMask_; // start at BuffSz boundary - this.maxHi_ = this.lo_ + (long) this.buff_.length; - if (this.diskPos_ != this.lo_) - { - super.seek(this.lo_); - this.diskPos_ = this.lo_; - } - int n = this.fillBuffer(); - this.hi_ = this.lo_ + (long) n; - } - this.curr_ = pos; - } - - @Override - public long getFilePointer() - { - return this.curr_; - } - - @Override - public long length() throws IOException - { - return Math.max(this.curr_, super.length()); - } - - @Override - public int read() throws IOException - { - if (this.curr_ >= this.hi_) - { - // test for EOF - // if (this.hi < this.maxHi) return -1; - if (this.hitEOF_) - return -1; - - // slow path -- read another buffer - this.seek(this.curr_); - if (this.curr_ == this.hi_) - return -1; - } - byte res = this.buff_[(int) (this.curr_ - this.lo_)]; - this.curr_++; - return ((int) res) & 0xFF; // convert byte -> int - } - - public byte read1() throws IOException { - if (this.curr_ >= this.hi_) - { - // test for EOF - // if (this.hi < this.maxHi) return -1; - if (this.hitEOF_) - return -1; - - // slow path -- read another buffer - this.seek(this.curr_); - if (this.curr_ == this.hi_) - return -1; - } - byte res = this.buff_[(int) (this.curr_++ - this.lo_)]; - return res; - } - - @Override - public int read(byte[] b) throws IOException - { - return this.read(b, 0, b.length); - } - - @Override - public int read(byte[] b, int off, int len) throws IOException - { - if (this.curr_ >= this.hi_) - { - // test for EOF - // if (this.hi < this.maxHi) return -1; - if (this.hitEOF_) - return -1; - - // slow path -- read another buffer - this.seek(this.curr_); - if (this.curr_ == this.hi_) - return -1; - } - len = Math.min(len, (int) (this.hi_ - this.curr_)); - int buffOff = (int) (this.curr_ - this.lo_); - System.arraycopy(this.buff_, buffOff, b, off, len); - this.curr_ += len; - return len; - } - - public byte readCurrent() throws IOException { - if (this.curr_ >= this.hi_) - { - // test for EOF - // if (this.hi < this.maxHi) return -1; - if (this.hitEOF_) - return -1; - - // slow path -- read another buffer - this.seek(this.curr_); - if (this.curr_ == this.hi_) - return -1; - } - byte res = this.buff_[(int) (this.curr_ - this.lo_)]; - return res; - } - - public void writeCurrent(byte b) throws IOException { - if (this.curr_ >= this.hi_) - { - if (this.hitEOF_ && this.hi_ < this.maxHi_) - { - // at EOF -- bump "hi" - this.hi_++; - } - else - { - // slow path -- write current buffer; read next one - this.seek(this.curr_); - if (this.curr_ == this.hi_) - { - // appending to EOF -- bump "hi" - this.hi_++; - } - } - } - this.buff_[(int) (this.curr_ - this.lo_)] = b; - this.dirty_ = true; - } - - @Override - public void write(int b) throws IOException - { - if (this.curr_ >= this.hi_) - { - if (this.hitEOF_ && this.hi_ < this.maxHi_) - { - // at EOF -- bump "hi" - this.hi_++; - } - else - { - // slow path -- write current buffer; read next one - this.seek(this.curr_); - if (this.curr_ == this.hi_) - { - // appending to EOF -- bump "hi" - this.hi_++; - } - } - } - this.buff_[(int) (this.curr_ - this.lo_)] = (byte) b; - this.curr_++; - this.dirty_ = true; - } - - @Override - public void write(byte[] b) throws IOException - { - this.write(b, 0, b.length); - } - - @Override - public void write(byte[] b, int off, int len) throws IOException - { - while (len > 0) - { - int n = this.writeAtMost(b, off, len); - off += n; - len -= n; - this.dirty_ = true; - } - } - - /* - * Write at most "len" bytes to "b" starting at position "off", and return - * the number of bytes written. - */ - private int writeAtMost(byte[] b, int off, int len) throws IOException - { - if (this.curr_ >= this.hi_) - { - if (this.hitEOF_ && this.hi_ < this.maxHi_) - { - // at EOF -- bump "hi" - this.hi_ = this.maxHi_; - } - else - { - // slow path -- write current buffer; read next one - this.seek(this.curr_); - if (this.curr_ == this.hi_) - { - // appending to EOF -- bump "hi" - this.hi_ = this.maxHi_; - } - } - } - len = Math.min(len, (int) (this.hi_ - this.curr_)); - int buffOff = (int) (this.curr_ - this.lo_); - System.arraycopy(b, off, this.buff_, buffOff, len); - this.curr_ += len; - return len; - } -} diff --git a/src/main/java/cn/nukkit/nbt/stream/FastByteArrayOutputStream.java b/src/main/java/cn/nukkit/nbt/stream/FastByteArrayOutputStream.java index 175ac8a7e09..501e89de519 100644 --- a/src/main/java/cn/nukkit/nbt/stream/FastByteArrayOutputStream.java +++ b/src/main/java/cn/nukkit/nbt/stream/FastByteArrayOutputStream.java @@ -83,24 +83,20 @@ public FastByteArrayOutputStream reset() { } public void write( final int b ) { - if ( position == length ) { - length++; - if ( position == array.length ) array = grow( array, length ); - } + if ( position >= array.length ) array = grow( array, position + 1, length ); array[ position++ ] = (byte)b; + if ( length < position ) length = position; } public static void ensureOffsetLength( final int arrayLength, final int offset, final int length ) { if ( offset < 0 ) throw new ArrayIndexOutOfBoundsException( "Offset (" + offset + ") is negative" ); if ( length < 0 ) throw new IllegalArgumentException( "Length (" + length + ") is negative" ); - if ( offset + length > arrayLength ) throw new ArrayIndexOutOfBoundsException( "Last index (" + ( offset + length ) + ") is greater than array length (" + arrayLength + ")" ); + if ( offset + length > arrayLength ) throw new ArrayIndexOutOfBoundsException( "Last index (" + ( offset + length ) + ") is greater than array length (" + arrayLength + ')'); } public static byte[] grow( final byte[] array, final int length ) { if ( length > array.length ) { - final int newLength = (int)Math.min( Math.max( ( ONEOVERPHI * array.length ) >>> 16, length ), Integer.MAX_VALUE ); - final byte[] t = - new byte[ newLength ]; + final byte[] t = new byte[(int) Math.min( Math.max( ( ONEOVERPHI * array.length ) >>> 16, length ), Integer.MAX_VALUE )]; System.arraycopy( array, 0, t, 0, array.length ); return t; } @@ -109,9 +105,7 @@ public static byte[] grow( final byte[] array, final int length ) { public static byte[] grow( final byte[] array, final int length, final int preserve ) { if ( length > array.length ) { - final int newLength = (int)Math.min( Math.max( ( ONEOVERPHI * array.length ) >>> 16, length ), Integer.MAX_VALUE ); - final byte[] t = - new byte[ newLength ]; + final byte[] t = new byte[(int) Math.min( Math.max( ( ONEOVERPHI * array.length ) >>> 16, length ), Integer.MAX_VALUE )]; System.arraycopy( array, 0, t, 0, preserve ); return t; } @@ -125,7 +119,7 @@ public void write( final byte[] b, final int off, final int len ) throws IOExcep } public void position( long newPosition ) { - if ( position > Integer.MAX_VALUE ) throw new IllegalArgumentException( "Position too large: " + newPosition ); + if ( newPosition > Integer.MAX_VALUE ) throw new IllegalArgumentException( "Position too large: " + newPosition ); position = (int)newPosition; } @@ -138,7 +132,6 @@ public long length() throws IOException { } public byte[] toByteArray() { - if (position == array.length) return array; return Arrays.copyOfRange(array, 0, position); } } \ No newline at end of file diff --git a/src/main/java/cn/nukkit/nbt/stream/NBTInputStream.java b/src/main/java/cn/nukkit/nbt/stream/NBTInputStream.java index 8382ecaf613..45a19616ada 100644 --- a/src/main/java/cn/nukkit/nbt/stream/NBTInputStream.java +++ b/src/main/java/cn/nukkit/nbt/stream/NBTInputStream.java @@ -10,10 +10,11 @@ import java.nio.charset.StandardCharsets; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class NBTInputStream implements DataInput, AutoCloseable { + private final DataInputStream stream; private final ByteOrder endianness; private final boolean network; @@ -149,6 +150,16 @@ public String readUTF() throws IOException { return new String(bytes, StandardCharsets.UTF_8); } + public String readUTF(int maxLen) throws IOException { + int length = network ? (int) VarInt.readUnsignedVarInt(stream) : this.readUnsignedShort(); + if (length > maxLen) { + throw new RuntimeException("Input too long!"); + } + byte[] bytes = new byte[length]; + this.stream.read(bytes); + return new String(bytes, StandardCharsets.UTF_8); + } + public int available() throws IOException { return this.stream.available(); } diff --git a/src/main/java/cn/nukkit/nbt/stream/NBTOutputStream.java b/src/main/java/cn/nukkit/nbt/stream/NBTOutputStream.java index 276dd733854..bc8846ab0ba 100644 --- a/src/main/java/cn/nukkit/nbt/stream/NBTOutputStream.java +++ b/src/main/java/cn/nukkit/nbt/stream/NBTOutputStream.java @@ -10,10 +10,11 @@ import java.nio.charset.StandardCharsets; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class NBTOutputStream implements DataOutput, AutoCloseable { + private final DataOutputStream stream; private final ByteOrder endianness; private final boolean network; diff --git a/src/main/java/cn/nukkit/nbt/stream/PGZIPBlock.java b/src/main/java/cn/nukkit/nbt/stream/PGZIPBlock.java index 1b9a15d141d..8be3372764b 100644 --- a/src/main/java/cn/nukkit/nbt/stream/PGZIPBlock.java +++ b/src/main/java/cn/nukkit/nbt/stream/PGZIPBlock.java @@ -3,6 +3,7 @@ import java.util.concurrent.Callable; public class PGZIPBlock implements Callable { + public PGZIPBlock(final PGZIPOutputStream parent) { STATE = new PGZIPThreadLocal(parent); } @@ -11,35 +12,24 @@ public PGZIPBlock(final PGZIPOutputStream parent) { * This ThreadLocal avoids the recycling of a lot of memory, causing lumpy performance. */ protected final ThreadLocal STATE; - public static final int SIZE = 64 * 1024; - // private final int index; + public static final int SIZE = 65536; // 64 * 1024 protected final byte[] in = new byte[SIZE]; protected int in_length = 0; - /* - public Block(@Nonnegative int index) { - this.index = index; - } - */ - // Only on worker thread @Override public byte[] call() throws Exception { - // LOG.info("Processing " + this + " on " + Thread.currentThread()); PGZIPState state = STATE.get(); - // ByteArrayOutputStream buf = new ByteArrayOutputStream(in.length); // Overestimate output size required. - // DeflaterOutputStream def = newDeflaterOutputStream(buf); state.def.reset(); state.buf.reset(); state.str.write(in, 0, in_length); state.str.flush(); - // return Arrays.copyOf(in, in_length); return state.buf.toByteArray(); } @Override public String toString() { - return "Block" /* + index */ + "(" + in_length + "/" + in.length + " bytes)"; + return "Block" + "(" + in_length + "/" + in.length + " bytes)"; } -} \ No newline at end of file +} diff --git a/src/main/java/cn/nukkit/nbt/stream/PGZIPOutputStream.java b/src/main/java/cn/nukkit/nbt/stream/PGZIPOutputStream.java index 99ee3d21ac9..15096b1741c 100644 --- a/src/main/java/cn/nukkit/nbt/stream/PGZIPOutputStream.java +++ b/src/main/java/cn/nukkit/nbt/stream/PGZIPOutputStream.java @@ -27,13 +27,9 @@ public static ExecutorService getSharedThreadPool() { return EXECUTOR; } - - // private static final Logger LOG = LoggerFactory.getLogger(PGZIPOutputStream.class); private final static int GZIP_MAGIC = 0x8b1f; - // todo: remove after block guessing is implemented - // array list that contains the block sizes - private IntList blockSizes = new IntArrayList(); + private final IntList blockSizes = new IntArrayList(); private int level = Deflater.BEST_SPEED; private int strategy = Deflater.DEFAULT_STRATEGY; @@ -56,7 +52,6 @@ protected static DeflaterOutputStream newDeflaterOutputStream(OutputStream out, return new DeflaterOutputStream(out, deflater, 512, true); } - // TODO: Share, daemonize. private final ExecutorService executor; private final int nthreads; private final CRC32 crc = new CRC32(); @@ -187,7 +182,6 @@ private void tryEmit() throws IOException, InterruptedException, ExecutionExcept private void emitUntil(int taskCountAllowed) throws IOException { try { while (emitQueue.size() > taskCountAllowed) { - // LOG.info("Waiting for taskCount=" + emitQueue.size() + " -> " + taskCountAllowed); Future future = emitQueue.remove(); // Valid because emitQueue.size() > 0 byte[] toWrite = future.get(); // Blocks until this task is done. blockSizes.add(toWrite.length); // todo: remove after block guessing is implemented @@ -206,7 +200,6 @@ private void emitUntil(int taskCountAllowed) throws IOException { // Master thread only @Override public void flush() throws IOException { - // LOG.info("Flush: " + block); if (block.in_length > 0) submit(); emitUntil(0); @@ -216,7 +209,6 @@ public void flush() throws IOException { // Master thread only @Override public void close() throws IOException { - // LOG.info("Closing: bytesWritten=" + bytesWritten); if (bytesWritten >= 0) { flush(); @@ -224,18 +216,14 @@ public void close() throws IOException { ByteBuffer buf = ByteBuffer.allocate(8); buf.order(ByteOrder.LITTLE_ENDIAN); - // LOG.info("CRC is " + crc.getValue()); buf.putInt((int) crc.getValue()); buf.putInt(bytesWritten); - out.write(buf.array()); // allocate() guarantees a backing array. - // LOG.info("trailer is " + Arrays.toString(buf.array())); + out.write(buf.array()); out.flush(); out.close(); bytesWritten = Integer.MIN_VALUE; - // } else { - // LOG.warn("Already closed."); } } -} \ No newline at end of file +} diff --git a/src/main/java/cn/nukkit/nbt/stream/PGZIPState.java b/src/main/java/cn/nukkit/nbt/stream/PGZIPState.java index f075f49f833..f98be44bb95 100644 --- a/src/main/java/cn/nukkit/nbt/stream/PGZIPState.java +++ b/src/main/java/cn/nukkit/nbt/stream/PGZIPState.java @@ -5,6 +5,7 @@ import java.util.zip.DeflaterOutputStream; public class PGZIPState { + protected final DeflaterOutputStream str; protected final ByteArrayOutputStream buf; protected final Deflater def; @@ -14,6 +15,4 @@ public PGZIPState(PGZIPOutputStream parent) { this.buf = new ByteArrayOutputStream(PGZIPBlock.SIZE); this.str = PGZIPOutputStream.newDeflaterOutputStream(buf, def); } - - } diff --git a/src/main/java/cn/nukkit/nbt/tag/ByteArrayTag.java b/src/main/java/cn/nukkit/nbt/tag/ByteArrayTag.java index b0e809477b5..762bdbfb587 100644 --- a/src/main/java/cn/nukkit/nbt/tag/ByteArrayTag.java +++ b/src/main/java/cn/nukkit/nbt/tag/ByteArrayTag.java @@ -8,6 +8,7 @@ import java.util.Arrays; public class ByteArrayTag extends Tag { + public byte[] data; public ByteArrayTag(String name) { @@ -30,7 +31,7 @@ void write(NBTOutputStream dos) throws IOException { } @Override - void load(NBTInputStream dis) throws IOException { + public void load(NBTInputStream dis) throws IOException { int length = dis.readInt(); data = new byte[length]; dis.readFully(data); diff --git a/src/main/java/cn/nukkit/nbt/tag/ByteTag.java b/src/main/java/cn/nukkit/nbt/tag/ByteTag.java index 8678d52fd4c..2105ab5183c 100644 --- a/src/main/java/cn/nukkit/nbt/tag/ByteTag.java +++ b/src/main/java/cn/nukkit/nbt/tag/ByteTag.java @@ -6,6 +6,7 @@ import java.io.IOException; public class ByteTag extends NumberTag { + public int data; @Override @@ -33,7 +34,7 @@ void write(NBTOutputStream dos) throws IOException { } @Override - void load(NBTInputStream dis) throws IOException { + public void load(NBTInputStream dis) throws IOException { data = dis.readByte(); } @@ -51,9 +52,9 @@ public Integer parseValue() { public String toString() { String hex = Integer.toHexString(this.data); if (hex.length() < 2) { - hex = "0" + hex; + hex = '0' + hex; } - return "ByteTag " + this.getName() + " (data: 0x" + hex + ")"; + return "ByteTag " + this.getName() + " (data: 0x" + hex + ')'; } @Override diff --git a/src/main/java/cn/nukkit/nbt/tag/CompoundTag.java b/src/main/java/cn/nukkit/nbt/tag/CompoundTag.java index 10def9433b0..8e4cfacfd42 100644 --- a/src/main/java/cn/nukkit/nbt/tag/CompoundTag.java +++ b/src/main/java/cn/nukkit/nbt/tag/CompoundTag.java @@ -12,6 +12,7 @@ import java.util.StringJoiner; public class CompoundTag extends Tag implements Cloneable { + private final Map tags = new HashMap<>(); public CompoundTag() { @@ -23,8 +24,7 @@ public CompoundTag(String name) { } @Override - public void write(NBTOutputStream dos) throws IOException { - + void write(NBTOutputStream dos) throws IOException { for (Map.Entry entry : this.tags.entrySet()) { Tag.writeNamedTag(entry.getValue(), entry.getKey(), dos); } @@ -132,70 +132,86 @@ public T removeAndGet(String name) { return (T) tags.remove(name); } - public int getByte(String name) { - if (!tags.containsKey(name)) return (byte) 0; - return ((NumberTag) tags.get(name)).getData().intValue(); + Tag t = tags.get(name); + if (t == null) return (byte) 0; + return ((NumberTag) t).getData().intValue(); } public int getShort(String name) { - if (!tags.containsKey(name)) return 0; - return ((NumberTag) tags.get(name)).getData().intValue(); + Tag t = tags.get(name); + if (t == null) return 0; + return ((NumberTag) t).getData().intValue(); } public int getInt(String name) { - if (!tags.containsKey(name)) return 0; - return ((NumberTag) tags.get(name)).getData().intValue(); + Tag t = tags.get(name); + if (t == null) return 0; + return ((NumberTag) t).getData().intValue(); } public long getLong(String name) { - if (!tags.containsKey(name)) return 0; - return ((NumberTag) tags.get(name)).getData().longValue(); + Tag t = tags.get(name); + if (t == null) return 0; + return ((NumberTag) t).getData().longValue(); } public float getFloat(String name) { - if (!tags.containsKey(name)) return (float) 0; - return ((NumberTag) tags.get(name)).getData().floatValue(); + Tag t = tags.get(name); + if (t == null) return 0f; + return ((NumberTag) t).getData().floatValue(); } public double getDouble(String name) { - if (!tags.containsKey(name)) return 0; - return ((NumberTag) tags.get(name)).getData().doubleValue(); + Tag t = tags.get(name); + if (t == null) return 0; + return ((NumberTag) t).getData().doubleValue(); } public String getString(String name) { - if (!tags.containsKey(name)) return ""; - Tag tag = tags.get(name); - if (tag instanceof NumberTag) { - return String.valueOf(((NumberTag) tag).getData()); + Tag t = tags.get(name); + if (t == null) return ""; + if (t instanceof NumberTag) { + return String.valueOf(((NumberTag) t).getData()); } - return ((StringTag) tag).data; + return ((StringTag) t).data; } public byte[] getByteArray(String name) { - if (!tags.containsKey(name)) return new byte[0]; - return ((ByteArrayTag) tags.get(name)).data; + Tag t = tags.get(name); + if (t == null) return new byte[0]; + return ((ByteArrayTag) t).data; + } + + public byte[] getByteArray(String name, int defaultSize) { + Tag t = tags.get(name); + if (t == null) return new byte[defaultSize]; + return ((ByteArrayTag) t).data; } public int[] getIntArray(String name) { - if (!tags.containsKey(name)) return new int[0]; - return ((IntArrayTag) tags.get(name)).data; + Tag t = tags.get(name); + if (t == null) return new int[0]; + return ((IntArrayTag) t).data; } public CompoundTag getCompound(String name) { - if (!tags.containsKey(name)) return new CompoundTag(name); - return (CompoundTag) tags.get(name); + Tag t = tags.get(name); + if (t == null) return new CompoundTag(name); + return (CompoundTag) t; } public ListTag getList(String name) { - if (!tags.containsKey(name)) return new ListTag<>(name); - return (ListTag) tags.get(name); + Tag t = tags.get(name); + if (t == null) return new ListTag<>(name); + return (ListTag) t; } @SuppressWarnings("unchecked") public ListTag getList(String name, Class type) { - if (tags.containsKey(name)) { - return (ListTag) tags.get(name); + Tag t = tags.get(name); + if (t != null) { + return (ListTag) t; } return new ListTag<>(name); } @@ -219,6 +235,12 @@ public boolean getBoolean(String name) { return getByte(name) != 0; } + public boolean getBoolean(String name, boolean def) { + Tag t = tags.get(name); + if (t == null) return def; + return (((NumberTag) t).getData().intValue()) != 0; + } + public String toString() { StringJoiner joiner = new StringJoiner(",\n\t"); tags.forEach((key, tag) -> joiner.add('\'' + key + "' : " + tag.toString().replace("\n", "\n\t"))); @@ -227,13 +249,13 @@ public String toString() { public void print(String prefix, PrintStream out) { super.print(prefix, out); - out.println(prefix + "{"); + out.println(prefix + '{'); String orgPrefix = prefix; prefix += " "; for (Tag tag : tags.values()) { tag.print(prefix, out); } - out.println(orgPrefix + "}"); + out.println(orgPrefix + '}'); } public boolean isEmpty() { @@ -242,8 +264,8 @@ public boolean isEmpty() { public CompoundTag copy() { CompoundTag tag = new CompoundTag(getName()); - for (String key : tags.keySet()) { - tag.put(key, tags.get(key).copy()); + for (Entry entry : tags.entrySet()) { + tag.put(entry.getKey(), entry.getValue().copy()); } return tag; } @@ -273,4 +295,4 @@ public CompoundTag clone() { this.getTags().forEach((key, value) -> nbt.put(key, value.copy())); return nbt; } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/nbt/tag/DoubleTag.java b/src/main/java/cn/nukkit/nbt/tag/DoubleTag.java index f594beaade4..aa83d87bced 100644 --- a/src/main/java/cn/nukkit/nbt/tag/DoubleTag.java +++ b/src/main/java/cn/nukkit/nbt/tag/DoubleTag.java @@ -6,6 +6,7 @@ import java.io.IOException; public class DoubleTag extends NumberTag { + public double data; @Override @@ -33,7 +34,7 @@ void write(NBTOutputStream dos) throws IOException { } @Override - void load(NBTInputStream dis) throws IOException { + public void load(NBTInputStream dis) throws IOException { data = dis.readDouble(); } @@ -49,7 +50,7 @@ public byte getId() { @Override public String toString() { - return "DoubleTag " + this.getName() + " (data: " + data + ")"; + return "DoubleTag " + this.getName() + " (data: " + data + ')'; } @Override @@ -65,5 +66,4 @@ public boolean equals(Object obj) { } return false; } - } diff --git a/src/main/java/cn/nukkit/nbt/tag/EndTag.java b/src/main/java/cn/nukkit/nbt/tag/EndTag.java index 8f4851a2dc9..9c5665e3939 100644 --- a/src/main/java/cn/nukkit/nbt/tag/EndTag.java +++ b/src/main/java/cn/nukkit/nbt/tag/EndTag.java @@ -12,7 +12,7 @@ public EndTag() { } @Override - void load(NBTInputStream dis) throws IOException { + public void load(NBTInputStream dis) throws IOException { } @Override diff --git a/src/main/java/cn/nukkit/nbt/tag/FloatTag.java b/src/main/java/cn/nukkit/nbt/tag/FloatTag.java index 795b04f1cad..cb52a9d7508 100644 --- a/src/main/java/cn/nukkit/nbt/tag/FloatTag.java +++ b/src/main/java/cn/nukkit/nbt/tag/FloatTag.java @@ -6,6 +6,7 @@ import java.io.IOException; public class FloatTag extends NumberTag { + public float data; @Override @@ -33,7 +34,7 @@ void write(NBTOutputStream dos) throws IOException { } @Override - void load(NBTInputStream dis) throws IOException { + public void load(NBTInputStream dis) throws IOException { data = dis.readFloat(); } @@ -49,7 +50,7 @@ public byte getId() { @Override public String toString() { - return "FloatTag " + this.getName() + " (data: " + data + ")"; + return "FloatTag " + this.getName() + " (data: " + data + ')'; } @Override @@ -65,5 +66,4 @@ public boolean equals(Object obj) { } return false; } - } diff --git a/src/main/java/cn/nukkit/nbt/tag/IntArrayTag.java b/src/main/java/cn/nukkit/nbt/tag/IntArrayTag.java index 23b99b90747..dce99f7c1ed 100644 --- a/src/main/java/cn/nukkit/nbt/tag/IntArrayTag.java +++ b/src/main/java/cn/nukkit/nbt/tag/IntArrayTag.java @@ -7,6 +7,7 @@ import java.util.Arrays; public class IntArrayTag extends Tag { + public int[] data; public IntArrayTag(String name) { @@ -27,7 +28,7 @@ void write(NBTOutputStream dos) throws IOException { } @Override - void load(NBTInputStream dis) throws IOException { + public void load(NBTInputStream dis) throws IOException { int length = dis.readInt(); data = new int[length]; for (int i = 0; i < length; i++) { diff --git a/src/main/java/cn/nukkit/nbt/tag/IntTag.java b/src/main/java/cn/nukkit/nbt/tag/IntTag.java index a4d21d20f64..d309322cc8d 100644 --- a/src/main/java/cn/nukkit/nbt/tag/IntTag.java +++ b/src/main/java/cn/nukkit/nbt/tag/IntTag.java @@ -6,6 +6,7 @@ import java.io.IOException; public class IntTag extends NumberTag { + public int data; @Override @@ -33,7 +34,7 @@ void write(NBTOutputStream dos) throws IOException { } @Override - void load(NBTInputStream dis) throws IOException { + public void load(NBTInputStream dis) throws IOException { data = dis.readInt(); } @@ -49,7 +50,7 @@ public byte getId() { @Override public String toString() { - return "IntTag " + this.getName() + "(data: " + data + ")"; + return "IntTag " + this.getName() + "(data: " + data + ')'; } @Override @@ -65,5 +66,4 @@ public boolean equals(Object obj) { } return false; } - } diff --git a/src/main/java/cn/nukkit/nbt/tag/ListTag.java b/src/main/java/cn/nukkit/nbt/tag/ListTag.java index 071db2c3431..073326cdd9b 100644 --- a/src/main/java/cn/nukkit/nbt/tag/ListTag.java +++ b/src/main/java/cn/nukkit/nbt/tag/ListTag.java @@ -26,7 +26,7 @@ public ListTag(String name) { @Override void write(NBTOutputStream dos) throws IOException { - if (list.size() > 0) type = list.get(0).getId(); + if (!list.isEmpty()) type = list.get(0).getId(); else type = 1; dos.writeByte(type); @@ -36,7 +36,7 @@ void write(NBTOutputStream dos) throws IOException { @Override @SuppressWarnings("unchecked") - void load(NBTInputStream dis) throws IOException { + public void load(NBTInputStream dis) throws IOException { type = dis.readByte(); int size = dis.readInt(); @@ -64,11 +64,11 @@ public String toString() { public void print(String prefix, PrintStream out) { super.print(prefix, out); - out.println(prefix + "{"); + out.println(prefix + '{'); String orgPrefix = prefix; prefix += " "; for (T aList : list) aList.print(prefix, out); - out.println(orgPrefix + "}"); + out.println(orgPrefix + '}'); } public ListTag add(T tag) { @@ -152,5 +152,4 @@ public boolean equals(Object obj) { } return false; } - } diff --git a/src/main/java/cn/nukkit/nbt/tag/LongTag.java b/src/main/java/cn/nukkit/nbt/tag/LongTag.java index a37df491729..6f37370a14b 100644 --- a/src/main/java/cn/nukkit/nbt/tag/LongTag.java +++ b/src/main/java/cn/nukkit/nbt/tag/LongTag.java @@ -6,6 +6,7 @@ import java.io.IOException; public class LongTag extends NumberTag { + public long data; @Override @@ -33,7 +34,7 @@ void write(NBTOutputStream dos) throws IOException { } @Override - void load(NBTInputStream dis) throws IOException { + public void load(NBTInputStream dis) throws IOException { data = dis.readLong(); } @@ -49,7 +50,7 @@ public byte getId() { @Override public String toString() { - return "LongTag " + this.getName() + " (data:" + data + ")"; + return "LongTag " + this.getName() + " (data:" + data + ')'; } @Override @@ -65,5 +66,4 @@ public boolean equals(Object obj) { } return false; } - } diff --git a/src/main/java/cn/nukkit/nbt/tag/NumberTag.java b/src/main/java/cn/nukkit/nbt/tag/NumberTag.java index 0e01650a4a9..6e91d2aea45 100644 --- a/src/main/java/cn/nukkit/nbt/tag/NumberTag.java +++ b/src/main/java/cn/nukkit/nbt/tag/NumberTag.java @@ -1,10 +1,11 @@ package cn.nukkit.nbt.tag; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class NumberTag extends Tag { + protected NumberTag(String name) { super(name); } diff --git a/src/main/java/cn/nukkit/nbt/tag/ShortTag.java b/src/main/java/cn/nukkit/nbt/tag/ShortTag.java index e6465316d63..a10ee20069c 100644 --- a/src/main/java/cn/nukkit/nbt/tag/ShortTag.java +++ b/src/main/java/cn/nukkit/nbt/tag/ShortTag.java @@ -6,6 +6,7 @@ import java.io.IOException; public class ShortTag extends NumberTag { + public int data; @Override @@ -33,7 +34,7 @@ void write(NBTOutputStream dos) throws IOException { } @Override - void load(NBTInputStream dis) throws IOException { + public void load(NBTInputStream dis) throws IOException { data = dis.readShort(); } @@ -49,7 +50,7 @@ public byte getId() { @Override public String toString() { - return "" + data; + return "ShortTag " + this.getName() + "(data: " + data + ')'; } @Override @@ -65,5 +66,4 @@ public boolean equals(Object obj) { } return false; } - } diff --git a/src/main/java/cn/nukkit/nbt/tag/StringTag.java b/src/main/java/cn/nukkit/nbt/tag/StringTag.java index 95094cc7685..7798406410e 100644 --- a/src/main/java/cn/nukkit/nbt/tag/StringTag.java +++ b/src/main/java/cn/nukkit/nbt/tag/StringTag.java @@ -6,6 +6,7 @@ import java.io.IOException; public class StringTag extends Tag { + public String data; public StringTag(String name) { @@ -24,7 +25,7 @@ void write(NBTOutputStream dos) throws IOException { } @Override - void load(NBTInputStream dis) throws IOException { + public void load(NBTInputStream dis) throws IOException { data = dis.readUTF(); } @@ -40,7 +41,7 @@ public byte getId() { @Override public String toString() { - return "StringTag " + this.getName() + " (data: " + data + ")"; + return "StringTag " + this.getName() + " (data: " + data + ')'; } @Override @@ -56,5 +57,4 @@ public boolean equals(Object obj) { } return false; } - } diff --git a/src/main/java/cn/nukkit/nbt/tag/Tag.java b/src/main/java/cn/nukkit/nbt/tag/Tag.java index 3b66e063b2b..7969bc74c55 100644 --- a/src/main/java/cn/nukkit/nbt/tag/Tag.java +++ b/src/main/java/cn/nukkit/nbt/tag/Tag.java @@ -7,6 +7,7 @@ import java.io.PrintStream; public abstract class Tag { + public static final byte TAG_End = 0; public static final byte TAG_Byte = 1; public static final byte TAG_Short = 2; @@ -56,7 +57,7 @@ public void print(String prefix, PrintStream out) { out.print(prefix); out.print(getTagName(getId())); - if (name.length() > 0) { + if (!name.isEmpty()) { out.print("(\"" + name + "\")"); } out.print(": "); @@ -81,7 +82,7 @@ public static Tag readNamedTag(NBTInputStream dis) throws IOException { byte type = dis.readByte(); if (type == 0) return new EndTag(); - String name = dis.readUTF(); + String name = dis.readUTF(1024); Tag tag = newTag(type, name); diff --git a/src/main/java/cn/nukkit/network/AdvancedSourceInterface.java b/src/main/java/cn/nukkit/network/AdvancedSourceInterface.java index 6a982696c63..240c2ea3dcb 100644 --- a/src/main/java/cn/nukkit/network/AdvancedSourceInterface.java +++ b/src/main/java/cn/nukkit/network/AdvancedSourceInterface.java @@ -6,7 +6,7 @@ import java.net.InetSocketAddress; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface AdvancedSourceInterface extends SourceInterface { diff --git a/src/main/java/cn/nukkit/network/BatchingHelper.java b/src/main/java/cn/nukkit/network/BatchingHelper.java new file mode 100644 index 00000000000..fb731ea4238 --- /dev/null +++ b/src/main/java/cn/nukkit/network/BatchingHelper.java @@ -0,0 +1,46 @@ +package cn.nukkit.network; + +import cn.nukkit.Player; +import cn.nukkit.Server; +import cn.nukkit.event.server.BatchPacketsEvent; +import cn.nukkit.network.protocol.DataPacket; +import com.google.common.util.concurrent.ThreadFactoryBuilder; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public class BatchingHelper { + + private final ExecutorService threadedExecutor; + + public BatchingHelper() { + ThreadFactoryBuilder builder = new ThreadFactoryBuilder(); + builder.setNameFormat("Batching Executor"); + builder.setUncaughtExceptionHandler((thread, ex) -> Server.getInstance().getLogger().error("Exception in " + thread.getName(), ex)); + this.threadedExecutor = Executors.newSingleThreadExecutor(builder.build()); + } + + public void batchPackets(Server server, Player[] players, DataPacket[] packets) { + if (players == null || packets == null || players.length == 0 || packets.length == 0) { + return; + } + + BatchPacketsEvent ev = new BatchPacketsEvent(players, packets, true); + server.getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + return; + } + + this.threadedExecutor.execute(() -> { // Maybe players could have separate threads assigned to them? + for (Player player : players) { + for (DataPacket packet : packets) { + player.getNetworkSession().sendPacket(packet); + } + } + }); + } + + public void shutdown() { + this.threadedExecutor.shutdownNow(); + } +} diff --git a/src/main/java/cn/nukkit/network/CompressBatchedPacket.java b/src/main/java/cn/nukkit/network/CompressBatchedPacket.java deleted file mode 100644 index bcf4f135e8f..00000000000 --- a/src/main/java/cn/nukkit/network/CompressBatchedPacket.java +++ /dev/null @@ -1,50 +0,0 @@ -package cn.nukkit.network; - -import cn.nukkit.Server; -import cn.nukkit.scheduler.AsyncTask; - -import java.net.InetSocketAddress; -import java.util.List; - -/** - * author: MagicDroidX - * Nukkit Project - */ -public class CompressBatchedPacket extends AsyncTask { - - public int level = 7; - public byte[] data; - public byte[] finalData; - public int channel = 0; - public List targets; - - public CompressBatchedPacket(byte[] data, List targets) { - this(data, targets, 7); - } - - public CompressBatchedPacket(byte[] data, List targets, int level) { - this(data, targets, level, 0); - } - - public CompressBatchedPacket(byte[] data, List targets, int level, int channel) { - this.data = data; - this.targets = targets; - this.level = level; - this.channel = channel; - } - - @Override - public void onRun() { - try { - this.finalData = Network.deflateRaw(data, level); - this.data = null; - } catch (Exception e) { - //ignore - } - } - - @Override - public void onCompletion(Server server) { - server.broadcastPacketsCallback(this.finalData, this.targets); - } -} diff --git a/src/main/java/cn/nukkit/network/CompressBatchedTask.java b/src/main/java/cn/nukkit/network/CompressBatchedTask.java deleted file mode 100644 index bd64ccd0579..00000000000 --- a/src/main/java/cn/nukkit/network/CompressBatchedTask.java +++ /dev/null @@ -1,50 +0,0 @@ -package cn.nukkit.network; - -import cn.nukkit.Server; -import cn.nukkit.scheduler.AsyncTask; - -import java.net.InetSocketAddress; -import java.util.List; - -/** - * author: MagicDroidX - * Nukkit Project - */ -public class CompressBatchedTask extends AsyncTask { - - public int level = 7; - public byte[][] data; - public byte[] finalData; - public int channel = 0; - public List targets; - - public CompressBatchedTask(byte[][] data, List targets) { - this(data, targets, 7); - } - - public CompressBatchedTask(byte[][] data, List targets, int level) { - this(data, targets, level, 0); - } - - public CompressBatchedTask(byte[][] data, List targets, int level, int channel) { - this.data = data; - this.targets = targets; - this.level = level; - this.channel = channel; - } - - @Override - public void onRun() { - try { - this.finalData = Network.deflateRaw(this.data, this.level); - this.data = null; - } catch (Exception e) { - //ignore - } - } - - @Override - public void onCompletion(Server server) { - server.broadcastPacketsCallback(this.finalData, this.targets); - } -} diff --git a/src/main/java/cn/nukkit/network/CompressionProvider.java b/src/main/java/cn/nukkit/network/CompressionProvider.java index a416d7c33de..e1131b8ce30 100644 --- a/src/main/java/cn/nukkit/network/CompressionProvider.java +++ b/src/main/java/cn/nukkit/network/CompressionProvider.java @@ -2,6 +2,8 @@ import cn.nukkit.network.protocol.types.PacketCompressionAlgorithm; import cn.nukkit.utils.BinaryStream; +import cn.nukkit.utils.SnappyCompression; +import cn.nukkit.utils.Zlib; public interface CompressionProvider { @@ -16,21 +18,31 @@ public byte[] decompress(byte[] compressed) throws Exception { return compressed; } + @Override + public byte[] decompress(byte[] compressed, int maxSize) throws Exception { + return compressed; + } + @Override public byte getPrefix() { return (byte) 0xff; } }; - CompressionProvider ZLIB = new CompressionProvider() { + CompressionProvider ZLIB_RAW = new CompressionProvider() { @Override public byte[] compress(BinaryStream packet, int level) throws Exception { - return Network.deflateRaw(packet.getBuffer(), level); + return Zlib.deflateRaw(packet.getBuffer(), level); } @Override public byte[] decompress(byte[] compressed) throws Exception { - return Network.inflateRaw(compressed); + return Zlib.inflateRaw(compressed, 6291456); + } + + @Override + public byte[] decompress(byte[] compressed, int maxSize) throws Exception { + return Zlib.inflateRaw(compressed, maxSize); } @Override @@ -39,15 +51,43 @@ public byte getPrefix() { } }; + CompressionProvider SNAPPY = new CompressionProvider() { + @Override + public byte[] compress(BinaryStream packet, int level) throws Exception { + return SnappyCompression.compress(packet.getBuffer()); + } + + @Override + public byte[] decompress(byte[] compressed) throws Exception { + return SnappyCompression.decompress(compressed, 6291456); + } + + @Override + public byte[] decompress(byte[] compressed, int maxSize) throws Exception { + return SnappyCompression.decompress(compressed, maxSize); + } + + @Override + public byte getPrefix() { + return (byte) 0x01; + } + }; + byte[] compress(BinaryStream packet, int level) throws Exception; byte[] decompress(byte[] compressed) throws Exception; + default byte[] decompress(byte[] compressed, int maxSize) throws Exception { + return this.decompress(compressed); + } + static CompressionProvider from(PacketCompressionAlgorithm algorithm) { if (algorithm == null) { return NONE; } else if (algorithm == PacketCompressionAlgorithm.ZLIB) { - return ZLIB; + return ZLIB_RAW; + } else if (algorithm == PacketCompressionAlgorithm.SNAPPY) { + return SNAPPY; } throw new UnsupportedOperationException(); } @@ -59,10 +99,12 @@ default byte getPrefix() { static CompressionProvider byPrefix(byte prefix) { switch (prefix) { case 0x00: - return ZLIB; + return ZLIB_RAW; + case 0x01: + return SNAPPY; case (byte) 0xff: return NONE; } - throw new IllegalArgumentException("Unsupported compression type: " + prefix); + throw new IllegalArgumentException("Unknown compression type: " + prefix); } } diff --git a/src/main/java/cn/nukkit/network/Network.java b/src/main/java/cn/nukkit/network/Network.java index 3fbfce0efaf..71e4b4506de 100644 --- a/src/main/java/cn/nukkit/network/Network.java +++ b/src/main/java/cn/nukkit/network/Network.java @@ -2,51 +2,29 @@ import cn.nukkit.Nukkit; import cn.nukkit.Server; -import cn.nukkit.nbt.stream.FastByteArrayOutputStream; import cn.nukkit.network.protocol.*; import cn.nukkit.utils.BinaryStream; -import cn.nukkit.utils.ThreadCache; import cn.nukkit.utils.Utils; import cn.nukkit.utils.VarInt; import io.netty.buffer.ByteBuf; -import io.netty.buffer.ByteBufUtil; -import io.netty.buffer.Unpooled; import lombok.extern.log4j.Log4j2; import java.io.ByteArrayInputStream; -import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ProtocolException; import java.util.Collection; import java.util.HashSet; import java.util.Set; -import java.util.zip.DataFormatException; -import java.util.zip.Deflater; -import java.util.zip.Inflater; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @Log4j2 +@SuppressWarnings("unchecked") public class Network { - private static final ThreadLocal INFLATER_RAW = ThreadLocal.withInitial(() -> new Inflater(true)); - private static final ThreadLocal DEFLATER_RAW = ThreadLocal.withInitial(() -> new Deflater(7, true)); - private static final ThreadLocal BUFFER = ThreadLocal.withInitial(() -> new byte[2 * 1024 * 1024]); - - - public static final byte CHANNEL_NONE = 0; - public static final byte CHANNEL_PRIORITY = 1; //Priority channel, only to be used when it matters - public static final byte CHANNEL_WORLD_CHUNKS = 2; //Chunk sending - public static final byte CHANNEL_MOVEMENT = 3; //Movement sending - public static final byte CHANNEL_BLOCKS = 4; //Block updates or explosions - public static final byte CHANNEL_WORLD_EVENTS = 5; //Entity, level or blockentity entity events - public static final byte CHANNEL_ENTITY_SPAWNING = 6; //Entity spawn/despawn channel - public static final byte CHANNEL_TEXT = 7; //Chat and other text stuff - public static final byte CHANNEL_END = 31; - private Class[] packetPool = new Class[256]; private final Server server; @@ -55,8 +33,8 @@ public class Network { private final Set advancedInterfaces = new HashSet<>(); - private double upload = 0; - private double download = 0; + private double upload; + private double download; private String name; private String subName; @@ -66,87 +44,23 @@ public Network(Server server) { this.server = server; } - public static byte[] inflateRaw(byte[] data) throws IOException, DataFormatException { - Inflater inflater = INFLATER_RAW.get(); - try { - inflater.setInput(data); - inflater.finished(); - - FastByteArrayOutputStream bos = ThreadCache.fbaos.get(); - bos.reset(); - byte[] buf = BUFFER.get(); - while (!inflater.finished()) { - int i = inflater.inflate(buf); - if (i == 0) { - throw new IOException("Could not decompress the data. Needs input: " + inflater.needsInput() + ", Needs Dictionary: " + inflater.needsDictionary()); - } - bos.write(buf, 0, i); - } - return bos.toByteArray(); - } finally { - inflater.reset(); - } - } - - public static byte[] deflateRaw(byte[] data, int level) throws IOException { - Deflater deflater = DEFLATER_RAW.get(); - try { - deflater.setLevel(data.length < Server.getInstance().networkCompressionThreshold ? 0 : level); - deflater.setInput(data); - deflater.finish(); - FastByteArrayOutputStream bos = ThreadCache.fbaos.get(); - bos.reset(); - byte[] buffer = BUFFER.get(); - while (!deflater.finished()) { - int i = deflater.deflate(buffer); - bos.write(buffer, 0, i); - } - - return bos.toByteArray(); - } finally { - deflater.reset(); - } - } - - public static byte[] deflateRaw(byte[][] datas, int level) throws IOException { - Deflater deflater = DEFLATER_RAW.get(); - try { - deflater.setLevel(level); - FastByteArrayOutputStream bos = ThreadCache.fbaos.get(); - bos.reset(); - byte[] buffer = BUFFER.get(); - - for (byte[] data : datas) { - deflater.setInput(data); - while (!deflater.needsInput()) { - int i = deflater.deflate(buffer); - bos.write(buffer, 0, i); - } - } - deflater.finish(); - while (!deflater.finished()) { - int i = deflater.deflate(buffer); - bos.write(buffer, 0, i); - } - return bos.toByteArray(); - } finally { - deflater.reset(); - } - } - + @Deprecated public void addStatistics(double upload, double download) { this.upload += upload; this.download += download; } + @Deprecated public double getUpload() { return upload; } + @Deprecated public double getDownload() { return download; } + @Deprecated public void resetStatistics() { this.upload = 0; this.download = 0; @@ -161,13 +75,9 @@ public void processInterfaces() { try { interfaz.process(); } catch (Exception e) { - if (Nukkit.DEBUG > 1) { - this.server.getLogger().logException(e); - } - interfaz.emergencyShutdown(); this.unregisterInterface(interfaz); - log.fatal(this.server.getLanguage().translateString("nukkit.server.networkError", new String[]{interfaz.getClass().getName(), Utils.getExceptionMessage(e)})); + log.fatal(this.server.getLanguage().translateString("nukkit.server.networkError", new String[]{interfaz.getClass().getName(), Utils.getExceptionMessage(e)}), e); } } } @@ -219,55 +129,44 @@ public Server getServer() { return server; } - public void processBatch(byte[] payload, Collection packets, CompressionProvider compression) { - byte[] data; - try { - data = compression.decompress(payload); - } catch (Exception e) { - log.debug("Exception while inflating batch packet", e); - return; - } + public void processBatch(byte[] payload, Collection packets, CompressionProvider compression) throws Exception { + byte[] data = compression.decompress(payload, 6291456); BinaryStream stream = new BinaryStream(data); - try { - int count = 0; - while (!stream.feof()) { - count++; - if (count >= 1000) { - throw new ProtocolException("Illegal batch with " + count + " packets"); - } - byte[] buf = stream.getByteArray(); - - ByteArrayInputStream bais = new ByteArrayInputStream(buf); - int header = (int) VarInt.readUnsignedVarInt(bais); - - // | Client ID | Sender ID | Packet ID | - // | 2 bits | 2 bits | 10 bits | - int packetId = header & 0x3ff; - - // Use internal backwards compatible IDs until pid() is rewritten - DataPacket pk = this.getPacket(packetId >= 300 ? packetId - 100 : packetId); - if (pk != null) { - pk.setBuffer(buf, buf.length - bais.available()); - try { - pk.decode(); - } catch (Exception e) { - if (log.isTraceEnabled()) { - log.trace("Dumping Packet\n{}", ByteBufUtil.prettyHexDump(Unpooled.wrappedBuffer(buf))); - } - log.error("Unable to decode packet", e); - throw new IllegalStateException("Unable to decode " + pk.getClass().getSimpleName()); - } - - packets.add(pk); - } else { - log.debug("Received unknown packet with vanilla ID 0x{}", Integer.toHexString(packetId)); + int count = 0; + while (!stream.feof()) { + count++; + if (count > 1300) { + throw new ProtocolException("Too big batch packet (count > 1300)"); + } + + byte[] buf = stream.getByteArray(); + ByteArrayInputStream bais = new ByteArrayInputStream(buf); + + int packetId = ((int) VarInt.readUnsignedVarInt(bais) & 0x3ff); + + // Use internal backwards compatible IDs until pid() is rewritten + DataPacket pk = this.getPacket(packetId >= 300 ? packetId - 100 : packetId); + if (pk == null) { + if (Nukkit.DEBUG > 1) { + log.debug("Received unknown packet with ID: 0x{}", Integer.toHexString(packetId)); } + continue; } - } catch (Exception e) { - if (log.isDebugEnabled()) { - log.debug("Error whilst decoding batch packet", e); + + pk.setBuffer(buf, buf.length - bais.available()); + + try { + pk.decode(); + + if (Nukkit.DEBUG > 1 && pk.offset < pk.getRawBuffer().length) { + log.debug(pk.getClass().getSimpleName() + " still has " + (pk.getRawBuffer().length - pk.offset) + " bytes to read!"); + } + } catch (Exception e) { + throw new IllegalStateException("Unable to decode " + pk.getClass().getSimpleName(), e); } + + packets.add(pk); } } @@ -310,122 +209,60 @@ public void unblockAddress(InetAddress address) { private void registerPackets() { this.packetPool = new Class[256]; - this.registerPacket(ProtocolInfo.ADD_ENTITY_PACKET, AddEntityPacket.class); - this.registerPacket(ProtocolInfo.ADD_ITEM_ENTITY_PACKET, AddItemEntityPacket.class); - this.registerPacket(ProtocolInfo.ADD_PAINTING_PACKET, AddPaintingPacket.class); - this.registerPacket(ProtocolInfo.ADD_PLAYER_PACKET, AddPlayerPacket.class); - this.registerPacket(ProtocolInfo.ADVENTURE_SETTINGS_PACKET, AdventureSettingsPacket.class); - this.registerPacket(ProtocolInfo.ANIMATE_PACKET, AnimatePacket.class); - this.registerPacket(ProtocolInfo.ANVIL_DAMAGE_PACKET, AnvilDamagePacket.class); - this.registerPacket(ProtocolInfo.AVAILABLE_COMMANDS_PACKET, AvailableCommandsPacket.class); this.registerPacket(ProtocolInfo.BATCH_PACKET, BatchPacket.class); + + this.registerPacket(ProtocolInfo.ANIMATE_PACKET, AnimatePacket.class); this.registerPacket(ProtocolInfo.BLOCK_ENTITY_DATA_PACKET, BlockEntityDataPacket.class); - this.registerPacket(ProtocolInfo.BLOCK_EVENT_PACKET, BlockEventPacket.class); this.registerPacket(ProtocolInfo.BLOCK_PICK_REQUEST_PACKET, BlockPickRequestPacket.class); this.registerPacket(ProtocolInfo.BOOK_EDIT_PACKET, BookEditPacket.class); - this.registerPacket(ProtocolInfo.BOSS_EVENT_PACKET, BossEventPacket.class); - this.registerPacket(ProtocolInfo.CHANGE_DIMENSION_PACKET, ChangeDimensionPacket.class); - this.registerPacket(ProtocolInfo.CHUNK_RADIUS_UPDATED_PACKET, ChunkRadiusUpdatedPacket.class); - this.registerPacket(ProtocolInfo.CLIENTBOUND_MAP_ITEM_DATA_PACKET, ClientboundMapItemDataPacket.class); this.registerPacket(ProtocolInfo.COMMAND_REQUEST_PACKET, CommandRequestPacket.class); this.registerPacket(ProtocolInfo.CONTAINER_CLOSE_PACKET, ContainerClosePacket.class); - this.registerPacket(ProtocolInfo.CONTAINER_OPEN_PACKET, ContainerOpenPacket.class); - this.registerPacket(ProtocolInfo.CONTAINER_SET_DATA_PACKET, ContainerSetDataPacket.class); - this.registerPacket(ProtocolInfo.CRAFTING_DATA_PACKET, CraftingDataPacket.class); - this.registerPacket(ProtocolInfo.CRAFTING_EVENT_PACKET, CraftingEventPacket.class); - this.registerPacket(ProtocolInfo.DISCONNECT_PACKET, DisconnectPacket.class); this.registerPacket(ProtocolInfo.ENTITY_EVENT_PACKET, EntityEventPacket.class); - this.registerPacket(ProtocolInfo.ENTITY_FALL_PACKET, EntityFallPacket.class); - this.registerPacket(ProtocolInfo.FULL_CHUNK_DATA_PACKET, LevelChunkPacket.class); - this.registerPacket(ProtocolInfo.GAME_RULES_CHANGED_PACKET, GameRulesChangedPacket.class); - this.registerPacket(ProtocolInfo.HURT_ARMOR_PACKET, HurtArmorPacket.class); this.registerPacket(ProtocolInfo.INTERACT_PACKET, InteractPacket.class); - this.registerPacket(ProtocolInfo.INVENTORY_CONTENT_PACKET, InventoryContentPacket.class); - this.registerPacket(ProtocolInfo.INVENTORY_SLOT_PACKET, InventorySlotPacket.class); this.registerPacket(ProtocolInfo.INVENTORY_TRANSACTION_PACKET, InventoryTransactionPacket.class); - this.registerPacket(ProtocolInfo.ITEM_FRAME_DROP_ITEM_PACKET, ItemFrameDropItemPacket.class); - this.registerPacket(ProtocolInfo.LEVEL_EVENT_PACKET, LevelEventPacket.class); - this.registerPacket(ProtocolInfo.LEVEL_SOUND_EVENT_PACKET_V1, LevelSoundEventPacketV1.class); this.registerPacket(ProtocolInfo.LOGIN_PACKET, LoginPacket.class); this.registerPacket(ProtocolInfo.MAP_INFO_REQUEST_PACKET, MapInfoRequestPacket.class); - this.registerPacket(ProtocolInfo.MOB_ARMOR_EQUIPMENT_PACKET, MobArmorEquipmentPacket.class); this.registerPacket(ProtocolInfo.MOB_EQUIPMENT_PACKET, MobEquipmentPacket.class); - this.registerPacket(ProtocolInfo.MODAL_FORM_REQUEST_PACKET, ModalFormRequestPacket.class); this.registerPacket(ProtocolInfo.MODAL_FORM_RESPONSE_PACKET, ModalFormResponsePacket.class); - this.registerPacket(ProtocolInfo.MOVE_ENTITY_ABSOLUTE_PACKET, MoveEntityAbsolutePacket.class); - this.registerPacket(ProtocolInfo.MOVE_PLAYER_PACKET, MovePlayerPacket.class); this.registerPacket(ProtocolInfo.PLAYER_ACTION_PACKET, PlayerActionPacket.class); this.registerPacket(ProtocolInfo.PLAYER_INPUT_PACKET, PlayerInputPacket.class); - this.registerPacket(ProtocolInfo.PLAYER_LIST_PACKET, PlayerListPacket.class); this.registerPacket(ProtocolInfo.PLAYER_HOTBAR_PACKET, PlayerHotbarPacket.class); - this.registerPacket(ProtocolInfo.PLAY_SOUND_PACKET, PlaySoundPacket.class); - this.registerPacket(ProtocolInfo.PLAY_STATUS_PACKET, PlayStatusPacket.class); - this.registerPacket(ProtocolInfo.REMOVE_ENTITY_PACKET, RemoveEntityPacket.class); this.registerPacket(ProtocolInfo.REQUEST_CHUNK_RADIUS_PACKET, RequestChunkRadiusPacket.class); - this.registerPacket(ProtocolInfo.RESOURCE_PACKS_INFO_PACKET, ResourcePacksInfoPacket.class); - this.registerPacket(ProtocolInfo.RESOURCE_PACK_STACK_PACKET, ResourcePackStackPacket.class); this.registerPacket(ProtocolInfo.RESOURCE_PACK_CLIENT_RESPONSE_PACKET, ResourcePackClientResponsePacket.class); - this.registerPacket(ProtocolInfo.RESOURCE_PACK_DATA_INFO_PACKET, ResourcePackDataInfoPacket.class); - this.registerPacket(ProtocolInfo.RESOURCE_PACK_CHUNK_DATA_PACKET, ResourcePackChunkDataPacket.class); this.registerPacket(ProtocolInfo.RESOURCE_PACK_CHUNK_REQUEST_PACKET, ResourcePackChunkRequestPacket.class); this.registerPacket(ProtocolInfo.PLAYER_SKIN_PACKET, PlayerSkinPacket.class); this.registerPacket(ProtocolInfo.RESPAWN_PACKET, RespawnPacket.class); - this.registerPacket(ProtocolInfo.RIDER_JUMP_PACKET, RiderJumpPacket.class); - this.registerPacket(ProtocolInfo.SET_COMMANDS_ENABLED_PACKET, SetCommandsEnabledPacket.class); this.registerPacket(ProtocolInfo.SET_DIFFICULTY_PACKET, SetDifficultyPacket.class); - this.registerPacket(ProtocolInfo.SET_ENTITY_DATA_PACKET, SetEntityDataPacket.class); - this.registerPacket(ProtocolInfo.SET_ENTITY_LINK_PACKET, SetEntityLinkPacket.class); - this.registerPacket(ProtocolInfo.SET_ENTITY_MOTION_PACKET, SetEntityMotionPacket.class); - this.registerPacket(ProtocolInfo.SET_HEALTH_PACKET, SetHealthPacket.class); this.registerPacket(ProtocolInfo.SET_PLAYER_GAME_TYPE_PACKET, SetPlayerGameTypePacket.class); - this.registerPacket(ProtocolInfo.SET_SPAWN_POSITION_PACKET, SetSpawnPositionPacket.class); - this.registerPacket(ProtocolInfo.SET_TITLE_PACKET, SetTitlePacket.class); - this.registerPacket(ProtocolInfo.SET_TIME_PACKET, SetTimePacket.class); this.registerPacket(ProtocolInfo.SERVER_SETTINGS_REQUEST_PACKET, ServerSettingsRequestPacket.class); - this.registerPacket(ProtocolInfo.SERVER_SETTINGS_RESPONSE_PACKET, ServerSettingsResponsePacket.class); - this.registerPacket(ProtocolInfo.SHOW_CREDITS_PACKET, ShowCreditsPacket.class); - this.registerPacket(ProtocolInfo.SPAWN_EXPERIENCE_ORB_PACKET, SpawnExperienceOrbPacket.class); - this.registerPacket(ProtocolInfo.START_GAME_PACKET, StartGamePacket.class); - this.registerPacket(ProtocolInfo.TAKE_ITEM_ENTITY_PACKET, TakeItemEntityPacket.class); this.registerPacket(ProtocolInfo.TEXT_PACKET, TextPacket.class); - this.registerPacket(ProtocolInfo.UPDATE_ATTRIBUTES_PACKET, UpdateAttributesPacket.class); - this.registerPacket(ProtocolInfo.UPDATE_BLOCK_PACKET, UpdateBlockPacket.class); - this.registerPacket(ProtocolInfo.UPDATE_TRADE_PACKET, UpdateTradePacket.class); - this.registerPacket(ProtocolInfo.MOVE_ENTITY_DELTA_PACKET, MoveEntityDeltaPacket.class); this.registerPacket(ProtocolInfo.SET_LOCAL_PLAYER_AS_INITIALIZED_PACKET, SetLocalPlayerAsInitializedPacket.class); - this.registerPacket(ProtocolInfo.NETWORK_STACK_LATENCY_PACKET, NetworkStackLatencyPacket.class); - this.registerPacket(ProtocolInfo.UPDATE_SOFT_ENUM_PACKET, UpdateSoftEnumPacket.class); - this.registerPacket(ProtocolInfo.NETWORK_CHUNK_PUBLISHER_UPDATE_PACKET, NetworkChunkPublisherUpdatePacket.class); - this.registerPacket(ProtocolInfo.AVAILABLE_ENTITY_IDENTIFIERS_PACKET, AvailableEntityIdentifiersPacket.class); - this.registerPacket(ProtocolInfo.LEVEL_SOUND_EVENT_PACKET_V2, LevelSoundEventPacket.class); - this.registerPacket(ProtocolInfo.SCRIPT_CUSTOM_EVENT_PACKET, ScriptCustomEventPacket.class); - this.registerPacket(ProtocolInfo.SPAWN_PARTICLE_EFFECT_PACKET, SpawnParticleEffectPacket.class); - this.registerPacket(ProtocolInfo.BIOME_DEFINITION_LIST_PACKET, BiomeDefinitionListPacket.class); - this.registerPacket(ProtocolInfo.LEVEL_SOUND_EVENT_PACKET, LevelSoundEventPacket.class); - this.registerPacket(ProtocolInfo.LEVEL_EVENT_GENERIC_PACKET, LevelEventGenericPacket.class); this.registerPacket(ProtocolInfo.LECTERN_UPDATE_PACKET, LecternUpdatePacket.class); - this.registerPacket(ProtocolInfo.VIDEO_STREAM_CONNECT_PACKET, VideoStreamConnectPacket.class); - this.registerPacket(ProtocolInfo.CLIENT_CACHE_STATUS_PACKET, ClientCacheStatusPacket.class); - this.registerPacket(ProtocolInfo.MAP_CREATE_LOCKED_COPY_PACKET, MapCreateLockedCopyPacket.class); - this.registerPacket(ProtocolInfo.EMOTE_PACKET, EmotePacket.class); - this.registerPacket(ProtocolInfo.ON_SCREEN_TEXTURE_ANIMATION_PACKET, OnScreenTextureAnimationPacket.class); - this.registerPacket(ProtocolInfo.COMPLETED_USING_ITEM_PACKET, CompletedUsingItemPacket.class); this.registerPacket(ProtocolInfo.NETWORK_SETTINGS_PACKET, NetworkSettingsPacket.class); - this.registerPacket(ProtocolInfo.CODE_BUILDER_PACKET, CodeBuilderPacket.class); this.registerPacket(ProtocolInfo.PLAYER_AUTH_INPUT_PACKET, PlayerAuthInputPacket.class); - this.registerPacket(ProtocolInfo.CREATIVE_CONTENT_PACKET, CreativeContentPacket.class); - this.registerPacket(ProtocolInfo.DEBUG_INFO_PACKET, DebugInfoPacket.class); - this.registerPacket(ProtocolInfo.EMOTE_LIST_PACKET, EmoteListPacket.class); this.registerPacket(ProtocolInfo.PACKET_VIOLATION_WARNING_PACKET, PacketViolationWarningPacket.class); - this.registerPacket(ProtocolInfo.PLAYER_ARMOR_DAMAGE_PACKET, PlayerArmorDamagePacket.class); - this.registerPacket(ProtocolInfo.PLAYER_ENCHANT_OPTIONS_PACKET, PlayerEnchantOptionsPacket.class); - this.registerPacket(ProtocolInfo.UPDATE_PLAYER_GAME_TYPE_PACKET, UpdatePlayerGameTypePacket.class); - this.registerPacket(ProtocolInfo.UPDATE_ABILITIES_PACKET, UpdateAbilitiesPacket.class); - this.registerPacket(ProtocolInfo.REQUEST_ABILITY_PACKET, RequestAbilityPacket.class); - this.registerPacket(ProtocolInfo.UPDATE_ADVENTURE_SETTINGS_PACKET, UpdateAdventureSettingsPacket.class); - this.registerPacket(ProtocolInfo.FILTER_TEXT_PACKET, FilterTextPacket.class); - this.registerPacket(ProtocolInfo.TOAST_REQUEST_PACKET, ToastRequestPacket.class); + this.registerPacket(ProtocolInfo.EMOTE_PACKET, EmotePacket.class); this.registerPacket(ProtocolInfo.REQUEST_NETWORK_SETTINGS_PACKET, RequestNetworkSettingsPacket.class); this.registerPacket(ProtocolInfo.CLIENT_TO_SERVER_HANDSHAKE_PACKET, ClientToServerHandshakePacket.class); + this.registerPacket(ProtocolInfo.REQUEST_PERMISSIONS_PACKET, RequestPermissionsPacket.class); + this.registerPacket(ProtocolInfo.SET_DEFAULT_GAME_TYPE_PACKET, SetDefaultGameTypePacket.class); + this.registerPacket(ProtocolInfo.SETTINGS_COMMAND_PACKET, SettingsCommandPacket.class); + + // Unused but sent by the client + this.registerPacket(ProtocolInfo.SET_ENTITY_LINK_PACKET, SetEntityLinkPacket.class); + this.registerPacket(ProtocolInfo.SET_ENTITY_MOTION_PACKET, SetEntityMotionPacket.class); + this.registerPacket(ProtocolInfo.LEVEL_SOUND_EVENT_PACKET, LevelSoundEventPacket.class); + this.registerPacket(ProtocolInfo.RIDER_JUMP_PACKET, RiderJumpPacket.class); + this.registerPacket(ProtocolInfo.REQUEST_ABILITY_PACKET, RequestAbilityPacket.class); + this.registerPacket(ProtocolInfo.NETWORK_STACK_LATENCY_PACKET, NetworkStackLatencyPacket.class); + this.registerPacket(ProtocolInfo.NPC_REQUEST_PACKET, NPCRequestPacket.class); + this.registerPacket(ProtocolInfo.MOVE_ENTITY_ABSOLUTE_PACKET, MoveEntityAbsolutePacket.class); + this.registerPacket(ProtocolInfo.MOB_ARMOR_EQUIPMENT_PACKET, MobArmorEquipmentPacket.class); + this.registerPacket(ProtocolInfo.MAP_CREATE_LOCKED_COPY_PACKET, MapCreateLockedCopyPacket.class); + this.registerPacket(ProtocolInfo.GUI_DATA_PICK_ITEM_PACKET, GUIDataPickItemPacket.class); + this.registerPacket(ProtocolInfo.EMOTE_LIST_PACKET, EmoteListPacket.class); + this.registerPacket(ProtocolInfo.DISCONNECT_PACKET, DisconnectPacket.class); + this.registerPacket(ProtocolInfo.BOSS_EVENT_PACKET, BossEventPacket.class); + this.registerPacket(ProtocolInfo.ANVIL_DAMAGE_PACKET, AnvilDamagePacket.class); } } diff --git a/src/main/java/cn/nukkit/network/RakNetInterface.java b/src/main/java/cn/nukkit/network/RakNetInterface.java index d8a6015b96e..d0b80fc7a87 100644 --- a/src/main/java/cn/nukkit/network/RakNetInterface.java +++ b/src/main/java/cn/nukkit/network/RakNetInterface.java @@ -10,45 +10,93 @@ import cn.nukkit.network.session.RakNetPlayerSession; import cn.nukkit.utils.Utils; import com.google.common.base.Strings; -import com.nukkitx.network.raknet.*; +import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; +import io.netty.buffer.Unpooled; +import io.netty.channel.*; +import io.netty.channel.epoll.Epoll; +import io.netty.channel.epoll.EpollDatagramChannel; +import io.netty.channel.epoll.EpollEventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.DatagramChannel; import io.netty.channel.socket.DatagramPacket; +import io.netty.channel.socket.nio.NioDatagramChannel; import io.netty.util.internal.PlatformDependent; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; import lombok.extern.log4j.Log4j2; +import org.cloudburstmc.netty.channel.raknet.RakChannelFactory; +import org.cloudburstmc.netty.channel.raknet.config.RakChannelOption; +import org.cloudburstmc.netty.handler.codec.raknet.server.RakServerRateLimiter; import java.lang.reflect.Constructor; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.util.*; +import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; +import java.util.function.IntFunction; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @Log4j2 -public class RakNetInterface implements RakNetServerListener, AdvancedSourceInterface { +public class RakNetInterface implements AdvancedSourceInterface { private final Server server; private Network network; - private final RakNetServer raknet; + private final List channels = new ObjectArrayList<>(); private final Map sessions = new HashMap<>(); private final Queue sessionCreationQueue = PlatformDependent.newMpscQueue(); - - private byte[] advertisement; + private final long serverId = ThreadLocalRandom.current().nextLong(); public RakNetInterface(Server server) { this.server = server; - InetSocketAddress bindAddress = new InetSocketAddress(Strings.isNullOrEmpty(this.server.getIp()) ? "0.0.0.0" : this.server.getIp(), this.server.getPort()); - this.raknet = new RakNetServer(bindAddress, Runtime.getRuntime().availableProcessors()); - this.raknet.setProtocolVersion(11); - this.raknet.bind().join(); - this.raknet.setListener(this); + boolean disableNative = Boolean.parseBoolean(System.getProperty("disableNativeEventLoop")); + + Transport transport; + if (!disableNative && Epoll.isAvailable()) { + transport = new Transport(EpollDatagramChannel.class, EpollEventLoopGroup::new); + } else { + transport = new Transport(NioDatagramChannel.class, NioEventLoopGroup::new); + } + + EventLoopGroup group = transport.eventLoopGroupFactory.apply(Runtime.getRuntime().availableProcessors()); + + ServerBootstrap bootstrap = new ServerBootstrap() + .channelFactory(RakChannelFactory.server(transport.datagramChannel)) + .group(group) + .option(RakChannelOption.RAK_GUID, this.serverId) + .childOption(RakChannelOption.RAK_ORDERING_CHANNELS, 1) + .handler(new ChannelInitializer() { + @Override + protected void initChannel(Channel channel) { + if (server.getPropertyBoolean("enable-query", false)) { + channel.pipeline().addLast("query-handler", new SimpleChannelInboundHandler() { + @Override + protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) { + server.handlePacket(packet.sender(), packet.content()); + } + }); + } + } + }) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(Channel channel) { + RakNetPlayerSession nukkitSession = new RakNetPlayerSession(RakNetInterface.this, channel); + channel.pipeline().addLast("nukkit-handler", nukkitSession); + RakNetInterface.this.sessionCreationQueue.offer(nukkitSession); + } + }); + + String address = Strings.isNullOrEmpty(this.server.getIp()) ? "0.0.0.0" : this.server.getIp(); + + this.channels.add(bootstrap.bind(address, this.server.getPort()).awaitUninterruptibly().channel()); } @Override @@ -60,7 +108,7 @@ public void setNetwork(Network network) { public boolean process() { RakNetPlayerSession session; while ((session = this.sessionCreationQueue.poll()) != null) { - InetSocketAddress address = session.getRakNetSession().getAddress(); + InetSocketAddress address = (InetSocketAddress) session.getChannel().remoteAddress(); try { PlayerCreationEvent event = new PlayerCreationEvent(this, Player.class, Player.class, null, address); this.server.getPluginManager().callEvent(event); @@ -69,11 +117,11 @@ public boolean process() { Constructor constructor = event.getPlayerClass().getConstructor(SourceInterface.class, Long.class, InetSocketAddress.class); Player player = constructor.newInstance(this, event.getClientId(), event.getSocketAddress()); - this.server.addPlayer(address, player); session.setPlayer(player); + this.server.addPlayer(address, player); } catch (Exception e) { - Server.getInstance().getLogger().error("Failed to create player", e); - session.disconnect("Internal error"); + Server.getInstance().getLogger().error("Failed to create Player", e); + session.disconnect("Internal Server Error"); this.sessions.remove(address); } } @@ -94,8 +142,7 @@ public boolean process() { @Override public int getNetworkLatency(Player player) { - RakNetServerSession session = this.raknet.getSession(player.getSocketAddress()); - return session == null ? -1 : (int) session.getPing(); + return (int) player.getNetworkSession().getPing(); } @Override @@ -119,39 +166,39 @@ public void close(Player player, String reason) { @Override public void shutdown() { this.sessions.values().forEach(session -> session.disconnect("Shutdown")); - this.raknet.close(); + this.channels.forEach(channel -> channel.close().awaitUninterruptibly()); } @Override public void emergencyShutdown() { this.sessions.values().forEach(session -> session.disconnect("Shutdown")); - this.raknet.close(); + this.channels.forEach(channel -> channel.close().awaitUninterruptibly()); } @Override public void blockAddress(InetAddress address) { - this.raknet.block(address); + this.channels.get(0).pipeline().get(RakServerRateLimiter.class).blockAddress(address, 100, TimeUnit.DAYS); } @Override public void blockAddress(InetAddress address, int timeout) { - this.raknet.block(address, timeout, TimeUnit.SECONDS); + this.channels.get(0).pipeline().get(RakServerRateLimiter.class).blockAddress(address, timeout, TimeUnit.SECONDS); } @Override public void unblockAddress(InetAddress address) { - this.raknet.unblock(address); + this.channels.get(0).pipeline().get(RakServerRateLimiter.class).unblockAddress(address); } @Override public void sendRawPacket(InetSocketAddress socketAddress, ByteBuf payload) { - this.raknet.send(socketAddress, payload); + this.channels.get(0).write(new DatagramPacket(payload, socketAddress)); } @Override public void setName(String name) { QueryRegenerateEvent info = this.server.getQueryInformation(); - String[] names = name.split("!@#"); //Split double names within the program + String[] names = name.split("!@#"); // Split double names within the program String motd = Utils.rtrim(names[0].replace(";", "\\;"), '\\'); String subMotd = names.length > 1 ? Utils.rtrim(names[1].replace(";", "\\;"), '\\') : ""; StringJoiner joiner = new StringJoiner(";") @@ -161,12 +208,16 @@ public void setName(String name) { .add(ProtocolInfo.MINECRAFT_VERSION_NETWORK) .add(Integer.toString(info.getPlayerCount())) .add(Integer.toString(info.getMaxPlayerCount())) - .add(Long.toString(this.raknet.getGuid())) + .add(Long.toString(this.serverId)) .add(subMotd) .add(Server.getGamemodeString(this.server.getDefaultGamemode(), true)) .add("1"); - this.advertisement = joiner.toString().getBytes(StandardCharsets.UTF_8); + byte[] advertisement = joiner.toString().getBytes(StandardCharsets.UTF_8); + + for (Channel channel : this.channels) { + channel.config().setOption(RakChannelOption.RAK_ADVERTISEMENT, Unpooled.wrappedBuffer(advertisement)); + } } @Override @@ -188,39 +239,18 @@ public Integer putPacket(Player player, DataPacket packet, boolean needACK, bool return null; } - @Override - public boolean onConnectionRequest(InetSocketAddress address, InetSocketAddress realAddress) { - return true; - } - - @Override - public byte[] onQuery(InetSocketAddress inetSocketAddress) { - return this.advertisement; + public Network getNetwork() { + return this.network; } - @Override - public void onSessionCreation(RakNetServerSession session) { - // We need to make sure this gets put into the correct thread local hashmap - // for ticking or race conditions will occur. - if (session.getEventLoop().inEventLoop()) { - this.onSessionCreation0(session); - } else { - session.getEventLoop().execute(() -> this.onSessionCreation0(session)); - } - } + private static class Transport { - private void onSessionCreation0(RakNetServerSession session) { - RakNetPlayerSession nukkitSession = new RakNetPlayerSession(this, session); - session.setListener(nukkitSession); - this.sessionCreationQueue.offer(nukkitSession); - } + private final Class datagramChannel; + private final IntFunction eventLoopGroupFactory; - @Override - public void onUnhandledDatagram(ChannelHandlerContext ctx, DatagramPacket datagramPacket) { - this.server.handlePacket(datagramPacket.sender(), datagramPacket.content()); - } - - public Network getNetwork() { - return this.network; + private Transport(Class datagramChannel, IntFunction eventLoopGroupFactory) { + this.datagramChannel = datagramChannel; + this.eventLoopGroupFactory = eventLoopGroupFactory; + } } } diff --git a/src/main/java/cn/nukkit/network/SourceInterface.java b/src/main/java/cn/nukkit/network/SourceInterface.java index 3b29a763841..ac5cea7da53 100644 --- a/src/main/java/cn/nukkit/network/SourceInterface.java +++ b/src/main/java/cn/nukkit/network/SourceInterface.java @@ -8,24 +8,27 @@ /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface SourceInterface { @Deprecated default Integer putPacket(Player player, DataPacket packet) { - throw new UnsupportedOperationException("This method is deprecated"); + player.getNetworkSession().sendPacket(packet); + return null; } @Deprecated default Integer putPacket(Player player, DataPacket packet, boolean needACK) { - throw new UnsupportedOperationException("This method is deprecated"); + player.getNetworkSession().sendPacket(packet); + return null; } @Deprecated default Integer putPacket(Player player, DataPacket packet, boolean needACK, boolean immediate) { - throw new UnsupportedOperationException("This method is deprecated"); + player.getNetworkSession().sendPacket(packet); + return null; } NetworkPlayerSession getSession(InetSocketAddress address); diff --git a/src/main/java/cn/nukkit/network/encryption/EncryptionUtils.java b/src/main/java/cn/nukkit/network/encryption/EncryptionUtils.java index a52ca45877c..cce7d08c513 100644 --- a/src/main/java/cn/nukkit/network/encryption/EncryptionUtils.java +++ b/src/main/java/cn/nukkit/network/encryption/EncryptionUtils.java @@ -5,16 +5,9 @@ import com.nimbusds.jose.JWSHeader; import com.nimbusds.jose.JWSObject; import com.nimbusds.jose.crypto.ECDSASigner; -import com.nimbusds.jose.crypto.ECDSAVerifier; import com.nimbusds.jose.jwk.Curve; -import com.nimbusds.jose.shaded.json.JSONArray; -import com.nimbusds.jose.shaded.json.JSONObject; -import com.nimbusds.jose.shaded.json.JSONValue; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; -import com.nukkitx.natives.aes.AesFactory; -import com.nukkitx.natives.util.Natives; -import com.nukkitx.network.util.Preconditions; import lombok.experimental.UtilityClass; import javax.crypto.Cipher; @@ -30,10 +23,8 @@ import java.security.spec.ECGenParameterSpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; -import java.text.ParseException; import java.util.Arrays; import java.util.Base64; -import java.util.Iterator; /** * ... @@ -41,7 +32,6 @@ @UtilityClass public class EncryptionUtils { - private static final AesFactory AES_FACTORY; private static final ECPublicKey MOJANG_PUBLIC_KEY; private static final SecureRandom SECURE_RANDOM = new SecureRandom(); private static final String MOJANG_PUBLIC_KEY_BASE64 = @@ -54,14 +44,6 @@ public class EncryptionUtils { String namedGroups = System.getProperty("jdk.tls.namedGroups"); System.setProperty("jdk.tls.namedGroups", namedGroups == null || namedGroups.isEmpty() ? "secp384r1" : ", secp384r1"); - AesFactory aesFactory; - try { - aesFactory = Natives.AES_CFB8.get(); - } catch (NullPointerException | IllegalStateException e) { - aesFactory = null; - } - AES_FACTORY = aesFactory; - try { KEY_PAIR_GEN = KeyPairGenerator.getInstance("EC"); KEY_PAIR_GEN.initialize(new ECGenParameterSpec("secp384r1")); @@ -83,15 +65,6 @@ public static ECPublicKey generateKey(String b64) throws NoSuchAlgorithmExceptio return (ECPublicKey) KeyFactory.getInstance("EC").generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(b64))); } - /** - * Create EC key pair to be used for handshake and encryption - * - * @return EC KeyPair - */ - public static KeyPair createKeyPair() { - return KEY_PAIR_GEN.generateKeyPair(); - } - /** * Sign JWS object with a given private key. * @@ -103,73 +76,6 @@ public static void signJwt(JWSObject jws, ECPrivateKey key) throws JOSEException jws.sign(new ECDSASigner(key, Curve.P_384)); } - /** - * Check whether a JWS object is valid for a given public key. - * - * @param jws object to be verified - * @param key key to verify object with - * @return true if the JWS object is valid - * @throws JOSEException invalid key provided - */ - public static boolean verifyJwt(JWSObject jws, ECPublicKey key) throws JOSEException { - return jws.verify(new ECDSAVerifier(key)); - } - - /** - * Verify the validity of the login chain data from the LoginPacket - * - * @param chain array of JWS objects - * @return chain validity - * @throws JOSEException invalid JWS algorithm used - * @throws ParseException invalid JWS object - * @throws InvalidKeySpecException invalid EC key provided - * @throws NoSuchAlgorithmException runtime does not support EC spec - */ - public static boolean verifyChain(JSONArray chain) throws JOSEException, ParseException, InvalidKeySpecException, NoSuchAlgorithmException { - ECPublicKey lastKey = null; - boolean validChain = false; - Iterator iterator = chain.iterator(); - while (iterator.hasNext()) { - Object node = iterator.next(); - Preconditions.checkArgument(node instanceof String, "Chain node is not a string"); - JWSObject jwt = JWSObject.parse((String) node); - - // x509 cert is expected in every claim - URI x5u = jwt.getHeader().getX509CertURL(); - if (x5u == null) { - return false; - } - - ECPublicKey expectedKey = EncryptionUtils.generateKey(jwt.getHeader().getX509CertURL().toString()); - // First key is self-signed - if (lastKey == null) { - lastKey = expectedKey; - } else if (!lastKey.equals(expectedKey)) { - return false; - } - - if (!verifyJwt(jwt, lastKey)) { - return false; - } - - if (validChain) { - return !iterator.hasNext(); - } - - if (lastKey.equals(EncryptionUtils.getMojangPublicKey())) { - validChain = true; - } - - Object payload = JSONValue.parse(jwt.getPayload().toString()); - Preconditions.checkArgument(payload instanceof JSONObject, "Payload is not a object"); - - Object identityPublicKey = ((JSONObject) payload).get("identityPublicKey"); - Preconditions.checkArgument(identityPublicKey instanceof String, "identityPublicKey node is missing in chain"); - lastKey = generateKey((String) identityPublicKey); - } - return validChain; - } - /** * Generate the secret key used to encrypt the connection * @@ -239,15 +145,6 @@ public static byte[] generateRandomToken() { return token; } - /** - * Check whether java supports the encryption required to authenticate sessions. - * - * @return can use encryption - */ - public static boolean canUseEncryption() { - return AES_FACTORY != null; - } - /** * Mojang's public key used to verify the JWT during login. * diff --git a/src/main/java/cn/nukkit/network/encryption/Sha256.java b/src/main/java/cn/nukkit/network/encryption/Sha256.java new file mode 100644 index 00000000000..d5b00637217 --- /dev/null +++ b/src/main/java/cn/nukkit/network/encryption/Sha256.java @@ -0,0 +1,34 @@ +package cn.nukkit.network.encryption; + +import java.nio.ByteBuffer; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class Sha256 { + + private final MessageDigest digest; + + public Sha256() { + try { + this.digest = MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException ex) { + throw new AssertionError(ex); + } + } + + public void update(byte[] input, int offset, int len) { + this.digest.update(input, offset, len); + } + + public void update(ByteBuffer buffer) { + this.digest.update(buffer); + } + + public byte[] digest() { + return this.digest.digest(); + } + + public void reset() { + this.digest.reset(); + } +} diff --git a/src/main/java/cn/nukkit/network/protocol/AddBehaviorTreePacket.java b/src/main/java/cn/nukkit/network/protocol/AddBehaviorTreePacket.java index 59eb42d690b..e2005c16e83 100644 --- a/src/main/java/cn/nukkit/network/protocol/AddBehaviorTreePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/AddBehaviorTreePacket.java @@ -5,21 +5,23 @@ @ToString public class AddBehaviorTreePacket extends DataPacket { - public String unknown; + public static final byte NETWORK_ID = ProtocolInfo.ADD_BEHAVIOR_TREE_PACKET; + + public String behaviorTreeJson; @Override public byte pid() { - return ProtocolInfo.ADD_BEHAVIOR_TREE_PACKET; + return NETWORK_ID; } @Override public void decode() { - + this.behaviorTreeJson = this.getString(); } @Override public void encode() { this.reset(); - this.putString(unknown); + this.putString(behaviorTreeJson); } } diff --git a/src/main/java/cn/nukkit/network/protocol/AddEntityPacket.java b/src/main/java/cn/nukkit/network/protocol/AddEntityPacket.java index 9d9a2db9495..318b86ba006 100644 --- a/src/main/java/cn/nukkit/network/protocol/AddEntityPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/AddEntityPacket.java @@ -1,6 +1,8 @@ package cn.nukkit.network.protocol; import cn.nukkit.entity.Attribute; +import cn.nukkit.entity.custom.EntityDefinition; +import cn.nukkit.entity.custom.EntityManager; import cn.nukkit.entity.data.EntityMetadata; import cn.nukkit.entity.item.*; import cn.nukkit.entity.mob.*; @@ -13,14 +15,15 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class AddEntityPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.ADD_ENTITY_PACKET; - public static ImmutableMap LEGACY_IDS = ImmutableMap.builder() + public static final ImmutableMap LEGACY_IDS = ImmutableMap.builder() .put(51, "minecraft:npc") .put(63, "minecraft:player") .put(EntityWitherSkeleton.NETWORK_ID, "minecraft:wither_skeleton") @@ -60,9 +63,9 @@ public class AddEntityPacket extends DataPacket { .put(EntityChicken.NETWORK_ID, "minecraft:chicken") .put(107, "minecraft:balloon") .put(EntityLlama.NETWORK_ID, "minecraft:llama") - .put(20, "minecraft:iron_golem") + .put(EntityIronGolem.NETWORK_ID, "minecraft:iron_golem") .put(EntityRabbit.NETWORK_ID, "minecraft:rabbit") - .put(21, "minecraft:snow_golem") + .put(EntitySnowGolem.NETWORK_ID, "minecraft:snow_golem") .put(EntityBat.NETWORK_ID, "minecraft:bat") .put(EntityOcelot.NETWORK_ID, "minecraft:ocelot") .put(EntityHorse.NETWORK_ID, "minecraft:horse") @@ -83,7 +86,7 @@ public class AddEntityPacket extends DataPacket { .put(EntityMinecartTNT.NETWORK_ID, "minecraft:tnt_minecart") .put(EntityMinecartChest.NETWORK_ID, "minecraft:chest_minecart") .put(100, "minecraft:command_block_minecart") - .put(61, "minecraft:armor_stand") + .put(EntityArmorStand.NETWORK_ID, "minecraft:armor_stand") .put(EntityItem.NETWORK_ID, "minecraft:item") .put(EntityPrimedTNT.NETWORK_ID, "minecraft:tnt") .put(EntityFallingBlock.NETWORK_ID, "minecraft:falling_block") @@ -109,8 +112,8 @@ public class AddEntityPacket extends DataPacket { .put(EntityLightning.NETWORK_ID, "minecraft:lightning_bolt") .put(94, "minecraft:small_fireball") .put(102, "minecraft:llama_spit") - .put(95, "minecraft:area_effect_cloud") - .put(101, "minecraft:lingering_potion") + .put(EntityAreaEffectCloud.NETWORK_ID, "minecraft:area_effect_cloud") + .put(EntityPotionLingering.NETWORK_ID, "minecraft:lingering_potion") .put(EntityFirework.NETWORK_ID, "minecraft:fireworks_rocket") .put(103, "minecraft:evocation_fang") .put(104, "minecraft:evocation_illager") @@ -138,13 +141,14 @@ public class AddEntityPacket extends DataPacket { .put(EntityFrog.NETWORK_ID, "minecraft:frog") .put(EntityTadpole.NETWORK_ID, "minecraft:tadpole") .put(EntityAllay.NETWORK_ID, "minecraft:allay") - .put(138, "minecraft:camel") - .put(139, "minecraft:sniffer") - .put(140, "minecraft:breeze") + .put(EntityChestBoat.NETWORK_ID, "minecraft:chest_boat") + .put(EntityCamel.NETWORK_ID, "minecraft:camel") + .put(EntitySniffer.NETWORK_ID, "minecraft:sniffer") + .put(EntityBreeze.NETWORK_ID, "minecraft:breeze") .put(141, "minecraft:breeze_wind_charge_projectile") - .put(142, "minecraft:armadillo") + .put(EntityArmadillo.NETWORK_ID, "minecraft:armadillo") .put(143, "minecraft:wind_charge_projectile") - .put(144, "minecraft:bogged") + .put(EntityBogged.NETWORK_ID, "minecraft:bogged") .build(); @Override @@ -172,7 +176,7 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override @@ -180,16 +184,13 @@ public void encode() { this.reset(); this.putEntityUniqueId(this.entityUniqueId); this.putEntityRuntimeId(this.entityRuntimeId); - if (id == null) { - id = LEGACY_IDS.get(type); - } - this.putString(this.id); + this.putString(this.getEntityIdentifier()); this.putVector3f(this.x, this.y, this.z); this.putVector3f(this.speedX, this.speedY, this.speedZ); this.putLFloat(this.pitch); this.putLFloat(this.yaw); this.putLFloat(this.headYaw); - this.putLFloat(this.bodyYaw == -1 ? this.yaw : this.bodyYaw); + this.putLFloat(this.bodyYaw == -1 ? this.yaw : this.bodyYaw); // For backwards compatibility this.putAttributeList(this.attributes); this.put(Binary.writeMetadata(this.metadata)); this.putUnsignedVarInt(0); // Entity properties int @@ -199,4 +200,25 @@ public void encode() { putEntityLink(link); } } + + private String getEntityIdentifier() { + if (this.id != null) { + return this.id; + } + + String identifier = LEGACY_IDS.get(type); + + if (identifier == null) { + // Maybe a custom entity + EntityDefinition definition = EntityManager.get().getDefinition(this.type); + if (definition != null) { + identifier = definition.getIdentifier(); + } + } + + if (identifier == null) { + throw new IllegalStateException("Unknown entity with network id " + this.type); + } + return identifier; + } } diff --git a/src/main/java/cn/nukkit/network/protocol/AddItemEntityPacket.java b/src/main/java/cn/nukkit/network/protocol/AddItemEntityPacket.java index b53ec71a9fd..8860508d329 100644 --- a/src/main/java/cn/nukkit/network/protocol/AddItemEntityPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/AddItemEntityPacket.java @@ -6,11 +6,12 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class AddItemEntityPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.ADD_ITEM_ENTITY_PACKET; @Override @@ -32,7 +33,7 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/AddPaintingPacket.java b/src/main/java/cn/nukkit/network/protocol/AddPaintingPacket.java index 0101c62b3c5..59a494c0d68 100644 --- a/src/main/java/cn/nukkit/network/protocol/AddPaintingPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/AddPaintingPacket.java @@ -20,7 +20,7 @@ public class AddPaintingPacket extends DataPacket { @Override public void decode() { - + this.decodeUnsupported(); } @Override @@ -28,7 +28,6 @@ public void encode() { this.reset(); this.putEntityUniqueId(this.entityUniqueId); this.putEntityRuntimeId(this.entityRuntimeId); - this.putVector3f(this.x, this.y, this.z); this.putVarInt(this.direction); this.putString(this.title); @@ -38,5 +37,4 @@ public void encode() { public byte pid() { return NETWORK_ID; } - } diff --git a/src/main/java/cn/nukkit/network/protocol/AddPlayerPacket.java b/src/main/java/cn/nukkit/network/protocol/AddPlayerPacket.java index e11053b5e23..6b94c09bb44 100644 --- a/src/main/java/cn/nukkit/network/protocol/AddPlayerPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/AddPlayerPacket.java @@ -9,11 +9,12 @@ import java.util.UUID; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class AddPlayerPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.ADD_PLAYER_PACKET; @Override @@ -34,16 +35,16 @@ public byte pid() { public float speedZ; public float pitch; public float yaw; + public float headYaw = -1; public Item item; public int gameType = Server.getInstance().getGamemode(); public EntityMetadata metadata = new EntityMetadata(); - //public EntityLink links = new EntityLink[0]; public String deviceId = ""; public int buildPlatform = -1; @Override public void decode() { - + this.decodeUnsupported(); } @Override @@ -51,29 +52,28 @@ public void encode() { this.reset(); this.putUUID(this.uuid); this.putString(this.username); - // this.putEntityUniqueId(this.entityUniqueId); this.putEntityRuntimeId(this.entityRuntimeId); this.putString(this.platformChatId); this.putVector3f(this.x, this.y, this.z); this.putVector3f(this.speedX, this.speedY, this.speedZ); this.putLFloat(this.pitch); - this.putLFloat(this.yaw); //TODO headrot this.putLFloat(this.yaw); + this.putLFloat(this.headYaw == -1 ? this.yaw : this.headYaw); this.putSlot(this.item); this.putVarInt(this.gameType); this.put(Binary.writeMetadata(this.metadata)); this.putUnsignedVarInt(0); // Entity properties int this.putUnsignedVarInt(0); // Entity properties float this.putLLong(entityUniqueId); - this.putUnsignedVarInt(0); // playerPermission - this.putUnsignedVarInt(0); // commandPermission - this.putUnsignedVarInt(1); // abilitiesLayer size - this.putLShort(1); // BASE layer type - this.putLInt(262143); // abilitiesSet - all abilities - this.putLInt(63); // abilityValues - survival abilities - this.putLFloat(0.1f); // flySpeed - this.putLFloat(0.05f); // walkSpeed - this.putUnsignedVarInt(0); //TODO: Entity links + this.putUnsignedVarInt(0); // getPlayerPermission().ordinal() + this.putUnsignedVarInt(0); // getCommandPermission().ordinal() + this.putUnsignedVarInt(1); // getAbilityLayers().size() + this.putLShort(1); // getLayerType().ordinal() == BASE + this.putLInt(262143); // getAbilitiesSet() + this.putLInt(63); // getAbilityValues() + this.putLFloat(0.1f); // getFlySpeed() + this.putLFloat(0.05f); // getWalkSpeed() + this.putUnsignedVarInt(0); // Entity links this.putString(deviceId); this.putLInt(buildPlatform); } diff --git a/src/main/java/cn/nukkit/network/protocol/AdventureSettingsPacket.java b/src/main/java/cn/nukkit/network/protocol/AdventureSettingsPacket.java index 347275f7ac0..98378cef3c5 100644 --- a/src/main/java/cn/nukkit/network/protocol/AdventureSettingsPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/AdventureSettingsPacket.java @@ -6,8 +6,8 @@ /** * @author Nukkit Project Team */ -@ToString @Deprecated +@ToString public class AdventureSettingsPacket extends DataPacket { public static final byte NETWORK_ID = ProtocolInfo.ADVENTURE_SETTINGS_PACKET; @@ -35,7 +35,6 @@ public class AdventureSettingsPacket extends DataPacket { public static final int WORLD_BUILDER = 0x100; public static final int FLYING = 0x200; public static final int MUTED = 0x400; - public static final int MINE = 0x01 | BITFLAG_SECOND_SET; public static final int DOORS_AND_SWITCHES = 0x02 | BITFLAG_SECOND_SET; public static final int OPEN_CONTAINERS = 0x04 | BITFLAG_SECOND_SET; @@ -47,17 +46,15 @@ public class AdventureSettingsPacket extends DataPacket { public static final int DEFAULT_LEVEL_PERMISSIONS = 0x200 | BITFLAG_SECOND_SET; public long flags = 0; - - public long commandPermission = PERMISSION_NORMAL; - public long flags2 = 0; + public long customFlags; + public long commandPermission = PERMISSION_NORMAL; public long playerPermission = Player.PERMISSION_MEMBER; - public long customFlags; //... - public long entityUniqueId; //This is a little-endian long, NOT a var-long. (WTF Mojang) + @Override public void decode() { this.flags = getUnsignedVarInt(); this.commandPermission = getUnsignedVarInt(); @@ -67,6 +64,7 @@ public void decode() { this.entityUniqueId = getLLong(); } + @Override public void encode() { this.reset(); this.putUnsignedVarInt(this.flags); diff --git a/src/main/java/cn/nukkit/network/protocol/AnimateEntityPacket.java b/src/main/java/cn/nukkit/network/protocol/AnimateEntityPacket.java index 03e0ecf849d..6d467452771 100644 --- a/src/main/java/cn/nukkit/network/protocol/AnimateEntityPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/AnimateEntityPacket.java @@ -51,6 +51,7 @@ public class AnimateEntityPacket extends DataPacket { @Override public void decode() { + this.decodeUnsupported(); } @Override @@ -60,7 +61,9 @@ public void encode() { this.putString(this.animation); this.putString(this.nextState); this.putString(this.stopExpression); + this.putLInt(this.stopExpressionVersion); + this.putString(this.controller); this.putLFloat(this.blendOutTime); diff --git a/src/main/java/cn/nukkit/network/protocol/AnimatePacket.java b/src/main/java/cn/nukkit/network/protocol/AnimatePacket.java index 1cc3b18c404..09898e7cc3b 100644 --- a/src/main/java/cn/nukkit/network/protocol/AnimatePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/AnimatePacket.java @@ -12,7 +12,6 @@ public class AnimatePacket extends DataPacket { public static final byte NETWORK_ID = ProtocolInfo.ANIMATE_PACKET; - public long eid; public Action action; public float rowingTime; diff --git a/src/main/java/cn/nukkit/network/protocol/AnvilDamagePacket.java b/src/main/java/cn/nukkit/network/protocol/AnvilDamagePacket.java index f03d8b886f0..bd65246bc89 100644 --- a/src/main/java/cn/nukkit/network/protocol/AnvilDamagePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/AnvilDamagePacket.java @@ -6,6 +6,8 @@ @ToString public class AnvilDamagePacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.ANVIL_DAMAGE_PACKET; + public int damage; public int x; public int y; @@ -13,7 +15,7 @@ public class AnvilDamagePacket extends DataPacket { @Override public byte pid() { - return ProtocolInfo.ANVIL_DAMAGE_PACKET; + return NETWORK_ID; } @Override @@ -27,6 +29,6 @@ public void decode() { @Override public void encode() { - + this.encodeUnsupported(); } } diff --git a/src/main/java/cn/nukkit/network/protocol/AvailableCommandsPacket.java b/src/main/java/cn/nukkit/network/protocol/AvailableCommandsPacket.java index 4be1509d86f..22b829215cf 100644 --- a/src/main/java/cn/nukkit/network/protocol/AvailableCommandsPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/AvailableCommandsPacket.java @@ -8,7 +8,7 @@ import java.util.function.ObjIntConsumer; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString @@ -55,7 +55,7 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override @@ -131,7 +131,7 @@ public void encode() { this.putUnsignedVarInt(0); //subCommandData - putUnsignedVarInt(commands.size()); + this.putUnsignedVarInt(commands.size()); commands.forEach((name, cmdData) -> { CommandData data = cmdData.versions.get(0); @@ -170,12 +170,13 @@ public void encode() { putLInt(type); putBoolean(parameter.optional); - putByte(parameter.options); // TODO: 19/03/2019 Bit flags. Only first bit is used for GameRules. + putByte(parameter.options); } } }); this.putUnsignedVarInt(softEnums.size()); + softEnums.forEach((name, values) -> { this.putString(name); this.putUnsignedVarInt(values.size()); diff --git a/src/main/java/cn/nukkit/network/protocol/AvailableEntityIdentifiersPacket.java b/src/main/java/cn/nukkit/network/protocol/AvailableEntityIdentifiersPacket.java index 97b22f9b641..e46da20a248 100644 --- a/src/main/java/cn/nukkit/network/protocol/AvailableEntityIdentifiersPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/AvailableEntityIdentifiersPacket.java @@ -1,31 +1,10 @@ package cn.nukkit.network.protocol; -import cn.nukkit.Nukkit; -import com.google.common.io.ByteStreams; -import lombok.ToString; +import cn.nukkit.entity.custom.EntityManager; -import java.io.InputStream; - -@ToString(exclude = {"tag"}) public class AvailableEntityIdentifiersPacket extends DataPacket { - public static final byte NETWORK_ID = ProtocolInfo.AVAILABLE_ENTITY_IDENTIFIERS_PACKET; - - private static final byte[] TAG; - static { - try { - InputStream inputStream = Nukkit.class.getClassLoader().getResourceAsStream("entity_identifiers.dat"); - if (inputStream == null) { - throw new AssertionError("Could not find entity_identifiers.dat"); - } - //noinspection UnstableApiUsage - TAG = ByteStreams.toByteArray(inputStream); - } catch (Exception e) { - throw new AssertionError("Error whilst loading entity_identifiers.dat", e); - } - } - - public byte[] tag = TAG; + public static final byte NETWORK_ID = ProtocolInfo.AVAILABLE_ENTITY_IDENTIFIERS_PACKET; @Override public byte pid() { @@ -34,12 +13,12 @@ public byte pid() { @Override public void decode() { - this.tag = this.get(); + this.decodeUnsupported(); } @Override public void encode() { this.reset(); - this.put(this.tag); + this.put(EntityManager.get().createNetworkTag()); } } diff --git a/src/main/java/cn/nukkit/network/protocol/BatchPacket.java b/src/main/java/cn/nukkit/network/protocol/BatchPacket.java index 5e67c79ef79..5171ece01c8 100644 --- a/src/main/java/cn/nukkit/network/protocol/BatchPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/BatchPacket.java @@ -1,10 +1,11 @@ package cn.nukkit.network.protocol; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BatchPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.BATCH_PACKET; public byte[] payload; @@ -21,10 +22,19 @@ public void decode() { @Override public void encode() { - + this.encodeUnsupported(); } public void trim() { setBuffer(null); } + + @Override + public BatchPacket clone() { + BatchPacket packet = (BatchPacket) super.clone(); + if (this.payload != null) { + packet.payload = this.payload.clone(); + } + return packet; + } } diff --git a/src/main/java/cn/nukkit/network/protocol/BiomeDefinitionListPacket.java b/src/main/java/cn/nukkit/network/protocol/BiomeDefinitionListPacket.java index 49727aa1750..b82b581517c 100644 --- a/src/main/java/cn/nukkit/network/protocol/BiomeDefinitionListPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/BiomeDefinitionListPacket.java @@ -4,28 +4,31 @@ import com.google.common.io.ByteStreams; import lombok.ToString; -import java.io.InputStream; +import java.util.zip.Deflater; @ToString(exclude = "tag") public class BiomeDefinitionListPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.BIOME_DEFINITION_LIST_PACKET; - private static final byte[] TAG; + private static final BatchPacket CACHED_PACKET; + + private byte[] tag; static { try { - InputStream inputStream = Nukkit.class.getClassLoader().getResourceAsStream("biome_definitions.dat"); - if (inputStream == null) { - throw new AssertionError("Could not find biome_definitions.dat"); - } - //noinspection UnstableApiUsage - TAG = ByteStreams.toByteArray(inputStream); + BiomeDefinitionListPacket pk = new BiomeDefinitionListPacket(); + pk.tag = ByteStreams.toByteArray(Nukkit.class.getClassLoader().getResourceAsStream("biome_definitions.dat")); + pk.tryEncode(); + CACHED_PACKET = pk.compress(Deflater.BEST_COMPRESSION); } catch (Exception e) { - throw new AssertionError("Error whilst loading biome_definitions.dat", e); + throw new AssertionError("Error whilst loading biome definitions", e); } } - public byte[] tag = TAG; + public static BatchPacket getCachedPacket() { + return CACHED_PACKET; + } @Override public byte pid() { @@ -34,11 +37,16 @@ public byte pid() { @Override public void decode() { + this.decodeUnsupported(); } @Override public void encode() { + if (this.tag == null) { + throw new RuntimeException("tag == null, use getCachedPacket!"); + } + this.reset(); - this.put(tag); + this.put(this.tag); } } diff --git a/src/main/java/cn/nukkit/network/protocol/BlockEntityDataPacket.java b/src/main/java/cn/nukkit/network/protocol/BlockEntityDataPacket.java index ea21643a338..ecfe75151ca 100644 --- a/src/main/java/cn/nukkit/network/protocol/BlockEntityDataPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/BlockEntityDataPacket.java @@ -4,11 +4,12 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString(exclude = "namedTag") public class BlockEntityDataPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.BLOCK_ENTITY_DATA_PACKET; public int x; diff --git a/src/main/java/cn/nukkit/network/protocol/BlockEventPacket.java b/src/main/java/cn/nukkit/network/protocol/BlockEventPacket.java index 566603238b1..841cd323dcb 100644 --- a/src/main/java/cn/nukkit/network/protocol/BlockEventPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/BlockEventPacket.java @@ -3,11 +3,12 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class BlockEventPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.BLOCK_EVENT_PACKET; @Override @@ -23,7 +24,7 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/BlockPickRequestPacket.java b/src/main/java/cn/nukkit/network/protocol/BlockPickRequestPacket.java index 52f81f782c2..cd672f85e4f 100644 --- a/src/main/java/cn/nukkit/network/protocol/BlockPickRequestPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/BlockPickRequestPacket.java @@ -31,6 +31,6 @@ public void decode() { @Override public void encode() { - + this.encodeUnsupported(); } } diff --git a/src/main/java/cn/nukkit/network/protocol/BookEditPacket.java b/src/main/java/cn/nukkit/network/protocol/BookEditPacket.java index b9ec95c7048..d5cc0b1b26f 100644 --- a/src/main/java/cn/nukkit/network/protocol/BookEditPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/BookEditPacket.java @@ -53,7 +53,7 @@ public void decode() { @Override public void encode() { - + this.encodeUnsupported(); } public enum Action { diff --git a/src/main/java/cn/nukkit/network/protocol/BossEventPacket.java b/src/main/java/cn/nukkit/network/protocol/BossEventPacket.java index 0610691c25c..e8ee6b2133d 100644 --- a/src/main/java/cn/nukkit/network/protocol/BossEventPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/BossEventPacket.java @@ -10,23 +10,25 @@ public class BossEventPacket extends DataPacket { public static final byte NETWORK_ID = ProtocolInfo.BOSS_EVENT_PACKET; - /* S2C: Shows the bossbar to the player. */ + /** Shows the bossbar to the player. */ public static final int TYPE_SHOW = 0; - /* C2S: Registers a player to a boss fight. */ + /** Registers a player to a boss fight. */ public static final int TYPE_REGISTER_PLAYER = 1; + /** Not sure on this. */ public static final int TYPE_UPDATE = 1; - /* S2C: Removes the bossbar from the client. */ + /** Removes the bossbar from the client. */ public static final int TYPE_HIDE = 2; - /* C2S: Unregisters a player from a boss fight. */ + /** Unregisters a player from a boss fight. */ public static final int TYPE_UNREGISTER_PLAYER = 3; - /* S2C: Sets the bar percentage. */ + /** Sets the bar percentage. */ public static final int TYPE_HEALTH_PERCENT = 4; - /* S2C: Sets title of the bar. */ + /** Sets title of the bar. */ public static final int TYPE_TITLE = 5; - /* S2C: Not sure on this. Includes color and overlay fields, plus an unknown short. TODO: check this */ + /** Not sure on this. Includes color and overlay fields, plus an unknown short. */ public static final int TYPE_UPDATE_PROPERTIES = 6; - /* S2C: Sets color and overlay of the bar. */ + /** S2C: Sets color and overlay of the bar. **/ public static final int TYPE_TEXTURE = 7; + /** Unknown. Since 1.18.10 **/ public static final int TYPE_QUERY = 8; public long bossEid; diff --git a/src/main/java/cn/nukkit/network/protocol/CameraPacket.java b/src/main/java/cn/nukkit/network/protocol/CameraPacket.java index deb610056e7..f1b74a28d0d 100644 --- a/src/main/java/cn/nukkit/network/protocol/CameraPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/CameraPacket.java @@ -5,18 +5,19 @@ @ToString public class CameraPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.CAMERA_PACKET; + public long cameraUniqueId; public long playerUniqueId; @Override public byte pid() { - return ProtocolInfo.CAMERA_PACKET; + return NETWORK_ID; } @Override public void decode() { - this.cameraUniqueId = this.getVarLong(); - this.playerUniqueId = this.getVarLong(); + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/ChangeDimensionPacket.java b/src/main/java/cn/nukkit/network/protocol/ChangeDimensionPacket.java index 906304dabb0..eae9bb8ae24 100644 --- a/src/main/java/cn/nukkit/network/protocol/ChangeDimensionPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ChangeDimensionPacket.java @@ -23,7 +23,7 @@ public class ChangeDimensionPacket extends DataPacket { @Override public void decode() { - + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/ChunkRadiusUpdatedPacket.java b/src/main/java/cn/nukkit/network/protocol/ChunkRadiusUpdatedPacket.java index f17e058b561..1948c667e2f 100644 --- a/src/main/java/cn/nukkit/network/protocol/ChunkRadiusUpdatedPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ChunkRadiusUpdatedPacket.java @@ -3,7 +3,7 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString @@ -15,12 +15,12 @@ public class ChunkRadiusUpdatedPacket extends DataPacket { @Override public void decode() { - this.radius = this.getVarInt(); + this.decodeUnsupported(); } @Override public void encode() { - super.reset(); + this.reset(); this.putVarInt(this.radius); } @@ -28,5 +28,4 @@ public void encode() { public byte pid() { return NETWORK_ID; } - } diff --git a/src/main/java/cn/nukkit/network/protocol/ClientCacheStatusPacket.java b/src/main/java/cn/nukkit/network/protocol/ClientCacheStatusPacket.java index 45cdc00aa31..49c9ef520fa 100644 --- a/src/main/java/cn/nukkit/network/protocol/ClientCacheStatusPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ClientCacheStatusPacket.java @@ -1,6 +1,10 @@ package cn.nukkit.network.protocol; +import lombok.ToString; + +@ToString public class ClientCacheStatusPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.CLIENT_CACHE_STATUS_PACKET; public boolean supported; diff --git a/src/main/java/cn/nukkit/network/protocol/ClientToServerHandshakePacket.java b/src/main/java/cn/nukkit/network/protocol/ClientToServerHandshakePacket.java index 3e8689fad9e..f5907b67868 100644 --- a/src/main/java/cn/nukkit/network/protocol/ClientToServerHandshakePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ClientToServerHandshakePacket.java @@ -5,18 +5,20 @@ @ToString public class ClientToServerHandshakePacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.CLIENT_TO_SERVER_HANDSHAKE_PACKET; + @Override public byte pid() { - return ProtocolInfo.CLIENT_TO_SERVER_HANDSHAKE_PACKET; + return NETWORK_ID; } @Override public void decode() { - //no content + // No payload } @Override public void encode() { - + this.encodeUnsupported(); } } diff --git a/src/main/java/cn/nukkit/network/protocol/ClientboundMapItemDataPacket.java b/src/main/java/cn/nukkit/network/protocol/ClientboundMapItemDataPacket.java index 730f1fde8cd..86b4dd587f3 100644 --- a/src/main/java/cn/nukkit/network/protocol/ClientboundMapItemDataPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ClientboundMapItemDataPacket.java @@ -15,8 +15,6 @@ public class ClientboundMapItemDataPacket extends DataPacket { public static final byte NETWORK_ID = ProtocolInfo.CLIENTBOUND_MAP_ITEM_DATA_PACKET; - public int[] eids = new int[0]; - public long mapId; public int update; public byte scale; @@ -25,14 +23,19 @@ public class ClientboundMapItemDataPacket extends DataPacket { public int height; public int offsetX; public int offsetZ; - public byte dimensionId; - public BlockVector3 origin = new BlockVector3(); - - public MapDecorator[] decorators = new MapDecorator[0]; - public MapTrackedObject[] trackedEntities = new MapTrackedObject[0]; - public int[] colors = new int[0]; - public BufferedImage image = null; + public BlockVector3 origin = EMPTY_BlockVector3; + public MapDecorator[] decorators = EMPTY_MapDecorator; + public MapTrackedObject[] trackedEntities = EMPTY_MapTrackedObject; + public long[] eids = EMPTY_long; + public int[] colors = EMPTY_int; + public BufferedImage image; + + private static final BlockVector3 EMPTY_BlockVector3 = new BlockVector3(); + private static final MapDecorator[] EMPTY_MapDecorator = new MapDecorator[0]; + private static final MapTrackedObject[] EMPTY_MapTrackedObject = new MapTrackedObject[0]; + private static final long[] EMPTY_long = new long[0]; + private static final int[] EMPTY_int = new int[0]; public static final int TEXTURE_UPDATE = 0x02; public static final int DECORATIONS_UPDATE = 0x04; @@ -45,7 +48,7 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override @@ -68,11 +71,11 @@ public void encode() { this.putUnsignedVarInt(update); this.putByte(this.dimensionId); this.putBoolean(this.isLocked); - this.putBlockVector3(this.origin); + this.putSignedBlockPosition(origin); if ((update & ENTITIES_UPDATE) != 0) { this.putUnsignedVarInt(eids.length); - for (int eid : eids) { + for (long eid : eids) { this.putEntityUniqueId(eid); } } @@ -121,7 +124,7 @@ public void encode() { } image.flush(); - } else if (colors.length > 0) { + } else { for (int color : colors) { this.putUnsignedVarInt(color); } diff --git a/src/main/java/cn/nukkit/network/protocol/CodeBuilderPacket.java b/src/main/java/cn/nukkit/network/protocol/CodeBuilderPacket.java index a7289d26430..d01c477a3f5 100644 --- a/src/main/java/cn/nukkit/network/protocol/CodeBuilderPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/CodeBuilderPacket.java @@ -4,6 +4,7 @@ @ToString public class CodeBuilderPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.CODE_BUILDER_PACKET; public boolean isOpening; @@ -16,8 +17,7 @@ public byte pid() { @Override public void decode() { - this.url = this.getString(); - this.isOpening = this.getBoolean(); + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/CommandBlockUpdatePacket.java b/src/main/java/cn/nukkit/network/protocol/CommandBlockUpdatePacket.java index 4d5e579eb38..faca28de079 100644 --- a/src/main/java/cn/nukkit/network/protocol/CommandBlockUpdatePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/CommandBlockUpdatePacket.java @@ -6,6 +6,8 @@ @ToString public class CommandBlockUpdatePacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.COMMAND_BLOCK_UPDATE_PACKET; + public boolean isBlock; public int x; public int y; @@ -21,7 +23,7 @@ public class CommandBlockUpdatePacket extends DataPacket { @Override public byte pid() { - return ProtocolInfo.COMMAND_BLOCK_UPDATE_PACKET; + return NETWORK_ID; } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/CommandRequestPacket.java b/src/main/java/cn/nukkit/network/protocol/CommandRequestPacket.java index 4dc10ad1a23..f887a0b5c28 100644 --- a/src/main/java/cn/nukkit/network/protocol/CommandRequestPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/CommandRequestPacket.java @@ -6,7 +6,7 @@ import java.util.UUID; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString @@ -28,6 +28,7 @@ public class CommandRequestPacket extends DataPacket { public String command; public CommandOriginData data; + public boolean internal; @Override public byte pid() { @@ -46,10 +47,12 @@ public void decode() { varLong = this.getVarLong(); } this.data = new CommandOriginData(type, uuid, requestId, varLong); + this.internal = this.getBoolean(); + this.getVarInt(); // version } @Override public void encode() { + this.encodeUnsupported(); } - } diff --git a/src/main/java/cn/nukkit/network/protocol/CompletedUsingItemPacket.java b/src/main/java/cn/nukkit/network/protocol/CompletedUsingItemPacket.java index 8f34df797d2..433817dcaf6 100644 --- a/src/main/java/cn/nukkit/network/protocol/CompletedUsingItemPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/CompletedUsingItemPacket.java @@ -27,7 +27,6 @@ public class CompletedUsingItemPacket extends DataPacket { public int itemId; public int action; - @Override public byte pid() { return NETWORK_ID; @@ -35,6 +34,7 @@ public byte pid() { @Override public void decode() { + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/ContainerClosePacket.java b/src/main/java/cn/nukkit/network/protocol/ContainerClosePacket.java index d22b02279b3..3b727a54073 100644 --- a/src/main/java/cn/nukkit/network/protocol/ContainerClosePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ContainerClosePacket.java @@ -3,11 +3,12 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class ContainerClosePacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.CONTAINER_CLOSE_PACKET; @Override diff --git a/src/main/java/cn/nukkit/network/protocol/ContainerOpenPacket.java b/src/main/java/cn/nukkit/network/protocol/ContainerOpenPacket.java index 557dc71f156..0f2f3002ffc 100644 --- a/src/main/java/cn/nukkit/network/protocol/ContainerOpenPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ContainerOpenPacket.java @@ -1,14 +1,14 @@ package cn.nukkit.network.protocol; -import cn.nukkit.math.BlockVector3; import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class ContainerOpenPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.CONTAINER_OPEN_PACKET; @Override @@ -25,13 +25,7 @@ public byte pid() { @Override public void decode() { - this.windowId = this.getByte(); - this.type = this.getByte(); - BlockVector3 v = this.getBlockVector3(); - this.x = v.x; - this.y = v.y; - this.z = v.z; - this.entityId = this.getEntityUniqueId(); + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/ContainerSetDataPacket.java b/src/main/java/cn/nukkit/network/protocol/ContainerSetDataPacket.java index 087fbcbf5b6..9a811166844 100644 --- a/src/main/java/cn/nukkit/network/protocol/ContainerSetDataPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ContainerSetDataPacket.java @@ -3,17 +3,18 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class ContainerSetDataPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.CONTAINER_SET_DATA_PACKET; public static final int PROPERTY_FURNACE_TICK_COUNT = 0; public static final int PROPERTY_FURNACE_LIT_TIME = 1; public static final int PROPERTY_FURNACE_LIT_DURATION = 2; - //TODO: check property 3 + public static final int PROPERTY_UNKNOWN = 3; public static final int PROPERTY_FURNACE_FUEL_AUX = 4; public static final int PROPERTY_BREWING_STAND_BREW_TIME = 0; @@ -31,7 +32,7 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/CraftingDataPacket.java b/src/main/java/cn/nukkit/network/protocol/CraftingDataPacket.java index 6cfd944bdea..b59e8cbabf7 100644 --- a/src/main/java/cn/nukkit/network/protocol/CraftingDataPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/CraftingDataPacket.java @@ -23,11 +23,12 @@ public class CraftingDataPacket extends DataPacket { public static final String CRAFTING_TAG_CAMPFIRE = "campfire"; public static final String CRAFTING_TAG_BLAST_FURNACE = "blast_furnace"; public static final String CRAFTING_TAG_SMOKER = "smoker"; + public static final String CRAFTING_TAG_SMITHING_TABLE = "smithing_table"; private List entries = new ArrayList<>(); private final List brewingEntries = new ArrayList<>(); private final List containerEntries = new ArrayList<>(); - public boolean cleanRecipes; + public boolean cleanRecipes = true; public void addShapelessRecipe(ShapelessRecipe... recipe) { Collections.addAll(entries, recipe); @@ -41,14 +42,14 @@ public void addFurnaceRecipe(FurnaceRecipe... recipe) { Collections.addAll(entries, recipe); } - public void addMultiRecipe(MultiRecipe... recipe) { - Collections.addAll(entries, recipe); - } - public void addBrewingRecipe(BrewingRecipe... recipe) { Collections.addAll(brewingEntries, recipe); } + public void addMultiRecipe(MultiRecipe... recipe) { + Collections.addAll(entries, recipe); + } + public void addContainerRecipe(ContainerRecipe... recipe) { Collections.addAll(containerEntries, recipe); } @@ -61,7 +62,7 @@ public DataPacket clean() { @Override public void decode() { - + this.decodeUnsupported(); } @Override @@ -69,10 +70,13 @@ public void encode() { this.reset(); this.putUnsignedVarInt(entries.size()); - int recipeNetworkId = 1; - for (Recipe recipe : entries) { - this.putVarInt(recipe.getType().ordinal()); + RecipeType networkType = recipe.getType(); + if (networkType == RecipeType.SMITHING_TRANSFORM) { + networkType = RecipeType.REPAIR; + } + this.putVarInt(networkType.ordinal()); + switch (recipe.getType()) { case SHAPELESS: ShapelessRecipe shapeless = (ShapelessRecipe) recipe; @@ -88,7 +92,7 @@ public void encode() { this.putString(CRAFTING_TAG_CRAFTING_TABLE); this.putVarInt(shapeless.getPriority()); this.putByte((byte) 1); // Requirement ordinal, 1 = ALWAYS_UNLOCKED - this.putUnsignedVarInt(recipeNetworkId++); + this.putUnsignedVarInt(shapeless.getNetworkId()); break; case SHAPED: ShapedRecipe shaped = (ShapedRecipe) recipe; @@ -113,7 +117,7 @@ public void encode() { this.putVarInt(shaped.getPriority()); this.putBoolean(true); // Assume symmetry this.putByte((byte) 1); // Requirement ordinal, 1 = ALWAYS_UNLOCKED - this.putUnsignedVarInt(recipeNetworkId++); + this.putUnsignedVarInt(shaped.getNetworkId()); break; case FURNACE: case FURNACE_DATA: @@ -128,7 +132,29 @@ public void encode() { break; case MULTI: this.putUUID(((MultiRecipe) recipe).getId()); - this.putUnsignedVarInt(recipeNetworkId++); + this.putUnsignedVarInt(((MultiRecipe) recipe).getNetworkId()); + break; + case SHULKER_BOX: + break; + case SHAPELESS_CHEMISTRY: + break; + case SHAPED_CHEMISTRY: + break; + case REPAIR: + break; + case CAMPFIRE: + break; + case CAMPFIRE_DATA: + break; + case SMITHING_TRANSFORM: + SmithingRecipe smithing = (SmithingRecipe) recipe; + this.putString(smithing.getRecipeId()); + this.putRecipeIngredient(Item.get(Item.AIR)); //template + this.putRecipeIngredient(smithing.getEquipment()); + this.putRecipeIngredient(smithing.getIngredient()); + this.putSlot(smithing.getResult(), true); + this.putString(CRAFTING_TAG_SMITHING_TABLE); + this.putUnsignedVarInt(smithing.getNetworkId()); break; } } @@ -159,5 +185,4 @@ public void encode() { public byte pid() { return NETWORK_ID; } - } diff --git a/src/main/java/cn/nukkit/network/protocol/CraftingEventPacket.java b/src/main/java/cn/nukkit/network/protocol/CraftingEventPacket.java index 54b351fe739..34e33085e53 100644 --- a/src/main/java/cn/nukkit/network/protocol/CraftingEventPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/CraftingEventPacket.java @@ -1,7 +1,7 @@ package cn.nukkit.network.protocol; + import cn.nukkit.item.Item; -import cn.nukkit.utils.BinaryStream; import lombok.ToString; import java.util.UUID; @@ -9,6 +9,7 @@ /** * @author Nukkit Project Team */ +@Deprecated @ToString public class CraftingEventPacket extends DataPacket { @@ -34,18 +35,26 @@ public void decode() { this.type = (int) this.getUnsignedVarInt(); this.id = this.getUUID(); - this.input = this.getArray(Item.class, BinaryStream::getSlot); - this.output = this.getArray(Item.class, BinaryStream::getSlot); + int inputSize = (int) this.getUnsignedVarInt(); + this.input = new Item[Math.min(inputSize, 128)]; + for (int i = 0; i < this.input.length; ++i) { + this.input[i] = this.getSlot(); + } + + int outputSize = (int) this.getUnsignedVarInt(); + this.output = new Item[Math.min(outputSize, 128)]; + for (int i = 0; i < this.output.length; ++i) { + this.output[i] = this.getSlot(); + } } @Override public void encode() { - + this.encodeUnsupported(); } @Override public byte pid() { return NETWORK_ID; } - } diff --git a/src/main/java/cn/nukkit/network/protocol/CreativeContentPacket.java b/src/main/java/cn/nukkit/network/protocol/CreativeContentPacket.java index efc9847b8a2..a2649a36157 100644 --- a/src/main/java/cn/nukkit/network/protocol/CreativeContentPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/CreativeContentPacket.java @@ -5,9 +5,10 @@ @ToString public class CreativeContentPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.CREATIVE_CONTENT_PACKET; - public Item[] entries = new Item[0]; + public Item[] entries; @Override public byte pid() { @@ -16,16 +17,17 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override public void encode() { this.reset(); this.putUnsignedVarInt(entries.length); - for (int i = 0; i < entries.length; i++) { - this.putUnsignedVarInt(i + 1); - this.putSlot(entries[i], true); + int i = 1; //HACK around since 0 is not indexed by client + for (Item entry : entries) { + this.putUnsignedVarInt(i++); + this.putSlot(entry, true); } } } diff --git a/src/main/java/cn/nukkit/network/protocol/DataPacket.java b/src/main/java/cn/nukkit/network/protocol/DataPacket.java index 3bebf44a984..2d9852bd083 100644 --- a/src/main/java/cn/nukkit/network/protocol/DataPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/DataPacket.java @@ -1,20 +1,18 @@ package cn.nukkit.network.protocol; +import cn.nukkit.Nukkit; import cn.nukkit.Server; -import cn.nukkit.network.Network; import cn.nukkit.utils.BinaryStream; -import com.nukkitx.network.raknet.RakNetReliability; +import cn.nukkit.utils.SnappyCompression; +import cn.nukkit.utils.Zlib; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class DataPacket extends BinaryStream implements Cloneable { public volatile boolean isEncoded = false; - private int channel = 0; - - public RakNetReliability reliability = RakNetReliability.RELIABLE_ORDERED; public abstract byte pid(); @@ -43,14 +41,6 @@ public DataPacket reset() { return this; } - public void setChannel(int channel) { - this.channel = channel; - } - - public int getChannel() { - return channel; - } - public DataPacket clean() { this.setBuffer(null); this.setOffset(0); @@ -72,20 +62,38 @@ public DataPacket clone() { } public BatchPacket compress() { - return compress(Server.getInstance().networkCompressionLevel); + return this.compress(Server.getInstance().networkCompressionLevel); } public BatchPacket compress(int level) { - BinaryStream stream = new BinaryStream(); byte[] buf = this.getBuffer(); + BinaryStream stream = new BinaryStream(new byte[5 + buf.length]).reset(); stream.putUnsignedVarInt(buf.length); stream.put(buf); try { + byte[] bytes = stream.getBuffer(); BatchPacket batched = new BatchPacket(); - batched.payload = Network.deflateRaw(stream.getBuffer(), level); + if (Server.getInstance().useSnappy) { + batched.payload = SnappyCompression.compress(bytes); + } else { + batched.payload = Zlib.deflateRaw(bytes, level); + } return batched; } catch (Exception e) { throw new RuntimeException(e); } } + + void decodeUnsupported() { + if (Nukkit.DEBUG > 1) { + Server.getInstance().getLogger().debug("Warning: decode() not implemented for " + this.getClass().getName()); + } + } + + void encodeUnsupported() { + if (Nukkit.DEBUG > 1) { + Server.getInstance().getLogger().debug("Warning: encode() not implemented for " + this.getClass().getName()); + Thread.dumpStack(); + } + } } diff --git a/src/main/java/cn/nukkit/network/protocol/DeathInfoPacket.java b/src/main/java/cn/nukkit/network/protocol/DeathInfoPacket.java index 092347e01dd..74e1ba3111f 100644 --- a/src/main/java/cn/nukkit/network/protocol/DeathInfoPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/DeathInfoPacket.java @@ -14,6 +14,7 @@ public byte pid() { @Override public void decode() { + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/DebugInfoPacket.java b/src/main/java/cn/nukkit/network/protocol/DebugInfoPacket.java index a5bb7aecdf4..9bcb6d535df 100644 --- a/src/main/java/cn/nukkit/network/protocol/DebugInfoPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/DebugInfoPacket.java @@ -1,9 +1,7 @@ package cn.nukkit.network.protocol; -import lombok.ToString; - -@ToString public class DebugInfoPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.DEBUG_INFO_PACKET; public long entityId; diff --git a/src/main/java/cn/nukkit/network/protocol/DimensionDataPacket.java b/src/main/java/cn/nukkit/network/protocol/DimensionDataPacket.java new file mode 100644 index 00000000000..1e2407ff3eb --- /dev/null +++ b/src/main/java/cn/nukkit/network/protocol/DimensionDataPacket.java @@ -0,0 +1,36 @@ +package cn.nukkit.network.protocol; + +import cn.nukkit.network.protocol.types.DimensionDefinition; +import lombok.ToString; + +import java.util.List; + +@ToString +public class DimensionDataPacket extends DataPacket { + + public static final byte NETWORK_ID = ProtocolInfo.DIMENSION_DATA_PACKET; + + public List definitions; + + @Override + public byte pid() { + return NETWORK_ID; + } + + @Override + public void decode() { + this.decodeUnsupported(); + } + + @Override + public void encode() { + this.reset(); + this.putUnsignedVarInt(definitions.size()); + for (DimensionDefinition definition : definitions) { + this.putString(definition.getId()); + this.putVarInt(definition.getMaximumHeight()); + this.putVarInt(definition.getMinimumHeight()); + this.putVarInt(definition.getGeneratorType()); + } + } +} diff --git a/src/main/java/cn/nukkit/network/protocol/DisconnectPacket.java b/src/main/java/cn/nukkit/network/protocol/DisconnectPacket.java index f690b9e69e7..3ba15c4341e 100644 --- a/src/main/java/cn/nukkit/network/protocol/DisconnectPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/DisconnectPacket.java @@ -2,9 +2,6 @@ import lombok.ToString; -/** - * Created by on 15-10-12. - */ @ToString public class DisconnectPacket extends DataPacket { diff --git a/src/main/java/cn/nukkit/network/protocol/EmoteListPacket.java b/src/main/java/cn/nukkit/network/protocol/EmoteListPacket.java index ba49ea4c280..0c0884bab72 100644 --- a/src/main/java/cn/nukkit/network/protocol/EmoteListPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/EmoteListPacket.java @@ -8,6 +8,7 @@ @ToString public class EmoteListPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.EMOTE_LIST_PACKET; public long runtimeId; @@ -22,6 +23,9 @@ public byte pid() { public void decode() { this.runtimeId = this.getEntityRuntimeId(); int size = (int) this.getUnsignedVarInt(); + if (size > 1000) { + throw new RuntimeException("Too big EmoteListPacket: " + size); + } for (int i = 0; i < size; i++) { UUID id = this.getUUID(); pieceIds.add(id); diff --git a/src/main/java/cn/nukkit/network/protocol/EmotePacket.java b/src/main/java/cn/nukkit/network/protocol/EmotePacket.java index 87a3c525d4d..d580180ada0 100644 --- a/src/main/java/cn/nukkit/network/protocol/EmotePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/EmotePacket.java @@ -4,10 +4,15 @@ @ToString public class EmotePacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.EMOTE_PACKET; + + public static final byte FLAG_SERVER = 1; + public static final byte FLAG_MUTE_ANNOUNCEMENT = 2; + public long runtimeId; - public String xuid; - public String platformId; + public String xuid = ""; + public String platformId = ""; public String emoteID; public byte flags; public long emoteTicks; diff --git a/src/main/java/cn/nukkit/network/protocol/EntityEventPacket.java b/src/main/java/cn/nukkit/network/protocol/EntityEventPacket.java index 6fccf347d67..cbde32c5b6a 100644 --- a/src/main/java/cn/nukkit/network/protocol/EntityEventPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/EntityEventPacket.java @@ -3,12 +3,13 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class EntityEventPacket extends DataPacket { - public static final int NETWORK_ID = ProtocolInfo.ENTITY_EVENT_PACKET; + + public static final byte NETWORK_ID = ProtocolInfo.ENTITY_EVENT_PACKET; public static final int JUMP = 1; public static final int HURT_ANIMATION = 2; @@ -49,9 +50,7 @@ public class EntityEventPacket extends DataPacket { public static final int ENDER_DRAGON_DEATH = 37; public static final int DUST_PARTICLES = 38; public static final int ARROW_SHAKE = 39; - public static final int EATING_ITEM = 57; - public static final int BABY_ANIMAL_FEED = 60; public static final int DEATH_SMOKE_CLOUD = 61; public static final int COMPLETE_TRADE = 62; @@ -79,7 +78,7 @@ public byte pid() { public long eid; public int event; - public int data; + public int data = 0; @Override public void decode() { diff --git a/src/main/java/cn/nukkit/network/protocol/EntityFallPacket.java b/src/main/java/cn/nukkit/network/protocol/EntityFallPacket.java index 611002c32a9..104d4b5875b 100644 --- a/src/main/java/cn/nukkit/network/protocol/EntityFallPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/EntityFallPacket.java @@ -2,24 +2,26 @@ import lombok.ToString; +@Deprecated @ToString public class EntityFallPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.ENTITY_FALL_PACKET; public long eid; public float fallDistance; - public boolean unknown; + public boolean isInVoid; @Override public void decode() { this.eid = this.getEntityRuntimeId(); this.fallDistance = this.getLFloat(); - this.unknown = this.getBoolean(); + this.isInVoid = this.getBoolean(); } @Override public void encode() { - + this.encodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/EntityPickRequestPacket.java b/src/main/java/cn/nukkit/network/protocol/EntityPickRequestPacket.java index 952e9f12a59..8e7c8ce22ab 100644 --- a/src/main/java/cn/nukkit/network/protocol/EntityPickRequestPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/EntityPickRequestPacket.java @@ -14,11 +14,11 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override public void encode() { - //TODO + this.encodeUnsupported(); } } diff --git a/src/main/java/cn/nukkit/network/protocol/EventPacket.java b/src/main/java/cn/nukkit/network/protocol/EventPacket.java index 03f044e97dc..58130b3165d 100644 --- a/src/main/java/cn/nukkit/network/protocol/EventPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/EventPacket.java @@ -5,22 +5,50 @@ @ToString public class EventPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.EVENT_PACKET; + public long eid; - public int unknown1; - public byte unknown2; + public int eventData; + public byte eventType; + + public static final int TYPE_ACHIEVEMENT_AWARDED = 0; + public static final int TYPE_ENTITY_INTERACT = 1; + public static final int TYPE_PORTAL_BUILT = 2; + public static final int TYPE_PORTAL_USED = 3; + public static final int TYPE_MOB_KILLED = 4; + public static final int TYPE_CAULDRON_USED = 5; + public static final int TYPE_PLAYER_DEATH = 6; + public static final int TYPE_BOSS_KILLED = 7; + public static final int TYPE_AGENT_COMMAND = 8; + public static final int TYPE_AGENT_CREATED = 9; + public static final int TYPE_PATTERN_REMOVED = 10; + public static final int TYPE_COMMANED_EXECUTED = 11; + public static final int TYPE_FISH_BUCKETED = 12; + public static final int TYPE_MOB_BORN = 13; + public static final int TYPE_PET_DIED = 14; + public static final int TYPE_CAULDRON_BLOCK_USED = 15; + public static final int TYPE_COMPOSTER_BLOCK_USED = 16; + public static final int TYPE_BELL_BLOCK_USED = 17; + public static final int TYPE_ACTOR_DEFINITION = 18; + public static final int TYPE_RAID_UPDATE = 19; + public static final int TYPE_PLAYER_MOVEMENT_ANOMALY = 20; + public static final int TYPE_PLAYER_MOVEMENT_CORRECTED = 21; + public static final int TYPE_HONEY_HARVESTED = 22; + public static final int TYPE_TARGET_BLOCK_HIT = 23; + public static final int TYPE_PIGLIN_BARTER = 24; @Override public byte pid() { - return ProtocolInfo.EVENT_PACKET; + return NETWORK_ID; } @Override public void decode() { - + this.decodeUnsupported(); } @Override public void encode() { - + this.encodeUnsupported(); } } diff --git a/src/main/java/cn/nukkit/network/protocol/GUIDataPickItemPacket.java b/src/main/java/cn/nukkit/network/protocol/GUIDataPickItemPacket.java index 5458b3167f3..2a77b7ab1ef 100644 --- a/src/main/java/cn/nukkit/network/protocol/GUIDataPickItemPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/GUIDataPickItemPacket.java @@ -5,11 +5,13 @@ @ToString public class GUIDataPickItemPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.GUI_DATA_PICK_ITEM_PACKET; + public int hotbarSlot; @Override public byte pid() { - return ProtocolInfo.GUI_DATA_PICK_ITEM_PACKET; + return NETWORK_ID; } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/GameRulesChangedPacket.java b/src/main/java/cn/nukkit/network/protocol/GameRulesChangedPacket.java index bb4216829a6..5c5c2995361 100644 --- a/src/main/java/cn/nukkit/network/protocol/GameRulesChangedPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/GameRulesChangedPacket.java @@ -1,14 +1,18 @@ package cn.nukkit.network.protocol; +import cn.nukkit.level.GameRule; import cn.nukkit.level.GameRules; import lombok.ToString; +import java.util.Map; + /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class GameRulesChangedPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.GAME_RULES_CHANGED_PACKET; @Override @@ -17,14 +21,20 @@ public byte pid() { } public GameRules gameRules; + public Map gameRulesMap; @Override public void decode() { + this.decodeUnsupported(); } @Override public void encode() { this.reset(); - putGameRules(gameRules); + if (gameRulesMap == null) { // For compatibility + putGameRules(gameRules); + } else { + putGameRulesMap(gameRulesMap); + } } } diff --git a/src/main/java/cn/nukkit/network/protocol/HurtArmorPacket.java b/src/main/java/cn/nukkit/network/protocol/HurtArmorPacket.java index 0622bfecf49..4387c1ea6e0 100644 --- a/src/main/java/cn/nukkit/network/protocol/HurtArmorPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/HurtArmorPacket.java @@ -16,7 +16,7 @@ public class HurtArmorPacket extends DataPacket { @Override public void decode() { - + this.decodeUnsupported(); } @Override @@ -31,5 +31,4 @@ public void encode() { public byte pid() { return NETWORK_ID; } - } diff --git a/src/main/java/cn/nukkit/network/protocol/InitiateWebSocketConnectionPacket.java b/src/main/java/cn/nukkit/network/protocol/InitiateWebSocketConnectionPacket.java index 242a46a7c96..2d39fc4610b 100644 --- a/src/main/java/cn/nukkit/network/protocol/InitiateWebSocketConnectionPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/InitiateWebSocketConnectionPacket.java @@ -5,18 +5,20 @@ @ToString public class InitiateWebSocketConnectionPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.INITIATE_WEB_SOCKET_CONNECTION_PACKET; + @Override public byte pid() { - return ProtocolInfo.INITIATE_WEB_SOCKET_CONNECTION_PACKET; + return NETWORK_ID; } @Override public void decode() { - + this.decodeUnsupported(); } @Override public void encode() { - //TODO + this.encodeUnsupported(); } } diff --git a/src/main/java/cn/nukkit/network/protocol/InteractPacket.java b/src/main/java/cn/nukkit/network/protocol/InteractPacket.java index 5587ece9e5e..b56f32d12f8 100644 --- a/src/main/java/cn/nukkit/network/protocol/InteractPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/InteractPacket.java @@ -2,9 +2,6 @@ import lombok.ToString; -/** - * Created on 15-10-15. - */ @ToString public class InteractPacket extends DataPacket { @@ -12,16 +9,24 @@ public class InteractPacket extends DataPacket { public static final int ACTION_VEHICLE_EXIT = 3; public static final int ACTION_MOUSEOVER = 4; - + public static final int ACTION_OPEN_NPC = 5; public static final int ACTION_OPEN_INVENTORY = 6; public int action; public long target; + float x; + float y; + float z; @Override public void decode() { this.action = this.getByte(); this.target = this.getEntityRuntimeId(); + if (this.action == ACTION_MOUSEOVER || this.action == ACTION_VEHICLE_EXIT) { + this.x = this.getFloat(); + this.y = this.getFloat(); + this.z = this.getFloat(); + } } @Override @@ -35,5 +40,4 @@ public void encode() { public byte pid() { return NETWORK_ID; } - } diff --git a/src/main/java/cn/nukkit/network/protocol/InventoryContentPacket.java b/src/main/java/cn/nukkit/network/protocol/InventoryContentPacket.java index b7b6f248c22..376f89252cb 100644 --- a/src/main/java/cn/nukkit/network/protocol/InventoryContentPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/InventoryContentPacket.java @@ -4,11 +4,12 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class InventoryContentPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.INVENTORY_CONTENT_PACKET; @Override @@ -26,6 +27,7 @@ public byte pid() { private static final Item EMPTY_STORAGE_ITEM = Item.get(Item.AIR); public int inventoryId; + public int networkId; public Item[] slots = new Item[0]; @Override @@ -36,7 +38,7 @@ public DataPacket clean() { @Override public void decode() { - + this.decodeUnsupported(); } @Override @@ -51,11 +53,4 @@ public void encode() { this.putBoolean(false); // fullContainerName.optional.present this.putSlot(EMPTY_STORAGE_ITEM); } - - @Override - public InventoryContentPacket clone() { - InventoryContentPacket pk = (InventoryContentPacket) super.clone(); - pk.slots = this.slots.clone(); - return pk; - } } diff --git a/src/main/java/cn/nukkit/network/protocol/InventorySlotPacket.java b/src/main/java/cn/nukkit/network/protocol/InventorySlotPacket.java index 5a456e9c643..29a14e0fa03 100644 --- a/src/main/java/cn/nukkit/network/protocol/InventorySlotPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/InventorySlotPacket.java @@ -4,7 +4,7 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString @@ -25,6 +25,7 @@ public byte pid() { @Override public void decode() { + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/InventoryTransactionPacket.java b/src/main/java/cn/nukkit/network/protocol/InventoryTransactionPacket.java index cb07bd343b7..7af1b5aae7e 100644 --- a/src/main/java/cn/nukkit/network/protocol/InventoryTransactionPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/InventoryTransactionPacket.java @@ -4,15 +4,15 @@ import cn.nukkit.inventory.transaction.data.TransactionData; import cn.nukkit.inventory.transaction.data.UseItemData; import cn.nukkit.inventory.transaction.data.UseItemOnEntityData; +import cn.nukkit.math.Vector3; import cn.nukkit.network.protocol.types.NetworkInventoryAction; import lombok.ToString; -import java.util.ArrayDeque; -import java.util.Collection; - @ToString public class InventoryTransactionPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.INVENTORY_TRANSACTION_PACKET; + public static final int TYPE_NORMAL = 0; public static final int TYPE_MISMATCH = 1; public static final int TYPE_USE_ITEM = 2; @@ -39,6 +39,7 @@ public class InventoryTransactionPacket extends DataPacket { public int transactionType; public NetworkInventoryAction[] actions; public TransactionData transactionData; + public boolean hasNetworkIds = false; public int legacyRequestId; /** @@ -51,16 +52,19 @@ public class InventoryTransactionPacket extends DataPacket { @Override public byte pid() { - return ProtocolInfo.INVENTORY_TRANSACTION_PACKET; + return NETWORK_ID; } @Override public void encode() { this.reset(); + this.putVarInt(this.legacyRequestId); - //TODO legacySlot array + this.putUnsignedVarInt(this.transactionType); + this.putBoolean(this.hasNetworkIds); this.putUnsignedVarInt(this.actions.length); + for (NetworkInventoryAction action : this.actions) { action.write(this); } @@ -111,22 +115,23 @@ public void decode() { this.legacyRequestId = this.getVarInt(); if (legacyRequestId < -1 && (legacyRequestId & 1) == 0) { int length = (int) this.getUnsignedVarInt(); + if (length > 4096) { + throw new RuntimeException("Too many inventory transactions in one packet"); + } + for (int i = 0; i < length; i++) { this.getByte(); int bufLen = (int) this.getUnsignedVarInt(); this.get(bufLen); } - } this.transactionType = (int) this.getUnsignedVarInt(); - int length = (int) this.getUnsignedVarInt(); - Collection actions = new ArrayDeque<>(); - for (int i = 0; i < length; i++) { - actions.add(new NetworkInventoryAction().read(this)); + this.actions = new NetworkInventoryAction[Math.min((int) this.getUnsignedVarInt(), 4096)]; + for (int i = 0; i < this.actions.length; i++) { + this.actions[i] = new NetworkInventoryAction().read(this); } - this.actions = actions.toArray(new NetworkInventoryAction[0]); switch (this.transactionType) { case TYPE_NORMAL: @@ -142,7 +147,7 @@ public void decode() { itemData.face = this.getBlockFace(); itemData.hotbarSlot = this.getVarInt(); itemData.itemInHand = this.getSlot(); - itemData.playerPos = this.getVector3f().asVector3(); + itemData.playerPos = this.getVector3fAsVector3(); itemData.clickPos = this.getVector3f(); itemData.blockRuntimeId = (int) this.getUnsignedVarInt(); itemData.clientInteractPrediction = (int) this.getUnsignedVarInt(); @@ -156,8 +161,8 @@ public void decode() { useItemOnEntityData.actionType = (int) this.getUnsignedVarInt(); useItemOnEntityData.hotbarSlot = this.getVarInt(); useItemOnEntityData.itemInHand = this.getSlot(); - useItemOnEntityData.playerPos = this.getVector3f().asVector3(); - useItemOnEntityData.clickPos = this.getVector3f().asVector3(); + useItemOnEntityData.playerPos = this.getVector3fAsVector3(); + useItemOnEntityData.clickPos = this.getVector3fAsVector3(); this.transactionData = useItemOnEntityData; break; @@ -166,8 +171,8 @@ public void decode() { releaseItemData.actionType = (int) getUnsignedVarInt(); releaseItemData.hotbarSlot = getVarInt(); - releaseItemData.itemInHand = getSlot(); - releaseItemData.headRot = this.getVector3f().asVector3(); + releaseItemData.itemInHand = this.getSlot(); + releaseItemData.headRot = this.getVector3fAsVector3(); this.transactionData = releaseItemData; break; @@ -175,4 +180,8 @@ public void decode() { throw new RuntimeException("Unknown transaction type " + this.transactionType); } } + + private Vector3 getVector3fAsVector3() { + return new Vector3(this.getLFloat(), this.getLFloat(), this.getLFloat()); + } } diff --git a/src/main/java/cn/nukkit/network/protocol/ItemComponentPacket.java b/src/main/java/cn/nukkit/network/protocol/ItemComponentPacket.java new file mode 100644 index 00000000000..635ffe7c20e --- /dev/null +++ b/src/main/java/cn/nukkit/network/protocol/ItemComponentPacket.java @@ -0,0 +1,41 @@ +package cn.nukkit.network.protocol; + +import cn.nukkit.item.custom.ItemDefinition; +import cn.nukkit.nbt.NBTIO; +import lombok.ToString; + +import java.io.IOException; +import java.nio.ByteOrder; +import java.util.List; + +@ToString +public class ItemComponentPacket extends DataPacket { + + public static final byte NETWORK_ID = ProtocolInfo.ITEM_COMPONENT_PACKET; + + public List itemDefinitions; + + @Override + public byte pid() { + return NETWORK_ID; + } + + @Override + public void decode() { + this.decodeUnsupported(); + } + + @Override + public void encode() { + this.reset(); + this.putUnsignedVarInt(this.itemDefinitions.size()); + for (ItemDefinition definition : this.itemDefinitions) { + this.putString(definition.getIdentifier()); + try { + this.put(NBTIO.write(definition.getNetworkData(), ByteOrder.LITTLE_ENDIAN, true)); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } +} diff --git a/src/main/java/cn/nukkit/network/protocol/ItemFrameDropItemPacket.java b/src/main/java/cn/nukkit/network/protocol/ItemFrameDropItemPacket.java index c6d75c543d2..d1619c75a20 100644 --- a/src/main/java/cn/nukkit/network/protocol/ItemFrameDropItemPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ItemFrameDropItemPacket.java @@ -6,6 +6,7 @@ /** * Created by Pub4Game on 03.07.2016. */ +@Deprecated @ToString public class ItemFrameDropItemPacket extends DataPacket { @@ -25,7 +26,7 @@ public void decode() { @Override public void encode() { - + this.encodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/ItemStackRequestPacket.java b/src/main/java/cn/nukkit/network/protocol/ItemStackRequestPacket.java deleted file mode 100644 index 998e6bfc5f0..00000000000 --- a/src/main/java/cn/nukkit/network/protocol/ItemStackRequestPacket.java +++ /dev/null @@ -1,103 +0,0 @@ -package cn.nukkit.network.protocol; - -import cn.nukkit.item.Item; -import lombok.Value; - -import java.util.ArrayList; -import java.util.List; -import java.util.StringJoiner; - -public class ItemStackRequestPacket extends DataPacket { - public final List requests = new ArrayList<>(); - - @Override - public byte pid() { - return ProtocolInfo.ITEM_STACK_REQUEST_PACKET; - } - - @Override - public void decode() { - - } - - @Override - public void encode() { - - } - - @Value - public static class Request { - private final int requestId; - private final List actions; - } - - @Value - public static class ItemStackAction { - private final byte type; - private final boolean bool0; - private final byte byte0; - private final int varInt0; - private final int varInt1; - private final byte baseByte0; - private final byte baseByte1; - private final byte baseByte2; - private final int baseVarInt0; - private final byte flagsByte0; - private final byte flagsByte1; - private final int flagsVarInt0; - private final List items; - - @Override - public String toString() { - StringJoiner joiner = new StringJoiner(", "); - joiner.add("type=" + type); - - switch (type) { - case 0: - case 1: - case 2: - joiner.add("baseByte0=" + baseByte0) - .add("baseByte1=" + baseByte1) - .add("baseByte2=" + baseByte2) - .add("baseVarInt0=" + baseVarInt0) - .add("flagsByte0=" + flagsByte0) - .add("flagsByte1=" + flagsByte1) - .add("flagsVarInt0=" + flagsVarInt0); - break; - case 3: - joiner.add("bool0=" + bool0) - .add("baseByte0=" + baseByte0) - .add("baseByte1=" + baseByte1) - .add("baseByte2=" + baseByte2) - .add("baseVarInt0=" + baseVarInt0); - break; - case 4: - case 5: - joiner.add("baseByte0=" + baseByte0) - .add("baseByte1=" + baseByte1) - .add("baseByte2=" + baseByte2) - .add("baseVarInt0=" + baseVarInt0); - break; - case 6: - joiner.add("byte0=" + byte0); - break; - case 8: - joiner.add("varInt0=" + varInt0) - .add("varInt1=" + varInt1); - break; - case 10: - case 11: - case 12: - case 13: - case 14: - case 15: - joiner.add("varInt0=" + varInt0); - break; - case 17: - joiner.add("items=" + items); - break; - } - return "ItemStackAction(" + joiner.toString() + ")"; - } - } -} diff --git a/src/main/java/cn/nukkit/network/protocol/LecternUpdatePacket.java b/src/main/java/cn/nukkit/network/protocol/LecternUpdatePacket.java index c2819021295..a61aae31c7d 100644 --- a/src/main/java/cn/nukkit/network/protocol/LecternUpdatePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/LecternUpdatePacket.java @@ -11,6 +11,7 @@ public class LecternUpdatePacket extends DataPacket { public int page; public int totalPages; public BlockVector3 blockPosition; + public boolean dropBook; @Override public byte pid() { @@ -26,5 +27,6 @@ public void decode() { @Override public void encode() { + this.encodeUnsupported(); } } diff --git a/src/main/java/cn/nukkit/network/protocol/LevelChunkPacket.java b/src/main/java/cn/nukkit/network/protocol/LevelChunkPacket.java index 7b4119ba94d..20fa7b4b447 100644 --- a/src/main/java/cn/nukkit/network/protocol/LevelChunkPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/LevelChunkPacket.java @@ -3,11 +3,12 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString(exclude = "data") public class LevelChunkPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.FULL_CHUNK_DATA_PACKET; @Override @@ -27,7 +28,7 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override @@ -44,11 +45,9 @@ public void encode() { this.putUnsignedVarInt(-2); this.putUnsignedVarInt(this.subChunkLimit); } - this.putBoolean(cacheEnabled); if (this.cacheEnabled) { this.putUnsignedVarInt(blobIds.length); - for (long blobId : blobIds) { this.putLLong(blobId); } diff --git a/src/main/java/cn/nukkit/network/protocol/LevelEventGenericPacket.java b/src/main/java/cn/nukkit/network/protocol/LevelEventGenericPacket.java index 557ae35e63f..b91b4968b09 100644 --- a/src/main/java/cn/nukkit/network/protocol/LevelEventGenericPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/LevelEventGenericPacket.java @@ -2,11 +2,14 @@ import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.CompoundTag; +import lombok.ToString; import java.io.IOException; import java.nio.ByteOrder; +@ToString public class LevelEventGenericPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.LEVEL_EVENT_GENERIC_PACKET; public int eventId; @@ -19,6 +22,7 @@ public byte pid() { @Override public void decode() { + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/LevelEventPacket.java b/src/main/java/cn/nukkit/network/protocol/LevelEventPacket.java index eb99ca5c00b..8146b91e396 100644 --- a/src/main/java/cn/nukkit/network/protocol/LevelEventPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/LevelEventPacket.java @@ -1,14 +1,14 @@ package cn.nukkit.network.protocol; -import cn.nukkit.math.Vector3f; import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class LevelEventPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.LEVEL_EVENT_PACKET; public static final int EVENT_SOUND_CLICK = 1000; @@ -152,12 +152,7 @@ public byte pid() { @Override public void decode() { - this.evid = this.getVarInt(); - Vector3f v = this.getVector3f(); - this.x = v.x; - this.y = v.y; - this.z = v.z; - this.data = this.getVarInt(); + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/LevelSoundEventPacket.java b/src/main/java/cn/nukkit/network/protocol/LevelSoundEventPacket.java index aacc612af67..8d4672f8161 100644 --- a/src/main/java/cn/nukkit/network/protocol/LevelSoundEventPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/LevelSoundEventPacket.java @@ -5,6 +5,7 @@ @ToString public class LevelSoundEventPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.LEVEL_SOUND_EVENT_PACKET; public static final int SOUND_ITEM_USE_ON = 0; @@ -120,7 +121,7 @@ public class LevelSoundEventPacket extends DataPacket { public static final int SOUND_RECORD_WARD = 110; public static final int SOUND_RECORD_11 = 111; public static final int SOUND_RECORD_WAIT = 112; - public static final int SOUND_STOP_RECORD = 113; //Not really a sound + public static final int SOUND_STOP_RECORD = 113; public static final int SOUND_GUARDIAN_FLOP = 114; public static final int SOUND_ELDERGUARDIAN_CURSE = 115; public static final int SOUND_MOB_WARNING = 116; @@ -430,7 +431,6 @@ public class LevelSoundEventPacket extends DataPacket { public static final int SOUND_GOAT_BASS_7 = 420; public static final int SOUND_GOAT_BASS_8 = 421; public static final int SOUND_GOAT_BASS_9 = 422; - public static final int SOUND_IMITATE_WARDEN = 426; public static final int SOUND_LISTENING_ANGRY = 427; public static final int SOUND_ITEM_GIVEN = 428; @@ -448,7 +448,6 @@ public class LevelSoundEventPacket extends DataPacket { public static final int SOUND_CONVERT_TO_FROG = 440; public static final int SOUND_RECORD_PLAYING = 441; public static final int SOUND_ENCHANTING_TABLE_USE = 442; - public static final int SOUND_PRESSURE_PLATE_CLICK_OFF = 448; public static final int SOUND_PRESSURE_PLATE_CLICK_ON = 449; public static final int SOUND_BUTTON_CLICK_OFF = 450; @@ -480,6 +479,13 @@ public class LevelSoundEventPacket extends DataPacket { public static final int SOUND_AMBIENT_UNDERWATER_EXIT = 476; public static final int SOUND_BOTTLE_FILL = 477; public static final int SOUND_BOTTLE_EMPTY = 478; + public static final int SOUND_CRAFTER_CRAFT = 479; + public static final int SOUND_CRAFTER_FAILED = 480; + public static final int SOUND_CRAFTER_DISABLE_SLOT = 481; + public static final int SOUND_DECORATED_POT_INSERT = 482; + public static final int SOUND_DECORATED_POT_INSERT_FAILED = 483; + public static final int SOUND_COPPER_BULB_ON = 490; + public static final int SOUND_COPPER_BULB_OFF = 491; public int sound; public float x; @@ -518,4 +524,4 @@ public void encode() { public byte pid() { return NETWORK_ID; } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/network/protocol/LevelSoundEventPacketV1.java b/src/main/java/cn/nukkit/network/protocol/LevelSoundEventPacketV1.java index e3729f51989..6c56245c67d 100644 --- a/src/main/java/cn/nukkit/network/protocol/LevelSoundEventPacketV1.java +++ b/src/main/java/cn/nukkit/network/protocol/LevelSoundEventPacketV1.java @@ -6,14 +6,15 @@ @ToString public class LevelSoundEventPacketV1 extends LevelSoundEventPacket { + public static final byte NETWORK_ID = ProtocolInfo.LEVEL_SOUND_EVENT_PACKET_V1; public int sound; public float x; public float y; public float z; - public int extraData = -1; //TODO: Check name - public int pitch = 1; //TODO: Check name + public int extraData = -1; + public int pitch = 1; public boolean isBabyMob; public boolean isGlobal; diff --git a/src/main/java/cn/nukkit/network/protocol/LevelSoundEventPacketV2.java b/src/main/java/cn/nukkit/network/protocol/LevelSoundEventPacketV2.java index 7e3bc64a1b6..30955fea20d 100644 --- a/src/main/java/cn/nukkit/network/protocol/LevelSoundEventPacketV2.java +++ b/src/main/java/cn/nukkit/network/protocol/LevelSoundEventPacketV2.java @@ -5,6 +5,7 @@ @ToString public class LevelSoundEventPacketV2 extends LevelSoundEventPacket { + public static final byte NETWORK_ID = ProtocolInfo.LEVEL_SOUND_EVENT_PACKET_V2; public int sound; diff --git a/src/main/java/cn/nukkit/network/protocol/LoginPacket.java b/src/main/java/cn/nukkit/network/protocol/LoginPacket.java index 78023e86943..12d01564784 100644 --- a/src/main/java/cn/nukkit/network/protocol/LoginPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/LoginPacket.java @@ -1,5 +1,6 @@ package cn.nukkit.network.protocol; +import cn.nukkit.Server; import cn.nukkit.entity.data.Skin; import cn.nukkit.utils.*; import com.google.gson.Gson; @@ -11,21 +12,19 @@ import java.nio.charset.StandardCharsets; import java.util.*; - -/** - * Created by on 15-10-13. - */ @ToString public class LoginPacket extends DataPacket { public static final byte NETWORK_ID = ProtocolInfo.LOGIN_PACKET; public String username; - public int protocol; + private int protocol_; public UUID clientUUID; public long clientId; public Skin skin; + private static final Gson GSON = new Gson(); + @Override public byte pid() { return NETWORK_ID; @@ -33,47 +32,42 @@ public byte pid() { @Override public void decode() { - this.protocol = this.getInt(); - if (protocol == 0) { + this.protocol_ = this.getInt(); + if (this.protocol_ == 0) { setOffset(getOffset() + 2); - this.protocol = getInt(); + this.protocol_ = getInt(); } - if (!ProtocolInfo.SUPPORTED_PROTOCOLS.contains(protocol)) { - // decoding the chain could cause issues on newer or older versions. - return; + if (ProtocolInfo.SUPPORTED_PROTOCOLS.contains(this.protocol_)) { // Avoid errors with unsupported versions + this.setBuffer(this.getByteArray(), 0); + decodeChainData(); + decodeSkinData(); } - - this.setBuffer(this.getByteArray(), 0); - decodeChainData(); - decodeSkinData(); } @Override public void encode() { - + this.encodeUnsupported(); } public int getProtocol() { - return protocol; + return protocol_; } - private static final Gson GSON = new Gson(); - private void decodeChainData() { int size = this.getLInt(); - if (size > 52428800) { - throw new IllegalArgumentException(this.username + ": Chain data too big: " + size); + if (size > 3145728) { + throw new IllegalArgumentException("The chain data is too big: " + size); } String data = new String(this.get(size), StandardCharsets.UTF_8); - Map> map = GSON.fromJson(data, - new TypeToken>>() { - }.getType()); + + Map> map = GSON.fromJson(data, new MapTypeToken().getType()); if (map.isEmpty() || !map.containsKey("chain") || map.get("chain").isEmpty()) return; - List chains = map.get("chain"); - for (String c : chains) { + + for (String c : map.get("chain")) { JsonObject chainMap = ClientChainData.decodeToken(c); if (chainMap == null) continue; + if (chainMap.has("extraData")) { JsonObject extra = chainMap.get("extraData").getAsJsonObject(); if (extra.has("displayName")) this.username = extra.get("displayName").getAsString(); @@ -85,81 +79,104 @@ private void decodeChainData() { private void decodeSkinData() { int size = this.getLInt(); if (size > 52428800) { - throw new IllegalArgumentException(this.username + ": Skin data too big: " + size); + Server.getInstance().getLogger().warning(username + ": The skin data is too big: " + size); + return; // Get disconnected due to "invalid skin" } JsonObject skinToken = ClientChainData.decodeToken(new String(this.get(size), StandardCharsets.UTF_8)); if (skinToken == null) throw new RuntimeException("Invalid null skin token"); - if (skinToken.has("ClientRandomId")) this.clientId = skinToken.get("ClientRandomId").getAsLong(); + if (skinToken.has("ClientRandomId")) { + this.clientId = skinToken.get("ClientRandomId").getAsLong(); + } skin = new Skin(); skin.setTrusted(false); // Don't trust player skins if (skinToken.has("SkinId")) { skin.setSkinId(skinToken.get("SkinId").getAsString()); + } else { + skin.setSkinId(UUID.randomUUID().toString()); } skin.setFullSkinId(skin.getSkinId()); - if (skinToken.has("PlayFabId")) { - skin.setPlayFabId(skinToken.get("PlayFabId").getAsString()); - } + if (protocol_ < 388) { + if (skinToken.has("SkinData")) { + skin.setSkinData(Base64.getDecoder().decode(skinToken.get("SkinData").getAsString())); + } - if (skinToken.has("CapeId")) { - skin.setCapeId(skinToken.get("CapeId").getAsString()); - } + if (skinToken.has("CapeData")) { + skin.setCapeData(Base64.getDecoder().decode(skinToken.get("CapeData").getAsString())); + } - skin.setSkinData(getImage(skinToken, "Skin")); - skin.setCapeData(getImage(skinToken, "Cape")); + if (skinToken.has("SkinGeometryName")) { + skin.setGeometryName(skinToken.get("SkinGeometryName").getAsString()); + } - if (skinToken.has("PremiumSkin")) { - skin.setPremium(skinToken.get("PremiumSkin").getAsBoolean()); - } + if (skinToken.has("SkinGeometry")) { + skin.setGeometryData(new String(Base64.getDecoder().decode(skinToken.get("SkinGeometry").getAsString()), StandardCharsets.UTF_8)); + } + } else { + if (skinToken.has("PlayFabId")) { + skin.setPlayFabId(skinToken.get("PlayFabId").getAsString()); + } - if (skinToken.has("PersonaSkin")) { - skin.setPersona(skinToken.get("PersonaSkin").getAsBoolean()); - } + if (skinToken.has("CapeId")) { + skin.setCapeId(skinToken.get("CapeId").getAsString()); + } - if (skinToken.has("CapeOnClassicSkin")) { - skin.setCapeOnClassic(skinToken.get("CapeOnClassicSkin").getAsBoolean()); - } + skin.setSkinData(getImage(skinToken, "Skin")); + skin.setCapeData(getImage(skinToken, "Cape")); - if (skinToken.has("SkinResourcePatch")) { - skin.setSkinResourcePatch(new String(Base64.getDecoder().decode(skinToken.get("SkinResourcePatch").getAsString()), StandardCharsets.UTF_8)); - } + if (skinToken.has("PremiumSkin")) { + skin.setPremium(skinToken.get("PremiumSkin").getAsBoolean()); + } - if (skinToken.has("SkinGeometryData")) { - skin.setGeometryData(new String(Base64.getDecoder().decode(skinToken.get("SkinGeometryData").getAsString()), StandardCharsets.UTF_8)); - } + if (skinToken.has("PersonaSkin")) { + skin.setPersona(skinToken.get("PersonaSkin").getAsBoolean()); + } - if (skinToken.has("SkinAnimationData")) { - skin.setAnimationData(new String(Base64.getDecoder().decode(skinToken.get("SkinAnimationData").getAsString()), StandardCharsets.UTF_8)); - } + if (skinToken.has("CapeOnClassicSkin")) { + skin.setCapeOnClassic(skinToken.get("CapeOnClassicSkin").getAsBoolean()); + } - if (skinToken.has("AnimatedImageData")) { - for (JsonElement element : skinToken.get("AnimatedImageData").getAsJsonArray()) { - skin.getAnimations().add(getAnimation(element.getAsJsonObject())); + if (skinToken.has("SkinResourcePatch")) { + skin.setSkinResourcePatch(new String(Base64.getDecoder().decode(skinToken.get("SkinResourcePatch").getAsString()), StandardCharsets.UTF_8)); } - } - if (skinToken.has("SkinColor")) { - skin.setSkinColor(skinToken.get("SkinColor").getAsString()); - } + if (skinToken.has("SkinGeometryData")) { + skin.setGeometryData(new String(Base64.getDecoder().decode(skinToken.get("SkinGeometryData").getAsString()), StandardCharsets.UTF_8)); + } - if (skinToken.has("ArmSize")) { - skin.setArmSize(skinToken.get("ArmSize").getAsString()); - } + if (skinToken.has("SkinAnimationData")) { + skin.setAnimationData(new String(Base64.getDecoder().decode(skinToken.get("SkinAnimationData").getAsString()), StandardCharsets.UTF_8)); + } - if (skinToken.has("PersonaPieces")) { - for (JsonElement object : skinToken.get("PersonaPieces").getAsJsonArray()) { - skin.getPersonaPieces().add(getPersonaPiece(object.getAsJsonObject())); + if (skinToken.has("AnimatedImageData")) { + for (JsonElement element : skinToken.get("AnimatedImageData").getAsJsonArray()) { + skin.getAnimations().add(getAnimation(element.getAsJsonObject())); + } + } + + if (skinToken.has("SkinColor")) { + skin.setSkinColor(skinToken.get("SkinColor").getAsString()); + } + + if (skinToken.has("ArmSize")) { + skin.setArmSize(skinToken.get("ArmSize").getAsString()); + } + + if (skinToken.has("PersonaPieces")) { + for (JsonElement object : skinToken.get("PersonaPieces").getAsJsonArray()) { + skin.getPersonaPieces().add(getPersonaPiece(object.getAsJsonObject())); + } } - } - if (skinToken.has("PieceTintColors")) { - for (JsonElement object : skinToken.get("PieceTintColors").getAsJsonArray()) { - skin.getTintColors().add(getTint(object.getAsJsonObject())); + if (skinToken.has("PieceTintColors")) { + for (JsonElement object : skinToken.get("PieceTintColors").getAsJsonArray()) { + skin.getTintColors().add(getTint(object.getAsJsonObject())); + } } } } @@ -205,4 +222,7 @@ public static PersonaPieceTint getTint(JsonObject object) { } return new PersonaPieceTint(pieceType, colors); } -} + + private static class MapTypeToken extends TypeToken>> { + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/network/protocol/MapCreateLockedCopyPacket.java b/src/main/java/cn/nukkit/network/protocol/MapCreateLockedCopyPacket.java index 792e0997215..91cc5fbfbe9 100644 --- a/src/main/java/cn/nukkit/network/protocol/MapCreateLockedCopyPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/MapCreateLockedCopyPacket.java @@ -1,13 +1,18 @@ package cn.nukkit.network.protocol; +import lombok.ToString; + +@ToString public class MapCreateLockedCopyPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.MAP_CREATE_LOCKED_COPY_PACKET; + public long originalMapId; public long newMapId; @Override public byte pid() { - return ProtocolInfo.MAP_CREATE_LOCKED_COPY_PACKET; + return NETWORK_ID; } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/MapInfoRequestPacket.java b/src/main/java/cn/nukkit/network/protocol/MapInfoRequestPacket.java index e1e42c5b27b..f8a26077865 100644 --- a/src/main/java/cn/nukkit/network/protocol/MapInfoRequestPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/MapInfoRequestPacket.java @@ -7,11 +7,14 @@ */ @ToString public class MapInfoRequestPacket extends DataPacket { + + public static final byte NETWORK_ID = ProtocolInfo.MAP_INFO_REQUEST_PACKET; + public long mapId; @Override public byte pid() { - return ProtocolInfo.MAP_INFO_REQUEST_PACKET; + return NETWORK_ID; } @Override @@ -21,6 +24,6 @@ public void decode() { @Override public void encode() { - + this.encodeUnsupported(); } } diff --git a/src/main/java/cn/nukkit/network/protocol/MobArmorEquipmentPacket.java b/src/main/java/cn/nukkit/network/protocol/MobArmorEquipmentPacket.java index 300dd49568f..f0c18a3cf39 100644 --- a/src/main/java/cn/nukkit/network/protocol/MobArmorEquipmentPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/MobArmorEquipmentPacket.java @@ -4,11 +4,12 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class MobArmorEquipmentPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.MOB_ARMOR_EQUIPMENT_PACKET; @Override diff --git a/src/main/java/cn/nukkit/network/protocol/MobEffectPacket.java b/src/main/java/cn/nukkit/network/protocol/MobEffectPacket.java index cdc1430c29f..42d279be769 100644 --- a/src/main/java/cn/nukkit/network/protocol/MobEffectPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/MobEffectPacket.java @@ -3,7 +3,7 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString @@ -30,7 +30,7 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/MobEquipmentPacket.java b/src/main/java/cn/nukkit/network/protocol/MobEquipmentPacket.java index 826ec1ee572..361ac146a08 100644 --- a/src/main/java/cn/nukkit/network/protocol/MobEquipmentPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/MobEquipmentPacket.java @@ -4,11 +4,12 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class MobEquipmentPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.MOB_EQUIPMENT_PACKET; @Override @@ -24,7 +25,7 @@ public byte pid() { @Override public void decode() { - this.eid = this.getEntityRuntimeId(); //EntityRuntimeID + this.eid = this.getEntityRuntimeId(); this.item = this.getSlot(); this.inventorySlot = this.getByte(); this.hotbarSlot = this.getByte(); @@ -34,7 +35,7 @@ public void decode() { @Override public void encode() { this.reset(); - this.putEntityRuntimeId(this.eid); //EntityRuntimeID + this.putEntityRuntimeId(this.eid); this.putSlot(this.item); this.putByte((byte) this.inventorySlot); this.putByte((byte) this.hotbarSlot); diff --git a/src/main/java/cn/nukkit/network/protocol/ModalFormRequestPacket.java b/src/main/java/cn/nukkit/network/protocol/ModalFormRequestPacket.java index 72da652e6a9..5592e608b86 100644 --- a/src/main/java/cn/nukkit/network/protocol/ModalFormRequestPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ModalFormRequestPacket.java @@ -5,17 +5,19 @@ @ToString public class ModalFormRequestPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.MODAL_FORM_REQUEST_PACKET; + public int formId; public String data; @Override public byte pid() { - return ProtocolInfo.MODAL_FORM_REQUEST_PACKET; + return NETWORK_ID; } @Override public void decode() { - + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/ModalFormResponsePacket.java b/src/main/java/cn/nukkit/network/protocol/ModalFormResponsePacket.java index eae893fdc0f..5bf8c657425 100644 --- a/src/main/java/cn/nukkit/network/protocol/ModalFormResponsePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ModalFormResponsePacket.java @@ -5,13 +5,15 @@ @ToString public class ModalFormResponsePacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.MODAL_FORM_RESPONSE_PACKET; + public int formId; public String data = "null"; public int cancelReason; @Override public byte pid() { - return ProtocolInfo.MODAL_FORM_RESPONSE_PACKET; + return NETWORK_ID; } @Override @@ -27,6 +29,6 @@ public void decode() { @Override public void encode() { - + this.encodeUnsupported(); } } diff --git a/src/main/java/cn/nukkit/network/protocol/MoveEntityAbsolutePacket.java b/src/main/java/cn/nukkit/network/protocol/MoveEntityAbsolutePacket.java index 9ce410cf137..e0c25b10395 100644 --- a/src/main/java/cn/nukkit/network/protocol/MoveEntityAbsolutePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/MoveEntityAbsolutePacket.java @@ -4,11 +4,12 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class MoveEntityAbsolutePacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.MOVE_ENTITY_ABSOLUTE_PACKET; public long eid; diff --git a/src/main/java/cn/nukkit/network/protocol/MoveEntityDeltaPacket.java b/src/main/java/cn/nukkit/network/protocol/MoveEntityDeltaPacket.java index 4e728b64a42..373ccf6dc38 100644 --- a/src/main/java/cn/nukkit/network/protocol/MoveEntityDeltaPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/MoveEntityDeltaPacket.java @@ -4,26 +4,24 @@ @ToString public class MoveEntityDeltaPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.MOVE_ENTITY_DELTA_PACKET; - public static final int FLAG_HAS_X = 0B1; - public static final int FLAG_HAS_Y = 0B10; - public static final int FLAG_HAS_Z = 0B100; - public static final int FLAG_HAS_PITCH = 0B1000; - public static final int FLAG_HAS_YAW = 0B10000; - public static final int FLAG_HAS_HEAD_YAW = 0B100000; - public static final int FLAG_ON_GROUND = 0B1000000; - public static final int FLAG_TELEPORTING = 0B10000000; - public static final int FLAG_FORCE_MOVE_LOCAL_ENTITY = 0B100000000; + public static final int FLAG_HAS_X = 0b1; + public static final int FLAG_HAS_Y = 0b10; + public static final int FLAG_HAS_Z = 0b100; + public static final int FLAG_HAS_YAW = 0b1000; + public static final int FLAG_HAS_HEAD_YAW = 0b10000; + public static final int FLAG_HAS_PITCH = 0b100000; - public long runtimeEntityId; + public long eid; public int flags = 0; public float x = 0; public float y = 0; public float z = 0; - public float pitch = 0; - public float yaw = 0; - public float headYaw = 0; + public double yawDelta = 0; + public double headYawDelta = 0; + public double pitchDelta = 0; @Override public byte pid() { @@ -32,70 +30,31 @@ public byte pid() { @Override public void decode() { - this.runtimeEntityId = this.getEntityRuntimeId(); - this.flags = this.getByte(); - if ((this.flags & FLAG_HAS_X) != 0) { - this.x = this.getCoordinate(); - } - if ((this.flags & FLAG_HAS_Y) != 0) { - this.y = this.getCoordinate(); - } - if ((this.flags & FLAG_HAS_Z) != 0) { - this.z = this.getCoordinate(); - } - if ((this.flags & FLAG_HAS_PITCH) != 0) { - this.pitch = this.getRotation(); - } - if ((this.flags & FLAG_HAS_YAW) != 0) { - this.yaw = this.getRotation(); - } - if ((this.flags & FLAG_HAS_HEAD_YAW) != 0) { - this.headYaw = this.getRotation(); - } + this.decodeUnsupported(); } @Override public void encode() { this.reset(); - this.putEntityRuntimeId(this.runtimeEntityId); - this.putLShort(this.flags); - if ((this.flags & FLAG_HAS_X) != 0) { - this.putCoordinate(this.x); - } - if ((this.flags & FLAG_HAS_Y) != 0) { - this.putCoordinate(this.y); - } - if ((this.flags & FLAG_HAS_Z) != 0) { - this.putCoordinate(this.z); - } - if ((this.flags & FLAG_HAS_PITCH) != 0) { - this.putRotation(this.pitch); - } - if ((this.flags & FLAG_HAS_YAW) != 0) { - this.putRotation(this.yaw); - } - if ((this.flags & FLAG_HAS_HEAD_YAW) != 0) { - this.putRotation(this.headYaw); - } - } - - private float getCoordinate() { - return this.getLFloat(); - } - - private void putCoordinate(float value) { - this.putLFloat(value); - } - - private float getRotation() { - return this.getByte() * (360F / 256F); + this.putEntityRuntimeId(this.eid); + this.putByte((byte) flags); + putCoordinate(FLAG_HAS_X, this.x); + putCoordinate(FLAG_HAS_Y, this.y); + putCoordinate(FLAG_HAS_Z, this.z); + putRotation(FLAG_HAS_YAW, this.yawDelta); + putRotation(FLAG_HAS_HEAD_YAW, this.headYawDelta); + putRotation(FLAG_HAS_PITCH, this.pitchDelta); } - private void putRotation(float value) { - this.putByte((byte) (value / (360F / 256F))); + private void putCoordinate(int flag, float value) { + if ((flags & flag) != 0) { + this.putLFloat(value); + } } - public boolean hasFlag(int flag) { - return (this.flags & flag) != 0; + private void putRotation(int flag, double value) { + if ((flags & flag) != 0) { + this.putByte((byte) (value / 1.40625)); + } } } diff --git a/src/main/java/cn/nukkit/network/protocol/MovePlayerPacket.java b/src/main/java/cn/nukkit/network/protocol/MovePlayerPacket.java index e8d4a50c9fc..62432bc7237 100644 --- a/src/main/java/cn/nukkit/network/protocol/MovePlayerPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/MovePlayerPacket.java @@ -3,9 +3,6 @@ import cn.nukkit.math.Vector3f; import lombok.ToString; -/** - * Created on 15-10-14. - */ @ToString public class MovePlayerPacket extends DataPacket { @@ -14,7 +11,7 @@ public class MovePlayerPacket extends DataPacket { public static final int MODE_NORMAL = 0; public static final int MODE_RESET = 1; public static final int MODE_TELEPORT = 2; - public static final int MODE_PITCH = 3; //facepalm Mojang + public static final int MODE_PITCH = 3; public long eid; public float x; @@ -26,8 +23,8 @@ public class MovePlayerPacket extends DataPacket { public int mode = MODE_NORMAL; public boolean onGround; public long ridingEid; - public int int1 = 0; - public int int2 = 0; + public int teleportCause = 0; + public int teleportItem = 0; public long frame; @Override @@ -44,8 +41,8 @@ public void decode() { this.onGround = this.getBoolean(); this.ridingEid = this.getEntityRuntimeId(); if (this.mode == MODE_TELEPORT) { - this.int1 = this.getLInt(); - this.int2 = this.getLInt(); + this.teleportCause = this.getLInt(); + this.teleportItem = this.getLInt(); } this.frame = this.getUnsignedVarLong(); } @@ -62,8 +59,8 @@ public void encode() { this.putBoolean(this.onGround); this.putEntityRuntimeId(this.ridingEid); if (this.mode == MODE_TELEPORT) { - this.putLInt(this.int1); - this.putLInt(this.int2); + this.putLInt(this.teleportCause); + this.putLInt(this.teleportItem); } this.putUnsignedVarLong(this.frame); } @@ -72,5 +69,4 @@ public void encode() { public byte pid() { return NETWORK_ID; } - } diff --git a/src/main/java/cn/nukkit/network/protocol/NPCRequestPacket.java b/src/main/java/cn/nukkit/network/protocol/NPCRequestPacket.java index 21b498a526f..79123e147d5 100644 --- a/src/main/java/cn/nukkit/network/protocol/NPCRequestPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/NPCRequestPacket.java @@ -5,30 +5,27 @@ @ToString public class NPCRequestPacket extends DataPacket { - public long entityRuntimeId; + public static final byte NETWORK_ID = ProtocolInfo.NPC_REQUEST_PACKET; + public long entityRuntimeId; public RequestType requestType; - public String commandString; - public int actionType; - public String sceneName; public enum RequestType { - SET_ACTIONS, EXECUTE_ACTION, EXECUTE_CLOSING_COMMANDS, SET_NAME, SET_SKIN, - SET_INTERACTION_TEXT - + SET_INTERACTION_TEXT, + EXECUTE_OPENING_COMMANDS } @Override public byte pid() { - return ProtocolInfo.NPC_REQUEST_PACKET; + return NETWORK_ID; } @Override @@ -42,6 +39,7 @@ public void decode() { @Override public void encode() { + this.reset(); this.putEntityRuntimeId(this.entityRuntimeId); this.putByte((byte) requestType.ordinal()); this.putString(this.commandString); diff --git a/src/main/java/cn/nukkit/network/protocol/NetworkChunkPublisherUpdatePacket.java b/src/main/java/cn/nukkit/network/protocol/NetworkChunkPublisherUpdatePacket.java index 2e0fbf75f8d..51547a101ba 100644 --- a/src/main/java/cn/nukkit/network/protocol/NetworkChunkPublisherUpdatePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/NetworkChunkPublisherUpdatePacket.java @@ -6,18 +6,19 @@ @ToString public class NetworkChunkPublisherUpdatePacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.NETWORK_CHUNK_PUBLISHER_UPDATE_PACKET; + public BlockVector3 position; public int radius; @Override public byte pid() { - return ProtocolInfo.NETWORK_CHUNK_PUBLISHER_UPDATE_PACKET; + return NETWORK_ID; } @Override public void decode() { - this.position = this.getSignedBlockPosition(); - this.radius = (int) this.getUnsignedVarInt(); + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/NetworkSettingsPacket.java b/src/main/java/cn/nukkit/network/protocol/NetworkSettingsPacket.java index 448315de4fe..ab7342c495b 100644 --- a/src/main/java/cn/nukkit/network/protocol/NetworkSettingsPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/NetworkSettingsPacket.java @@ -6,6 +6,8 @@ @ToString public class NetworkSettingsPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.NETWORK_SETTINGS_PACKET; + public int compressionThreshold; public PacketCompressionAlgorithm compressionAlgorithm; public boolean clientThrottleEnabled; @@ -14,7 +16,7 @@ public class NetworkSettingsPacket extends DataPacket { @Override public byte pid() { - return ProtocolInfo.NETWORK_SETTINGS_PACKET; + return NETWORK_ID; } @Override @@ -29,6 +31,6 @@ public void encode() { @Override public void decode() { - throw new UnsupportedOperationException(); + this.decodeUnsupported(); } } diff --git a/src/main/java/cn/nukkit/network/protocol/NetworkStackLatencyPacket.java b/src/main/java/cn/nukkit/network/protocol/NetworkStackLatencyPacket.java index 2491f0f0caf..5d09cf62dcf 100644 --- a/src/main/java/cn/nukkit/network/protocol/NetworkStackLatencyPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/NetworkStackLatencyPacket.java @@ -5,23 +5,26 @@ @ToString public class NetworkStackLatencyPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.NETWORK_STACK_LATENCY_PACKET; + public long timestamp; - public boolean unknownBool; + public boolean needResponse; @Override public byte pid() { - return ProtocolInfo.NETWORK_STACK_LATENCY_PACKET; + return NETWORK_ID; } @Override public void decode() { timestamp = this.getLLong(); + needResponse = this.getBoolean(); } @Override public void encode() { this.reset(); this.putLLong(timestamp); - this.putBoolean(unknownBool); + this.putBoolean(needResponse); } } diff --git a/src/main/java/cn/nukkit/network/protocol/NpcDialoguePacket.java b/src/main/java/cn/nukkit/network/protocol/NpcDialoguePacket.java new file mode 100644 index 00000000000..b44f9b1fa30 --- /dev/null +++ b/src/main/java/cn/nukkit/network/protocol/NpcDialoguePacket.java @@ -0,0 +1,40 @@ +package cn.nukkit.network.protocol; + +import lombok.ToString; + +@ToString +public class NpcDialoguePacket extends DataPacket { + + public static final byte NETWORK_ID = ProtocolInfo.NPC_DIALOGUE_PACKET; + + public static final int ACTION_OPEN = 0; + public static final int ACTION_CLOSE = 1; + + public long entityId; + public int actionType; + public String dialogue; + public String sceneName; + public String npcName; + public String actionJson; + + @Override + public byte pid() { + return NETWORK_ID; + } + + @Override + public void encode() { + this.reset(); + this.putLLong(this.entityId); + this.putVarInt(this.actionType); + this.putString(this.dialogue); + this.putString(this.sceneName); + this.putString(this.npcName); + this.putString(this.actionJson); + } + + @Override + public void decode() { + // Noop + } +} diff --git a/src/main/java/cn/nukkit/network/protocol/OnScreenTextureAnimationPacket.java b/src/main/java/cn/nukkit/network/protocol/OnScreenTextureAnimationPacket.java index fccbc9b3abf..a5559382a9d 100644 --- a/src/main/java/cn/nukkit/network/protocol/OnScreenTextureAnimationPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/OnScreenTextureAnimationPacket.java @@ -1,17 +1,22 @@ package cn.nukkit.network.protocol; +import lombok.ToString; + +@ToString public class OnScreenTextureAnimationPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.ON_SCREEN_TEXTURE_ANIMATION_PACKET; + public int effectId; @Override public byte pid() { - return ProtocolInfo.ON_SCREEN_TEXTURE_ANIMATION_PACKET; + return NETWORK_ID; } @Override public void decode() { - this.effectId = this.getLInt(); + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/OpenSignPacket.java b/src/main/java/cn/nukkit/network/protocol/OpenSignPacket.java index 71676db504c..1baf17507dc 100644 --- a/src/main/java/cn/nukkit/network/protocol/OpenSignPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/OpenSignPacket.java @@ -14,7 +14,7 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/PacketViolationWarningPacket.java b/src/main/java/cn/nukkit/network/protocol/PacketViolationWarningPacket.java index 3899fed58cb..d9cec0fb12c 100644 --- a/src/main/java/cn/nukkit/network/protocol/PacketViolationWarningPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/PacketViolationWarningPacket.java @@ -2,8 +2,11 @@ import lombok.ToString; +import java.nio.charset.StandardCharsets; + @ToString public class PacketViolationWarningPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.PACKET_VIOLATION_WARNING_PACKET; public PacketViolationType type; @@ -21,16 +24,23 @@ public void decode() { this.type = PacketViolationType.values()[this.getVarInt() + 1]; this.severity = PacketViolationSeverity.values()[this.getVarInt()]; this.packetId = this.getVarInt(); - this.context = this.getString(); + + // BinaryStream::getString() + int contextLength = (int) this.getUnsignedVarInt(); + String context; + + if (contextLength > 1024) { + context = "Context too long: " + contextLength; + } else { + context = new String(this.get(contextLength), StandardCharsets.UTF_8); + } + + this.context = context; } @Override public void encode() { - this.reset(); - this.putVarInt(this.type.ordinal() - 1); - this.putVarInt(this.severity.ordinal()); - this.putVarInt(this.packetId); - this.putString(this.context); + this.encodeUnsupported(); } public enum PacketViolationType { diff --git a/src/main/java/cn/nukkit/network/protocol/PlaySoundPacket.java b/src/main/java/cn/nukkit/network/protocol/PlaySoundPacket.java index 6ed137a5752..e685b3029cf 100644 --- a/src/main/java/cn/nukkit/network/protocol/PlaySoundPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/PlaySoundPacket.java @@ -21,14 +21,14 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override public void encode() { this.reset(); this.putString(this.name); - this.putBlockVector3(this.x * 8, this.y * 8, this.z * 8); + this.putBlockVector3(this.x << 3, this.y << 3, this.z << 3); this.putLFloat(this.volume); this.putLFloat(this.pitch); } diff --git a/src/main/java/cn/nukkit/network/protocol/PlayStatusPacket.java b/src/main/java/cn/nukkit/network/protocol/PlayStatusPacket.java index 0a58e25b2ca..0230a0eb745 100644 --- a/src/main/java/cn/nukkit/network/protocol/PlayStatusPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/PlayStatusPacket.java @@ -2,9 +2,6 @@ import lombok.ToString; -/** - * Created on 15-10-13. - */ @ToString public class PlayStatusPacket extends DataPacket { @@ -15,22 +12,52 @@ public byte pid() { return NETWORK_ID; } + /** + * Sent to confirm login success and move onto resource pack sequence + */ public static final int LOGIN_SUCCESS = 0; + /** + * Displays outdated client disconnection screen + */ public static final int LOGIN_FAILED_CLIENT = 1; + /** + * Displays outdated server disconnection screen + */ public static final int LOGIN_FAILED_SERVER = 2; + /** + * Spawns player into the world + */ public static final int PLAYER_SPAWN = 3; + /** + * Unknown + */ public static final int LOGIN_FAILED_INVALID_TENANT = 4; + /** + * Sent when an Education Edition client joins a Bedrock Edition server + */ public static final int LOGIN_FAILED_VANILLA_EDU = 5; + /** + * Sent when a Bedrock Edition client joins an EducationEdition server + */ public static final int LOGIN_FAILED_EDU_VANILLA = 6; + /** + * Sent to a split screen player when the server is full + */ public static final int LOGIN_FAILED_SERVER_FULL = 7; + /** + * Unknown + */ public static final int LOGIN_FAILED_EDITOR_TO_VANILLA_MISMATCH = 8; + /** + * Unknown + */ public static final int LOGIN_FAILED_VANILLA_TO_EDITOR_MISMATCH = 9; public int status; @Override public void decode() { - + this.decodeUnsupported(); } @Override @@ -38,5 +65,4 @@ public void encode() { this.reset(); this.putInt(this.status); } - } diff --git a/src/main/java/cn/nukkit/network/protocol/PlayerActionPacket.java b/src/main/java/cn/nukkit/network/protocol/PlayerActionPacket.java index ffdacc5fc4e..01918a17cd8 100644 --- a/src/main/java/cn/nukkit/network/protocol/PlayerActionPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/PlayerActionPacket.java @@ -30,6 +30,7 @@ public class PlayerActionPacket extends DataPacket { public static final int ACTION_STOP_GLIDE = 16; public static final int ACTION_BUILD_DENIED = 17; public static final int ACTION_CONTINUE_BREAK = 18; + public static final int ACTION_CHANGE_SKIN = 19; public static final int ACTION_SET_ENCHANTMENT_SEED = 20; public static final int ACTION_START_SWIMMING = 21; public static final int ACTION_STOP_SWIMMING = 22; @@ -67,7 +68,11 @@ public void encode() { this.putEntityRuntimeId(this.entityId); this.putVarInt(this.action); this.putBlockVector3(this.x, this.y, this.z); - this.putBlockVector3(this.resultPosition); + if (this.resultPosition == null) { + this.putBlockVector3(new BlockVector3()); + } else { + this.putBlockVector3(this.resultPosition); + } this.putVarInt(this.face); } @@ -75,5 +80,4 @@ public void encode() { public byte pid() { return NETWORK_ID; } - } diff --git a/src/main/java/cn/nukkit/network/protocol/PlayerArmorDamagePacket.java b/src/main/java/cn/nukkit/network/protocol/PlayerArmorDamagePacket.java index a473339561b..7d12969c6ec 100644 --- a/src/main/java/cn/nukkit/network/protocol/PlayerArmorDamagePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/PlayerArmorDamagePacket.java @@ -7,6 +7,7 @@ @ToString public class PlayerArmorDamagePacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.PLAYER_ARMOR_DAMAGE_PACKET; public final Set flags = EnumSet.noneOf(PlayerArmorDamageFlag.class); @@ -19,13 +20,7 @@ public byte pid() { @Override public void decode() { - int flagsval = this.getByte(); - for (int i = 0; i < 4; i++) { - if ((flagsval & (1 << i)) != 0) { - this.flags.add(PlayerArmorDamageFlag.values()[i]); - this.damage[i] = this.getVarInt(); - } - } + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/PlayerAuthInputPacket.java b/src/main/java/cn/nukkit/network/protocol/PlayerAuthInputPacket.java index f90a7fdf02d..5c4bfeb23f5 100644 --- a/src/main/java/cn/nukkit/network/protocol/PlayerAuthInputPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/PlayerAuthInputPacket.java @@ -15,13 +15,14 @@ @ToString @Getter public class PlayerAuthInputPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.PLAYER_AUTH_INPUT_PACKET; private float yaw; private float pitch; private float headYaw; private Vector3f position; - private Vector2 motion; + private Vector2 motion; // Vector2 for backwards compatibility private final Set inputData = EnumSet.noneOf(AuthInputAction.class); private InputMode inputMode; private ClientPlayMode playMode; @@ -57,6 +58,7 @@ public void decode() { this.inputMode = InputMode.fromOrdinal((int) this.getUnsignedVarInt()); this.playMode = ClientPlayMode.fromOrdinal((int) this.getUnsignedVarInt()); + this.interactionModel = AuthInteractionModel.fromOrdinal((int) this.getUnsignedVarInt()); this.interactRotation = this.getVector2f(); @@ -94,6 +96,6 @@ public void decode() { @Override public void encode() { - // Noop + this.encodeUnsupported(); } } diff --git a/src/main/java/cn/nukkit/network/protocol/PlayerEnchantOptionsPacket.java b/src/main/java/cn/nukkit/network/protocol/PlayerEnchantOptionsPacket.java index a8eecd819c9..74fd2fd93e5 100644 --- a/src/main/java/cn/nukkit/network/protocol/PlayerEnchantOptionsPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/PlayerEnchantOptionsPacket.java @@ -1,6 +1,5 @@ package cn.nukkit.network.protocol; -import it.unimi.dsi.fastutil.objects.ObjectArrayList; import lombok.ToString; import lombok.Value; @@ -9,6 +8,7 @@ @ToString public class PlayerEnchantOptionsPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.PLAYER_ENCHANT_OPTIONS_PACKET; public final List options = new ArrayList<>(); @@ -20,36 +20,7 @@ public byte pid() { @Override public void decode() { - int size = (int) this.getUnsignedVarInt(); - for (int i = 0; i < size; i++) { - int minLevel = this.getVarInt(); - int slot = this.getInt(); - - int eSize = (int) this.getUnsignedVarInt(); - List list1 = new ObjectArrayList<>(); - for (int j = 0; j < eSize; j++) { - EnchantData data = new EnchantData(this.getByte(), this.getByte()); - list1.add(data); - } - - eSize = (int) this.getUnsignedVarInt(); - List list2 = new ObjectArrayList<>(); - for (int j = 0; j < eSize; j++) { - EnchantData data = new EnchantData(this.getByte(), this.getByte()); - list2.add(data); - } - - eSize = (int) this.getUnsignedVarInt(); - List list3 = new ObjectArrayList<>(); - for (int j = 0; j < eSize; j++) { - EnchantData data = new EnchantData(this.getByte(), this.getByte()); - list3.add(data); - } - String enchantName = this.getString(); - int eNetId = (int) this.getUnsignedVarInt(); - this.options.add(new EnchantOptionData(minLevel, slot, list1, list2, list3, enchantName, eNetId)); - } - + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/PlayerHotbarPacket.java b/src/main/java/cn/nukkit/network/protocol/PlayerHotbarPacket.java index c96bd8e6dd9..a1a1df5d3b6 100644 --- a/src/main/java/cn/nukkit/network/protocol/PlayerHotbarPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/PlayerHotbarPacket.java @@ -6,14 +6,15 @@ @ToString public class PlayerHotbarPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.PLAYER_HOTBAR_PACKET; + public int selectedHotbarSlot; public int windowId = ContainerIds.INVENTORY; - public boolean selectHotbarSlot = true; @Override public byte pid() { - return ProtocolInfo.PLAYER_HOTBAR_PACKET; + return NETWORK_ID; } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/PlayerInputPacket.java b/src/main/java/cn/nukkit/network/protocol/PlayerInputPacket.java index d6adb559d0a..bfcb8b3d627 100644 --- a/src/main/java/cn/nukkit/network/protocol/PlayerInputPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/PlayerInputPacket.java @@ -26,12 +26,11 @@ public void decode() { @Override public void encode() { - + this.encodeUnsupported(); } @Override public byte pid() { return NETWORK_ID; } - } diff --git a/src/main/java/cn/nukkit/network/protocol/PlayerListPacket.java b/src/main/java/cn/nukkit/network/protocol/PlayerListPacket.java index cea7d5c2f59..a9e09dfa742 100644 --- a/src/main/java/cn/nukkit/network/protocol/PlayerListPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/PlayerListPacket.java @@ -21,7 +21,7 @@ public class PlayerListPacket extends DataPacket { @Override public void decode() { - + this.decodeUnsupported(); } @Override @@ -29,25 +29,28 @@ public void encode() { this.reset(); this.putByte(this.type); this.putUnsignedVarInt(this.entries.length); - for (Entry entry : this.entries) { - this.putUUID(entry.uuid); - if (type == TYPE_ADD) { - this.putVarLong(entry.entityId); - this.putString(entry.name); - this.putString(entry.xboxUserId); - this.putString(entry.platformChatId); - this.putLInt(entry.buildPlatform); - this.putSkin(entry.skin); - this.putBoolean(entry.isTeacher); - this.putBoolean(entry.isHost); - this.putBoolean(entry.isSubClient); - } - } - - if (type == TYPE_ADD) { - for (Entry entry : this.entries) { - this.putBoolean(entry.skin.isTrusted()); - } + switch (type) { + case TYPE_ADD: + for (Entry entry : this.entries) { + this.putUUID(entry.uuid); + this.putVarLong(entry.entityId); + this.putString(entry.name); + this.putString(entry.xboxUserId); + this.putString(entry.platformChatId); + this.putLInt(entry.buildPlatform); + this.putSkin(entry.skin); + this.putBoolean(entry.isTeacher); + this.putBoolean(entry.isHost); + this.putBoolean(entry.isSubClient); + } + for (Entry entry : this.entries) { // WTF Mojang + this.putBoolean(entry.skin.isTrusted()); + } + break; + case TYPE_REMOVE: + for (Entry entry : this.entries) { + this.putUUID(entry.uuid); + } } } @@ -62,10 +65,10 @@ public static class Entry { public final UUID uuid; public long entityId = 0; public String name = ""; - public String xboxUserId = ""; //TODO - public String platformChatId = ""; //TODO - public int buildPlatform = -1; public Skin skin; + public String xboxUserId = ""; + public String platformChatId = ""; + public int buildPlatform = -1; public boolean isTeacher; public boolean isHost; public boolean isSubClient; @@ -86,5 +89,4 @@ public Entry(UUID uuid, long entityId, String name, Skin skin, String xboxUserId this.xboxUserId = xboxUserId == null ? "" : xboxUserId; } } - } diff --git a/src/main/java/cn/nukkit/network/protocol/PlayerSkinPacket.java b/src/main/java/cn/nukkit/network/protocol/PlayerSkinPacket.java index b93833b5a84..9b3232457b8 100644 --- a/src/main/java/cn/nukkit/network/protocol/PlayerSkinPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/PlayerSkinPacket.java @@ -8,14 +8,17 @@ @ToString public class PlayerSkinPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.PLAYER_SKIN_PACKET; + public UUID uuid; public Skin skin; public String newSkinName; public String oldSkinName; + public boolean premium; @Override public byte pid() { - return ProtocolInfo.PLAYER_SKIN_PACKET; + return NETWORK_ID; } @Override @@ -39,4 +42,4 @@ public void encode() { putString(oldSkinName); putBoolean(skin.isTrusted()); } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/network/protocol/PlayerStartItemCooldownPacket.java b/src/main/java/cn/nukkit/network/protocol/PlayerStartItemCooldownPacket.java new file mode 100644 index 00000000000..04b47655889 --- /dev/null +++ b/src/main/java/cn/nukkit/network/protocol/PlayerStartItemCooldownPacket.java @@ -0,0 +1,29 @@ +package cn.nukkit.network.protocol; + +import lombok.ToString; + +@ToString +public class PlayerStartItemCooldownPacket extends DataPacket { + + public static final byte NETWORK_ID = ProtocolInfo.PLAYER_START_ITEM_COOLDOWN_PACKET; + + public String itemCategory; + public int cooldownDuration; + + @Override + public byte pid() { + return NETWORK_ID; + } + + @Override + public void decode() { + this.decodeUnsupported(); + } + + @Override + public void encode() { + this.reset(); + this.putString(this.itemCategory); + this.putVarInt(this.cooldownDuration); + } +} diff --git a/src/main/java/cn/nukkit/network/protocol/ProtocolInfo.java b/src/main/java/cn/nukkit/network/protocol/ProtocolInfo.java index 638c1c1fc20..9586b3e1b04 100644 --- a/src/main/java/cn/nukkit/network/protocol/ProtocolInfo.java +++ b/src/main/java/cn/nukkit/network/protocol/ProtocolInfo.java @@ -5,13 +5,13 @@ import java.util.List; /** - * author: MagicDroidX & iNevet + * @author MagicDroidX & iNevet * Nukkit Project */ public interface ProtocolInfo { /** - * Actual Minecraft: PE protocol version + * Actual Minecraft protocol version */ @SuppressWarnings("UnnecessaryBoxing") int CURRENT_PROTOCOL = Integer.valueOf("748"); // DO NOT REMOVE BOXING @@ -136,7 +136,6 @@ public interface ProtocolInfo { byte SET_LOCAL_PLAYER_AS_INITIALIZED_PACKET = 0x71; byte UPDATE_SOFT_ENUM_PACKET = 0x72; byte NETWORK_STACK_LATENCY_PACKET = 0x73; - byte SCRIPT_CUSTOM_EVENT_PACKET = 0x75; byte SPAWN_PARTICLE_EFFECT_PACKET = 0x76; byte AVAILABLE_ENTITY_IDENTIFIERS_PACKET = 0x77; @@ -147,8 +146,8 @@ public interface ProtocolInfo { byte LEVEL_EVENT_GENERIC_PACKET = 0x7c; byte LECTERN_UPDATE_PACKET = 0x7d; byte VIDEO_STREAM_CONNECT_PACKET = 0x7e; - //byte ADD_ENTITY_PACKET = 0x7f; - //byte REMOVE_ENTITY_PACKET = 0x80; + byte ADD_ENTITY_PACKET_2 = 0x7f; + byte REMOVE_ENTITY_PACKET_2 = (byte) 0x80; byte CLIENT_CACHE_STATUS_PACKET = (byte) 0x81; byte ON_SCREEN_TEXTURE_ANIMATION_PACKET = (byte) 0x82; byte MAP_CREATE_LOCKED_COPY_PACKET = (byte) 0x83; @@ -219,7 +218,7 @@ public interface ProtocolInfo { byte UNLOCKED_RECIPES_PACKET = (byte) 0xc7; // MC packet IDs continue from 300 (0x12c) // Hack: 100 is added to the IDs below on encode - // TODO: New pid() function (int) while trying not to break too many plugins + // TODO: New pid() function (int) that calls the old one by default byte __INTERNAL__CAMERA_INSTRUCTION_PACKET = (byte) 200; byte __INTERNAL__COMPRESSED_BIOME_DEFINITIONS_LIST_PACKET = (byte) 201; byte __INTERNAL__TRIM_DATA_PACKET = (byte) 202; diff --git a/src/main/java/cn/nukkit/network/protocol/RemoveEntityPacket.java b/src/main/java/cn/nukkit/network/protocol/RemoveEntityPacket.java index 4c2faa91cac..0f74c3246e8 100644 --- a/src/main/java/cn/nukkit/network/protocol/RemoveEntityPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/RemoveEntityPacket.java @@ -3,11 +3,12 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class RemoveEntityPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.REMOVE_ENTITY_PACKET; public long eid; @@ -19,7 +20,7 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/RemoveObjectivePacket.java b/src/main/java/cn/nukkit/network/protocol/RemoveObjectivePacket.java index 6b7ceabb117..43dc9ead4a7 100644 --- a/src/main/java/cn/nukkit/network/protocol/RemoveObjectivePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/RemoveObjectivePacket.java @@ -16,6 +16,7 @@ public byte pid() { @Override public void decode() { + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/RequestAbilityPacket.java b/src/main/java/cn/nukkit/network/protocol/RequestAbilityPacket.java index 19ae4f9b81b..bbafa9e4003 100644 --- a/src/main/java/cn/nukkit/network/protocol/RequestAbilityPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/RequestAbilityPacket.java @@ -9,6 +9,9 @@ @Getter @Setter public class RequestAbilityPacket extends DataPacket { + + public static final byte NETWORK_ID = ProtocolInfo.REQUEST_ABILITY_PACKET; + protected static final PlayerAbility[] ABILITIES = UpdateAbilitiesPacket.VALID_FLAGS; protected static final AbilityType[] ABILITY_TYPES = AbilityType.values(); @@ -27,12 +30,12 @@ public void decode() { @Override public void encode() { - throw new UnsupportedOperationException(); + this.encodeUnsupported(); } @Override public byte pid() { - return ProtocolInfo.REQUEST_ABILITY_PACKET; + return NETWORK_ID; } public enum AbilityType { diff --git a/src/main/java/cn/nukkit/network/protocol/RequestChunkRadiusPacket.java b/src/main/java/cn/nukkit/network/protocol/RequestChunkRadiusPacket.java index f547e0dd6b7..9a9ec0358f0 100644 --- a/src/main/java/cn/nukkit/network/protocol/RequestChunkRadiusPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/RequestChunkRadiusPacket.java @@ -3,7 +3,7 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString @@ -22,12 +22,11 @@ public void decode() { @Override public void encode() { - + this.encodeUnsupported(); } @Override public byte pid() { return NETWORK_ID; } - } diff --git a/src/main/java/cn/nukkit/network/protocol/RequestNetworkSettingsPacket.java b/src/main/java/cn/nukkit/network/protocol/RequestNetworkSettingsPacket.java index 0c09ad2489a..6faea0a6b4d 100644 --- a/src/main/java/cn/nukkit/network/protocol/RequestNetworkSettingsPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/RequestNetworkSettingsPacket.java @@ -5,16 +5,18 @@ @ToString public class RequestNetworkSettingsPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.REQUEST_NETWORK_SETTINGS_PACKET; + public int protocolVersion; @Override public byte pid() { - return ProtocolInfo.REQUEST_NETWORK_SETTINGS_PACKET; + return NETWORK_ID; } @Override public void encode() { - throw new UnsupportedOperationException(); + this.encodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/RequestPermissionsPacket.java b/src/main/java/cn/nukkit/network/protocol/RequestPermissionsPacket.java new file mode 100644 index 00000000000..c963589b9f3 --- /dev/null +++ b/src/main/java/cn/nukkit/network/protocol/RequestPermissionsPacket.java @@ -0,0 +1,21 @@ +package cn.nukkit.network.protocol; + +public class RequestPermissionsPacket extends DataPacket { + + public static final byte NETWORK_ID = ProtocolInfo.REQUEST_PERMISSIONS_PACKET; + + @Override + public void decode() { + // TODO + } + + @Override + public void encode() { + this.encodeUnsupported(); + } + + @Override + public byte pid() { + return NETWORK_ID; + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/network/protocol/ResourcePackChunkDataPacket.java b/src/main/java/cn/nukkit/network/protocol/ResourcePackChunkDataPacket.java index 72232810409..a18c9cda865 100644 --- a/src/main/java/cn/nukkit/network/protocol/ResourcePackChunkDataPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ResourcePackChunkDataPacket.java @@ -16,10 +16,7 @@ public class ResourcePackChunkDataPacket extends DataPacket { @Override public void decode() { - this.packId = UUID.fromString(this.getString()); - this.chunkIndex = this.getLInt(); - this.progress = this.getLLong(); - this.data = this.getByteArray(); + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/ResourcePackClientResponsePacket.java b/src/main/java/cn/nukkit/network/protocol/ResourcePackClientResponsePacket.java index 5fc44e1fe3c..ad5aa00fe69 100644 --- a/src/main/java/cn/nukkit/network/protocol/ResourcePackClientResponsePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ResourcePackClientResponsePacket.java @@ -44,6 +44,7 @@ public byte pid() { @ToString public static class Entry { + public final UUID uuid; public final String version; diff --git a/src/main/java/cn/nukkit/network/protocol/ResourcePackDataInfoPacket.java b/src/main/java/cn/nukkit/network/protocol/ResourcePackDataInfoPacket.java index d1960c9ec2c..551c5a990bb 100644 --- a/src/main/java/cn/nukkit/network/protocol/ResourcePackDataInfoPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ResourcePackDataInfoPacket.java @@ -30,13 +30,7 @@ public class ResourcePackDataInfoPacket extends DataPacket { @Override public void decode() { - this.packId = UUID.fromString(this.getString()); - this.maxChunkSize = this.getLInt(); - this.chunkCount = this.getLInt(); - this.compressedPackSize = this.getLLong(); - this.sha256 = this.getByteArray(); - this.premium = this.getBoolean(); - this.type = this.getByte(); + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/ResourcePackStackPacket.java b/src/main/java/cn/nukkit/network/protocol/ResourcePackStackPacket.java index 7a7ea9d6968..a9714d1e905 100644 --- a/src/main/java/cn/nukkit/network/protocol/ResourcePackStackPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ResourcePackStackPacket.java @@ -1,46 +1,46 @@ package cn.nukkit.network.protocol; +import cn.nukkit.network.protocol.types.ExperimentData; import cn.nukkit.resourcepacks.ResourcePack; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; import lombok.ToString; +import java.util.List; + @ToString public class ResourcePackStackPacket extends DataPacket { public static final byte NETWORK_ID = ProtocolInfo.RESOURCE_PACK_STACK_PACKET; - public boolean mustAccept = false; + public boolean mustAccept; + public String gameVersion = ProtocolInfo.MINECRAFT_VERSION_NETWORK; public ResourcePack[] behaviourPackStack = ResourcePack.EMPTY_ARRAY; public ResourcePack[] resourcePackStack = ResourcePack.EMPTY_ARRAY; - public boolean isExperimental = false; - public String gameVersion = ProtocolInfo.MINECRAFT_VERSION_NETWORK; + public final List experiments = new ObjectArrayList<>(1); @Override public void decode() { - + this.decodeUnsupported(); } @Override public void encode() { this.reset(); this.putBoolean(this.mustAccept); - this.putUnsignedVarInt(this.behaviourPackStack.length); for (ResourcePack entry : this.behaviourPackStack) { this.putString(entry.getPackId().toString()); this.putString(entry.getPackVersion()); - this.putString(""); //TODO: subpack name + this.putString(""); } - this.putUnsignedVarInt(this.resourcePackStack.length); for (ResourcePack entry : this.resourcePackStack) { this.putString(entry.getPackId().toString()); this.putString(entry.getPackVersion()); - this.putString(""); //TODO: subpack name + this.putString(""); } - this.putString(this.gameVersion); - this.putLInt(0); // Experiments length - this.putBoolean(false); // Were experiments previously toggled + this.putExperiments(this.experiments); this.putBoolean(false); // Has editor packs } diff --git a/src/main/java/cn/nukkit/network/protocol/ResourcePacksInfoPacket.java b/src/main/java/cn/nukkit/network/protocol/ResourcePacksInfoPacket.java index bd81801f0df..07502f22e59 100644 --- a/src/main/java/cn/nukkit/network/protocol/ResourcePacksInfoPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ResourcePacksInfoPacket.java @@ -16,7 +16,7 @@ public class ResourcePacksInfoPacket extends DataPacket { @Override public void decode() { - + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/RespawnPacket.java b/src/main/java/cn/nukkit/network/protocol/RespawnPacket.java index 9cdc223ba94..fe6907e67b5 100644 --- a/src/main/java/cn/nukkit/network/protocol/RespawnPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/RespawnPacket.java @@ -43,5 +43,4 @@ public void encode() { public byte pid() { return NETWORK_ID; } - } diff --git a/src/main/java/cn/nukkit/network/protocol/RiderJumpPacket.java b/src/main/java/cn/nukkit/network/protocol/RiderJumpPacket.java index dff26bc18c6..d810349d489 100644 --- a/src/main/java/cn/nukkit/network/protocol/RiderJumpPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/RiderJumpPacket.java @@ -7,7 +7,7 @@ public class RiderJumpPacket extends DataPacket { public static final byte NETWORK_ID = ProtocolInfo.RIDER_JUMP_PACKET; - public int unknown; + public int jumpStrength; @Override public byte pid() { @@ -16,12 +16,12 @@ public byte pid() { @Override public void decode() { - this.unknown = this.getVarInt(); + this.jumpStrength = this.getVarInt(); } @Override public void encode() { this.reset(); - this.putVarInt(this.unknown); + this.putVarInt(this.jumpStrength); } } diff --git a/src/main/java/cn/nukkit/network/protocol/ScriptCustomEventPacket.java b/src/main/java/cn/nukkit/network/protocol/ScriptCustomEventPacket.java index f03ca85bebb..1dc114d97eb 100644 --- a/src/main/java/cn/nukkit/network/protocol/ScriptCustomEventPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ScriptCustomEventPacket.java @@ -2,15 +2,18 @@ import lombok.ToString; +@Deprecated @ToString public class ScriptCustomEventPacket extends DataPacket { - + + public static final byte NETWORK_ID = ProtocolInfo.SCRIPT_CUSTOM_EVENT_PACKET; + public String eventName; public byte[] eventData; @Override public byte pid() { - return ProtocolInfo.SCRIPT_CUSTOM_EVENT_PACKET; + return NETWORK_ID; } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/ServerSettingsRequestPacket.java b/src/main/java/cn/nukkit/network/protocol/ServerSettingsRequestPacket.java index 9e83cd1475f..8c9f8788263 100644 --- a/src/main/java/cn/nukkit/network/protocol/ServerSettingsRequestPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ServerSettingsRequestPacket.java @@ -5,18 +5,20 @@ @ToString public class ServerSettingsRequestPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.SERVER_SETTINGS_REQUEST_PACKET; + @Override public byte pid() { - return ProtocolInfo.SERVER_SETTINGS_REQUEST_PACKET; + return NETWORK_ID; } @Override public void decode() { - + // Nothing to decode } @Override public void encode() { - + this.encodeUnsupported(); } } diff --git a/src/main/java/cn/nukkit/network/protocol/ServerSettingsResponsePacket.java b/src/main/java/cn/nukkit/network/protocol/ServerSettingsResponsePacket.java index 640b592c400..b2bd5aad165 100644 --- a/src/main/java/cn/nukkit/network/protocol/ServerSettingsResponsePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ServerSettingsResponsePacket.java @@ -5,17 +5,19 @@ @ToString public class ServerSettingsResponsePacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.SERVER_SETTINGS_RESPONSE_PACKET; + public int formId; public String data; @Override public byte pid() { - return ProtocolInfo.SERVER_SETTINGS_RESPONSE_PACKET; + return NETWORK_ID; } @Override public void decode() { - + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/ServerToClientHandshakePacket.java b/src/main/java/cn/nukkit/network/protocol/ServerToClientHandshakePacket.java index edd3abbc4a8..d3f9801abd2 100644 --- a/src/main/java/cn/nukkit/network/protocol/ServerToClientHandshakePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ServerToClientHandshakePacket.java @@ -5,16 +5,18 @@ @ToString public class ServerToClientHandshakePacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.SERVER_TO_CLIENT_HANDSHAKE_PACKET; + @Override public byte pid() { - return ProtocolInfo.SERVER_TO_CLIENT_HANDSHAKE_PACKET; + return NETWORK_ID; } public String jwt; @Override public void decode() { - + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/SetCommandsEnabledPacket.java b/src/main/java/cn/nukkit/network/protocol/SetCommandsEnabledPacket.java index 98465c28836..d79c85368b4 100644 --- a/src/main/java/cn/nukkit/network/protocol/SetCommandsEnabledPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/SetCommandsEnabledPacket.java @@ -16,7 +16,7 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/SetDefaultGameTypePacket.java b/src/main/java/cn/nukkit/network/protocol/SetDefaultGameTypePacket.java new file mode 100644 index 00000000000..60889d2efe9 --- /dev/null +++ b/src/main/java/cn/nukkit/network/protocol/SetDefaultGameTypePacket.java @@ -0,0 +1,24 @@ +package cn.nukkit.network.protocol; + +public class SetDefaultGameTypePacket extends DataPacket { + + public static final byte NETWORK_ID = ProtocolInfo.SET_DEFAULT_GAME_TYPE_PACKET; + + public int gamemode; + + @Override + public void decode() { + this.gamemode = this.getVarInt(); + } + + @Override + public void encode() { + this.reset(); + this.putVarInt(this.gamemode); + } + + @Override + public byte pid() { + return NETWORK_ID; + } +} diff --git a/src/main/java/cn/nukkit/network/protocol/SetDifficultyPacket.java b/src/main/java/cn/nukkit/network/protocol/SetDifficultyPacket.java index ce1ac54b082..40eb48d2d31 100644 --- a/src/main/java/cn/nukkit/network/protocol/SetDifficultyPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/SetDifficultyPacket.java @@ -27,5 +27,4 @@ public void encode() { public byte pid() { return NETWORK_ID; } - } diff --git a/src/main/java/cn/nukkit/network/protocol/SetDisplayObjectivePacket.java b/src/main/java/cn/nukkit/network/protocol/SetDisplayObjectivePacket.java index 9956751e9df..37c10b7bf3f 100644 --- a/src/main/java/cn/nukkit/network/protocol/SetDisplayObjectivePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/SetDisplayObjectivePacket.java @@ -21,6 +21,7 @@ public byte pid() { @Override public void decode() { + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/SetEntityDataPacket.java b/src/main/java/cn/nukkit/network/protocol/SetEntityDataPacket.java index 318a9656cb8..67d5c4dc173 100644 --- a/src/main/java/cn/nukkit/network/protocol/SetEntityDataPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/SetEntityDataPacket.java @@ -5,11 +5,12 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class SetEntityDataPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.SET_ENTITY_DATA_PACKET; @Override @@ -23,7 +24,7 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/SetEntityLinkPacket.java b/src/main/java/cn/nukkit/network/protocol/SetEntityLinkPacket.java index 60dba261043..71fed7dfc7e 100644 --- a/src/main/java/cn/nukkit/network/protocol/SetEntityLinkPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/SetEntityLinkPacket.java @@ -2,9 +2,6 @@ import lombok.ToString; -/** - * Created on 15-10-22. - */ @ToString public class SetEntityLinkPacket extends DataPacket { @@ -14,8 +11,8 @@ public class SetEntityLinkPacket extends DataPacket { public static final byte TYPE_RIDE = 1; public static final byte TYPE_PASSENGER = 2; - public long vehicleUniqueId; //from - public long riderUniqueId; //to + public long vehicleUniqueId; + public long riderUniqueId; public byte type; public byte immediate; public boolean riderInitiated; @@ -23,7 +20,11 @@ public class SetEntityLinkPacket extends DataPacket { @Override public void decode() { - + this.vehicleUniqueId = this.getEntityUniqueId(); + this.riderUniqueId = this.getEntityUniqueId(); + this.type = (byte) this.getByte(); + this.immediate = (byte) this.getByte(); + this.riderInitiated = this.getBoolean(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/SetEntityMotionPacket.java b/src/main/java/cn/nukkit/network/protocol/SetEntityMotionPacket.java index c09d3be420d..ecdf74f7513 100644 --- a/src/main/java/cn/nukkit/network/protocol/SetEntityMotionPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/SetEntityMotionPacket.java @@ -3,11 +3,12 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class SetEntityMotionPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.SET_ENTITY_MOTION_PACKET; public long eid; @@ -23,7 +24,11 @@ public byte pid() { @Override public void decode() { - + this.eid = this.getEntityRuntimeId(); + this.motionX = this.getLFloat(); + this.motionY = this.getLFloat(); + this.motionZ = this.getLFloat(); + this.tick = this.getUnsignedVarLong(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/SetHealthPacket.java b/src/main/java/cn/nukkit/network/protocol/SetHealthPacket.java index 2972fede444..2b5ba7329ec 100644 --- a/src/main/java/cn/nukkit/network/protocol/SetHealthPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/SetHealthPacket.java @@ -16,7 +16,7 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/SetHudPacket.java b/src/main/java/cn/nukkit/network/protocol/SetHudPacket.java index 52af99108d1..cb9f9e50e04 100644 --- a/src/main/java/cn/nukkit/network/protocol/SetHudPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/SetHudPacket.java @@ -21,6 +21,7 @@ public byte pid() { @Override public void decode() { + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/SetLastHurtByPacket.java b/src/main/java/cn/nukkit/network/protocol/SetLastHurtByPacket.java index 8d55cf10cbc..c42f0cf1eba 100644 --- a/src/main/java/cn/nukkit/network/protocol/SetLastHurtByPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/SetLastHurtByPacket.java @@ -5,18 +5,20 @@ @ToString public class SetLastHurtByPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.SET_LAST_HURT_BY_PACKET; + @Override public byte pid() { - return ProtocolInfo.SET_LAST_HURT_BY_PACKET; + return NETWORK_ID; } @Override public void decode() { - + this.decodeUnsupported(); } @Override public void encode() { - //TODO + this.encodeUnsupported(); } } diff --git a/src/main/java/cn/nukkit/network/protocol/SetLocalPlayerAsInitializedPacket.java b/src/main/java/cn/nukkit/network/protocol/SetLocalPlayerAsInitializedPacket.java index 472e186941a..d5e8a6d7d0c 100644 --- a/src/main/java/cn/nukkit/network/protocol/SetLocalPlayerAsInitializedPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/SetLocalPlayerAsInitializedPacket.java @@ -4,6 +4,7 @@ @ToString public class SetLocalPlayerAsInitializedPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.SET_LOCAL_PLAYER_AS_INITIALIZED_PACKET; public long eid; @@ -15,11 +16,12 @@ public byte pid() { @Override public void decode() { - eid = this.getUnsignedVarLong(); + this.eid = this.getUnsignedVarLong(); } @Override public void encode() { + this.reset(); this.putUnsignedVarLong(eid); } } diff --git a/src/main/java/cn/nukkit/network/protocol/SetPlayerGameTypePacket.java b/src/main/java/cn/nukkit/network/protocol/SetPlayerGameTypePacket.java index 1ca96859525..9c363bbf5c3 100644 --- a/src/main/java/cn/nukkit/network/protocol/SetPlayerGameTypePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/SetPlayerGameTypePacket.java @@ -3,12 +3,13 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class SetPlayerGameTypePacket extends DataPacket { - public final static byte NETWORK_ID = ProtocolInfo.SET_PLAYER_GAME_TYPE_PACKET; + + public static final byte NETWORK_ID = ProtocolInfo.SET_PLAYER_GAME_TYPE_PACKET; @Override public byte pid() { diff --git a/src/main/java/cn/nukkit/network/protocol/SetScorePacket.java b/src/main/java/cn/nukkit/network/protocol/SetScorePacket.java index cf3fe6b6d9b..1e6cdff2d9a 100644 --- a/src/main/java/cn/nukkit/network/protocol/SetScorePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/SetScorePacket.java @@ -22,6 +22,7 @@ public byte pid() { @Override public void decode() { + this.decodeUnsupported(); } @Override @@ -72,8 +73,8 @@ public static class ScoreInfo { /** * Score info for fake player - * @param scoreboardId - * @param objectiveId + * @param scoreboardId scoreboard id + * @param objectiveId objective id * @param score score * @param name line text */ @@ -88,8 +89,8 @@ public ScoreInfo(long scoreboardId, String objectiveId, int score, String name) /** * Score info for player/entity - * @param scoreboardId - * @param objectiveId + * @param scoreboardId scoreboard id + * @param objectiveId objective id * @param type entity type; PLAYER or ENTITY * @param score score * @param entityId entity id diff --git a/src/main/java/cn/nukkit/network/protocol/SetSpawnPositionPacket.java b/src/main/java/cn/nukkit/network/protocol/SetSpawnPositionPacket.java index e24015fd743..368ea6c2ded 100644 --- a/src/main/java/cn/nukkit/network/protocol/SetSpawnPositionPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/SetSpawnPositionPacket.java @@ -21,7 +21,7 @@ public class SetSpawnPositionPacket extends DataPacket { @Override public void decode() { - + this.decodeUnsupported(); } @Override @@ -29,7 +29,7 @@ public void encode() { this.reset(); this.putVarInt(this.spawnType); this.putBlockVector3(this.x, this.y, this.z); - this.putVarInt(dimension); + this.putVarInt(this.dimension); this.putBlockVector3(this.x, this.y, this.z); } @@ -37,5 +37,4 @@ public void encode() { public byte pid() { return NETWORK_ID; } - } diff --git a/src/main/java/cn/nukkit/network/protocol/SetTimePacket.java b/src/main/java/cn/nukkit/network/protocol/SetTimePacket.java index 76d5542b085..db31c5d61ef 100644 --- a/src/main/java/cn/nukkit/network/protocol/SetTimePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/SetTimePacket.java @@ -3,11 +3,12 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class SetTimePacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.SET_TIME_PACKET; public int time; @@ -19,7 +20,7 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override @@ -27,5 +28,4 @@ public void encode() { this.reset(); this.putVarInt(this.time); } - } diff --git a/src/main/java/cn/nukkit/network/protocol/SetTitlePacket.java b/src/main/java/cn/nukkit/network/protocol/SetTitlePacket.java index 606905c4a03..bb31e2dd8cf 100644 --- a/src/main/java/cn/nukkit/network/protocol/SetTitlePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/SetTitlePacket.java @@ -7,6 +7,7 @@ */ @ToString public class SetTitlePacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.SET_TITLE_PACKET; public static final int TYPE_CLEAR = 0; @@ -32,13 +33,7 @@ public byte pid() { @Override public void decode() { - this.type = this.getVarInt(); - this.text = this.getString(); - this.fadeInTime = this.getVarInt(); - this.stayTime = this.getVarInt(); - this.fadeOutTime = this.getVarInt(); - this.xuid = this.getString(); - this.platformOnlineId = this.getString(); + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/SettingsCommandPacket.java b/src/main/java/cn/nukkit/network/protocol/SettingsCommandPacket.java new file mode 100644 index 00000000000..df4d909d9ce --- /dev/null +++ b/src/main/java/cn/nukkit/network/protocol/SettingsCommandPacket.java @@ -0,0 +1,25 @@ +package cn.nukkit.network.protocol; + +public class SettingsCommandPacket extends DataPacket { + + public static final byte NETWORK_ID = ProtocolInfo.SETTINGS_COMMAND_PACKET; + + public String command; + public boolean suppressOutput; + + @Override + public void decode() { + this.command = this.getString(); + this.suppressOutput = this.getBoolean(); + } + + @Override + public void encode() { + this.encodeUnsupported(); + } + + @Override + public byte pid() { + return NETWORK_ID; + } +} diff --git a/src/main/java/cn/nukkit/network/protocol/ShowProfilePacket.java b/src/main/java/cn/nukkit/network/protocol/ShowProfilePacket.java index d7a6784a8fc..1cfdd5571de 100644 --- a/src/main/java/cn/nukkit/network/protocol/ShowProfilePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ShowProfilePacket.java @@ -3,11 +3,12 @@ import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class ShowProfilePacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.SHOW_PROFILE_PACKET; public String xuid; @@ -19,7 +20,7 @@ public byte pid() { @Override public void decode() { - this.xuid = this.getString(); + this.decodeUnsupported(); } @Override @@ -27,5 +28,4 @@ public void encode() { this.reset(); this.putString(this.xuid); } - } diff --git a/src/main/java/cn/nukkit/network/protocol/SimpleEventPacket.java b/src/main/java/cn/nukkit/network/protocol/SimpleEventPacket.java index 972f1578216..68e44bf0895 100644 --- a/src/main/java/cn/nukkit/network/protocol/SimpleEventPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/SimpleEventPacket.java @@ -5,21 +5,27 @@ @ToString public class SimpleEventPacket extends DataPacket { - public short unknown; + public static final byte NETWORK_ID = ProtocolInfo.SIMPLE_EVENT_PACKET; + + public static final int TYPE_ENABLE_COMMANDS = 1; + public static final int TYPE_DISABLE_COMMANDS = 2; + public static final int TYPE_UNLOCK_WORLD_TEMPLATE_SETTINGS = 3; + + public short eventType; @Override public byte pid() { - return ProtocolInfo.SIMPLE_EVENT_PACKET; + return NETWORK_ID; } @Override public void decode() { - + this.eventType = (short) this.getShort(); } @Override public void encode() { this.reset(); - this.putShort(this.unknown); + this.putShort(this.eventType); } } diff --git a/src/main/java/cn/nukkit/network/protocol/SpawnExperienceOrbPacket.java b/src/main/java/cn/nukkit/network/protocol/SpawnExperienceOrbPacket.java index 5dc0a4317c2..e0c543e762a 100644 --- a/src/main/java/cn/nukkit/network/protocol/SpawnExperienceOrbPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/SpawnExperienceOrbPacket.java @@ -14,7 +14,10 @@ public class SpawnExperienceOrbPacket extends DataPacket { @Override public void decode() { - + this.x = this.getLFloat(); + this.y = this.getLFloat(); + this.z = this.getLFloat(); + this.amount = (int) this.getUnsignedVarInt(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/SpawnParticleEffectPacket.java b/src/main/java/cn/nukkit/network/protocol/SpawnParticleEffectPacket.java index 3f20056224e..1c34b2e44cb 100644 --- a/src/main/java/cn/nukkit/network/protocol/SpawnParticleEffectPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/SpawnParticleEffectPacket.java @@ -3,14 +3,18 @@ import cn.nukkit.math.Vector3f; import lombok.ToString; +import java.util.Optional; + @ToString public class SpawnParticleEffectPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.SPAWN_PARTICLE_EFFECT_PACKET; public int dimensionId; public long uniqueEntityId = -1; public Vector3f position; public String identifier; + public Optional molangVariablesJson = Optional.empty(); @Override public byte pid() { @@ -19,6 +23,7 @@ public byte pid() { @Override public void decode() { + this.decodeUnsupported(); } @Override @@ -28,6 +33,7 @@ public void encode() { this.putEntityUniqueId(uniqueEntityId); this.putVector3f(this.position); this.putString(this.identifier); - this.putBoolean(false); + this.putBoolean(this.molangVariablesJson.isPresent()); + this.molangVariablesJson.ifPresent(this::putString); } } diff --git a/src/main/java/cn/nukkit/network/protocol/StartGamePacket.java b/src/main/java/cn/nukkit/network/protocol/StartGamePacket.java index 6b3ba29fea4..41cde605b0d 100644 --- a/src/main/java/cn/nukkit/network/protocol/StartGamePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/StartGamePacket.java @@ -2,18 +2,17 @@ import cn.nukkit.item.RuntimeItems; import cn.nukkit.level.GameRules; +import cn.nukkit.network.protocol.types.ExperimentData; import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.CompoundTag; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; import lombok.ToString; -import lombok.extern.log4j.Log4j2; import java.io.IOException; import java.util.UUID; -/** - * Created on 15-10-13. - */ -@Log4j2 +import java.util.List; + @ToString public class StartGamePacket extends DataPacket { @@ -48,36 +47,36 @@ public byte pid() { public int spawnZ; public boolean hasAchievementsDisabled = true; public boolean worldEditor; - public int dayCycleStopTime = -1; //-1 = not stopped, any positive value = stopped at that time + public int dayCycleStopTime = -1; // -1 = not stopped, any positive value = stopped public int eduEditionOffer = 0; - public boolean hasEduFeaturesEnabled = false; + public boolean hasEduFeaturesEnabled; public float rainLevel; public float lightningLevel; - public boolean hasConfirmedPlatformLockedContent = false; + public boolean hasConfirmedPlatformLockedContent; public boolean multiplayerGame = true; public boolean broadcastToLAN = true; public int xblBroadcastIntent = GAME_PUBLISH_SETTING_PUBLIC; public int platformBroadcastIntent = GAME_PUBLISH_SETTING_PUBLIC; public boolean commandsEnabled; - public boolean isTexturePacksRequired = false; + public boolean isTexturePacksRequired; public GameRules gameRules; - public boolean bonusChest = false; - public boolean hasStartWithMapEnabled = false; + public boolean bonusChest; + public boolean hasStartWithMapEnabled; public int permissionLevel = 1; public int serverChunkTickRange = 4; - public boolean hasLockedBehaviorPack = false; - public boolean hasLockedResourcePack = false; - public boolean isFromLockedWorldTemplate = false; - public boolean isUsingMsaGamertagsOnly = false; - public boolean isFromWorldTemplate = false; - public boolean isWorldTemplateOptionLocked = false; - public boolean isOnlySpawningV1Villagers = false; + public boolean hasLockedBehaviorPack; + public boolean hasLockedResourcePack; + public boolean isFromLockedWorldTemplate; + public boolean isUsingMsaGamertagsOnly; + public boolean isFromWorldTemplate; + public boolean isWorldTemplateOptionLocked; + public boolean isOnlySpawningV1Villagers; public String vanillaVersion = ProtocolInfo.MINECRAFT_VERSION_NETWORK; - public String levelId = ""; //base64 string, usually the same as world folder name in vanilla + public String levelId = ""; // base64 string, usually the same as world folder name in vanilla public String worldName; public String premiumWorldTemplateId = ""; - public boolean isTrial = false; - public boolean isMovementServerAuthoritative; + public boolean isTrial; + public boolean isMovementServerAuthoritative = true; public boolean isInventoryServerAuthoritative; public long currentTick; public int enchantmentSeed; @@ -89,10 +88,11 @@ public byte pid() { public boolean disablePlayerInteractions; public boolean emoteChatMuted; public boolean hardcore; + public final List experiments = new ObjectArrayList<>(1); @Override public void decode() { - + this.decodeUnsupported(); } @Override @@ -132,8 +132,7 @@ public void encode() { this.putBoolean(this.commandsEnabled); this.putBoolean(this.isTexturePacksRequired); this.putGameRules(this.gameRules); - this.putLInt(0); // Experiment count - this.putBoolean(false); // Were experiments previously toggled + this.putExperiments(this.experiments); this.putBoolean(this.bonusChest); this.putBoolean(this.hasStartWithMapEnabled); this.putVarInt(this.permissionLevel); @@ -148,12 +147,13 @@ public void encode() { this.putBoolean(this.isDisablingPersonas); this.putBoolean(this.isDisablingCustomSkins); this.putBoolean(this.emoteChatMuted); - this.putString(this.vanillaVersion); + this.putString(ProtocolInfo.MINECRAFT_VERSION_NETWORK); this.putLInt(16); // Limited world width this.putLInt(16); // Limited world height this.putBoolean(false); // Nether type - this.putString(""); // EduSharedUriResource buttonName - this.putString(""); // EduSharedUriResource linkUri + // EduSharedUriResource + this.putString(""); // buttonName + this.putString(""); // linkUri this.putBoolean(false); // Experimental Gameplay this.putByte(this.chatRestrictionLevel); this.putBoolean(this.disablePlayerInteractions); @@ -170,11 +170,11 @@ public void encode() { this.putBoolean(true); // isServerAuthoritativeBlockBreaking this.putLLong(this.currentTick); this.putVarInt(this.enchantmentSeed); - this.putUnsignedVarInt(0); // Custom blocks + this.putUnsignedVarInt(0); // No custom blocks this.put(RuntimeItems.getMapping().getItemPalette()); this.putString(this.multiplayerCorrelationId); - this.putBoolean(this.isInventoryServerAuthoritative); - this.putString(""); // Server Engine + this.putBoolean(false); // isInventoryServerAuthoritative + this.putString(""); // serverEngine try { this.put(NBTIO.writeNetwork(new CompoundTag(""))); // playerPropertyData } catch (IOException e) { @@ -184,6 +184,6 @@ public void encode() { this.putUUID(new UUID(0, 0)); // worldTemplateId this.putBoolean(this.clientSideGenerationEnabled); this.putBoolean(false); // blockIdsAreHashed - this.putBoolean(false); // serverAuthSounds + this.putBoolean(true); // isServerAuthSounds } } diff --git a/src/main/java/cn/nukkit/network/protocol/StopSoundPacket.java b/src/main/java/cn/nukkit/network/protocol/StopSoundPacket.java index 289fcb0a606..2b4612fd2e1 100644 --- a/src/main/java/cn/nukkit/network/protocol/StopSoundPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/StopSoundPacket.java @@ -18,7 +18,7 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/StructureBlockUpdatePacket.java b/src/main/java/cn/nukkit/network/protocol/StructureBlockUpdatePacket.java index 11bfde67133..44f47b98423 100644 --- a/src/main/java/cn/nukkit/network/protocol/StructureBlockUpdatePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/StructureBlockUpdatePacket.java @@ -5,18 +5,20 @@ @ToString public class StructureBlockUpdatePacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.STRUCTURE_BLOCK_UPDATE_PACKET; + @Override public byte pid() { - return ProtocolInfo.STRUCTURE_BLOCK_UPDATE_PACKET; + return NETWORK_ID; } @Override public void decode() { - + this.decodeUnsupported(); } @Override public void encode() { - //TODO + this.encodeUnsupported(); } } diff --git a/src/main/java/cn/nukkit/network/protocol/SubClientLoginPacket.java b/src/main/java/cn/nukkit/network/protocol/SubClientLoginPacket.java index c8e94b2a43c..578c18c693b 100644 --- a/src/main/java/cn/nukkit/network/protocol/SubClientLoginPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/SubClientLoginPacket.java @@ -5,18 +5,20 @@ @ToString public class SubClientLoginPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.SUB_CLIENT_LOGIN_PACKET; + @Override public byte pid() { - return ProtocolInfo.SUB_CLIENT_LOGIN_PACKET; + return NETWORK_ID; } @Override public void decode() { - + this.decodeUnsupported(); } @Override public void encode() { - //TODO + this.encodeUnsupported(); } } diff --git a/src/main/java/cn/nukkit/network/protocol/TakeItemEntityPacket.java b/src/main/java/cn/nukkit/network/protocol/TakeItemEntityPacket.java index a5eec2a4652..608a8d75083 100644 --- a/src/main/java/cn/nukkit/network/protocol/TakeItemEntityPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/TakeItemEntityPacket.java @@ -2,9 +2,6 @@ import lombok.ToString; -/** - * Created on 15-10-14. - */ @ToString public class TakeItemEntityPacket extends DataPacket { @@ -15,8 +12,7 @@ public class TakeItemEntityPacket extends DataPacket { @Override public void decode() { - this.target = this.getEntityRuntimeId(); - this.entityId = this.getEntityRuntimeId(); + this.decodeUnsupported(); } @Override @@ -30,5 +26,4 @@ public void encode() { public byte pid() { return NETWORK_ID; } - } diff --git a/src/main/java/cn/nukkit/network/protocol/TextPacket.java b/src/main/java/cn/nukkit/network/protocol/TextPacket.java index 99791fc7246..5d188ed319f 100644 --- a/src/main/java/cn/nukkit/network/protocol/TextPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/TextPacket.java @@ -1,11 +1,7 @@ package cn.nukkit.network.protocol; -import cn.nukkit.utils.BinaryStream; import lombok.ToString; -/** - * Created on 15-10-13. - */ @ToString public class TextPacket extends DataPacket { @@ -58,7 +54,11 @@ public void decode() { case TYPE_POPUP: case TYPE_JUKEBOX_POPUP: this.message = this.getString(); - this.parameters = this.getArray(String.class, BinaryStream::getString); + int paramCount = (int) this.getUnsignedVarInt(); + this.parameters = new String[Math.min(paramCount, 128)]; + for (int i = 0; i < this.parameters.length; i++) { + this.parameters[i] = this.getString(); + } } this.xboxUserId = this.getString(); this.platformChatId = this.getString(); diff --git a/src/main/java/cn/nukkit/network/protocol/ToastRequestPacket.java b/src/main/java/cn/nukkit/network/protocol/ToastRequestPacket.java index 81ae08556d6..834171b7433 100644 --- a/src/main/java/cn/nukkit/network/protocol/ToastRequestPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/ToastRequestPacket.java @@ -5,18 +5,19 @@ @ToString public class ToastRequestPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.TOAST_REQUEST_PACKET; + public String title = ""; public String content = ""; @Override public byte pid() { - return ProtocolInfo.TOAST_REQUEST_PACKET; + return NETWORK_ID; } @Override public void decode() { - this.title = this.getString(); - this.content = this.getString(); + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/TransferPacket.java b/src/main/java/cn/nukkit/network/protocol/TransferPacket.java index 5d45142a7bc..e6d2fc92187 100644 --- a/src/main/java/cn/nukkit/network/protocol/TransferPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/TransferPacket.java @@ -4,15 +4,15 @@ @ToString public class TransferPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.TRANSFER_PACKET; - public String address; // Server address - public int port = 19132; // Server port + public String address; + public int port = 19132; @Override public void decode() { - this.address = this.getString(); - this.port = (short) this.getLShort(); + this.decodeUnsupported(); } @Override @@ -25,6 +25,6 @@ public void encode() { @Override public byte pid() { - return ProtocolInfo.TRANSFER_PACKET; + return NETWORK_ID; } } diff --git a/src/main/java/cn/nukkit/network/protocol/UpdateAbilitiesPacket.java b/src/main/java/cn/nukkit/network/protocol/UpdateAbilitiesPacket.java index 28743aaa1a4..712d7985fe6 100644 --- a/src/main/java/cn/nukkit/network/protocol/UpdateAbilitiesPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/UpdateAbilitiesPacket.java @@ -17,6 +17,8 @@ @Setter public class UpdateAbilitiesPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.UPDATE_ABILITIES_PACKET; + protected static final PlayerAbility[] VALID_FLAGS = { PlayerAbility.BUILD, PlayerAbility.MINE, @@ -38,6 +40,7 @@ public class UpdateAbilitiesPacket extends DataPacket { PlayerAbility.NO_CLIP, PlayerAbility.PRIVILEGED_BUILDER }; + private static final EnumMap FLAGS_TO_BITS = new EnumMap<>(PlayerAbility.class); static { @@ -49,11 +52,11 @@ public class UpdateAbilitiesPacket extends DataPacket { private long entityId; private PlayerPermission playerPermission; private CommandPermission commandPermission; - private final List abilityLayers = new ObjectArrayList<>(); + private final List abilityLayers = new ObjectArrayList<>(2); @Override public void decode() { - throw new UnsupportedOperationException(); + this.decodeUnsupported(); } @Override @@ -83,7 +86,7 @@ private static int getAbilitiesNumber(Set abilities) { @Override public byte pid() { - return ProtocolInfo.UPDATE_ABILITIES_PACKET; + return NETWORK_ID; } public enum PlayerPermission { diff --git a/src/main/java/cn/nukkit/network/protocol/UpdateAdventureSettingsPacket.java b/src/main/java/cn/nukkit/network/protocol/UpdateAdventureSettingsPacket.java index 634f57b1cf5..872ff0c4c50 100644 --- a/src/main/java/cn/nukkit/network/protocol/UpdateAdventureSettingsPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/UpdateAdventureSettingsPacket.java @@ -8,6 +8,9 @@ @Getter @Setter public class UpdateAdventureSettingsPacket extends DataPacket { + + public static final byte NETWORK_ID = ProtocolInfo.UPDATE_ADVENTURE_SETTINGS_PACKET; + private boolean noPvM; private boolean noMvP; private boolean immutableWorld; @@ -16,7 +19,7 @@ public class UpdateAdventureSettingsPacket extends DataPacket { @Override public void decode() { - throw new UnsupportedOperationException(); + this.decodeUnsupported(); } @Override @@ -31,6 +34,6 @@ public void encode() { @Override public byte pid() { - return ProtocolInfo.UPDATE_ADVENTURE_SETTINGS_PACKET; + return NETWORK_ID; } } diff --git a/src/main/java/cn/nukkit/network/protocol/UpdateAttributesPacket.java b/src/main/java/cn/nukkit/network/protocol/UpdateAttributesPacket.java index 33eae1921d1..c15160f7c8a 100644 --- a/src/main/java/cn/nukkit/network/protocol/UpdateAttributesPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/UpdateAttributesPacket.java @@ -20,10 +20,12 @@ public byte pid() { return NETWORK_ID; } + @Override public void decode() { - + this.decodeUnsupported(); } + @Override public void encode() { this.reset(); @@ -41,10 +43,11 @@ public void encode() { this.putLFloat(entry.getMaxValue()); // defaultMaxValue this.putLFloat(entry.getDefaultValue()); this.putString(entry.getName()); + this.putUnsignedVarInt(0); // Modifiers } } + this.putUnsignedVarInt(this.frame); } - } diff --git a/src/main/java/cn/nukkit/network/protocol/UpdateBlockPacket.java b/src/main/java/cn/nukkit/network/protocol/UpdateBlockPacket.java index 94748131473..a15dbf06ef6 100644 --- a/src/main/java/cn/nukkit/network/protocol/UpdateBlockPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/UpdateBlockPacket.java @@ -1,14 +1,14 @@ package cn.nukkit.network.protocol; - import lombok.ToString; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ @ToString public class UpdateBlockPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.UPDATE_BLOCK_PACKET; public static final int FLAG_NONE = 0b0000; @@ -34,7 +34,7 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/UpdateEquipmentPacket.java b/src/main/java/cn/nukkit/network/protocol/UpdateEquipmentPacket.java index 6280ea29aa0..6a6747394d8 100644 --- a/src/main/java/cn/nukkit/network/protocol/UpdateEquipmentPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/UpdateEquipmentPacket.java @@ -5,21 +5,23 @@ @ToString(exclude = "namedtag") public class UpdateEquipmentPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.UPDATE_EQUIPMENT_PACKET; + public int windowId; public int windowType; - public int unknown; //TODO: find out what this is (vanilla always sends 0) + public int unknown; public long eid; public byte[] namedtag; @Override public byte pid() { - return ProtocolInfo.UPDATE_EQUIPMENT_PACKET; + return NETWORK_ID; } @Override public void decode() { - + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/UpdatePlayerGameTypePacket.java b/src/main/java/cn/nukkit/network/protocol/UpdatePlayerGameTypePacket.java index eaa92a524f0..59cd3e838e7 100644 --- a/src/main/java/cn/nukkit/network/protocol/UpdatePlayerGameTypePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/UpdatePlayerGameTypePacket.java @@ -4,6 +4,7 @@ @ToString public class UpdatePlayerGameTypePacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.UPDATE_PLAYER_GAME_TYPE_PACKET; public GameType gameType; @@ -17,8 +18,7 @@ public byte pid() { @Override public void decode() { - this.gameType = GameType.from(this.getVarInt()); - this.entityId = this.getVarLong(); + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/UpdateSoftEnumPacket.java b/src/main/java/cn/nukkit/network/protocol/UpdateSoftEnumPacket.java index c2629cbd547..3e9fd8842f7 100644 --- a/src/main/java/cn/nukkit/network/protocol/UpdateSoftEnumPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/UpdateSoftEnumPacket.java @@ -5,17 +5,20 @@ @ToString public class UpdateSoftEnumPacket extends DataPacket { + public static final byte NETWORK_ID = ProtocolInfo.UPDATE_SOFT_ENUM_PACKET; + public final String[] values = new String[0]; public String name = ""; public Type type = Type.SET; @Override public byte pid() { - return ProtocolInfo.UPDATE_SOFT_ENUM_PACKET; + return NETWORK_ID; } @Override public void decode() { + this.decodeUnsupported(); } @Override diff --git a/src/main/java/cn/nukkit/network/protocol/UpdateTradePacket.java b/src/main/java/cn/nukkit/network/protocol/UpdateTradePacket.java index b93bd97d6d0..10b24244120 100644 --- a/src/main/java/cn/nukkit/network/protocol/UpdateTradePacket.java +++ b/src/main/java/cn/nukkit/network/protocol/UpdateTradePacket.java @@ -8,8 +8,10 @@ public class UpdateTradePacket extends DataPacket { public static final byte NETWORK_ID = ProtocolInfo.UPDATE_TRADE_PACKET; public byte windowId; - public byte windowType = 15; //trading id - public int unknownVarInt1; // hardcoded to 0 + public byte windowType = 15; + public int unknownVarInt1; + public int unknownVarInt2; + public int unknownVarInt3; public int tradeTier; public long trader; public long player; @@ -25,7 +27,7 @@ public byte pid() { @Override public void decode() { - + this.decodeUnsupported(); } @Override @@ -42,5 +44,4 @@ public void encode() { this.putBoolean(isWilling); this.put(this.offers); } - } diff --git a/src/main/java/cn/nukkit/network/protocol/VideoStreamConnectPacket.java b/src/main/java/cn/nukkit/network/protocol/VideoStreamConnectPacket.java index 5f1b67c5f3a..9a63f45ac58 100644 --- a/src/main/java/cn/nukkit/network/protocol/VideoStreamConnectPacket.java +++ b/src/main/java/cn/nukkit/network/protocol/VideoStreamConnectPacket.java @@ -21,10 +21,12 @@ public byte pid() { @Override public void decode() { + this.decodeUnsupported(); } @Override public void encode() { + this.reset(); this.putString(address); this.putLFloat(screenshotFrequency); this.putByte(action); diff --git a/src/main/java/cn/nukkit/network/protocol/types/AbilityLayer.java b/src/main/java/cn/nukkit/network/protocol/types/AbilityLayer.java index 0d2b8d263b6..561b82b9dbd 100644 --- a/src/main/java/cn/nukkit/network/protocol/types/AbilityLayer.java +++ b/src/main/java/cn/nukkit/network/protocol/types/AbilityLayer.java @@ -7,6 +7,7 @@ @Data public class AbilityLayer { + private Type layerType; private final Set abilitiesSet = EnumSet.noneOf(PlayerAbility.class); private final Set abilityValues = EnumSet.noneOf(PlayerAbility.class); diff --git a/src/main/java/cn/nukkit/network/protocol/types/AuthInputAction.java b/src/main/java/cn/nukkit/network/protocol/types/AuthInputAction.java index 317a061324a..2695692b3c4 100644 --- a/src/main/java/cn/nukkit/network/protocol/types/AuthInputAction.java +++ b/src/main/java/cn/nukkit/network/protocol/types/AuthInputAction.java @@ -1,6 +1,7 @@ package cn.nukkit.network.protocol.types; public enum AuthInputAction { + ASCEND, DESCEND, NORTH_JUMP, diff --git a/src/main/java/cn/nukkit/network/protocol/types/AuthInteractionModel.java b/src/main/java/cn/nukkit/network/protocol/types/AuthInteractionModel.java index 0ed43728ce6..3ce41575fba 100644 --- a/src/main/java/cn/nukkit/network/protocol/types/AuthInteractionModel.java +++ b/src/main/java/cn/nukkit/network/protocol/types/AuthInteractionModel.java @@ -1,6 +1,7 @@ package cn.nukkit.network.protocol.types; public enum AuthInteractionModel { + TOUCH, CROSSHAIR, CLASSIC; diff --git a/src/main/java/cn/nukkit/network/protocol/types/ClientPlayMode.java b/src/main/java/cn/nukkit/network/protocol/types/ClientPlayMode.java index f68c998bac7..0766890d791 100644 --- a/src/main/java/cn/nukkit/network/protocol/types/ClientPlayMode.java +++ b/src/main/java/cn/nukkit/network/protocol/types/ClientPlayMode.java @@ -1,6 +1,7 @@ package cn.nukkit.network.protocol.types; public enum ClientPlayMode { + NORMAL, TEASER, SCREEN, diff --git a/src/main/java/cn/nukkit/network/protocol/types/CommandOriginData.java b/src/main/java/cn/nukkit/network/protocol/types/CommandOriginData.java index fa0a73ea810..e00ab1edfae 100644 --- a/src/main/java/cn/nukkit/network/protocol/types/CommandOriginData.java +++ b/src/main/java/cn/nukkit/network/protocol/types/CommandOriginData.java @@ -1,6 +1,5 @@ package cn.nukkit.network.protocol.types; - import lombok.ToString; import java.util.OptionalLong; @@ -12,6 +11,7 @@ */ @ToString public final class CommandOriginData { + public final Origin type; public final UUID uuid; public final String requestId; diff --git a/src/main/java/cn/nukkit/network/protocol/types/DimensionDefinition.java b/src/main/java/cn/nukkit/network/protocol/types/DimensionDefinition.java new file mode 100644 index 00000000000..29256fd517d --- /dev/null +++ b/src/main/java/cn/nukkit/network/protocol/types/DimensionDefinition.java @@ -0,0 +1,12 @@ +package cn.nukkit.network.protocol.types; + +import lombok.Value; + +@Value +public class DimensionDefinition { + + String id; + int maximumHeight; + int minimumHeight; + int generatorType; +} diff --git a/src/main/java/cn/nukkit/network/protocol/types/EntityLink.java b/src/main/java/cn/nukkit/network/protocol/types/EntityLink.java index 39aac8c8e5d..dc88e78a837 100644 --- a/src/main/java/cn/nukkit/network/protocol/types/EntityLink.java +++ b/src/main/java/cn/nukkit/network/protocol/types/EntityLink.java @@ -26,4 +26,4 @@ public EntityLink(long fromEntityUniquieId, long toEntityUniquieId, byte type, b this.riderInitiated = riderInitiated; this.vehicleAngularVelocity = vehicleAngularVelocity; } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/network/protocol/types/ExperimentData.java b/src/main/java/cn/nukkit/network/protocol/types/ExperimentData.java new file mode 100644 index 00000000000..bfb2053d0dd --- /dev/null +++ b/src/main/java/cn/nukkit/network/protocol/types/ExperimentData.java @@ -0,0 +1,9 @@ +package cn.nukkit.network.protocol.types; + +import lombok.Data; + +@Data +public class ExperimentData { + private final String name; + private final boolean enabled; +} diff --git a/src/main/java/cn/nukkit/network/protocol/types/NetworkInventoryAction.java b/src/main/java/cn/nukkit/network/protocol/types/NetworkInventoryAction.java index 254c80f6756..4016b47a6d1 100644 --- a/src/main/java/cn/nukkit/network/protocol/types/NetworkInventoryAction.java +++ b/src/main/java/cn/nukkit/network/protocol/types/NetworkInventoryAction.java @@ -1,13 +1,11 @@ package cn.nukkit.network.protocol.types; import cn.nukkit.Player; -import cn.nukkit.inventory.AnvilInventory; -import cn.nukkit.inventory.BeaconInventory; -import cn.nukkit.inventory.EnchantInventory; -import cn.nukkit.inventory.Inventory; -import cn.nukkit.inventory.PlayerUIComponent; +import cn.nukkit.block.BlockID; +import cn.nukkit.inventory.*; import cn.nukkit.inventory.transaction.action.*; import cn.nukkit.item.Item; +import cn.nukkit.item.ItemID; import cn.nukkit.network.protocol.InventoryTransactionPacket; import lombok.ToString; @@ -68,7 +66,6 @@ public class NetworkInventoryAction { public int inventorySlot; public Item oldItem; public Item newItem; - public int stackNetworkId; public NetworkInventoryAction read(InventoryTransactionPacket packet) { this.sourceType = (int) packet.getUnsignedVarInt(); @@ -108,6 +105,7 @@ public NetworkInventoryAction read(InventoryTransactionPacket packet) { this.inventorySlot = (int) packet.getUnsignedVarInt(); this.oldItem = packet.getSlot(); this.newItem = packet.getSlot(); + return this; } @@ -116,8 +114,6 @@ public void write(InventoryTransactionPacket packet) { switch (this.sourceType) { case SOURCE_CONTAINER: - case SOURCE_CRAFT_SLOT: - case SOURCE_TODO: packet.putVarInt(this.windowId); break; case SOURCE_WORLD: @@ -125,6 +121,10 @@ public void write(InventoryTransactionPacket packet) { break; case SOURCE_CREATIVE: break; + case SOURCE_CRAFT_SLOT: + case SOURCE_TODO: + packet.putVarInt(this.windowId); + break; } packet.putUnsignedVarInt(this.inventorySlot); @@ -136,22 +136,30 @@ public InventoryAction createInventoryAction(Player player) { switch (this.sourceType) { case SOURCE_CONTAINER: if (this.windowId == ContainerIds.ARMOR) { - //TODO: HACK! this.inventorySlot += 36; this.windowId = ContainerIds.INVENTORY; + if (this.newItem == null || + (this.inventorySlot == 36 && !(this.newItem.canBePutInHelmetSlot() || this.newItem.getId() == (255 - BlockID.CARVED_PUMPKIN)) && !(this.oldItem.canBePutInHelmetSlot() || this.oldItem.getId() == (255 - BlockID.CARVED_PUMPKIN))) || + (this.inventorySlot == 37 && !this.newItem.isChestplate() && !this.oldItem.isChestplate()) || + (this.inventorySlot == 38 && !this.newItem.isLeggings() && !this.oldItem.isLeggings()) || + (this.inventorySlot == 39 && !this.newItem.isBoots()) && !this.oldItem.isBoots()) { + player.getServer().getLogger().warning(player.getName() + " tried to set an invalid armor item"); + return null; + } } + // ID 124 with slot 14/15 is enchant inventory if (this.windowId == ContainerIds.UI) { switch (this.inventorySlot) { case PlayerUIComponent.CREATED_ITEM_OUTPUT_UI_SLOT: - if (player.getWindowById(Player.ANVIL_WINDOW_ID) != null) { + if (player.getWindowById(Player.ANVIL_WINDOW_ID) instanceof AnvilInventory) { this.windowId = Player.ANVIL_WINDOW_ID; this.inventorySlot = 2; } break; case EnchantInventory.ENCHANT_INPUT_ITEM_UI_SLOT: - if (player.getWindowById(Player.ENCHANT_WINDOW_ID) == null) { - player.getServer().getLogger().error("Player " + player.getName() + " does not have enchant window open"); + if (!(player.getWindowById(Player.ENCHANT_WINDOW_ID) instanceof EnchantInventory)) { + player.getServer().getLogger().debug(player.getName() + " does not have enchant window open"); return null; } this.windowId = Player.ENCHANT_WINDOW_ID; @@ -159,29 +167,49 @@ public InventoryAction createInventoryAction(Player player) { // TODO, check if unenchanted item and send EnchantOptionsPacket break; case EnchantInventory.ENCHANT_REAGENT_UI_SLOT: - if (player.getWindowById(Player.ENCHANT_WINDOW_ID) == null) { - player.getServer().getLogger().error("Player " + player.getName() + " does not have enchant window open"); + if (!(player.getWindowById(Player.ENCHANT_WINDOW_ID) instanceof EnchantInventory)) { + player.getServer().getLogger().debug(player.getName() + " does not have enchant window open"); return null; } this.windowId = Player.ENCHANT_WINDOW_ID; this.inventorySlot = 1; break; case AnvilInventory.ANVIL_INPUT_UI_SLOT: - if (player.getWindowById(Player.ANVIL_WINDOW_ID) == null) { - player.getServer().getLogger().error("Player " + player.getName() + " does not have anvil window open"); + if (!(player.getWindowById(Player.ANVIL_WINDOW_ID) instanceof AnvilInventory)) { + player.getServer().getLogger().debug(player.getName() + " does not have anvil window open"); return null; } this.windowId = Player.ANVIL_WINDOW_ID; this.inventorySlot = 0; break; case AnvilInventory.ANVIL_MATERIAL_UI_SLOT: - if (player.getWindowById(Player.ANVIL_WINDOW_ID) == null) { - player.getServer().getLogger().error("Player " + player.getName() + " does not have anvil window open"); + if (!(player.getWindowById(Player.ANVIL_WINDOW_ID) instanceof AnvilInventory)) { + player.getServer().getLogger().debug(player.getName() + " does not have anvil window open"); return null; } this.windowId = Player.ANVIL_WINDOW_ID; this.inventorySlot = 1; break; + case SmithingInventory.SMITHING_EQUIPMENT_UI_SLOT: + if (!(player.getWindowById(Player.SMITHING_WINDOW_ID) instanceof SmithingInventory)) { + player.getServer().getLogger().debug(player.getName() + " does not have smithing table window open"); + return null; + } + this.windowId = Player.SMITHING_WINDOW_ID; + this.inventorySlot = 0; + break; + case SmithingInventory.SMITHING_INGREDIENT_UI_SLOT: + if (!(player.getWindowById(Player.SMITHING_WINDOW_ID) instanceof SmithingInventory)) { + player.getServer().getLogger().debug(player.getName() + " does not have smithing table window open"); + return null; + } + if (!(this.oldItem == null || this.oldItem.getId() == 0 || this.oldItem.getId() == ItemID.NETHERITE_INGOT) || !(this.newItem == null || this.newItem.getId() == 0 || this.newItem.getId() == ItemID.NETHERITE_INGOT)) { + player.getServer().getLogger().debug(player.getName() + " had invalid smithing ingredient"); + return null; + } + this.windowId = Player.SMITHING_WINDOW_ID; + this.inventorySlot = 1; + break; } } @@ -190,7 +218,7 @@ public InventoryAction createInventoryAction(Player player) { return new SlotChangeAction(window, this.inventorySlot, this.oldItem, this.newItem); } - player.getServer().getLogger().debug("Player " + player.getName() + " has no open container with window ID " + this.windowId); + player.getServer().getLogger().debug(player.getName() + " has no open container with window ID " + this.windowId); return null; case SOURCE_WORLD: if (this.inventorySlot != InventoryTransactionPacket.ACTION_MAGIC_SLOT_DROP_ITEM) { @@ -220,7 +248,6 @@ public InventoryAction createInventoryAction(Player player) { return new CreativeInventoryAction(this.oldItem, this.newItem, type); case SOURCE_CRAFT_SLOT: case SOURCE_TODO: - //These types need special handling. switch (this.windowId) { case SOURCE_TYPE_CRAFTING_ADD_INGREDIENT: case SOURCE_TYPE_CRAFTING_REMOVE_INGREDIENT: @@ -235,17 +262,37 @@ public InventoryAction createInventoryAction(Player player) { case SOURCE_TYPE_CRAFTING_RESULT: return new CraftingTakeResultAction(this.oldItem, this.newItem); case SOURCE_TYPE_CRAFTING_USE_INGREDIENT: + Inventory inv = player.getWindowById(Player.LOOM_WINDOW_ID); + if (inv instanceof LoomInventory) { + LoomInventory loomInventory = (LoomInventory) inv; + return new LoomItemAction(this.oldItem, this.newItem, loomInventory); + } return new CraftingTransferMaterialAction(this.oldItem, this.newItem, this.inventorySlot); } - if (this.windowId >= SOURCE_TYPE_ANVIL_OUTPUT && this.windowId <= SOURCE_TYPE_ANVIL_INPUT) { //anvil actions + if (this.windowId >= SOURCE_TYPE_ANVIL_OUTPUT && this.windowId <= SOURCE_TYPE_ANVIL_INPUT) { Inventory inv = player.getWindowById(Player.ANVIL_WINDOW_ID); if (!(inv instanceof AnvilInventory)) { - player.getServer().getLogger().debug("Player " + player.getName() + " has no open anvil inventory"); + // Hack: Fix beacon payment // TODO: Better fix + if ((inv = player.getWindowById(Player.BEACON_WINDOW_ID)) instanceof BeaconInventory) { + inv.setItem(0, Item.get(Item.AIR)); + return null; + } + + if (player.getWindowById(Player.SMITHING_WINDOW_ID) instanceof SmithingInventory) { + switch (this.windowId) { + case SOURCE_TYPE_ANVIL_INPUT: + case SOURCE_TYPE_ANVIL_MATERIAL: + case SOURCE_TYPE_ANVIL_OUTPUT: + case SOURCE_TYPE_ANVIL_RESULT: + return new SmithingItemAction(this.oldItem, this.newItem, this.inventorySlot); + } + } + + player.getServer().getLogger().debug(player.getName() + " has no open anvil inventory"); return null; } - AnvilInventory anvil = (AnvilInventory) inv; switch (this.windowId) { case SOURCE_TYPE_ANVIL_INPUT: @@ -254,14 +301,14 @@ public InventoryAction createInventoryAction(Player player) { return new RepairItemAction(this.oldItem, this.newItem, this.windowId); } - return new SlotChangeAction(anvil, this.inventorySlot, this.oldItem, this.newItem); + return new SlotChangeAction(inv, this.inventorySlot, this.oldItem, this.newItem); } if (this.windowId >= SOURCE_TYPE_ENCHANT_OUTPUT && this.windowId <= SOURCE_TYPE_ENCHANT_INPUT) { Inventory inv = player.getWindowById(Player.ENCHANT_WINDOW_ID); if (!(inv instanceof EnchantInventory)) { - player.getServer().getLogger().debug("Player " + player.getName() + " has no open enchant inventory"); + player.getServer().getLogger().debug(player.getName() + " has no open enchant inventory"); return null; } EnchantInventory enchant = (EnchantInventory) inv; @@ -282,7 +329,7 @@ public InventoryAction createInventoryAction(Player player) { Inventory inv = player.getWindowById(Player.BEACON_WINDOW_ID); if (!(inv instanceof BeaconInventory)) { - player.getServer().getLogger().debug("Player " + player.getName() + " has no open beacon inventory"); + player.getServer().getLogger().debug(player.getName() + " has no open beacon inventory"); return null; } BeaconInventory beacon = (BeaconInventory) inv; @@ -291,8 +338,7 @@ public InventoryAction createInventoryAction(Player player) { return new SlotChangeAction(beacon, this.inventorySlot, this.oldItem, this.newItem); } - //TODO: more stuff - player.getServer().getLogger().debug("Player " + player.getName() + " has no open container with window ID " + this.windowId); + player.getServer().getLogger().debug(player.getName() + " has no open container with window ID " + this.windowId); return null; default: player.getServer().getLogger().debug("Unknown inventory source type " + this.sourceType); diff --git a/src/main/java/cn/nukkit/network/protocol/types/PacketCompressionAlgorithm.java b/src/main/java/cn/nukkit/network/protocol/types/PacketCompressionAlgorithm.java index c7eb3c67265..1f9b0fe99c3 100644 --- a/src/main/java/cn/nukkit/network/protocol/types/PacketCompressionAlgorithm.java +++ b/src/main/java/cn/nukkit/network/protocol/types/PacketCompressionAlgorithm.java @@ -1,6 +1,7 @@ package cn.nukkit.network.protocol.types; public enum PacketCompressionAlgorithm { + ZLIB, SNAPPY } diff --git a/src/main/java/cn/nukkit/network/protocol/types/PlayerAbility.java b/src/main/java/cn/nukkit/network/protocol/types/PlayerAbility.java index 3b5b5c95201..0736937aa16 100644 --- a/src/main/java/cn/nukkit/network/protocol/types/PlayerAbility.java +++ b/src/main/java/cn/nukkit/network/protocol/types/PlayerAbility.java @@ -4,6 +4,7 @@ import java.util.List; public enum PlayerAbility { + BUILD, MINE, DOORS_AND_SWITCHES, diff --git a/src/main/java/cn/nukkit/network/protocol/types/PlayerBlockActionData.java b/src/main/java/cn/nukkit/network/protocol/types/PlayerBlockActionData.java index 8e46210db9f..414cc949d4b 100644 --- a/src/main/java/cn/nukkit/network/protocol/types/PlayerBlockActionData.java +++ b/src/main/java/cn/nukkit/network/protocol/types/PlayerBlockActionData.java @@ -7,6 +7,7 @@ @Data @AllArgsConstructor public class PlayerBlockActionData { + private PlayerActionType action; private BlockVector3 position; private int facing; diff --git a/src/main/java/cn/nukkit/network/query/QueryHandler.java b/src/main/java/cn/nukkit/network/query/QueryHandler.java index d9b45fb9c06..845ecfda0f5 100644 --- a/src/main/java/cn/nukkit/network/query/QueryHandler.java +++ b/src/main/java/cn/nukkit/network/query/QueryHandler.java @@ -2,6 +2,7 @@ import cn.nukkit.Server; import cn.nukkit.event.server.QueryRegenerateEvent; +import cn.nukkit.utils.Utils; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; @@ -12,17 +13,15 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; -import java.util.Random; -import java.util.concurrent.ThreadLocalRandom; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class QueryHandler { - public static final byte HANDSHAKE = 0x09; - public static final byte STATISTICS = 0x00; + private static final byte HANDSHAKE = 0x09; + private static final byte STATISTICS = 0x00; private final Server server; private byte[] lastToken; @@ -33,6 +32,7 @@ public class QueryHandler { public QueryHandler() { this.server = Server.getInstance(); + this.server.getLogger().info(this.server.getLanguage().translateString("nukkit.server.query.start")); String ip = this.server.getIp(); String addr = (!ip.isEmpty()) ? ip : "0.0.0.0"; @@ -47,8 +47,8 @@ public QueryHandler() { public void regenerateInfo() { QueryRegenerateEvent ev = this.server.getQueryInformation(); - this.longData = ev.getLongQuery(this.longData); - this.shortData = ev.getShortQuery(this.shortData); + this.longData = ev.getLongQuery(); + this.shortData = ev.getShortQuery(); this.timeout = System.currentTimeMillis() + ev.getTimeout(); } @@ -56,7 +56,7 @@ public void regenerateToken() { this.lastToken = this.token; byte[] token = new byte[16]; for (int i = 0; i < 16; i++) { - token[i] = (byte) new Random().nextInt(255); + token[i] = (byte) Utils.random.nextInt(255); } this.token = token; } @@ -65,6 +65,7 @@ public static byte[] getTokenString(String token, InetAddress address) { return getTokenString(token.getBytes(StandardCharsets.UTF_8), address); } + public static byte[] getTokenString(byte[] token, InetAddress address) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); @@ -72,7 +73,7 @@ public static byte[] getTokenString(byte[] token, InetAddress address) { digest.update(token); return Arrays.copyOf(digest.digest(), 4); } catch (NoSuchAlgorithmException e) { - return ByteBuffer.allocate(4).putInt(ThreadLocalRandom.current().nextInt()).array(); + return ByteBuffer.allocate(4).putInt(Utils.random.nextInt()).array(); } } @@ -102,7 +103,8 @@ public void handle(InetSocketAddress address, ByteBuf packet) { if (this.timeout < System.currentTimeMillis()) { this.regenerateInfo(); } - reply = ByteBufAllocator.DEFAULT.ioBuffer(64); + + reply = ByteBufAllocator.DEFAULT.directBuffer(64); reply.writeByte(STATISTICS); reply.writeInt(sessionId); if (packet.readableBytes() == 8) { diff --git a/src/main/java/cn/nukkit/network/rcon/RCON.java b/src/main/java/cn/nukkit/network/rcon/RCON.java index 47438a8f595..ec08b82b8b0 100644 --- a/src/main/java/cn/nukkit/network/rcon/RCON.java +++ b/src/main/java/cn/nukkit/network/rcon/RCON.java @@ -9,19 +9,20 @@ /** * Implementation of Source RCON protocol. - * https://developer.valvesoftware.com/wiki/Source_RCON_Protocol + * ... *

* Wrapper for RCONServer. Handles data. * * @author Tee7even */ public class RCON { + private final Server server; private final RCONServer serverThread; public RCON(Server server, String password, String address, int port) { if (password.isEmpty()) { - throw new IllegalArgumentException("nukkit.server.rcon.emptyPasswordError"); + throw new IllegalArgumentException(server.getLanguage().translateString("nukkit.server.rcon.emptyPasswordError")); } this.server = server; @@ -30,10 +31,11 @@ public RCON(Server server, String password, String address, int port) { this.serverThread = new RCONServer(address, port, password); this.serverThread.start(); } catch (IOException e) { - throw new IllegalArgumentException("nukkit.server.rcon.startupError", e); + throw new IllegalArgumentException(server.getLanguage().translateString("nukkit.server.rcon.startupError"), e); } - this.server.getLogger().info(this.server.getLanguage().translateString("nukkit.server.rcon.running", new String[]{address, String.valueOf(port)})); + server.getLogger().info(server.getLanguage().translateString("nukkit.server.rcon.running", new String[]{address, String.valueOf(port)})); + server.getLogger().warning("RCON is not secure! Please consider using other remote control solutions or at least make sure RCON is running behind a firewall."); } public void check() { @@ -54,6 +56,7 @@ public void check() { } this.serverThread.respond(command.getSender(), command.getId(), TextFormat.clean(sender.getMessages())); + sender.clearMessages(); } } @@ -63,8 +66,6 @@ public void close() { serverThread.close(); serverThread.wait(5000); } - } catch (InterruptedException exception) { - // - } + } catch (InterruptedException ignored) {} } } diff --git a/src/main/java/cn/nukkit/network/rcon/RCONCommand.java b/src/main/java/cn/nukkit/network/rcon/RCONCommand.java index a992cd35c24..b85eb5cbe62 100644 --- a/src/main/java/cn/nukkit/network/rcon/RCONCommand.java +++ b/src/main/java/cn/nukkit/network/rcon/RCONCommand.java @@ -8,6 +8,7 @@ * @author Tee7even */ public class RCONCommand { + private final SocketChannel sender; private final int id; private final String command; diff --git a/src/main/java/cn/nukkit/network/rcon/RCONPacket.java b/src/main/java/cn/nukkit/network/rcon/RCONPacket.java index afa057c2753..43cbca63b13 100644 --- a/src/main/java/cn/nukkit/network/rcon/RCONPacket.java +++ b/src/main/java/cn/nukkit/network/rcon/RCONPacket.java @@ -1,6 +1,7 @@ package cn.nukkit.network.rcon; import java.io.IOException; +import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; @@ -10,6 +11,7 @@ * @author Tee7even */ public class RCONPacket { + private final int id; private final int type; private final byte[] payload; @@ -23,6 +25,10 @@ public RCONPacket(int id, int type, byte[] payload) { public RCONPacket(ByteBuffer buffer) throws IOException { int size = buffer.getInt(); + if (size > 524288) { + throw new RuntimeException("Too big RCON packet: " + size); + } + this.id = buffer.getInt(); this.type = buffer.getInt(); this.payload = new byte[size - 10]; @@ -43,7 +49,8 @@ public ByteBuffer toBuffer() { buffer.put((byte) 0); buffer.put((byte) 0); - buffer.flip(); + //noinspection RedundantCast + ((Buffer) buffer).flip(); // do not remove the cast return buffer; } diff --git a/src/main/java/cn/nukkit/network/rcon/RCONServer.java b/src/main/java/cn/nukkit/network/rcon/RCONServer.java index 330db5abe84..946f4f1404e 100644 --- a/src/main/java/cn/nukkit/network/rcon/RCONServer.java +++ b/src/main/java/cn/nukkit/network/rcon/RCONServer.java @@ -4,6 +4,7 @@ import java.io.IOException; import java.net.InetSocketAddress; +import java.nio.Buffer; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.ByteOrder; @@ -12,7 +13,7 @@ import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.channels.spi.SelectorProvider; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.*; /** @@ -21,6 +22,7 @@ * @author Tee7even */ public class RCONServer extends Thread { + private static final int SERVERDATA_AUTH = 3; private static final int SERVERDATA_AUTH_RESPONSE = 2; private static final int SERVERDATA_EXECCOMMAND = 2; @@ -28,10 +30,10 @@ public class RCONServer extends Thread { private volatile boolean running; - private ServerSocketChannel serverChannel; - private Selector selector; + private final ServerSocketChannel serverChannel; + private final Selector selector; - private String password; + private final String password; private final Set rconSessions = new HashSet<>(); private final List receiveQueue = new ArrayList<>(); @@ -101,8 +103,7 @@ public void run() { this.write(key); } } - } catch (BufferUnderflowException exception) { - //Corrupted packet, ignore + } catch (BufferUnderflowException ignored) { } catch (Exception exception) { Server.getInstance().getLogger().logException(exception); } @@ -145,7 +146,8 @@ private void read(SelectionKey key) throws IOException { return; } - buffer.flip(); + //noinspection RedundantCast + ((Buffer) buffer).flip(); // do not remove the cast this.handle(channel, new RCONPacket(buffer)); } @@ -154,12 +156,14 @@ private void handle(SocketChannel channel, RCONPacket packet) { case SERVERDATA_AUTH: byte[] payload = new byte[1]; - if (new String(packet.getPayload(), Charset.forName("UTF-8")).equals(this.password)) { + if (new String(packet.getPayload(), StandardCharsets.UTF_8).equals(this.password)) { this.rconSessions.add(channel); this.send(channel, new RCONPacket(packet.getId(), SERVERDATA_AUTH_RESPONSE, payload)); + try { Server.getInstance().getLogger().info("[RCON] " + channel.getRemoteAddress().toString() + " connected"); } catch (Exception ignored) {} return; } + try { Server.getInstance().getLogger().info("[RCON] Authentication failed for " + channel.getRemoteAddress().toString()); } catch (Exception ignored) {} this.send(channel, new RCONPacket(-1, SERVERDATA_AUTH_RESPONSE, payload)); break; case SERVERDATA_EXECCOMMAND: @@ -167,7 +171,7 @@ private void handle(SocketChannel channel, RCONPacket packet) { return; } - String command = new String(packet.getPayload(), Charset.forName("UTF-8")).trim(); + String command = new String(packet.getPayload(), StandardCharsets.UTF_8).trim(); synchronized (this.receiveQueue) { this.receiveQueue.add(new RCONCommand(channel, packet.getId(), command)); } @@ -213,4 +217,4 @@ private void send(SocketChannel channel, RCONPacket packet) { this.selector.wakeup(); } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/network/session/NetworkPlayerSession.java b/src/main/java/cn/nukkit/network/session/NetworkPlayerSession.java index 166828045f8..1c5d684ba14 100644 --- a/src/main/java/cn/nukkit/network/session/NetworkPlayerSession.java +++ b/src/main/java/cn/nukkit/network/session/NetworkPlayerSession.java @@ -12,10 +12,6 @@ public interface NetworkPlayerSession { void sendPacket(DataPacket packet); void sendImmediatePacket(DataPacket packet, Runnable callback); - default void flush() { - - } - void disconnect(String reason); Player getPlayer(); @@ -26,4 +22,8 @@ default void flush() { default void setEncryption(SecretKey encryptionKey, Cipher encryptionCipher, Cipher decryptionCipher) { } + + default long getPing() { + return -1; + } } diff --git a/src/main/java/cn/nukkit/network/session/RakNetPlayerSession.java b/src/main/java/cn/nukkit/network/session/RakNetPlayerSession.java index a091c76854c..6b706060a92 100644 --- a/src/main/java/cn/nukkit/network/session/RakNetPlayerSession.java +++ b/src/main/java/cn/nukkit/network/session/RakNetPlayerSession.java @@ -5,23 +5,25 @@ import cn.nukkit.Server; import cn.nukkit.network.CompressionProvider; import cn.nukkit.network.RakNetInterface; +import cn.nukkit.network.encryption.Sha256; import cn.nukkit.network.protocol.BatchPacket; import cn.nukkit.network.protocol.DataPacket; import cn.nukkit.network.protocol.DisconnectPacket; -import cn.nukkit.network.protocol.ProtocolInfo; import cn.nukkit.utils.BinaryStream; import com.google.common.base.Preconditions; -import com.nukkitx.natives.sha256.Sha256; -import com.nukkitx.natives.util.Natives; -import com.nukkitx.network.raknet.*; -import com.nukkitx.network.util.DisconnectReason; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.Unpooled; +import io.netty.channel.Channel; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; import io.netty.util.internal.PlatformDependent; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import lombok.extern.log4j.Log4j2; import org.apache.logging.log4j.message.FormattedMessage; +import org.cloudburstmc.netty.channel.raknet.RakChannel; +import org.cloudburstmc.netty.channel.raknet.packet.RakMessage; +import org.cloudburstmc.netty.handler.codec.raknet.common.RakSessionCodec; import javax.crypto.Cipher; import javax.crypto.SecretKey; @@ -35,10 +37,10 @@ import java.util.concurrent.atomic.AtomicLong; @Log4j2 -public class RakNetPlayerSession implements NetworkPlayerSession, RakNetSessionListener { +public class RakNetPlayerSession extends SimpleChannelInboundHandler implements NetworkPlayerSession { private final RakNetInterface server; - private final RakNetServerSession session; + private final Channel channel; private final Queue inbound = PlatformDependent.newSpscQueue(); private final Queue outbound = PlatformDependent.newMpscQueue(); @@ -55,17 +57,26 @@ public class RakNetPlayerSession implements NetworkPlayerSession, RakNetSessionL private Cipher decryptionCipher; private final AtomicLong sentEncryptedPacketCount = new AtomicLong(); - public RakNetPlayerSession(RakNetInterface server, RakNetServerSession session) { + public RakNetPlayerSession(RakNetInterface server, Channel channel) { this.server = server; - this.session = session; - this.tickFuture = session.getEventLoop().scheduleAtFixedRate(this::networkTick, 0, 50, TimeUnit.MILLISECONDS); + this.channel = channel; + this.tickFuture = channel.eventLoop().scheduleAtFixedRate(this::networkTick, 0, 20, TimeUnit.MILLISECONDS); } @Override - public void onEncapsulated(EncapsulatedPacket packet) { - ByteBuf buffer = packet.getBuffer(); + protected void channelRead0(ChannelHandlerContext channelHandlerContext, RakMessage msg) throws Exception { + ByteBuf buffer = msg.content(); short packetId = buffer.readUnsignedByte(); if (packetId == 0xfe) { + int len = buffer.readableBytes(); + if (len > 12582912) { + Server.getInstance().getLogger().error("Received too big packet: " + len); + if (this.player != null) { + this.player.close("Too big packet"); + } + return; + } + byte[] packetBuffer; CompressionProvider compressionIn = CompressionProvider.NONE; @@ -98,29 +109,16 @@ public void onEncapsulated(EncapsulatedPacket packet) { this.server.getNetwork().processBatch(packetBuffer, this.inbound, compressionIn); } catch (Exception e) { this.disconnect("Sent malformed packet"); - log.error("[{}] Unable to process batch packet", (this.player == null ? this.session.getAddress() : this.player.getName()), e); + log.error("[{}] Unable to process batch packet", (this.player == null ? this.channel.remoteAddress() : this.player.getName()), e); } } else if (Nukkit.DEBUG > 1) { - log.debug("Unknown EncapsulatedPacket: " +packetId); + log.debug("Unknown RakMessage: " + packetId); } } @Override - public void onDirect(ByteBuf byteBuf) { - // We don't allow any direct packets so ignore. - } - - @Override - public void onSessionChangeState(RakNetState rakNetState) { - } - - @Override - public void onDisconnect(DisconnectReason reason) { - if (reason == DisconnectReason.TIMED_OUT) { - this.disconnect("Timed out"); - } else { - this.disconnect("Disconnected from Server"); - } + public void channelInactive(ChannelHandlerContext ctx) { + this.disconnect("Disconnected from Server"); // TODO: timeout reason } @Override @@ -135,41 +133,38 @@ public void disconnect(String reason) { } // Give it a short time to make sure cancel message is delivered - this.session.getEventLoop().schedule(() -> this.session.close(), 10, TimeUnit.MILLISECONDS); + this.channel.eventLoop().schedule(() -> this.channel.close(), 10, TimeUnit.MILLISECONDS); } @Override public void sendPacket(DataPacket packet) { - if (this.session.isClosed()) { + if (!this.channel.isActive()) { return; } - if (packet.pid() != ProtocolInfo.BATCH_PACKET) { + if (!(packet instanceof BatchPacket)) { packet.tryEncode(); } + this.outbound.offer(packet); } @Override public void sendImmediatePacket(DataPacket packet, Runnable callback) { - if (this.session.isClosed()) { + if (!this.channel.isActive()) { return; } + this.sendPacket(packet); - this.session.getEventLoop().execute(() -> { + this.channel.eventLoop().execute(() -> { this.networkTick(); callback.run(); }); } - @Override - public void flush() { - this.session.getEventLoop().execute(this::networkTick); - } - private void networkTick() { - if (this.session.isClosed()) { + if (!this.channel.isActive()) { return; } @@ -178,13 +173,13 @@ private void networkTick() { DataPacket packet; while ((packet = this.outbound.poll()) != null) { if (packet instanceof DisconnectPacket) { - BinaryStream batched = new BinaryStream(); byte[] buf = packet.getBuffer(); + BinaryStream batched = new BinaryStream(new byte[5 + buf.length]).reset(); batched.putUnsignedVarInt(buf.length); batched.put(buf); try { - this.sendPacket(this.compressionOut.compress(batched, Server.getInstance().networkCompressionLevel), RakNetPriority.IMMEDIATE); + this.sendPacket(this.compressionOut.compress(batched, Server.getInstance().networkCompressionLevel)); } catch (Exception e) { log.error("Unable to compress disconnect packet", e); } @@ -195,7 +190,7 @@ private void networkTick() { toBatch.clear(); } - this.sendPacket(((BatchPacket) packet).payload, RakNetPriority.MEDIUM); + this.sendPacket(((BatchPacket) packet).payload); } else { toBatch.add(packet); } @@ -205,7 +200,7 @@ private void networkTick() { this.sendPackets(toBatch); } } catch (Throwable e) { - log.error("[{}] Failed to tick RakNetPlayerSession", this.session.getAddress(), e); + log.error("[{}] Failed to tick RakNetPlayerSession", this.channel.remoteAddress(), e); } } @@ -236,13 +231,13 @@ private void sendPackets(Collection packets) { } try { - this.sendPacket(this.compressionOut.compress(batched, Server.getInstance().networkCompressionLevel), RakNetPriority.MEDIUM); + this.sendPacket(this.compressionOut.compress(batched, Server.getInstance().networkCompressionLevel)); } catch (Exception e) { log.error("Unable to compress batched packets", e); } } - private void sendPacket(byte[] compressedPayload, RakNetPriority priority) { + private void sendPacket(byte[] compressedPayload) { ByteBuf finalPayload = ByteBufAllocator.DEFAULT.directBuffer((this.compressionInitialized ? 10 : 9) + compressedPayload.length); // prefix(1)+id(1)+encryption(8)+data finalPayload.writeByte(0xfe); @@ -271,7 +266,7 @@ private void sendPacket(byte[] compressedPayload, RakNetPriority priority) { finalPayload.writeBytes(compressedPayload); } - this.session.send(finalPayload, priority); + this.channel.writeAndFlush(finalPayload); } @Override @@ -296,8 +291,8 @@ public Player getPlayer() { return this.player; } - public RakNetServerSession getRakNetSession() { - return this.session; + public Channel getChannel() { + return this.channel; } public String getDisconnectReason() { @@ -311,7 +306,19 @@ public void setEncryption(SecretKey encryptionKey, Cipher encryptionCipher, Ciph this.decryptionCipher = decryptionCipher; } - private static final ThreadLocal HASH_LOCAL = ThreadLocal.withInitial(Natives.SHA_256); + @Override + public long getPing() { + if (this.channel instanceof RakChannel) { + RakChannel rakChannel = (RakChannel) this.channel; + RakSessionCodec session = rakChannel.rakPipeline().get(RakSessionCodec.class); + if (session != null) { + return session.getPing(); + } + } + return -1; + } + + private static final ThreadLocal HASH_LOCAL = ThreadLocal.withInitial(Sha256::new); private byte[] generateTrailer(ByteBuf buf) { Sha256 hash = HASH_LOCAL.get(); diff --git a/src/main/java/cn/nukkit/permission/BanEntry.java b/src/main/java/cn/nukkit/permission/BanEntry.java index b7bd159f446..1d767c62f3f 100644 --- a/src/main/java/cn/nukkit/permission/BanEntry.java +++ b/src/main/java/cn/nukkit/permission/BanEntry.java @@ -6,23 +6,21 @@ import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.TreeMap; +import java.util.*; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BanEntry { + public static final String format = "yyyy-MM-dd HH:mm:ss Z"; private final String name; - private Date creationDate = null; + private Date creationDate; private String source = "(Unknown)"; private Date expirationDate = null; - private String reason = "Banned by an operator."; + private String reason = "Banned"; public BanEntry(String name) { this.name = name.toLowerCase(); @@ -72,11 +70,11 @@ public void setReason(String reason) { public LinkedHashMap getMap() { LinkedHashMap map = new LinkedHashMap<>(); - map.put("name", getName()); - map.put("creationDate", new SimpleDateFormat(format).format(getCreationDate())); - map.put("source", this.getSource()); - map.put("expireDate", getExpirationDate() != null ? new SimpleDateFormat(format).format(getExpirationDate()) : "Forever"); - map.put("reason", this.getReason()); + map.put("name", name); + map.put("creationDate", new SimpleDateFormat(format).format(creationDate)); + map.put("source", this.source); + map.put("expireDate", expirationDate != null ? new SimpleDateFormat(format).format(expirationDate) : "Forever"); + map.put("reason", this.reason); return map; } @@ -98,8 +96,7 @@ public String getString() { } public static BanEntry fromString(String str) { - Map map = new Gson().fromJson(str, new TypeToken>() { - }.getType()); + Map map = new Gson().fromJson(str, new TreeMapTypeToken().getType()); BanEntry banEntry = new BanEntry(map.get("name")); try { banEntry.setCreationDate(new SimpleDateFormat(format).parse(map.get("creationDate"))); @@ -112,4 +109,6 @@ public static BanEntry fromString(String str) { return banEntry; } + private static class TreeMapTypeToken extends TypeToken> { + } } diff --git a/src/main/java/cn/nukkit/permission/BanList.java b/src/main/java/cn/nukkit/permission/BanList.java index 636a78c0875..27b7e4a96d1 100644 --- a/src/main/java/cn/nukkit/permission/BanList.java +++ b/src/main/java/cn/nukkit/permission/BanList.java @@ -13,7 +13,7 @@ import java.util.*; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class BanList { @@ -42,7 +42,7 @@ public LinkedHashMap getEntires() { } public boolean isBanned(String name) { - if (!this.isEnable() || name == null) { + if (!this.enable || name == null) { return false; } else { this.removeExpired(); @@ -106,17 +106,15 @@ public void load() { this.save(); } else { - LinkedList> list = new Gson().fromJson(Utils.readFile(this.file), new TypeToken>>() { - }.getType()); + LinkedList> list = new Gson().fromJson(Utils.readFile(this.file), new LinkedListTypeToken().getType()); for (TreeMap map : list) { BanEntry entry = BanEntry.fromMap(map); this.list.put(entry.getName(), entry); } } } catch (IOException e) { - MainLogger.getLogger().error("Could not load ban list: ", e); + MainLogger.getLogger().error("Could not load ban list", e); } - } public void save() { @@ -134,7 +132,10 @@ public void save() { } Utils.writeFile(this.file, new ByteArrayInputStream(new GsonBuilder().setPrettyPrinting().create().toJson(list).getBytes(StandardCharsets.UTF_8))); } catch (IOException e) { - MainLogger.getLogger().error("Could not save ban list ", e); + MainLogger.getLogger().error("Could not save ban list", e); } } + + private static class LinkedListTypeToken extends TypeToken>> { + } } diff --git a/src/main/java/cn/nukkit/permission/DefaultPermissions.java b/src/main/java/cn/nukkit/permission/DefaultPermissions.java index 195b843c9bb..6af2185495b 100644 --- a/src/main/java/cn/nukkit/permission/DefaultPermissions.java +++ b/src/main/java/cn/nukkit/permission/DefaultPermissions.java @@ -3,11 +3,10 @@ import cn.nukkit.Server; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public abstract class DefaultPermissions { - public static final String ROOT = "nukkit"; public static Permission registerPermission(Permission perm) { return registerPermission(perm, null); @@ -23,105 +22,105 @@ public static Permission registerPermission(Permission perm, Permission parent) } public static void registerCorePermissions() { - Permission parent = registerPermission(new Permission(ROOT, "Allows using all Nukkit commands and utilities")); + Permission parent = registerPermission(new Permission("nukkit", "Allows using all Nukkit commands and utilities")); - Permission broadcasts = registerPermission(new Permission(ROOT + ".broadcast", "Allows the user to receive all broadcast messages"), parent); + Permission broadcasts = registerPermission(new Permission("nukkit.broadcast", "Allows the user to receive all broadcast messages"), parent); - registerPermission(new Permission(ROOT + ".broadcast.admin", "Allows the user to receive administrative broadcasts", Permission.DEFAULT_OP), broadcasts); - registerPermission(new Permission(ROOT + ".broadcast.user", "Allows the user to receive user broadcasts", Permission.DEFAULT_TRUE), broadcasts); + registerPermission(new Permission("nukkit.broadcast.admin", "Allows the user to receive administrative broadcasts", Permission.DEFAULT_OP), broadcasts); + registerPermission(new Permission("nukkit.broadcast.user", "Allows the user to receive user broadcasts", Permission.DEFAULT_TRUE), broadcasts); broadcasts.recalculatePermissibles(); - Permission commands = registerPermission(new Permission(ROOT + ".command", "Allows using all Nukkit commands"), parent); + Permission commands = registerPermission(new Permission("nukkit.command", "Allows using all Nukkit commands"), parent); - Permission whitelist = registerPermission(new Permission(ROOT + ".command.whitelist", "Allows the user to modify the server whitelist", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.whitelist.add", "Allows the user to add a player to the server whitelist"), whitelist); - registerPermission(new Permission(ROOT + ".command.whitelist.remove", "Allows the user to remove a player to the server whitelist"), whitelist); - registerPermission(new Permission(ROOT + ".command.whitelist.reload", "Allows the user to reload the server whitelist"), whitelist); - registerPermission(new Permission(ROOT + ".command.whitelist.enable", "Allows the user to enable the server whitelist"), whitelist); - registerPermission(new Permission(ROOT + ".command.whitelist.disable", "Allows the user to disable the server whitelist"), whitelist); - registerPermission(new Permission(ROOT + ".command.whitelist.list", "Allows the user to list all the players on the server whitelist"), whitelist); + Permission whitelist = registerPermission(new Permission("nukkit.command.whitelist", "Allows the user to modify the server whitelist", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.whitelist.add", "Allows the user to add a player to the server whitelist"), whitelist); + registerPermission(new Permission("nukkit.command.whitelist.remove", "Allows the user to remove a player to the server whitelist"), whitelist); + registerPermission(new Permission("nukkit.command.whitelist.reload", "Allows the user to reload the server whitelist"), whitelist); + registerPermission(new Permission("nukkit.command.whitelist.enable", "Allows the user to enable the server whitelist"), whitelist); + registerPermission(new Permission("nukkit.command.whitelist.disable", "Allows the user to disable the server whitelist"), whitelist); + registerPermission(new Permission("nukkit.command.whitelist.list", "Allows the user to list all the players on the server whitelist"), whitelist); whitelist.recalculatePermissibles(); - Permission ban = registerPermission(new Permission(ROOT + ".command.ban", "Allows the user to ban people", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.ban.player", "Allows the user to ban players"), ban); - registerPermission(new Permission(ROOT + ".command.ban.ip", "Allows the user to ban IP addresses"), ban); - registerPermission(new Permission(ROOT + ".command.ban.list", "Allows the user to list all the banned ips or players"), ban); + Permission ban = registerPermission(new Permission("nukkit.command.ban", "Allows the user to ban people", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.ban.player", "Allows the user to ban players"), ban); + registerPermission(new Permission("nukkit.command.ban.ip", "Allows the user to ban IP addresses"), ban); + registerPermission(new Permission("nukkit.command.ban.list", "Allows the user to list all the banned ips or players"), ban); ban.recalculatePermissibles(); - Permission unban = registerPermission(new Permission(ROOT + ".command.unban", "Allows the user to unban people", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.unban.player", "Allows the user to unban players"), unban); - registerPermission(new Permission(ROOT + ".command.unban.ip", "Allows the user to unban IP addresses"), unban); + Permission unban = registerPermission(new Permission("nukkit.command.unban", "Allows the user to unban people", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.unban.player", "Allows the user to unban players"), unban); + registerPermission(new Permission("nukkit.command.unban.ip", "Allows the user to unban IP addresses"), unban); unban.recalculatePermissibles(); - Permission op = registerPermission(new Permission(ROOT + ".command.op", "Allows the user to change operators", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.op.give", "Allows the user to give a player operator status"), op); - registerPermission(new Permission(ROOT + ".command.op.take", "Allows the user to take a players operator status"), op); + Permission op = registerPermission(new Permission("nukkit.command.op", "Allows the user to change operators", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.op.give", "Allows the user to give a player operator status"), op); + registerPermission(new Permission("nukkit.command.op.take", "Allows the user to take a players operator status"), op); op.recalculatePermissibles(); - Permission save = registerPermission(new Permission(ROOT + ".command.save", "Allows the user to save the worlds", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.save.enable", "Allows the user to enable automatic saving"), save); - registerPermission(new Permission(ROOT + ".command.save.disable", "Allows the user to disable automatic saving"), save); - registerPermission(new Permission(ROOT + ".command.save.perform", "Allows the user to perform a manual save"), save); + Permission save = registerPermission(new Permission("nukkit.command.save", "Allows the user to save the worlds", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.save.enable", "Allows the user to enable automatic saving"), save); + registerPermission(new Permission("nukkit.command.save.disable", "Allows the user to disable automatic saving"), save); + registerPermission(new Permission("nukkit.command.save.perform", "Allows the user to perform a manual save"), save); save.recalculatePermissibles(); - Permission time = registerPermission(new Permission(ROOT + ".command.time", "Allows the user to alter the time", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.time.add", "Allows the user to fast-forward time"), time); - registerPermission(new Permission(ROOT + ".command.time.set", "Allows the user to change the time"), time); - registerPermission(new Permission(ROOT + ".command.time.start", "Allows the user to restart the time"), time); - registerPermission(new Permission(ROOT + ".command.time.stop", "Allows the user to stop the time"), time); - registerPermission(new Permission(ROOT + ".command.time.query", "Allows the user query the time"), time); + Permission time = registerPermission(new Permission("nukkit.command.time", "Allows the user to alter the time", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.time.add", "Allows the user to fast-forward time"), time); + registerPermission(new Permission("nukkit.command.time.set", "Allows the user to change the time"), time); + registerPermission(new Permission("nukkit.command.time.start", "Allows the user to restart the time"), time); + registerPermission(new Permission("nukkit.command.time.stop", "Allows the user to stop the time"), time); + registerPermission(new Permission("nukkit.command.time.query", "Allows the user query the time"), time); time.recalculatePermissibles(); - Permission kill = registerPermission(new Permission(ROOT + ".command.kill", "Allows the user to kill players", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.kill.self", "Allows the user to commit suicide", Permission.DEFAULT_TRUE), kill); - registerPermission(new Permission(ROOT + ".command.kill.other", "Allows the user to kill other players"), kill); + Permission kill = registerPermission(new Permission("nukkit.command.kill", "Allows the user to kill players", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.kill.self", "Allows the user to commit suicide", Permission.DEFAULT_TRUE), kill); + registerPermission(new Permission("nukkit.command.kill.other", "Allows the user to kill other players"), kill); kill.recalculatePermissibles(); - Permission gamemode = registerPermission(new Permission(ROOT + ".command.gamemode", "Allows the user to change the gamemode of players", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.gamemode.survival", "Allows the user to change the gamemode to survival", Permission.DEFAULT_OP), gamemode); - registerPermission(new Permission(ROOT + ".command.gamemode.creative", "Allows the user to change the gamemode to creative", Permission.DEFAULT_OP), gamemode); - registerPermission(new Permission(ROOT + ".command.gamemode.adventure", "Allows the user to change the gamemode to adventure", Permission.DEFAULT_OP), gamemode); - registerPermission(new Permission(ROOT + ".command.gamemode.spectator", "Allows the user to change the gamemode to spectator", Permission.DEFAULT_OP), gamemode); - registerPermission(new Permission(ROOT + ".command.gamemode.other", "Allows the user to change the gamemode of other players", Permission.DEFAULT_OP), gamemode); + Permission gamemode = registerPermission(new Permission("nukkit.command.gamemode", "Allows the user to change the gamemode of players", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.gamemode.survival", "Allows the user to change the gamemode to survival", Permission.DEFAULT_OP), gamemode); + registerPermission(new Permission("nukkit.command.gamemode.creative", "Allows the user to change the gamemode to creative", Permission.DEFAULT_OP), gamemode); + registerPermission(new Permission("nukkit.command.gamemode.adventure", "Allows the user to change the gamemode to adventure", Permission.DEFAULT_OP), gamemode); + registerPermission(new Permission("nukkit.command.gamemode.spectator", "Allows the user to change the gamemode to spectator", Permission.DEFAULT_OP), gamemode); + registerPermission(new Permission("nukkit.command.gamemode.other", "Allows the user to change the gamemode of other players", Permission.DEFAULT_OP), gamemode); gamemode.recalculatePermissibles(); - registerPermission(new Permission(ROOT + ".command.me", "Allows the user to perform a chat action", Permission.DEFAULT_TRUE), commands); - registerPermission(new Permission(ROOT + ".command.tell", "Allows the user to privately message another player", Permission.DEFAULT_TRUE), commands); - registerPermission(new Permission(ROOT + ".command.say", "Allows the user to talk as the console", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.give", "Allows the user to give items to players", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.clear", "Allows the user to clear items from players", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.effect", "Allows the user to give/take potion effects", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.particle", "Allows the user to create particle effects", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.teleport", "Allows the user to teleport players", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.kick", "Allows the user to kick players", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.stop", "Allows the user to stop the server", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.list", "Allows the user to list all online players", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.help", "Allows the user to view the help menu", Permission.DEFAULT_TRUE), commands); - registerPermission(new Permission(ROOT + ".command.plugins", "Allows the user to view the list of plugins", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.reload", "Allows the user to reload the server settings", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.version", "Allows the user to view the version of the server", Permission.DEFAULT_TRUE), commands); - registerPermission(new Permission(ROOT + ".command.defaultgamemode", "Allows the user to change the default gamemode", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.seed", "Allows the user to view the seed of the world", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.status", "Allows the user to view the server performance", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.gc", "Allows the user to fire garbage collection tasks", Permission.DEFAULT_OP), commands); - //registerPermission(new Permission(ROOT + ".command.dumpmemory", "Allows the user to dump memory contents", Permission.DEFAULT_OP), commands); // this command is not implemented - registerPermission(new Permission(ROOT + ".command.gamerule", "Sets or queries a game rule value", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.timings", "Allows the user to records timings for all plugin events", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.title", "Allows the user to send titles to players", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.spawnpoint", "Allows the user to change player's spawnpoint", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.setworldspawn", "Allows the user to change the world spawn", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.weather", "Allows the user to change the weather", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.xp", "Allows the user to give experience", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.enchant", "Allows the user to enchant items", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.difficulty", "Allows the user to change the difficulty", Permission.DEFAULT_OP), commands); - registerPermission(new Permission(ROOT + ".command.debug.perform", "Allows the user to use debugpaste command", Permission.DEFAULT_OP), commands); - - registerPermission(new Permission(ROOT + ".textcolor", "Allows the user to write colored text", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.me", "Allows the user to perform a chat action", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.tell", "Allows the user to privately message another player", Permission.DEFAULT_TRUE), commands); + registerPermission(new Permission("nukkit.command.say", "Allows the user to talk as the console", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.give", "Allows the user to give items to players", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.clear", "Allows the user to clear items from players", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.effect", "Allows the user to give/take potion effects", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.particle", "Allows the user to create particle effects", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.teleport", "Allows the user to teleport players", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.kick", "Allows the user to kick players", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.stop", "Allows the user to stop the server", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.list", "Allows the user to list all online players", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.help", "Allows the user to view the help menu", Permission.DEFAULT_TRUE), commands); + registerPermission(new Permission("nukkit.command.plugins", "Allows the user to view the list of plugins", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.reload", "Allows the user to reload the server settings", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.version", "Allows the user to view the version of the server", Permission.DEFAULT_TRUE), commands); + registerPermission(new Permission("nukkit.command.version.plugins", "Allows the user to view the version of the plugins", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.defaultgamemode", "Allows the user to change the default gamemode", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.status", "Allows the user to view the server performance", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.gc", "Allows the user to fire garbage collection tasks", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.title", "Allows the user to send titles to players", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.spawnpoint", "Allows the user to change player's spawnpoint", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.setworldspawn", "Allows the user to change the world spawn", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.weather", "Allows the user to change the weather", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.xp", "Allows the user to give experience", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.summon", "Allows the user to summon entities", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.seed", "Allows the user to see world's seed", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.playsound", "Allows the user to play sounds", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.gamerule", "Allows the user to change game rules", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.enchant", "Allows the user to enchant items", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.difficulty", "Allows the user to change difficulty", Permission.DEFAULT_OP), commands); + registerPermission(new Permission("nukkit.command.world.convert", "Allows the user to convert worlds to LevelDB format", Permission.DEFAULT_FALSE), commands); // Console only + + registerPermission(new Permission("nukkit.textcolor", "Allows the user to write colored text", Permission.DEFAULT_OP), commands); commands.recalculatePermissibles(); parent.recalculatePermissibles(); } - } diff --git a/src/main/java/cn/nukkit/permission/Permissible.java b/src/main/java/cn/nukkit/permission/Permissible.java index fd393e4ba94..795c8d3c647 100644 --- a/src/main/java/cn/nukkit/permission/Permissible.java +++ b/src/main/java/cn/nukkit/permission/Permissible.java @@ -5,7 +5,7 @@ import java.util.Map; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface Permissible extends ServerOperator { @@ -29,5 +29,4 @@ public interface Permissible extends ServerOperator { void recalculatePermissions(); Map getEffectivePermissions(); - } diff --git a/src/main/java/cn/nukkit/permission/PermissibleBase.java b/src/main/java/cn/nukkit/permission/PermissibleBase.java index d521a475310..778b8f09eb5 100644 --- a/src/main/java/cn/nukkit/permission/PermissibleBase.java +++ b/src/main/java/cn/nukkit/permission/PermissibleBase.java @@ -4,26 +4,24 @@ import cn.nukkit.plugin.Plugin; import cn.nukkit.utils.PluginException; import cn.nukkit.utils.ServerException; -import co.aikar.timings.Timings; -import java.util.HashMap; -import java.util.HashSet; import java.util.Map; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class PermissibleBase implements Permissible { - ServerOperator opable = null; + private final ServerOperator opable; private Permissible parent = null; - private final Set attachments = new HashSet<>(); + private final Set attachments = ConcurrentHashMap.newKeySet(); - private final Map permissions = new HashMap<>(); + private final Map permissions = new ConcurrentHashMap<>(); public PermissibleBase(ServerOperator opable) { this.opable = opable; @@ -58,8 +56,9 @@ public boolean isPermissionSet(Permission permission) { @Override public boolean hasPermission(String name) { - if (this.isPermissionSet(name)) { - return this.permissions.get(name).getValue(); + PermissionAttachmentInfo isPermissionSet = this.permissions.get(name); + if (isPermissionSet != null) { + return isPermissionSet.getValue(); } Permission perm = Server.getInstance().getPluginManager().getPermission(name); @@ -67,9 +66,11 @@ public boolean hasPermission(String name) { if (perm != null) { String permission = perm.getDefault(); - return Permission.DEFAULT_TRUE.equals(permission) || (this.isOp() && Permission.DEFAULT_OP.equals(permission)) || (!this.isOp() && Permission.DEFAULT_NOT_OP.equals(permission)); + boolean op; + return Permission.DEFAULT_TRUE.equals(permission) || ((op = this.isOp()) && Permission.DEFAULT_OP.equals(permission)) || (!op && Permission.DEFAULT_NOT_OP.equals(permission)); } else { - return Permission.DEFAULT_TRUE.equals(Permission.DEFAULT_PERMISSION) || (this.isOp() && Permission.DEFAULT_OP.equals(Permission.DEFAULT_PERMISSION)) || (!this.isOp() && Permission.DEFAULT_NOT_OP.equals(Permission.DEFAULT_PERMISSION)); + return this.isOp(); + //return Permission.DEFAULT_TRUE.equals(Permission.DEFAULT_PERMISSION) || ((op = this.isOp()) && Permission.DEFAULT_OP.equals(Permission.DEFAULT_PERMISSION)) || (!op && Permission.DEFAULT_NOT_OP.equals(Permission.DEFAULT_PERMISSION)); } } @@ -118,8 +119,6 @@ public void removeAttachment(PermissionAttachment attachment) { @Override public void recalculatePermissions() { - Timings.permissibleCalculationTimer.startTiming(); - this.clearPermissions(); Map defaults = Server.getInstance().getPluginManager().getDefaultPermissions(this.isOp()); Server.getInstance().getPluginManager().subscribeToDefaultPerms(this.isOp(), this.parent != null ? this.parent : this); @@ -134,7 +133,6 @@ public void recalculatePermissions() { for (PermissionAttachment attachment : this.attachments) { this.calculateChildPermissions(attachment.getPermissions(), false, attachment); } - Timings.permissibleCalculationTimer.stopTiming(); } public void clearPermissions() { @@ -142,7 +140,6 @@ public void clearPermissions() { Server.getInstance().getPluginManager().unsubscribeFromPermission(name, this.parent != null ? this.parent : this); } - Server.getInstance().getPluginManager().unsubscribeFromDefaultPerms(false, this.parent != null ? this.parent : this); Server.getInstance().getPluginManager().unsubscribeFromDefaultPerms(true, this.parent != null ? this.parent : this); diff --git a/src/main/java/cn/nukkit/permission/Permission.java b/src/main/java/cn/nukkit/permission/Permission.java index 00039105b87..e3cbaf346ec 100644 --- a/src/main/java/cn/nukkit/permission/Permission.java +++ b/src/main/java/cn/nukkit/permission/Permission.java @@ -5,7 +5,7 @@ import java.util.*; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class Permission { @@ -47,7 +47,7 @@ public static String getByName(String value) { private String description; - private Map children = new HashMap<>(); + private final Map children; private String defaultValue; @@ -114,7 +114,7 @@ public void recalculatePermissibles() { } public void addParent(Permission permission, boolean value) { - this.getChildren().put(this.getName(), value); + this.children.put(this.name, value); permission.recalculatePermissibles(); } @@ -173,9 +173,7 @@ public static Permission loadPermission(String name, Map data, S Object v = entry.getValue(); if (v instanceof Map) { Permission permission = loadPermission(k, (Map) v, defaultValue, output); - if (permission != null) { - output.add(permission); - } + output.add(permission); } children.put(k, true); } @@ -190,5 +188,4 @@ public static Permission loadPermission(String name, Map data, S return new Permission(name, desc, defaultValue, children); } - } diff --git a/src/main/java/cn/nukkit/permission/PermissionAttachment.java b/src/main/java/cn/nukkit/permission/PermissionAttachment.java index 1103b658f57..bfe5a70caa4 100644 --- a/src/main/java/cn/nukkit/permission/PermissionAttachment.java +++ b/src/main/java/cn/nukkit/permission/PermissionAttachment.java @@ -8,7 +8,7 @@ import java.util.Map; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class PermissionAttachment { @@ -17,9 +17,9 @@ public class PermissionAttachment { private final Map permissions = new HashMap<>(); - private Permissible permissible; + private final Permissible permissible; - private Plugin plugin; + private final Plugin plugin; public PermissionAttachment(Plugin plugin, Permissible permissible) { if (!plugin.isEnabled()) { @@ -95,5 +95,4 @@ public void unsetPermission(String name, boolean value) { public void remove() { this.permissible.removeAttachment(this); } - } diff --git a/src/main/java/cn/nukkit/permission/PermissionAttachmentInfo.java b/src/main/java/cn/nukkit/permission/PermissionAttachmentInfo.java index 0e952fea9ea..10d02619d58 100644 --- a/src/main/java/cn/nukkit/permission/PermissionAttachmentInfo.java +++ b/src/main/java/cn/nukkit/permission/PermissionAttachmentInfo.java @@ -1,16 +1,16 @@ package cn.nukkit.permission; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class PermissionAttachmentInfo { - private Permissible permissible; + private final Permissible permissible; - private String permission; + private final String permission; - private PermissionAttachment attachment; + private final PermissionAttachment attachment; private boolean value; @@ -40,4 +40,13 @@ public PermissionAttachment getAttachment() { public boolean getValue() { return value; } + + /** + * Set value. + * + * @param value value + */ + public void setValue(boolean value) { + this.value = value; + } } diff --git a/src/main/java/cn/nukkit/permission/PermissionRemovedExecutor.java b/src/main/java/cn/nukkit/permission/PermissionRemovedExecutor.java index 35008233126..8d6affbe412 100644 --- a/src/main/java/cn/nukkit/permission/PermissionRemovedExecutor.java +++ b/src/main/java/cn/nukkit/permission/PermissionRemovedExecutor.java @@ -1,7 +1,7 @@ package cn.nukkit.permission; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public interface PermissionRemovedExecutor { diff --git a/src/main/java/cn/nukkit/permission/ServerOperator.java b/src/main/java/cn/nukkit/permission/ServerOperator.java index 1051458a49a..cd0575655de 100644 --- a/src/main/java/cn/nukkit/permission/ServerOperator.java +++ b/src/main/java/cn/nukkit/permission/ServerOperator.java @@ -1,32 +1,24 @@ package cn.nukkit.permission; /** - * 能成为服务器管理员(OP)的对象。
- * Who can be an operator(OP). + * Who can be an operator (OP). * * @author MagicDroidX(code) @ Nukkit Project - * @author 粉鞋大妈(javadoc) @ Nukkit Project * @see cn.nukkit.permission.Permissible - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public interface ServerOperator { /** - * 返回这个对象是不是服务器管理员。
* Returns if this object is an operator. * - * @return 这个对象是不是服务器管理员。
if this object is an operator. - * @since Nukkit 1.0 | Nukkit API 1.0.0 + * @return if this object is an operator. */ boolean isOp(); /** - * 把这个对象设置成服务器管理员。
* Sets this object to be an operator or not to be. * - * @param value {@code true}为授予管理员,{@code false}为取消管理员。
- * {@code true} for giving this operator or {@code false} for cancelling. - * @since Nukkit 1.0 | Nukkit API 1.0.0 + * @param value {@code true} for giving this operator or {@code false} for cancelling. */ void setOp(boolean value); } diff --git a/src/main/java/cn/nukkit/plugin/EventExecutor.java b/src/main/java/cn/nukkit/plugin/EventExecutor.java index f9c4ee692a5..297e0e4a2d6 100644 --- a/src/main/java/cn/nukkit/plugin/EventExecutor.java +++ b/src/main/java/cn/nukkit/plugin/EventExecutor.java @@ -5,7 +5,7 @@ import cn.nukkit.utils.EventException; /** - * author: iNevet + * @author iNevet * Nukkit Project */ public interface EventExecutor { diff --git a/src/main/java/cn/nukkit/plugin/JavaPluginLoader.java b/src/main/java/cn/nukkit/plugin/JavaPluginLoader.java index 8c1b7501567..f713b35654d 100644 --- a/src/main/java/cn/nukkit/plugin/JavaPluginLoader.java +++ b/src/main/java/cn/nukkit/plugin/JavaPluginLoader.java @@ -58,11 +58,10 @@ public Plugin loadPlugin(File file) throws Exception { return plugin; } catch (ClassCastException e) { - throw new PluginException("Error whilst initializing main class `" + description.getMain() + "'", e); + throw new PluginException("Error whilst initializing main class `" + description.getMain() + '\'', e); } catch (InstantiationException | IllegalAccessException e) { Server.getInstance().getLogger().logException(e); } - } catch (ClassNotFoundException e) { throw new PluginException("Couldn't load plugin " + description.getName() + ": main class not found"); } @@ -99,9 +98,11 @@ public PluginDescription getPluginDescription(String filename) { return this.getPluginDescription(new File(filename)); } + private static final Pattern[] FILTERS = new Pattern[]{Pattern.compile("^.+\\.jar$")}; + @Override public Pattern[] getPluginFilters() { - return new Pattern[]{Pattern.compile("^.+\\.jar$")}; + return FILTERS; } private void initPlugin(PluginBase plugin, PluginDescription description, File dataFolder, File file) { @@ -143,8 +144,7 @@ Class getClassByName(final String name) { try { cachedClass = loader.findClass(name, false); - } catch (ClassNotFoundException e) { - //ignore + } catch (ClassNotFoundException ignored) { } if (cachedClass != null) { return cachedClass; @@ -159,8 +159,4 @@ void setClass(final String name, final Class clazz) { classes.put(name, clazz); } } - - private void removeClass(String name) { - Class clazz = classes.remove(name); - } } diff --git a/src/main/java/cn/nukkit/plugin/LambdaEventExecutor.java b/src/main/java/cn/nukkit/plugin/LambdaEventExecutor.java new file mode 100644 index 00000000000..70c05f6611c --- /dev/null +++ b/src/main/java/cn/nukkit/plugin/LambdaEventExecutor.java @@ -0,0 +1,29 @@ +package cn.nukkit.plugin; + +import cn.nukkit.event.Event; +import cn.nukkit.event.Listener; +import cn.nukkit.utils.EventException; + +import java.util.function.BiConsumer; + +public class LambdaEventExecutor implements EventExecutor { + + private final Class clazz; + private final BiConsumer callback; + + public LambdaEventExecutor(Class clazz, BiConsumer callback) { + this.clazz = clazz; + this.callback = callback; + } + + @Override + public void execute(Listener listener, Event event) throws EventException { + if (clazz.isAssignableFrom(event.getClass())) { + try { + this.callback.accept(listener, event); + } catch (Throwable t) { + throw new EventException(t); + } + } + } +} diff --git a/src/main/java/cn/nukkit/plugin/Library.java b/src/main/java/cn/nukkit/plugin/Library.java index 02cd7a356dd..b5f8eff9566 100644 --- a/src/main/java/cn/nukkit/plugin/Library.java +++ b/src/main/java/cn/nukkit/plugin/Library.java @@ -1,8 +1,5 @@ package cn.nukkit.plugin; -/** - * Created on 15-12-13. - */ public interface Library { String getGroupId(); @@ -10,5 +7,4 @@ public interface Library { String getArtifactId(); String getVersion(); - } diff --git a/src/main/java/cn/nukkit/plugin/LibraryLoadException.java b/src/main/java/cn/nukkit/plugin/LibraryLoadException.java index f274d277d95..509dc852f8a 100644 --- a/src/main/java/cn/nukkit/plugin/LibraryLoadException.java +++ b/src/main/java/cn/nukkit/plugin/LibraryLoadException.java @@ -1,12 +1,9 @@ package cn.nukkit.plugin; -/** - * Created on 15-12-13. - */ +@SuppressWarnings("serial") public class LibraryLoadException extends RuntimeException { public LibraryLoadException(Library library) { super("Load library " + library.getArtifactId() + " failed!"); } - } diff --git a/src/main/java/cn/nukkit/plugin/LibraryLoader.java b/src/main/java/cn/nukkit/plugin/LibraryLoader.java index 3ea82670da1..7bb98c0f79c 100644 --- a/src/main/java/cn/nukkit/plugin/LibraryLoader.java +++ b/src/main/java/cn/nukkit/plugin/LibraryLoader.java @@ -10,9 +10,6 @@ import java.nio.file.Files; import java.util.logging.Logger; -/** - * Created on 15-12-13. - */ public class LibraryLoader { private static final File BASE_FOLDER = new File("./libraries"); @@ -21,7 +18,7 @@ public class LibraryLoader { static { if (BASE_FOLDER.mkdir()) { - LOGGER.info("Created libraries folder."); + LOGGER.info("[LibraryLoader] Created libraries folder"); } } @@ -84,5 +81,4 @@ public static void load(Library library) { public static File getBaseFolder() { return BASE_FOLDER; } - } diff --git a/src/main/java/cn/nukkit/plugin/MethodEventExecutor.java b/src/main/java/cn/nukkit/plugin/MethodEventExecutor.java index 79bac4bf19e..5efd61626a8 100644 --- a/src/main/java/cn/nukkit/plugin/MethodEventExecutor.java +++ b/src/main/java/cn/nukkit/plugin/MethodEventExecutor.java @@ -8,7 +8,7 @@ import java.lang.reflect.Method; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class MethodEventExecutor implements EventExecutor { diff --git a/src/main/java/cn/nukkit/plugin/Plugin.java b/src/main/java/cn/nukkit/plugin/Plugin.java index f53c1e3d751..5566a3e862b 100644 --- a/src/main/java/cn/nukkit/plugin/Plugin.java +++ b/src/main/java/cn/nukkit/plugin/Plugin.java @@ -10,41 +10,38 @@ /** * 所有Nukkit插件必须实现的接口。
* An interface what must be implemented by all Nukkit plugins. - * - *

对于插件作者,我们建议让插件主类继承{@link cn.nukkit.plugin.PluginBase}类,而不是实现这个接口。
+ *

+ * 对于插件作者,我们建议让插件主类继承{@link cn.nukkit.plugin.PluginBase}类,而不是实现这个接口。
* For plugin developers: it's recommended to use {@link cn.nukkit.plugin.PluginBase} for an actual plugin - * instead of implement this interface.

+ * instead of implement this interface. * * @author MagicDroidX(code) @ Nukkit Project * @author 粉鞋大妈(javadoc) @ Nukkit Project * @see cn.nukkit.plugin.PluginBase * @see cn.nukkit.plugin.PluginDescription - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public interface Plugin extends CommandExecutor { /** * 在一个Nukkit插件被加载时调用的方法。这个方法会在{@link Plugin#onEnable()}之前调用。
* Called when a Nukkit plugin is loaded, before {@link Plugin#onEnable()} . + *

+ * 应该填写加载插件时需要作出的动作。例如:初始化数组、初始化数据库连接。
+ * Use this to init a Nukkit plugin, such as init arrays or init database connections. * - *

应该填写加载插件时需要作出的动作。例如:初始化数组、初始化数据库连接。
- * Use this to init a Nukkit plugin, such as init arrays or init database connections.

- * - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ void onLoad(); /** * 在一个Nukkit插件被启用时调用的方法。
* Called when a Nukkit plugin is enabled. - * - *

应该填写插件启用时需要作出的动作。例如:读取配置文件、读取资源、连接数据库。
- * Use this to open config files, open resources, connect databases.

- * - *

注意到可能存在的插件管理器插件,这个方法在插件多次重启时可能被调用多次。
+ *

+ * 应该填写插件启用时需要作出的动作。例如:读取配置文件、读取资源、连接数据库。
+ * Use this to open config files, open resources, connect databases. + *

+ * 注意到可能存在的插件管理器插件,这个方法在插件多次重启时可能被调用多次。
* Notes that there may be plugin manager plugins, - * this method can be called many times when a plugin is restarted many times.

+ * this method can be called many times when a plugin is restarted many times. * - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ void onEnable(); @@ -53,23 +50,21 @@ public interface Plugin extends CommandExecutor { * Whether this Nukkit plugin is enabled. * * @return 这个插件是否已经启用。
Whether this plugin is enabled. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ boolean isEnabled(); /** * 在一个Nukkit插件被停用时调用的方法。
* Called when a Nukkit plugin is disabled. - * - *

应该填写插件停用时需要作出的动作。例如:关闭数据库,断开资源。
+ *

+ * 应该填写插件停用时需要作出的动作。例如:关闭数据库,断开资源。
* Use this to free open things and finish actions, - * such as disconnecting databases and close resources.

- * - *

注意到可能存在的插件管理器插件,这个方法在插件多次重启时可能被调用多次。
+ * such as disconnecting databases and close resources. + *

+ * 注意到可能存在的插件管理器插件,这个方法在插件多次重启时可能被调用多次。
* Notes that there may be plugin manager plugins, - * this method can be called many times when a plugin is restarted many times.

+ * this method can be called many times when a plugin is restarted many times. * - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ void onDisable(); @@ -78,100 +73,94 @@ public interface Plugin extends CommandExecutor { * Whether this Nukkit plugin is disabled. * * @return 这个插件是否已经停用。
Whether this plugin is disabled. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ boolean isDisabled(); /** * 返回这个Nukkit插件的数据文件夹。
* The data folder of this Nukkit plugin. - * - *

一般情况下,数据文件夹名字与插件名字相同,而且都放在nukkit安装目录下的plugins文件夹里。
+ *

+ * 一般情况下,数据文件夹名字与插件名字相同,而且都放在nukkit安装目录下的plugins文件夹里。
* Under normal circumstances, the data folder has the same name with the plugin, - * and is placed in the 'plugins' folder inside the nukkit installation directory.

+ * and is placed in the 'plugins' folder inside the nukkit installation directory. * * @return 这个插件的数据文件夹。
The data folder of this plugin. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ File getDataFolder(); /** * 返回描述这个Nukkit插件的{@link PluginDescription}对象。
* The description this Nukkit plugin as a {@link PluginDescription} object. - * - *

对于jar格式的Nukkit插件,插件的描述在plugin.yml文件内定义。
- * For jar-packed Nukkit plugins, the description is defined in the 'plugin.yml' file.

+ *

+ * 对于jar格式的Nukkit插件,插件的描述在plugin.yml文件内定义。
+ * For jar-packed Nukkit plugins, the description is defined in the 'plugin.yml' file. * * @return 这个插件的描述。
A description of this plugin. * @see cn.nukkit.plugin.PluginDescription - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ PluginDescription getDescription(); /** * 读取这个插件特定的资源文件,并返回为{@code InputStream}对象。
* Reads a resource of this plugin, and returns as an {@code InputStream} object. - * - *

对于jar格式的Nukkit插件,Nukkit会在jar包内的资源文件夹(一般为resources文件夹)寻找资源文件。
+ *

+ * 对于jar格式的Nukkit插件,Nukkit会在jar包内的资源文件夹(一般为resources文件夹)寻找资源文件。
* For jar-packed Nukkit plugins, Nukkit will look for your resource file in the resources folder, - * which is normally named 'resources' and placed in plugin jar file.

- * - *

当你需要把一个文件的所有内容读取为字符串,可以使用{@link cn.nukkit.utils.Utils#readFile}函数, + * which is normally named 'resources' and placed in plugin jar file. + *

+ * 当你需要把一个文件的所有内容读取为字符串,可以使用 函数, * 来从{@code InputStream}读取所有内容为字符串。例如:
- * When you need to read the whole file content as a String, you can use {@link cn.nukkit.utils.Utils#readFile} - * to read from a {@code InputStream} and get whole content as a String. For example:

- *

String string = Utils.readFile(this.getResource("string.txt"));

+ * When you need to read the whole file content as a String, you can use + * to read from a {@code InputStream} and get whole content as a String. For example: + * {@code String string = Utils.readFile(this.getResource("string.txt"));} * * @param filename 要读取的资源文件名字。
The name of the resource file to read. * @return 读取的资源文件的 {@code InputStream}对象。若错误会返回{@code null}
* The resource as an {@code InputStream} object, or {@code null} when an error occurred. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ InputStream getResource(String filename); /** * 保存这个Nukkit插件的资源。
* Saves the resource of this plugin. - * - *

对于jar格式的Nukkit插件,Nukkit会在jar包内的资源文件夹寻找资源文件,然后保存到数据文件夹。
+ *

+ * 对于jar格式的Nukkit插件,Nukkit会在jar包内的资源文件夹寻找资源文件,然后保存到数据文件夹。
* For jar-packed Nukkit plugins, Nukkit will look for your resource file in the resources folder, - * which is normally named 'resources' and placed in plugin jar file, and copy it into data folder.

- * - *

这个函数通常用来在插件被加载(load)时,保存默认的资源文件。这样插件在启用(enable)时不会错误读取空的资源文件, + * which is normally named 'resources' and placed in plugin jar file, and copy it into data folder. + *

+ * 这个函数通常用来在插件被加载(load)时,保存默认的资源文件。这样插件在启用(enable)时不会错误读取空的资源文件, * 用户也无需从开发者处手动下载资源文件后再使用插件。
* This is usually used to save the default plugin resource when the plugin is LOADED .If this is used, * it won't happen to load an empty resource when plugin is ENABLED, and plugin users are not required to get - * default resources from the developer and place it manually.

- * - *

如果需要替换已存在的资源文件,建议使用{@link cn.nukkit.plugin.Plugin#saveResource(String, boolean)}
+ * default resources from the developer and place it manually. + *

+ * 如果需要替换已存在的资源文件,建议使用{@link cn.nukkit.plugin.Plugin#saveResource(String, boolean)}
* If you need to REPLACE an existing resource file, it's recommended - * to use {@link cn.nukkit.plugin.Plugin#saveResource(String, boolean)}.

+ * to use {@link cn.nukkit.plugin.Plugin#saveResource(String, boolean)}. * * @param filename 要保存的资源文件名字。
The name of the resource file to save. * @return 保存是否成功。
true if the saving action is successful. * @see cn.nukkit.plugin.Plugin#saveDefaultConfig * @see cn.nukkit.plugin.Plugin#saveResource(String, boolean) - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ boolean saveResource(String filename); /** * 保存或替换这个Nukkit插件的资源。
* Saves or replaces the resource of this plugin. - * - *

对于jar格式的Nukkit插件,Nukkit会在jar包内的资源文件夹寻找资源文件,然后保存到数据文件夹。
+ *

+ * 对于jar格式的Nukkit插件,Nukkit会在jar包内的资源文件夹寻找资源文件,然后保存到数据文件夹。
* For jar-packed Nukkit plugins, Nukkit will look for your resource file in the resources folder, - * which is normally named 'resources' and placed in plugin jar file, and copy it into data folder.

- * - *

如果需要保存默认的资源文件,建议使用{@link cn.nukkit.plugin.Plugin#saveResource(String)}
+ * which is normally named 'resources' and placed in plugin jar file, and copy it into data folder. + *

+ * 如果需要保存默认的资源文件,建议使用{@link cn.nukkit.plugin.Plugin#saveResource(String)}
* If you need to SAVE DEFAULT resource file, it's recommended - * to use {@link cn.nukkit.plugin.Plugin#saveResource(String)}.

+ * to use {@link cn.nukkit.plugin.Plugin#saveResource(String)}. * * @param filename 要保存的资源文件名字。
The name of the resource file to save. * @param replace 是否替换目标文件。
if true, Nukkit will replace the target resource file. * @return 保存是否成功。
true if the saving action is successful. * @see cn.nukkit.plugin.Plugin#saveResource(String) - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ boolean saveResource(String filename, boolean replace); @@ -181,13 +170,12 @@ public interface Plugin extends CommandExecutor { /** * 返回这个Nukkit插件配置文件的{@link cn.nukkit.utils.Config}对象。
* The config file this Nukkit plugin as a {@link cn.nukkit.utils.Config} object. - * - *

一般地,插件的配置保存在数据文件夹下的config.yml文件。
- * Normally, the plugin config is saved in the 'config.yml' file in its data folder.

+ *

+ * 一般地,插件的配置保存在数据文件夹下的config.yml文件。
+ * Normally, the plugin config is saved in the 'config.yml' file in its data folder. * * @return 插件的配置文件。
The configuration of this plugin. * @see cn.nukkit.plugin.Plugin#getDataFolder - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ Config getConfig(); @@ -196,42 +184,39 @@ public interface Plugin extends CommandExecutor { * Saves the plugin config. * * @see cn.nukkit.plugin.Plugin#getDataFolder - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ void saveConfig(); /** * 保存这个Nukkit插件的默认配置文件。
* Saves the DEFAULT plugin config. - * - *

执行这个函数时,Nukkit会在资源文件夹内寻找开发者配置好的默认配置文件config.yml,然后保存在数据文件夹。 + *

+ * 执行这个函数时,Nukkit会在资源文件夹内寻找开发者配置好的默认配置文件config.yml,然后保存在数据文件夹。 * 如果数据文件夹已经有一个config.yml文件,Nukkit不会替换这个文件。
* When this is used, Nukkit will look for the default 'config.yml' file which is configured by plugin developer - * and save it to the data folder. If a config.yml file exists in the data folder, Nukkit won't replace it.

- * - *

这个函数通常用来在插件被加载(load)时,保存默认的配置文件。这样插件在启用(enable)时不会错误读取空的配置文件, + * and save it to the data folder. If a config.yml file exists in the data folder, Nukkit won't replace it. + *

+ * 这个函数通常用来在插件被加载(load)时,保存默认的配置文件。这样插件在启用(enable)时不会错误读取空的配置文件, * 用户也无需从开发者处手动下载配置文件保存后再使用插件。
* This is usually used to save the default plugin config when the plugin is LOADED .If this is used, * it won't happen to load an empty config when plugin is ENABLED, and plugin users are not required to get - * default config from the developer and place it manually.

+ * default config from the developer and place it manually. * * @see cn.nukkit.plugin.Plugin#getDataFolder * @see cn.nukkit.plugin.Plugin#saveResource - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ void saveDefaultConfig(); /** * 重新读取这个Nukkit插件的默认配置文件。
* Reloads the plugin config. - * - *

执行这个函数时,Nukkit会从数据文件夹中的config.yml文件重新加载配置。 + *

+ * 执行这个函数时,Nukkit会从数据文件夹中的config.yml文件重新加载配置。 * 这样用户在调整插件配置后,无需重启就可以马上使用新的配置。
* By using this, Nukkit will reload the config from 'config.yml' file, then it isn't necessary to restart - * for plugin user who changes the config and needs to use new config at once.

+ * for plugin user who changes the config and needs to use new config at once. * * @see cn.nukkit.plugin.Plugin#getDataFolder - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ void reloadConfig(); @@ -240,31 +225,28 @@ public interface Plugin extends CommandExecutor { * Gets the server which is running this plugin, and returns as a {@link cn.nukkit.Server} object. * * @see cn.nukkit.Server - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ Server getServer(); /** * 返回这个插件的名字。
* Returns the name of this plugin. - * - *

Nukkit会从已经读取的插件描述中获取插件的名字。
- * Nukkit will read plugin name from plugin description.

+ *

+ * Nukkit会从已经读取的插件描述中获取插件的名字。
+ * Nukkit will read plugin name from plugin description. * * @see cn.nukkit.plugin.Plugin#getDescription - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ String getName(); /** * 返回这个插件的日志记录器为{@link cn.nukkit.plugin.PluginLogger}对象。
* Returns the logger of this plugin as a {@link cn.nukkit.plugin.PluginLogger} object. - * - *

使用日志记录器,你可以在控制台和日志文件输出信息。
- * You can use a plugin logger to output messages to the console and log file.

+ *

+ * 使用日志记录器,你可以在控制台和日志文件输出信息。
+ * You can use a plugin logger to output messages to the console and log file. * * @see cn.nukkit.plugin.PluginLogger - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ PluginLogger getLogger(); @@ -273,8 +255,6 @@ public interface Plugin extends CommandExecutor { * Returns the loader of this plugin as a {@link cn.nukkit.plugin.PluginLoader} object. * * @see cn.nukkit.plugin.PluginLoader - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ PluginLoader getPluginLoader(); - } diff --git a/src/main/java/cn/nukkit/plugin/PluginBase.java b/src/main/java/cn/nukkit/plugin/PluginBase.java index 0cb31902274..75b54b23d82 100644 --- a/src/main/java/cn/nukkit/plugin/PluginBase.java +++ b/src/main/java/cn/nukkit/plugin/PluginBase.java @@ -26,7 +26,6 @@ * @author MagicDroidX(code) @ Nukkit Project * @author 粉鞋大妈(javadoc) @ Nukkit Project * @see cn.nukkit.plugin.PluginDescription - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ abstract public class PluginBase implements Plugin { @@ -67,10 +66,9 @@ public final boolean isEnabled() { * 加载这个插件。
* Enables this plugin. *

- *

如果你需要卸载这个插件,建议使用{@link #setEnabled(boolean)}
- * If you need to disable this plugin, it's recommended to use {@link #setEnabled(boolean)}

+ * 如果你需要卸载这个插件,建议使用{@link #setEnabled(boolean)}
+ * If you need to disable this plugin, it's recommended to use {@link #setEnabled(boolean)} * - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public final void setEnabled() { this.setEnabled(true); @@ -80,11 +78,10 @@ public final void setEnabled() { * 加载或卸载这个插件。
* Enables or disables this plugin. *

- *

插件管理器插件常常使用这个方法。
- * It's normally used by a plugin manager plugin to manage plugins.

+ * 插件管理器插件常常使用这个方法。
+ * It's normally used by a plugin manager plugin to manage plugins. * * @param value {@code true}为加载,{@code false}为卸载。
{@code true} for enable, {@code false} for disable. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public final void setEnabled(boolean value) { if (isEnabled != value) { @@ -113,8 +110,8 @@ public final PluginDescription getDescription() { * 初始化这个插件。
* Initialize the plugin. *

- *

这个方法会在加载(load)之前被插件加载器调用,初始化关于插件的一些事项,不能被重写。
- * Called by plugin loader before load, and initialize the plugin. Can't be overridden.

+ * 这个方法会在加载(load)之前被插件加载器调用,初始化关于插件的一些事项,不能被重写。
+ * Called by plugin loader before load, and initialize the plugin. Can't be overridden. * * @param loader 加载这个插件的插件加载器的{@code PluginLoader}对象。
* The plugin loader ,which loads this plugin, as a {@code PluginLoader} object. @@ -126,7 +123,6 @@ public final PluginDescription getDescription() { * The data folder of this plugin. * @param file 这个插件的文件{@code File}对象。对于jar格式的插件,就是jar文件本身。
* The {@code File} object of this plugin itself. For jar-packed plugins, it is the jar file itself. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public final void init(PluginLoader loader, Server server, PluginDescription description, File dataFolder, File file) { if (!initialized) { @@ -150,7 +146,6 @@ public PluginLogger getLogger() { * Returns if this plugin is initialized. * * @return 这个插件是否已初始化。
if this plugin is initialized. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public final boolean isInitialized() { return initialized; @@ -160,9 +155,9 @@ public final boolean isInitialized() { * TODO: FINISH JAVADOC */ public PluginIdentifiableCommand getCommand(String name) { - PluginIdentifiableCommand command = this.getServer().getPluginCommand(name); + PluginIdentifiableCommand command = this.server.getPluginCommand(name); if (command == null || !command.getPlugin().equals(this)) { - command = this.getServer().getPluginCommand(this.description.getName().toLowerCase() + ":" + name); + command = this.server.getPluginCommand(this.description.getName().toLowerCase() + ':' + name); } if (command != null && command.getPlugin().equals(this)) { @@ -195,7 +190,7 @@ public boolean saveResource(String filename, boolean replace) { @Override public boolean saveResource(String filename, String outputName, boolean replace) { Preconditions.checkArgument(filename != null && outputName != null, "Filename can not be null!"); - Preconditions.checkArgument(filename.trim().length() != 0 && outputName.trim().length() != 0, "Filename can not be empty!"); + Preconditions.checkArgument(!filename.trim().isEmpty() && !outputName.trim().isEmpty(), "Filename can not be empty!"); File out = new File(dataFolder, outputName); if (!out.exists() || replace) { @@ -227,7 +222,7 @@ public Config getConfig() { @Override public void saveConfig() { if (!this.getConfig().save()) { - this.getLogger().critical("Could not save config to " + this.configFile.toString()); + this.logger.critical("Could not save config to " + this.configFile.toString()); } } @@ -270,13 +265,12 @@ public String getName() { * 返回这个插件完整的名字。
* Returns the full name of this plugin. *

- *

一个插件完整的名字由{@code 名字+" v"+版本号}组成。比如:
- * A full name of a plugin is composed by {@code name+" v"+version}.for example:

- *

{@code HelloWorld v1.0.0}

+ * 一个插件完整的名字由{@code 名字+" v"+版本号}组成。比如:
+ * A full name of a plugin is composed by {@code name+" v"+version}.for example: + * {@code HelloWorld v1.0.0} * * @return 这个插件完整的名字。
The full name of this plugin. * @see cn.nukkit.plugin.PluginDescription#getFullName - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public final String getFullName() { return this.description.getFullName(); @@ -287,9 +281,8 @@ public final String getFullName() { * Returns the {@code File} object of this plugin itself. For jar-packed plugins, it is the jar file itself. * * @return 这个插件的文件 {@code File}对象。
The {@code File} object of this plugin itself. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ - protected File getFile() { + public File getFile() { return file; } diff --git a/src/main/java/cn/nukkit/plugin/PluginClassLoader.java b/src/main/java/cn/nukkit/plugin/PluginClassLoader.java index 29d5208098b..1904bf19e89 100644 --- a/src/main/java/cn/nukkit/plugin/PluginClassLoader.java +++ b/src/main/java/cn/nukkit/plugin/PluginClassLoader.java @@ -6,15 +6,14 @@ import java.net.URLClassLoader; import java.util.HashMap; import java.util.Map; -import java.util.Set; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class PluginClassLoader extends URLClassLoader { - private JavaPluginLoader loader; + private final JavaPluginLoader loader; private final Map classes = new HashMap<>(); @@ -53,9 +52,4 @@ protected Class findClass(String name, boolean checkGlobal) throws ClassNotFo return result; } - - Set getClasses() { - return classes.keySet(); - } - } diff --git a/src/main/java/cn/nukkit/plugin/PluginDescription.java b/src/main/java/cn/nukkit/plugin/PluginDescription.java index e62bc82c608..d28a11f63b7 100644 --- a/src/main/java/cn/nukkit/plugin/PluginDescription.java +++ b/src/main/java/cn/nukkit/plugin/PluginDescription.java @@ -6,20 +6,12 @@ import org.yaml.snakeyaml.Yaml; import java.util.*; - -/* TODO Add these to Javadoc: - *
  • softdepend
    - *
    - *
  • - *
  • loadbefore
    - *
    - *
  • - */ +import java.util.regex.Pattern; /** * 描述一个Nukkit插件的类。
    * Describes a Nukkit plugin. - * + *

    * 在jar格式的插件中,插件的描述内容可以在plugin.yml中定义。比如这个:
    * The description of a jar-packed plugin can be defined in the 'plugin.yml' file. For example: *

    @@ -28,9 +20,9 @@
      * version: "1.0.0"
      * api: ["1.0.0"]
      * load: POSTWORLD
    - * author: 粉鞋大妈
    + * @author 粉鞋大妈
      * description: A simple Hello World plugin for Nukkit
    - * website: http://www.cnblogs.com/xtypr
    + * website: ...
      * permissions:
      *  helloworldplugin.command.helloworld:
      *   description: Allows to use helloworld command.
    @@ -49,11 +41,10 @@
      * {@code name},{@code main},{@code version} and {@code api}.You are supposed to fill these items to make sure
      * your plugin can be normally loaded by Nukkit.
    * - *

    接下来对所有的字段做一些说明,加粗的字段表示必需,斜体表示可选:(来自 + * 接下来对所有的字段做一些说明,加粗的字段表示必需,斜体表示可选:(来自 * 粉鞋大妈的博客文章
    * Here are some instructions for there items, bold means required, italic means optional: (From * a blog article of @粉鞋大妈) - *

    *
      *
    • name
      * 字符串,表示这个插件的名字,名字是区分不同插件的标准之一。 @@ -105,7 +96,6 @@ * @author 粉鞋大妈(javadoc) @ Nukkit Project * @see Plugin * @see PluginLoadOrder - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public class PluginDescription { @@ -136,14 +126,18 @@ public PluginDescription(String yamlString) { this.loadMap(yaml.loadAs(yamlString, LinkedHashMap.class)); } + private static final Pattern FILTER = Pattern.compile("[^A-Za-z0-9 _.-]"); + private void loadMap(Map plugin) throws PluginException { - this.name = ((String) plugin.get("name")).replaceAll("[^A-Za-z0-9 _.-]", ""); - if (this.name.equals("")) { - throw new PluginException("Invalid PluginDescription name"); + this.name = FILTER.matcher((String) plugin.get("name")).replaceAll(""); + if (this.name.isEmpty()) { + throw new PluginException("plugin.yml must contain 'name'"); } + this.name = this.name.replace(" ", "_"); this.version = String.valueOf(plugin.get("version")); this.main = (String) plugin.get("main"); + Object api = plugin.get("api"); if (api instanceof List) { this.api = (List) api; @@ -152,8 +146,9 @@ private void loadMap(Map plugin) throws PluginException { list.add((String) api); this.api = list; } + if (this.main.startsWith("cn.nukkit.")) { - throw new PluginException("Invalid PluginDescription main, cannot start within the cn.nukkit. package"); + throw new PluginException(this.name + " has an invalid 'main' in plugin.yml (plugins can't be in cn.nukkit): " + this.main); } if (plugin.containsKey("commands") && plugin.get("commands") instanceof Map) { @@ -189,7 +184,7 @@ private void loadMap(Map plugin) throws PluginException { try { this.order = PluginLoadOrder.valueOf(order); } catch (Exception e) { - throw new PluginException("Invalid PluginDescription load"); + throw new PluginException(this.name + " has an invalid 'load' in plugin.yml: " + order); } } @@ -209,14 +204,12 @@ private void loadMap(Map plugin) throws PluginException { /** * 返回这个插件完整的名字。
      * Returns the full name of this plugin. - * - *

      一个插件完整的名字由{@code 名字+" v"+版本号}组成。比如:
      - * A full name of a plugin is composed by {@code name+" v"+version}.for example:

      - *

      {@code HelloWorld v1.0.0}

      + *

      + * 一个插件完整的名字由{@code 名字+" v"+版本号}组成。比如:
      + * A full name of a plugin is composed by {@code name+" v"+version}.for example: + * {@code HelloWorld v1.0.0} * * @return 这个插件完整的名字。
      The full name of this plugin. - * @see PluginDescription - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public String getFullName() { return this.name + " v" + this.version; @@ -227,8 +220,6 @@ public String getFullName() { * Returns all Nukkit API versions this plugin supports. * * @return 这个插件支持的Nukkit API版本列表。
      A list of all Nukkit API versions String this plugin supports. - * @see PluginDescription - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public List getCompatibleAPIs() { return api; @@ -239,8 +230,6 @@ public List getCompatibleAPIs() { * Returns all the authors of this plugin. * * @return 这个插件的作者列表。
      A list of all authors of this plugin. - * @see PluginDescription - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public List getAuthors() { return authors; @@ -249,16 +238,14 @@ public List getAuthors() { /** * 返回这个插件的信息前缀。
      * Returns the message title of this plugin. - * - *

      插件的信息前缀在记录器记录信息时,会作为信息头衔使用。如果没有定义记录器,会使用插件的名字作为信息头衔。
      + *

      + * 插件的信息前缀在记录器记录信息时,会作为信息头衔使用。如果没有定义记录器,会使用插件的名字作为信息头衔。
      * When a PluginLogger logs, the message title is used as the prefix of message. If prefix is undefined, - * the plugin name will be used instead.

      + * the plugin name will be used instead. * * @return 这个插件的作信息前缀。如果没定义,返回{@code null}。
      * The message title of this plugin, or{@code null} if undefined. * @see PluginLogger - * @see PluginDescription - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public String getPrefix() { return prefix; @@ -269,8 +256,6 @@ public String getPrefix() { * Returns all the defined commands of this plugin. * * @return 这个插件定义的命令列表。
      A map of all defined commands of this plugin. - * @see PluginDescription - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public Map getCommands() { return commands; @@ -279,7 +264,7 @@ public Map getCommands() { /** * 返回这个插件所依赖的插件名字。
      * The names of the plugins what is depended by this plugin. - * + *

      * Nukkit插件的依赖有这些注意事项:
      Here are some note for Nukkit plugin depending: *

        *
      • 一个插件不能依赖自己(否则会报错)。
        A plugin can not depend on itself (or there will be an exception).
      • @@ -290,16 +275,14 @@ public Map getCommands() { * When the required dependency plugin does not exists, Nukkit won't load this plugin, but will tell the * user that this dependency is required. *
      - * - *

      举个例子,如果A插件依赖于B插件,在没有安装B插件而安装A插件的情况下,Nukkit会阻止A插件的加载。 + * + * 举个例子,如果A插件依赖于B插件,在没有安装B插件而安装A插件的情况下,Nukkit会阻止A插件的加载。 * 只有在安装B插件前安装了它所依赖的A插件,Nukkit才会允许加载B插件。
      * For example, there is a Plugin A which relies on Plugin B. If you installed A without installing B, * Nukkit won't load A because its dependency B is lost. Only when B is installed, A will be loaded - * by Nukkit.

      + * by Nukkit. * * @return 插件名字列表的 {@code List}对象。
      A {@code List} object carries the plugin names. - * @see PluginDescription - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public List getDepend() { return depend; @@ -310,8 +293,6 @@ public List getDepend() { * Returns the description text of this plugin. * * @return 这个插件的描述文字。
      The description text of this plugin. - * @see PluginDescription - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public String getDescription() { return description; @@ -327,15 +308,13 @@ public List getLoadBefore() { /** * 返回这个插件的主类名。
      * Returns the main class name of this plugin. - * - *

      一个插件的加载都是从主类开始的。主类的名字在插件的配置文件中定义后可以通过这个函数返回。一个返回值例子:
      + *

      + * 一个插件的加载都是从主类开始的。主类的名字在插件的配置文件中定义后可以通过这个函数返回。一个返回值例子:
      * The load action of a Nukkit plugin begins from main class. The name of main class should be defined * in the plugin configuration, and it can be returned by this function. An example for return value:
      - * {@code "com.example.ExamplePlugin"}

      + * {@code "com.example.ExamplePlugin"} * * @return 这个插件的主类名。
      The main class name of this plugin. - * @see PluginDescription - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public String getMain() { return main; @@ -346,8 +325,6 @@ public String getMain() { * Returns the name of this plugin. * * @return 这个插件的名字。
      The name of this plugin. - * @see PluginDescription - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public String getName() { return name; @@ -358,9 +335,7 @@ public String getName() { * Returns the order the plugin loads, or when the plugin is loaded. * * @return 这个插件加载的顺序。
      The order the plugin loads. - * @see PluginDescription * @see PluginLoadOrder - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public PluginLoadOrder getOrder() { return order; @@ -371,8 +346,6 @@ public PluginLoadOrder getOrder() { * Returns all the defined permissions of this plugin. * * @return 这个插件定义的权限列表。
      A map of all defined permissions of this plugin. - * @see PluginDescription - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public List getPermissions() { return permissions; @@ -390,8 +363,6 @@ public List getSoftDepend() { * Returns the version string of this plugin. * * @return 这个插件的版本号。
      The version string od this plugin. - * @see PluginDescription - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public String getVersion() { return version; @@ -402,8 +373,6 @@ public String getVersion() { * Returns the website of this plugin. * * @return 这个插件的网站。
      The website of this plugin. - * @see PluginDescription - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public String getWebsite() { return website; diff --git a/src/main/java/cn/nukkit/plugin/PluginLoadOrder.java b/src/main/java/cn/nukkit/plugin/PluginLoadOrder.java index 341730ed834..3a87dff020b 100644 --- a/src/main/java/cn/nukkit/plugin/PluginLoadOrder.java +++ b/src/main/java/cn/nukkit/plugin/PluginLoadOrder.java @@ -4,15 +4,14 @@ * 描述一个Nukkit插件加载顺序的类。
      * Describes a Nukkit plugin load order. *

      - *

      Nukkit插件的加载顺序有两个:{@link cn.nukkit.plugin.PluginLoadOrder#STARTUP} + * Nukkit插件的加载顺序有两个:{@link cn.nukkit.plugin.PluginLoadOrder#STARTUP} * 和 {@link cn.nukkit.plugin.PluginLoadOrder#POSTWORLD}。
      * The load order of a Nukkit plugin can be {@link cn.nukkit.plugin.PluginLoadOrder#STARTUP} - * or {@link cn.nukkit.plugin.PluginLoadOrder#POSTWORLD}.

      + * or {@link cn.nukkit.plugin.PluginLoadOrder#POSTWORLD}. * * @author MagicDroidX(code) @ Nukkit Project * @author iNevet(code) @ Nukkit Project * @author 粉鞋大妈(javadoc) @ Nukkit Project - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public enum PluginLoadOrder { /** @@ -20,7 +19,6 @@ public enum PluginLoadOrder { * Indicates that the plugin will be loaded at startup. * * @see cn.nukkit.plugin.PluginLoadOrder - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ STARTUP, /** @@ -28,7 +26,6 @@ public enum PluginLoadOrder { * Indicates that the plugin will be loaded after the first/default world was created. * * @see cn.nukkit.plugin.PluginLoadOrder - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ POSTWORLD } diff --git a/src/main/java/cn/nukkit/plugin/PluginLoader.java b/src/main/java/cn/nukkit/plugin/PluginLoader.java index 4d36c55fbbf..35eba5447d5 100644 --- a/src/main/java/cn/nukkit/plugin/PluginLoader.java +++ b/src/main/java/cn/nukkit/plugin/PluginLoader.java @@ -10,108 +10,100 @@ * @author iNevet(code) @ Nukkit Project * @author 粉鞋大妈(javadoc) @ Nukkit Project * @see JavaPluginLoader - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public interface PluginLoader { /** * 通过文件名字的字符串,来加载和初始化一个插件。
      * Loads and initializes a plugin by its file name. - * - *

      这个方法应该设置好插件的相关属性。比如,插件所在的服务器对象,插件的加载器对象,插件的描述对象,插件的数据文件夹。
      + *

      + * 这个方法应该设置好插件的相关属性。比如,插件所在的服务器对象,插件的加载器对象,插件的描述对象,插件的数据文件夹。
      * Properties for loaded plugin should be set in this method. Such as, the {@code Server} object for which this * plugin is running in, the {@code PluginLoader} object for its loader, and the {@code File} object for its - * data folder.

      - * - *

      如果插件加载失败,这个方法应该返回{@code null},或者抛出异常。
      + * data folder. + *

      + * 如果插件加载失败,这个方法应该返回{@code null},或者抛出异常。
      * If the plugin loader does not load this plugin successfully, a {@code null} should be returned, - * or an exception should be thrown.

      + * or an exception should be thrown. * * @param filename 这个插件的文件名字字符串。
      A string of its file name. * @return 加载完毕的插件的 {@code Plugin}对象。
      The loaded plugin as a {@code Plugin} object. * @throws java.lang.Exception 插件加载失败所抛出的异常。
      Thrown when an error occurred. * @see #loadPlugin(File) * @see cn.nukkit.plugin.PluginBase#init(PluginLoader, cn.nukkit.Server, PluginDescription, File, File) - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ Plugin loadPlugin(String filename) throws Exception; /** * 通过插件的 {@code File}对象,来加载和初始化一个插件。
      * Loads and initializes a plugin by a {@code File} object describes the file. - * - *

      这个方法应该设置好插件的相关属性。比如,插件所在的服务器对象,插件的加载器对象,插件的描述对象,插件的数据文件夹。
      + *

      + * 这个方法应该设置好插件的相关属性。比如,插件所在的服务器对象,插件的加载器对象,插件的描述对象,插件的数据文件夹。
      * Properties for loaded plugin should be set in this method. Such as, the {@code Server} object for which this * plugin is running in, the {@code PluginLoader} object for its loader, and the {@code File} object for its - * data folder.

      - * - *

      如果插件加载失败,这个方法应该返回{@code null},或者抛出异常。
      + * data folder. + *

      + * 如果插件加载失败,这个方法应该返回{@code null},或者抛出异常。
      * If the plugin loader does not load this plugin successfully, a {@code null} should be returned, - * or an exception should be thrown.

      + * or an exception should be thrown. * * @param file 这个插件的文件的 {@code File}对象。
      A {@code File} object for this plugin. * @return 加载完毕的插件的 {@code Plugin}对象。
      The loaded plugin as a {@code Plugin} object. * @throws java.lang.Exception 插件加载失败所抛出的异常。
      Thrown when an error occurred. * @see #loadPlugin(String) * @see cn.nukkit.plugin.PluginBase#init(PluginLoader, cn.nukkit.Server, PluginDescription, File, File) - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ Plugin loadPlugin(File file) throws Exception; /** * 通过插件文件名的字符串,来获得描述这个插件的 {@code PluginDescription}对象。
      * Gets a {@code PluginDescription} object describes the plugin by its file name. - * - *

      如果插件的描述对象获取失败,这个方法应该返回{@code null}。
      - * If the plugin loader does not get its description successfully, a {@code null} should be returned.

      + *

      + * 如果插件的描述对象获取失败,这个方法应该返回{@code null}。
      + * If the plugin loader does not get its description successfully, a {@code null} should be returned. * * @param filename 这个插件的文件名字。
      A string of its file name. * @return 描述这个插件的 {@code PluginDescription}对象。
      * A {@code PluginDescription} object describes the plugin. * @see #getPluginDescription(File) - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ PluginDescription getPluginDescription(String filename); /** * 通过插件的 {@code File}对象,来获得描述这个插件的 {@code PluginDescription}对象。
      * Gets a {@code PluginDescription} object describes the plugin by a {@code File} object describes the plugin file. - * - *

      如果插件的描述对象获取失败,这个方法应该返回{@code null}。
      - * If the plugin loader does not get its description successfully, a {@code null} should be returned.

      + *

      + * 如果插件的描述对象获取失败,这个方法应该返回{@code null}。
      + * If the plugin loader does not get its description successfully, a {@code null} should be returned. * * @param file 这个插件的文件的 {@code File}对象。
      A {@code File} object for this plugin. * @return 描述这个插件的 {@code PluginDescription}对象。
      * A {@code PluginDescription} object describes the plugin. * @see #getPluginDescription(String) - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ PluginDescription getPluginDescription(File file); /** * 返回这个插件加载器支持的文件类型。
      * Returns the file types this plugin loader supports. - * - *

      在Nukkit读取所有插件时,插件管理器会查找所有已经安装的插件加载器,通过识别这个插件是否满足下面的条件, + *

      + * 在Nukkit读取所有插件时,插件管理器会查找所有已经安装的插件加载器,通过识别这个插件是否满足下面的条件, * 来选择对应的插件加载器。
      * When Nukkit is trying to load all its plugins, the plugin manager will look for all installed plugin loader, - * and choose the correct one by checking if this plugin matches the filters given below.

      - * - *

      举个例子,识别这个文件是否以jar为扩展名,它的正则表达式是:
      + * and choose the correct one by checking if this plugin matches the filters given below. + *

      + * 举个例子,识别这个文件是否以jar为扩展名,它的正则表达式是:
      * For example, to check if this file is has a "jar" extension, the regular expression should be:
      * {@code ^.+\\.jar$}
      * 所以只读取jar扩展名的插件加载器,这个函数应该写成:
      * So, for a jar-extension-only file plugin loader, this method should be: - *

      *
       {@code           @Override}
            *      public Pattern[] getPluginFilters() {
            *          return new Pattern[]{Pattern.compile("^.+\\.jar$")};
      -     *      }
      -     * 
      + * }
    * * @return 表达这个插件加载器支持的文件类型的正则表达式数组。
    * An array of regular expressions, that describes what kind of file this plugin loader supports. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ Pattern[] getPluginFilters(); @@ -121,7 +113,6 @@ public interface PluginLoader { * * @param plugin 要被启用的插件。
    The plugin to enable. * @see #disablePlugin - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ void enablePlugin(Plugin plugin); @@ -131,8 +122,6 @@ public interface PluginLoader { * * @param plugin 要被停用的插件。
    The plugin to disable. * @see #enablePlugin - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ void disablePlugin(Plugin plugin); - } diff --git a/src/main/java/cn/nukkit/plugin/PluginLogger.java b/src/main/java/cn/nukkit/plugin/PluginLogger.java index 9b7f50229c1..95064713144 100644 --- a/src/main/java/cn/nukkit/plugin/PluginLogger.java +++ b/src/main/java/cn/nukkit/plugin/PluginLogger.java @@ -5,7 +5,7 @@ import cn.nukkit.utils.Logger; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class PluginLogger implements Logger { @@ -14,7 +14,7 @@ public class PluginLogger implements Logger { public PluginLogger(Plugin context) { String prefix = context.getDescription().getPrefix(); - this.pluginName = prefix != null ? "[" + prefix + "] " : "[" + context.getDescription().getName() + "] "; + this.pluginName = prefix != null ? '[' + prefix + "] " : '[' + context.getDescription().getName() + "] "; } @Override @@ -106,5 +106,4 @@ public void debug(String message, Throwable t) { public void log(LogLevel level, String message, Throwable t) { Server.getInstance().getLogger().log(level, this.pluginName + message, t); } - } diff --git a/src/main/java/cn/nukkit/plugin/PluginManager.java b/src/main/java/cn/nukkit/plugin/PluginManager.java index 0ee96b95d06..b172782c25c 100644 --- a/src/main/java/cn/nukkit/plugin/PluginManager.java +++ b/src/main/java/cn/nukkit/plugin/PluginManager.java @@ -1,5 +1,6 @@ package cn.nukkit.plugin; +import cn.nukkit.Nukkit; import cn.nukkit.Server; import cn.nukkit.command.PluginCommand; import cn.nukkit.command.SimpleCommandMap; @@ -9,19 +10,25 @@ import cn.nukkit.utils.MainLogger; import cn.nukkit.utils.PluginException; import cn.nukkit.utils.Utils; -import co.aikar.timings.Timing; -import co.aikar.timings.Timings; +import com.google.common.reflect.TypeToken; +import org.lanternpowered.lmbda.LambdaFactory; +import org.lanternpowered.lmbda.LambdaType; import java.io.File; +import java.lang.invoke.MethodHandles; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BiConsumer; import java.util.regex.Pattern; /** * @author MagicDroidX */ public class PluginManager { + private static final MethodHandles.Lookup CALLER = MethodHandles.lookup(); + private static final LambdaType> EVENT_EXECUTOR_TYPE = LambdaType.of(new TypeToken>(){}.getType()); private final Server server; @@ -29,17 +36,17 @@ public class PluginManager { protected final Map plugins = new LinkedHashMap<>(); - protected final Map permissions = new HashMap<>(); + protected final Map permissions = new ConcurrentHashMap<>(); - protected final Map defaultPerms = new HashMap<>(); + protected final Map defaultPerms = new ConcurrentHashMap<>(); - protected final Map defaultPermsOp = new HashMap<>(); + protected final Map defaultPermsOp = new ConcurrentHashMap<>(); - protected final Map> permSubs = new HashMap<>(); + protected final Map> permSubs = new ConcurrentHashMap<>(); - protected final Set defSubs = Collections.newSetFromMap(new WeakHashMap<>()); + protected final Set defSubs = ConcurrentHashMap.newKeySet(); - protected final Set defSubsOp = Collections.newSetFromMap(new WeakHashMap<>()); + protected final Set defSubsOp = ConcurrentHashMap.newKeySet(); protected final Map fileAssociations = new HashMap<>(); @@ -49,10 +56,7 @@ public PluginManager(Server server, SimpleCommandMap commandMap) { } public Plugin getPlugin(String name) { - if (this.plugins.containsKey(name)) { - return this.plugins.get(name); - } - return null; + return this.plugins.get(name); } public boolean registerInterface(Class loaderClass) { @@ -223,8 +227,7 @@ public Map loadPlugins(File dictionary, List newLoaders, } } } catch (Exception e) { - this.server.getLogger().error(this.server.getLanguage().translateString("nukkit.plugin" + - ".fileError", file.getName(), dictionary.toString(), Utils + this.server.getLogger().error(this.server.getLanguage().translateString("nukkit.plugin.fileError", file.getName(), dictionary.toString(), Utils .getExceptionMessage(e))); MainLogger logger = this.server.getLogger(); if (logger != null) { @@ -243,8 +246,7 @@ public Map loadPlugins(File dictionary, List newLoaders, if (loadedPlugins.containsKey(dependency) || this.getPlugin(dependency) != null) { dependencies.get(name).remove(dependency); } else if (!plugins.containsKey(dependency)) { - this.server.getLogger().critical(this.server.getLanguage().translateString("nukkit" + - ".plugin.loadError", new String[]{name, "%nukkit.plugin.unknownDependency"}) + ": " + dependency); + this.server.getLogger().critical(this.server.getLanguage().translateString("nukkit.plugin.loadError", new String[]{name, "%nukkit.plugin.unknownDependency"}) + ' ' + dependency); break; } } @@ -255,8 +257,11 @@ public Map loadPlugins(File dictionary, List newLoaders, } if (softDependencies.containsKey(name)) { - softDependencies.get(name).removeIf(dependency -> - loadedPlugins.containsKey(dependency) || this.getPlugin(dependency) != null); + for (String dependency : new ArrayList<>(softDependencies.get(name))) { + if (loadedPlugins.containsKey(dependency) || this.getPlugin(dependency) != null) { + softDependencies.get(name).remove(dependency); + } + } if (softDependencies.get(name).isEmpty()) { softDependencies.remove(name); @@ -307,10 +312,7 @@ public Map loadPlugins(File dictionary, List newLoaders, } public Permission getPermission(String name) { - if (this.permissions.containsKey(name)) { - return this.permissions.get(name); - } - return null; + return this.permissions.get(name); } public boolean addPermission(Permission permission) { @@ -349,7 +351,6 @@ public void recalculatePermissionDefaults(Permission permission) { } private void calculatePermissionDefault(Permission permission) { - Timings.permissionDefaultTimer.startTiming(); if (permission.getDefault().equals(Permission.DEFAULT_OP) || permission.getDefault().equals(Permission.DEFAULT_TRUE)) { this.defaultPermsOp.put(permission.getName(), permission); this.dirtyPermissibles(true); @@ -359,7 +360,6 @@ private void calculatePermissionDefault(Permission permission) { this.defaultPerms.put(permission.getName(), permission); this.dirtyPermissibles(false); } - Timings.permissionDefaultTimer.startTiming(); } private void dirtyPermissibles(boolean op) { @@ -370,7 +370,7 @@ private void dirtyPermissibles(boolean op) { public void subscribeToPermission(String permission, Permissible permissible) { if (!this.permSubs.containsKey(permission)) { - this.permSubs.put(permission, Collections.newSetFromMap(new WeakHashMap<>())); + this.permSubs.put(permission, ConcurrentHashMap.newKeySet()); } this.permSubs.get(permission).add(permissible); } @@ -378,7 +378,7 @@ public void subscribeToPermission(String permission, Permissible permissible) { public void unsubscribeFromPermission(String permission, Permissible permissible) { if (this.permSubs.containsKey(permission)) { this.permSubs.get(permission).remove(permissible); - if (this.permSubs.get(permission).size() == 0) { + if (this.permSubs.get(permission).isEmpty()) { this.permSubs.remove(permission); } } @@ -444,6 +444,7 @@ public void enablePlugin(Plugin plugin) { } } + @SuppressWarnings("unchecked") protected List parseYamlCommands(Plugin plugin) { List pluginCmds = new ArrayList<>(); @@ -497,7 +498,7 @@ protected List parseYamlCommands(Plugin plugin) { } public void disablePlugins() { - ListIterator plugins = new ArrayList<>(this.getPlugins().values()).listIterator(this.getPlugins().size()); + ListIterator plugins = new ArrayList<>(this.plugins.values()).listIterator(this.plugins.size()); while (plugins.hasPrevious()) { this.disablePlugin(plugins.previous()); @@ -534,7 +535,12 @@ public void clearPlugins() { public void callEvent(Event event) { try { - for (RegisteredListener registration : getEventListeners(event.getClass()).getRegisteredListeners()) { + RegisteredListener[] listeners = this.getEventListeners(event.getClass()).getRegisteredListeners(); + if (listeners == null) { + return; + } + + for (RegisteredListener registration : listeners) { if (!registration.getPlugin().isEnabled()) { continue; } @@ -556,7 +562,6 @@ public void registerEvents(Listener listener, Plugin plugin) { throw new PluginException("Plugin attempted to register " + listener.getClass().getName() + " while not enabled"); } - Map, Set> ret = new HashMap<>(); Set methods; try { Method[] publicMethods = listener.getClass().getMethods(); @@ -585,16 +590,21 @@ public void registerEvents(Listener listener, Plugin plugin) { final Class eventClass = checkClass.asSubclass(Event.class); method.setAccessible(true); - for (Class clazz = eventClass; Event.class.isAssignableFrom(clazz); clazz = clazz.getSuperclass()) { - // This loop checks for extending deprecated events - if (clazz.getAnnotation(Deprecated.class) != null) { - if (Boolean.parseBoolean(String.valueOf(this.server.getConfig("settings.deprecated-verbose", true)))) { + if (Nukkit.DEBUG > 1) { + for (Class clazz = eventClass; Event.class.isAssignableFrom(clazz); clazz = clazz.getSuperclass()) { + if (clazz.getAnnotation(Deprecated.class) != null) { this.server.getLogger().warning(this.server.getLanguage().translateString("nukkit.plugin.deprecatedEvent", plugin.getName(), clazz.getName(), listener.getClass().getName() + "." + method.getName() + "()")); + break; } - break; } } - this.registerEvent(eventClass, listener, eh.priority(), new MethodEventExecutor(method), plugin, eh.ignoreCancelled()); + + try { + BiConsumer consumer = LambdaFactory.create(EVENT_EXECUTOR_TYPE, CALLER.unreflect(method)); + this.registerEvent(eventClass, listener, eh.priority(), new LambdaEventExecutor(eventClass, consumer), plugin, eh.ignoreCancelled()); + } catch (IllegalAccessException e) { + plugin.getLogger().error(plugin.getDescription().getFullName() + " attempted to register an invalid EventHandler method signature \"" + method.toGenericString() + "\" in " + listener.getClass()); + } } } @@ -608,23 +618,34 @@ public void registerEvent(Class event, Listener listener, Event } try { - Timing timing = Timings.getPluginEventTiming(event, listener, executor, plugin); - this.getEventListeners(event).register(new RegisteredListener(listener, executor, priority, plugin, ignoreCancelled, timing)); + this.getEventListeners(event).register(new RegisteredListener(listener, executor, priority, plugin, ignoreCancelled)); } catch (IllegalAccessException e) { Server.getInstance().getLogger().logException(e); } } private HandlerList getEventListeners(Class type) throws IllegalAccessException { + HandlerList handlerList = HandlerList.getCachedHandlerList(type); + if (handlerList != null) { + return handlerList; + } + try { Method method = getRegistrationClass(type).getDeclaredMethod("getHandlers"); method.setAccessible(true); - return (HandlerList) method.invoke(null); + handlerList = (HandlerList) method.invoke(null); } catch (NullPointerException e) { - throw new IllegalArgumentException("getHandlers method in " + type.getName() + " was not static!"); + if (Nukkit.DEBUG > 1) { + Server.getInstance().getLogger().debug("Static getHandlers method in " + type.getName() + " was not found. Creating HandlerList dynamically."); + } } catch (Exception e) { throw new IllegalAccessException(Utils.getExceptionMessage(e)); } + + if (handlerList == null) { // do not require user to create static HandlerList anymore + HandlerList.putCachedHandlerList(type, handlerList = new HandlerList()); + } + return handlerList; } private Class getRegistrationClass(Class clazz) throws IllegalAccessException { @@ -633,7 +654,7 @@ private Class getRegistrationClass(Class clazz return clazz; } catch (NoSuchMethodException e) { if (clazz.getSuperclass() != null - && !clazz.getSuperclass().equals(Event.class) + && clazz.getSuperclass() != Event.class && Event.class.isAssignableFrom(clazz.getSuperclass())) { return getRegistrationClass(clazz.getSuperclass().asSubclass(Event.class)); } else { diff --git a/src/main/java/cn/nukkit/plugin/RegisteredListener.java b/src/main/java/cn/nukkit/plugin/RegisteredListener.java index 0744db1f04c..9c6a6f0e025 100644 --- a/src/main/java/cn/nukkit/plugin/RegisteredListener.java +++ b/src/main/java/cn/nukkit/plugin/RegisteredListener.java @@ -5,10 +5,9 @@ import cn.nukkit.event.EventPriority; import cn.nukkit.event.Listener; import cn.nukkit.utils.EventException; -import co.aikar.timings.Timing; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class RegisteredListener { @@ -23,15 +22,12 @@ public class RegisteredListener { private final boolean ignoreCancelled; - private final Timing timing; - - public RegisteredListener(Listener listener, EventExecutor executor, EventPriority priority, Plugin plugin, boolean ignoreCancelled, Timing timing) { + public RegisteredListener(Listener listener, EventExecutor executor, EventPriority priority, Plugin plugin, boolean ignoreCancelled) { this.listener = listener; this.priority = priority; this.plugin = plugin; this.executor = executor; this.ignoreCancelled = ignoreCancelled; - this.timing = timing; } public Listener getListener() { @@ -48,13 +44,11 @@ public EventPriority getPriority() { public void callEvent(Event event) throws EventException { if (event instanceof Cancellable) { - if (event.isCancelled() && isIgnoringCancelled()) { + if (event.isCancelled() && ignoreCancelled) { return; } } - this.timing.startTiming(); executor.execute(listener, event); - this.timing.stopTiming(); } public boolean isIgnoringCancelled() { diff --git a/src/main/java/cn/nukkit/plugin/service/NKServiceManager.java b/src/main/java/cn/nukkit/plugin/service/NKServiceManager.java index 95bfa43a082..5f4ffa94160 100644 --- a/src/main/java/cn/nukkit/plugin/service/NKServiceManager.java +++ b/src/main/java/cn/nukkit/plugin/service/NKServiceManager.java @@ -1,6 +1,5 @@ package cn.nukkit.plugin.service; - import cn.nukkit.Server; import cn.nukkit.plugin.Plugin; import com.google.common.base.Preconditions; @@ -8,18 +7,15 @@ import java.util.*; -/** - * Created on 16-11-20. - */ public class NKServiceManager implements ServiceManager { private final Map, List>> handle = new HashMap<>(); @Override public boolean register(Class service, T provider, Plugin plugin, ServicePriority priority) { - Preconditions.checkNotNull(provider); - Preconditions.checkNotNull(priority); - Preconditions.checkNotNull(service); + Preconditions.checkNotNull(provider, "provider"); + Preconditions.checkNotNull(priority, "priority"); + Preconditions.checkNotNull(service, "service"); // build-in service provider needn't plugin param if (plugin == null && provider.getClass().getClassLoader() != Server.class.getClassLoader()) { @@ -63,7 +59,6 @@ public List> cancel(Plugin plugin) { builder.add(registered); } } - } } @@ -71,6 +66,7 @@ public List> cancel(Plugin plugin) { } @Override + @SuppressWarnings("unchecked") public RegisteredServiceProvider cancel(Class service, T provider) { RegisteredServiceProvider result = null; @@ -85,13 +81,13 @@ public RegisteredServiceProvider cancel(Class service, T provider) { result = next; } } - } return result; } @Override + @SuppressWarnings("unchecked") public RegisteredServiceProvider getProvider(Class service) { synchronized (handle) { List> list = handle.get(service); @@ -126,8 +122,7 @@ public List> getRegistrations(Class service) synchronized (handle) { List> registered = handle.get(service); if (registered == null) { - ImmutableList> empty = ImmutableList.of(); - return empty; + return ImmutableList.of(); } for (RegisteredServiceProvider provider : registered) { builder.add((RegisteredServiceProvider)provider); diff --git a/src/main/java/cn/nukkit/plugin/service/RegisteredServiceProvider.java b/src/main/java/cn/nukkit/plugin/service/RegisteredServiceProvider.java index abecb212298..a43575f864d 100644 --- a/src/main/java/cn/nukkit/plugin/service/RegisteredServiceProvider.java +++ b/src/main/java/cn/nukkit/plugin/service/RegisteredServiceProvider.java @@ -1,17 +1,13 @@ package cn.nukkit.plugin.service; - import cn.nukkit.plugin.Plugin; -/** - * Created on 16-11-20. - */ public class RegisteredServiceProvider implements Comparable> { - private Plugin plugin; - private ServicePriority priority; - private Class service; - private T provider; + private final Plugin plugin; + private final ServicePriority priority; + private final Class service; + private final T provider; RegisteredServiceProvider(Class service, T provider, ServicePriority priority, Plugin plugin) { this.plugin = plugin; @@ -70,5 +66,4 @@ public int hashCode() { public int compareTo(RegisteredServiceProvider other) { return other.priority.ordinal() - priority.ordinal(); } - } diff --git a/src/main/java/cn/nukkit/plugin/service/ServiceManager.java b/src/main/java/cn/nukkit/plugin/service/ServiceManager.java index b58eb8cfcc8..2478c907421 100644 --- a/src/main/java/cn/nukkit/plugin/service/ServiceManager.java +++ b/src/main/java/cn/nukkit/plugin/service/ServiceManager.java @@ -4,9 +4,6 @@ import java.util.List; -/** - * Created on 16-11-20. - */ public interface ServiceManager { /** diff --git a/src/main/java/cn/nukkit/plugin/service/ServicePriority.java b/src/main/java/cn/nukkit/plugin/service/ServicePriority.java index 241f13acef1..d4b9db365fa 100644 --- a/src/main/java/cn/nukkit/plugin/service/ServicePriority.java +++ b/src/main/java/cn/nukkit/plugin/service/ServicePriority.java @@ -1,10 +1,6 @@ package cn.nukkit.plugin.service; -/** - * Created on 16-11-20. - */ public enum ServicePriority { LOWEST, LOWER, NORMAL, HIGHER, HIGHEST, - } diff --git a/src/main/java/cn/nukkit/potion/Effect.java b/src/main/java/cn/nukkit/potion/Effect.java index 2f29e329583..d922ca2391b 100644 --- a/src/main/java/cn/nukkit/potion/Effect.java +++ b/src/main/java/cn/nukkit/potion/Effect.java @@ -1,14 +1,16 @@ package cn.nukkit.potion; import cn.nukkit.Player; +import cn.nukkit.entity.Attribute; import cn.nukkit.entity.Entity; +import cn.nukkit.entity.EntityBoss; import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; import cn.nukkit.event.entity.EntityRegainHealthEvent; import cn.nukkit.network.protocol.MobEffectPacket; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class Effect implements Cloneable { @@ -16,7 +18,7 @@ public class Effect implements Cloneable { public static final int SPEED = 1; public static final int SLOWNESS = 2; public static final int HASTE = 3; - public static final int SWIFTNESS = 3; + public static final int SWIFTNESS = 3; // incorrect? public static final int FATIGUE = 4; public static final int MINING_FATIGUE = 4; public static final int STRENGTH = 5; @@ -58,7 +60,7 @@ public static void init() { effects[Effect.SPEED] = new Effect(Effect.SPEED, "%potion.moveSpeed", 124, 175, 198); effects[Effect.SLOWNESS] = new Effect(Effect.SLOWNESS, "%potion.moveSlowdown", 90, 108, 129, true); - effects[Effect.SWIFTNESS] = new Effect(Effect.SWIFTNESS, "%potion.digSpeed", 217, 192, 67); + effects[Effect.HASTE] = new Effect(Effect.HASTE, "%potion.digSpeed", 217, 192, 67); effects[Effect.FATIGUE] = new Effect(Effect.FATIGUE, "%potion.digSlowDown", 74, 66, 23, true); effects[Effect.STRENGTH] = new Effect(Effect.STRENGTH, "%potion.damageBoost", 147, 36, 35); effects[Effect.HEALING] = new InstantEffect(Effect.HEALING, "%potion.heal", 248, 36, 35); @@ -70,16 +72,13 @@ public static void init() { effects[Effect.FIRE_RESISTANCE] = new Effect(Effect.FIRE_RESISTANCE, "%potion.fireResistance", 228, 154, 58); effects[Effect.WATER_BREATHING] = new Effect(Effect.WATER_BREATHING, "%potion.waterBreathing", 46, 82, 153); effects[Effect.INVISIBILITY] = new Effect(Effect.INVISIBILITY, "%potion.invisibility", 127, 131, 146); - effects[Effect.BLINDNESS] = new Effect(Effect.BLINDNESS, "%potion.blindness", 191, 192, 192); effects[Effect.NIGHT_VISION] = new Effect(Effect.NIGHT_VISION, "%potion.nightVision", 0, 0, 139); effects[Effect.HUNGER] = new Effect(Effect.HUNGER, "%potion.hunger", 46, 139, 87); - effects[Effect.WEAKNESS] = new Effect(Effect.WEAKNESS, "%potion.weakness", 72, 77, 72, true); effects[Effect.POISON] = new Effect(Effect.POISON, "%potion.poison", 78, 147, 49, true); effects[Effect.WITHER] = new Effect(Effect.WITHER, "%potion.wither", 53, 42, 39, true); effects[Effect.HEALTH_BOOST] = new Effect(Effect.HEALTH_BOOST, "%potion.healthBoost", 248, 125, 35); - effects[Effect.ABSORPTION] = new Effect(Effect.ABSORPTION, "%potion.absorption", 36, 107, 251); effects[Effect.SATURATION] = new Effect(Effect.SATURATION, "%potion.saturation", 255, 0, 255); effects[Effect.LEVITATION] = new Effect(Effect.LEVITATION, "%potion.levitation", 206, 255, 255, true); @@ -115,13 +114,13 @@ public static Effect getEffectByName(String name) { protected int duration; - protected int amplifier = 0; + protected int amplifier; protected int color; protected boolean show = true; - protected boolean ambient = false; + protected boolean ambient; protected final boolean bad; @@ -187,18 +186,18 @@ public boolean isBad() { public boolean canTick() { int interval; switch (this.id) { - case Effect.POISON: //POISON + case Effect.POISON: case Effect.FATAL_POISON: if ((interval = (25 >> this.amplifier)) > 0) { return (this.duration % interval) == 0; } return true; - case Effect.WITHER: //WITHER + case Effect.WITHER: if ((interval = (50 >> this.amplifier)) > 0) { return (this.duration % interval) == 0; } return true; - case Effect.REGENERATION: //REGENERATION + case Effect.REGENERATION: if ((interval = (40 >> this.amplifier)) > 0) { return (this.duration % interval) == 0; } @@ -208,18 +207,19 @@ public boolean canTick() { } public void applyEffect(Entity entity) { + if (entity instanceof EntityBoss) return; // Boss mobs are immune to poison, wither and regeneration switch (this.id) { - case Effect.POISON: //POISON + case Effect.POISON: case Effect.FATAL_POISON: if (entity.getHealth() > 1 || this.id == FATAL_POISON) { entity.attack(new EntityDamageEvent(entity, DamageCause.MAGIC, 1)); } break; - case Effect.WITHER: //WITHER + case Effect.WITHER: entity.attack(new EntityDamageEvent(entity, DamageCause.MAGIC, 1)); break; - case Effect.REGENERATION: //REGENERATION - if (entity.getHealth() < entity.getMaxHealth()) { + case Effect.REGENERATION: + if (entity.getHealth() < entity.getRealMaxHealth()) { entity.heal(new EntityRegainHealthEvent(entity, 1, EntityRegainHealthEvent.CAUSE_MAGIC)); } break; @@ -235,10 +235,10 @@ public void setColor(int r, int g, int b) { } public void add(Entity entity) { - Effect oldEffect = entity.getEffect(getId()); - if (oldEffect != null && (Math.abs(this.getAmplifier()) < Math.abs(oldEffect.getAmplifier()) || - Math.abs(this.getAmplifier()) == Math.abs(oldEffect.getAmplifier()) - && this.getDuration() < oldEffect.getDuration())) { + Effect oldEffect = entity.getEffect(id); + if (oldEffect != null && (Math.abs(this.amplifier) < Math.abs(oldEffect.amplifier) || + Math.abs(this.amplifier) == Math.abs(oldEffect.amplifier) + && this.duration < oldEffect.duration)) { return; } if (entity instanceof Player) { @@ -246,10 +246,10 @@ public void add(Entity entity) { MobEffectPacket pk = new MobEffectPacket(); pk.eid = entity.getId(); - pk.effectId = this.getId(); - pk.amplifier = this.getAmplifier(); - pk.particles = this.isVisible(); - pk.duration = this.getDuration(); + pk.effectId = this.id; + pk.amplifier = this.amplifier; + pk.particles = this.show; + pk.duration = this.duration; if (oldEffect != null) { pk.eventId = MobEffectPacket.EVENT_MODIFY; } else { @@ -259,17 +259,19 @@ public void add(Entity entity) { player.dataPacket(pk); if (this.id == Effect.SPEED) { - if (oldEffect != null) { + /*if (oldEffect != null) { player.setMovementSpeed(player.getMovementSpeed() / (1 + 0.2f * (oldEffect.amplifier + 1)), false); } - player.setMovementSpeed(player.getMovementSpeed() * (1 + 0.2f * (this.amplifier + 1))); + player.setMovementSpeed(player.getMovementSpeed() * (1 + 0.2f * (this.amplifier + 1)));*/ + player.setMovementSpeed(Player.DEFAULT_SPEED * (1 + 0.2f * (this.amplifier + 1))); //HACK: Fix beacon exploit } if (this.id == Effect.SLOWNESS) { - if (oldEffect != null) { + /*if (oldEffect != null) { player.setMovementSpeed(player.getMovementSpeed() / (1 - 0.15f * (oldEffect.amplifier + 1)), false); } - player.setMovementSpeed(player.getMovementSpeed() * (1 - 0.15f * (this.amplifier + 1))); + player.setMovementSpeed(player.getMovementSpeed() * (1 - 0.15f * (this.amplifier + 1)));*/ + player.setMovementSpeed(Player.DEFAULT_SPEED * (1 - 0.15f * (this.amplifier + 1))); } } @@ -279,7 +281,7 @@ public void add(Entity entity) { } if (this.id == Effect.ABSORPTION) { - int add = (this.amplifier + 1) * 4; + int add = (this.amplifier + 1) << 2; if (add > entity.getAbsorption()) entity.setAbsorption(add); } } @@ -288,16 +290,22 @@ public void remove(Entity entity) { if (entity instanceof Player) { MobEffectPacket pk = new MobEffectPacket(); pk.eid = entity.getId(); - pk.effectId = this.getId(); + pk.effectId = this.id; pk.eventId = MobEffectPacket.EVENT_REMOVE; ((Player) entity).dataPacket(pk); if (this.id == Effect.SPEED) { - ((Player) entity).setMovementSpeed(((Player) entity).getMovementSpeed() / (1 + 0.2f * (this.amplifier + 1))); + //((Player) entity).setMovementSpeed(((Player) entity).getMovementSpeed() / (1 + 0.2f * (this.amplifier + 1))); + + ((Player) entity).setMovementSpeed(entity.isSprinting() ? Player.DEFAULT_SPEED * 1.3f : Player.DEFAULT_SPEED, false); + ((Player) entity).setAttribute(Attribute.getAttribute(Attribute.MOVEMENT_SPEED).setValue(Player.DEFAULT_SPEED).setDefaultValue(Player.DEFAULT_SPEED)); } if (this.id == Effect.SLOWNESS) { - ((Player) entity).setMovementSpeed(((Player) entity).getMovementSpeed() / (1 - 0.15f * (this.amplifier + 1))); + //((Player) entity).setMovementSpeed(((Player) entity).getMovementSpeed() / (1 - 0.15f * (this.amplifier + 1))); + + ((Player) entity).setMovementSpeed(entity.isSprinting() ? Player.DEFAULT_SPEED * 1.3f : Player.DEFAULT_SPEED, false); + ((Player) entity).setAttribute(Attribute.getAttribute(Attribute.MOVEMENT_SPEED).setValue(Player.DEFAULT_SPEED).setDefaultValue(Player.DEFAULT_SPEED)); } } diff --git a/src/main/java/cn/nukkit/potion/InstantEffect.java b/src/main/java/cn/nukkit/potion/InstantEffect.java index 90501c6bca0..db549b51c60 100644 --- a/src/main/java/cn/nukkit/potion/InstantEffect.java +++ b/src/main/java/cn/nukkit/potion/InstantEffect.java @@ -1,10 +1,11 @@ package cn.nukkit.potion; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class InstantEffect extends Effect { + public InstantEffect(int id, String name, int r, int g, int b) { super(id, name, r, g, b); } diff --git a/src/main/java/cn/nukkit/potion/Potion.java b/src/main/java/cn/nukkit/potion/Potion.java index bc9bbb66271..d49501d3fcb 100644 --- a/src/main/java/cn/nukkit/potion/Potion.java +++ b/src/main/java/cn/nukkit/potion/Potion.java @@ -1,9 +1,12 @@ package cn.nukkit.potion; -import cn.nukkit.Player; import cn.nukkit.entity.Entity; import cn.nukkit.entity.EntityLiving; import cn.nukkit.entity.EntitySmite; +import cn.nukkit.entity.mob.EntityBlaze; +import cn.nukkit.entity.mob.EntityEnderman; +import cn.nukkit.entity.mob.EntitySnowGolem; +import cn.nukkit.entity.passive.EntityStrider; import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; import cn.nukkit.event.entity.EntityPotionEffectEvent; @@ -11,7 +14,7 @@ import cn.nukkit.event.potion.PotionApplyEvent; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class Potion implements Cloneable { @@ -60,6 +63,7 @@ public class Potion implements Cloneable { public static final int SLOW_FALLING = 40; public static final int SLOW_FALLING_LONG = 41; public static final int SLOWNESS_LONG_II = 42; + public static final int SLOWNESS_IV = 43; protected static Potion[] potions; @@ -109,6 +113,7 @@ public static void init() { potions[Potion.SLOW_FALLING] = new Potion(Potion.SLOW_FALLING); potions[Potion.SLOW_FALLING_LONG] = new Potion(Potion.SLOW_FALLING_LONG); potions[Potion.SLOWNESS_LONG_II] = new Potion(Potion.SLOWNESS_LONG_II, 2); + potions[Potion.SLOWNESS_IV] = new Potion(Potion.SLOWNESS, 4); } public static Potion getPotion(int id) { @@ -132,7 +137,7 @@ public static Potion getPotionByName(String name) { protected final int level; - protected boolean splash = false; + protected boolean splash; public Potion(int id) { this(id, 1); @@ -149,7 +154,7 @@ public Potion(int id, int level, boolean splash) { } public Effect getEffect() { - return getEffect(this.getId(), this.isSplash()); + return getEffect(this.id, this.splash); } public int getId() { @@ -178,17 +183,22 @@ public void applyPotion(Entity entity, double health) { return; } - Effect applyEffect = getEffect(this.getId(), this.isSplash()); + if (this.id == WATER && (entity instanceof EntityEnderman || entity instanceof EntityStrider || entity instanceof EntitySnowGolem || entity instanceof EntityBlaze)) { + entity.attack(new EntityDamageEvent(entity, DamageCause.MAGIC, 1f)); + return; + } + + Effect applyEffect = getEffect(this.id, this.splash); if (applyEffect == null) { return; } - if (entity instanceof Player) { + /*if (entity instanceof Player) { if (!((Player) entity).isSurvival() && !((Player) entity).isAdventure() && applyEffect.isBad()) { return; } - } + }*/ PotionApplyEvent event = new PotionApplyEvent(this, applyEffect, entity); @@ -199,26 +209,31 @@ public void applyPotion(Entity entity, double health) { applyEffect = event.getApplyEffect(); - switch (this.getId()) { + switch (this.id) { case INSTANT_HEALTH: case INSTANT_HEALTH_II: if (entity instanceof EntitySmite) { - entity.attack(new EntityDamageEvent(entity, DamageCause.MAGIC, (float) (health * (double) (6 << (applyEffect.getAmplifier() + 1))))); + entity.attack(new EntityDamageEvent(entity, DamageCause.MAGIC, (float) (health * (6 << (applyEffect.getAmplifier() + 1))))); } else { entity.heal(new EntityRegainHealthEvent(entity, (float) (health * (double) (4 << (applyEffect.getAmplifier() + 1))), EntityRegainHealthEvent.CAUSE_MAGIC)); } break; case HARMING: + if (entity instanceof EntitySmite) { + entity.heal(new EntityRegainHealthEvent(entity, (float) (health * (double) (4 << (applyEffect.getAmplifier() + 1))), EntityRegainHealthEvent.CAUSE_MAGIC)); + } else { + entity.attack(new EntityDamageEvent(entity, DamageCause.MAGIC, (float) (health * 6))); + } + break; case HARMING_II: if (entity instanceof EntitySmite) { entity.heal(new EntityRegainHealthEvent(entity, (float) (health * (double) (4 << (applyEffect.getAmplifier() + 1))), EntityRegainHealthEvent.CAUSE_MAGIC)); } else { - entity.attack(new EntityDamageEvent(entity, DamageCause.MAGIC, (float) (health * (double) (6 << (applyEffect.getAmplifier() + 1))))); + entity.attack(new EntityDamageEvent(entity, DamageCause.MAGIC, (float) (health * 12))); } break; default: - int duration = (int) ((isSplash() ? health : 1) * (double) applyEffect.getDuration() + 0.5); - applyEffect.setDuration(duration); + applyEffect.setDuration((int) ((splash ? health : 1) * (double) applyEffect.getDuration() + 0.5)); entity.addEffect(applyEffect, this.splash ? EntityPotionEffectEvent.Cause.POTION_SPLASH : EntityPotionEffectEvent.Cause.POTION_DRINK); } } @@ -235,6 +250,12 @@ public Potion clone() { public static Effect getEffect(int potionType, boolean isSplash) { Effect effect; switch (potionType) { + case NO_EFFECTS: + case MUNDANE: + case MUNDANE_II: + case THICK: + case AWKWARD: + return null; case NIGHT_VISION: case NIGHT_VISION_LONG: effect = Effect.getEffect(Effect.NIGHT_VISION); @@ -259,6 +280,8 @@ public static Effect getEffect(int potionType, boolean isSplash) { break; case SLOWNESS: case SLOWNESS_LONG: + case SLOWNESS_LONG_II: + case SLOWNESS_IV: effect = Effect.getEffect(Effect.SLOWNESS); break; case WATER_BREATHING: @@ -310,6 +333,8 @@ public static Effect getEffect(int potionType, boolean isSplash) { public static int getLevel(int potionType) { switch (potionType) { + case SLOWNESS_IV: + return 4; case MUNDANE_II: case LEAPING_II: case SPEED_II: @@ -320,6 +345,7 @@ public static int getLevel(int potionType) { case STRENGTH_II: case WITHER_II: case TURTLE_MASTER_II: + case SLOWNESS_LONG_II: return 2; default: return 1; @@ -341,83 +367,163 @@ public static boolean isInstant(int potionType) { public static int getApplySeconds(int potionType, boolean isSplash) { if (isSplash) { switch (potionType) { + case NO_EFFECTS: + return 0; + case MUNDANE: + return 0; + case MUNDANE_II: + return 0; + case THICK: + return 0; + case AWKWARD: + return 0; case NIGHT_VISION: - case STRENGTH: - case WATER_BREATHING: - case SPEED: - case FIRE_RESISTANCE: - case LEAPING: - case INVISIBLE: return 135; case NIGHT_VISION_LONG: - case STRENGTH_LONG: - case WATER_BREATHING_LONG: - case SPEED_LONG: - case FIRE_RESISTANCE_LONG: - case LEAPING_LONG: + return 360; + case INVISIBLE: + return 135; case INVISIBLE_LONG: return 360; + case LEAPING: + return 135; + case LEAPING_LONG: + return 360; case LEAPING_II: - case WEAKNESS: - case STRENGTH_II: - case SLOWNESS: + return 67; + case FIRE_RESISTANCE: + return 135; + case FIRE_RESISTANCE_LONG: + return 360; + case SPEED: + return 135; + case SPEED_LONG: + return 360; case SPEED_II: return 67; + case SLOWNESS: + return 67; case SLOWNESS_LONG: - case WEAKNESS_LONG: return 180; + case WATER_BREATHING: + return 135; + case WATER_BREATHING_LONG: + return 360; + case INSTANT_HEALTH: + return 0; + case INSTANT_HEALTH_II: + return 0; + case HARMING: + return 0; + case HARMING_II: + return 0; case POISON: - case REGENERATION: return 33; case POISON_LONG: - case REGENERATION_LONG: return 90; case POISON_II: + return 16; + case REGENERATION: + return 33; + case REGENERATION_LONG: + return 90; case REGENERATION_II: return 16; + case STRENGTH: + return 135; + case STRENGTH_LONG: + return 360; + case STRENGTH_II: + return 67; + case WEAKNESS: + return 67; + case WEAKNESS_LONG: + return 180; case WITHER_II: return 30; + case SLOWNESS_IV: + return 15; default: return 0; } } else { switch (potionType) { + case NO_EFFECTS: + return 0; + case MUNDANE: + return 0; + case MUNDANE_II: + return 0; + case THICK: + return 0; + case AWKWARD: + return 0; case NIGHT_VISION: - case STRENGTH: - case WATER_BREATHING: - case SPEED: - case FIRE_RESISTANCE: - case LEAPING: - case INVISIBLE: return 180; case NIGHT_VISION_LONG: - case STRENGTH_LONG: - case WATER_BREATHING_LONG: - case SPEED_LONG: - case FIRE_RESISTANCE_LONG: - case LEAPING_LONG: + return 480; + case INVISIBLE: + return 180; case INVISIBLE_LONG: return 480; - case SPEED_II: + case LEAPING: + return 180; + case LEAPING_LONG: + return 480; case LEAPING_II: - case WEAKNESS: - case STRENGTH_II: + return 90; + case FIRE_RESISTANCE: + return 180; + case FIRE_RESISTANCE_LONG: + return 480; + case SPEED: + return 180; + case SPEED_LONG: + return 480; + case SPEED_II: + return 90; case SLOWNESS: return 90; case SLOWNESS_LONG: - case WEAKNESS_LONG: return 240; + case WATER_BREATHING: + return 180; + case WATER_BREATHING_LONG: + return 480; + case INSTANT_HEALTH: + return 0; + case INSTANT_HEALTH_II: + return 0; + case HARMING: + return 0; + case HARMING_II: + return 0; case POISON: - case REGENERATION: return 45; case POISON_LONG: - case REGENERATION_LONG: return 120; case POISON_II: + return 22; + case REGENERATION: + return 45; + case REGENERATION_LONG: + return 120; case REGENERATION_II: return 22; + case STRENGTH: + return 180; + case STRENGTH_LONG: + return 480; + case STRENGTH_II: + return 90; + case WEAKNESS: + return 90; + case WEAKNESS_LONG: + return 240; case WITHER_II: return 30; + case SLOWNESS_IV: + return 20; default: return 0; } diff --git a/src/main/java/cn/nukkit/resourcepacks/AbstractResourcePack.java b/src/main/java/cn/nukkit/resourcepacks/AbstractResourcePack.java index 7c95e8b19f2..93714e8a1b2 100644 --- a/src/main/java/cn/nukkit/resourcepacks/AbstractResourcePack.java +++ b/src/main/java/cn/nukkit/resourcepacks/AbstractResourcePack.java @@ -6,8 +6,9 @@ import java.util.UUID; public abstract class AbstractResourcePack implements ResourcePack { + protected JsonObject manifest; - protected UUID id = null; + protected UUID id; @Override public String getPackName() { diff --git a/src/main/java/cn/nukkit/resourcepacks/JarPluginResourcePack.java b/src/main/java/cn/nukkit/resourcepacks/JarPluginResourcePack.java index 791dac461b0..764adc364dc 100644 --- a/src/main/java/cn/nukkit/resourcepacks/JarPluginResourcePack.java +++ b/src/main/java/cn/nukkit/resourcepacks/JarPluginResourcePack.java @@ -18,7 +18,9 @@ import java.util.zip.ZipOutputStream; public class JarPluginResourcePack extends AbstractResourcePack { + public static final String RESOURCE_PACK_PATH = "assets/resource_pack/"; + protected File jarPluginFile; protected ByteBuffer zippedByteBuffer; protected byte[] sha256; @@ -148,18 +150,19 @@ public byte[] getPackChunk(int off, int len) { return chunk; } - private byte[] readAllBytes(ZipFile jar, ZipEntry encryptionKeyEntry) { + private static byte[] readAllBytes(ZipFile jar, ZipEntry encryptionKeyEntry) { byte[] data = null; try (InputStream is = jar.getInputStream(encryptionKeyEntry)) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; - byte[] temp = new byte[1024]; + byte[] temp = new byte[2048]; while ((nRead = is.read(temp, 0, temp.length)) != -1) { buffer.write(temp, 0, nRead); } data = buffer.toByteArray(); + buffer.close(); } catch (IOException e) { - Server.getInstance().getLogger().error("An error occurred while reading the data", e); + Server.getInstance().getLogger().error("An error occurred while reading ZipFile", e); } return data; } diff --git a/src/main/java/cn/nukkit/resourcepacks/ResourcePack.java b/src/main/java/cn/nukkit/resourcepacks/ResourcePack.java index c041865446f..2d125a8f18f 100644 --- a/src/main/java/cn/nukkit/resourcepacks/ResourcePack.java +++ b/src/main/java/cn/nukkit/resourcepacks/ResourcePack.java @@ -4,7 +4,6 @@ public interface ResourcePack { - ResourcePack[] EMPTY_ARRAY = new ResourcePack[0]; String getPackName(); diff --git a/src/main/java/cn/nukkit/resourcepacks/ResourcePackManager.java b/src/main/java/cn/nukkit/resourcepacks/ResourcePackManager.java index 53484f265e4..c8b8b101418 100644 --- a/src/main/java/cn/nukkit/resourcepacks/ResourcePackManager.java +++ b/src/main/java/cn/nukkit/resourcepacks/ResourcePackManager.java @@ -3,23 +3,28 @@ import cn.nukkit.Server; import cn.nukkit.resourcepacks.loader.ResourcePackLoader; import cn.nukkit.resourcepacks.loader.ZippedResourcePackLoader; +import cn.nukkit.utils.MainLogger; import com.google.common.collect.Sets; +import lombok.Getter; +import lombok.Setter; import java.io.File; import java.util.*; public class ResourcePackManager { - private int maxChunkSize = 1024 * 32;// 32kb is default - + @Getter + @Setter + private int maxChunkSize = 32768; // 32kb is default + private final Map resourcePacksById = new HashMap<>(); private final Set resourcePacks = new HashSet<>(); private final Set loaders; - public ResourcePackManager(Set loaders) { this.loaders = loaders; - reloadPacks(); + + this.reloadPacks(); } public ResourcePackManager(ResourcePackLoader... loaders) { @@ -38,19 +43,13 @@ public ResourcePack getPackById(UUID id) { return this.resourcePacksById.get(id); } - public int getMaxChunkSize() { - return this.maxChunkSize; - } - - public void setMaxChunkSize(int size) { - this.maxChunkSize = size; - } - public void registerPackLoader(ResourcePackLoader loader) { this.loaders.add(loader); } public void reloadPacks() { + MainLogger.getLogger().debug("Loading resource packs..."); + this.resourcePacksById.clear(); this.resourcePacks.clear(); this.loaders.forEach(loader -> { diff --git a/src/main/java/cn/nukkit/resourcepacks/ZippedResourcePack.java b/src/main/java/cn/nukkit/resourcepacks/ZippedResourcePack.java index f9a9ee41bae..73ee0a8303d 100644 --- a/src/main/java/cn/nukkit/resourcepacks/ZippedResourcePack.java +++ b/src/main/java/cn/nukkit/resourcepacks/ZippedResourcePack.java @@ -16,14 +16,12 @@ import java.util.zip.ZipFile; public class ZippedResourcePack extends AbstractResourcePack { - protected File file; - + protected final File file; protected ByteBuffer byteBuffer; protected byte[] sha256; protected String encryptionKey = ""; - public ZippedResourcePack(File file) { if (!file.exists()) { throw new IllegalArgumentException(Server.getInstance().getLanguage() @@ -127,6 +125,6 @@ public byte[] getSha256() { @Override public String getEncryptionKey() { - return encryptionKey; + return this.encryptionKey; } } diff --git a/src/main/java/cn/nukkit/resourcepacks/loader/JarPluginResourcePackLoader.java b/src/main/java/cn/nukkit/resourcepacks/loader/JarPluginResourcePackLoader.java index 965cf54b558..408f0159609 100644 --- a/src/main/java/cn/nukkit/resourcepacks/loader/JarPluginResourcePackLoader.java +++ b/src/main/java/cn/nukkit/resourcepacks/loader/JarPluginResourcePackLoader.java @@ -1,7 +1,6 @@ package cn.nukkit.resourcepacks.loader; import cn.nukkit.Server; -import cn.nukkit.lang.BaseLang; import cn.nukkit.resourcepacks.JarPluginResourcePack; import cn.nukkit.resourcepacks.ResourcePack; import com.google.common.io.Files; @@ -21,24 +20,18 @@ public JarPluginResourcePackLoader(File jarPath) { @Override public List loadPacks() { - BaseLang baseLang = Server.getInstance().getLanguage(); List loadedResourcePacks = new ArrayList<>(); for (File jar : Objects.requireNonNull(jarPath.listFiles())) { try { - ResourcePack resourcePack = null; String fileExt = Files.getFileExtension(jar.getName()); if (!jar.isDirectory()) { if (fileExt.equals("jar") && JarPluginResourcePack.hasResourcePack(jar)) { - Server.getInstance().getLogger().info(baseLang.translateString("nukkit.resources.plugin.loading", jar.getName())); - resourcePack = new JarPluginResourcePack(jar); + Server.getInstance().getLogger().info(Server.getInstance().getLanguage().translateString("nukkit.resources.plugin.loading", jar.getName())); + loadedResourcePacks.add(new JarPluginResourcePack(jar)); } } - if (resourcePack != null) { - loadedResourcePacks.add(resourcePack); - Server.getInstance().getLogger().info(baseLang.translateString("nukkit.resources.plugin.loaded", jar.getName(), resourcePack.getPackName())); - } } catch (IllegalArgumentException e) { - Server.getInstance().getLogger().warning(baseLang.translateString("nukkit.resources.fail", jar.getName(), e.getMessage()), e); + Server.getInstance().getLogger().warning(Server.getInstance().getLanguage().translateString("nukkit.resources.fail", jar.getName(), e.getMessage()), e); } } return loadedResourcePacks; diff --git a/src/main/java/cn/nukkit/resourcepacks/loader/ZippedResourcePackLoader.java b/src/main/java/cn/nukkit/resourcepacks/loader/ZippedResourcePackLoader.java index e1adeec5e2f..d515b22cdb9 100644 --- a/src/main/java/cn/nukkit/resourcepacks/loader/ZippedResourcePackLoader.java +++ b/src/main/java/cn/nukkit/resourcepacks/loader/ZippedResourcePackLoader.java @@ -1,7 +1,6 @@ package cn.nukkit.resourcepacks.loader; import cn.nukkit.Server; -import cn.nukkit.lang.BaseLang; import cn.nukkit.resourcepacks.ResourcePack; import cn.nukkit.resourcepacks.ZippedResourcePack; import com.google.common.io.Files; @@ -26,24 +25,22 @@ public ZippedResourcePackLoader(File path) { @Override public List loadPacks() { - BaseLang baseLang = Server.getInstance().getLanguage(); List loadedResourcePacks = new ArrayList<>(); for (File pack : path.listFiles()) { try { - ResourcePack resourcePack = null; String fileExt = Files.getFileExtension(pack.getName()); - if (!pack.isDirectory() && !fileExt.equals("key")) { //directory resource packs temporarily unsupported + if (!pack.isDirectory() && !fileExt.equals("key")) { // Directory resource packs temporarily unsupported switch (fileExt) { - case "zip": case "mcpack" : resourcePack = new ZippedResourcePack(pack); break; - default : Server.getInstance().getLogger().warning(baseLang.translateString("nukkit.resources.unknown-format", pack.getName())); + case "zip": + case "mcpack": + loadedResourcePacks.add(new ZippedResourcePack(pack)); + break; + default: + Server.getInstance().getLogger().warning(Server.getInstance().getLanguage().translateString("nukkit.resources.unknown-format", pack.getName())); } } - if (resourcePack != null) { - loadedResourcePacks.add(resourcePack); - Server.getInstance().getLogger().info(baseLang.translateString("nukkit.resources.zip.loaded", pack.getName())); - } } catch (IllegalArgumentException e) { - Server.getInstance().getLogger().warning(baseLang.translateString("nukkit.resources.fail", pack.getName(), e.getMessage()), e); + Server.getInstance().getLogger().warning(Server.getInstance().getLanguage().translateString("nukkit.resources.fail", pack.getName(), e.getMessage()), e); } } return loadedResourcePacks; diff --git a/src/main/java/cn/nukkit/scheduler/AsyncPool.java b/src/main/java/cn/nukkit/scheduler/AsyncPool.java index ed3b03fdca7..a825aa27601 100644 --- a/src/main/java/cn/nukkit/scheduler/AsyncPool.java +++ b/src/main/java/cn/nukkit/scheduler/AsyncPool.java @@ -2,7 +2,7 @@ import cn.nukkit.Server; -import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; @@ -10,10 +10,11 @@ * @author Nukkit Project Team */ public class AsyncPool extends ThreadPoolExecutor { + private final Server server; public AsyncPool(Server server, int size) { - super(size, Integer.MAX_VALUE, 60, TimeUnit.MILLISECONDS, new SynchronousQueue<>()); + super(size, size, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>()); this.setThreadFactory(runnable -> new Thread(runnable) {{ setDaemon(true); setName(String.format("Nukkit Asynchronous Task Handler #%s", getPoolSize())); diff --git a/src/main/java/cn/nukkit/scheduler/AsyncTask.java b/src/main/java/cn/nukkit/scheduler/AsyncTask.java index 29698d7c5f8..9552dbc1f18 100644 --- a/src/main/java/cn/nukkit/scheduler/AsyncTask.java +++ b/src/main/java/cn/nukkit/scheduler/AsyncTask.java @@ -2,7 +2,6 @@ import cn.nukkit.Server; import cn.nukkit.utils.ThreadStore; -import co.aikar.timings.Timings; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; @@ -50,11 +49,11 @@ public int getTaskId() { } public Object getFromThreadStore(String identifier) { - return this.isFinished() ? null : ThreadStore.store.get(identifier); + return this.finished ? null : ThreadStore.store.get(identifier); } public void saveToThreadStore(String identifier, Object value) { - if (!this.isFinished()) { + if (!this.finished) { if (value == null) { ThreadStore.store.remove(identifier); } else { @@ -76,18 +75,15 @@ public void cleanObject() { } public static void collectTask() { - Timings.schedulerAsyncTimer.startTiming(); while (!FINISHED_LIST.isEmpty()) { AsyncTask task = FINISHED_LIST.poll(); try { task.onCompletion(Server.getInstance()); } catch (Exception e) { Server.getInstance().getLogger().critical("Exception while async task " - + task.getTaskId() + + task.taskId + " invoking onCompletion", e); } } - Timings.schedulerAsyncTimer.stopTiming(); } - } diff --git a/src/main/java/cn/nukkit/scheduler/AsyncWorker.java b/src/main/java/cn/nukkit/scheduler/AsyncWorker.java index 868233478bd..338627342ac 100644 --- a/src/main/java/cn/nukkit/scheduler/AsyncWorker.java +++ b/src/main/java/cn/nukkit/scheduler/AsyncWorker.java @@ -5,10 +5,11 @@ import java.util.LinkedList; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class AsyncWorker extends Thread implements InterruptibleThread { + private final LinkedList stack = new LinkedList<>(); public AsyncWorker() { @@ -44,10 +45,7 @@ public void run() { } try { sleep(5); - } catch (InterruptedException e) { - //igonre - } + } catch (InterruptedException ignored) {} } } - } diff --git a/src/main/java/cn/nukkit/scheduler/BlockUpdateScheduler.java b/src/main/java/cn/nukkit/scheduler/BlockUpdateScheduler.java index bb1a26a24b6..f3592969968 100644 --- a/src/main/java/cn/nukkit/scheduler/BlockUpdateScheduler.java +++ b/src/main/java/cn/nukkit/scheduler/BlockUpdateScheduler.java @@ -3,23 +3,23 @@ import cn.nukkit.block.Block; import cn.nukkit.level.Level; import cn.nukkit.math.AxisAlignedBB; -import cn.nukkit.math.NukkitMath; +import cn.nukkit.math.SimpleAxisAlignedBB; import cn.nukkit.math.Vector3; import cn.nukkit.utils.BlockUpdateEntry; -import com.google.common.collect.Maps; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; public class BlockUpdateScheduler { + private final Level level; private long lastTick; - private Map> queuedUpdates; + private final Map> queuedUpdates = new ConcurrentHashMap<>(); private Set pendingUpdates; public BlockUpdateScheduler(Level level, long currentTick) { - queuedUpdates = Maps.newHashMap(); // Change to ConcurrentHashMap if this needs to be concurrent - lastTick = currentTick; + this.lastTick = currentTick; this.level = level; } @@ -49,9 +49,8 @@ private void perform(long tick) { Set updates = pendingUpdates = queuedUpdates.remove(tick); if (updates != null) { for (BlockUpdateEntry entry : updates) { - Vector3 pos = entry.pos; - if (level.isChunkLoaded(NukkitMath.floorDouble(pos.x) >> 4, NukkitMath.floorDouble(pos.z) >> 4)) { - Block block = level.getBlock(entry.pos); + if (level.isAreaLoaded(new SimpleAxisAlignedBB(entry.pos, entry.pos))) { + Block block = level.getBlock(entry.pos, entry.block.getLayer(), true); if (Block.equals(block, entry.block, false)) { block.onUpdate(Level.BLOCK_UPDATE_SCHEDULED); @@ -127,7 +126,7 @@ public boolean remove(BlockUpdateEntry entry) { public boolean remove(Vector3 pos) { for (Map.Entry> tickUpdateSet : queuedUpdates.entrySet()) { - if (tickUpdateSet.getValue().remove(pos)) { + if (tickUpdateSet.getValue().remove(new BlockUpdateEntry(pos, null))) { return true; } } diff --git a/src/main/java/cn/nukkit/scheduler/FileWriteTask.java b/src/main/java/cn/nukkit/scheduler/FileWriteTask.java index e2911d4a587..982c638834c 100644 --- a/src/main/java/cn/nukkit/scheduler/FileWriteTask.java +++ b/src/main/java/cn/nukkit/scheduler/FileWriteTask.java @@ -10,10 +10,11 @@ import java.nio.charset.StandardCharsets; /** - * author: MagicDroidX + * @author MagicDroidX * Nukkit Project */ public class FileWriteTask extends AsyncTask { + private final File file; private final InputStream contents; @@ -53,5 +54,4 @@ public void onRun() { Server.getInstance().getLogger().logException(e); } } - } diff --git a/src/main/java/cn/nukkit/scheduler/NukkitRunnable.java b/src/main/java/cn/nukkit/scheduler/NukkitRunnable.java index 55db31ab632..888f3d41f6d 100644 --- a/src/main/java/cn/nukkit/scheduler/NukkitRunnable.java +++ b/src/main/java/cn/nukkit/scheduler/NukkitRunnable.java @@ -7,6 +7,7 @@ * This class is provided as an easy way to handle scheduling tasks. */ public abstract class NukkitRunnable implements Runnable { + private TaskHandler taskHandler; /** @@ -64,8 +65,7 @@ public synchronized int getTaskId() throws IllegalStateException { if (taskHandler == null) { throw new IllegalStateException("Not scheduled yet"); } - final int id = taskHandler.getTaskId(); - return id; + return taskHandler.getTaskId(); } private void checkState() { diff --git a/src/main/java/cn/nukkit/scheduler/PluginTask.java b/src/main/java/cn/nukkit/scheduler/PluginTask.java index cde6a544dd8..6b631b8579c 100644 --- a/src/main/java/cn/nukkit/scheduler/PluginTask.java +++ b/src/main/java/cn/nukkit/scheduler/PluginTask.java @@ -5,34 +5,33 @@ /** * 插件创建的任务。
    Task that created by a plugin. - * - *

    对于插件作者,通过继承这个类创建的任务,可以在插件被禁用时不被执行。
    - * For plugin developers: Tasks that extend this class, won't be executed when the plugin is disabled.

    - * - *

    另外,继承这个类的任务可以通过{@link #getOwner()}来获得这个任务所属的插件。
    - * Otherwise, tasks that extend this class can use {@link #getOwner()} to get its owner.

    - * + *

    + * 对于插件作者,通过继承这个类创建的任务,可以在插件被禁用时不被执行。
    + * For plugin developers: Tasks that extend this class, won't be executed when the plugin is disabled. + *

    + * 另外,继承这个类的任务可以通过{@link #getOwner()}来获得这个任务所属的插件。
    + * Otherwise, tasks that extend this class can use {@link #getOwner()} to get its owner. + *

    * 下面是一个插件创建任务的例子:
    An example for plugin create a task: *

      *     public class ExampleTask extends PluginTask<ExamplePlugin>{
    - *         public ExampleTask(ExamplePlugin plugin){
    + *         public ExampleTask(ExamplePlugin plugin) {
      *             super(plugin);
      *         }
      *
      *        {@code @Override}
    - *         public void onRun(int currentTick){
    + *         public void onRun(int currentTick) {
      *             getOwner().getLogger().info("Task is executed in tick "+currentTick);
      *         }
      *     }
    - * 
    + * * - *

    如果要让Nukkit能够延时或循环执行这个任务,请使用{@link ServerScheduler}。
    - * If you want Nukkit to execute this task with delay or repeat, use {@link ServerScheduler}.

    + * 如果要让Nukkit能够延时或循环执行这个任务,请使用{@link ServerScheduler}。
    + * If you want Nukkit to execute this task with delay or repeat, use {@link ServerScheduler}. * * @param 这个任务所属的插件。
    The plugin that owns this task. * @author MagicDroidX(code) @ Nukkit Project * @author 粉鞋大妈(javadoc) @ Nukkit Project - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public abstract class PluginTask extends Task { @@ -42,7 +41,6 @@ public abstract class PluginTask extends Task { * 构造一个插件拥有的任务的方法。
    Constructs a plugin-owned task. * * @param owner 这个任务的所有者插件。
    The plugin object that owns this task. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public PluginTask(T owner) { this.owner = owner; @@ -53,10 +51,8 @@ public PluginTask(T owner) { * Returns the owner of this task. * * @return 这个任务的所有者插件。
    The plugin that owns this task. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public final T getOwner() { return this.owner; } - } diff --git a/src/main/java/cn/nukkit/scheduler/ServerScheduler.java b/src/main/java/cn/nukkit/scheduler/ServerScheduler.java index d36de738939..7d4213a093e 100644 --- a/src/main/java/cn/nukkit/scheduler/ServerScheduler.java +++ b/src/main/java/cn/nukkit/scheduler/ServerScheduler.java @@ -85,10 +85,6 @@ public int getAsyncTaskPoolSize() { return asyncPool.getCorePoolSize(); } - public void increaseAsyncTaskPoolSize(int newSize) { - throw new UnsupportedOperationException("Cannot increase a working pool size."); //wtf? - } - public TaskHandler scheduleDelayedTask(Task task, int delay) { return this.addTask(task, delay, 0, false); } @@ -205,7 +201,7 @@ public void cancelTask(Plugin plugin) { // It is only there for backwards compatibility! if (taskHandler.getPlugin() == null || plugin.equals(taskHandler.getPlugin())) { try { - taskHandler.cancel(); /* It will remove from task map automatic in next main heartbeat. */ + taskHandler.cancel(); // It will remove from task map automatic in next main heartbeat } catch (RuntimeException ex) { Server.getInstance().getLogger().critical("Exception while invoking onCancel", ex); } @@ -291,14 +287,12 @@ private void runTasks(int currentTick) { } else if (taskHandler.isAsynchronous()) { asyncPool.execute(taskHandler.getTask()); } else { - taskHandler.timing.startTiming(); try { taskHandler.run(currentTick); } catch (Throwable e) { - Server.getInstance().getLogger().critical("Could not execute taskHandler " + taskHandler.getTaskId() + ": " + e.getMessage()); - Server.getInstance().getLogger().logException(e instanceof Exception ? (Exception) e : new RuntimeException(e)); + Server.getInstance().getLogger().critical("Could not execute taskHandler " + taskHandler.getTaskId() + ": " + e.getMessage(), + e instanceof Exception ? e : new RuntimeException(e)); } - taskHandler.timing.stopTiming(); } if (taskHandler.isRepeating()) { taskHandler.setNextRunTick(currentTick + taskHandler.getPeriod()); @@ -326,5 +320,4 @@ public int getQueueSize() { private int nextTaskId() { return currentTaskId.incrementAndGet(); } - } diff --git a/src/main/java/cn/nukkit/scheduler/Task.java b/src/main/java/cn/nukkit/scheduler/Task.java index 089fa3025d7..97f379f2286 100644 --- a/src/main/java/cn/nukkit/scheduler/Task.java +++ b/src/main/java/cn/nukkit/scheduler/Task.java @@ -4,22 +4,22 @@ /** * 表达一个任务的类。
    A class that describes a task. - * - *

    一个任务可以被Nukkit服务器立即,延时,循环或延时循环执行。参见:{@link ServerScheduler}
    + *

    + * 一个任务可以被Nukkit服务器立即,延时,循环或延时循环执行。参见:{@link ServerScheduler}
    * A task can be executed by Nukkit server with a/an express, delay, repeat or delay&repeat. - * See:{@link ServerScheduler}

    - * - *

    对于插件开发者,为确保自己任务能够在安全的情况下执行(比如:在插件被禁用时不执行), + * See:{@link ServerScheduler} + * + * 对于插件开发者,为确保自己任务能够在安全的情况下执行(比如:在插件被禁用时不执行), * 建议让任务继承{@link PluginTask}类而不是这个类。
    * For plugin developers: To make sure your task will only be executed in the case of safety * (such as: prevent this task from running if its owner plugin is disabled), - * it's suggested to use {@link PluginTask} instead of extend this class.

    + * it's suggested to use {@link PluginTask} instead of extend this class. * * @author MagicDroidX(code) @ Nukkit Project * @author 粉鞋大妈(javadoc) @ Nukkit Project - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public abstract class Task implements Runnable { + private TaskHandler taskHandler = null; public final TaskHandler getHandler() { @@ -42,7 +42,6 @@ public final void setHandler(TaskHandler taskHandler) { * * @param currentTick 服务器从开始运行到现在所经过的tick数,20ticks = 1秒,1tick = 0.05秒。
    * The elapsed tick count from the server is started. 20ticks = 1second, 1tick = 0.05second. - * @since Nukkit 1.0 | Nukkit API 1.0.0 */ public abstract void onRun(int currentTick); @@ -57,10 +56,9 @@ public void onCancel() { public void cancel() { try { - this.getHandler().cancel(); + this.taskHandler.cancel(); } catch (RuntimeException ex) { Server.getInstance().getLogger().critical("Exception while invoking onCancel", ex); } } - } diff --git a/src/main/java/cn/nukkit/scheduler/TaskHandler.java b/src/main/java/cn/nukkit/scheduler/TaskHandler.java index 99e2d8c88a9..09444cbbcaa 100644 --- a/src/main/java/cn/nukkit/scheduler/TaskHandler.java +++ b/src/main/java/cn/nukkit/scheduler/TaskHandler.java @@ -2,13 +2,12 @@ import cn.nukkit.Server; import cn.nukkit.plugin.Plugin; -import co.aikar.timings.Timing; -import co.aikar.timings.Timings; /** * @author MagicDroidX */ public class TaskHandler { + private final int taskId; private final boolean asynchronous; @@ -23,14 +22,11 @@ public class TaskHandler { private boolean cancelled; - public final Timing timing; - public TaskHandler(Plugin plugin, Runnable task, int taskId, boolean asynchronous) { this.asynchronous = asynchronous; this.plugin = plugin; this.task = task; this.taskId = taskId; - this.timing = Timings.getTaskTiming(this, period); } public boolean isCancelled() { @@ -82,7 +78,7 @@ public void setLastRunTick(int lastRunTick) { } public void cancel() { - if (!this.isCancelled() && this.task instanceof Task) { + if (!this.cancelled && this.task instanceof Task) { ((Task) this.task).onCancel(); } this.cancelled = true; @@ -96,17 +92,12 @@ public void remove() { public void run(int currentTick) { try { setLastRunTick(currentTick); - getTask().run(); + task.run(); } catch (RuntimeException ex) { Server.getInstance().getLogger().critical("Exception while invoking run", ex); } } - @Deprecated - public String getTaskName() { - return "Unknown"; - } - public boolean isAsynchronous() { return asynchronous; } @@ -118,5 +109,4 @@ public void setDelay(int delay) { public void setPeriod(int period) { this.period = period; } - } diff --git a/src/main/java/cn/nukkit/timings/JsonUtil.java b/src/main/java/cn/nukkit/timings/JsonUtil.java deleted file mode 100644 index 104ffd0eb8f..00000000000 --- a/src/main/java/cn/nukkit/timings/JsonUtil.java +++ /dev/null @@ -1,72 +0,0 @@ -package cn.nukkit.timings; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; - -import java.util.*; -import java.util.function.Function; - -/** - * @author Tee7even - *

    - * Various methods for more compact JSON object constructing - */ -@SuppressWarnings("unchecked") -public class JsonUtil { - private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); - - public static JsonArray toArray(Object... objects) { - List array = new ArrayList(); - Collections.addAll(array, objects); - return GSON.toJsonTree(array).getAsJsonArray(); - } - - public static JsonObject toObject(Object object) { - return GSON.toJsonTree(object).getAsJsonObject(); - } - - public static JsonObject mapToObject(Iterable collection, Function mapper) { - Map object = new LinkedHashMap(); - for (E e : collection) { - JSONPair pair = mapper.apply(e); - if (pair != null) { - object.put(pair.key, pair.value); - } - } - return GSON.toJsonTree(object).getAsJsonObject(); - } - - public static JsonArray mapToArray(E[] elements, Function mapper) { - ArrayList array = new ArrayList(); - Collections.addAll(array, elements); - return mapToArray(array, mapper); - } - - public static JsonArray mapToArray(Iterable collection, Function mapper) { - List array = new ArrayList(); - for (E e : collection) { - Object obj = mapper.apply(e); - if (obj != null) { - array.add(obj); - } - } - return GSON.toJsonTree(array).getAsJsonArray(); - } - - public static class JSONPair { - public final String key; - public final Object value; - - public JSONPair(String key, Object value) { - this.key = key; - this.value = value; - } - - public JSONPair(int key, Object value) { - this.key = String.valueOf(key); - this.value = value; - } - } -} diff --git a/src/main/java/cn/nukkit/timings/LevelTimings.java b/src/main/java/cn/nukkit/timings/LevelTimings.java deleted file mode 100644 index be2416b236d..00000000000 --- a/src/main/java/cn/nukkit/timings/LevelTimings.java +++ /dev/null @@ -1,47 +0,0 @@ -package cn.nukkit.timings; - -import cn.nukkit.level.Level; -import co.aikar.timings.Timing; -import co.aikar.timings.TimingsManager; - -/** - * @author Pub4Game - * @author Tee7even - */ -public class LevelTimings { - public final Timing doChunkUnload; - public final Timing doTickPending; - public final Timing doChunkGC; - public final Timing doTick; - - public final Timing tickChunks; - public final Timing entityTick; - public final Timing blockEntityTick; - - public final Timing syncChunkSendTimer; - public final Timing syncChunkSendPrepareTimer; - public final Timing syncChunkLoadTimer; - public final Timing syncChunkLoadDataTimer; - public final Timing syncChunkLoadEntitiesTimer; - public final Timing syncChunkLoadBlockEntitiesTimer; - - public LevelTimings(Level level) { - String name = level.getFolderName() + " - "; - - this.doChunkUnload = TimingsManager.getTiming(name + "doChunkUnload"); - this.doTickPending = TimingsManager.getTiming(name + "doTickPending"); - this.doChunkGC = TimingsManager.getTiming(name + "doChunkGC"); - this.doTick = TimingsManager.getTiming(name + "doTick"); - - this.tickChunks = TimingsManager.getTiming(name + "tickChunks"); - this.entityTick = TimingsManager.getTiming(name + "entityTick"); - this.blockEntityTick = TimingsManager.getTiming(name + "blockEntityTick"); - - this.syncChunkSendTimer = TimingsManager.getTiming(name + "syncChunkSend"); - this.syncChunkSendPrepareTimer = TimingsManager.getTiming(name + "syncChunkSendPrepare"); - this.syncChunkLoadTimer = TimingsManager.getTiming(name + "syncChunkLoad"); - this.syncChunkLoadDataTimer = TimingsManager.getTiming(name + "syncChunkLoad - Data"); - this.syncChunkLoadEntitiesTimer = TimingsManager.getTiming(name + "syncChunkLoad - Entities"); - this.syncChunkLoadBlockEntitiesTimer = TimingsManager.getTiming(name + "syncChunkLoad - BlockEntities"); - } -} diff --git a/src/main/java/cn/nukkit/utils/BannerPattern.java b/src/main/java/cn/nukkit/utils/BannerPattern.java index 2b5804afe33..3d8dd2f0cae 100644 --- a/src/main/java/cn/nukkit/utils/BannerPattern.java +++ b/src/main/java/cn/nukkit/utils/BannerPattern.java @@ -5,30 +5,51 @@ import java.util.HashMap; import java.util.Map; +/** + * Banner pattern + */ public class BannerPattern { - private Type type; - private DyeColor color; + private final Type type; + private final DyeColor color; public BannerPattern(Type type, DyeColor color) { this.type = type; this.color = color; } + /** + * Get banner pattern color + * + * @return color as DyeColor + */ public DyeColor getColor() { return this.color; } + /** + * Get banner pattern type + * + * @return type as BannerPattern.Type + */ public Type getType() { return this.type; } + /** + * Read banner pattern from CompoundTag + * + * @param compoundTag CompoundTag in + * @return BannerPattern out + */ public static BannerPattern fromCompoundTag(CompoundTag compoundTag) { return new BannerPattern(Type.getByName(compoundTag.contains("Pattern") ? compoundTag.getString("Pattern") : ""), compoundTag.contains("Color") ? DyeColor.getByDyeData(compoundTag.getInt("Color")) : DyeColor.BLACK); } + /** + * Banner pattern type enum + */ public enum Type { - PATTERN_BOTTOM_STRIPE("bs"), PATTERN_TOP_STRIPE("ts"), PATTERN_LEFT_STRIPE("ls"), @@ -70,7 +91,7 @@ public enum Type { private final static Map BY_NAME = new HashMap<>(); - private String name; + private final String name; Type(String name) { this.name = name; @@ -89,7 +110,5 @@ public String getName() { public static Type getByName(String name) { return BY_NAME.get(name); } - } - } diff --git a/src/main/java/cn/nukkit/utils/Binary.java b/src/main/java/cn/nukkit/utils/Binary.java index 2d5bbef300a..2921bf647c0 100644 --- a/src/main/java/cn/nukkit/utils/Binary.java +++ b/src/main/java/cn/nukkit/utils/Binary.java @@ -17,7 +17,9 @@ import java.util.UUID; /** - * author: MagicDroidX + * Binary + * + * @author MagicDroidX * Nukkit Project */ public class Binary { @@ -102,11 +104,16 @@ public static byte[] writeUUID(UUID uuid) { public static byte[] writeMetadata(EntityMetadata metadata) { BinaryStream stream = new BinaryStream(); Map map = metadata.getMap(); + stream.putUnsignedVarInt(map.size()); - for (int id : map.keySet()) { - EntityData d = map.get(id); + for (Map.Entry entry : map.entrySet()) { + EntityData d = entry.getValue(); + int id = entry.getKey(); + + stream.putUnsignedVarInt(id); stream.putUnsignedVarInt(d.getType()); + switch (d.getType()) { case Entity.DATA_TYPE_BYTE: stream.putByte(((ByteEntityData) d).getData().byteValue()); @@ -383,13 +390,13 @@ public static byte[] writeLLong(long l) { } public static byte[] writeVarInt(int v) { - BinaryStream stream = new BinaryStream(); + BinaryStream stream = new BinaryStream(new byte[5]).reset(); stream.putVarInt(v); return stream.getBuffer(); } public static byte[] writeUnsignedVarInt(long v) { - BinaryStream stream = new BinaryStream(); + BinaryStream stream = new BinaryStream(new byte[5]).reset(); stream.putUnsignedVarInt(v); return stream.getBuffer(); } @@ -408,13 +415,13 @@ public static String bytesToHexString(byte[] src) { public static String bytesToHexString(byte[] src, boolean blank) { StringBuilder stringBuilder = new StringBuilder(); - if (src == null || src.length <= 0) { + if (src == null || src.length == 0) { return null; } for (byte b : src) { if (!(stringBuilder.length() == 0) && blank) { - stringBuilder.append(" "); + stringBuilder.append(' '); } int v = b & 0xFF; String hv = Integer.toHexString(v); @@ -427,16 +434,16 @@ public static String bytesToHexString(byte[] src, boolean blank) { } public static byte[] hexStringToBytes(String hexString) { - if (hexString == null || hexString.equals("")) { + if (hexString == null || hexString.isEmpty()) { return null; } String str = "0123456789ABCDEF"; hexString = hexString.toUpperCase().replace(" ", ""); - int length = hexString.length() / 2; + int length = hexString.length() >> 1; char[] hexChars = hexString.toCharArray(); byte[] d = new byte[length]; for (int i = 0; i < length; i++) { - int pos = i * 2; + int pos = i << 1; d[i] = (byte) (((byte) str.indexOf(hexChars[pos]) << 4) | ((byte) str.indexOf(hexChars[pos + 1]))); } return d; @@ -472,7 +479,6 @@ public static byte[] appendBytes(byte[][] bytes) { for (byte[] b : bytes) { length += b.length; } - byte[] appendedBytes = new byte[length]; int index = 0; for (byte[] b : bytes) { @@ -500,7 +506,6 @@ public static byte[] appendBytes(byte[] bytes1, byte[]... bytes2) { for (byte[] bytes : bytes2) { length += bytes.length; } - byte[] appendedBytes = new byte[length]; System.arraycopy(bytes1, 0, appendedBytes, 0, bytes1.length); int index = bytes1.length; @@ -511,6 +516,4 @@ public static byte[] appendBytes(byte[] bytes1, byte[]... bytes2) { } return appendedBytes; } - - } diff --git a/src/main/java/cn/nukkit/utils/BinaryStream.java b/src/main/java/cn/nukkit/utils/BinaryStream.java index e00e1f62edb..e372261b4af 100644 --- a/src/main/java/cn/nukkit/utils/BinaryStream.java +++ b/src/main/java/cn/nukkit/utils/BinaryStream.java @@ -20,10 +20,13 @@ import cn.nukkit.network.LittleEndianByteBufInputStream; import cn.nukkit.network.LittleEndianByteBufOutputStream; import cn.nukkit.network.protocol.types.EntityLink; -import io.netty.buffer.AbstractByteBufAllocator; +import cn.nukkit.network.protocol.types.ExperimentData; +import org.cloudburstmc.nbt.NBTOutputStream; +import org.cloudburstmc.nbt.NbtUtils; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.reflect.Array; import java.nio.ByteOrder; @@ -33,7 +36,9 @@ import java.util.function.Function; /** - * author: MagicDroidX + * BinaryStream + * + * @author MagicDroidX * Nukkit Project */ public class BinaryStream { @@ -88,6 +93,10 @@ public byte[] getBuffer() { return Arrays.copyOf(buffer, count); } + public byte[] getRawBuffer() { + return buffer; + } + public int getCount() { return count; } @@ -101,16 +110,12 @@ public byte[] get(int len) { this.offset = this.count - 1; return new byte[0]; } - len = Math.min(len, this.getCount() - this.offset); + len = Math.min(len, this.count - this.offset); this.offset += len; return Arrays.copyOfRange(this.buffer, this.offset - len, this.offset); } public void put(byte[] bytes) { - if (bytes == null) { - return; - } - this.ensureCapacity(this.count + bytes.length); System.arraycopy(bytes, 0, this.buffer, this.count, bytes.length); @@ -239,7 +244,7 @@ public Attribute[] getAttributeList() throws Exception { attr.setMaxValue(this.getLFloat()); list.add(attr); } else { - throw new Exception("Unknown attribute type \"" + name + "\""); + throw new Exception("Unknown attribute type \"" + name + '"'); } } @@ -269,6 +274,7 @@ public UUID getUUID() { public void putSkin(Skin skin) { this.putString(skin.getSkinId()); + this.putString(skin.getPlayFabId()); this.putString(skin.getSkinResourcePatch()); this.putImage(skin.getSkinData()); @@ -290,6 +296,7 @@ public void putSkin(Skin skin) { this.putString(skin.getFullSkinId()); this.putString(skin.getArmSize()); this.putString(skin.getSkinColor()); + List pieces = skin.getPersonaPieces(); this.putLInt(pieces.size()); for (PersonaPiece piece : pieces) { @@ -318,6 +325,19 @@ public void putSkin(Skin skin) { this.putBoolean(skin.isOverridingPlayerAppearance()); } + public void putImage(SerializedImage image) { + this.putLInt(image.width); + this.putLInt(image.height); + this.putByteArray(image.data); + } + + public SerializedImage getImage() { + int width = this.getLInt(); + int height = this.getLInt(); + byte[] data = this.getByteArray(); + return new SerializedImage(width, height, data); + } + public Skin getSkin() { Skin skin = new Skin(); skin.setSkinId(this.getString()); @@ -372,19 +392,6 @@ public Skin getSkin() { return skin; } - public void putImage(SerializedImage image) { - this.putLInt(image.width); - this.putLInt(image.height); - this.putByteArray(image.data); - } - - public SerializedImage getImage() { - int width = this.getLInt(); - int height = this.getLInt(); - byte[] data = this.getByteArray(); - return new SerializedImage(width, height, data); - } - public Item getSlot() { int runtimeId = this.getVarInt(); if (runtimeId == 0) { @@ -407,15 +414,15 @@ public Item getSlot() { } int blockRuntimeId = this.getVarInt(); - if (id < 256 && id != 166) { // ItemBlock + /*if (id < 256 && id != 166) { // ItemBlock int fullId = GlobalBlockPalette.getLegacyFullId(blockRuntimeId); if (fullId != -1) { damage = fullId & 0x3f; } - } + }*/ byte[] bytes = this.getByteArray(); - ByteBuf buf = AbstractByteBufAllocator.DEFAULT.ioBuffer(bytes.length); + ByteBuf buf = ByteBufAllocator.DEFAULT.ioBuffer(bytes.length); buf.writeBytes(bytes); byte[] nbt = new byte[0]; @@ -434,8 +441,8 @@ public Item getSlot() { compoundTag = NBTIO.read(stream, ByteOrder.LITTLE_ENDIAN); } - if (compoundTag != null && compoundTag.getAllTags().size() > 0) { - if (compoundTag.contains("Damage") && !legacyEntry.isHasDamage()) { + if (compoundTag != null && !compoundTag.getAllTags().isEmpty()) { + if (!legacyEntry.isHasDamage() && compoundTag.contains("Damage")) { damage = compoundTag.getInt("Damage"); compoundTag.remove("Damage"); } @@ -447,12 +454,22 @@ public Item getSlot() { } } - canPlace = new String[stream.readInt()]; + int canPlaceCount = stream.readInt(); + if (canPlaceCount > 4096) { + throw new RuntimeException("Too many CanPlaceOn blocks: " + canPlaceCount); + } + + canPlace = new String[canPlaceCount]; for (int i = 0; i < canPlace.length; i++) { canPlace[i] = stream.readUTF(); } - canBreak = new String[stream.readInt()]; + int canBreakCount = stream.readInt(); + if (canBreakCount > 4096) { + throw new RuntimeException("Too many CanDestroy blocks: " + canBreakCount); + } + + canBreak = new String[canBreakCount]; for (int i = 0; i < canBreak.length; i++) { canBreak[i] = stream.readUTF(); } @@ -522,7 +539,7 @@ public void putSlot(Item item, boolean instanceItem) { if (!instanceItem) { this.putBoolean(true); - this.putVarInt(1); + this.putVarInt(1); // Item is present } Block block = isBlock ? item.getBlockUnsafe() : null; @@ -586,16 +603,17 @@ public Item getRecipeIngredient() { return Item.get(Item.AIR, 0, 0); } - RuntimeItemMapping mapping = RuntimeItems.getMapping(); - LegacyEntry legacyEntry = mapping.fromRuntime(runtimeId); - - int id = legacyEntry.getLegacyId(); int damage = this.getVarInt(); + if (damage == 0x7fff) { + damage = -1; + } + int id; + RuntimeItemMapping mapping = RuntimeItems.getMapping(); + LegacyEntry legacyEntry = mapping.fromRuntime(runtimeId); + id = legacyEntry.getLegacyId(); if (legacyEntry.isHasDamage()) { damage = legacyEntry.getDamage(); - } else if (damage == 0x7fff) { - damage = -1; } int count = this.getVarInt(); @@ -611,9 +629,10 @@ public void putRecipeIngredient(Item item) { this.putBoolean(true); // isValid? - true - RuntimeItemMapping mapping = RuntimeItems.getMapping(); - int runtimeId, damage; + int runtimeId; + int damage = item.hasMeta() ? item.getDamage() : 0x7fff; + RuntimeItemMapping mapping = RuntimeItems.getMapping(); if (!item.hasMeta()) { RuntimeEntry runtimeEntry = mapping.toRuntime(item.getId(), 0); runtimeId = runtimeEntry.getRuntimeId(); @@ -623,12 +642,13 @@ public void putRecipeIngredient(Item item) { runtimeId = runtimeEntry.getRuntimeId(); damage = runtimeEntry.isHasDamage() ? 0 : item.getDamage(); } + this.putLShort(runtimeId); this.putLShort(damage); this.putVarInt(item.getCount()); } - private List extractStringList(Item item, String tagName) { + private static List extractStringList(Item item, String tagName) { CompoundTag namedTag = item.getNamedTag(); if (namedTag == null) { return Collections.emptyList(); @@ -721,7 +741,7 @@ public void putBlockVector3(BlockVector3 v) { public void putBlockVector3(int x, int y, int z) { this.putVarInt(x); - this.putUnsignedVarInt(y); + this.putUnsignedVarInt(Integer.toUnsignedLong(y)); // we have even negative coordinates this.putVarInt(z); } @@ -744,10 +764,26 @@ public Vector2f getVector2f() { } public void putGameRules(GameRules gameRules) { - Map rules = gameRules.getGameRules(); - this.putUnsignedVarInt(rules.size()); - rules.forEach((gameRule, value) -> { - this.putString(gameRule.getName().toLowerCase()); + Map rulesToSend = new HashMap<>(gameRules.getGameRules()); + this.putUnsignedVarInt(rulesToSend.size()); + rulesToSend.forEach((gameRule, value) -> { + putString(gameRule.getName().toLowerCase()); + value.write(this); + }); + } + + public void putGameRulesMap(Map allGameRules) { + Map rulesToSend = new HashMap<>(); + allGameRules.forEach((gameRule, value) -> { + if (gameRule == GameRule.NATURAL_REGENERATION) { + rulesToSend.put(gameRule, new GameRules.Value<>(GameRules.Type.BOOLEAN, false)); // Fix client-side desync? + } else { + rulesToSend.put(gameRule, value); + } + }); + this.putUnsignedVarInt(rulesToSend.size()); + rulesToSend.forEach((gameRule, value) -> { + putString(gameRule.getName().toLowerCase()); value.write(this); }); } @@ -861,4 +897,23 @@ private static int hugeCapacity(int minCapacity) { Integer.MAX_VALUE : MAX_ARRAY_SIZE; } + + public void putNbtTag(T tag) { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + try (NBTOutputStream writer = NbtUtils.createNetworkWriter(stream)) { + writer.writeTag(tag); + } catch (IOException e) { + throw new RuntimeException(e); + } + this.put(stream.toByteArray()); + } + + public void putExperiments(Collection experiments) { + this.putLInt(experiments.size()); + for (ExperimentData experimentData : experiments) { + this.putString(experimentData.getName()); + this.putBoolean(experimentData.isEnabled()); + } + this.putBoolean(!experiments.isEmpty()); + } } diff --git a/src/main/java/cn/nukkit/utils/BlockColor.java b/src/main/java/cn/nukkit/utils/BlockColor.java index 0812f295992..1b4e4d22418 100644 --- a/src/main/java/cn/nukkit/utils/BlockColor.java +++ b/src/main/java/cn/nukkit/utils/BlockColor.java @@ -1,8 +1,10 @@ package cn.nukkit.utils; /** + * Block color + *

    * Created by Snake1999 on 2016/1/10. - * Package cn.nukkit.utils in project nukkit + * Package cn.nukkit.utils in project Nukkit */ public class BlockColor { @@ -70,6 +72,16 @@ public class BlockColor { public static final BlockColor RED_TERRACOTA_BLOCK_COLOR = new BlockColor(0x8e, 0x3c, 0x2e); public static final BlockColor BLACK_TERRACOTA_BLOCK_COLOR = new BlockColor(0x25, 0x16, 0x10); + public static final BlockColor CRIMSON_NYLIUM_BLOCK_COLOR = new BlockColor(0xBD, 0x30, 0x31); + public static final BlockColor CRIMSON_STEM_BLOCK_COLOR = new BlockColor(0x94, 0x3F, 0x61); + public static final BlockColor CRIMSON_HYPHAE_BLOCK_COLOR = new BlockColor(0x5C, 0x19, 0x1D); + public static final BlockColor WARPED_NYLIUM_BLOCK_COLOR = new BlockColor(0x16, 0x7E, 0x86); + public static final BlockColor WARPED_STEM_BLOCK_COLOR = new BlockColor(0x3A, 0x8E, 0x8C); + public static final BlockColor WARPED_HYPHAE_BLOCK_COLOR = new BlockColor(0x56, 0x2C, 0x3E); + public static final BlockColor WARPED_WART_BLOCK_COLOR = new BlockColor(0x14, 0xB4, 0x85); + + public static final BlockColor DEEPSLATE_GRAY = new BlockColor(0x64, 0x64, 0x64); + private final int red; private final int green; private final int blue; @@ -97,6 +109,13 @@ public BlockColor(int rgb, boolean hasAlpha) { this.alpha = hasAlpha ? (rgb >> 24) & 0xff : 0xff; } + public BlockColor(String colorStr) { + this.red = Integer.valueOf(colorStr.substring(1, 3), 16); + this.green = Integer.valueOf(colorStr.substring(3, 5), 16); + this.blue = Integer.valueOf(colorStr.substring(5, 7), 16); + this.alpha = 0xff; + } + @Override public boolean equals(Object obj) { if (!(obj instanceof BlockColor)) { @@ -109,7 +128,7 @@ public boolean equals(Object obj) { @Override public String toString() { - return "BlockColor[r=" + this.red + ",g=" + this.green + ",b=" + this.blue + ",a=" + this.alpha + "]"; + return "BlockColor[r=" + this.red + ",g=" + this.green + ",b=" + this.blue + ",a=" + this.alpha + ']'; } public int getRed() { @@ -136,6 +155,12 @@ public int getARGB() { return this.alpha << 24 | this.red << 16 | this.green << 8 | this.blue; } + /** + * Get BlockColor by dye item meta value + * + * @param dyeColorMeta dye item meta value + * @return BlockColor + */ @Deprecated public static BlockColor getDyeColor(int dyeColorMeta) { return DyeColor.getByDyeData(dyeColorMeta).getColor(); diff --git a/src/main/java/cn/nukkit/utils/BlockIterator.java b/src/main/java/cn/nukkit/utils/BlockIterator.java index 1c9c6bb48c0..7b6d20667ad 100644 --- a/src/main/java/cn/nukkit/utils/BlockIterator.java +++ b/src/main/java/cn/nukkit/utils/BlockIterator.java @@ -3,16 +3,19 @@ import cn.nukkit.block.Block; import cn.nukkit.level.Level; import cn.nukkit.math.BlockFace; +import cn.nukkit.math.NukkitMath; import cn.nukkit.math.Vector3; import java.util.Iterator; /** - * author: MagicDroidX + * Block iterator + * + * @author MagicDroidX * Nukkit Project */ public class BlockIterator implements Iterator { - private final Level level; + private final int maxDistance; private static final int gridSize = 1 << 24; @@ -20,11 +23,10 @@ public class BlockIterator implements Iterator { private boolean end = false; private final Block[] blockQueue; - private int currentBlock = 0; + private int currentBlock; - private Block currentBlockObject = null; private int currentDistance; - private int maxDistanceInt = 0; + private final int maxDistanceInt; private int secondError; private int thirdError; @@ -45,7 +47,6 @@ public BlockIterator(Level level, Vector3 start, Vector3 direction, double yOffs } public BlockIterator(Level level, Vector3 start, Vector3 direction, double yOffset, int maxDistance) { - this.level = level; this.maxDistance = maxDistance; this.blockQueue = new Block[3]; @@ -63,7 +64,7 @@ public BlockIterator(Level level, Vector3 start, Vector3 direction, double yOffs double thirdPosition = 0; Vector3 pos = new Vector3(startClone.x, startClone.y, startClone.z); - Block startBlock = this.level.getBlock(new Vector3(Math.floor(pos.x), Math.floor(pos.y), Math.floor(pos.z))); + Block startBlock = level.getBlock(NukkitMath.floorDouble(pos.x), NukkitMath.floorDouble(pos.y), NukkitMath.floorDouble(pos.z)); if (this.getXLength(direction) > mainDirection) { this.mainFace = this.getXFace(direction); @@ -208,12 +209,13 @@ private double getZPosition(Vector3 direction, Vector3 position, Block block) { public Block next() { this.scan(); + Block currentBlockObject; if (this.currentBlock <= -1) { throw new IndexOutOfBoundsException(); } else { - this.currentBlockObject = this.blockQueue[this.currentBlock--]; + currentBlockObject = this.blockQueue[this.currentBlock--]; } - return this.currentBlockObject; + return currentBlockObject; } @Override diff --git a/src/main/java/cn/nukkit/utils/BlockUpdateEntry.java b/src/main/java/cn/nukkit/utils/BlockUpdateEntry.java index 8ca0e3dcdfd..cc3a55770b3 100644 --- a/src/main/java/cn/nukkit/utils/BlockUpdateEntry.java +++ b/src/main/java/cn/nukkit/utils/BlockUpdateEntry.java @@ -4,11 +4,14 @@ import cn.nukkit.math.Vector3; /** - * author: MagicDroidX + * Entry of a block update + * + * @author MagicDroidX * Nukkit Project */ public class BlockUpdateEntry implements Comparable { - private static long entryID = 0; + + private static long entryID; public int priority; public long delay; @@ -54,4 +57,4 @@ public boolean equals(Object object) { public int hashCode() { return this.pos.hashCode(); } -} \ No newline at end of file +} diff --git a/src/main/java/cn/nukkit/utils/BossBarColor.java b/src/main/java/cn/nukkit/utils/BossBarColor.java index a23b8d2401a..8d7eda6ccaa 100644 --- a/src/main/java/cn/nukkit/utils/BossBarColor.java +++ b/src/main/java/cn/nukkit/utils/BossBarColor.java @@ -1,5 +1,8 @@ package cn.nukkit.utils; +/** + * Boss bar colors (1.18+) + */ public enum BossBarColor { PINK, @@ -9,5 +12,4 @@ public enum BossBarColor { YELLOW, PURPLE, WHITE - } diff --git a/src/main/java/cn/nukkit/utils/ChunkException.java b/src/main/java/cn/nukkit/utils/ChunkException.java index 0fa2468c85c..fad2b68ae9d 100644 --- a/src/main/java/cn/nukkit/utils/ChunkException.java +++ b/src/main/java/cn/nukkit/utils/ChunkException.java @@ -1,7 +1,9 @@ package cn.nukkit.utils; /** - * author: MagicDroidX + * ChunkException + * + * @author MagicDroidX * Nukkit Project */ public class ChunkException extends RuntimeException { @@ -17,5 +19,4 @@ public ChunkException(String message, Throwable cause) { public ChunkException(Throwable cause) { super(cause); } - } diff --git a/src/main/java/cn/nukkit/utils/ClientChainData.java b/src/main/java/cn/nukkit/utils/ClientChainData.java index 909a9cf455b..dbb1fac22da 100644 --- a/src/main/java/cn/nukkit/utils/ClientChainData.java +++ b/src/main/java/cn/nukkit/utils/ClientChainData.java @@ -5,7 +5,6 @@ import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; -import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JWSObject; import com.nimbusds.jose.crypto.ECDSAVerifier; @@ -27,7 +26,7 @@ * To get chain data, you can use player.getLoginChainData() or read(loginPacket) *

    * =============== - * author: boybook + * @author boybook * Nukkit Project * =============== */ @@ -128,6 +127,11 @@ public int getUIProfile() { return UIProfile; } + @Override + public String getTitleId() { + return titleId; + } + @Override public JsonObject getRawData() { return rawData; @@ -171,14 +175,13 @@ private static ECPublicKey generateKey(String base64) throws NoSuchAlgorithmExce private String languageCode; private int currentInputMode; private int defaultInputMode; - private int UIProfile; - private String capeData; + private String titleId; private JsonObject rawData; - private BinaryStream bs = new BinaryStream(); + private final BinaryStream bs = new BinaryStream(); private ClientChainData(byte[] buffer) { bs.setBuffer(buffer, 0); @@ -194,12 +197,11 @@ public boolean isXboxAuthed() { private void decodeSkinData() { int size = bs.getLInt(); if (size > 52428800) { - throw new IllegalArgumentException("Skin data too big: " + size); + throw new TooBigSkinException("The skin data is too big: " + size); } JsonObject skinToken = decodeToken(new String(bs.get(size), StandardCharsets.UTF_8)); - - if (skinToken == null) return; + if (skinToken == null) throw new RuntimeException("Invalid null skin token"); if (skinToken.has("ClientRandomId")) this.clientId = skinToken.get("ClientRandomId").getAsLong(); if (skinToken.has("ServerAddress")) this.serverAddress = skinToken.get("ServerAddress").getAsString(); if (skinToken.has("DeviceModel")) this.deviceModel = skinToken.get("DeviceModel").getAsString(); @@ -212,7 +214,6 @@ private void decodeSkinData() { if (skinToken.has("DefaultInputMode")) this.defaultInputMode = skinToken.get("DefaultInputMode").getAsInt(); if (skinToken.has("UIProfile")) this.UIProfile = skinToken.get("UIProfile").getAsInt(); if (skinToken.has("CapeData")) this.capeData = skinToken.get("CapeData").getAsString(); - this.rawData = skinToken; } @@ -224,14 +225,11 @@ public static JsonObject decodeToken(String token) { private void decodeChainData() { int size = bs.getLInt(); - if (size > 52428800) { - throw new IllegalArgumentException("Chain data too big: " + size); + if (size > 3145728) { + throw new IllegalArgumentException("The chain data is too big: " + size); } - String data = new String(bs.get(size), StandardCharsets.UTF_8); - Map> map = GSON.fromJson(data, - new TypeToken>>() { - }.getType()); + Map> map = GSON.fromJson(new String(bs.get(size), StandardCharsets.UTF_8), new MapTypeToken().getType()); if (map.isEmpty() || !map.containsKey("chain") || map.get("chain").isEmpty()) return; List chains = map.get("chain"); @@ -245,14 +243,18 @@ private void decodeChainData() { for (String c : chains) { JsonObject chainMap = decodeToken(c); if (chainMap == null) continue; + if (chainMap.has("extraData")) { JsonObject extra = chainMap.get("extraData").getAsJsonObject(); if (extra.has("displayName")) this.username = extra.get("displayName").getAsString(); if (extra.has("identity")) this.clientUUID = UUID.fromString(extra.get("identity").getAsString()); if (extra.has("XUID")) this.xuid = extra.get("XUID").getAsString(); + if (extra.has("titleId")) this.titleId = extra.get("titleId").getAsString(); } - if (chainMap.has("identityPublicKey")) + + if (chainMap.has("identityPublicKey")) { this.identityPublicKey = chainMap.get("identityPublicKey").getAsString(); + } } if (!xboxAuthed) { @@ -260,7 +262,7 @@ private void decodeChainData() { } } - private boolean verifyChain(List chains) throws Exception { + private static boolean verifyChain(List chains) throws Exception { ECPublicKey lastKey = null; boolean mojangKeyVerified = false; Iterator iterator = chains.iterator(); @@ -280,7 +282,7 @@ private boolean verifyChain(List chains) throws Exception { return false; } - if (!verify(lastKey, jws)) { + if (!jws.verify(new ECDSAVerifier(lastKey))) { return false; } @@ -292,8 +294,7 @@ private boolean verifyChain(List chains) throws Exception { mojangKeyVerified = true; } - Map payload = jws.getPayload().toJSONObject(); - Object base64key = payload.get("identityPublicKey"); + Object base64key = jws.getPayload().toJSONObject().get("identityPublicKey"); if (!(base64key instanceof String)) { throw new RuntimeException("No key found"); } @@ -302,7 +303,13 @@ private boolean verifyChain(List chains) throws Exception { return mojangKeyVerified; } - private boolean verify(ECPublicKey key, JWSObject object) throws JOSEException { - return object.verify(new ECDSAVerifier(key)); + private static class MapTypeToken extends TypeToken>> { + } + + public static class TooBigSkinException extends RuntimeException { + + public TooBigSkinException(String s) { + super(s); + } } } diff --git a/src/main/java/cn/nukkit/utils/Config.java b/src/main/java/cn/nukkit/utils/Config.java index 08e7f4af0b0..03ff758babc 100644 --- a/src/main/java/cn/nukkit/utils/Config.java +++ b/src/main/java/cn/nukkit/utils/Config.java @@ -1,5 +1,6 @@ package cn.nukkit.utils; +import cn.nukkit.Nukkit; import cn.nukkit.Server; import cn.nukkit.scheduler.FileWriteTask; import com.google.gson.Gson; @@ -15,12 +16,13 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Pattern; /** - * author: MagicDroidX + * Config + * + * @author MagicDroidX * Nukkit */ public class Config { @@ -35,12 +37,14 @@ public class Config { public static final int ENUM = 5; // .txt, .list, .enum public static final int ENUMERATION = Config.ENUM; - //private LinkedHashMap config = new LinkedHashMap<>(); private ConfigSection config = new ConfigSection(); private File file; private boolean correct = false; private int type = Config.DETECT; + /** + * List of supported config file formats and their types + */ public static final Map format = new TreeMap<>(); static { @@ -111,23 +115,45 @@ public Config(File file, int type, LinkedHashMap defaultMap) { this(file.toString(), type, new ConfigSection(defaultMap)); } + /** + * Reload config from disk + */ public void reload() { this.config.clear(); this.correct = false; - //this.load(this.file.toString()); if (this.file == null) throw new IllegalStateException("Failed to reload Config. File object is undefined."); this.load(this.file.toString(), this.type); - } + /** + * Try to load a config file and automatically detect its type + * + * @param file file path + * @return loaded + */ public boolean load(String file) { return this.load(file, Config.DETECT); } + /** + * Try to load a config file with a given type + * + * @param file file path + * @param type file type + * @return loaded + */ public boolean load(String file, int type) { return this.load(file, type, new ConfigSection()); } + /** + * Try to load a config file with a given type and default content + * + * @param file file path + * @param type file type + * @param defaultMap default content + * @return loaded + */ public boolean load(String file, int type, ConfigSection defaultMap) { this.correct = true; this.type = type; @@ -144,8 +170,8 @@ public boolean load(String file, int type, ConfigSection defaultMap) { } else { if (this.type == Config.DETECT) { String extension = ""; - if (this.file.getName().lastIndexOf(".") != -1 && this.file.getName().lastIndexOf(".") != 0) { - extension = this.file.getName().substring(this.file.getName().lastIndexOf(".") + 1); + if (this.file.getName().lastIndexOf('.') != -1 && this.file.getName().lastIndexOf('.') != 0) { + extension = this.file.getName().substring(this.file.getName().lastIndexOf('.') + 1); } if (format.containsKey(extension)) { this.type = format.get(extension); @@ -172,6 +198,12 @@ public boolean load(String file, int type, ConfigSection defaultMap) { return true; } + /** + * Load Config from InputStream + * + * @param inputStream InputStream + * @return loaded + */ public boolean load(InputStream inputStream) { if (inputStream == null) return false; if (this.correct) { @@ -187,36 +219,84 @@ public boolean load(InputStream inputStream) { return correct; } + /** + * Load and return a Config from InputStream + * + * @param inputStream InputStream + * @return Config + */ + public Config loadFromStream(InputStream inputStream) { + if (inputStream == null) return null; + if (this.correct) { + String content; + try { + content = Utils.readFile(inputStream); + } catch (IOException e) { + Server.getInstance().getLogger().logException(e); + return null; + } + this.parseContent(content); + } + return this; + } + + /** + * Check if the config is valid + * + * @return valid + */ public boolean check() { return this.correct; } + /** + * Check if the config is valid + * + * @return valid + */ public boolean isCorrect() { - return correct; + return this.correct; } /** * Save configuration into provided file. Internal file object will be set to new file. * - * @param file - * @param async - * @return + * @param file file + * @param async async + * @return save success */ public boolean save(File file, boolean async) { this.file = file; return save(async); } + /** + * Save configuration into provided file. Internal file object will be set to new file. + * + * @param file file + * @return save success + */ public boolean save(File file) { this.file = file; return save(); } + /** + * Save the config to disk + * + * @return saved + */ public boolean save() { return this.save(false); } - public boolean save(Boolean async) { + /** + * Save the config to disk + * + * @param async async + * @return saved + */ + public boolean save(Boolean async) { // Note: do not change to 'boolean' or plugins will break if (this.file == null) throw new IllegalStateException("Failed to save Config. File object is undefined."); if (this.correct) { StringBuilder content = new StringBuilder(); @@ -243,8 +323,7 @@ public boolean save(Boolean async) { break; } if (async) { - Server.getInstance().getScheduler().scheduleAsyncTask(new FileWriteTask(this.file, content.toString())); - + Server.getInstance().getScheduler().scheduleAsyncTask(null, new FileWriteTask(this.file, content.toString())); } else { try { Utils.writeFile(this.file, content.toString()); @@ -258,10 +337,22 @@ public boolean save(Boolean async) { } } + /** + * Set a value in the config + * + * @param key key + * @param value value + */ public void set(final String key, Object value) { this.config.set(key, value); } + /** + * Get a value in the config + * + * @param key key + * @return value + */ public Object get(String key) { return this.get(key, null); } @@ -425,7 +516,7 @@ public Map getAll() { /** * Get root (main) config section of the Config * - * @return + * @return root config section of the Config */ public ConfigSection getRootSection() { return config; @@ -462,7 +553,7 @@ private void parseList(String content) { } private String writeProperties() { - StringBuilder content = new StringBuilder("#Properties Config file\r\n#" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + "\r\n"); + StringBuilder content = new StringBuilder(); for (Object o : this.config.entrySet()) { Map.Entry entry = (Map.Entry) o; Object v = entry.getValue(); @@ -470,25 +561,26 @@ private String writeProperties() { if (v instanceof Boolean) { v = (Boolean) v ? "on" : "off"; } - content.append(k).append("=").append(v).append("\r\n"); + content.append(k).append('=').append(v).append("\r\n"); } return content.toString(); } + private static final Pattern PROP_LINE_PATTERN = Pattern.compile("[a-zA-Z0-9\\-_.]*+=+[^\\r\\n]*"); + private void parseProperties(String content) { for (final String line : content.split("\n")) { - if (Pattern.compile("[a-zA-Z0-9\\-_.]*+=+[^\\r\\n]*").matcher(line).matches()) { + if (PROP_LINE_PATTERN.matcher(line).matches()) { final int splitIndex = line.indexOf('='); if (splitIndex == -1) { continue; } final String key = line.substring(0, splitIndex); final String value = line.substring(splitIndex + 1); - final String valueLower = value.toLowerCase(); - if (this.config.containsKey(key)) { - MainLogger.getLogger().debug("[Config] Repeated property " + key + " on file " + this.file.toString()); + if (Nukkit.DEBUG > 1 && this.config.containsKey(key)) { + MainLogger.getLogger().debug("[Config] Repeated property " + key + " in file " + this.file.toString()); } - switch (valueLower) { + switch (value.toLowerCase()) { case "on": case "true": case "yes": @@ -540,6 +632,7 @@ public void removeNested(String key) { remove(key); } + @SuppressWarnings("unchecked") private void parseContent(String content) { switch (this.type) { case Config.PROPERTIES: @@ -548,8 +641,7 @@ private void parseContent(String content) { case Config.JSON: GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); - this.config = new ConfigSection(gson.fromJson(content, new TypeToken>() { - }.getType())); + this.config = new ConfigSection(gson.fromJson(content, new LinkedHashMapTypeToken().getType())); break; case Config.YAML: DumperOptions dumperOptions = new DumperOptions(); @@ -577,4 +669,7 @@ public Set getKeys(boolean child) { if (this.correct) return config.getKeys(child); return new HashSet<>(); } + + private static class LinkedHashMapTypeToken extends TypeToken> { + } } diff --git a/src/main/java/cn/nukkit/utils/ConfigSection.java b/src/main/java/cn/nukkit/utils/ConfigSection.java index 572813221e7..86e89c38232 100644 --- a/src/main/java/cn/nukkit/utils/ConfigSection.java +++ b/src/main/java/cn/nukkit/utils/ConfigSection.java @@ -3,6 +3,8 @@ import java.util.*; /** + * Config section + *

    * Created by fromgate on 26.04.2016. */ public class ConfigSection extends LinkedHashMap { @@ -17,8 +19,8 @@ public ConfigSection() { /** * Constructor of ConfigSection that contains initial key/value data * - * @param key - * @param value + * @param key key + * @param value value */ public ConfigSection(String key, Object value) { this(); @@ -28,8 +30,9 @@ public ConfigSection(String key, Object value) { /** * Constructor of ConfigSection, based on values stored in map. * - * @param map + * @param map map */ + @SuppressWarnings("unchecked") public ConfigSection(LinkedHashMap map) { this(); if (map == null || map.isEmpty()) return; @@ -44,6 +47,7 @@ public ConfigSection(LinkedHashMap map) { } } + @SuppressWarnings("unchecked") private List parseList(List list) { List newList = new ArrayList<>(); @@ -61,7 +65,7 @@ private List parseList(List list) { /** * Get root section as LinkedHashMap * - * @return + * @return root section as LinkedHashMap */ public Map getAllMap() { return new LinkedHashMap<>(this); @@ -71,7 +75,7 @@ public Map getAllMap() { /** * Get new instance of config section * - * @return + * @return new instance of config section */ public ConfigSection getAll() { return new ConfigSection(this); @@ -87,10 +91,11 @@ public Object get(String key) { /** * Get object by key. If section does not contain value, return default value * - * @param key - * @param defaultValue - * @return + * @param key key + * @param defaultValue default value + * @return object by key or default value */ + @SuppressWarnings("unchecked") public T get(String key, T defaultValue) { if (key == null || key.isEmpty()) return defaultValue; if (super.containsKey(key)) return (T) super.get(key); @@ -107,8 +112,8 @@ public T get(String key, T defaultValue) { /** * Store value into config section * - * @param key - * @param value + * @param key key + * @param value value */ public void set(String key, Object value) { String[] subKeys = key.split("\\.", 2); @@ -122,21 +127,20 @@ public void set(String key, Object value) { } /** - * Check type of section element defined by key. Return true this element is ConfigSection + * Check type of section element defined by key. Return true if this element is ConfigSection * - * @param key - * @return + * @param key key + * @return true if this element is ConfigSection */ public boolean isSection(String key) { - Object value = this.get(key); - return value instanceof ConfigSection; + return this.get(key) instanceof ConfigSection; } /** * Get config section element defined by key * - * @param key - * @return + * @param key key + * @return config section element defined by key */ public ConfigSection getSection(String key) { return this.get(key, new ConfigSection()); @@ -161,7 +165,7 @@ public ConfigSection getSection(String key) { *

    * getSections() will return new ConfigSection, that contains sections a1 and a2 only. * - * @return + * @return all ConfigSections in root path */ //@formatter:on public ConfigSection getSections() { @@ -172,7 +176,7 @@ public ConfigSection getSections() { * Get sections (and only sections) from provided path * * @param key - config section path, if null or empty root path will used. - * @return + * @return sections */ public ConfigSection getSections(String key) { ConfigSection sections = new ConfigSection(); @@ -189,7 +193,7 @@ public ConfigSection getSections(String key) { * Get int value of config section element * * @param key - key (inside) current section (default value equals to 0) - * @return + * @return int value of config section element */ public int getInt(String key) { return this.getInt(key, 0); @@ -200,28 +204,27 @@ public int getInt(String key) { * * @param key - key (inside) current section * @param defaultValue - default value that will returned if section element is not exists - * @return + * @return int value of config section element */ public int getInt(String key, int defaultValue) { return this.get(key, ((Number) defaultValue)).intValue(); } /** - * Check type of section element defined by key. Return true this element is Integer + * Check type of section element defined by key. Return true if this element is Integer * - * @param key - * @return + * @param key key + * @return true if this element is Integer */ public boolean isInt(String key) { - Object val = get(key); - return val instanceof Integer; + return get(key) instanceof Integer; } /** * Get long value of config section element * * @param key - key (inside) current section - * @return + * @return long value of config section element */ public long getLong(String key) { return this.getLong(key, 0); @@ -232,28 +235,27 @@ public long getLong(String key) { * * @param key - key (inside) current section * @param defaultValue - default value that will returned if section element is not exists - * @return + * @return long value of config section element */ public long getLong(String key, long defaultValue) { return this.get(key, ((Number) defaultValue)).longValue(); } /** - * Check type of section element defined by key. Return true this element is Long + * Check type of section element defined by key. Return true if this element is Long * - * @param key - * @return + * @param key key + * @return true if this element is Long */ public boolean isLong(String key) { - Object val = get(key); - return val instanceof Long; + return get(key) instanceof Long; } /** * Get double value of config section element * * @param key - key (inside) current section - * @return + * @return double value of config section element */ public double getDouble(String key) { return this.getDouble(key, 0); @@ -264,28 +266,27 @@ public double getDouble(String key) { * * @param key - key (inside) current section * @param defaultValue - default value that will returned if section element is not exists - * @return + * @return double value of config section element */ public double getDouble(String key, double defaultValue) { return this.get(key, ((Number) defaultValue)).doubleValue(); } /** - * Check type of section element defined by key. Return true this element is Double + * Check type of section element defined by key. Return true if this element is Double * - * @param key - * @return + * @param key key + * @return true if this element is Double */ public boolean isDouble(String key) { - Object val = get(key); - return val instanceof Double; + return get(key) instanceof Double; } /** * Get String value of config section element * * @param key - key (inside) current section - * @return + * @return String value of config section element */ public String getString(String key) { return this.getString(key, ""); @@ -296,29 +297,27 @@ public String getString(String key) { * * @param key - key (inside) current section * @param defaultValue - default value that will returned if section element is not exists - * @return + * @return String value of config section element */ public String getString(String key, String defaultValue) { - Object result = this.get(key, defaultValue); - return String.valueOf(result); + return String.valueOf(this.get(key, defaultValue)); } /** - * Check type of section element defined by key. Return true this element is String + * Check type of section element defined by key. Return true if this element is String * - * @param key - * @return + * @param key key + * @return true if this element is String */ public boolean isString(String key) { - Object val = get(key); - return val instanceof String; + return get(key) instanceof String; } /** * Get boolean value of config section element * * @param key - key (inside) current section - * @return + * @return boolean value of config section element */ public boolean getBoolean(String key) { return this.getBoolean(key, false); @@ -329,28 +328,27 @@ public boolean getBoolean(String key) { * * @param key - key (inside) current section * @param defaultValue - default value that will returned if section element is not exists - * @return + * @return boolean value of config section element */ public boolean getBoolean(String key, boolean defaultValue) { return this.get(key, defaultValue); } /** - * Check type of section element defined by key. Return true this element is Integer + * Check type of section element defined by key. Return true if this element is Integer * - * @param key - * @return + * @param key key + * @return true if this element is Integer */ public boolean isBoolean(String key) { - Object val = get(key); - return val instanceof Boolean; + return get(key) instanceof Boolean; } /** * Get List value of config section element * * @param key - key (inside) current section - * @return + * @return List value of config section element */ public List getList(String key) { return this.getList(key, null); @@ -361,28 +359,27 @@ public List getList(String key) { * * @param key - key (inside) current section * @param defaultList - default value that will returned if section element is not exists - * @return + * @return List value of config section element */ public List getList(String key, List defaultList) { return this.get(key, defaultList); } /** - * Check type of section element defined by key. Return true this element is List + * Check type of section element defined by key. Return true if this element is List * - * @param key - * @return + * @param key key + * @return true if this element is List */ public boolean isList(String key) { - Object val = get(key); - return val instanceof List; + return get(key) instanceof List; } /** * Get String List value of config section element * * @param key - key (inside) current section - * @return + * @return String List value of config section element */ public List getStringList(String key) { List value = this.getList(key); @@ -402,7 +399,7 @@ public List getStringList(String key) { * Get Integer List value of config section element * * @param key - key (inside) current section - * @return + * @return Integer List value of config section element */ public List getIntegerList(String key) { List list = getList(key); @@ -417,8 +414,7 @@ public List getIntegerList(String key) { } else if (object instanceof String) { try { result.add(Integer.valueOf((String) object)); - } catch (Exception ex) { - //ignore + } catch (Exception ignored) { } } else if (object instanceof Character) { result.add((int) (Character) object); @@ -433,7 +429,7 @@ public List getIntegerList(String key) { * Get Boolean List value of config section element * * @param key - key (inside) current section - * @return + * @return Boolean List value of config section element */ public List getBooleanList(String key) { List list = getList(key); @@ -459,7 +455,7 @@ public List getBooleanList(String key) { * Get Double List value of config section element * * @param key - key (inside) current section - * @return + * @return Double List value of config section element */ public List getDoubleList(String key) { List list = getList(key); @@ -473,8 +469,7 @@ public List getDoubleList(String key) { } else if (object instanceof String) { try { result.add(Double.valueOf((String) object)); - } catch (Exception ex) { - //ignore + } catch (Exception ignored) { } } else if (object instanceof Character) { result.add((double) (Character) object); @@ -489,7 +484,7 @@ public List getDoubleList(String key) { * Get Float List value of config section element * * @param key - key (inside) current section - * @return + * @return Float List value of config section element */ public List getFloatList(String key) { List list = getList(key); @@ -503,8 +498,7 @@ public List getFloatList(String key) { } else if (object instanceof String) { try { result.add(Float.valueOf((String) object)); - } catch (Exception ex) { - //ignore + } catch (Exception ignored) { } } else if (object instanceof Character) { result.add((float) (Character) object); @@ -519,7 +513,7 @@ public List getFloatList(String key) { * Get Long List value of config section element * * @param key - key (inside) current section - * @return + * @return Long List value of config section element */ public List getLongList(String key) { List list = getList(key); @@ -533,8 +527,7 @@ public List getLongList(String key) { } else if (object instanceof String) { try { result.add(Long.valueOf((String) object)); - } catch (Exception ex) { - //ignore + } catch (Exception ignored) { } } else if (object instanceof Character) { result.add((long) (Character) object); @@ -549,7 +542,7 @@ public List getLongList(String key) { * Get Byte List value of config section element * * @param key - key (inside) current section - * @return + * @return Byte List value of config section element */ public List getByteList(String key) { List list = getList(key); @@ -566,8 +559,7 @@ public List getByteList(String key) { } else if (object instanceof String) { try { result.add(Byte.valueOf((String) object)); - } catch (Exception ex) { - //ignore + } catch (Exception ignored) { } } else if (object instanceof Character) { result.add((byte) ((Character) object).charValue()); @@ -583,7 +575,7 @@ public List getByteList(String key) { * Get Character List value of config section element * * @param key - key (inside) current section - * @return + * @return Character List value of config section element */ public List getCharacterList(String key) { List list = getList(key); @@ -615,7 +607,7 @@ public List getCharacterList(String key) { * Get Short List value of config section element * * @param key - key (inside) current section - * @return + * @return Short List value of config section element */ public List getShortList(String key) { List list = getList(key); @@ -632,8 +624,7 @@ public List getShortList(String key) { } else if (object instanceof String) { try { result.add(Short.valueOf((String) object)); - } catch (Exception ex) { - //ignore + } catch (Exception ignored) { } } else if (object instanceof Character) { result.add((short) ((Character) object).charValue()); @@ -649,8 +640,9 @@ public List getShortList(String key) { * Get Map List value of config section element * * @param key - key (inside) current section - * @return + * @return Map List value of config section element */ + @SuppressWarnings("unchecked") public List getMapList(String key) { List list = getList(key); List result = new ArrayList<>(); @@ -671,15 +663,17 @@ public List getMapList(String key) { /** * Check existence of config section element * - * @param key - * @param ignoreCase - * @return + * @param key key + * @param ignoreCase ignore case + * @return existence of config section element */ public boolean exists(String key, boolean ignoreCase) { - if (ignoreCase) key = key.toLowerCase(); for (String existKey : this.getKeys(true)) { - if (ignoreCase) existKey = existKey.toLowerCase(); - if (existKey.equals(key)) return true; + if (ignoreCase) { + if (existKey.equalsIgnoreCase(key)) return true; + } else { + if (existKey.equals(key)) return true; + } } return false; } @@ -687,8 +681,8 @@ public boolean exists(String key, boolean ignoreCase) { /** * Check existence of config section element * - * @param key - * @return + * @param key key + * @return existence of config section element */ public boolean exists(String key) { return exists(key, false); @@ -697,7 +691,7 @@ public boolean exists(String key) { /** * Remove config section element * - * @param key + * @param key key */ public void remove(String key) { if (key == null || key.isEmpty()) return; @@ -715,7 +709,7 @@ else if (this.containsKey(".")) { * Get all keys * * @param child - true = include child keys - * @return + * @return all keys */ public Set getKeys(boolean child) { Set keys = new LinkedHashSet<>(); @@ -723,7 +717,7 @@ public Set getKeys(boolean child) { keys.add(key); if (value instanceof ConfigSection) { if (child) - ((ConfigSection) value).getKeys(true).forEach(childKey -> keys.add(key + "." + childKey)); + ((ConfigSection) value).getKeys(true).forEach(childKey -> keys.add(key + '.' + childKey)); } }); return keys; @@ -732,7 +726,7 @@ public Set getKeys(boolean child) { /** * Get all keys * - * @return + * @return all keys */ public Set getKeys() { return this.getKeys(true); diff --git a/src/main/java/cn/nukkit/utils/DefaultPlayerDataSerializer.java b/src/main/java/cn/nukkit/utils/DefaultPlayerDataSerializer.java index 8c9cf530e67..acb9640db6d 100644 --- a/src/main/java/cn/nukkit/utils/DefaultPlayerDataSerializer.java +++ b/src/main/java/cn/nukkit/utils/DefaultPlayerDataSerializer.java @@ -4,36 +4,39 @@ import com.google.common.base.Preconditions; import java.io.*; +import java.nio.file.Files; import java.util.Optional; import java.util.UUID; +/** + * Default player data serializer that saves the player data as .dat files into the 'players' folder. + */ public class DefaultPlayerDataSerializer implements PlayerDataSerializer { - private String dataPath; - + + private final String dataPath; + public DefaultPlayerDataSerializer(Server server) { this(server.getDataPath()); } - + public DefaultPlayerDataSerializer(String dataPath) { this.dataPath = dataPath; } @Override public Optional read(String name, UUID uuid) throws IOException { - String path = dataPath + "players/" + name + ".dat"; - File file = new File(path); + File file = new File(dataPath + "players/" + name + ".dat"); if (!file.exists()) { return Optional.empty(); } - return Optional.of(new FileInputStream(file)); + return Optional.of(Files.newInputStream(file.toPath())); } @Override public OutputStream write(String name, UUID uuid) throws IOException { Preconditions.checkNotNull(name, "name"); - String path = dataPath + "players/" + name + ".dat"; - File file = new File(path); - return new FileOutputStream(file); + File file = new File(dataPath + "players/" + name + ".dat"); + return Files.newOutputStream(file.toPath()); } } diff --git a/src/main/java/cn/nukkit/utils/DummyBossBar.java b/src/main/java/cn/nukkit/utils/DummyBossBar.java index 7dc1f9811eb..b2b0103267f 100644 --- a/src/main/java/cn/nukkit/utils/DummyBossBar.java +++ b/src/main/java/cn/nukkit/utils/DummyBossBar.java @@ -7,12 +7,10 @@ import cn.nukkit.entity.mob.EntityCreeper; import cn.nukkit.network.protocol.*; -import java.util.concurrent.ThreadLocalRandom; - /** * DummyBossBar * =============== - * author: boybook + * @author boybook * Nukkit Project * =============== */ @@ -33,6 +31,9 @@ private DummyBossBar(Builder builder) { this.color = builder.color; } + /** + * Boss bar builder + */ public static class Builder { private final Player player; private final long bossBarId; @@ -43,7 +44,7 @@ public static class Builder { public Builder(Player player) { this.player = player; - this.bossBarId = 1095216660480L + ThreadLocalRandom.current().nextLong(0, 0x7fffffffL); + this.bossBarId = 1095216660480L + Utils.random.nextLong(0, 0x7fffffffL); } public Builder text(String text) { @@ -66,18 +67,38 @@ public DummyBossBar build() { } } + /** + * Get boss bar owner + * + * @return player + */ public Player getPlayer() { return player; } + /** + * Get boss bar id + * + * @return boss bar id + */ public long getBossBarId() { return bossBarId; } + /** + * Get boss bar text + * + * @return current text + */ public String getText() { return text; } + /** + * Set the boss bar text and send it to player if changed + * + * @param text new text + */ public void setText(String text) { if (!this.text.equals(text)) { this.text = text; @@ -86,10 +107,20 @@ public void setText(String text) { } } + /** + * Get boss bar length + * + * @return length + */ public float getLength() { return length; } + /** + * Set boss bar length + * + * @param length new length + */ public void setLength(float length) { if (this.length != length) { this.length = length; @@ -98,6 +129,10 @@ public void setLength(float length) { } } + /** + * Set boss bar color. Requires client version 1.18 or newer. + * @param color the boss bar color + */ public void setColor(BossBarColor color) { if (this.color == null || !this.color.equals(color)) { this.color = color; @@ -105,6 +140,10 @@ public void setColor(BossBarColor color) { } } + /** + * Get boss bar color + * @return current color of the boss bar + */ public BossBarColor getColor() { return this.color; } @@ -128,7 +167,6 @@ private void createBossEntity() { .putLong(Entity.DATA_LEAD_HOLDER_EID, -1) .putString(Entity.DATA_NAMETAG, text) // Set the entity name .putFloat(Entity.DATA_SCALE, 0); // And make it invisible - player.dataPacket(pkAdd); } @@ -212,6 +250,9 @@ private void removeBossEntity() { player.dataPacket(pkRemove); } + /** + * Create boss bar entity and send its data + */ public void create() { createBossEntity(); sendAttributes(); @@ -233,5 +274,4 @@ public void destroy() { sendHideBossBar(); removeBossEntity(); } - } diff --git a/src/main/java/cn/nukkit/utils/DyeColor.java b/src/main/java/cn/nukkit/utils/DyeColor.java index dda243ae37e..9998895d0b5 100644 --- a/src/main/java/cn/nukkit/utils/DyeColor.java +++ b/src/main/java/cn/nukkit/utils/DyeColor.java @@ -1,6 +1,10 @@ package cn.nukkit.utils; +/** + * Dye color enum + */ public enum DyeColor { + BLACK(0, 15, "Black", "Ink Sac", BlockColor.BLACK_BLOCK_COLOR, new BlockColor(0x00, 0x00, 0x00)), RED(1, 14, "Red", BlockColor.RED_BLOCK_COLOR, new BlockColor(0xb0, 0x2e, 0x26)), GREEN(2, 13, "Green", BlockColor.GREEN_BLOCK_COLOR, new BlockColor(0x5e, 0x7c, 0x16)), @@ -41,6 +45,11 @@ public enum DyeColor { this.dyeName = dyeName; } + /** + * Get as BlockColor + * + * @return BlockColor of the DyeColor + */ public BlockColor getColor() { return this.blockColor; } @@ -49,18 +58,38 @@ public BlockColor getSignColor() { return this.signColor; } + /** + * Get as dye item meta value + * + * @return dye item meta value of the DyeColor + */ public int getDyeData() { return this.dyeColorMeta; } + /** + * Get as wool block meta value + * + * @return wool block meta value of the DyeColor + */ public int getWoolData() { return this.woolColorMeta; } + /** + * Get color name + * + * @return color name + */ public String getName() { return this.colorName; } + /** + * Get dye name + * + * @return dye name + */ public String getDyeName() { return this.dyeName; } @@ -75,10 +104,22 @@ public String getDyeName() { } } + /** + * Get DyeColor by dye item meta value + * + * @param dyeColorMeta dye item meta value + * @return DyeColor + */ public static DyeColor getByDyeData(int dyeColorMeta) { return BY_DYE_DATA[dyeColorMeta & 0x0f]; } + /** + * Get DyeColor by wool block meta value + * + * @param woolColorMeta wool block meta value + * @return DyeColor + */ public static DyeColor getByWoolData(int woolColorMeta) { return BY_WOOL_DATA[woolColorMeta & 0x0f]; } diff --git a/src/main/java/cn/nukkit/utils/EventException.java b/src/main/java/cn/nukkit/utils/EventException.java index f7f313907c5..ca0b487b0a0 100644 --- a/src/main/java/cn/nukkit/utils/EventException.java +++ b/src/main/java/cn/nukkit/utils/EventException.java @@ -1,10 +1,13 @@ package cn.nukkit.utils; /** - * author: MagicDroidX + * EventException + * + * @author MagicDroidX * Nukkit Project */ public class EventException extends RuntimeException { + private final Throwable cause; /** diff --git a/src/main/java/cn/nukkit/utils/Faceable.java b/src/main/java/cn/nukkit/utils/Faceable.java index 02d2cfc700b..53ea2dc7286 100644 --- a/src/main/java/cn/nukkit/utils/Faceable.java +++ b/src/main/java/cn/nukkit/utils/Faceable.java @@ -2,8 +2,15 @@ import cn.nukkit.math.BlockFace; +/** + * Interface of a faceable Block + */ public interface Faceable { + /** + * Get BlockFace of the direction the block is facing + * + * @return BlockFace of the direction the block is facing + */ BlockFace getBlockFace(); - -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/utils/Hash.java b/src/main/java/cn/nukkit/utils/Hash.java index 3864583db8b..d4b56175b04 100644 --- a/src/main/java/cn/nukkit/utils/Hash.java +++ b/src/main/java/cn/nukkit/utils/Hash.java @@ -1,20 +1,23 @@ package cn.nukkit.utils; +/** + * Hash utils + */ public class Hash { + public static long hashBlock(int x, int y, int z) { - return y + (((long) x & 0x3FFFFFF) << 8) + (((long) z & 0x3FFFFFF) << 34); + return ((long) y << 52) + (((long) z & 0x3ffffff) << 26) + ((long) x & 0x3ffffff); } - - public static final int hashBlockX(long triple) { - return (int) ((((triple >> 8) & 0x3FFFFFF) << 38) >> 38); + public static int hashBlockX(long triple) { + return (int) (((triple & 0x3ffffff) << 38) >> 38); } - public static final int hashBlockY(long triple) { - return (int) (triple & 0xFF); + public static int hashBlockY(long triple) { + return (int) (triple >> 52); } - public static final int hashBlockZ(long triple) { - return (int) ((((triple >> 34) & 0x3FFFFFF) << 38) >> 38); + public static int hashBlockZ(long triple) { + return (int) ((((triple >> 26) & 0x3ffffff) << 38) >> 38); } } diff --git a/src/main/java/cn/nukkit/utils/HastebinUtility.java b/src/main/java/cn/nukkit/utils/HastebinUtility.java deleted file mode 100644 index cf75be3f12e..00000000000 --- a/src/main/java/cn/nukkit/utils/HastebinUtility.java +++ /dev/null @@ -1,65 +0,0 @@ -package cn.nukkit.utils; - -import java.io.*; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class HastebinUtility { - - public static final String BIN_URL = "https://hastebin.com/documents", USER_AGENT = "Mozilla/5.0"; - public static final Pattern PATTERN = Pattern.compile("\\{\"key\":\"([\\S\\s]*)\"}"); - - public static String upload(final String string) throws IOException { - final URL url = new URL(BIN_URL); - final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - - connection.setRequestMethod("POST"); - connection.setRequestProperty("User-Agent", USER_AGENT); - connection.setDoOutput(true); - - try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { - outputStream.write(string.getBytes()); - outputStream.flush(); - } - - StringBuilder response; - try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { - response = new StringBuilder(); - - String inputLine; - while ((inputLine = in.readLine()) != null) { - response.append(inputLine); - } - } - - Matcher matcher = PATTERN.matcher(response.toString()); - if (matcher.matches()) { - return "https://hastebin.com/" + matcher.group(1); - } else { - throw new RuntimeException("Couldn't read response!"); - } - } - - public static String upload(final File file) throws IOException { - final StringBuilder content = new StringBuilder(); - List lines = new ArrayList<>(); - try (BufferedReader reader = new BufferedReader(new FileReader(file))) { - String line; - int i = 0; - while ((line = reader.readLine()) != null) { - if (!line.contains("rcon.password=")) { - lines.add(line); - } - } - } - for (int i = Math.max(0, lines.size() - 1000); i < lines.size(); i++) { - content.append(lines.get(i)).append("\n"); - } - return upload(content.toString()); - } - -} diff --git a/src/main/java/cn/nukkit/utils/LevelException.java b/src/main/java/cn/nukkit/utils/LevelException.java index 0a24194f3ff..44f9a5c9530 100644 --- a/src/main/java/cn/nukkit/utils/LevelException.java +++ b/src/main/java/cn/nukkit/utils/LevelException.java @@ -1,10 +1,13 @@ package cn.nukkit.utils; /** - * author: MagicDroidX + * LevelException + * + * @author MagicDroidX * Nukkit Project */ public class LevelException extends ServerException { + public LevelException(String message) { super(message); } diff --git a/src/main/java/cn/nukkit/utils/LogLevel.java b/src/main/java/cn/nukkit/utils/LogLevel.java index 192e4c62486..599d410798c 100644 --- a/src/main/java/cn/nukkit/utils/LogLevel.java +++ b/src/main/java/cn/nukkit/utils/LogLevel.java @@ -5,10 +5,13 @@ import java.util.function.BiConsumer; /** - * author: MagicDroidX + * Log level enum + * + * @author MagicDroidX * Nukkit Project */ public enum LogLevel implements Comparable { + NONE((logger, message) -> {}, (mainLogger, s, throwable) -> {}), EMERGENCY(MainLogger::emergency, MainLogger::emergency), ALERT(MainLogger::alert, MainLogger::alert), @@ -19,6 +22,10 @@ public enum LogLevel implements Comparable { INFO(MainLogger::info, MainLogger::info), DEBUG(MainLogger::debug, MainLogger::debug); + /** + * Default logging level: INFO + */ + @Deprecated public static final LogLevel DEFAULT_LEVEL = INFO; private final BiConsumer logTo; @@ -37,7 +44,12 @@ public void log(MainLogger logger, String message, Throwable throwable) { logThrowableTo.accept(logger, message, throwable); } + /** + * Get log level + * + * @return log level + */ public int getLevel() { return ordinal(); } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/utils/Logger.java b/src/main/java/cn/nukkit/utils/Logger.java index 7f635409162..0db36e86b28 100644 --- a/src/main/java/cn/nukkit/utils/Logger.java +++ b/src/main/java/cn/nukkit/utils/Logger.java @@ -1,7 +1,9 @@ package cn.nukkit.utils; /** - * author: MagicDroidX + * Logger + * + * @author MagicDroidX * Nukkit Project */ public interface Logger { diff --git a/src/main/java/cn/nukkit/utils/LoginChainData.java b/src/main/java/cn/nukkit/utils/LoginChainData.java index 398d9367d10..c4dacc85662 100644 --- a/src/main/java/cn/nukkit/utils/LoginChainData.java +++ b/src/main/java/cn/nukkit/utils/LoginChainData.java @@ -5,6 +5,8 @@ import java.util.UUID; /** + * Login chain data + * * @author CreeperFace */ public interface LoginChainData { @@ -44,4 +46,6 @@ public interface LoginChainData { int getUIProfile(); JsonObject getRawData(); + + String getTitleId(); } diff --git a/src/main/java/cn/nukkit/utils/MainLogger.java b/src/main/java/cn/nukkit/utils/MainLogger.java index 02a430cc0d4..cb9c8295578 100644 --- a/src/main/java/cn/nukkit/utils/MainLogger.java +++ b/src/main/java/cn/nukkit/utils/MainLogger.java @@ -1,19 +1,20 @@ package cn.nukkit.utils; +import cn.nukkit.Nukkit; import lombok.AccessLevel; import lombok.NoArgsConstructor; import lombok.extern.log4j.Log4j2; /** - * author: MagicDroidX + * Main logger + * + * @author MagicDroidX * Nukkit */ -/* -We need to keep this class for backwards compatibility - */ +//We need to keep this class for backwards compatibility @Log4j2 @NoArgsConstructor(access = AccessLevel.PRIVATE) -public class MainLogger extends ThreadedLogger { +public class MainLogger extends Thread implements Logger { private static final MainLogger logger = new MainLogger(); @@ -58,11 +59,9 @@ public void info(String message) { @Override public void debug(String message) { - log.debug(message); - } - - public void setLogDebug(Boolean logDebug) { - throw new UnsupportedOperationException(); + if (Nukkit.DEBUG > 1) { + log.debug(message); + } } public void logException(Throwable t) { @@ -74,10 +73,6 @@ public void log(LogLevel level, String message) { level.log(this, message); } - public void shutdown() { - throw new UnsupportedOperationException(); - } - @Override public void emergency(String message, Throwable t) { log.fatal(message, t); @@ -122,4 +117,4 @@ public void debug(String message, Throwable t) { public void log(LogLevel level, String message, Throwable t) { level.log(this, message, t); } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/utils/MinecartType.java b/src/main/java/cn/nukkit/utils/MinecartType.java index dda0805e554..44ab179c0a8 100644 --- a/src/main/java/cn/nukkit/utils/MinecartType.java +++ b/src/main/java/cn/nukkit/utils/MinecartType.java @@ -1,9 +1,7 @@ package cn.nukkit.utils; -import cn.nukkit.api.API; - -import java.util.HashMap; -import java.util.Map; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; /** * Helper class of Minecart variants @@ -11,7 +9,6 @@ * By Adam Matthew * Creation time: 2017/7/17 19:55. */ -@API(usage = API.Usage.STABLE, definition = API.Definition.INTERNAL) public enum MinecartType { /** * Represents an empty vehicle. @@ -49,11 +46,11 @@ public enum MinecartType { private final int type; private final boolean hasBlockInside; private final String realName; - private static final Map TYPES = new HashMap<>(); + private static final Int2ObjectMap TYPES = new Int2ObjectOpenHashMap<>(); static { for (MinecartType var3 : values()) { - TYPES.put(var3.getId(), var3); + TYPES.put(var3.type, var3); } } diff --git a/src/main/java/cn/nukkit/utils/PersonaPiece.java b/src/main/java/cn/nukkit/utils/PersonaPiece.java index 7bd7bf372d2..6edaed09480 100644 --- a/src/main/java/cn/nukkit/utils/PersonaPiece.java +++ b/src/main/java/cn/nukkit/utils/PersonaPiece.java @@ -2,8 +2,12 @@ import lombok.ToString; +/** + * Persona skin piece + */ @ToString public class PersonaPiece { + public final String id; public final String type; public final String packId; diff --git a/src/main/java/cn/nukkit/utils/PersonaPieceTint.java b/src/main/java/cn/nukkit/utils/PersonaPieceTint.java index a24088c25a4..fb6cfedc98e 100644 --- a/src/main/java/cn/nukkit/utils/PersonaPieceTint.java +++ b/src/main/java/cn/nukkit/utils/PersonaPieceTint.java @@ -5,8 +5,12 @@ import java.util.List; +/** + * Persona skin piece tint + */ @ToString public class PersonaPieceTint { + public final String pieceType; public final ImmutableList colors; diff --git a/src/main/java/cn/nukkit/utils/PlayerDataSerializer.java b/src/main/java/cn/nukkit/utils/PlayerDataSerializer.java index fad786cbec0..bfa390096e2 100644 --- a/src/main/java/cn/nukkit/utils/PlayerDataSerializer.java +++ b/src/main/java/cn/nukkit/utils/PlayerDataSerializer.java @@ -6,6 +6,11 @@ import java.util.Optional; import java.util.UUID; +/** + * A serializer that handles the player data saving. + *

    + * Use setPlayerDataSerializer() in Server to register it. + */ public interface PlayerDataSerializer { /** diff --git a/src/main/java/cn/nukkit/utils/PluginException.java b/src/main/java/cn/nukkit/utils/PluginException.java index 6e7751e97cf..c9d19c71d10 100644 --- a/src/main/java/cn/nukkit/utils/PluginException.java +++ b/src/main/java/cn/nukkit/utils/PluginException.java @@ -1,10 +1,13 @@ package cn.nukkit.utils; /** - * author: MagicDroidX + * PluginException + * + * @author MagicDroidX * Nukkit Project */ public class PluginException extends ServerException { + public PluginException(String message) { super(message); } diff --git a/src/main/java/cn/nukkit/utils/Rail.java b/src/main/java/cn/nukkit/utils/Rail.java index 7cb9d958e2a..6ab4883f5df 100644 --- a/src/main/java/cn/nukkit/utils/Rail.java +++ b/src/main/java/cn/nukkit/utils/Rail.java @@ -1,6 +1,5 @@ package cn.nukkit.utils; -import cn.nukkit.api.API; import cn.nukkit.block.Block; import cn.nukkit.math.BlockFace; @@ -16,17 +15,25 @@ /** * INTERNAL helper class of railway *

    - * By lmlstarqaq http://snake1999.com/ + * By lmlstarqaq ... * Creation time: 2017/7/1 17:42. */ -@API(usage = API.Usage.BLEEDING, definition = API.Definition.INTERNAL) public final class Rail { + /** + * Check if the block is a rail block + * + * @param block block + * @return is rail block + */ public static boolean isRailBlock(Block block) { Objects.requireNonNull(block, "Rail block predicate can not accept null block"); return isRailBlock(block.getId()); } + /** + * Rail orientation enum + */ public enum Orientation { STRAIGHT_NORTH_SOUTH(0, STRAIGHT, NORTH, SOUTH, null), STRAIGHT_EAST_WEST(1, STRAIGHT, EAST, WEST, null), @@ -120,6 +127,9 @@ public Optional ascendingDirection() { return Optional.ofNullable(ascendingDirection); } + /** + * Rail orientation state enum + */ public enum State { STRAIGHT, ASCENDING, CURVED } @@ -143,6 +153,12 @@ public boolean isCurved() { } } + /** + * Check if the block is a rail block + * + * @param blockId block id + * @return is rail block + */ public static boolean isRailBlock(int blockId) { switch (blockId) { case Block.RAIL: diff --git a/src/main/java/cn/nukkit/utils/SerializedImage.java b/src/main/java/cn/nukkit/utils/SerializedImage.java index 2fddf118d96..546e8882676 100644 --- a/src/main/java/cn/nukkit/utils/SerializedImage.java +++ b/src/main/java/cn/nukkit/utils/SerializedImage.java @@ -6,8 +6,15 @@ import static cn.nukkit.entity.data.Skin.*; -@ToString(exclude = {"data"}) +/** + * Serialized image + */ +@ToString(exclude = "data") public class SerializedImage { + + /** + * Empty SerializedImage + */ public static final SerializedImage EMPTY = new SerializedImage(0, 0, new byte[0]); public final int width; @@ -20,6 +27,12 @@ public SerializedImage(int width, int height, byte[] data) { this.data = data; } + /** + * Get SerializedImage from legacy skin data + * + * @param skinData legacy skin data bytes + * @return SerializedImage + */ public static SerializedImage fromLegacy(byte[] skinData) { Objects.requireNonNull(skinData, "skinData"); switch (skinData.length) { diff --git a/src/main/java/cn/nukkit/utils/ServerException.java b/src/main/java/cn/nukkit/utils/ServerException.java index 77987b1ba4a..365011fc934 100644 --- a/src/main/java/cn/nukkit/utils/ServerException.java +++ b/src/main/java/cn/nukkit/utils/ServerException.java @@ -1,10 +1,13 @@ package cn.nukkit.utils; /** - * author: MagicDroidX + * ServerException + * + * @author MagicDroidX * Nukkit Project */ public class ServerException extends RuntimeException { + public ServerException(String message) { super(message); } diff --git a/src/main/java/cn/nukkit/utils/ServerKiller.java b/src/main/java/cn/nukkit/utils/ServerKiller.java index 28f16d39d00..8ff264c580e 100644 --- a/src/main/java/cn/nukkit/utils/ServerKiller.java +++ b/src/main/java/cn/nukkit/utils/ServerKiller.java @@ -3,7 +3,9 @@ import java.util.concurrent.TimeUnit; /** - * author: MagicDroidX + * A task that kills the server process after given time. + * + * @author MagicDroidX * Nukkit Project */ public class ServerKiller extends Thread { @@ -23,10 +25,8 @@ public ServerKiller(long time, TimeUnit unit) { public void run() { try { sleep(sleepTime); - } catch (InterruptedException e) { - // ignore - } - System.out.println("\nTook too long to stop, server was killed forcefully!\n"); + } catch (InterruptedException ignored) {} + System.out.println("Took too long to stop, server was killed forcefully!"); System.exit(1); } } diff --git a/src/main/java/cn/nukkit/utils/SimpleConfig.java b/src/main/java/cn/nukkit/utils/SimpleConfig.java index 8aa73c526a1..01d188a4b99 100644 --- a/src/main/java/cn/nukkit/utils/SimpleConfig.java +++ b/src/main/java/cn/nukkit/utils/SimpleConfig.java @@ -15,9 +15,11 @@ import java.util.List; /** - * SimpleConfig for Nukkit - * added 11/02/2016 by fromgate + * Simple config for Nukkit + *

    + * Added 11/02/2016 by fromgate */ +@SuppressWarnings("unused") public abstract class SimpleConfig { private final File configFile; @@ -35,10 +37,21 @@ public SimpleConfig(File file) { configFile.getParentFile().mkdirs(); } + /** + * Save the config to disk + * + * @return saved + */ public boolean save() { return save(false); } + /** + * Save the config to disk + * + * @param async async + * @return saved + */ public boolean save(boolean async) { if (configFile.exists()) try { configFile.createNewFile(); @@ -59,12 +72,17 @@ public boolean save(boolean async) { return true; } + /** + * Load + * + * @return loaded + */ public boolean load() { if (!this.configFile.exists()) return false; Config cfg = new Config(configFile, Config.YAML); for (Field field : this.getClass().getDeclaredFields()) { if (field.getName().equals("configFile")) continue; - if (skipSave(field)) continue; + if (skipLoad(field)) continue; String path = getPath(field); if (path == null) continue; if (path.isEmpty()) continue; @@ -106,19 +124,19 @@ else if (field.getType() == List.class) { return true; } - private String getPath(Field field) { + private static String getPath(Field field) { String path = null; if (field.isAnnotationPresent(Path.class)) { Path pathDefine = field.getAnnotation(Path.class); path = pathDefine.value(); } - if (path == null || path.isEmpty()) path = field.getName().replaceAll("_", "."); + if (path == null || path.isEmpty()) path = field.getName().replace("_", "."); if (Modifier.isFinal(field.getModifiers())) return null; if (Modifier.isPrivate(field.getModifiers())) field.setAccessible(true); return path; } - private boolean skipSave(Field field) { + private static boolean skipSave(Field field) { if (!field.isAnnotationPresent(Skip.class)) return false; return field.getAnnotation(Skip.class).skipSave(); } diff --git a/src/main/java/cn/nukkit/utils/SkinAnimation.java b/src/main/java/cn/nukkit/utils/SkinAnimation.java index 236261d21ae..10bcf2ba171 100644 --- a/src/main/java/cn/nukkit/utils/SkinAnimation.java +++ b/src/main/java/cn/nukkit/utils/SkinAnimation.java @@ -2,17 +2,21 @@ import lombok.ToString; +/** + * Skin animation + */ @ToString public class SkinAnimation { + public final SerializedImage image; public final int type; public final float frames; public final int expression; public SkinAnimation(SerializedImage image, int type, float frames, int expression) { - this.image = image; - this.type = type; - this.frames = frames; - this.expression = expression; + this.image = image; + this.type = type; + this.frames = frames; + this.expression = expression; } } diff --git a/src/main/java/cn/nukkit/utils/SnappyCompression.java b/src/main/java/cn/nukkit/utils/SnappyCompression.java new file mode 100644 index 00000000000..9584811a848 --- /dev/null +++ b/src/main/java/cn/nukkit/utils/SnappyCompression.java @@ -0,0 +1,26 @@ +package cn.nukkit.utils; + +import org.xerial.snappy.Snappy; + +import java.io.IOException; + +/** + * Implements data compression and decompression using Snappy, powered by snappy-java (org.xerial.snappy) + * @author PetteriM1 + */ +public class SnappyCompression { + + public static byte[] compress(byte[] data) throws IOException { + return Snappy.compress(data); + } + + public static byte[] decompress(byte[] data, int maxSize) throws IOException { + int size = Snappy.uncompressedLength(data); + if (size > maxSize && maxSize > 0) { + throw new IllegalArgumentException("Input is too big"); + } + byte[] decompressed = new byte[size]; + Snappy.uncompress(data, 0, data.length, decompressed, 0); + return decompressed; + } +} diff --git a/src/main/java/cn/nukkit/utils/TerracottaColor.java b/src/main/java/cn/nukkit/utils/TerracottaColor.java index 519532ff562..d43747ebe2f 100644 --- a/src/main/java/cn/nukkit/utils/TerracottaColor.java +++ b/src/main/java/cn/nukkit/utils/TerracottaColor.java @@ -1,5 +1,8 @@ package cn.nukkit.utils; +/** + * Terracotta color enum + */ public enum TerracottaColor { BLACK(0, 15, "Black", "Ink Sac", BlockColor.BLACK_TERRACOTA_BLOCK_COLOR), @@ -20,11 +23,11 @@ public enum TerracottaColor { WHITE(15, 0, "White", "Bone Meal", BlockColor.WHITE_TERRACOTA_BLOCK_COLOR); - private int dyeColorMeta; - private int terracottaColorMeta; - private String colorName; - private String dyeName; - private BlockColor blockColor; + private final int dyeColorMeta; + private final int terracottaColorMeta; + private final String colorName; + private final String dyeName; + private final BlockColor blockColor; private final static TerracottaColor[] BY_TERRACOTA_DATA; @@ -42,22 +45,47 @@ public enum TerracottaColor { this.dyeName = dyeName; } + /** + * Get as BlockColor + * + * @return BlockColor of the TerracottaColor + */ public BlockColor getColor() { return this.blockColor; } + /** + * Get as dye item meta value + * + * @return dye item meta value of the TerracottaColor + */ public int getDyeData() { return this.dyeColorMeta; } + /** + * Get as terracotta block meta value + * + * @return terracotta block meta value of the TerracottaColor + */ public int getTerracottaData() { return this.terracottaColorMeta; } + /** + * Get color name + * + * @return color name + */ public String getName() { return this.colorName; } + /** + * Get dye name + * + * @return dye name + */ public String getDyeName() { return this.dyeName; } @@ -72,10 +100,21 @@ public String getDyeName() { } } + /** + * Get TerracottaColor by dye item meta value + * @param dyeColorMeta dye item meta value + * @return TerracottaColor + */ public static TerracottaColor getByDyeData(int dyeColorMeta) { return BY_DYE_DATA[dyeColorMeta & 0x0f]; } - public static TerracottaColor getByTerracottaData(int terracottaColorMeta) { return BY_TERRACOTA_DATA[terracottaColorMeta & 0x0f]; } - + /** + * Get TerracottaColor by terracotta block meta value + * @param terracottaColorMeta terracotta block meta value + * @return TerracottaColor + */ + public static TerracottaColor getByTerracottaData(int terracottaColorMeta) { + return BY_TERRACOTA_DATA[terracottaColorMeta & 0x0f]; + } } diff --git a/src/main/java/cn/nukkit/utils/TextFormat.java b/src/main/java/cn/nukkit/utils/TextFormat.java index e0f0413cafc..393c87a4bc0 100644 --- a/src/main/java/cn/nukkit/utils/TextFormat.java +++ b/src/main/java/cn/nukkit/utils/TextFormat.java @@ -11,106 +11,106 @@ public enum TextFormat { /** * Represents black. */ - BLACK('0', 0x00), + BLACK('0'), /** * Represents dark blue. */ - DARK_BLUE('1', 0x1), + DARK_BLUE('1'), /** * Represents dark green. */ - DARK_GREEN('2', 0x2), + DARK_GREEN('2'), /** * Represents dark blue (aqua). */ - DARK_AQUA('3', 0x3), + DARK_AQUA('3'), /** * Represents dark red. */ - DARK_RED('4', 0x4), + DARK_RED('4'), /** * Represents dark purple. */ - DARK_PURPLE('5', 0x5), + DARK_PURPLE('5'), /** * Represents gold. */ - GOLD('6', 0x6), + GOLD('6'), /** * Represents gray. */ - GRAY('7', 0x7), + GRAY('7'), /** * Represents dark gray. */ - DARK_GRAY('8', 0x8), + DARK_GRAY('8'), /** * Represents blue. */ - BLUE('9', 0x9), + BLUE('9'), /** * Represents green. */ - GREEN('a', 0xA), + GREEN('a'), /** * Represents aqua. */ - AQUA('b', 0xB), + AQUA('b'), /** * Represents red. */ - RED('c', 0xC), + RED('c'), /** * Represents light purple. */ - LIGHT_PURPLE('d', 0xD), + LIGHT_PURPLE('d'), /** * Represents yellow. */ - YELLOW('e', 0xE), + YELLOW('e'), /** * Represents white. */ - WHITE('f', 0xF), + WHITE('f'), /** * Represents minecoins gold. */ - MINECOIN_GOLD('g', 0x16), + MINECOIN_GOLD('g'), /** * Makes the text obfuscated. */ - OBFUSCATED('k', 0x10, true), + OBFUSCATED('k', true), /** * Makes the text bold. */ - BOLD('l', 0x11, true), + BOLD('l', true), /** * Makes a line appear through the text. */ - STRIKETHROUGH('m', 0x12, true), + STRIKETHROUGH('m', true), /** * Makes the text appear underlined. */ - UNDERLINE('n', 0x13, true), + UNDERLINE('n', true), /** * Makes the text italic. */ - ITALIC('o', 0x14, true), + ITALIC('o', true), /** * Resets all previous chat colors or formats. */ - RESET('r', 0x15), + RESET('r'), - MATERIAL_QUARTZ('h', 0), - MATERIAL_IRON('i', 0), - MATERIAL_NETHERITE('j', 0), - MATERIAL_REDSTONE('m', 0), - MATERIAL_COPPER('n', 0), - MATERIAL_GOLD('p', 0), - MATERIAL_EMERALD('q', 0), - MATERIAL_DIAMOND('s', 0), - MATERIAL_LAPIS('t', 0), - MATERIAL_AMETHYST('u', 0); + MATERIAL_QUARTZ('h'), + MATERIAL_IRON('i'), + MATERIAL_NETHERITE('j'), + MATERIAL_REDSTONE('m'), + MATERIAL_COPPER('n'), + MATERIAL_GOLD('p'), + MATERIAL_EMERALD('q'), + MATERIAL_DIAMOND('s'), + MATERIAL_LAPIS('t'), + MATERIAL_AMETHYST('u'); /** * The special character which prefixes all format codes. Use this if @@ -119,28 +119,24 @@ public enum TextFormat { public static final char ESCAPE = '\u00A7'; private static final Pattern CLEAN_PATTERN = Pattern.compile("(?i)" + ESCAPE + "[0-9A-U]"); - //private final static Map BY_ID = new TreeMap<>(); //unused private final static Map BY_CHAR = new HashMap<>(); static { for (TextFormat color : values()) { - //BY_ID.put(color.intCode, color); BY_CHAR.put(color.code, color); } } - //private final int intCode; private final char code; private final boolean isFormat; private final String toString; - TextFormat(char code, int intCode) { - this(code, intCode, false); + TextFormat(char code) { + this(code, false); } - TextFormat(char code, int intCode, boolean isFormat) { + TextFormat(char code, boolean isFormat) { this.code = code; - //this.intCode = intCode; this.isFormat = isFormat; this.toString = new String(new char[]{ESCAPE, code}); } @@ -149,7 +145,7 @@ public enum TextFormat { * Gets the TextFormat represented by the specified format code. * * @param code Code to check - * @return Associative {@link TextFormat} with the given code, + * @return Associative with the given code, * or null if it doesn't exist */ public static TextFormat getByChar(char code) { @@ -160,7 +156,7 @@ public static TextFormat getByChar(char code) { * Gets the TextFormat represented by the specified format code. * * @param code Code to check - * @return Associative {@link TextFormat} with the given code, + * @return Associative with the given code, * or null if it doesn't exist */ public static TextFormat getByChar(String code) { @@ -181,6 +177,13 @@ public static String clean(final String input) { return clean(input, false); } + /** + * Cleans the given message of all format codes. + * + * @param input String to clean. + * @param recursive Do recursively. + * @return A copy of the input string, without any formatting. + */ public static String clean(final String input, final boolean recursive) { if (input == null) { return null; @@ -200,7 +203,7 @@ public static String clean(final String input, final boolean recursive) { * character. The alternate format code character will only be replaced if * it is immediately followed by 0-9, A-G, a-g, K-O, k-o, R or r. * - * @param altFormatChar The alternate format code character to replace. Ex: & + * @param altFormatChar The alternate format code character to replace. Ex: &amp; * @param textToTranslate Text containing the alternate format code character. * @return Text containing the TextFormat.ESCAPE format code character. */ @@ -241,10 +244,8 @@ public static String getLastColors(String input) { // Search backwards from the end as it is faster for (int index = length - 1; index > -1; index--) { - char section = input.charAt(index); - if (section == ESCAPE && index < length - 1) { - char c = input.charAt(index + 1); - TextFormat color = getByChar(c); + if (input.charAt(index) == ESCAPE && index < length - 1) { + TextFormat color = getByChar(input.charAt(index + 1)); if (color != null) { result.insert(0, color.toString()); @@ -287,4 +288,4 @@ public boolean isFormat() { public boolean isColor() { return !isFormat && this != RESET; } -} +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/utils/ThreadCache.java b/src/main/java/cn/nukkit/utils/ThreadCache.java index 1bb09c06f2b..c9546606b80 100644 --- a/src/main/java/cn/nukkit/utils/ThreadCache.java +++ b/src/main/java/cn/nukkit/utils/ThreadCache.java @@ -4,24 +4,34 @@ import java.util.BitSet; +/** + * Thread cache + */ public class ThreadCache { @Deprecated public static void clean() { } + @Deprecated public static final ThreadLocal idArray = ThreadLocal.withInitial(() -> new byte[16][]); + @Deprecated public static final ThreadLocal dataArray = ThreadLocal.withInitial(() -> new byte[16][]); + @Deprecated public static final ThreadLocal byteCache6144 = ThreadLocal.withInitial(() -> new byte[6144]); + @Deprecated public static final ThreadLocal byteCache256 = ThreadLocal.withInitial(() -> new byte[256]); + @Deprecated public static final ThreadLocal boolCache4096 = ThreadLocal.withInitial(() -> new BitSet(4096)); + @Deprecated public static final ThreadLocal charCache4096v2 = ThreadLocal.withInitial(() -> new char[4096]); + @Deprecated public static final ThreadLocal charCache4096 = ThreadLocal.withInitial(() -> new char[4096]); public static final ThreadLocal intCache256 = ThreadLocal.withInitial(() -> new int[256]); diff --git a/src/main/java/cn/nukkit/utils/ThreadStore.java b/src/main/java/cn/nukkit/utils/ThreadStore.java index 1aa2bb836e2..41285f61f71 100644 --- a/src/main/java/cn/nukkit/utils/ThreadStore.java +++ b/src/main/java/cn/nukkit/utils/ThreadStore.java @@ -4,9 +4,12 @@ import java.util.concurrent.ConcurrentHashMap; /** - * author: MagicDroidX + * Thread store + * + * @author MagicDroidX * Nukkit Project */ public class ThreadStore { + public static final Map store = new ConcurrentHashMap<>(); } diff --git a/src/main/java/cn/nukkit/utils/ThreadedLogger.java b/src/main/java/cn/nukkit/utils/ThreadedLogger.java deleted file mode 100644 index b567b1d964d..00000000000 --- a/src/main/java/cn/nukkit/utils/ThreadedLogger.java +++ /dev/null @@ -1,8 +0,0 @@ -package cn.nukkit.utils; - -/** - * author: MagicDroidX - * Nukkit Project - */ -public abstract class ThreadedLogger extends Thread implements Logger { -} diff --git a/src/main/java/cn/nukkit/utils/Utils.java b/src/main/java/cn/nukkit/utils/Utils.java index 377fa3db031..4ef795cd25d 100644 --- a/src/main/java/cn/nukkit/utils/Utils.java +++ b/src/main/java/cn/nukkit/utils/Utils.java @@ -1,21 +1,39 @@ package cn.nukkit.utils; +import cn.nukkit.Player; +import cn.nukkit.Server; +import cn.nukkit.nbt.NBTIO; +import cn.nukkit.nbt.tag.Tag; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; + import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; +import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.Arrays; import java.util.Map; +import java.util.SplittableRandom; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import java.util.zip.GZIPInputStream; /** - * author: MagicDroidX + * This class contains miscellaneous stuff used in other parts of the program. + * + * @author MagicDroidX * Nukkit Project */ public class Utils { + /** + * A SplittableRandom you can use without having to create a new object every time. + */ + public static final SplittableRandom random = new SplittableRandom(); + public static void writeFile(String fileName, String content) throws IOException { writeFile(fileName, new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8))); } @@ -49,7 +67,7 @@ public static String readFile(File file) throws IOException { if (!file.exists() || file.isDirectory()) { throw new FileNotFoundException(); } - return readFile(new FileInputStream(file)); + return readFile(Files.newInputStream(file.toPath())); } public static String readFile(String filename) throws IOException { @@ -57,7 +75,7 @@ public static String readFile(String filename) throws IOException { if (!file.exists() || file.isDirectory()) { throw new FileNotFoundException(); } - return readFile(new FileInputStream(file)); + return readFile(Files.newInputStream(file.toPath())); } public static String readFile(InputStream inputStream) throws IOException { @@ -71,7 +89,7 @@ private static String readFile(Reader reader) throws IOException { temp = br.readLine(); while (temp != null) { if (stringBuilder.length() != 0) { - stringBuilder.append("\n"); + stringBuilder.append('\n'); } stringBuilder.append(temp); temp = br.readLine(); @@ -209,7 +227,7 @@ public static T[] reverseArray(T[] array, boolean copy) { } for (int left = 0, right = data.length - 1; left < right; left++, right--) { - // swap the values at the left and right indices + // Swap the values at the left and right indices T temp = data[left]; data[left] = data[right]; data[right] = temp; @@ -268,28 +286,139 @@ public static int toInt(Object number) { public static byte[] parseHexBinary(String s) { final int len = s.length(); - // "111" is not a valid hex encoding. - if(len % 2 != 0) + // "111" is not a valid hex encoding + if (len % 2 != 0) throw new IllegalArgumentException("hexBinary needs to be even-length: " + s); - byte[] out = new byte[len / 2]; + byte[] out = new byte[(len >> 1)]; - for(int i = 0; i < len; i += 2) { + for (int i = 0; i < len; i += 2) { int h = hexToBin(s.charAt(i)); int l = hexToBin(s.charAt(i + 1)); - if(h == -1 || l == -1) + if (h == -1 || l == -1) throw new IllegalArgumentException("contains illegal character for hexBinary: " + s); - out[i / 2] = (byte)(h * 16 + l); + out[(i >> 1)] = (byte)((h << 4) + l); } return out; } private static int hexToBin( char ch ) { - if('0' <= ch && ch <= '9') return ch - '0'; - if('A' <= ch && ch <= 'F') return ch - 'A' + 10; - if('a' <= ch && ch <= 'f') return ch - 'a' + 10; + if ('0' <= ch && ch <= '9') return ch - '0'; + if ('A' <= ch && ch <= 'F') return ch - 'A' + 10; + if ('a' <= ch && ch <= 'f') return ch - 'a' + 10; return -1; } + + /** + * Get a random int + * + * @param min minimum value + * @param max maximum value + * @return random int between min and max + */ + public static int rand(int min, int max) { + if (min == max) { + return max; + } + return random.nextInt(max + 1 - min) + min; + } + + /** + * Get a random double + * + * @param min minimum value + * @param max maximum value + * @return random double between min and max + */ + public static double rand(double min, double max) { + if (min == max) { + return max; + } + return min + random.nextDouble() * (max-min); + } + + /** + * Get a random boolean + * + * @return random boolean + */ + public static boolean rand() { + return random.nextBoolean(); + } + + /** + * Get player's operating system/device name from login chain data. + * NOTICE: It's possible to spoof this. + * + * @param player player + * @return operating system/device name + */ + public static String getOS(Player player) { + switch (player.getLoginChainData().getDeviceOS()) { + case 1: + return "Android"; + case 2: + return "iOS"; + case 3: + return "macOS"; + case 4: + return "Fire OS"; + case 5: + return "Gear VR"; + case 6: + return "HoloLens"; + case 7: + return "Windows 10"; + case 8: + return "Windows"; + case 9: + return "Dedicated"; + case 10: + return "tvOS"; + case 11: + return "PlayStation"; + case 12: + return "Switch"; + case 13: + return "Xbox"; + case 14: + return "Windows Phone"; + case 15: + return "Linux"; + default: + return "Unknown"; + } + } + + public static JsonElement loadJsonResource(String file) { + try { + InputStream stream = Server.class.getClassLoader().getResourceAsStream(file); + if (stream == null) { + throw new AssertionError("Unable to load " + file); + } + + JsonElement element = JsonParser.parseReader(new InputStreamReader(stream, StandardCharsets.UTF_8)); + stream.close(); + return element; + } catch (Exception e) { + throw new RuntimeException("Unable to load " + file, e); + } + } + + public static Tag loadTagResource(String file) { + try { + InputStream stream = Server.class.getClassLoader().getResourceAsStream(file); + if (stream == null) { + throw new AssertionError("Unable to load " + file); + } + + Tag tag = NBTIO.readTag(new BufferedInputStream(new GZIPInputStream(stream)), ByteOrder.BIG_ENDIAN, false); + stream.close(); + return tag; + } catch (Exception e) { + throw new RuntimeException("Unable to load " + file, e); + } + } } diff --git a/src/main/java/cn/nukkit/utils/VarInt.java b/src/main/java/cn/nukkit/utils/VarInt.java index b820d21144c..09ee51e5be9 100644 --- a/src/main/java/cn/nukkit/utils/VarInt.java +++ b/src/main/java/cn/nukkit/utils/VarInt.java @@ -1,23 +1,17 @@ package cn.nukkit.utils; -import cn.nukkit.api.API; - import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import static cn.nukkit.api.API.Definition.UNIVERSAL; -import static cn.nukkit.api.API.Usage.EXPERIMENTAL; - /** * Tool class for VarInt or VarLong operations. *

    - * Some code from http://wiki.vg/Protocol. + * Some code from .... * * @author MagicDroidX * @author lmlstarqaq */ -@API(usage = EXPERIMENTAL, definition = UNIVERSAL) public final class VarInt { private VarInt() { diff --git a/src/main/java/cn/nukkit/utils/Watchdog.java b/src/main/java/cn/nukkit/utils/Watchdog.java index 54ce13617e4..b42925c3abb 100644 --- a/src/main/java/cn/nukkit/utils/Watchdog.java +++ b/src/main/java/cn/nukkit/utils/Watchdog.java @@ -1,49 +1,59 @@ package cn.nukkit.utils; import cn.nukkit.Server; + import java.lang.management.ManagementFactory; import java.lang.management.MonitorInfo; import java.lang.management.ThreadInfo; +/** + * Watchdog monitors the server's main thread and kills the server if it gets frozen. + */ public class Watchdog extends Thread { private final Server server; - private final long time; - public boolean running; - private boolean responding = true; + /** + * Watchdog threshold + */ + public volatile long time; + /** + * Watchdog running + */ + public volatile boolean running; public Watchdog(Server server, long time) { this.server = server; this.time = time; this.running = true; this.setName("Watchdog"); + this.setDaemon(true); } + /** + * Disable Watchdog + */ public void kill() { - running = false; - synchronized (this) { - this.notifyAll(); - } + this.running = false; + this.interrupt(); } @Override public void run() { while (this.running) { - long current = server.getNextTick(); + long current = this.server.getNextTick(); if (current != 0) { long diff = System.currentTimeMillis() - current; - if (!responding && diff > time * 2) { - System.exit(1); // Kill the server if it gets stuck on shutdown - } - if (server.isRunning() && diff > time) { - if (responding) { + if (diff > this.time) { + if (this.server.isRunning()) { MainLogger logger = this.server.getLogger(); - logger.emergency("--------- Server stopped responding --------- (" + Math.round(diff / 1000d) + "s)"); - logger.emergency("Please report this to Nukkit:"); - logger.emergency(" - https://github.com/NukkitX/Nukkit/issues/new"); + long lastResponse = Math.round(diff / 1000d); + + logger.emergency("--------- Server stopped responding ---------"); + logger.emergency("Last response " + lastResponse + " seconds ago"); logger.emergency("---------------- Main thread ----------------"); - dumpThread(ManagementFactory.getThreadMXBean().getThreadInfo(this.server.getPrimaryThread().getId(), Integer.MAX_VALUE), logger); + ThreadInfo mainThread = ManagementFactory.getThreadMXBean().getThreadInfo(this.server.getPrimaryThread().getId(), Integer.MAX_VALUE); + dumpThread(mainThread, logger); logger.emergency("---------------- All threads ----------------"); ThreadInfo[] threads = ManagementFactory.getThreadMXBean().dumpAllThreads(true, true); @@ -52,25 +62,41 @@ public void run() { dumpThread(threads[i], logger); } logger.emergency("---------------------------------------------"); - responding = false; - this.server.forceShutdown(); + + if ("TIMED_WAITING".equals(mainThread.getThreadState().toString())) { + logger.warning("Make sure your plugins are not calling sleep() on main thread and that your terminal doesn't suspend server process when not focused"); + } + + this.server.forceShutdown("§cServer stopped responding"); + } else if (diff > time << 1) { + System.out.println("\nTook too long to stop, server was killed forcefully!\n"); + System.exit(1); + return; } - } else { - responding = true; } } try { - synchronized (this) { - this.wait(Math.max(time / 4, 1000)); + Thread.sleep(Math.max(this.time >> 2, 1000)); + } catch (InterruptedException ignore) { + if (this.running) { + this.running = false; + this.server.getLogger().emergency("The Watchdog thread has been interrupted and is no longer monitoring the server state"); } - } catch (InterruptedException ignore) {} + return; + } } } + /** + * Dump thread stack trace + * + * @param thread thread to dump + * @param logger logger + */ private static void dumpThread(ThreadInfo thread, Logger logger) { - logger.emergency("Current Thread: " + thread.getThreadName()); + logger.emergency("Thread: " + thread.getThreadName()); logger.emergency("\tPID: " + thread.getThreadId() + " | Suspended: " + thread.isSuspended() + " | Native: " + thread.isInNative() + " | State: " + thread.getThreadState()); - // Monitors + if (thread.getLockedMonitors().length != 0) { logger.emergency("\tThread is waiting on monitor(s):"); for (MonitorInfo monitor : thread.getLockedMonitors()) { diff --git a/src/main/java/cn/nukkit/utils/Zlib.java b/src/main/java/cn/nukkit/utils/Zlib.java index c4ca79a275e..f9cef72b868 100644 --- a/src/main/java/cn/nukkit/utils/Zlib.java +++ b/src/main/java/cn/nukkit/utils/Zlib.java @@ -3,40 +3,9 @@ import java.io.IOException; import java.util.zip.Deflater; - public abstract class Zlib { - private static ZlibProvider[] providers; - private static ZlibProvider provider; - - static { - providers = new ZlibProvider[3]; - providers[2] = new ZlibThreadLocal(); - provider = providers[2]; - } - - public static void setProvider(int providerIndex) { - MainLogger.getLogger().info("Selected Zlib Provider: " + providerIndex + " (" + provider.getClass().getCanonicalName() + ")"); - switch (providerIndex) { - case 0: - if (providers[providerIndex] == null) - providers[providerIndex] = new ZlibOriginal(); - break; - case 1: - if (providers[providerIndex] == null) - providers[providerIndex] = new ZlibSingleThreadLowMem(); - break; - case 2: - if (providers[providerIndex] == null) - providers[providerIndex] = new ZlibThreadLocal(); - break; - default: - throw new UnsupportedOperationException("Invalid provider: " + providerIndex); - } - if (providerIndex != 2) { - MainLogger.getLogger().warning(" - This Zlib will negatively affect performance"); - } - provider = providers[providerIndex]; - } + + private static final ZlibProvider provider = new ZlibThreadLocal(); public static byte[] deflate(byte[] data) throws Exception { return deflate(data, Deflater.DEFAULT_COMPRESSION); @@ -50,6 +19,14 @@ public static byte[] deflate(byte[][] data, int level) throws Exception { return provider.deflate(data, level); } + public static byte[] deflateRaw(byte[] data, int level) throws Exception { + return provider.deflateRaw(data, level); + } + + public static byte[] deflateRaw(byte[][] data, int level) throws Exception { + return provider.deflateRaw(data, level); + } + public static byte[] inflate(byte[] data) throws IOException { return inflate(data, -1); } @@ -57,4 +34,8 @@ public static byte[] inflate(byte[] data) throws IOException { public static byte[] inflate(byte[] data, int maxSize) throws IOException { return provider.inflate(data, maxSize); } + + public static byte[] inflateRaw(byte[] data, int maxSize) throws IOException { + return provider.inflateRaw(data, maxSize); + } } diff --git a/src/main/java/cn/nukkit/utils/ZlibOriginal.java b/src/main/java/cn/nukkit/utils/ZlibOriginal.java deleted file mode 100644 index ae3ebeb41a8..00000000000 --- a/src/main/java/cn/nukkit/utils/ZlibOriginal.java +++ /dev/null @@ -1,80 +0,0 @@ -package cn.nukkit.utils; - -import cn.nukkit.nbt.stream.FastByteArrayOutputStream; - -import java.io.IOException; -import java.util.zip.DataFormatException; -import java.util.zip.Deflater; -import java.util.zip.Inflater; - -public class ZlibOriginal implements ZlibProvider { - - @Override - public byte[] deflate(byte[][] datas, int level) throws IOException { - Deflater deflater = new Deflater(level); - byte[] buffer = new byte[1024]; - FastByteArrayOutputStream bos = ThreadCache.fbaos.get(); - bos.reset(); - try { - for (byte[] data : datas) { - deflater.setInput(data); - while (!deflater.needsInput()) { - int i = deflater.deflate(buffer); - bos.write(buffer, 0, i); - } - } - deflater.finish(); - while (!deflater.finished()) { - int i = deflater.deflate(buffer); - bos.write(buffer, 0, i); - } - } finally { - deflater.end(); - } - return bos.toByteArray(); - } - - @Override - public byte[] deflate(byte[] data, int level) throws IOException { - Deflater deflater = new Deflater(level); - deflater.setInput(data); - deflater.finish(); - FastByteArrayOutputStream bos = ThreadCache.fbaos.get(); - bos.reset(); - byte[] buf = new byte[1024]; - try { - while (!deflater.finished()) { - int i = deflater.deflate(buf); - bos.write(buf, 0, i); - } - } finally { - deflater.end(); - } - return bos.toByteArray(); - } - - @Override - public byte[] inflate(byte[] data, int maxSize) throws IOException { - Inflater inflater = new Inflater(); - inflater.setInput(data); - inflater.finished(); - FastByteArrayOutputStream bos = ThreadCache.fbaos.get(); - bos.reset(); - - byte[] buffer = new byte[1024]; - try { - int length = 0; - while (!inflater.finished()) { - int i = inflater.inflate(buffer); - length += i; - if (maxSize > 0 && length >= maxSize) { - throw new IOException("Inflated data exceeds maximum size"); - } - bos.write(buffer, 0, i); - } - return bos.toByteArray(); - } catch (DataFormatException e) { - throw new IOException("Unable to inflate zlib stream", e); - } - } -} diff --git a/src/main/java/cn/nukkit/utils/ZlibProvider.java b/src/main/java/cn/nukkit/utils/ZlibProvider.java index 936d8bbbbf6..1c4dad79026 100644 --- a/src/main/java/cn/nukkit/utils/ZlibProvider.java +++ b/src/main/java/cn/nukkit/utils/ZlibProvider.java @@ -3,13 +3,21 @@ import java.io.IOException; /** + * ZlibProvider * * @author ScraMTeam */ interface ZlibProvider { + byte[] deflate(byte[][] data, int level) throws IOException; byte[] deflate(byte[] data, int level) throws IOException; + byte[] deflateRaw(byte[][] data, int level) throws IOException; + + byte[] deflateRaw(byte[] data, int level) throws IOException; + byte[] inflate(byte[] data, int maxSize) throws IOException; + + byte[] inflateRaw(byte[] data, int maxSize) throws IOException; } diff --git a/src/main/java/cn/nukkit/utils/ZlibSingleThreadLowMem.java b/src/main/java/cn/nukkit/utils/ZlibSingleThreadLowMem.java deleted file mode 100644 index 030646d0c7d..00000000000 --- a/src/main/java/cn/nukkit/utils/ZlibSingleThreadLowMem.java +++ /dev/null @@ -1,77 +0,0 @@ -package cn.nukkit.utils; - -import cn.nukkit.nbt.stream.FastByteArrayOutputStream; - -import java.io.IOException; -import java.util.zip.DataFormatException; -import java.util.zip.Deflater; -import java.util.zip.Inflater; - -public class ZlibSingleThreadLowMem implements ZlibProvider { - private static final int BUFFER_SIZE = 8192; - private static final Deflater DEFLATER = new Deflater(Deflater.BEST_COMPRESSION); - private static final Inflater INFLATER = new Inflater(); - private static final byte[] BUFFER = new byte[BUFFER_SIZE]; - - @Override - public synchronized byte[] deflate(byte[][] datas, int level) throws IOException { - DEFLATER.reset(); - FastByteArrayOutputStream bos = ThreadCache.fbaos.get(); - bos.reset(); - for (byte[] data : datas) { - DEFLATER.setInput(data); - while (!DEFLATER.needsInput()) { - int i = DEFLATER.deflate(BUFFER); - bos.write(BUFFER, 0, i); - } - } - DEFLATER.finish(); - while (!DEFLATER.finished()) { - int i = DEFLATER.deflate(BUFFER); - bos.write(BUFFER, 0, i); - } - //Deflater::end is called the time when the process exits. - return bos.toByteArray(); - } - - @Override - public synchronized byte[] deflate(byte[] data, int level) throws IOException { - DEFLATER.reset(); - DEFLATER.setInput(data); - DEFLATER.finish(); - FastByteArrayOutputStream bos = ThreadCache.fbaos.get(); - bos.reset(); - try { - while (!DEFLATER.finished()) { - int i = DEFLATER.deflate(BUFFER); - bos.write(BUFFER, 0, i); - } - } finally { - //deflater.end(); - } - return bos.toByteArray(); - } - - @Override - public synchronized byte[] inflate(byte[] data, int maxSize) throws IOException { - INFLATER.reset(); - INFLATER.setInput(data); - INFLATER.finished(); - FastByteArrayOutputStream bos = ThreadCache.fbaos.get(); - bos.reset(); - try { - int length = 0; - while (!INFLATER.finished()) { - int i = INFLATER.inflate(BUFFER); - length += i; - if (maxSize > 0 && length >= maxSize) { - throw new IOException("Inflated data exceeds maximum size"); - } - bos.write(BUFFER, 0, i); - } - return bos.toByteArray(); - } catch (DataFormatException e) { - throw new IOException("Unable to inflate zlib stream", e); - } - } -} diff --git a/src/main/java/cn/nukkit/utils/ZlibThreadLocal.java b/src/main/java/cn/nukkit/utils/ZlibThreadLocal.java index 5be7557bfa2..33b5807f90a 100644 --- a/src/main/java/cn/nukkit/utils/ZlibThreadLocal.java +++ b/src/main/java/cn/nukkit/utils/ZlibThreadLocal.java @@ -1,15 +1,20 @@ package cn.nukkit.utils; +import cn.nukkit.Server; import cn.nukkit.nbt.stream.FastByteArrayOutputStream; + import java.io.IOException; import java.util.zip.DataFormatException; import java.util.zip.Deflater; import java.util.zip.Inflater; public final class ZlibThreadLocal implements ZlibProvider { + private static final ThreadLocal INFLATER = ThreadLocal.withInitial(Inflater::new); private static final ThreadLocal DEFLATER = ThreadLocal.withInitial(Deflater::new); - private static final ThreadLocal BUFFER = ThreadLocal.withInitial(() -> new byte[8192]); + private static final ThreadLocal INFLATER_RAW = ThreadLocal.withInitial(() -> new Inflater(true)); + private static final ThreadLocal DEFLATER_RAW = ThreadLocal.withInitial(() -> new Deflater(7, true)); + private static final ThreadLocal BUFFER = ThreadLocal.withInitial(() -> new byte[32768]); @Override public byte[] deflate(byte[][] datas, int level) throws IOException { @@ -54,6 +59,49 @@ public byte[] deflate(byte[] data, int level) throws IOException { return bos.toByteArray(); } + @Override + public byte[] deflateRaw(byte[][] datas, int level) throws IOException { + Deflater deflater = DEFLATER_RAW.get(); + deflater.reset(); + deflater.setLevel(level); + FastByteArrayOutputStream bos = ThreadCache.fbaos.get(); + bos.reset(); + byte[] buffer = BUFFER.get(); + + for (byte[] data : datas) { + deflater.setInput(data); + while (!deflater.needsInput()) { + int i = deflater.deflate(buffer); + bos.write(buffer, 0, i); + } + } + deflater.finish(); + while (!deflater.finished()) { + int i = deflater.deflate(buffer); + bos.write(buffer, 0, i); + } + //Deflater::end is called the time when the process exits. + return bos.toByteArray(); + } + + @Override + public byte[] deflateRaw(byte[] data, int level) throws IOException { + Deflater deflater = DEFLATER_RAW.get(); + deflater.reset(); + deflater.setLevel(data.length < Server.getInstance().networkCompressionThreshold ? 0 : level); + deflater.setInput(data); + deflater.finish(); + FastByteArrayOutputStream bos = ThreadCache.fbaos.get(); + bos.reset(); + byte[] buffer = BUFFER.get(); + while (!deflater.finished()) { + int i = deflater.deflate(buffer); + bos.write(buffer, 0, i); + } + //Deflater::end is called the time when the process exits. + return bos.toByteArray(); + } + @Override public byte[] inflate(byte[] data, int maxSize) throws IOException { Inflater inflater = INFLATER.get(); @@ -76,7 +124,36 @@ public byte[] inflate(byte[] data, int maxSize) throws IOException { } return bos.toByteArray(); } catch (DataFormatException e) { - throw new IOException("Unable to inflate zlib stream", e); + throw new IOException("Unable to inflate Zlib stream", e); + } + } + + @Override + public byte[] inflateRaw(byte[] data, int maxSize) throws IOException { + Inflater inflater = INFLATER_RAW.get(); + inflater.reset(); + inflater.setInput(data); + inflater.finished(); + FastByteArrayOutputStream bos = ThreadCache.fbaos.get(); + bos.reset(); + + byte[] buffer = BUFFER.get(); + try { + int length = 0; + while (!inflater.finished()) { + int i = inflater.inflate(buffer); + if (i == 0) { + throw new IOException("Could not decompress data"); + } + length += i; + if (maxSize > 0 && length >= maxSize) { + throw new IOException("Inflated data exceeds maximum size"); + } + bos.write(buffer, 0, i); + } + return bos.toByteArray(); + } catch (DataFormatException e) { + throw new IOException("Unable to inflate Zlib stream", e); } } } diff --git a/src/main/java/cn/nukkit/utils/bugreport/BugReportGenerator.java b/src/main/java/cn/nukkit/utils/bugreport/BugReportGenerator.java index 8753c6a6059..d1d459a8da2 100644 --- a/src/main/java/cn/nukkit/utils/bugreport/BugReportGenerator.java +++ b/src/main/java/cn/nukkit/utils/bugreport/BugReportGenerator.java @@ -18,17 +18,23 @@ import java.text.SimpleDateFormat; import java.util.Date; -/** - * Project nukkit - */ public class BugReportGenerator extends Thread { - private Throwable throwable; + private final Throwable throwable; BugReportGenerator(Throwable throwable) { this.throwable = throwable; } + //Code section from SOF + private static String getCount(long bytes) { + int unit = 1000; + if (bytes < unit) return bytes + " B"; + int exp = (int) (Math.log(bytes) / Math.log(unit)); + String pre = ("kMGTPE").charAt(exp - 1) + (""); + return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); + } + @Override public void run() { BaseLang baseLang = Server.getInstance().getLanguage(); @@ -58,12 +64,9 @@ private String generate() throws IOException { for (Path root : FileSystems.getDefault().getRootDirectories()) { try { FileStore store = Files.getFileStore(root); - model.append("Disk ").append(diskNum++).append(":(avail=").append(getCount(store.getUsableSpace(), true)) - .append(", total=").append(getCount(store.getTotalSpace(), true)) - .append(") "); + model.append("Disk ").append(diskNum++).append(":(avail=").append(getCount(store.getUsableSpace())).append(", total=").append(getCount(store.getTotalSpace())).append(") "); totalDiskSpace += store.getTotalSpace(); - } catch (IOException e) { - // + } catch (IOException ignore) { } } @@ -76,7 +79,6 @@ private String generate() throws IOException { pluginError = !throwable.getStackTrace()[0].getClassName().startsWith("cn.nukkit"); } - File mdReport = new File(reports, date + "_" + throwable.getClass().getSimpleName() + ".md"); mdReport.createNewFile(); String content = Utils.readFile(this.getClass().getClassLoader().getResourceAsStream("report_template.md")); @@ -86,8 +88,8 @@ private String generate() throws IOException { content = content.replace("${NUKKIT_VERSION}", Nukkit.VERSION); content = content.replace("${JAVA_VERSION}", System.getProperty("java.vm.name") + " (" + System.getProperty("java.runtime.version") + ")"); content = content.replace("${HOSTOS}", osMXBean.getName() + "-" + osMXBean.getArch() + " [" + osMXBean.getVersion() + "]"); - content = content.replace("${MEMORY}", getCount(osMXBean.getTotalPhysicalMemorySize(), true)); - content = content.replace("${STORAGE_SIZE}", getCount(totalDiskSpace, true)); + content = content.replace("${MEMORY}", getCount(osMXBean.getTotalPhysicalMemorySize())); + content = content.replace("${STORAGE_SIZE}", getCount(totalDiskSpace)); content = content.replace("${CPU_TYPE}", cpuType == null ? "UNKNOWN" : cpuType); content = content.replace("${AVAILABLE_CORE}", String.valueOf(osMXBean.getAvailableProcessors())); content = content.replace("${STACKTRACE}", stringWriter.toString()); @@ -98,14 +100,4 @@ private String generate() throws IOException { return mdReport.getAbsolutePath(); } - - //Code section from SOF - public static String getCount(long bytes, boolean si) { - int unit = si ? 1000 : 1024; - if (bytes < unit) return bytes + " B"; - int exp = (int) (Math.log(bytes) / Math.log(unit)); - String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i"); - return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); - } - } diff --git a/src/main/java/cn/nukkit/utils/bugreport/ExceptionHandler.java b/src/main/java/cn/nukkit/utils/bugreport/ExceptionHandler.java index 1493dd189a3..b3ba667f076 100644 --- a/src/main/java/cn/nukkit/utils/bugreport/ExceptionHandler.java +++ b/src/main/java/cn/nukkit/utils/bugreport/ExceptionHandler.java @@ -1,8 +1,5 @@ package cn.nukkit.utils.bugreport; -/** - * Project nukkit - */ public class ExceptionHandler implements Thread.UncaughtExceptionHandler { public static void registerExceptionHandler() { @@ -23,5 +20,4 @@ public void handle(Thread thread, Throwable throwable) { // Fail Safe } } - } \ No newline at end of file diff --git a/src/main/java/cn/nukkit/utils/functional/ToIntTriFunctionTwoInts.java b/src/main/java/cn/nukkit/utils/functional/ToIntTriFunctionTwoInts.java new file mode 100644 index 00000000000..9d973b55ed1 --- /dev/null +++ b/src/main/java/cn/nukkit/utils/functional/ToIntTriFunctionTwoInts.java @@ -0,0 +1,46 @@ +package cn.nukkit.utils.functional; + +import java.util.Objects; +import java.util.function.Function; +import java.util.function.IntUnaryOperator; + +/** + * Represents a function that accepts three arguments where the last two are int and produces an int result. + * This is the three-arity specialization of {@link Function}. + * + *

    This is a functional interface + * whose functional method is {@link #apply(Object, int, int)}. + * + * @param the type of the first argument to the function + * + * @see Function + */ +@FunctionalInterface +public interface ToIntTriFunctionTwoInts { + + /** + * Applies this function to the given arguments. + * + * @param f the first function argument + * @param s the second function argument + * @param t the third function argument + * @return the function result + */ + int apply(F f, int s, int t); + + /** + * Returns a composed function that first applies this function to + * its input, and then applies the {@code after} function to the result. + * If evaluation of either function throws an exception, it is relayed to + * the caller of the composed function. + * + * @param after the function to apply after this function is applied + * @return a composed function that first applies this function and then + * applies the {@code after} function + * @throws NullPointerException if after is null + */ + default ToIntTriFunctionTwoInts andThen(IntUnaryOperator after) { + Objects.requireNonNull(after); + return (F f, int s, int t) -> after.applyAsInt(apply(f, s, t)); + } +} \ No newline at end of file diff --git a/src/main/java/cn/nukkit/utils/functional/ToLongTriFunctionOneIntOneLong.java b/src/main/java/cn/nukkit/utils/functional/ToLongTriFunctionOneIntOneLong.java new file mode 100644 index 00000000000..b7cf07a6424 --- /dev/null +++ b/src/main/java/cn/nukkit/utils/functional/ToLongTriFunctionOneIntOneLong.java @@ -0,0 +1,46 @@ +package cn.nukkit.utils.functional; + +import java.util.Objects; +import java.util.function.Function; +import java.util.function.LongUnaryOperator; + +/** + * Represents a function that accepts three arguments mixing F, int and long and produces a long result. + * This is the three-arity specialization of {@link Function}. + * + *

    This is a functional interface + * whose functional method is {@link #apply(Object, int, long)}. + * + * @param the type of the first argument to the function + * + * @see Function + */ +@FunctionalInterface +public interface ToLongTriFunctionOneIntOneLong { + + /** + * Applies this function to the given arguments. + * + * @param f the first function argument + * @param s the second function argument + * @param t the third function argument + * @return the function result + */ + long apply(F f, int s, long t); + + /** + * Returns a composed function that first applies this function to + * its input, and then applies the {@code after} function to the result. + * If evaluation of either function throws an exception, it is relayed to + * the caller of the composed function. + * + * @param after the function to apply after this function is applied + * @return a composed function that first applies this function and then + * applies the {@code after} function + * @throws NullPointerException if after is null + */ + default ToLongTriFunctionOneIntOneLong andThen(LongUnaryOperator after) { + Objects.requireNonNull(after); + return (F f, int s, long t) -> after.applyAsLong(apply(f, s, t)); + } +} diff --git a/src/main/java/cn/nukkit/utils/material/BlockType.java b/src/main/java/cn/nukkit/utils/material/BlockType.java new file mode 100644 index 00000000000..239061fe383 --- /dev/null +++ b/src/main/java/cn/nukkit/utils/material/BlockType.java @@ -0,0 +1,4 @@ +package cn.nukkit.utils.material; + +public interface BlockType extends MaterialType { +} diff --git a/src/main/java/cn/nukkit/utils/material/ItemType.java b/src/main/java/cn/nukkit/utils/material/ItemType.java new file mode 100644 index 00000000000..1f64047484a --- /dev/null +++ b/src/main/java/cn/nukkit/utils/material/ItemType.java @@ -0,0 +1,4 @@ +package cn.nukkit.utils.material; + +public interface ItemType extends MaterialType { +} diff --git a/src/main/java/cn/nukkit/utils/material/MaterialType.java b/src/main/java/cn/nukkit/utils/material/MaterialType.java new file mode 100644 index 00000000000..e5b4a460d5c --- /dev/null +++ b/src/main/java/cn/nukkit/utils/material/MaterialType.java @@ -0,0 +1,7 @@ +package cn.nukkit.utils.material; + +public interface MaterialType { + int getLegacyId(); + + String getIdentifier(); +} diff --git a/src/main/java/cn/nukkit/utils/material/TypesGeneratorHelper.java b/src/main/java/cn/nukkit/utils/material/TypesGeneratorHelper.java new file mode 100644 index 00000000000..4e6f1c81273 --- /dev/null +++ b/src/main/java/cn/nukkit/utils/material/TypesGeneratorHelper.java @@ -0,0 +1,123 @@ +package cn.nukkit.utils.material; + +import cn.nukkit.block.BlockID; +import cn.nukkit.item.ItemID; +import cn.nukkit.item.RuntimeItems; +import cn.nukkit.utils.material.tags.MaterialTags; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import lombok.extern.log4j.Log4j2; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.*; + +@Log4j2 +public class TypesGeneratorHelper { + + private static final String ITEMS_FILE = "item_types.txt"; + private static final String BLOCKS_FILE = "block_types.txt"; + private static final String TAGS_FILE = "material_tags.txt"; + + public static void main(String[] args) throws Exception { + RuntimeItems.init(); + + generateItems(); + generateBlocks(); + generateTags(); + } + + private static void generateItems() throws Exception { + Map> types = new TreeMap<>(); + + for (Field field : ItemID.class.getDeclaredFields()) { + field.setAccessible(true); + + String name = field.getName(); + + int legacyId = field.getInt(null); + + types.computeIfAbsent(field.getInt(null), id -> new ArrayList<>()) + .add("public static final ItemType " + name + " = register(\"" + getIdentifierFromId(legacyId) + "\", ItemID." + name + ");"); + } + + log.info("Saving {} item types to {}", types.size(), ITEMS_FILE); + saveFile(toString(types), ITEMS_FILE); + } + + private static void generateBlocks() throws Exception { + Map> types = new TreeMap<>(); + + for (Field field : BlockID.class.getDeclaredFields()) { + field.setAccessible(true); + + String name = field.getName(); + int legacyId = field.getInt(null); + + + if (legacyId > 255) { + legacyId = 255 - legacyId; + } + + types.computeIfAbsent(field.getInt(null), id -> new ArrayList<>()) + .add("public static final BlockType " + name + " = register(\"" + getIdentifierFromId(legacyId) + "\", BlockID." + name + ");"); + } + + log.info("Saving {} block types to {}", types.size(), BLOCKS_FILE); + saveFile(toString(types), BLOCKS_FILE); + } + + private static void generateTags() throws Exception { + StringJoiner joiner = new StringJoiner("\n"); + + try (InputStream stream = MaterialTags.class.getClassLoader().getResourceAsStream("item_tags.json")) { + if (stream == null) { + throw new IllegalStateException("Resource file item_tags.json is missing"); + } + try (InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) { + JsonObject json = JsonParser.parseReader(reader).getAsJsonObject(); + for (String tag : json.keySet()) { + String name = tag.split(":")[1].toUpperCase(); + joiner.add("public static final MaterialTag " + name + " = register(\"" + tag + "\", new LazilyInitializedMaterialTag(\"" + tag + "\"));"); + } + } + } + + log.info("Saving tags to {}", TAGS_FILE); + saveFile(joiner.toString(), TAGS_FILE); + } + + private static String toString(Map> types) { + StringJoiner joiner = new StringJoiner("\n"); + for (List value : types.values()) { + for (String type : value) { + joiner.add(type); + } + } + return joiner.toString(); + } + + private static void saveFile(String buffer, String path) { + try { + Files.write(Paths.get(path), buffer.getBytes(StandardCharsets.UTF_8), + StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); + } catch (IOException e) { + log.error("Unable to save file " + path, e); + } + } + + private static String getIdentifierFromId(int legacyId) { + // yes, we still use legacy identifiers internally + String identifier = RuntimeItems.getLegacyStringFromLegacyId(legacyId); + if (legacyId == 0) { + identifier = "minecraft:air"; + } + return identifier; + } +} diff --git a/src/main/java/cn/nukkit/utils/material/tags/LazilyInitializedMaterialTag.java b/src/main/java/cn/nukkit/utils/material/tags/LazilyInitializedMaterialTag.java new file mode 100644 index 00000000000..ceef48f52c4 --- /dev/null +++ b/src/main/java/cn/nukkit/utils/material/tags/LazilyInitializedMaterialTag.java @@ -0,0 +1,48 @@ +package cn.nukkit.utils.material.tags; + +import cn.nukkit.block.BlockTypes; +import cn.nukkit.item.ItemTypes; +import cn.nukkit.utils.material.MaterialType; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; + +import java.util.Collections; +import java.util.Set; + +public class LazilyInitializedMaterialTag implements MaterialTag { + + private final String tag; + private Set materials; + + public LazilyInitializedMaterialTag(String tag) { + this.tag = tag; + } + + private void init() { + Set definitions = MaterialTags.getVanillaDefinitions(tag); + if (definitions == null) { + throw new IllegalStateException("Unknown vanilla tag " + this.tag); + } + + Set materials = new ObjectOpenHashSet<>(); + for (String definition : definitions) { + MaterialType material = BlockTypes.get(definition); + if (material == null) { + material = ItemTypes.get(definition); + } + + if (material != null) { + materials.add(material); + } + } + + this.materials = Collections.unmodifiableSet(materials); + } + + @Override + public Set getMaterials() { + if (this.materials == null) { + this.init(); + } + return this.materials; + } +} diff --git a/src/main/java/cn/nukkit/utils/material/tags/MaterialTag.java b/src/main/java/cn/nukkit/utils/material/tags/MaterialTag.java new file mode 100644 index 00000000000..f7699797de6 --- /dev/null +++ b/src/main/java/cn/nukkit/utils/material/tags/MaterialTag.java @@ -0,0 +1,18 @@ +package cn.nukkit.utils.material.tags; + +import cn.nukkit.utils.material.MaterialType; + +import java.util.Set; + +public interface MaterialTag { + + default boolean has(MaterialType type) { + return this.getMaterials().contains(type); + } + + Set getMaterials(); + + static MaterialTag of(MaterialType... materials) { + return new SimpleMaterialTag(materials); + } +} diff --git a/src/main/java/cn/nukkit/utils/material/tags/MaterialTags.java b/src/main/java/cn/nukkit/utils/material/tags/MaterialTags.java new file mode 100644 index 00000000000..368f345dcc4 --- /dev/null +++ b/src/main/java/cn/nukkit/utils/material/tags/MaterialTags.java @@ -0,0 +1,111 @@ +package cn.nukkit.utils.material.tags; + +import cn.nukkit.item.RuntimeItems; +import cn.nukkit.utils.Utils; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; +import lombok.extern.log4j.Log4j2; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +@Log4j2 +public class MaterialTags { + + private static final Map tags = new HashMap<>(); + private static final Map> vanillaTagDefinitions = new HashMap<>(); + + static { + JsonObject json = Utils.loadJsonResource("item_tags.json").getAsJsonObject(); + for (Map.Entry entry : json.entrySet()) { + Set materials = vanillaTagDefinitions.computeIfAbsent(entry.getKey(), key -> new ObjectOpenHashSet<>()); + for (JsonElement element : entry.getValue().getAsJsonArray()) { + String identifier = element.getAsString(); + // We use here legacy name as all items in Nukkit still use those, + // I guess it is also better in terms of updating stuff + String legacyName = RuntimeItems.getLegacyStringFromNew(identifier); + if (legacyName == null) { + log.warn("No legacy name for " + identifier); + } else { + materials.add(legacyName); + } + } + } + } + + public static final MaterialTag ARROW = register("minecraft:arrow", new LazilyInitializedMaterialTag("minecraft:arrow")); + public static final MaterialTag BANNER = register("minecraft:banner", new LazilyInitializedMaterialTag("minecraft:banner")); + public static final MaterialTag BOAT = register("minecraft:boat", new LazilyInitializedMaterialTag("minecraft:boat")); + public static final MaterialTag BOATS = register("minecraft:boats", new LazilyInitializedMaterialTag("minecraft:boats")); + public static final MaterialTag BOOKSHELF_BOOKS = register("minecraft:bookshelf_books", new LazilyInitializedMaterialTag("minecraft:bookshelf_books")); + public static final MaterialTag CHAINMAIL_TIER = register("minecraft:chainmail_tier", new LazilyInitializedMaterialTag("minecraft:chainmail_tier")); + public static final MaterialTag COALS = register("minecraft:coals", new LazilyInitializedMaterialTag("minecraft:coals")); + public static final MaterialTag CRIMSON_STEMS = register("minecraft:crimson_stems", new LazilyInitializedMaterialTag("minecraft:crimson_stems")); + public static final MaterialTag DECORATED_POT_SHERDS = register("minecraft:decorated_pot_sherds", new LazilyInitializedMaterialTag("minecraft:decorated_pot_sherds")); + public static final MaterialTag DIAMOND_TIER = register("minecraft:diamond_tier", new LazilyInitializedMaterialTag("minecraft:diamond_tier")); + public static final MaterialTag DIGGER = register("minecraft:digger", new LazilyInitializedMaterialTag("minecraft:digger")); + public static final MaterialTag DOOR = register("minecraft:door", new LazilyInitializedMaterialTag("minecraft:door")); + public static final MaterialTag GOLDEN_TIER = register("minecraft:golden_tier", new LazilyInitializedMaterialTag("minecraft:golden_tier")); + public static final MaterialTag HANGING_ACTOR = register("minecraft:hanging_actor", new LazilyInitializedMaterialTag("minecraft:hanging_actor")); + public static final MaterialTag HANGING_SIGN = register("minecraft:hanging_sign", new LazilyInitializedMaterialTag("minecraft:hanging_sign")); + public static final MaterialTag HORSE_ARMOR = register("minecraft:horse_armor", new LazilyInitializedMaterialTag("minecraft:horse_armor")); + public static final MaterialTag IRON_TIER = register("minecraft:iron_tier", new LazilyInitializedMaterialTag("minecraft:iron_tier")); + public static final MaterialTag IS_ARMOR = register("minecraft:is_armor", new LazilyInitializedMaterialTag("minecraft:is_armor")); + public static final MaterialTag IS_AXE = register("minecraft:is_axe", new LazilyInitializedMaterialTag("minecraft:is_axe")); + public static final MaterialTag IS_COOKED = register("minecraft:is_cooked", new LazilyInitializedMaterialTag("minecraft:is_cooked")); + public static final MaterialTag IS_FISH = register("minecraft:is_fish", new LazilyInitializedMaterialTag("minecraft:is_fish")); + public static final MaterialTag IS_FOOD = register("minecraft:is_food", new LazilyInitializedMaterialTag("minecraft:is_food")); + public static final MaterialTag IS_HOE = register("minecraft:is_hoe", new LazilyInitializedMaterialTag("minecraft:is_hoe")); + public static final MaterialTag IS_MEAT = register("minecraft:is_meat", new LazilyInitializedMaterialTag("minecraft:is_meat")); + public static final MaterialTag IS_MINECART = register("minecraft:is_minecart", new LazilyInitializedMaterialTag("minecraft:is_minecart")); + public static final MaterialTag IS_PICKAXE = register("minecraft:is_pickaxe", new LazilyInitializedMaterialTag("minecraft:is_pickaxe")); + public static final MaterialTag IS_SHOVEL = register("minecraft:is_shovel", new LazilyInitializedMaterialTag("minecraft:is_shovel")); + public static final MaterialTag IS_SWORD = register("minecraft:is_sword", new LazilyInitializedMaterialTag("minecraft:is_sword")); + public static final MaterialTag IS_TOOL = register("minecraft:is_tool", new LazilyInitializedMaterialTag("minecraft:is_tool")); + public static final MaterialTag IS_TRIDENT = register("minecraft:is_trident", new LazilyInitializedMaterialTag("minecraft:is_trident")); + public static final MaterialTag LEATHER_TIER = register("minecraft:leather_tier", new LazilyInitializedMaterialTag("minecraft:leather_tier")); + public static final MaterialTag LECTERN_BOOKS = register("minecraft:lectern_books", new LazilyInitializedMaterialTag("minecraft:lectern_books")); + public static final MaterialTag LOGS = register("minecraft:logs", new LazilyInitializedMaterialTag("minecraft:logs")); + public static final MaterialTag LOGS_THAT_BURN = register("minecraft:logs_that_burn", new LazilyInitializedMaterialTag("minecraft:logs_that_burn")); + public static final MaterialTag MANGROVE_LOGS = register("minecraft:mangrove_logs", new LazilyInitializedMaterialTag("minecraft:mangrove_logs")); + public static final MaterialTag MUSIC_DISC = register("minecraft:music_disc", new LazilyInitializedMaterialTag("minecraft:music_disc")); + public static final MaterialTag NETHERITE_TIER = register("minecraft:netherite_tier", new LazilyInitializedMaterialTag("minecraft:netherite_tier")); + public static final MaterialTag PLANKS = register("minecraft:planks", new LazilyInitializedMaterialTag("minecraft:planks")); + public static final MaterialTag SAND = register("minecraft:sand", new LazilyInitializedMaterialTag("minecraft:sand")); + public static final MaterialTag SIGN = register("minecraft:sign", new LazilyInitializedMaterialTag("minecraft:sign")); + public static final MaterialTag SOUL_FIRE_BASE_BLOCKS = register("minecraft:soul_fire_base_blocks", new LazilyInitializedMaterialTag("minecraft:soul_fire_base_blocks")); + public static final MaterialTag SPAWN_EGG = register("minecraft:spawn_egg", new LazilyInitializedMaterialTag("minecraft:spawn_egg")); + public static final MaterialTag STONE_BRICKS = register("minecraft:stone_bricks", new LazilyInitializedMaterialTag("minecraft:stone_bricks")); + public static final MaterialTag STONE_CRAFTING_MATERIALS = register("minecraft:stone_crafting_materials", new LazilyInitializedMaterialTag("minecraft:stone_crafting_materials")); + public static final MaterialTag STONE_TIER = register("minecraft:stone_tier", new LazilyInitializedMaterialTag("minecraft:stone_tier")); + public static final MaterialTag STONE_TOOL_MATERIALS = register("minecraft:stone_tool_materials", new LazilyInitializedMaterialTag("minecraft:stone_tool_materials")); + public static final MaterialTag TRANSFORM_MATERIALS = register("minecraft:transform_materials", new LazilyInitializedMaterialTag("minecraft:transform_materials")); + public static final MaterialTag TRANSFORM_TEMPLATES = register("minecraft:transform_templates", new LazilyInitializedMaterialTag("minecraft:transform_templates")); + public static final MaterialTag TRANSFORMABLE_ITEMS = register("minecraft:transformable_items", new LazilyInitializedMaterialTag("minecraft:transformable_items")); + public static final MaterialTag TRIM_MATERIALS = register("minecraft:trim_materials", new LazilyInitializedMaterialTag("minecraft:trim_materials")); + public static final MaterialTag TRIM_TEMPLATES = register("minecraft:trim_templates", new LazilyInitializedMaterialTag("minecraft:trim_templates")); + public static final MaterialTag TRIMMABLE_ARMORS = register("minecraft:trimmable_armors", new LazilyInitializedMaterialTag("minecraft:trimmable_armors")); + public static final MaterialTag VIBRATION_DAMPER = register("minecraft:vibration_damper", new LazilyInitializedMaterialTag("minecraft:vibration_damper")); + public static final MaterialTag WARPED_STEMS = register("minecraft:warped_stems", new LazilyInitializedMaterialTag("minecraft:warped_stems")); + public static final MaterialTag WOODEN_SLABS = register("minecraft:wooden_slabs", new LazilyInitializedMaterialTag("minecraft:wooden_slabs")); + public static final MaterialTag WOODEN_TIER = register("minecraft:wooden_tier", new LazilyInitializedMaterialTag("minecraft:wooden_tier")); + public static final MaterialTag WOOL = register("minecraft:wool", new LazilyInitializedMaterialTag("minecraft:wool")); + + public static MaterialTag register(String tagName, MaterialTag tag) { + if (tags.containsKey(tagName)) { + throw new IllegalArgumentException("Tag " + tagName + " is already registered"); + } + tags.put(tagName, tag); + return tag; + } + + public static MaterialTag get(String tag) { + return tags.get(tag); + } + + protected static Set getVanillaDefinitions(String tag) { + return vanillaTagDefinitions.get(tag); + } +} diff --git a/src/main/java/cn/nukkit/utils/material/tags/SimpleMaterialTag.java b/src/main/java/cn/nukkit/utils/material/tags/SimpleMaterialTag.java new file mode 100644 index 00000000000..192e5229d57 --- /dev/null +++ b/src/main/java/cn/nukkit/utils/material/tags/SimpleMaterialTag.java @@ -0,0 +1,27 @@ +package cn.nukkit.utils.material.tags; + +import cn.nukkit.utils.material.MaterialType; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Set; + +public class SimpleMaterialTag implements MaterialTag { + + private final Set materials; + + public SimpleMaterialTag(MaterialType... materials) { + this(Arrays.asList(materials)); + } + + public SimpleMaterialTag(Collection materials) { + this.materials = Collections.unmodifiableSet(new ObjectOpenHashSet<>(materials)); + } + + @Override + public Set getMaterials() { + return this.materials; + } +} diff --git a/src/main/java/co/aikar/timings/FullServerTickTiming.java b/src/main/java/co/aikar/timings/FullServerTickTiming.java deleted file mode 100644 index 66526bf8ec6..00000000000 --- a/src/main/java/co/aikar/timings/FullServerTickTiming.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import static co.aikar.timings.TimingIdentifier.DEFAULT_GROUP; -import static co.aikar.timings.TimingsManager.*; - -public class FullServerTickTiming extends Timing { - private static final TimingIdentifier IDENTIFIER = new TimingIdentifier(DEFAULT_GROUP.name, "Full Server Tick", null); - final TimingData minuteData; - double avgFreeMemory = -1D; - double avgUsedMemory = -1D; - - FullServerTickTiming() { - super(IDENTIFIER); - this.minuteData = new TimingData(this.id); - - TIMING_MAP.put(IDENTIFIER, this); - } - - @Override - public Timing startTiming() { - if (TimingsManager.needsFullReset) { - TimingsManager.resetTimings(); - } else if (TimingsManager.needsRecheckEnabled) { - TimingsManager.recheckEnabled(); - } - super.startTiming(); - return this; - } - - @Override - public void stopTiming() { - super.stopTiming(); - if (!this.enabled) { - return; - } - - if (TimingsHistory.timedTicks % 20 == 0) { - final Runtime runtime = Runtime.getRuntime(); - double usedMemory = runtime.totalMemory() - runtime.freeMemory(); - double freeMemory = runtime.maxMemory() - usedMemory; - - if (this.avgFreeMemory == -1) { - this.avgFreeMemory = freeMemory; - } else { - this.avgFreeMemory = (this.avgFreeMemory * (59 / 60D)) + (freeMemory * (1 / 60D)); - } - - if (this.avgUsedMemory == -1) { - this.avgUsedMemory = usedMemory; - } else { - this.avgUsedMemory = (this.avgUsedMemory * (59 / 60D)) + (usedMemory * (1 / 60D)); - } - } - - long start = System.nanoTime(); - TimingsManager.tick(); - long diff = System.nanoTime() - start; - - CURRENT = Timings.timingsTickTimer; - Timings.timingsTickTimer.addDiff(diff); - //addDiff for timingsTickTimer incremented this, bring it back down to 1 per tick. - this.record.curTickCount--; - this.minuteData.curTickTotal = this.record.curTickTotal; - this.minuteData.curTickCount = 1; - boolean violated = isViolated(); - this.minuteData.tick(violated); - Timings.timingsTickTimer.tick(violated); - tick(violated); - - if (TimingsHistory.timedTicks % 1200 == 0) { - MINUTE_REPORTS.add(new TimingsHistory.MinuteReport()); - TimingsHistory.resetTicks(false); - this.minuteData.reset(); - } - - if (TimingsHistory.timedTicks % Timings.getHistoryInterval() == 0) { - TimingsManager.HISTORY.add(new TimingsHistory()); - TimingsManager.resetTimings(); - } - } - - boolean isViolated() { - return this.record.curTickTotal > 50000000; - } -} diff --git a/src/main/java/co/aikar/timings/Timing.java b/src/main/java/co/aikar/timings/Timing.java deleted file mode 100644 index b9430d2d4ae..00000000000 --- a/src/main/java/co/aikar/timings/Timing.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import java.util.HashMap; -import java.util.Map; - -public class Timing implements AutoCloseable { - private static int idPool = 1; - final int id = idPool++; - - final String name; - private final boolean verbose; - - final Map children = new HashMap<>(); - private Timing parent; - - private final Timing groupTiming; - final TimingData record; - - private long start = 0; - private int timingDepth = 0; - private boolean added; - boolean timed; - boolean enabled; - - Timing(TimingIdentifier id) { - if (id.name.startsWith("##")) { - this.verbose = true; - this.name = id.name.substring(3); - } else { - this.name = id.name; - this.verbose = false; - } - - this.record = new TimingData(this.id); - this.groupTiming = id.groupTiming; - - TimingIdentifier.getGroup(id.group).timings.add(this); - this.checkEnabled(); - } - - final void checkEnabled() { - this.enabled = Timings.isTimingsEnabled() && (!this.verbose || Timings.isVerboseEnabled()); - } - - void tick(boolean violated) { - if (this.timingDepth != 0 || this.record.curTickCount == 0) { - this.timingDepth = 0; - this.start = 0; - return; - } - - this.record.tick(violated); - for (TimingData data : this.children.values()) { - data.tick(violated); - } - } - - public Timing startTiming() { - if (!this.enabled) { - return this; - } - - if (++this.timingDepth == 1) { - this.start = System.nanoTime(); - this.parent = TimingsManager.CURRENT; - TimingsManager.CURRENT = this; - } - - return this; - } - - public void stopTiming() { - if (!this.enabled) { - return; - } - - if (--this.timingDepth == 0 && this.start != 0) { - this.addDiff(System.nanoTime() - this.start); - this.start = 0; - } - } - - public void abort() { - if (this.enabled && this.timingDepth > 0) { - this.start = 0; - } - } - - void addDiff(long diff) { - if (TimingsManager.CURRENT == this) { - TimingsManager.CURRENT = this.parent; - if (this.parent != null) { - if (!this.parent.children.containsKey(this.id)) - this.parent.children.put(this.id, new TimingData(this.id)); - this.parent.children.get(this.id).add(diff); - } - } - - this.record.add(diff); - if (!this.added) { - this.added = true; - this.timed = true; - TimingsManager.TIMINGS.add(this); - } - - if (this.groupTiming != null) { - this.groupTiming.addDiff(diff); - - if (!this.groupTiming.children.containsKey(this.id)) - this.groupTiming.children.put(this.id, new TimingData(this.id)); - this.groupTiming.children.get(this.id).add(diff); - } - } - - void reset(boolean full) { - this.record.reset(); - if (full) { - this.timed = false; - } - this.start = 0; - this.timingDepth = 0; - this.added = false; - this.children.clear(); - this.checkEnabled(); - } - - @Override - public boolean equals(Object o) { - return (o instanceof Timing && this == o); - } - - @Override - public int hashCode() { - return this.id; - } - - //For try-with-resources - @Override - public void close() { - this.stopTiming(); - } - - boolean isSpecial() { - return this == Timings.fullServerTickTimer || this == Timings.timingsTickTimer; - } -} diff --git a/src/main/java/co/aikar/timings/TimingData.java b/src/main/java/co/aikar/timings/TimingData.java deleted file mode 100644 index 8757d6990cf..00000000000 --- a/src/main/java/co/aikar/timings/TimingData.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import com.google.gson.JsonArray; - -import cn.nukkit.timings.JsonUtil; - -class TimingData { - private int id; - int count = 0; - private int lagCount = 0; - long totalTime = 0; - private long lagTotalTime = 0; - - int curTickCount = 0; - int curTickTotal = 0; - - TimingData(int id) { - this.id = id; - } - - TimingData(TimingData data) { - this.id = data.id; - this.count = data.count; - this.lagCount = data.lagCount; - this.totalTime = data.totalTime; - this.lagTotalTime = data.lagTotalTime; - } - - void add(long diff) { - ++this.curTickCount; - this.curTickTotal += diff; - } - - void tick(boolean violated) { - this.count += this.curTickCount; - this.totalTime += this.curTickTotal; - - if (violated) { - this.lagCount += this.curTickCount; - this.lagTotalTime += this.curTickTotal; - } - - this.curTickCount = 0; - this.curTickTotal = 0; - } - - void reset() { - this.count = 0; - this.lagCount = 0; - this.totalTime = 0; - this.lagTotalTime = 0; - this.curTickCount = 0; - this.curTickTotal = 0; - } - - protected TimingData clone() { - return new TimingData(this); - } - - JsonArray export() { - JsonArray json = JsonUtil.toArray(this.id, this.count, this.totalTime); - if (this.lagCount > 0) { - json.add(this.lagCount); - json.add(this.lagTotalTime); - } - return json; - } -} diff --git a/src/main/java/co/aikar/timings/TimingIdentifier.java b/src/main/java/co/aikar/timings/TimingIdentifier.java deleted file mode 100644 index 845f071a03d..00000000000 --- a/src/main/java/co/aikar/timings/TimingIdentifier.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import java.util.ArrayDeque; -import java.util.IdentityHashMap; -import java.util.Map; - -class TimingIdentifier { - static final Map GROUP_MAP = new IdentityHashMap<>(64); - static final TimingGroup DEFAULT_GROUP = getGroup("Nukkit"); - - final String group; - final String name; - final Timing groupTiming; - private final int hashCode; - - TimingIdentifier(String group, String name, Timing groupTiming) { - this.group = group != null ? group.intern() : DEFAULT_GROUP.name; - this.name = name.intern(); - this.groupTiming = groupTiming; - this.hashCode = (31 * this.group.hashCode()) + this.name.hashCode(); - } - - static TimingGroup getGroup(String name) { - if (name == null) { - return DEFAULT_GROUP; - } - - return GROUP_MAP.computeIfAbsent(name, k -> new TimingGroup(name)); - } - - @Override - @SuppressWarnings("all") - public boolean equals(Object o) { - if (o == null || !(o instanceof TimingIdentifier)) { - return false; - } - - TimingIdentifier that = (TimingIdentifier) o; - //Using intern() method on strings makes possible faster string comparison with == - return this.group == that.group && this.name == that.name; - } - - @Override - public int hashCode() { - return this.hashCode; - } - - static class TimingGroup { - private static int idPool = 1; - final int id = idPool++; - - final String name; - ArrayDeque timings = new ArrayDeque<>(64); - - TimingGroup(String name) { - this.name = name.intern(); - } - } -} diff --git a/src/main/java/co/aikar/timings/Timings.java b/src/main/java/co/aikar/timings/Timings.java deleted file mode 100644 index 0dc60448421..00000000000 --- a/src/main/java/co/aikar/timings/Timings.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import cn.nukkit.Server; -import cn.nukkit.blockentity.BlockEntity; -import cn.nukkit.command.Command; -import cn.nukkit.entity.Entity; -import cn.nukkit.event.Event; -import cn.nukkit.event.Listener; -import cn.nukkit.network.protocol.DataPacket; -import cn.nukkit.plugin.EventExecutor; -import cn.nukkit.plugin.MethodEventExecutor; -import cn.nukkit.plugin.Plugin; -import cn.nukkit.scheduler.PluginTask; -import cn.nukkit.scheduler.TaskHandler; - -import java.util.HashSet; -import java.util.Queue; -import java.util.Set; - -import static co.aikar.timings.TimingIdentifier.DEFAULT_GROUP; - -public final class Timings { - private static boolean timingsEnabled = false; - private static boolean verboseEnabled = false; - private static boolean privacy = false; - private static Set ignoredConfigSections = new HashSet<>(); - - private static final int MAX_HISTORY_FRAMES = 12; - private static int historyInterval = -1; - private static int historyLength = -1; - - public static final FullServerTickTiming fullServerTickTimer; - public static final Timing timingsTickTimer; - public static final Timing pluginEventTimer; - - public static final Timing connectionTimer; - public static final Timing schedulerTimer; - public static final Timing schedulerAsyncTimer; - public static final Timing schedulerSyncTimer; - public static final Timing commandTimer; - public static final Timing serverCommandTimer; - public static final Timing levelSaveTimer; - - public static final Timing playerNetworkSendTimer; - public static final Timing playerNetworkReceiveTimer; - public static final Timing playerChunkOrderTimer; - public static final Timing playerChunkSendTimer; - public static final Timing playerCommandTimer; - - public static final Timing tickEntityTimer; - public static final Timing tickBlockEntityTimer; - public static final Timing entityMoveTimer; - public static final Timing entityBaseTickTimer; - public static final Timing livingEntityBaseTickTimer; - - public static final Timing generationTimer; - public static final Timing populationTimer; - public static final Timing generationCallbackTimer; - - public static final Timing permissibleCalculationTimer; - public static final Timing permissionDefaultTimer; - - static { - setTimingsEnabled(Server.getInstance().getConfig("timings.enabled", false)); - setVerboseEnabled(Server.getInstance().getConfig("timings.verbose", false)); - setHistoryInterval(Server.getInstance().getConfig("timings.history-interval", 6000)); - setHistoryLength(Server.getInstance().getConfig("timings.history-length", 72000)); - - privacy = Server.getInstance().getConfig("timings.privacy", false); - ignoredConfigSections.addAll(Server.getInstance().getConfig().getStringList("timings.ignore")); - - Server.getInstance().getLogger().debug("Timings: \n" + - "Enabled - " + isTimingsEnabled() + "\n" + - "Verbose - " + isVerboseEnabled() + "\n" + - "History Interval - " + getHistoryInterval() + "\n" + - "History Length - " + getHistoryLength()); - - fullServerTickTimer = new FullServerTickTiming(); - timingsTickTimer = TimingsManager.getTiming(DEFAULT_GROUP.name, "Timings Tick", fullServerTickTimer); - pluginEventTimer = TimingsManager.getTiming("Plugin Events"); - - connectionTimer = TimingsManager.getTiming("Connection Handler"); - schedulerTimer = TimingsManager.getTiming("Scheduler"); - schedulerAsyncTimer = TimingsManager.getTiming("## Scheduler - Async Tasks"); - schedulerSyncTimer = TimingsManager.getTiming("## Scheduler - Sync Tasks"); - commandTimer = TimingsManager.getTiming("Commands"); - serverCommandTimer = TimingsManager.getTiming("Server Command"); - levelSaveTimer = TimingsManager.getTiming("Level Save"); - - playerNetworkSendTimer = TimingsManager.getTiming("Player Network Send"); - playerNetworkReceiveTimer = TimingsManager.getTiming("Player Network Receive"); - playerChunkOrderTimer = TimingsManager.getTiming("Player Order Chunks"); - playerChunkSendTimer = TimingsManager.getTiming("Player Send Chunks"); - playerCommandTimer = TimingsManager.getTiming("Player Command"); - - tickEntityTimer = TimingsManager.getTiming("## Entity Tick"); - tickBlockEntityTimer = TimingsManager.getTiming("## BlockEntity Tick"); - entityMoveTimer = TimingsManager.getTiming("## Entity Move"); - entityBaseTickTimer = TimingsManager.getTiming("## Entity Base Tick"); - livingEntityBaseTickTimer = TimingsManager.getTiming("## LivingEntity Base Tick"); - - generationTimer = TimingsManager.getTiming("Level Generation"); - populationTimer = TimingsManager.getTiming("Level Population"); - generationCallbackTimer = TimingsManager.getTiming("Level Generation Callback"); - - permissibleCalculationTimer = TimingsManager.getTiming("Permissible Calculation"); - permissionDefaultTimer = TimingsManager.getTiming("Default Permission Calculation"); - } - - public static boolean isTimingsEnabled() { - return timingsEnabled; - } - - public static void setTimingsEnabled(boolean enabled) { - timingsEnabled = enabled; - TimingsManager.reset(); - } - - public static boolean isVerboseEnabled() { - return verboseEnabled; - } - - public static void setVerboseEnabled(boolean enabled) { - verboseEnabled = enabled; - TimingsManager.needsRecheckEnabled = true; - } - - public static boolean isPrivacy() { - return privacy; - } - - public static Set getIgnoredConfigSections() { - return ignoredConfigSections; - } - - public static int getHistoryInterval() { - return historyInterval; - } - - public static void setHistoryInterval(int interval) { - historyInterval = Math.max(20 * 60, interval); - //Recheck the history length with the new Interval - if (historyLength != -1) { - setHistoryLength(historyLength); - } - } - - public static int getHistoryLength() { - return historyLength; - } - - public static void setHistoryLength(int length) { - //Cap at 12 History Frames, 1 hour at 5 minute frames. - int maxLength = historyInterval * MAX_HISTORY_FRAMES; - //For special cases of servers with special permission to bypass the max. - //This max helps keep data file sizes reasonable for processing on Aikar's Timing parser side. - //Setting this will not help you bypass the max unless Aikar has added an exception on the API side. - if (Server.getInstance().getConfig().getBoolean("timings.bypass-max", false)) { - maxLength = Integer.MAX_VALUE; - } - - historyLength = Math.max(Math.min(maxLength, length), historyInterval); - - Queue oldQueue = TimingsManager.HISTORY; - int frames = (getHistoryLength() / getHistoryInterval()); - if (length > maxLength) { - Server.getInstance().getLogger().warning( - "Timings Length too high. Requested " + length + ", max is " + maxLength - + ". To get longer history, you must increase your interval. Set Interval to " - + Math.ceil((float) length / MAX_HISTORY_FRAMES) - + " to achieve this length."); - } - - TimingsManager.HISTORY = new TimingsManager.BoundedQueue<>(frames); - TimingsManager.HISTORY.addAll(oldQueue); - } - - public static void reset() { - TimingsManager.reset(); - } - - - public static Timing getCommandTiming(Command command) { - return TimingsManager.getTiming(DEFAULT_GROUP.name, "Command: " + command.getLabel(), commandTimer); - } - - public static Timing getTaskTiming(TaskHandler handler, long period) { - String repeating = " "; - if (period > 0) { - repeating += "(interval:" + period + ")"; - } else { - repeating += "(Single)"; - } - - if (handler.getTask() instanceof PluginTask) { - String owner = ((PluginTask) handler.getTask()).getOwner().getName(); - return TimingsManager.getTiming(owner, "PluginTask: " + handler.getTaskId() + repeating, schedulerSyncTimer); - } else if (!handler.isAsynchronous()) { - return TimingsManager.getTiming(DEFAULT_GROUP.name, "Task: " + handler.getTaskId() + repeating, schedulerSyncTimer); - } else { - return null; - } - } - - public static Timing getPluginEventTiming(Class event, Listener listener, EventExecutor executor, Plugin plugin) { - Timing group = TimingsManager.getTiming(plugin.getName(), "Combined Total", pluginEventTimer); - - return TimingsManager.getTiming(plugin.getName(), "Event: " + listener.getClass().getName() + "." - + (executor instanceof MethodEventExecutor ? ((MethodEventExecutor) executor).getMethod().getName() : "???") - + " (" + event.getSimpleName() + ")", group); - } - - public static Timing getEntityTiming(Entity entity) { - return TimingsManager.getTiming(DEFAULT_GROUP.name, "## Entity Tick: " + entity.getClass().getSimpleName(), tickEntityTimer); - } - - public static Timing getBlockEntityTiming(BlockEntity blockEntity) { - return TimingsManager.getTiming(DEFAULT_GROUP.name, "## BlockEntity Tick: " + blockEntity.getClass().getSimpleName(), tickBlockEntityTimer); - } - - public static Timing getReceiveDataPacketTiming(DataPacket pk) { - return TimingsManager.getTiming(DEFAULT_GROUP.name, "## Receive Packet: " + pk.getClass().getSimpleName(), playerNetworkReceiveTimer); - } - - public static Timing getSendDataPacketTiming(DataPacket pk) { - return TimingsManager.getTiming(DEFAULT_GROUP.name, "## Send Packet: " + pk.getClass().getSimpleName(), playerNetworkSendTimer); - } - - public static void stopServer() { - setTimingsEnabled(false); - TimingsManager.recheckEnabled(); - } -} diff --git a/src/main/java/co/aikar/timings/TimingsExport.java b/src/main/java/co/aikar/timings/TimingsExport.java deleted file mode 100644 index 9c322a3c82c..00000000000 --- a/src/main/java/co/aikar/timings/TimingsExport.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import cn.nukkit.Server; -import cn.nukkit.command.CommandSender; -import cn.nukkit.command.ConsoleCommandSender; -import cn.nukkit.command.RemoteConsoleCommandSender; -import cn.nukkit.lang.TranslationContainer; -import cn.nukkit.nbt.stream.PGZIPOutputStream; -import cn.nukkit.timings.JsonUtil; -import cn.nukkit.utils.TextFormat; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonObject; - -import java.io.*; -import java.lang.management.ManagementFactory; -import java.lang.management.RuntimeMXBean; -import java.net.HttpURLConnection; -import java.net.InetAddress; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.zip.Deflater; - -import static co.aikar.timings.TimingsManager.HISTORY; - -public class TimingsExport extends Thread { - private final CommandSender sender; - private final JsonObject out; - private final TimingsHistory[] history; - - private TimingsExport(CommandSender sender, JsonObject out, TimingsHistory[] history) { - super("Timings paste thread"); - this.sender = sender; - this.out = out; - this.history = history; - } - - /** - * Builds a JSON timings report and sends it to Aikar's viewer - * - * @param sender Sender that issued the command - */ - public static void reportTimings(CommandSender sender) { - JsonObject out = new JsonObject(); - out.addProperty("version", Server.getInstance().getVersion()); - out.addProperty("maxplayers", Server.getInstance().getMaxPlayers()); - out.addProperty("start", TimingsManager.timingStart / 1000); - out.addProperty("end", System.currentTimeMillis() / 1000); - out.addProperty("sampletime", (System.currentTimeMillis() - TimingsManager.timingStart) / 1000); - - if (!Timings.isPrivacy()) { - out.addProperty("server", Server.getInstance().getName()); - out.addProperty("motd", Server.getInstance().getMotd()); - out.addProperty("online-mode", false); //In MCPE we have permanent offline mode. - out.addProperty("icon", ""); //"data:image/png;base64," - } - - final Runtime runtime = Runtime.getRuntime(); - RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); - - JsonObject system = new JsonObject(); - system.addProperty("timingcost", getCost()); - system.addProperty("name", System.getProperty("os.name")); - system.addProperty("version", System.getProperty("os.version")); - system.addProperty("jvmversion", System.getProperty("java.version")); - system.addProperty("arch", System.getProperty("os.arch")); - system.addProperty("maxmem", runtime.maxMemory()); - system.addProperty("cpu", runtime.availableProcessors()); - system.addProperty("runtime", ManagementFactory.getRuntimeMXBean().getUptime()); - system.addProperty("flags", String.join(" ", runtimeBean.getInputArguments())); - system.add("gc", JsonUtil.mapToObject(ManagementFactory.getGarbageCollectorMXBeans(), (input) -> - new JsonUtil.JSONPair(input.getName(), JsonUtil.toArray(input.getCollectionCount(), input.getCollectionTime())))); - out.add("system", system); - - TimingsHistory[] history = HISTORY.toArray(new TimingsHistory[HISTORY.size() + 1]); - history[HISTORY.size()] = new TimingsHistory(); //Current snapshot - - JsonObject timings = new JsonObject(); - for (TimingIdentifier.TimingGroup group : TimingIdentifier.GROUP_MAP.values()) { - for (Timing id : group.timings) { - if (!id.timed && !id.isSpecial()) { - continue; - } - - timings.add(String.valueOf(id.id), JsonUtil.toArray(group.id, id.name)); - } - } - - JsonObject idmap = new JsonObject(); - idmap.add("groups", JsonUtil.mapToObject(TimingIdentifier.GROUP_MAP.values(), (group) -> - new JsonUtil.JSONPair(group.id, group.name))); - idmap.add("handlers", timings); - idmap.add("worlds", JsonUtil.mapToObject(TimingsHistory.levelMap.entrySet(), (entry) -> - new JsonUtil.JSONPair(entry.getValue(), entry.getKey()))); - idmap.add("tileentity", JsonUtil.mapToObject(TimingsHistory.blockEntityMap.entrySet(), (entry) -> - new JsonUtil.JSONPair(entry.getKey(), entry.getValue()))); - idmap.add("entity", JsonUtil.mapToObject(TimingsHistory.entityMap.entrySet(), (entry) -> - new JsonUtil.JSONPair(entry.getKey(), entry.getValue()))); - out.add("idmap", idmap); - - //Information about loaded plugins - out.add("plugins", JsonUtil.mapToObject(Server.getInstance().getPluginManager().getPlugins().values(), (plugin) -> { - JsonObject jsonPlugin = new JsonObject(); - jsonPlugin.addProperty("version", plugin.getDescription().getVersion()); - jsonPlugin.addProperty("description", plugin.getDescription().getDescription());// Sounds legit - jsonPlugin.addProperty("website", plugin.getDescription().getWebsite()); - jsonPlugin.addProperty("authors", String.join(", ", plugin.getDescription().getAuthors())); - return new JsonUtil.JSONPair(plugin.getName(), jsonPlugin); - })); - - //Information on the users Config - JsonObject config = new JsonObject(); - if (!Timings.getIgnoredConfigSections().contains("all")) { - JsonObject nukkit = JsonUtil.toObject(Server.getInstance().getConfig().getRootSection()); - Timings.getIgnoredConfigSections().forEach(nukkit::remove); - config.add("nukkit", nukkit); - } else { - config.add("nukkit", null); - } - out.add("config", config); - - new TimingsExport(sender, out, history).start(); - } - - private static long getCost() { - int passes = 200; - Timing SAMPLER1 = TimingsManager.getTiming(null, "Timings sampler 1", null); - Timing SAMPLER2 = TimingsManager.getTiming(null, "Timings sampler 2", null); - Timing SAMPLER3 = TimingsManager.getTiming(null, "Timings sampler 3", null); - Timing SAMPLER4 = TimingsManager.getTiming(null, "Timings sampler 4", null); - Timing SAMPLER5 = TimingsManager.getTiming(null, "Timings sampler 5", null); - Timing SAMPLER6 = TimingsManager.getTiming(null, "Timings sampler 6", null); - - long start = System.nanoTime(); - for (int i = 0; i < passes; i++) { - SAMPLER1.startTiming(); - SAMPLER2.startTiming(); - SAMPLER3.startTiming(); - SAMPLER4.startTiming(); - SAMPLER5.startTiming(); - SAMPLER6.startTiming(); - SAMPLER6.stopTiming(); - SAMPLER5.stopTiming(); - SAMPLER4.stopTiming(); - SAMPLER3.stopTiming(); - SAMPLER2.stopTiming(); - SAMPLER1.stopTiming(); - } - - long timingsCost = (System.nanoTime() - start) / passes / 6; - - SAMPLER1.reset(true); - SAMPLER2.reset(true); - SAMPLER3.reset(true); - SAMPLER4.reset(true); - SAMPLER5.reset(true); - SAMPLER6.reset(true); - - return timingsCost; - } - - @Override - public synchronized void start() { - if (this.sender instanceof RemoteConsoleCommandSender) { - this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.rcon")); - run(); - } else { - super.start(); - } - } - - @Override - public void run() { - this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.uploadStart")); - this.out.add("data", JsonUtil.mapToArray(this.history, TimingsHistory::export)); - - String response = null; - try { - HttpURLConnection con = (HttpURLConnection) new URL("http://timings.aikar.co/post").openConnection(); - con.setDoOutput(true); - con.setRequestProperty("User-Agent", "Nukkit/" + Server.getInstance().getName() + "/" + InetAddress.getLocalHost().getHostName()); - con.setRequestMethod("POST"); - con.setInstanceFollowRedirects(false); - - PGZIPOutputStream request = new PGZIPOutputStream(con.getOutputStream()); - request.setLevel(Deflater.BEST_COMPRESSION); - - request.write(new Gson().toJson(this.out).getBytes(StandardCharsets.UTF_8)); - request.close(); - - response = getResponse(con); - - if (con.getResponseCode() != 302) { - this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.uploadError", String.valueOf(con.getResponseCode()), con.getResponseMessage())); - if (response != null) { - Server.getInstance().getLogger().alert(response); - } - return; - } - - String location = con.getHeaderField("Location"); - this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.timingsLocation", location)); - if (!(this.sender instanceof ConsoleCommandSender)) { - Server.getInstance().getLogger().info(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsLocation", location)); - } - - if (response != null && !response.isEmpty()) { - Server.getInstance().getLogger().info(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsResponse", response)); - } - - File timingFolder = new File(Server.getInstance().getDataPath() + File.separator + "timings"); - timingFolder.mkdirs(); - String fileName = timingFolder + File.separator + new SimpleDateFormat("'timings-'yyyy-MM-dd-hh-mm'.txt'").format(new Date()); - - FileWriter writer = new FileWriter(fileName); - writer.write(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsLocation", location) + "\n\n"); - writer.write(new GsonBuilder().setPrettyPrinting().create().toJson(this.out)); - writer.close(); - - Server.getInstance().getLogger().info(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsWrite", fileName)); - } catch (IOException exception) { - this.sender.sendMessage(TextFormat.RED + "" + new TranslationContainer("nukkit.command.timings.reportError")); - if (response != null) { - Server.getInstance().getLogger().alert(response); - } - Server.getInstance().getLogger().logException(exception); - } - } - - private String getResponse(HttpURLConnection con) throws IOException { - try (InputStream is = con.getInputStream()) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - byte[] b = new byte[1024]; - int bytesRead; - while ((bytesRead = is.read(b)) != -1) { - bos.write(b, 0, bytesRead); - } - return bos.toString(); - - } catch (IOException exception) { - this.sender.sendMessage(TextFormat.RED + "" + new TranslationContainer("nukkit.command.timings.reportError")); - Server.getInstance().getLogger().warning(con.getResponseMessage(), exception); - return null; - } - } -} diff --git a/src/main/java/co/aikar/timings/TimingsHistory.java b/src/main/java/co/aikar/timings/TimingsHistory.java deleted file mode 100644 index e7e25c07cd9..00000000000 --- a/src/main/java/co/aikar/timings/TimingsHistory.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import cn.nukkit.Player; -import cn.nukkit.Server; -import cn.nukkit.blockentity.BlockEntity; -import cn.nukkit.entity.Entity; -import cn.nukkit.level.Level; -import cn.nukkit.level.format.FullChunk; -import cn.nukkit.timings.JsonUtil; -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; - -import java.lang.management.ManagementFactory; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; - -import static co.aikar.timings.Timings.fullServerTickTimer; -import static co.aikar.timings.TimingsManager.MINUTE_REPORTS; - -public class TimingsHistory { - public static long lastMinuteTime; - public static long timedTicks; - public static long playerTicks; - public static long entityTicks; - public static long tileEntityTicks; - public static long activatedEntityTicks; - - private static int levelIdPool = 1; - static Map levelMap = new HashMap<>(); - static Map entityMap = new HashMap<>(); - static Map blockEntityMap = new HashMap<>(); - - private final long endTime; - private final long startTime; - private final long totalTicks; - // Represents all time spent running the server this history - private final long totalTime; - private final MinuteReport[] minuteReports; - - private final TimingsHistoryEntry[] entries; - private final JsonObject levels = new JsonObject(); - - TimingsHistory() { - this.endTime = System.currentTimeMillis() / 1000; - this.startTime = TimingsManager.historyStart / 1000; - - if (timedTicks % 1200 != 0 || MINUTE_REPORTS.isEmpty()) { - this.minuteReports = MINUTE_REPORTS.toArray(new MinuteReport[MINUTE_REPORTS.size() + 1]); - this.minuteReports[this.minuteReports.length - 1] = new MinuteReport(); - } else { - this.minuteReports = MINUTE_REPORTS.toArray(new MinuteReport[0]); - } - - long ticks = 0; - for (MinuteReport mr : this.minuteReports) { - ticks += mr.ticksRecord.timed; - } - - this.totalTicks = ticks; - this.totalTime = fullServerTickTimer.record.totalTime; - this.entries = new TimingsHistoryEntry[TimingsManager.TIMINGS.size()]; - - int i = 0; - for (Timing timing : TimingsManager.TIMINGS) { - this.entries[i++] = new TimingsHistoryEntry(timing); - } - - final Map entityCounts = new HashMap<>(); - final Map blockEntityCounts = new HashMap<>(); - final Gson GSON = new Gson(); - // Information about all loaded entities/block entities - for (Level level : Server.getInstance().getLevels().values()) { - JsonArray jsonLevel = new JsonArray(); - for (FullChunk chunk : level.getChunks().values()) { - entityCounts.clear(); - blockEntityCounts.clear(); - - //count entities - for (Entity entity : chunk.getEntities().values()) { - if (!entityCounts.containsKey(entity.getNetworkId())) - entityCounts.put(entity.getNetworkId(), new AtomicInteger(0)); - entityCounts.get(entity.getNetworkId()).incrementAndGet(); - entityMap.put(entity.getNetworkId(), entity.getClass().getSimpleName()); - } - - //count block entities - for (BlockEntity blockEntity : chunk.getBlockEntities().values()) { - if (!blockEntityCounts.containsKey(blockEntity.getBlock().getId())) - blockEntityCounts.put(blockEntity.getBlock().getId(), new AtomicInteger(0)); - blockEntityCounts.get(blockEntity.getBlock().getId()).incrementAndGet(); - blockEntityMap.put(blockEntity.getBlock().getId(), blockEntity.getClass().getSimpleName()); - } - - if (blockEntityCounts.isEmpty() && entityCounts.isEmpty()) { - continue; - } - - JsonArray jsonChunk = new JsonArray(); - jsonChunk.add(chunk.getX()); - jsonChunk.add(chunk.getZ()); - jsonChunk.add(GSON.toJsonTree(JsonUtil.mapToObject(entityCounts.entrySet(), (entry) -> new JsonUtil.JSONPair(entry.getKey(), entry.getValue().get()))).getAsJsonObject()); - jsonChunk.add(GSON.toJsonTree(JsonUtil.mapToObject(blockEntityCounts.entrySet(), (entry) -> new JsonUtil.JSONPair(entry.getKey(), entry.getValue().get()))).getAsJsonObject()); - jsonLevel.add(jsonChunk); - } - - if (!levelMap.containsKey(level.getName())) levelMap.put(level.getName(), levelIdPool++); - levels.add(String.valueOf(levelMap.get(level.getName())), jsonLevel); - } - } - - static void resetTicks(boolean fullReset) { - if (fullReset) { - timedTicks = 0; - } - lastMinuteTime = System.nanoTime(); - playerTicks = 0; - tileEntityTicks = 0; - entityTicks = 0; - activatedEntityTicks = 0; - } - - JsonObject export() { - JsonObject json = new JsonObject(); - json.addProperty("s", this.startTime); - json.addProperty("e", this.endTime); - json.addProperty("tk", this.totalTicks); - json.addProperty("tm", this.totalTime); - json.add("w", this.levels); - json.add("h", JsonUtil.mapToArray(this.entries, (entry) -> { - if (entry.data.count == 0) { - return null; - } - return entry.export(); - })); - json.add("mp", JsonUtil.mapToArray(this.minuteReports, MinuteReport::export)); - return json; - } - - static class MinuteReport { - final long time = System.currentTimeMillis() / 1000; - - final TicksRecord ticksRecord = new TicksRecord(); - final PingRecord pingRecord = new PingRecord(); - final TimingData fst = Timings.fullServerTickTimer.minuteData.clone(); - final double tps = 1E9 / (System.nanoTime() - lastMinuteTime) * this.ticksRecord.timed; - final double usedMemory = Timings.fullServerTickTimer.avgUsedMemory; - final double freeMemory = Timings.fullServerTickTimer.avgFreeMemory; - final double loadAvg = ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage(); - - JsonArray export() { - return JsonUtil.toArray(this.time, - Math.round(this.tps * 100D) / 100D, - Math.round(this.pingRecord.avg * 100D) / 100D, - this.fst.export(), - JsonUtil.toArray(this.ticksRecord.timed, - this.ticksRecord.player, - this.ticksRecord.entity, - this.ticksRecord.activatedEntity, - this.ticksRecord.tileEntity), - this.usedMemory, - this.freeMemory, - this.loadAvg); - } - } - - private static class TicksRecord { - final long timed; - final long player; - final long entity; - final long activatedEntity; - final long tileEntity; - - TicksRecord() { - this.timed = timedTicks - (TimingsManager.MINUTE_REPORTS.size() * 1200); - this.player = playerTicks; - this.entity = entityTicks; - this.activatedEntity = activatedEntityTicks; - this.tileEntity = tileEntityTicks; - } - } - - private static class PingRecord { - final double avg; - - PingRecord() { - final Collection onlinePlayers = Server.getInstance().getOnlinePlayers().values(); - int totalPing = 0; - for (Player player : onlinePlayers) { - totalPing += player.getPing(); - } - - this.avg = onlinePlayers.isEmpty() ? 0 : (float) totalPing / onlinePlayers.size(); - } - } -} diff --git a/src/main/java/co/aikar/timings/TimingsHistoryEntry.java b/src/main/java/co/aikar/timings/TimingsHistoryEntry.java deleted file mode 100644 index 6782b7184dd..00000000000 --- a/src/main/java/co/aikar/timings/TimingsHistoryEntry.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import com.google.gson.JsonArray; - -import cn.nukkit.timings.JsonUtil; - -class TimingsHistoryEntry { - final TimingData data; - final TimingData[] children; - - TimingsHistoryEntry(Timing timing) { - this.data = timing.record.clone(); - this.children = new TimingData[timing.children.size()]; - - int i = 0; - for (TimingData child : timing.children.values()) { - this.children[i++] = child.clone(); - } - } - - JsonArray export() { - JsonArray json = this.data.export(); - if (this.children.length > 0) json.add(JsonUtil.mapToArray(this.children, TimingData::export)); - return json; - } -} diff --git a/src/main/java/co/aikar/timings/TimingsManager.java b/src/main/java/co/aikar/timings/TimingsManager.java deleted file mode 100644 index 3622b329cd6..00000000000 --- a/src/main/java/co/aikar/timings/TimingsManager.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import cn.nukkit.Server; - -import java.util.*; - -public class TimingsManager { - static final Map TIMING_MAP = Collections.synchronizedMap(new HashMap<>(256, 0.5f)); - - static final Queue TIMINGS = new ArrayDeque<>(); - static final ArrayDeque MINUTE_REPORTS = new ArrayDeque<>(); - - static Queue HISTORY = new BoundedQueue<>(12); - - static Timing CURRENT; - - static long timingStart = 0; - static long historyStart = 0; - static boolean needsFullReset = false; - static boolean needsRecheckEnabled = false; - - static void reset() { - needsFullReset = true; - } - - /** - * Called every tick to count the number of times a timer caused TPS loss. - */ - static void tick() { - if (Timings.isTimingsEnabled()) { - boolean violated = Timings.fullServerTickTimer.isViolated(); - - synchronized (TIMINGS) { - for (Timing timing : TIMINGS) { - if (timing.isSpecial()) { - // Called manually - continue; - } - - timing.tick(violated); - } - } - - TimingsHistory.playerTicks += Server.getInstance().getOnlinePlayers().size(); - TimingsHistory.timedTicks++; - } - } - - static void recheckEnabled() { - synchronized (TIMING_MAP) { - TIMING_MAP.values().forEach(Timing::checkEnabled); - } - - needsRecheckEnabled = false; - } - - static void resetTimings() { - if (needsFullReset) { - // Full resets need to re-check every handlers enabled state - // Timing map can be modified from async so we must sync on it. - synchronized (TIMING_MAP) { - for (Timing timing : TIMING_MAP.values()) { - timing.reset(true); - } - } - - HISTORY.clear(); - needsFullReset = false; - needsRecheckEnabled = false; - timingStart = System.currentTimeMillis(); - } else { - // Soft resets only need to act on timings that have done something - // Handlers can only be modified on main thread. - for (Timing timing : TIMINGS) { - timing.reset(false); - } - } - - TIMINGS.clear(); - MINUTE_REPORTS.clear(); - - TimingsHistory.resetTicks(true); - historyStart = System.currentTimeMillis(); - } - - public static Timing getTiming(String name) { - return getTiming(null, name, null); - } - - static Timing getTiming(String group, String name, Timing groupTiming) { - TimingIdentifier id = new TimingIdentifier(group, name, groupTiming); - return TIMING_MAP.computeIfAbsent(id, k -> new Timing(id)); - } - - static final class BoundedQueue extends LinkedList { - final int maxSize; - - BoundedQueue(int maxSize) { - if (maxSize <= 0) { - throw new IllegalArgumentException("maxSize must be greater than zero"); - } - - this.maxSize = maxSize; - } - - @Override - public boolean add(E e) { - if (this.size() == maxSize) { - this.remove(); - } - - return super.add(e); - } - } -} diff --git a/src/main/resources/biome_id_map.json b/src/main/resources/biome_id_map.json index 2995c043916..e23def0c1a4 100644 --- a/src/main/resources/biome_id_map.json +++ b/src/main/resources/biome_id_map.json @@ -1,87 +1 @@ -{ - "bamboo_jungle": 48, - "bamboo_jungle_hills": 49, - "basalt_deltas": 181, - "beach": 16, - "birch_forest": 27, - "birch_forest_hills": 28, - "birch_forest_hills_mutated": 156, - "birch_forest_mutated": 155, - "cold_beach": 26, - "cold_ocean": 44, - "cold_taiga": 30, - "cold_taiga_hills": 31, - "cold_taiga_mutated": 158, - "crimson_forest": 179, - "deep_cold_ocean": 45, - "deep_dark": 190, - "deep_frozen_ocean": 47, - "deep_lukewarm_ocean": 43, - "deep_ocean": 24, - "deep_warm_ocean": 41, - "desert": 2, - "desert_hills": 17, - "desert_mutated": 130, - "dripstone_caves": 188, - "extreme_hills": 3, - "extreme_hills_edge": 20, - "extreme_hills_mutated": 131, - "extreme_hills_plus_trees": 34, - "extreme_hills_plus_trees_mutated": 162, - "flower_forest": 132, - "forest": 4, - "forest_hills": 18, - "frozen_ocean": 46, - "frozen_peaks": 183, - "frozen_river": 11, - "grove": 185, - "hell": 8, - "ice_mountains": 13, - "ice_plains": 12, - "ice_plains_spikes": 140, - "jagged_peaks": 182, - "jungle": 21, - "jungle_edge": 23, - "jungle_edge_mutated": 151, - "jungle_hills": 22, - "jungle_mutated": 149, - "legacy_frozen_ocean": 10, - "lukewarm_ocean": 42, - "lush_caves": 187, - "mangrove_swamp": 191, - "meadow": 186, - "mega_taiga": 32, - "mega_taiga_hills": 33, - "mesa": 37, - "mesa_bryce": 165, - "mesa_plateau": 39, - "mesa_plateau_mutated": 167, - "mesa_plateau_stone": 38, - "mesa_plateau_stone_mutated": 166, - "mushroom_island": 14, - "mushroom_island_shore": 15, - "ocean": 0, - "plains": 1, - "redwood_taiga_hills_mutated": 161, - "redwood_taiga_mutated": 160, - "river": 7, - "roofed_forest": 29, - "roofed_forest_mutated": 157, - "savanna": 35, - "savanna_mutated": 163, - "savanna_plateau": 36, - "savanna_plateau_mutated": 164, - "snowy_slopes": 184, - "soulsand_valley": 178, - "stone_beach": 25, - "stony_peaks": 189, - "sunflower_plains": 129, - "swampland": 6, - "swampland_mutated": 134, - "taiga": 5, - "taiga_hills": 19, - "taiga_mutated": 133, - "the_end": 9, - "warm_ocean": 40, - "warped_forest": 180 -} \ No newline at end of file +{"bamboo_jungle":48,"bamboo_jungle_hills":49,"basalt_deltas":181,"beach":16,"birch_forest":27,"birch_forest_hills":28,"birch_forest_hills_mutated":156,"birch_forest_mutated":155,"cold_beach":26,"cold_ocean":44,"cold_taiga":30,"cold_taiga_hills":31,"cold_taiga_mutated":158,"crimson_forest":179,"deep_cold_ocean":45,"deep_frozen_ocean":47,"deep_lukewarm_ocean":43,"deep_ocean":24,"deep_warm_ocean":41,"desert":2,"desert_hills":17,"desert_mutated":130,"dripstone_caves":188,"extreme_hills":3,"extreme_hills_edge":20,"extreme_hills_mutated":131,"extreme_hills_plus_trees":34,"extreme_hills_plus_trees_mutated":162,"flower_forest":132,"forest":4,"forest_hills":18,"frozen_ocean":46,"frozen_peaks":183,"frozen_river":11,"grove":185,"hell":8,"ice_mountains":13,"ice_plains":12,"ice_plains_spikes":140,"jagged_peaks":182,"jungle":21,"jungle_edge":23,"jungle_edge_mutated":151,"jungle_hills":22,"jungle_mutated":149,"legacy_frozen_ocean":10,"lukewarm_ocean":42,"lush_caves":187,"meadow":186,"mega_taiga":32,"mega_taiga_hills":33,"mesa":37,"mesa_bryce":165,"mesa_plateau":39,"mesa_plateau_mutated":167,"mesa_plateau_stone":38,"mesa_plateau_stone_mutated":166,"mushroom_island":14,"mushroom_island_shore":15,"ocean":0,"plains":1,"redwood_taiga_hills_mutated":161,"redwood_taiga_mutated":160,"river":7,"roofed_forest":29,"roofed_forest_mutated":157,"savanna":35,"savanna_mutated":163,"savanna_plateau":36,"savanna_plateau_mutated":164,"snowy_slopes":184,"soulsand_valley":178,"stone_beach":25,"stony_peaks":189,"sunflower_plains":129,"swampland":6,"swampland_mutated":134,"taiga":5,"taiga_hills":19,"taiga_mutated":133,"the_end":9,"warm_ocean":40,"warped_forest":180} \ No newline at end of file diff --git a/src/main/resources/block_palette_729.nbt b/src/main/resources/block_palette_729.nbt new file mode 100644 index 00000000000..bb19c11ca73 Binary files /dev/null and b/src/main/resources/block_palette_729.nbt differ diff --git a/src/main/resources/command_default.json b/src/main/resources/command_default.json deleted file mode 100644 index 99f67e9c6f8..00000000000 --- a/src/main/resources/command_default.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "aliases": [], - "description": "insert_description_here", - "overloads": { - "default": { - "input": { - "parameters": [ - { - "name": "args", - "type": "rawtext", - "optional": true - } - ] - }, - "output": {} - } - }, - "permission": "any" -} \ No newline at end of file diff --git a/src/main/resources/entity_identifiers.dat b/src/main/resources/entity_identifiers.dat index 4e8d836c6df..297d3053714 100644 Binary files a/src/main/resources/entity_identifiers.dat and b/src/main/resources/entity_identifiers.dat differ diff --git a/src/main/resources/item_tags.json b/src/main/resources/item_tags.json new file mode 100644 index 00000000000..735fbac6b3d --- /dev/null +++ b/src/main/resources/item_tags.json @@ -0,0 +1 @@ +{"minecraft:arrow":["minecraft:arrow"],"minecraft:banner":["minecraft:banner"],"minecraft:boat":["minecraft:acacia_boat","minecraft:acacia_chest_boat","minecraft:bamboo_chest_raft","minecraft:bamboo_raft","minecraft:birch_boat","minecraft:birch_chest_boat","minecraft:cherry_boat","minecraft:cherry_chest_boat","minecraft:dark_oak_boat","minecraft:dark_oak_chest_boat","minecraft:jungle_boat","minecraft:jungle_chest_boat","minecraft:mangrove_boat","minecraft:mangrove_chest_boat","minecraft:oak_boat","minecraft:oak_chest_boat","minecraft:spruce_boat","minecraft:spruce_chest_boat"],"minecraft:boats":["minecraft:acacia_boat","minecraft:acacia_chest_boat","minecraft:bamboo_chest_raft","minecraft:bamboo_raft","minecraft:birch_boat","minecraft:birch_chest_boat","minecraft:cherry_boat","minecraft:cherry_chest_boat","minecraft:dark_oak_boat","minecraft:dark_oak_chest_boat","minecraft:jungle_boat","minecraft:jungle_chest_boat","minecraft:mangrove_boat","minecraft:mangrove_chest_boat","minecraft:oak_boat","minecraft:oak_chest_boat","minecraft:spruce_boat","minecraft:spruce_chest_boat"],"minecraft:bookshelf_books":["minecraft:book","minecraft:enchanted_book","minecraft:writable_book","minecraft:written_book"],"minecraft:chainmail_tier":["minecraft:chainmail_boots","minecraft:chainmail_chestplate","minecraft:chainmail_helmet","minecraft:chainmail_leggings"],"minecraft:coals":["minecraft:charcoal","minecraft:coal"],"minecraft:crimson_stems":["minecraft:crimson_hyphae","minecraft:crimson_stem","minecraft:stripped_crimson_hyphae","minecraft:stripped_crimson_stem"],"minecraft:decorated_pot_sherds":["minecraft:angler_pottery_sherd","minecraft:archer_pottery_sherd","minecraft:arms_up_pottery_sherd","minecraft:blade_pottery_sherd","minecraft:brewer_pottery_sherd","minecraft:brick","minecraft:burn_pottery_sherd","minecraft:danger_pottery_sherd","minecraft:explorer_pottery_sherd","minecraft:friend_pottery_sherd","minecraft:heart_pottery_sherd","minecraft:heartbreak_pottery_sherd","minecraft:howl_pottery_sherd","minecraft:miner_pottery_sherd","minecraft:mourner_pottery_sherd","minecraft:plenty_pottery_sherd","minecraft:prize_pottery_sherd","minecraft:sheaf_pottery_sherd","minecraft:shelter_pottery_sherd","minecraft:skull_pottery_sherd","minecraft:snort_pottery_sherd"],"minecraft:diamond_tier":["minecraft:diamond_axe","minecraft:diamond_boots","minecraft:diamond_chestplate","minecraft:diamond_helmet","minecraft:diamond_hoe","minecraft:diamond_leggings","minecraft:diamond_pickaxe","minecraft:diamond_shovel","minecraft:diamond_sword"],"minecraft:digger":["minecraft:diamond_axe","minecraft:diamond_hoe","minecraft:diamond_pickaxe","minecraft:diamond_shovel","minecraft:golden_axe","minecraft:golden_hoe","minecraft:golden_pickaxe","minecraft:golden_shovel","minecraft:iron_axe","minecraft:iron_hoe","minecraft:iron_pickaxe","minecraft:iron_shovel","minecraft:netherite_axe","minecraft:netherite_hoe","minecraft:netherite_pickaxe","minecraft:netherite_shovel","minecraft:stone_axe","minecraft:stone_hoe","minecraft:stone_pickaxe","minecraft:stone_shovel","minecraft:wooden_axe","minecraft:wooden_hoe","minecraft:wooden_pickaxe","minecraft:wooden_shovel"],"minecraft:door":["minecraft:acacia_door","minecraft:bamboo_door","minecraft:birch_door","minecraft:cherry_door","minecraft:crimson_door","minecraft:dark_oak_door","minecraft:iron_door","minecraft:jungle_door","minecraft:mangrove_door","minecraft:spruce_door","minecraft:warped_door","minecraft:wooden_door"],"minecraft:golden_tier":["minecraft:golden_axe","minecraft:golden_boots","minecraft:golden_chestplate","minecraft:golden_helmet","minecraft:golden_hoe","minecraft:golden_leggings","minecraft:golden_pickaxe","minecraft:golden_shovel","minecraft:golden_sword"],"minecraft:hanging_actor":["minecraft:painting"],"minecraft:hanging_sign":["minecraft:acacia_hanging_sign","minecraft:bamboo_hanging_sign","minecraft:birch_hanging_sign","minecraft:cherry_hanging_sign","minecraft:crimson_hanging_sign","minecraft:dark_oak_hanging_sign","minecraft:jungle_hanging_sign","minecraft:mangrove_hanging_sign","minecraft:oak_hanging_sign","minecraft:spruce_hanging_sign","minecraft:warped_hanging_sign"],"minecraft:horse_armor":["minecraft:diamond_horse_armor","minecraft:golden_horse_armor","minecraft:iron_horse_armor","minecraft:leather_horse_armor"],"minecraft:iron_tier":["minecraft:iron_axe","minecraft:iron_boots","minecraft:iron_chestplate","minecraft:iron_helmet","minecraft:iron_hoe","minecraft:iron_leggings","minecraft:iron_pickaxe","minecraft:iron_shovel","minecraft:iron_sword"],"minecraft:is_armor":["minecraft:chainmail_boots","minecraft:chainmail_chestplate","minecraft:chainmail_helmet","minecraft:chainmail_leggings","minecraft:diamond_boots","minecraft:diamond_chestplate","minecraft:diamond_helmet","minecraft:diamond_leggings","minecraft:elytra","minecraft:golden_boots","minecraft:golden_chestplate","minecraft:golden_helmet","minecraft:golden_leggings","minecraft:iron_boots","minecraft:iron_chestplate","minecraft:iron_helmet","minecraft:iron_leggings","minecraft:leather_boots","minecraft:leather_chestplate","minecraft:leather_helmet","minecraft:leather_leggings","minecraft:netherite_boots","minecraft:netherite_chestplate","minecraft:netherite_helmet","minecraft:netherite_leggings","minecraft:turtle_helmet"],"minecraft:is_axe":["minecraft:diamond_axe","minecraft:golden_axe","minecraft:iron_axe","minecraft:netherite_axe","minecraft:stone_axe","minecraft:wooden_axe"],"minecraft:is_cooked":["minecraft:cooked_beef","minecraft:cooked_chicken","minecraft:cooked_cod","minecraft:cooked_mutton","minecraft:cooked_porkchop","minecraft:cooked_rabbit","minecraft:cooked_salmon","minecraft:rabbit_stew"],"minecraft:is_fish":["minecraft:cod","minecraft:cooked_cod","minecraft:cooked_salmon","minecraft:pufferfish","minecraft:salmon","minecraft:tropical_fish"],"minecraft:is_food":["minecraft:apple","minecraft:baked_potato","minecraft:beef","minecraft:beetroot","minecraft:beetroot_soup","minecraft:bread","minecraft:carrot","minecraft:chicken","minecraft:cooked_beef","minecraft:cooked_chicken","minecraft:cooked_mutton","minecraft:cooked_porkchop","minecraft:cooked_rabbit","minecraft:cookie","minecraft:dried_kelp","minecraft:enchanted_golden_apple","minecraft:golden_apple","minecraft:golden_carrot","minecraft:melon_slice","minecraft:mushroom_stew","minecraft:mutton","minecraft:porkchop","minecraft:potato","minecraft:pumpkin_pie","minecraft:rabbit","minecraft:rabbit_stew","minecraft:rotten_flesh","minecraft:sweet_berries"],"minecraft:is_hoe":["minecraft:diamond_hoe","minecraft:golden_hoe","minecraft:iron_hoe","minecraft:netherite_hoe","minecraft:stone_hoe","minecraft:wooden_hoe"],"minecraft:is_meat":["minecraft:beef","minecraft:chicken","minecraft:cooked_beef","minecraft:cooked_chicken","minecraft:cooked_mutton","minecraft:cooked_porkchop","minecraft:cooked_rabbit","minecraft:mutton","minecraft:porkchop","minecraft:rabbit","minecraft:rabbit_stew","minecraft:rotten_flesh"],"minecraft:is_minecart":["minecraft:chest_minecart","minecraft:command_block_minecart","minecraft:hopper_minecart","minecraft:minecart","minecraft:tnt_minecart"],"minecraft:is_pickaxe":["minecraft:diamond_pickaxe","minecraft:golden_pickaxe","minecraft:iron_pickaxe","minecraft:netherite_pickaxe","minecraft:stone_pickaxe","minecraft:wooden_pickaxe"],"minecraft:is_shovel":["minecraft:diamond_shovel","minecraft:golden_shovel","minecraft:iron_shovel","minecraft:netherite_shovel","minecraft:stone_shovel","minecraft:wooden_shovel"],"minecraft:is_sword":["minecraft:diamond_sword","minecraft:golden_sword","minecraft:iron_sword","minecraft:netherite_sword","minecraft:stone_sword","minecraft:wooden_sword"],"minecraft:is_tool":["minecraft:diamond_axe","minecraft:diamond_hoe","minecraft:diamond_pickaxe","minecraft:diamond_shovel","minecraft:diamond_sword","minecraft:golden_axe","minecraft:golden_hoe","minecraft:golden_pickaxe","minecraft:golden_shovel","minecraft:golden_sword","minecraft:iron_axe","minecraft:iron_hoe","minecraft:iron_pickaxe","minecraft:iron_shovel","minecraft:iron_sword","minecraft:netherite_axe","minecraft:netherite_hoe","minecraft:netherite_pickaxe","minecraft:netherite_shovel","minecraft:netherite_sword","minecraft:stone_axe","minecraft:stone_hoe","minecraft:stone_pickaxe","minecraft:stone_shovel","minecraft:stone_sword","minecraft:wooden_axe","minecraft:wooden_hoe","minecraft:wooden_pickaxe","minecraft:wooden_shovel","minecraft:wooden_sword"],"minecraft:is_trident":["minecraft:trident"],"minecraft:leather_tier":["minecraft:leather_boots","minecraft:leather_chestplate","minecraft:leather_helmet","minecraft:leather_leggings"],"minecraft:lectern_books":["minecraft:writable_book","minecraft:written_book"],"minecraft:logs":["minecraft:acacia_log","minecraft:birch_log","minecraft:cherry_log","minecraft:cherry_wood","minecraft:crimson_hyphae","minecraft:crimson_stem","minecraft:dark_oak_log","minecraft:jungle_log","minecraft:mangrove_log","minecraft:mangrove_wood","minecraft:oak_log","minecraft:spruce_log","minecraft:stripped_acacia_log","minecraft:stripped_birch_log","minecraft:stripped_cherry_log","minecraft:stripped_cherry_wood","minecraft:stripped_crimson_hyphae","minecraft:stripped_crimson_stem","minecraft:stripped_dark_oak_log","minecraft:stripped_jungle_log","minecraft:stripped_mangrove_log","minecraft:stripped_mangrove_wood","minecraft:stripped_oak_log","minecraft:stripped_spruce_log","minecraft:stripped_warped_hyphae","minecraft:stripped_warped_stem","minecraft:warped_hyphae","minecraft:warped_stem","minecraft:wood"],"minecraft:logs_that_burn":["minecraft:acacia_log","minecraft:birch_log","minecraft:cherry_log","minecraft:cherry_wood","minecraft:dark_oak_log","minecraft:jungle_log","minecraft:mangrove_log","minecraft:mangrove_wood","minecraft:oak_log","minecraft:spruce_log","minecraft:stripped_acacia_log","minecraft:stripped_birch_log","minecraft:stripped_cherry_log","minecraft:stripped_cherry_wood","minecraft:stripped_dark_oak_log","minecraft:stripped_jungle_log","minecraft:stripped_mangrove_log","minecraft:stripped_mangrove_wood","minecraft:stripped_oak_log","minecraft:stripped_spruce_log","minecraft:wood"],"minecraft:mangrove_logs":["minecraft:mangrove_log","minecraft:mangrove_wood","minecraft:stripped_mangrove_log","minecraft:stripped_mangrove_wood"],"minecraft:music_disc":["minecraft:music_disc_11","minecraft:music_disc_13","minecraft:music_disc_5","minecraft:music_disc_blocks","minecraft:music_disc_cat","minecraft:music_disc_chirp","minecraft:music_disc_far","minecraft:music_disc_mall","minecraft:music_disc_mellohi","minecraft:music_disc_otherside","minecraft:music_disc_pigstep","minecraft:music_disc_relic","minecraft:music_disc_stal","minecraft:music_disc_strad","minecraft:music_disc_wait","minecraft:music_disc_ward"],"minecraft:netherite_tier":["minecraft:netherite_axe","minecraft:netherite_boots","minecraft:netherite_chestplate","minecraft:netherite_helmet","minecraft:netherite_hoe","minecraft:netherite_leggings","minecraft:netherite_pickaxe","minecraft:netherite_shovel","minecraft:netherite_sword"],"minecraft:planks":["minecraft:bamboo_planks","minecraft:cherry_planks","minecraft:crimson_planks","minecraft:mangrove_planks","minecraft:planks","minecraft:warped_planks"],"minecraft:sand":["minecraft:sand"],"minecraft:sign":["minecraft:acacia_hanging_sign","minecraft:acacia_sign","minecraft:bamboo_hanging_sign","minecraft:bamboo_sign","minecraft:birch_hanging_sign","minecraft:birch_sign","minecraft:cherry_hanging_sign","minecraft:cherry_sign","minecraft:crimson_hanging_sign","minecraft:crimson_sign","minecraft:dark_oak_hanging_sign","minecraft:dark_oak_sign","minecraft:jungle_hanging_sign","minecraft:jungle_sign","minecraft:mangrove_hanging_sign","minecraft:mangrove_sign","minecraft:oak_hanging_sign","minecraft:oak_sign","minecraft:spruce_hanging_sign","minecraft:spruce_sign","minecraft:warped_hanging_sign","minecraft:warped_sign"],"minecraft:soul_fire_base_blocks":["minecraft:soul_sand","minecraft:soul_soil"],"minecraft:spawn_egg":["minecraft:agent_spawn_egg","minecraft:allay_spawn_egg","minecraft:axolotl_spawn_egg","minecraft:bat_spawn_egg","minecraft:bee_spawn_egg","minecraft:blaze_spawn_egg","minecraft:camel_spawn_egg","minecraft:cat_spawn_egg","minecraft:cave_spider_spawn_egg","minecraft:chicken_spawn_egg","minecraft:cod_spawn_egg","minecraft:cow_spawn_egg","minecraft:creeper_spawn_egg","minecraft:dolphin_spawn_egg","minecraft:donkey_spawn_egg","minecraft:drowned_spawn_egg","minecraft:elder_guardian_spawn_egg","minecraft:ender_dragon_spawn_egg","minecraft:enderman_spawn_egg","minecraft:endermite_spawn_egg","minecraft:evoker_spawn_egg","minecraft:fox_spawn_egg","minecraft:frog_spawn_egg","minecraft:ghast_spawn_egg","minecraft:glow_squid_spawn_egg","minecraft:goat_spawn_egg","minecraft:guardian_spawn_egg","minecraft:hoglin_spawn_egg","minecraft:horse_spawn_egg","minecraft:husk_spawn_egg","minecraft:iron_golem_spawn_egg","minecraft:llama_spawn_egg","minecraft:magma_cube_spawn_egg","minecraft:mooshroom_spawn_egg","minecraft:mule_spawn_egg","minecraft:npc_spawn_egg","minecraft:ocelot_spawn_egg","minecraft:panda_spawn_egg","minecraft:parrot_spawn_egg","minecraft:phantom_spawn_egg","minecraft:pig_spawn_egg","minecraft:piglin_brute_spawn_egg","minecraft:piglin_spawn_egg","minecraft:pillager_spawn_egg","minecraft:polar_bear_spawn_egg","minecraft:pufferfish_spawn_egg","minecraft:rabbit_spawn_egg","minecraft:ravager_spawn_egg","minecraft:salmon_spawn_egg","minecraft:sheep_spawn_egg","minecraft:shulker_spawn_egg","minecraft:silverfish_spawn_egg","minecraft:skeleton_horse_spawn_egg","minecraft:skeleton_spawn_egg","minecraft:slime_spawn_egg","minecraft:sniffer_spawn_egg","minecraft:snow_golem_spawn_egg","minecraft:spawn_egg","minecraft:spider_spawn_egg","minecraft:squid_spawn_egg","minecraft:stray_spawn_egg","minecraft:strider_spawn_egg","minecraft:tadpole_spawn_egg","minecraft:trader_llama_spawn_egg","minecraft:tropical_fish_spawn_egg","minecraft:turtle_spawn_egg","minecraft:vex_spawn_egg","minecraft:villager_spawn_egg","minecraft:vindicator_spawn_egg","minecraft:wandering_trader_spawn_egg","minecraft:warden_spawn_egg","minecraft:witch_spawn_egg","minecraft:wither_skeleton_spawn_egg","minecraft:wither_spawn_egg","minecraft:wolf_spawn_egg","minecraft:zoglin_spawn_egg","minecraft:zombie_horse_spawn_egg","minecraft:zombie_pigman_spawn_egg","minecraft:zombie_spawn_egg","minecraft:zombie_villager_spawn_egg"],"minecraft:stone_bricks":["minecraft:stonebrick"],"minecraft:stone_crafting_materials":["minecraft:blackstone","minecraft:cobbled_deepslate","minecraft:cobblestone"],"minecraft:stone_tier":["minecraft:stone_axe","minecraft:stone_hoe","minecraft:stone_pickaxe","minecraft:stone_shovel","minecraft:stone_sword"],"minecraft:stone_tool_materials":["minecraft:blackstone","minecraft:cobbled_deepslate","minecraft:cobblestone"],"minecraft:transform_materials":["minecraft:netherite_ingot"],"minecraft:transform_templates":["minecraft:netherite_upgrade_smithing_template"],"minecraft:transformable_items":["minecraft:diamond_axe","minecraft:diamond_boots","minecraft:diamond_chestplate","minecraft:diamond_helmet","minecraft:diamond_hoe","minecraft:diamond_leggings","minecraft:diamond_pickaxe","minecraft:diamond_shovel","minecraft:diamond_sword","minecraft:golden_boots"],"minecraft:trim_materials":["minecraft:amethyst_shard","minecraft:copper_ingot","minecraft:diamond","minecraft:emerald","minecraft:gold_ingot","minecraft:iron_ingot","minecraft:lapis_lazuli","minecraft:netherite_ingot","minecraft:quartz","minecraft:redstone"],"minecraft:trim_templates":["minecraft:coast_armor_trim_smithing_template","minecraft:dune_armor_trim_smithing_template","minecraft:eye_armor_trim_smithing_template","minecraft:host_armor_trim_smithing_template","minecraft:raiser_armor_trim_smithing_template","minecraft:rib_armor_trim_smithing_template","minecraft:sentry_armor_trim_smithing_template","minecraft:shaper_armor_trim_smithing_template","minecraft:silence_armor_trim_smithing_template","minecraft:snout_armor_trim_smithing_template","minecraft:spire_armor_trim_smithing_template","minecraft:tide_armor_trim_smithing_template","minecraft:vex_armor_trim_smithing_template","minecraft:ward_armor_trim_smithing_template","minecraft:wayfinder_armor_trim_smithing_template","minecraft:wild_armor_trim_smithing_template"],"minecraft:trimmable_armors":["minecraft:chainmail_boots","minecraft:chainmail_chestplate","minecraft:chainmail_helmet","minecraft:chainmail_leggings","minecraft:diamond_boots","minecraft:diamond_chestplate","minecraft:diamond_helmet","minecraft:diamond_leggings","minecraft:golden_boots","minecraft:golden_chestplate","minecraft:golden_helmet","minecraft:golden_leggings","minecraft:iron_boots","minecraft:iron_chestplate","minecraft:iron_helmet","minecraft:iron_leggings","minecraft:leather_boots","minecraft:leather_chestplate","minecraft:leather_helmet","minecraft:leather_leggings","minecraft:netherite_boots","minecraft:netherite_chestplate","minecraft:netherite_helmet","minecraft:netherite_leggings","minecraft:turtle_helmet"],"minecraft:vibration_damper":["minecraft:black_carpet","minecraft:black_wool","minecraft:blue_carpet","minecraft:blue_wool","minecraft:brown_carpet","minecraft:brown_wool","minecraft:cyan_carpet","minecraft:cyan_wool","minecraft:gray_carpet","minecraft:gray_wool","minecraft:green_carpet","minecraft:green_wool","minecraft:light_blue_carpet","minecraft:light_blue_wool","minecraft:light_gray_carpet","minecraft:light_gray_wool","minecraft:lime_carpet","minecraft:lime_wool","minecraft:magenta_carpet","minecraft:magenta_wool","minecraft:orange_carpet","minecraft:orange_wool","minecraft:pink_carpet","minecraft:pink_wool","minecraft:purple_carpet","minecraft:purple_wool","minecraft:red_carpet","minecraft:red_wool","minecraft:white_carpet","minecraft:white_wool","minecraft:yellow_carpet","minecraft:yellow_wool"],"minecraft:warped_stems":["minecraft:stripped_warped_hyphae","minecraft:stripped_warped_stem","minecraft:warped_hyphae","minecraft:warped_stem"],"minecraft:wooden_slabs":["minecraft:bamboo_slab","minecraft:cherry_slab","minecraft:crimson_slab","minecraft:mangrove_slab","minecraft:warped_slab","minecraft:wooden_slab"],"minecraft:wooden_tier":["minecraft:wooden_axe","minecraft:wooden_hoe","minecraft:wooden_pickaxe","minecraft:wooden_shovel","minecraft:wooden_sword"],"minecraft:wool":["minecraft:black_wool","minecraft:blue_wool","minecraft:brown_wool","minecraft:cyan_wool","minecraft:gray_wool","minecraft:green_wool","minecraft:light_blue_wool","minecraft:light_gray_wool","minecraft:lime_wool","minecraft:magenta_wool","minecraft:orange_wool","minecraft:pink_wool","minecraft:purple_wool","minecraft:red_wool","minecraft:white_wool","minecraft:yellow_wool"]} \ No newline at end of file diff --git a/src/main/resources/lang b/src/main/resources/lang deleted file mode 160000 index 2eb7d3dc102..00000000000 --- a/src/main/resources/lang +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 2eb7d3dc1023ff32aa578d9af412252ce2e31c55 diff --git a/src/main/resources/lang/ara/lang.ini b/src/main/resources/lang/ara/lang.ini new file mode 100644 index 00000000000..80db7ed4895 --- /dev/null +++ b/src/main/resources/lang/ara/lang.ini @@ -0,0 +1,327 @@ +# Language file compatible with Minecraft: Pocket Edition identifiers +# +# A message doesn't need to be there to be shown correctly on the client. +# Only messages shown in Nukkit itself need to be here +# Using the language property from PocketMine-MP + +language.name=Arabic +language.selected=Selected {%0} ({%1}) تم اختيارها كلغه + +multiplayer.player.joined={%0} دخل الى اللعبه +multiplayer.player.left={%0} خرج من اللعبه + +chat.type.text=<{%0}> {%1} +chat.type.emote=* {%0} {%1} +chat.type.announcement=[{%0}] {%1} +chat.type.admin=[{%0}: {%1}] +chat.type.achievement={%0} لقد فقط تلقى انجاز! {%1} + +disconnectionScreen.outdatedClient=نوع خارج الاصدار! +disconnectionScreen.outdatedServer=الخادم خارج الاصدار! +disconnectionScreen.serverFull=الخادم ممتلئ! +disconnectionScreen.noReason=قطع اتصاله من الخادم! +disconnectionScreen.invalidSkin=جلد غير معروف! +disconnectionScreen.invalidName=اسم غير معروف! +disconnectionScreen.resourcePack=مشكله حدثت اثناء تحميل ملفات اللعبه او الخادم. + +death.fell.accident.generic={%0} وقع من مسافه عاليه +death.attack.inFire={%0} انحرف باللهب! +death.attack.onFire={%0} انحرق حتى الموت +death.attack.lava={%0} جرب السباحه بالحمم +death.attack.inWall={%0} دخل الى داخل الجدار +death.attack.drown={%0} غرق +death.attack.cactus={%0} لقد وغز حتى الموت +death.attack.generic={%0} مات +death.attack.explosion={%0} فجر +death.attack.explosion.player={%0} فجر من قبل {%1} +death.attack.magic={%0} لقد قتل من السحر +death.attack.wither={%0} !رمي بعيدا +death.attack.mob={%0} قتل من قبل {%1} +death.attack.player={%0} قتل من قبل {%1} +death.attack.player.item={%0} قتل من قبل {%1} باستعمال {%2} +death.attack.arrow={%0} لقد طلق من قبل {%1} +death.attack.arrow.item={%0} لقد طلق من قبل {%1} باستعمال{%2} +death.attack.fall={%0} ضرب الارض بقوه +death.attack.outOfWorld={%0} وقع من خارج العالم + +gameMode.survival=طور البقاء +gameMode.creative=طور الابداع +gameMode.adventure=طور الاستكشاف +gameMode.spectator=طور الزائر +gameMode.changed=لقد تغير طورك + +potion.moveSpeed=السرعه +potion.moveSlowdown=المبطئ +potion.digSpeed=Haste +potion.digSlowDown=Mining Fatigue +potion.damageBoost=القوه +potion.heal=مزود الصحه +potion.harm=منقص الصحه +potion.jump=مقوي القفزات +potion.confusion=Nausea +potion.regeneration=معيد للصحه +potion.resistance=مضاد +potion.fireResistance=مضاد النار +potion.waterBreathing=تنفس الماء +potion.invisibility=الاختفاء +potion.blindness=الاعميان +potion.nightVision=الرؤيه الليله +potion.hunger=الجوع +potion.weakness=الضعف +potion.poison=السب +potion.wither=سحر +potion.healthBoost=مقوي الصحه +potion.absorption=Absorption +potion.saturation=مفقد الوعي + +commands.generic.exception=خطا غير معروف حدث عندما تم تشغيل هذا الامر +commands.generic.permission=لا توجد اي صلاحيه لك تمكنك من فعل هذا الامر +commands.generic.ingame=تستطيع فعل هذا الامر كلاعب فقط +commands.generic.unknown=امر غير معروف. جرب كتابة /help لرؤية الاوامر الموجوده +commands.generic.player.notFound=هذا اللاعب غير قابل للوجود +commands.generic.usage=الاستعمال:{%0} + +commands.time.added=اضاف {%0} الى الوقت +commands.time.set=وضع الوقت الى{%0} +commands.time.query=الوقت الان{%0} + +commands.me.usage=/me <الفعل ...> + +commands.give.item.notFound=لا يوجد وقت بهذا الشكل{%0} +commands.give.success=Given {%0} * {%1} الى {%2} +commands.give.tagError=فشل وضع الداتا: {%0} + +commands.effect.usage=/effect <اللاعب> <التاثير> [الثواني] [التعويذه] [اخفاء الـ بارتيكيلز] او /effect <الاعب> مسح +commands.effect.notFound=لا يوجد كائن بهذا المعرف {%0} +commands.effect.success=اعطى {%0} (ID {%1}) * {%2} to {%3} لـ {%4} ثواني +commands.effect.success.removed=اخذ {%0} من {%1} +commands.effect.success.removed.all=اخذ جميع التعويذات من {%0} +commands.effect.failure.notActive=لم يستطع اخذ {%0} from {%1} لانه لا يملك اي نوع من هذه التعويذات +commands.effect.failure.notActive.all=لم يستطع اخذ {%0} لانه لا يملك اي واحد منها + +commands.enchant.noItem=هذا المحدد لايحمل اي شيء +commands.enchant.notFound=لا يوجد اي سحر بهذا المعرف {%0} +commands.enchant.success=تم السحر +commands.enchant.usage=/enchant <اللاعب> <السحر > [المستوى] +commands.particle.success=يعمل التعويذه {%0} لـ {%1} الاوقات +commands.particle.notFound=اسم غير معروف {%0} +commands.players.usage=/list لرؤية الاعبين الموجودن حاليا +commands.players.list=هنالك {%0}/{%1} لاعب متصل: +commands.kill.successful=قتل {%0} +commands.kill.all.successful=قتل جميع الاعبين +commands.kill.entities.successful=قتل جميع الاشياء +commands.banlist.ips=هنالك {%0} محظورون بمعارفهم: +commands.banlist.players=هنلك {%0} لاعبون محظورون: +commands.banlist.usage=/banlist [المعارف|اللاعبون] +commands.defaultgamemode.usage=/defaultgamemode <الطور> +commands.defaultgamemode.success=طور العالم الرئيسي الحالي الان هو{%0} + +commands.op.success=الافضليه {%0} +commands.op.usage=/op <الاعب> + +commands.deop.success=اخذ الافضليه من {%0} +commands.deop.usage=/deop <الاعب> + +commands.say.usage=/say <الرساله ...> + +commands.seed.usage=/seed +commands.seed.success=Seed: {%0} + +commands.ban.success=حظر الاعب{%0} +commands.ban.usage=/ban <الاسم> [السبب ...] + +commands.unban.success=فك الحظر {%0} +commands.unban.usage=/pardon <الاسم> + +commands.banip.invalid=لقد ادخلت معرف غير معروف, او هو غير موجود بالاصل +commands.banip.offline.invalid=لا يوجد ايـ IP بهذا الاسم, او انه غير موجود بالاصل +commands.banip.success=حظر IP ADDRESS{%0} +commands.banip.success.players=حظر الـ IP {%0} لـ {%1} +commands.banip.usage=/ban-ip <الاسم|الاسم> [السبب ...] + +commands.unbanip.invalid=لقد ادخلت IP غير معروف +commands.unbanip.success=فك حظر IP ADDRESS {%0} +commands.unbanip.usage=/pardon-ip

    + +commands.save.usage=/save [on|off|hold|resume] +commands.save.enabled=حافظ العالم الاوتوماتيكي شغل +commands.save.disabled=حافظ العالم الاوتوماتيكي اطفئ +commands.save.start=قيد الحفظ... +commands.save.success=تم حفظ العالم + +commands.stop.usage=/stop +commands.stop.start=اطفاء السيرفر + +commands.kick.success=طرد {%0} من اللعبه +commands.kick.success.reason=طرد {%0} من اللعبه بسبب: '{%1}' +commands.kick.usage=/kick <اللاعب> [السبب ...] + +commands.tp.success=نقل {%0} الى {%1} +commands.tp.success.coordinates=نقل {%0} الى {%1}, {%2}, {%3} +commands.tp.usage=/tp [اللاعب المحدد] <بعد الاعب> OR /tp [اللاعب المحدد] [ ] + +commands.whitelist.list=هنالك {%0} (من {%1} نظر) :في اللائحه البيضاء +commands.whitelist.enabled=اللائحه البيضاء اشتغلت +commands.whitelist.disabled=اللائحه البيضاء اطفئت +commands.whitelist.reloaded=اعاد تشغيل اللائحه البيضاء +commands.whitelist.add.success=اضاف {%0} الى الائحه البيضاء +commands.whitelist.add.usage=/whitelist ضيف <الاعب> +commands.whitelist.remove.success=ازال {%0} من اللائحه البيضاء +commands.whitelist.remove.usage=/whitelist ازال <اللاعب> +commands.whitelist.usage=/whitelist + +commands.gamemode.success.self=جعلت طور لعبك الى {%0} +commands.gamemode.success.other=وضع {%0} طور لعبه الى{%1} +commands.gamemode.usage=/gamemode <الطور> [اللاعب] +commands.help.header=--- اظهار لائحه المساعده {%0} من {%1} (/help <صفحه>) --- +commands.help.usage=/help [page|command name] +commands.message.usage=/tell <اللاعب <الرساله الخاصه...> +commands.message.sameTarget=لا تستطيع ارسال رساله خاصه لنفسك! + +commands.difficulty.usage=/difficulty <الصعوبه> +commands.difficulty.success=وضع الصعوبه الى {%0} + +commands.spawnpoint.usage=/spawnpoint [player] [ ] +commands.spawnpoint.success=Set {%0}'s spawn point to ({%1}, {%2}, {%3}) +commands.setworldspawn.usage=/setworldspawn [ ] +commands.setworldspawn.success=Set the world spawn point to ({%0}, {%1}, {%2}) +commands.weather.clear=وضع الطقس الى صافي +commands.weather.rain=وضع الطقس الى ممطر +commands.weather.thunder=وضع الطقس الى ممطر و مرعد +commands.weather.usage=/weather [duration in seconds] +commands.xp.success=اعطى {%0} نقاط الخبره الى {%1} +commands.xp.success.levels=Given {%0} levels to {%1} +commands.xp.success.levels.minus=Taken {%0} levels from {%1} +commands.xp.usage=/xp [player] OR /xp L [player] +# -------------------- Nukkit language files, only for console -------------------- +nukkit.data.playerNotFound=Player data not found for "{%0}", creating new profile +nukkit.data.playerCorrupted=Corrupted data found for "{%0}", creating new profile +nukkit.data.playerOld=Old Player data found for "{%0}", upgrading profile +nukkit.data.saveError=Could not save player "{%0}": {%1} +nukkit.level.notFound=Level "{%0}" not found +nukkit.level.loadError=Could not load level "{%0}": {%1} +nukkit.level.generationError=Could not generate level "{%0}": {%1} +nukkit.level.tickError=Could not tick level "{%0}": {%1} +nukkit.level.chunkUnloadError=Error while unloading a chunk: {%0} +nukkit.level.backgroundGeneration=Spawn terrain for level "{%0}" is being generated in the background +nukkit.level.defaultError=No default level has been loaded +nukkit.level.preparing=Preparing level "{%0}" +nukkit.level.unloading=Unloading level "{%0}" +nukkit.level.updating=Old level data found for "{%0}", converting format +nukkit.server.start=Starting Minecraft: PE server version (ترجم من قبل : بايت - BITE){%0} +nukkit.server.networkError=[Network] Stopped interface {%0} due to {%1} +nukkit.server.networkStart=Opening server on {%0}:{%1} +nukkit.server.info=This server is running {%0} version {%1} "{%2}" (API {%3}) +nukkit.server.info.extended=This server is running {%0} {%1} 「{%2}」 implementing API version {%3} for Minecraft: PE {%4} (protocol version {%5}) +nukkit.server.license={%0} is distributed under the LGPL License +nukkit.server.tickOverload=Can't keep up! Is the server overloaded? +nukkit.server.startFinished=Done ({%0}s)! For help, type "help" or "?" +nukkit.server.defaultGameMode=Default game type: {%0} +nukkit.server.query.start=Starting GS4 status listener +nukkit.server.query.info=Setting query port to {%0} +nukkit.server.query.running=Query is running on {%0}:{%1} +nukkit.server.rcon.emptyPasswordError=Failed to start RCON: password is empty +nukkit.server.rcon.startupError=Failed to start RCON: {%0} +nukkit.server.rcon.running=RCON is running on {%0}:{%1} + +nukkit.command.alias.illegal=Could not register alias {%0} because it contains illegal characters +nukkit.command.alias.notFound=Could not register alias {%0} because it contains commands that do not exist: {%1} +nukkit.command.exception=Unhandled exception executing command '{%0}' in {%1}: {%2} + +nukkit.command.plugins.description=Gets a list of plugins running on the server +nukkit.command.plugins.success=Plugins ({%0}): {%1} +nukkit.command.plugins.usage=/plugins + +nukkit.command.reload.description=Reloads the server configuration and plugins +nukkit.command.reload.usage=/reload +nukkit.command.reload.reloading=Reloading server... +nukkit.command.reload.reloaded=Reload complete. + +nukkit.command.status.description=Reads back the server's performance. +nukkit.command.status.usage=/status +nukkit.command.gc.description=Fires garbage collection tasks +nukkit.command.gc.usage=/gc +nukkit.command.title.description=Sends a title to the specified player or modifies title settings for that player +nukkit.command.title.usage=/title OR /title OR /title <player> <times> <fade in time> <stay time> <fade out time> +nukkit.command.title.clear=Successfully cleared {%0}'s screen +nukkit.command.title.reset=Successfully reset title animation settings for {%0} +nukkit.command.title.title=Successfully shown "{%0}" title to {%1} +nukkit.command.title.subtitle=Successfully set subtitle to "{%0}" for {%1}'s next title +nukkit.command.title.actionbar=Successfully shown "{%0}" actionbar title to {%1} +nukkit.command.title.times.success=Successfully set title animation times to {%0}, {%1}, {%2} for {%3} +nukkit.command.title.times.fail=Times of title animations must be numeric values +nukkit.command.version.description=Gets the version of this server including any plugins in use +nukkit.command.version.usage=/version [plugin name] +nukkit.command.version.noSuchPlugin=This server is not running any plugin by that name. Use /plugins to get a list of plugins. +nukkit.command.give.description=Gives the specified player a certain amount of items +nukkit.command.give.usage=/give <player> <item[:damage]> [amount] [tags...] +nukkit.command.kill.description=Commit suicide or kill other players +nukkit.command.kill.usage=/kill [player] +nukkit.command.particle.description=Adds particles to a world +nukkit.command.particle.usage=/particle <name> <x> <y> <z> <xd> <yd> <zd> [count] [data] +nukkit.command.time.description=Changes the time on each world +nukkit.command.time.usage=/time <set|add> <value> OR /time <start|stop|query> +nukkit.command.ban.player.description=Prevents the specified player from using this server +nukkit.command.ban.ip.description=Prevents the specified IP address from using this server +nukkit.command.banlist.description=View all players banned from this server +nukkit.command.defaultgamemode.description=Set the default gamemode +nukkit.command.deop.description=Takes the specified player's operator status +nukkit.command.difficulty.description=Sets the game difficulty +nukkit.command.enchant.description=Adds enchantments on items +nukkit.command.effect.description=Adds/Removes effects on players +nukkit.command.gamemode.description=Changes the player to a specific game mode +nukkit.command.help.description=Shows the help menu +nukkit.command.kick.description=Removes the specified player from the server +nukkit.command.list.description=Lists all online players +nukkit.command.me.description=Performs the specified action in chat +nukkit.command.op.description=Gives the specified player operator status +nukkit.command.unban.player.description=Allows the specified player to use this server +nukkit.command.unban.ip.description=Allows the specified IP address to use this server +nukkit.command.save.description=Saves the server to disk + +nukkit.command.say.description=Broadcasts the given message as the sender +nukkit.command.seed.description=Shows the world seed +nukkit.command.setworldspawn.description=Sets a worlds's spawn point. If no coordinates are specified, the player's coordinates will be used. +nukkit.command.spawnpoint.description=Sets a player's spawn point +nukkit.command.stop.description=Stops the server +nukkit.command.tp.description=Teleports the given player (or yourself) to another player or coordinates +nukkit.command.tell.description=Sends a private message to the given player +nukkit.command.weather.description=Sets the weather in current world +nukkit.command.xp.description=Gives the specified player a certain amount of experience +nukkit.command.whitelist.description=Manages the list of players allowed to use this server +nukkit.crash.create=An unrecoverable error has occurred and the server has crashed. Creating a crash dump +nukkit.crash.error=Could not create crash dump: {%0} +nukkit.crash.submit=Please upload the "{%0}" file to the Crash Archive and submit the link to the Bug Reporting page. Give as much info as you can. +nukkit.crash.archive=The crash dump has been automatically submitted to the Crash Archive. You can view it on {%0} or use the ID #{%1}. +nukkit.debug.enable=LevelDB support enabled +nukkit.bugreport.create=An error has been detected, creating a bug report. +nukkit.bugreport.error=Could not create bug report: {%0} +nukkit.bugreport.archive=A bug report has been created: {%0} +nukkit.player.invalidMove={%0} moved wrongly! +nukkit.player.logIn={%0}[/{%1}:{%2}] logged in with entity id {%3} at ({%4}, {%5}, {%6}, {%7}) +nukkit.player.logOut={%0}[/{%1}:{%2}] logged out due to {%3} +nukkit.player.invalidEntity={%0} tried to attack an invalid entity +nukkit.plugin.load=Loading {%0} +nukkit.plugin.enable=Enabling {%0} +nukkit.plugin.disable=Disabling {%0} +nukkit.plugin.restrictedName=Restricted name +nukkit.plugin.incompatibleAPI=Incompatible API version +nukkit.plugin.unknownDependency=Unknown dependency +nukkit.plugin.circularDependency=Circular dependency detected +nukkit.plugin.genericLoadError=Could not load plugin '{%0}' +nukkit.plugin.spacesDiscouraged=Plugin '{%0}' uses spaces in its name, this is discouraged +nukkit.plugin.loadError=Could not load plugin '{%0}': {%1} +nukkit.plugin.duplicateError=Could not load plugin '{%0}': plugin exists +nukkit.plugin.fileError=Could not load '{%0}' in folder '{%1}': {%2} +nukkit.plugin.commandError=Could not load command {%0} for plugin {%1} +nukkit.plugin.aliasError=Could not load alias {%0} for plugin {%1} +nukkit.plugin.deprecatedEvent=Plugin '{%0}' has registered a listener for '{%1}' on method '{%2}', but the event is Deprecated. +nukkit.plugin.eventError=Could not pass event '{%0}' to '{%1}': {%2} on {%3} +nukkit.resources.invalid-path=Resource packs path '{%0}' exists and is not a directory +nukkit.resources.unknown-format=Could not load '{%0}' due to format not recognized +nukkit.resources.fail=Could not load '{%0}': {%1} +nukkit.resources.success=Successfully loaded {%0} resource packs +nukkit.resources.zip.not-found=File '{%0}' is not found +nukkit.resources.zip.no-manifest='manifest.json' is not found +nukkit.resources.zip.invalid-manifest='manifest.json' is invalid or incomplete +nukkit.resources.plugin.loading=Loading resource pack from plugin {%0} diff --git a/src/main/resources/lang/ara/nukkit.yml b/src/main/resources/lang/ara/nukkit.yml new file mode 100644 index 00000000000..164795a7179 --- /dev/null +++ b/src/main/resources/lang/ara/nukkit.yml @@ -0,0 +1,91 @@ +# Advanced configuration file for Nukkit +# Some of these settings are safe, others can break your server if modified incorrectly +# New settings/defaults won't appear automatically on this file when upgrading + +settings: + #Multi-language setting + #Available: eng, chs, cht, jpn, rus, spa, pol, bra, kor, ukr, deu, ltu + language: "ara" + #Whether to send all strings translated to server locale or let the device handle them + force-language: false + shutdown-message: "تم ايقاف الخادم" + #Allow listing plugins via Query + query-plugins: true + #Show a console message when a plugin uses deprecated API methods + deprecated-verbose: true + #Number of AsyncTask workers + #If set to auto, it'll try to detect the number of cores (and at least 4) + async-workers: auto + +network: + #Threshold for batching packets, in bytes. Only these packets will be compressed + #Set to 0 to compress everything, -1 to disable + batch-threshold: 256 + #Compression level used of Zlib when sending batched packets. Higher = more CPU, less bandwidth usage + compression-level: 5 + #Enable network encryption + encryption: true + +debug: + #If > 1, it will show debug messages in the console + level: 1 + +level-settings: + #The default format that levels will use when created + default-format: leveldb + #Automatically change levels tick rate to maintain 20 ticks per second + auto-tick-rate: true + auto-tick-rate-limit: 20 + #Sets the base tick rate (1 = 20 ticks per second, 2 = 10 ticks per second, etc.) + base-tick-rate: 1 + #Tick all players each tick even when other settings disallow this + always-tick-players: false + +chunk-sending: + #Amount of chunks sent to players per tick + per-tick: 4 + #Amount of chunks that need to be sent before spawning the player + spawn-threshold: 56 + #Save a serialized copy of the chunk in memory for faster sending + #Useful in mostly-static worlds where lots of players join at the same time + cache-chunks: false + +chunk-ticking: + #Max amount of chunks processed each tick + per-tick: 40 + #Radius of chunks around a player to tick + tick-radius: 3 + clear-tick-list: false + +chunk-generation: + #Max. amount of chunks in the waiting queue to be generated + queue-size: 8 + #Max. amount of chunks in the waiting queue to be populated + population-queue-size: 8 + +leveldb: + #Use native LevelDB implementation for better performance + use-native: false + #Set LevelDB memory cache size + cache-size-mb: 80 + +ticks-per: + autosave: 6000 + +player: + #If true, player data will be saved as players/playername.dat + #If false, nukkit won't save player data as "dat" files, in order that plugins can do something on it. + save-player-data: true + +aliases: + #Aliases for commands + #Examples: + #showtheversion: version + #savestop: [save-all, stop] + +worlds: + #These settings will override the generator set in server.properties and allows loading multiple levels + #Example: + #world: + # seed: 404 + # generator: FLAT:2;7,59x1,3x3,2;1;decoration(treecount=80 grasscount=45) \ No newline at end of file diff --git a/src/main/resources/lang/bra/lang.ini b/src/main/resources/lang/bra/lang.ini new file mode 100644 index 00000000000..be8d745cc0a --- /dev/null +++ b/src/main/resources/lang/bra/lang.ini @@ -0,0 +1,363 @@ +# Arquivo de linguagem compatível com os identificadores do Minecraft: Bedrock Edition +# +# A mensagem não precisa estar aqui para ser mostrada corretamente no cliente. +# Somente as mensagens mostradas no Nukkit devem estar aqui +# Usando o sistema de linguagens do PocketMine-MP +# +# Traduzido pelo MrPowerGamerBR (mrpowergamerbr.com) + +language.name=Português +language.selected=Selecionado {%0} ({%1}) como a linguagem base + +multiplayer.player.joined={%0} entrou no jogo +multiplayer.player.left={%0} saiu do jogo + +chat.type.text=<{%0}> {%1} +chat.type.emote=* {%0} {%1} +chat.type.announcement=[{%0}] {%1} +chat.type.admin=[{%0}: {%1}] +chat.type.achievement={%0} adquiriu a conquista {%1} + +disconnectionScreen.outdatedClient=Cliente desatualizado! +disconnectionScreen.outdatedServer=Servidor desatualizado! +disconnectionScreen.serverFull=O servidor está cheio! +disconnectionScreen.noReason=Você foi desconectado +disconnectionScreen.invalidSkin=Skin inválida! +disconnectionScreen.invalidName=Nome inválido! +disconnectionScreen.resourcePack=Encountered a problem while downloading or applying resource pack. + +death.fell.accident.generic={%0} caiu de um lugar alto +death.attack.inFire={%0} pegou fogo +death.attack.onFire={%0} queimou até a morte +death.attack.lava={%0} tentou nadar na lava +death.attack.lava.magma={%0} discovered floor was lava +death.attack.inWall={%0} sufocou-se em uma parede +death.attack.drown={%0} morreu afogado(a) +death.attack.cactus={%0} foi espetado(a) até a morte +death.attack.generic={%0} morreu +death.attack.explosion={%0} explodiu +death.attack.explosion.player={%0} foi explodido(a) por {%1} +death.attack.magic={%0} foi morto(a) por magia +death.attack.wither={%0} apodreceu +death.attack.mob={%0} foi morto(a) por {%1} +death.attack.player={%0} foi morto(a) por {%1} +death.attack.player.item={%0} foi morto(a) por {%1} usando {%2} +death.attack.arrow={%0} foi atingido(a) por {%1} +death.attack.arrow.item={%0} foi atingido(a) por {%1} usando {%2} +death.attack.fall={%0} caiu no chão com muita força +death.attack.outOfWorld={%0} caiu para fora do mundo +death.attack.starve={%0} starved to death + +gameMode.survival=Modo Sobrevivência +gameMode.creative=Modo Criativo +gameMode.adventure=Modo Aventura +gameMode.spectator=Modo Espectador +gameMode.changed=Seu modo de jogo foi atualizado + +potion.moveSpeed=Velocidade +potion.moveSlowdown=Lentidão +potion.digSpeed=Pressa +potion.digSlowDown=Cansaço +potion.damageBoost=Força +potion.heal=Vida Instantânea +potion.harm=Dano Instantâneo +potion.jump=Super Pulo +potion.confusion=Náusea +potion.regeneration=Regeneração +potion.resistance=Resistência +potion.fireResistance=Resistência ao Fogo +potion.waterBreathing=Respiração Aquática +potion.invisibility=Invisibilidade +potion.blindness=Cegueira +potion.nightVision=Visão Noturna +potion.hunger=Fome +potion.weakness=Fraqueza +potion.poison=Veneno +potion.wither=Wither +potion.healthBoost=Vida Extra +potion.absorption=Absorção +potion.saturation=Saturação + +commands.generic.exception=Um erro ocorreu ao tentar realizar este comando +commands.generic.permission=Você não tem permissão para usar este comando +commands.generic.ingame=Você só pode usar este comando como um player +commands.generic.unknown=Comando desconhecido. Tente /help para uma lista de comandos +commands.generic.player.notFound=Esse(a) jogador(a) não pôde ser encontrado(a) +commands.generic.usage=Uso: {%0} + +commands.time.added=Adicionado {%0} ao tempo +commands.time.set=Tempo mudado para {%0} +commands.time.query=O tempo é {%0} + +commands.me.usage=/me <ação ...> + +commands.give.item.notFound=Não há nenhum item com o nome: {%0} +commands.give.success=Dado {%0} * {%1} para {%2} +commands.give.tagError=Análise da tag de dados falhou: {%0} + +commands.effect.usage=/effect <jogador> <efeito> [segundos] [amplificador] [esconderPartículas] OU /effect <jogador> clear +commands.effect.notFound=Não há nenhum efeito de monstro com o ID {%0} +commands.effect.success=Dado {%0} (ID {%1}) * {%2} para {%3} por {%4} segundos +commands.effect.success.removed=Retirado {%0} de {%1} +commands.effect.success.removed.all=Todos os efeitos de {%0} foram removidos +commands.effect.failure.notActive=Não foi possível retirar {%0} de {%1} pois este não possui o efeito +commands.effect.failure.notActive.all=Nenhum efeito pôde ser removido de {%0} já que ele(a) não tem nenhum + +commands.enchant.noItem=O alvo não está segurando um item +commands.enchant.notFound=Não há um encantamento com o ID {%0} +commands.enchant.success=Encantado com sucesso +commands.enchant.usage=/enchant <jogador> <ID do encantamento> [nível] + +commands.particle.success=Reproduzindo efeito {%0} por {%1} vezes +commands.particle.notFound=Nome do efeito desconhecido {%0} + +commands.players.usage=/list +commands.players.list=Existem {%0}/{%1} jogadores(as) online: + +commands.kill.successful=Eliminado(a) {%0} +commands.kill.all.successful=Eliminou todos os jogadores +commands.kill.entities.successful=Eliminou todas as entidades + +commands.banlist.ips=Existem {%0} endereços de IP banidos no total: +commands.banlist.players=Existem {%0} jogadores(as) banidos(as) no total: +commands.banlist.usage=/banlist [ips|players] + +commands.defaultgamemode.usage=/defaultgamemode <modo> +commands.defaultgamemode.success=O modo de jogo padrão do mundo agora é {%0} + +commands.op.success={%0} virou operador(a) +commands.op.usage=/op <jogador> + +commands.deop.success={%0} não é mais operador(a) +commands.deop.usage=/deop <jogador> + +commands.say.usage=/say <mensagem ...> + +commands.seed.usage=/seed +commands.seed.success=Seed: {%0} + +commands.ban.success={%0} foi banido(a) +commands.ban.usage=/ban <nome> [razão ...] + +commands.unban.success={%0} foi desbanido(a) +commands.unban.usage=/pardon <nome> + +commands.banip.invalid=Você digitou um IP inválido ou um(a) jogador(a) que não está online. +commands.banip.offline.invalid=Não existe este IP na data dos players ou o IP é inválido +commands.banip.success=Endereço IP banido {%0} +commands.banip.success.players=Endereço IP banido {%0} pertencente a {%1} +commands.banip.usage=/ban-ip <address|nome> [razão ...] + +commands.unbanip.invalid=Você digitou um IP inválido +commands.unbanip.success=IP desbanido: {%0} +commands.unbanip.usage=/pardon-ip <ip> + +commands.save.usage=/save [on|off|hold|resume] +commands.save.enabled=Salvamento automático ligado +commands.save.disabled=Salvamento automático desligado +commands.save.start=Salvando... +commands.save.success=Mundo salvo + +commands.stop.usage=/stop +commands.stop.start=Parando o servidor + +commands.kick.success={%0} foi expulso(a) do jogo +commands.kick.success.reason={%0} foi expulso(a) do jogo. Motivo: '{%1}' +commands.kick.usage=/kick <jogador> [motivo ...] + +commands.tp.success={%0} teletransportado(a) para {%1} +commands.tp.success.coordinates=Teletransportado(a) {%0} para {%1}, {%2}, {%3} +commands.tp.usage=/tp [jogador alvo] <jogador de destino> OU /tp [jogador alvo] <x> <y> <z> [<rot-x> <rot-y>] + +commands.whitelist.list=Existem {%0} (de {%1} vistos) jogadores(as) na whitelist: +commands.whitelist.enabled=Whitelist ligada +commands.whitelist.disabled=Whitelist desligada +commands.whitelist.reloaded=Whitelist recarregada +commands.whitelist.add.success={%0} foi adicionado(a) à whitelist +commands.whitelist.add.usage=/whitelist add <jogador> +commands.whitelist.remove.success={%0} foi removido(a) da whitelist +commands.whitelist.remove.usage=/whitelist remove <jogador> +commands.whitelist.usage=/whitelist <on|off|list|add|remove|reload> + +commands.gamemode.success.self=Mudado o próprio modo de jogo para {%0} +commands.gamemode.success.other=Mudado o modo de jogo de {%0} para {%1} +commands.gamemode.usage=/gamemode <modo> [jogador] + +commands.help.header=--- Mostrando página {%0} de {%1} (/help <página>) --- +commands.help.usage=/help [página|nome do comando] + +commands.message.usage=/tell <jogador> <mensagem privada ...> +commands.message.sameTarget=Você não pode enviar uma mensagem privada para si mesmo! + +commands.difficulty.usage=/difficulty <nova dificuldade> +commands.difficulty.success=Dificuldade do jogo modificada para %s + +commands.spawnpoint.usage=/spawnpoint [jogador] [<x> <y> <z>] +commands.spawnpoint.success=Local de renascimento de {%0} definido para ({%1}, {%2}, {%3}) + +commands.setworldspawn.usage=/setworldspawn [<x> <y> <z>] +commands.setworldspawn.success=Ponto de renascimento do mundo definido para ({%0}, {%1}, {%2}) + +commands.weather.clear=Mudando para tempo limpo +commands.weather.rain=Mudando para tempo chuvoso +commands.weather.thunder=Mudando para chuva e trovões +commands.weather.usage=/weather <clear|rain|thunder> [duração em segundos] + +commands.xp.success=Given {%0} experience to {%1} +commands.xp.success.levels=Given {%0} levels to {%1} +commands.xp.success.levels.minus=Taken {%0} levels from {%1} +commands.xp.usage=/xp <amount> [player] OR /xp <level>L [player] + +# -------------------- Nukkit language files, only for console -------------------- + +nukkit.data.playerNotFound=Data não encontrada do player "{%0}", criando novo perfil +nukkit.data.playerCorrupted=Data corrompida do player "{%0}" encontrada, criando novo perfil +nukkit.data.playerOld=Data antiga do player "{%0}" encontrada, atualizando perfil +nukkit.data.saveError=Não foi possível salvar o player "{%0}": {%1} + +nukkit.level.notFound=Mundo "{%0}" não encontrado +nukkit.level.loadError=Não foi possível carregar o mundo "{%0}": {%1} +nukkit.level.generationError=Não foi possível gerar o mundo "{%0}": {%1} +nukkit.level.tickError=Não foi possível fazer tick no mundo "{%0}": {%1} +nukkit.level.chunkUnloadError=Erro ao descarregar o chunk: {%0} +nukkit.level.backgroundGeneration=Spawn do terreno para o nível "{%0}" está sendo gerado em segundo plano +nukkit.level.defaultError=Nenhum mundo padrão foi carregado +nukkit.level.preparing=Preparando mundo "{%0}" +nukkit.level.unloading=Descarregando mundo "{%0}" +nukkit.level.updating=Old level data found for "{%0}", converting format + +nukkit.server.start=Iniciando Servidor de Minecraft: BE, versão {%0} +nukkit.server.networkError=[Rede] Interface finalizada em {%0} devido a {%1} +nukkit.server.networkStart=Abrindo servidor em {%0}:{%1} +nukkit.server.info=Este servidor está rodando {%0} versão {%1} "{%2}" (API {%3}) +nukkit.server.info.extended=Este servidor está rodando {%0} {%1} 「{%2}」 implementando versão da API {%3} para Minecraft: BE {%4} (versão do protocolo {%5}) +nukkit.server.license={%0} é distribuido com a licença GPL +nukkit.server.tickOverload=Não foi possível aguentar! Será que o servidor está sobrecarregado? +nukkit.server.startFinished=Finalizado ({%0}s)! Para ver a ajuda, escreva "help" ou "?" +nukkit.server.defaultGameMode=Modo de jogo padrão: {%0} +nukkit.server.query.start=Iniciando listener de status GS4 +nukkit.server.query.info=Porta de query está ativada em {%0} +nukkit.server.query.running=Query rodando em {%0}:{%1} +nukkit.server.rcon.emptyPasswordError=Failed to start RCON: password is empty +nukkit.server.rcon.startupError=Failed to start RCON: {%0} +nukkit.server.rcon.running=RCON is running on {%0}:{%1} + +nukkit.command.alias.illegal=Não foi possível registrar a alias {%0} porque ela contém caracteres ilegais. +nukkit.command.alias.notFound=Não foi possível registrar a alias {%0} porque ela contém comandos que não existem: {%1} +nukkit.command.exception=Exceção não tratada ao executando comando "{%0}" em {%1}: {%2} + +nukkit.command.plugins.description=Pega uma lista de plugins rodando no servidor +nukkit.command.plugins.success=Plugins ({%0}): {%1} +nukkit.command.plugins.usage=/plugins + +nukkit.command.reload.description=Recarrega a configuração do servidor e os plugins +nukkit.command.reload.usage=/reload +nukkit.command.reload.reloading=Recarregando server... +nukkit.command.reload.reloaded=Recarregamento completo. + +nukkit.command.status.description=Mostra a performance do servidor. +nukkit.command.status.usage=/status + +nukkit.command.gc.description=Ativa o garbage collection +nukkit.command.gc.usage=/gc + +nukkit.command.title.description=Sends a title to the specified player or modifies title settings for that player +nukkit.command.title.usage=/title <player> <clear|reset> OR /title <player> <title|subtitle|actionbar> <title text> OR /title <player> <times> <fade in time> <stay time> <fade out time> +nukkit.command.title.clear=Successfully cleared {%0}'s screen +nukkit.command.title.reset=Successfully reset title animation settings for {%0} +nukkit.command.title.title=Successfully shown "{%0}" title to {%1} +nukkit.command.title.subtitle=Successfully set subtitle to "{%0}" for {%1}'s next title +nukkit.command.title.actionbar=Successfully shown "{%0}" actionbar title to {%1} +nukkit.command.title.times.success=Successfully set title animation times to {%0}, {%1}, {%2} for {%3} +nukkit.command.title.times.fail=Times of title animations must be numeric values + +nukkit.command.version.description=Pega a versão deste servidor incluindo todos os plugins em uso +nukkit.command.version.usage=/version [nome do plugin] +nukkit.command.version.noSuchPlugin=Este servidor não está usando nenhum plugin com este nome. Use /plugins para ver a lista de plugins. + +nukkit.command.give.description=Dá ao player especificado uma certa quantidade de itens +nukkit.command.give.usage=/give <jogador> <item[:damage]> [quantidade] [tags ...] + +nukkit.command.kill.description=Comite suicídio ou mata outros players +nukkit.command.kill.usage=/kill [jogador] + +nukkit.command.particle.description=Adiciona partículas a um mundo +nukkit.command.particle.usage=/particle <nome> <x> <y> <z> <xd> <yd> <zd> [quantidade] [data] + +nukkit.command.time.description=Altera o tempo em todos os mundos +nukkit.command.time.usage=/time <alterar|adicionar> <value> OU /time <iniciar|parar|ver> + +nukkit.command.gamerule.description=Define ou questiona um valor da regra de jogo +nukkit.command.gamerule.usage=/gamerule <rule> [value] + +nukkit.command.ban.player.description=Bloqueia o player especificado de usar este servidor +nukkit.command.ban.ip.description=Bloqueia o IP especificado de usar este servidor +nukkit.command.banlist.description=Ver todos os jogadores banidos deste servidor +nukkit.command.defaultgamemode.description=Altera o modo de jogo padrão +nukkit.command.deop.description=Remove o status de operador do player especificado +nukkit.command.difficulty.description=Altera a dificuldade do jogo +nukkit.command.enchant.description=Adiciona encantamento nos itens +nukkit.command.effect.description=Adiciona/Remove efeitos nos players +nukkit.command.gamemode.description=Altera o player para um tipo de jogo específico +nukkit.command.help.description=Mostra o menu de ajuda +nukkit.command.kick.description=Remove o player especificado do servidor +nukkit.command.list.description=Mostra todos os players online +nukkit.command.me.description=Performa a ação específica no chat +nukkit.command.op.description=Dá o player especificado o status de operador +nukkit.command.unban.player.description=Permite o jogador especificado usar este servidor +nukkit.command.unban.ip.description=Permite o IP especificado usar este servidor +nukkit.command.save.description=Salva o servidor para o disco +nukkit.command.saveoff.description=Desativa o auto-salvamento do servidor +nukkit.command.saveon.description=Ativa o auto-salvamento do servidor +nukkit.command.say.description=Envia uma mensagem específica utilizando o enviador +nukkit.command.seed.description=Mostra a seed do mundo +nukkit.command.setworldspawn.description=Marca o spawn de um mundo. Se nenhuma coordenada está especificada, as coordenadas do player serão utilizadas. +nukkit.command.spawnpoint.description=Marca o spawn de um player +nukkit.command.stop.description=Fecha o servidor +nukkit.command.tp.description=Teletransporta o player especificado (ou você) para outro player ou coordenadas +nukkit.command.tell.description=Envia uma mensagem privada para o player +nukkit.command.weather.description=Altera o tempo no mundo atual +nukkit.command.xp.description=Gives the specified player a certain amount of experience +nukkit.command.whitelist.description=Administra a lista de players que podem usar este servidor + +nukkit.crash.create=Um erro irrecuperável ocorreu e o servidor travou. Criando um arquivo de erro +nukkit.crash.error=Não foi possível criar o arquivo de erros: {%0} +nukkit.crash.submit=Por favor envie o arquivo "{%0}" para o arquivo de erros e envie o link para a página de bug report. Dê o máximo de informações possíveis +nukkit.crash.archive=O erro já foi automaticamente enviado para os arquivos de erros. Você pode ver no {%0} ou usando o ID #{%1} + +nukkit.debug.enable=Suporte a mundos LevelDB ativado + +nukkit.bugreport.create=An error has been detected, creating a bug report. +nukkit.bugreport.error=Could not create bug report: {%0} +nukkit.bugreport.archive=A bug report has been created: {%0} + +nukkit.player.invalidMove={%0} moveu erradamente! +nukkit.player.logIn={%0}[/{%1}:{%2}] entrou com o id de entidade {%3} em ({%4}, {%5}, {%6}, {%7}) +nukkit.player.logOut={%0}[/{%1}:{%2}] saiu devido a {%3} +nukkit.player.invalidEntity={%0} tentou atacar uma entidade inválida + +nukkit.plugin.load=Carregando {%0} +nukkit.plugin.enable=Ativando {%0} +nukkit.plugin.disable=Desativando {%0} +nukkit.plugin.restrictedName=Nome restrito +nukkit.plugin.incompatibleAPI=Versão da API incompatível +nukkit.plugin.unknownDependency=Dependência desconhecida +nukkit.plugin.circularDependency=Dependência circular detectada +nukkit.plugin.genericLoadError=Não foi possível carregar o plugin "{%0}" +nukkit.plugin.spacesDiscouraged=Plugin "{%0}" usa espaço nos nome, isto é desencorajado +nukkit.plugin.loadError=Não foi possível carregar o plugin "{%0}": {%1} +nukkit.plugin.duplicateError=Não foi possível carregar o plugin "{%0}": plugin já existe +nukkit.plugin.fileError=Não foi possível carregar "{%0}" na pasta "{%1}": {%2} +nukkit.plugin.commandError=Não foi possível carregar o comando {%0} para o plugin {%1} +nukkit.plugin.aliasError=Não foi possível carregar a alias {%0} para o plugin {%1} +nukkit.plugin.deprecatedEvent=Plugin "{%0}" registrou um listener para "{%1}" no método "{%2}", mas o evento é obsoleto. +nukkit.plugin.eventError=Não foi possível passar o evento "{%0}" para "{%1}": {%2} em {%3} + +nukkit.resources.invalid-path=Resource packs path "{%0}" exists and is not a directory +nukkit.resources.unknown-format=Could not load "{%0}" due to format not recognized +nukkit.resources.fail=Could not load "{%0}": {%1} +nukkit.resources.success=Successfully loaded {%0} resource packs +nukkit.resources.zip.not-found=File "{%0}" is not found +nukkit.resources.zip.no-manifest="manifest.json" is not found +nukkit.resources.zip.invalid-manifest="manifest.json" is invalid or incomplete +nukkit.resources.plugin.loading=Loading resource pack from plugin {%0} diff --git a/src/main/resources/lang/bra/nukkit.yml b/src/main/resources/lang/bra/nukkit.yml new file mode 100644 index 00000000000..740a04d726f --- /dev/null +++ b/src/main/resources/lang/bra/nukkit.yml @@ -0,0 +1,98 @@ +# Configurações avançadas para o Nukkit +# Algumas destas configurações são seguras, outras podem destruir o seu servidor caso modificadas incorretamente +# Novas configurações/padrões não irão aparecer neste arquivo ao atualizar. + +settings: + #Configuração de Multi-Linguagem + #Disponível: eng, chs, cht, jpn, rus, spa, pol, bra, kor, ukr, deu, ltu, cze + language: "bra" + #Se é para enviar todos os textos traduzidos para a linguagem do servidor ou se é para o próprio dispositivo traduzir elas + force-language: false + shutdown-message: "Servidor fechado" + #Permitir a listagem dos plugins via query + query-plugins: true + #Mostrar no console uma mensagem quando um plugin usa métodos obsoletos da API + deprecated-verbose: true + #Número de trabalhadores da AsyncTask + #Se marcado como auto, ele irá tentar detectar o número de núcleos (e no mínimo 4) + async-workers: auto + +network: + #Limite de lotes de packets, em bytes. Somente estes packets serão compactados + #Coloque 0 para compactar tudo, -1 para desativar. + batch-threshold: 256 + #Nível de compressão usado pelo Zlib ao enviar packets compactados. Maior = mais uso na CPU, menos bandwidth utilizado. + compression-level: 5 + #Enable network encryption + encryption: true + +debug: + #Se maior de 1, as mensagens para debug irão ser mostradas no console + level: 1 + +level-settings: + #O formato padrão que os mundos irão usar ao serem criados + default-format: leveldb + #Mudar automaticamente o tick rate dos mundos para manter 20 ticks por segundo + auto-tick-rate: true + auto-tick-rate-limit: 20 + #Altera a base do tick rate (1 = 20 ticks por segundos, 2 = 10 ticks por segundo, etc.) + base-tick-rate: 1 + #Fazer tick em todos os players em todos os ticks mesmo quando as outras opções não permitem isto. + always-tick-players: false + +chunk-sending: + #Número de chunks enviados para os players por tick + per-tick: 4 + #Número de chunks que deverão ser enviados antes de spawnar o player + spawn-threshold: 56 + #Salva uma cópia serializada do chunk na memória para enviar mais rapidamente. + #Útil em mundos normalmente estásticos que muitos players entram ao mesmo tempo + cache-chunks: false + +chunk-ticking: + #Máximo número de chunks processados em cada tick + per-tick: 40 + #Raio de chunks em volta do player a ser tickados + tick-radius: 3 + clear-tick-list: false + +chunk-generation: + #Máximo número de chunks na fila de chunks para serem gerados + queue-size: 8 + #Máximo número de chunks na fila de chunks para serem populados + population-queue-size: 8 + +leveldb: + #Use native LevelDB implementation for better performance + use-native: false + #Set LevelDB memory cache size + cache-size-mb: 80 + +ticks-per: + autosave: 6000 + +player: + #If true, player data will be saved as players/playername.dat + #If false, nukkit won't save player data as "dat" files, in order that plugins can do something on it. + save-player-data: true + #The time between skin change action in seconds, set to 0 if you dont want the cooldown + skin-change-cooldown: 15 + +aliases: + #Aliases para comandos + #Exemplos: + #showtheversion: version + #savestop: [save-all, stop] + +worlds: + #Worlds that the server will use. Options are specific to the chosen generator, and may result in broken generation or + #be ignored completely. + world: + #seed: 404 + generator: normal + options: + nether: + #seed: my_cool_nether_seed + generator: nether + options: diff --git a/src/main/resources/lang/chs/lang.ini b/src/main/resources/lang/chs/lang.ini new file mode 100644 index 00000000000..f05fce1a4d5 --- /dev/null +++ b/src/main/resources/lang/chs/lang.ini @@ -0,0 +1,361 @@ +# 与 Minecraft: Bedrock Edition 标识符兼容的语言文件 +# +# 并不是所有消息都需要写在这个文件里才能在客户端上正确显示。 +# 只有 Nukkit 自己的信息需要写在这里 +# 使用 PocketMine-MP 中的语言属性 + +language.name=中文(简体) +language.selected=将 {%0} ({%1}) 设置为基本语言 + +multiplayer.player.joined={%0} 加入了游戏 +multiplayer.player.left={%0} 退出了游戏 + +chat.type.text=<{%0}> {%1} +chat.type.emote=* {%0} {%1} +chat.type.announcement=[{%0}] {%1} +chat.type.admin=[{%0}: {%1}] +chat.type.achievement={%0} 刚刚获得了 {%1} 成就! + +disconnectionScreen.outdatedClient=客户端已过期! +disconnectionScreen.outdatedServer=服务器已过期! +disconnectionScreen.serverFull=服务器已满! +disconnectionScreen.noReason=已断开与服务器的连接 +disconnectionScreen.invalidSkin=无效的皮肤! +disconnectionScreen.invalidName=无效的名称! +disconnectionScreen.resourcePack=下载或应用资源包时出现问题。 + +death.fell.accident.generic={%0} 从高处摔了下来 +death.attack.inFire={%0} 浴火焚身 +death.attack.onFire={%0} 被烧死了 +death.attack.lava={%0} 试图在熔岩里游泳 +death.attack.lava.magma={%0} 发现了地板是熔岩做的 +death.attack.inWall={%0} 在墙里窒息而亡 +death.attack.drown={%0} 淹死了 +death.attack.cactus={%0} 被戳死了 +death.attack.generic={%0} 死了 +death.attack.explosion={%0} 爆炸了 +death.attack.explosion.player={%0} 被 {%1} 炸死了 +death.attack.magic={%0} 被魔法杀死了 +death.attack.wither={%0} 凋零了 +death.attack.mob={%0} 被 {%1} 杀死了 +death.attack.player={%0} 被 {%1} 杀死了 +death.attack.player.item={%0} 被 {%1} 用 {%2} 杀死了 +death.attack.arrow={%0} 被 {%1} 射杀 +death.attack.arrow.item={%0} 被 {%1} 用 {%2} 射杀 +death.attack.fall={%0} 落地过猛 +death.attack.outOfWorld={%0} 掉出了这个世界 +death.attack.starve={%0} 饿死了 + +gameMode.survival=生存模式 +gameMode.creative=创造模式 +gameMode.adventure=冒险模式 +gameMode.spectator=旁观模式 +gameMode.changed=您的游戏模式已更新 + +potion.moveSpeed=速度 +potion.moveSlowdown=缓慢 +potion.digSpeed=急迫 +potion.digSlowDown=挖掘疲劳 +potion.damageBoost=力量 +potion.heal=瞬间治疗 +potion.harm=瞬间伤害 +potion.jump=跳跃提升 +potion.confusion=反胃 +potion.regeneration=生命恢复 +potion.resistance=抗性提升 +potion.fireResistance=防火 +potion.waterBreathing=水下呼吸 +potion.invisibility=隐身 +potion.blindness=失明 +potion.nightVision=夜视 +potion.hunger=饥饿 +potion.weakness=虚弱 +potion.poison=中毒 +potion.wither=凋零 +potion.healthBoost=生命提升 +potion.absorption=伤害吸收 +potion.saturation=饱和 + +commands.generic.exception=试图执行该命令时出现意外错误 +commands.generic.permission=您没有使用此命令的权限 +commands.generic.ingame=您只能作为玩家使用该命令 +commands.generic.notFound=未知的命令。使用 /help 显示命令列表。 +commands.generic.player.notFound=未找到玩家 +commands.generic.usage=用法:{%0} + +commands.time.added=将时间增加了 {%0} +commands.time.set=将时间设为 {%0} +commands.time.query=目前时间为 {%0} + +commands.me.usage=/me <动作 ...> + +commands.give.item.notFound=名为 {%0} 的物品不存在 +commands.give.success=已将 {%1} 个 {%0} 给予 {%2} +commands.give.tagError=物品数据格式错误: {%0} + +commands.effect.usage=/effect <玩家名称> <效果> [秒数] [强度] [隐藏粒子] 或 /effect <玩家名称> clear +commands.effect.notFound=ID 为 {%0} 的效果不存在 +commands.effect.success=已将 {%4} 秒的 {%0} (ID {%1}) * {%2} 效果应用于 {%3} +commands.effect.success.removed=已移除 {%1} 的 {%0} 效果 +commands.effect.success.removed.all=已移除 {%0} 的所有效果 +commands.effect.failure.notActive={%1} 没有 {%0} 效果 +commands.effect.failure.notActive.all= {%0} 没有可以移除的效果 + +commands.enchant.noItem=目标未手持任何物品 +commands.enchant.notFound=ID 为 {%0} 的附魔不存在 +commands.enchant.success=已将魔咒应用于物品上 +commands.enchant.usage=/enchant <玩家名称> <附魔 ID> [等级] + +commands.particle.success=正在显示 {%0} 颗粒 {%1} 次 +commands.particle.notFound=未知的颗粒名称 {%0} + +commands.players.usage=/list +commands.players.list=当前共有 {%0} 名玩家在线 (最大玩家数为 {%1}) : + +commands.kill.successful=已清除 {%0} +commands.kill.all.successful=已清除所有玩家 +commands.kill.entities.successful=已清除所有实体 + +commands.banlist.ips=共有 {%0} 个被封禁的 IP 地址: +commands.banlist.players=共有 {%0} 个被封禁的玩家: +commands.banlist.usage=/banlist [IP 地址|玩家] + +commands.defaultgamemode.usage=/defaultgamemode <模式> +commands.defaultgamemode.success=默认游戏模式现在为 {%0} + +commands.op.success=已将 {%0} 设为服务器管理员 +commands.op.usage=/op <玩家名称> + +commands.deop.success={%0} 不再是服务器管理员了 +commands.deop.usage=/deop <玩家名称> + +commands.say.usage=/say <消息 ...> + +commands.seed.usage=/seed +commands.seed.success=种子:{%0} + +commands.ban.success=已封禁玩家 {%0} +commands.ban.usage=/ban <玩家名称> [原因 ...] + +commands.unban.success=已解封玩家 {%0} +commands.unban.usage=/pardon <玩家名称> + +commands.banip.invalid=IP 地址无效或玩家不在线 +commands.banip.offline.invalid=玩家数据中无 IP 地址或 IP 地址无效 +commands.banip.success=已封禁 IP 地址 {%0} +commands.banip.success.players=已封禁 {%1} 的 IP 地址 {%0} +commands.banip.usage=/ban-ip <IP 地址|玩家名称> [原因 ...] + +commands.unbanip.invalid=无效的 IP 地址 +commands.unbanip.success=已解封 IP 地址 {%0} +commands.unbanip.usage=/pardon-ip <IP 地址> + +commands.save.usage=/save [on|off|hold|resume] +commands.save.enabled=自动保存已启用 +commands.save.disabled=自动保存已禁用 +commands.save.start=正在保存游戏 +commands.save.success=游戏已保存 + +commands.stop.usage=/stop +commands.stop.start=正在关闭服务器 + +commands.kick.success=已将 {%0} 从游戏中踢出 +commands.kick.success.reason={%0} 被踢出游戏,"{%1}" +commands.kick.usage=/kick <玩家名称> [原因 ...] + +commands.tp.success=将 {%0} 传送至 {%1} +commands.tp.success.coordinates=已将 {%0} 传送到 {%1}, {%2}, {%3} +commands.tp.usage=/tp [玩家名称] <目标玩家> 或 /tp [玩家名称] <x> <y> <z> [<y偏转> <x偏转>] + +commands.whitelist.list=白名单中共有 {%0} 名 (全部 {%1} 人) 玩家: +commands.whitelist.enabled=白名单已开启 +commands.whitelist.disabled=白名单已关闭 +commands.whitelist.reloaded=已重新读取白名单 +commands.whitelist.add.success=已将 {%0} 加入白名单 +commands.whitelist.add.usage=/whitelist add <玩家名称> +commands.whitelist.remove.success=已将 {%0} 移出白名单 +commands.whitelist.remove.usage=/whitelist remove <玩家名称> +commands.whitelist.usage=/whitelist <on|off|list|add|remove|reload> + +commands.gamemode.success.self=您的游戏模式已被设置为 {%0} +commands.gamemode.success.other=将 {%0} 的游戏模式修改为 {%1} +commands.gamemode.usage=/gamemode <模式> [玩家名称] + +commands.help.header=--- 显示帮助手册总 {%1} 页中的第 {%0} 页 (/help <页码>) --- +commands.help.usage=/help [页数|命令名称] + +commands.message.usage=/tell <玩家名称> <私密信息 ...> +commands.message.sameTarget=您不能向自己发送私密信息! + +commands.difficulty.usage=/difficulty <新难度> +commands.difficulty.success=难度已被设置为 {%0} + +commands.spawnpoint.usage=/spawnpoint [玩家名称] [<x> <y> <z>] +commands.spawnpoint.success=已将 {%0} 的出生点设置为 ({%1}, {%2}, {%3}) + +commands.setworldspawn.usage=/setworldspawn [<x> <y> <z>] +commands.setworldspawn.success=已将世界出生点设置为 ({%0}, {%1}, {%2}) + +commands.weather.clear=天气已设为晴天 +commands.weather.rain=天气已设为雨天 +commands.weather.thunder=天气已设为雷雨 +commands.weather.usage=/weather <clear|rain|thunder> [持续秒数] + +commands.xp.success=已给予 {%1} {%0} 点经验 +commands.xp.success.levels=已给予 {%1} {%0} 级经验 +commands.xp.success.levels.minus=已减少 {%1} {%0} 级经验 +commands.xp.usage=/xp <经验数量> [玩家] 或 /xp <等级数量>L [玩家] + +# -------------------- Nukkit 语言文件,仅用于 console -------------------- + +nukkit.data.playerNotFound=无法找到玩家数据 "{%0}",正在创建新的数据 +nukkit.data.playerCorrupted=发现损坏的玩家数据 "{%0}",正在创建新的数据 +nukkit.data.playerOld=发现旧的玩家数据 "{%0}",正在更新数据 +nukkit.data.saveError=无法保存 "{%0}" 的玩家数据:{%1} + +nukkit.level.notFound=无法找到世界 "{%0}" +nukkit.level.loadError=无法加载世界 "{%0}":{%1} +nukkit.level.generationError=无法生成世界 "{%0}":{%1} +nukkit.level.tickError=更新世界 "{%0}" 时出现错误:{%1} +nukkit.level.chunkUnloadError=卸载区块时发生错误:{%0} +nukkit.level.backgroundGeneration=正在后台生成世界 "{%0}" 地形 +nukkit.level.defaultError=没有读取预设的世界 +nukkit.level.preparing=准备世界 "{%0}" 中 +nukkit.level.unloading=正在卸载世界 "{%0}" +nukkit.level.updating=发现旧的世界 "{%0}",正在转换格式 + +nukkit.server.start=正在启动 Minecraft: BE {%0} +nukkit.server.networkError=[Network] 终止交互 {%0} 原因 {%1} +nukkit.server.networkStart=正在于 {%0}:{%1} 启动服务器 +nukkit.server.info=此服务器正在运行 {%0} {%1} 版本 "{%2}" (API {%3}) +nukkit.server.info.extended=此服务器正在运行 {%0} {%1} 「{%2}」API 版本 {%3} 的 Minecraft: BE {%4} (协议版本 {%5}) +nukkit.server.license={%0} 根据 GPL 许可发行 +nukkit.server.tickOverload=注意!服务器可能超载? +nukkit.server.startFinished=启动完成 ({%0}s)!如需帮助,请输入 "help" 或 "?" +nukkit.server.defaultGameMode=默认游戏模式:{%0} +nukkit.server.query.start=启动 GS4 状态监听器 +nukkit.server.query.info=将 Query 端口设置为 {%0} +nukkit.server.query.running=Query 运行于 {%0}:{%1} +nukkit.server.rcon.emptyPasswordError=启动 RCON 失败:密码为空 +nukkit.server.rcon.startupError=启动 RCON 失败:{%0} +nukkit.server.rcon.running=RCON 运行于 {%0}:{%1} + +nukkit.command.alias.illegal=无法注册别名 {%0},因为它包含非法字符 +nukkit.command.alias.notFound=无法注册别名 {%0},因为它包含不存在的命令:{%1} +nukkit.command.exception=于 {%1} 执行命令 "{%0}" 时,出现了未被处理的错误:{%2} + +nukkit.command.plugins.description=获取服务器上运行的插件列表 +nukkit.command.plugins.success=插件 ({%0}):{%1} +nukkit.command.plugins.usage=/plugins + +nukkit.command.reload.description=重新加载服务器配置和插件 +nukkit.command.reload.usage=/reload +nukkit.command.reload.reloading=重新加载中... +nukkit.command.reload.reloaded=重新加载完成 + +nukkit.command.status.description=显示服务器的运行状态。 +nukkit.command.status.usage=/status + +nukkit.command.gc.description=启动垃圾清理任务 +nukkit.command.gc.usage=/gc + +nukkit.command.title.description=向一个玩家显示屏幕标题,或者更改该玩家显示的屏幕标题设置 +nukkit.command.title.usage=/title <玩家> <clear|reset> 或 /title <玩家> <title|subtitle|actionbar> <标题内容> 或 /title <玩家> <次数> <淡入时间> <持续时间> <淡出时间> +nukkit.command.title.clear=已清除 {%0} 的标题 +nukkit.command.title.reset=已重置 {%0} 的标题设置 +nukkit.command.title.title=正在向 {%1} 显示新的标题 "{%0}" +nukkit.command.title.subtitle=正在向 {%1} 显示新的副标题 "{%0}" +nukkit.command.title.actionbar=正在向 {%1} 显示新的快捷栏标题 "{%0}" +nukkit.command.title.times.success=已更改 {%3} 的标题显示时间为:{%0}, {%1}, {%2} (淡入时间, 持续时间, 淡出时间)。 +nukkit.command.title.times.fail=标题的时间必须为数字值 + +nukkit.command.version.description=查看此服务器及其使用的插件的版本 +nukkit.command.version.usage=/version [插件名称] +nukkit.command.version.noSuchPlugin=该服务器未在运行名为此的插件。使用 /plugins 获取插件列表。 + +nukkit.command.give.description=给指定玩家一定数量的物品 +nukkit.command.give.usage=/give <玩家名称> <物品[:特殊值]> [数量] [附加数据 ...] + +nukkit.command.kill.description=自杀或杀死其他玩家 +nukkit.command.kill.usage=/kill [玩家名称] + +nukkit.command.particle.description=向某个世界中添加粒子效果 +nukkit.command.particle.usage=/particle <玩家名称> <x> <y> <z> <xd> <yd> <zd> [数量] [数据值] + +nukkit.command.time.description=更改每个世界的时间 +nukkit.command.time.usage=/time <set|add> <数值> 或 /time <start|stop|query> + +nukkit.command.gamerule.description=设置或查询游戏规则的值 +nukkit.command.gamerule.usage=/gamerule <规则> [值] + +nukkit.command.ban.player.description=禁止指定的玩家加入此服务器 +nukkit.command.ban.ip.description=禁止指定的 IP 地址加入此服务器 +nukkit.command.banlist.description=查看该服务器封禁的所有玩家 +nukkit.command.defaultgamemode.description=设置默认的游戏模式 +nukkit.command.deop.description=取消指定玩家的管理员权限 +nukkit.command.difficulty.description=设置游戏的难度 +nukkit.command.enchant.description=为物品附魔 +nukkit.command.effect.description=增加/减少玩家身上的效果 +nukkit.command.gamemode.description=设置某个玩家的游戏模式 +nukkit.command.help.description=显示帮助列表 +nukkit.command.kick.description=从服务器中踢出指定玩家 +nukkit.command.list.description=显示在线玩家列表 +nukkit.command.me.description=在聊天中作出指定的动作 +nukkit.command.op.description=赋予指定玩家管理员权限 +nukkit.command.unban.player.description=允许指定玩家加入此服务器 +nukkit.command.unban.ip.description=允许指定 IP 地址加入此服务器 +nukkit.command.save.description=保存服务器数据到硬盘上 +nukkit.command.saveoff.description=停用自动保存服务器数据 +nukkit.command.saveon.description=启用自动保存服务器数据 +nukkit.command.say.description=以发送命令者身份广播指定的讯息 +nukkit.command.seed.description=显示世界种子 +nukkit.command.setworldspawn.description=设置一个世界重生点。未指定坐标则将使用玩家的坐标。 +nukkit.command.spawnpoint.description=设置玩家重生点 +nukkit.command.stop.description=关闭服务器 +nukkit.command.tp.description=传送指定玩家(或是自己)到另一位玩家或某坐标 +nukkit.command.tell.description=向指定玩家发送私密信息 +nukkit.command.weather.description=设置当前世界的天气状态 +nukkit.command.whitelist.description=管理员允许加入此服务器的玩家列表 +nukkit.command.xp.description=为玩家添加一定数量或等级的经验 + +nukkit.crash.create=发生了一个无法恢复的错误,导致服务器崩溃。正在生成错误报告。 +nukkit.crash.error=未能保存错误报告:{%0} +nukkit.crash.submit=请上传错误报告「{%0}」,并把链接提交至错误报告反馈页。请尽量提供更多资料。 +nukkit.crash.archive=错误报告已被自动上传。您可以在 {%0} 查看,或使用 ID #{%1}。 + +nukkit.debug.enable=启用 LevelDB 支持 + +nukkit.bugreport.create=侦测到一个错误,正在生成错误报告。 +nukkit.bugreport.error=无法生成错误报告:{%0} +nukkit.bugreport.archive=创建错误报告:{%0} + +nukkit.player.invalidMove={%0} 行动可疑! +nukkit.player.logIn={%0}[/{%1}:{%2}] 登入游戏,实体 ID 为 {%3},坐标位于 ({%4}, {%5}, {%6}, {%7}) +nukkit.player.logOut={%0}[/{%1}:{%2}] 登出游戏,原因:{%3} +nukkit.player.invalidEntity={%0} 尝试攻击一个无效的实体 + +nukkit.plugin.load=读取 {%0} 中 +nukkit.plugin.enable=开启 {%0} 中 +nukkit.plugin.disable=关闭 {%0} 中 +nukkit.plugin.restrictedName=受限的名称 +nukkit.plugin.incompatibleAPI=不兼容的 API 版本 +nukkit.plugin.unknownDependency=本插件无法单独使用 +nukkit.plugin.circularDependency=检测到循环依赖 +nukkit.plugin.genericLoadError=无法读取插件 "{%0}" +nukkit.plugin.spacesDiscouraged=插件 "{%0}" 在名称中使用了空格,不建议这样做 +nukkit.plugin.loadError=无法读取插件 "{%0}":{%1} +nukkit.plugin.duplicateError=无法读取插件 "{%0}":已有相同插件 +nukkit.plugin.fileError=无法读取 "{%1}" 目录中的 "{%0}":{%2} +nukkit.plugin.commandError=无法读取 {%1} 插件的 {%0} 命令 +nukkit.plugin.aliasError=无法读取 {%1} 插件的 {%0} 别名 +nukkit.plugin.deprecatedEvent=插件 "{%0}" 已在 "{%2}" 方法中注册了一个用于 "{%1}" 的监听器,但该事件已过时。 +nukkit.plugin.eventError=无法处理事件 "{%0}" 至 "{%1}":{%2} 于 {%3} + +nukkit.resources.invalid-path=资源包路径 "{%0}" 存在,但不是个目录 +nukkit.resources.unknown-format=无法加载 "{%0}" ,格式无法识别 +nukkit.resources.fail=无法加载 "{%0}":{%1} +nukkit.resources.success=成功加载 {%0} 个资源包 +nukkit.resources.zip.not-found=文件 "{%0}" 未找到 +nukkit.resources.zip.no-manifest="manifest.json" 未找到 +nukkit.resources.zip.invalid-manifest="manifest.json" 无效或不完整 +nukkit.resources.plugin.loading=Loading resource pack from plugin {%0} diff --git a/src/main/resources/lang/chs/nukkit.yml b/src/main/resources/lang/chs/nukkit.yml new file mode 100644 index 00000000000..df9b6d46c98 --- /dev/null +++ b/src/main/resources/lang/chs/nukkit.yml @@ -0,0 +1,98 @@ +# Nukkit 高级设置 +# 警告:此处部分设置是安全的,而一些在设置不当的情况下可能会损害您的服务器 +# 升级后,新的设置及默认值将不会自动显示在这里,它们将以默认值运行直到您手动更新配置文件 + +settings: + #多语言设置 + #可用:eng, chs, cht, jpn, rus, spa, pol, bra, kor, ukr, deu, ltu, cze + language: "chs" + #服务器强制语言 + force-language: false + shutdown-message: "服务器已关闭" + #允许使用Query协议查询您的插件 + query-plugins: true + #当某插件使用不被推荐的API时,在控制台提醒 + deprecated-verbose: true + #异步线程数量 + #如果设置为auto,则自动识别CPU核心数量(最少4线程) + async-workers: auto + +network: + #数据包大小阀值(单位:字节)。仅这些包会被压缩 + #设为 0 以压缩全部。设为 -1 以禁用此功能 + batch-threshold: 256 + #压缩等级。等级越高,CPU 占用越高,占用带宽越少 + compression-level: 5 + #Enable network encryption + encryption: true + +debug: + #当调试级别 > 1 时,将在控制台显示调试信息 + level: 1 + +level-settings: + #默认生成的地图格式 + default-format: leveldb + #自动改变世界 TPS 以维持每秒 20 ticks(TPS:ticks per second) + auto-tick-rate: true + auto-tick-rate-limit: 20 + #设置基本 TPS(1 = 20TPS,2 = 10TPS,以此类推) + base-tick-rate: 1 + #始终保持玩家Tick,即使其他选项不允许这么做 + always-tick-players: false + +chunk-sending: + #每 tick 内发送给玩家区块的数量 + per-tick: 4 + #玩家生成前需要的区块数量 + spawn-threshold: 56 + #在内存中存储一系列的区块复制以加快区块发送 + #在多玩家同时加入一个大多是静态的服务器时较有效 + cache-chunks: false + +chunk-ticking: + #每 tick 中处理的区块数量 + per-tick: 40 + #玩家周围区块处理的半径 + tick-radius: 3 + clear-tick-list: false + +chunk-generation: + #等待队列中,被生成的区块的数量上限 + queue-size: 8 + #等待队列中,被填充的区块的数量上限 + population-queue-size: 8 + +leveldb: + #Use native LevelDB implementation for better performance + use-native: false + #Set LevelDB memory cache size + cache-size-mb: 80 + +ticks-per: + autosave: 6000 + +player: + #决定服务器是否以 players/playername.dat 的形式保存玩家数据。默认 true 为保存。 + #如果设置为 false,nukkit 将不会保存玩家数据,这样一些与玩家数据有关的插件就可以大展身手了。 + save-player-data: true + #The time between skin change action in seconds, set to 0 if you dont want the cooldown + skin-change-cooldown: 15 + +aliases: + #指令别称 + #例如: + #showtheversion: version + #savestop: [save-all, stop] + +worlds: + #Worlds that the server will use. Options are specific to the chosen generator, and may result in broken generation or + #be ignored completely. + world: + #seed: 404 + generator: normal + options: + nether: + #seed: my_cool_nether_seed + generator: nether + options: diff --git a/src/main/resources/lang/cht/lang.ini b/src/main/resources/lang/cht/lang.ini new file mode 100644 index 00000000000..e2a2bee0258 --- /dev/null +++ b/src/main/resources/lang/cht/lang.ini @@ -0,0 +1,361 @@ +# Language file compatible with Minecraft: Bedrock Edition identifiers +# +# A message doesn't need to be there to be shown correctly on the client. +# Only messages shown in Nukkit itself need to be here +# Using the language property from PocketMine-MP + +language.name=中文(繁體) +language.selected=設定 {%0} ({%1}) 為基本語言 + +multiplayer.player.joined={%0} 加入了遊戲 +multiplayer.player.left={%0} 離開了遊戲 + +chat.type.text=<{%0}> {%1} +chat.type.emote=* {%0} {%1} +chat.type.announcement=[{%0}] {%1} +chat.type.admin=[{%0}: {%1}] +chat.type.achievement={%0} 剛剛獲得了成就 {%1} + +disconnectionScreen.outdatedClient=用戶端過舊! +disconnectionScreen.outdatedServer=伺服器過舊! +disconnectionScreen.serverFull=伺服器已滿! +disconnectionScreen.noReason=與伺服器連線中斷 +disconnectionScreen.invalidSkin=無效的皮膚! +disconnectionScreen.invalidName=無效的玩家代號! +disconnectionScreen.resourcePack=下載或套用資源包時遇到問題。 + +death.fell.accident.generic={%0} 從高處跌落 +death.attack.inFire={%0} 在火焰中昇天 +death.attack.onFire={%0} 被燒死了 +death.attack.lava={%0} 試圖在熔岩中游泳 +death.attack.lava.magma={%0} 察覺地面是片熔岩 +death.attack.inWall={%0} 在牆壁裡窒息 +death.attack.drown={%0} 溺死了 +death.attack.cactus={%0} 被仙人掌刺死了 +death.attack.generic={%0} 死亡 +death.attack.explosion={%0} 被炸飛了 +death.attack.explosion.player={%0} 被 {%1} 炸死了 +death.attack.magic={%0} 被魔法殺死了 +death.attack.wither={%0} 凋零了 +death.attack.mob={%0} 被 {%1} 殺死了 +death.attack.player={%0} 被 {%1} 殺死了 +death.attack.player.item={%0} 被 {%1} 用 {%2} 殺死 +death.attack.arrow={%0} 被 {%1} 射殺了 +death.attack.arrow.item={%0} 被 {%1} 用 {%2} 射殺 +death.attack.fall={%0} 以為能安然無恙的著地 +death.attack.outOfWorld={%0} 掉到世界外面了 +death.attack.starve={%0} 餓死了 + +gameMode.survival=生存模式 +gameMode.creative=創造模式 +gameMode.adventure=冒險模式 +gameMode.spectator=旁觀者模式 +gameMode.changed=您的遊戲模式已更新 + +potion.moveSpeed=速度 +potion.moveSlowdown=緩速 +potion.digSpeed=挖掘加速 +potion.digSlowDown=挖掘減速 +potion.damageBoost=強力 +potion.heal=立即治療 +potion.harm=立即傷害 +potion.jump=跳躍提升 +potion.confusion=噁心 +potion.regeneration=回復 +potion.resistance=抗性 +potion.fireResistance=抗火性 +potion.waterBreathing=水中呼吸 +potion.invisibility=隱身 +potion.blindness=失明 +potion.nightVision=夜視 +potion.hunger=飢餓 +potion.weakness=虛弱 +potion.poison=中毒 +potion.wither=凋零 +potion.healthBoost=生命值提升 +potion.absorption=吸收 +potion.saturation=飽食 + +commands.generic.exception=嘗試執行此指令時發生未知錯誤 +commands.generic.permission=您沒有使用此指令的權限 +commands.generic.ingame=您只能在遊戲內執行此指令 +commands.generic.unknown=未知的指令。請使用 /help 來顯示指令列表。 +commands.generic.player.notFound=找不到該玩家 +commands.generic.usage=用法:{%0} + +commands.time.added=時間增加了 {%0} +commands.time.set=設定時間為 {%0} +commands.time.query=目前時間為 {%0} + +commands.me.usage=/me <狀態 ...> + +commands.give.item.notFound=ID為 {%0} 的物品並不存在 +commands.give.success=已將 {%0} 個 {%1} 給予 {%2} +commands.give.tagError=資料格式不正確:{%0} + +commands.effect.usage=/effect <玩家代號> <效果> [秒數] [倍數] [隱藏粒子] 或 /effect <玩家代號> clear +commands.effect.notFound=ID 為 {%0} 的特殊效果並不存在 +commands.effect.success=已將 {%4} 秒的 {%0} (ID {%1}) * {%2} 效果作用於 {%3} +commands.effect.success.removed=已移除 {%1} 身上的 {%0} 效果 +commands.effect.success.removed.all=已移除 {%0} 身上的所有效果 +commands.effect.failure.notActive=無法從 {%1} 身上移除 {%0},該對象沒有您指定的效果 +commands.effect.failure.notActive.all=無法移除效果,因為 {%0} 沒有可以移除的效果 + +commands.enchant.noItem=對象手中沒有物品 +commands.enchant.notFound=沒有一個附魔ID為 {%0} +commands.enchant.success=已將附魔套用於物品 +commands.enchant.usage=/enchant <玩家代號> <附魔ID> [物品等級] + +commands.particle.success=顯示粒子 {%0} {%1} 次 +commands.particle.notFound=未知的效果名稱 {%0} + +commands.players.usage=/list +commands.players.list=至多 {%1} 個玩家之中的 {%0} 個玩家在線上: + +commands.kill.successful=已消滅 {%0} +commands.kill.all.successful=已消滅所有玩家 +commands.kill.entities.successful=已消滅所有實體 + +commands.banlist.ips=以下 {%0} 個 IP 位址被封鎖: +commands.banlist.players=以下 {%0} 個玩家被封鎖: +commands.banlist.usage=/banlist [IP 位址|玩家代號] + +commands.defaultgamemode.usage=/defaultgamemode <模式> +commands.defaultgamemode.success=這個世界的預設遊戲模式目前為 {%0} + +commands.op.success=已將 {%0} 設為伺服器管理員 +commands.op.usage=/op <玩家代號> + +commands.deop.success=已將 {%0} 從伺服器管理員中除名 +commands.deop.usage=/deop <玩家代號> + +commands.say.usage=/say <訊息 ...> + +commands.seed.usage=/seed +commands.seed.success=世界種子碼:{%0} + +commands.ban.success={%0} 已被封鎖 +commands.ban.usage=/ban <玩家代號> [原因 ...] + +commands.unban.success=已解除封鎖 {%0} +commands.unban.usage=/pardon <玩家代號> + +commands.banip.invalid=無效的 IP 位址或該玩家不在線上 +commands.banip.offline.invalid=玩家數據中不包含有效的 IP 位址 +commands.banip.success=已封鎖 IP {%0} +commands.banip.success.players=封鎖 IP 位址 {%0} 來自 {%1} +commands.banip.usage=/ban-ip <IP 位址|玩家代號> [原因 ...] + +commands.unbanip.invalid=無效的 IP 位址 +commands.unbanip.success=已解除封鎖 IP {%0} +commands.unbanip.usage=/pardon-ip <IP 位址> + +commands.save.usage=/save [on|off|hold|resume] +commands.save.enabled=自動存檔已啟用 +commands.save.disabled=自動存檔已停用 +commands.save.start=儲存遊戲中 +commands.save.success=遊戲已儲存 + +commands.stop.usage=/stop +commands.stop.start=正在停止伺服器 + +commands.kick.success={%0} 已被踢出 +commands.kick.success.reason={%0} 已被踢出:{%1} +commands.kick.usage=/kick <玩家代號> [原因 ...] + +commands.tp.success=傳送 {%0} 到 {%1} +commands.tp.success.coordinates=傳送 {%0} 到 {%1}, {%2}, {%3} +commands.tp.usage=/tp [玩家代號] <目標玩家> 或是 /tp [玩家代號] <x> <y> <z> [<y-rot> <x-rot>] + +commands.whitelist.list=以下 {%0} 個玩家 (全部 {%1} 人) 在白名單中: +commands.whitelist.enabled=已啟用白名單 +commands.whitelist.disabled=已關閉白名單 +commands.whitelist.reloaded=已重新載入白名單 +commands.whitelist.add.success=已新增 {%0} 到白名單 +commands.whitelist.add.usage=/whitelist add <玩家代號> +commands.whitelist.remove.success=已將 {%0} 從白名單中移除 +commands.whitelist.remove.usage=/whitelist remove <玩家代號> +commands.whitelist.usage=/whitelist <on|off|list|add|remove|reload> + +commands.gamemode.success.self=已將自己的遊戲模式切換為 {%0} +commands.gamemode.success.other=已將 {%0} 的遊戲模式切換為 {%1} +commands.gamemode.usage=/gamemode <模式> [玩家代號] + +commands.help.header=--- 檢視幫助列表第 {%0} 頁共 {%1} 頁 (/help <page>) --- +commands.help.usage=/help [頁數|指令名稱] + +commands.message.usage=/tell <玩家代號> <訊息 ...> +commands.message.sameTarget=您不能傳送訊息給自己! + +commands.difficulty.usage=/difficulty <難度> +commands.difficulty.success=已將難度設為 {%0} + +commands.spawnpoint.usage=/spawnpoint [玩家代號] [<x> <y> <z>] +commands.spawnpoint.success=已將 {%0} 的重生點設為 ({%1}, {%2}, {%3}) + +commands.setworldspawn.usage=/setworldspawn [<x> <y> <z>] +commands.setworldspawn.success=已將世界重生點設為 ({%0}, {%1}, {%2}) + +commands.weather.clear=已將天氣設為晴朗 +commands.weather.rain=已將天氣設為降雨 +commands.weather.thunder=已將天氣設為雷雨 +commands.weather.usage=/weather <clear|rain|thunder> [持續時間] + +commands.xp.success=已給予 {%1} {%0} 點經驗值 +commands.xp.success.levels=已給予 {%1} {%0} 等經驗等級 +commands.xp.success.levels.minus=已取走 {%1} {%0} 等經驗等級 +commands.xp.usage=/xp <經驗數量> [玩家] 或 /xp <等級數量>L [玩家] + +# -------------------- Nukkit language files, only for console -------------------- + +nukkit.data.playerNotFound=無法找到玩家資料 "{%0}",正在創建新的資料檔 +nukkit.data.playerCorrupted=發現損壞的資料 "{%0}",創建新的設定檔 +nukkit.data.playerOld=發現舊的玩家資料 "{%0}",更新設定檔 +nukkit.data.saveError=無法儲存 "{%0}" 的玩家資料:{%1} + +nukkit.level.notFound=無法找到 "{%0}" 地圖 +nukkit.level.loadError=無法讀取地圖 "{%0}":{%1} +nukkit.level.generationError=無法產生地圖 "{%0}":{%1} +nukkit.level.tickError=計算地圖「{%0}」時出現錯誤:{%1} +nukkit.level.chunkUnloadError=移除一個區塊時發生錯誤:{%0} +nukkit.level.backgroundGeneration=正在於背景生成世界 "{%0}" 的地形 +nukkit.level.defaultError=沒有讀取預設的地圖 +nukkit.level.preparing=準備地圖中... "{%0}" +nukkit.level.unloading=正在移除地圖 "{%0}" +nukkit.level.updating=發現舊的地圖 "{%0}",正在轉換格式 + +nukkit.server.start=正在啟動支援 Minecraft: BE {%0} 版本的伺服器 +nukkit.server.networkError=[Network] 停止介面 {%0} 由於 {%1} +nukkit.server.networkStart=正在啟動伺服器在 {%0}:{%1} +nukkit.server.info=此伺服器正在運作 {%0} {%1} 版本 "{%2}" (API {%3}) +nukkit.server.info.extended=此伺服器正在運作 {%0} {%1} 「{%2}」 執行 API 版本 {%3} 支援 Minecraft: BE {%4} (協定版本 {%5}) +nukkit.server.license={%0} 根據 GPL 許可發行 +nukkit.server.tickOverload=注意!伺服器有超載的可能 +nukkit.server.startFinished=讀取完成 ({%0}s)!如需幫助,請輸入 "help" 或 "?" +nukkit.server.defaultGameMode=預設的遊戲類型:{%0} +nukkit.server.query.start=啟動 GS4 狀態監聽器 +nukkit.server.query.info=設定 query 介面到 {%0} +nukkit.server.query.running=Query 運作在 {%0}:{%1} +nukkit.server.rcon.emptyPasswordError=無法啟動 RCON:密碼為空 +nukkit.server.rcon.startupError=無法啟動 RCON:{%0} +nukkit.server.rcon.running=RCON 正在運行於 {%0}:{%1} + +nukkit.command.alias.illegal=不能註冊別名 {%0},因為它包含非法字元 +nukkit.command.alias.notFound=未能登記別稱 {%0} ,因為它包含不存在的指令:{%1} +nukkit.command.exception=於 {%1} 執行指令 「{%0}」 時,出現了未被處理的錯誤:{%2} + +nukkit.command.plugins.description=取得伺服器插件列表 +nukkit.command.plugins.success=插件 ({%0}):{%1} +nukkit.command.plugins.usage=/plugins + +nukkit.command.reload.description=重新讀取伺服器設定和插件 +nukkit.command.reload.usage=/reload +nukkit.command.reload.reloading=重新讀取伺服器... +nukkit.command.reload.reloaded=重新讀取完成 + +nukkit.command.status.description=顯示伺服器狀態。 +nukkit.command.status.usage=/status + +nukkit.command.gc.description=進行清理 +nukkit.command.gc.usage=/gc + +nukkit.command.title.description=顯示螢幕標題給一個玩家,或者更改該玩家顯示的螢幕標題設置 +nukkit.command.title.usage=/title <玩家> <clear|reset> 或 /title <玩家> <title|subtitle|actionbar> <標題內容> 或 /title <玩家> <times> <淡入時間> <持續時間> <淡出時間> +nukkit.command.title.clear=已清除 {%0} 的標題 +nukkit.command.title.reset=已重設 {%0} 的標題設定 +nukkit.command.title.title=已對 {%1} 顯示了新的標題 "{%0}" +nukkit.command.title.subtitle=已對 {%1} 顯示了新的副標題 "{%0}" +nukkit.command.title.actionbar=已對 {%1} 顯示了新的動作欄標題 "{%0}" +nukkit.command.title.times.success=已變更 {%3} 的標題顯示時間為:{%0}, {%1}, {%2} (淡入時間, 持續時間, 淡出時間). +nukkit.command.title.times.fail=設置失敗, 標題的時間必須為數字值 + +nukkit.command.version.description=檢視此伺服器及其使用的插件的版本 +nukkit.command.version.usage=/version [插件名稱] +nukkit.command.version.noSuchPlugin=此伺服器沒有運行任何名稱相符的插件。使用 /plugins 來取得插件列表。 + +nukkit.command.give.description=給予指定玩家物品 +nukkit.command.give.usage=/give <玩家代號> <物品[:耐久度]> [數量] [附加資料值] + +nukkit.command.kill.description=自殺或殺死其他玩家 +nukkit.command.kill.usage=/kill [玩家代號] + +nukkit.command.particle.description=加入粒子效果至世界 +nukkit.command.particle.usage=/particle <玩家代號> <x> <y> <z> <xd> <yd> <zd> [數量] [資料值] + +nukkit.command.time.description=更改每個世界的時間 +nukkit.command.time.usage=/time <set|add> <數值> 或 /time <start|stop|query> + +nukkit.command.gamerule.description=可設定或查詢遊戲規則值 +nukkit.command.gamerule.usage=/gamerule <規則> [值] + +nukkit.command.ban.player.description=禁止指定的玩家進入伺服器 +nukkit.command.ban.ip.description=禁止指定的 IP 位址進入伺服器 +nukkit.command.banlist.description=檢視伺服器禁止列表 +nukkit.command.defaultgamemode.description=設定預設的遊戲模式 +nukkit.command.deop.description=移除指定玩家的管理員權限 +nukkit.command.difficulty.description=設定遊戲的難易度 +nukkit.command.enchant.description=附魔物品 +nukkit.command.effect.description=增加/減少玩家身上的效果 +nukkit.command.gamemode.description=改變玩家到一個特定的遊戲模式 +nukkit.command.help.description=顯示指令列表 +nukkit.command.kick.description=從伺服器中踢除指定玩家 +nukkit.command.list.description=顯示線上玩家列表 +nukkit.command.me.description=於聊天中作出指定的動作 +nukkit.command.op.description=賦予指定玩家管理員權限 +nukkit.command.unban.player.description=解禁玩家 +nukkit.command.unban.ip.description=解除封鎖 IP 位址 +nukkit.command.save.description=儲存伺服器到磁碟上 +nukkit.command.saveoff.description=停用自動儲存伺服器 +nukkit.command.saveon.description=啟用自動儲存伺服器 +nukkit.command.say.description=以傳送指令者身份廣播指定的訊息 +nukkit.command.seed.description=顯示世界種子碼 +nukkit.command.setworldspawn.description=設定一個世界重生點。未指定坐標,將使用玩家的坐標。 +nukkit.command.spawnpoint.description=設定玩家重生點 +nukkit.command.stop.description=關閉伺服器 +nukkit.command.tp.description=傳送指定玩家(或是自己)到另一位玩家或座標 +nukkit.command.tell.description=傳送私訊給指定玩家 +nukkit.command.weather.description=設定目前地圖的天氣狀態 +nukkit.command.whitelist.description=管理員允許使用此伺服器的玩家列表 +nukkit.command.xp.description=為玩家新增一定數量或等級的經驗 + +nukkit.crash.create=一個不能恢復的錯誤發生了,使伺服器崩潰。正在儲存錯誤報告。 +nukkit.crash.error=未能儲存錯誤報告:{%0} +nukkit.crash.submit=請上傳檔案「{%0}」至線上崩潰資料庫,並把所獲之連結提交至漏洞報告網頁。請盡量提供更多資料。 +nukkit.crash.archive=毀損傾印報告已經自動地被提交到毀損傾印存檔。您可以在{%0} 檢視到它或使用 ID #{%1}。 + +nukkit.debug.enable=啟用 LevelDB 支援 + +nukkit.bugreport.create=檢測到一個錯誤,正在創建錯誤報告。 +nukkit.bugreport.error=無法創建錯誤報告:{%0} +nukkit.bugreport.archive=已創建錯誤報告:{%0} + +nukkit.player.invalidMove={%0} 行動可疑! +nukkit.player.logIn={%0}[/{%1}:{%2}] 登入遊戲,ID 為 {%3} 座標位於 ({%4}, {%5}, {%6}, {%7}) +nukkit.player.logOut={%0}[/{%1}:{%2}] 登出遊戲,原因:{%3} +nukkit.player.invalidEntity={%0} 嘗試攻擊一個無效的實體 + +nukkit.plugin.load=讀取中... {%0} +nukkit.plugin.enable=開啟中... {%0} +nukkit.plugin.disable=關閉中... {%0} +nukkit.plugin.restrictedName=受限的名稱 +nukkit.plugin.incompatibleAPI=不相容的 API 版本 +nukkit.plugin.unknownDependency=本插件無法單獨使用 +nukkit.plugin.circularDependency=檢測出迴圈依賴 +nukkit.plugin.genericLoadError=無法讀取插件 "{%0}" +nukkit.plugin.spacesDiscouraged=插件 "{%0}" 在名稱中使用了空格,不建議這樣做 +nukkit.plugin.loadError=無法讀取插件 "{%0}":{%1} +nukkit.plugin.duplicateError=無法讀取插件 "{%0}":已有相同插件 +nukkit.plugin.fileError=無法讀取在 "{%1}" 資料夾中的 "{%0}":{%2} +nukkit.plugin.commandError=無法讀取 {%1} 插件的 {%0} 指令 +nukkit.plugin.aliasError=無法讀取 {%1} 插件的 {%0} 別名 +nukkit.plugin.deprecatedEvent=插件 "{%0}" 已經使用 "{%2}" 方法註冊了一個在 "{%1}" 的監聽器,但是該事件已過時。 +nukkit.plugin.eventError=無法處理事件 "{%0}" 至 "{%1}":{%2} 在 {%3} 上 + +nukkit.resources.invalid-path=資源包路徑 "{%0}" 已存在且不是一個目錄 +nukkit.resources.unknown-format=由於資​​源包格式無法識別,未能加載 "{%0}" +nukkit.resources.fail=無法加載 "{%0}":{%1} +nukkit.resources.success=成功加載 {%0} 個資源包 +nukkit.resources.zip.not-found=找不到文件 "{%0}" +nukkit.resources.zip.no-manifest=找不到 "manifest.json" +nukkit.resources.zip.invalid-manifest="manifest.json" 無效或不完整 +nukkit.resources.plugin.loading=Loading resource pack from plugin {%0} diff --git a/src/main/resources/lang/cht/nukkit.yml b/src/main/resources/lang/cht/nukkit.yml new file mode 100644 index 00000000000..db1d466ba11 --- /dev/null +++ b/src/main/resources/lang/cht/nukkit.yml @@ -0,0 +1,102 @@ +# Nukkit 進階設定 +# 警告:此處部分設定是安全的,而在一些設定不當的情況下可能會損害您的伺服器。 +# 升級後,新的設定及預設值將不會自動顯示在這裡,它們將以預設值運行直到您手動更新設定檔 + +settings: + #多語言設定 + #可用:eng, chs, cht, jpn, rus, spa, pol, bra, kor, ukr, deu, ltu, cze + language: "cht" + #伺服器強制語言 + force-language: false + #伺服器關閉訊息 + shutdown-message: "伺服器已關閉" + #允許使用Query協定查詢您的插件 + query-plugins: true + #當某插件使用不推薦的API時,在後台提醒 + deprecated-verbose: true + #非同步線程數量,如果設定為auto,則自動識別CPU核心數量(最少4線程) + async-workers: auto + +network: + #數據包大小閥值(單位:位元組),這些包將被壓縮 + #設為0,壓縮全部。設為-1,停用功能 + batch-threshold: 256 + #壓縮等級,等級越高,CPU佔用越高,佔用頻寬越少 + compression-level: 5 + #Enable network encryption + encryption: true + +debug: + #當調試級別 > 1 時,將在控制台顯示調試資訊 + level: 1 + +level-settings: + #預設生成的地圖格式 + default-format: leveldb + #自動保持Level的tick速度 + auto-tick-rate: true + auto-tick-rate-limit: 20 + #基本tick速率(1 = 20tick,2 = 10tick,以此類推) + base-tick-rate: 1 + #始終保持玩家Tick + always-tick-players: false + +chunk-sending: + #區塊發送設定 + #組織時間(tick)內發送給玩家區塊的數量 + per-tick: 4 + #玩家完成進服需要的區塊數量 + spawn-threshold: 56 + #使用區塊緩存 + #緩解多玩家同時加入時的伺服器壓力 + cache-chunks: false + +chunk-ticking: + #區塊處理設定 + #每組織時間(tick)中處理的區塊數量 + per-tick: 40 + #玩家周圍區塊處理的半徑設定 + tick-radius: 3 + clear-tick-list: false + +chunk-generation: + #區塊生成設定 + #等待隊列中,被生成的區塊的數量上限 + queue-size: 8 + #等待隊列中,被填充的區塊的數量上限 + population-queue-size: 8 + +leveldb: + #Use native LevelDB implementation for better performance + use-native: false + #Set LevelDB memory cache size + cache-size-mb: 80 + +ticks-per: + #自動儲存 + autosave: 6000 + +player: + #設置為 ture,玩家資料將被儲存為 player/<玩家代號>.dat + #設置為 false,nukkit 將不會儲存玩家資料為 "dat" 檔案,以便插件可以在其上執行某些操作。 + save-player-data: true + #The time between skin change action in seconds, set to 0 if you dont want the cooldown + skin-change-cooldown: 15 + +aliases: + #指令別稱 + #例: + #showtheversion: version + #savestop: [save-all, stop] + +worlds: + #Worlds that the server will use. Options are specific to the chosen generator, and may result in broken generation or + #be ignored completely. + world: + #seed: 404 + generator: normal + options: + nether: + #seed: my_cool_nether_seed + generator: nether + options: diff --git a/src/main/resources/lang/cze/lang.ini b/src/main/resources/lang/cze/lang.ini new file mode 100644 index 00000000000..8f2ace44c0b --- /dev/null +++ b/src/main/resources/lang/cze/lang.ini @@ -0,0 +1,361 @@ +#Jazykový soubor kompatibilní s identifikátory Minecraft: Bedrock Edition +# +#Zpráva nemusí být tam, aby se zobrazovala správně u klienta. +#Musí být zde pouze zprávy zobrazené v Nukkitu +#Použití vlastností jazyka od PocketMine-MP + +language.name=Czech +language.selected=Vybráno {%0} ({%1}) jako zakladní jazyk + +multiplayer.player.joined={%0} se připojil do hry +multiplayer.player.left={%0} opustil hru + +chat.type.text=<{%0}> {%1} +chat.type.emote=* {%0} {%1} +chat.type.announcement=[{%0}] {%1} +chat.type.admin=[{%0}: {%1}] +chat.type.achievement={%0} získal úspěch {%1} + +disconnectionScreen.outdatedClient=Zastaralý client! +disconnectionScreen.outdatedServer=Zastaralý server! +disconnectionScreen.serverFull=Server je plný! +disconnectionScreen.noReason=Ospojen ze serveru +disconnectionScreen.invalidSkin=Neplatný skin! +disconnectionScreen.invalidName=Neplatná přezdívka! +disconnectionScreen.resourcePack=Při stahování nebo použití resource packu došlo k problému. + +death.fell.accident.generic={%0} zpadl z výšky +death.attack.inFire={%0} vyšel v plamenech +death.attack.onFire={%0} schořel v plamenech +death.attack.lava={%0} zkusil plavat v lávě +death.attack.lava.magma={%0} discovered floor was lava +death.attack.inWall={%0} udusil se ve zdi +death.attack.drown={%0} utopil se +death.attack.cactus={%0} byl upíchán k smrti +death.attack.generic={%0} zemřel +death.attack.explosion={%0} vybuchl +death.attack.explosion.player={%0} byl odhozen {%1} +death.attack.magic={%0} byl zabit magií +death.attack.wither={%0} withered away +death.attack.mob={%0} byl zabit {%1} +death.attack.player={%0} byl zabit {%1} +death.attack.player.item={%0} byl zabit {%1} pouzitim {%2} +death.attack.arrow={%0} byl zastřelen {%1} +death.attack.arrow.item={%0} byl zastřelen {%1} pouzitim {%2} +death.attack.fall={%0} Narazil na zem příliš silně +death.attack.outOfWorld={%0} vypadl ze světa +death.attack.starve={%0} starved to death + +gameMode.survival=Mod preziti +gameMode.creative=Kreativni mod +gameMode.adventure=Dobrodruzny mod +gameMode.spectator=Mod divaka +gameMode.changed=Tvuj herní mod byl aktualizován + +potion.moveSpeed=Rychlost +potion.moveSlowdown=Pomalost +potion.digSpeed=Spěch +potion.digSlowDown=Miningová únava +potion.damageBoost=Síla +potion.heal=Okamžité zdraví +potion.harm=Okamžité poškození +potion.jump=Boost skoku +potion.confusion=Nevolnost +potion.regeneration=Regenerace +potion.resistance=Odpor +potion.fireResistance=Ohnivzdornost +potion.waterBreathing=Pod vodní dýchaní +potion.invisibility=Neviditelnost +potion.blindness=Slepota +potion.nightVision=Noční vydění +potion.hunger=Hlad +potion.weakness=Slabost +potion.poison=Jed +potion.wither=Wither +potion.healthBoost=Boost Zdraví +potion.absorption=Vstřebávání +potion.saturation=Nasycení + +commands.generic.exception=Při pokusu o provedení tohoto příkazu došlo k neznámé chybě +commands.generic.permission=Nemáš oprávnění na tento příkaz +commands.generic.ingame=Tento příkaz můžete provést pouze jako hráč +commands.generic.unknown=Neznámý příkaz. Vyzkoušejte / help pro seznam příkazů +commands.generic.player.notFound=Tento hráč nebyl nalezen +commands.generic.usage=Použij: {%0} + +commands.time.added=Přidáno {%0} k času +commands.time.set=Čas byl nastaven na {%0} +commands.time.query=Čas je {%0} + +commands.me.usage=/me <akce ...> + +commands.give.item.notFound=Neni zadna takova polozka s timto nazvem {%0} +commands.give.success=<Server>Dano {%0} * {%1} na {%2} +commands.give.tagError=Data tag parsovani selhalo: {%0} + +commands.effect.usage=/effect <hrac> <effect> [sekundy/ticky] [sila efektu] [hideParticles] OR /effect <hrac> clear +commands.effect.notFound=Neni zadny takovy effect s ID {%0} +commands.effect.success=Dal jsi {%0} (ID {%1}) * {%2} hraci {%3} na {%4} sekund/ticku +commands.effect.success.removed=Sebral jsi {%0} od {%1} +commands.effect.success.removed.all=Sebral jsi vsechny efekty od {%0} +commands.effect.failure.notActive=Nepodarilo se sebrat efekt {%0} od {%1} protoze nema zadny efekt +commands.effect.failure.notActive.all=Nesebral si efekt {%0} protoze zadny nema + +commands.enchant.noItem=Cil nedrzi zadny takovy item +commands.enchant.notFound=Neni zadny takovy enchant s ID {%0} +commands.enchant.success=Uspesne oenchatovano +commands.enchant.usage=/enchant <hrac> <enchantment ID> [level] + +commands.particle.success=Spustil jsi particle {%0} na dobu {%1} +commands.particle.notFound=Nezname jmeno efektu {%0} + +commands.players.usage=/list +commands.players.list=Zde je {%0}/{%1} hracu online: + +commands.kill.successful=Zabit {%0} +commands.kill.all.successful=Byli zabiti vsichni hraci +commands.kill.entities.successful=Byly zabyty vsechny entity + +commands.banlist.ips=Je zde dohromady {%0} zabanovanych IP adres: +commands.banlist.players=Je zde {%0} zabanovanych hracu: +commands.banlist.usage=/banlist [ips|hracu] + +commands.defaultgamemode.usage=/defaultgamemode <mode> +commands.defaultgamemode.success=Defaultni mod hry je {%0} + +commands.op.success=Tento hrac {%0} ziskal opravneni OP +commands.op.usage=/op <hrac> + +commands.deop.success=Tento hrac {%0} pozbyl opravneni OP +commands.deop.usage=/deop <hrac> + +commands.say.usage=/say <zprava ...> + +commands.seed.usage=/seed +commands.seed.success=Seed: {%0} + +commands.ban.success=Zabanovat hrace {%0} +commands.ban.usage=/ban <hrac> [duvod ...] + +commands.unban.success=Odbanovat hrace {%0} +commands.unban.usage=/pardon <hrac> + +commands.banip.invalid=Zadal jsi spatnou IP adresu nebo hrac neni online +commands.banip.offline.invalid=Neni takova IP adresa hrace nebo jsi ji zadal spatne +commands.banip.success=IP adresa zabanovana {%0} +commands.banip.success.players=Zabanovana IP adresa {%0} patrici {%1} +commands.banip.usage=/ban-ip <address|name> [reason ...] + +commands.unbanip.invalid=Zadal jsi nespravnoj IP adresu +commands.unbanip.success=IP adresa odbanovana {%0} +commands.unbanip.usage=/pardon-ip <address> + +commands.save.usage=/save [on|off|hold|resume] +commands.save.enabled=Zapinam autosave sveta +commands.save.disabled=Vypinam autosavd sveta +commands.save.start=Ukladam... +commands.save.success=Svet ulozen + +commands.stop.usage=/stop +commands.stop.start=Vypínám server + +commands.kick.success=Vykopnut {%0} ze serveru +commands.kick.success.reason=Vypkonut {%0} ze serveru: '{%1}' +commands.kick.usage=/kick <hrac> [duvod ...] + +commands.tp.success=Byl jsi teleportovan z {%0} na {%1} +commands.tp.success.coordinates=Byl jsi teleportovan z {%0} na {%1}, {%2}, {%3} +commands.tp.usage=/tp [target player] <destination player> OR /tp [target player] <x> <y> <z> [<y-rot> <x-rot>] + +commands.whitelist.list=Je zde {%0} (out of {%1} seen) hracu na whitelistu: +commands.whitelist.enabled=Whitelist zapnut +commands.whitelist.disabled=Whitelist vypnut +commands.whitelist.reloaded=Znovu nacist whitelist +commands.whitelist.add.success=Hrac {%0} pridan na whitelist +commands.whitelist.add.usage=/whitelist add <player> +commands.whitelist.remove.success=Hrac {%0} odebran z whitelist +commands.whitelist.remove.usage=/whitelist remove <player> +commands.whitelist.usage=/whitelist <on|off|list|add|remove|reload> + +commands.gamemode.success.self=Nastavil sis herni rezim na {%0} +commands.gamemode.success.other=Herni mod hrace {%0} nastaven na {%1} +commands.gamemode.usage=/gamemode <mode> [player] + +commands.help.header=HelpPage {%0} z {%1} (/help <page>) +commands.help.usage=/help [page|command name] + +commands.message.usage=/tell <player> < message ...> +commands.message.sameTarget=Nemuzes posilat zpravy sobe + +commands.difficulty.usage=/difficulty <new difficulty> +commands.difficulty.success=Obtiznost nastavena na {%0} + +commands.spawnpoint.usage=/spawnpoint [player] [<x> <y> <z>] +commands.spawnpoint.success=Spawn point hrace {%0} nastaven na ({%1}, {%2}, {%3}) + +commands.setworldspawn.usage=/setworldspawn [<x> <y> <z>] +commands.setworldspawn.success=Spawn sveta nastaven na ({%0}, {%1}, {%2}) + +commands.weather.clear=Cistim oblohu +commands.weather.rain=Zapinam dest +commands.weather.thunder=Zapinam bourku +commands.weather.usage=/weather <clear|rain|thunder> [doba trvani v sekundach] + +commands.xp.success=Davam {%0} zkusenosti hraci {%1} +commands.xp.success.levels=Davam {%0} levely/u hraci {%1} +commands.xp.success.levels.minus=Beru {%0} levely/u od hrace {%1} +commands.xp.usage=/xp <amount> [player] OR /xp <level>L [player] + +# -------------------- Nukkit language files, only for console -------------------- + +nukkit.data.playerNotFound=Data hrace nenalezena "{%0}", vytvarim novy profil +nukkit.data.playerCorrupted=Narusena data hrace "{%0}", vytvarim novy profil +nukkit.data.playerOld=Byla nalezena Stara data hraci "{%0}", upgraduju profil +nukkit.data.saveError=Nepodarilo se ulozit data "{%0}": {%1} + +nukkit.level.notFound=Uroven "{%0}" nenalezena +nukkit.level.loadError=Nepodarilo se nacist uroven "{%0}": {%1} +nukkit.level.generationError=Nepodarilo se vygenerovat uroven "{%0}": {%1} +nukkit.level.tickError=Nepodarilo se tick uroven "{%0}": {%1} +nukkit.level.chunkUnloadError=Chyba pri nacitani chunku: {%0} +nukkit.level.backgroundGeneration=Teren spawnu pro "{%0}" je generovana na pozadi +nukkit.level.defaultError=Nenacetla se defaultni uroven +nukkit.level.preparing=Pripravuji uroven "{%0}" +nukkit.level.unloading=Odnacitavam uroven "{%0}" +nukkit.level.updating=Stara data nelezena prl "{%0}", konvertuji uroven + +nukkit.server.start=Zapinam Minecraft: BE server verze {%0} +nukkit.server.networkError=[Network] Stopuji rozhrani {%0} kvuli {%1} +nukkit.server.networkStart=Zapinam server {%0}:{%1} +nukkit.server.info=Server bezi na {%0} verzi {%1} "{%2}" (API {%3}) +nukkit.server.info.extended=Server bezi {%0} {%1} 「{%2}」 implementovano API verze {%3} pro Minecraft: BE {%4} (protocol version {%5}) +nukkit.server.license={%0} je poskytovano GPL License +nukkit.server.tickOverload=Neudrzim to! Neni server prenacteny? +nukkit.server.startFinished=Hotovo ({%0}s)! Pro pomoc, napis "help" nebo "?" +nukkit.server.defaultGameMode=Defaultni herni mod: {%0} +nukkit.server.query.start=Zapinam GS4 status listener +nukkit.server.query.info=Setting query port to {%0} +nukkit.server.query.running=Query is running on {%0}:{%1} +nukkit.server.rcon.emptyPasswordError=Nepodarilo se spustit RCON: heslo je prazdne +nukkit.server.rcon.startupError=Nepodarilo se spustit RCON: {%0} +nukkit.server.rcon.running=RCON bezi na {%0}:{%1} + +nukkit.command.alias.illegal=Nepodarilo se vytvorit alias {%0} protoze obsahuje nepovolene znaky +nukkit.command.alias.notFound=Nepodarilo se vytvorit alias {%0} protozr obsahuje prikaz, ktery neexistuje: {%1} +nukkit.command.exception=Nezadana vyjimka pri prevadeni prikazu "{%0}" v {%1}: {%2} + +nukkit.command.plugins.description=Vypise list prikazu bezicich na serveru +nukkit.command.plugins.success=Pluginy ({%0}): {%1} +nukkit.command.plugins.usage=/plugins + +nukkit.command.reload.description=Reloaduji nastaveni server a pluginy +nukkit.command.reload.usage=/reload +nukkit.command.reload.reloading=Reloaduji server... +nukkit.command.reload.reloaded=Reload hotovy. + +nukkit.command.status.description=Kontroluji vykon serveru. +nukkit.command.status.usage=/status + +nukkit.command.gc.description=Uvolnuji RAM, vyhazovanim bordelu +nukkit.command.gc.usage=/gc + +nukkit.command.title.description=Sends a title to the specified player or modifies title settings for that player +nukkit.command.title.usage=/title <player> <clear|reset> OR /title <player> <title|subtitle|actionbar> <title text> OR /title <player> <times> <fade in time> <stay time> <fade out time> +nukkit.command.title.clear=Successfully cleared {%0}'s screen +nukkit.command.title.reset=Successfully reset title animation settings for {%0} +nukkit.command.title.title=Successfully shown "{%0}" title to {%1} +nukkit.command.title.subtitle=Successfully set subtitle to "{%0}" for {%1}'s next title +nukkit.command.title.actionbar=Successfully shown "{%0}" actionbar title to {%1} +nukkit.command.title.times.success=Successfully set title animation times to {%0}, {%1}, {%2} for {%3} +nukkit.command.title.times.fail=Times of title animations must be numeric values + +nukkit.command.version.description=Dostanes verzi serveru, obsahujici pouzivane pluginy +nukkit.command.version.usage=/version [plugin name] +nukkit.command.version.noSuchPlugin=Na tomto serveru neni zadny plugin s timhle jmenem. Pouzij /plugins pro ziskani listu pluginu. + +nukkit.command.give.description=Da specifikovanemu hraci presny pocet daneho itemu +nukkit.command.give.usage=/give <hrac> <item[:damage]> [mnozstvi] [tags ...] + +nukkit.command.kill.description=Spacha sebevrazdu nebo zabije daneho hrace +nukkit.command.kill.usage=/kill [player] + +nukkit.command.particle.description=Prida particly do sveta +nukkit.command.particle.usage=/particle <name> <x> <y> <z> <xd> <yd> <zd> [count] [data] + +nukkit.command.time.description=Zmeni cas pro jeden svet +nukkit.command.time.usage=/time <set|add> <value> NEBO /time <start|stop|query> + +nukkit.command.gamerule.description=Nastaví nebo vyšle dotaz na hodnotu herního pravidla +nukkit.command.gamerule.usage=/gamerule <rule> [value] + +nukkit.command.ban.player.description=Zabrani danemu hraci pouzit tento server +nukkit.command.ban.ip.description=Zabrani dane IP adrese pouzit tento server +nukkit.command.banlist.description=Zobrazi seznam zaBANovanych hracu +nukkit.command.defaultgamemode.description=Nastavi defaultni GM +nukkit.command.deop.description=Sebere danemu hraci operatorska prava (OP) +nukkit.command.difficulty.description=Nastavi herni obtiznost +nukkit.command.enchant.description=Prida ocarovani na item +nukkit.command.effect.description=Prida/Odebere efekt danemu hraci +nukkit.command.gamemode.description=Zmeni danemu hraci GM +nukkit.command.help.description=Zobrazi Help menu +nukkit.command.kick.description=Vyhodi daneho hrace ze serveru +nukkit.command.list.description=Seznam vsech hracu kteri jsou online +nukkit.command.me.description=Udela danou akci v chatu +nukkit.command.op.description=Da danemu hraci operatorka prava (OP) +nukkit.command.unban.player.description=Povoli danemu hraci pouzit tento server +nukkit.command.unban.ip.description=Povoli dane IP adrese pouzit tento srrver +nukkit.command.save.description=Ulozi server na disk +nukkit.command.saveoff.description=Vypne automaticke ukladani +nukkit.command.saveon.description=Zapne automaticke ukladani +nukkit.command.say.description=Rekni neco jako server +nukkit.command.seed.description=Ukaze ti seed sveta +nukkit.command.setworldspawn.description=Nastavi spawn pro svet. Pokud nebyli napsany zadne souradnice, budou pouzity souradnice hrace. +nukkit.command.spawnpoint.description=Nastavit hracuv spawn +nukkit.command.stop.description=Zastavi server +nukkit.command.tp.description=Teleportuje daneho hrace (nebo tebe) k jinemu hraci nebo na souradnice +nukkit.command.tell.description= Posle soukromou zpravu danemu hraci +nukkit.command.weather.description=Nastavi pocasi pro dany svet +nukkit.command.xp.description=Da danemu hraci presnou sumu zkusenosti +nukkit.command.whitelist.description=Upravi seznam hracu kteri jsou na whitelistu + +nukkit.crash.create=Neobnovitelna chyba se objevila a server crashnul. Vytvarim crash dump +nukkit.crash.error=Nepodarilo se vytvoritcrash dump: {%0} +nukkit.crash.submit=Prosim uploadujte "{%0}" soubor do Crash Archivu a pridejte odkaz na Bug Reporting stranku. Dej nam tolik informaci kolik jen muzes. +nukkit.crash.archive=Crash dump byl automaticky pridam do Crash Archivu. Muzes si ho zobrazi na {%0} nebo pouzi ID #{%1}. + +nukkit.debug.enable=LevelDB podpora zapnuta + +nukkit.bugreport.create=An error has been detected, creating a bug report. +nukkit.bugreport.error=Could not create bug report: {%0} +nukkit.bugreport.archive=A bug report has been created: {%0} + +nukkit.player.invalidMove={%0} se hnul spatne! +nukkit.player.logIn={%0}[/{%1}:{%2}] se prihlasil s entity id {%3} na ({%4}, {%5}, {%6}, {%7}) +nukkit.player.logOut={%0}[/{%1}:{%2}] se prihlasil diky {%3} +nukkit.player.invalidEntity={%0} se pokusil zautocit na neznamou entitu + +nukkit.plugin.load=Nacitam {%0} +nukkit.plugin.enable=Zapinam {%0} +nukkit.plugin.disable=Vypinam {%0} +nukkit.plugin.restrictedName=Zakazane jmeno +nukkit.plugin.incompatibleAPI=Nekompatibilni API verze +nukkit.plugin.unknownDependency=Neznama zavislost +nukkit.plugin.circularDependency=Cirkularni zavislost nalezena +nukkit.plugin.genericLoadError=Nelze nacist plugin"{%0}" +nukkit.plugin.spacesDiscouraged=Plugin "{%0}" pouziva mezery ve svem jmene, je to nechutne +nukkit.plugin.loadError=Nepodarilo se nacist plugin "{%0}": {%1} +nukkit.plugin.duplicateError=Nepodarilo se nacist "{%0}": plugin existuje +nukkit.plugin.fileError=Nejde nacist "{%0}" ve slozce "{%1}": {%2} +nukkit.plugin.commandError=Nepodarilo se nacist prikaz {%0} pro plugin {%1} +nukkit.plugin.aliasError=Nejde nacist alias {%0} pro plugin {%1} +nukkit.plugin.deprecatedEvent=Plugin "{%0}" registroval listener pro "{%1}" na metodu "{%2}", ale tato udalost je zastarala. +nukkit.plugin.eventError=Nepodarilo se provest udalost "{%0}" v "{%1}": {%2} na {%3} + +nukkit.resources.invalid-path=Resource pack cesta "{%0}" existuje a není adresářem +nukkit.resources.unknown-format=Nelze načíst "{%0}" protože formát není rozpoznán +nukkit.resources.fail=Nelze načíst "{%0}": {%1} +nukkit.resources.success=Úspěšne načteno {%0} resource packs +nukkit.resources.zip.not-found=Soubor "{%0}" nebyl nalezen +nukkit.resources.zip.no-manifest="manifest.json" nebyl nalezen +nukkit.resources.zip.invalid-manifest="manifest.json" je neplatný nebo neúplný +nukkit.resources.plugin.loading=Loading resource pack from plugin {%0} diff --git a/src/main/resources/lang/cze/nukkit.yml b/src/main/resources/lang/cze/nukkit.yml new file mode 100644 index 00000000000..f7efc26879b --- /dev/null +++ b/src/main/resources/lang/cze/nukkit.yml @@ -0,0 +1,99 @@ +# Hlavni nastavovaci soubor pro Nukkit +# Některé z těchto nastavení jsou bezpečné, jiné mohou přerušit váš server, pokud jsou nesprávně upraveny +# Nové nastavení/výchozí hodnoty se v tomto souboru automaticky nezobrazí při upgradu + +settings: + #Multi-jazykove nastaveni + #Dostupne: eng, chs, cht, jpn, rus, spa, pol, bra, kor, ukr, deu, ltu, cze + language: "cze" + #Whether to send all strings translated to server locale or let the device handle them + #Zda chcete odeslat všechny řetězce přeložené do lokálního serveru nebo nechat zařízení zvládnout + force-language: false + shutdown-message: "Server se vypíná" + #Povolí prohlížení pluginu pomoci Query + query-plugins: true + #Console pošle zprávu pokud plugin používá zastaralé metody API + deprecated-verbose: true + #Počet pracovníků AsyncTasku + #Pokud je nastaven na automatické, pokusí se detekovat počet jader (a nejméně 4) + async-workers: auto + +network: + #Threshold pro dávkové pakety v bajtech. Pouze tyto pakety budou komprimovány + #Nastavte na 0, chcete-li vše komprimovat, -1 zakázat + batch-threshold: 256 + #Compression level používaný Zlib při odesílání dávkových paketů. Vyšší = více CPU, méně využití šířky pásma + compression-level: 5 + #Enable network encryption + encryption: true + +debug: + #Pokud je nastavena 1, console posílá debug zprávy + level: 1 + +level-settings: + #Výchozí formát, který budou světy používat při vytvoření + default-format: leveldb + #Automaticky měnit level tick a zachovat 20 ticků za sekundu + auto-tick-rate: true + auto-tick-rate-limit: 20 + #Nastaví základní ticky (1 = 20 ticků za sekundu, 2 = 10 ticku za sekundu atd.). + base-tick-rate: 1 + #Tickne všechny hráče každý tick, i když to ostatní nastavení zakáže + always-tick-players: false + +chunk-sending: + #Množství chunků které se pošlou hráčovi každý tick + per-tick: 4 + #Množství chunků, které je třeba poslat před tím, než se hráč spawne + spawn-threshold: 56 + #Uloží serializovanou kopii chunků v paměti pro rychlejší odesílání + #Použije se ve většině statických světech, kde se najednou připojuje spousta hráčů + cache-chunks: false + +chunk-ticking: + #Max množství chunků které se zpracovává každý tick + per-tick: 40 + #Radius chunků kolem hráče, který se má ticknout + tick-radius: 3 + clear-tick-list: false + +chunk-generation: + #Max. Množství chunků v čekací frontě, která má být generována + queue-size: 8 + #Max. množství chunků ktere vyčkává ve frontě na "osídlení" + population-queue-size: 8 + +leveldb: + #Use native LevelDB implementation for better performance + use-native: false + #Set LevelDB memory cache size + cache-size-mb: 80 + +ticks-per: + autosave: 6000 + +player: + #Pokud je true, data hráče budou uložena jako players/playername.dat + #Pokud je false, nukkit neukládá data hráče jako "datové" soubory, aby mohly pluginy něco udělat. + save-player-data: true + #The time between skin change action in seconds, set to 0 if you dont want the cooldown + skin-change-cooldown: 15 + +aliases: + #Aliasy pro příkazy + #Například: + #showtheversion: version + #savestop: [save-all, stop] + +worlds: + #Worlds that the server will use. Options are specific to the chosen generator, and may result in broken generation or + #be ignored completely. + world: + #seed: 404 + generator: normal + options: + nether: + #seed: my_cool_nether_seed + generator: nether + options: diff --git a/src/main/resources/lang/deu/lang.ini b/src/main/resources/lang/deu/lang.ini new file mode 100644 index 00000000000..8ed69cfb2b9 --- /dev/null +++ b/src/main/resources/lang/deu/lang.ini @@ -0,0 +1,361 @@ +# Language file compatible with Minecraft: Bedrock Edition identifiers +# +# A message doesn't need to be there to be shown correctly on the client. +# Only messages shown in Nukkit itself need to be here +# Using the language property from PocketMine-MP + +language.name=Deutsch +language.selected={%0} ({%1}) als Standard eingestellt + +multiplayer.player.joined={%0} betrat das Spiel +multiplayer.player.left={%0} hat das Spiel verlassen + +chat.type.text=<{%0}> {%1} +chat.type.emote=* {%0} {%1} +chat.type.announcement=[{%0}] {%1} +chat.type.admin=[{%0}: {%1}] +chat.type.achievement={%0} hat die Errungenschaft {%1} erzielt + +disconnectionScreen.outdatedClient=Veralteter Client! +disconnectionScreen.outdatedServer=Veralteter Server! +disconnectionScreen.serverFull=Server ist voll! +disconnectionScreen.noReason=Verbindung zum Server getrennt +disconnectionScreen.invalidSkin=Ungültiger Skin! +disconnectionScreen.invalidName=Ungültiger Name! +disconnectionScreen.resourcePack=Encountered a problem while downloading or applying resource pack. + +death.fell.accident.generic={%0} fiel aus zu großer Höhe +death.attack.inFire={%0} ging in Flammen auf +death.attack.onFire={%0} verbrannte +death.attack.lava={%0} versuchte in Lava zu schwimmen +death.attack.lava.magma={%0} wurde der Boden zu heiß +death.attack.inWall={%0} wurde lebendig begraben +death.attack.drown={%0} ertrank +death.attack.cactus={%0} wurde zu Tode gestochen +death.attack.generic={%0} starb +death.attack.explosion={%0} wurde in die Luft gesprengt +death.attack.explosion.player={%0} wurde durch {%1} in die Luft gesprengt +death.attack.magic={%0} wurde durch Magie getötet +death.attack.wither={%0} verdorrte +death.attack.mob={%0} wurde von {%1} erschlagen +death.attack.player={%0} wurde von {%1} erschlagen +death.attack.player.item={%0} wurde von {%1} mit {%2} erschlagen +death.attack.arrow={%0} wurde von {%1} erschossen +death.attack.arrow.item={%0} wurde von {%1} mit {%2} erschossen +death.attack.fall={%0} fiel der Schwerkraft zum Opfer +death.attack.outOfWorld={%0} fiel aus der Welt +death.attack.starve={%0} starved to death + +gameMode.survival=Überlebensmodus +gameMode.creative=Kreativmodus +gameMode.adventure=Abenteuermodus +gameMode.spectator=Zuschauermodus +gameMode.changed=Dein Spielmodus wurde aktualisiert + +potion.moveSpeed=Schnelligkeit +potion.moveSlowdown=Langsamkeit +potion.digSpeed=Eile +potion.digSlowDown=Langsames Abbauen +potion.damageBoost=Stärke +potion.heal=Direktheilung +potion.harm=Schaden +potion.jump=Sprungkraft +potion.confusion=Übelkeit +potion.regeneration=Regeneration +potion.resistance=Resistenz +potion.fireResistance=Feuerresistenz +potion.waterBreathing=Unterwasser-Atmung +potion.invisibility=Unsichtbarkeit +potion.blindness=Blindheit +potion.nightVision=Nachtsicht +potion.hunger=Hunger +potion.weakness=Schwäche +potion.poison=Gift +potion.wither=Wither +potion.healthBoost=Lebenserweiterung +potion.absorption=Absorption +potion.saturation=Sättigung + +commands.generic.exception=Es trat ein unbekannter Fehler, beim Ausführen des Befehls, auf! +commands.generic.permission=Du hast nicht die Erlaubnis, diesen Befehl auszuführen! +commands.generic.ingame=Dieser Befehl kann nur als Spieler ausgeführt werden! +commands.generic.unknown=Unbekannter Befehl. Gebe /help ein, um eine Übersicht der Befehle zu sehen! +commands.generic.player.notFound=Der Spieler wurde nicht gefunden! +commands.generic.usage=Nutze: {%0} + +commands.time.added={%0} wurde als Zeit hinzugefügt! +commands.time.set=Zeit wurde auf {%0} gestellt! +commands.time.query=Die Zeit ist {%0} + +commands.me.usage=/me <aktion ...> + +commands.give.item.notFound=Es gibt kein Item mit dem Namen: {%0} +commands.give.success=Gebe {%0} * {%1} zu {%2} +commands.give.tagError=Data tag parsing failed: {%0} + +commands.effect.usage=/effect <Spieler> <Effekt> [Sekunden] [amplifier] [hideParticles] ODER /effect <Spieler> clear +commands.effect.notFound=Es gibt keinen Mob Effekt mit der ID {%0} +commands.effect.success=Gebe {%0} (ID {%1}) * {%2} zu {%3} für {%4} Sekunden +commands.effect.success.removed=Nehme {%0} vom {%1} +commands.effect.success.removed.all=Alle Effekte von {%0} entfernt! +commands.effect.failure.notActive=Der Effekt {%0} konnte nicht von {%1} entfernt werden, weil er den Effekt nicht besitzt! +commands.effect.failure.notActive.all=Es konnten keine Effekte von {%0} entfernt werden, da er keine besitzt! + +commands.enchant.noItem=The target doesn't hold an item +commands.enchant.notFound=Es gibt keine Verzauberung mit der ID {%0} +commands.enchant.success=Verzaubert! +commands.enchant.usage=/enchant <Spieler> <Verzauberungs-ID> [Level] + +commands.particle.success=Der Effekt {%0} bleibt {%1} Sekunden +commands.particle.notFound=Unbekannter Effektname {%0} + +commands.players.usage=/list +commands.players.list=Es sind {%0}/{%1} Spieler online: + +commands.kill.successful={%0} wurde umgebracht! +commands.kill.all.successful=Alle Spieler wurde umgebracht +commands.kill.entities.successful=Alle Entitäten wurde umgebracht + +commands.banlist.ips=Es gibt {%0} gebannte IP-Adressen: +commands.banlist.players=Es gibt {%0} gebannte Spieler: +commands.banlist.usage=/banlist [ips|players] + +commands.defaultgamemode.usage=/defaultgamemode <mode> +commands.defaultgamemode.success=Der Welt Spielmodus wurde auf {%0} gesetzt! + +commands.op.success=Opped {%0} +commands.op.usage=/op <Spieler> + +commands.deop.success=De-opped {%0} +commands.deop.usage=/deop <Spieler> + +commands.say.usage=/say <Nachricht ...> + +commands.seed.usage=/seed +commands.seed.success=Seed: {%0} + +commands.ban.success=Der Spieler {%0} wurde gebannt! +commands.ban.usage=/ban <Spieler> [Grund ...] + +commands.unban.success=Der Spieler {%0} wurde entbannt! +commands.unban.usage=/pardon <Spieler> + +commands.banip.invalid=Du hast eine ungültige IP-Adresse angegeben oder die IP ist offline! +commands.banip.offline.invalid=Diese IP-Adresse ist nicht in den Spielerdaten oder die IP-Adresse ist ungültig! +commands.banip.success=IP-Adresse {%0} wurde gebannt! +commands.banip.success.players=Die IP-Adresse {%0} von {%1} wurde gebannt! +commands.banip.usage=/ban-ip <IP|Spieler> [Grund ...] + +commands.unbanip.invalid=Ungültige IP-Adresse! +commands.unbanip.success=Die IP-Adresse {%0} wurde entbannt! +commands.unbanip.usage=/pardon-ip <IP> + +commands.save.usage=/save [on|off|hold|resume] +commands.save.enabled=Automatisches Welt-Speichern wurde aktiviert! +commands.save.disabled=Automatisches Welt-Speichern wurde deaktiviert! +commands.save.start=Speichere... +commands.save.success=Die Welt wurde gespeichert. + +commands.stop.usage=/stop +commands.stop.start=Server wird gestoppt! + +commands.kick.success=Der Spieler {%0} wurde gekickt! +commands.kick.success.reason=Der Spieler {%0} wurde wegen '{%1}' vom Server gekickt! +commands.kick.usage=/kick <Spieler> [Grund ...] + +commands.tp.success={%0} zu {%1} teleportiert! +commands.tp.success.coordinates=Teleportiere {%0} zu {%1}, {%2}, {%3} +commands.tp.usage=/tp [teleportierender Spieler] <Ziel-Spieler> ODER /tp [teleportierender Spieler] <x> <y> <z> [<y-rot> <x-rot>] + +commands.whitelist.list=Es sind {%0} (out of {%1} seen) Spieler gewhitelistet: +commands.whitelist.enabled=Whitelist aktiviert +commands.whitelist.disabled=Whitelist deaktiviert +commands.whitelist.reloaded=Whitelist neugeladen +commands.whitelist.add.success=Spieler {%0} wurde zur Whitelist hinzugefügt! +commands.whitelist.add.usage=/whitelist add <Spieler> +commands.whitelist.remove.success=Spieler {%0} wurde von der Whitelist entfernt! +commands.whitelist.remove.usage=/whitelist remove <Spieler> +commands.whitelist.usage=/whitelist <on|off|list|add|remove|reload> + +commands.gamemode.success.self=Spielmodus zu {%0} gesetzt +commands.gamemode.success.other=Spielmodus von {%0} auf {%1} gesetzt +commands.gamemode.usage=/gamemode <Modus> [Spieler] + +commands.help.header=--- Befehlsseite {%0} von {%1} (/help <Seite>) --- +commands.help.usage=/help [Seite|Befehl] + +commands.message.usage=/tell <Spieler> <Nachricht ...> +commands.message.sameTarget=Du kannst keine Nachricht die selbst senden! + +commands.difficulty.usage=/difficulty <Schwierigkeit> +commands.difficulty.success=Der Schwierigkeitsgrad wurde auf {%0} gesetzt + +commands.spawnpoint.usage=/spawnpoint [Spieler] [<x> <y> <z>] +commands.spawnpoint.success=Der Spawnpoint von {%0} wurde zu ({%1}, {%2}, {%3}) gesetzt + +commands.setworldspawn.usage=/setworldspawn [<x> <y> <z>] +commands.setworldspawn.success=Der Weltspawn wurde zu ({%0}, {%1}, {%2}) gesetzt + +commands.weather.clear=Wetter auf Sonnenschein gesetzt +commands.weather.rain=Wetter auf Regen gesetzt +commands.weather.thunder=Wetter auf Sturm gesetzt +commands.weather.usage=/weather <clear|rain|thunder> [Dauer] + +commands.xp.success={%0} Erfahrung zu {%1} gegeben +commands.xp.success.levels={%0} Level zu {%1} gegeben +commands.xp.success.levels.minus={%0} Level von {%1} entfernt +commands.xp.usage=/xp <Anzahl> [Spieler] ODER /xp <Level>L [Spieler] + +# -------------------- Nukkit language files, only for console -------------------- + +nukkit.data.playerNotFound=Keine Spielerdaten von "{%0}" vorhanden, neue Spielerdaten werden erstellt +nukkit.data.playerCorrupted=Fehlerhafte Spielerdaten von "{%0}" vorhanden, erstelle neue Spielerdate +nukkit.data.playerOld=Alte Spielerdaten von "{%0}" vorhanden, upgrade Spielerdaten +nukkit.data.saveError=Spieler "{%0}": {%1} konnte nicht gespeichert + +nukkit.level.notFound=Welt "{%0}" nicht gefunden +nukkit.level.loadError=Konnte Welt "{%0}" nicht laden: {%1} +nukkit.level.generationError=Konnte Welt "{%0}" nicht generieren: {%1} +nukkit.level.tickError=Welt "{%0}" konnte nicht getickt werden: {%1} +nukkit.level.chunkUnloadError=Fehler beim Entladen eines Chunks: {%0} +nukkit.level.backgroundGeneration=Spawn-Landschaft für Level "{%0}" wird im Hintergrund generiert +nukkit.level.defaultError=Keine Standart-Welt wurde geladen +nukkit.level.preparing=Vorbereiten der Welt "{%0}" +nukkit.level.unloading=Entladen der Welt "{%0}" +nukkit.level.updating=Old level data found for "{%0}", converting format + +nukkit.server.start=Starte Minecraft: BE mit Version {%0} +nukkit.server.networkError=[Netzwerk] Interface {%0} wegen {%1} gestoppt +nukkit.server.networkStart=Starte Server auf {%0}:{%1} +nukkit.server.info=Dieser Server startet mit der Version {%0} {%1} "{%2}" (API: {%3}) +nukkit.server.info.extended=Dieser Server läuft unter der Version {%0} {%1} 「{%2}」und nutzt die Version {%3} der API für Minecraft:BE {%4} (Protokoll Version {%5}) +nukkit.server.license={%0} wird unter der GPL-Lizenz vertrieben +nukkit.server.tickOverload=Kann nicht mithalten! Ist der Server überladen? +nukkit.server.startFinished=Fertig! ({%0}s)! Für Hilfe, tippe "help" oder "?" +nukkit.server.defaultGameMode=Standard-Spielmodus: {%0} +nukkit.server.query.start=Starte GS4 Status-Listener +nukkit.server.query.info=Setze Query-Port auf {%0} +nukkit.server.query.running=Query startet auf {%0}:{%1} +nukkit.server.rcon.emptyPasswordError=Fehler beim Starten von RCON: Leeres Passwort +nukkit.server.rcon.startupError=Fehler beim Starten von RCON: {%0} +nukkit.server.rcon.running=RCON läuft auf {%0}:{%1} + +nukkit.command.alias.illegal=Konnte Alias {%0} nicht registrieren, da er unzulässige Zeichen enthält +nukkit.command.alias.notFound=Konnte Alias {%0} nicht registrieren, da er Kommandos enthält, die nicht existieren: {%1} +nukkit.command.exception=Unbehandelter Fehler beim Ausführen des Kommandos "{%0}" in {%1}: {%2} + +nukkit.command.plugins.description=Gibt eine Liste aller auf dem Server laufenden Plugins zurück +nukkit.command.plugins.success=Plugins ({%0}): {%1} +nukkit.command.plugins.usage=/plugins + +nukkit.command.reload.description=Lädt die Servereinstellungen und Plugins neu +nukkit.command.reload.usage=/reload +nukkit.command.reload.reloading=Lade Server neu... +nukkit.command.reload.reloaded=Neuladen abgeschlossen. + +nukkit.command.status.description=Gibt die Serverauslastung aus. +nukkit.command.status.usage=/status + +nukkit.command.gc.description=Startet Automatische Speicherbereinigungs Aufgaben +nukkit.command.gc.usage=/gc + +nukkit.command.title.description=Sendet einen Titel an den angegebenen Spieler oder ändert die Titeleinstellungen für diesen Spieler. +nukkit.command.title.usage=/title <player> <clear|reset> OR /title <player> <title|subtitle|actionbar> <title text> OR /title <player> <times> <fade in time> <stay time> <fade out time> +nukkit.command.title.clear=Successfully cleared {%0}'s screen +nukkit.command.title.reset=Titelanimationseinstellungen für {%0} +nukkit.command.title.title=Erfolgreich gezeigt "{%0}" Titel zu {%1} +nukkit.command.title.subtitle=Untertitel erfolgreich auf "{%0}" für {%1}'s nächster Titel. +nukkit.command.title.actionbar=Erfolgreich gezeigt "{%0}" actionbar Titel zu {%1} +nukkit.command.title.times.success=Erfolgreich festgelegt Titelanimationszeiten auf {%0}, {%1}, {%2} für {%3} +nukkit.command.title.times.fail=Zeiten von Titelanimationen müssen numerische Werte sein. + +nukkit.command.version.description=Gibt die Version eines Plugins wieder +nukkit.command.version.usage=/version [Plugin] +nukkit.command.version.noSuchPlugin=Dieses Plugin ist nicht installiert. Nutze /plugins um eine Liste mit allen Plugins zu erhalten. + +nukkit.command.give.description=Gibt einem Spieler eine bestimmte Anzahl an Items +nukkit.command.give.usage=/give <Spieler> <item[:damage]> [amount] [tags ...] + +nukkit.command.kill.description=Tötet einen Spieler (oder dich) +nukkit.command.kill.usage=/kill [Spieler] + +nukkit.command.particle.description=Setzt Partikel in einer Welt +nukkit.command.particle.usage=/particle <Weltname> <x> <y> <z> <xd> <yd> <zd> [Anzahl] [Partikelname] + +nukkit.command.time.description=Wechselt die Zeit in jeder Welt +nukkit.command.time.usage=/time <set|add> <Name/Zeit> ODER /time <start|stop|query> + +nukkit.command.gamerule.description=Setzt einen Spielregelwert fest oder fragt ihn ab +nukkit.command.gamerule.usage=/gamerule <rule> [value] + +nukkit.command.ban.player.description=Bannt einen Spieler und verhindert das er den Server betreten kann +nukkit.command.ban.ip.description=Bannt eine IP und verhindert das sie den Server betreten kann +nukkit.command.banlist.description=Listet alle gebannten Spieler auf +nukkit.command.defaultgamemode.description=Setzt den Standard-Spielmodus +nukkit.command.deop.description=Entfernt den Admin-/OP-Rang von einem Spieler +nukkit.command.difficulty.description=Setzt die Spielschwierigkeit +nukkit.command.enchant.description=Verzaubert Items +nukkit.command.effect.description=Gibt/Entfernt Effekte von Spielren +nukkit.command.gamemode.description=Wechselt von einem Spieler den SpielmodusCircular dependency detected +nukkit.command.help.description=Zeigt eine Befehlsliste +nukkit.command.kick.description=Entfernt/Kickt einen Spieler vom Server +nukkit.command.list.description=Listet alle Online-Spieler auf +nukkit.command.me.description=Gibt eine Aktion im Chat wieder +nukkit.command.op.description=Gibt einem Spieler OP-/Admin-Rechte +nukkit.command.unban.player.description=Entbannt einen Spieler +nukkit.command.unban.ip.description=Entbannt eine IP-Adresse +nukkit.command.save.description=Speichert den Server +nukkit.command.saveoff.description=Deaktiviert automatisches Server Speichern +nukkit.command.saveon.description=Aktiviert automatisches Server Speichern +nukkit.command.say.description=Gibt die Nachricht als Sender aus +nukkit.command.seed.description=Zeigt den Welt-Seed +nukkit.command.setworldspawn.description=Setzt einen Spawnpoin an bestimmten Koordinaten. Wenn keine Koordinaten angegeben werden, werden die Spieler Koordinaten verwendet. +nukkit.command.spawnpoint.description=Setzt den Spieler Spawnpunkt +nukkit.command.stop.description=Stoppt den Server +nukkit.command.tp.description=Teleportiert einen anderen Spieler (oder Du selbst) zu einem Spieler oder zu Koordinaten +nukkit.command.tell.description=Sendet eine private Nachricht an einen Spieler +nukkit.command.weather.description=Setzt das derzeitige Wetter in der Welt +nukkit.command.xp.description=Gibt einem Spieler eine bestimmte Anzahl an Erfahrung +nukkit.command.whitelist.description=Eine Liste der Spieler die den Server bei aktivierter Whitelist betreten darf + +nukkit.crash.create=Es trat ein unbekannter Fehler auf bei dem der Server gecrasht ist. Eine Crash-Datei wird erstellt... +nukkit.crash.error=Eine Crash-Datei konnte nicht erstellt werden: {%0} +nukkit.crash.submit=Bitte lade die "{%0}" Datei in das Crash Archive hoch und erstelle einen Bugreport auf der Bugreport-Seite. Gebe uns so viele Informationen wie du kannst. +nukkit.crash.archive=Eine Crash-Datei wurde in Archiv abgelegt. Du kannst es auf {%0} oder mit der ID #{%1} anschauen. + +nukkit.debug.enable=LevelDB support aktiviert + +nukkit.bugreport.create=Ein Fehler ist entstanden, erstelle ein Bug Report. +nukkit.bugreport.error=Konnte kein Bug Report machen aufgrund: {%0} +nukkit.bugreport.archive=Ein Bug Report wurde erfolgreich erstellt: {%0} + +nukkit.player.invalidMove={%0} bewegte sich fehlerhaft! +nukkit.player.logIn={%0}[/{%1}:{%2}] hat sich mit der ID {%3} bei ({%4}, {%5}, {%6}, {%7}) angemeldet +nukkit.player.logOut={%0}[/{%1}:{%2}] hat sich ausgeloggt {%3} +nukkit.player.invalidEntity={%0} versuchte ein fehlerhaftes Entity anzugreifen + +nukkit.plugin.load=Lade {%0} +nukkit.plugin.enable=Aktiviere {%0} +nukkit.plugin.disable=Deaktiviere {%0} +nukkit.plugin.restrictedName=Verbotener Name +nukkit.plugin.incompatibleAPI=Inkompatible API +nukkit.plugin.unknownDependency=Unbekannte Dependency +nukkit.plugin.circularDependency=Ringabhängigkeit erkannt +nukkit.plugin.genericLoadError=Das Plugin "{%0}" konnte nicht geladen werden. +nukkit.plugin.spacesDiscouraged=Das Plugin "{%0}" nutzt Leerzeichen in seinem Namen, dies ist nicht erlaubt +nukkit.plugin.loadError=Das Plugin "{%0}": {%1} konnte nicht geladen werden. +nukkit.plugin.duplicateError=Das Plugin "{%0}" ist doppelt vorhanden. +nukkit.plugin.fileError=Die Datei "{%0}" im Ordner "{%1}": {%2} konnte nicht geladen werden! +nukkit.plugin.commandError=Der Befehl {%0} vom Plugin {%1} konnte nicht geladen werden! +nukkit.plugin.aliasError=Der Alias {%0} vom Plugin {%1} konnte nicht geladen werden. +nukkit.plugin.deprecatedEvent=Das Plugin "{%0}" hat ein veraltetes Event "{%1}" in Methode "{%2}" benutzt. +nukkit.plugin.eventError=Das Event "{%0}" konnte nicht zu "{%1}": {%2} in Zeile {%3} weitergegeben werden + +nukkit.resources.invalid-path=Resource packs Pfad "{%0}" existiert nicht. +nukkit.resources.unknown-format=Konnte nicht "{%0}" laden weil das Format nicht erkannt wurde. +nukkit.resources.fail=Konnte nicht laden "{%0}": {%1} +nukkit.resources.success=Erfolgreich Resource Pack {%0} geladen. +nukkit.resources.zip.not-found=Datei "{%0}" wurde nicht gefunden. +nukkit.resources.zip.no-manifest="manifest.json" wurde nicht gefunden. +nukkit.resources.zip.invalid-manifest="manifest.json" ist fehlerhaft oder existiert nicht. +nukkit.resources.plugin.loading=Loading resource pack from plugin {%0} diff --git a/src/main/resources/lang/deu/nukkit.yml b/src/main/resources/lang/deu/nukkit.yml new file mode 100644 index 00000000000..785b6b05418 --- /dev/null +++ b/src/main/resources/lang/deu/nukkit.yml @@ -0,0 +1,98 @@ +# Fortgeschrittene Konfiguration für Nukkit +# Bei fehlerhaften Einstellungen kann der Server abstürzen +# Neue Einstellungen/Standards erscheinen nicht automatisch beim upgraden + +settings: + #Multilingual + #Verfügbar: eng, chs, cht, jpn, rus, spa, pol, bra, kor, ukr, deu, ltu, cze + language: "deu" + #Sollen alle Nachrichten in Serversprache ausgegeben werden oder sollen Sie vom Client verarbeitet werden + force-language: false + shutdown-message: "Server heruntergefahren" + #Erlaube das auflisten von Plugins über eine Query + query-plugins: true + #Soll in der Konsole eine Nachricht erscheinen, wenn ein Plugin eine veraltete Funkttiopn verwendet + deprecated-verbose: true + #Anzahl an AsyncTasks + #Wenn es auf auto gestellt ist, wird Nukkit versuchen die Anzahl der Cores zu ermitteln (und setzt mindestens 4) + async-workers: auto + +network: + #Grenze der gesendeten Dateien/Pakete zur gleiden Zeit, in Bytes. Nur diese Pakete werden komprimiert + #Setze zu 0 to um alles zu komprimieren, -1 um die Komprimierung deaktivieren + batch-threshold: 256 + #Komprimierungslevel von Zlib wenn eine Menge Pakete/Daten gesendet werden. Höher = mehr CPU, weniger Bandbreitennutzung + compression-level: 5 + #Enable network encryption + encryption: true + +debug: + #Wenn > 1, werden Debug-Nachrichten in der Konsole angezeigt + level: 1 + +level-settings: + #Das Standard-Welt Format wenn neue Welten erstellt werden + default-format: leveldb + #Automatiches ändern von Ticks in Welten, um 20 Ticks zu erreichen + auto-tick-rate: true + auto-tick-rate-limit: 20 + #Setzt die Tickgeschwindigkeit (1 = 20 Ticks pro Sekunde, 2 = 10 Ticks pro Sekunde, usw.) + base-tick-rate: 1 + #Tick alle Spieler auch wenn es andere Einstellungen verhindern + always-tick-players: false + +chunk-sending: + #Anzahl der Chuncks die während eines Ticks zum Spieler gesendet wird + per-tick: 4 + #Anzahl an Chuncks die gesendet werden sollen, bevor der Spieler spawnt + spawn-threshold: 56 + #Speichere eine Kopie eines Chuncks im Arbeitspeicher um Chuncks schneller zu verarbeiten + #Hilfreich in statischen Welten wo viele Spieler zur gleichen Zeit den Server betreten + cache-chunks: false + +chunk-ticking: + #Maximale Anzahl an Chuncks die, während eines Ticks, verarbeitet werden + per-tick: 40 + #Radius von Chuncks, die bei jedem Tick, bei einem Spieler verarbeitet werden + tick-radius: 3 + clear-tick-list: false + +chunk-generation: + #Maximale Anzahl der Chuncks die generiert werden müssen, in der Warteschlange + queue-size: 8 + #Maximale Anzahl der Chuncks die geladen werden müssen, in der Warteschchlange + population-queue-size: 8 + +leveldb: + #Use native LevelDB implementation for better performance + use-native: false + #Set LevelDB memory cache size + cache-size-mb: 80 + +ticks-per: + autosave: 6000 + +player: + #If true, player data will be saved as players/playername.dat + #If false, nukkit won't save player data as "dat" files, in order that plugins can do something on it. + save-player-data: true + #The time between skin change action in seconds, set to 0 if you dont want the cooldown + skin-change-cooldown: 15 + +aliases: + #Aliasse für Befehle + #Beispiele: + #showtheversion: version + #savestop: [save-all, stop] + +worlds: + #Die Welten, die vom Server gebraucht werden. Optionen sind auf dem Generator spezifisch, und können zu unerwartetem + #Verhalten führen oder komplett ignoriert werden. + world: + #seed: 404 + generator: normal + options: + nether: + #seed: my_cool_nether_seed + generator: nether + options: diff --git a/src/main/resources/lang/eng/lang.ini b/src/main/resources/lang/eng/lang.ini new file mode 100644 index 00000000000..dd2b6b62c53 --- /dev/null +++ b/src/main/resources/lang/eng/lang.ini @@ -0,0 +1,364 @@ +# Language file compatible with Minecraft: Bedrock Edition identifiers +# +# A message doesn't need to be there to be shown correctly on the client. +# Only messages shown in Nukkit itself need to be here +# Using the language property from PocketMine-MP + +language.name=English +language.selected=Selected {%0} ({%1}) as the base language + +multiplayer.player.joined={%0} joined the game +multiplayer.player.left={%0} left the game + +chat.type.text=<{%0}> {%1} +chat.type.emote=* {%0} {%1} +chat.type.announcement=[{%0}] {%1} +chat.type.admin=[{%0}: {%1}] +chat.type.achievement={%0} has just earned the achievement {%1} + +disconnectionScreen.outdatedClient=Outdated client! +disconnectionScreen.outdatedServer=Outdated server! +disconnectionScreen.serverFull=Server is full! +disconnectionScreen.noReason=Disconnected from server +disconnectionScreen.invalidSkin=Invalid skin! +disconnectionScreen.invalidName=Invalid name! +disconnectionScreen.resourcePack=Encountered a problem while downloading or applying resource pack. + +death.fell.accident.generic={%0} fell from a high place +death.attack.inFire={%0} went up in flames +death.attack.onFire={%0} burned to death +death.attack.lava={%0} tried to swim in lava +death.attack.lava.magma={%0} discovered floor was lava +death.attack.inWall={%0} suffocated in a wall +death.attack.drown={%0} drowned +death.attack.cactus={%0} was pricked to death +death.attack.generic={%0} died +death.attack.explosion={%0} blew up +death.attack.explosion.player={%0} was blown up by {%1} +death.attack.magic={%0} was killed by magic +death.attack.wither={%0} withered away +death.attack.mob={%0} was slain by {%1} +death.attack.player={%0} was slain by {%1} +death.attack.player.item={%0} was slain by {%1} using {%2} +death.attack.arrow={%0} was shot by {%1} +death.attack.arrow.item={%0} was shot by {%1} using {%2} +death.attack.fall={%0} hit the ground too hard +death.attack.outOfWorld={%0} fell out of the world +death.attack.starve={%0} starved to death + +gameMode.survival=Survival Mode +gameMode.creative=Creative Mode +gameMode.adventure=Adventure Mode +gameMode.spectator=Spectator Mode +gameMode.changed=Your game mode has been updated + +potion.moveSpeed=Speed +potion.moveSlowdown=Slowness +potion.digSpeed=Haste +potion.digSlowDown=Mining Fatigue +potion.damageBoost=Strength +potion.heal=Instant Health +potion.harm=Instant Damage +potion.jump=Jump Boost +potion.confusion=Nausea +potion.regeneration=Regeneration +potion.resistance=Resistance +potion.fireResistance=Fire Resistance +potion.waterBreathing=Water Breathing +potion.invisibility=Invisibility +potion.blindness=Blindness +potion.nightVision=Night Vision +potion.hunger=Hunger +potion.weakness=Weakness +potion.poison=Poison +potion.wither=Wither +potion.healthBoost=Health Boost +potion.absorption=Absorption +potion.saturation=Saturation + +commands.generic.exception=An unknown error occurred while attempting to perform this command +commands.generic.permission=You do not have permission to use this command +commands.generic.ingame=You can only perform this command as a player +commands.generic.unknown=Unknown command. Try /help for a list of commands +commands.generic.player.notFound=That player cannot be found +commands.generic.usage=Usage: {%0} + +commands.time.added=Added {%0} to the time +commands.time.set=Set the time to {%0} +commands.time.query=Time is {%0} + +commands.me.usage=/me <action ...> + +commands.give.item.notFound=There is no such item with name {%0} +commands.give.success=Given {%0} * {%1} to {%2} +commands.give.tagError=Data tag parsing failed: {%0} + +commands.effect.usage=/effect <player> <effect> [seconds] [amplifier] [hideParticles] OR /effect <player> clear +commands.effect.notFound=There is no such mob effect with ID {%0} +commands.effect.success=Given {%0} (ID {%1}) * {%2} to {%3} for {%4} seconds +commands.effect.success.removed=Took {%0} from {%1} +commands.effect.success.removed.all=Took all effects from {%0} +commands.effect.failure.notActive=Couldn't take {%0} from {%1} as they do not have the effect +commands.effect.failure.notActive.all=Couldn't take any effects from {%0} as they do not have any + +commands.enchant.noItem=The target doesn't hold an item +commands.enchant.notFound=There is no such enchantment with ID {%0} +commands.enchant.success=Enchanting succeeded +commands.enchant.usage=/enchant <player> <enchantment ID> [level] + +commands.particle.success=Playing effect {%0} for {%1} times +commands.particle.notFound=Unknown effect name {%0} + +commands.players.usage=/list +commands.players.list=There are {%0}/{%1} players online: + +commands.kill.successful=Killed {%0} +commands.kill.all.successful=Killed all players +commands.kill.entities.successful=Killed all entities + +commands.banlist.ips=There are {%0} total banned IP addresses: +commands.banlist.players=There are {%0} total banned players: +commands.banlist.usage=/banlist [ips|players] + +commands.defaultgamemode.usage=/defaultgamemode <mode> +commands.defaultgamemode.success=The world's default game mode is now {%0} + +commands.op.success=Opped {%0} +commands.op.usage=/op <player> + +commands.deop.success=De-opped {%0} +commands.deop.usage=/deop <player> + +commands.say.usage=/say <message ...> + +commands.seed.usage=/seed +commands.seed.success=Seed: {%0} + +commands.summon.success=Object successfully summoned +commands.summon.failed=Unable to summon object + +commands.ban.success=Banned player {%0} +commands.ban.usage=/ban <name> [reason ...] + +commands.unban.success=Unbanned player {%0} +commands.unban.usage=/pardon <name> + +commands.banip.invalid=You have entered an invalid IP address or a player that is not online +commands.banip.offline.invalid=There is no IP address in player data or IP address is invalid +commands.banip.success=Banned IP address {%0} +commands.banip.success.players=Banned IP address {%0} belonging to {%1} +commands.banip.usage=/ban-ip <address|name> [reason ...] + +commands.unbanip.invalid=You have entered an invalid IP address +commands.unbanip.success=Unbanned IP address {%0} +commands.unbanip.usage=/pardon-ip <address> + +commands.save.usage=/save [on|off|hold|resume] +commands.save.enabled=Turned on world auto-saving +commands.save.disabled=Turned off world auto-saving +commands.save.start=Saving... +commands.save.success=Saved the world + +commands.stop.usage=/stop +commands.stop.start=Stopping the server + +commands.kick.success=Kicked {%0} from the game +commands.kick.success.reason=Kicked {%0} from the game: '{%1}' +commands.kick.usage=/kick <player> [reason ...] + +commands.tp.success=Teleported {%0} to {%1} +commands.tp.success.coordinates=Teleported {%0} to {%1}, {%2}, {%3} +commands.tp.usage=/tp [target player] <destination player> OR /tp [target player] <x> <y> <z> [<y-rot> <x-rot>] + +commands.whitelist.list=There are {%0} (out of {%1} seen) whitelisted players: +commands.whitelist.enabled=Turned on the whitelist +commands.whitelist.disabled=Turned off the whitelist +commands.whitelist.reloaded=Reloaded the whitelist +commands.whitelist.add.success=Added {%0} to the whitelist +commands.whitelist.add.usage=/whitelist add <player> +commands.whitelist.remove.success=Removed {%0} from the whitelist +commands.whitelist.remove.usage=/whitelist remove <player> +commands.whitelist.usage=/whitelist <on|off|list|add|remove|reload> + +commands.gamemode.success.self=Set own game mode to {%0} +commands.gamemode.success.other=Set {%0}'s game mode to {%1} +commands.gamemode.fail.invalid=Game mode '{%0}' is invalid +commands.gamemode.usage=/gamemode <mode> [player] + +commands.help.header=--- Showing help page {%0} of {%1} (/help <page>) --- +commands.help.usage=/help [page|command name] + +commands.message.usage=/tell <player> <private message ...> +commands.message.sameTarget=You can't send a private message to yourself! + +commands.difficulty.usage=/difficulty <new difficulty> +commands.difficulty.success=Set game difficulty to {%0} + +commands.spawnpoint.usage=/spawnpoint [player] [<x> <y> <z>] +commands.spawnpoint.success=Set {%0}'s spawn point to ({%1}, {%2}, {%3}) + +commands.setworldspawn.usage=/setworldspawn [<x> <y> <z>] +commands.setworldspawn.success=Set the world spawn point to ({%0}, {%1}, {%2}) + +commands.weather.clear=Changing to clear weather +commands.weather.rain=Changing to rainy weather +commands.weather.thunder=Changing to rain and thunder +commands.weather.usage=/weather <clear|rain|thunder> [duration in seconds] + +commands.xp.success=Given {%0} experience to {%1} +commands.xp.success.levels=Given {%0} levels to {%1} +commands.xp.success.levels.minus=Taken {%0} levels from {%1} +commands.xp.usage=/xp <amount> [player] OR /xp <level>L [player] + +# -------------------- Nukkit language files, only for console -------------------- + +nukkit.data.playerNotFound=Player data not found for "{%0}", creating new profile +nukkit.data.playerCorrupted=Corrupted data found for "{%0}", creating new profile +nukkit.data.playerOld=Old Player data found for "{%0}", upgrading profile +nukkit.data.saveError=Could not save player "{%0}": {%1} + +nukkit.level.notFound=Level "{%0}" not found +nukkit.level.loadError=Could not load level "{%0}": {%1} +nukkit.level.generationError=Could not generate level "{%0}": {%1} +nukkit.level.tickError=Could not tick level "{%0}": {%1} +nukkit.level.chunkUnloadError=Error while unloading a chunk: {%0} +nukkit.level.backgroundGeneration=Spawn terrain for level "{%0}" is being generated in the background +nukkit.level.defaultError=No default level has been loaded +nukkit.level.preparing=Preparing level "{%0}" +nukkit.level.unloading=Unloading level "{%0}" +nukkit.level.updating=Old level data found for "{%0}", converting format + +nukkit.server.start=Starting Minecraft: BE server version {%0} +nukkit.server.networkError=[Network] Stopped interface {%0} due to {%1} +nukkit.server.networkStart=Opening server on {%0}:{%1} +nukkit.server.info=This server is running {%0} version {%1} "{%2}" (API {%3}) +nukkit.server.info.extended=This server is running {%0} {%1} 「{%2}」 implementing API version {%3} for Minecraft: BE {%4} (protocol version {%5}) +nukkit.server.license={%0} is distributed under the GPL License +nukkit.server.tickOverload=Can't keep up! Is the server overloaded? +nukkit.server.startFinished=Done ({%0}s)! For help, type "help" or "?" +nukkit.server.defaultGameMode=Default game type: {%0} +nukkit.server.query.start=Starting GS4 status listener +nukkit.server.query.info=Setting query port to {%0} +nukkit.server.query.running=Query is running on {%0}:{%1} +nukkit.server.rcon.emptyPasswordError=Failed to start RCON: password is empty +nukkit.server.rcon.startupError=Failed to start RCON: {%0} +nukkit.server.rcon.running=RCON is running on {%0}:{%1} + +nukkit.command.alias.illegal=Could not register alias {%0} because it contains illegal characters +nukkit.command.alias.notFound=Could not register alias {%0} because it contains commands that do not exist: {%1} +nukkit.command.exception=Unhandled exception executing command "{%0}" in {%1}: {%2} + +nukkit.command.plugins.description=Gets a list of plugins running on the server +nukkit.command.plugins.success=Plugins ({%0}): {%1} +nukkit.command.plugins.usage=/plugins + +nukkit.command.reload.description=Reloads the server configuration and plugins +nukkit.command.reload.usage=/reload +nukkit.command.reload.reloading=Reloading server... +nukkit.command.reload.reloaded=Reload complete. + +nukkit.command.status.description=Reads back the server's performance. +nukkit.command.status.usage=/status + +nukkit.command.gc.description=Fires garbage collection tasks +nukkit.command.gc.usage=/gc + +nukkit.command.title.description=Sends a title to the specified player or modifies title settings for that player +nukkit.command.title.usage=/title <player> <clear|reset> OR /title <player> <title|subtitle|actionbar> <title text> OR /title <player> <times> <fade in time> <stay time> <fade out time> +nukkit.command.title.clear=Successfully cleared {%0}'s screen +nukkit.command.title.reset=Successfully reset title animation settings for {%0} +nukkit.command.title.title=Successfully shown "{%0}" title to {%1} +nukkit.command.title.subtitle=Successfully set subtitle to "{%0}" for {%1}'s next title +nukkit.command.title.actionbar=Successfully shown "{%0}" actionbar title to {%1} +nukkit.command.title.times.success=Successfully set title animation times to {%0}, {%1}, {%2} for {%3} +nukkit.command.title.times.fail=Times of title animations must be numeric values + +nukkit.command.version.description=Gets the version of this server including any plugins in use +nukkit.command.version.usage=/version [plugin name] +nukkit.command.version.noSuchPlugin=This server is not running any plugin by that name. Use /plugins to get a list of plugins. + +nukkit.command.give.description=Gives the specified player a certain amount of items +nukkit.command.give.usage=/give <player> <item[:damage]> [amount] [tags ...] + +nukkit.command.kill.description=Commit suicide or kill other players +nukkit.command.kill.usage=/kill [player] + +nukkit.command.particle.description=Adds particles to a world +nukkit.command.particle.usage=/particle <name> <x> <y> <z> <xd> <yd> <zd> [count] [data] + +nukkit.command.time.description=Changes the time on each world +nukkit.command.time.usage=/time <set|add> <value> OR /time <start|stop|query> + +nukkit.command.gamerule.description=Sets or queries a game rule value +nukkit.command.gamerule.usage=/gamerule <rule> [value] + +nukkit.command.ban.player.description=Prevents the specified player from using this server +nukkit.command.ban.ip.description=Prevents the specified IP address from using this server +nukkit.command.banlist.description=View all players banned from this server +nukkit.command.defaultgamemode.description=Set the default gamemode +nukkit.command.deop.description=Takes the specified player's operator status +nukkit.command.difficulty.description=Sets the game difficulty +nukkit.command.enchant.description=Adds enchantments on items +nukkit.command.effect.description=Adds/Removes effects on players +nukkit.command.gamemode.description=Changes the player to a specific game mode +nukkit.command.help.description=Shows the help menu +nukkit.command.kick.description=Removes the specified player from the server +nukkit.command.list.description=Lists all online players +nukkit.command.me.description=Performs the specified action in chat +nukkit.command.op.description=Gives the specified player operator status +nukkit.command.unban.player.description=Allows the specified player to use this server +nukkit.command.unban.ip.description=Allows the specified IP address to use this server +nukkit.command.save.description=Saves the server to disk + +nukkit.command.say.description=Broadcasts the given message as the sender +nukkit.command.seed.description=Shows the world seed +nukkit.command.setworldspawn.description=Sets a worlds's spawn point. If no coordinates are specified, the player's coordinates will be used. +nukkit.command.spawnpoint.description=Sets a player's spawn point +nukkit.command.stop.description=Stops the server +nukkit.command.tp.description=Teleports the given player (or yourself) to another player or coordinates +nukkit.command.tell.description=Sends a private message to the given player +nukkit.command.weather.description=Sets the weather in current world +nukkit.command.xp.description=Gives the specified player a certain amount of experience +nukkit.command.whitelist.description=Manages the list of players allowed to use this server + +nukkit.crash.create=An unrecoverable error has occurred and the server has crashed. Creating a crash dump +nukkit.crash.error=Could not create crash dump: {%0} +nukkit.crash.submit=Please upload the "{%0}" file to the Crash Archive and submit the link to the Bug Reporting page. Give as much info as you can. +nukkit.crash.archive=The crash dump has been automatically submitted to the Crash Archive. You can view it on {%0} or use the ID #{%1}. + +nukkit.debug.enable=LevelDB support enabled + +nukkit.bugreport.create=An error has been detected, creating a bug report. +nukkit.bugreport.error=Could not create bug report: {%0} +nukkit.bugreport.archive=A bug report has been created: {%0} + +nukkit.player.invalidMove={%0} moved wrongly! +nukkit.player.logIn={%0}[/{%1}:{%2}] logged in with entity id {%3} at ({%4}, {%5}, {%6}, {%7}) +nukkit.player.logOut={%0}[/{%1}:{%2}] logged out due to {%3} +nukkit.player.invalidEntity={%0} tried to attack an invalid entity + +nukkit.plugin.load=Loading {%0} +nukkit.plugin.enable=Enabling {%0} +nukkit.plugin.disable=Disabling {%0} +nukkit.plugin.restrictedName=Restricted name +nukkit.plugin.incompatibleAPI=Incompatible API version +nukkit.plugin.unknownDependency=Unknown dependency +nukkit.plugin.circularDependency=Circular dependency detected +nukkit.plugin.genericLoadError=Could not load plugin "{%0}" +nukkit.plugin.spacesDiscouraged=Plugin "{%0}" uses spaces in its name, this is discouraged +nukkit.plugin.loadError=Could not load plugin "{%0}": {%1} +nukkit.plugin.duplicateError=Could not load plugin "{%0}": plugin exists +nukkit.plugin.fileError=Could not load "{%0}" in folder "{%1}": {%2} +nukkit.plugin.commandError=Could not load command {%0} for plugin {%1} +nukkit.plugin.aliasError=Could not load alias {%0} for plugin {%1} +nukkit.plugin.deprecatedEvent=Plugin "{%0}" has registered a listener for "{%1}" on method "{%2}", but the event is Deprecated. +nukkit.plugin.eventError=Could not pass event "{%0}" to "{%1}": {%2} on {%3} + +nukkit.resources.invalid-path=Resource packs path "{%0}" exists and is not a directory +nukkit.resources.unknown-format=Could not load "{%0}" due to format not recognized +nukkit.resources.fail=Could not load "{%0}": {%1} +nukkit.resources.success=Successfully loaded {%0} resource packs +nukkit.resources.zip.not-found=File "{%0}" is not found +nukkit.resources.zip.no-manifest="manifest.json" is not found +nukkit.resources.zip.invalid-manifest="manifest.json" is invalid or incomplete +nukkit.resources.plugin.loading=Loading resource pack from plugin {%0} diff --git a/src/main/resources/lang/eng/nukkit.yml b/src/main/resources/lang/eng/nukkit.yml new file mode 100644 index 00000000000..f6cd617b524 --- /dev/null +++ b/src/main/resources/lang/eng/nukkit.yml @@ -0,0 +1,101 @@ +# Advanced configuration file for Nukkit +# Some of these settings are safe, others can break your server if modified incorrectly +# New settings/defaults won't appear automatically on this file when upgrading + +settings: + #Multi-language setting + #Available: eng, chs, cht, jpn, rus, spa, pol, bra, kor, ukr, deu, ltu, idn, cze, tur, fin + language: "eng" + #Whether to send all strings translated to server locale or let the device handle them + force-language: false + shutdown-message: "Server closed" + #Allow listing plugins via Query + query-plugins: true + #Show a console message when a plugin uses deprecated API methods + deprecated-verbose: true + #Number of AsyncTask workers + #If set to auto, it'll try to detect the number of cores (and at least 4) + async-workers: auto + +network: + #Threshold for batching packets, in bytes. Only these packets will be compressed + #Set to 0 to compress everything, -1 to disable + batch-threshold: 256 + #Compression level used of Zlib when sending batched packets. Higher = more CPU, less bandwidth usage + compression-level: 5 + #Enable network encryption + encryption: true + +debug: + #If > 1, it will show debug messages in the console + level: 1 + +level-settings: + #The default format that levels will use when created + default-format: leveldb + #Automatically change levels tick rate to maintain 20 ticks per second + auto-tick-rate: true + auto-tick-rate-limit: 20 + #Sets the base tick rate (1 = 20 ticks per second, 2 = 10 ticks per second, etc.) + base-tick-rate: 1 + #Tick all players each tick even when other settings disallow this + always-tick-players: false + +chunk-sending: + #Amount of chunks sent to players per tick + per-tick: 4 + #Amount of chunks that need to be sent before spawning the player + spawn-threshold: 56 + #Save a serialized copy of the chunk in memory for faster sending + #Useful in mostly-static worlds where lots of players join at the same time + cache-chunks: false + +chunk-ticking: + #Max amount of chunks processed each tick + per-tick: 40 + #Radius of chunks around a player to tick + tick-radius: 3 + clear-tick-list: false + +chunk-generation: + #Max. amount of chunks in the waiting queue to be generated + queue-size: 8 + #Max. amount of chunks in the waiting queue to be populated + population-queue-size: 8 + +leveldb: + #Use native LevelDB implementation for better performance + use-native: false + #Set LevelDB memory cache size + cache-size-mb: 80 + +ticks-per: + #How often worlds and player data are saved when auto-save=on in server.properties + autosave: 6000 + +player: + #If true, player data will be saved as players/playername.dat + #If false, nukkit won't save player data as "dat" files, in order that plugins can do something on it. + save-player-data: true + #The time between skin change action in seconds, set to 0 if you dont want the cooldown + skin-change-cooldown: 15 + #Attacking entities resets sprinting, you can disable that here + attack-stop-sprint: true + +aliases: + #Aliases for commands + #Examples: + #showtheversion: version + #savestop: [save-all, stop] + +worlds: + #Worlds that the server will use. Options are specific to the chosen generator, and may result in broken generation or + #be ignored completely. + world: + #seed: 404 + generator: normal + #options: + nether: + #seed: my_cool_nether_seed + generator: nether + #options: diff --git a/src/main/resources/lang/fin/lang.ini b/src/main/resources/lang/fin/lang.ini new file mode 100644 index 00000000000..aabc20af6e5 --- /dev/null +++ b/src/main/resources/lang/fin/lang.ini @@ -0,0 +1,361 @@ +# Language file compatible with Minecraft: Bedrock Edition identifiers +# +# A message doesn't need to be there to be shown correctly on the client. +# Only messages shown in Nukkit itself need to be here +# Using the language property from PocketMine-MP + +language.name=Suomi +language.selected=Valittiin kieleksi suomi (fin) + +multiplayer.player.joined={%0} liittyi peliin +multiplayer.player.left={%0} poistui pelistä + +chat.type.text=<{%0}> {%1} +chat.type.emote=* {%0} {%1} +chat.type.announcement=[{%0}] {%1} +chat.type.admin=[{%0}: {%1}] +chat.type.achievement={%0} ansaitsi saavutuksen {%1} + +disconnectionScreen.outdatedClient=Vanhentunut asiakasohjelma! +disconnectionScreen.outdatedServer=Vanhentunut palvelin! +disconnectionScreen.serverFull=Palvelin on täynnä! +disconnectionScreen.noReason=Yhteys palvelimeen katkaistu +disconnectionScreen.invalidSkin=Virheellinen olemus! +disconnectionScreen.invalidName=Virheellinen nimi! +disconnectionScreen.resourcePack=Resurssipaketin kanssa esiintyi ongelma + +death.fell.accident.generic={%0} putosi korkealta +death.attack.inFire={%0} paloi poroksi +death.attack.onFire={%0} käristyi korpuksi +death.attack.lava={%0} yritti uida laavassa +death.attack.lava.magma={%0} huomasi lattian olevan laavaa +death.attack.inWall={%0} tukehtui seinään +death.attack.drown={%0} hukkui +death.attack.cactus={%0} tunsi piston sydämmessään ja kuoli +death.attack.generic={%0} kuoli +death.attack.explosion={%0} räjähti +death.attack.explosion.player={%0} joutui pelaajan {%1} räjäyttämäksi +death.attack.magic={%0} taiottiin hengiltä +death.attack.wither={%0} näivettyi hengiltä +death.attack.mob={%1} tappoi pelaajan {%0} +death.attack.player={%1} tappoi pelaajan {%0} +death.attack.player.item={%1} tappoi pelaajan {%0} käyttäen {%2} +death.attack.arrow={%1} ampui pelaajan {%0} +death.attack.arrow.item={%0} joutui pelaajan {%1} ampumaksi aseella {%2} +death.attack.fall={%0} iskeytyi maahan liian lujaa +death.attack.outOfWorld={%0} tipahti maailman laidalta +death.attack.starve={%0} nääntyi nälkään + +gameMode.survival=Selviytyjä +gameMode.creative=Nikkaroija +gameMode.adventure=Seikkailija +gameMode.spectator=Katsoja +gameMode.changed=Pelimuotosi on päivitetty + +potion.moveSpeed=Nopeutus +potion.moveSlowdown=Hidastus +potion.digSpeed=Pikakaivuu +potion.digSlowDown=Kaivuuhidastus +potion.damageBoost=Lisävoima +potion.heal=Pikaparannus +potion.harm=Pikavahinko +potion.jump=Tehohyppy +potion.confusion=Yökötys +potion.regeneration=Parantuminen +potion.resistance=Sietokyky +potion.fireResistance=Tulensieto +potion.waterBreathing=Kidukset +potion.invisibility=Näkymättömyys +potion.blindness=Sokeutus +potion.nightVision=Yönäkö +potion.hunger=Nälkä +potion.weakness=Heiveröitys +potion.poison=Myrkky +potion.wither=Näivetys +potion.healthBoost=Kuntotehoste +potion.absorption=Imeytyminen +potion.saturation=Kyllästyminen + +commands.generic.exception=Tämän komennon suorittamisen yhteydessä tapahtui tuntematon virhe +commands.generic.permission=Sinulla ei ole oikeutta käyttää tätä komentoa +commands.generic.ingame=Voit käyttää tätä komentoa vain ollessasi pelaaja +commands.generic.unknown=Tuntematon komento. Kokeile /help nähdäksesi listan komennoista. +commands.generic.player.notFound=Pelaajaa ei löydy +commands.generic.usage=Käyttö: {%0} + +commands.time.added=Lisätty {%0} aikaan +commands.time.set=Aseta ajaksi {%0} +commands.time.query=Aika on {%0} + +commands.me.usage=/me <toiminto ...> + +commands.give.item.notFound=Esinettä nimellä {%0} ei löytynyt +commands.give.success=Annettin {%0} * {%1} pelaajalle {%2} +commands.give.tagError=Tagin parsinta epäonnistui: {%0} + +commands.effect.usage=/effect <pelaaja> <vaikutus> [sekuntteja] [vahvuus] [piilota partikkelit] TAI /effect <pelaaja> clear +commands.effect.notFound=Vaikutusta tunnuksella {%0} ei löytynyt +commands.effect.success=Annettiin {%0} (ID {%1}) * {%2} pelaajalle {%3} {%4} sekunniksi +commands.effect.success.removed=Poistettiin {%0} pelaajalta {%1} +commands.effect.success.removed.all=Poistettiin kaikki vaikutukset pelaajalta {%0} +commands.effect.failure.notActive=Ei voitu poistaa vaikutusta {%0} pelaajalta {%1}, koska sitä ei ole +commands.effect.failure.notActive.all=Ei voitu poistaa vaikutuksia pelaajalta {%0}, koska niitä ei ole + +commands.enchant.noItem=Kohteella ei ole esinettä kädessään +commands.enchant.notFound=Lumousta tunnuksella {%0} ei ole +commands.enchant.success=Lumous onnistui +commands.enchant.usage=/enchant <pelaaja> <lumouksen tunnus> [taso] + +commands.particle.success=Näytetään vaikutus {%0} {%1} kertaa +commands.particle.notFound=Tuntematon vaikutus: {%0} + +commands.players.usage=/list +commands.players.list={%0}/{%1} pelaajaa: + +commands.kill.successful=Tapettu {%0} +commands.kill.all.successful=Tapettiin kaikki pelaajat +commands.kill.entities.successful=Tapettiin kaikki olennot + +commands.banlist.ips={%0} estettyä IP osoitetta: +commands.banlist.players={%0} estettyä pelaajaa: +commands.banlist.usage=/banlist [ip:t|pelaajat] + +commands.defaultgamemode.usage=/defaultgamemode <pelitila> +commands.defaultgamemode.success=Maailman oletuspelitila on nyt {%0} + +commands.op.success=Ylennettiin pelaaja {%0} +commands.op.usage=/op <pelaaja> + +commands.deop.success=Alennettiin pelaaja {%0} +commands.deop.usage=/deop <pelaaja> + +commands.say.usage=/say <viesti ...> + +commands.seed.usage=/seed +commands.seed.success=Siemen: {%0} + +commands.ban.success=Estettiin pelaaja {%0} +commands.ban.usage=/ban <nimi> [syy ...] + +commands.unban.success=Esto poistettu pelaajalta {%0} +commands.unban.usage=/pardon <nimi> + +commands.banip.invalid=Virheellinen IP osoite tai pelaaja ei ole paikalla +commands.banip.offline.invalid=IP osoitetta ei löytynyt pelaajatiedoista +commands.banip.success=Estettiin IP osoite {%0} +commands.banip.success.players=Estettiin IP osoite {%0} joka kuuluu pelaajalle {%1} +commands.banip.usage=/ban-ip <osoite|nimi> [syy ...] + +commands.unbanip.invalid=Virheellinen IP osoite +commands.unbanip.success=Poistettiin esto osoitteelta {%0} +commands.unbanip.usage=/pardon-ip <osoite> + +commands.save.usage=/save [on|off|hold|resume] +commands.save.enabled=Otettiin maailman käyttöön automaattinen tallennus +commands.save.disabled=Poistettiin maailman automaattinen tallennus käytöstä +commands.save.start=Tallennetaan... +commands.save.success=Maailma tallennettu + +commands.stop.usage=/stop +commands.stop.start=Pysäytetään palvelinta... + +commands.kick.success=Poistettiin pelaaja {%0} pelistä +commands.kick.success.reason=Poistettiin pelaaja {%0} pelistä: "{%1}" +commands.kick.usage=/kick <pelaaja> [syy ...] + +commands.tp.success=Kaukosiirrettiin {%0} paikkaan {%1} +commands.tp.success.coordinates=Kaukosiirrettiin {%0} paikkaan {%1}, {%2}, {%3} +commands.tp.usage=/tp [kohdepelaaja] <kohdepelaaja> TAI /tp [kohdepelaaja] <x> <y> <z> [<y-rot> <x-rot>] + +commands.whitelist.list=Täällä on {%0}/{%1} valkoisella listalla olevaa pelaajaa: +commands.whitelist.enabled=Otettiin valkoinen lista käyttöön +commands.whitelist.disabled=Poistettiin valkoinen lista käytöstä +commands.whitelist.reloaded=Ladattiin valkoinen lista uudelleen +commands.whitelist.add.success=Lisättiin {%0} valkoiselle listalle +commands.whitelist.add.usage=/whitelist add <pelaaja> +commands.whitelist.remove.success=Poistettiin {%0} valkoiselta listalta +commands.whitelist.remove.usage=/whitelist remove <pelaaja> +commands.whitelist.usage=/whitelist <on|off|list|add|remove|reload> + +commands.gamemode.success.self=Vaihdettiin pelitilaksi {%0} +commands.gamemode.success.other=Vaihdettiin pelaajan {%0} pelitilaksi {%1} +commands.gamemode.usage=/gamemode <pelitila> [pelaaja] + +commands.help.header=--- Näytetään sivu {%0}/{%1} (/help <sivu>) --- +commands.help.usage=/help [sivu|komennon nimi] + +commands.message.usage=/tell <pelaaja> <yksityinen viesti ...> +commands.message.sameTarget=Et voi lähettää yksityisviestiä itsellesi! + +commands.difficulty.usage=/difficulty <uusi vaikeustaso> +commands.difficulty.success=Asetettiin vaikeustasoksi {%0} + +commands.spawnpoint.usage=/spawnpoint [pelaaja] [<x> <y> <z>] +commands.spawnpoint.success=Asetettiin pelaajan {%0} synnyinpaikka ({%1}, {%2}, {%3}) + +commands.setworldspawn.usage=/setworldspawn [<x> <y> <z>] +commands.setworldspawn.success=Asetettiin maailman synnyinpaikka ({%0}, {%1}, {%2}) + +commands.weather.clear=Vaihdetaan selkeään säähän +commands.weather.rain=Vaihdetaan sateiseen säähän +commands.weather.thunder=Vaihdetaan sateeseen ja ukonilmaan +commands.weather.usage=/weather <clear|rain|thunder> [kesto sekuntteina] + +commands.xp.success=Annettiin {%0} kokemuspistettä pelaajalle {%1} +commands.xp.success.levels=Annettiin {%0} tasoa pelaajalle {%1} +commands.xp.success.levels.minus=Otettiin {%0} tasoa pelaajalta {%1} +commands.xp.usage=/xp <määrä> [pelaaja] TAI /xp <taso>L [pelaaja] + +# -------------------- Nukkitin kielitiedostot, vain konsolille -------------------- + +nukkit.data.playerNotFound=Pelaajatietoja pelaajalle "{%0}" ei löytynyt, luodaan uusi profiili +nukkit.data.playerCorrupted=Vioittuneet pelaajatiedot löytyivät pelaajalle "{%0}", luodaan uusi profiili +nukkit.data.playerOld=Vanhat pelaajatiedot löytyivät pelaajalle "{%0}", päivitetään profiili +nukkit.data.saveError=Ei voitu tallentaa pelaajan "{%0}" tietoja: {%1} + +nukkit.level.notFound=Maailmaa "{%0}" ei löytynyt +nukkit.level.loadError=Maailmaa "{%0}" ei voida ladata: {%1} +nukkit.level.generationError=Maailmaa "{%0}" ei voida luoda: {%1} +nukkit.level.tickError=Maailmaa "{%0}" ei voida tickata: {%1} +nukkit.level.chunkUnloadError=Virhe vapauttaessa lohkoa: {%0} +nukkit.level.backgroundGeneration=Synnyinpaikan maasto maailmalle "{%0}" luodaan taustalla +nukkit.level.defaultError=Oletusmaailmaa ei ladattu +nukkit.level.preparing=Valmistellaan maailmaa "{%0}" +nukkit.level.unloading=Vapautetaan maailmaa "{%0}" +nukkit.level.updating=Vanhat maailman tiedot löytyivät maailmalle "{%0}", muutetaan formaattia + +nukkit.server.start=Käynnistetään Minecraft BE palvelinta versiolle {%0} +nukkit.server.networkError=[Verkko] Pysäytettiin liitäntä {%0}: {%1} +nukkit.server.networkStart=Avataan palvelinta osoitteessa {%0}:{%1} +nukkit.server.info=Tämä palvelin käyttää {%0} versiota {%1} "{%2}" (API {%3}) +nukkit.server.info.extended=Tämä palvelin {%0} versiota {%1} 「{%2}」 API {%3} Minecraft BE:n versio {%4}:lle (protokollaversio {%5}) +nukkit.server.license={%0} jaetaan GPL-lisenssin alaisena +nukkit.server.tickOverload=Ei pysyä ylhäällä! Onko palvelin ylikuormitettu? +nukkit.server.startFinished=Valmis ({%0}s)! Kirjoita "help" tai "?" saadaksesi apua +nukkit.server.defaultGameMode=Oletuspelitila: {%0} +nukkit.server.query.start=Käynnistetään GS4-tilan kuuntelija +nukkit.server.query.info=Käynnistetään query portissa {%0} +nukkit.server.query.running=Query on käynnissä osoitteessa {%0}:{%1} +nukkit.server.rcon.emptyPasswordError=RCON käynnistys epäonnistui: salasana on tyhjä +nukkit.server.rcon.startupError=RCON käynnistys epäonnistui: {%0} +nukkit.server.rcon.running=RCON on käynnissä osoitteessa {%0}:{%1} + +nukkit.command.alias.illegal=Aliasta {%0} ei voida rekisteröidä, koska se sisältää sopimattomia merkkejä +nukkit.command.alias.notFound=Aliasta {%0} ei voida rekisteröidä, koska se sisältää komentoja, joita ei ole: {%1} +nukkit.command.exception=Käsittelemätön poikkeustoiminnon komento "{%0}" {%1}: {%2} + +nukkit.command.plugins.description=Hanki lista palvelimen lisäosista +nukkit.command.plugins.success=Lisäosat ({%0}): {%1} +nukkit.command.plugins.usage=/plugins + +nukkit.command.reload.description=Lataa uudelleen palvelimen asetukset ja lisäosat +nukkit.command.reload.usage=/reload +nukkit.command.reload.reloading=Uudelleenladataan... +nukkit.command.reload.reloaded=Uudelleenlataus valmis + +nukkit.command.status.description=Tietoa palvelimen suorituskyvystä +nukkit.command.status.usage=/status + +nukkit.command.gc.description=Suorita garbage collection +nukkit.command.gc.usage=/gc + +nukkit.command.title.description=Lähetä otsikko pelaajalle tai muuta pelaajan otsikko asetuksia +nukkit.command.title.usage=/title <pelaaja> <clear|reset> TAI /title <pelaaja> <title|subtitle|actionbar> <otsikon teksti> TAI /title <pelaaja> <aika> <fade in aika> <kesto> <fade out aika> +nukkit.command.title.clear=Pyyhittiin pelaajan {%0} näyttö +nukkit.command.title.reset=Nollattiin pelaajan {%0} otsikko animaatio asetukset +nukkit.command.title.title=Näytettiin otsikko "{%0}" pelaajalle {%1} +nukkit.command.title.subtitle=Näytettiin alaotsikko "{%0}" pelaajalle {%1} +nukkit.command.title.actionbar=Näytettiin actionbar title "{%0}" pelaajalle {%1} +nukkit.command.title.times.success=Asetettiin otsikon animaation ajat {%0}, {%1}, {%2} pelaajalle {%3} +nukkit.command.title.times.fail=Animaation aikojen tulee olla numeroita + +nukkit.command.version.description=Näytä palvelimen tai lisäosan versio +nukkit.command.version.usage=/version [lisäosan nimi] +nukkit.command.version.noSuchPlugin=Lisäosaa ei löytynyt annetulla nimellä. Kirjoita /plugins nähdäksesi listan lisäosista. + +nukkit.command.give.description=Anna esineitä pelaajalle +nukkit.command.give.usage=/give <pelaaja> <esine[:vahinko]> [määrä] [tagit ...] + +nukkit.command.kill.description=Tee itsemurha tai tapa pelaaja +nukkit.command.kill.usage=/kill [pelaaja] + +nukkit.command.particle.description=Lisää maailmaan partikkeleja +nukkit.command.particle.usage=/particle <nimi> <x> <y> <z> <xd> <yd> <zd> [määrä] [data] + +nukkit.command.time.description=Muuta maailman aikaa +nukkit.command.time.usage=/time <set|add> <arvo> TAI /time <start|stop|query> + +nukkit.command.gamerule.description=Aseta pelisäännön arvo tai kysy sitä +nukkit.command.gamerule.usage=/gamerule <sääntö> [arvo] + +nukkit.command.ban.player.description=Estä pelaaja +nukkit.command.ban.ip.description=Estä IP osoite +nukkit.command.banlist.description=Näytä kaikki estetyt pelaajat +nukkit.command.defaultgamemode.description=Aseta oletuspelimuoto +nukkit.command.deop.description=Poista pelaajan OP oikeudet +nukkit.command.difficulty.description=Aseta vaikeustaso +nukkit.command.enchant.description=Lumoa esine +nukkit.command.effect.description=Lisää tai poista pelaajan vaikutuksia +nukkit.command.gamemode.description=Muuta pelaajan pelitila +nukkit.command.help.description=Näytä apuvalikko +nukkit.command.kick.description=Poista pelaaja pelistä +nukkit.command.list.description=Näytä pelaajalista +nukkit.command.me.description=Suorita tehtävä chatissa +nukkit.command.op.description=Anna pelaajalle OP oikeudet +nukkit.command.unban.player.description=Poista pelaajan esto +nukkit.command.unban.ip.description=Poista IP osoitteen esto +nukkit.command.save.description=Tallenna maailma +nukkit.command.saveoff.description=Poista automaattinen tallennus käytöstä +nukkit.command.saveon.description=Ota automaattinen tallennus käyttöön +nukkit.command.say.description=Lähetä viesti +nukkit.command.seed.description=Näytä maailman siemen +nukkit.command.setworldspawn.description=Aseta maailman syntypiste. Käytetään pelaajan sijaintia jos koordinaatteja ei anneta. +nukkit.command.spawnpoint.description=Aseta pelaajan syntypiste +nukkit.command.stop.description=Pysäytä palvelin +nukkit.command.tp.description=Kaukosiirrä pelaaja tai itsesi toisen pelaajan luo tai annettuun paikkaan +nukkit.command.tell.description=Lähetä yksityisviesti pelaajalle +nukkit.command.weather.description=Aseta maailman sää +nukkit.command.xp.description=Anna pelaajalle kokemuspisteitä +nukkit.command.whitelist.description=Muuta valkoista listaa + +nukkit.crash.create=Ohittamaton virhe on tapahtunut ja palvelin on kaatunut. Luodaan kaatumisvedos. +nukkit.crash.error=Ei voida luoda kaatumisvedosta: {%0} +nukkit.crash.submit=Lähetä tiedosto "{%0}" Crash Archiveen ja lähetä linkki Bug Reporting sivulle. Anna niin paljon tietoa kuin voit. +nukkit.crash.archive=Kaatumisvedos on lähetetty automaattisesti Crash Archiveen. Voit tarkastella sitä osoitteessa {%0} tai tunnuksella #{%1}. + +nukkit.debug.enable=LevelDB tuki otettu käyttöön + +nukkit.bugreport.create=Virhe tunnistettu, luodaan virheraporttia. +nukkit.bugreport.error=Virheraportin luonti epäonnistui: {%0} +nukkit.bugreport.archive=Virheraportti luotu: {%0} + +nukkit.player.invalidMove={%0} liikkui väärin! +nukkit.player.logIn={%0}[/{%1}:{%2}] kirjautui sisään (olion tunnus {%3}) sijainnissa ({%4}, {%5}, {%6}, {%7}) +nukkit.player.logOut={%0}[/{%1}:{%2}] kirjautui ulos: {%3} +nukkit.player.invalidEntity={%0} koitti vahingoittaa virheellistä oliota + +nukkit.plugin.load=Ladataan {%0} +nukkit.plugin.enable=Otetaan käyttöön {%0} +nukkit.plugin.disable=Poistetaan käytöstä {%0} +nukkit.plugin.restrictedName=Rajoitettu nimi +nukkit.plugin.incompatibleAPI=Yhteensopimaton API versio +nukkit.plugin.unknownDependency=Tuntematon riippuvuus +nukkit.plugin.circularDependency=Kiertävä riippuvuus havaittu +nukkit.plugin.genericLoadError=Lisäosaa "{%0}" ei voitu ladata" +nukkit.plugin.spacesDiscouraged=Lisäosa "{%0}" käyttää nimessään välejä, mikä ei ole suositeltavaa +nukkit.plugin.loadError=Lisäosaa "{%0}" ei voitu ladata: {%1} +nukkit.plugin.duplicateError=Lisäosaa "{%0}" ei voitu ladata": samanniminen lisäosa on jo ladattu +nukkit.plugin.fileError=Ei voitu ladata "{%0}" kansiossa "{%1}": {%2} +nukkit.plugin.commandError=Ei voitu ladata komentoa {%0} lisäosalle {%1} +nukkit.plugin.aliasError=Ei voitu ladata aliasta {%0} lisäosalle {%1} +nukkit.plugin.deprecatedEvent=Lisäosa "{%0}" on rekisteröinyt kuuntelijan "{%1}" menetelmällä "{%2}", mutta tapahtuma on vanhentunut +nukkit.plugin.eventError=Ei voida suorittaa tapahtumaa "{%0}" lisäosalle "{%1}": {%2} @ {%3} + +nukkit.resources.invalid-path=Resurssipaketin polku "{%0}" on olemassa ja se ei ole hakemisto +nukkit.resources.unknown-format=Ei voida ladata "{%0}", koska formaatti ei ole tunnistettavissa +nukkit.resources.fail=Ei voida ladata "{%0}": {%1} +nukkit.resources.success=Ladattiin {%0} resurssipakettia +nukkit.resources.zip.not-found=Tiedostoa "{%0}" ei löydy +nukkit.resources.zip.no-manifest=Tiedostoa "manifest.json" ei löydy +nukkit.resources.zip.invalid-manifest=Tiedosto "manifest.json" on virheellinen +nukkit.resources.plugin.loading=Ladataan resurssipakettia lisäosasta {%0} diff --git a/src/main/resources/lang/fin/nukkit.yml b/src/main/resources/lang/fin/nukkit.yml new file mode 100644 index 00000000000..700b9fb5646 --- /dev/null +++ b/src/main/resources/lang/fin/nukkit.yml @@ -0,0 +1,91 @@ +# Advanced configuration file for Nukkit +# Some of these settings are safe, others can break your server if modified incorrectly +# New settings/defaults won't appear automatically on this file when upgrading + +settings: + #Multi-language setting + #Available: eng, chs, cht, jpn, rus, spa, pol, bra, kor, ukr, deu, ltu, idn, cze, tur, fin + language: "fin" + #Whether to send all strings translated to server locale or let the device handle them + force-language: false + shutdown-message: "Palvelin suljettu" + #Allow listing plugins via Query + query-plugins: true + #Show a console message when a plugin uses deprecated API methods + deprecated-verbose: true + #Number of AsyncTask workers + #If set to auto, it'll try to detect the number of cores (and at least 4) + async-workers: auto + +network: + #Threshold for batching packets, in bytes. Only these packets will be compressed + #Set to 0 to compress everything, -1 to disable + batch-threshold: 256 + #Compression level used of Zlib when sending batched packets. Higher = more CPU, less bandwidth usage + compression-level: 5 + #Enable network encryption + encryption: true + +debug: + #If > 1, it will show debug messages in the console + level: 1 + +level-settings: + #The default format that levels will use when created + default-format: leveldb + #Automatically change levels tick rate to maintain 20 ticks per second + auto-tick-rate: true + auto-tick-rate-limit: 20 + #Sets the base tick rate (1 = 20 ticks per second, 2 = 10 ticks per second, etc.) + base-tick-rate: 1 + #Tick all players each tick even when other settings disallow this + always-tick-players: false + +chunk-sending: + #Amount of chunks sent to players per tick + per-tick: 4 + #Amount of chunks that need to be sent before spawning the player + spawn-threshold: 56 + #Save a serialized copy of the chunk in memory for faster sending + #Useful in mostly-static worlds where lots of players join at the same time + cache-chunks: false + +chunk-ticking: + #Max amount of chunks processed each tick + per-tick: 40 + #Radius of chunks around a player to tick + tick-radius: 3 + clear-tick-list: false + +chunk-generation: + #Max. amount of chunks in the waiting queue to be generated + queue-size: 8 + #Max. amount of chunks in the waiting queue to be populated + population-queue-size: 8 + +leveldb: + #Use native LevelDB implementation for better performance + use-native: false + #Set LevelDB memory cache size + cache-size-mb: 80 + +ticks-per: + autosave: 6000 + +player: + #If true, player data will be saved as players/playername.dat + #If false, nukkit won't save player data as "dat" files, in order that plugins can do something on it. + save-player-data: true + +aliases: + #Aliases for commands + #Examples: + #showtheversion: version + #savestop: [save-all, stop] + +worlds: + #These settings will override the generator set in server.properties and allows loading multiple levels + #Example: + #world: + # seed: 404 + # generator: FLAT:2;7,59x1,3x3,2;1;decoration(treecount=80 grasscount=45) diff --git a/src/main/resources/lang/idn/lang.ini b/src/main/resources/lang/idn/lang.ini new file mode 100644 index 00000000000..4921419474f --- /dev/null +++ b/src/main/resources/lang/idn/lang.ini @@ -0,0 +1,360 @@ +# Language file compatible with Minecraft: Bedrock Edition identifiers +# +# A message doesn't need to be there to be shown correctly on the client. +# Only messages shown in Nukkit itself need to be here +# Using the language property from PocketMine-MP + +language.name=Indonesian +language.selected=Memilih {%0} ({%1}) sebagai bahasa utama + +multiplayer.player.joined={%0} masuk ke permainan +multiplayer.player.left={%0} keluar dari permainan + +chat.type.text=<{%0}> {%1} +chat.type.emote=* {%0} {%1} +chat.type.announcement=[{%0}] {%1} +chat.type.admin=[{%0}: {%1}] +chat.type.achievement={%0} baru saja memperoleh prestasi {%1} + +disconnectionScreen.outdatedClient=Client terlalu lawas! +disconnectionScreen.outdatedServer=Server terlalu lawas! +disconnectionScreen.serverFull=Server sedang penuh! +disconnectionScreen.noReason=Terputus dari server +disconnectionScreen.invalidSkin=Skin tidak valid! +disconnectionScreen.invalidName=Nama tidak valid! +disconnectionScreen.resourcePack=Encountered a problem while downloading or applying resource pack. + +death.fell.accident.generic={%0} Jatuh dari ketingian +death.attack.inFire={%0} terbakar habis +death.attack.onFire={%0} terbakar sampai mati +death.attack.lava={%0} mencoba berenang dilava +death.attack.lava.magma={%0} discovered floor was lava +death.attack.inWall={%0} terjebak didalam dinding +death.attack.drown={%0} tenggelam +death.attack.cactus={%0} ditusuk sampai mati +death.attack.generic={%0} koid +death.attack.explosion={%0} meledak +death.attack.explosion.player={%0} diledakkan oleh {%1} +death.attack.magic={%0} dibunuh oleh makhluk gaib +death.attack.wither={%0} layu +death.attack.mob={%0} ditikam oleh {%1} +death.attack.player={%0} ditikam oleh {%1} +death.attack.player.item={%0} ditikam oleh {%1} memakai {%2} +death.attack.arrow={%0} ditembak oleh {%1} +death.attack.arrow.item={%0} ditembak oleh {%1} memakai {%2} +death.attack.fall={%0} menyentuh tanah terlalu keras. +death.attack.outOfWorld={%0} jatuh keluar dari dunia. +death.attack.starve={%0} starved to death + +gameMode.survival=Mode bertahan +gameMode.creative=Mode kreatif +gameMode.adventure=Mode berpetualangan +gameMode.spectator=Mode menonton +gameMode.changed=Mode permainan kamu telah diubah + +potion.moveSpeed=Kecepatan +potion.moveSlowdown=Kelambatan +potion.digSpeed=Bergegas +potion.digSlowDown=Kelelahan bertambang +potion.damageBoost=Kekuatan +potion.heal=Darah instan +potion.harm=Kerusakan instan +potion.jump=Lompatan meningkat +potion.confusion=Maul +potion.regeneration=Regenerasi +potion.resistance=Daya tahan +potion.fireResistance=Daya Tahan Api +potion.waterBreathing=Pernapasan air +potion.invisibility=Tak terlihat +potion.blindness=Buto +potion.nightVision=Penglihatan malam +potion.hunger=Lapar +potion.weakness=Cacat +potion.poison=Racun +potion.wither=Melayu +potion.healthBoost=Darah meningkat +potion.absorption=Penyerapan +potion.saturation=Jenuh + +commands.generic.exception=Terjadi kesalahan yang tidak diketahui ketika mencoba untuk melakukan perintah ini +commands.generic.permission=nda tidak memiliki izin untuk menggunakan perintah ini +commands.generic.ingame=Anda hanya dapat melakukan perintah ini sebagai pemain +commands.generic.unknown=Perintah yang tidak diketahui. Coba /help untuk daftar perintah +commands.generic.player.notFound=Pemain tidak ditemukan +commands.generic.usage=Pemakaian: {%0} + +commands.time.added=Menambahkan {%0} ke waktu +commands.time.set=Waktu di stel menjadi {%0} +commands.time.query=Waktu sekarang{%0} + +commands.me.usage=/me <aksi ...> + +commands.give.item.notFound=Tidak ada barang dengan nama {%0} +commands.give.success=Memberi {%0} * {%1} kepada {%2} +commands.give.tagError=Penguraian data gagal: {%0} + +commands.effect.usage=/effect <pemain> <efek> [detik] [pengerasan] [hilangkanPartikel] atau /effect <pemain> clear +commands.effect.notFound=Tidak ada efek mob dengan id {%0} +commands.effect.success=Memberi {%0} (ID {%1}) * {%2} ke {%3} untuk {%4} detik +commands.effect.success.removed=Pengambil {%0} dari {%1} +commands.effect.success.removed.all=Mengambil semua efek dari {%0} +commands.effect.failure.notActive=Tidak bisa mengambil {%0} dari {%1} karna mereka tidak mempunyai efek +commands.effect.failure.notActive.all=Tidak bsa mengambil efek apapun dari {%0} karna mereka tidak mempunyai efek + +commands.enchant.noItem=Target tidak memegang barang apapun. +commands.enchant.notFound=Tidak ada pemikatan dengan ID {%0} +commands.enchant.success=Pemikatan sukses +commands.enchant.usage=/enchant <pemain> <ID pemikatan> [tingkat] + +commands.particle.success=Bermain efek {%0} untuk {%1} kali +commands.particle.notFound=Nama efek tidak diketahui {%0} + +commands.players.usage=/list +commands.players.list=Ada {%0}/{%1} pemain online sedang online : + +commands.kill.successful=Membunuh {%0} +commands.kill.all.successful=Killed all players +commands.kill.entities.successful=Killed all entities + +commands.banlist.ips=Ada {%0} total alamat IP yang dibanned: +commands.banlist.players=Ada {%0} total pemain yang dibanned: +commands.banlist.usage=/banlist [ips|players] + +commands.defaultgamemode.usage=/defaultgamemode <mode> +commands.defaultgamemode.success=Mode permainin dunia ini sekarang adalah {%0} + +commands.op.success=Memberi OP {%0} +commands.op.usage=/op <player> + +commands.deop.success=Menurunkan OP {%0} +commands.deop.usage=/deop <player> + +commands.say.usage=/say <pesan ...> + +commands.seed.usage=/seed +commands.seed.success=Seed: {%0} + +commands.ban.success=Pemain terbanned {%0} +commands.ban.usage=/ban <nama> [alasan ...] + +commands.unban.success=Pemain diunbanned {%0} +commands.unban.usage=/pardon <name> + +commands.banip.invalid=Kami memasukan alamat IP yang salah atau pemain tersebut tidak online +commands.banip.offline.invalid=Tidak ada alamat IP data pemain atau alamat IP tidak valid +commands.banip.success=Alamat IP {%0} dibanned +commands.banip.success.players=Alamat ip terbanned {%0} milik {%1} +commands.banip.usage=/ban-ip <alamat|nama> [alasan ...] + +commands.unbanip.invalid=Kamu memasukan alamat IP yang salah +commands.unbanip.success=Unbanned IP address {%0} +commands.unbanip.usage=/pardon-ip <address> + +commands.save.usage=/save [on|off|hold|resume] +commands.save.enabled=Turned on world auto-saving +commands.save.disabled=Turned off world auto-saving +commands.save.start=Saving... +commands.save.success=Saved the world + +commands.stop.usage=/stop +commands.stop.start=Stopping the server + +commands.kick.success=Kicked {%0} from the game +commands.kick.success.reason=Kicked {%0} from the game: '{%1}' +commands.kick.usage=/kick <player> [reason ...] + +commands.tp.success=Teleported {%0} to {%1} +commands.tp.success.coordinates=Teleported {%0} to {%1}, {%2}, {%3} +commands.tp.usage=/tp [target player] <destination player> OR /tp [target player] <x> <y> <z> [<y-rot> <x-rot>] + +commands.whitelist.list=There are {%0} (out of {%1} seen) whitelisted players: +commands.whitelist.enabled=Turned on the whitelist +commands.whitelist.disabled=Turned off the whitelist +commands.whitelist.reloaded=Reloaded the whitelist +commands.whitelist.add.success=Added {%0} to the whitelist +commands.whitelist.add.usage=/whitelist add <player> +commands.whitelist.remove.success=Removed {%0} from the whitelist +commands.whitelist.remove.usage=/whitelist remove <player> +commands.whitelist.usage=/whitelist <on|off|list|add|remove|reload> + +commands.gamemode.success.self=Set own game mode to {%0} +commands.gamemode.success.other=Set {%0}'s game mode to {%1} +commands.gamemode.usage=/gamemode <mode> [player] + +commands.help.header=--- Showing help page {%0} of {%1} (/help <page>) --- +commands.help.usage=/help [page|command name] + +commands.message.usage=/tell <player> <private message ...> +commands.message.sameTarget=You can't send a private message to yourself! + +commands.difficulty.usage=/difficulty <new difficulty> +commands.difficulty.success=Set game difficulty to {%0} + +commands.spawnpoint.usage=/spawnpoint [player] [<x> <y> <z>] +commands.spawnpoint.success=Set {%0}'s spawn point to ({%1}, {%2}, {%3}) + +commands.setworldspawn.usage=/setworldspawn [<x> <y> <z>] +commands.setworldspawn.success=Set the world spawn point to ({%0}, {%1}, {%2}) + +commands.weather.clear=Changing to clear weather +commands.weather.rain=Changing to rainy weather +commands.weather.thunder=Changing to rain and thunder +commands.weather.usage=/weather <clear|rain|thunder> [duration in seconds] + +commands.xp.success=Given {%0} experience to {%1} +commands.xp.success.levels=Given {%0} levels to {%1} +commands.xp.success.levels.minus=Taken {%0} levels from {%1} +commands.xp.usage=/xp <amount> [player] OR /xp <level>L [player] + +# -------------------- Nukkit language files, only for console -------------------- + +nukkit.data.playerNotFound=Player data not found for "{%0}", creating new profile +nukkit.data.playerCorrupted=Corrupted data found for "{%0}", creating new profile +nukkit.data.playerOld=Old Player data found for "{%0}", upgrading profile +nukkit.data.saveError=Could not save player "{%0}": {%1} + +nukkit.level.notFound=Level "{%0}" not found +nukkit.level.loadError=Could not load level "{%0}": {%1} +nukkit.level.generationError=Could not generate level "{%0}": {%1} +nukkit.level.tickError=Could not tick level "{%0}": {%1} +nukkit.level.chunkUnloadError=Error while unloading a chunk: {%0} +nukkit.level.backgroundGeneration=Spawn terrain for level "{%0}" is being generated in the background +nukkit.level.defaultError=No default level has been loaded +nukkit.level.preparing=Preparing level "{%0}" +nukkit.level.unloading=Unloading level "{%0}" +nukkit.level.updating=Old level data found for "{%0}", converting format + +nukkit.server.start=Starting Minecraft: BE server version {%0} +nukkit.server.networkError=[Network] Stopped interface {%0} due to {%1} +nukkit.server.networkStart=Opening server on {%0}:{%1} +nukkit.server.info=This server is running {%0} version {%1} "{%2}" (API {%3}) +nukkit.server.info.extended=This server is running {%0} {%1} 「{%2}」 implementing API version {%3} for Minecraft: BE {%4} (protocol version {%5}) +nukkit.server.license={%0} is distributed under the GPL License +nukkit.server.tickOverload=Can't keep up! Is the server overloaded? +nukkit.server.startFinished=Done ({%0}s)! For help, type "help" or "?" +nukkit.server.defaultGameMode=Default game type: {%0} +nukkit.server.query.start=Starting GS4 status listener +nukkit.server.query.info=Setting query port to {%0} +nukkit.server.query.running=Query is running on {%0}:{%1} +nukkit.server.rcon.emptyPasswordError=Failed to start RCON: password is empty +nukkit.server.rcon.startupError=Failed to start RCON: {%0} +nukkit.server.rcon.running=RCON is running on {%0}:{%1} + +nukkit.command.alias.illegal=Could not register alias {%0} because it contains illegal characters +nukkit.command.alias.notFound=Could not register alias {%0} because it contains commands that do not exist: {%1} +nukkit.command.exception=Unhandled exception executing command "{%0}" in {%1}: {%2} + +nukkit.command.plugins.description=Gets a list of plugins running on the server +nukkit.command.plugins.success=Plugins ({%0}): {%1} +nukkit.command.plugins.usage=/plugins + +nukkit.command.reload.description=Reloads the server configuration and plugins +nukkit.command.reload.usage=/reload +nukkit.command.reload.reloading=Reloading server... +nukkit.command.reload.reloaded=Reload complete. + +nukkit.command.status.description=Reads back the server's performance. +nukkit.command.status.usage=/status + +nukkit.command.gc.description=Fires garbage collection tasks +nukkit.command.gc.usage=/gc + +nukkit.command.title.description=Sends a title to the specified player or modifies title settings for that player +nukkit.command.title.usage=/title <player> <clear|reset> OR /title <player> <title|subtitle|actionbar> <title text> OR /title <player> <times> <fade in time> <stay time> <fade out time> +nukkit.command.title.clear=Successfully cleared {%0}'s screen +nukkit.command.title.reset=Successfully reset title animation settings for {%0} +nukkit.command.title.title=Successfully shown "{%0}" title to {%1} +nukkit.command.title.subtitle=Successfully set subtitle to "{%0}" for {%1}'s next title +nukkit.command.title.actionbar=Successfully shown "{%0}" actionbar title to {%1} +nukkit.command.title.times.success=Successfully set title animation times to {%0}, {%1}, {%2} for {%3} +nukkit.command.title.times.fail=Times of title animations must be numeric values + +nukkit.command.version.description=Gets the version of this server including any plugins in use +nukkit.command.version.usage=/version [plugin name] +nukkit.command.version.noSuchPlugin=This server is not running any plugin by that name. Use /plugins to get a list of plugins. + +nukkit.command.give.description=Gives the specified player a certain amount of items +nukkit.command.give.usage=/give <player> <item[:damage]> [amount] [tags ...] + +nukkit.command.kill.description=Commit suicide or kill other players +nukkit.command.kill.usage=/kill [player] + +nukkit.command.particle.description=Adds particles to a world +nukkit.command.particle.usage=/particle <name> <x> <y> <z> <xd> <yd> <zd> [count] [data] + +nukkit.command.time.description=Changes the time on each world +nukkit.command.time.usage=/time <set|add> <value> OR /time <start|stop|query> + +nukkit.command.gamerule.description=Sets or queries a game rule value +nukkit.command.gamerule.usage=/gamerule <rule> [value] + +nukkit.command.ban.player.description=Prevents the specified player from using this server +nukkit.command.ban.ip.description=Prevents the specified IP address from using this server +nukkit.command.banlist.description=View all players banned from this server +nukkit.command.defaultgamemode.description=Set the default gamemode +nukkit.command.deop.description=Takes the specified player's operator status +nukkit.command.difficulty.description=Sets the game difficulty +nukkit.command.enchant.description=Adds enchantments on items +nukkit.command.effect.description=Adds/Removes effects on players +nukkit.command.gamemode.description=Changes the player to a specific game mode +nukkit.command.help.description=Shows the help menu +nukkit.command.kick.description=Removes the specified player from the server +nukkit.command.list.description=Lists all online players +nukkit.command.me.description=Performs the specified action in chat +nukkit.command.op.description=Gives the specified player operator status +nukkit.command.unban.player.description=Allows the specified player to use this server +nukkit.command.unban.ip.description=Allows the specified IP address to use this server +nukkit.command.save.description=Saves the server to disk + +nukkit.command.say.description=Broadcasts the given message as the sender +nukkit.command.seed.description=Shows the world seed +nukkit.command.setworldspawn.description=Sets a worlds's spawn point. If no coordinates are specified, the player's coordinates will be used. +nukkit.command.spawnpoint.description=Sets a player's spawn point +nukkit.command.stop.description=Stops the server +nukkit.command.tp.description=Teleports the given player (or yourself) to another player or coordinates +nukkit.command.tell.description=Sends a private message to the given player +nukkit.command.weather.description=Sets the weather in current world +nukkit.command.xp.description=Gives the specified player a certain amount of experience +nukkit.command.whitelist.description=Manages the list of players allowed to use this server + +nukkit.crash.create=An unrecoverable error has occurred and the server has crashed. Creating a crash dump +nukkit.crash.error=Could not create crash dump: {%0} +nukkit.crash.submit=Please upload the "{%0}" file to the Crash Archive and submit the link to the Bug Reporting page. Give as much info as you can. +nukkit.crash.archive=The crash dump has been automatically submitted to the Crash Archive. You can view it on {%0} or use the ID #{%1}. + +nukkit.debug.enable=LevelDB support enabled + +nukkit.bugreport.create=An error has been detected, creating a bug report. +nukkit.bugreport.error=Could not create bug report: {%0} +nukkit.bugreport.archive=A bug report has been created: {%0} + +nukkit.player.invalidMove={%0} moved wrongly! +nukkit.player.logIn={%0}[/{%1}:{%2}] logged in with entity id {%3} at ({%4}, {%5}, {%6}, {%7}) +nukkit.player.logOut={%0}[/{%1}:{%2}] logged out due to {%3} +nukkit.player.invalidEntity={%0} tried to attack an invalid entity + +nukkit.plugin.load=Loading {%0} +nukkit.plugin.enable=Enabling {%0} +nukkit.plugin.disable=Disabling {%0} +nukkit.plugin.restrictedName=Restricted name +nukkit.plugin.incompatibleAPI=Incompatible API version +nukkit.plugin.unknownDependency=Unknown dependency +nukkit.plugin.circularDependency=Circular dependency detected +nukkit.plugin.genericLoadError=Could not load plugin "{%0}" +nukkit.plugin.spacesDiscouraged=Plugin "{%0}" uses spaces in its name, this is discouraged +nukkit.plugin.loadError=Could not load plugin "{%0}": {%1} +nukkit.plugin.duplicateError=Could not load plugin "{%0}": plugin exists +nukkit.plugin.fileError=Could not load "{%0}" in folder "{%1}": {%2} +nukkit.plugin.commandError=Could not load command {%0} for plugin {%1} +nukkit.plugin.aliasError=Could not load alias {%0} for plugin {%1} +nukkit.plugin.deprecatedEvent=Plugin "{%0}" has registered a listener for "{%1}" on method "{%2}", but the event is Deprecated. +nukkit.plugin.eventError=Could not pass event "{%0}" to "{%1}": {%2} on {%3} + +nukkit.resources.invalid-path=Resource packs path "{%0}" exists and is not a directory +nukkit.resources.unknown-format=Could not load "{%0}" due to format not recognized +nukkit.resources.fail=Could not load "{%0}": {%1} +nukkit.resources.success=Successfully loaded {%0} resource packs +nukkit.resources.zip.not-found=File "{%0}" is not found +nukkit.resources.zip.no-manifest="manifest.json" is not found +nukkit.resources.zip.invalid-manifest="manifest.json" is invalid or incomplete +nukkit.resources.plugin.loading=Loading resource pack from plugin {%0} diff --git a/src/main/resources/lang/idn/nukkit.yml b/src/main/resources/lang/idn/nukkit.yml new file mode 100644 index 00000000000..f6cd617b524 --- /dev/null +++ b/src/main/resources/lang/idn/nukkit.yml @@ -0,0 +1,101 @@ +# Advanced configuration file for Nukkit +# Some of these settings are safe, others can break your server if modified incorrectly +# New settings/defaults won't appear automatically on this file when upgrading + +settings: + #Multi-language setting + #Available: eng, chs, cht, jpn, rus, spa, pol, bra, kor, ukr, deu, ltu, idn, cze, tur, fin + language: "eng" + #Whether to send all strings translated to server locale or let the device handle them + force-language: false + shutdown-message: "Server closed" + #Allow listing plugins via Query + query-plugins: true + #Show a console message when a plugin uses deprecated API methods + deprecated-verbose: true + #Number of AsyncTask workers + #If set to auto, it'll try to detect the number of cores (and at least 4) + async-workers: auto + +network: + #Threshold for batching packets, in bytes. Only these packets will be compressed + #Set to 0 to compress everything, -1 to disable + batch-threshold: 256 + #Compression level used of Zlib when sending batched packets. Higher = more CPU, less bandwidth usage + compression-level: 5 + #Enable network encryption + encryption: true + +debug: + #If > 1, it will show debug messages in the console + level: 1 + +level-settings: + #The default format that levels will use when created + default-format: leveldb + #Automatically change levels tick rate to maintain 20 ticks per second + auto-tick-rate: true + auto-tick-rate-limit: 20 + #Sets the base tick rate (1 = 20 ticks per second, 2 = 10 ticks per second, etc.) + base-tick-rate: 1 + #Tick all players each tick even when other settings disallow this + always-tick-players: false + +chunk-sending: + #Amount of chunks sent to players per tick + per-tick: 4 + #Amount of chunks that need to be sent before spawning the player + spawn-threshold: 56 + #Save a serialized copy of the chunk in memory for faster sending + #Useful in mostly-static worlds where lots of players join at the same time + cache-chunks: false + +chunk-ticking: + #Max amount of chunks processed each tick + per-tick: 40 + #Radius of chunks around a player to tick + tick-radius: 3 + clear-tick-list: false + +chunk-generation: + #Max. amount of chunks in the waiting queue to be generated + queue-size: 8 + #Max. amount of chunks in the waiting queue to be populated + population-queue-size: 8 + +leveldb: + #Use native LevelDB implementation for better performance + use-native: false + #Set LevelDB memory cache size + cache-size-mb: 80 + +ticks-per: + #How often worlds and player data are saved when auto-save=on in server.properties + autosave: 6000 + +player: + #If true, player data will be saved as players/playername.dat + #If false, nukkit won't save player data as "dat" files, in order that plugins can do something on it. + save-player-data: true + #The time between skin change action in seconds, set to 0 if you dont want the cooldown + skin-change-cooldown: 15 + #Attacking entities resets sprinting, you can disable that here + attack-stop-sprint: true + +aliases: + #Aliases for commands + #Examples: + #showtheversion: version + #savestop: [save-all, stop] + +worlds: + #Worlds that the server will use. Options are specific to the chosen generator, and may result in broken generation or + #be ignored completely. + world: + #seed: 404 + generator: normal + #options: + nether: + #seed: my_cool_nether_seed + generator: nether + #options: diff --git a/src/main/resources/lang/jpn/lang.ini b/src/main/resources/lang/jpn/lang.ini new file mode 100644 index 00000000000..5d2719b115a --- /dev/null +++ b/src/main/resources/lang/jpn/lang.ini @@ -0,0 +1,361 @@ +# Language file compatible with Minecraft: Bedrock Edition identifiers +# +# A message doesn't need to be there to be shown correctly on the client. +# Only messages shown in Nukkit itself need to be here +# Using the language property from PocketMine-MP + +language.name=日本語 +language.selected={%0} ({%1}) を言語に選択しました + +multiplayer.player.joined={%0} がゲームに参加しました +multiplayer.player.left={%0} が退出しました + +chat.type.text=<{%0}> {%1} +chat.type.emote=* {%0} {%1} +chat.type.announcement=[{%0}] {%1} +chat.type.admin=[{%0}: {%1}] +chat.type.achievement={%0}は{%1}の実績を手に入れた + +disconnectionScreen.outdatedClient=違うバージョンのクライアントです! +disconnectionScreen.outdatedServer=違うバージョンのサーバーです! +disconnectionScreen.serverFull=サーバーは満員です! +disconnectionScreen.noReason=サーバーから切断されました +disconnectionScreen.invalidSkin=無効なスキンです! +disconnectionScreen.invalidName=無効な名前です! +disconnectionScreen.resourcePack=Encountered a problem while downloading or applying resource pack. + +death.fell.accident.generic={%0} は高いところから落ちてしまった +death.attack.inFire={%0}は炎に巻かれてしまった +death.attack.onFire={%0}はこんがりと焼けてしまった +death.attack.lava={%0}は溶岩遊泳を試みた +death.attack.lava.magma={%0} discovered floor was lava +death.attack.inWall={%0}は壁の中で窒息してしまった +death.attack.drown={%0}は溺れ死んでしまった +death.attack.cactus={%0}はサボテンに刺されて死んでしまった +death.attack.generic={%0}は死んでしまった +death.attack.explosion={%0}は爆発に巻き込まれてしまった +death.attack.explosion.player={%0}は{%1}に爆破されてしまった +death.attack.magic={%0}は魔法で殺されてしまった +death.attack.wither={%0}は干からびてしまった +death.attack.mob={%0}は{%1}に殺害されてしまった +death.attack.player={%0}は{%1}に殺害されてしまった +death.attack.player.item={%0}は{%1}の{%2}で殺害されてしまった +death.attack.arrow={%0}は{%1}に射抜かれてしまった +death.attack.arrow.item={%0}は{%1}の{%2}で射抜かれてしまった +death.attack.fall={%0}は地面と強く激突してしまった +death.attack.outOfWorld={%0}は奈落の底へ落ちてしまった +death.attack.starve={%0} starved to death + +gameMode.survival=サバイバルモード +gameMode.creative=クリエイティブモード +gameMode.adventure=アドベンチャーモード +gameMode.spectator=スペクテイターモード +gameMode.changed=ゲームモードが変更されました + +potion.moveSpeed=移動速度上昇 +potion.moveSlowdown=移動速度低下 +potion.digSpeed=採掘速度上昇 +potion.digSlowDown=採掘速度低下 +potion.damageBoost=攻撃力上昇 +potion.heal=即時回復 +potion.harm=ダメージ +potion.jump=跳躍力上昇 +potion.confusion=吐き気 +potion.regeneration=再生能力 +potion.resistance=耐性 +potion.fireResistance=火炎耐性 +potion.waterBreathing=水中呼吸 +potion.invisibility=透明化 +potion.blindness=盲目 +potion.nightVision=暗視 +potion.hunger=空腹 +potion.weakness=弱体化 +potion.poison=毒 +potion.wither=ウィザー +potion.healthBoost=体力増強 +potion.absorption=衝撃吸収 +potion.saturation=満腹度回復 + +commands.generic.exception=コマンドの実行中に不明なエラーが発生しました +commands.generic.permission=このコマンドを使用する権限がありません +commands.generic.ingame=You can only perform this command as a player +commands.generic.unknown=未知のコマンドです。/helpでコマンドの一覧を確認してください +commands.generic.player.notFound=プレイヤーが見つかりません +commands.generic.usage=使い方: {%0} + +commands.time.added=時間を{%0}進めました +commands.time.set=現在時刻を{%0}に設定しました +commands.time.query=現在の時間は {%0} です + +commands.me.usage=/me <アクション> + +commands.give.item.notFound={%0}という名前のアイテムはありません +commands.give.success={%0} を {%1} 個 {%2} に与えました +commands.give.tagError=データタグの解析に失敗しました: {%0} + +commands.effect.usage=/effect <プレイヤー名> <効果> [秒数] [倍数] [パーティクルの設定] か /effect <プレイヤー名> clear +commands.effect.notFound=ID{%0}のエフェクトは存在しません +commands.effect.success={%3}に{%0} (ID {%1})×{%2}を{%4}秒間与えました +commands.effect.success.removed={%0}を{%1}から除去しました +commands.effect.success.removed.all={%0}からすべての効果を除去しました +commands.effect.failure.notActive={%1} は {%0} という効果を受けていないので除去することができませんでした +commands.effect.failure.notActive.all={%0}はステータス効果を受けていないので除去することはできませんでした + +commands.enchant.noItem=対象のプレイヤーはアイテムを持っていません +commands.enchant.notFound=ID {%0} に該当するエンチャントはありません +commands.enchant.success=エンチャントに成功しました +commands.enchant.usage=/enchant <プレイヤー名> <エンチャントID> [レベル] + +commands.particle.success=効果{%0}を{%1}回発生させます +commands.particle.notFound=存在しないエフェクト:{%0} + +commands.players.usage=/list +commands.players.list=現在{%0}人(最大{%1}人)がオンライン: + +commands.kill.successful={%0}を殺しました +commands.kill.all.successful=Killed all players +commands.kill.entities.successful=Killed all entities + +commands.banlist.ips=%d 個のIPアドレスがBANされています: +commands.banlist.players={%0} 人のプレイヤーがBANされています: +commands.banlist.usage=/banlist [IPアドレス|プレイヤー名] + +commands.defaultgamemode.usage=/defaultgamemode <0 | 1 | 2 | 3> +commands.defaultgamemode.success=ワールドのデフォルトのゲームモードを {%0} にしました。 + +commands.op.success={%0} にオペレーター権を付与しました +commands.op.usage=/op <プレイヤー名> + +commands.deop.success={%0} からオペレーター権を剥奪しました +commands.deop.usage=/deop <プレイヤー名> + +commands.say.usage=/say <メッセージ ...> + +commands.seed.usage=/seed +commands.seed.success=Seed値:{%0} + +commands.ban.success={%0} をBANしました +commands.ban.usage=/ban <プレイヤー名> [理由 ...] + +commands.unban.success={%0} のbanを解除しました +commands.unban.usage=/pardon <プレイヤー名> + +commands.banip.invalid=無効なIPアドレスが入力されたか、プレイヤーがオンラインになっていません +commands.banip.offline.invalid=There is no IP address in player data or IP address is invalid +commands.banip.success=IPアドレス "{%0}" をBANしました。 +commands.banip.success.players={%1} のIPアドレス {%0} をBANしました +commands.banip.usage=/ban-ip <IPアドレス|プレイヤー名> [理由] + +commands.unbanip.invalid=無効なIPアドレスです +commands.unbanip.success=IPアドレス {%0} のBANが解除されました +commands.unbanip.usage=/pardon-ip <IPアドレス> + +commands.save.usage=/save [on|off|hold|resume] +commands.save.enabled=ワールドの自動保存を有効にしました +commands.save.disabled=ワールドの自動保存を無効にしました +commands.save.start=保存中… +commands.save.success=ワールドを保存しました + +commands.stop.usage=/stop +commands.stop.start=サーバーを停止しています + +commands.kick.success={%0}さんはキックされてゲームから切断しました +commands.kick.success.reason={%0} を {%1} サーバーからキックしました +commands.kick.usage=/kick <プレイヤー名> [理由 ...] + +commands.tp.success={%0} から {%1} へワープしました +commands.tp.success.coordinates={%0} は {%1}, {%2}, {%3} にテレポートしました +commands.tp.usage=/tp [対象のプレイヤー] <移動先のプレイヤー> または /tp [対象のプレイヤー] <x> <y> <z> [<y> <x>のみ] + +commands.whitelist.list=ホワイトリストには {%0} 人 (サーバー全体では {%1} 人) のプレイヤーがいます +commands.whitelist.enabled=ホワイトリストを有効にしました +commands.whitelist.disabled=ホワイトリストを無効にしました +commands.whitelist.reloaded=ホワイトリストを再読み込みしました +commands.whitelist.add.success={%0} をホワイトリストに追加しました +commands.whitelist.add.usage=/whitelist add <プレイヤー名> +commands.whitelist.remove.success={%0} をホワイトリストから削除しました +commands.whitelist.remove.usage=/whitelist remove <プレイヤー名> +commands.whitelist.usage=/whitelist <on|off|list|add|remove|reload> + +commands.gamemode.success.self=ゲームモードを{%0}に変更しました +commands.gamemode.success.other={%0}のゲームモードを{%1}に変更しました +commands.gamemode.usage=/gamemode <モード> [プレイヤー名] + +commands.help.header=--- ヘルプページの {%0} / {%1} ページを表示(/help <ページ番号>) --- +commands.help.usage=/help [ページ|コマンド名] + +commands.message.usage=/tell <プレイヤー名> <プライベートメッセージ> +commands.message.sameTarget=自分自身にプライベートメッセージを送信することはできません! + +commands.difficulty.usage=/difficulty <難易度> +commands.difficulty.success=ゲームの難易度を{%0}に設定しました + +commands.spawnpoint.usage=/spawnpoint [プレイヤー名] [<x><y><z>] +commands.spawnpoint.success={%0} のスポーン地点を ({%1}, {%2}, {%3}) に変更しました + +commands.setworldspawn.usage=/setworldspawn [<x> <y> <z>] +commands.setworldspawn.success=({%0},{%1},{%2}) にワールドのスポーンポイントを設定します + +commands.weather.clear=天気を晴れに変更します +commands.weather.rain=天気を雨に変更します +commands.weather.thunder=天気を雷雨に変更します +commands.weather.usage=/weather <clear|rain|thunder> [持続時間(単位:秒)] + +commands.xp.success=Given {%0} experience to {%1} +commands.xp.success.levels=Given {%0} levels to {%1} +commands.xp.success.levels.minus=Taken {%0} levels from {%1} +commands.xp.usage=/xp <amount> [player] OR /xp <level>L [player] + +# -------------------- コンソールの表示 -------------------- + +nukkit.data.playerNotFound={%0} のプレイヤーデータが見つからないため、新たに作成します +nukkit.data.playerCorrupted={%0} のデータの破損が見つかったため、新たに作成します +nukkit.data.playerOld={%0} の古いプレイヤーデータが見つかったため、更新します +nukkit.data.saveError={%0}のデータを保存できませんでした: {%1} + +nukkit.level.notFound=ワールド "{%0}" が見つかりません +nukkit.level.loadError=ワールド "{%0}" を読み込むことができませんでした: {%1} +nukkit.level.generationError=ワールド"{%0}"を生成することができませんでした: {%1} +nukkit.level.tickError=ワールド "{%0}" をチェックすることができませんでした: {%1} +nukkit.level.chunkUnloadError=チャンクの書き込み中にエラーが発生しました: {%0} +nukkit.level.backgroundGeneration=ワールド"{%0}"の地形をバックグラウンドで生成しています +nukkit.level.defaultError=デフォルトのワールドが読み込まれていません +nukkit.level.preparing=ワールド "{%0}" を読み込んでいます +nukkit.level.unloading=ワールド"{%0}"の書き込みをしています +nukkit.level.updating=古いレベルのデータが見つかりました "{%0}" フォーマットを変換しています。 + +nukkit.server.start=Minecraft: BEサーバー({%0}に対応)を起動しています +nukkit.server.networkError=[Network] {%1}によって{%0}のインターフェイスが停止しました +nukkit.server.networkStart={%0}:{%1}上でサーバーを開始しています +nukkit.server.info=このサーバーは{%0}のバージョン{%1}「{%2}」(API {%3})で動作しています +nukkit.server.info.extended=このサーバーが実行している{%0}のバージョンは{%1}「{%2}」Minecraft BE {%4}用実装APIバージョン{%3}(プロトコルバージョン{%5})です +nukkit.server.license={%0}はGPLライセンスに基づき配布されています +nukkit.server.tickOverload=注意! サーバーが高負荷になっている可能性があります +nukkit.server.startFinished=起動完了({%0}秒)! "help"または"?"でヘルプを表示 +nukkit.server.defaultGameMode=デフォルトゲームタイプ: {%0} +nukkit.server.query.start=GS4ステータス リスナーを開始 +nukkit.server.query.info=クエリポートを設定: {%0} +nukkit.server.query.running=クエリーは {%0}:{%1} で動作しています +nukkit.server.rcon.emptyPasswordError=RCONを開始できませんでした : パスワードが設定されていません +nukkit.server.rcon.startupError=RCONを開始できませんでした : {%0} +nukkit.server.rcon.running=RCONは {%0}:{%1} で動作しています + +nukkit.command.alias.illegal=無効な文字が含まれているため、{%0}を登録できませんでした +nukkit.command.alias.notFound=存在しないコマンドが含まれているため、{%0}を登録できませんでした: {%1} +nukkit.command.exception=コマンド"{%0}"を{%1}で実行中に、処理できない例外が発生:{%2} + +nukkit.command.plugins.description=サーバー上で実行されているプラグインを一覧にして表示します +nukkit.command.plugins.success=プラグイン ({%0}): {%1} +nukkit.command.plugins.usage=/plugins + +nukkit.command.reload.description=サーバーの設定やプラグインを再読み込みします +nukkit.command.reload.usage=/reload +nukkit.command.reload.reloading=サーバーを再読み込みしています... +nukkit.command.reload.reloaded=再読み込みが完了しました + +nukkit.command.status.description=サーバーのパフォーマンスを調べます +nukkit.command.status.usage=/status + +nukkit.command.gc.description=ガベージコレクションのタスクを起動しました +nukkit.command.gc.usage=/gc + +nukkit.command.title.description=Sends a title to the specified player or modifies title settings for that player +nukkit.command.title.usage=/title <player> <clear|reset> OR /title <player> <title|subtitle|actionbar> <title text> OR /title <player> <times> <fade in time> <stay time> <fade out time> +nukkit.command.title.clear=Successfully cleared {%0}'s screen +nukkit.command.title.reset=Successfully reset title animation settings for {%0} +nukkit.command.title.title=Successfully shown "{%0}" title to {%1} +nukkit.command.title.subtitle=Successfully set subtitle to "{%0}" for {%1}'s next title +nukkit.command.title.actionbar=Successfully shown "{%0}" actionbar title to {%1} +nukkit.command.title.times.success=Successfully set title animation times to {%0}, {%1}, {%2} for {%3} +nukkit.command.title.times.fail=Times of title animations must be numeric values + +nukkit.command.version.description=使用しているプラグインを含めたこのサーバーのバージョンを取得します +nukkit.command.version.usage=/version [プラグイン名] +nukkit.command.version.noSuchPlugin=このサーバーではその名前のどのプラグインも実行しまいません プラグインリストを取得するには /plugins を使用してください + +nukkit.command.give.description=指定したプレイヤーに一定量のアイテムを付与します +nukkit.command.give.usage=/give <プレイヤー名> <アイテム[:ダメージ値]> [量] [タグ] + +nukkit.command.kill.description=自殺または他のプレイヤーを殺すことができます +nukkit.command.kill.usage=/kill [プレイヤー名] + +nukkit.command.particle.description=ワールドにパーティクルを追加します +nukkit.command.particle.usage=/particle <パーティクル名> <x> <y> <z> <xd> <yd> <zd> [量] [データ値] + +nukkit.command.time.description=それぞれのワールドの時間を変更します +nukkit.command.time.usage=/time <set|add> <値> または /time <start|stop|query> + +nukkit.command.gamerule.description=ゲームルールの値を設定またはクエリする +nukkit.command.gamerule.usage=/gamerule <rule> [value] + +nukkit.command.ban.player.description=指定したプレーヤーのサーバーの使用を拒否します +nukkit.command.ban.ip.description=指定したIPアドレスからのサーバーの使用を拒否します +nukkit.command.banlist.description=このサーバーでBANされたすべてのプレイヤーを表示します +nukkit.command.defaultgamemode.description=デフォルトのゲームモードを設定します +nukkit.command.deop.description=指定プレイヤーのOP権限を剥奪します +nukkit.command.difficulty.description=ゲーム難易度を設定します +nukkit.command.enchant.description=アイテムにエンチャントを付加します +nukkit.command.effect.description=プレイヤーに効果を付与/削除します +nukkit.command.gamemode.description=プレイヤーのゲームモードを変更します +nukkit.command.help.description=ヘルプメニューを表示します +nukkit.command.kick.description=指定したプレイヤーをサーバーから追い出します +nukkit.command.list.description=サーバーに接続しているプレイヤーを一覧表示します +nukkit.command.me.description=チャットで指定したアクションを実行します +nukkit.command.op.description=指定したプレイヤーにOP権限を付与します +nukkit.command.unban.player.description=指定したプレイヤーのBANを解除します +nukkit.command.unban.ip.description=指定したIPアドレスのBANを解除します +nukkit.command.save.description=サーバーを保存します +nukkit.command.saveoff.description=サーバーの自動保存を無効にします +nukkit.command.saveon.description=サーバーの自動保存を有効にします +nukkit.command.say.description=送信者として指定したメッセージを送信します +nukkit.command.seed.description=ワールドのシード値を表示します +nukkit.command.setworldspawn.description=ワールドのスポーン地点を設定します 座標が指定されていない場合はプレイヤーの現在地の座標が使用されます +nukkit.command.spawnpoint.description=プレイヤーのスポーン地点を設定します +nukkit.command.stop.description=サーバーを停止します +nukkit.command.tp.description=他のプレイヤーまたは指定した座標にプレイヤー(または自分自身)をテレポートさせます +nukkit.command.tell.description=指定したプレイヤーにプライベートメッセージを送信します +nukkit.command.weather.description=Sets the weather in current world +nukkit.command.xp.description=Gives the specified player a certain amount of experience +nukkit.command.whitelist.description=このサーバーの利用を許可するプレイヤーリストを管理します + +nukkit.crash.create=リカバリー不可能なエラーが発生し、サーバーがクラッシュ(動作を停止)しました。クラッシュダンプを作成しました +nukkit.crash.error=クラッシュダンプの作成に失敗: {%0} +nukkit.crash.submit=「{%0}」のファイルをクラッシュアーカイブにアップロードし、そのリンクを送ってください 出来る限り多くの情報を記載してください +nukkit.crash.archive=クラッシュダンプが自動的にクラッシュアーカイブに提出されました {%0}で閲覧またはID #{%1}を使用可能です + +nukkit.debug.enable=LevelDB形式の対応を有効にしました + +nukkit.bugreport.create=An error has been detected, creating a bug report. +nukkit.bugreport.error=Could not create bug report: {%0} +nukkit.bugreport.archive=A bug report has been created: {%0} + +nukkit.player.invalidMove={%0} が正しく移動できませんでした! +nukkit.player.logIn={%0}[/{%1}:{%2}] がエンティティID {%3} として ({%4}, {%5}, {%6}, {%7})にログインしました +nukkit.player.logOut={%0}[/{%1}:{%2}] は {%3} でログアウト +nukkit.player.invalidEntity={%0} は無効なエンティティに攻撃しました + +nukkit.plugin.load={%0} を読み込み中... +nukkit.plugin.enable={%0}を有効にしています… +nukkit.plugin.disable={%0}を無効にしています… +nukkit.plugin.restrictedName=不審な名前 +nukkit.plugin.incompatibleAPI=互換性がないAPIバージョン +nukkit.plugin.unknownDependency=不明な依存関係 +nukkit.plugin.circularDependency=循環依存が検出されました +nukkit.plugin.genericLoadError=プラグイン"{%0}"の読み込みに失敗しました +nukkit.plugin.spacesDiscouraged=プラグイン"{%0}"の名前に空白が使用されていますが、これはおすすめしません +nukkit.plugin.loadError=プラグイン"{%0}"を読み込むことができませんでした: {%1} +nukkit.plugin.duplicateError=プラグイン"{%0}"を読み込むことができませんでした: 同じプラグインが存在します +nukkit.plugin.fileError=フォルダー"{%0}"内の"{%1}"を読み込むことができませんでした: {%2} +nukkit.plugin.commandError=プラグイン{%1}のコマンド{%0}を読み込むことができませんでした +nukkit.plugin.aliasError=プラグイン {%1} で、コマンド{%0} に対するエイリアスを登録できませんでした +nukkit.plugin.deprecatedEvent=プラグイン"{%0}"がメソッド"{%2}"に"{%1}"のリスナーを登録しましたが、イベントが廃止されました +nukkit.plugin.eventError="{%1}"に"{%0}"Eventを渡すことができませんでした: {%3}での{%2} + +nukkit.resources.invalid-path=Resource packs path "{%0}" exists and is not a directory +nukkit.resources.unknown-format=Could not load "{%0}" due to format not recognized +nukkit.resources.fail=Could not load "{%0}": {%1} +nukkit.resources.success=Successfully loaded {%0} resource packs +nukkit.resources.zip.not-found=File "{%0}" is not found +nukkit.resources.zip.no-manifest="manifest.json" is not found +nukkit.resources.zip.invalid-manifest="manifest.json" is invalid or incomplete +nukkit.resources.plugin.loading=Loading resource pack from plugin {%0} diff --git a/src/main/resources/lang/jpn/nukkit.yml b/src/main/resources/lang/jpn/nukkit.yml new file mode 100644 index 00000000000..18893f9d637 --- /dev/null +++ b/src/main/resources/lang/jpn/nukkit.yml @@ -0,0 +1,98 @@ +# Nukkitの設定ファイル(機械翻訳みたいな和訳でごめんなさいw) +# 安全な設定もありますが、誤って設定すると鯖が壊れる設定の項目もあります。 +# 鯖をアップデートしても、新しい設定はこのファイルには追加されません。 + +settings: + #言語設定 + #現在選べる言語: eng, chs, cht, jpn, rus, spa, pol, bra, kor, ukr, deu, ltu, cze + language: "jpn" + #端末に送る言語を強制するかどうか + force-language: false + shutdown-message: "サーバーが終了しました" + #クエリーからプラグインリストを見えるようにする + query-plugins: true + #プラグインが非推奨APIメソッドを使用すると、コンソールにメッセージを表示します + deprecated-verbose: true + #AsyncTask workersの数 + #auto に設定すると, コア数を検出しようとします(少なくとも4) + async-workers: auto + +network: + #バイト単位のバッチ処理パケットのしきい値。これらのパケットは圧縮されます + #0にするとすべてのパケットを圧縮します, -1 で無効です. + batch-threshold: 256 + #バッチパケットを送信するときのzlibの圧縮レベルですす。 値を大きくするとcpuに多く負荷かけ、低くすると通信量が増えます。 + compression-level: 5 + #Enable network encryption + encryption: true + +debug: + #1より大きいと、コンソールにデバッグメッセージが表示されます + level: 1 + +level-settings: + #マップが使用するデフォルトのフォーマット + default-format: leveldb + #自動的にレベルが毎秒20ティックを維持するためにtickの速度を変えます。 + auto-tick-rate: true + auto-tick-rate-limit: 20 + #基本のチックレートを設定します。 (1 = 20 ticks/毎秒, 2 = 10 ticks /毎秒, etc.) + base-tick-rate: 1 + #ほかの設定がこれを許可しなくても、全員のtickを同じにする + always-tick-players: false + +chunk-sending: + #チックあたりのプレイヤーに送られるチャンクの量 + per-tick: 4 + #プレーヤーがスポーンする前に送信する必要があるチャンクの量 + spawn-threshold: 56 + #より速く送信するために、メモリ内にチャンクのシリアル化されたコピーを保存します + #プレイヤーがたくさんが同時に参加し、主にあまりブロックを設置したり壊したりしないワールドに効果ありです。 + cache-chunks: false + +chunk-ticking: + #各チックで処理する最大のチャンク量 + per-tick: 40 + #プレイヤーの周りのチャンクの半径のtick + tick-radius: 3 + clear-tick-list: false + +chunk-generation: + # マップ生成のキューが待機できるチャンクのサイズ + queue-size: 8 + #読み込みのキューが待機できるチャンクのサイズ + population-queue-size: 8 + +leveldb: + #Use native LevelDB implementation for better performance + use-native: false + #Set LevelDB memory cache size + cache-size-mb: 80 + +ticks-per: + autosave: 6000 + +player: + #trueの場合、プレーヤーデータは players/playername.dat として保存されます + #falseの場合、nukkitはプレーヤのデータを "dat"ファイルとして保存せず、プラグインが何かを実行できるようにします。 + save-player-data: true + #スキンを変更する時のクールダウンを設定(秒単位)。なお不要な場合は0を設定してください。 + skin-change-cooldown: 15 + +aliases: + #コマンドのショートカット + #例: + #showtheversion: version + #savestop: [save-all, stop] + +worlds: + #Worlds that the server will use. Options are specific to the chosen generator, and may result in broken generation or + #be ignored completely. + world: + #seed: 404 + generator: normal + options: + nether: + #seed: my_cool_nether_seed + generator: nether + options: diff --git a/src/main/resources/lang/kor/lang.ini b/src/main/resources/lang/kor/lang.ini new file mode 100644 index 00000000000..0e51de8e7da --- /dev/null +++ b/src/main/resources/lang/kor/lang.ini @@ -0,0 +1,361 @@ +# Language file compatible with Minecraft: Bedrock Edition identifiers +# +# A message doesn't need to be there to be shown correctly on the client. +# Only messages shown in Nukkit itself need to be here +# Using the language property from PocketMine-MP + +language.name=한국어 +language.selected={%0} ({%1})을(를) 기본 언어로 선택했습니다 + +multiplayer.player.joined={%0}님이 게임에 참여했습니다 +multiplayer.player.left={%0}님이 게임을 떠났습니다 + +chat.type.text=<{%0}> {%1} +chat.type.emote=* {%0} {%1} +chat.type.announcement=[{%0}] {%1} +chat.type.admin=[{%0}: {%1}] +chat.type.achievement={%0}님이 {%1} 도전 과제를 획득했습니다 + +disconnectionScreen.outdatedClient=연결할 수 없습니다: 오래된 클라이언트! +disconnectionScreen.outdatedServer=연결할 수 없습니다: 오래된 서버! +disconnectionScreen.serverFull=이용자가 많은 인기 서버입니다. 나중에 다시 들러 자리가 있는지 확인하세요. +disconnectionScreen.noReason=연결이 끊어졌습니다 +disconnectionScreen.invalidSkin=유효하지 않거나 손상된 스킨입니다! +disconnectionScreen.invalidName=유효하지 않는 이름입니다! +disconnectionScreen.resourcePack=리소스 팩을 다운로드 또는 적용 중에 문제가 발생했습니다. + +death.fell.accident.generic={%0}이(가) 높은 곳에서 떨어졌습니다 +death.attack.inFire={%0}이(가) 화염에 휩싸였습니다 +death.attack.onFire={%0}이(가) 불타 죽었습니다 +death.attack.lava={%0}이(가) 용암에 빠졌습니다 +death.attack.lava.magma={%0}이(가) 바닥이 용암인 것을 발견했습니다 +death.attack.inWall={%0}이(가) 벽 속에서 질식했습니다 +death.attack.drown={%0}이(가) 익사했습니다 +death.attack.cactus={%0}이(가) 찔려 사망했습니다 +death.attack.generic={%0}이(가) 사망했습니다 +death.attack.explosion={%0}이(가) 폭파당했습니다 +death.attack.explosion.player={%0}이(가) {%1}에게 폭파당했습니다 +death.attack.magic={%0}이(가) 마법으로 살해당했습니다 +death.attack.wither={%0}이(가) 위더 때문에 사망했습니다 +death.attack.mob={%0}이(가) {%1}에게 살해당했습니다 +death.attack.player={%0}이(가) {%1}에게 살해당했습니다 +death.attack.player.item={%0}이(가) {%2}을(를) 사용한 {%1}에게 살해당했습니다 +death.attack.arrow={%0}이(가) {%1}에게 저격당했습니다 +death.attack.arrow.item={%0}이(가) {%2}을(를) 사용한 {%1}에게 저격당했습니다 +death.attack.fall={%0}이(가) 바닥으로 너무 심하게 떨어졌습니다 +death.attack.outOfWorld={%0}이(가) 월드 밖으로 떨어졌습니다 +death.attack.starve={%0}이(가) 아사했습니다 + +gameMode.survival=서바이벌 모드 +gameMode.creative=크리에이티브 모드 +gameMode.adventure=모험 모드 +gameMode.spectator=관람자 모드 +gameMode.changed=게임 모드가 업데이트되었습니다 + +potion.moveSpeed=속도 +potion.moveSlowdown=속도 저하 +potion.digSpeed=채굴 속도 향상 +potion.digSlowDown=채굴 속도 저하 +potion.damageBoost=피해 강화 +potion.heal=회복 +potion.harm=피해 +potion.jump=점프 강화 +potion.confusion=멀미 +potion.regeneration=재생 +potion.resistance=저항 +potion.fireResistance=화염 저항 +potion.waterBreathing=수중 호흡 +potion.invisibility=투명화 +potion.blindness=실명 +potion.nightVision=야간 시야 +potion.hunger=배고픔 +potion.weakness=피해 약화 +potion.poison=독 +potion.wither=위더 +potion.healthBoost=채력 강화 +potion.absorption=흡수 +potion.saturation=포화 + +commands.generic.exception=이 명령을 수행하는 동안 알 수 없는 오류가 발생했습니다 +commands.generic.permission=이 명령어를 사용할 수 있는 권한이 없습니다 +commands.generic.ingame=이 명령어는 플레이어로만 실행할 수 있습니다 +commands.generic.unknown=알 수 없는 명령어입니다. /help에서 명령어 목록을 참조하세요. +commands.generic.player.notFound=플레이어를 찾을 수 없습니다 +commands.generic.usage=사용법: {%0} + +commands.time.added=시간이 {%0} 추가되었습니다 +commands.time.set=시간을 {%0}으로 설정했습니다 +commands.time.query=현재 시간은 {%0}입니다 + +commands.me.usage=/me <행동 ...> + +commands.give.item.notFound=이름 {%0}에 해당되는 아이템이 없습니다 +commands.give.success={%2}에 {%0} * {%1}을(를) 적용했습니다 +commands.give.tagError=데이터 태그 구문 분석에 실패: {%0} + +commands.effect.usage=/effect <플레이어> <효과> [시간(초)] [증폭] [입자 숨김 여부] 또는 /effect <플레이어> clear +commands.effect.notFound=ID {%0}에 해당하는 몹 효과가 없습니다 +commands.effect.success={%3}에 효과 {%0} (ID {%1}) * {%2} 만큼을 {%4}초 동안 주었습니다 +commands.effect.success.removed={%1}의 {%0} 효과를 제거했습니다 +commands.effect.success.removed.all={%0}에게 적용된 모든 효과를 취소했습니다 +commands.effect.failure.notActive={%1}은(는) {%0} 효과를 지니지 않아 제거할 수 없습니다 +commands.effect.failure.notActive.all={%0}에게 현재 적용된 효과가 없어 취소할 수 없습니다 + +commands.enchant.noItem=대상이 아이템을 들고 있지 않습니다 +commands.enchant.notFound=ID {%0}에 해당하는 효과부여가 없습니다 +commands.enchant.success=효과부여에 성공했습니다 +commands.enchant.usage=/enchant <플레이어> <마법 ID> [레벨] + +commands.particle.success={%0} 효과를 {%1}번 플레이 +commands.particle.notFound=알 수 없는 효과 이름 ({%0}) + +commands.players.usage=/list +commands.players.list={%0}/{%1}명 온라인: + +commands.kill.successful={%0}님 사망 +commands.kill.all.successful=모든 플레이어가 사망했습니다 +commands.kill.entities.successful=모든 엔티티가 사망했습니다 + +commands.banlist.ips=차단한 IP 주소 총 {%0}개: +commands.banlist.players=차단한 플레이어 총 {%0}명: +commands.banlist.usage=/banlist [아이피|플레이어] + +commands.defaultgamemode.usage=/defaultgamemode <모드> +commands.defaultgamemode.success=현재 월드의 기본 모드: {%0} + +commands.op.success=관리자 권한 부여됨: {%0} +commands.op.usage=/op <플레이어> + +commands.deop.success=관리자 권한 취소됨: {%0} +commands.deop.usage=/deop <플레이어> + +commands.say.usage=/say <메시지 ...> + +commands.seed.usage=/seed +commands.seed.success=시드: {%0} + +commands.ban.success={%0}님을 차단했습니다 +commands.ban.usage=/ban <플레이어> [사유 ...] + +commands.unban.success={%0}님의 차단을 해제했습니다 +commands.unban.usage=/pardon <플레이어> + +commands.banip.invalid=잘못된 IP 주소 또는 오프라인인 플레이어입니다 +commands.banip.offline.invalid=플레이어 데이터에 IP 주소가 없거나 IP 주소가 잘못되었습니다 +commands.banip.success=IP 주소({%0})를 차단했습니다 +commands.banip.success.players={%1}님 소유의 IP 주소({%0})를 차단했습니다 +commands.banip.usage=/ban-ip <아이피|플레이어> [사유 ...] + +commands.unbanip.invalid=입력된 IP 주소가 유효하지 않습니다 +commands.unbanip.success=IP 주소 {%0}의 차단을 해제했습니다 +commands.unbanip.usage=/pardon-ip <아이피> + +commands.save.usage=/save [on|off|hold|resume] +commands.save.enabled=월드 자동 저장을 켰습니다 +commands.save.disabled=월드 자동 저장을 껐습니다 +commands.save.start=저장 중... +commands.save.success=월드를 저장했습니다 + +commands.stop.usage=/stop +commands.stop.start=서버 중지 중 + +commands.kick.success={%0}님을 게임에서 추방했습니다 +commands.kick.success.reason={%0}님을 '{%1}' 게임에서 추방했습니다 +commands.kick.usage=/kick <플레이어> [사유 ...] + +commands.tp.success={%0}님을 {%1}(으)로 순간이동했습니다 +commands.tp.success.coordinates={%0}님을 {%1}, {%2}, {%3} 좌표로 순간이동했습니다 +commands.tp.usage=/tp [대상 플레이어] <목적 플레이어> 또는 /tp [대상 플레이어] <x> <y> <z> [<수평회전> <수직회전>] + +commands.whitelist.list=허용 목록의 플레이어 총 {%1}명({%0}명 만남): +commands.whitelist.enabled=허용 목록을 켰습니다 +commands.whitelist.disabled=허용 목록을 껐습니다 +commands.whitelist.reloaded=파일에서 허용 목록을 다시 불러왔습니다 +commands.whitelist.add.success={%0}님을 허용 목록에 추가했습니다 +commands.whitelist.add.usage=/whitelist add <플레이어> +commands.whitelist.remove.success={%0}님을 허용 목록에서 제거했습니다 +commands.whitelist.remove.usage=/whitelist remove <플레이어> +commands.whitelist.usage=/whitelist <on|off|list|add|remove|reload> + +commands.gamemode.success.self=내 게임 모드를 {%0}(으)로 변경했습니다 +commands.gamemode.success.other={%0}님의 게임 모드를 {%1}(으)로 변경했습니다 +commands.gamemode.usage=/gamemode <모드> [플레이어] + +commands.help.header=--- 도움말 {%1}/{%0} 페이지 (/help <페이지>) --- +commands.help.usage=/help [페이지|명령어 이름] + +commands.message.usage=/tell <플레이어> <메시지 ...> +commands.message.sameTarget=자기 자신에게는 메시지를 보낼 수 없습니다! + +commands.difficulty.usage=/difficulty <새로운 난이도> +commands.difficulty.success=게임 난이도가 {%0}(으)로 설정되었습니다 + +commands.spawnpoint.usage=/spawnpoint [플레이어] [<x> <y> <z>] +commands.spawnpoint.success=설정된 {%0} 생성 지점은 ({%1}, {%2}, {%3})입니다 + +commands.setworldspawn.usage=/setworldspawn [<x> <y> <z>] +commands.setworldspawn.success= 설정된 월드 생성 지점은 ({%0}, {%1}, {%2})입니다 + +commands.weather.clear=날씨가 맑아집니다 +commands.weather.rain=비가 내리기 시작합니다 +commands.weather.thunder=폭풍우가 몰아치기 시작합니다 +commands.weather.usage=/weather <clear|rain|thunder> [지속 시간(초)] + +commands.xp.success={%1}님의 경험치가 {%0} 추가되었습니다 +commands.xp.success.levels={%1}님의 경험치가 {%0} 추가되었습니다 +commands.xp.success.levels.minus={%1}님의 경험치가 {%0} 레벨 감소되었습니다 +commands.xp.usage=/xp <수량> [플레이어] 또는 /xp <수량>L [플레이어] + +# -------------------- Nukkit language files, only for console -------------------- + +nukkit.data.playerNotFound="{%0}"의 플레이어 데이터를 찾을 수 없습니다, 새로운 프로필을 생성합니다 +nukkit.data.playerCorrupted="{%0}"의 데이터가 손상되었습니다, 새로운 프로필을 생성합니다 +nukkit.data.playerOld="{%0}"의 플레이어 데이터가 오래되었습니다, 프로필을 업그레이드합니다 +nukkit.data.saveError=플레이어 "{%0}"의 데이터를 저장할 수 없습니다: {%1} + +nukkit.level.notFound="{%0}" 레벨을 찾을 수 없습니다 +nukkit.level.loadError="{%0}" 레벨을 불러올 수 없습니다: {%1} +nukkit.level.generationError="{%0}" 레벨을 생성할 수 없습니다: {%1} +nukkit.level.tickError="{%0}" 레벨의 틱을 처리할 수 없습니다: {%1} +nukkit.level.chunkUnloadError=청크 언로드 중 오류가 발생했습니다: {%0} +nukkit.level.backgroundGeneration="{%0}" 레벨의 스폰 지형이 백그라운드에서 생성 중입니다 +nukkit.level.defaultError=기본 레벨이 불러와지지 않았습니다 +nukkit.level.preparing="{%0}" 레벨을 준비 중입니다 +nukkit.level.unloading="{%0}" 레벨을 언로드 중입니다 +nukkit.level.updating="{%0}"의 레벨 데이터가 오래되었습니다, 포맷을 변환합니다 + +nukkit.server.start=Minecraft: BE 서버 버전 {%0}을(를) 시작 중입니다 +nukkit.server.networkError=[네트워크] {%0} 인터페이스가 {%1}(으)로 인해 작동 중단되었습니다 +nukkit.server.networkStart=서버를 {%0}:{%1}에서 여는 중입니다 +nukkit.server.info=이 서버는 {%0} 버전 {%1} "{%2}" (API {%3})을(를) 실행하고 있습니다 +nukkit.server.info.extended=이 서버는 Minecraft: BE {%4} (프로토콜 버전 {%5})용 API 버전 {%3}을(를) 포함하는 {%0} {%1} 「{%2}」을(를) 실행하고 있습니다 +nukkit.server.license={%0}은(는) GPL 라이선스 하에 배포됩니다 +nukkit.server.tickOverload=유지할 수 없습니다! 서버가 과부하되었나요? +nukkit.server.startFinished=완료 ({%0}초)! 도움말을 참조하시려면 "help" 또는 "?"를 입력해주세요 +nukkit.server.defaultGameMode=기본 게임 유형: {%0} +nukkit.server.query.start=GS4 상태 리스너를 시작 중입니다 +nukkit.server.query.info=Query 포트를 {%0}(으)로 설정 중입니다 +nukkit.server.query.running=Query가 {%0}:{%1}에서 실행 중입니다 +nukkit.server.rcon.emptyPasswordError=RCON을 시작하지 못했습니다: 비밀번호가 비어있습니다 +nukkit.server.rcon.startupError=RCON을 시작하지 못했습니다: {%0} +nukkit.server.rcon.running=RCON이 {%0}:{%1}에서 실행 중입니다 + +nukkit.command.alias.illegal=잘못된 문자를 포함하기에 '{%0}' 별칭을 등록할 수 없습니다 +nukkit.command.alias.notFound=존재하지 않는 명령어를 포함하기에 '{%0}' 별칭을 등록할 수 없습니다: {%1} +nukkit.command.exception={%1}에서 "{%0}" 명령어 실행 중 처리되지 않은 예외가 발생했습니다: {%2} + +nukkit.command.plugins.description=서버에서 실행 중인 플러그인 목록을 확인합니다 +nukkit.command.plugins.success=플러그인({%0}): {%1} +nukkit.command.plugins.usage=/plugins + +nukkit.command.reload.description=서버 설정과 플러그인을 새로 고칩니다 +nukkit.command.reload.usage=/reload +nukkit.command.reload.reloading=서버를 새로 고침 중입니다... +nukkit.command.reload.reloaded=새로 고침 완료. + +nukkit.command.status.description=서버의 성능을 읽습니다. +nukkit.command.status.usage=/status + +nukkit.command.gc.description=쓰레기 수집 작업을 시작합니다 +nukkit.command.gc.usage=/gc + +nukkit.command.title.description=지정된 플레이어에게 제목을 보내거나 해당 플레이어의 제목 설정을 수정합니다 +nukkit.command.title.usage=/title <플레이어> <clear|reset> 또는 /title <플레이어> <title|subtitle|actionbar> <제목 텍스트> 또는 /title <플레이어> <times> <페이드 인 시간> <대기 시간> <페이드 아웃 시간> +nukkit.command.title.clear={%0}의 화면을 성공적으로 초기화했습니다 +nukkit.command.title.reset={%0}의 제목 애니메이션 설정을 성공적으로 초기화했습니다 +nukkit.command.title.title={%1}에게 "{%0}" 제목을 성공적으로 보여주었습니다 +nukkit.command.title.subtitle={%1}의 다음 제목의 부제를 "{%0}"(으)로 성공적으로 설정했습니다 +nukkit.command.title.actionbar={%1}에게 "{%0}" 액션바 제목을 성공적으로 표시했습니다 +nukkit.command.title.times.success={%3}의 제목 애니메이션 시간을 {%0}, {%1}, {%2}(으)로 성공적으로 설정했습니다 +nukkit.command.title.times.fail=제목 애니메이션의 시간은 숫자 값이어야 합니다 + +nukkit.command.version.description=사용 중인 플러그인을 포함해 이 서버의 버전을 확인합니다 +nukkit.command.version.usage=/version [플러그인 이름] +nukkit.command.version.noSuchPlugin=이 서버는 해당 이름의 플러그인을 실행하고 있지 않습니다. /plugins를 입력해 플러그인 목록을 확인하세요. + +nukkit.command.give.description=지정된 플레이어에게 일정량의 아이템을 지급합니다 +nukkit.command.give.usage=/give <플레이어> <아이템[:손상 정도]> [양] [태그 ...] + +nukkit.command.kill.description=자기 자신 또는 다른 플레이어를 죽입니다 +nukkit.command.kill.usage=/kill [플레이어] + +nukkit.command.particle.description=세계에 입자를 추가합니다 +nukkit.command.particle.usage=/particle <이름> <x> <y> <z> <xd> <yd> <zd> [개수] [데이터] + +nukkit.command.time.description=각 세계의 시간을 변경합니다 +nukkit.command.time.usage=/time <set|add> <값> 또는 /time <start|stop|query> + +nukkit.command.gamerule.description=게임 규칙 값을 설정 또는 쿼리합니다 +nukkit.command.gamerule.usage=/gamerule <rule> [value] + +nukkit.command.ban.player.description=지정된 플레이어가 이 서버를 이용하지 못하도록 합니다 +nukkit.command.ban.ip.description=지정된 IP 주소가 이 서버를 이용하지 못하도록 합니다 +nukkit.command.banlist.description=이 서버에서 차단된 모든 플레이어 목록을 보여줍니다 +nukkit.command.defaultgamemode.description=기본 게임 모드를 설정합니다 +nukkit.command.deop.description=지정된 플레이어의 관리자 지위를 박탈합니다 +nukkit.command.difficulty.description=게임 난이도를 설정합니다 +nukkit.command.enchant.description=아이템에 마법을 부여합니다 +nukkit.command.effect.description=플레이어에게 효과를 부여/제거합니다 +nukkit.command.gamemode.description=플레이어를 특정 게임 모드로 변경합니다 +nukkit.command.help.description=도움말 메뉴를 보여줍니다 +nukkit.command.kick.description=지정된 플레이어를 서버에서 제거합니다 +nukkit.command.list.description=모든 온라인 플레이어 목록을 보여줍니다 +nukkit.command.me.description=대화에서 지정된 행동을 합니다 +nukkit.command.op.description=지정된 플레이어에게 관리자 지위를 부여합니다 +nukkit.command.unban.player.description=지정된 플레이어가 이 서버를 이용할 수 있도록 합니다 +nukkit.command.unban.ip.description=지정된 IP 주소가 이 서버를 이용할 수 있도록 합니다 +nukkit.command.save.description=서버를 디스크에 저장합니다 +nukkit.command.saveoff.description=서버 자동 저장을 비활성화합니다 +nukkit.command.saveon.description=서버 자동 저장을 활성화합니다 +nukkit.command.say.description=입력된 메시지를 보낸 사람으로 방송합니다 +nukkit.command.seed.description=세계 시드를 보여줍니다 +nukkit.command.setworldspawn.description=세계의 스폰 지점을 설정합니다. 좌표가 지정되지 않으면 플레이어의 좌표가 사용됩니다. +nukkit.command.spawnpoint.description=플레이어의 스폰 지점을 설정합니다 +nukkit.command.stop.description=서버를 중지합니다 +nukkit.command.tp.description=입력된 플레이어 (또는 자기 자신)을 다른 플레이어나 좌표로 순간이동시킵니다 +nukkit.command.tell.description=입력된 플레이어에게 귓속말을 보냅니다 +nukkit.command.weather.description=현재 세계의 날씨를 설정합니다 +nukkit.command.xp.description=지정된 플레이어에게 일정량의 경험치를 지급합니다 +nukkit.command.whitelist.description=이 서버를 이용할 수 있는 플레이어 목록을 관리합니다 + +nukkit.crash.create=복구 불가능한 오류가 발생해 서버가 강제 종료되었습니다. 충돌 덤프를 생성합니다 +nukkit.crash.error=충돌 덤프를 생성할 수 없습니다: {%0} +nukkit.crash.submit="{%0}" 파일을 충돌 보관소에 업로드하고 버그 보고 페이지에 링크를 제출해주세요. 가능한 한 많은 정보를 주시기 바랍니다. +nukkit.crash.archive=충돌 덤프가 자동으로 충돌 보관소에 제출되었습니다. {%0}에서 확인하거나 ID #{%1}을(를) 사용할 수 있습니다. + +nukkit.debug.enable=LevelDB 지원이 활성화되었습니다 + +nukkit.bugreport.create=오류가 감지되었습니다, 버그 보고서를 생성합니다. +nukkit.bugreport.error=버그 보고서를 생성할 수 없습니다: {%0} +nukkit.bugreport.archive=버그 보고서가 생성되었습니다: {%0} + +nukkit.player.invalidMove={%0}이(가) 잘못된 움직임을 보였습니다! +nukkit.player.logIn={%0}[/{%1}:{%2}]이(가) 개체 ID {%3}(으)로 ({%4}, {%5}, {%6}, {%7})에 로그인했습니다 +nukkit.player.logOut={%0}[/{%1}:{%2}]이(가) {%3}(으)로 인해 로그아웃되었습니다 +nukkit.player.invalidEntity={%0}이(가) 잘못된 개체를 공격하려고 시도했습니다 + +nukkit.plugin.load={%0}을(를) 불러오는 중입니다 +nukkit.plugin.enable={%0}을(를) 활성화 중입니다 +nukkit.plugin.disable={%0}을(를) 비활성화 중입니다 +nukkit.plugin.restrictedName=제한된 이름입니다 +nukkit.plugin.incompatibleAPI=호환되지 않는 API 버전입니다 +nukkit.plugin.unknownDependency=알 수 없는 의존입니다: {%0} +nukkit.plugin.circularDependency=순환적 의존이 감지되었습니다 +nukkit.plugin.genericLoadError="{%0}" 플러그인을 불러올 수 없습니다 +nukkit.plugin.spacesDiscouraged="{%0}" 플러그인은 이름에 공백을 사용합니다, 이는 권장되지 않습니다 +nukkit.plugin.loadError="{%0}" 플러그인을 불러올 수 없습니다: {%1} +nukkit.plugin.duplicateError="{%0}" 플러그인을 불러올 수 없습니다: 이미 존재하는 플러그인입니다 +nukkit.plugin.fileError="{%1}" 폴더에서 "{%0}"을(를) 불러올 수 없습니다: {%2} +nukkit.plugin.commandError={%0} 명령어를 {%1} 플러그인에서 불러올 수 없습니다 +nukkit.plugin.aliasError={%0} 별칭을 {%1} 플러그인에서 불러올 수 없습니다 +nukkit.plugin.deprecatedEvent="{%0}" 플러그인이 "{%1}"에 대한 리스너를 "{%2}" 메서드에서 등록했지만, 이 이벤트는 사용되지 않습니다. +nukkit.plugin.eventError="{%0}" 이벤트를 "{%1}"에 전달할 수 없습니다: {%3}에서의 {%2} + +nukkit.resources.invalid-path="{%0}" 리소스 팩 경로가 존재하며 디렉터리가 아닙니다 +nukkit.resources.unknown-format=포맷이 인식되지 않아 "{%0}"을(를) 불러올 수 없습니다 +nukkit.resources.fail="{%0}"을(를) 불러올 수 없습니다: {%1} +nukkit.resources.success={%0}개의 리소스 팩을 성공적으로 불러왔습니다 +nukkit.resources.zip.not-found="{%0}" 파일을 찾을 수 없습니다 +nukkit.resources.zip.no-manifest="manifest.json"을 찾을 수 없습니다 +nukkit.resources.zip.invalid-manifest="manifest.json"이 잘못되었거나 불완전합니다 +nukkit.resources.plugin.loading=Loading resource pack from plugin {%0} diff --git a/src/main/resources/lang/kor/nukkit.yml b/src/main/resources/lang/kor/nukkit.yml new file mode 100644 index 00000000000..a45a5339a12 --- /dev/null +++ b/src/main/resources/lang/kor/nukkit.yml @@ -0,0 +1,98 @@ +# Nukkit용 고급 구성 파일 +# 이 설정들 중 일부는 안전하지만, 다른 것들은 잘못 수정되면 서버를 미작동하게 할 수 있습니다. +# 새로운 설정/기본은 업그레이드할 때 이 파일에 자동으로 나타나지 않습니다 + +settings: + #다국어 설정 + #사용 가능: eng, chs, cht, jpn, rus, spa, pol, bra, kor, ukr, deu, ltu, cze + language: "kor" + #모든 문자열을 서버 로캘로 번역해 전송하거나 기기가 처리할 수 있게 할지 여부 + force-language: false + shutdown-message: "Server closed" + #Query를 통한 플러그인 목록 보기를 허용합니다 + query-plugins: true + #플러그인이 사용되지 않는 API 메서드를 사용할 때 콘솔 메시지를 표시합니다 + deprecated-verbose: true + #AsyncTask Works의 개수 + #auto로 설정하면, 자동으로 코어의 개수를 감지하려고 시도합니다(최소 4개) + async-workers: auto + +network: + #일괄 처리 패킷에 대한 임곗값(바이트)입니다. 이 패킷들만 압축됩니다 + #모두 압축하려면 0으로 설정하고, 비활성화하려면 -1으로 설정하세요 + batch-threshold: 256 + #일괄 처리된 패킷을 전송할 때 Zlib에 사용되는 압축 수준입니다. 높을수록 더 많은 CPU 사용량으로, 적은 대역폭을 사용합니다 + compression-level: 5 + #Enable network encryption + encryption: true + +debug: + #1보다 크면, 콘솔에 디버그 메시지를 표시합니다 + level: 1 + +level-settings: + #레벨이 생성될 때 사용할 기본 포맷 + default-format: mcregion + #1초당 20틱을 유지하기 위해 자동으로 레벨의 틱을 변경합니다 + auto-tick-rate: true + auto-tick-rate-limit: 20 + #기본 틱을 설정합니다 (1 = 1초당 20틱, 2 = 1초당 10틱, 등등.) + base-tick-rate: 1 + #다른 설정들이 이를 허용하지 않더라도 모든 플레이어를 틱 처리합니다 + always-tick-players: false + +chunk-sending: + #플레이어에게 틱 당 보낼 청크의 양 + per-tick: 4 + #플레이어를 생성하기 전에 보내져야 할 청크의 양 + spawn-threshold: 56 + #빠른 전송을 위해 메모리에 직렬화된 청크의 복사본을 저장합니다 + #많은 플레이어가 동시에 참여하는 대부분 정적인 세계에서 유용합니다 + cache-chunks: false + +chunk-ticking: + #각 틱 당 처리될 청크의 최대량 + per-tick: 40 + #플레이어 주변의 틱 처리할 청크의 범위 + tick-radius: 3 + clear-tick-list: false + +chunk-generation: + #대기열에 있는 생성 대기 중인 청크의 최대량 + queue-size: 8 + #대기열에 있는 채울 대기 중인 청크의 최대량 + population-queue-size: 8 + +leveldb: + #Use native LevelDB implementation for better performance + use-native: false + #Set LevelDB memory cache size + cache-size-mb: 80 + +ticks-per: + autosave: 6000 + +player: + #true로 설정하면, 플레이어 데이터가 players/플레이어 이름.dat으로 저장됩니다 + #false로 설정하면, Nukkit이 플레이어 데이터를 "dat" 파일로 저장하지 않으므로 플러그인에서 무언가를 수행할 수 있습니다. + save-player-data: true + #The time between skin change action in seconds, set to 0 if you dont want the cooldown + skin-change-cooldown: 15 + +aliases: + #명령어의 별칭 + #예: + # showtheversion: version + # savestop: [save-all, stop] + +worlds: + #Worlds that the server will use. Options are specific to the chosen generator, and may result in broken generation or + #be ignored completely. + world: + #seed: 404 + generator: normal + options: + nether: + #seed: my_cool_nether_seed + generator: nether + options: diff --git a/src/main/resources/lang/language.list b/src/main/resources/lang/language.list new file mode 100644 index 00000000000..2f722e638c2 --- /dev/null +++ b/src/main/resources/lang/language.list @@ -0,0 +1,17 @@ +eng => English +chs => 中文(简体) +cht => 中文(繁體) +jpn => 日本語 +rus => Pyccĸий +spa => Español +pol => Polish +bra => Português-Brasil +kor => 한국어 +ukr => Українська +deu => Deutsch +ltu => Lietuviškai +idn => Indonesia +cze => Czech +tur => Turkish +fin => Suomi +ara => العربيه diff --git a/src/main/resources/lang/ltu/lang.ini b/src/main/resources/lang/ltu/lang.ini new file mode 100644 index 00000000000..7e9600628f1 --- /dev/null +++ b/src/main/resources/lang/ltu/lang.ini @@ -0,0 +1,362 @@ +# Language file compatible with Minecraft: Bedrock Edition identifiers +# +# A message doesn't need to be there to be shown correctly on the client. +# Only messages shown in Nukkit itself need to be here +# Using the language property from PocketMine-MP + +language.name=Lietuvių +language.selected=Pasirinkote {%0} ({%1}) kaip pagrindinę kalbą + +multiplayer.player.joined={%0} prisijungė į žaidimą +multiplayer.player.left={%0} atsijungė nuo žaidimo + +chat.type.text=<{%0}> {%1} +chat.type.emote=* {%0} {%1} +chat.type.announcement=[{%0}] {%1} +chat.type.admin=[{%0}: {%1}] +chat.type.achievement={%0} gavo pasiekimą {%1} + +disconnectionScreen.outdatedClient=Pasenęs klientas! +disconnectionScreen.outdatedServer=Pasenęs serveris! +disconnectionScreen.serverFull=Serveris pilnas! +disconnectionScreen.noReason=Atjungtas nuo serverio +disconnectionScreen.invalidSkin=Netinkamas skin! +disconnectionScreen.invalidName=Netinkamas vardas! +disconnectionScreen.resourcePack=Encountered a problem while downloading or applying resource pack. + +death.fell.accident.generic={%0} nukrito iš aukštai +death.attack.inFire={%0} sudegė +death.attack.onFire={%0} sudegė +death.attack.lava={%0} bandė plaukti lavoje +death.attack.lava.magma={%0} perkaito +death.attack.inWall={%0} buvo suplotas +death.attack.drown={%0} nuskendo +death.attack.cactus={%0} nusidūrė +death.attack.generic={%0} žuvo +death.attack.explosion={%0} sprogo +death.attack.explosion.player={%0} buvo susprogdintas {%1} +death.attack.magic={%0} buvo nužudytas magijos +death.attack.wither={%0} buvo nužudytas vitherio +death.attack.mob={%0} mirė nuo {%1} kirčio +death.attack.player={%0} mirė nuo {%1} kirčio +death.attack.player.item={%0} mirė nuo {%1} kirčio naudojant {%2} +death.attack.arrow={%0} buvo nušautas iš {%1} lanko +death.attack.arrow.item={%0} buvo nušautas iš {%1} lanko naudojant {%2} +death.attack.fall={%0} susiplojo ant žemės +death.attack.outOfWorld={%0} iškrito iš pasaulio +death.attack.starve={%0} starved to death + +gameMode.survival=Išgyvenimo rėžimas +gameMode.creative=Kūrybinis rėžimas +gameMode.adventure=Nuotykių rėžimas +gameMode.spectator=Stebėtojo rėžimas +gameMode.changed=Jūsų žaidimo rėžimas buvo pakeistas + +potion.moveSpeed=Greitis +potion.moveSlowdown=Lėtumas +potion.digSpeed=Greitas kasimas +potion.digSlowDown=Lėtas kasimas +potion.damageBoost=Jėga +potion.heal=Momentinė sveikata +potion.harm=Momentinė žala +potion.jump=Šoklumas +potion.confusion=Pykinimas +potion.regeneration=Atgijimas +potion.resistance=Atsparumas +potion.fireResistance=Atsparumas ugniai +potion.waterBreathing=Kvėpavimas po vandeniu +potion.invisibility=Nematomumas +potion.blindness=Aklumas +potion.nightVision=Naktinis matymas +potion.hunger=Alkis +potion.weakness=Silpnumas +potion.poison=Nuodai +potion.wither=Vitheris +potion.healthBoost=Papildoma sveikata +potion.absorption=Sugertis +potion.saturation=Pasisotinimas + +commands.generic.exception=Nežinoma klaida bandant įvykdyti komandą +commands.generic.permission=Jūs neturite teisės naudoti šią komandą +commands.generic.ingame=Jūs galite naudoti šią komandą tik kaip žaidėjas +commands.generic.unknown=Nežinoma komanda. Bandykite /help, norėdami gauti pagalbos +commands.generic.player.notFound=Žaidėjas nerastas +commands.generic.usage=Naudojimas: {%0} + +commands.time.added=Pridėta {%0} prie laiko +commands.time.set=Laikas nustatytas į {%0} +commands.time.query=Dabartinis laikas yra {%0} + +commands.me.usage=/me <veiksmas ...> + +commands.give.item.notFound=Nėra tokio daikto su pavadinimu {%0} +commands.give.success=Davėte {%0} * {%1} žaidėjui {%2} +commands.give.tagError=Neteisingas užrašymas: {%0} + +commands.effect.usage=/effect <žaidėjas> <efektas> [sekundės] [stiprumas] [slėpti-daleles] ARBA /effect <žaidėjas> clear +commands.effect.notFound=Nėra tokio monstro su ID {%0} +commands.effect.success=Davėte {%0} (ID {%1}) * {%2} žaidėjui {%3} {%4} sekundžių +commands.effect.success.removed=Paėmėte {%0} iš {%1} +commands.effect.success.removed.all=Išemėte visus efektus nuo {%0} +commands.effect.failure.notActive=Negalima išimti {%0} iš {%1}, nes jie neturi tokio efekto +commands.effect.failure.notActive.all=Negalima išmiti efektų iš {%0}, nes jie tokių neturi + +commands.enchant.noItem=Žaidėjas nelaiko jokio daikto rankoje +commands.enchant.notFound=Nėra tokio užkerėjimo ID {%0} +commands.enchant.success=Sėkmingai užkerėta +commands.enchant.usage=/enchant <žaidėjas> <užkerėjimo ID> [lygis] + +commands.particle.success=Rodomas efektas {%0} {%1} kartų +commands.particle.notFound=Nežinomas efektas {%0} + +commands.players.usage=/list +commands.players.list=Dabar prisijungę {%0}/{%1} žaidėjų: + +commands.kill.successful=Nužudyta (-as) {%0} +commands.kill.all.successful=Nužudyti visi žaidėjai +commands.kill.entities.successful=Nužudytos visos būtybės + +commands.banlist.ips=Yra iš viso {%0} užblokuotų IP adresų: +commands.banlist.players=Yra iš viso {%0} blokuotų žaidėjų: +commands.banlist.usage=/banlist [ips|players] + +commands.defaultgamemode.usage=/defaultgamemode <mode> +commands.defaultgamemode.success=Pasaulio įprastinis žaidimo rėžimas nustatytas į {%0} + +commands.op.success={%0} dabar turi administratoriaus teises +commands.op.usage=/op <žaidėjas> + +commands.deop.success={%0} nebeturi administratoriaus teisių +commands.deop.usage=/deop <player> + +commands.say.usage=/say <žinutė ...> + +commands.seed.usage=/seed +commands.seed.success=Pasaulio generavimo formulė: {%0} + +commands.ban.success={%0} užblokuotas +commands.ban.usage=/ban <žaidėjas> [priežastis ...] + +commands.unban.success=Žaidėjas {%0} atblokuotas +commands.unban.usage=/pardon <žaidėjas> + +commands.banip.invalid=Įvedėte blogą IP adresą arba šis žaidėjas nėra prisijungęs prie serverio +commands.banip.offline.invalid=Žaidėjo duomenyse IP adresas nerastas arba įvestas blogas IP adresas +commands.banip.success=Užblokuotas IP adresas {%0} +commands.banip.success.players=Užblokuotas IP adresas {%0} kuris priklauso žaidėjui {%1} +commands.banip.usage=/ban-ip <IP|žaidėjas> [priežastis ...] + +commands.unbanip.invalid=Įvedėte blogą IP adresą +commands.unbanip.success=Atblokuotas IP adresas {%0} +commands.unbanip.usage=/pardon-ip <IP> + +commands.save.usage=/save [on|off|hold|resume] +commands.save.enabled=Įjungtas pasaulio auto išsaugojimas +commands.save.disabled=Išjungtas pasaulio auto išsaugojimas +commands.save.start=Išsaugoma... +commands.save.success=Pasaulis išsaugotas + +commands.stop.usage=/stop +commands.stop.start=Serveris išjungiamas + +commands.kick.success=Žaidėjas {%0} išmestas iš žaidimo +commands.kick.success.reason=Žaidėjas {%0} išmestas iš žaidimo: '{%1}' +commands.kick.usage=/kick <žaidėjas> [priežastis ...] + +commands.tp.success=Perkeltas(-a) {%0} pas {%1} +commands.tp.success.coordinates=Perkeltas(-a) {%0} į koordinates {%1}, {%2}, {%3} +commands.tp.usage=/tp [ką] <pas ką> ARBA /tp [ką] <x> <y> <z> [<y-rot> <x-rot>] + +commands.whitelist.list=Yra {%0} (matyti {%1}) žaidėjai baltajame sąraše: +commands.whitelist.enabled=Baltasis sąrašas įjungtas +commands.whitelist.disabled=Baltasis sąrašas išjungtas +commands.whitelist.reloaded=Baltasis sąrašas perkrautas +commands.whitelist.add.success=Žaidėjas {%0} pridėtas į baltąjį sąrašą +commands.whitelist.add.usage=/whitelist add <žaidėjas> +commands.whitelist.remove.success=Žaidėjas {%0} pašalintas iš baltojo sąrašo +commands.whitelist.remove.usage=/whitelist remove <žaidėjas> +commands.whitelist.usage=/whitelist <on|off|list|add|remove|reload> + +commands.gamemode.success.self=Jūsų žaidimo rėžimas pakeistas į {%0} +commands.gamemode.success.other=Žaidėjo {%0} žaidimo rėžimas pakeistas į {%1} +commands.gamemode.usage=/gamemode <rėžimas> [žaidėjas] + +commands.help.header=--- Rodomas pagalbos puslapis {%0} iš {%1} (/help <puslapis>) --- +commands.help.usage=/help [puslapis|komanda] + +commands.message.usage=/tell <žaidėjui> <žinutę ...> +commands.message.sameTarget=Jūs negalite siųsti žinučių sau! + +commands.difficulty.usage=/difficulty <sudėtingumo lygis 0-3> +commands.difficulty.success=Nustatytas sudėtingumo lygis į {%0} + +commands.spawnpoint.usage=/spawnpoint [žaidėjas] [<x> <y> <z>] +commands.spawnpoint.success=Nustatyta žaidėjo {%0} atsiradimo vieta ({%1}, {%2}, {%3}) + +commands.setworldspawn.usage=/setworldspawn [<x> <y> <z>] +commands.setworldspawn.success=Nustatyta nauja pasaulio atsiradimo vieta ({%0}, {%1}, {%2}) + +commands.weather.clear=Keičiama į giedrą +commands.weather.rain=Keičiama į lietų +commands.weather.thunder=Keičiama į lietų ir griaustinį +commands.weather.usage=/weather <clear|rain|thunder> [trukmė] + +commands.xp.success=Duota {%0} patirties žaidėjui {%1} +commands.xp.success.levels=Duota {%0} lygių žaidėjui {%1} +commands.xp.success.levels.minus=Paimta {%0} lygių iš {%1} +commands.xp.usage=/xp <kiekis> [žaidėjas] ARBA /xp <lygis>L [žaidėjas] + +# -------------------- Nukkit language files, only for console -------------------- + +nukkit.data.playerNotFound=Žaidėjas "{%0}" nerastas, kuriamas naujas profilis +nukkit.data.playerCorrupted=Žaidėjo "{%0}" duomenys sugadinti, kuriamas naujas profilis +nukkit.data.playerOld=Žaidėjo "{%0}" duomenys pasenę, atnaujinamas profilis +nukkit.data.saveError=Neįmanoma išsaugoti žaidėjo "{%0}": {%1} + +nukkit.level.notFound=Pasaulis "{%0}" nerastas +nukkit.level.loadError=Neįmanoma įkelti pasaulio "{%0}": {%1} +nukkit.level.generationError=Neįmanoma sugeneruoti pasaulio "{%0}": {%1} +nukkit.level.tickError=Neįmanoma atnaujinti pasaulio "{%0}": {%1} +nukkit.level.chunkUnloadError=Klaida bandant iškrauti pasaulio dalį: {%0} +nukkit.level.backgroundGeneration=Atsiradimo vietovė pasaulyje "{%0}" šiuo metu generuojama fone +nukkit.level.defaultError=Nepakrautas joks įprastinis pasaulis +nukkit.level.preparing=Ruošiamas pasaulis "{%0}" +nukkit.level.unloading=Iškraunamas pasaulis "{%0}" +nukkit.level.updating=Rastas pasenęs pasaulis pavadinimu "{%0}", atnaujinamas formatas + +nukkit.server.start=Įjungiamas Minecraft: BE serveris (versija: {%0}) (Vertimas: nogalosa.lt) +nukkit.server.networkError=[Tinklas] Išjungta sąsaja {%0} dėl {%1} +nukkit.server.networkStart=Atidaromas serveris ant {%0}:{%1} +nukkit.server.info=Šis serveris veikia ant {%0} versijos {%1} "{%2}" (API {%3}) +nukkit.server.info.extended=Šis serveris veikia ant {%0} {%1} 「{%2}」 implementuodamas API versiją {%3} žaidimui Minecraft: BE {%4} (protokolo versija {%5}) +nukkit.server.license={%0} platinama pagal GPL licenciją +nukkit.server.tickOverload=Nespėju atnaujinti! Ar serveris perkrautas? +nukkit.server.startFinished=Baigta ({%0}s)! Jeigu reikia pagalbos, rašykite "help" arba "?" +nukkit.server.defaultGameMode=Įprastinis žaidimo rėžimas: {%0} +nukkit.server.query.start=Įjungiamas GS4 statistikos klausytojas +nukkit.server.query.info=Nustatomas query portas į {%0} +nukkit.server.query.running=Query veikia ant {%0}:{%1} +nukkit.server.rcon.emptyPasswordError=Neįmanoma įjungti RCON: neįrašytas slaptažodis +nukkit.server.rcon.startupError=Neįimanoma įjungti RCON: {%0} +nukkit.server.rcon.running=RCON veikia ant {%0}:{%1} + +nukkit.command.alias.illegal=Neįmanoma užregistruoti alternatyvos {%0}, nes ji turi netinkamų simbolių +nukkit.command.alias.notFound=Neįmanoma užregistruoti alternatyvos {%0}, nes ji turi komandų, kurios neegzistuoja: {%1} +nukkit.command.exception=Klaida bandant įvykdyti komandą "{%0}" - {%1}: {%2} + +nukkit.command.plugins.description=Įskiepių sąrašas, kurį naudoja serveris +nukkit.command.plugins.success=Įskiepiai ({%0}): {%1} +nukkit.command.plugins.usage=/plugins + +nukkit.command.reload.description=Perkrauna serverio konfigūraciją ir įskiepius +nukkit.command.reload.usage=/reload +nukkit.command.reload.reloading=Perkraunamas serveris... +nukkit.command.reload.reloaded=Sėkmingai perkrauta. + +nukkit.command.status.description=Informacija apie serverio būseną. +nukkit.command.status.usage=/status + +nukkit.command.gc.description=Įjungia programinių šiukšlių valymą +nukkit.command.gc.usage=/gc + +nukkit.command.title.description=Sends a title to the specified player or modifies title settings for that player +nukkit.command.title.usage=/title <player> <clear|reset> OR /title <player> <title|subtitle|actionbar> <title text> OR /title <player> <times> <fade in time> <stay time> <fade out time> +nukkit.command.title.clear=Successfully cleared {%0}'s screen +nukkit.command.title.reset=Successfully reset title animation settings for {%0} +nukkit.command.title.title=Successfully shown "{%0}" title to {%1} +nukkit.command.title.subtitle=Successfully set subtitle to "{%0}" for {%1}'s next title +nukkit.command.title.actionbar=Successfully shown "{%0}" actionbar title to {%1} +nukkit.command.title.times.success=Successfully set title animation times to {%0}, {%1}, {%2} for {%3} +nukkit.command.title.times.fail=Times of title animations must be numeric values + +nukkit.command.version.description=Parodo serverio versiją bei įskiepio informaciją +nukkit.command.version.usage=/version [plugin name] +nukkit.command.version.noSuchPlugin=Šis serveris neturi įskiepio su šiuo vardu. Naudokite /plugins, kad gautumėte įskiepių sąrašą. + +nukkit.command.give.description=Duoda pasirinktam žaidėjui tam tikrą skaičių nurodytų daiktų +nukkit.command.give.usage=/give <žaidėjas> <daiktas[:žala]> [kiekis] [duomenys ...] + +nukkit.command.kill.description=Nusižudyti arba nužudyti kitą žaidėją +nukkit.command.kill.usage=/kill [žaidėjas] + +nukkit.command.particle.description=Prideda dalelyčių į pasaulį +nukkit.command.particle.usage=/particle <name> <x> <y> <z> <xd> <yd> <zd> [skaičius] [duomenys] + +nukkit.command.time.description=Pakeičia pasaulio laiką +nukkit.command.time.usage=/time <set|add> <reikšmė> OR /time <start|stop|query> + +nukkit.command.gamerule.description=Sets or queries a game rule value +nukkit.command.gamerule.usage=/gamerule <rule> [value] + +nukkit.command.ban.player.description=Užblokuoja pasirinktą žaidėją +nukkit.command.ban.ip.description=Užblokuoja pasirinktą IP +nukkit.command.banlist.description=Peržiūrėti visus užblokuotus žaidėjus +nukkit.command.defaultgamemode.description=Nustatyti įprastinį žaidimo rėžimą +nukkit.command.deop.description=Atima administravimo teises +nukkit.command.difficulty.description=Nustato žaidimo sunkumą +nukkit.command.enchant.description=Daikto užkerėjimas +nukkit.command.effect.description=Prideda/nuima efektą nuo žaidėjo +nukkit.command.gamemode.description=Pakeičia žaidėjo žaidimo rėžimą +nukkit.command.help.description=Parodo pagalbos meniu +nukkit.command.kick.description=Išspiria žaidėją iš žaidimo +nukkit.command.list.description=Parodo prisijungusius žaidėjus +nukkit.command.me.description=Parodo tam tikrą žaidėjo veiksmą +nukkit.command.op.description=Duoda žaidėjui administratoravimo teises +nukkit.command.unban.player.description=Atblokuoja žaidėją +nukkit.command.unban.ip.description=Atblokuoja IP +nukkit.command.save.description=Išsaugo serverį į diską +nukkit.command.saveoff.description=Išjungia serverio automatinį išsaugojimą +nukkit.command.saveon.description=Įjungia serverio automatinį išsaugojimą +nukkit.command.say.description=Išsiunčiama žinutė visiems žaidėjams +nukkit.command.seed.description=Parodo pasaulio generavimo formulę. +nukkit.command.setworldspawn.description=Nustato pasaulio atsiradimo vietą. Jeigu nepateiktos koordinatės, naudojamos žaidėjo. +nukkit.command.spawnpoint.description=Nustato žaidėjo atsiradimo vietą. +nukkit.command.stop.description=Išjungia serverį +nukkit.command.tp.description=Perkelia nurodytą žaidėją (arba patį žaidėją) pas kitą žaidėją arba į koordinates +nukkit.command.tell.description=Nusiunčiama privati žinutė žaidėjui +nukkit.command.weather.description=Nustatomas pasaulio oras +nukkit.command.xp.description=Duoda nurodytam žaidėjui nurodytą kiekį patirties +nukkit.command.whitelist.description=Nustatoma kas gali įeitį į serverį + +nukkit.crash.create=Serveris nulūžo su nepataisoma klaida. Kaupiama nulūžimo informaciją į failą +nukkit.crash.error=Neįmanoma įrašyti nulūžimo informacijos į failą: {%0} +nukkit.crash.submit=Prašome įkelti failą "{%0}" į Crash Archive ir numeskite nuorodą į Bug Reporting puslapį. Pridėkite kuo įmanoma daugiau išsamesnės informacijos. +nukkit.crash.archive=Nulūžimo informacija buvo automatiškai įkelta į Crash Archive. Jūs galite ją pažiūrėti čia {%0} arba naudoti ID #{%1}. + +nukkit.debug.enable=LevelDB palaikymas įjungtas + +nukkit.bugreport.create=An error has been detected, creating a bug report. +nukkit.bugreport.error=Could not create bug report: {%0} +nukkit.bugreport.archive=A bug report has been created: {%0} + +nukkit.player.invalidMove={%0} neteisingai pajudėjo! + +nukkit.player.logIn={%0}[/{%1}:{%2}] prisijungė su būtybės id {%3} koordinatėse ({%4}, {%5}, {%6}, {%7}) +nukkit.player.logOut={%0}[/{%1}:{%2}] atsijungė dėl {%3} +nukkit.player.invalidEntity={%0} bandė atakuoti klaidingą būtybę + +nukkit.plugin.load=Kraunama {%0} +nukkit.plugin.enable=Įjungiama {%0} +nukkit.plugin.disable=Išjungiama {%0} +nukkit.plugin.restrictedName=Uždraustas vardas +nukkit.plugin.incompatibleAPI=Nepalaikoma API versija +nukkit.plugin.unknownDependency=Nežinoma priklausomybė +nukkit.plugin.circularDependency=Aptikta skritulinė priklausomybė +nukkit.plugin.genericLoadError=Negalima įkelti įskiepio "{%0}" +nukkit.plugin.spacesDiscouraged=Įskiepis "{%0}" naudoja tarpus savo pavadinime, tai yra nebepalaikoma +nukkit.plugin.loadError=Neįmanoma įkelti įskiepio "{%0}": {%1} +nukkit.plugin.duplicateError=Neįmanoma įkelti įskiepio "{%0}": įskiepis jau egzistuoja +nukkit.plugin.fileError=Neįmanoma įkelti "{%0}" kataloge "{%1}": {%2} +nukkit.plugin.commandError=Neįmanoma įkelti komandos {%0} įskiepiui {%1} +nukkit.plugin.aliasError=Neįmanoma įkelti alternatyvos {%0} įskiepiui {%1} +nukkit.plugin.deprecatedEvent=Įskiepis "{%0}" užregistravo listenerį "{%1}" ant metodo "{%2}", bet eventas jau nebepalaikomas. +nukkit.plugin.eventError=Neįmanoma pereiti per eventą "{%0}" to "{%1}": {%2} on {%3} + +nukkit.resources.invalid-path=Resource packs path "{%0}" exists and is not a directory +nukkit.resources.unknown-format=Could not load "{%0}" due to format not recognized +nukkit.resources.fail=Could not load "{%0}": {%1} +nukkit.resources.success=Successfully loaded {%0} resource packs +nukkit.resources.zip.not-found=File "{%0}" is not found +nukkit.resources.zip.no-manifest="manifest.json" is not found +nukkit.resources.zip.invalid-manifest="manifest.json" is invalid or incomplete +nukkit.resources.plugin.loading=Loading resource pack from plugin {%0} diff --git a/src/main/resources/lang/ltu/nukkit.yml b/src/main/resources/lang/ltu/nukkit.yml new file mode 100644 index 00000000000..b2d8813a894 --- /dev/null +++ b/src/main/resources/lang/ltu/nukkit.yml @@ -0,0 +1,98 @@ +# Konfigūracijos failas Nukkit platformai +# Vieni nustatymai yra saugūs, kiti gali sulaužyti Jūsų serverį, jeigu įrašytos blogos reikšmės +# Atnaujinant serverio platformą nustatymai turėtų išlikti + +settings: + #Kalbos nustatymas + #Galimos kalbos: bra, chs, cht, cze, deu, eng, idn, jpn, kor, ltu, pol, rus, spa, tur, ukr + language: "ltu" + #Ar priverstinai įjungti kalbą ar leisti pačiam įrenginiui susidoroti su vertimu + force-language: false + shutdown-message: "Serveris išjungtas" + #Rodo įskiepius per Query + query-plugins: true + #Rodyti pranešimą konsolėje, jei įskiepiai naudoja senus API metodus + deprecated-verbose: true + #AsyncTask workerių skaičius + #Jeigu nustatytas ant auto, jis automatiškai bandys aptikti branduolių skaičių (ir bent 4) + async-workers: auto + +network: + #Didžiausas leistinas paketų rūšiavimas bitais. Tik šie paketai bus suspausti + #Nustatykite 0, jeigu norite suspausti visus paketus, -1, kad išjungti + batch-threshold: 256 + #Suspaudimo lygis naudojant Zlib kai siunčiami suspausti paketai. Didesnė reikšmė = daugiau CPU, mažiau tinklo naudojimo + compression-level: 5 + #Enable network encryption + encryption: true + +debug: + #Jeigu > 1, jis rodys derinimo pranešimus konsolėje + level: 1 + +level-settings: + #Įprastinis formatas kuriant pasaulius + default-format: leveldb + #Automatiškai keisti impuslų greitį, kad atiktiktų pasaulio 20 impulsų per sekundę greitį + auto-tick-rate: true + auto-tick-rate-limit: 20 + #Nustatyti impulsų skaičių (1 = 20 impulsai per sekundę, 2 = 10 impulsai per sekunde ir t.t.) + base-tick-rate: 1 + #Atnaujinti visus žaidėjus pasaulyje kiekvieną impulsą, nors kiti nustatymai to neleidžia + always-tick-players: false + +chunk-sending: + #Chunkų skaičius nusiunčiamas žaidėjui per vieną impulsą + per-tick: 4 + #Minimalus chunkų skaičius norint, kad žaidėjas atsirastų pasaulyje + spawn-threshold: 56 + #Įrašyti pasaulio informaciją į RAM, kad informacija būtų greičiau pasiekiama + #Tobulas dalykas, jeigu pasaulis yra daugiausiai statinis ir į jį prisijungia daug žaidėjų vienu metu + cache-chunks: false + +chunk-ticking: + #Chunkų limitas, kurį gali apdoroti serveris per vieną impulsą + per-tick: 40 + #Kiek chunkų apdoroti aplink kiekvieną žaidėją + tick-radius: 3 + clear-tick-list: false + +chunk-generation: + #Kiek daugiausiai chunkų gali laukti generavimo laukimo eilėje + queue-size: 8 + #Kiek daugiausiai chunkų gali laukti antrinio generavimo laukimo eilėje + population-queue-size: 8 + +leveldb: + #Use native LevelDB implementation for better performance + use-native: false + #Set LevelDB memory cache size + cache-size-mb: 80 + +ticks-per: + autosave: 6000 + +player: + #Jeigu įvestis "true", tai žaidėjo informacija bus išsaugota faile players/zaidejo-vardas.dat + #Jeigu įvestis "false", nukkit neišsaugos žaidėjo informacijos į "dat" failus, kad įskiepiai galėtų kažką padaryti su jais + save-player-data: true + #The time between skin change action in seconds, set to 0 if you dont want the cooldown + skin-change-cooldown: 15 + +aliases: + #Alternatyvos komandoms + #Pavyzdžiai: + #showtheversion: version + #savestop: [save-all, stop] + +worlds: + #Worlds that the server will use. Options are specific to the chosen generator, and may result in broken generation or + #be ignored completely. + world: + #seed: 404 + generator: normal + options: + nether: + #seed: my_cool_nether_seed + generator: nether + options: diff --git a/src/main/resources/lang/pol/lang.ini b/src/main/resources/lang/pol/lang.ini new file mode 100644 index 00000000000..91d50e7e83a --- /dev/null +++ b/src/main/resources/lang/pol/lang.ini @@ -0,0 +1,361 @@ +# Language file compatible with Minecraft: Bedrock Edition identifiers +# +# A message doesn't need to be there to be shown correctly on the client. +# Only messages shown in Nukkit itself need to be here +# Using the language property from PocketMine-MP + +language.name=Polski +language.selected=Wybrano {%0} ({%1}) jako jezyk bazowy + +multiplayer.player.joined={%0} dolaczyl do gry +multiplayer.player.left={%0} opuscil gre + +chat.type.text=<{%0}> {%1} +chat.type.emote=* {%0} {%1} +chat.type.announcement=[{%0}] {%1} +chat.type.admin=[{%0}: {%1}] +chat.type.achievement={%0} zdobyl osiagniecie {%1} + +disconnectionScreen.outdatedClient=Twoja wersja klienta jest starsza od wersji serwera! +disconnectionScreen.outdatedServer=Wersja serwera jest starsza od twojej wersji klienta! +disconnectionScreen.serverFull=Serwer jest pelny! +disconnectionScreen.noReason=Rozlaczono z serwerem +disconnectionScreen.invalidSkin=Nieprawidlowy skin! +disconnectionScreen.invalidName=Nieprawidlowy nick! +disconnectionScreen.resourcePack=Natrafiono na problem podczas pobierania lub ladowania paczki zasobow + +death.fell.accident.generic={%0} upadl z wysokosci +death.attack.inFire={%0} spalil sie w plomieniach +death.attack.onFire={%0} spalil sie na smierc +death.attack.lava={%0} probowal plywac w lawie +death.attack.lava.magma={%0} odkryl, ze podloga jest lawa +death.attack.inWall={%0} umarl w scianie +death.attack.drown={%0} utonal +death.attack.cactus={%0} zostal zakluty na smierc +death.attack.generic={%0} zginal +death.attack.explosion={%0} zostal wysadzony +death.attack.explosion.player={%0} zostal wysadzony przez {%1} +death.attack.magic={%0} zostal zabity przez magie +death.attack.wither={%0} zamienil sie w pyl +death.attack.mob={%0} zostal zabity przez {%1} +death.attack.player={%0} zostal zabity przez {%1} +death.attack.player.item={%0} zostal zabity przez {%1} za pomoca {%2} +death.attack.arrow={%0} zostal zastrzelony przez {%1} +death.attack.arrow.item={%0} zostal zastrzelony przez {%1} za pomoca {%2} +death.attack.fall={%0} uderzyl sie o ziemie zbyt mocno +death.attack.outOfWorld={%0} wypadl ze swiata +death.attack.starve={%0} zaglodzil sie na smierc + +gameMode.survival=Tryb przetrwania +gameMode.creative=Tryb kreatywny +gameMode.adventure=Tryb przygody +gameMode.spectator=Tryb obserwatora +gameMode.changed=Twoj tryb gry zostal zmieniony + +potion.moveSpeed=Predkosc +potion.moveSlowdown=Spowolnienie +potion.digSpeed=Predkosc kopania +potion.digSlowDown=Spowolnione kopanie +potion.damageBoost=Zwiekszona sila +potion.heal=Natychmiastowe leczenie +potion.harm=Natychmiastowe obrazenie +potion.jump=Zwiekszony skok +potion.confusion=Dezorientacja +potion.regeneration=Regeneracja +potion.resistance=Odpornosc +potion.fireResistance=Odpornosc na ogien +potion.waterBreathing=Oddychanie pod woda +potion.invisibility=Niewidzialnosc +potion.blindness=Slepota +potion.nightVision=Widzenie w nocy +potion.hunger=Glod +potion.weakness=Slabosc +potion.poison=Trucizna +potion.wither=Wither +potion.healthBoost=Zwiekszone zdrowie +potion.absorption=Absorbcja +potion.saturation=Nasycenie + +commands.generic.exception=Wystapil nieznany blad podczas wykonywania tej komendy +commands.generic.permission=Nie masz uprawnien do wykonania tej komendy +commands.generic.ingame=Ta komende mozesz wykonac tylko bedac graczem +commands.generic.unknown=Nieznana komenda. Wpisz /help aby uzyskac liste komend +commands.generic.player.notFound=Nie znaleziono tego gracza +commands.generic.usage=Uzycie: {%0} + +commands.time.added=Dodano {%0} do czasu +commands.time.set=Ustawiono czas na {%0} +commands.time.query=Godzina to {%0} + +commands.me.usage=/me <akcja ...> + +commands.give.item.notFound=Nie ma przedmiotu o nazwie {%0} +commands.give.success=Dano {%0} * {%1} dla {%2} +commands.give.tagError=Parsowanie znacznika danych zawiodlo: {%0} + +commands.effect.usage=/effect <gracz> <efekt> [sekundy] [moc] [ukryjCzasteczki] LUB /effect <gracz> clear +commands.effect.notFound=Nie ma moba z ID {%0} +commands.effect.success=Dano {%0} (ID {%1}) * {%2} dla {%3} na {%4} sekund +commands.effect.success.removed=Zabrano {%0} od {%1} +commands.effect.success.removed.all=Zabrano wszystkie efekty graczowi {%0} +commands.effect.failure.notActive=Nie udalo sie zabrac {%0} od {%1} poniewaz nie ma tego efektu +commands.effect.failure.notActive.all=Nie udalo sie zabrac zadnego efektu {%0} jako ze nie ma zadnego + +commands.enchant.noItem=Cel nie trzyma zadnego przedmiotu +commands.enchant.notFound=Nie ma enchantu z ID {%0} +commands.enchant.success=Zakleto +commands.enchant.usage=/enchant <gracz> <ID enchantu> [poziom] + +commands.particle.success=Odtwarzanie efektu {%0} przez {%1} razy +commands.particle.notFound=Nieznana nazwa efektu {%0} + +commands.players.usage=/list +commands.players.list=Jest {%0}/{%1} graczy na serwerze: + +commands.kill.successful=Zabito {%0} +commands.kill.all.successful=Zabito wszystkich graczy +commands.kill.entities.successful=Zabito wszystkie byty + +commands.banlist.ips=Jest {%0} razem zbanowanych graczy na IP: +commands.banlist.players=Jest {%0} razem zbanowanych graczy: +commands.banlist.usage=/banlist [ips|players] + +commands.defaultgamemode.usage=/defaultgamemode <tryb> +commands.defaultgamemode.success=Domyslny tryb gry to teraz {%0} + +commands.op.success=Dodano OP graczowi {%0} +commands.op.usage=/op <gracz> + +commands.deop.success=Zabrano OP graczowi {%0} +commands.deop.usage=/deop <player> + +commands.say.usage=/say <wiadomosc ...> + +commands.seed.usage=/seed +commands.seed.success=Seed: {%0} + +commands.ban.success=Zbanowano gracza {%0} +commands.ban.usage=/ban <nazwa> [powod ...] + +commands.unban.success=Odbanowano gracza {%0} +commands.unban.usage=/pardon <nazwa> + +commands.banip.invalid=Wprowadziles niepoprawny adres IP albo gracz nie jest na serwerze +commands.banip.offline.invalid=Nie ma takiego IP w danych gracza lub IP jest nieprawidlowe +commands.banip.success=Zbanowano adres IP {%0} +commands.banip.success.players=Zbanowano adres IP {%0} nalezacy do {%1} +commands.banip.usage=/ban-ip <adres|nazwa> [powod ...] + +commands.unbanip.invalid=Wprowadziles niepoprawny adres IP +commands.unbanip.success=Odbanowano adres IP {%0} +commands.unbanip.usage=/pardon-ip <adres> + +commands.save.usage=/save [on|off|hold|resume] +commands.save.enabled=Wlaczono automatyczne zapisywanie swiata +commands.save.disabled=Wylaczono automatyczne zapisywania swiata +commands.save.start=Zapisywanie... +commands.save.success=Zapisano swiat! + +commands.stop.usage=/stop +commands.stop.start=Zatrzymuje serwer + +commands.kick.success=Gracz {%0} zostal wyrzucony z gry +commands.kick.success.reason=Wyrzucono {%0} z gry: '{%1}' +commands.kick.usage=/kick <gracz> [powod ...] + +commands.tp.success=Przeteleportowano {%0} do {%1} +commands.tp.success.coordinates=Przeteleportowano {%0} do {%1}, {%2}, {%3} +commands.tp.usage=/tp [cel gracz] <cel gracz> LUB /tp [cel gracz] <x> <y> <z> [<y-rot> <x-rot>] + +commands.whitelist.list=Jest {%0} (z {%1} widzianych) graczy na whiteliscie: +commands.whitelist.enabled=Wlaczono whiteliste +commands.whitelist.disabled=Wylaczono whiteliste +commands.whitelist.reloaded=Przeladowano whiteliste +commands.whitelist.add.success=Dodano {%0} do whitelisty +commands.whitelist.add.usage=/whitelist add <gracz> +commands.whitelist.remove.success=Usunieto {%0} z whitelisty +commands.whitelist.remove.usage=/whitelist remove <gracz> +commands.whitelist.usage=/whitelist <on|off|list|add|remove|reload> + +commands.gamemode.success.self=Ustawiono swoj tryb gry na {%0} +commands.gamemode.success.other=Ustawiono tryb gry gracza {%0} na {%1} +commands.gamemode.usage=/gamemode <tryb> [gracz] + +commands.help.header=--- Wyswietlona strona pomocy {%0} z {%1} (/help <strona>) --- +commands.help.usage=/help [strona|nazwa komendy] + +commands.message.usage=/tell <gracz> <prywatna wiadomosc ...> +commands.message.sameTarget=Nie mozesz wyslac prywatnej wiadomosci do siebie + +commands.difficulty.usage=/difficulty <nowy poziom trudnosci> +commands.difficulty.success=Ustawiono poziom trudnosci gry na {%0} + +commands.spawnpoint.usage=/spawnpoint [gracz] [<x> <y> <z>] +commands.spawnpoint.success=Ustawiono punkt spawnu gracza {%0} na pozycji ({%1}, {%2}, {%3}) + +commands.setworldspawn.usage=/setworldspawn [<x> <y> <z>] +commands.setworldspawn.success=Ustawiono punkt spawnu swiata na pozycji ({%0}, {%1}, {%2}) + +commands.weather.clear=Zmiana pogody na bezchmurna +commands.weather.rain=Zmiana pogody na deszczowa +commands.weather.thunder=Zmiana pogody na deszczowa lub burzowa +commands.weather.usage=/weather <clear|rain|thunder> [trwanie w sekundach] + +commands.xp.success=Dano {%0} EXPa dla gracza {%1} +commands.xp.success.levels=Dano {%0} poziomow dla gracz {%1} +commands.xp.success.levels.minus=Zabrano {%0} poziomow graczowi {%1} +commands.xp.usage=/xp <ilosc EXPa> [gracz] OR /xp <ilosc poziomow>L [gracz] + +# -------------------- Nukkit language files, only for console -------------------- + +nukkit.data.playerNotFound=Nie znaleziono danych gracza "{%0}", tworzenie nowego profilu +nukkit.data.playerCorrupted=Uszkodzone dane gracza "{%0}", tworzenie nowego profilu +nukkit.data.playerOld=Znaleziono stare dane gracza "{%0}", aktualizowanie profilu +nukkit.data.saveError=Nie udalo sie zapisac gracza "{%0}": {%1} + +nukkit.level.notFound=Poziom "{%0}" nie zostal znaleziony +nukkit.level.loadError=Nie udalo sie wczytac poziomu "{%0}": {%1} +nukkit.level.generationError=Nie udalo sie wygenerowac poziomu "{%0}": {%1} +nukkit.level.tickError=Nie udalo sie obsluzyc operacji tick w pozomie"{%0}": {%1} +nukkit.level.chunkUnloadError=Problem przy zwalnianiu chunka: {%0} +nukkit.level.backgroundGeneration=Tworzenie terenu dla poziomu "{%0}" jest generowane w tle +nukkit.level.defaultError=Zaden domyslny poziom nie zostal zaladowany +nukkit.level.preparing=Przygotowywanie poziomu "{%0}" +nukkit.level.unloading=Zwalnianie poziomu "{%0}" +nukkit.level.updating=Znaleziono informacje o poziomie dla "{%0}", zmiana formatu + +nukkit.server.start=Startowanie Serwera Minecraft: BE na wersji {%0} +nukkit.server.networkError=[Network] Zatrzymano interfejs {%0} z powodu {%1} +nukkit.server.networkStart=Otwieranie serwera na {%0}:{%1} +nukkit.server.info=Ten serwer dziala na {%0} w wersji {%1} "{%2}" (API {%3}) +nukkit.server.info.extended=Ten serwer dziala na {%0} {%1} 「{%2}」na implementacji API {%3} dla Minecraft: BE {%4} (wersja protokolu {%5}) +nukkit.server.license={%0} wydawany na licencji GPL +nukkit.server.tickOverload=Nie nadazam! Serwer jest przeciazony!? +nukkit.server.startFinished=Ukonczono w ({%0} sekund)! Aby uzyskac pomoc wpisz help lub ? +nukkit.server.defaultGameMode=Domyslny tryb gry: {%0} +nukkit.server.query.start=Uruchamianie statusu nasluchiwania GS4 +nukkit.server.query.info=Ustawiam query port na {%0} +nukkit.server.query.running=Query dziala na {%0}:{%1} +nukkit.server.rcon.emptyPasswordError=Wlaczanie RCON nie udalo sie: haslo jest puste +nukkit.server.rcon.startupError=Wlaczanie RCON nie udalo sie: {%0} +nukkit.server.rcon.running=RCON dziala na {%0}:{%1} + +nukkit.command.alias.illegal=Nie udalo sie zarejestrowac aliasu {%0} poniewaz zawiera niepoprawne znaki +nukkit.command.alias.notFound=Nie udalo sie zarejestrowac aliasu {%0} poniewaz zawiera komendy, ktore nie istnieja: {%1} +nukkit.command.exception=Nieoczekiwany wyjatek przy wykonywaniu komendy "{%0}" in {%1}: {%2} + +nukkit.command.plugins.description=Pobiera liste pluginow na serwerze +nukkit.command.plugins.success=Pluginy ({%0}): {%1} +nukkit.command.plugins.usage=/plugins + +nukkit.command.reload.description=Przeladowuje konfiguracje serwera i pluginy +nukkit.command.reload.usage=/reload +nukkit.command.reload.reloading=Przeladowywanie serwera... +nukkit.command.reload.reloaded=Przeladowano serwer + +nukkit.command.status.description=Odczytuje wydajnosc serwera. +nukkit.command.status.usage=/status + +nukkit.command.gc.description=Uruchamia procesy grabage colectora +nukkit.command.gc.usage=/gc + +nukkit.command.title.description=Wysyla title do wyznaczonego gracza, lub zmienia ustawienia title dla tego gracza +nukkit.command.title.usage=/title <gracz> <clear|reset> LUB /title <gracz> <title|subtitle|actionbar> <tekst title> LUB /title <gracz> <times> <fade in time> <stay time> <fade out time> +nukkit.command.title.clear=Wyczyszczenie ekranu {%0} zakonczone sukcesem +nukkit.command.title.reset=Reset ustawien animacji title dla {%0} zakonczony sukcesem +nukkit.command.title.title=Pokazanie title "{%0}" dla gracza {%1} zakonczone sukcesem +nukkit.command.title.subtitle=Ustawienie subtitle do "{%0}" dla nastepnego title gracza {%1} zakonczone sukcesem +nukkit.command.title.actionbar=Pokazanie tytulu actionbar'a "{%0}" graczowi {%1} zakonczone sukcesem +nukkit.command.title.times.success=Ustawienie czasow animacji title {%0}, {%1}, {%2} dla {%3} zakonczone sukcesem +nukkit.command.title.times.fail=Ilosc animacji title musi byc liczba + +nukkit.command.version.description=Wyswietla wersje serwera badz pluginu uzywanego przez serwer +nukkit.command.version.usage=/version [nazwa pluginu] +nukkit.command.version.noSuchPlugin=Nie ma pluginu o takiej nazwia. Uzyj /plugins aby uzyskac liste pluginow. + +nukkit.command.give.description=Daje wybranemu graczowi odpowiednia ilosc przedmiotu +nukkit.command.give.usage=/give <gracz> <przedmiot[:uszkodzenie]> [ilosc] [tagi ...] + +nukkit.command.kill.description=Powoduje popelnienie samobojstwa lub zabija innego gracza +nukkit.command.kill.usage=/kill [gracz] + +nukkit.command.particle.description=Dodaje czasteczki do swiata +nukkit.command.particle.usage=/particle <nazwa> <x> <y> <z> <xd> <yd> <zd> [ilosc] [dane] + +nukkit.command.time.description=Zmienia czas na kazdym swiecie +nukkit.command.time.usage=/time <set|add> <wartosc> LUB /time <start|stop|query> + +nukkit.command.gamerule.description=Ustawia lub wysyla zapytanie o wartosc reguly gry +nukkit.command.gamerule.usage=/gamerule <rule> [value] + +nukkit.command.ban.player.description=Banuje gracza na serwerze +nukkit.command.ban.ip.description=Banuje IP gracza na serwerze +nukkit.command.banlist.description=Wyswietla wszystkich zbanowanych graczy +nukkit.command.defaultgamemode.description=Ustawia domyslny tryb gry +nukkit.command.deop.description=Odbiera wybranemu graczowi OP na serwerze +nukkit.command.difficulty.description=ustawia poziom trudnosci gry +nukkit.command.enchant.description=Dodaje enchanty na przedmioty +nukkit.command.effect.description=Dodaje/Usuwa efekty na graczu +nukkit.command.gamemode.description=Zmienia tryb gry gracza +nukkit.command.help.description=Wyswietla menu pomocy +nukkit.command.kick.description=Wyrzuca gracza z serwera +nukkit.command.list.description=Wyswietla liste graczy na serwerze +nukkit.command.me.description=Wykonuje akcje na czacie +nukkit.command.op.description=Daje OP danemu graczowi +nukkit.command.unban.player.description=Odbanowuje gracza na serwerze +nukkit.command.unban.ip.description=Odbanowuje adres IP gracza na serwerze +nukkit.command.save.description=Zapisuje dane serwera na dysk +nukkit.command.saveoff.description=Wylacza automatyczny zapis serwera +nukkit.command.saveon.description=Wlacza automatyczny zapis serwera +nukkit.command.say.description=Wyswietla wiadomosc graczom +nukkit.command.seed.description=Pokazuje seed swiata +nukkit.command.setworldspawn.description=Ustawia punkt spawnu swiata. Jezeli nie zostana podane wspolrzedne to zostana ustawione jako pozycja gracza +nukkit.command.spawnpoint.description=Ustawia punkt spawnu gracza +nukkit.command.stop.description=Zatrzymuje serwer +nukkit.command.tp.description=Teleportuje podanego gracza (albo siebie) do innego gracza badz wsporzednych +nukkit.command.tell.description=Wysyla wiadomosc do okreslonego gracza +nukkit.command.weather.description=Ustawia pogode w obecnym swiecie +nukkit.command.xp.description=Daje podanemu graczu okreslona liczbe EXPa +nukkit.command.whitelist.description=Zarzadza whitelista + +nukkit.crash.create=Nieodwracalny blad wystapil na serwerze. Serwer zatrzymal sie! Zapisuje tresc bledu: +nukkit.crash.error=Nie udalo sie zapisac powodu bledu: {%0} +nukkit.crash.submit=Prosze wrzucic plik "{%0}" do archiwum bledow i wyslac link na stronie zglaszania bledow. Podaj najwiecej informacji ile mozesz. +nukkit.crash.archive=Plik z bledem zostal automatycznie wrzucony do archiwum bledow. Mozesz go zobaczyc tutaj {%0} lub uzyc ID #{%1}. + +nukkit.debug.enable=Wsparcie LevelDB zostalo wlaczone! + +nukkit.bugreport.create=Blad zostal znaleziony, tworzenie reportu +nukkit.bugreport.error=Nie mozna bylo stworzyc reportu o bledzie: {%0} +nukkit.bugreport.archive=Report o bledzie zostal stworzony: {%0} + +nukkit.player.invalidMove={%0} poruszyl sie nieprawidlowo! +nukkit.player.logIn={%0}[/{%1}:{%2}] zalogowal sie z id bytu {%3} na wspolrzednych ({%4}, {%5}, {%6}, {%7}) +nukkit.player.logOut={%0}[/{%1}:{%2}] rozlaczyl sie z powodu {%3} +nukkit.player.invalidEntity={%0} probowal zaatakowac niepoprawny byt + +nukkit.plugin.load=Wczytywanie {%0} +nukkit.plugin.enable=Wlaczanie {%0} +nukkit.plugin.disable=Wylaczanie {%0} +nukkit.plugin.restrictedName=Zabroniona nazwa +nukkit.plugin.incompatibleAPI=Niekompatybilna wersja API +nukkit.plugin.unknownDependency=Nieznana zaleznosc +nukkit.plugin.circularDependency=Wykryto zapetlona zaleznosc +nukkit.plugin.genericLoadError=Nie udalo sie wczytac pluginu "{%0}" +nukkit.plugin.spacesDiscouraged=Plugin "{%0}" uzywa spacji w nazwie! Jest to odradzane! +nukkit.plugin.loadError=Nie udalo sie wczytac pluginu "{%0}": {%1} +nukkit.plugin.duplicateError=Nie udalo sie wczytac pluginu "{%0}": plugin istnieje +nukkit.plugin.fileError=Nie udalo sie wczytac "{%0}" w folderze "{%1}": {%2} +nukkit.plugin.commandError=Nie udalo sie wczytac komendy {%0} dla pluginu {%1} +nukkit.plugin.aliasError=Nie udalo sie wczytac aliasu {%0} dla pluginu {%1} +nukkit.plugin.deprecatedEvent=Plugin "{%0}" zarejestrowal listener na "{%1}" w metodzie "{%2}", ale event jest przestarzaly +nukkit.plugin.eventError=Nie udalo sie wykonac eventu "{%0}" z "{%1}": {%2} na {%3} + +nukkit.resources.invalid-path=Sciezka do paczki zasobow "{%0}" istnieje i nie jest folderem +nukkit.resources.unknown-format=Nie mozna bylo zaladowac "{%0}", format nie zostal rozpoznany +nukkit.resources.fail=Nie mozna bylo zaladowac "{%0}": {%1} +nukkit.resources.success=Zaladowano {%0} paczek zasobow z sukcesem +nukkit.resources.zip.not-found=Plik "{%0}" nie zostal znaleziony +nukkit.resources.zip.no-manifest="manifest.json" nie zostal znaleziony +nukkit.resources.zip.invalid-manifest="manifest.json" jest nieprawidlowy, lub nieskonczony +nukkit.resources.plugin.loading=Loading resource pack from plugin {%0} diff --git a/src/main/resources/lang/pol/nukkit.yml b/src/main/resources/lang/pol/nukkit.yml new file mode 100644 index 00000000000..b5268a8de5f --- /dev/null +++ b/src/main/resources/lang/pol/nukkit.yml @@ -0,0 +1,99 @@ +# Zaawansowany plik konfiguracyjny Nukkit'a +# Niektore z tych ustawien sa bezpieczne, inne moga zniszczyc Twoj serwer jesli zostana zle zmienione +# Nowe ustawienia nie pojawia sie automatycznie w tym pliku podczas aktualizacji + +settings: + #Ustawienia jezyka + #Dostepne: eng, chs, cht, jpn, rus, spa, pol, bra, kor, ukr, deu, ltu, cze + language: "pol" + #Wyslac wiadomosci w jezyku serwera czy pozwolic urzadzeniu wybrac + force-language: false + shutdown-message: "Serwer wylaczony" + #Pozwol wyswietlic pluginy za pomoca Query + query-plugins: true + #Wyswietl wiadomosc w konsoli o wykorzystywaniu przez plugin starej funkcji API + deprecated-verbose: true + #Liczba AsyncTask worker'ow + #Jesli jest ustawione na auto, bedzie probowac wykryc ilosc rdzeni (i przynajmniej 4) + async-workers: auto + +network: + #Threshold for batching packets, in bytes. Only these packets will be compressed + #Set to 0 to compress everything, -1 to disable. + batch-threshold: 256 + #Compression level used of Zlib when sending batched packets. Higher = more CPU, less bandwidth usage + compression-level: 5 + #Enable network encryption + encryption: true + +debug: + #Jesli wartosc jest wieksza niz 1, bedzie pokazywac wiadomosci debug'u w konsoli + level: 1 + +level-settings: + #Podstawowy format, uzywany przez poziomy podczas tworzenia + default-format: leveldb + #Automatically change levels tick rate to maintain 20 ticks per second + auto-tick-rate: true + auto-tick-rate-limit: 20 + #Sets the base tick rate (1 = 20 ticks per second, 2 = 10 ticks per second, etc.) + base-tick-rate: 1 + #Tick all players each tick even when other settings disallow this. + always-tick-players: false + +chunk-sending: + #Ilosc chunk'ow wysylanych do gracza na tick + per-tick: 4 + #Amount of chunks that need to be sent before spawning the player + spawn-threshold: 56 + #Save a serialized copy of the chunk in memory for faster sending + #Useful in mostly-static worlds where lots of players join at the same time + cache-chunks: false + +chunk-ticking: + #Maksymalna ilosc chunk'ow przetwarzanych co tick + per-tick: 40 + #Radius of chunks around a player to tick + tick-radius: 3 + clear-tick-list: false + +chunk-generation: + #Max. amount of chunks in the waiting queue to be generated + queue-size: 8 + #Max. amount of chunks in the waiting queue to be populated + population-queue-size: 8 + +leveldb: + #Use native LevelDB implementation for better performance + use-native: false + #Set LevelDB memory cache size + cache-size-mb: 80 + +ticks-per: + autosave: 6000 + +player: + #Jesli ustawione na true, bedzie zapisywac gracza jako players/nickgracza.dat + #If false, nukkit won't save player data as "dat" files, in order that plugins can do something on it. + save-player-data: true + #The time between skin change action in seconds, set to 0 if you dont want the cooldown + skin-change-cooldown: 15 + +aliases: + #Alias'y dla komend + #Przyklad: + #alias: komenda LUB alias: [komenda1, komenda2, komenda3, itd.] + #pokazmiwersje: version + #zapisziwylacz: [save-all, stop] + +worlds: + #Worlds that the server will use. Options are specific to the chosen generator, and may result in broken generation or + #be ignored completely. + world: + #seed: 404 + generator: normal + options: + nether: + #seed: my_cool_nether_seed + generator: nether + options: diff --git a/src/main/resources/lang/rus/lang.ini b/src/main/resources/lang/rus/lang.ini new file mode 100644 index 00000000000..57d8717e47e --- /dev/null +++ b/src/main/resources/lang/rus/lang.ini @@ -0,0 +1,364 @@ +# Файл перевода совместим с Minecraft: Bedrock Edition на уровне идентификаторов +# +# Сообщению не обязательно находиться тут, чтобы отображаться правильно в клиенте +# Здесь обязательно должны быть сообщения, которые отображаются самим Nukkit'ом +# +# Если Вы нашли ошибку, приглашаем помочь с переводом: +# https://github.com/NukkitX/Languages +# Перевод осуществлён Pub4Game и fromgate (сообщество Nukkit.ru) + +language.name=Русский +language.selected=Выбран {%0} ({%1}) как основной язык + +multiplayer.player.joined={%0} присоединился к игре +multiplayer.player.left={%0} вышел из игры + +chat.type.text=<{%0}> {%1} +chat.type.emote=* {%0} {%1} +chat.type.announcement=[{%0}] {%1} +chat.type.admin=[{%0}: {%1}] +chat.type.achievement={%0} заработал(а) достижение {%1} + +disconnectionScreen.outdatedClient=Ваш клиент устарел! +disconnectionScreen.outdatedServer=Сервер устарел! +disconnectionScreen.serverFull=Сервер заполнен! +disconnectionScreen.noReason=Отключен от сервера +disconnectionScreen.invalidSkin=Неверный скин! +disconnectionScreen.invalidName=Недопустимое имя! +disconnectionScreen.resourcePack=Ошибка загрузки и применения набора ресурсов. + +death.fell.accident.generic={%0} упал(а) с высокого места +death.attack.inFire={%0} сгорел(а) заживо +death.attack.onFire={%0} сгорел(а) заживо +death.attack.lava={%0} решил(а) поплавать в лаве +death.attack.lava.magma={%0} узнал(а), что пол это лава +death.attack.inWall={%0} задохнулся(лась) в стене +death.attack.drown={%0} утонул(а) +death.attack.cactus={%0} закололся(лась) до смерти +death.attack.generic={%0} умер(ла) +death.attack.explosion={%0} взорвался(лась) +death.attack.explosion.player={%0} был(а) взорван(а), убийца: {%1} +death.attack.magic={%0} был(а) убит(а) магией +death.attack.wither={%0} высох(ла) +death.attack.mob={%0} был(а) убит(а), убийца: {%1} +death.attack.player={%0} был(а) убит(а), убийца: {%1} +death.attack.player.item={%0} был(а) убит(а), убийца: {%1}, {%2} +death.attack.arrow={%0} застрелен(а), убийца: {%1} +death.attack.arrow.item={%0} застрелен(а), убийца {%1}, {%2} +death.attack.fall={%0} ударился(лась) о землю слишком сильно +death.attack.outOfWorld={%0} выпал(а) из мира +death.attack.starve={%0} starved to death + +gameMode.survival=Выживание +gameMode.creative=Творческий режим +gameMode.adventure=Режим приключений +gameMode.spectator=Режим зрителя +gameMode.changed=Ваш игровой режим обновлён + +potion.moveSpeed=Скорость +potion.moveSlowdown=Замедление +potion.digSpeed=Спешка +potion.digSlowDown=Усталость +potion.damageBoost=Сила +potion.heal=Мгновенное лечение +potion.harm=Мгновенный урон +potion.jump=Мощный прыжок +potion.confusion=Тошнота +potion.regeneration=Регенерация +potion.resistance=Сопротивление урону +potion.fireResistance=Огнестойкость +potion.waterBreathing=Подводное дыхание +potion.invisibility=Невидимость +potion.blindness=Слепота +potion.nightVision=Ночное зрение +potion.hunger=Голод +potion.weakness=Слабость +potion.poison=Отравление +potion.wither=Иссушение +potion.healthBoost=Повышение здоровья +potion.absorption=Поглощение +potion.saturation=Насыщение + +commands.generic.exception=Произошла неизвестная ошибка при выполнении команды +commands.generic.permission=У Вас недостаточно прав для использования команды +commands.generic.ingame=Вы можете использовать эту команду только в игре +commands.generic.unknown=Неизвестная команда. Используйте /help для просмотра списка команд +commands.generic.player.notFound=Игрок не найден +commands.generic.usage=Используйте: {%0} + +commands.time.added=Добавлено {%0} к текущему времени +commands.time.set=Установлено время: {%0} +commands.time.query=Время: {%0} + +commands.me.usage=/me <действие ...> + +commands.give.item.notFound=Предмет с названием {%0} не найден +commands.give.success=Дано {%0} * {%1} игроку {%2} +commands.give.tagError=Сбой анализа тега данных: {%0} + +commands.effect.usage=/effect <игрок> <эффект> [кол-во секунд] [уровень] [убратьЧастицы] ИЛИ /effect <игрок> clear +commands.effect.notFound=Эффекта с ID {%0} не существует +commands.effect.success=Наложен эффект {%0} (ID {%1}) * {%2} на игрока {%3} на {%4} сек +commands.effect.success.removed=Эффект {%0} удален у {%1} +commands.effect.success.removed.all=Все эффекты были удалены у {%0} +commands.effect.failure.notActive=Невозможно убрать {%0} у {%1}, поскольку игрок не имеет данного эффекта +commands.effect.failure.notActive.all=Невозможно убрать эффекты у {%0}, потому что игрок не имеет никаких эффектов + +commands.enchant.noItem=У игрока нет такого предмета +commands.enchant.notFound=Зачарования с ID {%0} не существует +commands.enchant.success=Зачарование прошло успешно +commands.enchant.usage=/enchant <игрок> <ID зачарования> [уровень] + +commands.particle.success=Воспроизведение эффекта {%0} {%1} раз(-а) +commands.particle.notFound=Неизвестное название эффекта {%0} + +commands.players.usage=/list +commands.players.list=Сейчас {%0}/{%1} игроков на сервере: + +commands.kill.successful=Убит: {%0} +commands.kill.all.successful=Убил всех игроков +commands.kill.entities.successful=Убил всех сущностей + +commands.banlist.ips=Всего заблокирован(о) {%0} IP адрес(ов): +commands.banlist.players=Всего заблокирован(о) {%0} игрок(ов): +commands.banlist.usage=/banlist [ips|players] + +commands.defaultgamemode.usage=/defaultgamemode <режим игры> +commands.defaultgamemode.success=Режим игры по умолчанию в этом мире теперь {%0} + +commands.op.success={%0} теперь оператор +commands.op.usage=/op <игрок> + +commands.deop.success={%0} больше не оператор +commands.deop.usage=/deop <игрок> + +commands.say.usage=/say <сообщение ...> + +commands.seed.usage=/seed +commands.seed.success=Сид: {%0} + +commands.ban.success=Заблокирован игрок {%0} +commands.ban.usage=/ban <игрок> [причина ...] + +commands.unban.success=Разблокирован игрок {%0} +commands.unban.usage=/pardon <игрок> + +commands.banip.invalid=Введен неверный IP-адрес или данный игрок не в сети +commands.banip.offline.invalid=There is no IP address in player data or IP address is invalid +commands.banip.success=Заблокирован IP адрес {%0} +commands.banip.success.players=Заблокирован IP адрес {%0} принадлежащий {%1} +commands.banip.usage=/ban-ip <IP-адрес|игрок> [причина ...] + +commands.unbanip.invalid=Вы ввели неверный IP адрес +commands.unbanip.success=Разблокирован IP адрес {%0} +commands.unbanip.usage=/pardon-ip <IP-адрес> + +commands.save.usage=/save [on|off|hold|resume] +commands.save.enabled=Автосохранение включено +commands.save.disabled=Автосохранение выключено +commands.save.start=Сохранение... +commands.save.success=Мир успешно сохранён + +commands.stop.usage=/stop +commands.stop.start=Выключение сервера + +commands.kick.success={%0} кикнут(а) с сервера +commands.kick.success.reason={%0} кикнут(а) с сервера: '{%1}' +commands.kick.usage=/kick <игрок> [причина ...] + +commands.tp.success={%0} телепортирован(а) к {%1} +commands.tp.success.coordinates={%0} телепортирован(а) на {%1}, {%2}, {%3} +commands.tp.usage=/tp [целевой игрок] <назначенный игрок> или /tp [целевой игрок] <x> <y> <z> [<y-rot> <x-rot>] + +commands.whitelist.list=В вайтлисте {%0} игроков (из {%1} отображаемых): +commands.whitelist.enabled=Вайтлист включен +commands.whitelist.disabled=Вайтлист выключен +commands.whitelist.reloaded=Список игроков в whitelist был перезагружен +commands.whitelist.add.success={%0} добавлен(а) в вайтлист +commands.whitelist.add.usage=/whitelist add <игрок> +commands.whitelist.remove.success={%0} убран(а) из вайтлиста +commands.whitelist.remove.usage=/whitelist remove <игрок> +commands.whitelist.usage=/whitelist <on|off|list|add|remove|reload> + +commands.gamemode.success.self=Установлен режим игры {%0} для себя +commands.gamemode.success.other=Игровой режим игрока {%0} изменён на {%1} +commands.gamemode.usage=/gamemode <игровой режим> [игрок] + +commands.help.header=--- Отображается страница {%0} из {%1} (/help <страница>) --- +commands.help.usage=/help [страница|имя команды] + +commands.message.usage=/tell <игрок> <личное сообщение ...> +commands.message.sameTarget=Вы не можете отправить сообщение самому себе! + +commands.difficulty.usage=/difficulty <сложность игры> +commands.difficulty.success=Сложность игры установлена на {%0} + +commands.spawnpoint.usage=/spawnpoint [игрок] [<x> <y> <z>] +commands.spawnpoint.success=Точка респауна игрока установлена на {%0} ({%1}, {%2}, {%3}) + +commands.setworldspawn.usage=/setworldspawn [<x> <y> <z>] +commands.setworldspawn.success=Точка респауна в мире установлена на ({%0}, {%1}, {%2}) + +commands.weather.clear=Изменяет погоду на солнечную +commands.weather.rain=Изменяет погоду на дождливую +commands.weather.thunder=Изменяет погоду на штормовую +commands.weather.usage=/weather <clear|rain|thunder> [продолжительность в секундах] + +commands.xp.success=Выдано {%0} очков опыта игроку {%1} +commands.xp.success.levels=Выдано {%0} уровней игроку {%1} +commands.xp.success.levels.minus=Изъято {%0} уровней у игрока {%1} +commands.xp.usage=/xp <опыт> [игрок] ИЛИ /xp <уровень>L [игрок] + +# -------------------- Nukkit language files, only for console -------------------- + +nukkit.data.playerNotFound=Информация об игроке "{%0}" не найдена, создаётся новый профиль +nukkit.data.playerCorrupted=Повреждённые данные у игрока "{%0}", создание нового профиля +nukkit.data.playerOld=Обнаружен старый профиль игрока "{%0}", обновляем профиль +nukkit.data.saveError=Невозможно сохранить данные игрока "{%0}": {%1} + +nukkit.level.notFound=Мир "{%0}" не найден +nukkit.level.loadError=Невозможно загрузить мир "{%0}": {%1} +nukkit.level.generationError=Невозможно сгенерировать уровень "{%0}": {%1} +nukkit.level.tickError=Ошибка прорисовки мира "{%0}": {%1} +nukkit.level.chunkUnloadError=Ошибка при выгрузке чанка: {%0} +nukkit.level.backgroundGeneration=Генерируется территория спауна для мира "{%0}" +nukkit.level.defaultError=Мир по умолчанию не загружен +nukkit.level.preparing=Подготовка мира "{%0}" +nukkit.level.unloading=Выгрузка мира "{%0}" +nukkit.level.updating=Мир "{%0}" использует старый формат, конвертация + +nukkit.server.start=Запускается сервер Minecraft: BE версии {%0} +nukkit.server.networkError=[Сеть] Остановлен интерфейс {%0} из-за {%1} +nukkit.server.networkStart=Открытие сервера на {%0}:{%1} +nukkit.server.info=Этот сервер использует {%0}, версию {%1} "{%2}" (API {%3}) +nukkit.server.info.extended=Сервер использует {%0} {%1}「 {%2}」 , версия API {%3} для Minecraft: BE {%4} (версия протокола {%5}) +nukkit.server.license={%0} распространяется под лицензией GPL +nukkit.server.tickOverload=Сервер перегружен! +nukkit.server.startFinished=Загружено ({%0} секунд)! Для справки введите "help" или "?" +nukkit.server.defaultGameMode=Игровой режим по умолчанию: {%0} +nukkit.server.query.start=Запуск прослушивателя статуса GS4 +nukkit.server.query.info=Установлен порт query на {%0} +nukkit.server.query.running=Query запущен на {%0}:{%1} +nukkit.server.rcon.emptyPasswordError=Ошибка запуска RCON: пустой пароль +nukkit.server.rcon.startupError=Ошибка запуска RCON: {%0} +nukkit.server.rcon.running=RCON запущен на {%0}:{%1} + +nukkit.command.alias.illegal=Невозможно зарегистрировать альтернативу команды {%0}, поскольку она содержит недопустимые знаки +nukkit.command.alias.notFound=Невозможно зарегистрировать альтернативу команды {%0}, поскольку она содержит недопустимые команды: {%1} +nukkit.command.exception=Необработанное исключение при выполнении команды "{%0}" в {%1}: {%2} + +nukkit.command.plugins.description=Показывает список установленых плагинов на этом сервере. +nukkit.command.plugins.success=Плагины ({%0}): {%1} +nukkit.command.plugins.usage=/plugins + +nukkit.command.reload.description=Перезагружает плагины и настройки сервера. +nukkit.command.reload.usage=/reload +nukkit.command.reload.reloading=Перезагрузка сервера... +nukkit.command.reload.reloaded=Перезагрузка завершена. + +nukkit.command.status.description=Отображает производительность сервера. +nukkit.command.status.usage=/status + +nukkit.command.gc.description=Запускает процессы сборщика мусора. +nukkit.command.gc.usage=/gc + +nukkit.command.title.description=Показывает заголовок для определённого игрока или изменяет настройки показа заголовков для него +nukkit.command.title.usage=/title <игрок> <clear|reset> ИЛИ /title <игрок> <title|subtitle|actionbar> <текст заголовка> ИЛИ /title <игрок> <times> <время появления> <продолжительность> <время исчезания> +nukkit.command.title.clear=Экран игрока {%0} успешно очищен +nukkit.command.title.reset=Настройки анимации заголовка для игрока {%0} успешно сброшены +nukkit.command.title.title=Заголовок "{%0}" успешно показан игроку {%1} +nukkit.command.title.subtitle=Подзаголовок "{%0}" успешно установлен для следующей надписи игрока {%1} +nukkit.command.title.actionbar=Заголовок над тулбаром "{%0}" успешно показан игроку {%1} +nukkit.command.title.times.success=Время проигрывания анимаций заголовка успешно изменено на {%0}, {%1}, {%2} для игрока {%3} +nukkit.command.title.times.fail=Время проигрывания анимаций должно быть числом + +nukkit.command.version.description=Показывает версию сервера, включая все используемые плагины +nukkit.command.version.usage=/version [название плагина] +nukkit.command.version.noSuchPlugin=На сервере не установлен плагин с таким названием. Используйте /plugins, чтобы получить список используемых плагинов. + +nukkit.command.give.description=Даёт определённому игроку определённое количество предметов +nukkit.command.give.usage=/give <игрок> <предмет[:урон (мета)]> [кол-во] + +nukkit.command.kill.description=Совершает суицид или убивает других игроков +nukkit.command.kill.usage=/kill [игрок] + +nukkit.command.particle.description=Добавляет частицы в мир. +nukkit.command.particle.usage=/particle <игрок> <x> <y> <z> <xd> <yd> <zd> [значение] [данные] + +nukkit.command.time.description=Изменяет время в мире. +nukkit.command.time.usage=/time <set|add> <значение> ИЛИ /time <start|stop|query> + +nukkit.command.gamerule.description=Устанавливает или запрашивает правило игры +nukkit.command.gamerule.usage=/gamerule <rule> [value] + +nukkit.command.ban.player.description=Блокирует определённого игрока на сервере. +nukkit.command.ban.ip.description=Блокирует определённый IP адрес на сервере. +nukkit.command.banlist.description=Показывает список всех заблокированных игроков на сервере. +nukkit.command.defaultgamemode.description=Устанавливает режим игры по умолчанию. +nukkit.command.deop.description=Убирает статус оператора с определённого игрока. +nukkit.command.difficulty.description=Устанавливает сложность игры. +nukkit.command.enchant.description=Adds enchantments on items +nukkit.command.effect.description=Добавляет/Убирает эффекты у игроков. +nukkit.command.gamemode.description=Изменяет режим игры у игрока. +nukkit.command.help.description=Показывает меню помощи. +nukkit.command.kick.description=Кикает определённого игрока с сервера. +nukkit.command.list.description=Показывает список всех игроков на сервере. +nukkit.command.me.description=Выполняет указанное действие в чате. +nukkit.command.op.description=Даёт определённому игроку статус оператора. +nukkit.command.unban.player.description=Разблокирует игрока на сервере. +nukkit.command.unban.ip.description=Разблокирует определенный IP адрес на сервере. +nukkit.command.save.description=Сохраняет все файлы сервера. +nukkit.command.saveoff.description=Отключает автосохранение сервера. +nukkit.command.saveon.description=Включает автосохранение сервера. +nukkit.command.say.description=Транслирует сообщение в чат. +nukkit.command.seed.description=Показывает сид мира. +nukkit.command.setworldspawn.description=Устанавливает точку респауна мира. Если координаты не введены, будут использованы координаты игрока. +nukkit.command.spawnpoint.description=Устанавливает точку возрождения игрока. +nukkit.command.stop.description=Выключает сервер. +nukkit.command.tp.description=Телепортирует определённого игрока (или Вас) к другому игроку или на определенные координаты +nukkit.command.tell.description=Отправляет приватное сообщение указанному игроку. +nukkit.command.weather.description=Устанавливает определенную погоду в мире. +nukkit.command.xp.description=Выдает игроку указанное количество единиц опыта или уровень +nukkit.command.whitelist.description=Управляет списком игроков, которым можно заходить на сервер. + +nukkit.crash.create=Произошла фатальная ошибка и сервер вышел из строя. Создание аварийного дампа +nukkit.crash.error=Не удалось создать дамп: {%0} +nukkit.crash.submit=Пожалуйста, загрузите файл"{%0}" в Crash Archive и отправьте ссылку на страницу исправления ошибок. Дайте как можно больше информации. +nukkit.crash.archive=Дамп выхода из строя сервера был автоматически отправлен в Crash Archive. Вы можете его просмотреть тут: {%0}, или использовать ID #{%1}. + +nukkit.debug.enable=Поддержка LevelDB включена + +nukkit.bugreport.create=An error has been detected, creating a bug report. +nukkit.bugreport.error=Could not create bug report: {%0} +nukkit.bugreport.archive=A bug report has been created: {%0} + +nukkit.player.invalidMove={%0} некорректно передвинулся! +nukkit.player.logIn={%0}[/{%1}:{%2}] вошел с id сущности {%3} на ({%4}, {%5}, {%6}, {%7}) +nukkit.player.logOut={%0}[/{%1}:{%2}] отключился: {%3} +nukkit.player.invalidEntity={%0} попытался атаковать неправильную сущность + +nukkit.plugin.load=Загрузка {%0} +nukkit.plugin.enable=Включение {%0} +nukkit.plugin.disable=Выключение {%0} +nukkit.plugin.restrictedName=Ограниченное имя +nukkit.plugin.incompatibleAPI=Несовместимая версия API +nukkit.plugin.unknownDependency=Неизвестная зависимость +nukkit.plugin.circularDependency=Обнаружена круговая зависимость +nukkit.plugin.genericLoadError=Невозможно загрузить плагин "{%0}" +nukkit.plugin.spacesDiscouraged=Плагин "{%0}" использует пробелы в названии, это недопустимо +nukkit.plugin.loadError=Невозможно загрузить плагин "{%0}": {%1} +nukkit.plugin.duplicateError=Невозможно загрузить "{%0}": плагин уже существует +nukkit.plugin.fileError=Не удалось загрузить "{%0}" в папке "{%1}": {%2} +nukkit.plugin.commandError=Невозможно загрузить команду {%0} для плагина {%1} +nukkit.plugin.aliasError=Не удалось загрузить псевдоним {%0} для плагина {%1} +nukkit.plugin.deprecatedEvent=Плагин "{%0}" имеет зарегистрированный эвент "{%1}" по методу "{%2}", но событие считается устаревшим. +nukkit.plugin.eventError=Не мог пройти "{%0}" событий для "{%1}": {%2} на {%3} + +nukkit.resources.invalid-path=Путь "{%0}" существует и не является директорией +nukkit.resources.unknown-format=Невозможно загрузить "{%0}", т.к. формат не распознан +nukkit.resources.fail=Невозможно загрузить "{%0}": {%1} +nukkit.resources.success=Успешно загружено {%0} ресурс-паков +nukkit.resources.zip.not-found=Файл "{%0}" не найден +nukkit.resources.zip.no-manifest="manifest.json" не найден +nukkit.resources.zip.invalid-manifest="manifest.json" неправильный или неполный +nukkit.resources.plugin.loading=Loading resource pack from plugin {%0} diff --git a/src/main/resources/lang/rus/nukkit.yml b/src/main/resources/lang/rus/nukkit.yml new file mode 100644 index 00000000000..58fe745bf75 --- /dev/null +++ b/src/main/resources/lang/rus/nukkit.yml @@ -0,0 +1,104 @@ +# Расширенные настройки сервера Nukkit +# Некоторые из этих параметров безопасны, иные могут нарушить работу вашего сервера, если вы неправильно их измените +# Новые параметры и настройки не будут добавляться автоматически при обновлении этого файла +# +# Если Вы нашли ошибку, приглашаем помочь с переводом: +# https://github.com/Nukkit/Languages +# +# Перевод осуществлён Pub4Game и fromgate (сообщество Nukkit.ru) + +settings: + #Выбор языка. + #Доступные языки: eng, chs, cht, jpn, rus, spa, pol, bra, kor, ukr, deu, ltu, cze + language: "rus" + #true для отправки переведённых строк на сервер, или false - возложить перевод на устройство + force-language: false + shutdown-message: "Сервер выключен" + #Передавать список плагинов в ответ на запросы Query + query-plugins: true + #Показывать сообщение в консоли, когда плагин использует устаревшие методы API + deprecated-verbose: true + #Количество рабочих потоков AsyncTask + #При значении auto будет рассчитано исходя из числа ядер процессора (но не меньше 4) + async-workers: auto + +network: + #Предельное значение объема серии пакетов (в байтах), при достижении которого они будут сжаты. Сжиматься будут только эти пакеты. + #Укажите 0 - чтобы сжимать всё, -1 - чтобы отключить сжатие + batch-threshold: 256 + #Уровень сжатия используется Zlib при отправке сжатых пакетов + #Чем больше - тем больше нагрузка на процессор, но меньше нагрузка на сеть + compression-level: 5 + #Enable network encryption + encryption: true + +debug: + #При значении > 1 будет отображать дополнительную отладочную информацию в консоли + level: 1 + +level-settings: + #Формат мира, который будет использоваться (по умолчанию) при создании миров + default-format: leveldb + #Автоматически изменять уровень частоты тика, чтобы соответствовать 20 тиков в секунду + auto-tick-rate: true + auto-tick-rate-limit: 20 + #Базовая частота тика (1 = 20 тиков в секунду, 2 = 10 тиков в секунду и т.п.) + base-tick-rate: 1 + #Просчитывать игроков каждый тик, даже если другие настройки это запрещают + always-tick-players: false + +chunk-sending: + #Количество чанков отправляемое игроку за тик + per-tick: 4 + #Количество чанков, которое должно быть отправлено перед спавном игрока + spawn-threshold: 56 + #Кэшировать чанки в памяти, для обеспечения быстрой отправки + #Полезно в основном статических мирах, где много игроков присоединятся одновременно + cache-chunks: false + +chunk-ticking: + #Максимальное количестов чанков, обрабатываемых за один тик + per-tick: 40 + #Радиус (в чанках) вокруг игрока, в пределах которого будут обрабатываться чанки + tick-radius: 3 + clear-tick-list: false + +chunk-generation: + #Максимальное количество чанков в очереди ожидания генерации + queue-size: 8 + #Максимальное количество чанков в очереди ожидания "популяции" + population-queue-size: 8 + +leveldb: + #Use native LevelDB implementation for better performance + use-native: false + #Set LevelDB memory cache size + cache-size-mb: 80 + +ticks-per: + autosave: 6000 + +player: + #Если выбрано true,то данные игрока будут храниться в файле players/playername.dat + #Если выбрано false, Nukkit не будет хранить данные игрока в "dat" файлах, для того чтобы плагины с ними что-то делали. + save-player-data: true + #The time between skin change action in seconds, set to 0 if you dont want the cooldown + skin-change-cooldown: 15 + +aliases: + #Псевдонимы (алиасы) для команд + #Например: + #showtheversion: version + #savestop: [save-all, stop] + +worlds: + #Worlds that the server will use. Options are specific to the chosen generator, and may result in broken generation or + #be ignored completely. + world: + #seed: 404 + generator: normal + options: + nether: + #seed: my_cool_nether_seed + generator: nether + options: diff --git a/src/main/resources/lang/spa/lang.ini b/src/main/resources/lang/spa/lang.ini new file mode 100644 index 00000000000..22bf9d71428 --- /dev/null +++ b/src/main/resources/lang/spa/lang.ini @@ -0,0 +1,361 @@ +# Language file compatible with Minecraft: Bedrock Edition identifiers +# +# A message doesn't need to be there to be shown correctly on the client. +# Only messages shown in Nukkit itself need to be here +# Using the language property from PocketMine-MP + +language.name=Español +language.selected={%0} ({%1}) elegido como el idioma base + +multiplayer.player.joined={%0} se ha conectado +multiplayer.player.left={%0} dejó el juego + +chat.type.text=<{%0}> {%1} +chat.type.emote=* {%0} {%1} +chat.type.announcement=[{%0}] {%1} +chat.type.admin=[{%0}: {%1}] +chat.type.achievement={%0} acaba de ganar un logro {%1} + +disconnectionScreen.outdatedClient=Cliente desactualizado! +disconnectionScreen.outdatedServer=Servidor desactualizado! +disconnectionScreen.serverFull=El servidor está lleno! +disconnectionScreen.noReason=Desconectado del servidor +disconnectionScreen.invalidSkin=Skin inválido! +disconnectionScreen.invalidName=Nombre no válido! +disconnectionScreen.resourcePack=Encountered a problem while downloading or applying resource pack. + +death.fell.accident.generic={%0} cayó desde un lugar alto +death.attack.inFire={%0} ardió en llamas +death.attack.onFire={%0} ardió hasta la muerte +death.attack.lava={%0} intentó nadar en lava +death.attack.lava.magma={%0} discovered floor was lava +death.attack.inWall={%0} se asfixió en una pared +death.attack.drown={%0} se ahogó +death.attack.cactus={%0} fue pinchado hasta la muerte +death.attack.generic={%0} murió +death.attack.explosion={%0} explotó +death.attack.explosion.player={%0} fué explotado por {%1} +death.attack.magic={%0} fue matado por magia +death.attack.wither={%0} murió por el efecto de wither +death.attack.mob={%0} fué herido por {%1} +death.attack.player={%0} fué herido por {%1} +death.attack.player.item={%0} fué herido por {%1} usando {%2} +death.attack.arrow={%0} fué disparado por {%1} +death.attack.arrow.item={%0} fué disparado por {%1} usando {%2} +death.attack.fall={%0} chocó el suelo fuertemente +death.attack.outOfWorld={%0} se cayó fuera del mundo +death.attack.starve={%0} starved to death + +gameMode.survival=Modo Supervivencia +gameMode.creative=Modo Creativo +gameMode.adventure=Modo Aventura +gameMode.spectator=Modo Espectador +gameMode.changed=Tu modo de juego ha sido actualizado + +potion.moveSpeed=Velocidad +potion.moveSlowdown=Lentitud +potion.digSpeed=Prisa +potion.digSlowDown=Fatiga Minera +potion.damageBoost=Fuerza +potion.heal=Vida Instantánea +potion.harm=Daño Instantáneo +potion.jump=Impulso de salto +potion.confusion=Náuseas +potion.regeneration=Regeneración +potion.resistance=Resistencia +potion.fireResistance=Resistencia al fuego +potion.waterBreathing=Respiración Acuática +potion.invisibility=Invisibilidad +potion.blindness=Ceguera +potion.nightVision=Visión nocturna +potion.hunger=Hambre +potion.weakness=Debilidad +potion.poison=Veneno +potion.wither=Wither +potion.healthBoost=Impulso de Vida +potion.absorption=Absorción +potion.saturation=Saturación + +commands.generic.exception=Error desconocido al intentar ejecutar este comando +commands.generic.permission=No tienes permiso para usar este comando +commands.generic.ingame=You can only perform this command as a player +commands.generic.unknown=Desconocido comando. Intenta /help para obtener una lista de comandos +commands.generic.player.notFound=Ese jugador no se encuentra +commands.generic.usage=Uso: {%0} + +commands.time.added={%0} Agregados a el tiempo +commands.time.set=Cambiar tiempo a {%0} +commands.time.query=El Tiempo es {%0} + +commands.me.usage=/me <acción...> + +commands.give.item.notFound=No existe ítem con el nombre {%0} +commands.give.success=Dado {%0} * {%1} a {%2} +commands.give.tagError=Error en parseo de etiqueta de datos: {%0} + +commands.effect.usage=/efecto <player> <effect> [seconds] [amplifier] [hideParticles] o /efecto <player> quitar +commands.effect.notFound=No hay efecto con esa ID {%0} +commands.effect.success=Dando {%0} (ID {%1}) * {%2} a {%3} por {%4} segundos +commands.effect.success.removed=Quitando {%0} de {%1} +commands.effect.success.removed.all=Removiendo todos los efectos de {%0} +commands.effect.failure.notActive=No se puede quitar {%0} de {%1} ya que no tiene el efecto +commands.effect.failure.notActive.all=No se puede quitar ningun efecto de {%0} ya que no tiene ninguno + +commands.enchant.noItem=El objetivo no tiene un objecto en la mano +commands.enchant.notFound=No existe un encantamiento con ID {%0} +commands.enchant.success=El encantamiento fue aplicado correctamente +commands.enchant.usage=/enchant <jugador> <ID encantamiento> [nivel] + +commands.particle.success=Reproduciendo efecto {%0} por {%1} veces +commands.particle.notFound=Nombre de efecto desconocido {%0} + +commands.players.usage=/lista +commands.players.list=Hay {%0}/{%1} jugadores en linea: + +commands.kill.successful={%0} Murió +commands.kill.all.successful=Mató a todos los jugadores +commands.kill.entities.successful=Mató a todas las entidades + +commands.banlist.ips=Hay %d IPs Bloqueadas: +commands.banlist.players={%0} Jugadores Bloqueados: +commands.banlist.usage=/banlist [ip|Jugador] + +commands.defaultgamemode.usage=/defaultgamemode <modo> +commands.defaultgamemode.success=El modo de juego por defecto del mundo es ahora {%0} + +commands.op.success=Privilegio Op a {%0} +commands.op.usage=/op <jugador> + +commands.deop.success=Removido privilegio Op a {%0} +commands.deop.usage=/deop <jugador> + +commands.say.usage=/say <mensaje ...> + +commands.seed.usage=/seed +commands.seed.success=Semilla: {%0} + +commands.ban.success=Jugador {%0} castigado +commands.ban.usage=/ban <nombre> [razón ...] + +commands.unban.success=Levantado castigo de jugador {%0} +commands.unban.usage=/pardon <nombre> + +commands.banip.invalid=Has introducido un IP no válida o el Jugador no está en linea +commands.banip.offline.invalid=La ip introducida es inválida o está desconectada +commands.banip.success=Ip {%0} Bloqueada +commands.banip.success.players=Ip Bloqueada {%0} perteneciente a {%1} +commands.banip.usage=/ban-ip <address|name> [Razón ...] + +commands.unbanip.invalid=Has introducido una IP no válida +commands.unbanip.success=IP {%0} desbloqueada +commands.unbanip.usage=/pardon-ip <IP> + +commands.save.usage=/save [on|off|hold|resume] +commands.save.enabled=Auto-guardar mundo activado +commands.save.disabled=Auto-guardado de mundo desactivado +commands.save.start=Guardando... +commands.save.success=Mundo guardado + +commands.stop.usage=/stop +commands.stop.start=Deteniendo el servidor + +commands.kick.success={%0} echado del juego +commands.kick.success.reason=Echado {%0} del juego: "{%1}" +commands.kick.usage=/kick <player> [Razón ...] + +commands.tp.success=Teletransportado {%0} a {%1} +commands.tp.success.coordinates=Teletransportado {%0} a {%1}, {%2}, {%3} +commands.tp.usage=/tp [Jugador] <destination player> O /tp [Jugador] <x> <y> <z> [<y-rot> <x-rot>] + +commands.whitelist.list={%0} Jugadores (de {%1} ) en lista blanca: +commands.whitelist.enabled=Lista blanca encendidida +commands.whitelist.disabled=Lista blanca encendidida +commands.whitelist.reloaded=Lista Blanca Recargada +commands.whitelist.add.success=Añadido {%0} a la Lista Blanca +commands.whitelist.add.usage=/whitelist add <player> +commands.whitelist.remove.success={%0} Fué removido de la Lista Blanca +commands.whitelist.remove.usage=/whitelist remove <player> +commands.whitelist.usage=/whitelist <on|off|list|add|remove|reload> + +commands.gamemode.success.self={%0} Es ahora tu modo de juego +commands.gamemode.success.other={%0} Ha cambiado su modo de Juego a {%1} +commands.gamemode.usage=/gamemode <mode> [player] + +commands.help.header=---Mostrando ayuda, Pagina {%0} de {%1} (/help <page>) --- +commands.help.usage=/help [pagina|comando] + +commands.message.usage=/tell <player> <private message ...> +commands.message.sameTarget=No te envíes un mensaje privado a ti mismo! + +commands.difficulty.usage=/difficulty <new difficulty> +commands.difficulty.success=Cambiada la dificultad del juego a {%0} + +commands.spawnpoint.usage=/spawnpoint [player] [<x> <y> <z>] +commands.spawnpoint.success={%0} su Punto de aparición es ahora ({%1}, {%2}, {%3}) + +commands.setworldspawn.usage=/setworldspawn [<x> <y> <z>] +commands.setworldspawn.success=El punto de aparición en el mundo es ahora ({%0}, {%1}, {%2}) + +commands.weather.clear=Cambiando tiempo a soleado +commands.weather.rain=Cambiando tiempo a lluvia +commands.weather.thunder=Cambiando tiempo a lluvia con rayos +commands.weather.usage=/weather <clear|rain|thunder> [duración en segundos] + +commands.xp.success=Given {%0} experience to {%1} +commands.xp.success.levels=Given {%0} levels to {%1} +commands.xp.success.levels.minus=Taken {%0} levels from {%1} +commands.xp.usage=/xp <amount> [player] OR /xp <level>L [player] + +# -------------------- Archivos de lenguaje de Nukkit, solo para la consola -------------------- + +nukkit.data.playerNotFound=Datos del Jugador "{%0}" no encontrados, creando un nuevo Perfil +nukkit.data.playerCorrupted=Datos corruptos de "{%0}", creando nuevo Perfil +nukkit.data.playerOld=Datos antiguos de "{%0}" encontrados, actualizando Perfil +nukkit.data.saveError=Imposible guardar datos del Jugador "{%0}": {%1} + +nukkit.level.notFound=Nivel "{%0}" no encontrado +nukkit.level.loadError=No se puede cargar el nivel "{%0}": {%1} +nukkit.level.generationError=No se puede generar el nivel "{%0}": {%1} +nukkit.level.tickError=No se puede marcar el nivel "{%0}": {%1} +nukkit.level.chunkUnloadError=Error mientras se descargaba un chunk: {%0} +nukkit.level.backgroundGeneration=Terreno de aparicion para nivel "{%0}" está siendo generado en segundo plano +nukkit.level.defaultError=No ha sido cargado un nivel por defecto +nukkit.level.preparing=Preparando nivel "{%0}" +nukkit.level.unloading=Descargando nivel "{%0}" +nukkit.level.updating=Old level data found for "{%0}", converting format + +nukkit.server.start=Iniciando Minecraft BE: Versión del servidor {%0} +nukkit.server.networkError=[Network] Interfaz {%0} detenida debido a {%1} +nukkit.server.networkStart=Abriendo servidor en {%0}:{%1} +nukkit.server.info=Este servidor está corriendo {%0} versión {%1} "{%2}" (API {%3}) +nukkit.server.info.extended=Este servidor esta ejecutando {%0} {%1} {%2} implementando la API versión {%3} para Minecraft: BE {%4} (Protocolo versión {%5}) +nukkit.server.license={%0} es distribuido bajo la GPL License +nukkit.server.tickOverload=Imposible continuar! Está sobrecargado el servidor? +nukkit.server.startFinished=Listo ({%0}s)! Escribe "help" o "?" para recibir ayuda +nukkit.server.defaultGameMode=Modo de Juego por defecto: {%0} +nukkit.server.query.start=Iniciando GS4 status listener +nukkit.server.query.info=Configurando puerto query en {%0} +nukkit.server.query.running=Corriendo Query en {%0}:{%1} +nukkit.server.rcon.emptyPasswordError=Failed to start RCON: password is empty +nukkit.server.rcon.startupError=Failed to start RCON: {%0} +nukkit.server.rcon.running=RCON is running on {%0}:{%1} + +nukkit.command.alias.illegal=Imposible registrar alias {%0} contiene caracteres inválidos +nukkit.command.alias.notFound=Imposible registrar alias {%0} contiene comandos que no existen: {%1} +nukkit.command.exception=Excepcion incontrolada al ejecutar el comando "{%0}" en {%1}: {%2} + +nukkit.command.plugins.description=Obtén una lista de plugins ejecutandose en el servidor +nukkit.command.plugins.success=Plugins ({%0}): {%1} +nukkit.command.plugins.usage=/plugins + +nukkit.command.reload.description=Vuelve a cargar la configuración del servidor y sus plugins +nukkit.command.reload.usage=/reload +nukkit.command.reload.reloading=Reiniciando el servidor... +nukkit.command.reload.reloaded=Reinicio completo. + +nukkit.command.status.description=Mira el estado y rendimiento de el servidor. +nukkit.command.status.usage=/status + +nukkit.command.gc.description=Ejecuta tareas de recolección de basura +nukkit.command.gc.usage=/gc + +nukkit.command.title.description=Sends a title to the specified player or modifies title settings for that player +nukkit.command.title.usage=/title <player> <clear|reset> OR /title <player> <title|subtitle|actionbar> <title text> OR /title <player> <times> <fade in time> <stay time> <fade out time> +nukkit.command.title.clear=Successfully cleared {%0}'s screen +nukkit.command.title.reset=Successfully reset title animation settings for {%0} +nukkit.command.title.title=Successfully shown "{%0}" title to {%1} +nukkit.command.title.subtitle=Successfully set subtitle to "{%0}" for {%1}'s next title +nukkit.command.title.actionbar=Successfully shown "{%0}" actionbar title to {%1} +nukkit.command.title.times.success=Successfully set title animation times to {%0}, {%1}, {%2} for {%3} +nukkit.command.title.times.fail=Times of title animations must be numeric values + +nukkit.command.version.description=Obtén la version del servidor, incluyendo los plugins que utiliza +nukkit.command.version.usage=/version [Nombre del plugin] +nukkit.command.version.noSuchPlugin=Este servidor no contiene ningun plugin con ese nombre. Usa el comando /plugins para ver la lista de plugins de el servidor. + +nukkit.command.give.description=Obsequía, al jugador especificado, la cantidad de objetos deseada +nukkit.command.give.usage=/give <jugador> <objeto[:extra]> [cantidad] [etiquetas ...] + +nukkit.command.kill.description=Cometer un suicidio o matar a otros jugadores +nukkit.command.kill.usage=/kill [jugador] + +nukkit.command.particle.description=Añade particulas al mundo +nukkit.command.particle.usage=/particle <nombre> <x> <y> <z> <xd> <yd> <zd> [cantidad] [datos] + +nukkit.command.time.description=Cambia la hora en cada mundo +nukkit.command.time.usage="/time <set|add> <valor>" O "/time <start|stop|query>" + +nukkit.command.gamerule.description=Establece o consulta un valor de regla +nukkit.command.gamerule.usage=/gamerule <rule> [value] + +nukkit.command.ban.player.description=Previene que el jugador especificado utilice este servidor +nukkit.command.ban.ip.description=Previene que la dirección IP especificada utilice este servidor +nukkit.command.banlist.description=Muestra todos los jugadores betados de este servidor +nukkit.command.defaultgamemode.description=Especifíca el modo de juego por defecto +nukkit.command.deop.description=Retira el modo "operador" del jugador especificado +nukkit.command.difficulty.description=Definir dificultad de el juego +nukkit.command.enchant.description=Añade encantamientos a objetos +nukkit.command.effect.description=Añade o remueve efectos sobre los jugadores +nukkit.command.gamemode.description=Cambia el modo de juego del jugador +nukkit.command.help.description=Muestra el menú de ayuda +nukkit.command.kick.description=Remueve el jugador especificado del servidor +nukkit.command.list.description=Lista de todos los jugadores en línea +nukkit.command.me.description=Ejecuta una acción especifica en el chat +nukkit.command.op.description=Obsequía al jugador especificado la modalidad de "Operador" +nukkit.command.unban.player.description=Permite al jugador especificado utilizar este servidor +nukkit.command.unban.ip.description=Permite que la IP especificada utilice este servidor +nukkit.command.save.description=Guarda el servidor en el disco +nukkit.command.saveoff.description=Deshabilita el "Auto-Guardado" del servidor +nukkit.command.saveon.description=Habilita el "Auto-Guardado" del servidor +nukkit.command.say.description=Transmitir el mensaje como servidor +nukkit.command.seed.description=Muestra la semilla del mundo +nukkit.command.setworldspawn.description=Crea un punto de aparición. Si no hay coordenadas, se usan las del jugador. +nukkit.command.spawnpoint.description=Define un punto de aparicion de los jugadores +nukkit.command.stop.description=Detiene el servidor +nukkit.command.tp.description=Teletransporta a un jugador (O a ti mismo) a otro jugador o cordenadas +nukkit.command.tell.description=Enviar mensaje privado a un jugador +nukkit.command.weather.description=Establece el tiempo del mundo actual +nukkit.command.xp.description=Gives the specified player a certain amount of experience +nukkit.command.whitelist.description=Administra la lista de jugadores permitidos en el servidor + +nukkit.crash.create=Se ha producido un error irrecuperable y el servidor ha crasheado. Creando un reporte de error +nukkit.crash.error=No se pudo crear volcado de crasheo: {%0} +nukkit.crash.submit=Porfavor sube el "{%0}" archivo y envia el link a la pagina de informe de errores, da tanta informacion como te sea posible. +nukkit.crash.archive=El volcado de crasheo ha sido enviado automaticamente a el Archivo de Crasheo. Puedes verlo en {%0} o usando el ID #{%1}. + +nukkit.debug.enable=Soporte LevelDB activado + +nukkit.bugreport.create=An error has been detected, creating a bug report. +nukkit.bugreport.error=Could not create bug report: {%0} +nukkit.bugreport.archive=A bug report has been created: {%0} + +nukkit.player.invalidMove={%0} movido incorrectamente! +nukkit.player.logIn={%0}[/{%1}:{%2}] Conectado con el nombre {%3} en ({%4}, {%5}, {%6}, {%7}) +nukkit.player.logOut={%0}[/{%1}:{%2}] Desconectado por {%3} +nukkit.player.invalidEntity={%0} Intentó atacar una entidad invalida + +nukkit.plugin.load=Cargando {%0} +nukkit.plugin.enable=Activando {%0} +nukkit.plugin.disable=Deshabilitando {%0} +nukkit.plugin.restrictedName=Nombre Restringido +nukkit.plugin.incompatibleAPI=Versión API incompatible +nukkit.plugin.unknownDependency=Dependencia desconocida +nukkit.plugin.circularDependency=Dependencia circular detectada +nukkit.plugin.genericLoadError=No se puede cargar el complemento "{%0}" +nukkit.plugin.spacesDiscouraged=Complemento "{%0}" usa espacios en su nombre, esto no es recomendable +nukkit.plugin.loadError=No se puede cargar el complemento "{%0}": {%1} +nukkit.plugin.duplicateError=No se puede cargar el complemento "{%0}": ya existe +nukkit.plugin.fileError=No se puede cargar "{%0}" en la carpeta "{%1}": {%2} +nukkit.plugin.commandError=No se puede cargar el comando {%0} para el complemento {%1} +nukkit.plugin.aliasError=no se puede cargar el alias {%0} para el complemeto {%1} +nukkit.plugin.deprecatedEvent=Complemento "{%0}" ha registrado un oyente para "{%1}" en método "{%2}", pero el evento esta en des-uso. +nukkit.plugin.eventError=No se pudo pasar el evento "{%0}" a "{%1}": {%2} en {%3} + +nukkit.resources.invalid-path=Resource packs path "{%0}" exists and is not a directory +nukkit.resources.unknown-format=Could not load "{%0}" due to format not recognized +nukkit.resources.fail=Could not load "{%0}": {%1} +nukkit.resources.success=Successfully loaded {%0} resource packs +nukkit.resources.zip.not-found=File "{%0}" is not found +nukkit.resources.zip.no-manifest="manifest.json" is not found +nukkit.resources.zip.invalid-manifest="manifest.json" is invalid or incomplete +nukkit.resources.plugin.loading=Loading resource pack from plugin {%0} diff --git a/src/main/resources/lang/spa/nukkit.yml b/src/main/resources/lang/spa/nukkit.yml new file mode 100644 index 00000000000..9037352a85c --- /dev/null +++ b/src/main/resources/lang/spa/nukkit.yml @@ -0,0 +1,98 @@ +# Configuración avanzada para Nukkit +# Algunos de estos ajustes son seguros, otros pueden destruir tu servidor si son modificados incorrectamente +# Nuevos ajustes / valores predeterminados no aparecerán automáticamente en este archivo al actualizar . + +settings: + #Configuración de multi-lenguaje + #Disponibles: eng, chs, cht, jpn, rus, spa, pol, bra, kor, ukr, deu, ltu, cze + language: "spa" + #Ya sea para enviar todos los mensajes traducidos desde la consola o dejar que el dispositivo los interprete + force-language: false + shutdown-message: "Servidor cerrado" + #Permitir lista de plugins va Query + query-plugins: true + #Mostrar un mensaje en la consola cuando un plugin utiliza métodos de la API en desuso + deprecated-verbose: true + #Número de trabajadores AsyncTask + #Si se establece en auto = automático, tratará de detectar el número de núcleos ( al menos 4 ) + async-workers: auto + +network: + #Umbral para los paquetes a enviar , en bytes . Sólo estos paquetes se comprimirán + #Ajustar a 0 para comprimir todo, -1 para desactivar. + batch-threshold: 256 + #Nivel de compresion usada para el envió de paquetes. Alta = más CPU, menos banda ancha + compression-level: 5 + #Enable network encryption + encryption: true + +debug: + #Si es mayor que 1, mostrara mensajes de depuración en la consola + level: 1 + +level-settings: + #El formato por defecto que los niveles utilizarán cuando se creen + default-format: leveldb + #Cambian automáticamente los niveles de velocidad para mantener 20 ticks por segundo + auto-tick-rate: true + auto-tick-rate-limit: 20 + #Establece el número de ticks base ( 1 = 20 ticks por segundo , 2 = 10 ticks por segundo , etc. ) + base-tick-rate: 1 + #Ticks a todos los jugadores incluso cuando otros ajustes no permiten esto. + always-tick-players: false + +chunk-sending: + #Cantidad de paquetes que se envián al jugador por tick + per-tick: 4 + #Cantidad de paquetes que necesitan ser enviados antes de que aparezca el jugador + spawn-threshold: 56 + #Guardar una copia serializada del chunk en la memoria para acelerar el envío + #Útil en mundos mayormente estáticos donde muchos jugadores se unen al mismo tiempo + cache-chunks: false + +chunk-ticking: + #Máxima cantidad de paquetes procesados por tick + per-tick: 40 + #Radio de chunks alrededor de un jugador por tick + tick-radius: 3 + clear-tick-list: false + +chunk-generation: + #Máxima cantidad de chunks en espera de ser generados + queue-size: 8 + #Máxima cantidad de chunks en espera de ser ocupados + population-queue-size: 8 + +leveldb: + #Use native LevelDB implementation for better performance + use-native: false + #Set LevelDB memory cache size + cache-size-mb: 80 + +ticks-per: + autosave: 6000 + +player: + #If true, player data will be saved as players/playername.dat + #If false, nukkit won't save player data as "dat" files, in order that plugins can do something on it. + save-player-data: true + #The time between skin change action in seconds, set to 0 if you dont want the cooldown + skin-change-cooldown: 15 + +aliases: + #Alias de comandos + #Ejemplos: + #showtheversion: version + #savestop: [save-all, stop] + +worlds: + #Worlds that the server will use. Options are specific to the chosen generator, and may result in broken generation or + #be ignored completely. + world: + #seed: 404 + generator: normal + options: + nether: + #seed: my_cool_nether_seed + generator: nether + options: diff --git a/src/main/resources/lang/tur/lang.ini b/src/main/resources/lang/tur/lang.ini new file mode 100644 index 00000000000..dae0ec95068 --- /dev/null +++ b/src/main/resources/lang/tur/lang.ini @@ -0,0 +1,360 @@ +# Dil Paketi Minecraft ile uyumludur: Cep Paketi Sürümü +# +# Mesajın üyeye doğru şekilde görünmesine gerek yok. +# Sadece Nukkit'te görünen mesaj burada olmalı +# PocketMine-MP'deki dil özelliği kullanılmaktadır. + +language.name=Turkish +language.selected=Seçildi {%0} ({%1}) Taban dili + +multiplayer.player.joined={%0} oyuna katıldı +multiplayer.player.left={%0} oyunu terk etti + +chat.type.text=<{%0}> {%1} +chat.type.emote=* {%0} {%1} +chat.type.announcement=[{%0}] {%1} +chat.type.admin=[{%0}: {%1}] +chat.type.achievement={%0} başarımı kazandı {%1} + +disconnectionScreen.outdatedClient=Süresi Geçmiş Üyelik! +disconnectionScreen.outdatedServer=Süresi Dolmuş Server! +disconnectionScreen.serverFull=Server dolu! +disconnectionScreen.noReason=Server'a bağlanılamadı +disconnectionScreen.invalidSkin=Geçersiz skin! +disconnectionScreen.invalidName=Geçersiz isim! +disconnectionScreen.resourcePack=Kaynak paketi indirilirken ya da yüklenirken bir sorun oluştu. + +death.fell.accident.generic={%0} yüksek bir yerden düştü +death.attack.inFire={%0} Güme Gitti +death.attack.onFire={%0} Yanarak öldü +death.attack.lava={%0} Lav'da yüzmeye çalıştı +death.attack.lava.magma={%0} discovered floor was lava +death.attack.inWall={%0} Duvarda havasızlıktan öldü +death.attack.drown={%0} boğuldu +death.attack.cactus={%0} şişlenerek öldü +death.attack.generic={%0} öldü +death.attack.explosion={%0} havaya uçtu +death.attack.explosion.player={%0}, {%1} tarafından havaya uçuruldu. +death.attack.magic={%0} büyüyle öldürüldü +death.attack.wither={%0} buruştu +death.attack.mob={%0}, {%1} tarafından katledildi. +death.attack.player={%0} was slain by {%1} +death.attack.player.item={%0} was slain by {%1} using {%2} +death.attack.arrow={%0} was shot by {%1} +death.attack.arrow.item={%0} was shot by {%1} using {%2} +death.attack.fall={%0} hit the ground too hard +death.attack.outOfWorld={%0} fell out of the world +death.attack.starve={%0} starved to death + +gameMode.survival=Survival Mode +gameMode.creative=Creative Mode +gameMode.adventure=Adventure Mode +gameMode.spectator=Spectator Mode +gameMode.changed=Your game mode has been updated + +potion.moveSpeed=Speed +potion.moveSlowdown=Slowness +potion.digSpeed=Haste +potion.digSlowDown=Mining Fatigue +potion.damageBoost=Strength +potion.heal=Instant Health +potion.harm=Instant Damage +potion.jump=Jump Boost +potion.confusion=Nausea +potion.regeneration=Regeneration +potion.resistance=Resistance +potion.fireResistance=Fire Resistance +potion.waterBreathing=Water Breathing +potion.invisibility=Invisibility +potion.blindness=Blindness +potion.nightVision=Night Vision +potion.hunger=Hunger +potion.weakness=Weakness +potion.poison=Poison +potion.wither=Wither +potion.healthBoost=Health Boost +potion.absorption=Absorption +potion.saturation=Saturation + +commands.generic.exception=An unknown error occurred while attempting to perform this command +commands.generic.permission=You do not have permission to use this command +commands.generic.ingame=You can only perform this command as a player +commands.generic.unknown=Unknown command. Try /help for a list of commands +commands.generic.player.notFound=That player cannot be found +commands.generic.usage=Usage: {%0} + +commands.time.added=Added {%0} to the time +commands.time.set=Set the time to {%0} +commands.time.query=Time is {%0} + +commands.me.usage=/me <action ...> + +commands.give.item.notFound=There is no such item with name {%0} +commands.give.success=Given {%0} * {%1} to {%2} +commands.give.tagError=Data tag parsing failed: {%0} + +commands.effect.usage=/effect <player> <effect> [seconds] [amplifier] [hideParticles] OR /effect <player> clear +commands.effect.notFound=There is no such mob effect with ID {%0} +commands.effect.success=Given {%0} (ID {%1}) * {%2} to {%3} for {%4} seconds +commands.effect.success.removed=Took {%0} from {%1} +commands.effect.success.removed.all=Took all effects from {%0} +commands.effect.failure.notActive=Couldn't take {%0} from {%1} as they do not have the effect +commands.effect.failure.notActive.all=Couldn't take any effects from {%0} as they do not have any + +commands.enchant.noItem=The target doesn't hold an item +commands.enchant.notFound=There is no such enchantment with ID {%0} +commands.enchant.success=Enchanting succeeded +commands.enchant.usage=/enchant <player> <enchantment ID> [level] + +commands.particle.success=Playing effect {%0} for {%1} times +commands.particle.notFound=Unknown effect name {%0} + +commands.players.usage=/list +commands.players.list=There are {%0}/{%1} players online: + +commands.kill.successful=Killed {%0} +commands.kill.all.successful=Killed all players +commands.kill.entities.successful=Killed all entities + +commands.banlist.ips=There are {%0} total banned IP addresses: +commands.banlist.players=There are {%0} total banned players: +commands.banlist.usage=/banlist [ips|players] + +commands.defaultgamemode.usage=/defaultgamemode <mode> +commands.defaultgamemode.success=The world's default game mode is now {%0} + +commands.op.success=Opped {%0} +commands.op.usage=/op <player> + +commands.deop.success=De-opped {%0} +commands.deop.usage=/deop <player> + +commands.say.usage=/say <message ...> + +commands.seed.usage=/seed +commands.seed.success=Seed: {%0} + +commands.ban.success=Banned player {%0} +commands.ban.usage=/ban <name> [reason ...] + +commands.unban.success=Unbanned player {%0} +commands.unban.usage=/pardon <name> + +commands.banip.invalid=You have entered an invalid IP address or a player that is not online +commands.banip.offline.invalid=There is no IP address in player data or IP address is invalid +commands.banip.success=Banned IP address {%0} +commands.banip.success.players=Banned IP address {%0} belonging to {%1} +commands.banip.usage=/ban-ip <address|name> [reason ...] + +commands.unbanip.invalid=You have entered an invalid IP address +commands.unbanip.success=Unbanned IP address {%0} +commands.unbanip.usage=/pardon-ip <address> + +commands.save.usage=/save [on|off|hold|resume] +commands.save.enabled=Turned on world auto-saving +commands.save.disabled=Turned off world auto-saving +commands.save.start=Saving... +commands.save.success=Saved the world + +commands.stop.usage=/stop +commands.stop.start=Stopping the server + +commands.kick.success=Kicked {%0} from the game +commands.kick.success.reason=Kicked {%0} from the game: '{%1}' +commands.kick.usage=/kick <player> [reason ...] + +commands.tp.success=Teleported {%0} to {%1} +commands.tp.success.coordinates=Teleported {%0} to {%1}, {%2}, {%3} +commands.tp.usage=/tp [target player] <destination player> OR /tp [target player] <x> <y> <z> [<y-rot> <x-rot>] + +commands.whitelist.list=There are {%0} (out of {%1} seen) whitelisted players: +commands.whitelist.enabled=Turned on the whitelist +commands.whitelist.disabled=Turned off the whitelist +commands.whitelist.reloaded=Reloaded the whitelist +commands.whitelist.add.success=Added {%0} to the whitelist +commands.whitelist.add.usage=/whitelist add <player> +commands.whitelist.remove.success=Removed {%0} from the whitelist +commands.whitelist.remove.usage=/whitelist remove <player> +commands.whitelist.usage=/whitelist <on|off|list|add|remove|reload> + +commands.gamemode.success.self=Set own game mode to {%0} +commands.gamemode.success.other=Set {%0}'s game mode to {%1} +commands.gamemode.usage=/gamemode <mode> [player] + +commands.help.header=--- Showing help page {%0} of {%1} (/help <page>) --- +commands.help.usage=/help [page|command name] + +commands.message.usage=/tell <player> <private message ...> +commands.message.sameTarget=You can't send a private message to yourself! + +commands.difficulty.usage=/difficulty <new difficulty> +commands.difficulty.success=Set game difficulty to {%0} + +commands.spawnpoint.usage=/spawnpoint [player] [<x> <y> <z>] +commands.spawnpoint.success=Set {%0}'s spawn point to ({%1}, {%2}, {%3}) + +commands.setworldspawn.usage=/setworldspawn [<x> <y> <z>] +commands.setworldspawn.success=Set the world spawn point to ({%0}, {%1}, {%2}) + +commands.weather.clear=Changing to clear weather +commands.weather.rain=Changing to rainy weather +commands.weather.thunder=Changing to rain and thunder +commands.weather.usage=/weather <clear|rain|thunder> [duration in seconds] + +commands.xp.success=Given {%0} experience to {%1} +commands.xp.success.levels=Given {%0} levels to {%1} +commands.xp.success.levels.minus=Taken {%0} levels from {%1} +commands.xp.usage=/xp <amount> [player] OR /xp <level>L [player] + +# -------------------- Nukkit language files, only for console -------------------- + +nukkit.data.playerNotFound=Player data not found for "{%0}", creating new profile +nukkit.data.playerCorrupted=Corrupted data found for "{%0}", creating new profile +nukkit.data.playerOld=Old Player data found for "{%0}", upgrading profile +nukkit.data.saveError=Could not save player "{%0}": {%1} + +nukkit.level.notFound=Level "{%0}" not found +nukkit.level.loadError=Could not load level "{%0}": {%1} +nukkit.level.generationError=Could not generate level "{%0}": {%1} +nukkit.level.tickError=Could not tick level "{%0}": {%1} +nukkit.level.chunkUnloadError=Error while unloading a chunk: {%0} +nukkit.level.backgroundGeneration=Spawn terrain for level "{%0}" is being generated in the background +nukkit.level.defaultError=No default level has been loaded +nukkit.level.preparing=Preparing level "{%0}" +nukkit.level.unloading=Unloading level "{%0}" +nukkit.level.updating=Old level data found for "{%0}", converting format + +nukkit.server.start=Starting Minecraft: BE server version {%0} +nukkit.server.networkError=[Network] Stopped interface {%0} due to {%1} +nukkit.server.networkStart=Opening server on {%0}:{%1} +nukkit.server.info=This server is running {%0} version {%1} "{%2}" (API {%3}) +nukkit.server.info.extended=This server is running {%0} {%1} 「{%2}」 implementing API version {%3} for Minecraft: BE {%4} (protocol version {%5}) +nukkit.server.license={%0} is distributed under the GPL License +nukkit.server.tickOverload=Can't keep up! Is the server overloaded? +nukkit.server.startFinished=Done ({%0}s)! For help, type "help" or "?" +nukkit.server.defaultGameMode=Default game type: {%0} +nukkit.server.query.start=Starting GS4 status listener +nukkit.server.query.info=Setting query port to {%0} +nukkit.server.query.running=Query is running on {%0}:{%1} +nukkit.server.rcon.emptyPasswordError=Failed to start RCON: password is empty +nukkit.server.rcon.startupError=Failed to start RCON: {%0} +nukkit.server.rcon.running=RCON is running on {%0}:{%1} + +nukkit.command.alias.illegal=Could not register alias {%0} because it contains illegal characters +nukkit.command.alias.notFound=Could not register alias {%0} because it contains commands that do not exist: {%1} +nukkit.command.exception=Unhandled exception executing command "{%0}" in {%1}: {%2} + +nukkit.command.plugins.description=Gets a list of plugins running on the server +nukkit.command.plugins.success=Plugins ({%0}): {%1} +nukkit.command.plugins.usage=/plugins + +nukkit.command.reload.description=Reloads the server configuration and plugins +nukkit.command.reload.usage=/reload +nukkit.command.reload.reloading=Reloading server... +nukkit.command.reload.reloaded=Reload complete. + +nukkit.command.status.description=Reads back the server's performance. +nukkit.command.status.usage=/status + +nukkit.command.gc.description=Fires garbage collection tasks +nukkit.command.gc.usage=/gc + +nukkit.command.title.description=Sends a title to the specified player or modifies title settings for that player +nukkit.command.title.usage=/title <player> <clear|reset> OR /title <player> <title|subtitle|actionbar> <title text> OR /title <player> <times> <fade in time> <stay time> <fade out time> +nukkit.command.title.clear=Successfully cleared {%0}'s screen +nukkit.command.title.reset=Successfully reset title animation settings for {%0} +nukkit.command.title.title=Successfully shown "{%0}" title to {%1} +nukkit.command.title.subtitle=Successfully set subtitle to "{%0}" for {%1}'s next title +nukkit.command.title.actionbar=Successfully shown "{%0}" actionbar title to {%1} +nukkit.command.title.times.success=Successfully set title animation times to {%0}, {%1}, {%2} for {%3} +nukkit.command.title.times.fail=Times of title animations must be numeric values + +nukkit.command.version.description=Gets the version of this server including any plugins in use +nukkit.command.version.usage=/version [plugin name] +nukkit.command.version.noSuchPlugin=This server is not running any plugin by that name. Use /plugins to get a list of plugins. + +nukkit.command.give.description=Gives the specified player a certain amount of items +nukkit.command.give.usage=/give <player> <item[:damage]> [amount] [tags ...] + +nukkit.command.kill.description=Commit suicide or kill other players +nukkit.command.kill.usage=/kill [player] + +nukkit.command.particle.description=Adds particles to a world +nukkit.command.particle.usage=/particle <name> <x> <y> <z> <xd> <yd> <zd> [count] [data] + +nukkit.command.time.description=Changes the time on each world +nukkit.command.time.usage=/time <set|add> <value> OR /time <start|stop|query> + +nukkit.command.gamerule.description=Bir oyun kuralı değeri belirler veya sorgular +nukkit.command.gamerule.usage=/gamerule <rule> [value] + +nukkit.command.ban.player.description=Prevents the specified player from using this server +nukkit.command.ban.ip.description=Prevents the specified IP address from using this server +nukkit.command.banlist.description=View all players banned from this server +nukkit.command.defaultgamemode.description=Set the default gamemode +nukkit.command.deop.description=Takes the specified player's operator status +nukkit.command.difficulty.description=Sets the game difficulty +nukkit.command.enchant.description=Adds enchantments on items +nukkit.command.effect.description=Adds/Removes effects on players +nukkit.command.gamemode.description=Changes the player to a specific game mode +nukkit.command.help.description=Shows the help menu +nukkit.command.kick.description=Removes the specified player from the server +nukkit.command.list.description=Lists all online players +nukkit.command.me.description=Performs the specified action in chat +nukkit.command.op.description=Gives the specified player operator status +nukkit.command.unban.player.description=Allows the specified player to use this server +nukkit.command.unban.ip.description=Allows the specified IP address to use this server +nukkit.command.save.description=Saves the server to disk + +nukkit.command.say.description=Broadcasts the given message as the sender +nukkit.command.seed.description=Shows the world seed +nukkit.command.setworldspawn.description=Sets a worlds's spawn point. If no coordinates are specified, the player's coordinates will be used. +nukkit.command.spawnpoint.description=Sets a player's spawn point +nukkit.command.stop.description=Stops the server +nukkit.command.tp.description=Teleports the given player (or yourself) to another player or coordinates +nukkit.command.tell.description=Sends a private message to the given player +nukkit.command.weather.description=Sets the weather in current world +nukkit.command.xp.description=Gives the specified player a certain amount of experience +nukkit.command.whitelist.description=Manages the list of players allowed to use this server + +nukkit.crash.create=An unrecoverable error has occurred and the server has crashed. Creating a crash dump +nukkit.crash.error=Could not create crash dump: {%0} +nukkit.crash.submit=Please upload the "{%0}" file to the Crash Archive and submit the link to the Bug Reporting page. Give as much info as you can. +nukkit.crash.archive=The crash dump has been automatically submitted to the Crash Archive. You can view it on {%0} or use the ID #{%1}. + +nukkit.debug.enable=LevelDB support enabled + +nukkit.bugreport.create=An error has been detected, creating a bug report. +nukkit.bugreport.error=Could not create bug report: {%0} +nukkit.bugreport.archive=A bug report has been created: {%0} + +nukkit.player.invalidMove={%0} moved wrongly! +nukkit.player.logIn={%0}[/{%1}:{%2}] logged in with entity id {%3} at ({%4}, {%5}, {%6}, {%7}) +nukkit.player.logOut={%0}[/{%1}:{%2}] logged out due to {%3} +nukkit.player.invalidEntity={%0} tried to attack an invalid entity + +nukkit.plugin.load=Loading {%0} +nukkit.plugin.enable=Enabling {%0} +nukkit.plugin.disable=Disabling {%0} +nukkit.plugin.restrictedName=Restricted name +nukkit.plugin.incompatibleAPI=Incompatible API version +nukkit.plugin.unknownDependency=Unknown dependency +nukkit.plugin.circularDependency=Circular dependency detected +nukkit.plugin.genericLoadError=Could not load plugin "{%0}" +nukkit.plugin.spacesDiscouraged=Plugin "{%0}" uses spaces in its name, this is discouraged +nukkit.plugin.loadError=Could not load plugin "{%0}": {%1} +nukkit.plugin.duplicateError=Could not load plugin "{%0}": plugin exists +nukkit.plugin.fileError=Could not load "{%0}" in folder "{%1}": {%2} +nukkit.plugin.commandError=Could not load command {%0} for plugin {%1} +nukkit.plugin.aliasError=Could not load alias {%0} for plugin {%1} +nukkit.plugin.deprecatedEvent=Plugin "{%0}" has registered a listener for "{%1}" on method "{%2}", but the event is Deprecated. +nukkit.plugin.eventError=Could not pass event "{%0}" to "{%1}": {%2} on {%3} + +nukkit.resources.invalid-path=Resource packs path "{%0}" exists and is not a directory +nukkit.resources.unknown-format=Could not load "{%0}" due to format not recognized +nukkit.resources.fail=Could not load "{%0}": {%1} +nukkit.resources.success=Successfully loaded {%0} resource packs +nukkit.resources.zip.not-found=File "{%0}" is not found +nukkit.resources.zip.no-manifest="manifest.json" is not found +nukkit.resources.zip.invalid-manifest="manifest.json" is invalid or incomplete +nukkit.resources.plugin.loading=Loading resource pack from plugin {%0} diff --git a/src/main/resources/lang/tur/nukkit.yml b/src/main/resources/lang/tur/nukkit.yml new file mode 100644 index 00000000000..f6cd617b524 --- /dev/null +++ b/src/main/resources/lang/tur/nukkit.yml @@ -0,0 +1,101 @@ +# Advanced configuration file for Nukkit +# Some of these settings are safe, others can break your server if modified incorrectly +# New settings/defaults won't appear automatically on this file when upgrading + +settings: + #Multi-language setting + #Available: eng, chs, cht, jpn, rus, spa, pol, bra, kor, ukr, deu, ltu, idn, cze, tur, fin + language: "eng" + #Whether to send all strings translated to server locale or let the device handle them + force-language: false + shutdown-message: "Server closed" + #Allow listing plugins via Query + query-plugins: true + #Show a console message when a plugin uses deprecated API methods + deprecated-verbose: true + #Number of AsyncTask workers + #If set to auto, it'll try to detect the number of cores (and at least 4) + async-workers: auto + +network: + #Threshold for batching packets, in bytes. Only these packets will be compressed + #Set to 0 to compress everything, -1 to disable + batch-threshold: 256 + #Compression level used of Zlib when sending batched packets. Higher = more CPU, less bandwidth usage + compression-level: 5 + #Enable network encryption + encryption: true + +debug: + #If > 1, it will show debug messages in the console + level: 1 + +level-settings: + #The default format that levels will use when created + default-format: leveldb + #Automatically change levels tick rate to maintain 20 ticks per second + auto-tick-rate: true + auto-tick-rate-limit: 20 + #Sets the base tick rate (1 = 20 ticks per second, 2 = 10 ticks per second, etc.) + base-tick-rate: 1 + #Tick all players each tick even when other settings disallow this + always-tick-players: false + +chunk-sending: + #Amount of chunks sent to players per tick + per-tick: 4 + #Amount of chunks that need to be sent before spawning the player + spawn-threshold: 56 + #Save a serialized copy of the chunk in memory for faster sending + #Useful in mostly-static worlds where lots of players join at the same time + cache-chunks: false + +chunk-ticking: + #Max amount of chunks processed each tick + per-tick: 40 + #Radius of chunks around a player to tick + tick-radius: 3 + clear-tick-list: false + +chunk-generation: + #Max. amount of chunks in the waiting queue to be generated + queue-size: 8 + #Max. amount of chunks in the waiting queue to be populated + population-queue-size: 8 + +leveldb: + #Use native LevelDB implementation for better performance + use-native: false + #Set LevelDB memory cache size + cache-size-mb: 80 + +ticks-per: + #How often worlds and player data are saved when auto-save=on in server.properties + autosave: 6000 + +player: + #If true, player data will be saved as players/playername.dat + #If false, nukkit won't save player data as "dat" files, in order that plugins can do something on it. + save-player-data: true + #The time between skin change action in seconds, set to 0 if you dont want the cooldown + skin-change-cooldown: 15 + #Attacking entities resets sprinting, you can disable that here + attack-stop-sprint: true + +aliases: + #Aliases for commands + #Examples: + #showtheversion: version + #savestop: [save-all, stop] + +worlds: + #Worlds that the server will use. Options are specific to the chosen generator, and may result in broken generation or + #be ignored completely. + world: + #seed: 404 + generator: normal + #options: + nether: + #seed: my_cool_nether_seed + generator: nether + #options: diff --git a/src/main/resources/lang/ukr/lang.ini b/src/main/resources/lang/ukr/lang.ini new file mode 100644 index 00000000000..fdc98cdfc5f --- /dev/null +++ b/src/main/resources/lang/ukr/lang.ini @@ -0,0 +1,365 @@ +# Файл перекладу сумістний з Minecraft: Bedrock Edition на рівні ідентифікаторів +# +# Це повідомлення необов'язково повинно бути тут, щоб працювати у клієнті +# Тут тільки повідомлення з самого Nukkit +# +# Якщо ви знайшли помилку, то допоможіть виправити переклад. +# https://github.com/Nukkit/Languages +# +# Переклад @Charelene + +language.name=Українська +language.selected=Встановлено {%0} ({%1}) як основну мову + +multiplayer.player.joined={%0} приєднався +multiplayer.player.left={%0} покидає гру + +chat.type.text=<{%0}> {%1} +chat.type.emote=* {%0} {%1} +chat.type.announcement=[{%0}] {%1} +chat.type.admin=[{%0}: {%1}] +chat.type.achievement={%0} отримав досягнення {%1} + +disconnectionScreen.outdatedClient=Застарілий клієнт! +disconnectionScreen.outdatedServer=Застарілий сервер! +disconnectionScreen.serverFull=Сервер заповненний! +disconnectionScreen.noReason=Відключено від серверу +disconnectionScreen.invalidSkin=Некорректний скін! +disconnectionScreen.invalidName=Некорректне ім'я! +disconnectionScreen.resourcePack=Encountered a problem while downloading or applying resource pack. + +death.fell.accident.generic={%0} впав з високого місця +death.attack.inFire={%0} піджарився в вогні +death.attack.onFire={%0} зажарився насмерть +death.attack.lava={%0} вирішив поплавати в лаві +death.attack.lava.magma={%0} discovered floor was lava +death.attack.inWall={%0} задихнувся у стіні +death.attack.drown={%0} втопився +death.attack.cactus={%0} заколовся насмерть +death.attack.generic={%0} помер +death.attack.explosion={%0} підірвався +death.attack.explosion.player={%0} був підірваний {%1} +death.attack.magic={%0} помер від магії +death.attack.wither={%0} всох +death.attack.mob={%0} вбит {%1} +death.attack.player={%0} вбит {%1} +death.attack.player.item={%0} вбит {%1} використовуючи {%2} +death.attack.arrow={%0} застрілений {%1} +death.attack.arrow.item={%0} підстрілений {%1} використовуючи {%2} +death.attack.fall={%0} вдарився о землю дуже сильно +death.attack.outOfWorld={%0} випав з цього миру +death.attack.starve={%0} starved to death + +gameMode.survival=Режим Виживання +gameMode.creative=Режим Творчості +gameMode.adventure=Режим Пригод +gameMode.spectator=Режим Наглядача +gameMode.changed=Ваш режим гри було оновлено + +potion.moveSpeed=Швидкість +potion.moveSlowdown=Повільність +potion.digSpeed=Квапливість +potion.digSlowDown=Втома +potion.damageBoost=Сила +potion.heal=Миттєве Здоров'я +potion.harm=Миттєве Пошкодження +potion.jump=Потужний Стрибок +potion.confusion=Нудота +potion.regeneration=Відновлення +potion.resistance=Опір +potion.fireResistance=Опір Вогню +potion.waterBreathing=Підводне дихання +potion.invisibility=Невидимість +potion.blindness=Сліпота +potion.nightVision=Нічний Зор +potion.hunger=Голод +potion.weakness=Слабкість +potion.poison=Отруєння +potion.wither=Висушенність +potion.healthBoost=Підвищення Здоров'я +potion.absorption=Поглинання +potion.saturation=Насиченність + +commands.generic.exception=При виконанні команди сталася невідома помилка +commands.generic.permission=У вас нема прав для виконання цієї команди +commands.generic.ingame=Цю команду можна виконувати тільки у грі +commands.generic.unknown=Невідома команда. Спробуйте /help для списку команд +commands.generic.player.notFound=Цього гравця неможливо знайти +commands.generic.usage=Використання: {%0} + +commands.time.added=Додано {%0} до часу +commands.time.set=Час встановлено на {%0} +commands.time.query=Час: {%0} + +commands.me.usage=/me <дія ...> + +commands.give.item.notFound=Не існує предмету з ID {%0} +commands.give.success=Віддано {%0} * {%1} гравцю {%2} +commands.give.tagError=Сбій аналізу тега даних: {%0} + +commands.effect.usage=/effect <гравець> <ефект> [час] [рівень] [заховати частинки] АБО /effect <гравець> clear +commands.effect.notFound=Еффекта з ID {%0} не існує +commands.effect.success=Віддано {%0} (ID {%1}) * {%2} гравцю {%3} на {%4} секунди +commands.effect.success.removed=Ефект {%0} з {%1} видалено +commands.effect.success.removed.all=Видалено всі ефекти з {%0} +commands.effect.failure.notActive=Не вдалось видалити {%0} з гравця {%1} оскільки такого ефекта нема +commands.effect.failure.notActive.all=Не вдалось видалити всі ефекти з {%0} оскільки їх нема + +commands.enchant.noItem=Ціль не тримає жодного предмета +commands.enchant.notFound=Не існує зачарування з ID {%0} +commands.enchant.success=Зачарування успішне +commands.enchant.usage=/enchant <гравець> <ID зачарування> [рівень] + +commands.particle.success=Відтворено ефект {%0} {%1} раз(и) +commands.particle.notFound=Невідомий ефект {%0} + +commands.players.usage=/list +commands.players.list={%0}/{%1} гравців на сервері: + +commands.kill.successful=Вбито {%0} +commands.kill.all.successful=Killed all players +commands.kill.entities.successful=Killed all entities + +commands.banlist.ips={%0} всього заблокованих IP адрес: +commands.banlist.players={%0} всього заблокованих гравців: +commands.banlist.usage=/banlist [IP|гравці] + +commands.defaultgamemode.usage=/defaultgamemode <режим> +commands.defaultgamemode.success=На сервері встановлено {%0} + +commands.op.success={%0} тепер оператор +commands.op.usage=/op <гравець> + +commands.deop.success={%0} більше не оператор +commands.deop.usage=/deop <player> + +commands.say.usage=/say <повідомлення ...> + +commands.seed.usage=/seed +commands.seed.success=Зерно світу: {%0} + +commands.ban.success=Заблоковано гравця {%0} +commands.ban.usage=/ban <ім'я> [причина ...] + +commands.unban.success=Розблоковано гравця {%0} +commands.unban.usage=/pardon <ім'я> + +commands.banip.invalid=Ви ввели неправильну IP адресу або гравець оффлайн +commands.banip.offline.invalid=IP адреси в даних гравців не існує або адреса неправильна +commands.banip.success=Заблоковано IP адресу {%0} +commands.banip.success.players=Заблоковано IP адресу {%0} яка належить {%1} +commands.banip.usage=/ban-ip <address|name> [reason ...] + +commands.unbanip.invalid=Ви ввели неправильну IP адресу +commands.unbanip.success=Розбанено IP адресу {%0} +commands.unbanip.usage=/pardon-ip <address> + +commands.save.usage=/save [on|off|hold|resume] +commands.save.enabled=Автоматичне збереження ввімкнено +commands.save.disabled=Автоматичне збереження вимкнено +commands.save.start=Збереження... +commands.save.success=Світ збережено + +commands.stop.usage=/stop +commands.stop.start=Відключення серверу + +commands.kick.success=Викинуто {%0} з гри +commands.kick.success.reason=Викинуто {%0} з гри: '{%1}' +commands.kick.usage=/kick <гравець> [причина ...] + +commands.tp.success=Телепортовано {%0} до {%1} +commands.tp.success.coordinates=Телепортовано {%0} до координат {%1}, {%2}, {%3} +commands.tp.usage=/tp [цільовий гравець] <призначенний гравець> АБО /tp [цільовий гравець] <x> <y> <z> [<y-rot> <x-rot>] + +commands.whitelist.list={%0} (з {%1} зайшовших) гравців у білому списку: +commands.whitelist.enabled=Білий список ввімкнено +commands.whitelist.disabled=Білий список вимкнено +commands.whitelist.reloaded=Білий список перезавантажено +commands.whitelist.add.success=Додано {%0} до білого списку +commands.whitelist.add.usage=/whitelist add <гравець> +commands.whitelist.remove.success=Видалено {%0} з білого списку +commands.whitelist.remove.usage=/whitelist remove <гравець> +commands.whitelist.usage=/whitelist <on|off|list|add|remove|reload> + +commands.gamemode.success.self=Встановлено {%0} для себе +commands.gamemode.success.other={%0} було встановлено {%1} +commands.gamemode.usage=/gamemode <режим> [гравець] + +commands.help.header=--- Показано сторінку {%0} із {%1} (/help <сторінка>) --- +commands.help.usage=/help [сторінка|назва команди] + +commands.message.usage=/tell <гравець> <повідомлення ...> +commands.message.sameTarget=Знайди собі співбесідника вже! + +commands.difficulty.usage=/difficulty <складність> +commands.difficulty.success=Складність гри встановлено на {%0} + +commands.spawnpoint.usage=/spawnpoint [гравець] [<x> <y> <z>] +commands.spawnpoint.success={%0} тепер буде з'являтися на ({%1}, {%2}, {%3}) + +commands.setworldspawn.usage=/setworldspawn [<x> <y> <z>] +commands.setworldspawn.success=Точка відродження встановлена на ({%0}, {%1}, {%2}) + +commands.weather.clear=Змінено на сонячну погоду +commands.weather.rain=Змінено на дощову погоду +commands.weather.thunder=Змінено на дощ з грозою +commands.weather.usage=/weather <clear|rain|thunder> [тривалість] + +commands.xp.success=Видано {%0} досвіду гравцю {%1} +commands.xp.success.levels=Видано {%0} рівнів гравцю {%1} +commands.xp.success.levels.minus=Забрано {%0} рівнів з гравця {%1} +commands.xp.usage=/xp <кількість> [гравець] АБО /xp <рівень>L [гравець] + +# --------------------Файли мови Nukkit, тільки для консолі -------------------- + +nukkit.data.playerNotFound=Даних гравця не знайдено для "{%0}", створюємо новий профіль +nukkit.data.playerCorrupted=Дані гравця "{%0}" пошкоджено, створюємо новий профіль +nukkit.data.playerOld=Дані гравця "{%0}" застарілі, оновлюємо профіль +nukkit.data.saveError=Не вдалось зберігти гравця "{%0}": {%1} + +nukkit.level.notFound=Рівень "{%0}" не знайдено +nukkit.level.loadError=Не вдалось зберігти рівень "{%0}": {%1} +nukkit.level.generationError=Не вдалось згенерувати рівень "{%0}": {%1} +nukkit.level.tickError=Помилка промальовування рівня "{%0}": {%1} +nukkit.level.chunkUnloadError=Помилка при завантеженні чанку: {%0} +nukkit.level.backgroundGeneration=Spawn terrain for level "{%0}" is being generated in the background +nukkit.level.defaultError=Жоден рівень не було завантажено +nukkit.level.preparing=Готуємо рівень "{%0}" +nukkit.level.unloading=Вигрузка рівня "{%0}" +nukkit.level.updating=Old level data found for "{%0}", converting format + +nukkit.server.start=Запуск сервера Minecraft: BE версії {%0} +nukkit.server.networkError=[Мережа] Інтерфейс {%0} зупинено по причині {%1} +nukkit.server.networkStart=Відкриваємо сервер на {%0}:{%1} +nukkit.server.info=Цей сервер використовує {%0} версії {%1} "{%2}" (API {%3}) +nukkit.server.info.extended=This server is running {%0} {%1} 「{%2}」 implementing API version {%3} for Minecraft: BE {%4} (protocol version {%5}) +nukkit.server.license={%0} поширюється під ліцензією GPL +nukkit.server.tickOverload=Зараз рухне! Ти що, сервер перевантажив? +nukkit.server.startFinished=Готово ({%0}с)! Для допомоги, наберіть "help" або "?" +nukkit.server.defaultGameMode=Режим гри за замовчуванням: {%0} +nukkit.server.query.start=Запуск прослухувача статусу GS4 +nukkit.server.query.info=Встановлено порт query на {%0} +nukkit.server.query.running=Query запущено на {%0}:{%1} +nukkit.server.rcon.emptyPasswordError=Помилка при запуску RCON: пароль пустий +nukkit.server.rcon.startupError=Помилка при запуску RCON: {%0} +nukkit.server.rcon.running=RCON запущений на {%0}:{%1} + +nukkit.command.alias.illegal=Не вдалось зареєструвати альтернативу команди {%0} бо вона містить недопустимі символи +nukkit.command.alias.notFound=Не вдалось зареєструвати альтернативу команди {%0} оскільки вона містить команди, що не існують: {%1} +nukkit.command.exception=Необроблене виключення при виконанні команди "{%0}" у {%1}: {%2} + +nukkit.command.plugins.description=Отримує список плагінів, які встановлено на цей сервер +nukkit.command.plugins.success=Плагіни ({%0}): {%1} +nukkit.command.plugins.usage=/plugins + +nukkit.command.reload.description=Перезавантажує конфігурацію та плагіни сервера +nukkit.command.reload.usage=/reload +nukkit.command.reload.reloading=Перезавантаження сервера... +nukkit.command.reload.reloaded=Перезавантаження завершено. + +nukkit.command.status.description=Виводить інформацію стосовно продуктивності сервера. +nukkit.command.status.usage=/status + +nukkit.command.gc.description=Запускає процес збору сміття +nukkit.command.gc.usage=/gc + +nukkit.command.title.description=Sends a title to the specified player or modifies title settings for that player +nukkit.command.title.usage=/title <player> <clear|reset> OR /title <player> <title|subtitle|actionbar> <title text> OR /title <player> <times> <fade in time> <stay time> <fade out time> +nukkit.command.title.clear=Successfully cleared {%0}'s screen +nukkit.command.title.reset=Successfully reset title animation settings for {%0} +nukkit.command.title.title=Successfully shown "{%0}" title to {%1} +nukkit.command.title.subtitle=Successfully set subtitle to "{%0}" for {%1}'s next title +nukkit.command.title.actionbar=Successfully shown "{%0}" actionbar title to {%1} +nukkit.command.title.times.success=Successfully set title animation times to {%0}, {%1}, {%2} for {%3} +nukkit.command.title.times.fail=Times of title animations must be numeric values + +nukkit.command.version.description=Отримує версію цього серверу та використовані плагіни +nukkit.command.version.usage=/version [назва плагіну] +nukkit.command.version.noSuchPlugin=Цей сервер не використовує плагін з цією назвою. Використовуйте /plugins для списку плагінів. + +nukkit.command.give.description=Дає гравцю деяку кількість предметів +nukkit.command.give.usage=/give <гравець> <предмет[:пошкодження]> [кількість] [відмітки ...] + +nukkit.command.kill.description=Накласти на себе руки або вбити іншого гравця +nukkit.command.kill.usage=/kill [гравець] + +nukkit.command.particle.description=Додати частинки до миру +nukkit.command.particle.usage=/particle <назва> <x> <y> <z> <xd> <yd> <zd> [кількість] [дані] + +nukkit.command.time.description=Змінює час у кожному мирі +nukkit.command.time.usage=/time <set|add> <значення> АБО /time <start|stop|query> + +nukkit.command.gamerule.description=Визначає або запитує значення правила гри +nukkit.command.gamerule.usage=/gamerule <rule> [value] + +nukkit.command.ban.player.description=Забороняє вказанному гравцю користуватися сервером +nukkit.command.ban.ip.description=Забороняє вказанній IP адресі користуватися сервером +nukkit.command.banlist.description=Показує усіх заблокованих гравців на цьому сервері +nukkit.command.defaultgamemode.description=Встановлює режим гри за замовчуванням +nukkit.command.deop.description=Забирає у гравця статус оператора сервера +nukkit.command.difficulty.description=Встановлює складність гри +nukkit.command.enchant.description=Додає зачарування до предмета +nukkit.command.effect.description=Додає або вбирає ефекти з гравців +nukkit.command.gamemode.description=Змінює режим гри зазначенному гравцю +nukkit.command.help.description=Показує меню допомоги +nukkit.command.kick.description=Прибирає зазначенного гравця з серверу +nukkit.command.list.description=Показує список гравців на сервері +nukkit.command.me.description=Виконує зазначену дію у чаті +nukkit.command.op.description=Дає зазначенному гравцю оператора +nukkit.command.unban.player.description=Дозволяє зазначенному гравцю користуватися сервером +nukkit.command.unban.ip.description=Дозволяє зазначеній IP адресі користуватися сервером +nukkit.command.save.description=Зберігає усі дані на диск +nukkit.command.saveoff.description=Вимикає автозберігання серверу +nukkit.command.saveon.description=Вмикає автозберігання серверу +nukkit.command.say.description=Транслює повідомлення отримувачу +nukkit.command.seed.description=Показує зерно світу +nukkit.command.setworldspawn.description=Зазначує точку відродження. Якщо не задано координат, буде обрано координати гравця. +nukkit.command.spawnpoint.description=Задає точку відродження гравця +nukkit.command.stop.description=Вимикає сервер +nukkit.command.tp.description=Телепортує зазначеного гравця (або себе) до іншого або до координат +nukkit.command.tell.description=Відправляє повідомлення зазначенному гравцю +nukkit.command.weather.description=Встановлює погоду +nukkit.command.xp.description=Видає зазначену кількість досвіду гравцю +nukkit.command.whitelist.description=Дає змогу управляти білим списком цього серверу + +nukkit.crash.create=З'явилась невідновлювана помилка і сервер було аварійно зупинено. Створення аварійного дампу. +nukkit.crash.error=Помилка при створенні аварійного дампу: {%0} +nukkit.crash.submit=Будь ласка завантажте файл "{%0}" до багтрекеру. Надайте якомога більше інформації. +nukkit.crash.archive=Аварійний дамп було завантажено до Архіву автоматично. Ви можете переглянути його тут - {%0} або використати ID #{%1}. + +nukkit.debug.enable=Підтримка LevelDB ввімкнена + +nukkit.bugreport.create=An error has been detected, creating a bug report. +nukkit.bugreport.error=Could not create bug report: {%0} +nukkit.bugreport.archive=A bug report has been created: {%0} + +nukkit.player.invalidMove={%0} неправильно рухався! +nukkit.player.logIn={%0}[/{%1}:{%2}] увішов з id сутності {%3} на ({%4}, {%5}, {%6}, {%7}) +nukkit.player.logOut={%0}[/{%1}:{%2}] вийшов по причині {%3} +nukkit.player.invalidEntity={%0} намагався атакувати невірну сутність + +nukkit.plugin.load=Завантаження {%0} +nukkit.plugin.enable=Ввімкнення {%0} +nukkit.plugin.disable=Вимкнення {%0} +nukkit.plugin.restrictedName=Заборонене ім'я +nukkit.plugin.incompatibleAPI=Несумісна версія API +nukkit.plugin.unknownDependency=Невідома залежна +nukkit.plugin.circularDependency=Знайдена кругова залежність +nukkit.plugin.genericLoadError=Не вдалось завантажити плагін "{%0}" +nukkit.plugin.spacesDiscouraged=Плагін "{%0}" використовує пробіл в назві, так не роблять +nukkit.plugin.loadError=Не вдалось завантажити плагін "{%0}": {%1} +nukkit.plugin.duplicateError=Не вдалось завантажити плагін "{%0}": плагін існує +nukkit.plugin.fileError=Не вдалось завантажити "{%0}" у директорії "{%1}": {%2} +nukkit.plugin.commandError=Не вдалось завантажити команду {%0} for plugin {%1} +nukkit.plugin.aliasError=Не вдалось завантажити альтернативу команді {%0} для плагіну {%1} +nukkit.plugin.deprecatedEvent=Плагін "{%0}" має зареєстровану події "{%1}" у методі "{%2}", але подія застаріла +nukkit.plugin.eventError=Не зміг пройти "{%0}" подій для "{%1}": {%2} на {%3} + +nukkit.resources.invalid-path=Resource packs path "{%0}" exists and is not a directory +nukkit.resources.unknown-format=Could not load "{%0}" due to format not recognized +nukkit.resources.fail=Could not load "{%0}": {%1} +nukkit.resources.success=Successfully loaded {%0} resource packs +nukkit.resources.zip.not-found=File "{%0}" is not found +nukkit.resources.zip.no-manifest="manifest.json" is not found +nukkit.resources.zip.invalid-manifest="manifest.json" is invalid or incomplete +nukkit.resources.plugin.loading=Loading resource pack from plugin {%0} diff --git a/src/main/resources/lang/ukr/nukkit.yml b/src/main/resources/lang/ukr/nukkit.yml new file mode 100644 index 00000000000..572dc8c342f --- /dev/null +++ b/src/main/resources/lang/ukr/nukkit.yml @@ -0,0 +1,104 @@ +# Розширені налаштування серверу Nukkit +# Деякі з цих налаштувань безпечні, інші ж можуть зламати ваш сервер при некорректних змінах +# Нові налаштування або умовчання не з'являться автоматично у цьому файлі при оновленні +# +# Якщо ви знайшли помилку, то допоможіть виправити переклад. +# https://github.com/Nukkit/Languages +# +# Переклад @Charelene + +settings: + #Налаштування мови + #Доступні: eng, chs, cht, jpn, rus, spa, pol, bra, kor, ukr, deu, ltu, cze + language: "ukr" + #Вибір пристрою для обробки перекладу (true — сервер буде оброблювати переклад) + force-language: false + shutdown-message: "Сервер вимкнено" + #Дозволити передавати список плагінів через Query + query-plugins: true + #Показувати повідомлення у консолі, коли плагін використовує застарілі методи API + deprecated-verbose: true + #Кількість працюючих потоків AsyncTask + #Якщо auto, число буде розраховане з кількості ядер (як мінімум 4) + async-workers: auto + +network: + #Граничне значення обсягу серії пакетів (в байтах), при досягненні якого вони будуть стиснуті. Стискатися будуть тільки ці пакети. + #Встановіть 0, щоб стискати все; -1, щоб вимкнути стискання + batch-threshold: 256 + #Рівень стискання, який використовує Zlib при відправленні пакетів + #Чим більше значення - тим більше навантаження на процесор, але менше навантаження на мережу + compression-level: 5 + #Enable network encryption + encryption: true + +debug: + #Якщо > 1, у консолі будуть з'являтися повідомлення відладки + level: 1 + +level-settings: + #Формат, що рівні використовуватимуть при створенні + default-format: leveldb + #Автоматично змінювати рівень частоти тіка, щоб відповідати 20 тіків в секунду + auto-tick-rate: true + auto-tick-rate-limit: 20 + #Базова частота тіка (1 = 20 тіків/сек , 2 = 10 тіків/сек, і т.д.) + base-tick-rate: 1 + #Прораховувати гравців кожен тік, навіть якщо інші настройки це забороняють + always-tick-players: false + +chunk-sending: + #Кількість чанків, яка відправляється гравцеві за тік + per-tick: 4 + #Кількість чанків, які має бути відправлено перед відродженням гравця + spawn-threshold: 56 + #Кешувати чанки в пам'яті, для забезпечення швидкого відправлення + #Корисно в основному статичних світах, де багато гравців приєднуються одночасно + cache-chunks: false + +chunk-ticking: + #Максимальна можливість чанків, яка може оброблюватись за один тік + per-tick: 40 + #Радіус чанків навколо гравця, які будуть оброблюватись + tick-radius: 3 + clear-tick-list: false + +chunk-generation: + #Макс. кількість чанків у черзі завантаження для генерації + queue-size: 8 + #Макс. кількість чанків у черзі завантаження для населення + population-queue-size: 8 + +leveldb: + #Use native LevelDB implementation for better performance + use-native: false + #Set LevelDB memory cache size + cache-size-mb: 80 + +ticks-per: + autosave: 6000 + +player: + #If true, player data will be saved as players/playername.dat + #If false, nukkit won't save player data as "dat" files, in order that plugins can do something on it. + save-player-data: true + #The time between skin change action in seconds, set to 0 if you dont want the cooldown + skin-change-cooldown: 15 + +aliases: + #Альтернативи існуючим командам + #Наприклад: + #showtheversion: version + #savestop: [save-all, stop] + +worlds: + #Worlds that the server will use. Options are specific to the chosen generator, and may result in broken generation or + #be ignored completely. + world: + #seed: 404 + generator: normal + options: + nether: + #seed: my_cool_nether_seed + generator: nether + options: diff --git a/src/main/resources/legacy_item_ids.json b/src/main/resources/legacy_item_ids.json index 9f7c747c15d..d63c5815b61 100644 --- a/src/main/resources/legacy_item_ids.json +++ b/src/main/resources/legacy_item_ids.json @@ -1,1005 +1 @@ -{ - "minecraft:mangrove_double_slab": -499, - "minecraft:stripped_mangrove_wood": -498, - "minecraft:mangrove_wood": -497, - "minecraft:mangrove_trapdoor": -496, - "minecraft:mangrove_wall_sign": -495, - "minecraft:mangrove_standing_sign": -494, - "minecraft:item.mangrove_door": -493, - "minecraft:mangrove_fence_gate": -492, - "minecraft:mangrove_fence": -491, - "minecraft:mangrove_pressure_plate": -490, - "minecraft:mangrove_slab": -489, - "minecraft:mangrove_stairs": -488, - "minecraft:mangrove_button": -487, - "minecraft:mangrove_planks": -486, - "minecraft:stripped_mangrove_log": -485, - "minecraft:mangrove_log": -484, - "minecraft:muddy_mangrove_roots": -483, - "minecraft:mangrove_roots": -482, - "minecraft:mud_brick_wall": -481, - "minecraft:mud_brick_stairs": -480, - "minecraft:mud_brick_double_slab": -479, - "minecraft:mud_brick_slab": -478, - "minecraft:packed_mud": -477, - "minecraft:mud_bricks": -475, - "minecraft:mangrove_propagule": -474, - "minecraft:mud": -473, - "minecraft:mangrove_leaves": -472, - "minecraft:ochre_froglight": -471, - "minecraft:verdant_froglight": -470, - "minecraft:pearlescent_froglight": -469, - "minecraft:frog_spawn": -468, - "minecraft:reinforced_deepslate": -466, - "minecraft:client_request_placeholder_block": -465, - "minecraft:sculk_shrieker": -461, - "minecraft:sculk_catalyst": -460, - "minecraft:sculk_vein": -459, - "minecraft:sculk": -458, - "minecraft:infested_deepslate": -454, - "minecraft:raw_gold_block": -453, - "minecraft:raw_copper_block": -452, - "minecraft:raw_iron_block": -451, - "minecraft:waxed_oxidized_double_cut_copper_slab": -450, - "minecraft:waxed_oxidized_cut_copper_slab": -449, - "minecraft:waxed_oxidized_cut_copper_stairs": -448, - "minecraft:waxed_oxidized_cut_copper": -447, - "minecraft:waxed_oxidized_copper": -446, - "minecraft:black_candle_cake": -445, - "minecraft:red_candle_cake": -444, - "minecraft:green_candle_cake": -443, - "minecraft:brown_candle_cake": -442, - "minecraft:blue_candle_cake": -441, - "minecraft:purple_candle_cake": -440, - "minecraft:cyan_candle_cake": -439, - "minecraft:light_gray_candle_cake": -438, - "minecraft:gray_candle_cake": -437, - "minecraft:pink_candle_cake": -436, - "minecraft:lime_candle_cake": -435, - "minecraft:yellow_candle_cake": -434, - "minecraft:light_blue_candle_cake": -433, - "minecraft:magenta_candle_cake": -432, - "minecraft:orange_candle_cake": -431, - "minecraft:white_candle_cake": -430, - "minecraft:candle_cake": -429, - "minecraft:black_candle": -428, - "minecraft:red_candle": -427, - "minecraft:green_candle": -426, - "minecraft:brown_candle": -425, - "minecraft:blue_candle": -424, - "minecraft:purple_candle": -423, - "minecraft:cyan_candle": -422, - "minecraft:light_gray_candle": -421, - "minecraft:gray_candle": -420, - "minecraft:pink_candle": -419, - "minecraft:lime_candle": -418, - "minecraft:yellow_candle": -417, - "minecraft:light_blue_candle": -416, - "minecraft:magenta_candle": -415, - "minecraft:orange_candle": -414, - "minecraft:white_candle": -413, - "minecraft:candle": -412, - "minecraft:glow_lichen": -411, - "minecraft:cracked_deepslate_bricks": -410, - "minecraft:cracked_deepslate_tiles": -409, - "minecraft:deepslate_copper_ore": -408, - "minecraft:deepslate_emerald_ore": -407, - "minecraft:deepslate_coal_ore": -406, - "minecraft:deepslate_diamond_ore": -405, - "minecraft:lit_deepslate_redstone_ore": -404, - "minecraft:deepslate_redstone_ore": -403, - "minecraft:deepslate_gold_ore": -402, - "minecraft:deepslate_iron_ore": -401, - "minecraft:deepslate_lapis_ore": -400, - "minecraft:deepslate_brick_double_slab": -399, - "minecraft:deepslate_tile_double_slab": -398, - "minecraft:polished_deepslate_double_slab": -397, - "minecraft:cobbled_deepslate_double_slab": -396, - "minecraft:chiseled_deepslate": -395, - "minecraft:deepslate_brick_wall": -394, - "minecraft:deepslate_brick_stairs": -393, - "minecraft:deepslate_brick_slab": -392, - "minecraft:deepslate_bricks": -391, - "minecraft:deepslate_tile_wall": -390, - "minecraft:deepslate_tile_stairs": -389, - "minecraft:deepslate_tile_slab": -388, - "minecraft:deepslate_tiles": -387, - "minecraft:polished_deepslate_wall": -386, - "minecraft:polished_deepslate_stairs": -385, - "minecraft:polished_deepslate_slab": -384, - "minecraft:polished_deepslate": -383, - "minecraft:cobbled_deepslate_wall": -382, - "minecraft:cobbled_deepslate_stairs": -381, - "minecraft:cobbled_deepslate_slab": -380, - "minecraft:cobbled_deepslate": -379, - "minecraft:deepslate": -378, - "minecraft:smooth_basalt": -377, - "minecraft:cave_vines_head_with_berries": -376, - "minecraft:cave_vines_body_with_berries": -375, - "minecraft:waxed_weathered_double_cut_copper_slab": -374, - "minecraft:waxed_exposed_double_cut_copper_slab": -373, - "minecraft:waxed_double_cut_copper_slab": -372, - "minecraft:oxidized_double_cut_copper_slab": -371, - "minecraft:weathered_double_cut_copper_slab": -370, - "minecraft:exposed_double_cut_copper_slab": -369, - "minecraft:double_cut_copper_slab": -368, - "minecraft:waxed_weathered_cut_copper_slab": -367, - "minecraft:waxed_exposed_cut_copper_slab": -366, - "minecraft:waxed_cut_copper_slab": -365, - "minecraft:oxidized_cut_copper_slab": -364, - "minecraft:weathered_cut_copper_slab": -363, - "minecraft:exposed_cut_copper_slab": -362, - "minecraft:cut_copper_slab": -361, - "minecraft:waxed_weathered_cut_copper_stairs": -360, - "minecraft:waxed_exposed_cut_copper_stairs": -359, - "minecraft:waxed_cut_copper_stairs": -358, - "minecraft:oxidized_cut_copper_stairs": -357, - "minecraft:weathered_cut_copper_stairs": -356, - "minecraft:exposed_cut_copper_stairs": -355, - "minecraft:cut_copper_stairs": -354, - "minecraft:waxed_weathered_cut_copper": -353, - "minecraft:waxed_exposed_cut_copper": -352, - "minecraft:waxed_cut_copper": -351, - "minecraft:oxidized_cut_copper": -350, - "minecraft:weathered_cut_copper": -349, - "minecraft:exposed_cut_copper": -348, - "minecraft:cut_copper": -347, - "minecraft:waxed_weathered_copper": -346, - "minecraft:waxed_exposed_copper": -345, - "minecraft:waxed_copper": -344, - "minecraft:oxidized_copper": -343, - "minecraft:weathered_copper": -342, - "minecraft:exposed_copper": -341, - "minecraft:copper_block": -340, - "minecraft:item.glow_frame": -339, - "minecraft:flowering_azalea": -338, - "minecraft:azalea": -337, - "minecraft:small_dripleaf_block": -336, - "minecraft:moss_carpet": -335, - "minecraft:tinted_glass": -334, - "minecraft:tuff": -333, - "minecraft:small_amethyst_bud": -332, - "minecraft:medium_amethyst_bud": -331, - "minecraft:large_amethyst_bud": -330, - "minecraft:amethyst_cluster": -329, - "minecraft:budding_amethyst": -328, - "minecraft:amethyst_block": -327, - "minecraft:calcite": -326, - "minecraft:azalea_leaves_flowered": -325, - "minecraft:azalea_leaves": -324, - "minecraft:big_dripleaf": -323, - "minecraft:cave_vines": -322, - "minecraft:spore_blossom": -321, - "minecraft:moss_block": -320, - "minecraft:hanging_roots": -319, - "minecraft:dirt_with_roots": -318, - "minecraft:dripstone_block": -317, - "minecraft:lightning_rod": -312, - "minecraft:copper_ore": -311, - "minecraft:pointed_dripstone": -308, - "minecraft:sculk_sensor": -307, - "minecraft:powder_snow": -306, - "minecraft:unknown": -305, - "minecraft:quartz_bricks": -304, - "minecraft:cracked_nether_bricks": -303, - "minecraft:chiseled_nether_bricks": -302, - "minecraft:stripped_warped_hyphae": -301, - "minecraft:stripped_crimson_hyphae": -300, - "minecraft:crimson_hyphae": -299, - "minecraft:warped_hyphae": -298, - "minecraft:polished_blackstone_wall": -297, - "minecraft:polished_blackstone_button": -296, - "minecraft:polished_blackstone_pressure_plate": -295, - "minecraft:polished_blackstone_double_slab": -294, - "minecraft:polished_blackstone_slab": -293, - "minecraft:polished_blackstone_stairs": -292, - "minecraft:polished_blackstone": -291, - "minecraft:item.soul_campfire": -290, - "minecraft:crying_obsidian": -289, - "minecraft:nether_gold_ore": -288, - "minecraft:twisting_vines": -287, - "minecraft:item.chain": -286, - "minecraft:polished_blackstone_brick_double_slab": -285, - "minecraft:polished_blackstone_brick_slab": -284, - "minecraft:blackstone_double_slab": -283, - "minecraft:blackstone_slab": -282, - "minecraft:gilded_blackstone": -281, - "minecraft:cracked_polished_blackstone_bricks": -280, - "minecraft:chiseled_polished_blackstone": -279, - "minecraft:polished_blackstone_brick_wall": -278, - "minecraft:blackstone_wall": -277, - "minecraft:blackstone_stairs": -276, - "minecraft:polished_blackstone_brick_stairs": -275, - "minecraft:polished_blackstone_bricks": -274, - "minecraft:blackstone": -273, - "minecraft:respawn_anchor": -272, - "minecraft:ancient_debris": -271, - "minecraft:netherite_block": -270, - "minecraft:soul_lantern": -269, - "minecraft:soul_torch": -268, - "minecraft:warped_double_slab": -267, - "minecraft:crimson_double_slab": -266, - "minecraft:warped_slab": -265, - "minecraft:crimson_slab": -264, - "minecraft:warped_pressure_plate": -263, - "minecraft:crimson_pressure_plate": -262, - "minecraft:warped_button": -261, - "minecraft:crimson_button": -260, - "minecraft:warped_fence_gate": -259, - "minecraft:crimson_fence_gate": -258, - "minecraft:warped_fence": -257, - "minecraft:crimson_fence": -256, - "minecraft:warped_stairs": -255, - "minecraft:crimson_stairs": -254, - "minecraft:warped_wall_sign": -253, - "minecraft:crimson_wall_sign": -252, - "minecraft:warped_standing_sign": -251, - "minecraft:crimson_standing_sign": -250, - "minecraft:warped_trapdoor": -247, - "minecraft:crimson_trapdoor": -246, - "minecraft:item.warped_door": -245, - "minecraft:item.crimson_door": -244, - "minecraft:warped_planks": -243, - "minecraft:crimson_planks": -242, - "minecraft:stripped_warped_stem": -241, - "minecraft:stripped_crimson_stem": -240, - "minecraft:target": -239, - "minecraft:item.nether_sprouts": -238, - "minecraft:soul_fire": -237, - "minecraft:soul_soil": -236, - "minecraft:polished_basalt": -235, - "minecraft:basalt": -234, - "minecraft:warped_nylium": -233, - "minecraft:crimson_nylium": -232, - "minecraft:weeping_vines": -231, - "minecraft:shroomlight": -230, - "minecraft:warped_fungus": -229, - "minecraft:crimson_fungus": -228, - "minecraft:warped_wart_block": -227, - "minecraft:warped_stem": -226, - "minecraft:crimson_stem": -225, - "minecraft:warped_roots": -224, - "minecraft:crimson_roots": -223, - "minecraft:lodestone": -222, - "minecraft:honeycomb_block": -221, - "minecraft:honey_block": -220, - "minecraft:beehive": -219, - "minecraft:bee_nest": -218, - "minecraft:sticky_piston_arm_collision": -217, - "minecraft:wither_rose": -216, - "minecraft:light_block": -215, - "minecraft:lit_blast_furnace": -214, - "minecraft:composter": -213, - "minecraft:wood": -212, - "minecraft:jigsaw": -211, - "minecraft:lava_cauldron": -210, - "minecraft:item.campfire": -209, - "minecraft:lantern": -208, - "minecraft:sweet_berry_bush": -207, - "minecraft:bell": -206, - "minecraft:loom": -204, - "minecraft:barrel": -203, - "minecraft:smithing_table": -202, - "minecraft:fletching_table": -201, - "minecraft:cartography_table": -200, - "minecraft:lit_smoker": -199, - "minecraft:smoker": -198, - "minecraft:stonecutter_block": -197, - "minecraft:blast_furnace": -196, - "minecraft:grindstone": -195, - "minecraft:lectern": -194, - "minecraft:darkoak_wall_sign": -193, - "minecraft:darkoak_standing_sign": -192, - "minecraft:acacia_wall_sign": -191, - "minecraft:acacia_standing_sign": -190, - "minecraft:jungle_wall_sign": -189, - "minecraft:jungle_standing_sign": -188, - "minecraft:birch_wall_sign": -187, - "minecraft:birch_standing_sign": -186, - "minecraft:smooth_quartz_stairs": -185, - "minecraft:red_nether_brick_stairs": -184, - "minecraft:smooth_stone": -183, - "minecraft:spruce_wall_sign": -182, - "minecraft:spruce_standing_sign": -181, - "minecraft:normal_stone_stairs": -180, - "minecraft:mossy_cobblestone_stairs": -179, - "minecraft:end_brick_stairs": -178, - "minecraft:smooth_sandstone_stairs": -177, - "minecraft:smooth_red_sandstone_stairs": -176, - "minecraft:mossy_stone_brick_stairs": -175, - "minecraft:polished_andesite_stairs": -174, - "minecraft:polished_diorite_stairs": -173, - "minecraft:polished_granite_stairs": -172, - "minecraft:andesite_stairs": -171, - "minecraft:diorite_stairs": -170, - "minecraft:granite_stairs": -169, - "minecraft:double_stone_block_slab4": -168, - "minecraft:double_stone_block_slab3": -167, - "minecraft:stone_block_slab4": -166, - "minecraft:scaffolding": -165, - "minecraft:bamboo_sapling": -164, - "minecraft:bamboo": -163, - "minecraft:stone_block_slab3": -162, - "minecraft:barrier": -161, - "minecraft:bubble_column": -160, - "minecraft:turtle_egg": -159, - "minecraft:air": -158, - "minecraft:conduit": -157, - "minecraft:sea_pickle": -156, - "minecraft:carved_pumpkin": -155, - "minecraft:spruce_pressure_plate": -154, - "minecraft:jungle_pressure_plate": -153, - "minecraft:dark_oak_pressure_plate": -152, - "minecraft:birch_pressure_plate": -151, - "minecraft:acacia_pressure_plate": -150, - "minecraft:spruce_trapdoor": -149, - "minecraft:jungle_trapdoor": -148, - "minecraft:dark_oak_trapdoor": -147, - "minecraft:birch_trapdoor": -146, - "minecraft:acacia_trapdoor": -145, - "minecraft:spruce_button": -144, - "minecraft:jungle_button": -143, - "minecraft:dark_oak_button": -142, - "minecraft:birch_button": -141, - "minecraft:acacia_button": -140, - "minecraft:dried_kelp_block": -139, - "minecraft:item.kelp": -138, - "minecraft:coral_fan_hang3": -137, - "minecraft:coral_fan_hang2": -136, - "minecraft:coral_fan_hang": -135, - "minecraft:coral_fan_dead": -134, - "minecraft:coral_fan": -133, - "minecraft:coral_block": -132, - "minecraft:coral": -131, - "minecraft:seagrass": -130, - "minecraft:element_118": -129, - "minecraft:element_117": -128, - "minecraft:element_116": -127, - "minecraft:element_115": -126, - "minecraft:element_114": -125, - "minecraft:element_113": -124, - "minecraft:element_112": -123, - "minecraft:element_111": -122, - "minecraft:element_110": -121, - "minecraft:element_109": -120, - "minecraft:element_108": -119, - "minecraft:element_107": -118, - "minecraft:element_106": -117, - "minecraft:element_105": -116, - "minecraft:element_104": -115, - "minecraft:element_103": -114, - "minecraft:element_102": -113, - "minecraft:element_101": -112, - "minecraft:element_100": -111, - "minecraft:element_99": -110, - "minecraft:element_98": -109, - "minecraft:element_97": -108, - "minecraft:element_96": -107, - "minecraft:element_95": -106, - "minecraft:element_94": -105, - "minecraft:element_93": -104, - "minecraft:element_92": -103, - "minecraft:element_91": -102, - "minecraft:element_90": -101, - "minecraft:element_89": -100, - "minecraft:element_88": -99, - "minecraft:element_87": -98, - "minecraft:element_86": -97, - "minecraft:element_85": -96, - "minecraft:element_84": -95, - "minecraft:element_83": -94, - "minecraft:element_82": -93, - "minecraft:element_81": -92, - "minecraft:element_80": -91, - "minecraft:element_79": -90, - "minecraft:element_78": -89, - "minecraft:element_77": -88, - "minecraft:element_76": -87, - "minecraft:element_75": -86, - "minecraft:element_74": -85, - "minecraft:element_73": -84, - "minecraft:element_72": -83, - "minecraft:element_71": -82, - "minecraft:element_70": -81, - "minecraft:element_69": -80, - "minecraft:element_68": -79, - "minecraft:element_67": -78, - "minecraft:element_66": -77, - "minecraft:element_65": -76, - "minecraft:element_64": -75, - "minecraft:element_63": -74, - "minecraft:element_62": -73, - "minecraft:element_61": -72, - "minecraft:element_60": -71, - "minecraft:element_59": -70, - "minecraft:element_58": -69, - "minecraft:element_57": -68, - "minecraft:element_56": -67, - "minecraft:element_55": -66, - "minecraft:element_54": -65, - "minecraft:element_53": -64, - "minecraft:element_52": -63, - "minecraft:element_51": -62, - "minecraft:element_50": -61, - "minecraft:element_49": -60, - "minecraft:element_48": -59, - "minecraft:element_47": -58, - "minecraft:element_46": -57, - "minecraft:element_45": -56, - "minecraft:element_44": -55, - "minecraft:element_43": -54, - "minecraft:element_42": -53, - "minecraft:element_41": -52, - "minecraft:element_40": -51, - "minecraft:element_39": -50, - "minecraft:element_38": -49, - "minecraft:element_37": -48, - "minecraft:element_36": -47, - "minecraft:element_35": -46, - "minecraft:element_34": -45, - "minecraft:element_33": -44, - "minecraft:element_32": -43, - "minecraft:element_31": -42, - "minecraft:element_30": -41, - "minecraft:element_29": -40, - "minecraft:element_28": -39, - "minecraft:element_27": -38, - "minecraft:element_26": -37, - "minecraft:element_25": -36, - "minecraft:element_24": -35, - "minecraft:element_23": -34, - "minecraft:element_22": -33, - "minecraft:element_21": -32, - "minecraft:element_20": -31, - "minecraft:element_19": -30, - "minecraft:element_18": -29, - "minecraft:element_17": -28, - "minecraft:element_16": -27, - "minecraft:element_15": -26, - "minecraft:element_14": -25, - "minecraft:element_13": -24, - "minecraft:element_12": -23, - "minecraft:element_11": -22, - "minecraft:element_10": -21, - "minecraft:element_9": -20, - "minecraft:element_8": -19, - "minecraft:element_7": -18, - "minecraft:element_6": -17, - "minecraft:element_5": -16, - "minecraft:element_4": -15, - "minecraft:element_3": -14, - "minecraft:element_2": -13, - "minecraft:element_1": -12, - "minecraft:blue_ice": -11, - "minecraft:stripped_oak_log": -10, - "minecraft:stripped_dark_oak_log": -9, - "minecraft:stripped_acacia_log": -8, - "minecraft:stripped_jungle_log": -7, - "minecraft:stripped_birch_log": -6, - "minecraft:stripped_spruce_log": -5, - "minecraft:prismarine_bricks_stairs": -4, - "minecraft:dark_prismarine_stairs": -3, - "minecraft:prismarine_stairs": -2, - "minecraft:stone": 1, - "minecraft:grass": 2, - "minecraft:dirt": 3, - "minecraft:cobblestone": 4, - "minecraft:planks": 5, - "minecraft:sapling": 6, - "minecraft:bedrock": 7, - "minecraft:flowing_water": 8, - "minecraft:water": 9, - "minecraft:flowing_lava": 10, - "minecraft:lava": 11, - "minecraft:sand": 12, - "minecraft:gravel": 13, - "minecraft:gold_ore": 14, - "minecraft:iron_ore": 15, - "minecraft:coal_ore": 16, - "minecraft:log": 17, - "minecraft:leaves": 18, - "minecraft:sponge": 19, - "minecraft:glass": 20, - "minecraft:lapis_ore": 21, - "minecraft:lapis_block": 22, - "minecraft:dispenser": 23, - "minecraft:sandstone": 24, - "minecraft:noteblock": 25, - "minecraft:item.bed": 26, - "minecraft:golden_rail": 27, - "minecraft:detector_rail": 28, - "minecraft:sticky_piston": 29, - "minecraft:web": 30, - "minecraft:tallgrass": 31, - "minecraft:deadbush": 32, - "minecraft:piston": 33, - "minecraft:piston_arm_collision": 34, - "minecraft:wool": 35, - "minecraft:element_0": 36, - "minecraft:yellow_flower": 37, - "minecraft:red_flower": 38, - "minecraft:brown_mushroom": 39, - "minecraft:red_mushroom": 40, - "minecraft:gold_block": 41, - "minecraft:iron_block": 42, - "minecraft:double_stone_block_slab": 43, - "minecraft:stone_block_slab": 44, - "minecraft:brick_block": 45, - "minecraft:tnt": 46, - "minecraft:bookshelf": 47, - "minecraft:mossy_cobblestone": 48, - "minecraft:obsidian": 49, - "minecraft:torch": 50, - "minecraft:fire": 51, - "minecraft:mob_spawner": 52, - "minecraft:oak_stairs": 53, - "minecraft:chest": 54, - "minecraft:redstone_wire": 55, - "minecraft:diamond_ore": 56, - "minecraft:diamond_block": 57, - "minecraft:crafting_table": 58, - "minecraft:item.wheat": 59, - "minecraft:farmland": 60, - "minecraft:furnace": 61, - "minecraft:lit_furnace": 62, - "minecraft:standing_sign": 63, - "minecraft:item.wooden_door": 64, - "minecraft:ladder": 65, - "minecraft:rail": 66, - "minecraft:stone_stairs": 67, - "minecraft:wall_sign": 68, - "minecraft:lever": 69, - "minecraft:stone_pressure_plate": 70, - "minecraft:item.iron_door": 71, - "minecraft:wooden_pressure_plate": 72, - "minecraft:redstone_ore": 73, - "minecraft:lit_redstone_ore": 74, - "minecraft:unlit_redstone_torch": 75, - "minecraft:redstone_torch": 76, - "minecraft:stone_button": 77, - "minecraft:snow_layer": 78, - "minecraft:ice": 79, - "minecraft:snow": 80, - "minecraft:cactus": 81, - "minecraft:clay": 82, - "minecraft:item.reeds": 83, - "minecraft:jukebox": 84, - "minecraft:fence": 85, - "minecraft:pumpkin": 86, - "minecraft:netherrack": 87, - "minecraft:soul_sand": 88, - "minecraft:glowstone": 89, - "minecraft:portal": 90, - "minecraft:lit_pumpkin": 91, - "minecraft:item.cake": 92, - "minecraft:unpowered_repeater": 93, - "minecraft:powered_repeater": 94, - "minecraft:invisible_bedrock": 95, - "minecraft:trapdoor": 96, - "minecraft:monster_egg": 97, - "minecraft:stonebrick": 98, - "minecraft:brown_mushroom_block": 99, - "minecraft:red_mushroom_block": 100, - "minecraft:iron_bars": 101, - "minecraft:glass_pane": 102, - "minecraft:melon_block": 103, - "minecraft:pumpkin_stem": 104, - "minecraft:melon_stem": 105, - "minecraft:vine": 106, - "minecraft:fence_gate": 107, - "minecraft:brick_stairs": 108, - "minecraft:stone_brick_stairs": 109, - "minecraft:mycelium": 110, - "minecraft:waterlily": 111, - "minecraft:nether_brick": 112, - "minecraft:nether_brick_fence": 113, - "minecraft:nether_brick_stairs": 114, - "minecraft:item.nether_wart": 115, - "minecraft:enchanting_table": 116, - "minecraft:brewingstandblock": 117, - "minecraft:item.cauldron": 118, - "minecraft:end_portal": 119, - "minecraft:end_portal_frame": 120, - "minecraft:end_stone": 121, - "minecraft:dragon_egg": 122, - "minecraft:redstone_lamp": 123, - "minecraft:lit_redstone_lamp": 124, - "minecraft:dropper": 125, - "minecraft:activator_rail": 126, - "minecraft:cocoa": 127, - "minecraft:sandstone_stairs": 128, - "minecraft:emerald_ore": 129, - "minecraft:ender_chest": 130, - "minecraft:tripwire_hook": 131, - "minecraft:trip_wire": 132, - "minecraft:emerald_block": 133, - "minecraft:spruce_stairs": 134, - "minecraft:birch_stairs": 135, - "minecraft:jungle_stairs": 136, - "minecraft:command_block": 137, - "minecraft:beacon": 138, - "minecraft:cobblestone_wall": 139, - "minecraft:item.flower_pot": 140, - "minecraft:carrots": 141, - "minecraft:potatoes": 142, - "minecraft:wooden_button": 143, - "minecraft:item.skull": 144, - "minecraft:anvil": 145, - "minecraft:trapped_chest": 146, - "minecraft:light_weighted_pressure_plate": 147, - "minecraft:heavy_weighted_pressure_plate": 148, - "minecraft:unpowered_comparator": 149, - "minecraft:powered_comparator": 150, - "minecraft:daylight_detector": 151, - "minecraft:redstone_block": 152, - "minecraft:quartz_ore": 153, - "minecraft:item.hopper": 154, - "minecraft:quartz_block": 155, - "minecraft:quartz_stairs": 156, - "minecraft:double_wooden_slab": 157, - "minecraft:wooden_slab": 158, - "minecraft:stained_hardened_clay": 159, - "minecraft:stained_glass_pane": 160, - "minecraft:leaves2": 161, - "minecraft:log2": 162, - "minecraft:acacia_stairs": 163, - "minecraft:dark_oak_stairs": 164, - "minecraft:slime": 165, - "minecraft:glow_stick": 166, - "minecraft:iron_trapdoor": 167, - "minecraft:prismarine": 168, - "minecraft:sea_lantern": 169, - "minecraft:hay_block": 170, - "minecraft:carpet": 171, - "minecraft:hardened_clay": 172, - "minecraft:coal_block": 173, - "minecraft:packed_ice": 174, - "minecraft:double_plant": 175, - "minecraft:standing_banner": 176, - "minecraft:wall_banner": 177, - "minecraft:daylight_detector_inverted": 178, - "minecraft:red_sandstone": 179, - "minecraft:red_sandstone_stairs": 180, - "minecraft:double_stone_block_slab2": 181, - "minecraft:stone_block_slab2": 182, - "minecraft:spruce_fence_gate": 183, - "minecraft:birch_fence_gate": 184, - "minecraft:jungle_fence_gate": 185, - "minecraft:dark_oak_fence_gate": 186, - "minecraft:acacia_fence_gate": 187, - "minecraft:repeating_command_block": 188, - "minecraft:chain_command_block": 189, - "minecraft:hard_glass_pane": 190, - "minecraft:hard_stained_glass_pane": 191, - "minecraft:chemical_heat": 192, - "minecraft:item.spruce_door": 193, - "minecraft:item.birch_door": 194, - "minecraft:item.jungle_door": 195, - "minecraft:item.acacia_door": 196, - "minecraft:item.dark_oak_door": 197, - "minecraft:grass_path": 198, - "minecraft:item.frame": 199, - "minecraft:chorus_flower": 200, - "minecraft:purpur_block": 201, - "minecraft:colored_torch_rg": 202, - "minecraft:purpur_stairs": 203, - "minecraft:colored_torch_bp": 204, - "minecraft:undyed_shulker_box": 205, - "minecraft:end_bricks": 206, - "minecraft:frosted_ice": 207, - "minecraft:end_rod": 208, - "minecraft:end_gateway": 209, - "minecraft:allow": 210, - "minecraft:deny": 211, - "minecraft:border_block": 212, - "minecraft:magma": 213, - "minecraft:nether_wart_block": 214, - "minecraft:red_nether_brick": 215, - "minecraft:bone_block": 216, - "minecraft:structure_void": 217, - "minecraft:shulker_box": 218, - "minecraft:purple_glazed_terracotta": 219, - "minecraft:white_glazed_terracotta": 220, - "minecraft:orange_glazed_terracotta": 221, - "minecraft:magenta_glazed_terracotta": 222, - "minecraft:light_blue_glazed_terracotta": 223, - "minecraft:yellow_glazed_terracotta": 224, - "minecraft:lime_glazed_terracotta": 225, - "minecraft:pink_glazed_terracotta": 226, - "minecraft:gray_glazed_terracotta": 227, - "minecraft:silver_glazed_terracotta": 228, - "minecraft:cyan_glazed_terracotta": 229, - "minecraft:blue_glazed_terracotta": 231, - "minecraft:brown_glazed_terracotta": 232, - "minecraft:green_glazed_terracotta": 233, - "minecraft:red_glazed_terracotta": 234, - "minecraft:black_glazed_terracotta": 235, - "minecraft:concrete": 236, - "minecraft:concrete_powder": 237, - "minecraft:chemistry_table": 238, - "minecraft:underwater_torch": 239, - "minecraft:chorus_plant": 240, - "minecraft:stained_glass": 241, - "minecraft:item.camera": 242, - "minecraft:podzol": 243, - "minecraft:item.beetroot": 244, - "minecraft:stonecutter": 245, - "minecraft:glowingobsidian": 246, - "minecraft:netherreactor": 247, - "minecraft:info_update": 248, - "minecraft:info_update2": 249, - "minecraft:moving_block": 250, - "minecraft:observer": 251, - "minecraft:structure_block": 252, - "minecraft:hard_glass": 253, - "minecraft:hard_stained_glass": 254, - "minecraft:reserved6": 255, - "minecraft:iron_shovel": 256, - "minecraft:iron_pickaxe": 257, - "minecraft:iron_axe": 258, - "minecraft:flint_and_steel": 259, - "minecraft:apple": 260, - "minecraft:bow": 261, - "minecraft:arrow": 262, - "minecraft:coal": 263, - "minecraft:diamond": 264, - "minecraft:iron_ingot": 265, - "minecraft:gold_ingot": 266, - "minecraft:iron_sword": 267, - "minecraft:wooden_sword": 268, - "minecraft:wooden_shovel": 269, - "minecraft:wooden_pickaxe": 270, - "minecraft:wooden_axe": 271, - "minecraft:stone_sword": 272, - "minecraft:stone_shovel": 273, - "minecraft:stone_pickaxe": 274, - "minecraft:stone_axe": 275, - "minecraft:diamond_sword": 276, - "minecraft:diamond_shovel": 277, - "minecraft:diamond_pickaxe": 278, - "minecraft:diamond_axe": 279, - "minecraft:stick": 280, - "minecraft:bowl": 281, - "minecraft:mushroom_stew": 282, - "minecraft:golden_sword": 283, - "minecraft:golden_shovel": 284, - "minecraft:golden_pickaxe": 285, - "minecraft:golden_axe": 286, - "minecraft:string": 287, - "minecraft:feather": 288, - "minecraft:gunpowder": 289, - "minecraft:wooden_hoe": 290, - "minecraft:stone_hoe": 291, - "minecraft:iron_hoe": 292, - "minecraft:diamond_hoe": 293, - "minecraft:golden_hoe": 294, - "minecraft:wheat_seeds": 295, - "minecraft:wheat": 296, - "minecraft:bread": 297, - "minecraft:leather_helmet": 298, - "minecraft:leather_chestplate": 299, - "minecraft:leather_leggings": 300, - "minecraft:leather_boots": 301, - "minecraft:chainmail_helmet": 302, - "minecraft:chainmail_chestplate": 303, - "minecraft:chainmail_leggings": 304, - "minecraft:chainmail_boots": 305, - "minecraft:iron_helmet": 306, - "minecraft:iron_chestplate": 307, - "minecraft:iron_leggings": 308, - "minecraft:iron_boots": 309, - "minecraft:diamond_helmet": 310, - "minecraft:diamond_chestplate": 311, - "minecraft:diamond_leggings": 312, - "minecraft:diamond_boots": 313, - "minecraft:golden_helmet": 314, - "minecraft:golden_chestplate": 315, - "minecraft:golden_leggings": 316, - "minecraft:golden_boots": 317, - "minecraft:flint": 318, - "minecraft:porkchop": 319, - "minecraft:cooked_porkchop": 320, - "minecraft:painting": 321, - "minecraft:golden_apple": 322, - "minecraft:wooden_door": 324, - "minecraft:bucket": 325, - "minecraft:minecart": 328, - "minecraft:saddle": 329, - "minecraft:iron_door": 330, - "minecraft:redstone": 331, - "minecraft:snowball": 332, - "minecraft:boat": 333, - "minecraft:leather": 334, - "minecraft:kelp": 335, - "minecraft:brick": 336, - "minecraft:clay_ball": 337, - "minecraft:paper": 339, - "minecraft:book": 340, - "minecraft:slime_ball": 341, - "minecraft:chest_minecart": 342, - "minecraft:egg": 344, - "minecraft:compass": 345, - "minecraft:fishing_rod": 346, - "minecraft:clock": 347, - "minecraft:glowstone_dust": 348, - "minecraft:dye": 351, - "minecraft:bone": 352, - "minecraft:sugar": 353, - "minecraft:cake": 354, - "minecraft:bed": 355, - "minecraft:repeater": 356, - "minecraft:cookie": 357, - "minecraft:shears": 359, - "minecraft:pumpkin_seeds": 361, - "minecraft:melon_seeds": 362, - "minecraft:beef": 363, - "minecraft:cooked_beef": 364, - "minecraft:chicken": 365, - "minecraft:cooked_chicken": 366, - "minecraft:rotten_flesh": 367, - "minecraft:ender_pearl": 368, - "minecraft:blaze_rod": 369, - "minecraft:ghast_tear": 370, - "minecraft:gold_nugget": 371, - "minecraft:nether_wart": 372, - "minecraft:potion": 373, - "minecraft:glass_bottle": 374, - "minecraft:spider_eye": 375, - "minecraft:fermented_spider_eye": 376, - "minecraft:blaze_powder": 377, - "minecraft:magma_cream": 378, - "minecraft:brewing_stand": 379, - "minecraft:cauldron": 380, - "minecraft:ender_eye": 381, - "minecraft:spawn_egg": 383, - "minecraft:experience_bottle": 384, - "minecraft:writable_book": 386, - "minecraft:written_book": 387, - "minecraft:emerald": 388, - "minecraft:frame": 389, - "minecraft:flower_pot": 390, - "minecraft:carrot": 391, - "minecraft:potato": 392, - "minecraft:baked_potato": 393, - "minecraft:poisonous_potato": 394, - "minecraft:golden_carrot": 396, - "minecraft:skull": 397, - "minecraft:pumpkin_pie": 400, - "minecraft:enchanted_book": 403, - "minecraft:comparator": 404, - "minecraft:netherbrick": 405, - "minecraft:quartz": 406, - "minecraft:tnt_minecart": 407, - "minecraft:hopper_minecart": 408, - "minecraft:prismarine_shard": 409, - "minecraft:hopper": 410, - "minecraft:rabbit": 411, - "minecraft:cooked_rabbit": 412, - "minecraft:rabbit_stew": 413, - "minecraft:rabbit_foot": 414, - "minecraft:rabbit_hide": 415, - "minecraft:lead": 420, - "minecraft:name_tag": 421, - "minecraft:prismarine_crystals": 422, - "minecraft:armor_stand": 425, - "minecraft:end_crystal": 426, - "minecraft:spruce_door": 427, - "minecraft:birch_door": 428, - "minecraft:jungle_door": 429, - "minecraft:acacia_door": 430, - "minecraft:dark_oak_door": 431, - "minecraft:chorus_fruit": 432, - "minecraft:banner_pattern": 434, - "minecraft:dragon_breath": 437, - "minecraft:splash_potion": 438, - "minecraft:lingering_potion": 441, - "minecraft:sparkler": 442, - "minecraft:command_block_minecart": 443, - "minecraft:elytra": 444, - "minecraft:shulker_shell": 445, - "minecraft:banner": 446, - "minecraft:medicine": 447, - "minecraft:balloon": 448, - "minecraft:rapid_fertilizer": 449, - "minecraft:bleach": 451, - "minecraft:iron_nugget": 452, - "minecraft:ice_bomb": 453, - "minecraft:trident": 455, - "minecraft:beetroot": 457, - "minecraft:beetroot_seeds": 458, - "minecraft:beetroot_soup": 459, - "minecraft:salmon": 460, - "minecraft:pufferfish": 462, - "minecraft:cooked_salmon": 463, - "minecraft:dried_kelp": 464, - "minecraft:nautilus_shell": 465, - "minecraft:heart_of_the_sea": 467, - "minecraft:turtle_helmet": 469, - "minecraft:phantom_membrane": 470, - "minecraft:crossbow": 471, - "minecraft:spruce_sign": 472, - "minecraft:birch_sign": 473, - "minecraft:jungle_sign": 474, - "minecraft:acacia_sign": 475, - "minecraft:sweet_berries": 477, - "minecraft:camera": 498, - "minecraft:compound": 499, - "minecraft:shield": 513, - "minecraft:campfire": 720, - "minecraft:suspicious_stew": 734, - "minecraft:honeycomb": 736, - "minecraft:honey_bottle": 737, - "minecraft:netherite_ingot": 742, - "minecraft:netherite_sword": 743, - "minecraft:netherite_shovel": 744, - "minecraft:netherite_pickaxe": 745, - "minecraft:netherite_axe": 746, - "minecraft:netherite_hoe": 747, - "minecraft:netherite_helmet": 748, - "minecraft:netherite_chestplate": 749, - "minecraft:netherite_leggings": 750, - "minecraft:netherite_boots": 751, - "minecraft:netherite_scrap": 752, - "minecraft:crimson_sign": 753, - "minecraft:warped_sign": 754, - "minecraft:crimson_door": 755, - "minecraft:warped_door": 756, - "minecraft:warped_fungus_on_a_stick": 757, - "minecraft:chain": 758, - "minecraft:nether_sprouts": 760, - "minecraft:soul_campfire": 801, - "minecraft:enchanted_golden_apple": 466, - "minecraft:carrot_on_a_stick": 398, - "minecraft:popped_chorus_fruit": 433, - "minecraft:tropical_fish": 461, - "minecraft:cooked_cod": 350, - "minecraft:dark_oak_sign": 476, - "minecraft:empty_map": 395, - "minecraft:fire_charge": 385, - "minecraft:firework_rocket": 401, - "minecraft:firework_star": 402, - "minecraft:cod": 349, - "minecraft:diamond_horse_armor": 419, - "minecraft:golden_horse_armor": 418, - "minecraft:iron_horse_armor": 417, - "minecraft:leather_horse_armor": 416, - "minecraft:lodestone_compass": 741, - "minecraft:filled_map": 358, - "minecraft:melon_slice": 360, - "minecraft:cooked_mutton": 424, - "minecraft:mutton": 423, - "minecraft:nether_star": 399, - "minecraft:music_disc_11": 510, - "minecraft:music_disc_13": 500, - "minecraft:music_disc_blocks": 502, - "minecraft:music_disc_cat": 501, - "minecraft:music_disc_chirp": 503, - "minecraft:music_disc_far": 504, - "minecraft:music_disc_mall": 505, - "minecraft:music_disc_mellohi": 506, - "minecraft:music_disc_pigstep": 759, - "minecraft:music_disc_stal": 507, - "minecraft:music_disc_strad": 508, - "minecraft:music_disc_wait": 511, - "minecraft:music_disc_ward": 509, - "minecraft:sugar_cane": 338, - "minecraft:oak_sign": 323, - "minecraft:glistering_melon_slice": 382, - "minecraft:totem_of_undying": 450, - "minecraft:scute": 468, - "minecraft:raw_iron": 520, - "minecraft:raw_gold": 521, - "minecraft:raw_copper": 522, - "minecraft:music_disc_5": 643, - "minecraft:music_disc_relic": 701, - "minecraft:goat_horn": 761, - "minecraft:amethyst_shard": 771, - "minecraft:spyglass": 772, - "minecraft:music_disc_otherside": 773, - "minecraft:disc_fragment_5": 777, - "minecraft:recovery_compass": 778, - "minecraft:echo_shard": 779, - "minecraft:glow_frame": 850, - "minecraft:mangrove_door": 1004, - "minecraft:mangrove_sign": 1005 -} +{"minecraft:mangrove_double_slab":-499,"minecraft:stripped_mangrove_wood":-498,"minecraft:mangrove_wood":-497,"minecraft:mangrove_trapdoor":-496,"minecraft:mangrove_wall_sign":-495,"minecraft:mangrove_standing_sign":-494,"minecraft:mangrove_fence_gate":-492,"minecraft:mangrove_fence":-491,"minecraft:mangrove_pressure_plate":-490,"minecraft:mangrove_slab":-489,"minecraft:mangrove_stairs":-488,"minecraft:mangrove_button":-487,"minecraft:mangrove_planks":-486,"minecraft:stripped_mangrove_log":-485,"minecraft:mangrove_log":-484,"minecraft:muddy_mangrove_roots":-483,"minecraft:mangrove_roots":-482,"minecraft:mud_brick_wall":-481,"minecraft:mud_brick_stairs":-480,"minecraft:mud_brick_double_slab":-479,"minecraft:mud_brick_slab":-478,"minecraft:packed_mud":-477,"minecraft:mud_bricks":-475,"minecraft:mangrove_propagule":-474,"minecraft:mud":-473,"minecraft:mangrove_leaves":-472,"minecraft:ochre_froglight":-471,"minecraft:verdant_froglight":-470,"minecraft:pearlescent_froglight":-469,"minecraft:frog_spawn":-468,"minecraft:reinforced_deepslate":-466,"minecraft:client_request_placeholder_block":-465,"minecraft:sculk_shrieker":-461,"minecraft:sculk_catalyst":-460,"minecraft:sculk_vein":-459,"minecraft:sculk":-458,"minecraft:infested_deepslate":-454,"minecraft:raw_gold_block":-453,"minecraft:raw_copper_block":-452,"minecraft:raw_iron_block":-451,"minecraft:waxed_oxidized_double_cut_copper_slab":-450,"minecraft:waxed_oxidized_cut_copper_slab":-449,"minecraft:waxed_oxidized_cut_copper_stairs":-448,"minecraft:waxed_oxidized_cut_copper":-447,"minecraft:waxed_oxidized_copper":-446,"minecraft:black_candle_cake":-445,"minecraft:red_candle_cake":-444,"minecraft:green_candle_cake":-443,"minecraft:brown_candle_cake":-442,"minecraft:blue_candle_cake":-441,"minecraft:purple_candle_cake":-440,"minecraft:cyan_candle_cake":-439,"minecraft:light_gray_candle_cake":-438,"minecraft:gray_candle_cake":-437,"minecraft:pink_candle_cake":-436,"minecraft:lime_candle_cake":-435,"minecraft:yellow_candle_cake":-434,"minecraft:light_blue_candle_cake":-433,"minecraft:magenta_candle_cake":-432,"minecraft:orange_candle_cake":-431,"minecraft:white_candle_cake":-430,"minecraft:candle_cake":-429,"minecraft:black_candle":-428,"minecraft:red_candle":-427,"minecraft:green_candle":-426,"minecraft:brown_candle":-425,"minecraft:blue_candle":-424,"minecraft:purple_candle":-423,"minecraft:cyan_candle":-422,"minecraft:light_gray_candle":-421,"minecraft:gray_candle":-420,"minecraft:pink_candle":-419,"minecraft:lime_candle":-418,"minecraft:yellow_candle":-417,"minecraft:light_blue_candle":-416,"minecraft:magenta_candle":-415,"minecraft:orange_candle":-414,"minecraft:white_candle":-413,"minecraft:candle":-412,"minecraft:glow_lichen":-411,"minecraft:cracked_deepslate_bricks":-410,"minecraft:cracked_deepslate_tiles":-409,"minecraft:deepslate_copper_ore":-408,"minecraft:deepslate_emerald_ore":-407,"minecraft:deepslate_coal_ore":-406,"minecraft:deepslate_diamond_ore":-405,"minecraft:lit_deepslate_redstone_ore":-404,"minecraft:deepslate_redstone_ore":-403,"minecraft:deepslate_gold_ore":-402,"minecraft:deepslate_iron_ore":-401,"minecraft:deepslate_lapis_ore":-400,"minecraft:deepslate_brick_double_slab":-399,"minecraft:deepslate_tile_double_slab":-398,"minecraft:polished_deepslate_double_slab":-397,"minecraft:cobbled_deepslate_double_slab":-396,"minecraft:chiseled_deepslate":-395,"minecraft:deepslate_brick_wall":-394,"minecraft:deepslate_brick_stairs":-393,"minecraft:deepslate_brick_slab":-392,"minecraft:deepslate_bricks":-391,"minecraft:deepslate_tile_wall":-390,"minecraft:deepslate_tile_stairs":-389,"minecraft:deepslate_tile_slab":-388,"minecraft:deepslate_tiles":-387,"minecraft:polished_deepslate_wall":-386,"minecraft:polished_deepslate_stairs":-385,"minecraft:polished_deepslate_slab":-384,"minecraft:polished_deepslate":-383,"minecraft:cobbled_deepslate_wall":-382,"minecraft:cobbled_deepslate_stairs":-381,"minecraft:cobbled_deepslate_slab":-380,"minecraft:cobbled_deepslate":-379,"minecraft:deepslate":-378,"minecraft:smooth_basalt":-377,"minecraft:cave_vines_head_with_berries":-376,"minecraft:cave_vines_body_with_berries":-375,"minecraft:waxed_weathered_double_cut_copper_slab":-374,"minecraft:waxed_exposed_double_cut_copper_slab":-373,"minecraft:waxed_double_cut_copper_slab":-372,"minecraft:oxidized_double_cut_copper_slab":-371,"minecraft:weathered_double_cut_copper_slab":-370,"minecraft:exposed_double_cut_copper_slab":-369,"minecraft:double_cut_copper_slab":-368,"minecraft:waxed_weathered_cut_copper_slab":-367,"minecraft:waxed_exposed_cut_copper_slab":-366,"minecraft:waxed_cut_copper_slab":-365,"minecraft:oxidized_cut_copper_slab":-364,"minecraft:weathered_cut_copper_slab":-363,"minecraft:exposed_cut_copper_slab":-362,"minecraft:cut_copper_slab":-361,"minecraft:waxed_weathered_cut_copper_stairs":-360,"minecraft:waxed_exposed_cut_copper_stairs":-359,"minecraft:waxed_cut_copper_stairs":-358,"minecraft:oxidized_cut_copper_stairs":-357,"minecraft:weathered_cut_copper_stairs":-356,"minecraft:exposed_cut_copper_stairs":-355,"minecraft:cut_copper_stairs":-354,"minecraft:waxed_weathered_cut_copper":-353,"minecraft:waxed_exposed_cut_copper":-352,"minecraft:waxed_cut_copper":-351,"minecraft:oxidized_cut_copper":-350,"minecraft:weathered_cut_copper":-349,"minecraft:exposed_cut_copper":-348,"minecraft:cut_copper":-347,"minecraft:waxed_weathered_copper":-346,"minecraft:waxed_exposed_copper":-345,"minecraft:waxed_copper":-344,"minecraft:oxidized_copper":-343,"minecraft:weathered_copper":-342,"minecraft:exposed_copper":-341,"minecraft:copper_block":-340,"minecraft:item.glow_frame":-339,"minecraft:flowering_azalea":-338,"minecraft:azalea":-337,"minecraft:small_dripleaf_block":-336,"minecraft:moss_carpet":-335,"minecraft:tinted_glass":-334,"minecraft:tuff":-333,"minecraft:small_amethyst_bud":-332,"minecraft:medium_amethyst_bud":-331,"minecraft:large_amethyst_bud":-330,"minecraft:amethyst_cluster":-329,"minecraft:budding_amethyst":-328,"minecraft:amethyst_block":-327,"minecraft:calcite":-326,"minecraft:azalea_leaves_flowered":-325,"minecraft:azalea_leaves":-324,"minecraft:big_dripleaf":-323,"minecraft:cave_vines":-322,"minecraft:spore_blossom":-321,"minecraft:moss_block":-320,"minecraft:hanging_roots":-319,"minecraft:dirt_with_roots":-318,"minecraft:dripstone_block":-317,"minecraft:lightning_rod":-312,"minecraft:copper_ore":-311,"minecraft:pointed_dripstone":-308,"minecraft:sculk_sensor":-307,"minecraft:powder_snow":-306,"minecraft:quartz_bricks":-304,"minecraft:cracked_nether_bricks":-303,"minecraft:chiseled_nether_bricks":-302,"minecraft:stripped_warped_hyphae":-301,"minecraft:stripped_crimson_hyphae":-300,"minecraft:crimson_hyphae":-299,"minecraft:warped_hyphae":-298,"minecraft:polished_blackstone_wall":-297,"minecraft:polished_blackstone_button":-296,"minecraft:polished_blackstone_pressure_plate":-295,"minecraft:polished_blackstone_double_slab":-294,"minecraft:polished_blackstone_slab":-293,"minecraft:polished_blackstone_stairs":-292,"minecraft:polished_blackstone":-291,"minecraft:item.soul_campfire":-290,"minecraft:crying_obsidian":-289,"minecraft:nether_gold_ore":-288,"minecraft:twisting_vines":-287,"minecraft:item.chain":-286,"minecraft:polished_blackstone_brick_double_slab":-285,"minecraft:polished_blackstone_brick_slab":-284,"minecraft:blackstone_double_slab":-283,"minecraft:blackstone_slab":-282,"minecraft:gilded_blackstone":-281,"minecraft:cracked_polished_blackstone_bricks":-280,"minecraft:chiseled_polished_blackstone":-279,"minecraft:polished_blackstone_brick_wall":-278,"minecraft:blackstone_wall":-277,"minecraft:blackstone_stairs":-276,"minecraft:polished_blackstone_brick_stairs":-275,"minecraft:polished_blackstone_bricks":-274,"minecraft:blackstone":-273,"minecraft:respawn_anchor":-272,"minecraft:ancient_debris":-271,"minecraft:netherite_block":-270,"minecraft:soul_lantern":-269,"minecraft:soul_torch":-268,"minecraft:warped_double_slab":-267,"minecraft:crimson_double_slab":-266,"minecraft:warped_slab":-265,"minecraft:crimson_slab":-264,"minecraft:warped_pressure_plate":-263,"minecraft:crimson_pressure_plate":-262,"minecraft:warped_button":-261,"minecraft:crimson_button":-260,"minecraft:warped_fence_gate":-259,"minecraft:crimson_fence_gate":-258,"minecraft:warped_fence":-257,"minecraft:crimson_fence":-256,"minecraft:warped_stairs":-255,"minecraft:crimson_stairs":-254,"minecraft:warped_wall_sign":-253,"minecraft:crimson_wall_sign":-252,"minecraft:warped_standing_sign":-251,"minecraft:crimson_standing_sign":-250,"minecraft:warped_trapdoor":-247,"minecraft:crimson_trapdoor":-246,"minecraft:item.warped_door":-245,"minecraft:item.crimson_door":-244,"minecraft:warped_planks":-243,"minecraft:crimson_planks":-242,"minecraft:stripped_warped_stem":-241,"minecraft:stripped_crimson_stem":-240,"minecraft:target":-239,"minecraft:item.nether_sprouts":-238,"minecraft:soul_fire":-237,"minecraft:soul_soil":-236,"minecraft:polished_basalt":-235,"minecraft:basalt":-234,"minecraft:warped_nylium":-233,"minecraft:crimson_nylium":-232,"minecraft:weeping_vines":-231,"minecraft:shroomlight":-230,"minecraft:warped_fungus":-229,"minecraft:crimson_fungus":-228,"minecraft:warped_wart_block":-227,"minecraft:warped_stem":-226,"minecraft:crimson_stem":-225,"minecraft:warped_roots":-224,"minecraft:crimson_roots":-223,"minecraft:lodestone":-222,"minecraft:honeycomb_block":-221,"minecraft:honey_block":-220,"minecraft:beehive":-219,"minecraft:bee_nest":-218,"minecraft:stickypistonarmcollision":-217,"minecraft:sticky_piston_arm_collision":-217,"minecraft:wither_rose":-216,"minecraft:light_block":-215,"minecraft:lit_blast_furnace":-214,"minecraft:composter":-213,"minecraft:wood":-212,"minecraft:jigsaw":-211,"minecraft:lava_cauldron":-210,"minecraft:item.campfire":-209,"minecraft:lantern":-208,"minecraft:sweet_berry_bush":-207,"minecraft:bell":-206,"minecraft:loom":-204,"minecraft:barrel":-203,"minecraft:smithing_table":-202,"minecraft:fletching_table":-201,"minecraft:cartography_table":-200,"minecraft:lit_smoker":-199,"minecraft:smoker":-198,"minecraft:stonecutter_block":-197,"minecraft:blast_furnace":-196,"minecraft:grindstone":-195,"minecraft:lectern":-194,"minecraft:darkoak_wall_sign":-193,"minecraft:darkoak_standing_sign":-192,"minecraft:acacia_wall_sign":-191,"minecraft:acacia_standing_sign":-190,"minecraft:jungle_wall_sign":-189,"minecraft:jungle_standing_sign":-188,"minecraft:birch_wall_sign":-187,"minecraft:birch_standing_sign":-186,"minecraft:smooth_quartz_stairs":-185,"minecraft:red_nether_brick_stairs":-184,"minecraft:smooth_stone":-183,"minecraft:spruce_wall_sign":-182,"minecraft:spruce_standing_sign":-181,"minecraft:normal_stone_stairs":-180,"minecraft:mossy_cobblestone_stairs":-179,"minecraft:end_brick_stairs":-178,"minecraft:smooth_sandstone_stairs":-177,"minecraft:smooth_red_sandstone_stairs":-176,"minecraft:mossy_stone_brick_stairs":-175,"minecraft:polished_andesite_stairs":-174,"minecraft:polished_diorite_stairs":-173,"minecraft:polished_granite_stairs":-172,"minecraft:andesite_stairs":-171,"minecraft:diorite_stairs":-170,"minecraft:granite_stairs":-169,"minecraft:real_double_stone_slab4":-168,"minecraft:double_stone_block_slab4":-168,"minecraft:real_double_stone_slab3":-167,"minecraft:double_stone_block_slab3":-167,"minecraft:double_stone_slab4":-166,"minecraft:stone_block_slab4":-166,"minecraft:scaffolding":-165,"minecraft:bamboo_sapling":-164,"minecraft:bamboo":-163,"minecraft:double_stone_slab3":-162,"minecraft:stone_block_slab3":-162,"minecraft:barrier":-161,"minecraft:bubble_column":-160,"minecraft:turtle_egg":-159,"minecraft:air":-158,"minecraft:conduit":-157,"minecraft:sea_pickle":-156,"minecraft:carved_pumpkin":-155,"minecraft:spruce_pressure_plate":-154,"minecraft:jungle_pressure_plate":-153,"minecraft:dark_oak_pressure_plate":-152,"minecraft:birch_pressure_plate":-151,"minecraft:acacia_pressure_plate":-150,"minecraft:spruce_trapdoor":-149,"minecraft:jungle_trapdoor":-148,"minecraft:dark_oak_trapdoor":-147,"minecraft:birch_trapdoor":-146,"minecraft:acacia_trapdoor":-145,"minecraft:spruce_button":-144,"minecraft:jungle_button":-143,"minecraft:dark_oak_button":-142,"minecraft:birch_button":-141,"minecraft:acacia_button":-140,"minecraft:dried_kelp_block":-139,"minecraft:item.kelp":-138,"minecraft:coral_fan_hang3":-137,"minecraft:coral_fan_hang2":-136,"minecraft:coral_fan_hang":-135,"minecraft:coral_fan_dead":-134,"minecraft:coral_fan":-133,"minecraft:coral_block":-132,"minecraft:coral":-131,"minecraft:seagrass":-130,"minecraft:element_118":-129,"minecraft:element_117":-128,"minecraft:element_116":-127,"minecraft:element_115":-126,"minecraft:element_114":-125,"minecraft:element_113":-124,"minecraft:element_112":-123,"minecraft:element_111":-122,"minecraft:element_110":-121,"minecraft:element_109":-120,"minecraft:element_108":-119,"minecraft:element_107":-118,"minecraft:element_106":-117,"minecraft:element_105":-116,"minecraft:element_104":-115,"minecraft:element_103":-114,"minecraft:element_102":-113,"minecraft:element_101":-112,"minecraft:element_100":-111,"minecraft:element_99":-110,"minecraft:element_98":-109,"minecraft:element_97":-108,"minecraft:element_96":-107,"minecraft:element_95":-106,"minecraft:element_94":-105,"minecraft:element_93":-104,"minecraft:element_92":-103,"minecraft:element_91":-102,"minecraft:element_90":-101,"minecraft:element_89":-100,"minecraft:element_88":-99,"minecraft:element_87":-98,"minecraft:element_86":-97,"minecraft:element_85":-96,"minecraft:element_84":-95,"minecraft:element_83":-94,"minecraft:element_82":-93,"minecraft:element_81":-92,"minecraft:element_80":-91,"minecraft:element_79":-90,"minecraft:element_78":-89,"minecraft:element_77":-88,"minecraft:element_76":-87,"minecraft:element_75":-86,"minecraft:element_74":-85,"minecraft:element_73":-84,"minecraft:element_72":-83,"minecraft:element_71":-82,"minecraft:element_70":-81,"minecraft:element_69":-80,"minecraft:element_68":-79,"minecraft:element_67":-78,"minecraft:element_66":-77,"minecraft:element_65":-76,"minecraft:element_64":-75,"minecraft:element_63":-74,"minecraft:element_62":-73,"minecraft:element_61":-72,"minecraft:element_60":-71,"minecraft:element_59":-70,"minecraft:element_58":-69,"minecraft:element_57":-68,"minecraft:element_56":-67,"minecraft:element_55":-66,"minecraft:element_54":-65,"minecraft:element_53":-64,"minecraft:element_52":-63,"minecraft:element_51":-62,"minecraft:element_50":-61,"minecraft:element_49":-60,"minecraft:element_48":-59,"minecraft:element_47":-58,"minecraft:element_46":-57,"minecraft:element_45":-56,"minecraft:element_44":-55,"minecraft:element_43":-54,"minecraft:element_42":-53,"minecraft:element_41":-52,"minecraft:element_40":-51,"minecraft:element_39":-50,"minecraft:element_38":-49,"minecraft:element_37":-48,"minecraft:element_36":-47,"minecraft:element_35":-46,"minecraft:element_34":-45,"minecraft:element_33":-44,"minecraft:element_32":-43,"minecraft:element_31":-42,"minecraft:element_30":-41,"minecraft:element_29":-40,"minecraft:element_28":-39,"minecraft:element_27":-38,"minecraft:element_26":-37,"minecraft:element_25":-36,"minecraft:element_24":-35,"minecraft:element_23":-34,"minecraft:element_22":-33,"minecraft:element_21":-32,"minecraft:element_20":-31,"minecraft:element_19":-30,"minecraft:element_18":-29,"minecraft:element_17":-28,"minecraft:element_16":-27,"minecraft:element_15":-26,"minecraft:element_14":-25,"minecraft:element_13":-24,"minecraft:element_12":-23,"minecraft:element_11":-22,"minecraft:element_10":-21,"minecraft:element_9":-20,"minecraft:element_8":-19,"minecraft:element_7":-18,"minecraft:element_6":-17,"minecraft:element_5":-16,"minecraft:element_4":-15,"minecraft:element_3":-14,"minecraft:element_2":-13,"minecraft:element_1":-12,"minecraft:blue_ice":-11,"minecraft:stripped_oak_log":-10,"minecraft:stripped_dark_oak_log":-9,"minecraft:stripped_acacia_log":-8,"minecraft:stripped_jungle_log":-7,"minecraft:stripped_birch_log":-6,"minecraft:stripped_spruce_log":-5,"minecraft:prismarine_bricks_stairs":-4,"minecraft:dark_prismarine_stairs":-3,"minecraft:prismarine_stairs":-2,"minecraft:stone":1,"minecraft:grass":2,"minecraft:grass_block":2,"minecraft:dirt":3,"minecraft:cobblestone":4,"minecraft:planks":5,"minecraft:sapling":6,"minecraft:bedrock":7,"minecraft:flowing_water":8,"minecraft:water":9,"minecraft:flowing_lava":10,"minecraft:lava":11,"minecraft:sand":12,"minecraft:gravel":13,"minecraft:gold_ore":14,"minecraft:iron_ore":15,"minecraft:coal_ore":16,"minecraft:log":17,"minecraft:leaves":18,"minecraft:sponge":19,"minecraft:glass":20,"minecraft:lapis_ore":21,"minecraft:lapis_block":22,"minecraft:dispenser":23,"minecraft:sandstone":24,"minecraft:noteblock":25,"minecraft:item.bed":26,"minecraft:golden_rail":27,"minecraft:detector_rail":28,"minecraft:sticky_piston":29,"minecraft:web":30,"minecraft:tallgrass":31,"minecraft:deadbush":32,"minecraft:piston":33,"minecraft:pistonarmcollision":34,"minecraft:piston_arm_collision":34,"minecraft:wool":35,"minecraft:element_0":36,"minecraft:yellow_flower":37,"minecraft:red_flower":38,"minecraft:brown_mushroom":39,"minecraft:red_mushroom":40,"minecraft:gold_block":41,"minecraft:iron_block":42,"minecraft:real_double_stone_slab":43,"minecraft:double_stone_block_slab":43,"minecraft:double_stone_slab":44,"minecraft:stone_block_slab":44,"minecraft:brick_block":45,"minecraft:tnt":46,"minecraft:bookshelf":47,"minecraft:mossy_cobblestone":48,"minecraft:obsidian":49,"minecraft:torch":50,"minecraft:fire":51,"minecraft:mob_spawner":52,"minecraft:oak_stairs":53,"minecraft:chest":54,"minecraft:redstone_wire":55,"minecraft:diamond_ore":56,"minecraft:diamond_block":57,"minecraft:crafting_table":58,"minecraft:item.wheat":59,"minecraft:farmland":60,"minecraft:furnace":61,"minecraft:lit_furnace":62,"minecraft:standing_sign":63,"minecraft:item.wooden_door":64,"minecraft:ladder":65,"minecraft:rail":66,"minecraft:stone_stairs":67,"minecraft:wall_sign":68,"minecraft:lever":69,"minecraft:stone_pressure_plate":70,"minecraft:item.iron_door":71,"minecraft:wooden_pressure_plate":72,"minecraft:redstone_ore":73,"minecraft:lit_redstone_ore":74,"minecraft:unlit_redstone_torch":75,"minecraft:redstone_torch":76,"minecraft:stone_button":77,"minecraft:snow_layer":78,"minecraft:ice":79,"minecraft:snow":80,"minecraft:cactus":81,"minecraft:clay":82,"minecraft:item.reeds":83,"minecraft:jukebox":84,"minecraft:fence":85,"minecraft:pumpkin":86,"minecraft:netherrack":87,"minecraft:soul_sand":88,"minecraft:glowstone":89,"minecraft:portal":90,"minecraft:lit_pumpkin":91,"minecraft:item.cake":92,"minecraft:unpowered_repeater":93,"minecraft:powered_repeater":94,"minecraft:invisiblebedrock":95,"minecraft:invisible_bedrock":95,"minecraft:trapdoor":96,"minecraft:monster_egg":97,"minecraft:stonebrick":98,"minecraft:brown_mushroom_block":99,"minecraft:red_mushroom_block":100,"minecraft:iron_bars":101,"minecraft:glass_pane":102,"minecraft:melon_block":103,"minecraft:pumpkin_stem":104,"minecraft:melon_stem":105,"minecraft:vine":106,"minecraft:fence_gate":107,"minecraft:brick_stairs":108,"minecraft:stone_brick_stairs":109,"minecraft:mycelium":110,"minecraft:waterlily":111,"minecraft:nether_brick":112,"minecraft:nether_brick_fence":113,"minecraft:nether_brick_stairs":114,"minecraft:item.nether_wart":115,"minecraft:enchanting_table":116,"minecraft:brewingstandblock":117,"minecraft:item.cauldron":118,"minecraft:end_portal":119,"minecraft:end_portal_frame":120,"minecraft:end_stone":121,"minecraft:dragon_egg":122,"minecraft:redstone_lamp":123,"minecraft:lit_redstone_lamp":124,"minecraft:dropper":125,"minecraft:activator_rail":126,"minecraft:cocoa":127,"minecraft:sandstone_stairs":128,"minecraft:emerald_ore":129,"minecraft:ender_chest":130,"minecraft:tripwire_hook":131,"minecraft:tripwire":132,"minecraft:trip_wire":132,"minecraft:emerald_block":133,"minecraft:spruce_stairs":134,"minecraft:birch_stairs":135,"minecraft:jungle_stairs":136,"minecraft:command_block":137,"minecraft:beacon":138,"minecraft:cobblestone_wall":139,"minecraft:item.flower_pot":140,"minecraft:carrots":141,"minecraft:potatoes":142,"minecraft:wooden_button":143,"minecraft:item.skull":144,"minecraft:anvil":145,"minecraft:trapped_chest":146,"minecraft:light_weighted_pressure_plate":147,"minecraft:heavy_weighted_pressure_plate":148,"minecraft:unpowered_comparator":149,"minecraft:powered_comparator":150,"minecraft:daylight_detector":151,"minecraft:redstone_block":152,"minecraft:quartz_ore":153,"minecraft:item.hopper":154,"minecraft:quartz_block":155,"minecraft:quartz_stairs":156,"minecraft:double_wooden_slab":157,"minecraft:wooden_slab":158,"minecraft:stained_hardened_clay":159,"minecraft:stained_glass_pane":160,"minecraft:leaves2":161,"minecraft:log2":162,"minecraft:acacia_stairs":163,"minecraft:dark_oak_stairs":164,"minecraft:slime":165,"minecraft:glow_stick":166,"minecraft:iron_trapdoor":167,"minecraft:prismarine":168,"minecraft:sealantern":169,"minecraft:sea_lantern":169,"minecraft:hay_block":170,"minecraft:carpet":171,"minecraft:hardened_clay":172,"minecraft:coal_block":173,"minecraft:packed_ice":174,"minecraft:double_plant":175,"minecraft:standing_banner":176,"minecraft:wall_banner":177,"minecraft:daylight_detector_inverted":178,"minecraft:red_sandstone":179,"minecraft:red_sandstone_stairs":180,"minecraft:real_double_stone_slab2":181,"minecraft:double_stone_block_slab2":181,"minecraft:double_stone_slab2":182,"minecraft:stone_block_slab2":182,"minecraft:spruce_fence_gate":183,"minecraft:birch_fence_gate":184,"minecraft:jungle_fence_gate":185,"minecraft:dark_oak_fence_gate":186,"minecraft:acacia_fence_gate":187,"minecraft:repeating_command_block":188,"minecraft:chain_command_block":189,"minecraft:hard_glass_pane":190,"minecraft:hard_stained_glass_pane":191,"minecraft:chemical_heat":192,"minecraft:item.spruce_door":193,"minecraft:item.birch_door":194,"minecraft:item.jungle_door":195,"minecraft:item.acacia_door":196,"minecraft:item.dark_oak_door":197,"minecraft:grass_path":198,"minecraft:item.frame":199,"minecraft:chorus_flower":200,"minecraft:purpur_block":201,"minecraft:colored_torch_rg":202,"minecraft:purpur_stairs":203,"minecraft:colored_torch_bp":204,"minecraft:undyed_shulker_box":205,"minecraft:end_bricks":206,"minecraft:frosted_ice":207,"minecraft:end_rod":208,"minecraft:end_gateway":209,"minecraft:allow":210,"minecraft:deny":211,"minecraft:border_block":212,"minecraft:magma":213,"minecraft:nether_wart_block":214,"minecraft:red_nether_brick":215,"minecraft:bone_block":216,"minecraft:structure_void":217,"minecraft:shulker_box":218,"minecraft:purple_glazed_terracotta":219,"minecraft:white_glazed_terracotta":220,"minecraft:orange_glazed_terracotta":221,"minecraft:magenta_glazed_terracotta":222,"minecraft:light_blue_glazed_terracotta":223,"minecraft:yellow_glazed_terracotta":224,"minecraft:lime_glazed_terracotta":225,"minecraft:pink_glazed_terracotta":226,"minecraft:gray_glazed_terracotta":227,"minecraft:silver_glazed_terracotta":228,"minecraft:cyan_glazed_terracotta":229,"minecraft:blue_glazed_terracotta":231,"minecraft:brown_glazed_terracotta":232,"minecraft:green_glazed_terracotta":233,"minecraft:red_glazed_terracotta":234,"minecraft:black_glazed_terracotta":235,"minecraft:concrete":236,"minecraft:concrete_powder":237,"minecraft:chemistry_table":238,"minecraft:underwater_torch":239,"minecraft:chorus_plant":240,"minecraft:stained_glass":241,"minecraft:item.camera":242,"minecraft:podzol":243,"minecraft:item.beetroot":244,"minecraft:stonecutter":245,"minecraft:glowingobsidian":246,"minecraft:netherreactor":247,"minecraft:info_update":248,"minecraft:info_update2":249,"minecraft:movingblock":250,"minecraft:moving_block":250,"minecraft:observer":251,"minecraft:structure_block":252,"minecraft:hard_glass":253,"minecraft:hard_stained_glass":254,"minecraft:reserved6":255,"minecraft:iron_shovel":256,"minecraft:iron_pickaxe":257,"minecraft:iron_axe":258,"minecraft:flint_and_steel":259,"minecraft:apple":260,"minecraft:bow":261,"minecraft:arrow":262,"minecraft:coal":263,"minecraft:diamond":264,"minecraft:iron_ingot":265,"minecraft:gold_ingot":266,"minecraft:iron_sword":267,"minecraft:wooden_sword":268,"minecraft:wooden_shovel":269,"minecraft:wooden_pickaxe":270,"minecraft:wooden_axe":271,"minecraft:stone_sword":272,"minecraft:stone_shovel":273,"minecraft:stone_pickaxe":274,"minecraft:stone_axe":275,"minecraft:diamond_sword":276,"minecraft:diamond_shovel":277,"minecraft:diamond_pickaxe":278,"minecraft:diamond_axe":279,"minecraft:stick":280,"minecraft:bowl":281,"minecraft:mushroom_stew":282,"minecraft:golden_sword":283,"minecraft:golden_shovel":284,"minecraft:golden_pickaxe":285,"minecraft:golden_axe":286,"minecraft:string":287,"minecraft:feather":288,"minecraft:gunpowder":289,"minecraft:wooden_hoe":290,"minecraft:stone_hoe":291,"minecraft:iron_hoe":292,"minecraft:diamond_hoe":293,"minecraft:golden_hoe":294,"minecraft:wheat_seeds":295,"minecraft:wheat":296,"minecraft:bread":297,"minecraft:leather_helmet":298,"minecraft:leather_chestplate":299,"minecraft:leather_leggings":300,"minecraft:leather_boots":301,"minecraft:chainmail_helmet":302,"minecraft:chainmail_chestplate":303,"minecraft:chainmail_leggings":304,"minecraft:chainmail_boots":305,"minecraft:iron_helmet":306,"minecraft:iron_chestplate":307,"minecraft:iron_leggings":308,"minecraft:iron_boots":309,"minecraft:diamond_helmet":310,"minecraft:diamond_chestplate":311,"minecraft:diamond_leggings":312,"minecraft:diamond_boots":313,"minecraft:golden_helmet":314,"minecraft:golden_chestplate":315,"minecraft:golden_leggings":316,"minecraft:golden_boots":317,"minecraft:flint":318,"minecraft:porkchop":319,"minecraft:cooked_porkchop":320,"minecraft:painting":321,"minecraft:golden_apple":322,"minecraft:oak_sign":323,"minecraft:wooden_door":324,"minecraft:bucket":325,"minecraft:minecart":328,"minecraft:saddle":329,"minecraft:iron_door":330,"minecraft:redstone":331,"minecraft:snowball":332,"minecraft:boat":333,"minecraft:leather":334,"minecraft:kelp":335,"minecraft:brick":336,"minecraft:clay_ball":337,"minecraft:sugar_cane":338,"minecraft:paper":339,"minecraft:book":340,"minecraft:slime_ball":341,"minecraft:chest_minecart":342,"minecraft:egg":344,"minecraft:compass":345,"minecraft:fishing_rod":346,"minecraft:clock":347,"minecraft:glowstone_dust":348,"minecraft:cod":349,"minecraft:cooked_cod":350,"minecraft:dye":351,"minecraft:bone":352,"minecraft:sugar":353,"minecraft:cake":354,"minecraft:bed":355,"minecraft:repeater":356,"minecraft:cookie":357,"minecraft:filled_map":358,"minecraft:shears":359,"minecraft:melon_slice":360,"minecraft:pumpkin_seeds":361,"minecraft:melon_seeds":362,"minecraft:beef":363,"minecraft:cooked_beef":364,"minecraft:chicken":365,"minecraft:cooked_chicken":366,"minecraft:rotten_flesh":367,"minecraft:ender_pearl":368,"minecraft:blaze_rod":369,"minecraft:ghast_tear":370,"minecraft:gold_nugget":371,"minecraft:nether_wart":372,"minecraft:potion":373,"minecraft:glass_bottle":374,"minecraft:spider_eye":375,"minecraft:fermented_spider_eye":376,"minecraft:blaze_powder":377,"minecraft:magma_cream":378,"minecraft:brewing_stand":379,"minecraft:cauldron":380,"minecraft:ender_eye":381,"minecraft:glistering_melon_slice":382,"minecraft:spawn_egg":383,"minecraft:experience_bottle":384,"minecraft:fire_charge":385,"minecraft:writable_book":386,"minecraft:written_book":387,"minecraft:emerald":388,"minecraft:frame":389,"minecraft:flower_pot":390,"minecraft:carrot":391,"minecraft:potato":392,"minecraft:baked_potato":393,"minecraft:poisonous_potato":394,"minecraft:empty_map":395,"minecraft:golden_carrot":396,"minecraft:skull":397,"minecraft:carrot_on_a_stick":398,"minecraft:nether_star":399,"minecraft:pumpkin_pie":400,"minecraft:firework_rocket":401,"minecraft:firework_star":402,"minecraft:enchanted_book":403,"minecraft:comparator":404,"minecraft:netherbrick":405,"minecraft:quartz":406,"minecraft:tnt_minecart":407,"minecraft:hopper_minecart":408,"minecraft:prismarine_shard":409,"minecraft:hopper":410,"minecraft:rabbit":411,"minecraft:cooked_rabbit":412,"minecraft:rabbit_stew":413,"minecraft:rabbit_foot":414,"minecraft:rabbit_hide":415,"minecraft:leather_horse_armor":416,"minecraft:iron_horse_armor":417,"minecraft:golden_horse_armor":418,"minecraft:diamond_horse_armor":419,"minecraft:lead":420,"minecraft:name_tag":421,"minecraft:prismarine_crystals":422,"minecraft:mutton":423,"minecraft:cooked_mutton":424,"minecraft:armor_stand":425,"minecraft:end_crystal":426,"minecraft:spruce_door":427,"minecraft:birch_door":428,"minecraft:jungle_door":429,"minecraft:acacia_door":430,"minecraft:dark_oak_door":431,"minecraft:chorus_fruit":432,"minecraft:popped_chorus_fruit":433,"minecraft:banner_pattern":434,"minecraft:dragon_breath":437,"minecraft:splash_potion":438,"minecraft:lingering_potion":441,"minecraft:sparkler":442,"minecraft:command_block_minecart":443,"minecraft:elytra":444,"minecraft:shulker_shell":445,"minecraft:banner":446,"minecraft:medicine":447,"minecraft:balloon":448,"minecraft:rapid_fertilizer":449,"minecraft:totem_of_undying":450,"minecraft:bleach":451,"minecraft:iron_nugget":452,"minecraft:ice_bomb":453,"minecraft:trident":455,"minecraft:beetroot":457,"minecraft:beetroot_seeds":458,"minecraft:beetroot_soup":459,"minecraft:salmon":460,"minecraft:tropical_fish":461,"minecraft:pufferfish":462,"minecraft:cooked_salmon":463,"minecraft:dried_kelp":464,"minecraft:nautilus_shell":465,"minecraft:enchanted_golden_apple":466,"minecraft:heart_of_the_sea":467,"minecraft:scute":468,"minecraft:turtle_scute":468,"minecraft:turtle_helmet":469,"minecraft:phantom_membrane":470,"minecraft:crossbow":471,"minecraft:spruce_sign":472,"minecraft:birch_sign":473,"minecraft:jungle_sign":474,"minecraft:acacia_sign":475,"minecraft:dark_oak_sign":476,"minecraft:sweet_berries":477,"minecraft:camera":498,"minecraft:compound":499,"minecraft:music_disc_13":500,"minecraft:music_disc_cat":501,"minecraft:music_disc_blocks":502,"minecraft:music_disc_chirp":503,"minecraft:music_disc_far":504,"minecraft:music_disc_mall":505,"minecraft:music_disc_mellohi":506,"minecraft:music_disc_stal":507,"minecraft:music_disc_strad":508,"minecraft:music_disc_ward":509,"minecraft:music_disc_11":510,"minecraft:music_disc_wait":511,"minecraft:shield":513,"minecraft:raw_iron":520,"minecraft:raw_gold":521,"minecraft:raw_copper":522,"minecraft:glow_berries":654,"minecraft:campfire":720,"minecraft:suspicious_stew":734,"minecraft:honeycomb":736,"minecraft:honey_bottle":737,"minecraft:lodestone_compass":741,"minecraft:netherite_ingot":742,"minecraft:netherite_sword":743,"minecraft:netherite_shovel":744,"minecraft:netherite_pickaxe":745,"minecraft:netherite_axe":746,"minecraft:netherite_hoe":747,"minecraft:netherite_helmet":748,"minecraft:netherite_chestplate":749,"minecraft:netherite_leggings":750,"minecraft:netherite_boots":751,"minecraft:netherite_scrap":752,"minecraft:crimson_sign":753,"minecraft:warped_sign":754,"minecraft:crimson_door":755,"minecraft:warped_door":756,"minecraft:warped_fungus_on_a_stick":757,"minecraft:chain":758,"minecraft:nether_sprouts":760,"minecraft:soul_campfire":801,"minecraft:music_disc_pigstep":759,"minecraft:spyglass":772,"minecraft:music_disc_otherside":773,"minecraft:glow_frame":850,"minecraft:acacia_chest_boat":642,"minecraft:birch_chest_boat":639,"minecraft:chest_boat":645,"minecraft:dark_oak_chest_boat":643,"minecraft:disc_fragment_5":637,"minecraft:jungle_chest_boat":640,"minecraft:mangrove_chest_boat":644,"minecraft:music_disc_5":636,"minecraft:oak_chest_boat":638,"minecraft:spruce_chest_boat":641,"minecraft:amethyst_shard":771,"minecraft:echo_shard":647,"minecraft:goat_horn":761,"minecraft:music_disc_relic":701,"minecraft:copper_ingot":519,"minecraft:recovery_compass":648,"minecraft:mangrove_door":-493,"minecraft:trial_spawner":-315,"minecraft:exposed_copper_bulb":-777,"minecraft:cherry_planks":-537,"minecraft:calibrated_sculk_sensor":-580,"minecraft:oak_hanging_sign":-500,"minecraft:waxed_oxidized_copper_trapdoor":-799,"minecraft:stickyPistonArmCollision":-217,"minecraft:crimson_hanging_sign":-506,"minecraft:bamboo_door":-517,"minecraft:suspicious_gravel":-573,"minecraft:oxidized_copper_trapdoor":-795,"minecraft:exposed_copper_trapdoor":-793,"minecraft:suspicious_sand":-529,"minecraft:torchflower_crop":-567,"minecraft:birch_hanging_sign":-502,"minecraft:waxed_oxidized_copper_grate":-775,"minecraft:cherry_wall_sign":-544,"minecraft:cherry_trapdoor":-543,"minecraft:weathered_copper_grate":-770,"minecraft:waxed_exposed_copper_trapdoor":-797,"minecraft:copper_grate":-768,"minecraft:tuff_brick_slab":-755,"minecraft:waxed_exposed_copper_door":-789,"minecraft:bamboo_block":-527,"minecraft:bamboo_planks":-510,"minecraft:waxed_weathered_copper_trapdoor":-798,"minecraft:pink_petals":-549,"minecraft:chiseled_copper":-760,"minecraft:bamboo_fence":-515,"minecraft:waxed_weathered_copper_bulb":-782,"minecraft:bamboo_mosaic_stairs":-523,"minecraft:weathered_copper_trapdoor":-794,"minecraft:chiseled_tuff_bricks":-759,"minecraft:dark_oak_hanging_sign":-505,"minecraft:decorated_pot":-551,"minecraft:waxed_exposed_chiseled_copper":-765,"minecraft:deprecated_purpur_block_2":-952,"minecraft:chiseled_tuff":-753,"minecraft:polished_tuff_wall":-752,"minecraft:tuff_stairs":-746,"minecraft:cherry_log":-536,"minecraft:deprecated_purpur_block_1":-950,"minecraft:crafter":-313,"minecraft:polished_tuff":-748,"minecraft:cherry_stairs":-541,"minecraft:weathered_copper_door":-786,"minecraft:cherry_slab":-539,"minecraft:oxidized_chiseled_copper":-763,"minecraft:pitcher_plant":-612,"minecraft:waxed_exposed_copper_bulb":-781,"minecraft:bamboo_slab":-513,"minecraft:acacia_hanging_sign":-504,"minecraft:waxed_chiseled_copper":-764,"minecraft:cherry_pressure_plate":-538,"minecraft:copper_door":-784,"minecraft:waxed_oxidized_copper_bulb":-783,"minecraft:waxed_copper_grate":-772,"minecraft:bamboo_mosaic":-509,"minecraft:bamboo_mosaic_slab":-524,"minecraft:tuff_brick_wall":-758,"minecraft:bamboo_button":-511,"minecraft:waxed_copper_door":-788,"minecraft:cherry_button":-530,"minecraft:bamboo_pressure_plate":-514,"minecraft:polished_tuff_slab":-749,"minecraft:waxed_copper_bulb":-780,"minecraft:oxidized_copper_bulb":-779,"minecraft:heavy_core":-316,"minecraft:stripped_cherry_log":-535,"minecraft:bamboo_trapdoor":-520,"minecraft:spruce_hanging_sign":-501,"minecraft:torchflower":-568,"minecraft:exposed_chiseled_copper":-761,"minecraft:cherry_fence":-532,"minecraft:tuff_wall":-747,"minecraft:bamboo_standing_sign":-518,"minecraft:bamboo_fence_gate":-516,"minecraft:stripped_bamboo_block":-528,"minecraft:cherry_wood":-546,"minecraft:tuff_double_slab":-745,"minecraft:waxed_weathered_chiseled_copper":-767,"minecraft:copper_bulb":-776,"minecraft:waxed_weathered_copper_door":-790,"minecraft:unknown":-305,"minecraft:warped_hanging_sign":-507,"minecraft:jungle_hanging_sign":-503,"minecraft:copper_trapdoor":-792,"minecraft:oxidized_copper_grate":-771,"minecraft:stone_slab4":-166,"minecraft:stone_slab3":-162,"minecraft:waxed_exposed_copper_grate":-773,"minecraft:waxed_oxidized_copper_door":-791,"minecraft:waxed_copper_trapdoor":-796,"minecraft:cherry_door":-531,"minecraft:cherry_fence_gate":-533,"minecraft:cherry_standing_sign":-542,"minecraft:tuff_bricks":-754,"minecraft:bamboo_wall_sign":-519,"minecraft:waxed_oxidized_chiseled_copper":-766,"minecraft:chiseled_bookshelf":-526,"minecraft:exposed_copper_grate":-769,"minecraft:pitcher_crop":-574,"minecraft:vault":-314,"minecraft:tuff_brick_stairs":-757,"minecraft:waxed_weathered_copper_grate":-774,"minecraft:mangrove_hanging_sign":-508,"minecraft:bamboo_hanging_sign":-522,"minecraft:polished_tuff_double_slab":-750,"minecraft:weathered_copper_bulb":-778,"minecraft:weathered_chiseled_copper":-762,"minecraft:cherry_leaves":-548,"minecraft:tuff_slab":-744,"minecraft:polished_tuff_stairs":-751,"minecraft:cherry_hanging_sign":-534,"minecraft:bamboo_mosaic_double_slab":-525,"minecraft:cherry_sapling":-547,"minecraft:tuff_brick_double_slab":-756,"minecraft:oxidized_copper_door":-787,"minecraft:exposed_copper_door":-785,"minecraft:bamboo_double_slab":-521,"minecraft:stripped_cherry_wood":-545,"minecraft:cherry_double_slab":-540,"minecraft:bamboo_stairs":-512,"minecraft:sniffer_egg":-596} \ No newline at end of file diff --git a/src/main/resources/log4j2.xml b/src/main/resources/log4j2.xml index 851db6943d1..286e25c3c75 100644 --- a/src/main/resources/log4j2.xml +++ b/src/main/resources/log4j2.xml @@ -11,8 +11,18 @@ <OnStartupTriggeringPolicy/> </Policies> </RollingRandomAccessFile> + <RollingRandomAccessFile name="LevelDB" fileName="logs/leveldb/latest.log" filePattern="logs/leveldb/%d{yyyy-MM-dd}-%i.log.gz"> + <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level - %msg%n"/> + <Policies> + <TimeBasedTriggeringPolicy/> + <OnStartupTriggeringPolicy/> + </Policies> + </RollingRandomAccessFile> </Appenders> <Loggers> + <Logger name="LevelDB-Logger" level="DEBUG" additivity="false"> + <AppenderRef ref="LevelDB"/> + </Logger> <Root level="INFO"> <AppenderRef ref="Console"/> <AppenderRef ref="File"/> diff --git a/src/main/resources/recipes.json b/src/main/resources/recipes.json index 55f6791a5b9..25f43577d57 100644 --- a/src/main/resources/recipes.json +++ b/src/main/resources/recipes.json @@ -1 +1 @@ -{"recipes":[{"type":4,"uuid":"442d85ed-8272-4543-a6f1-418f90ded05d"},{"type":4,"uuid":"8b36268c-1829-483c-a0f1-993b7156a8f2"},{"type":4,"uuid":"602234e4-cac1-4353-8bb7-b1ebff70024b"},{"type":0,"input":[{"id":339,"damage":-1},{"id":345,"damage":-1}],"output":[{"id":395,"damage":2}],"block":"cartography_table","priority":0},{"type":0,"input":[{"id":339,"damage":-1}],"output":[{"id":395}],"block":"cartography_table","priority":0},{"type":4,"uuid":"98c84b38-1085-46bd-b1ce-dd38c159e6cc"},{"type":0,"input":[{"id":1,"damage":5}],"output":[{"id":-162,"damage":3,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":1,"damage":5}],"output":[{"id":-171}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":1,"damage":5}],"output":[{"id":139,"damage":4}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":-273,"damage":-1}],"output":[{"id":-282,"count":2}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":-273,"damage":-1}],"output":[{"id":-276}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":-273,"damage":-1}],"output":[{"id":-277}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":45}],"output":[{"id":44,"damage":4,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":-291,"damage":-1}],"output":[{"id":-284,"count":2}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":45}],"output":[{"id":108}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":-291,"damage":-1}],"output":[{"id":-275}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":45}],"output":[{"id":139,"damage":6}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":-291,"damage":-1}],"output":[{"id":-278}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":-291,"damage":-1}],"output":[{"id":-274}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":-291,"damage":-1}],"output":[{"id":-279}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":112,"damage":-1}],"output":[{"id":-302}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":-273,"damage":-1}],"output":[{"id":-279}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":4}],"output":[{"id":44,"damage":3,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":4}],"output":[{"id":67}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":4}],"output":[{"id":139}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":168,"damage":1}],"output":[{"id":182,"damage":3,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":168,"damage":1}],"output":[{"id":-3}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":1,"damage":3}],"output":[{"id":-162,"damage":4,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":1,"damage":3}],"output":[{"id":-170}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":1,"damage":3}],"output":[{"id":139,"damage":3}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":1}],"output":[{"id":-166,"damage":2,"count":2}],"block":"stonecutter","priority":5},{"type":0,"input":[{"id":121}],"output":[{"id":-162,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":206}],"output":[{"id":-162,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":121}],"output":[{"id":-178}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":206}],"output":[{"id":-178}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":121}],"output":[{"id":139,"damage":10}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":206}],"output":[{"id":139,"damage":10}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":121}],"output":[{"id":206}],"block":"stonecutter","priority":3},{"type":0,"input":[{"id":1,"damage":1}],"output":[{"id":-162,"damage":6,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":1,"damage":1}],"output":[{"id":-169}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":1,"damage":1}],"output":[{"id":139,"damage":2}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":48}],"output":[{"id":182,"damage":5,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":48}],"output":[{"id":-179}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":48}],"output":[{"id":139,"damage":1}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":98,"damage":1}],"output":[{"id":-166,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":98,"damage":1}],"output":[{"id":-175}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":98,"damage":1}],"output":[{"id":139,"damage":8}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":112}],"output":[{"id":44,"damage":7,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":112}],"output":[{"id":114}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":112}],"output":[{"id":139,"damage":9}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":1,"damage":5}],"output":[{"id":1,"damage":6}],"block":"stonecutter","priority":3},{"type":0,"input":[{"id":1,"damage":5}],"output":[{"id":-162,"damage":2,"count":2}],"block":"stonecutter","priority":4},{"type":0,"input":[{"id":1,"damage":6}],"output":[{"id":-162,"damage":2,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":1,"damage":5}],"output":[{"id":-174}],"block":"stonecutter","priority":5},{"type":0,"input":[{"id":1,"damage":6}],"output":[{"id":-174}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":-234,"damage":-1}],"output":[{"id":-235}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":-273,"damage":-1}],"output":[{"id":-284,"count":2}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":-273,"damage":-1}],"output":[{"id":-275}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":-273,"damage":-1}],"output":[{"id":-278}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":-273,"damage":-1}],"output":[{"id":-274}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":1,"damage":3}],"output":[{"id":1,"damage":4}],"block":"stonecutter","priority":3},{"type":0,"input":[{"id":1,"damage":3}],"output":[{"id":-162,"damage":5,"count":2}],"block":"stonecutter","priority":4},{"type":0,"input":[{"id":1,"damage":4}],"output":[{"id":-162,"damage":5,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":1,"damage":3}],"output":[{"id":-173}],"block":"stonecutter","priority":5},{"type":0,"input":[{"id":1,"damage":4}],"output":[{"id":-173}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":-273,"damage":-1}],"output":[{"id":-291}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":1,"damage":1}],"output":[{"id":1,"damage":2}],"block":"stonecutter","priority":3},{"type":0,"input":[{"id":1,"damage":1}],"output":[{"id":-162,"damage":7,"count":2}],"block":"stonecutter","priority":4},{"type":0,"input":[{"id":1,"damage":2}],"output":[{"id":-162,"damage":7,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":1,"damage":1}],"output":[{"id":-172}],"block":"stonecutter","priority":5},{"type":0,"input":[{"id":1,"damage":2}],"output":[{"id":-172}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":-273,"damage":-1}],"output":[{"id":-293,"count":2}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":-273,"damage":-1}],"output":[{"id":-292}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":-273,"damage":-1}],"output":[{"id":-297}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":168,"damage":2}],"output":[{"id":182,"damage":4,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":168,"damage":2}],"output":[{"id":-4}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":168}],"output":[{"id":182,"damage":2,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":168}],"output":[{"id":-2}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":168}],"output":[{"id":139,"damage":11}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":201}],"output":[{"id":201,"damage":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":201}],"output":[{"id":182,"damage":1,"count":2}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":201}],"output":[{"id":203}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":155}],"output":[{"id":-304}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":155}],"output":[{"id":155,"damage":1}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":155}],"output":[{"id":155,"damage":2}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":155}],"output":[{"id":44,"damage":6,"count":2}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":155}],"output":[{"id":156}],"block":"stonecutter","priority":3},{"type":0,"input":[{"id":215}],"output":[{"id":182,"damage":7,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":215}],"output":[{"id":-184}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":215}],"output":[{"id":139,"damage":13}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":179}],"output":[{"id":182,"count":2}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":179}],"output":[{"id":179,"damage":2}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":179}],"output":[{"id":179,"damage":1}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":179}],"output":[{"id":180}],"block":"stonecutter","priority":3},{"type":0,"input":[{"id":179}],"output":[{"id":139,"damage":12}],"block":"stonecutter","priority":4},{"type":0,"input":[{"id":24}],"output":[{"id":44,"damage":1,"count":2}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":24}],"output":[{"id":24,"damage":2}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":24}],"output":[{"id":24,"damage":1}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":24}],"output":[{"id":128}],"block":"stonecutter","priority":3},{"type":0,"input":[{"id":24}],"output":[{"id":139,"damage":5}],"block":"stonecutter","priority":4},{"type":0,"input":[{"id":-291,"damage":-1}],"output":[{"id":-293,"count":2}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":-274,"damage":-1}],"output":[{"id":-284,"count":2}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":-183}],"output":[{"id":44,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":155,"damage":3}],"output":[{"id":-166,"damage":1,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":155,"damage":3}],"output":[{"id":-185}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":179,"damage":3}],"output":[{"id":-162,"damage":1,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":179,"damage":3}],"output":[{"id":-176}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":24,"damage":3}],"output":[{"id":182,"damage":6,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":24,"damage":3}],"output":[{"id":-177}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":-291,"damage":-1}],"output":[{"id":-292}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":1}],"output":[{"id":-180}],"block":"stonecutter","priority":6},{"type":0,"input":[{"id":1}],"output":[{"id":98}],"block":"stonecutter","priority":4},{"type":0,"input":[{"id":1}],"output":[{"id":98,"damage":3}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":1}],"output":[{"id":44,"damage":5,"count":2}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":98}],"output":[{"id":44,"damage":5,"count":2}],"block":"stonecutter","priority":0},{"type":0,"input":[{"id":1}],"output":[{"id":109}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":98}],"output":[{"id":109}],"block":"stonecutter","priority":1},{"type":0,"input":[{"id":1}],"output":[{"id":139,"damage":7}],"block":"stonecutter","priority":3},{"type":0,"input":[{"id":98}],"output":[{"id":139,"damage":7}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":-291,"damage":-1}],"output":[{"id":-297}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":-274,"damage":-1}],"output":[{"id":-278}],"block":"stonecutter","priority":2},{"type":0,"input":[{"id":-274,"damage":-1}],"output":[{"id":-275}],"block":"stonecutter","priority":2},{"type":1,"input":{"A":{"id":5,"damage":-1},"B":{"id":340,"damage":-1}},"output":[{"id":47}],"shape":["AAA","BBB","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":-1}},"output":[{"id":281,"count":4}],"shape":["A A"," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":4}},"output":[{"id":-140}],"shape":["A"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":2}},"output":[{"id":-141}],"shape":["A"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":5}},"output":[{"id":-142}],"shape":["A"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":3}},"output":[{"id":-143}],"shape":["A"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":1}},"output":[{"id":-144}],"shape":["A"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":-1}},"output":[{"id":54}],"shape":["AAA","A A","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":20},"B":{"id":406,"damage":-1},"C":{"id":158,"damage":-1}},"output":[{"id":151}],"shape":["AAA","BBB","CCC"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":377,"damage":-1},{"id":263,"damage":1},{"id":289,"damage":-1}],"output":[{"id":385,"count":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":377,"damage":-1},{"id":263,"damage":-1},{"id":289,"damage":-1}],"output":[{"id":385,"count":3}],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":-1},"B":{"id":264,"damage":-1}},"output":[{"id":84}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":-1},"B":{"id":331,"damage":-1}},"output":[{"id":25}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":4}},"output":[{"id":44,"damage":3,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":112}},"output":[{"id":44,"damage":7,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":24}},"output":[{"id":44,"damage":1,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":35,"damage":0}},"output":[{"id":321}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":35,"damage":1}},"output":[{"id":321}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":35,"damage":2}},"output":[{"id":321}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":35,"damage":3}},"output":[{"id":321}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":35,"damage":4}},"output":[{"id":321}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":35,"damage":5}},"output":[{"id":321}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":35,"damage":6}},"output":[{"id":321}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":35,"damage":7}},"output":[{"id":321}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":35,"damage":8}},"output":[{"id":321}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":35,"damage":9}},"output":[{"id":321}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":35,"damage":10}},"output":[{"id":321}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":35,"damage":11}},"output":[{"id":321}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":35,"damage":12}},"output":[{"id":321}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":35,"damage":13}},"output":[{"id":321}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":35,"damage":14}},"output":[{"id":321}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":35,"damage":15}},"output":[{"id":321}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":-1},"B":{"id":4},"C":{"id":265,"damage":-1},"D":{"id":331,"damage":-1}},"output":[{"id":33,"damage":1}],"shape":["AAA","BCB","BDB"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":4}},"output":[{"id":-150}],"shape":["AA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":2}},"output":[{"id":-151}],"shape":["AA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":5}},"output":[{"id":-152}],"shape":["AA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":3}},"output":[{"id":-153}],"shape":["AA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":1}},"output":[{"id":-154}],"shape":["AA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":-163}},"output":[{"id":280}],"shape":["A","A"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":1}},"output":[{"id":-166,"damage":2,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":98,"damage":1}},"output":[{"id":-166,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":45}},"output":[{"id":44,"damage":4,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":98}},"output":[{"id":44,"damage":5,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":-183}},"output":[{"id":44,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":263,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":50,"count":4}],"shape":["A","B"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":263,"damage":1},"B":{"id":280,"damage":-1}},"output":[{"id":50,"count":4}],"shape":["A","B"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":4}},"output":[{"id":-145,"count":2}],"shape":["AAA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":2}},"output":[{"id":-146,"count":2}],"shape":["AAA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":5}},"output":[{"id":-147,"count":2}],"shape":["AAA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":3}},"output":[{"id":-148,"count":2}],"shape":["AAA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":1}},"output":[{"id":-149,"count":2}],"shape":["AAA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5}},"output":[{"id":96,"count":2}],"shape":["AAA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":265,"damage":-1},"B":{"id":280,"damage":-1},"C":{"id":5,"damage":-1}},"output":[{"id":131,"count":2}],"shape":["A","B","C"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5}},"output":[{"id":143}],"shape":["A"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5}},"output":[{"id":72}],"shape":["AA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":-1}},"output":[{"id":58}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":4}},"output":[{"id":163,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":50},{"type":4,"uuid":"d81aaeaf-e172-4440-9225-868df030d27b"},{"type":4,"uuid":"b5c5d105-75a2-4076-af2b-923ea2bf4bf0"},{"type":4,"uuid":"00000000-0000-0000-0000-000000000002"},{"type":1,"input":{"A":{"id":35},"B":{"id":5,"damage":-1}},"output":[{"id":355}],"shape":["AAA","BBB"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":35,"damage":1},"B":{"id":5,"damage":-1}},"output":[{"id":355,"damage":1}],"shape":["AAA","BBB"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":35,"damage":10},"B":{"id":5,"damage":-1}},"output":[{"id":355,"damage":10}],"shape":["AAA","BBB"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":35,"damage":11},"B":{"id":5,"damage":-1}},"output":[{"id":355,"damage":11}],"shape":["AAA","BBB"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":35,"damage":12},"B":{"id":5,"damage":-1}},"output":[{"id":355,"damage":12}],"shape":["AAA","BBB"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":35,"damage":13},"B":{"id":5,"damage":-1}},"output":[{"id":355,"damage":13}],"shape":["AAA","BBB"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":35,"damage":14},"B":{"id":5,"damage":-1}},"output":[{"id":355,"damage":14}],"shape":["AAA","BBB"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":35,"damage":15},"B":{"id":5,"damage":-1}},"output":[{"id":355,"damage":15}],"shape":["AAA","BBB"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":35,"damage":2},"B":{"id":5,"damage":-1}},"output":[{"id":355,"damage":2}],"shape":["AAA","BBB"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":35,"damage":3},"B":{"id":5,"damage":-1}},"output":[{"id":355,"damage":3}],"shape":["AAA","BBB"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":35,"damage":4},"B":{"id":5,"damage":-1}},"output":[{"id":355,"damage":4}],"shape":["AAA","BBB"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":35,"damage":5},"B":{"id":5,"damage":-1}},"output":[{"id":355,"damage":5}],"shape":["AAA","BBB"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":35,"damage":6},"B":{"id":5,"damage":-1}},"output":[{"id":355,"damage":6}],"shape":["AAA","BBB"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":35,"damage":7},"B":{"id":5,"damage":-1}},"output":[{"id":355,"damage":7}],"shape":["AAA","BBB"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":35,"damage":8},"B":{"id":5,"damage":-1}},"output":[{"id":355,"damage":8}],"shape":["AAA","BBB"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":35,"damage":9},"B":{"id":5,"damage":-1}},"output":[{"id":355,"damage":9}],"shape":["AAA","BBB"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":35},"B":{"id":-242,"damage":-1}},"output":[{"id":355}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":1},"B":{"id":-242,"damage":-1}},"output":[{"id":355,"damage":1}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":10},"B":{"id":-242,"damage":-1}},"output":[{"id":355,"damage":10}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":11},"B":{"id":-242,"damage":-1}},"output":[{"id":355,"damage":11}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":12},"B":{"id":-242,"damage":-1}},"output":[{"id":355,"damage":12}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":13},"B":{"id":-242,"damage":-1}},"output":[{"id":355,"damage":13}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":14},"B":{"id":-242,"damage":-1}},"output":[{"id":355,"damage":14}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":15},"B":{"id":-242,"damage":-1}},"output":[{"id":355,"damage":15}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":2},"B":{"id":-242,"damage":-1}},"output":[{"id":355,"damage":2}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":3},"B":{"id":-242,"damage":-1}},"output":[{"id":355,"damage":3}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":4},"B":{"id":-242,"damage":-1}},"output":[{"id":355,"damage":4}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":5},"B":{"id":-242,"damage":-1}},"output":[{"id":355,"damage":5}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":6},"B":{"id":-242,"damage":-1}},"output":[{"id":355,"damage":6}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":7},"B":{"id":-242,"damage":-1}},"output":[{"id":355,"damage":7}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":8},"B":{"id":-242,"damage":-1}},"output":[{"id":355,"damage":8}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":9},"B":{"id":-242,"damage":-1}},"output":[{"id":355,"damage":9}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35},"B":{"id":-243,"damage":-1}},"output":[{"id":355}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":1},"B":{"id":-243,"damage":-1}},"output":[{"id":355,"damage":1}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":10},"B":{"id":-243,"damage":-1}},"output":[{"id":355,"damage":10}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":11},"B":{"id":-243,"damage":-1}},"output":[{"id":355,"damage":11}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":12},"B":{"id":-243,"damage":-1}},"output":[{"id":355,"damage":12}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":13},"B":{"id":-243,"damage":-1}},"output":[{"id":355,"damage":13}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":14},"B":{"id":-243,"damage":-1}},"output":[{"id":355,"damage":14}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":15},"B":{"id":-243,"damage":-1}},"output":[{"id":355,"damage":15}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":2},"B":{"id":-243,"damage":-1}},"output":[{"id":355,"damage":2}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":3},"B":{"id":-243,"damage":-1}},"output":[{"id":355,"damage":3}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":4},"B":{"id":-243,"damage":-1}},"output":[{"id":355,"damage":4}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":5},"B":{"id":-243,"damage":-1}},"output":[{"id":355,"damage":5}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":6},"B":{"id":-243,"damage":-1}},"output":[{"id":355,"damage":6}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":7},"B":{"id":-243,"damage":-1}},"output":[{"id":355,"damage":7}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":8},"B":{"id":-243,"damage":-1}},"output":[{"id":355,"damage":8}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":9},"B":{"id":-243,"damage":-1}},"output":[{"id":355,"damage":9}],"shape":["AAA","BBB"],"block":"crafting_table","priority":2},{"type":0,"input":[{"id":355,"damage":14},{"id":351}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":5},{"id":351}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":4},{"id":351}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":3},{"id":351}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":2},{"id":351}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":1},{"id":351}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355},{"id":351}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":13},{"id":351}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":12},{"id":351}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":11},{"id":351}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":10},{"id":351}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":9},{"id":351}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":8},{"id":351}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":7},{"id":351}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":6},{"id":351}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":15},{"id":351,"damage":10}],"output":[{"id":355,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":14},{"id":351,"damage":10}],"output":[{"id":355,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":4},{"id":351,"damage":10}],"output":[{"id":355,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":3},{"id":351,"damage":10}],"output":[{"id":355,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":2},{"id":351,"damage":10}],"output":[{"id":355,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":1},{"id":351,"damage":10}],"output":[{"id":355,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355},{"id":351,"damage":10}],"output":[{"id":355,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":13},{"id":351,"damage":10}],"output":[{"id":355,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":12},{"id":351,"damage":10}],"output":[{"id":355,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":11},{"id":351,"damage":10}],"output":[{"id":355,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":10},{"id":351,"damage":10}],"output":[{"id":355,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":9},{"id":351,"damage":10}],"output":[{"id":355,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":8},{"id":351,"damage":10}],"output":[{"id":355,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":7},{"id":351,"damage":10}],"output":[{"id":355,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":6},{"id":351,"damage":10}],"output":[{"id":355,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":15},{"id":351,"damage":11}],"output":[{"id":355,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":14},{"id":351,"damage":11}],"output":[{"id":355,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":5},{"id":351,"damage":11}],"output":[{"id":355,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":3},{"id":351,"damage":11}],"output":[{"id":355,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":2},{"id":351,"damage":11}],"output":[{"id":355,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":1},{"id":351,"damage":11}],"output":[{"id":355,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355},{"id":351,"damage":11}],"output":[{"id":355,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":13},{"id":351,"damage":11}],"output":[{"id":355,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":12},{"id":351,"damage":11}],"output":[{"id":355,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":11},{"id":351,"damage":11}],"output":[{"id":355,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":10},{"id":351,"damage":11}],"output":[{"id":355,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":9},{"id":351,"damage":11}],"output":[{"id":355,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":8},{"id":351,"damage":11}],"output":[{"id":355,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":7},{"id":351,"damage":11}],"output":[{"id":355,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":6},{"id":351,"damage":11}],"output":[{"id":355,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":15},{"id":351,"damage":12}],"output":[{"id":355,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":14},{"id":351,"damage":12}],"output":[{"id":355,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":5},{"id":351,"damage":12}],"output":[{"id":355,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":4},{"id":351,"damage":12}],"output":[{"id":355,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":2},{"id":351,"damage":12}],"output":[{"id":355,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":1},{"id":351,"damage":12}],"output":[{"id":355,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355},{"id":351,"damage":12}],"output":[{"id":355,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":13},{"id":351,"damage":12}],"output":[{"id":355,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":12},{"id":351,"damage":12}],"output":[{"id":355,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":11},{"id":351,"damage":12}],"output":[{"id":355,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":10},{"id":351,"damage":12}],"output":[{"id":355,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":9},{"id":351,"damage":12}],"output":[{"id":355,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":8},{"id":351,"damage":12}],"output":[{"id":355,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":7},{"id":351,"damage":12}],"output":[{"id":355,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":6},{"id":351,"damage":12}],"output":[{"id":355,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":15},{"id":351,"damage":13}],"output":[{"id":355,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":14},{"id":351,"damage":13}],"output":[{"id":355,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":5},{"id":351,"damage":13}],"output":[{"id":355,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":4},{"id":351,"damage":13}],"output":[{"id":355,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":3},{"id":351,"damage":13}],"output":[{"id":355,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":1},{"id":351,"damage":13}],"output":[{"id":355,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355},{"id":351,"damage":13}],"output":[{"id":355,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":13},{"id":351,"damage":13}],"output":[{"id":355,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":12},{"id":351,"damage":13}],"output":[{"id":355,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":11},{"id":351,"damage":13}],"output":[{"id":355,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":10},{"id":351,"damage":13}],"output":[{"id":355,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":9},{"id":351,"damage":13}],"output":[{"id":355,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":8},{"id":351,"damage":13}],"output":[{"id":355,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":7},{"id":351,"damage":13}],"output":[{"id":355,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":6},{"id":351,"damage":13}],"output":[{"id":355,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":15},{"id":351,"damage":14}],"output":[{"id":355,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":14},{"id":351,"damage":14}],"output":[{"id":355,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":5},{"id":351,"damage":14}],"output":[{"id":355,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":4},{"id":351,"damage":14}],"output":[{"id":355,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":3},{"id":351,"damage":14}],"output":[{"id":355,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":2},{"id":351,"damage":14}],"output":[{"id":355,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355},{"id":351,"damage":14}],"output":[{"id":355,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":13},{"id":351,"damage":14}],"output":[{"id":355,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":12},{"id":351,"damage":14}],"output":[{"id":355,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":11},{"id":351,"damage":14}],"output":[{"id":355,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":10},{"id":351,"damage":14}],"output":[{"id":355,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":9},{"id":351,"damage":14}],"output":[{"id":355,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":8},{"id":351,"damage":14}],"output":[{"id":355,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":7},{"id":351,"damage":14}],"output":[{"id":355,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":6},{"id":351,"damage":14}],"output":[{"id":355,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":15},{"id":351,"damage":15}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":14},{"id":351,"damage":15}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":5},{"id":351,"damage":15}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":4},{"id":351,"damage":15}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":3},{"id":351,"damage":15}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":2},{"id":351,"damage":15}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":1},{"id":351,"damage":15}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":13},{"id":351,"damage":15}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":12},{"id":351,"damage":15}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":11},{"id":351,"damage":15}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":10},{"id":351,"damage":15}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":9},{"id":351,"damage":15}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":8},{"id":351,"damage":15}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":7},{"id":351,"damage":15}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":6},{"id":351,"damage":15}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":14},{"id":351,"damage":16}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":5},{"id":351,"damage":16}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":4},{"id":351,"damage":16}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":3},{"id":351,"damage":16}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":2},{"id":351,"damage":16}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":1},{"id":351,"damage":16}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355},{"id":351,"damage":16}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":13},{"id":351,"damage":16}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":12},{"id":351,"damage":16}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":11},{"id":351,"damage":16}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":10},{"id":351,"damage":16}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":9},{"id":351,"damage":16}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":8},{"id":351,"damage":16}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":7},{"id":351,"damage":16}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":6},{"id":351,"damage":16}],"output":[{"id":355,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":15},{"id":351,"damage":17}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":14},{"id":351,"damage":17}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":5},{"id":351,"damage":17}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":4},{"id":351,"damage":17}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":3},{"id":351,"damage":17}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":2},{"id":351,"damage":17}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":1},{"id":351,"damage":17}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355},{"id":351,"damage":17}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":13},{"id":351,"damage":17}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":11},{"id":351,"damage":17}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":10},{"id":351,"damage":17}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":9},{"id":351,"damage":17}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":8},{"id":351,"damage":17}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":7},{"id":351,"damage":17}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":6},{"id":351,"damage":17}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":15},{"id":351,"damage":18}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":14},{"id":351,"damage":18}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":5},{"id":351,"damage":18}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":4},{"id":351,"damage":18}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":3},{"id":351,"damage":18}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":2},{"id":351,"damage":18}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":1},{"id":351,"damage":18}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355},{"id":351,"damage":18}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":13},{"id":351,"damage":18}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":12},{"id":351,"damage":18}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":10},{"id":351,"damage":18}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":9},{"id":351,"damage":18}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":8},{"id":351,"damage":18}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":7},{"id":351,"damage":18}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":6},{"id":351,"damage":18}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":15},{"id":351,"damage":19}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":14},{"id":351,"damage":19}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":5},{"id":351,"damage":19}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":4},{"id":351,"damage":19}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":3},{"id":351,"damage":19}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":2},{"id":351,"damage":19}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":1},{"id":351,"damage":19}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":13},{"id":351,"damage":19}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":12},{"id":351,"damage":19}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":11},{"id":351,"damage":19}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":10},{"id":351,"damage":19}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":9},{"id":351,"damage":19}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":8},{"id":351,"damage":19}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":7},{"id":351,"damage":19}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":6},{"id":351,"damage":19}],"output":[{"id":355}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":15},{"id":351,"damage":1}],"output":[{"id":355,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":5},{"id":351,"damage":1}],"output":[{"id":355,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":4},{"id":351,"damage":1}],"output":[{"id":355,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":3},{"id":351,"damage":1}],"output":[{"id":355,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":2},{"id":351,"damage":1}],"output":[{"id":355,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":1},{"id":351,"damage":1}],"output":[{"id":355,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355},{"id":351,"damage":1}],"output":[{"id":355,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":13},{"id":351,"damage":1}],"output":[{"id":355,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":12},{"id":351,"damage":1}],"output":[{"id":355,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":11},{"id":351,"damage":1}],"output":[{"id":355,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":10},{"id":351,"damage":1}],"output":[{"id":355,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":9},{"id":351,"damage":1}],"output":[{"id":355,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":8},{"id":351,"damage":1}],"output":[{"id":355,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":7},{"id":351,"damage":1}],"output":[{"id":355,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":6},{"id":351,"damage":1}],"output":[{"id":355,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":15},{"id":351,"damage":2}],"output":[{"id":355,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":14},{"id":351,"damage":2}],"output":[{"id":355,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":5},{"id":351,"damage":2}],"output":[{"id":355,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":4},{"id":351,"damage":2}],"output":[{"id":355,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":3},{"id":351,"damage":2}],"output":[{"id":355,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":2},{"id":351,"damage":2}],"output":[{"id":355,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":1},{"id":351,"damage":2}],"output":[{"id":355,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355},{"id":351,"damage":2}],"output":[{"id":355,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":12},{"id":351,"damage":2}],"output":[{"id":355,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":11},{"id":351,"damage":2}],"output":[{"id":355,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":10},{"id":351,"damage":2}],"output":[{"id":355,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":9},{"id":351,"damage":2}],"output":[{"id":355,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":8},{"id":351,"damage":2}],"output":[{"id":355,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":7},{"id":351,"damage":2}],"output":[{"id":355,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":6},{"id":351,"damage":2}],"output":[{"id":355,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":15},{"id":351,"damage":3}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":14},{"id":351,"damage":3}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":5},{"id":351,"damage":3}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":4},{"id":351,"damage":3}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":3},{"id":351,"damage":3}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":2},{"id":351,"damage":3}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":1},{"id":351,"damage":3}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355},{"id":351,"damage":3}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":13},{"id":351,"damage":3}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":11},{"id":351,"damage":3}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":10},{"id":351,"damage":3}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":9},{"id":351,"damage":3}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":8},{"id":351,"damage":3}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":7},{"id":351,"damage":3}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":6},{"id":351,"damage":3}],"output":[{"id":355,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":15},{"id":351,"damage":4}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":14},{"id":351,"damage":4}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":5},{"id":351,"damage":4}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":4},{"id":351,"damage":4}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":3},{"id":351,"damage":4}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":2},{"id":351,"damage":4}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":1},{"id":351,"damage":4}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355},{"id":351,"damage":4}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":13},{"id":351,"damage":4}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":12},{"id":351,"damage":4}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":10},{"id":351,"damage":4}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":9},{"id":351,"damage":4}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":8},{"id":351,"damage":4}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":7},{"id":351,"damage":4}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":6},{"id":351,"damage":4}],"output":[{"id":355,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":15},{"id":351,"damage":5}],"output":[{"id":355,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":14},{"id":351,"damage":5}],"output":[{"id":355,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":5},{"id":351,"damage":5}],"output":[{"id":355,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":4},{"id":351,"damage":5}],"output":[{"id":355,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":3},{"id":351,"damage":5}],"output":[{"id":355,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":2},{"id":351,"damage":5}],"output":[{"id":355,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":1},{"id":351,"damage":5}],"output":[{"id":355,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355},{"id":351,"damage":5}],"output":[{"id":355,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":13},{"id":351,"damage":5}],"output":[{"id":355,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":12},{"id":351,"damage":5}],"output":[{"id":355,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":11},{"id":351,"damage":5}],"output":[{"id":355,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":9},{"id":351,"damage":5}],"output":[{"id":355,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":8},{"id":351,"damage":5}],"output":[{"id":355,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":7},{"id":351,"damage":5}],"output":[{"id":355,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":6},{"id":351,"damage":5}],"output":[{"id":355,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":15},{"id":351,"damage":6}],"output":[{"id":355,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":14},{"id":351,"damage":6}],"output":[{"id":355,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":5},{"id":351,"damage":6}],"output":[{"id":355,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":4},{"id":351,"damage":6}],"output":[{"id":355,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":3},{"id":351,"damage":6}],"output":[{"id":355,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":2},{"id":351,"damage":6}],"output":[{"id":355,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":1},{"id":351,"damage":6}],"output":[{"id":355,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355},{"id":351,"damage":6}],"output":[{"id":355,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":13},{"id":351,"damage":6}],"output":[{"id":355,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":12},{"id":351,"damage":6}],"output":[{"id":355,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":11},{"id":351,"damage":6}],"output":[{"id":355,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":10},{"id":351,"damage":6}],"output":[{"id":355,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":8},{"id":351,"damage":6}],"output":[{"id":355,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":7},{"id":351,"damage":6}],"output":[{"id":355,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":6},{"id":351,"damage":6}],"output":[{"id":355,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":15},{"id":351,"damage":7}],"output":[{"id":355,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":14},{"id":351,"damage":7}],"output":[{"id":355,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":5},{"id":351,"damage":7}],"output":[{"id":355,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":4},{"id":351,"damage":7}],"output":[{"id":355,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":3},{"id":351,"damage":7}],"output":[{"id":355,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":2},{"id":351,"damage":7}],"output":[{"id":355,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":1},{"id":351,"damage":7}],"output":[{"id":355,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355},{"id":351,"damage":7}],"output":[{"id":355,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":13},{"id":351,"damage":7}],"output":[{"id":355,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":12},{"id":351,"damage":7}],"output":[{"id":355,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":11},{"id":351,"damage":7}],"output":[{"id":355,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":10},{"id":351,"damage":7}],"output":[{"id":355,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":9},{"id":351,"damage":7}],"output":[{"id":355,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":7},{"id":351,"damage":7}],"output":[{"id":355,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":6},{"id":351,"damage":7}],"output":[{"id":355,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":15},{"id":351,"damage":8}],"output":[{"id":355,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":14},{"id":351,"damage":8}],"output":[{"id":355,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":5},{"id":351,"damage":8}],"output":[{"id":355,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":4},{"id":351,"damage":8}],"output":[{"id":355,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":3},{"id":351,"damage":8}],"output":[{"id":355,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":2},{"id":351,"damage":8}],"output":[{"id":355,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":1},{"id":351,"damage":8}],"output":[{"id":355,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355},{"id":351,"damage":8}],"output":[{"id":355,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":13},{"id":351,"damage":8}],"output":[{"id":355,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":12},{"id":351,"damage":8}],"output":[{"id":355,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":11},{"id":351,"damage":8}],"output":[{"id":355,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":10},{"id":351,"damage":8}],"output":[{"id":355,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":9},{"id":351,"damage":8}],"output":[{"id":355,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":8},{"id":351,"damage":8}],"output":[{"id":355,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":6},{"id":351,"damage":8}],"output":[{"id":355,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":15},{"id":351,"damage":9}],"output":[{"id":355,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":14},{"id":351,"damage":9}],"output":[{"id":355,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":5},{"id":351,"damage":9}],"output":[{"id":355,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":4},{"id":351,"damage":9}],"output":[{"id":355,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":3},{"id":351,"damage":9}],"output":[{"id":355,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":2},{"id":351,"damage":9}],"output":[{"id":355,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":1},{"id":351,"damage":9}],"output":[{"id":355,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355},{"id":351,"damage":9}],"output":[{"id":355,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":13},{"id":351,"damage":9}],"output":[{"id":355,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":12},{"id":351,"damage":9}],"output":[{"id":355,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":11},{"id":351,"damage":9}],"output":[{"id":355,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":10},{"id":351,"damage":9}],"output":[{"id":355,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":9},{"id":351,"damage":9}],"output":[{"id":355,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":8},{"id":351,"damage":9}],"output":[{"id":355,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":355,"damage":7},{"id":351,"damage":9}],"output":[{"id":355,"damage":6}],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":2}},"output":[{"id":135,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":50},{"type":4,"uuid":"d1ca6b84-338e-4f2f-9c6b-76cc8b4bd98d"},{"type":1,"input":{"A":{"id":44,"damage":6}},"output":[{"id":155,"damage":1}],"shape":["A","A"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":44,"damage":5}},"output":[{"id":98,"damage":3}],"shape":["A","A"],"block":"crafting_table","priority":50},{"type":4,"uuid":"85939755-ba10-4d9d-a4cc-efb7a8e943c4"},{"type":1,"input":{"A":{"id":5,"damage":5}},"output":[{"id":164,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":50},{"type":4,"uuid":"d392b075-4ba1-40ae-8789-af868d56f6ce"},{"type":1,"input":{"A":{"id":182}},"output":[{"id":179,"damage":1}],"shape":["A","A"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":44,"damage":1}},"output":[{"id":24,"damage":1}],"shape":["A","A"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":3}},"output":[{"id":136,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":182,"damage":1}},"output":[{"id":201,"damage":2}],"shape":["A","A"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":287,"damage":-1},"B":{"id":5,"damage":-1}},"output":[{"id":-204}],"shape":["AA","BB"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":4},"B":{"id":269,"damage":-1}},"output":[{"id":333,"damage":4}],"shape":["ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":4}},"output":[{"id":430,"count":3}],"shape":["AA","AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":4},"B":{"id":280,"damage":-1}},"output":[{"id":85,"damage":4,"count":3}],"shape":["ABA","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":5,"damage":4}},"output":[{"id":187}],"shape":["ABA","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":162}},"output":[{"id":5,"damage":4,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-8,"damage":-1}},"output":[{"id":5,"damage":4,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-212,"damage":12}},"output":[{"id":5,"damage":4,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-212,"damage":4}},"output":[{"id":5,"damage":4,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":4}},"output":[{"id":163,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":162}},"output":[{"id":-212,"damage":4,"count":3}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-8,"damage":-1}},"output":[{"id":-212,"damage":12,"count":3}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":4}},"output":[{"id":158,"damage":4,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1},"B":{"id":280,"damage":-1},"C":{"id":76,"damage":-1}},"output":[{"id":126,"count":6}],"shape":["ABA","ACA","ABA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":1,"damage":3},{"id":4,"damage":-1}],"output":[{"id":1,"damage":5,"count":2}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":1,"damage":5}},"output":[{"id":-171,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":1,"damage":5}},"output":[{"id":139,"damage":4,"count":6}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":42,"damage":-1},"B":{"id":265,"damage":-1}},"output":[{"id":145}],"shape":["AAA"," B ","BBB"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":44}},"output":[{"id":425}],"shape":["AAA"," A ","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":318,"damage":-1},"B":{"id":280,"damage":-1},"C":{"id":288,"damage":-1}},"output":[{"id":262,"count":4}],"shape":["A","B","C"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":339,"damage":-1},{"id":45,"damage":-1}],"output":[{"id":434,"damage":4}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":339,"damage":-1},{"id":397,"damage":4}],"output":[{"id":434}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":339,"damage":-1},{"id":38,"damage":8}],"output":[{"id":434,"damage":2}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":339,"damage":-1},{"id":397,"damage":1}],"output":[{"id":434,"damage":1}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":339,"damage":-1},{"id":466,"damage":-1}],"output":[{"id":434,"damage":3}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":339,"damage":-1},{"id":106,"damage":-1}],"output":[{"id":434,"damage":5}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":158,"damage":-1}},"output":[{"id":-203}],"shape":["ABA","A A","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-264,"damage":-1}},"output":[{"id":-203}],"shape":["ABA","A A","ABA"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-265,"damage":-1}},"output":[{"id":-203}],"shape":["ABA","A A","ABA"],"block":"crafting_table","priority":2},{"type":0,"input":[{"id":395,"damage":1},{"id":345,"damage":-1}],"output":[{"id":395,"damage":2}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":399,"damage":-1},"C":{"id":49,"damage":-1}},"output":[{"id":138}],"shape":["AAA","ABA","CCC"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":-1},"B":{"id":736,"damage":-1}},"output":[{"id":-219}],"shape":["AAA","BBB","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-242,"damage":-1},"B":{"id":736,"damage":-1}},"output":[{"id":-219}],"shape":["AAA","BBB","AAA"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-243,"damage":-1},"B":{"id":736,"damage":-1}},"output":[{"id":-219}],"shape":["AAA","BBB","AAA"],"block":"crafting_table","priority":2},{"type":0,"input":[{"id":281,"damage":-1},{"id":457,"damage":-1},{"id":457,"damage":-1},{"id":457,"damage":-1},{"id":457,"damage":-1},{"id":457,"damage":-1},{"id":457,"damage":-1}],"output":[{"id":459}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":2},"B":{"id":269,"damage":-1}},"output":[{"id":333,"damage":2}],"shape":["ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":2}},"output":[{"id":428,"count":3}],"shape":["AA","AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":2},"B":{"id":280,"damage":-1}},"output":[{"id":85,"damage":2,"count":3}],"shape":["ABA","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":5,"damage":2}},"output":[{"id":184}],"shape":["ABA","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":17,"damage":2}},"output":[{"id":5,"damage":2,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-6,"damage":-1}},"output":[{"id":5,"damage":2,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-212,"damage":10}},"output":[{"id":5,"damage":2,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-212,"damage":2}},"output":[{"id":5,"damage":2,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":2}},"output":[{"id":135,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":17,"damage":2}},"output":[{"id":-212,"damage":2,"count":3}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-6,"damage":-1}},"output":[{"id":-212,"damage":10,"count":3}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":2}},"output":[{"id":158,"damage":2,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":15},"B":{"id":280,"damage":-1}},"output":[{"id":446}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":15}},"output":[{"id":171,"damage":15,"count":3}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":171},"B":{"id":351,"damage":16}},"output":[{"id":171,"damage":15,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":1},{"type":0,"input":[{"id":351,"damage":16},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"damage":15,"count":8}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"damage":15,"count":8}],"block":"crafting_table","priority":1},{"type":0,"input":[{"id":351}],"output":[{"id":351,"damage":16}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":-216,"damage":-1}],"output":[{"id":351,"damage":16}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351,"damage":16}},"output":[{"id":241,"damage":15,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351}},"output":[{"id":241,"damage":15,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":241,"damage":15}},"output":[{"id":160,"damage":15,"count":16}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":102,"damage":-1},"B":{"id":351,"damage":16}},"output":[{"id":160,"damage":15,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351,"damage":16}},"output":[{"id":159,"damage":15,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351}},"output":[{"id":159,"damage":15,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":-273,"damage":-1}},"output":[{"id":-282,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-273,"damage":-1}},"output":[{"id":-276,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-273,"damage":-1}},"output":[{"id":-277,"count":6}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1},"B":{"id":61,"damage":-1},"C":{"id":-183,"damage":-1}},"output":[{"id":-196}],"shape":["AAA","ABA","CCC"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":369,"damage":-1}],"output":[{"id":377,"count":2}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":11},"B":{"id":280,"damage":-1}},"output":[{"id":446,"damage":4}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":11}},"output":[{"id":171,"damage":11,"count":3}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":171},"B":{"id":351,"damage":18}},"output":[{"id":171,"damage":11,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":18},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"damage":11,"count":8}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":4},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"damage":11,"count":8}],"block":"crafting_table","priority":1},{"type":0,"input":[{"id":38,"damage":9}],"output":[{"id":351,"damage":18}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":4}],"output":[{"id":351,"damage":18}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":174,"damage":-1}},"output":[{"id":-11}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351,"damage":18}},"output":[{"id":241,"damage":11,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351,"damage":4}},"output":[{"id":241,"damage":11,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":241,"damage":11}},"output":[{"id":160,"damage":11,"count":16}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":102,"damage":-1},"B":{"id":351,"damage":18}},"output":[{"id":160,"damage":11,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351,"damage":18}},"output":[{"id":159,"damage":11,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351,"damage":4}},"output":[{"id":159,"damage":11,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":5},"B":{"id":269,"damage":-1}},"output":[{"id":333}],"shape":["ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":351,"damage":15}},"output":[{"id":216}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":216,"damage":-1}],"output":[{"id":351,"damage":15,"count":9}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":352,"damage":-1}],"output":[{"id":351,"damage":15,"count":3}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":339},{"id":339},{"id":339},{"id":334}],"output":[{"id":340}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-242,"damage":-1},"B":{"id":340,"damage":-1}},"output":[{"id":47}],"shape":["AAA","BBB","AAA"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-243,"damage":-1},"B":{"id":340,"damage":-1}},"output":[{"id":47}],"shape":["AAA","BBB","AAA"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":287,"damage":-1}},"output":[{"id":261}],"shape":[" AB","A B"," AB"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-242,"damage":-1}},"output":[{"id":281,"count":4}],"shape":["A A"," A "],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-243,"damage":-1}},"output":[{"id":281,"count":4}],"shape":["A A"," A "],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":296,"damage":-1}},"output":[{"id":297}],"shape":["AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":369,"damage":-1},"B":{"id":4,"damage":-1}},"output":[{"id":379}],"shape":[" A ","BBB"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":336,"damage":-1}},"output":[{"id":45}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":45,"damage":-1}},"output":[{"id":108,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":45,"damage":-1}},"output":[{"id":139,"damage":6,"count":6}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":12},"B":{"id":280,"damage":-1}},"output":[{"id":446,"damage":3}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":12}},"output":[{"id":171,"damage":12,"count":3}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":171},"B":{"id":351,"damage":17}},"output":[{"id":171,"damage":12,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":17},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"damage":12,"count":8}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":3},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"damage":12,"count":8}],"block":"crafting_table","priority":1},{"type":0,"input":[{"id":351,"damage":3}],"output":[{"id":351,"damage":17}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351,"damage":17}},"output":[{"id":241,"damage":12,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351,"damage":3}},"output":[{"id":241,"damage":12,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":241,"damage":12}},"output":[{"id":160,"damage":12,"count":16}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":102,"damage":-1},"B":{"id":351,"damage":17}},"output":[{"id":160,"damage":12,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351,"damage":17}},"output":[{"id":159,"damage":12,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351,"damage":3}},"output":[{"id":159,"damage":12,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":265,"damage":-1}},"output":[{"id":325}],"shape":["A A"," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":325,"damage":1},"B":{"id":353,"damage":-1},"C":{"id":344,"damage":-1},"D":{"id":296,"damage":-1}},"output":[{"id":354},{"id":325,"count":3}],"shape":["AAA","BCB","DDD"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":263,"damage":-1},"C":{"id":17,"damage":-1}},"output":[{"id":720}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":263,"damage":1},"C":{"id":17,"damage":-1}},"output":[{"id":720}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":263,"damage":-1},"C":{"id":-225,"damage":-1}},"output":[{"id":720}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":263,"damage":-1},"C":{"id":162,"damage":-1}},"output":[{"id":720}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":263,"damage":-1},"C":{"id":-8,"damage":-1}},"output":[{"id":720}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":263,"damage":-1},"C":{"id":-6,"damage":-1}},"output":[{"id":720}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":263,"damage":-1},"C":{"id":-240,"damage":-1}},"output":[{"id":720}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":263,"damage":-1},"C":{"id":-9,"damage":-1}},"output":[{"id":720}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":263,"damage":-1},"C":{"id":-7,"damage":-1}},"output":[{"id":720}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":263,"damage":-1},"C":{"id":-10,"damage":-1}},"output":[{"id":720}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":263,"damage":-1},"C":{"id":-5,"damage":-1}},"output":[{"id":720}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":263,"damage":-1},"C":{"id":-241,"damage":-1}},"output":[{"id":720}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":263,"damage":-1},"C":{"id":-226,"damage":-1}},"output":[{"id":720}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":263,"damage":-1},"C":{"id":-212,"damage":-1}},"output":[{"id":720}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":346,"damage":-1},"B":{"id":391,"damage":-1}},"output":[{"id":398}],"shape":["A "," B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":339,"damage":-1},"B":{"id":5,"damage":-1}},"output":[{"id":-200}],"shape":["AA","BB","BB"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":339,"damage":-1},"B":{"id":-242,"damage":-1}},"output":[{"id":-200}],"shape":["AA","BB","BB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":339,"damage":-1},"B":{"id":-243,"damage":-1}},"output":[{"id":-200}],"shape":["AA","BB","BB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":265,"damage":-1}},"output":[{"id":380}],"shape":["A A","A A","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":452,"damage":-1},"B":{"id":265,"damage":-1}},"output":[{"id":758}],"shape":["A","B","A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-242,"damage":-1}},"output":[{"id":54}],"shape":["AAA","A A","AAA"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-243,"damage":-1}},"output":[{"id":54}],"shape":["AAA","A A","AAA"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":54,"damage":-1},"B":{"id":328,"damage":-1}},"output":[{"id":342}],"shape":["A","B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":44,"damage":7}},"output":[{"id":-302}],"shape":["A","A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-293,"damage":-1}},"output":[{"id":-279}],"shape":["A","A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":337,"damage":-1}},"output":[{"id":82}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":266,"damage":-1},"B":{"id":331,"damage":-1}},"output":[{"id":347}],"shape":[" A ","ABA"," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":173,"damage":-1}},"output":[{"id":263,"count":9}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":263}},"output":[{"id":173}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":3},"B":{"id":13,"damage":-1}},"output":[{"id":3,"damage":1,"count":4}],"shape":["AB","BA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":4,"damage":-1}},"output":[{"id":67,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":4,"damage":-1}},"output":[{"id":139,"count":6}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":30,"damage":-1}],"output":[{"id":287,"count":9}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":76,"damage":-1},"B":{"id":406,"damage":-1},"C":{"id":1}},"output":[{"id":404}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1},"B":{"id":331,"damage":-1}},"output":[{"id":345}],"shape":[" A ","ABA"," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":158,"damage":-1}},"output":[{"id":-213}],"shape":["A A","A A","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-264,"damage":-1}},"output":[{"id":-213}],"shape":["A A","A A","AAA"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-265,"damage":-1}},"output":[{"id":-213}],"shape":["A A","A A","AAA"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":465,"damage":-1},"B":{"id":467,"damage":-1}},"output":[{"id":-157}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":296,"damage":-1},"B":{"id":351,"damage":3}},"output":[{"id":357,"count":8}],"shape":["ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-242,"damage":-1}},"output":[{"id":58}],"shape":["AA","AA"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-243,"damage":-1}},"output":[{"id":58}],"shape":["AA","AA"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-242,"damage":-1}},"output":[{"id":-260}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-242,"damage":-1}},"output":[{"id":755,"count":3}],"shape":["AA","AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-242,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":-256,"count":3}],"shape":["ABA","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-242,"damage":-1}},"output":[{"id":-258}],"shape":["ABA","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-225,"damage":-1}},"output":[{"id":-299,"count":3}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-225,"damage":-1}},"output":[{"id":-242,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-299,"damage":-1}},"output":[{"id":-242,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-300,"damage":-1}},"output":[{"id":-242,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-240,"damage":-1}},"output":[{"id":-242,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-242,"damage":-1}},"output":[{"id":-262}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-242,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":753,"count":3}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-242,"damage":-1}},"output":[{"id":-264,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-242,"damage":-1}},"output":[{"id":-254,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-242,"damage":-1}},"output":[{"id":-246,"count":2}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":265,"damage":-1},"C":{"id":287,"damage":-1},"D":{"id":131,"damage":-1}},"output":[{"id":471}],"shape":["ABA","CDC"," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":9},"B":{"id":280,"damage":-1}},"output":[{"id":446,"damage":6}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":9}},"output":[{"id":171,"damage":9,"count":3}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":171},"B":{"id":351,"damage":6}},"output":[{"id":171,"damage":9,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":6},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"damage":9,"count":8}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":18},{"id":351,"damage":2}],"output":[{"id":351,"damage":6,"count":2}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":4},{"id":351,"damage":2}],"output":[{"id":351,"damage":6,"count":2}],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351,"damage":6}},"output":[{"id":241,"damage":9,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":241,"damage":9}},"output":[{"id":160,"damage":9,"count":16}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":102,"damage":-1},"B":{"id":351,"damage":6}},"output":[{"id":160,"damage":9,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351,"damage":6}},"output":[{"id":159,"damage":9,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":5},"B":{"id":269,"damage":-1}},"output":[{"id":333,"damage":5}],"shape":["ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":5}},"output":[{"id":431,"count":3}],"shape":["AA","AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":5},"B":{"id":280,"damage":-1}},"output":[{"id":85,"damage":5,"count":3}],"shape":["ABA","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":5,"damage":5}},"output":[{"id":186}],"shape":["ABA","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":162,"damage":1}},"output":[{"id":5,"damage":5,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-9,"damage":-1}},"output":[{"id":5,"damage":5,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-212,"damage":13}},"output":[{"id":5,"damage":5,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-212,"damage":5}},"output":[{"id":5,"damage":5,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":5}},"output":[{"id":164,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":162,"damage":1}},"output":[{"id":-212,"damage":5,"count":3}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-9,"damage":-1}},"output":[{"id":-212,"damage":13,"count":3}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":5}},"output":[{"id":158,"damage":5,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":409,"damage":-1},"B":{"id":351,"damage":16}},"output":[{"id":168,"damage":1}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":409,"damage":-1},"B":{"id":351}},"output":[{"id":168,"damage":1}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":406,"damage":-1},"C":{"id":-264,"damage":-1}},"output":[{"id":151}],"shape":["AAA","BBB","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":406,"damage":-1},"C":{"id":-265,"damage":-1}},"output":[{"id":151}],"shape":["AAA","BBB","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":265,"damage":-1},"B":{"id":70,"damage":-1},"C":{"id":331,"damage":-1}},"output":[{"id":28,"count":6}],"shape":["A A","ABA","ACA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":57,"damage":-1}},"output":[{"id":264,"count":9}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":264,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":279}],"shape":["AA","AB"," B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":264,"damage":-1}},"output":[{"id":57}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":264,"damage":-1}},"output":[{"id":313}],"shape":["A A","A A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":264,"damage":-1}},"output":[{"id":311}],"shape":["A A","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":264,"damage":-1}},"output":[{"id":310}],"shape":["AAA","A A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":264,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":293}],"shape":["AA"," B"," B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":264,"damage":-1}},"output":[{"id":312}],"shape":["AAA","A A","A A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":264,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":278}],"shape":["AAA"," B "," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":264,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":277}],"shape":["A","B","B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":264,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":276}],"shape":["A","A","B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":4,"damage":-1},"B":{"id":406,"damage":-1}},"output":[{"id":1,"damage":3,"count":2}],"shape":["AB","BA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":1,"damage":3}},"output":[{"id":-170,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":1,"damage":3}},"output":[{"id":139,"damage":3,"count":6}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":4,"damage":-1},"B":{"id":261,"damage":-1},"C":{"id":331,"damage":-1}},"output":[{"id":23,"damage":3}],"shape":["AAA","ABA","ACA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-139,"damage":-1}},"output":[{"id":464,"count":9}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":464,"damage":-1}},"output":[{"id":-139}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":4,"damage":-1},"B":{"id":331,"damage":-1}},"output":[{"id":125,"damage":3}],"shape":["AAA","A A","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":133,"damage":-1}},"output":[{"id":388,"count":9}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":388,"damage":-1}},"output":[{"id":133}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":395},{"id":345,"damage":-1}],"output":[{"id":395,"damage":2}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":340,"damage":-1},"B":{"id":264,"damage":-1},"C":{"id":49,"damage":-1}},"output":[{"id":116}],"shape":[" A ","BCB","CCC"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":206,"damage":-1}},"output":[{"id":-178,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":206,"damage":-1}},"output":[{"id":139,"damage":10,"count":6}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":121,"damage":-1}},"output":[{"id":206,"count":4}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":381,"damage":-1},"C":{"id":370,"damage":-1}},"output":[{"id":426}],"shape":["AAA","ABA","ACA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":369,"damage":-1},"B":{"id":433,"damage":-1}},"output":[{"id":208,"count":4}],"shape":["A","B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":49,"damage":-1},"B":{"id":381,"damage":-1}},"output":[{"id":130}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":368,"damage":-1},{"id":377,"damage":-1}],"output":[{"id":381}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5},"B":{"id":280,"damage":-1}},"output":[{"id":85,"count":3}],"shape":["ABA","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":5}},"output":[{"id":107}],"shape":["ABA","ABA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":375,"damage":-1},{"id":39,"damage":-1},{"id":353,"damage":-1}],"output":[{"id":376}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":287,"damage":-1}},"output":[{"id":346}],"shape":[" A"," AB","A B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":318,"damage":-1},"B":{"id":5,"damage":-1}},"output":[{"id":-201}],"shape":["AA","BB","BB"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":318,"damage":-1},"B":{"id":-242,"damage":-1}},"output":[{"id":-201}],"shape":["AA","BB","BB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":318,"damage":-1},"B":{"id":-243,"damage":-1}},"output":[{"id":-201}],"shape":["AA","BB","BB"],"block":"crafting_table","priority":2},{"type":0,"input":[{"id":265,"damage":-1},{"id":318,"damage":-1}],"output":[{"id":259}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":336,"damage":-1}},"output":[{"id":390}],"shape":["A A"," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":4,"damage":-1}},"output":[{"id":61}],"shape":["AAA","A A","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-273,"damage":-1}},"output":[{"id":61}],"shape":["AAA","A A","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":20,"damage":-1}},"output":[{"id":374,"count":3}],"shape":["A A"," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":20,"damage":-1}},"output":[{"id":102,"count":16}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":348,"damage":-1}},"output":[{"id":89}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":266,"damage":-1}},"output":[{"id":41}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":41,"damage":-1}},"output":[{"id":266,"count":9}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":371,"damage":-1}},"output":[{"id":266}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":266,"damage":-1}},"output":[{"id":371,"count":9}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":266,"damage":-1},"B":{"id":260,"damage":-1}},"output":[{"id":322}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":266,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":286}],"shape":["AA","AB"," B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":266,"damage":-1}},"output":[{"id":317}],"shape":["A A","A A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":371,"damage":-1},"B":{"id":391,"damage":-1}},"output":[{"id":396}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":266,"damage":-1}},"output":[{"id":315}],"shape":["A A","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":266,"damage":-1}},"output":[{"id":314}],"shape":["AAA","A A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":266,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":294}],"shape":["AA"," B"," B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":266,"damage":-1}},"output":[{"id":316}],"shape":["AAA","A A","A A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":266,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":285}],"shape":["AAA"," B "," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":266,"damage":-1},"B":{"id":280,"damage":-1},"C":{"id":331,"damage":-1}},"output":[{"id":27,"count":6}],"shape":["A A","ABA","ACA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":266,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":284}],"shape":["A","B","B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":266,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":283}],"shape":["A","A","B"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":1,"damage":3},{"id":406,"damage":-1}],"output":[{"id":1,"damage":1}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":1,"damage":1}},"output":[{"id":-169,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":1,"damage":1}},"output":[{"id":139,"damage":2,"count":6}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":7},"B":{"id":280,"damage":-1}},"output":[{"id":446,"damage":8}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":7}},"output":[{"id":171,"damage":7,"count":3}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":171},"B":{"id":351,"damage":8}},"output":[{"id":171,"damage":7,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":8},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"damage":7,"count":8}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":16},{"id":351,"damage":19}],"output":[{"id":351,"damage":8,"count":2}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":16},{"id":351,"damage":15}],"output":[{"id":351,"damage":8,"count":2}],"block":"crafting_table","priority":1},{"type":0,"input":[{"id":351},{"id":351,"damage":15}],"output":[{"id":351,"damage":8,"count":2}],"block":"crafting_table","priority":3},{"type":0,"input":[{"id":351},{"id":351,"damage":19}],"output":[{"id":351,"damage":8,"count":2}],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351,"damage":8}},"output":[{"id":241,"damage":7,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":241,"damage":7}},"output":[{"id":160,"damage":7,"count":16}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":102,"damage":-1},"B":{"id":351,"damage":8}},"output":[{"id":160,"damage":7,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351,"damage":8}},"output":[{"id":159,"damage":7,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":13},"B":{"id":280,"damage":-1}},"output":[{"id":446,"damage":2}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":13}},"output":[{"id":171,"damage":13,"count":3}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":171},"B":{"id":351,"damage":2}},"output":[{"id":171,"damage":13,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":2},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"damage":13,"count":8}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351,"damage":2}},"output":[{"id":241,"damage":13,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":241,"damage":13}},"output":[{"id":160,"damage":13,"count":16}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":102,"damage":-1},"B":{"id":351,"damage":2}},"output":[{"id":160,"damage":13,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351,"damage":2}},"output":[{"id":159,"damage":13,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-166,"damage":2},"C":{"id":5,"damage":-1}},"output":[{"id":-195}],"shape":["ABA","C C"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":44,"damage":-1},"C":{"id":-242,"damage":-1}},"output":[{"id":-195}],"shape":["ABA","C C"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":182,"damage":-1},"C":{"id":-242,"damage":-1}},"output":[{"id":-195}],"shape":["ABA","C C"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-162,"damage":-1},"C":{"id":-242,"damage":-1}},"output":[{"id":-195}],"shape":["ABA","C C"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-166,"damage":-1},"C":{"id":-242,"damage":-1}},"output":[{"id":-195}],"shape":["ABA","C C"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":44,"damage":-1},"C":{"id":-243,"damage":-1}},"output":[{"id":-195}],"shape":["ABA","C C"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":182,"damage":-1},"C":{"id":-243,"damage":-1}},"output":[{"id":-195}],"shape":["ABA","C C"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-162,"damage":-1},"C":{"id":-243,"damage":-1}},"output":[{"id":-195}],"shape":["ABA","C C"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-166,"damage":-1},"C":{"id":-243,"damage":-1}},"output":[{"id":-195}],"shape":["ABA","C C"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":296,"damage":-1}},"output":[{"id":170}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1}},"output":[{"id":148}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":737,"damage":-1}},"output":[{"id":-220},{"id":374,"count":4}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":-220,"damage":-1},{"id":374,"damage":-1},{"id":374,"damage":-1},{"id":374,"damage":-1},{"id":374,"damage":-1}],"output":[{"id":737,"count":4}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":737,"damage":-1}},"output":[{"id":353,"count":3},{"id":374}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":736,"damage":-1}},"output":[{"id":-221}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1},"B":{"id":54,"damage":-1}},"output":[{"id":410}],"shape":["A A","ABA"," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":410,"damage":-1},"B":{"id":328,"damage":-1}},"output":[{"id":408}],"shape":["A","B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":258}],"shape":["AA","AB"," B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1}},"output":[{"id":101,"count":16}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1}},"output":[{"id":42}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1}},"output":[{"id":309}],"shape":["A A","A A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1}},"output":[{"id":307}],"shape":["A A","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1}},"output":[{"id":330,"count":3}],"shape":["AA","AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1}},"output":[{"id":306}],"shape":["AAA","A A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":292}],"shape":["AA"," B"," B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":42,"damage":-1}},"output":[{"id":265,"count":9}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":452,"damage":-1}},"output":[{"id":265}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1}},"output":[{"id":308}],"shape":["AAA","A A","A A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1}},"output":[{"id":452,"count":9}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":257}],"shape":["AAA"," B "," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":256}],"shape":["A","B","B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":267}],"shape":["A","A","B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1}},"output":[{"id":167}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":334,"damage":-1}},"output":[{"id":389}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-242,"damage":-1},"B":{"id":264,"damage":-1}},"output":[{"id":84}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-243,"damage":-1},"B":{"id":264,"damage":-1}},"output":[{"id":84}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":5,"damage":3},"B":{"id":269,"damage":-1}},"output":[{"id":333,"damage":3}],"shape":["ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":3}},"output":[{"id":429,"count":3}],"shape":["AA","AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":3},"B":{"id":280,"damage":-1}},"output":[{"id":85,"damage":3,"count":3}],"shape":["ABA","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":5,"damage":3}},"output":[{"id":185}],"shape":["ABA","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":17,"damage":3}},"output":[{"id":5,"damage":3,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-7,"damage":-1}},"output":[{"id":5,"damage":3,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-212,"damage":11}},"output":[{"id":5,"damage":3,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-212,"damage":3}},"output":[{"id":5,"damage":3,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":3}},"output":[{"id":136,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":17,"damage":3}},"output":[{"id":-212,"damage":3,"count":3}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-7,"damage":-1}},"output":[{"id":-212,"damage":11,"count":3}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":3}},"output":[{"id":158,"damage":3,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":280,"damage":-1}},"output":[{"id":65,"count":3}],"shape":["A A","AAA","A A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":452,"damage":-1},"B":{"id":50,"damage":-1}},"output":[{"id":-208}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":351,"damage":4}},"output":[{"id":22}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":22,"damage":-1}},"output":[{"id":351,"damage":4,"count":9}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":287,"damage":-1},"B":{"id":341,"damage":-1}},"output":[{"id":420,"count":2}],"shape":["AA ","AB "," A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":415,"damage":-1}},"output":[{"id":334}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":334,"damage":-1}},"output":[{"id":301}],"shape":["A A","A A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":334,"damage":-1}},"output":[{"id":299}],"shape":["A A","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":334,"damage":-1}},"output":[{"id":298}],"shape":["AAA","A A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":334,"damage":-1}},"output":[{"id":416}],"shape":["A A","AAA","A A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":334,"damage":-1}},"output":[{"id":300}],"shape":["AAA","A A","A A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":158,"damage":-1},"B":{"id":47,"damage":-1}},"output":[{"id":-194}],"shape":["AAA"," B "," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-264,"damage":-1},"B":{"id":47,"damage":-1}},"output":[{"id":-194}],"shape":["AAA"," B "," A "],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-265,"damage":-1},"B":{"id":47,"damage":-1}},"output":[{"id":-194}],"shape":["AAA"," B "," A "],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":4,"damage":-1}},"output":[{"id":69}],"shape":["A","B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":3},"B":{"id":280,"damage":-1}},"output":[{"id":446,"damage":12}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":3}},"output":[{"id":171,"damage":3,"count":3}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":171},"B":{"id":351,"damage":12}},"output":[{"id":171,"damage":3,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":12},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"damage":3,"count":8}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":18},{"id":351,"damage":19}],"output":[{"id":351,"damage":12,"count":2}],"block":"crafting_table","priority":1},{"type":0,"input":[{"id":351,"damage":18},{"id":351,"damage":15}],"output":[{"id":351,"damage":12,"count":2}],"block":"crafting_table","priority":2},{"type":0,"input":[{"id":38,"damage":1}],"output":[{"id":351,"damage":12}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":4},{"id":351,"damage":15}],"output":[{"id":351,"damage":12,"count":2}],"block":"crafting_table","priority":4},{"type":0,"input":[{"id":351,"damage":4},{"id":351,"damage":19}],"output":[{"id":351,"damage":12,"count":2}],"block":"crafting_table","priority":3},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351,"damage":12}},"output":[{"id":241,"damage":3,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":241,"damage":3}},"output":[{"id":160,"damage":3,"count":16}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":102,"damage":-1},"B":{"id":351,"damage":12}},"output":[{"id":160,"damage":3,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351,"damage":12}},"output":[{"id":159,"damage":3,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":171},"B":{"id":351,"damage":7}},"output":[{"id":171,"damage":8,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":8},"B":{"id":280,"damage":-1}},"output":[{"id":446,"damage":7}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":8}},"output":[{"id":171,"damage":8,"count":3}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":7},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"damage":8,"count":8}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":16},{"id":351,"damage":19},{"id":351,"damage":19}],"output":[{"id":351,"damage":7,"count":3}],"block":"crafting_table","priority":3},{"type":0,"input":[{"id":38,"damage":3}],"output":[{"id":351,"damage":7}],"block":"crafting_table","priority":2},{"type":0,"input":[{"id":351,"damage":16},{"id":351,"damage":15},{"id":351,"damage":15}],"output":[{"id":351,"damage":7,"count":3}],"block":"crafting_table","priority":7},{"type":0,"input":[{"id":351,"damage":8},{"id":351,"damage":15}],"output":[{"id":351,"damage":7,"count":2}],"block":"crafting_table","priority":6},{"type":0,"input":[{"id":351,"damage":8},{"id":351,"damage":19}],"output":[{"id":351,"damage":7,"count":2}],"block":"crafting_table","priority":4},{"type":0,"input":[{"id":351},{"id":351,"damage":15},{"id":351,"damage":15}],"output":[{"id":351,"damage":7,"count":3}],"block":"crafting_table","priority":8},{"type":0,"input":[{"id":351},{"id":351,"damage":19},{"id":351,"damage":19}],"output":[{"id":351,"damage":7,"count":3}],"block":"crafting_table","priority":5},{"type":0,"input":[{"id":38,"damage":8}],"output":[{"id":351,"damage":7}],"block":"crafting_table","priority":1},{"type":0,"input":[{"id":38,"damage":6}],"output":[{"id":351,"damage":7}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351,"damage":7}},"output":[{"id":241,"damage":8,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":241,"damage":8}},"output":[{"id":160,"damage":8,"count":16}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":102,"damage":-1},"B":{"id":351,"damage":7}},"output":[{"id":160,"damage":8,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351,"damage":7}},"output":[{"id":159,"damage":8,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":266,"damage":-1}},"output":[{"id":147}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":171},"B":{"id":351,"damage":10}},"output":[{"id":171,"damage":5,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":5},"B":{"id":280,"damage":-1}},"output":[{"id":446,"damage":10}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":5}},"output":[{"id":171,"damage":5,"count":3}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":10},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"damage":5,"count":8}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":2},{"id":351,"damage":19}],"output":[{"id":351,"damage":10,"count":2}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":2},{"id":351,"damage":15}],"output":[{"id":351,"damage":10,"count":2}],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351,"damage":10}},"output":[{"id":241,"damage":5,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":241,"damage":5}},"output":[{"id":160,"damage":5,"count":16}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":102,"damage":-1},"B":{"id":351,"damage":10}},"output":[{"id":160,"damage":5,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351,"damage":10}},"output":[{"id":159,"damage":5,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-155,"damage":-1},"B":{"id":50,"damage":-1}},"output":[{"id":91}],"shape":["A","B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":339,"damage":-1},"B":{"id":345,"damage":-1}},"output":[{"id":395,"damage":2}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":98,"damage":3},"B":{"id":742,"damage":-1}},"output":[{"id":-222}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":287,"damage":-1},"B":{"id":-242,"damage":-1}},"output":[{"id":-204}],"shape":["AA","BB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":287,"damage":-1},"B":{"id":-243,"damage":-1}},"output":[{"id":-204}],"shape":["AA","BB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":35,"damage":2},"B":{"id":280,"damage":-1}},"output":[{"id":446,"damage":13}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":2}},"output":[{"id":171,"damage":2,"count":3}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":171},"B":{"id":351,"damage":13}},"output":[{"id":171,"damage":2,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":13},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"damage":2,"count":8}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":18},{"id":351,"damage":1},{"id":351,"damage":9}],"output":[{"id":351,"damage":13,"count":3}],"block":"crafting_table","priority":2},{"type":0,"input":[{"id":38,"damage":2}],"output":[{"id":351,"damage":13}],"block":"crafting_table","priority":1},{"type":0,"input":[{"id":351,"damage":18},{"id":351,"damage":1},{"id":351,"damage":1},{"id":351,"damage":15}],"output":[{"id":351,"damage":13,"count":4}],"block":"crafting_table","priority":6},{"type":0,"input":[{"id":351,"damage":18},{"id":351,"damage":1},{"id":351,"damage":1},{"id":351,"damage":19}],"output":[{"id":351,"damage":13,"count":4}],"block":"crafting_table","priority":4},{"type":0,"input":[{"id":351,"damage":4},{"id":351,"damage":1},{"id":351,"damage":1},{"id":351,"damage":15}],"output":[{"id":351,"damage":13,"count":4}],"block":"crafting_table","priority":8},{"type":0,"input":[{"id":351,"damage":4},{"id":351,"damage":1},{"id":351,"damage":1},{"id":351,"damage":19}],"output":[{"id":351,"damage":13,"count":4}],"block":"crafting_table","priority":7},{"type":0,"input":[{"id":351,"damage":4},{"id":351,"damage":1},{"id":351,"damage":9}],"output":[{"id":351,"damage":13,"count":3}],"block":"crafting_table","priority":5},{"type":0,"input":[{"id":175,"damage":1}],"output":[{"id":351,"damage":13,"count":2}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":5},{"id":351,"damage":9}],"output":[{"id":351,"damage":13,"count":2}],"block":"crafting_table","priority":3},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351,"damage":13}},"output":[{"id":241,"damage":2,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":241,"damage":2}},"output":[{"id":160,"damage":2,"count":16}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":102,"damage":-1},"B":{"id":351,"damage":13}},"output":[{"id":160,"damage":2,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351,"damage":13}},"output":[{"id":159,"damage":2,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":378,"damage":-1}},"output":[{"id":213}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":377,"damage":-1},{"id":341,"damage":-1}],"output":[{"id":378}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":339,"damage":-1}},"output":[{"id":395}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":360,"damage":-1}},"output":[{"id":103}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":360,"damage":-1}},"output":[{"id":362}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1}},"output":[{"id":328}],"shape":["A A","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":4,"damage":-1},{"id":106,"damage":-1}],"output":[{"id":48}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":48,"damage":-1}},"output":[{"id":-179,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":48,"damage":-1}},"output":[{"id":139,"damage":1,"count":6}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":98,"damage":1}},"output":[{"id":-175,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":98,"damage":1}},"output":[{"id":139,"damage":8,"count":6}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":98},{"id":106,"damage":-1}],"output":[{"id":98,"damage":1}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":39,"damage":-1},{"id":40,"damage":-1},{"id":281,"damage":-1}],"output":[{"id":282}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":405,"damage":-1}},"output":[{"id":112}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":112,"damage":-1},"B":{"id":405,"damage":-1}},"output":[{"id":113,"count":6}],"shape":["ABA","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":112,"damage":-1}},"output":[{"id":114,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":112,"damage":-1}},"output":[{"id":139,"damage":9,"count":6}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":372,"damage":-1}},"output":[{"id":214}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":742,"damage":-1}},"output":[{"id":-270}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":752,"damage":-1},{"id":752,"damage":-1},{"id":752,"damage":-1},{"id":752,"damage":-1},{"id":266,"damage":-1},{"id":266,"damage":-1},{"id":266,"damage":-1},{"id":266,"damage":-1}],"output":[{"id":742}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-270,"damage":-1}},"output":[{"id":742,"count":9}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-242,"damage":-1},"B":{"id":331,"damage":-1}},"output":[{"id":25}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-243,"damage":-1},"B":{"id":331,"damage":-1}},"output":[{"id":25}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":17}},"output":[{"id":5,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-10,"damage":-1}},"output":[{"id":5,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-212,"damage":8}},"output":[{"id":5,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-212}},"output":[{"id":5,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5}},"output":[{"id":53,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":17}},"output":[{"id":-212,"count":3}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-10,"damage":-1}},"output":[{"id":-212,"damage":8,"count":3}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5}},"output":[{"id":158,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":4,"damage":-1},"B":{"id":331,"damage":-1},"C":{"id":406,"damage":-1}},"output":[{"id":251}],"shape":["AAA","BBC","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":1},"B":{"id":280,"damage":-1}},"output":[{"id":446,"damage":14}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":1}},"output":[{"id":171,"damage":1,"count":3}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":171},"B":{"id":351,"damage":14}},"output":[{"id":171,"damage":1,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":14},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"damage":1,"count":8}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":38,"damage":5}],"output":[{"id":351,"damage":14}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":1},{"id":351,"damage":11}],"output":[{"id":351,"damage":14,"count":2}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351,"damage":14}},"output":[{"id":241,"damage":1,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":241,"damage":1}},"output":[{"id":160,"damage":1,"count":16}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":102,"damage":-1},"B":{"id":351,"damage":14}},"output":[{"id":160,"damage":1,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351,"damage":14}},"output":[{"id":159,"damage":1,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":79,"damage":-1}},"output":[{"id":174}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":338,"damage":-1}},"output":[{"id":339,"count":3}],"shape":["AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":155}},"output":[{"id":155,"damage":2,"count":2}],"shape":["A","A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":6},"B":{"id":280,"damage":-1}},"output":[{"id":446,"damage":9}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":6}},"output":[{"id":171,"damage":6,"count":3}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":171},"B":{"id":351,"damage":9}},"output":[{"id":171,"damage":6,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":9},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"damage":6,"count":8}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":1},{"id":351,"damage":19}],"output":[{"id":351,"damage":9,"count":2}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":175,"damage":5}],"output":[{"id":351,"damage":9,"count":2}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":38,"damage":7}],"output":[{"id":351,"damage":9}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":1},{"id":351,"damage":15}],"output":[{"id":351,"damage":9,"count":2}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351,"damage":9}},"output":[{"id":241,"damage":6,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":241,"damage":6}},"output":[{"id":160,"damage":6,"count":16}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":102,"damage":-1},"B":{"id":351,"damage":9}},"output":[{"id":160,"damage":6,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351,"damage":9}},"output":[{"id":159,"damage":6,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-242,"damage":-1},"B":{"id":4,"damage":-1},"C":{"id":265,"damage":-1},"D":{"id":331,"damage":-1}},"output":[{"id":33}],"shape":["AAA","BCB","BDB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-243,"damage":-1},"B":{"id":4,"damage":-1},"C":{"id":265,"damage":-1},"D":{"id":331,"damage":-1}},"output":[{"id":33}],"shape":["AAA","BCB","BDB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":1,"damage":5}},"output":[{"id":1,"damage":6,"count":4}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":1,"damage":6}},"output":[{"id":-174,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-234,"damage":-1}},"output":[{"id":-235,"count":4}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-273,"damage":-1}},"output":[{"id":-291,"count":4}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-274,"damage":-1}},"output":[{"id":-284,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-274,"damage":-1}},"output":[{"id":-275,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-274,"damage":-1}},"output":[{"id":-278,"count":6}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-291,"damage":-1}},"output":[{"id":-274,"count":4}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-291,"damage":-1}},"output":[{"id":-296}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-291,"damage":-1}},"output":[{"id":-295}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-291,"damage":-1}},"output":[{"id":-293,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-291,"damage":-1}},"output":[{"id":-292,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-291,"damage":-1}},"output":[{"id":-297,"count":6}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":1,"damage":3}},"output":[{"id":1,"damage":4,"count":4}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":1,"damage":4}},"output":[{"id":-173,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":1,"damage":1}},"output":[{"id":1,"damage":2,"count":4}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":1,"damage":2}},"output":[{"id":-172,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":409,"damage":-1}},"output":[{"id":168}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":409,"damage":-1}},"output":[{"id":168,"damage":2}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":168}},"output":[{"id":-2,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":168,"damage":2}},"output":[{"id":-4,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":168,"damage":1}},"output":[{"id":-3,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":168}},"output":[{"id":139,"damage":11,"count":6}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":86,"damage":-1},{"id":353,"damage":-1},{"id":344,"damage":-1}],"output":[{"id":400}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":86,"damage":-1}},"output":[{"id":361,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":10},"B":{"id":280,"damage":-1}},"output":[{"id":446,"damage":5}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":10}},"output":[{"id":171,"damage":10,"count":3}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":171},"B":{"id":351,"damage":5}},"output":[{"id":171,"damage":10,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":5},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"damage":10,"count":8}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":18},{"id":351,"damage":1}],"output":[{"id":351,"damage":5,"count":2}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":4},{"id":351,"damage":1}],"output":[{"id":351,"damage":5,"count":2}],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351,"damage":5}},"output":[{"id":241,"damage":10,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":241,"damage":10}},"output":[{"id":160,"damage":10,"count":16}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":102,"damage":-1},"B":{"id":351,"damage":5}},"output":[{"id":160,"damage":10,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351,"damage":5}},"output":[{"id":159,"damage":10,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":433,"damage":-1}},"output":[{"id":201,"count":4}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":201,"damage":-1}},"output":[{"id":203,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":406,"damage":-1}},"output":[{"id":155}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":155}},"output":[{"id":-304}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":155}},"output":[{"id":156,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":281,"damage":-1},{"id":393,"damage":-1},{"id":391,"damage":-1},{"id":39,"damage":-1},{"id":412,"damage":-1}],"output":[{"id":413}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":281,"damage":-1},{"id":393,"damage":-1},{"id":391,"damage":-1},{"id":40,"damage":-1},{"id":412,"damage":-1}],"output":[{"id":413}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":66,"count":16}],"shape":["A A","ABA","A A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":14},"B":{"id":280,"damage":-1}},"output":[{"id":446,"damage":1}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":14}},"output":[{"id":171,"damage":14,"count":3}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":171},"B":{"id":351,"damage":1}},"output":[{"id":171,"damage":14,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":1},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"damage":14,"count":8}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":457,"damage":-1}],"output":[{"id":351,"damage":1}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":38}],"output":[{"id":351,"damage":1}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":175,"damage":4}],"output":[{"id":351,"damage":1,"count":2}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":38,"damage":4}],"output":[{"id":351,"damage":1}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":405,"damage":-1},"B":{"id":372,"damage":-1}},"output":[{"id":215}],"shape":["AB","BA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":215,"damage":-1}},"output":[{"id":-184,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":215,"damage":-1}},"output":[{"id":139,"damage":13,"count":6}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":12,"damage":1}},"output":[{"id":179}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":179}},"output":[{"id":180,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":179}},"output":[{"id":139,"damage":12,"count":6}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351,"damage":1}},"output":[{"id":241,"damage":14,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":241,"damage":14}},"output":[{"id":160,"damage":14,"count":16}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":102,"damage":-1},"B":{"id":351,"damage":1}},"output":[{"id":160,"damage":14,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351,"damage":1}},"output":[{"id":159,"damage":14,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":152,"damage":-1}},"output":[{"id":331,"count":9}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":331,"damage":-1}},"output":[{"id":152}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":331,"damage":-1},"B":{"id":89,"damage":-1}},"output":[{"id":123}],"shape":[" A ","ABA"," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":331,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":76}],"shape":["A","B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":76,"damage":-1},"B":{"id":331,"damage":-1},"C":{"id":1}},"output":[{"id":356}],"shape":["ABA","CCC"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-289,"damage":-1},"B":{"id":89,"damage":-1}},"output":[{"id":-272}],"shape":["AAA","BBB","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":12}},"output":[{"id":24}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":24}},"output":[{"id":128,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":24}},"output":[{"id":139,"damage":5,"count":6}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-163,"damage":-1},"B":{"id":287,"damage":-1}},"output":[{"id":-165,"count":6}],"shape":["ABA","A A","A A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":409,"damage":-1},"B":{"id":422,"damage":-1}},"output":[{"id":169}],"shape":["ABA","BBB","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1}},"output":[{"id":359}],"shape":[" A","A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":-1},"B":{"id":265,"damage":-1}},"output":[{"id":513}],"shape":["ABA","AAA"," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-242,"damage":-1},"B":{"id":265,"damage":-1}},"output":[{"id":513}],"shape":["ABA","AAA"," A "],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-243,"damage":-1},"B":{"id":265,"damage":-1}},"output":[{"id":513}],"shape":["ABA","AAA"," A "],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":445,"damage":-1},"B":{"id":54,"damage":-1}},"output":[{"id":205}],"shape":["A","B","A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":4},"B":{"id":280,"damage":-1}},"output":[{"id":475,"count":3}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":2},"B":{"id":280,"damage":-1}},"output":[{"id":473,"count":3}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":5},"B":{"id":280,"damage":-1}},"output":[{"id":476,"count":3}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":3},"B":{"id":280,"damage":-1}},"output":[{"id":474,"count":3}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5},"B":{"id":280,"damage":-1}},"output":[{"id":323,"count":3}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":1},"B":{"id":280,"damage":-1}},"output":[{"id":472,"count":3}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":341,"damage":-1}},"output":[{"id":165}],"shape":["AAA","AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":165,"damage":-1}},"output":[{"id":341,"count":9}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1},"B":{"id":5,"damage":-1}},"output":[{"id":-202}],"shape":["AA","BB","BB"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1},"B":{"id":-242,"damage":-1}},"output":[{"id":-202}],"shape":["AA","BB","BB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":265,"damage":-1},"B":{"id":-243,"damage":-1}},"output":[{"id":-202}],"shape":["AA","BB","BB"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":17,"damage":-1},"B":{"id":61,"damage":-1}},"output":[{"id":-198}],"shape":[" A ","ABA"," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-225,"damage":-1},"B":{"id":61,"damage":-1}},"output":[{"id":-198}],"shape":[" A ","ABA"," A "],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":162,"damage":-1},"B":{"id":61,"damage":-1}},"output":[{"id":-198}],"shape":[" A ","ABA"," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-8,"damage":-1},"B":{"id":61,"damage":-1}},"output":[{"id":-198}],"shape":[" A ","ABA"," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-6,"damage":-1},"B":{"id":61,"damage":-1}},"output":[{"id":-198}],"shape":[" A ","ABA"," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-240,"damage":-1},"B":{"id":61,"damage":-1}},"output":[{"id":-198}],"shape":[" A ","ABA"," A "],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-9,"damage":-1},"B":{"id":61,"damage":-1}},"output":[{"id":-198}],"shape":[" A ","ABA"," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-7,"damage":-1},"B":{"id":61,"damage":-1}},"output":[{"id":-198}],"shape":[" A ","ABA"," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-10,"damage":-1},"B":{"id":61,"damage":-1}},"output":[{"id":-198}],"shape":[" A ","ABA"," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-5,"damage":-1},"B":{"id":61,"damage":-1}},"output":[{"id":-198}],"shape":[" A ","ABA"," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-241,"damage":-1},"B":{"id":61,"damage":-1}},"output":[{"id":-198}],"shape":[" A ","ABA"," A "],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-226,"damage":-1},"B":{"id":61,"damage":-1}},"output":[{"id":-198}],"shape":[" A ","ABA"," A "],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":155,"damage":3}},"output":[{"id":-185,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":179}},"output":[{"id":179,"damage":2,"count":4}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":179,"damage":3}},"output":[{"id":-176,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":24}},"output":[{"id":24,"damage":2,"count":4}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":24,"damage":3}},"output":[{"id":-177,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":332,"damage":-1}},"output":[{"id":80}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":80,"damage":-1}},"output":[{"id":78,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-236,"damage":-1},"C":{"id":-225,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":88,"damage":-1},"C":{"id":-225,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":88,"damage":-1},"C":{"id":17,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":88,"damage":-1},"C":{"id":162,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":88,"damage":-1},"C":{"id":-8,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":88,"damage":-1},"C":{"id":-6,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":88,"damage":-1},"C":{"id":-9,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":88,"damage":-1},"C":{"id":-7,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":88,"damage":-1},"C":{"id":-10,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":88,"damage":-1},"C":{"id":-5,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":88,"damage":-1},"C":{"id":-212,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-236,"damage":-1},"C":{"id":17,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-236,"damage":-1},"C":{"id":162,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-236,"damage":-1},"C":{"id":-8,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-236,"damage":-1},"C":{"id":-6,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-236,"damage":-1},"C":{"id":-9,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-236,"damage":-1},"C":{"id":-7,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-236,"damage":-1},"C":{"id":-10,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-236,"damage":-1},"C":{"id":-5,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-236,"damage":-1},"C":{"id":-212,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-236,"damage":-1},"C":{"id":-240,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":88,"damage":-1},"C":{"id":-240,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-236,"damage":-1},"C":{"id":-241,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":88,"damage":-1},"C":{"id":-241,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-236,"damage":-1},"C":{"id":-226,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":88,"damage":-1},"C":{"id":-226,"damage":-1}},"output":[{"id":801}],"shape":[" A ","ABA","CCC"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":452,"damage":-1},"B":{"id":-268,"damage":-1}},"output":[{"id":-269}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":263,"damage":-1},"B":{"id":280,"damage":-1},"C":{"id":88,"damage":-1}},"output":[{"id":-268,"count":4}],"shape":["A","B","C"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":263,"damage":-1},"B":{"id":280,"damage":-1},"C":{"id":-236,"damage":-1}},"output":[{"id":-268,"count":4}],"shape":["A","B","C"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":371,"damage":-1},"B":{"id":360,"damage":-1}},"output":[{"id":382}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":1},"B":{"id":269,"damage":-1}},"output":[{"id":333,"damage":1}],"shape":["ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":1}},"output":[{"id":427,"count":3}],"shape":["AA","AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":1},"B":{"id":280,"damage":-1}},"output":[{"id":85,"damage":1,"count":3}],"shape":["ABA","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":5,"damage":1}},"output":[{"id":183}],"shape":["ABA","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":17,"damage":1}},"output":[{"id":5,"damage":1,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-5,"damage":-1}},"output":[{"id":5,"damage":1,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-212,"damage":9}},"output":[{"id":5,"damage":1,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-212,"damage":1}},"output":[{"id":5,"damage":1,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":1}},"output":[{"id":134,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":17,"damage":1}},"output":[{"id":-212,"damage":1,"count":3}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-5,"damage":-1}},"output":[{"id":-212,"damage":9,"count":3}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":1}},"output":[{"id":158,"damage":1,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-242,"damage":-1}},"output":[{"id":280,"count":4}],"shape":["A","A"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-243,"damage":-1}},"output":[{"id":280,"count":4}],"shape":["A","A"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":341,"damage":-1},"B":{"id":33,"damage":-1}},"output":[{"id":29,"damage":1}],"shape":["A","B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":4,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":275}],"shape":["AA","AB"," B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-273,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":275}],"shape":["AA","AB"," B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":98}},"output":[{"id":109,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":98}},"output":[{"id":139,"damage":7,"count":6}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":1}},"output":[{"id":77}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":4,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":291}],"shape":["AA"," B"," B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-273,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":291}],"shape":["AA"," B"," B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":4,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":274}],"shape":["AAA"," B "," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-273,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":274}],"shape":["AAA"," B "," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":1}},"output":[{"id":70}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":4,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":273}],"shape":["A","B","B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-273,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":273}],"shape":["A","B","B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":1}},"output":[{"id":-180,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":4,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":272}],"shape":["A","A","B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-273,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":272}],"shape":["A","A","B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":1}},"output":[{"id":98,"count":4}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1},"B":{"id":1,"damage":-1}},"output":[{"id":-197}],"shape":[" A ","BBB"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":287,"damage":-1}},"output":[{"id":35}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-240,"damage":-1}},"output":[{"id":-300,"count":3}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-241,"damage":-1}},"output":[{"id":-301,"count":3}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":338,"damage":-1}},"output":[{"id":353}],"shape":["A"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":39,"damage":-1},{"id":40,"damage":-1},{"id":281,"damage":-1},{"id":38,"damage":2}],"output":[{"id":734,"damage":7}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":39,"damage":-1},{"id":40,"damage":-1},{"id":281,"damage":-1},{"id":38,"damage":3}],"output":[{"id":734,"damage":3}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":39,"damage":-1},{"id":40,"damage":-1},{"id":281,"damage":-1},{"id":38,"damage":1}],"output":[{"id":734,"damage":6}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":39,"damage":-1},{"id":40,"damage":-1},{"id":281,"damage":-1},{"id":38,"damage":9}],"output":[{"id":734,"damage":1}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":39,"damage":-1},{"id":40,"damage":-1},{"id":281,"damage":-1},{"id":37,"damage":-1}],"output":[{"id":734,"damage":5}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":39,"damage":-1},{"id":40,"damage":-1},{"id":281,"damage":-1},{"id":38,"damage":10}],"output":[{"id":734,"damage":4}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":39,"damage":-1},{"id":40,"damage":-1},{"id":281,"damage":-1},{"id":38,"damage":8}],"output":[{"id":734,"damage":8}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":39,"damage":-1},{"id":40,"damage":-1},{"id":281,"damage":-1},{"id":38}],"output":[{"id":734}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":39,"damage":-1},{"id":40,"damage":-1},{"id":281,"damage":-1},{"id":38,"damage":5}],"output":[{"id":734,"damage":2}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":39,"damage":-1},{"id":40,"damage":-1},{"id":281,"damage":-1},{"id":38,"damage":7}],"output":[{"id":734,"damage":2}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":39,"damage":-1},{"id":40,"damage":-1},{"id":281,"damage":-1},{"id":38,"damage":4}],"output":[{"id":734,"damage":2}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":39,"damage":-1},{"id":40,"damage":-1},{"id":281,"damage":-1},{"id":38,"damage":6}],"output":[{"id":734,"damage":2}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":39,"damage":-1},{"id":40,"damage":-1},{"id":281,"damage":-1},{"id":-216,"damage":-1}],"output":[{"id":734,"damage":9}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":331,"damage":-1},"B":{"id":170,"damage":-1}},"output":[{"id":-239}],"shape":[" A ","ABA"," A "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":289,"damage":-1},"B":{"id":12,"damage":-1}},"output":[{"id":46}],"shape":["ABA","BAB","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":46},"B":{"id":328,"damage":-1}},"output":[{"id":407}],"shape":["A","B"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":54,"damage":-1},{"id":131,"damage":-1}],"output":[{"id":146}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":265,"damage":-1},"B":{"id":280,"damage":-1},"C":{"id":-242,"damage":-1}},"output":[{"id":131}],"shape":["A","B","C"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":265,"damage":-1},"B":{"id":280,"damage":-1},"C":{"id":-243,"damage":-1}},"output":[{"id":131}],"shape":["A","B","C"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":468,"damage":-1}},"output":[{"id":469}],"shape":["AAA","A A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-243,"damage":-1}},"output":[{"id":-261}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-243,"damage":-1}},"output":[{"id":756,"count":3}],"shape":["AA","AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-243,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":-257,"count":3}],"shape":["ABA","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":280,"damage":-1},"B":{"id":-243,"damage":-1}},"output":[{"id":-259}],"shape":["ABA","ABA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":346,"damage":-1},"B":{"id":-229,"damage":-1}},"output":[{"id":757}],"shape":["A "," B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-226,"damage":-1}},"output":[{"id":-298,"count":3}],"shape":["AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-226,"damage":-1}},"output":[{"id":-243,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-241,"damage":-1}},"output":[{"id":-243,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-301,"damage":-1}},"output":[{"id":-243,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-298,"damage":-1}},"output":[{"id":-243,"count":4}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-243,"damage":-1}},"output":[{"id":-263}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-243,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":754,"count":3}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-243,"damage":-1}},"output":[{"id":-265,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-243,"damage":-1}},"output":[{"id":-255,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-243,"damage":-1}},"output":[{"id":-247,"count":2}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":170,"damage":-1}},"output":[{"id":296,"count":9}],"shape":["A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35},"B":{"id":280,"damage":-1}},"output":[{"id":446,"damage":15}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35}},"output":[{"id":171,"count":3}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":19},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"count":8}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":15},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"count":8}],"block":"crafting_table","priority":1},{"type":0,"input":[{"id":351,"damage":15}],"output":[{"id":351,"damage":19}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":38,"damage":10}],"output":[{"id":351,"damage":19}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351,"damage":19}},"output":[{"id":241,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351,"damage":15}},"output":[{"id":241,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":241}},"output":[{"id":160,"count":16}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":102,"damage":-1},"B":{"id":351,"damage":19}},"output":[{"id":160,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351,"damage":19}},"output":[{"id":159,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351,"damage":15}},"output":[{"id":159,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":1},{"type":1,"input":{"A":{"id":-242,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":271}],"shape":["AA","AB"," B"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-243,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":271}],"shape":["AA","AB"," B"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":5}},"output":[{"id":324,"count":3}],"shape":["AA","AA","AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":-242,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":290}],"shape":["AA "," B "," B "],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-243,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":290}],"shape":["AA "," B "," B "],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-242,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":270}],"shape":["AAA"," B "," B "],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-243,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":270}],"shape":["AAA"," B "," B "],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-242,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":269}],"shape":["A","B","B"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-243,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":269}],"shape":["A","B","B"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-242,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":268}],"shape":["A","A","B"],"block":"crafting_table","priority":2},{"type":1,"input":{"A":{"id":-243,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":268}],"shape":["A","A","B"],"block":"crafting_table","priority":2},{"type":0,"input":[{"id":340,"damage":-1},{"id":351},{"id":288,"damage":-1}],"output":[{"id":386}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":4},"B":{"id":280,"damage":-1}},"output":[{"id":446,"damage":11}],"shape":["AAA","AAA"," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":35,"damage":4}},"output":[{"id":171,"damage":4,"count":3}],"shape":["AA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":171},"B":{"id":351,"damage":11}},"output":[{"id":171,"damage":4,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351,"damage":11},{"id":12},{"id":12},{"id":12},{"id":12},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1},{"id":13,"damage":-1}],"output":[{"id":237,"damage":4,"count":8}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":37}],"output":[{"id":351,"damage":11}],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":175}],"output":[{"id":351,"damage":11,"count":2}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":20,"damage":-1},"B":{"id":351,"damage":11}},"output":[{"id":241,"damage":4,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":241,"damage":4}},"output":[{"id":160,"damage":4,"count":16}],"shape":["AAA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":102,"damage":-1},"B":{"id":351,"damage":11}},"output":[{"id":160,"damage":4,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":172,"damage":-1},"B":{"id":351,"damage":11}},"output":[{"id":159,"damage":4,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5}},"output":[{"id":53,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAAAAEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402,"damage":10}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAACgEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402,"damage":11}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAACwEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402,"damage":12}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAADAEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402,"damage":13}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAADQEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402,"damage":14}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAADgEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402,"damage":15}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAADwEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAAAAEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402,"damage":3}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAAAwEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402,"damage":4}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAABAEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402,"damage":15}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAADwEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402,"damage":1}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAAAQEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402,"damage":2}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAAAgEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402,"damage":3}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAAAwEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402,"damage":4}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAABAEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402,"damage":5}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAABQEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402,"damage":6}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAABgEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402,"damage":7}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAABwEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402,"damage":8}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAACAEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1},{"id":402,"damage":9}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMKAQAAAAcNAEZpcmV3b3JrQ29sb3IBAAAACQEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA"}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351}],"output":[{"id":402,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3IhHR3/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAAAAEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351,"damage":10}],"output":[{"id":402,"damage":10,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3Ifx4D/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAACgEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351,"damage":11}],"output":[{"id":402,"damage":11,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3I92P7/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAACwEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351,"damage":12}],"output":[{"id":402,"damage":12,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3Laszr/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAADAEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351,"damage":13}],"output":[{"id":402,"damage":13,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3K9Tsf/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAADQEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351,"damage":14}],"output":[{"id":402,"damage":14,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3IdgPn/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAADgEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351,"damage":15}],"output":[{"id":402,"damage":15,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3Lw8PD/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAADwEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351,"damage":16}],"output":[{"id":402,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3IhHR3/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAAAAEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351,"damage":17}],"output":[{"id":402,"damage":3,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3IyVIP/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAAAwEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351,"damage":18}],"output":[{"id":402,"damage":4,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3KqRDz/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAABAEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351,"damage":19}],"output":[{"id":402,"damage":15,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3Lw8PD/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAADwEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351,"damage":1}],"output":[{"id":402,"damage":1,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3ImLrD/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAAAQEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351,"damage":2}],"output":[{"id":402,"damage":2,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3IWfF7/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAAAgEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351,"damage":3}],"output":[{"id":402,"damage":3,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3IyVIP/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAAAwEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351,"damage":4}],"output":[{"id":402,"damage":4,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3KqRDz/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAABAEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351,"damage":5}],"output":[{"id":402,"damage":5,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3K4Mon/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAABQEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351,"damage":6}],"output":[{"id":402,"damage":6,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3KcnBb/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAABgEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351,"damage":7}],"output":[{"id":402,"damage":7,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3KXnZ3/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAABwEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351,"damage":8}],"output":[{"id":402,"damage":8,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3JST0f/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAACAEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":289,"damage":-1},{"id":351,"damage":9}],"output":[{"id":402,"damage":9,"nbt_b64":"CgAAAwsAY3VzdG9tQ29sb3Kqi/P/Cg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAACQEMAEZpcmV3b3JrVHlwZQAHDABGaXJld29ya0ZhZGUAAAAAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAA="}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":339,"damage":-1},{"id":289,"damage":-1}],"output":[{"id":401,"count":3,"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AQkKAEV4cGxvc2lvbnMAAAAAAAAA"}],"block":"crafting_table","priority":50},{"type":4,"uuid":"00000000-0000-0000-0000-000000000001"},{"type":5,"input":[{"id":218,"damage":5},{"id":351}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":4},{"id":351}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":3},{"id":351}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":2},{"id":351}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":1},{"id":351}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218},{"id":351}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":14},{"id":351}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":13},{"id":351}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":12},{"id":351}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":11},{"id":351}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":10},{"id":351}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":9},{"id":351}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":8},{"id":351}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":7},{"id":351}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":6},{"id":351}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":15},{"id":351,"damage":10}],"output":[{"id":218,"damage":5}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":4},{"id":351,"damage":10}],"output":[{"id":218,"damage":5}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":3},{"id":351,"damage":10}],"output":[{"id":218,"damage":5}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":2},{"id":351,"damage":10}],"output":[{"id":218,"damage":5}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":1},{"id":351,"damage":10}],"output":[{"id":218,"damage":5}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218},{"id":351,"damage":10}],"output":[{"id":218,"damage":5}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":14},{"id":351,"damage":10}],"output":[{"id":218,"damage":5}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":13},{"id":351,"damage":10}],"output":[{"id":218,"damage":5}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":12},{"id":351,"damage":10}],"output":[{"id":218,"damage":5}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":11},{"id":351,"damage":10}],"output":[{"id":218,"damage":5}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":10},{"id":351,"damage":10}],"output":[{"id":218,"damage":5}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":9},{"id":351,"damage":10}],"output":[{"id":218,"damage":5}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":8},{"id":351,"damage":10}],"output":[{"id":218,"damage":5}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":7},{"id":351,"damage":10}],"output":[{"id":218,"damage":5}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":6},{"id":351,"damage":10}],"output":[{"id":218,"damage":5}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":15},{"id":351,"damage":11}],"output":[{"id":218,"damage":4}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":5},{"id":351,"damage":11}],"output":[{"id":218,"damage":4}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":3},{"id":351,"damage":11}],"output":[{"id":218,"damage":4}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":2},{"id":351,"damage":11}],"output":[{"id":218,"damage":4}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":1},{"id":351,"damage":11}],"output":[{"id":218,"damage":4}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218},{"id":351,"damage":11}],"output":[{"id":218,"damage":4}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":14},{"id":351,"damage":11}],"output":[{"id":218,"damage":4}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":13},{"id":351,"damage":11}],"output":[{"id":218,"damage":4}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":12},{"id":351,"damage":11}],"output":[{"id":218,"damage":4}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":11},{"id":351,"damage":11}],"output":[{"id":218,"damage":4}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":10},{"id":351,"damage":11}],"output":[{"id":218,"damage":4}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":9},{"id":351,"damage":11}],"output":[{"id":218,"damage":4}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":8},{"id":351,"damage":11}],"output":[{"id":218,"damage":4}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":7},{"id":351,"damage":11}],"output":[{"id":218,"damage":4}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":6},{"id":351,"damage":11}],"output":[{"id":218,"damage":4}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":15},{"id":351,"damage":12}],"output":[{"id":218,"damage":3}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":5},{"id":351,"damage":12}],"output":[{"id":218,"damage":3}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":4},{"id":351,"damage":12}],"output":[{"id":218,"damage":3}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":2},{"id":351,"damage":12}],"output":[{"id":218,"damage":3}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":1},{"id":351,"damage":12}],"output":[{"id":218,"damage":3}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218},{"id":351,"damage":12}],"output":[{"id":218,"damage":3}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":14},{"id":351,"damage":12}],"output":[{"id":218,"damage":3}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":13},{"id":351,"damage":12}],"output":[{"id":218,"damage":3}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":12},{"id":351,"damage":12}],"output":[{"id":218,"damage":3}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":11},{"id":351,"damage":12}],"output":[{"id":218,"damage":3}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":10},{"id":351,"damage":12}],"output":[{"id":218,"damage":3}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":9},{"id":351,"damage":12}],"output":[{"id":218,"damage":3}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":8},{"id":351,"damage":12}],"output":[{"id":218,"damage":3}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":7},{"id":351,"damage":12}],"output":[{"id":218,"damage":3}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":6},{"id":351,"damage":12}],"output":[{"id":218,"damage":3}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":15},{"id":351,"damage":13}],"output":[{"id":218,"damage":2}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":5},{"id":351,"damage":13}],"output":[{"id":218,"damage":2}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":4},{"id":351,"damage":13}],"output":[{"id":218,"damage":2}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":3},{"id":351,"damage":13}],"output":[{"id":218,"damage":2}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":1},{"id":351,"damage":13}],"output":[{"id":218,"damage":2}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218},{"id":351,"damage":13}],"output":[{"id":218,"damage":2}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":14},{"id":351,"damage":13}],"output":[{"id":218,"damage":2}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":13},{"id":351,"damage":13}],"output":[{"id":218,"damage":2}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":12},{"id":351,"damage":13}],"output":[{"id":218,"damage":2}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":11},{"id":351,"damage":13}],"output":[{"id":218,"damage":2}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":10},{"id":351,"damage":13}],"output":[{"id":218,"damage":2}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":9},{"id":351,"damage":13}],"output":[{"id":218,"damage":2}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":8},{"id":351,"damage":13}],"output":[{"id":218,"damage":2}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":7},{"id":351,"damage":13}],"output":[{"id":218,"damage":2}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":6},{"id":351,"damage":13}],"output":[{"id":218,"damage":2}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":15},{"id":351,"damage":14}],"output":[{"id":218,"damage":1}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":5},{"id":351,"damage":14}],"output":[{"id":218,"damage":1}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":4},{"id":351,"damage":14}],"output":[{"id":218,"damage":1}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":3},{"id":351,"damage":14}],"output":[{"id":218,"damage":1}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":2},{"id":351,"damage":14}],"output":[{"id":218,"damage":1}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218},{"id":351,"damage":14}],"output":[{"id":218,"damage":1}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":14},{"id":351,"damage":14}],"output":[{"id":218,"damage":1}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":13},{"id":351,"damage":14}],"output":[{"id":218,"damage":1}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":12},{"id":351,"damage":14}],"output":[{"id":218,"damage":1}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":11},{"id":351,"damage":14}],"output":[{"id":218,"damage":1}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":10},{"id":351,"damage":14}],"output":[{"id":218,"damage":1}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":9},{"id":351,"damage":14}],"output":[{"id":218,"damage":1}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":8},{"id":351,"damage":14}],"output":[{"id":218,"damage":1}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":7},{"id":351,"damage":14}],"output":[{"id":218,"damage":1}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":6},{"id":351,"damage":14}],"output":[{"id":218,"damage":1}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":15},{"id":351,"damage":15}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":5},{"id":351,"damage":15}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":4},{"id":351,"damage":15}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":3},{"id":351,"damage":15}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":2},{"id":351,"damage":15}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":1},{"id":351,"damage":15}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":14},{"id":351,"damage":15}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":13},{"id":351,"damage":15}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":12},{"id":351,"damage":15}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":11},{"id":351,"damage":15}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":10},{"id":351,"damage":15}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":9},{"id":351,"damage":15}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":8},{"id":351,"damage":15}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":7},{"id":351,"damage":15}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":6},{"id":351,"damage":15}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":5},{"id":351,"damage":16}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":4},{"id":351,"damage":16}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":3},{"id":351,"damage":16}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":2},{"id":351,"damage":16}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":1},{"id":351,"damage":16}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218},{"id":351,"damage":16}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":14},{"id":351,"damage":16}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":13},{"id":351,"damage":16}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":12},{"id":351,"damage":16}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":11},{"id":351,"damage":16}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":10},{"id":351,"damage":16}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":9},{"id":351,"damage":16}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":8},{"id":351,"damage":16}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":7},{"id":351,"damage":16}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":6},{"id":351,"damage":16}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":15},{"id":351,"damage":17}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":5},{"id":351,"damage":17}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":4},{"id":351,"damage":17}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":3},{"id":351,"damage":17}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":2},{"id":351,"damage":17}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":1},{"id":351,"damage":17}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218},{"id":351,"damage":17}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":14},{"id":351,"damage":17}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":13},{"id":351,"damage":17}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":11},{"id":351,"damage":17}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":10},{"id":351,"damage":17}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":9},{"id":351,"damage":17}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":8},{"id":351,"damage":17}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":7},{"id":351,"damage":17}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":6},{"id":351,"damage":17}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":15},{"id":351,"damage":18}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":5},{"id":351,"damage":18}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":4},{"id":351,"damage":18}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":3},{"id":351,"damage":18}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":2},{"id":351,"damage":18}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":1},{"id":351,"damage":18}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218},{"id":351,"damage":18}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":14},{"id":351,"damage":18}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":13},{"id":351,"damage":18}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":12},{"id":351,"damage":18}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":10},{"id":351,"damage":18}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":9},{"id":351,"damage":18}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":8},{"id":351,"damage":18}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":7},{"id":351,"damage":18}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":6},{"id":351,"damage":18}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":15},{"id":351,"damage":19}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":5},{"id":351,"damage":19}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":4},{"id":351,"damage":19}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":3},{"id":351,"damage":19}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":2},{"id":351,"damage":19}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":1},{"id":351,"damage":19}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":14},{"id":351,"damage":19}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":13},{"id":351,"damage":19}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":12},{"id":351,"damage":19}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":11},{"id":351,"damage":19}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":10},{"id":351,"damage":19}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":9},{"id":351,"damage":19}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":8},{"id":351,"damage":19}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":7},{"id":351,"damage":19}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":6},{"id":351,"damage":19}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":15},{"id":351,"damage":1}],"output":[{"id":218,"damage":14}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":5},{"id":351,"damage":1}],"output":[{"id":218,"damage":14}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":4},{"id":351,"damage":1}],"output":[{"id":218,"damage":14}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":3},{"id":351,"damage":1}],"output":[{"id":218,"damage":14}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":2},{"id":351,"damage":1}],"output":[{"id":218,"damage":14}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":1},{"id":351,"damage":1}],"output":[{"id":218,"damage":14}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218},{"id":351,"damage":1}],"output":[{"id":218,"damage":14}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":13},{"id":351,"damage":1}],"output":[{"id":218,"damage":14}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":12},{"id":351,"damage":1}],"output":[{"id":218,"damage":14}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":11},{"id":351,"damage":1}],"output":[{"id":218,"damage":14}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":10},{"id":351,"damage":1}],"output":[{"id":218,"damage":14}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":9},{"id":351,"damage":1}],"output":[{"id":218,"damage":14}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":8},{"id":351,"damage":1}],"output":[{"id":218,"damage":14}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":7},{"id":351,"damage":1}],"output":[{"id":218,"damage":14}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":6},{"id":351,"damage":1}],"output":[{"id":218,"damage":14}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":15},{"id":351,"damage":2}],"output":[{"id":218,"damage":13}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":5},{"id":351,"damage":2}],"output":[{"id":218,"damage":13}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":4},{"id":351,"damage":2}],"output":[{"id":218,"damage":13}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":3},{"id":351,"damage":2}],"output":[{"id":218,"damage":13}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":2},{"id":351,"damage":2}],"output":[{"id":218,"damage":13}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":1},{"id":351,"damage":2}],"output":[{"id":218,"damage":13}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218},{"id":351,"damage":2}],"output":[{"id":218,"damage":13}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":14},{"id":351,"damage":2}],"output":[{"id":218,"damage":13}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":12},{"id":351,"damage":2}],"output":[{"id":218,"damage":13}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":11},{"id":351,"damage":2}],"output":[{"id":218,"damage":13}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":10},{"id":351,"damage":2}],"output":[{"id":218,"damage":13}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":9},{"id":351,"damage":2}],"output":[{"id":218,"damage":13}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":8},{"id":351,"damage":2}],"output":[{"id":218,"damage":13}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":7},{"id":351,"damage":2}],"output":[{"id":218,"damage":13}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":6},{"id":351,"damage":2}],"output":[{"id":218,"damage":13}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":15},{"id":351,"damage":3}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":5},{"id":351,"damage":3}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":4},{"id":351,"damage":3}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":3},{"id":351,"damage":3}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":2},{"id":351,"damage":3}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":1},{"id":351,"damage":3}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218},{"id":351,"damage":3}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":14},{"id":351,"damage":3}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":13},{"id":351,"damage":3}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":11},{"id":351,"damage":3}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":10},{"id":351,"damage":3}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":9},{"id":351,"damage":3}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":8},{"id":351,"damage":3}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":7},{"id":351,"damage":3}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":6},{"id":351,"damage":3}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":15},{"id":351,"damage":4}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":5},{"id":351,"damage":4}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":4},{"id":351,"damage":4}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":3},{"id":351,"damage":4}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":2},{"id":351,"damage":4}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":1},{"id":351,"damage":4}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218},{"id":351,"damage":4}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":14},{"id":351,"damage":4}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":13},{"id":351,"damage":4}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":12},{"id":351,"damage":4}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":10},{"id":351,"damage":4}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":9},{"id":351,"damage":4}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":8},{"id":351,"damage":4}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":7},{"id":351,"damage":4}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":6},{"id":351,"damage":4}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":15},{"id":351,"damage":5}],"output":[{"id":218,"damage":10}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":5},{"id":351,"damage":5}],"output":[{"id":218,"damage":10}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":4},{"id":351,"damage":5}],"output":[{"id":218,"damage":10}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":3},{"id":351,"damage":5}],"output":[{"id":218,"damage":10}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":2},{"id":351,"damage":5}],"output":[{"id":218,"damage":10}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":1},{"id":351,"damage":5}],"output":[{"id":218,"damage":10}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218},{"id":351,"damage":5}],"output":[{"id":218,"damage":10}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":14},{"id":351,"damage":5}],"output":[{"id":218,"damage":10}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":13},{"id":351,"damage":5}],"output":[{"id":218,"damage":10}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":12},{"id":351,"damage":5}],"output":[{"id":218,"damage":10}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":11},{"id":351,"damage":5}],"output":[{"id":218,"damage":10}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":9},{"id":351,"damage":5}],"output":[{"id":218,"damage":10}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":8},{"id":351,"damage":5}],"output":[{"id":218,"damage":10}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":7},{"id":351,"damage":5}],"output":[{"id":218,"damage":10}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":6},{"id":351,"damage":5}],"output":[{"id":218,"damage":10}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":15},{"id":351,"damage":6}],"output":[{"id":218,"damage":9}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":5},{"id":351,"damage":6}],"output":[{"id":218,"damage":9}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":4},{"id":351,"damage":6}],"output":[{"id":218,"damage":9}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":3},{"id":351,"damage":6}],"output":[{"id":218,"damage":9}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":2},{"id":351,"damage":6}],"output":[{"id":218,"damage":9}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":1},{"id":351,"damage":6}],"output":[{"id":218,"damage":9}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218},{"id":351,"damage":6}],"output":[{"id":218,"damage":9}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":14},{"id":351,"damage":6}],"output":[{"id":218,"damage":9}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":13},{"id":351,"damage":6}],"output":[{"id":218,"damage":9}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":12},{"id":351,"damage":6}],"output":[{"id":218,"damage":9}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":11},{"id":351,"damage":6}],"output":[{"id":218,"damage":9}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":10},{"id":351,"damage":6}],"output":[{"id":218,"damage":9}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":8},{"id":351,"damage":6}],"output":[{"id":218,"damage":9}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":7},{"id":351,"damage":6}],"output":[{"id":218,"damage":9}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":6},{"id":351,"damage":6}],"output":[{"id":218,"damage":9}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":15},{"id":351,"damage":7}],"output":[{"id":218,"damage":8}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":5},{"id":351,"damage":7}],"output":[{"id":218,"damage":8}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":4},{"id":351,"damage":7}],"output":[{"id":218,"damage":8}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":3},{"id":351,"damage":7}],"output":[{"id":218,"damage":8}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":2},{"id":351,"damage":7}],"output":[{"id":218,"damage":8}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":1},{"id":351,"damage":7}],"output":[{"id":218,"damage":8}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218},{"id":351,"damage":7}],"output":[{"id":218,"damage":8}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":14},{"id":351,"damage":7}],"output":[{"id":218,"damage":8}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":13},{"id":351,"damage":7}],"output":[{"id":218,"damage":8}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":12},{"id":351,"damage":7}],"output":[{"id":218,"damage":8}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":11},{"id":351,"damage":7}],"output":[{"id":218,"damage":8}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":10},{"id":351,"damage":7}],"output":[{"id":218,"damage":8}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":9},{"id":351,"damage":7}],"output":[{"id":218,"damage":8}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":7},{"id":351,"damage":7}],"output":[{"id":218,"damage":8}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":6},{"id":351,"damage":7}],"output":[{"id":218,"damage":8}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":15},{"id":351,"damage":8}],"output":[{"id":218,"damage":7}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":5},{"id":351,"damage":8}],"output":[{"id":218,"damage":7}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":4},{"id":351,"damage":8}],"output":[{"id":218,"damage":7}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":3},{"id":351,"damage":8}],"output":[{"id":218,"damage":7}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":2},{"id":351,"damage":8}],"output":[{"id":218,"damage":7}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":1},{"id":351,"damage":8}],"output":[{"id":218,"damage":7}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218},{"id":351,"damage":8}],"output":[{"id":218,"damage":7}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":14},{"id":351,"damage":8}],"output":[{"id":218,"damage":7}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":13},{"id":351,"damage":8}],"output":[{"id":218,"damage":7}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":12},{"id":351,"damage":8}],"output":[{"id":218,"damage":7}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":11},{"id":351,"damage":8}],"output":[{"id":218,"damage":7}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":10},{"id":351,"damage":8}],"output":[{"id":218,"damage":7}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":9},{"id":351,"damage":8}],"output":[{"id":218,"damage":7}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":8},{"id":351,"damage":8}],"output":[{"id":218,"damage":7}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":6},{"id":351,"damage":8}],"output":[{"id":218,"damage":7}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":15},{"id":351,"damage":9}],"output":[{"id":218,"damage":6}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":5},{"id":351,"damage":9}],"output":[{"id":218,"damage":6}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":4},{"id":351,"damage":9}],"output":[{"id":218,"damage":6}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":3},{"id":351,"damage":9}],"output":[{"id":218,"damage":6}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":2},{"id":351,"damage":9}],"output":[{"id":218,"damage":6}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":1},{"id":351,"damage":9}],"output":[{"id":218,"damage":6}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218},{"id":351,"damage":9}],"output":[{"id":218,"damage":6}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":14},{"id":351,"damage":9}],"output":[{"id":218,"damage":6}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":13},{"id":351,"damage":9}],"output":[{"id":218,"damage":6}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":12},{"id":351,"damage":9}],"output":[{"id":218,"damage":6}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":11},{"id":351,"damage":9}],"output":[{"id":218,"damage":6}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":10},{"id":351,"damage":9}],"output":[{"id":218,"damage":6}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":9},{"id":351,"damage":9}],"output":[{"id":218,"damage":6}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":8},{"id":351,"damage":9}],"output":[{"id":218,"damage":6}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":218,"damage":7},{"id":351,"damage":9}],"output":[{"id":218,"damage":6}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351,"damage":10}],"output":[{"id":218,"damage":5}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351,"damage":11}],"output":[{"id":218,"damage":4}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351,"damage":12}],"output":[{"id":218,"damage":3}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351,"damage":13}],"output":[{"id":218,"damage":2}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351,"damage":14}],"output":[{"id":218,"damage":1}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351,"damage":15}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351,"damage":16}],"output":[{"id":218,"damage":15}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351,"damage":17}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351,"damage":18}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351,"damage":19}],"output":[{"id":218}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351,"damage":1}],"output":[{"id":218,"damage":14}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351,"damage":2}],"output":[{"id":218,"damage":13}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351,"damage":3}],"output":[{"id":218,"damage":12}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351,"damage":4}],"output":[{"id":218,"damage":11}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351,"damage":5}],"output":[{"id":218,"damage":10}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351,"damage":6}],"output":[{"id":218,"damage":9}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351,"damage":7}],"output":[{"id":218,"damage":8}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351,"damage":8}],"output":[{"id":218,"damage":7}],"block":"crafting_table","priority":0},{"type":5,"input":[{"id":205},{"id":351,"damage":9}],"output":[{"id":218,"damage":6}],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":206}},"output":[{"id":-162,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":1}},"output":[{"id":134,"count":4}],"shape":["A ","AA ","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":-1}},"output":[{"id":280,"count":4}],"shape":["A","A"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":179}},"output":[{"id":182,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":168,"damage":2}},"output":[{"id":182,"damage":4,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":168,"damage":1}},"output":[{"id":182,"damage":3,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":201}},"output":[{"id":182,"damage":1,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":48}},"output":[{"id":182,"damage":5,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":215}},"output":[{"id":182,"damage":7,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":179,"damage":1}},"output":[{"id":182,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":24,"damage":3}},"output":[{"id":182,"damage":6,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":1,"damage":5}},"output":[{"id":-162,"damage":3,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":1,"damage":3}},"output":[{"id":-162,"damage":4,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":1,"damage":1}},"output":[{"id":-162,"damage":6,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":1,"damage":2}},"output":[{"id":-162,"damage":7,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":1,"damage":6}},"output":[{"id":-162,"damage":2,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":1,"damage":4}},"output":[{"id":-162,"damage":5,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":179,"damage":3}},"output":[{"id":-162,"damage":1,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":179,"damage":2}},"output":[{"id":-166,"damage":4,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":24,"damage":2}},"output":[{"id":-166,"damage":3,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":155,"damage":3}},"output":[{"id":-166,"damage":1,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":155}},"output":[{"id":44,"damage":6,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":168}},"output":[{"id":182,"damage":2,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":24,"damage":1}},"output":[{"id":44,"damage":1,"count":6}],"shape":["AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":270}],"shape":["AAA"," B "," B "],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":269}],"shape":["A","B","B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":271}],"shape":["AA","AB"," B"],"block":"crafting_table","priority":0},{"type":1,"input":{"A":{"id":5,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":290}],"shape":["AA"," B"," B"],"block":"crafting_table","priority":0},{"type":4,"uuid":"aecd2294-4b94-434b-8667-4499bb2c9327"},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":10}},"output":[{"id":262,"damage":11,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":11}},"output":[{"id":262,"damage":12,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":12}},"output":[{"id":262,"damage":13,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":13}},"output":[{"id":262,"damage":14,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":14}},"output":[{"id":262,"damage":15,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":15}},"output":[{"id":262,"damage":16,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":16}},"output":[{"id":262,"damage":17,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":17}},"output":[{"id":262,"damage":18,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":18}},"output":[{"id":262,"damage":19,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":19}},"output":[{"id":262,"damage":20,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":20}},"output":[{"id":262,"damage":21,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":21}},"output":[{"id":262,"damage":22,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":22}},"output":[{"id":262,"damage":23,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":23}},"output":[{"id":262,"damage":24,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":24}},"output":[{"id":262,"damage":25,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":25}},"output":[{"id":262,"damage":26,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":26}},"output":[{"id":262,"damage":27,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":27}},"output":[{"id":262,"damage":28,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":28}},"output":[{"id":262,"damage":29,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":29}},"output":[{"id":262,"damage":30,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":30}},"output":[{"id":262,"damage":31,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":31}},"output":[{"id":262,"damage":32,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":32}},"output":[{"id":262,"damage":33,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":33}},"output":[{"id":262,"damage":34,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":34}},"output":[{"id":262,"damage":35,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":35}},"output":[{"id":262,"damage":36,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":36}},"output":[{"id":262,"damage":37,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":37}},"output":[{"id":262,"damage":38,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":38}},"output":[{"id":262,"damage":39,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":39}},"output":[{"id":262,"damage":40,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":40}},"output":[{"id":262,"damage":41,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":41}},"output":[{"id":262,"damage":42,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":42}},"output":[{"id":262,"damage":43,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":5}},"output":[{"id":262,"damage":6,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":6}},"output":[{"id":262,"damage":7,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":7}},"output":[{"id":262,"damage":8,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":8}},"output":[{"id":262,"damage":9,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":262},"B":{"id":441,"damage":9}},"output":[{"id":262,"damage":10,"count":8}],"shape":["AAA","ABA","AAA"],"block":"crafting_table","priority":50},{"type":1,"input":{"A":{"id":5,"damage":-1},"B":{"id":280,"damage":-1}},"output":[{"id":268}],"shape":["A","A","B"],"block":"crafting_table","priority":0},{"type":0,"input":[{"id":351},{"id":35,"damage":14}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351},{"id":35,"damage":5}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351},{"id":35,"damage":4}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351},{"id":35,"damage":3}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351},{"id":35,"damage":2}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351},{"id":35,"damage":1}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351},{"id":35}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351},{"id":35,"damage":13}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351},{"id":35,"damage":12}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351},{"id":35,"damage":11}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351},{"id":35,"damage":10}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351},{"id":35,"damage":9}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351},{"id":35,"damage":8}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351},{"id":35,"damage":7}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351},{"id":35,"damage":6}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":10},{"id":35,"damage":15}],"output":[{"id":35,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":10},{"id":35,"damage":14}],"output":[{"id":35,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":10},{"id":35,"damage":4}],"output":[{"id":35,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":10},{"id":35,"damage":3}],"output":[{"id":35,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":10},{"id":35,"damage":2}],"output":[{"id":35,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":10},{"id":35,"damage":1}],"output":[{"id":35,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":10},{"id":35}],"output":[{"id":35,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":10},{"id":35,"damage":13}],"output":[{"id":35,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":10},{"id":35,"damage":12}],"output":[{"id":35,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":10},{"id":35,"damage":11}],"output":[{"id":35,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":10},{"id":35,"damage":10}],"output":[{"id":35,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":10},{"id":35,"damage":9}],"output":[{"id":35,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":10},{"id":35,"damage":8}],"output":[{"id":35,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":10},{"id":35,"damage":7}],"output":[{"id":35,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":10},{"id":35,"damage":6}],"output":[{"id":35,"damage":5}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":11},{"id":35,"damage":15}],"output":[{"id":35,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":11},{"id":35,"damage":14}],"output":[{"id":35,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":11},{"id":35,"damage":5}],"output":[{"id":35,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":11},{"id":35,"damage":3}],"output":[{"id":35,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":11},{"id":35,"damage":2}],"output":[{"id":35,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":11},{"id":35,"damage":1}],"output":[{"id":35,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":11},{"id":35}],"output":[{"id":35,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":11},{"id":35,"damage":13}],"output":[{"id":35,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":11},{"id":35,"damage":12}],"output":[{"id":35,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":11},{"id":35,"damage":11}],"output":[{"id":35,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":11},{"id":35,"damage":10}],"output":[{"id":35,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":11},{"id":35,"damage":9}],"output":[{"id":35,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":11},{"id":35,"damage":8}],"output":[{"id":35,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":11},{"id":35,"damage":7}],"output":[{"id":35,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":11},{"id":35,"damage":6}],"output":[{"id":35,"damage":4}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":12},{"id":35,"damage":15}],"output":[{"id":35,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":12},{"id":35,"damage":14}],"output":[{"id":35,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":12},{"id":35,"damage":5}],"output":[{"id":35,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":12},{"id":35,"damage":4}],"output":[{"id":35,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":12},{"id":35,"damage":2}],"output":[{"id":35,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":12},{"id":35,"damage":1}],"output":[{"id":35,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":12},{"id":35}],"output":[{"id":35,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":12},{"id":35,"damage":13}],"output":[{"id":35,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":12},{"id":35,"damage":12}],"output":[{"id":35,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":12},{"id":35,"damage":11}],"output":[{"id":35,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":12},{"id":35,"damage":10}],"output":[{"id":35,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":12},{"id":35,"damage":9}],"output":[{"id":35,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":12},{"id":35,"damage":8}],"output":[{"id":35,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":12},{"id":35,"damage":7}],"output":[{"id":35,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":12},{"id":35,"damage":6}],"output":[{"id":35,"damage":3}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":13},{"id":35,"damage":15}],"output":[{"id":35,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":13},{"id":35,"damage":14}],"output":[{"id":35,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":13},{"id":35,"damage":5}],"output":[{"id":35,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":13},{"id":35,"damage":4}],"output":[{"id":35,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":13},{"id":35,"damage":3}],"output":[{"id":35,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":13},{"id":35,"damage":1}],"output":[{"id":35,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":13},{"id":35}],"output":[{"id":35,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":13},{"id":35,"damage":13}],"output":[{"id":35,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":13},{"id":35,"damage":12}],"output":[{"id":35,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":13},{"id":35,"damage":11}],"output":[{"id":35,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":13},{"id":35,"damage":10}],"output":[{"id":35,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":13},{"id":35,"damage":9}],"output":[{"id":35,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":13},{"id":35,"damage":8}],"output":[{"id":35,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":13},{"id":35,"damage":7}],"output":[{"id":35,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":13},{"id":35,"damage":6}],"output":[{"id":35,"damage":2}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":14},{"id":35,"damage":15}],"output":[{"id":35,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":14},{"id":35,"damage":14}],"output":[{"id":35,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":14},{"id":35,"damage":5}],"output":[{"id":35,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":14},{"id":35,"damage":4}],"output":[{"id":35,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":14},{"id":35,"damage":3}],"output":[{"id":35,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":14},{"id":35,"damage":2}],"output":[{"id":35,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":14},{"id":35}],"output":[{"id":35,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":14},{"id":35,"damage":13}],"output":[{"id":35,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":14},{"id":35,"damage":12}],"output":[{"id":35,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":14},{"id":35,"damage":11}],"output":[{"id":35,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":14},{"id":35,"damage":10}],"output":[{"id":35,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":14},{"id":35,"damage":9}],"output":[{"id":35,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":14},{"id":35,"damage":8}],"output":[{"id":35,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":14},{"id":35,"damage":7}],"output":[{"id":35,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":14},{"id":35,"damage":6}],"output":[{"id":35,"damage":1}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":15},{"id":35,"damage":15}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":15},{"id":35,"damage":14}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":15},{"id":35,"damage":5}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":15},{"id":35,"damage":4}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":15},{"id":35,"damage":3}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":15},{"id":35,"damage":2}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":15},{"id":35,"damage":1}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":15},{"id":35,"damage":13}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":15},{"id":35,"damage":12}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":15},{"id":35,"damage":11}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":15},{"id":35,"damage":10}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":15},{"id":35,"damage":9}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":15},{"id":35,"damage":8}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":15},{"id":35,"damage":7}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":15},{"id":35,"damage":6}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":16},{"id":35,"damage":14}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":16},{"id":35,"damage":5}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":16},{"id":35,"damage":4}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":16},{"id":35,"damage":3}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":16},{"id":35,"damage":2}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":16},{"id":35,"damage":1}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":16},{"id":35}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":16},{"id":35,"damage":13}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":16},{"id":35,"damage":12}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":16},{"id":35,"damage":11}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":16},{"id":35,"damage":10}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":16},{"id":35,"damage":9}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":16},{"id":35,"damage":8}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":16},{"id":35,"damage":7}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":16},{"id":35,"damage":6}],"output":[{"id":35,"damage":15}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":17},{"id":35,"damage":15}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":17},{"id":35,"damage":14}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":17},{"id":35,"damage":5}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":17},{"id":35,"damage":4}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":17},{"id":35,"damage":3}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":17},{"id":35,"damage":2}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":17},{"id":35,"damage":1}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":17},{"id":35}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":17},{"id":35,"damage":13}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":17},{"id":35,"damage":11}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":17},{"id":35,"damage":10}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":17},{"id":35,"damage":9}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":17},{"id":35,"damage":8}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":17},{"id":35,"damage":7}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":17},{"id":35,"damage":6}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":18},{"id":35,"damage":15}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":18},{"id":35,"damage":14}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":18},{"id":35,"damage":5}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":18},{"id":35,"damage":4}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":18},{"id":35,"damage":3}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":18},{"id":35,"damage":2}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":18},{"id":35,"damage":1}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":18},{"id":35}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":18},{"id":35,"damage":13}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":18},{"id":35,"damage":12}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":18},{"id":35,"damage":10}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":18},{"id":35,"damage":9}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":18},{"id":35,"damage":8}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":18},{"id":35,"damage":7}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":18},{"id":35,"damage":6}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":19},{"id":35,"damage":15}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":19},{"id":35,"damage":14}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":19},{"id":35,"damage":5}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":19},{"id":35,"damage":4}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":19},{"id":35,"damage":3}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":19},{"id":35,"damage":2}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":19},{"id":35,"damage":1}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":19},{"id":35,"damage":13}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":19},{"id":35,"damage":12}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":19},{"id":35,"damage":11}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":19},{"id":35,"damage":10}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":19},{"id":35,"damage":9}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":19},{"id":35,"damage":8}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":19},{"id":35,"damage":7}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":19},{"id":35,"damage":6}],"output":[{"id":35}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":1},{"id":35,"damage":15}],"output":[{"id":35,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":1},{"id":35,"damage":5}],"output":[{"id":35,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":1},{"id":35,"damage":4}],"output":[{"id":35,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":1},{"id":35,"damage":3}],"output":[{"id":35,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":1},{"id":35,"damage":2}],"output":[{"id":35,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":1},{"id":35,"damage":1}],"output":[{"id":35,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":1},{"id":35}],"output":[{"id":35,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":1},{"id":35,"damage":13}],"output":[{"id":35,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":1},{"id":35,"damage":12}],"output":[{"id":35,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":1},{"id":35,"damage":11}],"output":[{"id":35,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":1},{"id":35,"damage":10}],"output":[{"id":35,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":1},{"id":35,"damage":9}],"output":[{"id":35,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":1},{"id":35,"damage":8}],"output":[{"id":35,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":1},{"id":35,"damage":7}],"output":[{"id":35,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":1},{"id":35,"damage":6}],"output":[{"id":35,"damage":14}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":2},{"id":35,"damage":15}],"output":[{"id":35,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":2},{"id":35,"damage":14}],"output":[{"id":35,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":2},{"id":35,"damage":5}],"output":[{"id":35,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":2},{"id":35,"damage":4}],"output":[{"id":35,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":2},{"id":35,"damage":3}],"output":[{"id":35,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":2},{"id":35,"damage":2}],"output":[{"id":35,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":2},{"id":35,"damage":1}],"output":[{"id":35,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":2},{"id":35}],"output":[{"id":35,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":2},{"id":35,"damage":12}],"output":[{"id":35,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":2},{"id":35,"damage":11}],"output":[{"id":35,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":2},{"id":35,"damage":10}],"output":[{"id":35,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":2},{"id":35,"damage":9}],"output":[{"id":35,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":2},{"id":35,"damage":8}],"output":[{"id":35,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":2},{"id":35,"damage":7}],"output":[{"id":35,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":2},{"id":35,"damage":6}],"output":[{"id":35,"damage":13}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":3},{"id":35,"damage":15}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":3},{"id":35,"damage":14}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":3},{"id":35,"damage":5}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":3},{"id":35,"damage":4}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":3},{"id":35,"damage":3}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":3},{"id":35,"damage":2}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":3},{"id":35,"damage":1}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":3},{"id":35}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":3},{"id":35,"damage":13}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":3},{"id":35,"damage":11}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":3},{"id":35,"damage":10}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":3},{"id":35,"damage":9}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":3},{"id":35,"damage":8}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":3},{"id":35,"damage":7}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":3},{"id":35,"damage":6}],"output":[{"id":35,"damage":12}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":4},{"id":35,"damage":15}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":4},{"id":35,"damage":14}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":4},{"id":35,"damage":5}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":4},{"id":35,"damage":4}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":4},{"id":35,"damage":3}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":4},{"id":35,"damage":2}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":4},{"id":35,"damage":1}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":4},{"id":35}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":4},{"id":35,"damage":13}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":4},{"id":35,"damage":12}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":4},{"id":35,"damage":10}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":4},{"id":35,"damage":9}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":4},{"id":35,"damage":8}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":4},{"id":35,"damage":7}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":4},{"id":35,"damage":6}],"output":[{"id":35,"damage":11}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":5},{"id":35,"damage":15}],"output":[{"id":35,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":5},{"id":35,"damage":14}],"output":[{"id":35,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":5},{"id":35,"damage":5}],"output":[{"id":35,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":5},{"id":35,"damage":4}],"output":[{"id":35,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":5},{"id":35,"damage":3}],"output":[{"id":35,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":5},{"id":35,"damage":2}],"output":[{"id":35,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":5},{"id":35,"damage":1}],"output":[{"id":35,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":5},{"id":35}],"output":[{"id":35,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":5},{"id":35,"damage":13}],"output":[{"id":35,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":5},{"id":35,"damage":12}],"output":[{"id":35,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":5},{"id":35,"damage":11}],"output":[{"id":35,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":5},{"id":35,"damage":9}],"output":[{"id":35,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":5},{"id":35,"damage":8}],"output":[{"id":35,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":5},{"id":35,"damage":7}],"output":[{"id":35,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":5},{"id":35,"damage":6}],"output":[{"id":35,"damage":10}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":6},{"id":35,"damage":15}],"output":[{"id":35,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":6},{"id":35,"damage":14}],"output":[{"id":35,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":6},{"id":35,"damage":5}],"output":[{"id":35,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":6},{"id":35,"damage":4}],"output":[{"id":35,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":6},{"id":35,"damage":3}],"output":[{"id":35,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":6},{"id":35,"damage":2}],"output":[{"id":35,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":6},{"id":35,"damage":1}],"output":[{"id":35,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":6},{"id":35}],"output":[{"id":35,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":6},{"id":35,"damage":13}],"output":[{"id":35,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":6},{"id":35,"damage":12}],"output":[{"id":35,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":6},{"id":35,"damage":11}],"output":[{"id":35,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":6},{"id":35,"damage":10}],"output":[{"id":35,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":6},{"id":35,"damage":8}],"output":[{"id":35,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":6},{"id":35,"damage":7}],"output":[{"id":35,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":6},{"id":35,"damage":6}],"output":[{"id":35,"damage":9}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":7},{"id":35,"damage":15}],"output":[{"id":35,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":7},{"id":35,"damage":14}],"output":[{"id":35,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":7},{"id":35,"damage":5}],"output":[{"id":35,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":7},{"id":35,"damage":4}],"output":[{"id":35,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":7},{"id":35,"damage":3}],"output":[{"id":35,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":7},{"id":35,"damage":2}],"output":[{"id":35,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":7},{"id":35,"damage":1}],"output":[{"id":35,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":7},{"id":35}],"output":[{"id":35,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":7},{"id":35,"damage":13}],"output":[{"id":35,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":7},{"id":35,"damage":12}],"output":[{"id":35,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":7},{"id":35,"damage":11}],"output":[{"id":35,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":7},{"id":35,"damage":10}],"output":[{"id":35,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":7},{"id":35,"damage":9}],"output":[{"id":35,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":7},{"id":35,"damage":7}],"output":[{"id":35,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":7},{"id":35,"damage":6}],"output":[{"id":35,"damage":8}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":8},{"id":35,"damage":15}],"output":[{"id":35,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":8},{"id":35,"damage":14}],"output":[{"id":35,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":8},{"id":35,"damage":5}],"output":[{"id":35,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":8},{"id":35,"damage":4}],"output":[{"id":35,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":8},{"id":35,"damage":3}],"output":[{"id":35,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":8},{"id":35,"damage":2}],"output":[{"id":35,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":8},{"id":35,"damage":1}],"output":[{"id":35,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":8},{"id":35}],"output":[{"id":35,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":8},{"id":35,"damage":13}],"output":[{"id":35,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":8},{"id":35,"damage":12}],"output":[{"id":35,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":8},{"id":35,"damage":11}],"output":[{"id":35,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":8},{"id":35,"damage":10}],"output":[{"id":35,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":8},{"id":35,"damage":9}],"output":[{"id":35,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":8},{"id":35,"damage":8}],"output":[{"id":35,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":8},{"id":35,"damage":6}],"output":[{"id":35,"damage":7}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":9},{"id":35,"damage":15}],"output":[{"id":35,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":9},{"id":35,"damage":14}],"output":[{"id":35,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":9},{"id":35,"damage":5}],"output":[{"id":35,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":9},{"id":35,"damage":4}],"output":[{"id":35,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":9},{"id":35,"damage":3}],"output":[{"id":35,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":9},{"id":35,"damage":2}],"output":[{"id":35,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":9},{"id":35,"damage":1}],"output":[{"id":35,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":9},{"id":35}],"output":[{"id":35,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":9},{"id":35,"damage":13}],"output":[{"id":35,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":9},{"id":35,"damage":12}],"output":[{"id":35,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":9},{"id":35,"damage":11}],"output":[{"id":35,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":9},{"id":35,"damage":10}],"output":[{"id":35,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":9},{"id":35,"damage":9}],"output":[{"id":35,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":9},{"id":35,"damage":8}],"output":[{"id":35,"damage":6}],"block":"crafting_table","priority":50},{"type":0,"input":[{"id":351,"damage":9},{"id":35,"damage":7}],"output":[{"id":35,"damage":6}],"block":"crafting_table","priority":50},{"type":3,"input":{"id":-288,"damage":-1},"output":{"id":266},"block":"furnace"},{"type":3,"input":{"id":-288,"damage":-1},"output":{"id":266},"block":"blast_furnace"},{"type":3,"input":{"id":-274,"damage":-1},"output":{"id":-280},"block":"furnace"},{"type":3,"input":{"id":-271,"damage":-1},"output":{"id":752},"block":"furnace"},{"type":3,"input":{"id":-271,"damage":-1},"output":{"id":752},"block":"blast_furnace"},{"type":3,"input":{"id":-212},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":-212,"damage":1},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":-212,"damage":2},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":-212,"damage":3},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":-212,"damage":4},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":-212,"damage":5},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":-212,"damage":8},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":-212,"damage":9},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":-212,"damage":10},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":-212,"damage":11},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":-212,"damage":12},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":-212,"damage":13},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":-156,"damage":-1},"output":{"id":351,"damage":10},"block":"furnace"},{"type":3,"input":{"id":-10,"damage":-1},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":-9,"damage":-1},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":-8,"damage":-1},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":-7,"damage":-1},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":-6,"damage":-1},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":-5,"damage":-1},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":1},"output":{"id":-183},"block":"furnace"},{"type":3,"input":{"id":4,"damage":-1},"output":{"id":1},"block":"furnace"},{"type":3,"input":{"id":12,"damage":-1},"output":{"id":20},"block":"furnace"},{"type":3,"input":{"id":14,"damage":-1},"output":{"id":266},"block":"furnace"},{"type":3,"input":{"id":14,"damage":-1},"output":{"id":266},"block":"blast_furnace"},{"type":3,"input":{"id":15,"damage":-1},"output":{"id":265},"block":"furnace"},{"type":3,"input":{"id":15,"damage":-1},"output":{"id":265},"block":"blast_furnace"},{"type":3,"input":{"id":16,"damage":-1},"output":{"id":263},"block":"furnace"},{"type":3,"input":{"id":16,"damage":-1},"output":{"id":263},"block":"blast_furnace"},{"type":3,"input":{"id":17},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":17,"damage":1},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":17,"damage":2},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":17,"damage":3},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":19,"damage":1},"output":{"id":19},"block":"furnace"},{"type":3,"input":{"id":21,"damage":-1},"output":{"id":351,"damage":4},"block":"furnace"},{"type":3,"input":{"id":21,"damage":-1},"output":{"id":351,"damage":4},"block":"blast_furnace"},{"type":3,"input":{"id":24,"damage":-1},"output":{"id":24,"damage":3},"block":"furnace"},{"type":3,"input":{"id":56,"damage":-1},"output":{"id":264},"block":"furnace"},{"type":3,"input":{"id":56,"damage":-1},"output":{"id":264},"block":"blast_furnace"},{"type":3,"input":{"id":73,"damage":-1},"output":{"id":331},"block":"furnace"},{"type":3,"input":{"id":73,"damage":-1},"output":{"id":331},"block":"blast_furnace"},{"type":3,"input":{"id":81,"damage":-1},"output":{"id":351,"damage":2},"block":"furnace"},{"type":3,"input":{"id":82,"damage":-1},"output":{"id":172},"block":"furnace"},{"type":3,"input":{"id":87,"damage":-1},"output":{"id":405},"block":"furnace"},{"type":3,"input":{"id":98},"output":{"id":98,"damage":2},"block":"furnace"},{"type":3,"input":{"id":112,"damage":-1},"output":{"id":-303},"block":"furnace"},{"type":3,"input":{"id":129,"damage":-1},"output":{"id":388},"block":"furnace"},{"type":3,"input":{"id":129,"damage":-1},"output":{"id":388},"block":"blast_furnace"},{"type":3,"input":{"id":153,"damage":-1},"output":{"id":406},"block":"furnace"},{"type":3,"input":{"id":153,"damage":-1},"output":{"id":406},"block":"blast_furnace"},{"type":3,"input":{"id":155},"output":{"id":155,"damage":3},"block":"furnace"},{"type":3,"input":{"id":159},"output":{"id":220},"block":"furnace"},{"type":3,"input":{"id":159,"damage":1},"output":{"id":221},"block":"furnace"},{"type":3,"input":{"id":159,"damage":2},"output":{"id":222},"block":"furnace"},{"type":3,"input":{"id":159,"damage":3},"output":{"id":223},"block":"furnace"},{"type":3,"input":{"id":159,"damage":4},"output":{"id":224},"block":"furnace"},{"type":3,"input":{"id":159,"damage":5},"output":{"id":225},"block":"furnace"},{"type":3,"input":{"id":159,"damage":6},"output":{"id":226},"block":"furnace"},{"type":3,"input":{"id":159,"damage":7},"output":{"id":227},"block":"furnace"},{"type":3,"input":{"id":159,"damage":8},"output":{"id":228},"block":"furnace"},{"type":3,"input":{"id":159,"damage":9},"output":{"id":229},"block":"furnace"},{"type":3,"input":{"id":159,"damage":10},"output":{"id":219},"block":"furnace"},{"type":3,"input":{"id":159,"damage":11},"output":{"id":231},"block":"furnace"},{"type":3,"input":{"id":159,"damage":12},"output":{"id":232},"block":"furnace"},{"type":3,"input":{"id":159,"damage":13},"output":{"id":233},"block":"furnace"},{"type":3,"input":{"id":159,"damage":14},"output":{"id":234},"block":"furnace"},{"type":3,"input":{"id":159,"damage":15},"output":{"id":235},"block":"furnace"},{"type":3,"input":{"id":162},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":162,"damage":1},"output":{"id":263,"damage":1},"block":"furnace"},{"type":3,"input":{"id":179,"damage":-1},"output":{"id":179,"damage":3},"block":"furnace"},{"type":3,"input":{"id":256,"damage":-1},"output":{"id":452},"block":"furnace"},{"type":3,"input":{"id":256,"damage":-1},"output":{"id":452},"block":"blast_furnace"},{"type":3,"input":{"id":257,"damage":-1},"output":{"id":452},"block":"furnace"},{"type":3,"input":{"id":257,"damage":-1},"output":{"id":452},"block":"blast_furnace"},{"type":3,"input":{"id":258,"damage":-1},"output":{"id":452},"block":"furnace"},{"type":3,"input":{"id":258,"damage":-1},"output":{"id":452},"block":"blast_furnace"},{"type":3,"input":{"id":267,"damage":-1},"output":{"id":452},"block":"furnace"},{"type":3,"input":{"id":267,"damage":-1},"output":{"id":452},"block":"blast_furnace"},{"type":3,"input":{"id":283,"damage":-1},"output":{"id":371},"block":"furnace"},{"type":3,"input":{"id":283,"damage":-1},"output":{"id":371},"block":"blast_furnace"},{"type":3,"input":{"id":284,"damage":-1},"output":{"id":371},"block":"furnace"},{"type":3,"input":{"id":284,"damage":-1},"output":{"id":371},"block":"blast_furnace"},{"type":3,"input":{"id":285,"damage":-1},"output":{"id":371},"block":"furnace"},{"type":3,"input":{"id":285,"damage":-1},"output":{"id":371},"block":"blast_furnace"},{"type":3,"input":{"id":286,"damage":-1},"output":{"id":371},"block":"furnace"},{"type":3,"input":{"id":286,"damage":-1},"output":{"id":371},"block":"blast_furnace"},{"type":3,"input":{"id":292,"damage":-1},"output":{"id":452},"block":"furnace"},{"type":3,"input":{"id":292,"damage":-1},"output":{"id":452},"block":"blast_furnace"},{"type":3,"input":{"id":294,"damage":-1},"output":{"id":371},"block":"furnace"},{"type":3,"input":{"id":294,"damage":-1},"output":{"id":371},"block":"blast_furnace"},{"type":3,"input":{"id":302},"output":{"id":452},"block":"furnace"},{"type":3,"input":{"id":302},"output":{"id":452},"block":"blast_furnace"},{"type":3,"input":{"id":303},"output":{"id":452},"block":"furnace"},{"type":3,"input":{"id":303},"output":{"id":452},"block":"blast_furnace"},{"type":3,"input":{"id":304},"output":{"id":452},"block":"furnace"},{"type":3,"input":{"id":304},"output":{"id":452},"block":"blast_furnace"},{"type":3,"input":{"id":305},"output":{"id":452},"block":"furnace"},{"type":3,"input":{"id":305},"output":{"id":452},"block":"blast_furnace"},{"type":3,"input":{"id":306},"output":{"id":452},"block":"furnace"},{"type":3,"input":{"id":306},"output":{"id":452},"block":"blast_furnace"},{"type":3,"input":{"id":307},"output":{"id":452},"block":"furnace"},{"type":3,"input":{"id":307},"output":{"id":452},"block":"blast_furnace"},{"type":3,"input":{"id":308},"output":{"id":452},"block":"furnace"},{"type":3,"input":{"id":308},"output":{"id":452},"block":"blast_furnace"},{"type":3,"input":{"id":309},"output":{"id":452},"block":"furnace"},{"type":3,"input":{"id":309},"output":{"id":452},"block":"blast_furnace"},{"type":3,"input":{"id":314},"output":{"id":371},"block":"furnace"},{"type":3,"input":{"id":314},"output":{"id":371},"block":"blast_furnace"},{"type":3,"input":{"id":315},"output":{"id":371},"block":"furnace"},{"type":3,"input":{"id":315},"output":{"id":371},"block":"blast_furnace"},{"type":3,"input":{"id":316},"output":{"id":371},"block":"furnace"},{"type":3,"input":{"id":316},"output":{"id":371},"block":"blast_furnace"},{"type":3,"input":{"id":317},"output":{"id":371},"block":"furnace"},{"type":3,"input":{"id":317},"output":{"id":371},"block":"blast_furnace"},{"type":3,"input":{"id":319,"damage":-1},"output":{"id":320},"block":"smoker"},{"type":3,"input":{"id":319,"damage":-1},"output":{"id":320},"block":"furnace"},{"type":3,"input":{"id":319,"damage":-1},"output":{"id":320},"block":"soul_campfire"},{"type":3,"input":{"id":319,"damage":-1},"output":{"id":320},"block":"campfire"},{"type":3,"input":{"id":335,"damage":-1},"output":{"id":464},"block":"smoker"},{"type":3,"input":{"id":335,"damage":-1},"output":{"id":464},"block":"furnace"},{"type":3,"input":{"id":335,"damage":-1},"output":{"id":464},"block":"soul_campfire"},{"type":3,"input":{"id":335,"damage":-1},"output":{"id":464},"block":"campfire"},{"type":3,"input":{"id":337,"damage":-1},"output":{"id":336},"block":"furnace"},{"type":3,"input":{"id":349,"damage":-1},"output":{"id":350},"block":"smoker"},{"type":3,"input":{"id":349,"damage":-1},"output":{"id":350},"block":"furnace"},{"type":3,"input":{"id":349,"damage":-1},"output":{"id":350},"block":"soul_campfire"},{"type":3,"input":{"id":349,"damage":-1},"output":{"id":350},"block":"campfire"},{"type":3,"input":{"id":363,"damage":-1},"output":{"id":364},"block":"smoker"},{"type":3,"input":{"id":363,"damage":-1},"output":{"id":364},"block":"furnace"},{"type":3,"input":{"id":363,"damage":-1},"output":{"id":364},"block":"soul_campfire"},{"type":3,"input":{"id":363,"damage":-1},"output":{"id":364},"block":"campfire"},{"type":3,"input":{"id":365,"damage":-1},"output":{"id":366},"block":"smoker"},{"type":3,"input":{"id":365,"damage":-1},"output":{"id":366},"block":"furnace"},{"type":3,"input":{"id":365,"damage":-1},"output":{"id":366},"block":"soul_campfire"},{"type":3,"input":{"id":365,"damage":-1},"output":{"id":366},"block":"campfire"},{"type":3,"input":{"id":392,"damage":-1},"output":{"id":393},"block":"smoker"},{"type":3,"input":{"id":392,"damage":-1},"output":{"id":393},"block":"furnace"},{"type":3,"input":{"id":392,"damage":-1},"output":{"id":393},"block":"soul_campfire"},{"type":3,"input":{"id":392,"damage":-1},"output":{"id":393},"block":"campfire"},{"type":3,"input":{"id":411,"damage":-1},"output":{"id":412},"block":"smoker"},{"type":3,"input":{"id":411,"damage":-1},"output":{"id":412},"block":"furnace"},{"type":3,"input":{"id":411,"damage":-1},"output":{"id":412},"block":"soul_campfire"},{"type":3,"input":{"id":411,"damage":-1},"output":{"id":412},"block":"campfire"},{"type":3,"input":{"id":417,"damage":-1},"output":{"id":452},"block":"furnace"},{"type":3,"input":{"id":417,"damage":-1},"output":{"id":452},"block":"blast_furnace"},{"type":3,"input":{"id":418,"damage":-1},"output":{"id":371},"block":"furnace"},{"type":3,"input":{"id":418,"damage":-1},"output":{"id":371},"block":"blast_furnace"},{"type":3,"input":{"id":423,"damage":-1},"output":{"id":424},"block":"smoker"},{"type":3,"input":{"id":423,"damage":-1},"output":{"id":424},"block":"furnace"},{"type":3,"input":{"id":423,"damage":-1},"output":{"id":424},"block":"soul_campfire"},{"type":3,"input":{"id":423,"damage":-1},"output":{"id":424},"block":"campfire"},{"type":3,"input":{"id":432,"damage":-1},"output":{"id":433},"block":"furnace"},{"type":3,"input":{"id":460,"damage":-1},"output":{"id":463},"block":"smoker"},{"type":3,"input":{"id":460,"damage":-1},"output":{"id":463},"block":"furnace"},{"type":3,"input":{"id":460,"damage":-1},"output":{"id":463},"block":"soul_campfire"},{"type":3,"input":{"id":460,"damage":-1},"output":{"id":463},"block":"campfire"}],"potionMixes":[{"inputId":373,"inputMeta":17,"reagentId":348,"reagentMeta":0,"outputId":373,"outputMeta":42},{"inputId":438,"inputMeta":17,"reagentId":348,"reagentMeta":0,"outputId":438,"outputMeta":42},{"inputId":441,"inputMeta":17,"reagentId":348,"reagentMeta":0,"outputId":441,"outputMeta":42},{"inputId":373,"inputMeta":27,"reagentId":376,"reagentMeta":0,"outputId":373,"outputMeta":24},{"inputId":438,"inputMeta":27,"reagentId":376,"reagentMeta":0,"outputId":438,"outputMeta":24},{"inputId":441,"inputMeta":27,"reagentId":376,"reagentMeta":0,"outputId":441,"outputMeta":24},{"inputId":373,"inputMeta":4,"reagentId":377,"reagentMeta":0,"outputId":373,"outputMeta":31},{"inputId":438,"inputMeta":4,"reagentId":377,"reagentMeta":0,"outputId":438,"outputMeta":31},{"inputId":441,"inputMeta":4,"reagentId":377,"reagentMeta":0,"outputId":441,"outputMeta":31},{"inputId":373,"inputMeta":4,"reagentId":376,"reagentMeta":0,"outputId":373,"outputMeta":34},{"inputId":438,"inputMeta":4,"reagentId":376,"reagentMeta":0,"outputId":438,"outputMeta":34},{"inputId":441,"inputMeta":4,"reagentId":376,"reagentMeta":0,"outputId":441,"outputMeta":34},{"inputId":373,"inputMeta":4,"reagentId":370,"reagentMeta":0,"outputId":373,"outputMeta":28},{"inputId":438,"inputMeta":4,"reagentId":370,"reagentMeta":0,"outputId":438,"outputMeta":28},{"inputId":441,"inputMeta":4,"reagentId":370,"reagentMeta":0,"outputId":441,"outputMeta":28},{"inputId":373,"inputMeta":4,"reagentId":396,"reagentMeta":0,"outputId":373,"outputMeta":5},{"inputId":438,"inputMeta":4,"reagentId":396,"reagentMeta":0,"outputId":438,"outputMeta":5},{"inputId":441,"inputMeta":4,"reagentId":396,"reagentMeta":0,"outputId":441,"outputMeta":5},{"inputId":373,"inputMeta":4,"reagentId":378,"reagentMeta":0,"outputId":373,"outputMeta":12},{"inputId":438,"inputMeta":4,"reagentId":378,"reagentMeta":0,"outputId":438,"outputMeta":12},{"inputId":441,"inputMeta":4,"reagentId":378,"reagentMeta":0,"outputId":441,"outputMeta":12},{"inputId":373,"inputMeta":4,"reagentId":470,"reagentMeta":0,"outputId":373,"outputMeta":40},{"inputId":438,"inputMeta":4,"reagentId":470,"reagentMeta":0,"outputId":438,"outputMeta":40},{"inputId":441,"inputMeta":4,"reagentId":470,"reagentMeta":0,"outputId":441,"outputMeta":40},{"inputId":373,"inputMeta":4,"reagentId":462,"reagentMeta":0,"outputId":373,"outputMeta":19},{"inputId":438,"inputMeta":4,"reagentId":462,"reagentMeta":0,"outputId":438,"outputMeta":19},{"inputId":441,"inputMeta":4,"reagentId":462,"reagentMeta":0,"outputId":441,"outputMeta":19},{"inputId":373,"inputMeta":4,"reagentId":414,"reagentMeta":0,"outputId":373,"outputMeta":9},{"inputId":438,"inputMeta":4,"reagentId":414,"reagentMeta":0,"outputId":438,"outputMeta":9},{"inputId":441,"inputMeta":4,"reagentId":414,"reagentMeta":0,"outputId":441,"outputMeta":9},{"inputId":373,"inputMeta":4,"reagentId":382,"reagentMeta":0,"outputId":373,"outputMeta":21},{"inputId":438,"inputMeta":4,"reagentId":382,"reagentMeta":0,"outputId":438,"outputMeta":21},{"inputId":441,"inputMeta":4,"reagentId":382,"reagentMeta":0,"outputId":441,"outputMeta":21},{"inputId":373,"inputMeta":4,"reagentId":375,"reagentMeta":0,"outputId":373,"outputMeta":25},{"inputId":438,"inputMeta":4,"reagentId":375,"reagentMeta":0,"outputId":438,"outputMeta":25},{"inputId":441,"inputMeta":4,"reagentId":375,"reagentMeta":0,"outputId":441,"outputMeta":25},{"inputId":373,"inputMeta":4,"reagentId":353,"reagentMeta":0,"outputId":373,"outputMeta":14},{"inputId":438,"inputMeta":4,"reagentId":353,"reagentMeta":0,"outputId":438,"outputMeta":14},{"inputId":441,"inputMeta":4,"reagentId":353,"reagentMeta":0,"outputId":441,"outputMeta":14},{"inputId":373,"inputMeta":4,"reagentId":469,"reagentMeta":0,"outputId":373,"outputMeta":37},{"inputId":438,"inputMeta":4,"reagentId":469,"reagentMeta":0,"outputId":438,"outputMeta":37},{"inputId":441,"inputMeta":4,"reagentId":469,"reagentMeta":0,"outputId":441,"outputMeta":37},{"inputId":373,"inputMeta":12,"reagentId":331,"reagentMeta":0,"outputId":373,"outputMeta":13},{"inputId":438,"inputMeta":12,"reagentId":331,"reagentMeta":0,"outputId":438,"outputMeta":13},{"inputId":441,"inputMeta":12,"reagentId":331,"reagentMeta":0,"outputId":441,"outputMeta":13},{"inputId":373,"inputMeta":23,"reagentId":348,"reagentMeta":0,"outputId":373,"outputMeta":24},{"inputId":438,"inputMeta":23,"reagentId":348,"reagentMeta":0,"outputId":438,"outputMeta":24},{"inputId":441,"inputMeta":23,"reagentId":348,"reagentMeta":0,"outputId":441,"outputMeta":24},{"inputId":373,"inputMeta":21,"reagentId":376,"reagentMeta":0,"outputId":373,"outputMeta":23},{"inputId":438,"inputMeta":21,"reagentId":376,"reagentMeta":0,"outputId":438,"outputMeta":23},{"inputId":441,"inputMeta":21,"reagentId":376,"reagentMeta":0,"outputId":441,"outputMeta":23},{"inputId":373,"inputMeta":21,"reagentId":348,"reagentMeta":0,"outputId":373,"outputMeta":22},{"inputId":438,"inputMeta":21,"reagentId":348,"reagentMeta":0,"outputId":438,"outputMeta":22},{"inputId":441,"inputMeta":21,"reagentId":348,"reagentMeta":0,"outputId":441,"outputMeta":22},{"inputId":373,"inputMeta":7,"reagentId":331,"reagentMeta":0,"outputId":373,"outputMeta":8},{"inputId":438,"inputMeta":7,"reagentId":331,"reagentMeta":0,"outputId":438,"outputMeta":8},{"inputId":441,"inputMeta":7,"reagentId":331,"reagentMeta":0,"outputId":441,"outputMeta":8},{"inputId":373,"inputMeta":9,"reagentId":376,"reagentMeta":0,"outputId":373,"outputMeta":17},{"inputId":438,"inputMeta":9,"reagentId":376,"reagentMeta":0,"outputId":438,"outputMeta":17},{"inputId":441,"inputMeta":9,"reagentId":376,"reagentMeta":0,"outputId":441,"outputMeta":17},{"inputId":373,"inputMeta":9,"reagentId":348,"reagentMeta":0,"outputId":373,"outputMeta":11},{"inputId":438,"inputMeta":9,"reagentId":348,"reagentMeta":0,"outputId":438,"outputMeta":11},{"inputId":441,"inputMeta":9,"reagentId":348,"reagentMeta":0,"outputId":441,"outputMeta":11},{"inputId":373,"inputMeta":9,"reagentId":331,"reagentMeta":0,"outputId":373,"outputMeta":10},{"inputId":438,"inputMeta":9,"reagentId":331,"reagentMeta":0,"outputId":438,"outputMeta":10},{"inputId":441,"inputMeta":9,"reagentId":331,"reagentMeta":0,"outputId":441,"outputMeta":10},{"inputId":373,"inputMeta":6,"reagentId":376,"reagentMeta":0,"outputId":373,"outputMeta":8},{"inputId":438,"inputMeta":6,"reagentId":376,"reagentMeta":0,"outputId":438,"outputMeta":8},{"inputId":441,"inputMeta":6,"reagentId":376,"reagentMeta":0,"outputId":441,"outputMeta":8},{"inputId":373,"inputMeta":15,"reagentId":376,"reagentMeta":0,"outputId":373,"outputMeta":18},{"inputId":438,"inputMeta":15,"reagentId":376,"reagentMeta":0,"outputId":438,"outputMeta":18},{"inputId":441,"inputMeta":15,"reagentId":376,"reagentMeta":0,"outputId":441,"outputMeta":18},{"inputId":373,"inputMeta":10,"reagentId":376,"reagentMeta":0,"outputId":373,"outputMeta":18},{"inputId":438,"inputMeta":10,"reagentId":376,"reagentMeta":0,"outputId":438,"outputMeta":18},{"inputId":441,"inputMeta":10,"reagentId":376,"reagentMeta":0,"outputId":441,"outputMeta":18},{"inputId":373,"inputMeta":2,"reagentId":376,"reagentMeta":0,"outputId":373,"outputMeta":35},{"inputId":438,"inputMeta":2,"reagentId":376,"reagentMeta":0,"outputId":438,"outputMeta":35},{"inputId":441,"inputMeta":2,"reagentId":376,"reagentMeta":0,"outputId":441,"outputMeta":35},{"inputId":373,"inputMeta":26,"reagentId":376,"reagentMeta":0,"outputId":373,"outputMeta":23},{"inputId":438,"inputMeta":26,"reagentId":376,"reagentMeta":0,"outputId":438,"outputMeta":23},{"inputId":441,"inputMeta":26,"reagentId":376,"reagentMeta":0,"outputId":441,"outputMeta":23},{"inputId":373,"inputMeta":32,"reagentId":376,"reagentMeta":0,"outputId":373,"outputMeta":35},{"inputId":438,"inputMeta":32,"reagentId":376,"reagentMeta":0,"outputId":438,"outputMeta":35},{"inputId":441,"inputMeta":32,"reagentId":376,"reagentMeta":0,"outputId":441,"outputMeta":35},{"inputId":373,"inputMeta":1,"reagentId":376,"reagentMeta":0,"outputId":373,"outputMeta":34},{"inputId":438,"inputMeta":1,"reagentId":376,"reagentMeta":0,"outputId":438,"outputMeta":34},{"inputId":441,"inputMeta":1,"reagentId":376,"reagentMeta":0,"outputId":441,"outputMeta":34},{"inputId":373,"inputMeta":5,"reagentId":376,"reagentMeta":0,"outputId":373,"outputMeta":7},{"inputId":438,"inputMeta":5,"reagentId":376,"reagentMeta":0,"outputId":438,"outputMeta":7},{"inputId":441,"inputMeta":5,"reagentId":376,"reagentMeta":0,"outputId":441,"outputMeta":7},{"inputId":373,"inputMeta":5,"reagentId":331,"reagentMeta":0,"outputId":373,"outputMeta":6},{"inputId":438,"inputMeta":5,"reagentId":331,"reagentMeta":0,"outputId":438,"outputMeta":6},{"inputId":441,"inputMeta":5,"reagentId":331,"reagentMeta":0,"outputId":441,"outputMeta":6},{"inputId":373,"inputMeta":25,"reagentId":376,"reagentMeta":0,"outputId":373,"outputMeta":23},{"inputId":438,"inputMeta":25,"reagentId":376,"reagentMeta":0,"outputId":438,"outputMeta":23},{"inputId":441,"inputMeta":25,"reagentId":376,"reagentMeta":0,"outputId":441,"outputMeta":23},{"inputId":373,"inputMeta":25,"reagentId":348,"reagentMeta":0,"outputId":373,"outputMeta":27},{"inputId":438,"inputMeta":25,"reagentId":348,"reagentMeta":0,"outputId":438,"outputMeta":27},{"inputId":441,"inputMeta":25,"reagentId":348,"reagentMeta":0,"outputId":441,"outputMeta":27},{"inputId":373,"inputMeta":25,"reagentId":331,"reagentMeta":0,"outputId":373,"outputMeta":26},{"inputId":438,"inputMeta":25,"reagentId":331,"reagentMeta":0,"outputId":438,"outputMeta":26},{"inputId":441,"inputMeta":25,"reagentId":331,"reagentMeta":0,"outputId":441,"outputMeta":26},{"inputId":373,"inputMeta":28,"reagentId":348,"reagentMeta":0,"outputId":373,"outputMeta":30},{"inputId":438,"inputMeta":28,"reagentId":348,"reagentMeta":0,"outputId":438,"outputMeta":30},{"inputId":441,"inputMeta":28,"reagentId":348,"reagentMeta":0,"outputId":441,"outputMeta":30},{"inputId":373,"inputMeta":28,"reagentId":331,"reagentMeta":0,"outputId":373,"outputMeta":29},{"inputId":438,"inputMeta":28,"reagentId":331,"reagentMeta":0,"outputId":438,"outputMeta":29},{"inputId":441,"inputMeta":28,"reagentId":331,"reagentMeta":0,"outputId":441,"outputMeta":29},{"inputId":373,"inputMeta":17,"reagentId":331,"reagentMeta":0,"outputId":373,"outputMeta":18},{"inputId":438,"inputMeta":17,"reagentId":331,"reagentMeta":0,"outputId":438,"outputMeta":18},{"inputId":441,"inputMeta":17,"reagentId":331,"reagentMeta":0,"outputId":441,"outputMeta":18},{"inputId":373,"inputMeta":40,"reagentId":331,"reagentMeta":0,"outputId":373,"outputMeta":41},{"inputId":438,"inputMeta":40,"reagentId":331,"reagentMeta":0,"outputId":438,"outputMeta":41},{"inputId":441,"inputMeta":40,"reagentId":331,"reagentMeta":0,"outputId":441,"outputMeta":41},{"inputId":373,"inputMeta":31,"reagentId":376,"reagentMeta":0,"outputId":373,"outputMeta":34},{"inputId":438,"inputMeta":31,"reagentId":376,"reagentMeta":0,"outputId":438,"outputMeta":34},{"inputId":441,"inputMeta":31,"reagentId":376,"reagentMeta":0,"outputId":441,"outputMeta":34},{"inputId":373,"inputMeta":31,"reagentId":348,"reagentMeta":0,"outputId":373,"outputMeta":33},{"inputId":438,"inputMeta":31,"reagentId":348,"reagentMeta":0,"outputId":438,"outputMeta":33},{"inputId":441,"inputMeta":31,"reagentId":348,"reagentMeta":0,"outputId":441,"outputMeta":33},{"inputId":373,"inputMeta":31,"reagentId":331,"reagentMeta":0,"outputId":373,"outputMeta":32},{"inputId":438,"inputMeta":31,"reagentId":331,"reagentMeta":0,"outputId":438,"outputMeta":32},{"inputId":441,"inputMeta":31,"reagentId":331,"reagentMeta":0,"outputId":441,"outputMeta":32},{"inputId":373,"inputMeta":22,"reagentId":376,"reagentMeta":0,"outputId":373,"outputMeta":24},{"inputId":438,"inputMeta":22,"reagentId":376,"reagentMeta":0,"outputId":438,"outputMeta":24},{"inputId":441,"inputMeta":22,"reagentId":376,"reagentMeta":0,"outputId":441,"outputMeta":24},{"inputId":373,"inputMeta":33,"reagentId":376,"reagentMeta":0,"outputId":373,"outputMeta":34},{"inputId":438,"inputMeta":33,"reagentId":376,"reagentMeta":0,"outputId":438,"outputMeta":34},{"inputId":441,"inputMeta":33,"reagentId":376,"reagentMeta":0,"outputId":441,"outputMeta":34},{"inputId":373,"inputMeta":14,"reagentId":376,"reagentMeta":0,"outputId":373,"outputMeta":17},{"inputId":438,"inputMeta":14,"reagentId":376,"reagentMeta":0,"outputId":438,"outputMeta":17},{"inputId":441,"inputMeta":14,"reagentId":376,"reagentMeta":0,"outputId":441,"outputMeta":17},{"inputId":373,"inputMeta":14,"reagentId":348,"reagentMeta":0,"outputId":373,"outputMeta":16},{"inputId":438,"inputMeta":14,"reagentId":348,"reagentMeta":0,"outputId":438,"outputMeta":16},{"inputId":441,"inputMeta":14,"reagentId":348,"reagentMeta":0,"outputId":441,"outputMeta":16},{"inputId":373,"inputMeta":14,"reagentId":331,"reagentMeta":0,"outputId":373,"outputMeta":15},{"inputId":438,"inputMeta":14,"reagentId":331,"reagentMeta":0,"outputId":438,"outputMeta":15},{"inputId":441,"inputMeta":14,"reagentId":331,"reagentMeta":0,"outputId":441,"outputMeta":15},{"inputId":373,"inputMeta":3,"reagentId":376,"reagentMeta":0,"outputId":373,"outputMeta":34},{"inputId":438,"inputMeta":3,"reagentId":376,"reagentMeta":0,"outputId":438,"outputMeta":34},{"inputId":441,"inputMeta":3,"reagentId":376,"reagentMeta":0,"outputId":441,"outputMeta":34},{"inputId":373,"inputMeta":37,"reagentId":348,"reagentMeta":0,"outputId":373,"outputMeta":39},{"inputId":438,"inputMeta":37,"reagentId":348,"reagentMeta":0,"outputId":438,"outputMeta":39},{"inputId":441,"inputMeta":37,"reagentId":348,"reagentMeta":0,"outputId":441,"outputMeta":39},{"inputId":373,"inputMeta":37,"reagentId":331,"reagentMeta":0,"outputId":373,"outputMeta":38},{"inputId":438,"inputMeta":37,"reagentId":331,"reagentMeta":0,"outputId":438,"outputMeta":38},{"inputId":441,"inputMeta":37,"reagentId":331,"reagentMeta":0,"outputId":441,"outputMeta":38},{"inputId":373,"inputMeta":0,"reagentId":377,"reagentMeta":0,"outputId":373,"outputMeta":1},{"inputId":438,"inputMeta":0,"reagentId":377,"reagentMeta":0,"outputId":438,"outputMeta":1},{"inputId":441,"inputMeta":0,"reagentId":377,"reagentMeta":0,"outputId":441,"outputMeta":1},{"inputId":373,"inputMeta":19,"reagentId":331,"reagentMeta":0,"outputId":373,"outputMeta":20},{"inputId":438,"inputMeta":19,"reagentId":331,"reagentMeta":0,"outputId":438,"outputMeta":20},{"inputId":441,"inputMeta":19,"reagentId":331,"reagentMeta":0,"outputId":441,"outputMeta":20},{"inputId":373,"inputMeta":0,"reagentId":376,"reagentMeta":0,"outputId":373,"outputMeta":34},{"inputId":438,"inputMeta":0,"reagentId":376,"reagentMeta":0,"outputId":438,"outputMeta":34},{"inputId":441,"inputMeta":0,"reagentId":376,"reagentMeta":0,"outputId":441,"outputMeta":34},{"inputId":373,"inputMeta":0,"reagentId":370,"reagentMeta":0,"outputId":373,"outputMeta":1},{"inputId":438,"inputMeta":0,"reagentId":370,"reagentMeta":0,"outputId":438,"outputMeta":1},{"inputId":441,"inputMeta":0,"reagentId":370,"reagentMeta":0,"outputId":441,"outputMeta":1},{"inputId":373,"inputMeta":0,"reagentId":348,"reagentMeta":0,"outputId":373,"outputMeta":3},{"inputId":438,"inputMeta":0,"reagentId":348,"reagentMeta":0,"outputId":438,"outputMeta":3},{"inputId":441,"inputMeta":0,"reagentId":348,"reagentMeta":0,"outputId":441,"outputMeta":3},{"inputId":373,"inputMeta":0,"reagentId":378,"reagentMeta":0,"outputId":373,"outputMeta":1},{"inputId":438,"inputMeta":0,"reagentId":378,"reagentMeta":0,"outputId":438,"outputMeta":1},{"inputId":441,"inputMeta":0,"reagentId":378,"reagentMeta":0,"outputId":441,"outputMeta":1},{"inputId":373,"inputMeta":0,"reagentId":372,"reagentMeta":0,"outputId":373,"outputMeta":4},{"inputId":438,"inputMeta":0,"reagentId":372,"reagentMeta":0,"outputId":438,"outputMeta":4},{"inputId":441,"inputMeta":0,"reagentId":372,"reagentMeta":0,"outputId":441,"outputMeta":4},{"inputId":373,"inputMeta":0,"reagentId":414,"reagentMeta":0,"outputId":373,"outputMeta":1},{"inputId":438,"inputMeta":0,"reagentId":414,"reagentMeta":0,"outputId":438,"outputMeta":1},{"inputId":441,"inputMeta":0,"reagentId":414,"reagentMeta":0,"outputId":441,"outputMeta":1},{"inputId":373,"inputMeta":0,"reagentId":331,"reagentMeta":0,"outputId":373,"outputMeta":1},{"inputId":438,"inputMeta":0,"reagentId":331,"reagentMeta":0,"outputId":438,"outputMeta":1},{"inputId":441,"inputMeta":0,"reagentId":331,"reagentMeta":0,"outputId":441,"outputMeta":1},{"inputId":373,"inputMeta":0,"reagentId":382,"reagentMeta":0,"outputId":373,"outputMeta":1},{"inputId":438,"inputMeta":0,"reagentId":382,"reagentMeta":0,"outputId":438,"outputMeta":1},{"inputId":441,"inputMeta":0,"reagentId":382,"reagentMeta":0,"outputId":441,"outputMeta":1},{"inputId":373,"inputMeta":0,"reagentId":375,"reagentMeta":0,"outputId":373,"outputMeta":1},{"inputId":438,"inputMeta":0,"reagentId":375,"reagentMeta":0,"outputId":438,"outputMeta":1},{"inputId":441,"inputMeta":0,"reagentId":375,"reagentMeta":0,"outputId":441,"outputMeta":1},{"inputId":373,"inputMeta":0,"reagentId":353,"reagentMeta":0,"outputId":373,"outputMeta":1},{"inputId":438,"inputMeta":0,"reagentId":353,"reagentMeta":0,"outputId":438,"outputMeta":1},{"inputId":441,"inputMeta":0,"reagentId":353,"reagentMeta":0,"outputId":441,"outputMeta":1},{"inputId":373,"inputMeta":34,"reagentId":331,"reagentMeta":0,"outputId":373,"outputMeta":35},{"inputId":438,"inputMeta":34,"reagentId":331,"reagentMeta":0,"outputId":438,"outputMeta":35},{"inputId":441,"inputMeta":34,"reagentId":331,"reagentMeta":0,"outputId":441,"outputMeta":35}],"containerMixes":[{"inputId":373,"reagentId":289,"outputId":438},{"inputId":438,"reagentId":437,"outputId":441}]} \ No newline at end of file +{"recipes":[{"output":[{"id":-140}],"input":{"A":{"damage":4,"id":5}},"shape":["A"],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":-141}],"input":{"A":{"damage":2,"id":5}},"shape":["A"],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":-142}],"input":{"A":{"damage":5,"id":5}},"shape":["A"],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":-143}],"input":{"A":{"damage":3,"id":5}},"shape":["A"],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":-144}],"input":{"A":{"damage":1,"id":5}},"shape":["A"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":3,"count":6,"id":44}],"input":{"A":{"id":4}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":7,"count":6,"id":44}],"input":{"A":{"id":112}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":1,"count":6,"id":44}],"input":{"A":{"id":24}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":-150}],"input":{"A":{"damage":4,"id":5}},"shape":["AA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":-151}],"input":{"A":{"damage":2,"id":5}},"shape":["AA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":-152}],"input":{"A":{"damage":5,"id":5}},"shape":["AA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":-153}],"input":{"A":{"damage":3,"id":5}},"shape":["AA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":-154}],"input":{"A":{"damage":1,"id":5}},"shape":["AA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":280}],"input":{"A":{"id":-163}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":2,"count":6,"id":-166}],"input":{"A":{"id":1}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"count":6,"id":-166}],"input":{"A":{"damage":1,"id":98}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":4,"count":6,"id":44}],"input":{"A":{"id":45}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":5,"count":6,"id":44}],"input":{"A":{"id":98}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"count":6,"id":44}],"input":{"A":{"id":-183}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"count":2,"id":-145}],"input":{"A":{"damage":4,"id":5}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"count":2,"id":-146}],"input":{"A":{"damage":2,"id":5}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"count":2,"id":-147}],"input":{"A":{"damage":5,"id":5}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"count":2,"id":-148}],"input":{"A":{"damage":3,"id":5}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"count":2,"id":-149}],"input":{"A":{"damage":1,"id":5}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"count":2,"id":96}],"input":{"A":{"id":5}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":143}],"input":{"A":{"id":5}},"shape":["A"],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":72}],"input":{"A":{"id":5}},"shape":["AA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"count":4,"id":163}],"input":{"A":{"damage":4,"id":5}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":14,"id":355}],"input":{"A":{"damage":14,"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":14,"id":355}],"input":{"A":{"damage":14,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":14,"id":355}],"input":{"A":{"damage":14,"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":14,"id":355}],"input":{"A":{"damage":14,"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":14,"id":355}],"input":{"A":{"damage":14,"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":14,"id":355}],"input":{"A":{"damage":14,"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":14,"id":355}],"input":{"A":{"damage":14,"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":14,"id":355}],"input":{"A":{"damage":14,"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":14,"id":355}],"input":{"A":{"damage":14,"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":14,"id":355}],"input":{"A":{"damage":14,"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":14,"id":355}],"input":{"A":{"damage":14,"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"id":355}],"input":{"A":{"damage":5,"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"id":355}],"input":{"A":{"damage":5,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"id":355}],"input":{"A":{"damage":5,"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"id":355}],"input":{"A":{"damage":5,"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"id":355}],"input":{"A":{"damage":5,"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"id":355}],"input":{"A":{"damage":5,"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"id":355}],"input":{"A":{"damage":5,"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"id":355}],"input":{"A":{"damage":5,"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"id":355}],"input":{"A":{"damage":5,"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"id":355}],"input":{"A":{"damage":5,"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"id":355}],"input":{"A":{"damage":5,"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"id":355}],"input":{"A":{"damage":4,"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"id":355}],"input":{"A":{"damage":4,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"id":355}],"input":{"A":{"damage":4,"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"id":355}],"input":{"A":{"damage":4,"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"id":355}],"input":{"A":{"damage":4,"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"id":355}],"input":{"A":{"damage":4,"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"id":355}],"input":{"A":{"damage":4,"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"id":355}],"input":{"A":{"damage":4,"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"id":355}],"input":{"A":{"damage":4,"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"id":355}],"input":{"A":{"damage":4,"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"id":355}],"input":{"A":{"damage":4,"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"id":355}],"input":{"A":{"damage":3,"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"id":355}],"input":{"A":{"damage":3,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"id":355}],"input":{"A":{"damage":3,"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"id":355}],"input":{"A":{"damage":3,"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"id":355}],"input":{"A":{"damage":3,"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"id":355}],"input":{"A":{"damage":3,"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"id":355}],"input":{"A":{"damage":3,"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"id":355}],"input":{"A":{"damage":3,"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"id":355}],"input":{"A":{"damage":3,"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"id":355}],"input":{"A":{"damage":3,"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"id":355}],"input":{"A":{"damage":3,"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"id":355}],"input":{"A":{"damage":2,"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"id":355}],"input":{"A":{"damage":2,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"id":355}],"input":{"A":{"damage":2,"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"id":355}],"input":{"A":{"damage":2,"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"id":355}],"input":{"A":{"damage":2,"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"id":355}],"input":{"A":{"damage":2,"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"id":355}],"input":{"A":{"damage":2,"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"id":355}],"input":{"A":{"damage":2,"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"id":355}],"input":{"A":{"damage":2,"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"id":355}],"input":{"A":{"damage":2,"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"id":355}],"input":{"A":{"damage":2,"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"id":355}],"input":{"A":{"damage":1,"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"id":355}],"input":{"A":{"damage":1,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"id":355}],"input":{"A":{"damage":1,"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"id":355}],"input":{"A":{"damage":1,"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"id":355}],"input":{"A":{"damage":1,"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"id":355}],"input":{"A":{"damage":1,"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"id":355}],"input":{"A":{"damage":1,"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"id":355}],"input":{"A":{"damage":1,"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"id":355}],"input":{"A":{"damage":1,"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"id":355}],"input":{"A":{"damage":1,"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"id":355}],"input":{"A":{"damage":1,"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":13,"id":355}],"input":{"A":{"damage":13,"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":13,"id":355}],"input":{"A":{"damage":13,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":13,"id":355}],"input":{"A":{"damage":13,"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":13,"id":355}],"input":{"A":{"damage":13,"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":13,"id":355}],"input":{"A":{"damage":13,"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":13,"id":355}],"input":{"A":{"damage":13,"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":13,"id":355}],"input":{"A":{"damage":13,"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":13,"id":355}],"input":{"A":{"damage":13,"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":13,"id":355}],"input":{"A":{"damage":13,"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":13,"id":355}],"input":{"A":{"damage":13,"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":13,"id":355}],"input":{"A":{"damage":13,"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":10,"id":355}],"input":{"A":{"damage":10,"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":10,"id":355}],"input":{"A":{"damage":10,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":10,"id":355}],"input":{"A":{"damage":10,"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":10,"id":355}],"input":{"A":{"damage":10,"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":10,"id":355}],"input":{"A":{"damage":10,"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":10,"id":355}],"input":{"A":{"damage":10,"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":10,"id":355}],"input":{"A":{"damage":10,"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":10,"id":355}],"input":{"A":{"damage":10,"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":10,"id":355}],"input":{"A":{"damage":10,"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":10,"id":355}],"input":{"A":{"damage":10,"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":10,"id":355}],"input":{"A":{"damage":10,"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":9,"id":355}],"input":{"A":{"damage":9,"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":9,"id":355}],"input":{"A":{"damage":9,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":9,"id":355}],"input":{"A":{"damage":9,"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":9,"id":355}],"input":{"A":{"damage":9,"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":9,"id":355}],"input":{"A":{"damage":9,"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":9,"id":355}],"input":{"A":{"damage":9,"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":9,"id":355}],"input":{"A":{"damage":9,"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":9,"id":355}],"input":{"A":{"damage":9,"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":9,"id":355}],"input":{"A":{"damage":9,"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":9,"id":355}],"input":{"A":{"damage":9,"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":9,"id":355}],"input":{"A":{"damage":9,"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":8,"id":355}],"input":{"A":{"damage":8,"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":8,"id":355}],"input":{"A":{"damage":8,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":8,"id":355}],"input":{"A":{"damage":8,"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":8,"id":355}],"input":{"A":{"damage":8,"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":8,"id":355}],"input":{"A":{"damage":8,"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":8,"id":355}],"input":{"A":{"damage":8,"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":8,"id":355}],"input":{"A":{"damage":8,"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":8,"id":355}],"input":{"A":{"damage":8,"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":8,"id":355}],"input":{"A":{"damage":8,"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":8,"id":355}],"input":{"A":{"damage":8,"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":8,"id":355}],"input":{"A":{"damage":8,"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":7,"id":355}],"input":{"A":{"damage":7,"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":7,"id":355}],"input":{"A":{"damage":7,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":7,"id":355}],"input":{"A":{"damage":7,"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":7,"id":355}],"input":{"A":{"damage":7,"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":7,"id":355}],"input":{"A":{"damage":7,"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":7,"id":355}],"input":{"A":{"damage":7,"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":7,"id":355}],"input":{"A":{"damage":7,"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":7,"id":355}],"input":{"A":{"damage":7,"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":7,"id":355}],"input":{"A":{"damage":7,"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":7,"id":355}],"input":{"A":{"damage":7,"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":7,"id":355}],"input":{"A":{"damage":7,"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":6,"id":355}],"input":{"A":{"damage":6,"id":35},"B":{"id":-537}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":6,"id":355}],"input":{"A":{"damage":6,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":6,"id":355}],"input":{"A":{"damage":6,"id":35},"B":{"id":-243}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":6,"id":355}],"input":{"A":{"damage":6,"id":35},"B":{"id":-486}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":6,"id":355}],"input":{"A":{"damage":6,"id":35},"B":{"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":6,"id":355}],"input":{"A":{"damage":6,"id":35},"B":{"damage":1,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":6,"id":355}],"input":{"A":{"damage":6,"id":35},"B":{"damage":2,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":6,"id":355}],"input":{"A":{"damage":6,"id":35},"B":{"damage":3,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":6,"id":355}],"input":{"A":{"damage":6,"id":35},"B":{"damage":4,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":6,"id":355}],"input":{"A":{"damage":6,"id":35},"B":{"damage":5,"id":5}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":6,"id":355}],"input":{"A":{"damage":6,"id":35},"B":{"id":-242}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":355}],"input":{"A":{"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":1,"id":355}],"input":{"A":{"damage":1,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":10,"id":355}],"input":{"A":{"damage":10,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":11,"id":355}],"input":{"A":{"damage":11,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":12,"id":355}],"input":{"A":{"damage":12,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":13,"id":355}],"input":{"A":{"damage":13,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":14,"id":355}],"input":{"A":{"damage":14,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":15,"id":355}],"input":{"A":{"damage":15,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":2,"id":355}],"input":{"A":{"damage":2,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":3,"id":355}],"input":{"A":{"damage":3,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":4,"id":355}],"input":{"A":{"damage":4,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":5,"id":355}],"input":{"A":{"damage":5,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":6,"id":355}],"input":{"A":{"damage":6,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":7,"id":355}],"input":{"A":{"damage":7,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":8,"id":355}],"input":{"A":{"damage":8,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":9,"id":355}],"input":{"A":{"damage":9,"id":35},"B":{"id":-510}},"shape":["AAA","BBB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":15,"id":355}],"input":[{"id":351},{"damage":14,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"id":351},{"damage":5,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"id":351},{"damage":4,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"id":351},{"damage":3,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"id":351},{"damage":2,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"id":351},{"damage":1,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"id":351},{"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"id":351},{"damage":13,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"id":351},{"damage":12,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"id":351},{"damage":11,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"id":351},{"damage":10,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"id":351},{"damage":9,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"id":351},{"damage":8,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"id":351},{"damage":7,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"id":351},{"damage":6,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":355}],"input":[{"damage":10,"id":351},{"damage":15,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":355}],"input":[{"damage":10,"id":351},{"damage":14,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":355}],"input":[{"damage":10,"id":351},{"damage":4,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":355}],"input":[{"damage":10,"id":351},{"damage":3,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":355}],"input":[{"damage":10,"id":351},{"damage":2,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":355}],"input":[{"damage":10,"id":351},{"damage":1,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":355}],"input":[{"damage":10,"id":351},{"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":355}],"input":[{"damage":10,"id":351},{"damage":13,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":355}],"input":[{"damage":10,"id":351},{"damage":12,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":355}],"input":[{"damage":10,"id":351},{"damage":11,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":355}],"input":[{"damage":10,"id":351},{"damage":10,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":355}],"input":[{"damage":10,"id":351},{"damage":9,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":355}],"input":[{"damage":10,"id":351},{"damage":8,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":355}],"input":[{"damage":10,"id":351},{"damage":7,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":355}],"input":[{"damage":10,"id":351},{"damage":6,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":355}],"input":[{"damage":11,"id":351},{"damage":15,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":355}],"input":[{"damage":11,"id":351},{"damage":14,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":355}],"input":[{"damage":11,"id":351},{"damage":5,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":355}],"input":[{"damage":11,"id":351},{"damage":3,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":355}],"input":[{"damage":11,"id":351},{"damage":2,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":355}],"input":[{"damage":11,"id":351},{"damage":1,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":355}],"input":[{"damage":11,"id":351},{"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":355}],"input":[{"damage":11,"id":351},{"damage":13,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":355}],"input":[{"damage":11,"id":351},{"damage":12,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":355}],"input":[{"damage":11,"id":351},{"damage":11,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":355}],"input":[{"damage":11,"id":351},{"damage":10,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":355}],"input":[{"damage":11,"id":351},{"damage":9,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":355}],"input":[{"damage":11,"id":351},{"damage":8,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":355}],"input":[{"damage":11,"id":351},{"damage":7,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":355}],"input":[{"damage":11,"id":351},{"damage":6,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":355}],"input":[{"damage":12,"id":351},{"damage":15,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":355}],"input":[{"damage":12,"id":351},{"damage":14,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":355}],"input":[{"damage":12,"id":351},{"damage":5,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":355}],"input":[{"damage":12,"id":351},{"damage":4,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":355}],"input":[{"damage":12,"id":351},{"damage":2,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":355}],"input":[{"damage":12,"id":351},{"damage":1,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":355}],"input":[{"damage":12,"id":351},{"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":355}],"input":[{"damage":12,"id":351},{"damage":13,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":355}],"input":[{"damage":12,"id":351},{"damage":12,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":355}],"input":[{"damage":12,"id":351},{"damage":11,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":355}],"input":[{"damage":12,"id":351},{"damage":10,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":355}],"input":[{"damage":12,"id":351},{"damage":9,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":355}],"input":[{"damage":12,"id":351},{"damage":8,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":355}],"input":[{"damage":12,"id":351},{"damage":7,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":355}],"input":[{"damage":12,"id":351},{"damage":6,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":355}],"input":[{"damage":13,"id":351},{"damage":15,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":355}],"input":[{"damage":13,"id":351},{"damage":14,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":355}],"input":[{"damage":13,"id":351},{"damage":5,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":355}],"input":[{"damage":13,"id":351},{"damage":4,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":355}],"input":[{"damage":13,"id":351},{"damage":3,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":355}],"input":[{"damage":13,"id":351},{"damage":1,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":355}],"input":[{"damage":13,"id":351},{"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":355}],"input":[{"damage":13,"id":351},{"damage":13,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":355}],"input":[{"damage":13,"id":351},{"damage":12,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":355}],"input":[{"damage":13,"id":351},{"damage":11,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":355}],"input":[{"damage":13,"id":351},{"damage":10,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":355}],"input":[{"damage":13,"id":351},{"damage":9,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":355}],"input":[{"damage":13,"id":351},{"damage":8,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":355}],"input":[{"damage":13,"id":351},{"damage":7,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":355}],"input":[{"damage":13,"id":351},{"damage":6,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":355}],"input":[{"damage":14,"id":351},{"damage":15,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":355}],"input":[{"damage":14,"id":351},{"damage":14,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":355}],"input":[{"damage":14,"id":351},{"damage":5,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":355}],"input":[{"damage":14,"id":351},{"damage":4,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":355}],"input":[{"damage":14,"id":351},{"damage":3,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":355}],"input":[{"damage":14,"id":351},{"damage":2,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":355}],"input":[{"damage":14,"id":351},{"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":355}],"input":[{"damage":14,"id":351},{"damage":13,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":355}],"input":[{"damage":14,"id":351},{"damage":12,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":355}],"input":[{"damage":14,"id":351},{"damage":11,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":355}],"input":[{"damage":14,"id":351},{"damage":10,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":355}],"input":[{"damage":14,"id":351},{"damage":9,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":355}],"input":[{"damage":14,"id":351},{"damage":8,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":355}],"input":[{"damage":14,"id":351},{"damage":7,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":355}],"input":[{"damage":14,"id":351},{"damage":6,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":15,"id":351},{"damage":15,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":15,"id":351},{"damage":14,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":15,"id":351},{"damage":5,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":15,"id":351},{"damage":4,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":15,"id":351},{"damage":3,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":15,"id":351},{"damage":2,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":15,"id":351},{"damage":1,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":15,"id":351},{"damage":13,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":15,"id":351},{"damage":12,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":15,"id":351},{"damage":11,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":15,"id":351},{"damage":10,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":15,"id":351},{"damage":9,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":15,"id":351},{"damage":8,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":15,"id":351},{"damage":7,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":15,"id":351},{"damage":6,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"damage":16,"id":351},{"damage":14,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"damage":16,"id":351},{"damage":5,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"damage":16,"id":351},{"damage":4,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"damage":16,"id":351},{"damage":3,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"damage":16,"id":351},{"damage":2,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"damage":16,"id":351},{"damage":1,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"damage":16,"id":351},{"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"damage":16,"id":351},{"damage":13,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"damage":16,"id":351},{"damage":12,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"damage":16,"id":351},{"damage":11,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"damage":16,"id":351},{"damage":10,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"damage":16,"id":351},{"damage":9,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"damage":16,"id":351},{"damage":8,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"damage":16,"id":351},{"damage":7,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":355}],"input":[{"damage":16,"id":351},{"damage":6,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":17,"id":351},{"damage":15,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":17,"id":351},{"damage":14,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":17,"id":351},{"damage":5,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":17,"id":351},{"damage":4,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":17,"id":351},{"damage":3,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":17,"id":351},{"damage":2,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":17,"id":351},{"damage":1,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":17,"id":351},{"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":17,"id":351},{"damage":13,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":17,"id":351},{"damage":11,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":17,"id":351},{"damage":10,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":17,"id":351},{"damage":9,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":17,"id":351},{"damage":8,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":17,"id":351},{"damage":7,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":17,"id":351},{"damage":6,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":18,"id":351},{"damage":15,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":18,"id":351},{"damage":14,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":18,"id":351},{"damage":5,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":18,"id":351},{"damage":4,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":18,"id":351},{"damage":3,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":18,"id":351},{"damage":2,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":18,"id":351},{"damage":1,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":18,"id":351},{"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":18,"id":351},{"damage":13,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":18,"id":351},{"damage":12,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":18,"id":351},{"damage":10,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":18,"id":351},{"damage":9,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":18,"id":351},{"damage":8,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":18,"id":351},{"damage":7,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":18,"id":351},{"damage":6,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":19,"id":351},{"damage":15,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":19,"id":351},{"damage":14,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":19,"id":351},{"damage":5,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":19,"id":351},{"damage":4,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":19,"id":351},{"damage":3,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":19,"id":351},{"damage":2,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":19,"id":351},{"damage":1,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":19,"id":351},{"damage":13,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":19,"id":351},{"damage":12,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":19,"id":351},{"damage":11,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":19,"id":351},{"damage":10,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":19,"id":351},{"damage":9,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":19,"id":351},{"damage":8,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":19,"id":351},{"damage":7,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":355}],"input":[{"damage":19,"id":351},{"damage":6,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":355}],"input":[{"damage":1,"id":351},{"damage":15,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":355}],"input":[{"damage":1,"id":351},{"damage":5,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":355}],"input":[{"damage":1,"id":351},{"damage":4,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":355}],"input":[{"damage":1,"id":351},{"damage":3,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":355}],"input":[{"damage":1,"id":351},{"damage":2,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":355}],"input":[{"damage":1,"id":351},{"damage":1,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":355}],"input":[{"damage":1,"id":351},{"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":355}],"input":[{"damage":1,"id":351},{"damage":13,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":355}],"input":[{"damage":1,"id":351},{"damage":12,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":355}],"input":[{"damage":1,"id":351},{"damage":11,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":355}],"input":[{"damage":1,"id":351},{"damage":10,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":355}],"input":[{"damage":1,"id":351},{"damage":9,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":355}],"input":[{"damage":1,"id":351},{"damage":8,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":355}],"input":[{"damage":1,"id":351},{"damage":7,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":355}],"input":[{"damage":1,"id":351},{"damage":6,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":355}],"input":[{"damage":2,"id":351},{"damage":15,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":355}],"input":[{"damage":2,"id":351},{"damage":14,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":355}],"input":[{"damage":2,"id":351},{"damage":5,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":355}],"input":[{"damage":2,"id":351},{"damage":4,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":355}],"input":[{"damage":2,"id":351},{"damage":3,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":355}],"input":[{"damage":2,"id":351},{"damage":2,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":355}],"input":[{"damage":2,"id":351},{"damage":1,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":355}],"input":[{"damage":2,"id":351},{"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":355}],"input":[{"damage":2,"id":351},{"damage":12,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":355}],"input":[{"damage":2,"id":351},{"damage":11,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":355}],"input":[{"damage":2,"id":351},{"damage":10,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":355}],"input":[{"damage":2,"id":351},{"damage":9,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":355}],"input":[{"damage":2,"id":351},{"damage":8,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":355}],"input":[{"damage":2,"id":351},{"damage":7,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":355}],"input":[{"damage":2,"id":351},{"damage":6,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":3,"id":351},{"damage":15,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":3,"id":351},{"damage":14,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":3,"id":351},{"damage":5,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":3,"id":351},{"damage":4,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":3,"id":351},{"damage":3,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":3,"id":351},{"damage":2,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":3,"id":351},{"damage":1,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":3,"id":351},{"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":3,"id":351},{"damage":13,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":3,"id":351},{"damage":11,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":3,"id":351},{"damage":10,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":3,"id":351},{"damage":9,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":3,"id":351},{"damage":8,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":3,"id":351},{"damage":7,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":355}],"input":[{"damage":3,"id":351},{"damage":6,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":4,"id":351},{"damage":15,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":4,"id":351},{"damage":14,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":4,"id":351},{"damage":5,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":4,"id":351},{"damage":4,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":4,"id":351},{"damage":3,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":4,"id":351},{"damage":2,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":4,"id":351},{"damage":1,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":4,"id":351},{"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":4,"id":351},{"damage":13,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":4,"id":351},{"damage":12,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":4,"id":351},{"damage":10,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":4,"id":351},{"damage":9,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":4,"id":351},{"damage":8,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":4,"id":351},{"damage":7,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":355}],"input":[{"damage":4,"id":351},{"damage":6,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":355}],"input":[{"damage":5,"id":351},{"damage":15,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":355}],"input":[{"damage":5,"id":351},{"damage":14,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":355}],"input":[{"damage":5,"id":351},{"damage":5,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":355}],"input":[{"damage":5,"id":351},{"damage":4,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":355}],"input":[{"damage":5,"id":351},{"damage":3,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":355}],"input":[{"damage":5,"id":351},{"damage":2,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":355}],"input":[{"damage":5,"id":351},{"damage":1,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":355}],"input":[{"damage":5,"id":351},{"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":355}],"input":[{"damage":5,"id":351},{"damage":13,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":355}],"input":[{"damage":5,"id":351},{"damage":12,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":355}],"input":[{"damage":5,"id":351},{"damage":11,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":355}],"input":[{"damage":5,"id":351},{"damage":9,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":355}],"input":[{"damage":5,"id":351},{"damage":8,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":355}],"input":[{"damage":5,"id":351},{"damage":7,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":355}],"input":[{"damage":5,"id":351},{"damage":6,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":355}],"input":[{"damage":6,"id":351},{"damage":15,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":355}],"input":[{"damage":6,"id":351},{"damage":14,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":355}],"input":[{"damage":6,"id":351},{"damage":5,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":355}],"input":[{"damage":6,"id":351},{"damage":4,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":355}],"input":[{"damage":6,"id":351},{"damage":3,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":355}],"input":[{"damage":6,"id":351},{"damage":2,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":355}],"input":[{"damage":6,"id":351},{"damage":1,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":355}],"input":[{"damage":6,"id":351},{"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":355}],"input":[{"damage":6,"id":351},{"damage":13,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":355}],"input":[{"damage":6,"id":351},{"damage":12,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":355}],"input":[{"damage":6,"id":351},{"damage":11,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":355}],"input":[{"damage":6,"id":351},{"damage":10,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":355}],"input":[{"damage":6,"id":351},{"damage":8,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":355}],"input":[{"damage":6,"id":351},{"damage":7,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":355}],"input":[{"damage":6,"id":351},{"damage":6,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":355}],"input":[{"damage":7,"id":351},{"damage":15,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":355}],"input":[{"damage":7,"id":351},{"damage":14,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":355}],"input":[{"damage":7,"id":351},{"damage":5,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":355}],"input":[{"damage":7,"id":351},{"damage":4,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":355}],"input":[{"damage":7,"id":351},{"damage":3,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":355}],"input":[{"damage":7,"id":351},{"damage":2,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":355}],"input":[{"damage":7,"id":351},{"damage":1,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":355}],"input":[{"damage":7,"id":351},{"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":355}],"input":[{"damage":7,"id":351},{"damage":13,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":355}],"input":[{"damage":7,"id":351},{"damage":12,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":355}],"input":[{"damage":7,"id":351},{"damage":11,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":355}],"input":[{"damage":7,"id":351},{"damage":10,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":355}],"input":[{"damage":7,"id":351},{"damage":9,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":355}],"input":[{"damage":7,"id":351},{"damage":7,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":355}],"input":[{"damage":7,"id":351},{"damage":6,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":355}],"input":[{"damage":8,"id":351},{"damage":15,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":355}],"input":[{"damage":8,"id":351},{"damage":14,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":355}],"input":[{"damage":8,"id":351},{"damage":5,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":355}],"input":[{"damage":8,"id":351},{"damage":4,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":355}],"input":[{"damage":8,"id":351},{"damage":3,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":355}],"input":[{"damage":8,"id":351},{"damage":2,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":355}],"input":[{"damage":8,"id":351},{"damage":1,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":355}],"input":[{"damage":8,"id":351},{"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":355}],"input":[{"damage":8,"id":351},{"damage":13,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":355}],"input":[{"damage":8,"id":351},{"damage":12,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":355}],"input":[{"damage":8,"id":351},{"damage":11,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":355}],"input":[{"damage":8,"id":351},{"damage":10,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":355}],"input":[{"damage":8,"id":351},{"damage":9,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":355}],"input":[{"damage":8,"id":351},{"damage":8,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":355}],"input":[{"damage":8,"id":351},{"damage":6,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":355}],"input":[{"damage":9,"id":351},{"damage":15,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":355}],"input":[{"damage":9,"id":351},{"damage":14,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":355}],"input":[{"damage":9,"id":351},{"damage":5,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":355}],"input":[{"damage":9,"id":351},{"damage":4,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":355}],"input":[{"damage":9,"id":351},{"damage":3,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":355}],"input":[{"damage":9,"id":351},{"damage":2,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":355}],"input":[{"damage":9,"id":351},{"damage":1,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":355}],"input":[{"damage":9,"id":351},{"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":355}],"input":[{"damage":9,"id":351},{"damage":13,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":355}],"input":[{"damage":9,"id":351},{"damage":12,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":355}],"input":[{"damage":9,"id":351},{"damage":11,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":355}],"input":[{"damage":9,"id":351},{"damage":10,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":355}],"input":[{"damage":9,"id":351},{"damage":9,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":355}],"input":[{"damage":9,"id":351},{"damage":8,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":355}],"input":[{"damage":9,"id":351},{"damage":7,"id":355}],"block":"crafting_table","type":0,"priority":50},{"output":[{"count":4,"id":135}],"input":{"A":{"damage":2,"id":5}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":1,"id":155}],"input":{"A":{"damage":6,"id":44}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":3,"id":98}],"input":{"A":{"damage":5,"id":44}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":50},{"output":[{"count":4,"id":164}],"input":{"A":{"damage":5,"id":5}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":-551}],"input":{"A":{"id":336}},"shape":[" A ","A A"," A "],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":1,"id":179}],"input":{"A":{"id":182}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":1,"id":24}],"input":{"A":{"damage":1,"id":44}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":50},{"output":[{"count":4,"id":136}],"input":{"A":{"damage":3,"id":5}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":2,"id":201}],"input":{"A":{"damage":1,"id":182}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":47}],"input":{"A":{"id":-537},"B":{"id":340}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":47}],"input":{"A":{"id":-510},"B":{"id":340}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":47}],"input":{"A":{"id":-243},"B":{"id":340}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":47}],"input":{"A":{"id":-486},"B":{"id":340}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":47}],"input":{"A":{"id":5},"B":{"id":340}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":47}],"input":{"A":{"damage":1,"id":5},"B":{"id":340}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":47}],"input":{"A":{"damage":2,"id":5},"B":{"id":340}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":47}],"input":{"A":{"damage":3,"id":5},"B":{"id":340}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":47}],"input":{"A":{"damage":4,"id":5},"B":{"id":340}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":47}],"input":{"A":{"damage":5,"id":5},"B":{"id":340}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":47}],"input":{"A":{"id":-242},"B":{"id":340}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":281}],"input":{"A":{"id":-537}},"shape":["A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":281}],"input":{"A":{"id":-510}},"shape":["A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":281}],"input":{"A":{"id":-243}},"shape":["A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":281}],"input":{"A":{"id":-486}},"shape":["A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":281}],"input":{"A":{"id":5}},"shape":["A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":281}],"input":{"A":{"damage":1,"id":5}},"shape":["A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":281}],"input":{"A":{"damage":2,"id":5}},"shape":["A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":281}],"input":{"A":{"damage":3,"id":5}},"shape":["A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":281}],"input":{"A":{"damage":4,"id":5}},"shape":["A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":281}],"input":{"A":{"damage":5,"id":5}},"shape":["A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":281}],"input":{"A":{"id":-242}},"shape":["A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":54}],"input":{"A":{"id":-537}},"shape":["AAA","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":54}],"input":{"A":{"id":-510}},"shape":["AAA","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":54}],"input":{"A":{"id":-243}},"shape":["AAA","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":54}],"input":{"A":{"id":-486}},"shape":["AAA","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":54}],"input":{"A":{"id":5}},"shape":["AAA","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":54}],"input":{"A":{"damage":1,"id":5}},"shape":["AAA","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":54}],"input":{"A":{"damage":2,"id":5}},"shape":["AAA","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":54}],"input":{"A":{"damage":3,"id":5}},"shape":["AAA","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":54}],"input":{"A":{"damage":4,"id":5}},"shape":["AAA","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":54}],"input":{"A":{"damage":5,"id":5}},"shape":["AAA","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":54}],"input":{"A":{"id":-242}},"shape":["AAA","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":151}],"input":{"A":{"id":20},"B":{"id":406},"C":{"id":-265}},"shape":["AAA","BBB","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":151}],"input":{"A":{"id":20},"B":{"id":406},"C":{"id":-539}},"shape":["AAA","BBB","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":151}],"input":{"A":{"id":20},"B":{"id":406},"C":{"id":-264}},"shape":["AAA","BBB","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":151}],"input":{"A":{"id":20},"B":{"id":406},"C":{"id":-513}},"shape":["AAA","BBB","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":151}],"input":{"A":{"id":20},"B":{"id":406},"C":{"id":158}},"shape":["AAA","BBB","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":151}],"input":{"A":{"id":20},"B":{"id":406},"C":{"damage":1,"id":158}},"shape":["AAA","BBB","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":151}],"input":{"A":{"id":20},"B":{"id":406},"C":{"damage":2,"id":158}},"shape":["AAA","BBB","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":151}],"input":{"A":{"id":20},"B":{"id":406},"C":{"damage":3,"id":158}},"shape":["AAA","BBB","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":151}],"input":{"A":{"id":20},"B":{"id":406},"C":{"damage":4,"id":158}},"shape":["AAA","BBB","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":151}],"input":{"A":{"id":20},"B":{"id":406},"C":{"damage":5,"id":158}},"shape":["AAA","BBB","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":151}],"input":{"A":{"id":20},"B":{"id":406},"C":{"id":-489}},"shape":["AAA","BBB","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":385}],"input":[{"damage":1,"id":263},{"id":289},{"id":377}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":3,"id":385}],"input":[{"id":263},{"id":289},{"id":377}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":3,"id":385}],"input":[{"damage":1,"id":263},{"id":289},{"id":377}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":84}],"input":{"A":{"id":-537},"B":{"id":264}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":84}],"input":{"A":{"id":-510},"B":{"id":264}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":84}],"input":{"A":{"id":-243},"B":{"id":264}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":84}],"input":{"A":{"id":-486},"B":{"id":264}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":84}],"input":{"A":{"id":5},"B":{"id":264}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":84}],"input":{"A":{"damage":1,"id":5},"B":{"id":264}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":84}],"input":{"A":{"damage":2,"id":5},"B":{"id":264}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":84}],"input":{"A":{"damage":3,"id":5},"B":{"id":264}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":84}],"input":{"A":{"damage":4,"id":5},"B":{"id":264}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":84}],"input":{"A":{"damage":5,"id":5},"B":{"id":264}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":84}],"input":{"A":{"id":-242},"B":{"id":264}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":50}],"input":{"A":{"damage":1,"id":263},"B":{"id":280}},"shape":["A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":58}],"input":{"A":{"id":-537}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":58}],"input":{"A":{"id":-510}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":58}],"input":{"A":{"id":-243}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":58}],"input":{"A":{"id":-486}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":58}],"input":{"A":{"id":5}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":58}],"input":{"A":{"damage":1,"id":5}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":58}],"input":{"A":{"damage":2,"id":5}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":58}],"input":{"A":{"damage":3,"id":5}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":58}],"input":{"A":{"damage":4,"id":5}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":58}],"input":{"A":{"damage":5,"id":5}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":58}],"input":{"A":{"id":-242}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":58}],"input":{"A":{"id":5}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":-1},{"output":[{"damage":4,"id":333}],"input":{"A":{"damage":4,"id":5}},"shape":["A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":642}],"input":[{"id":54},{"damage":4,"id":333}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":3,"id":430}],"input":{"A":{"damage":4,"id":5}},"shape":["AA","AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"count":3,"id":85}],"input":{"A":{"damage":4,"id":5},"B":{"id":280}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":187}],"input":{"A":{"id":280},"B":{"damage":4,"id":5}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-504}],"input":{"A":{"id":758},"B":{"id":-8}},"shape":["A A","BBB","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"count":4,"id":5}],"input":{"A":{"id":162}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"count":4,"id":5}],"input":{"A":{"id":-8}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"count":4,"id":5}],"input":{"A":{"damage":12,"id":-212}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"count":4,"id":5}],"input":{"A":{"damage":4,"id":-212}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":163}],"input":{"A":{"damage":4,"id":5}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"count":3,"id":-212}],"input":{"A":{"id":162}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"count":3,"id":-212}],"input":{"A":{"id":-8}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"count":6,"id":158}],"input":{"A":{"damage":4,"id":5}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":126}],"input":{"A":{"id":265},"B":{"id":280},"C":{"id":76}},"shape":["ABA","ACA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-327}],"input":{"A":{"id":771}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"damage":5,"count":2,"id":1}],"input":[{"damage":3,"id":1},{"id":4}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":4,"id":-171}],"input":{"A":{"damage":5,"id":1}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"count":6,"id":139}],"input":{"A":{"damage":5,"id":1}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":145}],"input":{"A":{"id":42},"B":{"id":265}},"shape":["AAA"," B ","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":425}],"input":{"A":{"id":280},"B":{"id":44}},"shape":["AAA"," A ","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":262}],"input":{"A":{"id":318},"B":{"id":280},"C":{"id":288}},"shape":["A","B","C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-527}],"input":{"A":{"id":-163}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-511}],"input":{"A":{"id":-510}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":-517}],"input":{"A":{"id":-510}},"shape":["AA","AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":-515}],"input":{"A":{"id":-510},"B":{"id":280}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-516}],"input":{"A":{"id":280},"B":{"id":-510}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-522}],"input":{"A":{"id":758},"B":{"id":-528}},"shape":["A A","BBB","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-509}],"input":{"A":{"id":-513}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-524}],"input":{"A":{"id":-509}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-523}],"input":{"A":{"id":-509}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":-510}],"input":{"A":{"id":-527}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":-510}],"input":{"A":{"id":-528}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-514}],"input":{"A":{"id":-510}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-513}],"input":{"A":{"id":-510}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-512}],"input":{"A":{"id":-510}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":-520}],"input":{"A":{"id":-510}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"id":434}],"input":[{"id":45},{"id":339}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":434}],"input":[{"id":339},{"damage":4,"id":397}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":2,"id":434}],"input":[{"damage":8,"id":38},{"id":339}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":1,"id":434}],"input":[{"id":339},{"damage":1,"id":397}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":3,"id":434}],"input":[{"id":339},{"id":466}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":5,"id":434}],"input":[{"id":106},{"id":339}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-537},"B":{"id":-265}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-537},"B":{"id":-539}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-537},"B":{"id":-264}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-537},"B":{"id":-513}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-537},"B":{"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-537},"B":{"damage":1,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-537},"B":{"damage":2,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-537},"B":{"damage":3,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-537},"B":{"damage":4,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-537},"B":{"damage":5,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-537},"B":{"id":-489}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-510},"B":{"id":-265}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-510},"B":{"id":-539}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-510},"B":{"id":-264}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-510},"B":{"id":-513}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-510},"B":{"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-510},"B":{"damage":1,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-510},"B":{"damage":2,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-510},"B":{"damage":3,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-510},"B":{"damage":4,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-510},"B":{"damage":5,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-510},"B":{"id":-489}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-243},"B":{"id":-265}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-243},"B":{"id":-539}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-243},"B":{"id":-264}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-243},"B":{"id":-513}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-243},"B":{"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-243},"B":{"damage":1,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-243},"B":{"damage":2,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-243},"B":{"damage":3,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-243},"B":{"damage":4,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-243},"B":{"damage":5,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-243},"B":{"id":-489}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-486},"B":{"id":-265}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-486},"B":{"id":-539}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-486},"B":{"id":-264}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-486},"B":{"id":-513}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-486},"B":{"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-486},"B":{"damage":1,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-486},"B":{"damage":2,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-486},"B":{"damage":3,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-486},"B":{"damage":4,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-486},"B":{"damage":5,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-486},"B":{"id":-489}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":5},"B":{"id":-265}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":1,"id":5},"B":{"id":-265}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":2,"id":5},"B":{"id":-265}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":3,"id":5},"B":{"id":-265}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":4,"id":5},"B":{"id":-265}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":5,"id":5},"B":{"id":-265}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":5},"B":{"id":-539}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":1,"id":5},"B":{"id":-539}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":2,"id":5},"B":{"id":-539}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":3,"id":5},"B":{"id":-539}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":4,"id":5},"B":{"id":-539}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":5,"id":5},"B":{"id":-539}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":5},"B":{"id":-264}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":1,"id":5},"B":{"id":-264}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":2,"id":5},"B":{"id":-264}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":3,"id":5},"B":{"id":-264}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":4,"id":5},"B":{"id":-264}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":5,"id":5},"B":{"id":-264}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":5},"B":{"id":-513}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":1,"id":5},"B":{"id":-513}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":2,"id":5},"B":{"id":-513}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":3,"id":5},"B":{"id":-513}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":4,"id":5},"B":{"id":-513}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":5,"id":5},"B":{"id":-513}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":5},"B":{"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":5},"B":{"damage":1,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":5},"B":{"damage":2,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":5},"B":{"damage":3,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":5},"B":{"damage":4,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":5},"B":{"damage":5,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":5},"B":{"id":-489}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":1,"id":5},"B":{"id":-489}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":2,"id":5},"B":{"id":-489}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":3,"id":5},"B":{"id":-489}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":4,"id":5},"B":{"id":-489}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"damage":5,"id":5},"B":{"id":-489}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-242},"B":{"id":-265}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-242},"B":{"id":-539}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-242},"B":{"id":-264}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-242},"B":{"id":-513}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-242},"B":{"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-242},"B":{"damage":1,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-242},"B":{"damage":2,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-242},"B":{"damage":3,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-242},"B":{"damage":4,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-242},"B":{"damage":5,"id":158}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-203}],"input":{"A":{"id":-242},"B":{"id":-489}},"shape":["ABA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"id":395}],"input":[{"id":345},{"damage":1,"id":395}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":138}],"input":{"A":{"id":20},"B":{"id":399},"C":{"id":49}},"shape":["AAA","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-219}],"input":{"A":{"id":-537},"B":{"id":736}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-219}],"input":{"A":{"id":-510},"B":{"id":736}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-219}],"input":{"A":{"id":-243},"B":{"id":736}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-219}],"input":{"A":{"id":-486},"B":{"id":736}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-219}],"input":{"A":{"id":5},"B":{"id":736}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-219}],"input":{"A":{"damage":1,"id":5},"B":{"id":736}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-219}],"input":{"A":{"damage":2,"id":5},"B":{"id":736}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-219}],"input":{"A":{"damage":3,"id":5},"B":{"id":736}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-219}],"input":{"A":{"damage":4,"id":5},"B":{"id":736}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-219}],"input":{"A":{"damage":5,"id":5},"B":{"id":736}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-219}],"input":{"A":{"id":-242},"B":{"id":736}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-219}],"input":{"A":{"id":-242},"B":{"id":736}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-219}],"input":{"A":{"id":-486},"B":{"id":736}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-219}],"input":{"A":{"id":-243},"B":{"id":736}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":459}],"input":[{"id":281},{"id":457},{"id":457},{"id":457},{"id":457},{"id":457},{"id":457}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":2,"id":333}],"input":{"A":{"damage":2,"id":5}},"shape":["A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":639}],"input":[{"id":54},{"damage":2,"id":333}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":3,"id":428}],"input":{"A":{"damage":2,"id":5}},"shape":["AA","AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"count":3,"id":85}],"input":{"A":{"damage":2,"id":5},"B":{"id":280}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":184}],"input":{"A":{"id":280},"B":{"damage":2,"id":5}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-502}],"input":{"A":{"id":758},"B":{"id":-6}},"shape":["A A","BBB","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"count":4,"id":5}],"input":{"A":{"damage":2,"id":17}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"count":4,"id":5}],"input":{"A":{"id":-6}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"count":4,"id":5}],"input":{"A":{"damage":10,"id":-212}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"count":4,"id":5}],"input":{"A":{"damage":2,"id":-212}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":135}],"input":{"A":{"damage":2,"id":5}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"count":3,"id":-212}],"input":{"A":{"damage":2,"id":17}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":10,"count":3,"id":-212}],"input":{"A":{"id":-6}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"count":6,"id":158}],"input":{"A":{"damage":2,"id":5}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"nbt_b64":"CgAAAwQAVHlwZQAAAAAA","id":446}],"input":{"A":{"damage":15,"id":35},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-428}],"input":[{"id":-412},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":-428}],"input":[{"id":-412},{"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":15,"count":3,"id":171}],"input":{"A":{"damage":15,"id":35}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"count":8,"id":171}],"input":{"A":{"id":171},"B":{"damage":16,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"damage":15,"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":15,"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"id":351}],"block":"crafting_table","type":0,"priority":1},{"output":[{"damage":16,"id":351}],"input":[{"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":16,"id":351}],"input":[{"id":-216}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":15,"count":8,"id":241}],"input":{"A":{"id":20},"B":{"damage":16,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"count":8,"id":241}],"input":{"A":{"id":20},"B":{"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"damage":15,"count":16,"id":160}],"input":{"A":{"damage":15,"id":241}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"count":8,"id":160}],"input":{"A":{"id":102},"B":{"damage":16,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"count":8,"id":159}],"input":{"A":{"id":172},"B":{"damage":16,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"count":8,"id":159}],"input":{"A":{"id":172},"B":{"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":6,"id":-282}],"input":{"A":{"id":-273}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-276}],"input":{"A":{"id":-273}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-277}],"input":{"A":{"id":-273}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-196}],"input":{"A":{"id":265},"B":{"id":61},"C":{"id":-183}},"shape":["AAA","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":377}],"input":[{"id":369}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":4,"nbt_b64":"CgAAAwQAVHlwZQAAAAAA","id":446}],"input":{"A":{"damage":11,"id":35},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-424}],"input":[{"id":-412},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":-424}],"input":[{"id":-412},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":11,"count":3,"id":171}],"input":{"A":{"damage":11,"id":35}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"count":8,"id":171}],"input":{"A":{"id":171},"B":{"damage":18,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":11,"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":1},{"output":[{"damage":18,"id":351}],"input":[{"damage":9,"id":38}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":18,"id":351}],"input":[{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":-11}],"input":{"A":{"id":174}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"count":8,"id":241}],"input":{"A":{"id":20},"B":{"damage":18,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"count":8,"id":241}],"input":{"A":{"id":20},"B":{"damage":4,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"damage":11,"count":16,"id":160}],"input":{"A":{"damage":11,"id":241}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"count":8,"id":160}],"input":{"A":{"id":102},"B":{"damage":18,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"count":8,"id":159}],"input":{"A":{"id":172},"B":{"damage":18,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"count":8,"id":159}],"input":{"A":{"id":172},"B":{"damage":4,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"id":333}],"input":{"A":{"id":5}},"shape":["A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":216}],"input":{"A":{"damage":15,"id":351}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"count":9,"id":351}],"input":[{"id":216}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":15,"count":3,"id":351}],"input":[{"id":352}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":340}],"input":[{"id":334},{"id":339},{"id":339},{"id":339}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":47}],"input":{"A":{"id":-242},"B":{"id":340}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":47}],"input":{"A":{"id":-486},"B":{"id":340}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":47}],"input":{"A":{"id":-243},"B":{"id":340}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":261}],"input":{"A":{"id":280},"B":{"id":287}},"shape":[" AB","A B"," AB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":281}],"input":{"A":{"id":-242}},"shape":["A A"," A "],"block":"crafting_table","type":1,"priority":2},{"output":[{"count":4,"id":281}],"input":{"A":{"id":-486}},"shape":["A A"," A "],"block":"crafting_table","type":1,"priority":2},{"output":[{"count":4,"id":281}],"input":{"A":{"id":-243}},"shape":["A A"," A "],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":297}],"input":{"A":{"id":296}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":379}],"input":{"A":{"id":369},"B":{"id":-273}},"shape":[" A ","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":379}],"input":{"A":{"id":369},"B":{"id":-379}},"shape":[" A ","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":379}],"input":{"A":{"id":369},"B":{"id":4}},"shape":[" A ","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":379}],"input":{"A":{"id":369},"B":{"id":-273}},"shape":[" A ","BBB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":379}],"input":{"A":{"id":369},"B":{"id":-379}},"shape":[" A ","BBB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":45}],"input":{"A":{"id":336}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":108}],"input":{"A":{"id":45}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":6,"count":6,"id":139}],"input":{"A":{"id":45}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"nbt_b64":"CgAAAwQAVHlwZQAAAAAA","id":446}],"input":{"A":{"damage":12,"id":35},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-425}],"input":[{"id":-412},{"damage":17,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":-425}],"input":[{"id":-412},{"damage":3,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":12,"count":3,"id":171}],"input":{"A":{"damage":12,"id":35}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"count":8,"id":171}],"input":{"A":{"id":171},"B":{"damage":17,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"damage":17,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":12,"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"damage":3,"id":351}],"block":"crafting_table","type":0,"priority":1},{"output":[{"damage":17,"id":351}],"input":[{"damage":3,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":12,"count":8,"id":241}],"input":{"A":{"id":20},"B":{"damage":17,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"count":8,"id":241}],"input":{"A":{"id":20},"B":{"damage":3,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"damage":12,"count":16,"id":160}],"input":{"A":{"damage":12,"id":241}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"count":8,"id":160}],"input":{"A":{"id":102},"B":{"damage":17,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"count":8,"id":159}],"input":{"A":{"id":172},"B":{"damage":17,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"count":8,"id":159}],"input":{"A":{"id":172},"B":{"damage":3,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"id":325}],"input":{"A":{"id":265}},"shape":["A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":354}],"input":{"A":{"damage":1,"id":325},"B":{"id":353},"C":{"id":344},"D":{"id":296}},"shape":["AAA","BCB","DDD"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-580}],"input":{"A":{"id":771},"B":{"id":-307}},"shape":[" A ","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-225}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-225}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":162}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":162}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-536}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-536}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-8}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-8}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-7}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-7}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-212}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-212}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-299}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-299}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-10}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-10}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-546}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-546}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":17}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":17}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-240}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-240}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-535}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-535}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-241}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-241}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-485}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-485}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-545}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-545}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-226}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-226}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-5}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-5}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-300}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-300}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-301}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-301}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-498}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-498}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-497}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-497}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-298}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-298}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-9}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-9}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-484}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-484}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"id":263},"C":{"id":-6}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-6}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-484}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-497}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-8}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-6}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-9}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-7}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-485}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-498}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-10}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":720}],"input":{"A":{"id":280},"B":{"damage":1,"id":263},"C":{"id":-5}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-412}],"input":{"A":{"id":287},"B":{"id":736}},"shape":["A","B"],"block":"crafting_table","type":1,"priority":1},{"output":[{"id":398}],"input":{"A":{"id":346},"B":{"id":391}},"shape":["A "," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-200}],"input":{"A":{"id":339},"B":{"id":-537}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-200}],"input":{"A":{"id":339},"B":{"id":-510}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-200}],"input":{"A":{"id":339},"B":{"id":-243}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-200}],"input":{"A":{"id":339},"B":{"id":-486}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-200}],"input":{"A":{"id":339},"B":{"id":5}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-200}],"input":{"A":{"id":339},"B":{"damage":1,"id":5}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-200}],"input":{"A":{"id":339},"B":{"damage":2,"id":5}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-200}],"input":{"A":{"id":339},"B":{"damage":3,"id":5}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-200}],"input":{"A":{"id":339},"B":{"damage":4,"id":5}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-200}],"input":{"A":{"id":339},"B":{"damage":5,"id":5}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-200}],"input":{"A":{"id":339},"B":{"id":-242}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-200}],"input":{"A":{"id":339},"B":{"id":-242}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-200}],"input":{"A":{"id":339},"B":{"id":-486}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-200}],"input":{"A":{"id":339},"B":{"id":-243}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":380}],"input":{"A":{"id":265}},"shape":["A A","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":758}],"input":{"A":{"id":452},"B":{"id":265}},"shape":["A","B","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-530}],"input":{"A":{"id":-537}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":-531}],"input":{"A":{"id":-537}},"shape":["AA","AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":-532}],"input":{"A":{"id":-537},"B":{"id":280}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-533}],"input":{"A":{"id":280},"B":{"id":-537}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-534}],"input":{"A":{"id":758},"B":{"id":-535}},"shape":["A A","BBB","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-537}],"input":{"A":{"id":-536}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-537}],"input":{"A":{"id":-535}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-537}],"input":{"A":{"id":-545}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-537}],"input":{"A":{"id":-546}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-538}],"input":{"A":{"id":-537}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-539}],"input":{"A":{"id":-537}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-541}],"input":{"A":{"id":-537}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":-543}],"input":{"A":{"id":-537}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":-546}],"input":{"A":{"id":-536}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":-545}],"input":{"A":{"id":-535}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":638}],"input":[{"id":54},{"id":333}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":54}],"input":{"A":{"id":-242}},"shape":["AAA","A A","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":54}],"input":{"A":{"id":-486}},"shape":["AAA","A A","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":54}],"input":{"A":{"id":-243}},"shape":["AAA","A A","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":342}],"input":[{"id":54},{"id":328}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-537},"B":{"id":-265}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-537},"B":{"id":-539}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-537},"B":{"id":-264}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-537},"B":{"id":-513}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-537},"B":{"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-537},"B":{"damage":1,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-537},"B":{"damage":2,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-537},"B":{"damage":3,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-537},"B":{"damage":4,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-537},"B":{"damage":5,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-537},"B":{"id":-489}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-510},"B":{"id":-265}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-510},"B":{"id":-539}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-510},"B":{"id":-264}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-510},"B":{"id":-513}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-510},"B":{"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-510},"B":{"damage":1,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-510},"B":{"damage":2,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-510},"B":{"damage":3,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-510},"B":{"damage":4,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-510},"B":{"damage":5,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-510},"B":{"id":-489}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-243},"B":{"id":-265}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-243},"B":{"id":-539}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-243},"B":{"id":-264}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-243},"B":{"id":-513}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-243},"B":{"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-243},"B":{"damage":1,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-243},"B":{"damage":2,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-243},"B":{"damage":3,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-243},"B":{"damage":4,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-243},"B":{"damage":5,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-243},"B":{"id":-489}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-486},"B":{"id":-265}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-486},"B":{"id":-539}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-486},"B":{"id":-264}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-486},"B":{"id":-513}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-486},"B":{"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-486},"B":{"damage":1,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-486},"B":{"damage":2,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-486},"B":{"damage":3,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-486},"B":{"damage":4,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-486},"B":{"damage":5,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-486},"B":{"id":-489}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":5},"B":{"id":-265}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":1,"id":5},"B":{"id":-265}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":2,"id":5},"B":{"id":-265}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":3,"id":5},"B":{"id":-265}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":4,"id":5},"B":{"id":-265}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":5,"id":5},"B":{"id":-265}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":5},"B":{"id":-539}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":1,"id":5},"B":{"id":-539}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":2,"id":5},"B":{"id":-539}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":3,"id":5},"B":{"id":-539}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":4,"id":5},"B":{"id":-539}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":5,"id":5},"B":{"id":-539}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":5},"B":{"id":-264}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":1,"id":5},"B":{"id":-264}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":2,"id":5},"B":{"id":-264}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":3,"id":5},"B":{"id":-264}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":4,"id":5},"B":{"id":-264}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":5,"id":5},"B":{"id":-264}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":5},"B":{"id":-513}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":1,"id":5},"B":{"id":-513}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":2,"id":5},"B":{"id":-513}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":3,"id":5},"B":{"id":-513}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":4,"id":5},"B":{"id":-513}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":5,"id":5},"B":{"id":-513}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":5},"B":{"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":5},"B":{"damage":1,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":5},"B":{"damage":2,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":5},"B":{"damage":3,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":5},"B":{"damage":4,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":5},"B":{"damage":5,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":5},"B":{"id":-489}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":1,"id":5},"B":{"id":-489}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":2,"id":5},"B":{"id":-489}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":3,"id":5},"B":{"id":-489}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":4,"id":5},"B":{"id":-489}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"damage":5,"id":5},"B":{"id":-489}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-242},"B":{"id":-265}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-242},"B":{"id":-539}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-242},"B":{"id":-264}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-242},"B":{"id":-513}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-242},"B":{"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-242},"B":{"damage":1,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-242},"B":{"damage":2,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-242},"B":{"damage":3,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-242},"B":{"damage":4,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-242},"B":{"damage":5,"id":158}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-526}],"input":{"A":{"id":-242},"B":{"id":-489}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-395}],"input":{"A":{"id":-380}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":1},{"output":[{"id":-302}],"input":{"A":{"damage":7,"id":44}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-279}],"input":{"A":{"id":-293}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-753}],"input":{"A":{"id":-744}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":1},{"output":[{"id":-759}],"input":{"A":{"id":-755}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":1},{"output":[{"id":82}],"input":{"A":{"id":337}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":347}],"input":{"A":{"id":266},"B":{"id":331}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":9,"id":263}],"input":{"A":{"id":173}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":173}],"input":{"A":{"id":263}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"count":4,"id":3}],"input":{"A":{"id":3},"B":{"id":13}},"shape":["AB","BA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-380}],"input":{"A":{"id":-379}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-381}],"input":{"A":{"id":-379}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":6,"id":-382}],"input":{"A":{"id":-379}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":67}],"input":{"A":{"id":4}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":139}],"input":{"A":{"id":4}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":404}],"input":{"A":{"id":76},"B":{"id":406},"C":{"id":1}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":345}],"input":{"A":{"id":265},"B":{"id":331}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-213}],"input":{"A":{"id":-265}},"shape":["A A","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-213}],"input":{"A":{"id":-539}},"shape":["A A","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-213}],"input":{"A":{"id":-264}},"shape":["A A","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-213}],"input":{"A":{"id":-513}},"shape":["A A","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-213}],"input":{"A":{"id":158}},"shape":["A A","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-213}],"input":{"A":{"damage":1,"id":158}},"shape":["A A","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-213}],"input":{"A":{"damage":2,"id":158}},"shape":["A A","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-213}],"input":{"A":{"damage":3,"id":158}},"shape":["A A","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-213}],"input":{"A":{"damage":4,"id":158}},"shape":["A A","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-213}],"input":{"A":{"damage":5,"id":158}},"shape":["A A","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-213}],"input":{"A":{"id":-489}},"shape":["A A","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-213}],"input":{"A":{"id":-264}},"shape":["A A","A A","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-213}],"input":{"A":{"id":-489}},"shape":["A A","A A","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-213}],"input":{"A":{"id":-265}},"shape":["A A","A A","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-157}],"input":{"A":{"id":465},"B":{"id":467}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":8,"id":357}],"input":{"A":{"id":296},"B":{"damage":3,"id":351}},"shape":["ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-340}],"input":{"A":{"id":519}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-776}],"input":{"A":{"id":-340},"B":{"id":369},"C":{"id":331}},"shape":[" A ","ABA"," C "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":-784}],"input":{"A":{"id":519}},"shape":["AA","AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-768}],"input":{"A":{"id":-340}},"shape":[" A ","A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":-792}],"input":{"A":{"id":519}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-313}],"input":{"A":{"id":265},"B":{"id":58},"C":{"id":331},"D":{"id":125}},"shape":["AAA","ABA","CDC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-760}],"input":{"A":{"id":-361}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-347}],"input":{"A":{"id":-340}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":6,"id":-361}],"input":{"A":{"id":-347}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-354}],"input":{"A":{"id":-347}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-348}],"input":{"A":{"id":-341}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":6,"id":-362}],"input":{"A":{"id":-348}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-355}],"input":{"A":{"id":-348}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"id":58}],"input":{"A":{"id":-242}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":58}],"input":{"A":{"id":-486}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":58}],"input":{"A":{"id":-243}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"count":4,"id":-350}],"input":{"A":{"id":-343}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":6,"id":-364}],"input":{"A":{"id":-350}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-357}],"input":{"A":{"id":-350}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":3,"id":-788}],"input":{"A":{"id":-344}},"shape":["AA","AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-351}],"input":{"A":{"id":-344}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":6,"id":-365}],"input":{"A":{"id":-351}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-358}],"input":{"A":{"id":-351}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-352}],"input":{"A":{"id":-345}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":6,"id":-366}],"input":{"A":{"id":-352}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-359}],"input":{"A":{"id":-352}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-447}],"input":{"A":{"id":-446}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":6,"id":-449}],"input":{"A":{"id":-447}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-448}],"input":{"A":{"id":-447}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-353}],"input":{"A":{"id":-346}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":6,"id":-367}],"input":{"A":{"id":-353}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-360}],"input":{"A":{"id":-353}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-349}],"input":{"A":{"id":-342}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":6,"id":-363}],"input":{"A":{"id":-349}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-356}],"input":{"A":{"id":-349}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"id":-260}],"input":{"A":{"id":-242}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":755}],"input":{"A":{"id":-242}},"shape":["AA","AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":-256}],"input":{"A":{"id":-242},"B":{"id":280}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-258}],"input":{"A":{"id":280},"B":{"id":-242}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-506}],"input":{"A":{"id":758},"B":{"id":-240}},"shape":["A A","BBB","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":-299}],"input":{"A":{"id":-225}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-242}],"input":{"A":{"id":-225}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-242}],"input":{"A":{"id":-299}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-242}],"input":{"A":{"id":-300}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-242}],"input":{"A":{"id":-240}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-262}],"input":{"A":{"id":-242}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":753}],"input":{"A":{"id":-242},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-264}],"input":{"A":{"id":-242}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-254}],"input":{"A":{"id":-242}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":-246}],"input":{"A":{"id":-242}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":471}],"input":{"A":{"id":280},"B":{"id":265},"C":{"id":287},"D":{"id":131}},"shape":["ABA","CDC"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":6,"nbt_b64":"CgAAAwQAVHlwZQAAAAAA","id":446}],"input":{"A":{"damage":9,"id":35},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-422}],"input":[{"id":-412},{"damage":6,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":9,"count":3,"id":171}],"input":{"A":{"damage":9,"id":35}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":9,"count":8,"id":171}],"input":{"A":{"id":171},"B":{"damage":6,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":9,"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"damage":6,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":6,"count":2,"id":351}],"input":[{"damage":2,"id":351},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":6,"count":2,"id":351}],"input":[{"damage":2,"id":351},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":1},{"output":[{"damage":6,"count":2,"id":351}],"input":[{"id":-612}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":9,"count":8,"id":241}],"input":{"A":{"id":20},"B":{"damage":6,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":9,"count":16,"id":160}],"input":{"A":{"damage":9,"id":241}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":9,"count":8,"id":160}],"input":{"A":{"id":102},"B":{"damage":6,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":9,"count":8,"id":159}],"input":{"A":{"id":172},"B":{"damage":6,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"id":333}],"input":{"A":{"damage":5,"id":5}},"shape":["A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":643}],"input":[{"id":54},{"damage":5,"id":333}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":3,"id":431}],"input":{"A":{"damage":5,"id":5}},"shape":["AA","AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"count":3,"id":85}],"input":{"A":{"damage":5,"id":5},"B":{"id":280}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":186}],"input":{"A":{"id":280},"B":{"damage":5,"id":5}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-505}],"input":{"A":{"id":758},"B":{"id":-9}},"shape":["A A","BBB","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"count":4,"id":5}],"input":{"A":{"damage":1,"id":162}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"count":4,"id":5}],"input":{"A":{"id":-9}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"count":4,"id":5}],"input":{"A":{"damage":13,"id":-212}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"count":4,"id":5}],"input":{"A":{"damage":5,"id":-212}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":164}],"input":{"A":{"damage":5,"id":5}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"count":3,"id":-212}],"input":{"A":{"damage":1,"id":162}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":13,"count":3,"id":-212}],"input":{"A":{"id":-9}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"count":6,"id":158}],"input":{"A":{"damage":5,"id":5}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"id":168}],"input":{"A":{"id":409},"B":{"damage":16,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"id":168}],"input":{"A":{"id":409},"B":{"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"id":151}],"input":{"A":{"id":20},"B":{"id":406},"C":{"id":-264}},"shape":["AAA","BBB","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":151}],"input":{"A":{"id":20},"B":{"id":406},"C":{"id":-489}},"shape":["AAA","BBB","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":151}],"input":{"A":{"id":20},"B":{"id":406},"C":{"id":-265}},"shape":["AAA","BBB","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"count":6,"id":-392}],"input":{"A":{"id":-391}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-393}],"input":{"A":{"id":-391}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":6,"id":-394}],"input":{"A":{"id":-391}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-391}],"input":{"A":{"id":-383}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":6,"id":-388}],"input":{"A":{"id":-387}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-389}],"input":{"A":{"id":-387}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":6,"id":-390}],"input":{"A":{"id":-387}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-387}],"input":{"A":{"id":-391}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":6,"id":28}],"input":{"A":{"id":265},"B":{"id":70},"C":{"id":331}},"shape":["A A","ABA","ACA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":9,"id":264}],"input":{"A":{"id":57}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":279}],"input":{"A":{"id":264},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":57}],"input":{"A":{"id":264}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":313}],"input":{"A":{"id":264}},"shape":["A A","A A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":311}],"input":{"A":{"id":264}},"shape":["A A","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":310}],"input":{"A":{"id":264}},"shape":["AAA","A A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":293}],"input":{"A":{"id":264},"B":{"id":280}},"shape":["AA"," B"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":312}],"input":{"A":{"id":264}},"shape":["AAA","A A","A A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":278}],"input":{"A":{"id":264},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":277}],"input":{"A":{"id":264},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":276}],"input":{"A":{"id":264},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"count":2,"id":1}],"input":{"A":{"id":4},"B":{"id":406}},"shape":["AB","BA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-170}],"input":{"A":{"damage":3,"id":1}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"count":6,"id":139}],"input":{"A":{"damage":3,"id":1}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":23}],"input":{"A":{"id":4},"B":{"id":261},"C":{"id":331}},"shape":["AAA","ABA","ACA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":9,"id":464}],"input":{"A":{"id":-139}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-139}],"input":{"A":{"id":464}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-317}],"input":{"A":{"id":-308}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-317}],"input":{"A":{"id":-308}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":125}],"input":{"A":{"id":4},"B":{"id":331}},"shape":["AAA","A A","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":9,"id":388}],"input":{"A":{"id":133}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":133}],"input":{"A":{"id":388}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"id":395}],"input":[{"id":345},{"id":395}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":116}],"input":{"A":{"id":340},"B":{"id":264},"C":{"id":49}},"shape":[" A ","BCB","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-178}],"input":{"A":{"id":206}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":10,"count":6,"id":139}],"input":{"A":{"id":206}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":206}],"input":{"A":{"id":121}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":426}],"input":{"A":{"id":20},"B":{"id":381},"C":{"id":370}},"shape":["AAA","ABA","ACA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":208}],"input":{"A":{"id":369},"B":{"id":433}},"shape":["A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":130}],"input":{"A":{"id":49},"B":{"id":381}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":381}],"input":[{"id":368},{"id":377}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":-761}],"input":{"A":{"id":-362}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-777}],"input":{"A":{"id":-341},"B":{"id":369},"C":{"id":331}},"shape":[" A ","ABA"," C "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-769}],"input":{"A":{"id":-341}},"shape":[" A ","A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":85}],"input":{"A":{"id":5},"B":{"id":280}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":107}],"input":{"A":{"id":280},"B":{"id":5}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":376}],"input":[{"id":39},{"id":353},{"id":375}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":346}],"input":{"A":{"id":280},"B":{"id":287}},"shape":[" A"," AB","A B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-201}],"input":{"A":{"id":318},"B":{"id":-537}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-201}],"input":{"A":{"id":318},"B":{"id":-510}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-201}],"input":{"A":{"id":318},"B":{"id":-243}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-201}],"input":{"A":{"id":318},"B":{"id":-486}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-201}],"input":{"A":{"id":318},"B":{"id":5}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-201}],"input":{"A":{"id":318},"B":{"damage":1,"id":5}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-201}],"input":{"A":{"id":318},"B":{"damage":2,"id":5}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-201}],"input":{"A":{"id":318},"B":{"damage":3,"id":5}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-201}],"input":{"A":{"id":318},"B":{"damage":4,"id":5}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-201}],"input":{"A":{"id":318},"B":{"damage":5,"id":5}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-201}],"input":{"A":{"id":318},"B":{"id":-242}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-201}],"input":{"A":{"id":318},"B":{"id":-242}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-201}],"input":{"A":{"id":318},"B":{"id":-486}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-201}],"input":{"A":{"id":318},"B":{"id":-243}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":259}],"input":[{"id":265},{"id":318}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":390}],"input":{"A":{"id":336}},"shape":["A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":61}],"input":{"A":{"id":-273}},"shape":["AAA","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":61}],"input":{"A":{"id":-379}},"shape":["AAA","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":61}],"input":{"A":{"id":4}},"shape":["AAA","A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":61}],"input":{"A":{"id":-273}},"shape":["AAA","A A","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":61}],"input":{"A":{"id":-379}},"shape":["AAA","A A","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"count":3,"id":374}],"input":{"A":{"id":20}},"shape":["A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":16,"id":102}],"input":{"A":{"id":20}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":850}],"input":[{"damage":20,"id":351},{"id":389}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":89}],"input":{"A":{"id":348}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":41}],"input":{"A":{"id":266}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":9,"id":266}],"input":{"A":{"id":41}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":266}],"input":{"A":{"id":371}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":9,"id":371}],"input":{"A":{"id":266}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":322}],"input":{"A":{"id":266},"B":{"id":260}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":286}],"input":{"A":{"id":266},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":317}],"input":{"A":{"id":266}},"shape":["A A","A A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":396}],"input":{"A":{"id":371},"B":{"id":391}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":315}],"input":{"A":{"id":266}},"shape":["A A","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":314}],"input":{"A":{"id":266}},"shape":["AAA","A A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":294}],"input":{"A":{"id":266},"B":{"id":280}},"shape":["AA"," B"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":316}],"input":{"A":{"id":266}},"shape":["AAA","A A","A A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":285}],"input":{"A":{"id":266},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":27}],"input":{"A":{"id":266},"B":{"id":280},"C":{"id":331}},"shape":["A A","ABA","ACA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":284}],"input":{"A":{"id":266},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":283}],"input":{"A":{"id":266},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"id":1}],"input":[{"damage":3,"id":1},{"id":406}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":4,"id":-169}],"input":{"A":{"damage":1,"id":1}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"count":6,"id":139}],"input":{"A":{"damage":1,"id":1}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":8,"nbt_b64":"CgAAAwQAVHlwZQAAAAAA","id":446}],"input":{"A":{"damage":7,"id":35},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-420}],"input":[{"id":-412},{"damage":8,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":7,"count":3,"id":171}],"input":{"A":{"damage":7,"id":35}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":7,"count":8,"id":171}],"input":{"A":{"id":171},"B":{"damage":8,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":7,"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"damage":8,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":8,"count":2,"id":351}],"input":[{"damage":16,"id":351},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":8,"count":2,"id":351}],"input":[{"damage":15,"id":351},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":1},{"output":[{"damage":8,"count":2,"id":351}],"input":[{"id":351},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":3},{"output":[{"damage":8,"count":2,"id":351}],"input":[{"id":351},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":2},{"output":[{"damage":7,"count":8,"id":241}],"input":{"A":{"id":20},"B":{"damage":8,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":7,"count":16,"id":160}],"input":{"A":{"damage":7,"id":241}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":7,"count":8,"id":160}],"input":{"A":{"id":102},"B":{"damage":8,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":7,"count":8,"id":159}],"input":{"A":{"id":172},"B":{"damage":8,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"nbt_b64":"CgAAAwQAVHlwZQAAAAAA","id":446}],"input":{"A":{"damage":13,"id":35},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-426}],"input":[{"id":-412},{"damage":2,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":13,"count":3,"id":171}],"input":{"A":{"damage":13,"id":35}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":13,"count":8,"id":171}],"input":{"A":{"id":171},"B":{"damage":2,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":13,"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"damage":2,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":13,"count":8,"id":241}],"input":{"A":{"id":20},"B":{"damage":2,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":13,"count":16,"id":160}],"input":{"A":{"damage":13,"id":241}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":13,"count":8,"id":160}],"input":{"A":{"id":102},"B":{"damage":2,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":13,"count":8,"id":159}],"input":{"A":{"id":172},"B":{"damage":2,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-195}],"input":{"A":{"id":280},"B":{"damage":2,"id":-166},"C":{"id":-537}},"shape":["ABA","C C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-195}],"input":{"A":{"id":280},"B":{"damage":2,"id":-166},"C":{"id":-510}},"shape":["ABA","C C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-195}],"input":{"A":{"id":280},"B":{"damage":2,"id":-166},"C":{"id":-243}},"shape":["ABA","C C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-195}],"input":{"A":{"id":280},"B":{"damage":2,"id":-166},"C":{"id":-486}},"shape":["ABA","C C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-195}],"input":{"A":{"id":280},"B":{"damage":2,"id":-166},"C":{"id":5}},"shape":["ABA","C C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-195}],"input":{"A":{"id":280},"B":{"damage":2,"id":-166},"C":{"damage":1,"id":5}},"shape":["ABA","C C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-195}],"input":{"A":{"id":280},"B":{"damage":2,"id":-166},"C":{"damage":2,"id":5}},"shape":["ABA","C C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-195}],"input":{"A":{"id":280},"B":{"damage":2,"id":-166},"C":{"damage":3,"id":5}},"shape":["ABA","C C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-195}],"input":{"A":{"id":280},"B":{"damage":2,"id":-166},"C":{"damage":4,"id":5}},"shape":["ABA","C C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-195}],"input":{"A":{"id":280},"B":{"damage":2,"id":-166},"C":{"damage":5,"id":5}},"shape":["ABA","C C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-195}],"input":{"A":{"id":280},"B":{"damage":2,"id":-166},"C":{"id":-242}},"shape":["ABA","C C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-195}],"input":{"A":{"id":280},"B":{"damage":2,"id":-166},"C":{"id":-242}},"shape":["ABA","C C"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-195}],"input":{"A":{"id":280},"B":{"damage":2,"id":-166},"C":{"id":-486}},"shape":["ABA","C C"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-195}],"input":{"A":{"id":280},"B":{"damage":2,"id":-166},"C":{"id":-243}},"shape":["ABA","C C"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":170}],"input":{"A":{"id":296}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":148}],"input":{"A":{"id":265}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-220}],"input":{"A":{"id":737}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":737}],"input":[{"id":-220},{"id":374},{"id":374},{"id":374},{"id":374}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":3,"id":353}],"input":{"A":{"id":737}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-221}],"input":{"A":{"id":736}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":410}],"input":{"A":{"id":265},"B":{"id":54}},"shape":["A A","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":408}],"input":[{"id":328},{"id":410}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":9,"id":519}],"input":{"A":{"id":-340}},"shape":["A"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":9,"id":519}],"input":{"A":{"id":-344}},"shape":["A"],"block":"crafting_table","type":1,"priority":1},{"output":[{"id":258}],"input":{"A":{"id":265},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":16,"id":101}],"input":{"A":{"id":265}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":42}],"input":{"A":{"id":265}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":309}],"input":{"A":{"id":265}},"shape":["A A","A A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":307}],"input":{"A":{"id":265}},"shape":["A A","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":330}],"input":{"A":{"id":265}},"shape":["AA","AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":306}],"input":{"A":{"id":265}},"shape":["AAA","A A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":292}],"input":{"A":{"id":265},"B":{"id":280}},"shape":["AA"," B"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":9,"id":265}],"input":{"A":{"id":42}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":265}],"input":{"A":{"id":452}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":308}],"input":{"A":{"id":265}},"shape":["AAA","A A","A A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":9,"id":452}],"input":{"A":{"id":265}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":257}],"input":{"A":{"id":265},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":256}],"input":{"A":{"id":265},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":267}],"input":{"A":{"id":265},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":167}],"input":{"A":{"id":265}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":389}],"input":{"A":{"id":280},"B":{"id":334}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":84}],"input":{"A":{"id":-242},"B":{"id":264}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":84}],"input":{"A":{"id":-486},"B":{"id":264}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":84}],"input":{"A":{"id":-243},"B":{"id":264}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":3,"id":333}],"input":{"A":{"damage":3,"id":5}},"shape":["A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":640}],"input":[{"id":54},{"damage":3,"id":333}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":3,"id":429}],"input":{"A":{"damage":3,"id":5}},"shape":["AA","AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"count":3,"id":85}],"input":{"A":{"damage":3,"id":5},"B":{"id":280}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":185}],"input":{"A":{"id":280},"B":{"damage":3,"id":5}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-503}],"input":{"A":{"id":758},"B":{"id":-7}},"shape":["A A","BBB","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"count":4,"id":5}],"input":{"A":{"damage":3,"id":17}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"count":4,"id":5}],"input":{"A":{"id":-7}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"count":4,"id":5}],"input":{"A":{"damage":11,"id":-212}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"count":4,"id":5}],"input":{"A":{"damage":3,"id":-212}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":136}],"input":{"A":{"damage":3,"id":5}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"count":3,"id":-212}],"input":{"A":{"damage":3,"id":17}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"count":3,"id":-212}],"input":{"A":{"id":-7}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"count":6,"id":158}],"input":{"A":{"damage":3,"id":5}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":65}],"input":{"A":{"id":280}},"shape":["A A","AAA","A A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-208}],"input":{"A":{"id":452},"B":{"id":50}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":22}],"input":{"A":{"damage":4,"id":351}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"count":9,"id":351}],"input":{"A":{"id":22}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":420}],"input":{"A":{"id":287},"B":{"id":341}},"shape":["AA ","AB "," A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":334}],"input":{"A":{"id":415}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":301}],"input":{"A":{"id":334}},"shape":["A A","A A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":299}],"input":{"A":{"id":334}},"shape":["A A","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":298}],"input":{"A":{"id":334}},"shape":["AAA","A A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":416}],"input":{"A":{"id":334}},"shape":["A A","AAA","A A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":300}],"input":{"A":{"id":334}},"shape":["AAA","A A","A A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-194}],"input":{"A":{"id":-265},"B":{"id":47}},"shape":["AAA"," B "," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-194}],"input":{"A":{"id":-539},"B":{"id":47}},"shape":["AAA"," B "," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-194}],"input":{"A":{"id":-264},"B":{"id":47}},"shape":["AAA"," B "," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-194}],"input":{"A":{"id":-513},"B":{"id":47}},"shape":["AAA"," B "," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-194}],"input":{"A":{"id":158},"B":{"id":47}},"shape":["AAA"," B "," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-194}],"input":{"A":{"damage":1,"id":158},"B":{"id":47}},"shape":["AAA"," B "," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-194}],"input":{"A":{"damage":2,"id":158},"B":{"id":47}},"shape":["AAA"," B "," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-194}],"input":{"A":{"damage":3,"id":158},"B":{"id":47}},"shape":["AAA"," B "," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-194}],"input":{"A":{"damage":4,"id":158},"B":{"id":47}},"shape":["AAA"," B "," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-194}],"input":{"A":{"damage":5,"id":158},"B":{"id":47}},"shape":["AAA"," B "," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-194}],"input":{"A":{"id":-489},"B":{"id":47}},"shape":["AAA"," B "," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-194}],"input":{"A":{"id":-264},"B":{"id":47}},"shape":["AAA"," B "," A "],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-194}],"input":{"A":{"id":-489},"B":{"id":47}},"shape":["AAA"," B "," A "],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-194}],"input":{"A":{"id":-265},"B":{"id":47}},"shape":["AAA"," B "," A "],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":69}],"input":{"A":{"id":280},"B":{"id":4}},"shape":["A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"nbt_b64":"CgAAAwQAVHlwZQAAAAAA","id":446}],"input":{"A":{"damage":3,"id":35},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-416}],"input":[{"id":-412},{"damage":12,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":3,"count":3,"id":171}],"input":{"A":{"damage":3,"id":35}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"count":8,"id":171}],"input":{"A":{"id":171},"B":{"damage":12,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"damage":12,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":12,"count":2,"id":351}],"input":[{"damage":18,"id":351},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":1},{"output":[{"damage":12,"count":2,"id":351}],"input":[{"damage":15,"id":351},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":2},{"output":[{"damage":12,"id":351}],"input":[{"damage":1,"id":38}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":12,"count":2,"id":351}],"input":[{"damage":4,"id":351},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":4},{"output":[{"damage":12,"count":2,"id":351}],"input":[{"damage":4,"id":351},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":3},{"output":[{"damage":3,"count":8,"id":241}],"input":{"A":{"id":20},"B":{"damage":12,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"count":16,"id":160}],"input":{"A":{"damage":3,"id":241}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"count":8,"id":160}],"input":{"A":{"id":102},"B":{"damage":12,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":3,"count":8,"id":159}],"input":{"A":{"id":172},"B":{"damage":12,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":8,"count":8,"id":171}],"input":{"A":{"id":171},"B":{"damage":7,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":7,"nbt_b64":"CgAAAwQAVHlwZQAAAAAA","id":446}],"input":{"A":{"damage":8,"id":35},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-421}],"input":[{"id":-412},{"damage":7,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":8,"count":3,"id":171}],"input":{"A":{"damage":8,"id":35}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":8,"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"damage":7,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":7,"count":3,"id":351}],"input":[{"damage":16,"id":351},{"damage":19,"id":351},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":3},{"output":[{"damage":7,"id":351}],"input":[{"damage":3,"id":38}],"block":"crafting_table","type":0,"priority":2},{"output":[{"damage":7,"count":3,"id":351}],"input":[{"damage":15,"id":351},{"damage":15,"id":351},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":7},{"output":[{"damage":7,"count":2,"id":351}],"input":[{"damage":8,"id":351},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":6},{"output":[{"damage":7,"count":2,"id":351}],"input":[{"damage":8,"id":351},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":4},{"output":[{"damage":7,"count":3,"id":351}],"input":[{"id":351},{"damage":15,"id":351},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":8},{"output":[{"damage":7,"count":3,"id":351}],"input":[{"id":351},{"damage":19,"id":351},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":5},{"output":[{"damage":7,"id":351}],"input":[{"damage":8,"id":38}],"block":"crafting_table","type":0,"priority":1},{"output":[{"damage":7,"id":351}],"input":[{"damage":6,"id":38}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":8,"count":8,"id":241}],"input":{"A":{"id":20},"B":{"damage":7,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":8,"count":16,"id":160}],"input":{"A":{"damage":8,"id":241}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":8,"count":8,"id":160}],"input":{"A":{"id":102},"B":{"damage":7,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":8,"count":8,"id":159}],"input":{"A":{"id":172},"B":{"damage":7,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":147}],"input":{"A":{"id":266}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-312}],"input":{"A":{"id":519}},"shape":["A","A","A"],"block":"crafting_table","type":1,"priority":1},{"output":[{"damage":5,"count":8,"id":171}],"input":{"A":{"id":171},"B":{"damage":10,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":10,"nbt_b64":"CgAAAwQAVHlwZQAAAAAA","id":446}],"input":{"A":{"damage":5,"id":35},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-418}],"input":[{"id":-412},{"damage":10,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":5,"count":3,"id":171}],"input":{"A":{"damage":5,"id":35}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"damage":10,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":10,"count":2,"id":351}],"input":[{"damage":2,"id":351},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":10,"count":2,"id":351}],"input":[{"damage":2,"id":351},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":1},{"output":[{"damage":5,"count":8,"id":241}],"input":{"A":{"id":20},"B":{"damage":10,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"count":16,"id":160}],"input":{"A":{"damage":5,"id":241}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"count":8,"id":160}],"input":{"A":{"id":102},"B":{"damage":10,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"count":8,"id":159}],"input":{"A":{"id":172},"B":{"damage":10,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":91}],"input":{"A":{"id":-155},"B":{"id":50}},"shape":["A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"id":395}],"input":{"A":{"id":339},"B":{"id":345}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-222}],"input":{"A":{"damage":3,"id":98},"B":{"id":742}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-204}],"input":{"A":{"id":287},"B":{"id":-537}},"shape":["AA","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-204}],"input":{"A":{"id":287},"B":{"id":-510}},"shape":["AA","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-204}],"input":{"A":{"id":287},"B":{"id":-243}},"shape":["AA","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-204}],"input":{"A":{"id":287},"B":{"id":-486}},"shape":["AA","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-204}],"input":{"A":{"id":287},"B":{"id":5}},"shape":["AA","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-204}],"input":{"A":{"id":287},"B":{"damage":1,"id":5}},"shape":["AA","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-204}],"input":{"A":{"id":287},"B":{"damage":2,"id":5}},"shape":["AA","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-204}],"input":{"A":{"id":287},"B":{"damage":3,"id":5}},"shape":["AA","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-204}],"input":{"A":{"id":287},"B":{"damage":4,"id":5}},"shape":["AA","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-204}],"input":{"A":{"id":287},"B":{"damage":5,"id":5}},"shape":["AA","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-204}],"input":{"A":{"id":287},"B":{"id":-242}},"shape":["AA","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-204}],"input":{"A":{"id":287},"B":{"id":-242}},"shape":["AA","BB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-204}],"input":{"A":{"id":287},"B":{"id":-486}},"shape":["AA","BB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-204}],"input":{"A":{"id":287},"B":{"id":-243}},"shape":["AA","BB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":13,"nbt_b64":"CgAAAwQAVHlwZQAAAAAA","id":446}],"input":{"A":{"damage":2,"id":35},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-415}],"input":[{"id":-412},{"damage":13,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":2,"count":3,"id":171}],"input":{"A":{"damage":2,"id":35}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"count":8,"id":171}],"input":{"A":{"id":171},"B":{"damage":13,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"damage":13,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":13,"count":3,"id":351}],"input":[{"damage":1,"id":351},{"damage":9,"id":351},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":2},{"output":[{"damage":13,"id":351}],"input":[{"damage":2,"id":38}],"block":"crafting_table","type":0,"priority":1},{"output":[{"damage":13,"count":4,"id":351}],"input":[{"damage":1,"id":351},{"damage":1,"id":351},{"damage":15,"id":351},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":6},{"output":[{"damage":13,"count":4,"id":351}],"input":[{"damage":1,"id":351},{"damage":1,"id":351},{"damage":18,"id":351},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":4},{"output":[{"damage":13,"count":4,"id":351}],"input":[{"damage":1,"id":351},{"damage":1,"id":351},{"damage":4,"id":351},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":8},{"output":[{"damage":13,"count":4,"id":351}],"input":[{"damage":1,"id":351},{"damage":1,"id":351},{"damage":4,"id":351},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":7},{"output":[{"damage":13,"count":3,"id":351}],"input":[{"damage":1,"id":351},{"damage":4,"id":351},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":5},{"output":[{"damage":13,"count":2,"id":351}],"input":[{"damage":1,"id":175}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":13,"count":2,"id":351}],"input":[{"damage":5,"id":351},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":3},{"output":[{"damage":2,"count":8,"id":241}],"input":{"A":{"id":20},"B":{"damage":13,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"count":16,"id":160}],"input":{"A":{"damage":2,"id":241}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"count":8,"id":160}],"input":{"A":{"id":102},"B":{"damage":13,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"count":8,"id":159}],"input":{"A":{"id":172},"B":{"damage":13,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":213}],"input":{"A":{"id":378}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":378}],"input":[{"id":341},{"id":377}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":6,"id":333}],"input":{"A":{"id":-486}},"shape":["A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-487}],"input":{"A":{"id":-486}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":644}],"input":[{"id":54},{"damage":6,"id":333}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":3,"id":-493}],"input":{"A":{"id":-486}},"shape":["AA","AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":-491}],"input":{"A":{"id":-486},"B":{"id":280}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-492}],"input":{"A":{"id":280},"B":{"id":-486}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-508}],"input":{"A":{"id":758},"B":{"id":-485}},"shape":["A A","BBB","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-486}],"input":{"A":{"id":-484}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-486}],"input":{"A":{"id":-485}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-486}],"input":{"A":{"id":-498}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-486}],"input":{"A":{"id":-497}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-490}],"input":{"A":{"id":-486}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-489}],"input":{"A":{"id":-486}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-488}],"input":{"A":{"id":-486}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":-496}],"input":{"A":{"id":-486}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":-497}],"input":{"A":{"id":-484}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":-498}],"input":{"A":{"id":-485}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":395}],"input":{"A":{"id":339}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":103}],"input":{"A":{"id":360}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":362}],"input":{"A":{"id":360}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":328}],"input":{"A":{"id":265}},"shape":["A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":-335}],"input":{"A":{"id":-320}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":48}],"input":[{"id":4},{"id":106}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":48}],"input":[{"id":-320},{"id":4}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":4,"id":-179}],"input":{"A":{"id":48}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"count":6,"id":139}],"input":{"A":{"id":48}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-175}],"input":{"A":{"damage":1,"id":98}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":8,"count":6,"id":139}],"input":{"A":{"damage":1,"id":98}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"id":98}],"input":[{"id":98},{"id":106}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":1,"id":98}],"input":[{"id":-320},{"id":98}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":6,"id":-478}],"input":{"A":{"id":-475}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-480}],"input":{"A":{"id":-475}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-481}],"input":{"A":{"id":-475}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-475}],"input":{"A":{"id":-477}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-483}],"input":[{"id":-482},{"id":-473}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":282}],"input":[{"id":39},{"id":40},{"id":281}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":112}],"input":{"A":{"id":405}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":113}],"input":{"A":{"id":112},"B":{"id":405}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":114}],"input":{"A":{"id":112}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":9,"count":6,"id":139}],"input":{"A":{"id":112}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":214}],"input":{"A":{"id":372}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-270}],"input":{"A":{"id":742}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":742}],"input":[{"id":266},{"id":266},{"id":266},{"id":266},{"id":752},{"id":752},{"id":752},{"id":752}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":9,"id":742}],"input":{"A":{"id":-270}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":25}],"input":{"A":{"id":-537},"B":{"id":331}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":25}],"input":{"A":{"id":-510},"B":{"id":331}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":25}],"input":{"A":{"id":-243},"B":{"id":331}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":25}],"input":{"A":{"id":-486},"B":{"id":331}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":25}],"input":{"A":{"id":5},"B":{"id":331}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":25}],"input":{"A":{"damage":1,"id":5},"B":{"id":331}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":25}],"input":{"A":{"damage":2,"id":5},"B":{"id":331}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":25}],"input":{"A":{"damage":3,"id":5},"B":{"id":331}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":25}],"input":{"A":{"damage":4,"id":5},"B":{"id":331}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":25}],"input":{"A":{"damage":5,"id":5},"B":{"id":331}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":25}],"input":{"A":{"id":-242},"B":{"id":331}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":25}],"input":{"A":{"id":-242},"B":{"id":331}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":25}],"input":{"A":{"id":-486},"B":{"id":331}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":25}],"input":{"A":{"id":-243},"B":{"id":331}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":2},{"output":[{"count":3,"id":85}],"input":{"A":{"id":5},"B":{"id":280}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-500}],"input":{"A":{"id":758},"B":{"id":-10}},"shape":["A A","BBB","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":5}],"input":{"A":{"id":17}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":5}],"input":{"A":{"id":-10}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":5}],"input":{"A":{"damage":8,"id":-212}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":5}],"input":{"A":{"id":-212}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":53}],"input":{"A":{"id":5}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":-212}],"input":{"A":{"id":17}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":8,"count":3,"id":-212}],"input":{"A":{"id":-10}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":158}],"input":{"A":{"id":5}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":251}],"input":{"A":{"id":4},"B":{"id":331},"C":{"id":406}},"shape":["AAA","BBC","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":14,"nbt_b64":"CgAAAwQAVHlwZQAAAAAA","id":446}],"input":{"A":{"damage":1,"id":35},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-414}],"input":[{"id":-412},{"damage":14,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":1,"count":3,"id":171}],"input":{"A":{"damage":1,"id":35}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"count":8,"id":171}],"input":{"A":{"id":171},"B":{"damage":14,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"damage":14,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":14,"id":351}],"input":[{"damage":5,"id":38}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":14,"count":2,"id":351}],"input":[{"damage":1,"id":351},{"damage":11,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":14,"id":351}],"input":[{"id":-568}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":1,"count":8,"id":241}],"input":{"A":{"id":20},"B":{"damage":14,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"count":16,"id":160}],"input":{"A":{"damage":1,"id":241}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"count":8,"id":160}],"input":{"A":{"id":102},"B":{"damage":14,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"count":8,"id":159}],"input":{"A":{"id":172},"B":{"damage":14,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-763}],"input":{"A":{"id":-364}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-779}],"input":{"A":{"id":-343},"B":{"id":369},"C":{"id":331}},"shape":[" A ","ABA"," C "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-771}],"input":{"A":{"id":-343}},"shape":[" A ","A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":174}],"input":{"A":{"id":79}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-477}],"input":[{"id":-473},{"id":296}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":321}],"input":{"A":{"id":280},"B":{"id":35}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":339}],"input":{"A":{"id":338}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"count":2,"id":155}],"input":{"A":{"id":155}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":9,"nbt_b64":"CgAAAwQAVHlwZQAAAAAA","id":446}],"input":{"A":{"damage":6,"id":35},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-419}],"input":[{"id":-412},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":6,"count":3,"id":171}],"input":{"A":{"damage":6,"id":35}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":6,"count":8,"id":171}],"input":{"A":{"id":171},"B":{"damage":9,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":6,"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":9,"count":2,"id":351}],"input":[{"damage":1,"id":351},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":9,"count":2,"id":351}],"input":[{"damage":5,"id":175}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":9,"id":351}],"input":[{"id":-549}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":9,"id":351}],"input":[{"damage":7,"id":38}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":9,"count":2,"id":351}],"input":[{"damage":1,"id":351},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":6,"count":8,"id":241}],"input":{"A":{"id":20},"B":{"damage":9,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":6,"count":16,"id":160}],"input":{"A":{"damage":6,"id":241}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":6,"count":8,"id":160}],"input":{"A":{"id":102},"B":{"damage":9,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":6,"count":8,"id":159}],"input":{"A":{"id":172},"B":{"damage":9,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":33}],"input":{"A":{"id":-537},"B":{"id":4},"C":{"id":265},"D":{"id":331}},"shape":["AAA","BCB","BDB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":33}],"input":{"A":{"id":-510},"B":{"id":4},"C":{"id":265},"D":{"id":331}},"shape":["AAA","BCB","BDB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":33}],"input":{"A":{"id":-243},"B":{"id":4},"C":{"id":265},"D":{"id":331}},"shape":["AAA","BCB","BDB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":33}],"input":{"A":{"id":-486},"B":{"id":4},"C":{"id":265},"D":{"id":331}},"shape":["AAA","BCB","BDB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":33}],"input":{"A":{"id":5},"B":{"id":4},"C":{"id":265},"D":{"id":331}},"shape":["AAA","BCB","BDB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":33}],"input":{"A":{"damage":1,"id":5},"B":{"id":4},"C":{"id":265},"D":{"id":331}},"shape":["AAA","BCB","BDB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":33}],"input":{"A":{"damage":2,"id":5},"B":{"id":4},"C":{"id":265},"D":{"id":331}},"shape":["AAA","BCB","BDB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":33}],"input":{"A":{"damage":3,"id":5},"B":{"id":4},"C":{"id":265},"D":{"id":331}},"shape":["AAA","BCB","BDB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":33}],"input":{"A":{"damage":4,"id":5},"B":{"id":4},"C":{"id":265},"D":{"id":331}},"shape":["AAA","BCB","BDB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":33}],"input":{"A":{"damage":5,"id":5},"B":{"id":4},"C":{"id":265},"D":{"id":331}},"shape":["AAA","BCB","BDB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":33}],"input":{"A":{"id":-242},"B":{"id":4},"C":{"id":265},"D":{"id":331}},"shape":["AAA","BCB","BDB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":33}],"input":{"A":{"id":-242},"B":{"id":4},"C":{"id":265},"D":{"id":331}},"shape":["AAA","BCB","BDB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":33}],"input":{"A":{"id":-486},"B":{"id":4},"C":{"id":265},"D":{"id":331}},"shape":["AAA","BCB","BDB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":33}],"input":{"A":{"id":-243},"B":{"id":4},"C":{"id":265},"D":{"id":331}},"shape":["AAA","BCB","BDB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"damage":6,"count":4,"id":1}],"input":{"A":{"damage":5,"id":1}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-174}],"input":{"A":{"damage":6,"id":1}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-235}],"input":{"A":{"id":-234}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-291}],"input":{"A":{"id":-273}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-284}],"input":{"A":{"id":-274}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-275}],"input":{"A":{"id":-274}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-278}],"input":{"A":{"id":-274}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-274}],"input":{"A":{"id":-291}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-296}],"input":{"A":{"id":-291}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-295}],"input":{"A":{"id":-291}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-293}],"input":{"A":{"id":-291}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-292}],"input":{"A":{"id":-291}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-297}],"input":{"A":{"id":-291}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-383}],"input":{"A":{"id":-379}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":6,"id":-384}],"input":{"A":{"id":-383}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-385}],"input":{"A":{"id":-383}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":6,"id":-386}],"input":{"A":{"id":-383}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"damage":4,"count":4,"id":1}],"input":{"A":{"damage":3,"id":1}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-173}],"input":{"A":{"damage":4,"id":1}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"count":4,"id":1}],"input":{"A":{"damage":1,"id":1}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-172}],"input":{"A":{"damage":2,"id":1}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-748}],"input":{"A":{"id":-333}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-749}],"input":{"A":{"id":-748}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-751}],"input":{"A":{"id":-748}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":6,"id":-752}],"input":{"A":{"id":-748}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":168}],"input":{"A":{"id":409}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"id":168}],"input":{"A":{"id":409}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-2}],"input":{"A":{"id":168}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-4}],"input":{"A":{"damage":2,"id":168}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-3}],"input":{"A":{"damage":1,"id":168}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":11,"count":6,"id":139}],"input":{"A":{"id":168}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":400}],"input":[{"id":86},{"id":344},{"id":353}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":4,"id":361}],"input":{"A":{"id":86}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"nbt_b64":"CgAAAwQAVHlwZQAAAAAA","id":446}],"input":{"A":{"damage":10,"id":35},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-423}],"input":[{"id":-412},{"damage":5,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":10,"count":3,"id":171}],"input":{"A":{"damage":10,"id":35}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":10,"count":8,"id":171}],"input":{"A":{"id":171},"B":{"damage":5,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":10,"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"damage":5,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":5,"count":2,"id":351}],"input":[{"damage":1,"id":351},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":5,"count":2,"id":351}],"input":[{"damage":1,"id":351},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":1},{"output":[{"damage":10,"count":8,"id":241}],"input":{"A":{"id":20},"B":{"damage":5,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":10,"count":16,"id":160}],"input":{"A":{"damage":10,"id":241}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":10,"count":8,"id":160}],"input":{"A":{"id":102},"B":{"damage":5,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":10,"count":8,"id":159}],"input":{"A":{"id":172},"B":{"damage":5,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":201}],"input":{"A":{"id":433}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":203}],"input":{"A":{"id":201}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":155}],"input":{"A":{"id":406}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-304}],"input":{"A":{"id":155}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":156}],"input":{"A":{"id":155}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":413}],"input":[{"id":39},{"id":281},{"id":391},{"id":393},{"id":412}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":413}],"input":[{"id":40},{"id":281},{"id":391},{"id":393},{"id":412}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":16,"id":66}],"input":{"A":{"id":265},"B":{"id":280}},"shape":["A A","ABA","A A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":9,"id":522}],"input":{"A":{"id":-452}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-452}],"input":{"A":{"id":522}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":9,"id":521}],"input":{"A":{"id":-453}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-453}],"input":{"A":{"id":521}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":9,"id":520}],"input":{"A":{"id":-451}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-451}],"input":{"A":{"id":520}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":636}],"input":{"A":{"id":637}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"id":648}],"input":{"A":{"id":647},"B":{"id":345}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"id":648}],"input":{"A":{"id":647},"B":{"id":741}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"damage":1,"nbt_b64":"CgAAAwQAVHlwZQAAAAAA","id":446}],"input":{"A":{"damage":14,"id":35},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-427}],"input":[{"id":-412},{"damage":1,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":14,"count":3,"id":171}],"input":{"A":{"damage":14,"id":35}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":14,"count":8,"id":171}],"input":{"A":{"id":171},"B":{"damage":1,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":14,"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"damage":1,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":1,"id":351}],"input":[{"id":457}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":1,"id":351}],"input":[{"id":38}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":1,"count":2,"id":351}],"input":[{"damage":4,"id":175}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":1,"id":351}],"input":[{"damage":4,"id":38}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":215}],"input":{"A":{"id":405},"B":{"id":372}},"shape":["AB","BA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-184}],"input":{"A":{"id":215}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":13,"count":6,"id":139}],"input":{"A":{"id":215}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":179}],"input":{"A":{"damage":1,"id":12}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":180}],"input":{"A":{"id":179}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":12,"count":6,"id":139}],"input":{"A":{"id":179}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":14,"count":8,"id":241}],"input":{"A":{"id":20},"B":{"damage":1,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":14,"count":16,"id":160}],"input":{"A":{"damage":14,"id":241}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":14,"count":8,"id":160}],"input":{"A":{"id":102},"B":{"damage":1,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":14,"count":8,"id":159}],"input":{"A":{"id":172},"B":{"damage":1,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":9,"id":331}],"input":{"A":{"id":152}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":152}],"input":{"A":{"id":331}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":123}],"input":{"A":{"id":331},"B":{"id":89}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":76}],"input":{"A":{"id":331},"B":{"id":280}},"shape":["A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":356}],"input":{"A":{"id":76},"B":{"id":331},"C":{"id":1}},"shape":["ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-272}],"input":{"A":{"id":-289},"B":{"id":89}},"shape":["AAA","BBB","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":24}],"input":{"A":{"id":12}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":128}],"input":{"A":{"id":24}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":5,"count":6,"id":139}],"input":{"A":{"id":24}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-165}],"input":{"A":{"id":-163},"B":{"id":287}},"shape":["ABA","A A","A A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":169}],"input":{"A":{"id":409},"B":{"id":422}},"shape":["ABA","BBB","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":359}],"input":{"A":{"id":265}},"shape":[" A","A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":513}],"input":{"A":{"id":-537},"B":{"id":265}},"shape":["ABA","AAA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":513}],"input":{"A":{"id":-510},"B":{"id":265}},"shape":["ABA","AAA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":513}],"input":{"A":{"id":-243},"B":{"id":265}},"shape":["ABA","AAA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":513}],"input":{"A":{"id":-486},"B":{"id":265}},"shape":["ABA","AAA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":513}],"input":{"A":{"id":5},"B":{"id":265}},"shape":["ABA","AAA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":513}],"input":{"A":{"damage":1,"id":5},"B":{"id":265}},"shape":["ABA","AAA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":513}],"input":{"A":{"damage":2,"id":5},"B":{"id":265}},"shape":["ABA","AAA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":513}],"input":{"A":{"damage":3,"id":5},"B":{"id":265}},"shape":["ABA","AAA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":513}],"input":{"A":{"damage":4,"id":5},"B":{"id":265}},"shape":["ABA","AAA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":513}],"input":{"A":{"damage":5,"id":5},"B":{"id":265}},"shape":["ABA","AAA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":513}],"input":{"A":{"id":-242},"B":{"id":265}},"shape":["ABA","AAA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":513}],"input":{"A":{"id":-242},"B":{"id":265}},"shape":["ABA","AAA"," A "],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":513}],"input":{"A":{"id":-486},"B":{"id":265}},"shape":["ABA","AAA"," A "],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":513}],"input":{"A":{"id":-243},"B":{"id":265}},"shape":["ABA","AAA"," A "],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":205}],"input":{"A":{"id":445},"B":{"id":54}},"shape":["A","B","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":475}],"input":{"A":{"damage":4,"id":5},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":473}],"input":{"A":{"damage":2,"id":5},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":476}],"input":{"A":{"damage":5,"id":5},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":474}],"input":{"A":{"damage":3,"id":5},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":323}],"input":{"A":{"id":5},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":472}],"input":{"A":{"damage":1,"id":5},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":165}],"input":{"A":{"id":341}},"shape":["AAA","AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":9,"id":341}],"input":{"A":{"id":165}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-202}],"input":{"A":{"id":265},"B":{"id":-537}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-202}],"input":{"A":{"id":265},"B":{"id":-510}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-202}],"input":{"A":{"id":265},"B":{"id":-243}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-202}],"input":{"A":{"id":265},"B":{"id":-486}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-202}],"input":{"A":{"id":265},"B":{"id":5}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-202}],"input":{"A":{"id":265},"B":{"damage":1,"id":5}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-202}],"input":{"A":{"id":265},"B":{"damage":2,"id":5}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-202}],"input":{"A":{"id":265},"B":{"damage":3,"id":5}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-202}],"input":{"A":{"id":265},"B":{"damage":4,"id":5}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-202}],"input":{"A":{"id":265},"B":{"damage":5,"id":5}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-202}],"input":{"A":{"id":265},"B":{"id":-242}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-202}],"input":{"A":{"id":265},"B":{"id":-242}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-202}],"input":{"A":{"id":265},"B":{"id":-486}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-202}],"input":{"A":{"id":265},"B":{"id":-243}},"shape":["AA","BB","BB"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-198}],"input":{"A":{"id":-225},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":162},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-536},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-8},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-7},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-212},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-299},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-10},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-546},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":17},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-240},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-535},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-241},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-485},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-545},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-226},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-5},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-300},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-301},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-498},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-497},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-298},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-9},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-484},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-6},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-225},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-198}],"input":{"A":{"id":-484},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-198}],"input":{"A":{"id":-497},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":-198}],"input":{"A":{"id":-8},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-6},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-240},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-198}],"input":{"A":{"id":-9},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-7},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-485},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-498},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":-198}],"input":{"A":{"id":-10},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-5},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-198}],"input":{"A":{"id":-241},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-198}],"input":{"A":{"id":-226},"B":{"id":61}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":2},{"output":[{"count":4,"id":-185}],"input":{"A":{"damage":3,"id":155}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"count":4,"id":179}],"input":{"A":{"id":179}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-176}],"input":{"A":{"damage":3,"id":179}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":2,"count":4,"id":24}],"input":{"A":{"id":24}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-177}],"input":{"A":{"damage":3,"id":24}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":80}],"input":{"A":{"id":332}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":78}],"input":{"A":{"id":80}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-225}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":162}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-536}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-8}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-7}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-212}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-299}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-10}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-546}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":17}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-240}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-535}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-241}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-485}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-545}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-226}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-5}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-300}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-301}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-498}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-497}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-298}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-9}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-484}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-6}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-225}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":162}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-536}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-8}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-7}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-212}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-299}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-10}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-546}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":17}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-240}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-535}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-241}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-485}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-545}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-226}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-5}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-300}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-301}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-498}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-497}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-298}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-9}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-484}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-6}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-225}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-225}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-484}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-484}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-497}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-497}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-8}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-6}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-9}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-7}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-10}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-5}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-8}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-6}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-9}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-7}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-10}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-5}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-240}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-240}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-485}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-485}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-498}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-498}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":50},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-241}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-241}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":-236},"C":{"id":-226}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":801}],"input":{"A":{"id":280},"B":{"id":88},"C":{"id":-226}},"shape":[" A ","ABA","CCC"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":-269}],"input":{"A":{"id":452},"B":{"id":-268}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-268}],"input":{"A":{"id":263},"B":{"id":280},"C":{"id":88}},"shape":["A","B","C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-268}],"input":{"A":{"damage":1,"id":263},"B":{"id":280},"C":{"id":88}},"shape":["A","B","C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-268}],"input":{"A":{"id":263},"B":{"id":280},"C":{"id":-236}},"shape":["A","B","C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-268}],"input":{"A":{"damage":1,"id":263},"B":{"id":280},"C":{"id":-236}},"shape":["A","B","C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":382}],"input":{"A":{"id":371},"B":{"id":360}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"id":333}],"input":{"A":{"damage":1,"id":5}},"shape":["A A","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":641}],"input":[{"id":54},{"damage":1,"id":333}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":3,"id":427}],"input":{"A":{"damage":1,"id":5}},"shape":["AA","AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"count":3,"id":85}],"input":{"A":{"damage":1,"id":5},"B":{"id":280}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":183}],"input":{"A":{"id":280},"B":{"damage":1,"id":5}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-501}],"input":{"A":{"id":758},"B":{"id":-5}},"shape":["A A","BBB","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"count":4,"id":5}],"input":{"A":{"damage":1,"id":17}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"count":4,"id":5}],"input":{"A":{"id":-5}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"count":4,"id":5}],"input":{"A":{"damage":9,"id":-212}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"count":4,"id":5}],"input":{"A":{"damage":1,"id":-212}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":134}],"input":{"A":{"damage":1,"id":5}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"count":3,"id":-212}],"input":{"A":{"damage":1,"id":17}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":9,"count":3,"id":-212}],"input":{"A":{"id":-5}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":1,"count":6,"id":158}],"input":{"A":{"damage":1,"id":5}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":772}],"input":{"A":{"id":771},"B":{"id":519}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":280}],"input":{"A":{"id":-537}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":280}],"input":{"A":{"id":-510}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":280}],"input":{"A":{"id":-243}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":280}],"input":{"A":{"id":-486}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":280}],"input":{"A":{"id":5}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":280}],"input":{"A":{"damage":1,"id":5}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":280}],"input":{"A":{"damage":2,"id":5}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":280}],"input":{"A":{"damage":3,"id":5}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":280}],"input":{"A":{"damage":4,"id":5}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":280}],"input":{"A":{"damage":5,"id":5}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":280}],"input":{"A":{"id":-242}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":280}],"input":{"A":{"id":-242}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":2},{"output":[{"count":4,"id":280}],"input":{"A":{"id":-486}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":2},{"output":[{"count":4,"id":280}],"input":{"A":{"id":-243}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":29}],"input":{"A":{"id":341},"B":{"id":33}},"shape":["A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":275}],"input":{"A":{"id":-273},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":275}],"input":{"A":{"id":-379},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":275}],"input":{"A":{"id":4},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":275}],"input":{"A":{"id":-273},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":275}],"input":{"A":{"id":-379},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":2},{"output":[{"count":4,"id":109}],"input":{"A":{"id":98}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":7,"count":6,"id":139}],"input":{"A":{"id":98}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":77}],"input":{"A":{"id":1}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":291}],"input":{"A":{"id":-273},"B":{"id":280}},"shape":["AA"," B"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":291}],"input":{"A":{"id":-379},"B":{"id":280}},"shape":["AA"," B"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":291}],"input":{"A":{"id":4},"B":{"id":280}},"shape":["AA"," B"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":291}],"input":{"A":{"id":-273},"B":{"id":280}},"shape":["AA"," B"," B"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":291}],"input":{"A":{"id":-379},"B":{"id":280}},"shape":["AA"," B"," B"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":274}],"input":{"A":{"id":-273},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":274}],"input":{"A":{"id":-379},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":274}],"input":{"A":{"id":4},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":274}],"input":{"A":{"id":-273},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":274}],"input":{"A":{"id":-379},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":70}],"input":{"A":{"id":1}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":273}],"input":{"A":{"id":-273},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":273}],"input":{"A":{"id":-379},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":273}],"input":{"A":{"id":4},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":273}],"input":{"A":{"id":-273},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":273}],"input":{"A":{"id":-379},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":2},{"output":[{"count":4,"id":-180}],"input":{"A":{"id":1}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":272}],"input":{"A":{"id":-273},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":272}],"input":{"A":{"id":-379},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":272}],"input":{"A":{"id":4},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":272}],"input":{"A":{"id":-273},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":272}],"input":{"A":{"id":-379},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":2},{"output":[{"count":4,"id":98}],"input":{"A":{"id":1}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-197}],"input":{"A":{"id":265},"B":{"id":1}},"shape":[" A ","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":35}],"input":{"A":{"id":287}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":-300}],"input":{"A":{"id":-240}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":-301}],"input":{"A":{"id":-241}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":353}],"input":{"A":{"id":338}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":7,"id":734}],"input":[{"damage":2,"id":38},{"id":39},{"id":40},{"id":281}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":3,"id":734}],"input":[{"damage":3,"id":38},{"id":39},{"id":40},{"id":281}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":6,"id":734}],"input":[{"damage":1,"id":38},{"id":39},{"id":40},{"id":281}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":1,"id":734}],"input":[{"damage":9,"id":38},{"id":39},{"id":40},{"id":281}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":5,"id":734}],"input":[{"id":37},{"id":39},{"id":40},{"id":281}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":4,"id":734}],"input":[{"damage":10,"id":38},{"id":39},{"id":40},{"id":281}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":8,"id":734}],"input":[{"damage":8,"id":38},{"id":39},{"id":40},{"id":281}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":734}],"input":[{"id":38},{"id":39},{"id":40},{"id":281}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":10,"id":734}],"input":[{"id":-568},{"id":39},{"id":40},{"id":281}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":2,"id":734}],"input":[{"damage":5,"id":38},{"id":39},{"id":40},{"id":281}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":2,"id":734}],"input":[{"damage":7,"id":38},{"id":39},{"id":40},{"id":281}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":2,"id":734}],"input":[{"damage":4,"id":38},{"id":39},{"id":40},{"id":281}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":2,"id":734}],"input":[{"damage":6,"id":38},{"id":39},{"id":40},{"id":281}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":9,"id":734}],"input":[{"id":-216},{"id":39},{"id":40},{"id":281}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":-239}],"input":{"A":{"id":331},"B":{"id":170}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":-334}],"input":{"A":{"id":771},"B":{"id":20}},"shape":[" A ","ABA"," A "],"block":"crafting_table","type":1,"priority":1},{"output":[{"id":46}],"input":{"A":{"id":289},"B":{"id":12}},"shape":["ABA","BAB","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":407}],"input":[{"id":46},{"id":328}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":4,"id":50}],"input":{"A":{"id":263},"B":{"id":280}},"shape":["A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":50}],"input":{"A":{"damage":1,"id":263},"B":{"id":280}},"shape":["A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":146}],"input":[{"id":54},{"id":131}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":2,"id":131}],"input":{"A":{"id":265},"B":{"id":280},"C":{"id":-537}},"shape":["A","B","C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":131}],"input":{"A":{"id":265},"B":{"id":280},"C":{"id":-510}},"shape":["A","B","C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":131}],"input":{"A":{"id":265},"B":{"id":280},"C":{"id":-243}},"shape":["A","B","C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":131}],"input":{"A":{"id":265},"B":{"id":280},"C":{"id":-486}},"shape":["A","B","C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":131}],"input":{"A":{"id":265},"B":{"id":280},"C":{"id":5}},"shape":["A","B","C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":131}],"input":{"A":{"id":265},"B":{"id":280},"C":{"damage":1,"id":5}},"shape":["A","B","C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":131}],"input":{"A":{"id":265},"B":{"id":280},"C":{"damage":2,"id":5}},"shape":["A","B","C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":131}],"input":{"A":{"id":265},"B":{"id":280},"C":{"damage":3,"id":5}},"shape":["A","B","C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":131}],"input":{"A":{"id":265},"B":{"id":280},"C":{"damage":4,"id":5}},"shape":["A","B","C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":131}],"input":{"A":{"id":265},"B":{"id":280},"C":{"damage":5,"id":5}},"shape":["A","B","C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":131}],"input":{"A":{"id":265},"B":{"id":280},"C":{"id":-242}},"shape":["A","B","C"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":131}],"input":{"A":{"id":265},"B":{"id":280},"C":{"id":-242}},"shape":["A","B","C"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":131}],"input":{"A":{"id":265},"B":{"id":280},"C":{"id":-486}},"shape":["A","B","C"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":131}],"input":{"A":{"id":265},"B":{"id":280},"C":{"id":-243}},"shape":["A","B","C"],"block":"crafting_table","type":1,"priority":2},{"output":[{"count":6,"id":-755}],"input":{"A":{"id":-754}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-757}],"input":{"A":{"id":-754}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":6,"id":-758}],"input":{"A":{"id":-754}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-754}],"input":{"A":{"id":-748}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-744}],"input":{"A":{"id":-333}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":4,"id":-746}],"input":{"A":{"id":-333}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":6,"id":-747}],"input":{"A":{"id":-333}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":469}],"input":{"A":{"id":468}},"shape":["AAA","A A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-261}],"input":{"A":{"id":-243}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":756}],"input":{"A":{"id":-243}},"shape":["AA","AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":-257}],"input":{"A":{"id":-243},"B":{"id":280}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-259}],"input":{"A":{"id":280},"B":{"id":-243}},"shape":["ABA","ABA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":757}],"input":{"A":{"id":346},"B":{"id":-229}},"shape":["A "," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-507}],"input":{"A":{"id":758},"B":{"id":-241}},"shape":["A A","BBB","BBB"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":-298}],"input":{"A":{"id":-226}},"shape":["AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-243}],"input":{"A":{"id":-226}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-243}],"input":{"A":{"id":-241}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-243}],"input":{"A":{"id":-301}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-243}],"input":{"A":{"id":-298}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-263}],"input":{"A":{"id":-243}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":3,"id":754}],"input":{"A":{"id":-243},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":6,"id":-265}],"input":{"A":{"id":-243}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-255}],"input":{"A":{"id":-243}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":2,"id":-247}],"input":{"A":{"id":-243}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-764}],"input":{"A":{"id":-365}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-780}],"input":{"A":{"id":-344},"B":{"id":369},"C":{"id":331}},"shape":[" A ","ABA"," C "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-772}],"input":{"A":{"id":-344}},"shape":[" A ","A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-765}],"input":{"A":{"id":-366}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-765}],"input":[{"id":-761},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"count":4,"id":-781}],"input":{"A":{"id":-345},"B":{"id":369},"C":{"id":331}},"shape":[" A ","ABA"," C "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-773}],"input":{"A":{"id":-345}},"shape":[" A ","A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-766}],"input":{"A":{"id":-449}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-766}],"input":[{"id":-763},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"count":4,"id":-783}],"input":{"A":{"id":-446},"B":{"id":369},"C":{"id":331}},"shape":[" A ","ABA"," C "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-775}],"input":{"A":{"id":-446}},"shape":[" A ","A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-767}],"input":{"A":{"id":-367}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-767}],"input":[{"id":-762},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"count":4,"id":-782}],"input":{"A":{"id":-346},"B":{"id":369},"C":{"id":331}},"shape":[" A ","ABA"," C "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-774}],"input":{"A":{"id":-346}},"shape":[" A ","A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-764}],"input":[{"id":-760},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-344}],"input":[{"id":-340},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-780}],"input":[{"id":-776},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-788}],"input":[{"id":-784},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-772}],"input":[{"id":-768},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-796}],"input":[{"id":-792},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-351}],"input":[{"id":-347},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-365}],"input":[{"id":-361},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-358}],"input":[{"id":-354},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-345}],"input":[{"id":-341},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-781}],"input":[{"id":-777},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-789}],"input":[{"id":-785},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-773}],"input":[{"id":-769},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-797}],"input":[{"id":-793},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-352}],"input":[{"id":-348},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-366}],"input":[{"id":-362},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-359}],"input":[{"id":-355},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-446}],"input":[{"id":-343},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-783}],"input":[{"id":-779},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-791}],"input":[{"id":-787},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-775}],"input":[{"id":-771},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-799}],"input":[{"id":-795},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-447}],"input":[{"id":-350},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-449}],"input":[{"id":-364},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-448}],"input":[{"id":-357},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-346}],"input":[{"id":-342},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-782}],"input":[{"id":-778},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-790}],"input":[{"id":-786},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-774}],"input":[{"id":-770},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-798}],"input":[{"id":-794},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-353}],"input":[{"id":-349},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-367}],"input":[{"id":-363},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-360}],"input":[{"id":-356},{"id":736}],"block":"crafting_table","type":0,"priority":1},{"output":[{"id":-762}],"input":{"A":{"id":-363}},"shape":["A","A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-778}],"input":{"A":{"id":-342},"B":{"id":369},"C":{"id":331}},"shape":[" A ","ABA"," C "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":-770}],"input":{"A":{"id":-342}},"shape":[" A ","A A"," A "],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":9,"id":296}],"input":{"A":{"id":170}},"shape":["A"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":15,"nbt_b64":"CgAAAwQAVHlwZQAAAAAA","id":446}],"input":{"A":{"id":35},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-413}],"input":[{"id":-412},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"id":-413}],"input":[{"id":-412},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":3,"id":171}],"input":{"A":{"id":35}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":1},{"output":[{"damage":19,"id":351}],"input":[{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":19,"id":351}],"input":[{"damage":10,"id":38}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":8,"id":241}],"input":{"A":{"id":20},"B":{"damage":19,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":8,"id":241}],"input":{"A":{"id":20},"B":{"damage":15,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"count":16,"id":160}],"input":{"A":{"id":241}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":8,"id":160}],"input":{"A":{"id":102},"B":{"damage":19,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":8,"id":159}],"input":{"A":{"id":172},"B":{"damage":19,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":8,"id":159}],"input":{"A":{"id":172},"B":{"damage":15,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":1},{"output":[{"id":271}],"input":{"A":{"id":-537},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":271}],"input":{"A":{"id":-510},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":271}],"input":{"A":{"id":-243},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":271}],"input":{"A":{"id":-486},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":271}],"input":{"A":{"id":5},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":271}],"input":{"A":{"damage":1,"id":5},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":271}],"input":{"A":{"damage":2,"id":5},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":271}],"input":{"A":{"damage":3,"id":5},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":271}],"input":{"A":{"damage":4,"id":5},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":271}],"input":{"A":{"damage":5,"id":5},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":271}],"input":{"A":{"id":-242},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":271}],"input":{"A":{"id":-242},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":271}],"input":{"A":{"id":-486},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":271}],"input":{"A":{"id":-243},"B":{"id":280}},"shape":["AA","AB"," B"],"block":"crafting_table","type":1,"priority":2},{"output":[{"count":3,"id":324}],"input":{"A":{"id":5}},"shape":["AA","AA","AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":290}],"input":{"A":{"id":-537},"B":{"id":280}},"shape":["AA"," B"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":290}],"input":{"A":{"id":-510},"B":{"id":280}},"shape":["AA"," B"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":290}],"input":{"A":{"id":-243},"B":{"id":280}},"shape":["AA"," B"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":290}],"input":{"A":{"id":-486},"B":{"id":280}},"shape":["AA"," B"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":290}],"input":{"A":{"id":5},"B":{"id":280}},"shape":["AA"," B"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":290}],"input":{"A":{"damage":1,"id":5},"B":{"id":280}},"shape":["AA"," B"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":290}],"input":{"A":{"damage":2,"id":5},"B":{"id":280}},"shape":["AA"," B"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":290}],"input":{"A":{"damage":3,"id":5},"B":{"id":280}},"shape":["AA"," B"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":290}],"input":{"A":{"damage":4,"id":5},"B":{"id":280}},"shape":["AA"," B"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":290}],"input":{"A":{"damage":5,"id":5},"B":{"id":280}},"shape":["AA"," B"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":290}],"input":{"A":{"id":-242},"B":{"id":280}},"shape":["AA"," B"," B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":290}],"input":{"A":{"id":-242},"B":{"id":280}},"shape":["AA "," B "," B "],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":290}],"input":{"A":{"id":-486},"B":{"id":280}},"shape":["AA "," B "," B "],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":290}],"input":{"A":{"id":-243},"B":{"id":280}},"shape":["AA "," B "," B "],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":270}],"input":{"A":{"id":-537},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":270}],"input":{"A":{"id":-510},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":270}],"input":{"A":{"id":-243},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":270}],"input":{"A":{"id":-486},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":270}],"input":{"A":{"id":5},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":270}],"input":{"A":{"damage":1,"id":5},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":270}],"input":{"A":{"damage":2,"id":5},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":270}],"input":{"A":{"damage":3,"id":5},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":270}],"input":{"A":{"damage":4,"id":5},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":270}],"input":{"A":{"damage":5,"id":5},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":270}],"input":{"A":{"id":-242},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":270}],"input":{"A":{"id":-242},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":270}],"input":{"A":{"id":-486},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":270}],"input":{"A":{"id":-243},"B":{"id":280}},"shape":["AAA"," B "," B "],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":269}],"input":{"A":{"id":-537},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":269}],"input":{"A":{"id":-510},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":269}],"input":{"A":{"id":-243},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":269}],"input":{"A":{"id":-486},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":269}],"input":{"A":{"id":5},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":269}],"input":{"A":{"damage":1,"id":5},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":269}],"input":{"A":{"damage":2,"id":5},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":269}],"input":{"A":{"damage":3,"id":5},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":269}],"input":{"A":{"damage":4,"id":5},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":269}],"input":{"A":{"damage":5,"id":5},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":269}],"input":{"A":{"id":-242},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":269}],"input":{"A":{"id":-242},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":269}],"input":{"A":{"id":-486},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":269}],"input":{"A":{"id":-243},"B":{"id":280}},"shape":["A","B","B"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":268}],"input":{"A":{"id":-537},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":268}],"input":{"A":{"id":-510},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":268}],"input":{"A":{"id":-243},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":268}],"input":{"A":{"id":-486},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":268}],"input":{"A":{"id":5},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":268}],"input":{"A":{"damage":1,"id":5},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":268}],"input":{"A":{"damage":2,"id":5},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":268}],"input":{"A":{"damage":3,"id":5},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":268}],"input":{"A":{"damage":4,"id":5},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":268}],"input":{"A":{"damage":5,"id":5},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":268}],"input":{"A":{"id":-242},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":268}],"input":{"A":{"id":-242},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":268}],"input":{"A":{"id":-486},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":268}],"input":{"A":{"id":-243},"B":{"id":280}},"shape":["A","A","B"],"block":"crafting_table","type":1,"priority":2},{"output":[{"id":386}],"input":[{"id":288},{"id":340},{"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":11,"nbt_b64":"CgAAAwQAVHlwZQAAAAAA","id":446}],"input":{"A":{"damage":4,"id":35},"B":{"id":280}},"shape":["AAA","AAA"," B "],"block":"crafting_table","type":1,"priority":0},{"output":[{"id":-417}],"input":[{"id":-412},{"damage":11,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":4,"count":3,"id":171}],"input":{"A":{"damage":4,"id":35}},"shape":["AA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"count":8,"id":171}],"input":{"A":{"id":171},"B":{"damage":11,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"count":8,"id":237}],"input":[{"id":12},{"id":12},{"id":12},{"id":12},{"id":13},{"id":13},{"id":13},{"id":13},{"damage":11,"id":351}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":11,"id":351}],"input":[{"id":37}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":11,"count":2,"id":351}],"input":[{"id":175}],"block":"crafting_table","type":0,"priority":0},{"output":[{"damage":4,"count":8,"id":241}],"input":{"A":{"id":20},"B":{"damage":11,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"count":16,"id":160}],"input":{"A":{"damage":4,"id":241}},"shape":["AAA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"count":8,"id":160}],"input":{"A":{"id":102},"B":{"damage":11,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"damage":4,"count":8,"id":159}],"input":{"A":{"id":172},"B":{"damage":11,"id":351}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":0},{"output":[{"count":4,"id":53}],"input":{"A":{"id":5}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAAABwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAABDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAABDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAAKBwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"damage":10,"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAoBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"damage":10,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAoBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"damage":10,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAALBwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"damage":11,"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAsBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"damage":11,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAsBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"damage":11,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAAMBwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"damage":12,"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAwBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"damage":12,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAwBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"damage":12,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAANBwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"damage":13,"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAA0BDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"damage":13,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAA0BDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"damage":13,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAAOBwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"damage":14,"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAA4BDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"damage":14,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAA4BDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"damage":14,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAAPBwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"damage":15,"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAA8BDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"damage":15,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAA8BDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"damage":15,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAAABwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAABDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAABDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAADBwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"damage":3,"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAMBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"damage":3,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAMBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"damage":3,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAAEBwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"damage":4,"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAQBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"damage":4,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAQBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"damage":4,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAAPBwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"damage":15,"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAA8BDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"damage":15,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAA8BDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"damage":15,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAABBwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"damage":1,"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAEBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"damage":1,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAEBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"damage":1,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAACBwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"damage":2,"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAIBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"damage":2,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAIBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"damage":2,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAADBwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"damage":3,"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAMBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"damage":3,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAMBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"damage":3,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAAEBwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"damage":4,"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAQBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"damage":4,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAQBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"damage":4,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAAFBwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"damage":5,"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAUBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"damage":5,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAUBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"damage":5,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAAGBwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"damage":6,"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAYBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"damage":6,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAYBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"damage":6,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAAHBwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"damage":7,"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAcBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"damage":7,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAcBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"damage":7,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAAIBwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"damage":8,"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAgBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"damage":8,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAgBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"damage":8,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwoBAAAABw0ARmlyZXdvcmtDb2xvcgEAAAAJBwwARmlyZXdvcmtGYWRlAAAAAAEPAEZpcmV3b3JrRmxpY2tlcgABDQBGaXJld29ya1RyYWlsAAEMAEZpcmV3b3JrVHlwZQAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339},{"damage":9,"id":402}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAkBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339},{"damage":9,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMKAQAAAAcMAEZpcmV3b3JrRmFkZQAAAAAHDQBGaXJld29ya0NvbG9yAQAAAAkBDABGaXJld29ya1R5cGUAAQ0ARmlyZXdvcmtUcmFpbAABDwBGaXJld29ya0ZsaWNrZXIAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339},{"damage":9,"id":402}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAAAAcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9yIR0d/wA\u003d","id":402}],"input":[{"id":289},{"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAACgcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9yH8eA/wA\u003d","id":402}],"input":[{"id":289},{"damage":10,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAACwcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9yPdj+/wA\u003d","id":402}],"input":[{"id":289},{"damage":11,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAADAcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9y2rM6/wA\u003d","id":402}],"input":[{"id":289},{"damage":12,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAADQcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9yvU7H/wA\u003d","id":402}],"input":[{"id":289},{"damage":13,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAADgcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9yHYD5/wA\u003d","id":402}],"input":[{"id":289},{"damage":14,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAADwcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9y8PDw/wA\u003d","id":402}],"input":[{"id":289},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAAAAcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9yIR0d/wA\u003d","id":402}],"input":[{"id":289},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAAAwcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9yMlSD/wA\u003d","id":402}],"input":[{"id":289},{"damage":17,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAABAcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9yqkQ8/wA\u003d","id":402}],"input":[{"id":289},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAADwcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9y8PDw/wA\u003d","id":402}],"input":[{"id":289},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAAAQcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9yJi6w/wA\u003d","id":402}],"input":[{"id":289},{"damage":1,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAAAgcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9yFnxe/wA\u003d","id":402}],"input":[{"id":289},{"damage":2,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAAAwcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9yMlSD/wA\u003d","id":402}],"input":[{"id":289},{"damage":3,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAABAcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9yqkQ8/wA\u003d","id":402}],"input":[{"id":289},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAABQcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9yuDKJ/wA\u003d","id":402}],"input":[{"id":289},{"damage":5,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAABgcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9ynJwW/wA\u003d","id":402}],"input":[{"id":289},{"damage":6,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAABwcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9yl52d/wA\u003d","id":402}],"input":[{"id":289},{"damage":7,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAACAcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9yUk9H/wA\u003d","id":402}],"input":[{"id":289},{"damage":8,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"nbt_b64":"CgAACg0ARmlyZXdvcmtzSXRlbQcNAEZpcmV3b3JrQ29sb3IBAAAACQcMAEZpcmV3b3JrRmFkZQAAAAABDwBGaXJld29ya0ZsaWNrZXIAAQ0ARmlyZXdvcmtUcmFpbAABDABGaXJld29ya1R5cGUAAAMLAGN1c3RvbUNvbG9yqovz/wA\u003d","id":402}],"input":[{"id":289},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzCQoARXhwbG9zaW9ucwAAAAAAAQYARmxpZ2h0AQAA","count":3,"id":401}],"input":[{"id":289},{"id":339}],"block":"crafting_table","type":0,"priority":50},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AgkKAEV4cGxvc2lvbnMBAAAAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":339}],"block":"crafting_table","type":0,"priority":0},{"output":[{"nbt_b64":"CgAACgkARmlyZXdvcmtzAQYARmxpZ2h0AwkKAEV4cGxvc2lvbnMBAAAAAAAA","count":3,"id":401}],"input":[{"id":289},{"id":289},{"id":289},{"id":339}],"block":"crafting_table","type":0,"priority":0},{"output":[{"count":6,"id":-162}],"input":{"A":{"id":206}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"count":4,"id":134}],"input":{"A":{"damage":1,"id":5}},"shape":["A ","AA ","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"count":6,"id":182}],"input":{"A":{"id":179}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":4,"count":6,"id":182}],"input":{"A":{"damage":2,"id":168}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":3,"count":6,"id":182}],"input":{"A":{"damage":1,"id":168}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":1,"count":6,"id":182}],"input":{"A":{"id":201}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":5,"count":6,"id":182}],"input":{"A":{"id":48}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":7,"count":6,"id":182}],"input":{"A":{"id":215}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"count":6,"id":182}],"input":{"A":{"damage":1,"id":179}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":6,"count":6,"id":182}],"input":{"A":{"damage":3,"id":24}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":3,"count":6,"id":-162}],"input":{"A":{"damage":5,"id":1}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":4,"count":6,"id":-162}],"input":{"A":{"damage":3,"id":1}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":6,"count":6,"id":-162}],"input":{"A":{"damage":1,"id":1}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":7,"count":6,"id":-162}],"input":{"A":{"damage":2,"id":1}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":2,"count":6,"id":-162}],"input":{"A":{"damage":6,"id":1}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":5,"count":6,"id":-162}],"input":{"A":{"damage":4,"id":1}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":1,"count":6,"id":-162}],"input":{"A":{"damage":3,"id":179}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":4,"count":6,"id":-166}],"input":{"A":{"damage":2,"id":179}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":3,"count":6,"id":-166}],"input":{"A":{"damage":2,"id":24}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":1,"count":6,"id":-166}],"input":{"A":{"damage":3,"id":155}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":6,"count":6,"id":44}],"input":{"A":{"id":155}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":2,"count":6,"id":182}],"input":{"A":{"id":168}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":1,"count":6,"id":44}],"input":{"A":{"damage":1,"id":24}},"shape":["AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":11,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":10,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":12,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":11,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":13,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":12,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":14,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":13,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":15,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":14,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":16,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":15,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":17,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":16,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":18,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":17,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":19,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":18,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":20,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":19,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":21,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":20,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":22,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":21,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":23,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":22,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":24,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":23,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":25,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":24,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":26,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":25,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":27,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":26,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":28,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":27,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":29,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":28,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":30,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":29,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":31,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":30,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":32,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":31,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":33,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":32,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":34,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":33,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":35,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":34,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":36,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":35,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":37,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":36,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":38,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":37,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":39,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":38,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":40,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":39,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":41,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":40,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":42,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":41,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":43,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":42,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":44,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":43,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":45,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":44,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":46,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":45,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":47,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":46,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":6,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":5,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":7,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":6,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":8,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":7,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":9,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":8,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":10,"count":8,"id":262}],"input":{"A":{"id":262},"B":{"damage":9,"id":441}},"shape":["AAA","ABA","AAA"],"block":"crafting_table","type":1,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":14,"id":35},{"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":5,"id":35},{"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":4,"id":35},{"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":3,"id":35},{"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":2,"id":35},{"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":1,"id":35},{"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"id":35},{"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":13,"id":35},{"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":12,"id":35},{"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":11,"id":35},{"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":10,"id":35},{"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":9,"id":35},{"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":8,"id":35},{"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":7,"id":35},{"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":6,"id":35},{"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":35}],"input":[{"damage":15,"id":35},{"damage":10,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":35}],"input":[{"damage":14,"id":35},{"damage":10,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":35}],"input":[{"damage":4,"id":35},{"damage":10,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":35}],"input":[{"damage":3,"id":35},{"damage":10,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":35}],"input":[{"damage":2,"id":35},{"damage":10,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":35}],"input":[{"damage":1,"id":35},{"damage":10,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":35}],"input":[{"id":35},{"damage":10,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":35}],"input":[{"damage":13,"id":35},{"damage":10,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":35}],"input":[{"damage":12,"id":35},{"damage":10,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":35}],"input":[{"damage":11,"id":35},{"damage":10,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":35}],"input":[{"damage":10,"id":35},{"damage":10,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":35}],"input":[{"damage":9,"id":35},{"damage":10,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":35}],"input":[{"damage":8,"id":35},{"damage":10,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":35}],"input":[{"damage":7,"id":35},{"damage":10,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":5,"id":35}],"input":[{"damage":6,"id":35},{"damage":10,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":35}],"input":[{"damage":15,"id":35},{"damage":11,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":35}],"input":[{"damage":14,"id":35},{"damage":11,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":35}],"input":[{"damage":5,"id":35},{"damage":11,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":35}],"input":[{"damage":3,"id":35},{"damage":11,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":35}],"input":[{"damage":2,"id":35},{"damage":11,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":35}],"input":[{"damage":1,"id":35},{"damage":11,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":35}],"input":[{"id":35},{"damage":11,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":35}],"input":[{"damage":13,"id":35},{"damage":11,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":35}],"input":[{"damage":12,"id":35},{"damage":11,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":35}],"input":[{"damage":11,"id":35},{"damage":11,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":35}],"input":[{"damage":10,"id":35},{"damage":11,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":35}],"input":[{"damage":9,"id":35},{"damage":11,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":35}],"input":[{"damage":8,"id":35},{"damage":11,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":35}],"input":[{"damage":7,"id":35},{"damage":11,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":4,"id":35}],"input":[{"damage":6,"id":35},{"damage":11,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":35}],"input":[{"damage":15,"id":35},{"damage":12,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":35}],"input":[{"damage":14,"id":35},{"damage":12,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":35}],"input":[{"damage":5,"id":35},{"damage":12,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":35}],"input":[{"damage":4,"id":35},{"damage":12,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":35}],"input":[{"damage":2,"id":35},{"damage":12,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":35}],"input":[{"damage":1,"id":35},{"damage":12,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":35}],"input":[{"id":35},{"damage":12,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":35}],"input":[{"damage":13,"id":35},{"damage":12,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":35}],"input":[{"damage":12,"id":35},{"damage":12,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":35}],"input":[{"damage":11,"id":35},{"damage":12,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":35}],"input":[{"damage":10,"id":35},{"damage":12,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":35}],"input":[{"damage":9,"id":35},{"damage":12,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":35}],"input":[{"damage":8,"id":35},{"damage":12,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":35}],"input":[{"damage":7,"id":35},{"damage":12,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":3,"id":35}],"input":[{"damage":6,"id":35},{"damage":12,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":35}],"input":[{"damage":15,"id":35},{"damage":13,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":35}],"input":[{"damage":14,"id":35},{"damage":13,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":35}],"input":[{"damage":5,"id":35},{"damage":13,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":35}],"input":[{"damage":4,"id":35},{"damage":13,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":35}],"input":[{"damage":3,"id":35},{"damage":13,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":35}],"input":[{"damage":1,"id":35},{"damage":13,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":35}],"input":[{"id":35},{"damage":13,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":35}],"input":[{"damage":13,"id":35},{"damage":13,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":35}],"input":[{"damage":12,"id":35},{"damage":13,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":35}],"input":[{"damage":11,"id":35},{"damage":13,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":35}],"input":[{"damage":10,"id":35},{"damage":13,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":35}],"input":[{"damage":9,"id":35},{"damage":13,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":35}],"input":[{"damage":8,"id":35},{"damage":13,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":35}],"input":[{"damage":7,"id":35},{"damage":13,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":2,"id":35}],"input":[{"damage":6,"id":35},{"damage":13,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":35}],"input":[{"damage":15,"id":35},{"damage":14,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":35}],"input":[{"damage":14,"id":35},{"damage":14,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":35}],"input":[{"damage":5,"id":35},{"damage":14,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":35}],"input":[{"damage":4,"id":35},{"damage":14,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":35}],"input":[{"damage":3,"id":35},{"damage":14,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":35}],"input":[{"damage":2,"id":35},{"damage":14,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":35}],"input":[{"id":35},{"damage":14,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":35}],"input":[{"damage":13,"id":35},{"damage":14,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":35}],"input":[{"damage":12,"id":35},{"damage":14,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":35}],"input":[{"damage":11,"id":35},{"damage":14,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":35}],"input":[{"damage":10,"id":35},{"damage":14,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":35}],"input":[{"damage":9,"id":35},{"damage":14,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":35}],"input":[{"damage":8,"id":35},{"damage":14,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":35}],"input":[{"damage":7,"id":35},{"damage":14,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":1,"id":35}],"input":[{"damage":6,"id":35},{"damage":14,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":15,"id":35},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":14,"id":35},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":5,"id":35},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":4,"id":35},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":3,"id":35},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":2,"id":35},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":1,"id":35},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":13,"id":35},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":12,"id":35},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":11,"id":35},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":10,"id":35},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":9,"id":35},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":8,"id":35},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":7,"id":35},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":6,"id":35},{"damage":15,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":14,"id":35},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":5,"id":35},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":4,"id":35},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":3,"id":35},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":2,"id":35},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":1,"id":35},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"id":35},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":13,"id":35},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":12,"id":35},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":11,"id":35},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":10,"id":35},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":9,"id":35},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":8,"id":35},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":7,"id":35},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":15,"id":35}],"input":[{"damage":6,"id":35},{"damage":16,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":15,"id":35},{"damage":17,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":14,"id":35},{"damage":17,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":5,"id":35},{"damage":17,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":4,"id":35},{"damage":17,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":3,"id":35},{"damage":17,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":2,"id":35},{"damage":17,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":1,"id":35},{"damage":17,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"id":35},{"damage":17,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":13,"id":35},{"damage":17,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":11,"id":35},{"damage":17,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":10,"id":35},{"damage":17,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":9,"id":35},{"damage":17,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":8,"id":35},{"damage":17,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":7,"id":35},{"damage":17,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":6,"id":35},{"damage":17,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":15,"id":35},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":14,"id":35},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":5,"id":35},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":4,"id":35},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":3,"id":35},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":2,"id":35},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":1,"id":35},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"id":35},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":13,"id":35},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":12,"id":35},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":10,"id":35},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":9,"id":35},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":8,"id":35},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":7,"id":35},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":6,"id":35},{"damage":18,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":15,"id":35},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":14,"id":35},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":5,"id":35},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":4,"id":35},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":3,"id":35},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":2,"id":35},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":1,"id":35},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":13,"id":35},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":12,"id":35},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":11,"id":35},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":10,"id":35},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":9,"id":35},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":8,"id":35},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":7,"id":35},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"id":35}],"input":[{"damage":6,"id":35},{"damage":19,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":35}],"input":[{"damage":15,"id":35},{"damage":1,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":35}],"input":[{"damage":5,"id":35},{"damage":1,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":35}],"input":[{"damage":4,"id":35},{"damage":1,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":35}],"input":[{"damage":3,"id":35},{"damage":1,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":35}],"input":[{"damage":2,"id":35},{"damage":1,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":35}],"input":[{"damage":1,"id":35},{"damage":1,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":35}],"input":[{"id":35},{"damage":1,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":35}],"input":[{"damage":13,"id":35},{"damage":1,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":35}],"input":[{"damage":12,"id":35},{"damage":1,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":35}],"input":[{"damage":11,"id":35},{"damage":1,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":35}],"input":[{"damage":10,"id":35},{"damage":1,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":35}],"input":[{"damage":9,"id":35},{"damage":1,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":35}],"input":[{"damage":8,"id":35},{"damage":1,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":35}],"input":[{"damage":7,"id":35},{"damage":1,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":14,"id":35}],"input":[{"damage":6,"id":35},{"damage":1,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":35}],"input":[{"damage":15,"id":35},{"damage":2,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":35}],"input":[{"damage":14,"id":35},{"damage":2,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":35}],"input":[{"damage":5,"id":35},{"damage":2,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":35}],"input":[{"damage":4,"id":35},{"damage":2,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":35}],"input":[{"damage":3,"id":35},{"damage":2,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":35}],"input":[{"damage":2,"id":35},{"damage":2,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":35}],"input":[{"damage":1,"id":35},{"damage":2,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":35}],"input":[{"id":35},{"damage":2,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":35}],"input":[{"damage":12,"id":35},{"damage":2,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":35}],"input":[{"damage":11,"id":35},{"damage":2,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":35}],"input":[{"damage":10,"id":35},{"damage":2,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":35}],"input":[{"damage":9,"id":35},{"damage":2,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":35}],"input":[{"damage":8,"id":35},{"damage":2,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":35}],"input":[{"damage":7,"id":35},{"damage":2,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":13,"id":35}],"input":[{"damage":6,"id":35},{"damage":2,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":15,"id":35},{"damage":3,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":14,"id":35},{"damage":3,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":5,"id":35},{"damage":3,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":4,"id":35},{"damage":3,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":3,"id":35},{"damage":3,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":2,"id":35},{"damage":3,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":1,"id":35},{"damage":3,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"id":35},{"damage":3,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":13,"id":35},{"damage":3,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":11,"id":35},{"damage":3,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":10,"id":35},{"damage":3,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":9,"id":35},{"damage":3,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":8,"id":35},{"damage":3,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":7,"id":35},{"damage":3,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":12,"id":35}],"input":[{"damage":6,"id":35},{"damage":3,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":15,"id":35},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":14,"id":35},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":5,"id":35},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":4,"id":35},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":3,"id":35},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":2,"id":35},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":1,"id":35},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"id":35},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":13,"id":35},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":12,"id":35},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":10,"id":35},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":9,"id":35},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":8,"id":35},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":7,"id":35},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":11,"id":35}],"input":[{"damage":6,"id":35},{"damage":4,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":35}],"input":[{"damage":15,"id":35},{"damage":5,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":35}],"input":[{"damage":14,"id":35},{"damage":5,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":35}],"input":[{"damage":5,"id":35},{"damage":5,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":35}],"input":[{"damage":4,"id":35},{"damage":5,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":35}],"input":[{"damage":3,"id":35},{"damage":5,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":35}],"input":[{"damage":2,"id":35},{"damage":5,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":35}],"input":[{"damage":1,"id":35},{"damage":5,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":35}],"input":[{"id":35},{"damage":5,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":35}],"input":[{"damage":13,"id":35},{"damage":5,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":35}],"input":[{"damage":12,"id":35},{"damage":5,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":35}],"input":[{"damage":11,"id":35},{"damage":5,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":35}],"input":[{"damage":9,"id":35},{"damage":5,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":35}],"input":[{"damage":8,"id":35},{"damage":5,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":35}],"input":[{"damage":7,"id":35},{"damage":5,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":10,"id":35}],"input":[{"damage":6,"id":35},{"damage":5,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":35}],"input":[{"damage":15,"id":35},{"damage":6,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":35}],"input":[{"damage":14,"id":35},{"damage":6,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":35}],"input":[{"damage":5,"id":35},{"damage":6,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":35}],"input":[{"damage":4,"id":35},{"damage":6,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":35}],"input":[{"damage":3,"id":35},{"damage":6,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":35}],"input":[{"damage":2,"id":35},{"damage":6,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":35}],"input":[{"damage":1,"id":35},{"damage":6,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":35}],"input":[{"id":35},{"damage":6,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":35}],"input":[{"damage":13,"id":35},{"damage":6,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":35}],"input":[{"damage":12,"id":35},{"damage":6,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":35}],"input":[{"damage":11,"id":35},{"damage":6,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":35}],"input":[{"damage":10,"id":35},{"damage":6,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":35}],"input":[{"damage":8,"id":35},{"damage":6,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":35}],"input":[{"damage":7,"id":35},{"damage":6,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":9,"id":35}],"input":[{"damage":6,"id":35},{"damage":6,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":35}],"input":[{"damage":15,"id":35},{"damage":7,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":35}],"input":[{"damage":14,"id":35},{"damage":7,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":35}],"input":[{"damage":5,"id":35},{"damage":7,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":35}],"input":[{"damage":4,"id":35},{"damage":7,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":35}],"input":[{"damage":3,"id":35},{"damage":7,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":35}],"input":[{"damage":2,"id":35},{"damage":7,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":35}],"input":[{"damage":1,"id":35},{"damage":7,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":35}],"input":[{"id":35},{"damage":7,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":35}],"input":[{"damage":13,"id":35},{"damage":7,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":35}],"input":[{"damage":12,"id":35},{"damage":7,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":35}],"input":[{"damage":11,"id":35},{"damage":7,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":35}],"input":[{"damage":10,"id":35},{"damage":7,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":35}],"input":[{"damage":9,"id":35},{"damage":7,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":35}],"input":[{"damage":7,"id":35},{"damage":7,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":8,"id":35}],"input":[{"damage":6,"id":35},{"damage":7,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":35}],"input":[{"damage":15,"id":35},{"damage":8,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":35}],"input":[{"damage":14,"id":35},{"damage":8,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":35}],"input":[{"damage":5,"id":35},{"damage":8,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":35}],"input":[{"damage":4,"id":35},{"damage":8,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":35}],"input":[{"damage":3,"id":35},{"damage":8,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":35}],"input":[{"damage":2,"id":35},{"damage":8,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":35}],"input":[{"damage":1,"id":35},{"damage":8,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":35}],"input":[{"id":35},{"damage":8,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":35}],"input":[{"damage":13,"id":35},{"damage":8,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":35}],"input":[{"damage":12,"id":35},{"damage":8,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":35}],"input":[{"damage":11,"id":35},{"damage":8,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":35}],"input":[{"damage":10,"id":35},{"damage":8,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":35}],"input":[{"damage":9,"id":35},{"damage":8,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":35}],"input":[{"damage":8,"id":35},{"damage":8,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":7,"id":35}],"input":[{"damage":6,"id":35},{"damage":8,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":35}],"input":[{"damage":15,"id":35},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":35}],"input":[{"damage":14,"id":35},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":35}],"input":[{"damage":5,"id":35},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":35}],"input":[{"damage":4,"id":35},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":35}],"input":[{"damage":3,"id":35},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":35}],"input":[{"damage":2,"id":35},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":35}],"input":[{"damage":1,"id":35},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":35}],"input":[{"id":35},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":35}],"input":[{"damage":13,"id":35},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":35}],"input":[{"damage":12,"id":35},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":35}],"input":[{"damage":11,"id":35},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":35}],"input":[{"damage":10,"id":35},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":35}],"input":[{"damage":9,"id":35},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":35}],"input":[{"damage":8,"id":35},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":[{"damage":6,"id":35}],"input":[{"damage":7,"id":35},{"damage":9,"id":351}],"block":"crafting_table","type":0,"priority":50},{"output":{"damage":0,"count":1,"id":266},"input":{"damage":0,"count":1,"id":-288},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":0,"count":1,"id":-497},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":265},"input":{"damage":0,"count":1,"id":520},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":371},"input":{"damage":0,"count":1,"id":283},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":406},"input":{"damage":0,"count":1,"id":153},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":3,"count":1,"id":-212},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":0,"count":1,"id":-5},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":231},"input":{"damage":11,"count":1,"id":159},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":219},"input":{"damage":10,"count":1,"id":159},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":452},"input":{"damage":0,"count":1,"id":306},"block":"furnace","type":3},{"output":{"damage":4,"count":1,"id":351},"input":{"damage":0,"count":1,"id":-400},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":4,"count":1,"id":-212},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":0,"count":1,"id":-10},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":2,"count":1,"id":-212},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":0,"count":1,"id":-535},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":264},"input":{"damage":0,"count":1,"id":-405},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":0,"count":1,"id":-484},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":5,"count":1,"id":-212},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":1,"count":1,"id":-212},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":405},"input":{"damage":0,"count":1,"id":87},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":320},"input":{"damage":0,"count":1,"id":319},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":-409},"input":{"damage":0,"count":1,"id":-387},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":172},"input":{"damage":0,"count":1,"id":82},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":0,"count":1,"id":-545},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":3,"count":1,"id":17},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":371},"input":{"damage":0,"count":1,"id":314},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":-377},"input":{"damage":0,"count":1,"id":-234},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":366},"input":{"damage":0,"count":1,"id":365},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":371},"input":{"damage":0,"count":1,"id":286},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":336},"input":{"damage":0,"count":1,"id":337},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":452},"input":{"damage":0,"count":1,"id":258},"block":"furnace","type":3},{"output":{"damage":3,"count":1,"id":179},"input":{"damage":0,"count":1,"id":179},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":452},"input":{"damage":0,"count":1,"id":309},"block":"furnace","type":3},{"output":{"damage":4,"count":1,"id":351},"input":{"damage":0,"count":1,"id":21},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":412},"input":{"damage":0,"count":1,"id":411},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":0,"count":1,"id":-7},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":226},"input":{"damage":6,"count":1,"id":159},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":452},"input":{"damage":0,"count":1,"id":304},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":234},"input":{"damage":14,"count":1,"id":159},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":263},"input":{"damage":0,"count":1,"id":16},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":266},"input":{"damage":0,"count":1,"id":-402},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":2,"count":1,"id":17},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":-378},"input":{"damage":0,"count":1,"id":-379},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":388},"input":{"damage":0,"count":1,"id":-407},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":371},"input":{"damage":0,"count":1,"id":294},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":371},"input":{"damage":0,"count":1,"id":317},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":9,"count":1,"id":-212},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":220},"input":{"damage":0,"count":1,"id":159},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":-183},"input":{"damage":0,"count":1,"id":1},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":266},"input":{"damage":0,"count":1,"id":521},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":224},"input":{"damage":4,"count":1,"id":159},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":13,"count":1,"id":-212},"block":"furnace","type":3},{"output":{"damage":3,"count":1,"id":24},"input":{"damage":0,"count":1,"id":24},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":364},"input":{"damage":0,"count":1,"id":363},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":232},"input":{"damage":12,"count":1,"id":159},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":371},"input":{"damage":0,"count":1,"id":284},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":228},"input":{"damage":8,"count":1,"id":159},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":464},"input":{"damage":0,"count":1,"id":335},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":452},"input":{"damage":0,"count":1,"id":256},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":452},"input":{"damage":0,"count":1,"id":307},"block":"furnace","type":3},{"output":{"damage":2,"count":1,"id":98},"input":{"damage":0,"count":1,"id":98},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":0,"count":1,"id":-9},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":463},"input":{"damage":0,"count":1,"id":460},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":433},"input":{"damage":0,"count":1,"id":432},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":452},"input":{"damage":0,"count":1,"id":302},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":266},"input":{"damage":0,"count":1,"id":14},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":-280},"input":{"damage":0,"count":1,"id":-274},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":222},"input":{"damage":2,"count":1,"id":159},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":11,"count":1,"id":-212},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":19},"input":{"damage":1,"count":1,"id":19},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":0,"count":1,"id":162},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":452},"input":{"damage":0,"count":1,"id":292},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":223},"input":{"damage":3,"count":1,"id":159},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":1},"input":{"damage":0,"count":1,"id":4},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":10,"count":1,"id":-212},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":221},"input":{"damage":1,"count":1,"id":159},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":371},"input":{"damage":0,"count":1,"id":315},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":12,"count":1,"id":-212},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":-410},"input":{"damage":0,"count":1,"id":-391},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":452},"input":{"damage":0,"count":1,"id":417},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":388},"input":{"damage":0,"count":1,"id":129},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":0,"count":1,"id":-498},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":331},"input":{"damage":0,"count":1,"id":73},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":0,"count":1,"id":-6},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":452},"input":{"damage":0,"count":1,"id":305},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":0,"count":1,"id":17},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":265},"input":{"damage":0,"count":1,"id":-401},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":752},"input":{"damage":0,"count":1,"id":-271},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":0,"count":1,"id":-536},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":20},"input":{"damage":0,"count":1,"id":12},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":263},"input":{"damage":0,"count":1,"id":-406},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":0,"count":1,"id":-485},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":452},"input":{"damage":0,"count":1,"id":267},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":20},"input":{"damage":1,"count":1,"id":12},"block":"furnace","type":3},{"output":{"damage":2,"count":1,"id":351},"input":{"damage":0,"count":1,"id":81},"block":"furnace","type":3},{"output":{"damage":10,"count":1,"id":351},"input":{"damage":0,"count":1,"id":-156},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":0,"count":1,"id":-546},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":1,"count":1,"id":17},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":393},"input":{"damage":0,"count":1,"id":392},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":519},"input":{"damage":0,"count":1,"id":522},"block":"furnace","type":3},{"output":{"damage":3,"count":1,"id":155},"input":{"damage":0,"count":1,"id":155},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":371},"input":{"damage":0,"count":1,"id":285},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":225},"input":{"damage":5,"count":1,"id":159},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":227},"input":{"damage":7,"count":1,"id":159},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":0,"count":1,"id":-212},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":452},"input":{"damage":0,"count":1,"id":257},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":452},"input":{"damage":0,"count":1,"id":308},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":0,"count":1,"id":-8},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":8,"count":1,"id":-212},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":452},"input":{"damage":0,"count":1,"id":303},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":265},"input":{"damage":0,"count":1,"id":15},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":331},"input":{"damage":0,"count":1,"id":-403},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":350},"input":{"damage":0,"count":1,"id":349},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":519},"input":{"damage":0,"count":1,"id":-408},"block":"furnace","type":3},{"output":{"damage":1,"count":1,"id":263},"input":{"damage":1,"count":1,"id":162},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":229},"input":{"damage":9,"count":1,"id":159},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":-303},"input":{"damage":0,"count":1,"id":112},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":424},"input":{"damage":0,"count":1,"id":423},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":233},"input":{"damage":13,"count":1,"id":159},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":235},"input":{"damage":15,"count":1,"id":159},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":264},"input":{"damage":0,"count":1,"id":56},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":371},"input":{"damage":0,"count":1,"id":316},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":519},"input":{"damage":0,"count":1,"id":-311},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":371},"input":{"damage":0,"count":1,"id":418},"block":"furnace","type":3},{"output":{"damage":0,"count":1,"id":320},"input":{"damage":0,"count":1,"id":319},"block":"campfire","type":3},{"output":{"damage":0,"count":1,"id":364},"input":{"damage":0,"count":1,"id":363},"block":"campfire","type":3},{"output":{"damage":0,"count":1,"id":393},"input":{"damage":0,"count":1,"id":392},"block":"campfire","type":3},{"output":{"damage":0,"count":1,"id":350},"input":{"damage":0,"count":1,"id":349},"block":"campfire","type":3},{"output":{"damage":0,"count":1,"id":464},"input":{"damage":0,"count":1,"id":335},"block":"campfire","type":3},{"output":{"damage":0,"count":1,"id":366},"input":{"damage":0,"count":1,"id":365},"block":"campfire","type":3},{"output":{"damage":0,"count":1,"id":424},"input":{"damage":0,"count":1,"id":423},"block":"campfire","type":3},{"output":{"damage":0,"count":1,"id":463},"input":{"damage":0,"count":1,"id":460},"block":"campfire","type":3},{"output":{"damage":0,"count":1,"id":412},"input":{"damage":0,"count":1,"id":411},"block":"campfire","type":3}],"containerMixes":[{"inputId":438,"outputId":441,"reagentId":437},{"inputId":373,"outputId":438,"reagentId":289}],"potionMixes":[{"inputId":441,"outputId":441,"inputMeta":23,"outputMeta":24,"reagentMeta":0,"reagentId":348},{"inputId":438,"outputId":438,"inputMeta":17,"outputMeta":42,"reagentMeta":0,"reagentId":348},{"inputId":373,"outputId":373,"inputMeta":6,"outputMeta":8,"reagentMeta":0,"reagentId":376},{"inputId":438,"outputId":438,"inputMeta":1,"outputMeta":34,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":19,"outputMeta":20,"reagentMeta":0,"reagentId":331},{"inputId":373,"outputId":373,"inputMeta":5,"outputMeta":7,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":382},{"inputId":441,"outputId":441,"inputMeta":6,"outputMeta":8,"reagentMeta":0,"reagentId":376},{"inputId":438,"outputId":438,"inputMeta":33,"outputMeta":34,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":4,"outputMeta":25,"reagentMeta":0,"reagentId":375},{"inputId":441,"outputId":441,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":30},{"inputId":441,"outputId":441,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":414},{"inputId":438,"outputId":438,"inputMeta":32,"outputMeta":35,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":9,"outputMeta":17,"reagentMeta":0,"reagentId":376},{"inputId":373,"outputId":373,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":30},{"inputId":373,"outputId":373,"inputMeta":3,"outputMeta":34,"reagentMeta":0,"reagentId":376},{"inputId":373,"outputId":373,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":414},{"inputId":373,"outputId":373,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":382},{"inputId":441,"outputId":441,"inputMeta":21,"outputMeta":22,"reagentMeta":0,"reagentId":348},{"inputId":438,"outputId":438,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":375},{"inputId":373,"outputId":373,"inputMeta":4,"outputMeta":34,"reagentMeta":0,"reagentId":376},{"inputId":373,"outputId":373,"inputMeta":25,"outputMeta":27,"reagentMeta":0,"reagentId":348},{"inputId":373,"outputId":373,"inputMeta":21,"outputMeta":22,"reagentMeta":0,"reagentId":348},{"inputId":373,"outputId":373,"inputMeta":23,"outputMeta":24,"reagentMeta":0,"reagentId":348},{"inputId":438,"outputId":438,"inputMeta":4,"outputMeta":14,"reagentMeta":0,"reagentId":353},{"inputId":438,"outputId":438,"inputMeta":4,"outputMeta":31,"reagentMeta":0,"reagentId":377},{"inputId":438,"outputId":438,"inputMeta":4,"outputMeta":46,"reagentMeta":0,"reagentId":1},{"inputId":373,"outputId":373,"inputMeta":9,"outputMeta":17,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":25,"outputMeta":27,"reagentMeta":0,"reagentId":348},{"inputId":438,"outputId":438,"inputMeta":14,"outputMeta":15,"reagentMeta":0,"reagentId":331},{"inputId":438,"outputId":438,"inputMeta":12,"outputMeta":13,"reagentMeta":0,"reagentId":331},{"inputId":438,"outputId":438,"inputMeta":5,"outputMeta":7,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":3,"outputMeta":34,"reagentMeta":0,"reagentId":376},{"inputId":373,"outputId":373,"inputMeta":1,"outputMeta":34,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":4,"outputMeta":44,"reagentMeta":0,"reagentId":30},{"inputId":438,"outputId":438,"inputMeta":21,"outputMeta":22,"reagentMeta":0,"reagentId":348},{"inputId":441,"outputId":441,"inputMeta":4,"outputMeta":40,"reagentMeta":0,"reagentId":470},{"inputId":441,"outputId":441,"inputMeta":4,"outputMeta":19,"reagentMeta":0,"reagentId":462},{"inputId":438,"outputId":438,"inputMeta":31,"outputMeta":34,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":4,"outputMeta":9,"reagentMeta":0,"reagentId":414},{"inputId":441,"outputId":441,"inputMeta":4,"outputMeta":21,"reagentMeta":0,"reagentId":382},{"inputId":441,"outputId":441,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":375},{"inputId":441,"outputId":441,"inputMeta":14,"outputMeta":15,"reagentMeta":0,"reagentId":331},{"inputId":373,"outputId":373,"inputMeta":12,"outputMeta":13,"reagentMeta":0,"reagentId":331},{"inputId":441,"outputId":441,"inputMeta":5,"outputMeta":7,"reagentMeta":0,"reagentId":376},{"inputId":438,"outputId":438,"inputMeta":3,"outputMeta":34,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":1,"outputMeta":34,"reagentMeta":0,"reagentId":376},{"inputId":373,"outputId":373,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":375},{"inputId":438,"outputId":438,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":382},{"inputId":438,"outputId":438,"inputMeta":23,"outputMeta":24,"reagentMeta":0,"reagentId":348},{"inputId":438,"outputId":438,"inputMeta":40,"outputMeta":41,"reagentMeta":0,"reagentId":331},{"inputId":438,"outputId":438,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":30},{"inputId":373,"outputId":373,"inputMeta":4,"outputMeta":25,"reagentMeta":0,"reagentId":375},{"inputId":438,"outputId":438,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":414},{"inputId":438,"outputId":438,"inputMeta":4,"outputMeta":28,"reagentMeta":0,"reagentId":370},{"inputId":438,"outputId":438,"inputMeta":4,"outputMeta":12,"reagentMeta":0,"reagentId":378},{"inputId":438,"outputId":438,"inputMeta":9,"outputMeta":17,"reagentMeta":0,"reagentId":376},{"inputId":373,"outputId":373,"inputMeta":14,"outputMeta":15,"reagentMeta":0,"reagentId":331},{"inputId":441,"outputId":441,"inputMeta":15,"outputMeta":18,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":12,"outputMeta":13,"reagentMeta":0,"reagentId":331},{"inputId":438,"outputId":438,"inputMeta":25,"outputMeta":23,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":4,"outputMeta":37,"reagentMeta":0,"reagentId":469},{"inputId":441,"outputId":441,"inputMeta":4,"outputMeta":45,"reagentMeta":0,"reagentId":165},{"inputId":441,"outputId":441,"inputMeta":0,"outputMeta":3,"reagentMeta":0,"reagentId":348},{"inputId":441,"outputId":441,"inputMeta":0,"outputMeta":4,"reagentMeta":0,"reagentId":372},{"inputId":441,"outputId":441,"inputMeta":14,"outputMeta":17,"reagentMeta":0,"reagentId":376},{"inputId":373,"outputId":373,"inputMeta":31,"outputMeta":34,"reagentMeta":0,"reagentId":376},{"inputId":438,"outputId":438,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":353},{"inputId":438,"outputId":438,"inputMeta":7,"outputMeta":8,"reagentMeta":0,"reagentId":331},{"inputId":373,"outputId":373,"inputMeta":28,"outputMeta":30,"reagentMeta":0,"reagentId":348},{"inputId":438,"outputId":438,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":1},{"inputId":373,"outputId":373,"inputMeta":4,"outputMeta":44,"reagentMeta":0,"reagentId":30},{"inputId":373,"outputId":373,"inputMeta":4,"outputMeta":40,"reagentMeta":0,"reagentId":470},{"inputId":373,"outputId":373,"inputMeta":0,"outputMeta":3,"reagentMeta":0,"reagentId":348},{"inputId":373,"outputId":373,"inputMeta":0,"outputMeta":4,"reagentMeta":0,"reagentId":372},{"inputId":438,"outputId":438,"inputMeta":19,"outputMeta":20,"reagentMeta":0,"reagentId":331},{"inputId":373,"outputId":373,"inputMeta":4,"outputMeta":19,"reagentMeta":0,"reagentId":462},{"inputId":373,"outputId":373,"inputMeta":4,"outputMeta":9,"reagentMeta":0,"reagentId":414},{"inputId":441,"outputId":441,"inputMeta":17,"outputMeta":42,"reagentMeta":0,"reagentId":348},{"inputId":373,"outputId":373,"inputMeta":4,"outputMeta":21,"reagentMeta":0,"reagentId":382},{"inputId":438,"outputId":438,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":377},{"inputId":373,"outputId":373,"inputMeta":17,"outputMeta":42,"reagentMeta":0,"reagentId":348},{"inputId":438,"outputId":438,"inputMeta":4,"outputMeta":25,"reagentMeta":0,"reagentId":375},{"inputId":441,"outputId":441,"inputMeta":31,"outputMeta":34,"reagentMeta":0,"reagentId":376},{"inputId":373,"outputId":373,"inputMeta":15,"outputMeta":18,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":28,"outputMeta":30,"reagentMeta":0,"reagentId":348},{"inputId":373,"outputId":373,"inputMeta":14,"outputMeta":17,"reagentMeta":0,"reagentId":376},{"inputId":373,"outputId":373,"inputMeta":10,"outputMeta":18,"reagentMeta":0,"reagentId":376},{"inputId":373,"outputId":373,"inputMeta":2,"outputMeta":35,"reagentMeta":0,"reagentId":376},{"inputId":373,"outputId":373,"inputMeta":27,"outputMeta":24,"reagentMeta":0,"reagentId":376},{"inputId":373,"outputId":373,"inputMeta":5,"outputMeta":6,"reagentMeta":0,"reagentId":331},{"inputId":441,"outputId":441,"inputMeta":4,"outputMeta":5,"reagentMeta":0,"reagentId":396},{"inputId":441,"outputId":441,"inputMeta":10,"outputMeta":18,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":165},{"inputId":441,"outputId":441,"inputMeta":2,"outputMeta":35,"reagentMeta":0,"reagentId":376},{"inputId":373,"outputId":373,"inputMeta":37,"outputMeta":38,"reagentMeta":0,"reagentId":331},{"inputId":441,"outputId":441,"inputMeta":9,"outputMeta":10,"reagentMeta":0,"reagentId":331},{"inputId":373,"outputId":373,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":165},{"inputId":373,"outputId":373,"inputMeta":4,"outputMeta":37,"reagentMeta":0,"reagentId":469},{"inputId":373,"outputId":373,"inputMeta":4,"outputMeta":45,"reagentMeta":0,"reagentId":165},{"inputId":441,"outputId":441,"inputMeta":17,"outputMeta":18,"reagentMeta":0,"reagentId":331},{"inputId":373,"outputId":373,"inputMeta":25,"outputMeta":26,"reagentMeta":0,"reagentId":331},{"inputId":438,"outputId":438,"inputMeta":0,"outputMeta":34,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":37,"outputMeta":38,"reagentMeta":0,"reagentId":331},{"inputId":373,"outputId":373,"inputMeta":17,"outputMeta":18,"reagentMeta":0,"reagentId":331},{"inputId":438,"outputId":438,"inputMeta":4,"outputMeta":34,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":25,"outputMeta":26,"reagentMeta":0,"reagentId":331},{"inputId":373,"outputId":373,"inputMeta":9,"outputMeta":10,"reagentMeta":0,"reagentId":331},{"inputId":438,"outputId":438,"inputMeta":14,"outputMeta":16,"reagentMeta":0,"reagentId":348},{"inputId":373,"outputId":373,"inputMeta":22,"outputMeta":24,"reagentMeta":0,"reagentId":376},{"inputId":438,"outputId":438,"inputMeta":31,"outputMeta":32,"reagentMeta":0,"reagentId":331},{"inputId":441,"outputId":441,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":370},{"inputId":441,"outputId":441,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":378},{"inputId":373,"outputId":373,"inputMeta":34,"outputMeta":35,"reagentMeta":0,"reagentId":331},{"inputId":373,"outputId":373,"inputMeta":37,"outputMeta":39,"reagentMeta":0,"reagentId":348},{"inputId":441,"outputId":441,"inputMeta":9,"outputMeta":11,"reagentMeta":0,"reagentId":348},{"inputId":438,"outputId":438,"inputMeta":28,"outputMeta":29,"reagentMeta":0,"reagentId":331},{"inputId":441,"outputId":441,"inputMeta":5,"outputMeta":6,"reagentMeta":0,"reagentId":331},{"inputId":441,"outputId":441,"inputMeta":22,"outputMeta":24,"reagentMeta":0,"reagentId":376},{"inputId":373,"outputId":373,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":370},{"inputId":373,"outputId":373,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":378},{"inputId":441,"outputId":441,"inputMeta":21,"outputMeta":23,"reagentMeta":0,"reagentId":376},{"inputId":373,"outputId":373,"inputMeta":4,"outputMeta":5,"reagentMeta":0,"reagentId":396},{"inputId":373,"outputId":373,"inputMeta":25,"outputMeta":23,"reagentMeta":0,"reagentId":376},{"inputId":438,"outputId":438,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":331},{"inputId":373,"outputId":373,"inputMeta":21,"outputMeta":23,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":37,"outputMeta":39,"reagentMeta":0,"reagentId":348},{"inputId":438,"outputId":438,"inputMeta":4,"outputMeta":37,"reagentMeta":0,"reagentId":469},{"inputId":438,"outputId":438,"inputMeta":4,"outputMeta":45,"reagentMeta":0,"reagentId":165},{"inputId":373,"outputId":373,"inputMeta":9,"outputMeta":11,"reagentMeta":0,"reagentId":348},{"inputId":441,"outputId":441,"inputMeta":25,"outputMeta":23,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":27,"outputMeta":24,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":26,"outputMeta":23,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":40,"outputMeta":41,"reagentMeta":0,"reagentId":331},{"inputId":438,"outputId":438,"inputMeta":34,"outputMeta":35,"reagentMeta":0,"reagentId":331},{"inputId":373,"outputId":373,"inputMeta":26,"outputMeta":23,"reagentMeta":0,"reagentId":376},{"inputId":438,"outputId":438,"inputMeta":21,"outputMeta":23,"reagentMeta":0,"reagentId":376},{"inputId":438,"outputId":438,"inputMeta":31,"outputMeta":33,"reagentMeta":0,"reagentId":348},{"inputId":441,"outputId":441,"inputMeta":4,"outputMeta":28,"reagentMeta":0,"reagentId":370},{"inputId":441,"outputId":441,"inputMeta":4,"outputMeta":12,"reagentMeta":0,"reagentId":378},{"inputId":441,"outputId":441,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":331},{"inputId":373,"outputId":373,"inputMeta":40,"outputMeta":41,"reagentMeta":0,"reagentId":331},{"inputId":438,"outputId":438,"inputMeta":37,"outputMeta":39,"reagentMeta":0,"reagentId":348},{"inputId":373,"outputId":373,"inputMeta":28,"outputMeta":29,"reagentMeta":0,"reagentId":331},{"inputId":441,"outputId":441,"inputMeta":34,"outputMeta":35,"reagentMeta":0,"reagentId":331},{"inputId":373,"outputId":373,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":331},{"inputId":438,"outputId":438,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":370},{"inputId":438,"outputId":438,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":378},{"inputId":438,"outputId":438,"inputMeta":4,"outputMeta":44,"reagentMeta":0,"reagentId":30},{"inputId":438,"outputId":438,"inputMeta":4,"outputMeta":40,"reagentMeta":0,"reagentId":470},{"inputId":438,"outputId":438,"inputMeta":4,"outputMeta":19,"reagentMeta":0,"reagentId":462},{"inputId":438,"outputId":438,"inputMeta":4,"outputMeta":9,"reagentMeta":0,"reagentId":414},{"inputId":438,"outputId":438,"inputMeta":4,"outputMeta":21,"reagentMeta":0,"reagentId":382},{"inputId":438,"outputId":438,"inputMeta":15,"outputMeta":18,"reagentMeta":0,"reagentId":376},{"inputId":438,"outputId":438,"inputMeta":9,"outputMeta":11,"reagentMeta":0,"reagentId":348},{"inputId":441,"outputId":441,"inputMeta":28,"outputMeta":29,"reagentMeta":0,"reagentId":331},{"inputId":441,"outputId":441,"inputMeta":32,"outputMeta":35,"reagentMeta":0,"reagentId":376},{"inputId":438,"outputId":438,"inputMeta":5,"outputMeta":6,"reagentMeta":0,"reagentId":331},{"inputId":438,"outputId":438,"inputMeta":26,"outputMeta":23,"reagentMeta":0,"reagentId":376},{"inputId":438,"outputId":438,"inputMeta":25,"outputMeta":27,"reagentMeta":0,"reagentId":348},{"inputId":441,"outputId":441,"inputMeta":4,"outputMeta":14,"reagentMeta":0,"reagentId":353},{"inputId":441,"outputId":441,"inputMeta":4,"outputMeta":31,"reagentMeta":0,"reagentId":377},{"inputId":441,"outputId":441,"inputMeta":4,"outputMeta":46,"reagentMeta":0,"reagentId":1},{"inputId":373,"outputId":373,"inputMeta":31,"outputMeta":33,"reagentMeta":0,"reagentId":348},{"inputId":441,"outputId":441,"inputMeta":0,"outputMeta":34,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":14,"outputMeta":16,"reagentMeta":0,"reagentId":348},{"inputId":438,"outputId":438,"inputMeta":27,"outputMeta":24,"reagentMeta":0,"reagentId":376},{"inputId":438,"outputId":438,"inputMeta":37,"outputMeta":38,"reagentMeta":0,"reagentId":331},{"inputId":373,"outputId":373,"inputMeta":32,"outputMeta":35,"reagentMeta":0,"reagentId":376},{"inputId":373,"outputId":373,"inputMeta":0,"outputMeta":34,"reagentMeta":0,"reagentId":376},{"inputId":438,"outputId":438,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":165},{"inputId":373,"outputId":373,"inputMeta":4,"outputMeta":28,"reagentMeta":0,"reagentId":370},{"inputId":373,"outputId":373,"inputMeta":4,"outputMeta":12,"reagentMeta":0,"reagentId":378},{"inputId":441,"outputId":441,"inputMeta":33,"outputMeta":34,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":31,"outputMeta":33,"reagentMeta":0,"reagentId":348},{"inputId":438,"outputId":438,"inputMeta":9,"outputMeta":10,"reagentMeta":0,"reagentId":331},{"inputId":373,"outputId":373,"inputMeta":14,"outputMeta":16,"reagentMeta":0,"reagentId":348},{"inputId":441,"outputId":441,"inputMeta":7,"outputMeta":8,"reagentMeta":0,"reagentId":331},{"inputId":438,"outputId":438,"inputMeta":17,"outputMeta":18,"reagentMeta":0,"reagentId":331},{"inputId":438,"outputId":438,"inputMeta":22,"outputMeta":24,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":353},{"inputId":441,"outputId":441,"inputMeta":4,"outputMeta":34,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":1},{"inputId":441,"outputId":441,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":377},{"inputId":438,"outputId":438,"inputMeta":25,"outputMeta":26,"reagentMeta":0,"reagentId":331},{"inputId":373,"outputId":373,"inputMeta":31,"outputMeta":32,"reagentMeta":0,"reagentId":331},{"inputId":373,"outputId":373,"inputMeta":33,"outputMeta":34,"reagentMeta":0,"reagentId":376},{"inputId":438,"outputId":438,"inputMeta":28,"outputMeta":30,"reagentMeta":0,"reagentId":348},{"inputId":373,"outputId":373,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":353},{"inputId":373,"outputId":373,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":1},{"inputId":373,"outputId":373,"inputMeta":0,"outputMeta":1,"reagentMeta":0,"reagentId":377},{"inputId":373,"outputId":373,"inputMeta":7,"outputMeta":8,"reagentMeta":0,"reagentId":331},{"inputId":373,"outputId":373,"inputMeta":4,"outputMeta":31,"reagentMeta":0,"reagentId":377},{"inputId":373,"outputId":373,"inputMeta":4,"outputMeta":46,"reagentMeta":0,"reagentId":1},{"inputId":373,"outputId":373,"inputMeta":4,"outputMeta":14,"reagentMeta":0,"reagentId":353},{"inputId":438,"outputId":438,"inputMeta":0,"outputMeta":3,"reagentMeta":0,"reagentId":348},{"inputId":438,"outputId":438,"inputMeta":0,"outputMeta":4,"reagentMeta":0,"reagentId":372},{"inputId":373,"outputId":373,"inputMeta":19,"outputMeta":20,"reagentMeta":0,"reagentId":331},{"inputId":438,"outputId":438,"inputMeta":2,"outputMeta":35,"reagentMeta":0,"reagentId":376},{"inputId":438,"outputId":438,"inputMeta":6,"outputMeta":8,"reagentMeta":0,"reagentId":376},{"inputId":438,"outputId":438,"inputMeta":4,"outputMeta":5,"reagentMeta":0,"reagentId":396},{"inputId":438,"outputId":438,"inputMeta":14,"outputMeta":17,"reagentMeta":0,"reagentId":376},{"inputId":441,"outputId":441,"inputMeta":31,"outputMeta":32,"reagentMeta":0,"reagentId":331},{"inputId":438,"outputId":438,"inputMeta":10,"outputMeta":18,"reagentMeta":0,"reagentId":376}]} \ No newline at end of file diff --git a/src/main/resources/report_template.md b/src/main/resources/report_template.md deleted file mode 100644 index e234b49344b..00000000000 --- a/src/main/resources/report_template.md +++ /dev/null @@ -1,41 +0,0 @@ -<!--- Please do not ask questions or create discussion in the bug tracker. Use cloudburstmc.org forum or Discord for that. --> -<!--- ONLY POST ISSUES WITH A CLEAN SERVER ON THE LATEST VERSION --> - -## Generated Bug Report - -<!--- DO NOT OPEN A ISSUE IF THIS IS A PLUGIN ERROR --> -PLUGIN ERROR: ${PLUGIN_ERROR} - -### Expected Behavior -<!--- What would you expect to happen --> - - -### Actual Behavior -<!--- What actually happened --> - - -### Steps to Reproduce -<!--- Reliable steps which someone can use to reproduce the issue. Please do not create issues for non reproducible bug! --> - - -### OS and Versions - -* Nukkit Version: ${NUKKIT_VERSION} -* Java Version: ${JAVA_VERSION} - -* Host Configuration: - -| Item | Value | -|:----:|:-----:| -| Host OS | ${HOSTOS} | -| Memory(RAM) | ${MEMORY} | -| Storage Size | ${STORAGE_SIZE} | -| Storage Type | ${STORAGE_TYPE} | -| CPU Type | ${CPU_TYPE} | -| CPU Core Count | ${AVAILABLE_CORE} | - -### Crashdump, Backtrace or Other Files - -``` -${STACKTRACE} -``` diff --git a/src/main/resources/runtime_block_states_729.dat b/src/main/resources/runtime_block_states_729.dat new file mode 100644 index 00000000000..b37e2702fb5 Binary files /dev/null and b/src/main/resources/runtime_block_states_729.dat differ diff --git a/src/main/resources/smithing.json b/src/main/resources/smithing.json new file mode 100644 index 00000000000..e315cc9092c --- /dev/null +++ b/src/main/resources/smithing.json @@ -0,0 +1 @@ +{"smithing":[{"id":"minecraft:netherite_axe","input":[{"id":"minecraft:diamond_axe"},{"id":"minecraft:netherite_ingot"}],"output":[{"id":"minecraft:netherite_axe"}]},{"id":"minecraft:netherite_boots","input":[{"id":"minecraft:diamond_boots"},{"id":"minecraft:netherite_ingot"}],"output":[{"id":"minecraft:netherite_boots"}]},{"id":"minecraft:netherite_chestplate","input":[{"id":"minecraft:diamond_chestplate"},{"id":"minecraft:netherite_ingot"}],"output":[{"id":"minecraft:netherite_chestplate"}]},{"id":"minecraft:netherite_helmet","input":[{"id":"minecraft:diamond_helmet"},{"id":"minecraft:netherite_ingot"}],"output":[{"id":"minecraft:netherite_helmet"}]},{"id":"minecraft:netherite_hoe","input":[{"id":"minecraft:diamond_hoe"},{"id":"minecraft:netherite_ingot"}],"output":[{"id":"minecraft:netherite_hoe"}]},{"id":"minecraft:netherite_leggings","input":[{"id":"minecraft:diamond_leggings"},{"id":"minecraft:netherite_ingot"}],"output":[{"id":"minecraft:netherite_leggings"}]},{"id":"minecraft:netherite_pickaxe","input":[{"id":"minecraft:diamond_pickaxe"},{"id":"minecraft:netherite_ingot"}],"output":[{"id":"minecraft:netherite_pickaxe"}]},{"id":"minecraft:netherite_shovel","input":[{"id":"minecraft:diamond_shovel"},{"id":"minecraft:netherite_ingot"}],"output":[{"id":"minecraft:netherite_shovel"}]},{"id":"minecraft:netherite_sword","input":[{"id":"minecraft:diamond_sword"},{"id":"minecraft:netherite_ingot"}],"output":[{"id":"minecraft:netherite_sword"}]}]} \ No newline at end of file diff --git a/src/test/java/cn/nukkit/test/ClientChainDataTest.java b/src/test/java/cn/nukkit/test/ClientChainDataTest.java deleted file mode 100644 index 15c351fddfd..00000000000 --- a/src/test/java/cn/nukkit/test/ClientChainDataTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package cn.nukkit.test; - -import cn.nukkit.utils.ClientChainData; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -import java.io.ByteArrayOutputStream; -import java.io.InputStream; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * An example to show how to use ClientChainData - * This is also a test for client chain data. - * - * By lmlstarqaq http://snake1999.com/ - * Creation time: 2017/6/7 15:07. - */ -@DisplayName("ClientChainData") -class ClientChainDataTest { - - @DisplayName("Getters") - @Test - void testGetter() throws Exception { - InputStream is = ClientChainDataTest.class.getResourceAsStream("chain.dat"); - ClientChainData data = ClientChainData.of(readStream(is)); - String got = String.format("userName=%s, clientUUID=%s, " + - "identityPublicKey=%s, clientId=%d, " + - "serverAddress=%s, deviceModel=%s, " + - "deviceOS=%d, gameVersion=%s, " + - "guiScale=%d, languageCode=%s, " + - "xuid=%s, currentInputMode=%d, " + - "defaultInputMode=%d, UIProfile=%d" - , - data.getUsername(), data.getClientUUID(), - data.getIdentityPublicKey(), data.getClientId(), - data.getServerAddress(), data.getDeviceModel(), - data.getDeviceOS(), data.getGameVersion(), - data.getGuiScale(), data.getLanguageCode(), - data.getXUID(), data.getCurrentInputMode(), - data.getDefaultInputMode(), data.getUIProfile() - ); - String expecting = "userName=lmlstarqaq, clientUUID=8323afe1-641e-3b61-9a92-d5d20b279065, " + - "identityPublicKey=MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE4lyvA1iVhV2u3pLQqJAjJnJZSlSjib8mM1uB5h5yqOBSvCHW+nZxDmkOAW6MS1GA7yGHitGmfS4jW/yUISUdWvLzEWJYOzphb3GNh5J1oLJRwESc5278i4MEDk1y21/q, " + - "clientId=-6315607246631494544, " + - "serverAddress=192.168.1.108:19132, deviceModel=iPhone6,2, " + - "deviceOS=2, gameVersion=1.1.0, " + - "guiScale=0, languageCode=zh_CN, " + - "xuid=null, currentInputMode=2, " + //TODO: get new test data up to date key and enable xbox auth testing again - "defaultInputMode=2, UIProfile=1"; - assertEquals(got, expecting); - } - - private static byte[] readStream(InputStream inStream) throws Exception { - ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); - byte[] buffer = new byte[65536]; - int len; - while ((len = inStream.read(buffer)) != -1) { - outSteam.write(buffer, 0, len); - } - outSteam.close(); - inStream.close(); - return outSteam.toByteArray(); - } -} diff --git a/src/test/java/cn/nukkit/test/VarIntTest.java b/src/test/java/cn/nukkit/test/VarIntTest.java index 8ed8083951d..c573d51e83f 100644 --- a/src/test/java/cn/nukkit/test/VarIntTest.java +++ b/src/test/java/cn/nukkit/test/VarIntTest.java @@ -118,5 +118,5 @@ private void sizeTest(TestConsumer<ByteArrayOutputStream> write, int size) throw write.accept(os); ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); assertEquals(size, is.available()); - }; + } } diff --git a/src/test/java/cn/nukkit/test/ZlibTest.java b/src/test/java/cn/nukkit/test/ZlibTest.java index fedde89f415..ba29f6b9c49 100644 --- a/src/test/java/cn/nukkit/test/ZlibTest.java +++ b/src/test/java/cn/nukkit/test/ZlibTest.java @@ -17,5 +17,4 @@ void testAll() throws Exception { byte[] out = Zlib.inflate(compressed); assertArrayEquals(in, out); } - } diff --git a/src/test/resources/cn/nukkit/test/chain.dat b/src/test/resources/cn/nukkit/test/chain.dat deleted file mode 100644 index 9c69e4f9094..00000000000 Binary files a/src/test/resources/cn/nukkit/test/chain.dat and /dev/null differ