diff --git a/catalog/export/catalog.json b/catalog/export/catalog.json index f4dc83bd..5007ad5b 100644 --- a/catalog/export/catalog.json +++ b/catalog/export/catalog.json @@ -31597,6 +31597,161 @@ } } }, + { + "id": "damageteleport", + "category": "misc_challenge", + "icon": { + "material": "SHULKER_SHELL" + }, + "name": { + "en": "Damage = Random Teleport", + "de": "Schaden = Zufälliger Teleport" + }, + "description": { + "en": [ + "You'll be teleported randomly when you take damage" + ], + "de": [ + "Du wirst zufällig teleportiert, wenn du Schaden erleidest" + ] + }, + "styled": { + "en": { + "name": [ + { + "text": "Damage = Random Teleport", + "color": "#FF5555" + } + ], + "description": [ + [ + { + "text": "You'll be teleported randomly" + } + ], + [ + { + "text": "when you take damage" + } + ] + ], + "tooltip": [ + [ + { + "text": "»", + "color": "#555555" + }, + { + "text": " " + }, + { + "text": "Damage = Random Teleport", + "color": "#FF5555" + } + ], + [ + { + "text": " " + } + ], + [ + { + "text": "You'll be teleported randomly", + "color": "#AAAAAA" + } + ], + [ + { + "text": "when you take damage", + "color": "#AAAAAA" + } + ] + ] + }, + "de": { + "name": [ + { + "text": "Schaden = Zufälliger Teleport", + "color": "#FF5555" + } + ], + "description": [ + [ + { + "text": "Du wirst " + }, + { + "text": "zufällig teleportiert", + "color": "#FF5555" + }, + { + "text": "," + } + ], + [ + { + "text": "wenn du " + }, + { + "text": "Schaden", + "color": "#FF5555" + }, + { + "text": " erleidest" + } + ] + ], + "tooltip": [ + [ + { + "text": "»", + "color": "#555555" + }, + { + "text": " " + }, + { + "text": "Schaden = Zufälliger Teleport", + "color": "#FF5555" + } + ], + [ + { + "text": " " + } + ], + [ + { + "text": "Du wirst ", + "color": "#AAAAAA" + }, + { + "text": "zufällig teleportiert", + "color": "#FF5555" + }, + { + "text": ",", + "color": "#AAAAAA" + } + ], + [ + { + "text": "wenn du ", + "color": "#AAAAAA" + }, + { + "text": "Schaden", + "color": "#FF5555" + }, + { + "text": " erleidest", + "color": "#AAAAAA" + } + ] + ] + } + } + }, { "id": "neverfullhearts", "category": "misc_challenge", @@ -38214,29 +38369,29 @@ } }, { - "id": "collectworkstations", + "id": "collectnetheritearmor", "category": "fastest_time", "icon": { - "material": "FLETCHING_TABLE" + "material": "NETHERITE_CHESTPLATE" }, "name": { - "en": "Collect Workstations", - "de": "Sammle Arbeitsblöcke" + "en": "Full Netherite Armor", + "de": "Volle Netheritrüstung" }, "description": { "en": [ - "The player that collects every villager workstation first wins" + "The player that collects every netherite armor piece first wins" ], "de": [ - "Der Spieler, der als erstes alle Villager Arbeitsblöcke hat, gewinnt" + "Der Spieler, der als erstes die ganze Netheritrüstung hat, gewinnt" ] }, "styled": { "en": { "name": [ { - "text": "Collect Workstations", - "color": "#FFAA00" + "text": "Full Netherite Armor", + "color": "#8F7C7C" } ], "description": [ @@ -38246,7 +38401,7 @@ }, { "text": "collects", - "color": "#FFAA00" + "color": "#8F7C7C" }, { "text": " every" @@ -38254,11 +38409,11 @@ ], [ { - "text": "villager workstation first " + "text": "netherite armor piece first " }, { "text": "wins", - "color": "#FFAA00" + "color": "#8F7C7C" } ] ], @@ -38272,8 +38427,8 @@ "text": " " }, { - "text": "Collect Workstations", - "color": "#FFAA00" + "text": "Full Netherite Armor", + "color": "#8F7C7C" } ], [ @@ -38288,7 +38443,7 @@ }, { "text": "collects", - "color": "#FFAA00" + "color": "#8F7C7C" }, { "text": " every", @@ -38297,12 +38452,12 @@ ], [ { - "text": "villager workstation first ", + "text": "netherite armor piece first ", "color": "#AAAAAA" }, { "text": "wins", - "color": "#FFAA00" + "color": "#8F7C7C" } ] ] @@ -38310,8 +38465,8 @@ "de": { "name": [ { - "text": "Sammle Arbeitsblöcke", - "color": "#FFAA00" + "text": "Volle Netheritrüstung", + "color": "#8F7C7C" } ], "description": [ @@ -38321,13 +38476,16 @@ }, { "text": "erstes", - "color": "#FFAA00" + "color": "#8F7C7C" + }, + { + "text": " die" } ], [ { - "text": "alle Villager Arbeitsblöcke", - "color": "#FFAA00" + "text": "ganze Netheritrüstung", + "color": "#8F7C7C" }, { "text": " hat, gewinnt" @@ -38344,8 +38502,8 @@ "text": " " }, { - "text": "Sammle Arbeitsblöcke", - "color": "#FFAA00" + "text": "Volle Netheritrüstung", + "color": "#8F7C7C" } ], [ @@ -38360,13 +38518,17 @@ }, { "text": "erstes", - "color": "#FFAA00" + "color": "#8F7C7C" + }, + { + "text": " die", + "color": "#AAAAAA" } ], [ { - "text": "alle Villager Arbeitsblöcke", - "color": "#FFAA00" + "text": "ganze Netheritrüstung", + "color": "#8F7C7C" }, { "text": " hat, gewinnt", @@ -38378,46 +38540,51 @@ } }, { - "id": "findelytra", + "id": "collectworkstations", "category": "fastest_time", "icon": { - "material": "ELYTRA" + "material": "FLETCHING_TABLE" }, "name": { - "en": "Find Elytra", - "de": "Elytra Finden" + "en": "Collect Workstations", + "de": "Sammle Arbeitsblöcke" }, "description": { "en": [ - "The player that finds an elytra wins" + "The player that collects every villager workstation first wins" ], "de": [ - "Der Spieler, der als erstes eine Elytra findet, gewinnt" + "Der Spieler, der als erstes alle Villager Arbeitsblöcke hat, gewinnt" ] }, "styled": { "en": { "name": [ { - "text": "Find Elytra", - "color": "#FFFFFF" + "text": "Collect Workstations", + "color": "#FFAA00" } ], "description": [ [ { - "text": "The " + "text": "The player that " }, { - "text": "player", - "color": "#FFFFFF" + "text": "collects", + "color": "#FFAA00" }, { - "text": " that finds an elytra " + "text": " every" + } + ], + [ + { + "text": "villager workstation first " }, { "text": "wins", - "color": "#FFFFFF" + "color": "#FFAA00" } ] ], @@ -38431,8 +38598,8 @@ "text": " " }, { - "text": "Find Elytra", - "color": "#FFFFFF" + "text": "Collect Workstations", + "color": "#FFAA00" } ], [ @@ -38442,20 +38609,26 @@ ], [ { - "text": "The ", + "text": "The player that ", "color": "#AAAAAA" }, { - "text": "player", - "color": "#FFFFFF" + "text": "collects", + "color": "#FFAA00" }, { - "text": " that finds an elytra ", + "text": " every", + "color": "#AAAAAA" + } + ], + [ + { + "text": "villager workstation first ", "color": "#AAAAAA" }, { "text": "wins", - "color": "#FFFFFF" + "color": "#FFAA00" } ] ] @@ -38463,8 +38636,8 @@ "de": { "name": [ { - "text": "Elytra Finden", - "color": "#FFFFFF" + "text": "Sammle Arbeitsblöcke", + "color": "#FFAA00" } ], "description": [ @@ -38474,19 +38647,16 @@ }, { "text": "erstes", - "color": "#FFFFFF" + "color": "#FFAA00" } ], [ { - "text": "eine " - }, - { - "text": "Elytra findet", - "color": "#FFFFFF" + "text": "alle Villager Arbeitsblöcke", + "color": "#FFAA00" }, { - "text": ", gewinnt" + "text": " hat, gewinnt" } ] ], @@ -38500,8 +38670,8 @@ "text": " " }, { - "text": "Elytra Finden", - "color": "#FFFFFF" + "text": "Sammle Arbeitsblöcke", + "color": "#FFAA00" } ], [ @@ -38516,17 +38686,857 @@ }, { "text": "erstes", - "color": "#FFFFFF" + "color": "#FFAA00" } ], [ { - "text": "eine ", - "color": "#AAAAAA" + "text": "alle Villager Arbeitsblöcke", + "color": "#FFAA00" }, { - "text": "Elytra findet", - "color": "#FFFFFF" + "text": " hat, gewinnt", + "color": "#AAAAAA" + } + ] + ] + } + } + }, + { + "id": "findelytra", + "category": "fastest_time", + "icon": { + "material": "ELYTRA" + }, + "name": { + "en": "Find Elytra", + "de": "Elytra Finden" + }, + "description": { + "en": [ + "The player that finds an elytra wins" + ], + "de": [ + "Der Spieler, der als erstes eine Elytra findet, gewinnt" + ] + }, + "styled": { + "en": { + "name": [ + { + "text": "Find Elytra", + "color": "#FFFFFF" + } + ], + "description": [ + [ + { + "text": "The " + }, + { + "text": "player", + "color": "#FFFFFF" + }, + { + "text": " that finds an elytra " + }, + { + "text": "wins", + "color": "#FFFFFF" + } + ] + ], + "tooltip": [ + [ + { + "text": "»", + "color": "#555555" + }, + { + "text": " " + }, + { + "text": "Find Elytra", + "color": "#FFFFFF" + } + ], + [ + { + "text": " " + } + ], + [ + { + "text": "The ", + "color": "#AAAAAA" + }, + { + "text": "player", + "color": "#FFFFFF" + }, + { + "text": " that finds an elytra ", + "color": "#AAAAAA" + }, + { + "text": "wins", + "color": "#FFFFFF" + } + ] + ] + }, + "de": { + "name": [ + { + "text": "Elytra Finden", + "color": "#FFFFFF" + } + ], + "description": [ + [ + { + "text": "Der Spieler, der als " + }, + { + "text": "erstes", + "color": "#FFFFFF" + } + ], + [ + { + "text": "eine " + }, + { + "text": "Elytra findet", + "color": "#FFFFFF" + }, + { + "text": ", gewinnt" + } + ] + ], + "tooltip": [ + [ + { + "text": "»", + "color": "#555555" + }, + { + "text": " " + }, + { + "text": "Elytra Finden", + "color": "#FFFFFF" + } + ], + [ + { + "text": " " + } + ], + [ + { + "text": "Der Spieler, der als ", + "color": "#AAAAAA" + }, + { + "text": "erstes", + "color": "#FFFFFF" + } + ], + [ + { + "text": "eine ", + "color": "#AAAAAA" + }, + { + "text": "Elytra findet", + "color": "#FFFFFF" + }, + { + "text": ", gewinnt", + "color": "#AAAAAA" + } + ] + ] + } + } + }, + { + "id": "findsnifferegg", + "category": "fastest_time", + "icon": { + "material": "SNIFFER_EGG" + }, + "name": { + "en": "Find Sniffer Egg", + "de": "Schnüffler-Ei Finden" + }, + "description": { + "en": [ + "The player that finds a sniffer egg first wins" + ], + "de": [ + "Der Spieler, der als erstes ein Schnüffler-Ei findet, gewinnt" + ] + }, + "styled": { + "en": { + "name": [ + { + "text": "Find Sniffer Egg", + "color": "#FF5555" + } + ], + "description": [ + [ + { + "text": "The " + }, + { + "text": "player", + "color": "#FF5555" + }, + { + "text": " that finds a" + } + ], + [ + { + "text": "sniffer egg first " + }, + { + "text": "wins", + "color": "#FF5555" + } + ] + ], + "tooltip": [ + [ + { + "text": "»", + "color": "#555555" + }, + { + "text": " " + }, + { + "text": "Find Sniffer Egg", + "color": "#FF5555" + } + ], + [ + { + "text": " " + } + ], + [ + { + "text": "The ", + "color": "#AAAAAA" + }, + { + "text": "player", + "color": "#FF5555" + }, + { + "text": " that finds a", + "color": "#AAAAAA" + } + ], + [ + { + "text": "sniffer egg first ", + "color": "#AAAAAA" + }, + { + "text": "wins", + "color": "#FF5555" + } + ] + ] + }, + "de": { + "name": [ + { + "text": "Schnüffler-Ei Finden", + "color": "#FF5555" + } + ], + "description": [ + [ + { + "text": "Der Spieler, der als " + }, + { + "text": "erstes", + "color": "#FF5555" + } + ], + [ + { + "text": "ein " + }, + { + "text": "Schnüffler-Ei findet", + "color": "#FF5555" + }, + { + "text": ", gewinnt" + } + ] + ], + "tooltip": [ + [ + { + "text": "»", + "color": "#555555" + }, + { + "text": " " + }, + { + "text": "Schnüffler-Ei Finden", + "color": "#FF5555" + } + ], + [ + { + "text": " " + } + ], + [ + { + "text": "Der Spieler, der als ", + "color": "#AAAAAA" + }, + { + "text": "erstes", + "color": "#FF5555" + } + ], + [ + { + "text": "ein ", + "color": "#AAAAAA" + }, + { + "text": "Schnüffler-Ei findet", + "color": "#FF5555" + }, + { + "text": ", gewinnt", + "color": "#AAAAAA" + } + ] + ] + } + } + }, + { + "id": "findtotem", + "category": "fastest_time", + "icon": { + "material": "TOTEM_OF_UNDYING" + }, + "name": { + "en": "Find Totem", + "de": "Totem Finden" + }, + "description": { + "en": [ + "The player that finds a totem of undying first wins" + ], + "de": [ + "Der Spieler, der als erstes ein Totem findet, gewinnt" + ] + }, + "styled": { + "en": { + "name": [ + { + "text": "Find Totem", + "color": "#FFAA00" + } + ], + "description": [ + [ + { + "text": "The " + }, + { + "text": "player", + "color": "#FFAA00" + }, + { + "text": " that finds a totem" + } + ], + [ + { + "text": "of undying first " + }, + { + "text": "wins", + "color": "#FFAA00" + } + ] + ], + "tooltip": [ + [ + { + "text": "»", + "color": "#555555" + }, + { + "text": " " + }, + { + "text": "Find Totem", + "color": "#FFAA00" + } + ], + [ + { + "text": " " + } + ], + [ + { + "text": "The ", + "color": "#AAAAAA" + }, + { + "text": "player", + "color": "#FFAA00" + }, + { + "text": " that finds a totem", + "color": "#AAAAAA" + } + ], + [ + { + "text": "of undying first ", + "color": "#AAAAAA" + }, + { + "text": "wins", + "color": "#FFAA00" + } + ] + ] + }, + "de": { + "name": [ + { + "text": "Totem Finden", + "color": "#FFAA00" + } + ], + "description": [ + [ + { + "text": "Der Spieler, der als " + }, + { + "text": "erstes", + "color": "#FFAA00" + } + ], + [ + { + "text": "ein " + }, + { + "text": "Totem findet", + "color": "#FFAA00" + }, + { + "text": ", gewinnt" + } + ] + ], + "tooltip": [ + [ + { + "text": "»", + "color": "#555555" + }, + { + "text": " " + }, + { + "text": "Totem Finden", + "color": "#FFAA00" + } + ], + [ + { + "text": " " + } + ], + [ + { + "text": "Der Spieler, der als ", + "color": "#AAAAAA" + }, + { + "text": "erstes", + "color": "#FFAA00" + } + ], + [ + { + "text": "ein ", + "color": "#AAAAAA" + }, + { + "text": "Totem findet", + "color": "#FFAA00" + }, + { + "text": ", gewinnt", + "color": "#AAAAAA" + } + ] + ] + } + } + }, + { + "id": "findenchantedgoldenapple", + "category": "fastest_time", + "icon": { + "material": "ENCHANTED_GOLDEN_APPLE" + }, + "name": { + "en": "Find Enchanted Apple", + "de": "Verzauberten Apfel Finden" + }, + "description": { + "en": [ + "The player that finds an enchanted golden apple first wins" + ], + "de": [ + "Der Spieler, der als erstes einen verzauberten Apfel findet, gewinnt" + ] + }, + "styled": { + "en": { + "name": [ + { + "text": "Find Enchanted Apple", + "color": "#FF55FF" + } + ], + "description": [ + [ + { + "text": "The " + }, + { + "text": "player", + "color": "#FF55FF" + }, + { + "text": " that finds an" + } + ], + [ + { + "text": "enchanted golden apple first " + }, + { + "text": "wins", + "color": "#FF55FF" + } + ] + ], + "tooltip": [ + [ + { + "text": "»", + "color": "#555555" + }, + { + "text": " " + }, + { + "text": "Find Enchanted Apple", + "color": "#FF55FF" + } + ], + [ + { + "text": " " + } + ], + [ + { + "text": "The ", + "color": "#AAAAAA" + }, + { + "text": "player", + "color": "#FF55FF" + }, + { + "text": " that finds an", + "color": "#AAAAAA" + } + ], + [ + { + "text": "enchanted golden apple first ", + "color": "#AAAAAA" + }, + { + "text": "wins", + "color": "#FF55FF" + } + ] + ] + }, + "de": { + "name": [ + { + "text": "Verzauberten Apfel Finden", + "color": "#FF55FF" + } + ], + "description": [ + [ + { + "text": "Der Spieler, der als " + }, + { + "text": "erstes", + "color": "#FF55FF" + }, + { + "text": " einen" + } + ], + [ + { + "text": "verzauberten Apfel findet", + "color": "#FF55FF" + }, + { + "text": ", gewinnt" + } + ] + ], + "tooltip": [ + [ + { + "text": "»", + "color": "#555555" + }, + { + "text": " " + }, + { + "text": "Verzauberten Apfel Finden", + "color": "#FF55FF" + } + ], + [ + { + "text": " " + } + ], + [ + { + "text": "Der Spieler, der als ", + "color": "#AAAAAA" + }, + { + "text": "erstes", + "color": "#FF55FF" + }, + { + "text": " einen", + "color": "#AAAAAA" + } + ], + [ + { + "text": "verzauberten Apfel findet", + "color": "#FF55FF" + }, + { + "text": ", gewinnt", + "color": "#AAAAAA" + } + ] + ] + } + } + }, + { + "id": "findheartofthesea", + "category": "fastest_time", + "icon": { + "material": "HEART_OF_THE_SEA" + }, + "name": { + "en": "Find Heart of the Sea", + "de": "Herz des Meeres Finden" + }, + "description": { + "en": [ + "The player that finds a heart of the sea first wins" + ], + "de": [ + "Der Spieler, der als erstes ein Herz des Meeres findet, gewinnt" + ] + }, + "styled": { + "en": { + "name": [ + { + "text": "Find Heart of the Sea", + "color": "#00AAAA" + } + ], + "description": [ + [ + { + "text": "The " + }, + { + "text": "player", + "color": "#00AAAA" + }, + { + "text": " that finds a" + } + ], + [ + { + "text": "heart of the sea first " + }, + { + "text": "wins", + "color": "#00AAAA" + } + ] + ], + "tooltip": [ + [ + { + "text": "»", + "color": "#555555" + }, + { + "text": " " + }, + { + "text": "Find Heart of the Sea", + "color": "#00AAAA" + } + ], + [ + { + "text": " " + } + ], + [ + { + "text": "The ", + "color": "#AAAAAA" + }, + { + "text": "player", + "color": "#00AAAA" + }, + { + "text": " that finds a", + "color": "#AAAAAA" + } + ], + [ + { + "text": "heart of the sea first ", + "color": "#AAAAAA" + }, + { + "text": "wins", + "color": "#00AAAA" + } + ] + ] + }, + "de": { + "name": [ + { + "text": "Herz des Meeres Finden", + "color": "#00AAAA" + } + ], + "description": [ + [ + { + "text": "Der Spieler, der als " + }, + { + "text": "erstes", + "color": "#00AAAA" + } + ], + [ + { + "text": "ein " + }, + { + "text": "Herz des Meeres findet", + "color": "#00AAAA" + }, + { + "text": ", gewinnt" + } + ] + ], + "tooltip": [ + [ + { + "text": "»", + "color": "#555555" + }, + { + "text": " " + }, + { + "text": "Herz des Meeres Finden", + "color": "#00AAAA" + } + ], + [ + { + "text": " " + } + ], + [ + { + "text": "Der Spieler, der als ", + "color": "#AAAAAA" + }, + { + "text": "erstes", + "color": "#00AAAA" + } + ], + [ + { + "text": "ein ", + "color": "#AAAAAA" + }, + { + "text": "Herz des Meeres findet", + "color": "#00AAAA" }, { "text": ", gewinnt", diff --git a/catalog/src/main/resources/challenges-catalog/challenges.json b/catalog/src/main/resources/challenges-catalog/challenges.json index 08922ffd..f311d649 100644 --- a/catalog/src/main/resources/challenges-catalog/challenges.json +++ b/catalog/src/main/resources/challenges-catalog/challenges.json @@ -1516,8 +1516,7 @@ "category": "misc_challenge", "icon": "SHULKER_SHELL", "class": "challenge.DamageTeleportChallenge", - "since": "2.0.2", - "registered": false + "since": "2.0.2" }, { "id": "zerohearts", @@ -1724,6 +1723,14 @@ "class": "goal.CollectSwordsGoal", "since": "2.1.2" }, + { + "id": "collectnetheritearmor", + "key": "collect-netherite-armor", + "category": "fastest_time", + "icon": "NETHERITE_CHESTPLATE", + "class": "goal.CollectNetheriteArmorGoal", + "since": "3.1" + }, { "id": "collectworkstations", "key": "collect-workstations", @@ -1740,6 +1747,38 @@ "class": "goal.FindElytraGoal", "since": "2.1.1" }, + { + "id": "findsnifferegg", + "key": "find-sniffer-egg", + "category": "fastest_time", + "icon": "SNIFFER_EGG", + "class": "goal.FindSnifferEggGoal", + "since": "3.1" + }, + { + "id": "findtotem", + "key": "find-totem", + "category": "fastest_time", + "icon": "TOTEM_OF_UNDYING", + "class": "goal.FindTotemGoal", + "since": "3.1" + }, + { + "id": "findenchantedgoldenapple", + "key": "find-enchanted-golden-apple", + "category": "fastest_time", + "icon": "ENCHANTED_GOLDEN_APPLE", + "class": "goal.FindEnchantedGoldenAppleGoal", + "since": "3.1" + }, + { + "id": "findheartofthesea", + "key": "find-heart-of-the-sea", + "category": "fastest_time", + "icon": "HEART_OF_THE_SEA", + "class": "goal.FindHeartOfTheSeaGoal", + "since": "3.1" + }, { "id": "eatcake", "key": "eat-cake", diff --git a/catalog/src/test/java/net/cyperia/challenges/catalog/ChallengeCatalogTest.java b/catalog/src/test/java/net/cyperia/challenges/catalog/ChallengeCatalogTest.java index 0930067d..4ddcec21 100644 --- a/catalog/src/test/java/net/cyperia/challenges/catalog/ChallengeCatalogTest.java +++ b/catalog/src/test/java/net/cyperia/challenges/catalog/ChallengeCatalogTest.java @@ -41,7 +41,7 @@ void readsAChallengeWithItsClassAndRelease() { @Test void anEntryIsRegisteredUnlessItSaysOtherwise() { assertTrue(bundled.challenge("cutclean").orElseThrow().registered()); - assertFalse(bundled.challenge("damageteleport").orElseThrow().registered()); + assertFalse(bundled.challenge("zerohearts").orElseThrow().registered()); } // Enabling one moves every player to the spawn of a new world, so a random pick would reset the run diff --git a/language/locales/de.json b/language/locales/de.json index 18a3d95b..1b24b6df 100644 --- a/language/locales/de.json +++ b/language/locales/de.json @@ -303,6 +303,11 @@ "found": "Gefundene" }, "switch-filter": "{0} anzeigen" + }, + "category": { + "progress": "Gefunden: {0} / {1}", + "show": "Nur diese anzeigen", + "show-all": "Alles anzeigen" } }, "challenges": { @@ -2349,6 +2354,34 @@ "eine *Elytra findet*, gewinnt" ] }, + "find-sniffer-egg": { + "name": "*Schnüffler-Ei Finden*", + "desc": [ + "Der Spieler, der als *erstes*", + "ein *Schnüffler-Ei findet*, gewinnt" + ] + }, + "find-totem": { + "name": "*Totem Finden*", + "desc": [ + "Der Spieler, der als *erstes*", + "ein *Totem findet*, gewinnt" + ] + }, + "find-enchanted-golden-apple": { + "name": "*Verzauberten Apfel Finden*", + "desc": [ + "Der Spieler, der als *erstes* einen", + "*verzauberten Apfel findet*, gewinnt" + ] + }, + "find-heart-of-the-sea": { + "name": "*Herz des Meeres Finden*", + "desc": [ + "Der Spieler, der als *erstes*", + "ein *Herz des Meeres findet*, gewinnt" + ] + }, "eat-cake": { "name": "*Kuchen Essen*", "desc": [ @@ -2370,6 +2403,13 @@ "*alle Eisblöcke* und Schnee hat, gewinnt" ] }, + "collect-netherite-armor": { + "name": "*Volle Netheritrüstung*", + "desc": [ + "Der Spieler, der als *erstes* die", + "*ganze Netheritrüstung* hat, gewinnt" + ] + }, "collect-swords": { "name": "*Sammle Schwerter*", "desc": [ @@ -2600,10 +2640,12 @@ "menu": "Alles sammeln", "bossbar-next": "{@bossbar.format-arg('{@name}', '{0} {@symbol.vertical} {1} / {2}')}", "category": { - "items": "Items", - "mobs": "Mobs", - "advancements": "Fortschritte" - } + "items": "*Items*", + "mobs": "*Mobs*", + "advancements": "*Fortschritte*", + "overall": "*Gesamt*" + }, + "ranking": "Am meisten gefunden: {0}" }, "damage-teleport": { "name": "*Schaden = Zufälliger Teleport*", @@ -3822,6 +3864,20 @@ "thunder": "Wetter zu stürmisch geändert", "description": "Ändert das Wetter." }, + "worldborder": { + "set": "Die Weltgrenze ist jetzt {0} Blöcke breit", + "set-over": "Die Weltgrenze ist in {1} Sekunden {0} Blöcke breit", + "center": "Die Weltgrenze liegt jetzt um {0}, {1}", + "get": "Die Weltgrenze ist {0} Blöcke breit und liegt um {1}, {2}", + "damage-buffer": "Spieler außerhalb der Weltgrenze bekommen nach {0} Blöcken Schaden", + "damage-amount": "Spieler außerhalb der Weltgrenze bekommen {0} Schaden pro Block", + "mode": { + "damage": "Die Weltgrenze verletzt jetzt Spieler außerhalb", + "push": "Die Weltgrenze setzt Spieler außerhalb jetzt zurück nach innen" + }, + "reset": "Die Weltgrenze ist wieder normal", + "description": "Setzt, verschiebt oder zeigt die Weltgrenze der Challenge." + }, "invsee": { "open": "Inventar von {0} geöffnet", "description": "Öffnet das Inventar eines anderen Spielers." @@ -4097,7 +4153,7 @@ "translatable": { "damage-cause": { "kill": "Kill", - "world_border": "Weltbarriere", + "world_border": "Weltgrenze", "contact": "Kontakt", "entity_attack": "Angriff", "entity_sweep_attack": "Schwungangriff", diff --git a/language/locales/en.json b/language/locales/en.json index 5fa6c1eb..ad1ce683 100644 --- a/language/locales/en.json +++ b/language/locales/en.json @@ -303,6 +303,11 @@ "found": "found" }, "switch-filter": "Show {0}" + }, + "category": { + "progress": "Found: {0} / {1}", + "show": "Show only these", + "show-all": "Show everything" } }, "challenges": { @@ -2331,6 +2336,34 @@ "The *player* that finds an elytra *wins*" ] }, + "find-sniffer-egg": { + "name": "*Find Sniffer Egg*", + "desc": [ + "The *player* that finds a", + "sniffer egg first *wins*" + ] + }, + "find-totem": { + "name": "*Find Totem*", + "desc": [ + "The *player* that finds a totem", + "of undying first *wins*" + ] + }, + "find-enchanted-golden-apple": { + "name": "*Find Enchanted Apple*", + "desc": [ + "The *player* that finds an", + "enchanted golden apple first *wins*" + ] + }, + "find-heart-of-the-sea": { + "name": "*Find Heart of the Sea*", + "desc": [ + "The *player* that finds a", + "heart of the sea first *wins*" + ] + }, "eat-cake": { "name": "*Eat Cake*", "desc": [ @@ -2351,6 +2384,13 @@ "ice blocks and snow first *wins*" ] }, + "collect-netherite-armor": { + "name": "*Full Netherite Armor*", + "desc": [ + "The player that *collects* every", + "netherite armor piece first *wins*" + ] + }, "collect-swords": { "name": "*Collect Swords*", "desc": [ @@ -2581,10 +2621,12 @@ "menu": "Collect Everything", "bossbar-next": "{@bossbar.format-arg('{@name}', '{0} {@symbol.vertical} {1} / {2}')}", "category": { - "items": "Items", - "mobs": "Mobs", - "advancements": "Advancements" - } + "items": "*Items*", + "mobs": "*Mobs*", + "advancements": "*Advancements*", + "overall": "*Overall*" + }, + "ranking": "Most found: {0}" }, "damage-teleport": { "name": "*Damage = Random Teleport*", @@ -3802,6 +3844,20 @@ "thunder": "Weather was changed to thundery", "description": "Changes the weather." }, + "worldborder": { + "set": "The world border is now {0} blocks wide", + "set-over": "The world border will be {0} blocks wide in {1} seconds", + "center": "The world border is now centered on {0}, {1}", + "get": "The world border is {0} blocks wide around {1}, {2}", + "damage-buffer": "Players outside the world border take damage after {0} blocks", + "damage-amount": "Players outside the world border take {0} damage per block", + "mode": { + "damage": "The world border now damages players outside it", + "push": "The world border now puts players outside it back inside" + }, + "reset": "The world border is back to vanilla", + "description": "Sets, moves or shows the world border of the challenge." + }, "invsee": { "open": "Inventory of {0} opened", "description": "Opens another player's inventory." diff --git a/language/locales/global.json b/language/locales/global.json index a02a3e5d..576d067f 100644 --- a/language/locales/global.json +++ b/language/locales/global.json @@ -1005,6 +1005,18 @@ "find-elytra": { "*colorize*": "{0}" }, + "find-sniffer-egg": { + "*colorize*": "{0}" + }, + "find-totem": { + "*colorize*": "{0}" + }, + "find-enchanted-golden-apple": { + "*colorize*": "{0}" + }, + "find-heart-of-the-sea": { + "*colorize*": "{0}" + }, "eat-cake": { "*colorize*": "{0}" }, @@ -1014,6 +1026,9 @@ "collect-ice": { "*colorize*": "{0}" }, + "collect-netherite-armor": { + "*colorize*": "{0}" + }, "collect-swords": { "*colorize*": "{0}" }, @@ -1080,7 +1095,13 @@ "*colorize*": "{0}" }, "collect-everything": { - "*colorize*": "{0}" + "*colorize*": "{0}", + "category": { + "items.*colorize*": "{0}", + "mobs.*colorize*": "{0}", + "advancements.*colorize*": "{0}", + "overall.*colorize*": "{0}" + } }, "damage-teleport": { "*colorize*": "{0}" diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/Challenges.java b/plugin/src/main/java/net/cyperia/challenges/plugin/Challenges.java index ca8d0abf..9e59d2be 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/Challenges.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/Challenges.java @@ -216,6 +216,7 @@ private void registerCommands() { TimeCommand.shortcut("night"), TimeCommand.shortcut("noon"), TimeCommand.shortcut("midnight"), + new WorldborderCommand(), new ResultCommand(), new SkipTimerCommand(), new CancelChatInputCommand(), diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/CustomChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/CustomChallenge.java index a476897c..b6428341 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/CustomChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/CustomChallenge.java @@ -155,6 +155,13 @@ public String getUniqueName() { return uuid.toString(); } + // Custom challenges are not in the catalog and were never renamed + @NotNull + @Override + public List getFallbackNames() { + return List.of(); + } + @NotNull public static Component formatChallengeName(@NotNull String rawName) { try { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java index 5f6557b6..ad5e521a 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java @@ -10,13 +10,21 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.player.PlayerQuitEvent; import org.jetbrains.annotations.NotNull; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom; public class DamageTeleportChallenge extends SettingModifier { private static final int PLAYER = 1, EVERYONE = 2; + // A world without a border is 60 million blocks wide, which would put the target out of reach. + private static final double MAX_RADIUS = 2000; + + private final Set teleportPending = ConcurrentHashMap.newKeySet(); public DamageTeleportChallenge() { super(1, 2); @@ -32,25 +40,34 @@ public void onDamage(@NotNull EntityDamageEvent event) { handleDamage(((Player) event.getEntity())); } - private void handleDamage(@NotNull Player player) { + @EventHandler + public void onQuit(@NotNull PlayerQuitEvent event) { + teleportPending.remove(event.getPlayer().getUniqueId()); + } + + void handleDamage(@NotNull Player player) { + // damage over time would otherwise queue teleports that land in a burst + if (!teleportPending.add(player.getUniqueId())) return; + World world = player.getWorld(); Location random = getRandomLocation(world); - world.getChunkAtAsync(random).thenAccept(chunk -> Regions.at(Challenges.getInstance(), random, () -> { + Challenges.getInstance().getWorldManager().loadChunkAfterPrefetch(random, chunk -> { + if (!shouldExecuteEffect() || !player.isValid() || player.isDead()) return; + Location location = world.getHighestBlockAt(random).getLocation(); location.setY(location.getY() + 1); if (getValue() == PLAYER) { Regions.entity(Challenges.getInstance(), player, () -> player.teleportAsync(location)); } else { - broadcastFiltered(player1 -> player1.teleportAsync(location)); + broadcastFiltered(target -> Regions.entity(Challenges.getInstance(), target, () -> target.teleportAsync(location))); } - })); + }).whenComplete((result, ex) -> teleportPending.remove(player.getUniqueId())); } public Location getRandomLocation(World world) { - double size = Challenges.getInstance().getBorderManager().getSize(world) / 2; - size--; + double size = Math.min(Challenges.getInstance().getBorderManager().getSize(world) / 2 - 1, MAX_RADIUS); final double randomX = ThreadLocalRandom.current().nextDouble(-size, size); final double randomY = ThreadLocalRandom.current().nextDouble(-size, size); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/CollectNetheriteArmorGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/CollectNetheriteArmorGoal.java new file mode 100644 index 00000000..26809d7f --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/CollectNetheriteArmorGoal.java @@ -0,0 +1,12 @@ +package net.cyperia.challenges.plugin.challenges.implementation.goal; + +import net.cyperia.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; +import org.bukkit.Material; + +public class CollectNetheriteArmorGoal extends ItemCollectionGoal { + + public CollectNetheriteArmorGoal() { + super(Material.NETHERITE_HELMET, Material.NETHERITE_CHESTPLATE, Material.NETHERITE_LEGGINGS, Material.NETHERITE_BOOTS); + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/FindEnchantedGoldenAppleGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/FindEnchantedGoldenAppleGoal.java new file mode 100644 index 00000000..2ec92605 --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/FindEnchantedGoldenAppleGoal.java @@ -0,0 +1,12 @@ +package net.cyperia.challenges.plugin.challenges.implementation.goal; + +import net.cyperia.challenges.plugin.challenges.type.abstraction.FindItemGoal; +import org.bukkit.Material; + +public class FindEnchantedGoldenAppleGoal extends FindItemGoal { + + public FindEnchantedGoldenAppleGoal() { + super(Material.ENCHANTED_GOLDEN_APPLE); + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/FindHeartOfTheSeaGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/FindHeartOfTheSeaGoal.java new file mode 100644 index 00000000..e6273c1c --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/FindHeartOfTheSeaGoal.java @@ -0,0 +1,12 @@ +package net.cyperia.challenges.plugin.challenges.implementation.goal; + +import net.cyperia.challenges.plugin.challenges.type.abstraction.FindItemGoal; +import org.bukkit.Material; + +public class FindHeartOfTheSeaGoal extends FindItemGoal { + + public FindHeartOfTheSeaGoal() { + super(Material.HEART_OF_THE_SEA); + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/FindSnifferEggGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/FindSnifferEggGoal.java new file mode 100644 index 00000000..10b4be8c --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/FindSnifferEggGoal.java @@ -0,0 +1,12 @@ +package net.cyperia.challenges.plugin.challenges.implementation.goal; + +import net.cyperia.challenges.plugin.challenges.type.abstraction.FindItemGoal; +import org.bukkit.Material; + +public class FindSnifferEggGoal extends FindItemGoal { + + public FindSnifferEggGoal() { + super(Material.SNIFFER_EGG); + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/FindTotemGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/FindTotemGoal.java new file mode 100644 index 00000000..faefe1a7 --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/FindTotemGoal.java @@ -0,0 +1,12 @@ +package net.cyperia.challenges.plugin.challenges.implementation.goal; + +import net.cyperia.challenges.plugin.challenges.type.abstraction.FindItemGoal; +import org.bukkit.Material; + +public class FindTotemGoal extends FindItemGoal { + + public FindTotemGoal() { + super(Material.TOTEM_OF_UNDYING); + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java index 4d1d5638..87ef5a84 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java @@ -1,6 +1,7 @@ package net.cyperia.challenges.plugin.challenges.implementation.setting; import net.cyperia.challenges.plugin.ChallengeAPI; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.abstraction.Setting; import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.challenges.plugin.content.i18n.Prefix; @@ -55,8 +56,8 @@ private void teleportUp(@NotNull Player player) { World overworld = ChallengeAPI.getGameWorld(Environment.NORMAL); target.setWorld(overworld); target.multiply(8); - overworld.getChunkAtAsync(target).thenAccept(chunk -> Regions.at(plugin, target, () -> - teleport(player, overworld.getHighestBlockAt(target).getLocation().add(0.5, 1, 0.5)))); + Challenges.getInstance().getWorldManager().loadChunkAfterPrefetch(target, chunk -> + teleport(player, overworld.getHighestBlockAt(target).getLocation().add(0.5, 1, 0.5))); } else { Location location = player.getBedSpawnLocation(); if (location == null) location = BlockUtils.getCenteredSpawn(ChallengeAPI.getGameWorld(Environment.NORMAL)); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/ChecklistGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/ChecklistGoal.java index 16870ee3..f0af743c 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/ChecklistGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/ChecklistGoal.java @@ -1,5 +1,6 @@ package net.cyperia.challenges.plugin.challenges.type; +import net.cyperia.challenges.plugin.content.i18n.LocalizableMessage; import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.commons.bukkit.utils.item.ItemUtils; import org.bukkit.entity.Player; @@ -16,6 +17,12 @@ public interface ChecklistGoal extends IGoal { @NotNull List getChecklist(@NotNull Player viewer); + // Parts of the checklist the menu can show on their own, empty for a goal with one kind of entry + @NotNull + default List getChecklistCategories(@NotNull Player viewer) { + return List.of(); + } + // {0} is the names of the players who got an entry, like "Killed by {0}" @NotNull MessageKey getFinderMessage(); @@ -42,4 +49,12 @@ public static ChecklistEntry of(@NotNull Object value, boolean done, @NotNull Co } + record ChecklistCategory(@NotNull LocalizableMessage name, @NotNull ItemStack icon, @NotNull List entries) { + + public long doneCount() { + return entries.stream().filter(ChecklistEntry::done).count(); + } + + } + } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/FindItemGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/FindItemGoal.java index 30d31db6..9ba8cea4 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/FindItemGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/FindItemGoal.java @@ -1,6 +1,7 @@ package net.cyperia.challenges.plugin.challenges.type.abstraction; import net.cyperia.challenges.plugin.ChallengeAPI; +import net.cyperia.challenges.plugin.management.scheduler.task.ScheduledTask; import net.cyperia.challenges.plugin.management.server.ChallengeEndCause; import net.cyperia.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.cyperia.challenges.plugin.spigot.events.PlayerPickupItemEvent; @@ -27,10 +28,11 @@ public void getWinnersOnEnd(@NotNull List winners) { } - private void checkItem(ItemStack itemStack, @NotNull Player player) { - if (itemStack == null) return; - if (itemStack.getType() != searchedItem) return; + private boolean checkItem(ItemStack itemStack, @NotNull Player player) { + if (itemStack == null) return false; + if (itemStack.getType() != searchedItem) return false; ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(player)); + return true; } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @@ -47,4 +49,16 @@ public void onInventoryClick(PlayerInventoryClickEvent event) { checkItem(event.getCurrentItem(), event.getPlayer()); } + // An item shift-clicked out of a chest never passes a pickup or a click in the player's own + // inventory, so the inventory is scanned as well. + @ScheduledTask(ticks = 20, async = false) + public void scanInventories() { + for (Player player : ChallengeAPI.getIngamePlayers()) { + if (!shouldExecuteEffect(player)) continue; + for (ItemStack item : player.getInventory().getContents()) { + if (checkItem(item, player)) return; + } + } + } + } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java index d3d0039a..84e47397 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java @@ -63,7 +63,7 @@ public void updateDisplayStand(Player player) { } private void removeStand(@NotNull ArmorStand stand) { - Regions.entity(Challenges.getInstance(), stand, stand::remove); + Regions.remove(Challenges.getInstance(), stand); } public void handleDisplayStandUpdate(@NotNull Player player, @NotNull ArmorStand armorStand) { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java index a5d2c8ca..2aefabe3 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java @@ -1,8 +1,10 @@ package net.cyperia.challenges.plugin.challenges.type.abstraction; +import net.cyperia.challenges.plugin.ChallengeAPI; import net.cyperia.challenges.plugin.challenges.type.helper.GoalLeaderboard; import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.challenges.plugin.content.i18n.Prefix; +import net.cyperia.challenges.plugin.management.scheduler.task.ScheduledTask; import net.cyperia.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.cyperia.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.cyperia.commons.bukkit.utils.animation.SoundSample; @@ -10,6 +12,7 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.Collections; @@ -57,4 +60,17 @@ public void onPlayerInventoryClick(@NotNull PlayerInventoryClickEvent event) { handleCollect(player, material); } + // An item shift-clicked out of a chest or smithing table and equipped by right-click never passes + // a pickup or a click in the player's own inventory, so the inventory is scanned as well. + @ScheduledTask(ticks = 20, async = false) + public void scanInventories() { + for (Player player : ChallengeAPI.getIngamePlayers()) { + if (!shouldExecuteEffect()) return; + for (ItemStack item : player.getInventory().getContents()) { + if (item == null) continue; + handleCollect(player, item.getType()); + } + } + } + } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/SharedCollectionGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/SharedCollectionGoal.java index b9a8577a..2ce23200 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/SharedCollectionGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/SharedCollectionGoal.java @@ -3,6 +3,7 @@ import net.cyperia.challenges.plugin.challenges.type.abstraction.menu.MenuGoal; import net.cyperia.challenges.plugin.challenges.type.helper.GoalHelper; import net.cyperia.challenges.plugin.challenges.type.helper.GoalLeaderboard; +import net.cyperia.challenges.plugin.content.i18n.LocalizableMessage; import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.challenges.plugin.content.i18n.MessageKeySpace; import net.cyperia.challenges.plugin.content.i18n.Prefix; @@ -104,6 +105,12 @@ public final void skip(@NotNull CommandSender sender) { @NotNull protected abstract Collection getFinders(); + // A line above the ranking saying what it counts, null for none + @Nullable + protected LocalizableMessage getRankingHeading() { + return null; + } + protected abstract void enableGoal(); protected abstract void disableGoal(); @@ -111,7 +118,7 @@ public final void skip(@NotNull CommandSender sender) { @Override protected final void onEnable() { enableGoal(); - scoreboard.setContent(GoalLeaderboard.sharedScoreboardContent(this::getRanking)); + scoreboard.setContent(GoalLeaderboard.sharedScoreboardContent(this::getRanking, this::getRankingHeading)); updateRankingVisibility(); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/helper/GoalLeaderboard.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/helper/GoalLeaderboard.java index 0354e76c..0962c4b6 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/helper/GoalLeaderboard.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/helper/GoalLeaderboard.java @@ -101,10 +101,19 @@ public static BiConsumer scoreboardContent(@NotNull return content(points, null, additionalLines, true); } - // Everyone plays together, so there is no own placement to show above the ranking + // Everyone plays together, so there is no own placement above the ranking, only an optional heading (null for none) @NotNull - public static BiConsumer sharedScoreboardContent(@NotNull Supplier> points) { - return content(points, null, null, false); + public static BiConsumer sharedScoreboardContent(@NotNull Supplier> points, + @NotNull Supplier heading) { + BiConsumer ranking = content(points, null, null, false); + return (board, viewer) -> { + LocalizableMessage line = heading.get(); + if (line != null) { + board.addEmptyLine(); + board.addLine(line); + } + ranking.accept(board, viewer); + }; } /** diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/challenges/ChallengeManager.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/challenges/ChallengeManager.java index 1ac7ea6c..7176a901 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/challenges/ChallengeManager.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/challenges/ChallengeManager.java @@ -14,7 +14,6 @@ import net.cyperia.commons.common.config.document.GsonDocument; import net.cyperia.commons.common.config.document.wrapper.FileDocumentWrapper; import net.cyperia.commons.database.exceptions.DatabaseException; -import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -76,18 +75,6 @@ public void restoreDefaults() { } } - public void saveSettings(@NotNull Player player) throws DatabaseException { - Document document = new GsonDocument(); - saveSettingsInto(document); - savePlayerDocument(player.getUniqueId(), "config", document); - } - - public void saveCustomChallenges(@NotNull Player player) throws DatabaseException { - Document document = new GsonDocument(); - saveCustomChallengesInto(document); - savePlayerDocument(player.getUniqueId(), "custom_challenges", document); - } - public void saveSettings(@NotNull UUID player, @NotNull Document settings) throws DatabaseException { savePlayerDocument(player, "config", settings); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistMenuGenerator.java index 17a64433..8da67d09 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistMenuGenerator.java @@ -3,6 +3,7 @@ import org.jetbrains.annotations.Nullable; import net.cyperia.challenges.plugin.ChallengeAPI; import net.cyperia.challenges.plugin.challenges.type.ChecklistGoal; +import net.cyperia.challenges.plugin.challenges.type.ChecklistGoal.ChecklistCategory; import net.cyperia.challenges.plugin.challenges.type.ChecklistGoal.ChecklistEntry; import net.cyperia.challenges.plugin.challenges.type.helper.GoalLeaderboard; import net.cyperia.challenges.plugin.content.i18n.LocalizableMessage; @@ -26,6 +27,7 @@ import java.util.Arrays; import java.util.Comparator; +import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Set; @@ -51,6 +53,7 @@ public class GoalChecklistMenuGenerator extends MultiPageSelectMenuGenerator categories; private final int size; private final int[] slots; @@ -59,11 +62,17 @@ public GoalChecklistMenuGenerator(@NotNull ChecklistGoal goal, @NotNull Player v } private GoalChecklistMenuGenerator(@NotNull ChecklistGoal goal, @NotNull Player viewer, @NotNull GoalChecklistView view) { - super(view.apply(goal.getChecklist(viewer), uuid -> Bukkit.getOfflinePlayer(uuid).getName()) + this(goal, viewer, view, goal.getChecklistCategories(viewer)); + } + + private GoalChecklistMenuGenerator(@NotNull ChecklistGoal goal, @NotNull Player viewer, @NotNull GoalChecklistView view, + @NotNull List categories) { + super(view.apply(view.select(goal.getChecklist(viewer), categories), uuid -> Bukkit.getOfflinePlayer(uuid).getName()) .toArray(ChecklistEntry[]::new)); this.goal = goal; this.viewer = viewer; this.view = view; + this.categories = categories; int rows = Math.clamp(Math.ceilDiv(elements.length, COLUMNS), 1, MAX_ROWS); this.size = (rows + 2) * 9; this.slots = calcSlots(rows, COLUMNS, size); @@ -134,6 +143,32 @@ public void updateInventoryContent(@NotNull Inventory inventory, int page, @NotN .tooltip(MenuClickType.LEFT, MessageKey.of("menu.goal.view.switch-filter").withArgs( MessageKey.of("menu.goal.view.filter-name." + view.filter().next().name().toLowerCase(Locale.ROOT)))) .build(locale)); + for (int i = 0; i < categories.size(); i++) { + inventory.setItem(getCategorySlot(i), createCategoryItem(categories.get(i), i == view.category(), locale)); + } + } + + @NotNull + private ItemStack createCategoryItem(@NotNull ChecklistCategory category, boolean shown, @NotNull Locale locale) { + ItemStack icon = category.icon().clone(); + icon.editMeta(meta -> meta.setEnchantmentGlintOverride(shown)); + return new ItemFormatter(icon) + .name(category.name()) + .description(MessageKey.of("menu.goal.category.progress").withArgs(category.doneCount(), category.entries().size())) + .tooltip(MenuClickType.LEFT, MessageKey.of(shown ? "menu.goal.category.show-all" : "menu.goal.category.show")) + .build(locale); + } + + // Centered in the top row + private int getCategorySlot(int index) { + return 4 - categories.size() / 2 + index; + } + + private int getCategoryAt(int slot) { + for (int i = 0; i < categories.size(); i++) { + if (getCategorySlot(i) == slot) return i; + } + return -1; } private int getSortSlot() { @@ -173,12 +208,15 @@ public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player public void handleClick(@NotNull MenuClickInfo info) { Player player = info.getPlayer(); int slot = info.getSlot(); - if (slot == getSortSlot()) { - changeView(player, new GoalChecklistView(view.filter(), view.sort().next(), view.descending())); + int category = getCategoryAt(slot); + if (category >= 0) { + changeView(player, view.toggleCategory(category)); + } else if (slot == getSortSlot()) { + changeView(player, view.withSort(view.sort().next(), view.descending())); } else if (slot == getDirectionSlot()) { - changeView(player, new GoalChecklistView(view.filter(), view.sort(), !view.descending())); + changeView(player, view.withSort(view.sort(), !view.descending())); } else if (slot == getFilterSlot()) { - changeView(player, new GoalChecklistView(view.filter().next(), view.sort(), view.descending())); + changeView(player, view.withFilter(view.filter().next())); } else if (slot == getNavigateHomeSlot()) { SoundSample.OPEN.play(player); player.closeInventory(); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistView.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistView.java index 0d60b10e..5874ab59 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistView.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistView.java @@ -1,17 +1,24 @@ package net.cyperia.challenges.plugin.management.menu.generator.impl.goal; +import net.cyperia.challenges.plugin.challenges.type.ChecklistGoal.ChecklistCategory; import net.cyperia.challenges.plugin.challenges.type.ChecklistGoal.ChecklistEntry; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.Comparator; +import java.util.HashMap; +import java.util.IdentityHashMap; import java.util.List; +import java.util.Map; import java.util.UUID; import java.util.function.Function; -record GoalChecklistView(@NotNull Filter filter, @NotNull Sort sort, boolean descending) { +/** + * @param category index into the goal's checklist categories, {@link #ALL_CATEGORIES} to show every entry + */ +record GoalChecklistView(@NotNull Filter filter, @NotNull Sort sort, boolean descending, int category) { - static final GoalChecklistView DEFAULT = new GoalChecklistView(Filter.ALL, Sort.DEFAULT, false); + static final int ALL_CATEGORIES = -1; + static final GoalChecklistView DEFAULT = new GoalChecklistView(Filter.ALL, Sort.DEFAULT, false, ALL_CATEGORIES); enum Filter { ALL, MISSING, FOUND; @@ -31,26 +38,52 @@ Sort next() { } } + // A category the goal no longer has, like after switching goals, shows everything + @NotNull + List select(@NotNull List all, @NotNull List categories) { + return category >= 0 && category < categories.size() ? categories.get(category).entries() : all; + } + + @NotNull + GoalChecklistView withFilter(@NotNull Filter filter) { + return new GoalChecklistView(filter, sort, descending, category); + } + + @NotNull + GoalChecklistView withSort(@NotNull Sort sort, boolean descending) { + return new GoalChecklistView(filter, sort, descending, category); + } + + // Choosing the shown category again goes back to every entry + @NotNull + GoalChecklistView toggleCategory(int category) { + return new GoalChecklistView(filter, sort, descending, this.category == category ? ALL_CATEGORIES : category); + } + /** - * @param names name of a finder, {@code null} if unknown + * @param names name of a finder, {@code null} if unknown; called at most once per finder */ @NotNull List apply(@NotNull List entries, @NotNull Function names) { - // Entries without a time or finder stay at the end in both directions - Comparator order = switch (sort) { - // stable, so each goal's own order holds within missing and done - case DEFAULT -> descending ? Comparator.comparing(ChecklistEntry::done).reversed() : Comparator.comparing(ChecklistEntry::done); - case TIME -> Comparator.comparing(ChecklistEntry::foundAt, Comparator.nullsLast(direction(Comparator.naturalOrder()))); - case FINDER -> Comparator.comparing(entry -> firstFinder(entry, names), Comparator.nullsLast(direction(String.CASE_INSENSITIVE_ORDER))); - }; - return entries.stream() + List shown = entries.stream() .filter(entry -> switch (filter) { case ALL -> true; case MISSING -> !entry.done(); case FOUND -> entry.done(); }) - .sorted(order) .toList(); + // Entries without a time or finder stay at the end in both directions + Comparator order = switch (sort) { + // stable, so each goal's own order holds within missing and done + case DEFAULT -> descending ? Comparator.comparing(ChecklistEntry::done).reversed() : Comparator.comparing(ChecklistEntry::done); + case TIME -> Comparator.comparing(ChecklistEntry::foundAt, Comparator.nullsLast(direction(Comparator.naturalOrder()))); + case FINDER -> { + // Name lookups hit the server's player cache, so each entry's key is resolved once, not once per comparison + Map keys = firstFinders(shown, names); + yield Comparator.comparing(keys::get, Comparator.nullsLast(direction(String.CASE_INSENSITIVE_ORDER))); + } + }; + return shown.stream().sorted(order).toList(); } @NotNull @@ -58,9 +91,20 @@ private Comparator direction(@NotNull Comparator ascending) { return descending ? ascending.reversed() : ascending; } - @Nullable - private static String firstFinder(@NotNull ChecklistEntry entry, @NotNull Function names) { - return entry.finders().stream().map(names).filter(name -> name != null).min(String.CASE_INSENSITIVE_ORDER).orElse(null); + @NotNull + private static Map firstFinders(@NotNull List entries, @NotNull Function names) { + Map resolved = new HashMap<>(); + Map keys = new IdentityHashMap<>(); + for (ChecklistEntry entry : entries) { + String first = null; + for (UUID finder : entry.finders()) { + if (!resolved.containsKey(finder)) resolved.put(finder, names.apply(finder)); + String name = resolved.get(finder); + if (name != null && (first == null || String.CASE_INSENSITIVE_ORDER.compare(name, first) < 0)) first = name; + } + keys.put(entry, first); + } + return keys; } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/BorderManager.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/BorderManager.java index 8777a8c1..d6e36e19 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/BorderManager.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/BorderManager.java @@ -18,6 +18,8 @@ import org.bukkit.WorldBorder; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; +import org.bukkit.damage.DamageSource; +import org.bukkit.damage.DamageType; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -28,29 +30,34 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Map; +import java.util.Set; import java.util.UUID; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; /** - * The one world border every challenge shares. + * The one world border of a challenge round, the one /worldborder sets and every border challenge changes. *

* Challenges never touch {@link World#getWorldBorder()}: a challenge whose border starts small and * grows with the game state sets how far it has {@link #setGrowth(AbstractChallenge, double, boolean) * grown} it, one that only makes it bigger or smaller {@link #changeSize(double) changes} it, and all of - * them add up. Going through the world border instead would mean the last writer wins, so enabling a - * second border challenge would silently turn the first one into a no-op. + * them add up on top of the size /worldborder {@link #setSize(double, long) set}. Going through the world + * border instead would mean the last writer wins, so enabling a second border challenge would silently + * turn the first one into a no-op. *

- * What the players see is a border of this manager's own, sent per player, so the world keeps the - * border it was created with and a reset needs nothing but forgetting the numbers here. + * What the players see is a border of this manager's own, sent per player. The world keeps its vanilla + * border, because the server spawns no mobs in chunks outside the world's border. */ public final class BorderManager implements GamestateSaveable, Listener { - private static final double MIN_SIZE = 1; + public static final double MIN_SIZE = 1; + public static final double MAX_SIZE = 59_999_968; private static final double START_SIZE = 1; private final Map apiBorders = new ConcurrentHashMap<>(); @@ -58,6 +65,7 @@ public final class BorderManager implements GamestateSaveable, Listener { // Players a challenge has given a border of their own. The shared border leaves them alone until it // is handed back, so a challenge that traps somebody is not undone by one that shrinks the border. + private final Set teleporting = ConcurrentHashMap.newKeySet(); private final Map overrides = new ConcurrentHashMap<>(); // How far each challenge whose border starts small has grown it, by unique challenge name. Not saved: @@ -65,6 +73,22 @@ public final class BorderManager implements GamestateSaveable, Listener { private final Map growth = new ConcurrentHashMap<>(); private volatile double offset; + // The size the border is sliding from and to, so players are held to the line they see moving + // rather than to where it ends up. NaN while there is no border. + private volatile double drawnTarget = Double.NaN; + private volatile double slideFrom; + private volatile long slideStart; + private volatile long slideEnd; + + // The size /worldborder set, null while nobody did + private volatile Double size; + + // Unlike vanilla's 5 blocks, no buffer: a border that shrinks by a block has to hurt whoever it passes + private static final double DAMAGE_PER_BLOCK = 0.2; + private volatile double damageBuffer = 0; + private volatile double damagePerBlock = DAMAGE_PER_BLOCK; + private volatile Containment containment = Containment.DAMAGE; + // One bar for every challenge that drives the border, so two of them never stack two bars private final ChallengeBossBar bossbar = new ChallengeBossBar(); @@ -76,52 +100,143 @@ public void enable() { } /** - * Whether any challenge is currently driving the border. While nothing is, players keep the border - * their world came with. + * Whether there is a border at all: one set with /worldborder or one a challenge grows. While there is + * none, players keep the border their world came with. */ public boolean isActive() { - return !growth.isEmpty() || offset != 0; + return isGrowing() || size != null; + } + + private boolean isGrowing() { + return !growth.isEmpty(); } /** * Shrinks the border down to a single block while any challenge has set a growth, and grows it by the - * sum of all of them. Passing the same growth twice is free. + * sum of all of them. A border /worldborder set is grown from its own size instead. + * Passing the same growth twice is free. */ public void setGrowth(@NotNull AbstractChallenge challenge, double blocks, boolean animate) { Double previous = growth.put(challenge.getUniqueName(), blocks); if (previous != null && previous == blocks) return; - update(animate); + update(animate ? 1 : 0); } public void clearGrowth(@NotNull AbstractChallenge challenge) { if (growth.remove(challenge.getUniqueName()) == null) return; - update(false); + update(0); } /** * Grows or shrinks the border by {@code delta}, on top of whatever size it has otherwise. * The border slides to the new size rather than jumping to it, the way it does when the level border - * follows a level. + * follows a level. Without a border there is nothing to see, but the change is kept for when there is. */ public void changeSize(double delta) { offset += delta; - update(true); + update(1); + } + + /** + * Makes the border {@code target} blocks wide over {@code seconds}, the way /worldborder set does. + * Challenges that change the border go on from there. + */ + public void setSize(double target, long seconds) { + double clamped = Math.clamp(target, MIN_SIZE, MAX_SIZE); + size = clamped - (isGrowing() ? grown() : 0) - offset; + update(seconds); + } + + /** + * Takes back what /worldborder set, so without a challenge that grows one there is no border any more. + */ + public void reset() { + size = null; + centers.clear(); + update(0); + } + + public void setCenter(@NotNull World world, @NotNull Location center) { + centers.put(world, center.clone()); + if (isActive()) updateBorder(world); + } + + public void setDamage(double buffer, double perBlock) { + damageBuffer = Math.max(0, buffer); + damagePerBlock = Math.max(0, perBlock); + } + + public void setContainment(@NotNull Containment containment) { + this.containment = containment; + } + + @NotNull + public Containment getContainment() { + return containment; + } + + public double getDamageBuffer() { + return damageBuffer; + } + + public double getDamagePerBlock() { + return damagePerBlock; } /** - * The size players are actually held to in this world. + * The size the border has in this world once it stops sliding. */ public double getSize(@NotNull World world) { - double base = growth.isEmpty() - ? world.getWorldBorder().getSize() - : START_SIZE + growth.values().stream().mapToDouble(Double::doubleValue).sum(); - return Math.max(MIN_SIZE, base + offset); + if (!isActive()) return world.getWorldBorder().getSize(); + return targetSize(); + } + + private double targetSize() { + double base = size != null ? size : START_SIZE; + return Math.clamp(base + (isGrowing() ? grown() : 0) + offset, MIN_SIZE, MAX_SIZE); + } + + /** + * The size the border is drawn at right now, somewhere between where a slide started and + * {@link #getSize(World)}. + */ + public double getDrawnSize(@NotNull World world) { + if (!isActive()) return getSize(world); + return drawnSize(System.currentTimeMillis()); + } + + private double drawnSize(long now) { + if (now >= slideEnd) return drawnTarget; + double progress = (now - slideStart) / (double) (slideEnd - slideStart); + return slideFrom + (drawnTarget - slideFrom) * progress; + } + + private void startSlide(long seconds) { + long now = System.currentTimeMillis(); + double from = Double.isNaN(drawnTarget) ? Double.NaN : drawnSize(now); + double target = isActive() ? targetSize() : Double.NaN; + if (seconds > 0 && !Double.isNaN(from) && !Double.isNaN(target)) { + slideFrom = from; + slideStart = now; + slideEnd = now + seconds * 1000; + } else { + slideEnd = 0; + } + drawnTarget = target; + } + + private double grown() { + return growth.values().stream().mapToDouble(Double::doubleValue).sum(); } @NotNull public Location getCenter(@NotNull World world) { + if (!isActive()) return world.getWorldBorder().getCenter(); + Location center = centers.get(world); if (center != null) return center.clone(); + // a border that starts small opens where players spawn, one /worldborder set where vanilla's would be + if (!isGrowing()) return new Location(world, 0, 0, 0); Location spawn = world.getSpawnLocation(); spawn.setX(spawn.getBlockX() + 0.5); @@ -129,11 +244,6 @@ public Location getCenter(@NotNull World world) { return spawn; } - public void setCenter(@NotNull World world, @NotNull Location center) { - centers.put(world, center.clone()); - if (isActive()) updateBorder(world, false); - } - /** * Remembers a center only if the world does not have one yet, for challenges that follow the player * into a world rather than deciding where its border belongs. @@ -155,7 +265,7 @@ public boolean isOutside(@NotNull Location location) { if (world == null || !isActive()) return false; Location center = getCenter(world); - double radius = getSize(world) / 2; + double radius = getDrawnSize(world) / 2; return isOutside(location.getBlockX(), center.getX(), radius) || isOutside(location.getBlockZ(), center.getZ(), radius); } @@ -164,20 +274,61 @@ private static boolean isOutside(int block, double center, double radius) { return block < Math.floor(center - radius) || block >= Math.ceil(center + radius); } + /** + * How far this location lies past the area the client lets a player walk in, 0 inside it. Measured + * from the same whole-block bounds as {@link #isOutside(Location)}, so standing where the border let + * a player walk never hurts. + */ + public double distanceOutside(@NotNull Location location) { + World world = location.getWorld(); + if (world == null || !isActive()) return 0; + + Location center = getCenter(world); + double radius = getDrawnSize(world) / 2; + return Math.max(0, Math.max( + distanceOutside(location.getX(), center.getX(), radius), + distanceOutside(location.getZ(), center.getZ(), radius))); + } + + private static double distanceOutside(double position, double center, double radius) { + return Math.max(Math.floor(center - radius) - position, position - Math.ceil(center + radius)); + } + /** * Moves a player to the spot inside the drawn border closest to where they are. */ public void teleportInside(@NotNull Player player) { Location location = player.getLocation(); Location center = getCenter(player.getWorld()); - double radius = getSize(player.getWorld()) / 2; + double radius = getDrawnSize(player.getWorld()) / 2; double margin = Math.min(player.getWidth() / 2, radius); location.setX(Math.clamp(location.getX(), center.getX() - radius + margin, center.getX() + radius - margin)); location.setZ(Math.clamp(location.getZ(), center.getZ() - radius + margin, center.getZ() + radius - margin)); - Location spot = standingSpot(location); + if (!teleporting.add(player.getUniqueId())) return; player.setFallDistance(0); - player.teleportAsync(spot != null ? spot : surface(center, player.getWorld())); + + // The ground at the target belongs to another region than the player's, so it is read there. + Plugin plugin = Challenges.getInstance(); + Regions.at(plugin, location, () -> { + try { + Location spot = standingSpot(location); + if (spot != null) { + teleportTo(player, spot); + } else { + Regions.at(plugin, center, () -> teleportTo(player, surface(center, player.getWorld()))); + } + } catch (RuntimeException e) { + teleporting.remove(player.getUniqueId()); + throw e; + } + }); + } + + // One teleport per player at a time, so a player who stays outside until it lands does not queue another every tick. + private void teleportTo(@NotNull Player player, @NotNull Location spot) { + CompletableFuture teleport = player.teleportAsync(spot); + teleport.whenComplete((done, error) -> teleporting.remove(player.getUniqueId())); } @NotNull @@ -207,12 +358,12 @@ private static Location standingSpot(@NotNull Location location) { } /** - * Gives a player the border of the world they are in, or the world's own border while no challenge is - * driving one or the player left the game worlds behind. + * Gives a player the border of the world they are in, or the world's own border while there is none + * or the player left the game worlds behind. *

* Sending must not rewrite a border somebody else is already watching, or a join would cut short an * animated resize for the whole world. It only writes one it has never written before: a world can - * join the game worlds long after the border went active - {@code /world void} creates one on demand - + * join the game worlds long after the border went active - a world generator challenge swaps them - * and would otherwise hand out the untouched 59,999,968 block default. */ public void sendTo(@NotNull Player player) { @@ -227,7 +378,7 @@ public void sendTo(@NotNull Player player) { return; } - if (!hasBorder(world)) applyTo(world, false); + if (!hasBorder(world)) applyTo(world); bind(player); } @@ -239,11 +390,9 @@ public void sendTo(@NotNull Player player) { public void override(@NotNull Player player, @NotNull Location center, double size) { WorldBorder border = Bukkit.createWorldBorder(); // The world of the center, not of the player: a teleport hands this its destination while the - // player still stands in the world they came from. The client places a nether border at an eighth - // of the coordinates it is given. + // player still stands in the world they came from. World world = center.getWorld() == null ? player.getWorld() : center.getWorld(); - double factor = world.getEnvironment() == World.Environment.NETHER ? 8 : 1; - border.setCenter(center.getX() * factor, center.getZ() * factor); + setCenter(border, world, center); border.setSize(size); border.setWarningDistance(0); border.setWarningTime(0); @@ -257,15 +406,19 @@ public void clearOverride(@NotNull Player player) { if (player.isOnline()) sendTo(player); } - public void update(boolean animate) { + /** + * Writes the border onto every game world over {@code seconds}, 0 for at once. + */ + public void update(long seconds) { + startSlide(seconds); for (World world : ChallengeAPI.getGameWorlds()) { - updateBorder(world, animate); + updateBorder(world); } updateBossBar(); } private void updateBossBar() { - if (growth.isEmpty()) { + if (!isGrowing()) { if (bossbar.isShown()) bossbar.hide(); } else if (bossbar.isShown()) { bossbar.update(); @@ -307,7 +460,7 @@ public void onRespawn(@NotNull PlayerRespawnedEvent event) { // not around that world's spawn. @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPortal(@NotNull PlayerTeleportEvent event) { - if (!isActive() || !ChallengeAPI.isStarted() || ChallengeAPI.isWorldInUse() || event.getTo() == null) return; + if (!isGrowing() || !ChallengeAPI.isStarted() || ChallengeAPI.isWorldInUse() || event.getTo() == null) return; if (event.getCause() != PlayerTeleportEvent.TeleportCause.NETHER_PORTAL && event.getCause() != PlayerTeleportEvent.TeleportCause.END_PORTAL) return; if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; @@ -325,20 +478,45 @@ public void onDamageAcrossBorder(@NotNull EntityDamageByEntityEvent event) { } } - // Before the start too: a new player spawns scattered around the world spawn, outside a small border - @ScheduledTask(ticks = 20, async = false, timerPolicy = TimerPolicy.ALWAYS) + /** + * Puts every player who stands outside the border inside it, for a border that appears around players + * who never crossed it. + */ public void containPlayers() { Challenges.getInstance().getPlayerManager().forEachAudience(this::contain); } + // Before the start, a new player spawns scattered around the world spawn, outside a small border, and + // is put inside whatever the containment says. + @ScheduledTask(ticks = 10, async = false, timerPolicy = TimerPolicy.ALWAYS) + public void holdPlayers() { + if (!ChallengeAPI.isStarted() || containment == Containment.PUSH) { + containPlayers(); + return; + } + Challenges.getInstance().getPlayerManager().forEachAudience(this::hurtOutside); + } + private void contain(@NotNull Player player) { - if (!isActive() || ChallengeAPI.isWorldInUse()) return; - if (overrides.containsKey(player.getUniqueId())) return; - if (player.isDead() || AbstractChallenge.ignorePlayer(player)) return; + if (!isHeld(player)) return; if (isOutside(player.getLocation())) teleportInside(player); } - private void updateBorder(@NotNull World world, boolean animate) { + private void hurtOutside(@NotNull Player player) { + if (!isHeld(player) || damagePerBlock <= 0) return; + double beyond = distanceOutside(player.getLocation()) - damageBuffer; + if (beyond <= 0) return; + // vanilla's own formula, at least half a heart per hit + player.damage(Math.max(1, Math.floor(beyond * damagePerBlock)), DamageSource.builder(DamageType.OUTSIDE_BORDER).build()); + } + + private boolean isHeld(@NotNull Player player) { + if (!isActive() || ChallengeAPI.isWorldInUse()) return false; + if (overrides.containsKey(player.getUniqueId())) return false; + return !player.isDead() && !AbstractChallenge.ignorePlayer(player); + } + + private void updateBorder(@NotNull World world) { if (!isActive()) { forEachPlayerIn(world, this::resetFor); return; @@ -346,7 +524,7 @@ private void updateBorder(@NotNull World world, boolean animate) { // apply once for the whole world: re-applying per player would overwrite the animated transition // with an instant resize before anyone is told about it - applyTo(world, animate); + applyTo(world); forEachPlayerIn(world, this::bind); } @@ -373,20 +551,25 @@ private void bind(@NotNull Player player) { /** * Writes the current size and center onto the world's border object, without sending it anywhere. */ - private void applyTo(@NotNull World world, boolean animate) { - Location center = getCenter(world); - double size = getSize(world); - + private void applyTo(@NotNull World world) { WorldBorder border = apiBorder(world); - // the client places a nether border at an eighth of the coordinates it is given - double factor = world.getEnvironment() == World.Environment.NETHER ? 8 : 1; - border.setCenter(center.getX() * factor, center.getZ() * factor); - if (animate) border.setSize(size, 1); - else border.setSize(size); + setCenter(border, world, getCenter(world)); + // Written from where the slide is now, never from what the border object held before: a border + // that is new or was last used before a reset holds a size nobody is shown any more. + long now = System.currentTimeMillis(); + long remaining = slideEnd - now; + border.setSize(drawnSize(now)); + if (remaining > 0) border.changeSize(getSize(world), Math.max(1, remaining / 50)); border.setWarningDistance(0); border.setWarningTime(0); } + // the client places a nether border at an eighth of the coordinates it is given + private static void setCenter(@NotNull WorldBorder border, @NotNull World world, @NotNull Location center) { + double factor = world.getEnvironment() == World.Environment.NETHER ? 8 : 1; + border.setCenter(center.getX() * factor, center.getZ() * factor); + } + private void resetFor(@NotNull Player player) { if (overrides.containsKey(player.getUniqueId())) return; @@ -402,6 +585,14 @@ private WorldBorder apiBorder(@NotNull World world) { return apiBorders.computeIfAbsent(world, _ -> Bukkit.createWorldBorder()); } + /** + * What happens to a player the border moves over: vanilla border damage, or being put back inside. + */ + public enum Containment { + DAMAGE, + PUSH + } + @Override public String getUniqueGamestateName() { return "world-border"; @@ -410,6 +601,10 @@ public String getUniqueGamestateName() { @Override public void writeGameState(@NotNull Document document) { document.set("offset", offset); + if (size != null) document.set("size", size); + document.set("damage-buffer", damageBuffer); + document.set("damage-per-block", damagePerBlock); + document.set("containment", containment.name()); GsonDocument worlds = new GsonDocument(); centers.forEach((world, center) -> worlds.set(world.getName(), center)); @@ -419,6 +614,13 @@ public void writeGameState(@NotNull Document document) { @Override public void loadGameState(@NotNull Document document) { offset = document.getDouble("offset"); + damageBuffer = 0; + damagePerBlock = DAMAGE_PER_BLOCK; + containment = Containment.DAMAGE; + size = document.contains("size") ? document.getDouble("size") : null; + if (document.contains("damage-buffer")) damageBuffer = document.getDouble("damage-buffer"); + if (document.contains("damage-per-block")) damagePerBlock = document.getDouble("damage-per-block"); + if (document.contains("containment")) containment = Containment.valueOf(document.getString("containment")); centers.clear(); Document worlds = document.getDocument("centers"); @@ -428,7 +630,7 @@ public void loadGameState(@NotNull Document document) { centers.put(world, worlds.getInstance(worldName, Location.class)); } - update(false); + update(0); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/TerrainPrefetcher.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/TerrainPrefetcher.java new file mode 100644 index 00000000..5b4d8819 --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/TerrainPrefetcher.java @@ -0,0 +1,18 @@ +package net.cyperia.challenges.plugin.management.server; + +import org.bukkit.Location; +import org.jetbrains.annotations.NotNull; + +import java.util.concurrent.CompletableFuture; + +@FunctionalInterface +public interface TerrainPrefetcher { + + /** + * Makes the terrain around {@code at} available before its first chunk load. Implementations must + * not touch world state; the returned future may complete on any thread. + */ + @NotNull + CompletableFuture prefetch(@NotNull Location at); + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/WorldManager.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/WorldManager.java index 639cb926..53259071 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/WorldManager.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/WorldManager.java @@ -1,5 +1,6 @@ package net.cyperia.challenges.plugin.management.server; +import com.google.common.base.Preconditions; import lombok.Getter; import lombok.Setter; import net.cyperia.challenges.plugin.ChallengeAPI; @@ -25,7 +26,10 @@ import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.*; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; public final class WorldManager { @@ -41,6 +45,8 @@ public final class WorldManager { private boolean shutdownBecauseOfReset = false; private WorldSettings settings = new WorldSettings(); private World flatWorld; + private final AtomicBoolean prefetchFailureLogged = new AtomicBoolean(); + private TerrainPrefetcher terrainPrefetcher = at -> CompletableFuture.completedFuture(null); @Getter private boolean worldInUse; @@ -61,6 +67,66 @@ public WorldManager() { }; } + public void setTerrainPrefetcher(@NotNull TerrainPrefetcher terrainPrefetcher) { + Preconditions.checkNotNull(terrainPrefetcher, "Cannot set TerrainPrefetcher to null"); + this.terrainPrefetcher = terrainPrefetcher; + } + + /** + * Completes once the terrain at {@code at} is ready to be loaded, possibly on another thread. A + * prefetcher that fails only costs the head start, so the returned future never completes exceptionally. + */ + @NotNull + public CompletableFuture prefetchTerrain(@NotNull Location at) { + CompletableFuture prefetch; + try { + prefetch = terrainPrefetcher.prefetch(at); + } catch (Exception | LinkageError ex) { + logPrefetchFailure(ex); + return CompletableFuture.completedFuture(null); + } + if (prefetch == null) return CompletableFuture.completedFuture(null); + return prefetch.exceptionally(ex -> { + logPrefetchFailure(ex); + return null; + }); + } + + /** + * Loads the chunk at {@code at} after its terrain was prefetched and passes it to {@code action} on + * the region owning the location. The future completes after {@code action} ran, or exceptionally if + * a step failed. + */ + @NotNull + public CompletableFuture loadChunkAfterPrefetch(@NotNull Location at, @NotNull Consumer action) { + Challenges plugin = Challenges.getInstance(); + World world = at.getWorld(); + CompletableFuture done = new CompletableFuture<>(); + // the prefetch completes off the region thread and has to precede the first chunk load at the target + prefetchTerrain(at).thenRun(() -> Regions.at(plugin, at, () -> + world.getChunkAtAsync(at).thenAccept(chunk -> Regions.at(plugin, at, () -> { + try { + action.accept(chunk); + done.complete(null); + } catch (Throwable ex) { + done.completeExceptionally(ex); + } + })).exceptionally(ex -> { + done.completeExceptionally(ex); + return null; + }))).exceptionally(ex -> { + done.completeExceptionally(ex); + return null; + }); + return done; + } + + private void logPrefetchFailure(@NotNull Throwable ex) { + if (prefetchFailureLogged.compareAndSet(false, true)) { + Logger.warn("Terrain prefetch failed, loading chunks without it", ex); + } + } + public void load() { executeWorldResetIfNecessary(); } @@ -167,9 +233,13 @@ private void executeWorldResetIfNecessary() { public void executeWorldReset() { Logger.info("Deleting worlds.."); + File levelFolder = new File(Bukkit.getWorldContainer(), levelName); + List playerFolders = listPlayerFolders(levelFolder); for (String world : worlds) { deleteWorld(world); } + // Paper creates these before plugins load and never again, so without them every player save fails until the next restart + playerFolders.forEach(File::mkdirs); long newSeed = getCustomSeedOrRandom(); String newSeedString = String.valueOf(newSeed); @@ -297,6 +367,12 @@ private void injectSeedInto(Object obj, String oldSeed, String newSeed, int dept } } + @NotNull + static List listPlayerFolders(@NotNull File levelFolder) { + File[] folders = new File(levelFolder, "players").listFiles(File::isDirectory); + return folders == null ? List.of() : List.of(folders); + } + private void deleteWorld(@NotNull String name) { File folder = new File(Bukkit.getWorldContainer(), name); FileUtils.deleteWorldFolder(folder); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/permission/ChallengesPermissions.java b/plugin/src/main/java/net/cyperia/challenges/plugin/permission/ChallengesPermissions.java index f2b53bfa..c6c66eb9 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/permission/ChallengesPermissions.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/permission/ChallengesPermissions.java @@ -59,6 +59,7 @@ public final class ChallengesPermissions { public static final String COMMAND_TIME = COMMAND + "time"; public static final String COMMAND_WEATHER = COMMAND + "weather"; + public static final String COMMAND_WORLDBORDER = COMMAND + "worldborder"; public static final String COMMAND_DIFFICULTY = COMMAND + "difficulty"; public static final String COMMAND_INVSEE = COMMAND + "invsee"; public static final String COMMAND_VILLAGE = COMMAND + "village"; diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/DatabaseCommand.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/DatabaseCommand.java index 98508c89..875bb674 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/DatabaseCommand.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/DatabaseCommand.java @@ -11,10 +11,17 @@ import net.cyperia.challenges.plugin.management.files.ConfigManager; import net.cyperia.challenges.plugin.permission.ChallengesPermissions; import net.cyperia.commons.bukkit.utils.animation.SoundSample; +import net.cyperia.commons.bukkit.utils.logging.Logger; +import net.cyperia.commons.bukkit.utils.misc.Regions; +import net.cyperia.commons.common.config.Document; +import net.cyperia.commons.common.config.document.GsonDocument; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.Executor; +import java.util.function.Consumer; public class DatabaseCommand implements ChallengeCommand { @@ -30,51 +37,69 @@ public DatabaseCommand() { @Override public void save(Player player) throws Exception { if (checkFeatureDisabled(savePlayerConfigs, player)) return; - Challenges.getInstance().getChallengeManager().saveSettings(player); - MessageKey.of("command.database.config-saved").send(player, Prefix.CHALLENGES); + ChallengeManager manager = Challenges.getInstance().getChallengeManager(); + Document settings = new GsonDocument(); + manager.saveSettingsInto(settings); + offThread(player, () -> { + manager.saveSettings(player.getUniqueId(), settings); + return null; + }, none -> MessageKey.of("command.database.config-saved").send(player, Prefix.CHALLENGES)); } @Override public void load(Player player) throws Exception { if (checkFeatureDisabled(savePlayerConfigs, player)) return; ChallengeManager manager = Challenges.getInstance().getChallengeManager(); - manager.loadSettings(manager.getSavedSettings(player.getUniqueId())); - MessageKey.of("command.database.config-loaded").send(player, Prefix.CHALLENGES); + offThread(player, () -> manager.getSavedSettings(player.getUniqueId()), settings -> { + manager.loadSettings(settings); + MessageKey.of("command.database.config-loaded").send(player, Prefix.CHALLENGES); + }); } @Override public void reset(Player player) throws Exception { if (checkFeatureDisabled(savePlayerConfigs, player)) return; - Challenges.getInstance().getDatabaseManager().getDatabase().update("challenges") - .where("uuid", player.getUniqueId()) - .set("config", null) - .execute(); - MessageKey.of("command.database.config-reset").send(player, Prefix.CHALLENGES); + offThread(player, () -> { + Challenges.getInstance().getDatabaseManager().getDatabase().update("challenges") + .where("uuid", player.getUniqueId()) + .set("config", null) + .execute(); + return null; + }, none -> MessageKey.of("command.database.config-reset").send(player, Prefix.CHALLENGES)); } }, "customs", new DatabaseCommandExecutor() { @Override public void save(Player player) throws Exception { if (checkFeatureDisabled(savePlayerChallenges, player)) return; - Challenges.getInstance().getChallengeManager().saveCustomChallenges(player); - MessageKey.of("command.database.customs-saved").send(player, Prefix.CHALLENGES); + ChallengeManager manager = Challenges.getInstance().getChallengeManager(); + Document customChallenges = new GsonDocument(); + manager.saveCustomChallengesInto(customChallenges); + offThread(player, () -> { + manager.saveCustomChallenges(player.getUniqueId(), customChallenges); + return null; + }, none -> MessageKey.of("command.database.customs-saved").send(player, Prefix.CHALLENGES)); } @Override public void load(Player player) throws Exception { if (checkFeatureDisabled(savePlayerChallenges, player)) return; ChallengeManager manager = Challenges.getInstance().getChallengeManager(); - manager.loadCustomChallenges(manager.getSavedCustomChallenges(player.getUniqueId())); - MessageKey.of("command.database.customs-loaded").send(player, Prefix.CHALLENGES); + offThread(player, () -> manager.getSavedCustomChallenges(player.getUniqueId()), customChallenges -> { + manager.loadCustomChallenges(customChallenges); + MessageKey.of("command.database.customs-loaded").send(player, Prefix.CHALLENGES); + }); } @Override public void reset(Player player) throws Exception { if (checkFeatureDisabled(savePlayerChallenges, player)) return; - Challenges.getInstance().getDatabaseManager().getDatabase().update("challenges") - .where("uuid", player.getUniqueId()) - .set("custom_challenges", null) - .execute(); - MessageKey.of("command.database.customs-reset").send(player, Prefix.CHALLENGES); + offThread(player, () -> { + Challenges.getInstance().getDatabaseManager().getDatabase().update("challenges") + .where("uuid", player.getUniqueId()) + .set("custom_challenges", null) + .execute(); + return null; + }, none -> MessageKey.of("command.database.customs-reset").send(player, Prefix.CHALLENGES)); } }); } @@ -103,6 +128,28 @@ private LiteralArgumentBuilder action(@NotNull CommandNodes nodes, @No return node; } + private static void offThread(@NotNull Player player, @NotNull Callable database, @NotNull Consumer onGlobalThread) { + offThread(Challenges.getInstance().getExecutor(), task -> Regions.global(Challenges.getInstance(), task), database, onGlobalThread, + ex -> { + player.sendMessage(Prefix.FALLBACK + "§cSomething went wrong while executing the command"); + Logger.error("Something went wrong while accessing the database for {}", player.getName(), ex); + }); + } + + static void offThread(@NotNull Executor async, @NotNull Executor global, @NotNull Callable database, + @NotNull Consumer onGlobalThread, @NotNull Consumer onError) { + async.execute(() -> { + T result; + try { + result = database.call(); + } catch (Exception ex) { + onError.accept(ex); + return; + } + global.execute(() -> onGlobalThread.accept(result)); + }); + } + /** * Checks for disabled features and sends a proper messages to indicate that */ diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/VillageCommand.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/VillageCommand.java index 2a81828c..b2353ff5 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/VillageCommand.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/VillageCommand.java @@ -16,8 +16,14 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import java.util.function.Consumer; +import java.util.function.IntFunction; + public class VillageCommand implements ChallengeCommand { + // Chunks; the first ring is what vanilla /locate searches. Each ring runs on its own tick. + private static final int[] SEARCH_RADII = {100, 250, 500}; + @NotNull @Override public CommandInfo info() { @@ -32,22 +38,36 @@ public void define(@NotNull LiteralArgumentBuilder root, @NotNull Command private static void teleportToVillage(@NotNull Player player) { player.setNoDamageTicks(10); MessageKey.of("command.village.searching").send(player, Prefix.CHALLENGES); - Regions.nextTick(Challenges.getInstance(), player, () -> { - World world = player.getWorld(); - Location village = world.locateNearestStructure(player.getLocation(), StructureType.VILLAGE, 5000, true); - if (village == null) { - MessageKey.of("command.village.none").send(player, Prefix.CHALLENGES); - return; - } + searchRings(SEARCH_RADII, 0, + radius -> player.getWorld().locateNearestStructure(player.getLocation(), StructureType.VILLAGE, radius, true), + task -> Regions.nextTick(Challenges.getInstance(), player, task), + village -> teleportTo(player, village), + () -> MessageKey.of("command.village.none").send(player, Prefix.CHALLENGES)); + } - world.getChunkAtAsync(village).thenAccept(chunk -> Regions.at(Challenges.getInstance(), village, () -> { - Location target = world.getHighestBlockAt(village).getLocation().add(0.5, 1, 0.5); - Regions.later(Challenges.getInstance(), player, () -> player.teleportAsync(target).thenAccept(success -> { - SoundSample.TELEPORT.play(player); - MessageKey.of("command.village.done").send(player, Prefix.CHALLENGES); - }), 20 /* run after 1 second to give the chunks/world time to load/generate */); - })); + static void searchRings(int[] radii, int ring, @NotNull IntFunction locate, @NotNull Consumer nextTick, + @NotNull Consumer onFound, @NotNull Runnable onNone) { + nextTick.accept(() -> { + Location village = locate.apply(radii[ring]); + if (village != null) { + onFound.accept(village); + } else if (ring + 1 < radii.length) { + searchRings(radii, ring + 1, locate, nextTick, onFound, onNone); + } else { + onNone.run(); + } }); } + private static void teleportTo(@NotNull Player player, @NotNull Location village) { + World world = village.getWorld(); + world.getChunkAtAsync(village).thenAccept(chunk -> Regions.at(Challenges.getInstance(), village, () -> { + Location target = world.getHighestBlockAt(village).getLocation().add(0.5, 1, 0.5); + Regions.later(Challenges.getInstance(), player, () -> player.teleportAsync(target).thenAccept(success -> { + SoundSample.TELEPORT.play(player); + MessageKey.of("command.village.done").send(player, Prefix.CHALLENGES); + }), 20 /* run after 1 second to give the chunks/world time to load/generate */); + })); + } + } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/WorldborderCommand.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/WorldborderCommand.java new file mode 100644 index 00000000..50c43110 --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/WorldborderCommand.java @@ -0,0 +1,131 @@ +package net.cyperia.challenges.plugin.spigot.command; + +import com.mojang.brigadier.arguments.DoubleArgumentType; +import com.mojang.brigadier.arguments.LongArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import net.cyperia.challenges.plugin.ChallengeAPI; +import net.cyperia.challenges.plugin.Challenges; +import net.cyperia.challenges.plugin.content.i18n.MessageKey; +import net.cyperia.challenges.plugin.content.i18n.Prefix; +import net.cyperia.challenges.plugin.management.command.ChallengeCommand; +import net.cyperia.challenges.plugin.management.command.CommandInfo; +import net.cyperia.challenges.plugin.management.command.CommandNodes; +import net.cyperia.challenges.plugin.management.server.BorderManager; +import net.cyperia.challenges.plugin.management.server.BorderManager.Containment; +import net.cyperia.challenges.plugin.permission.ChallengesPermissions; +import net.cyperia.commons.bukkit.utils.misc.Regions; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.World.Environment; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.Locale; + +// Replaces the vanilla command: the border players see is the one BorderManager draws, so a vanilla +// border set next to it would be a second one nobody can see +public class WorldborderCommand implements ChallengeCommand { + + // keeps the slide, counted in milliseconds and ticks, far from overflowing + private static final long MAX_SECONDS = Integer.MAX_VALUE / 20; + + @NotNull + @Override + public CommandInfo info() { + return CommandInfo.command("worldborder", ChallengesPermissions.COMMAND_WORLDBORDER); + } + + @Override + public void define(@NotNull LiteralArgumentBuilder root, @NotNull CommandNodes nodes) { + root.then(nodes.literal("set").then(nodes.argument("size", DoubleArgumentType.doubleArg(BorderManager.MIN_SIZE, BorderManager.MAX_SIZE)) + .executes(nodes.run((sender, context) -> set(sender, DoubleArgumentType.getDouble(context, "size"), 0))) + .then(nodes.argument("seconds", LongArgumentType.longArg(0, MAX_SECONDS)) + .executes(nodes.run((sender, context) -> set(sender, DoubleArgumentType.getDouble(context, "size"), LongArgumentType.getLong(context, "seconds"))))))); + root.then(nodes.literal("add").then(nodes.argument("size", DoubleArgumentType.doubleArg(-BorderManager.MAX_SIZE, BorderManager.MAX_SIZE)) + .executes(nodes.run((sender, context) -> add(sender, DoubleArgumentType.getDouble(context, "size"), 0))) + .then(nodes.argument("seconds", LongArgumentType.longArg(0, MAX_SECONDS)) + .executes(nodes.run((sender, context) -> add(sender, DoubleArgumentType.getDouble(context, "size"), LongArgumentType.getLong(context, "seconds"))))))); + root.then(nodes.literal("center") + .executes(nodes.runAsPlayer((player, context) -> center(player, player.getLocation()))) + .then(nodes.argument("x", DoubleArgumentType.doubleArg()).then(nodes.argument("z", DoubleArgumentType.doubleArg()) + .executes(nodes.run((sender, context) -> center(sender, + new Location(world(sender), DoubleArgumentType.getDouble(context, "x"), 0, DoubleArgumentType.getDouble(context, "z")))))))); + root.then(nodes.literal("get").executes(nodes.run((sender, context) -> get(sender)))); + root.then(nodes.literal("damage") + .then(nodes.literal("buffer").then(nodes.argument("blocks", DoubleArgumentType.doubleArg(0)) + .executes(nodes.run((sender, context) -> { + double buffer = DoubleArgumentType.getDouble(context, "blocks"); + border().setDamage(buffer, border().getDamagePerBlock()); + MessageKey.of("command.worldborder.damage-buffer").send(sender, Prefix.CHALLENGES, format(buffer)); + })))) + .then(nodes.literal("amount").then(nodes.argument("damage", DoubleArgumentType.doubleArg(0)) + .executes(nodes.run((sender, context) -> { + double amount = DoubleArgumentType.getDouble(context, "damage"); + border().setDamage(border().getDamageBuffer(), amount); + MessageKey.of("command.worldborder.damage-amount").send(sender, Prefix.CHALLENGES, format(amount)); + }))))); + LiteralArgumentBuilder mode = nodes.literal("mode"); + for (Containment containment : Containment.values()) { + String name = containment.name().toLowerCase(Locale.ROOT); + mode.then(nodes.literal(name).executes(nodes.run((sender, context) -> { + border().setContainment(containment); + MessageKey.of("command.worldborder.mode." + name).send(sender, Prefix.CHALLENGES); + }))); + } + root.then(mode); + root.then(nodes.literal("reset").executes(nodes.run((sender, context) -> { + Regions.global(Challenges.getInstance(), () -> border().reset()); + MessageKey.of("command.worldborder.reset").send(sender, Prefix.CHALLENGES); + }))); + } + + private static void set(@NotNull CommandSender sender, double size, long seconds) { + Regions.global(Challenges.getInstance(), () -> border().setSize(size, seconds)); + sendSize(sender, size, seconds); + } + + private static void add(@NotNull CommandSender sender, double delta, long seconds) { + double size = Math.clamp(border().getSize(world(sender)) + delta, BorderManager.MIN_SIZE, BorderManager.MAX_SIZE); + set(sender, size, seconds); + } + + private static void sendSize(@NotNull CommandSender sender, double size, long seconds) { + if (seconds > 0) { + MessageKey.of("command.worldborder.set-over").send(sender, Prefix.CHALLENGES, format(size), seconds); + } else { + MessageKey.of("command.worldborder.set").send(sender, Prefix.CHALLENGES, format(size)); + } + } + + private static void center(@NotNull CommandSender sender, @NotNull Location center) { + Regions.global(Challenges.getInstance(), () -> border().setCenter(center.getWorld(), center)); + MessageKey.of("command.worldborder.center").send(sender, Prefix.CHALLENGES, format(center.getX()), format(center.getZ())); + } + + private static void get(@NotNull CommandSender sender) { + World world = world(sender); + Location center = border().getCenter(world); + MessageKey.of("command.worldborder.get").send(sender, Prefix.CHALLENGES, + format(border().getSize(world)), format(center.getX()), format(center.getZ())); + } + + // The console has no world of its own, so it means the overworld of the game + @NotNull + private static World world(@NotNull CommandSender sender) { + if (sender instanceof Player player) return player.getWorld(); + return ChallengeAPI.getGameWorld(Environment.NORMAL); + } + + @NotNull + private static BorderManager border() { + return Challenges.getInstance().getBorderManager(); + } + + @NotNull + static String format(double value) { + if (value == Math.rint(value)) return String.valueOf((long) value); + return String.format(Locale.ROOT, "%.1f", value); + } + +} diff --git a/plugin/src/main/java/net/cyperia/commons/bukkit/utils/misc/Regions.java b/plugin/src/main/java/net/cyperia/commons/bukkit/utils/misc/Regions.java index c468cd65..f7b4b5b2 100644 --- a/plugin/src/main/java/net/cyperia/commons/bukkit/utils/misc/Regions.java +++ b/plugin/src/main/java/net/cyperia/commons/bukkit/utils/misc/Regions.java @@ -17,6 +17,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.stream.Collectors; +import java.util.function.BooleanSupplier; import java.util.function.Consumer; /** @@ -31,6 +32,9 @@ public final class Regions { // Only Folia based servers have a regionised server private static final boolean REGIONIZED = isClassPresent("io.papermc.paper.threadedregions.RegionizedServer"); + // Tests replace this to simulate a regionised server. + static BooleanSupplier regionized = () -> REGIONIZED; + private Regions() { } @@ -60,6 +64,20 @@ else if (!plugin.isEnabled() || !entity.getScheduler().execute(plugin, task, ret } } + /** + * Removes the entity on its owning thread. While a regionised server stops, region data is gone + * and {@code remove} throws, so the entity is only marked non-persistent and is not saved. + */ + public static void remove(@NotNull Plugin plugin, @NotNull Entity entity) { + if (regionized.getAsBoolean() && Bukkit.isStopping()) { + entity.setPersistent(false); + return; + } + entity(plugin, entity, () -> { + if (entity.isValid()) entity.remove(); + }); + } + public static void at(@NotNull Plugin plugin, @NotNull Location location, @NotNull Runnable task) { if (Bukkit.isOwnedByCurrentRegion(location)) task.run(); else if (plugin.isEnabled()) Bukkit.getRegionScheduler().execute(plugin, location, task); @@ -83,7 +101,7 @@ public static CompletableFuture forEachRegion(@NotNull Plugin plugin, @Not List players = Bukkit.getOnlinePlayers().stream().filter(player -> player.getWorld() == world).collect(Collectors.toList()); if (players.isEmpty()) { - if (!REGIONIZED) runScan(plugin, world, scan); + if (!regionized.getAsBoolean()) runScan(plugin, world, scan); done.complete(null); return; } diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/custom/CustomChallengeTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/custom/CustomChallengeTest.java new file mode 100644 index 00000000..04f38066 --- /dev/null +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/custom/CustomChallengeTest.java @@ -0,0 +1,20 @@ +package net.cyperia.challenges.plugin.challenges.custom; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mock; + +class CustomChallengeTest { + + @Test + void hasNoFallbackNamesWithoutACatalogEntry() { + CustomChallenge challenge = mock(CustomChallenge.class, CALLS_REAL_METHODS); + + assertEquals(List.of(), challenge.getFallbackNames()); + } + +} diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallengeTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallengeTest.java new file mode 100644 index 00000000..76ef6009 --- /dev/null +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallengeTest.java @@ -0,0 +1,75 @@ +package net.cyperia.challenges.plugin.challenges.implementation.challenge; + +import net.cyperia.challenges.plugin.Challenges; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +class DamageTeleportChallengeTest { + + @Test + void aSecondHitWhileATeleportIsPendingStartsNothing() { + try (MockedStatic challenges = mockStatic(Challenges.class, RETURNS_DEEP_STUBS)) { + AtomicInteger started = new AtomicInteger(); + CompletableFuture pending = new CompletableFuture<>(); + challenges.when(() -> Challenges.getInstance().getWorldManager().loadChunkAfterPrefetch(any(), any())).thenAnswer(i -> { + started.incrementAndGet(); + return pending; + }); + challenges.when(() -> Challenges.getInstance().getBorderManager().getSize(any())).thenReturn(100d); + challenges.when(() -> Challenges.getInstance().getBorderManager().getCenter(any())).thenAnswer(i -> new Location(null, 0, 0, 0)); + DamageTeleportChallenge challenge = mock(DamageTeleportChallenge.class, withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS)); + Player player = mock(Player.class); + when(player.getUniqueId()).thenReturn(UUID.randomUUID()); + when(player.getWorld()).thenReturn(mock(World.class)); + + challenge.handleDamage(player); + challenge.handleDamage(player); + + assertEquals(1, started.get()); + pending.complete(null); + challenge.handleDamage(player); + assertEquals(2, started.get()); + } + } + + @Test + void aWorldWithoutABorderStillTeleportsNearby() { + try (MockedStatic challenges = mockStatic(Challenges.class, RETURNS_DEEP_STUBS)) { + challenges.when(() -> Challenges.getInstance().getBorderManager().getSize(any())).thenReturn(59_999_968d); + challenges.when(() -> Challenges.getInstance().getBorderManager().getCenter(any())).thenAnswer(i -> new Location(null, 0, 0, 0)); + DamageTeleportChallenge challenge = mock(DamageTeleportChallenge.class, withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS)); + + for (int i = 0; i < 100; i++) { + Location target = challenge.getRandomLocation(mock(World.class)); + assertTrue(Math.abs(target.getX()) <= 2000 && Math.abs(target.getZ()) <= 2000, target.toString()); + } + } + } + + @Test + void aSmallBorderStaysTheLimit() { + try (MockedStatic challenges = mockStatic(Challenges.class, RETURNS_DEEP_STUBS)) { + challenges.when(() -> Challenges.getInstance().getBorderManager().getSize(any())).thenReturn(100d); + challenges.when(() -> Challenges.getInstance().getBorderManager().getCenter(any())).thenAnswer(i -> new Location(null, 0, 0, 0)); + DamageTeleportChallenge challenge = mock(DamageTeleportChallenge.class, withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS)); + + for (int i = 0; i < 100; i++) { + Location target = challenge.getRandomLocation(mock(World.class)); + assertTrue(Math.abs(target.getX()) < 50 && Math.abs(target.getZ()) < 50, target.toString()); + } + } + } + +} diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistViewTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistViewTest.java index 0fa0068d..83bb41e5 100644 --- a/plugin/src/test/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistViewTest.java +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistViewTest.java @@ -1,10 +1,14 @@ package net.cyperia.challenges.plugin.management.menu.generator.impl.goal; +import net.cyperia.challenges.plugin.challenges.type.ChecklistGoal.ChecklistCategory; import net.cyperia.challenges.plugin.challenges.type.ChecklistGoal.ChecklistEntry; +import net.cyperia.challenges.plugin.content.i18n.LocalizableMessage; import org.bukkit.inventory.ItemStack; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -28,7 +32,7 @@ private static ChecklistEntry entry(String name, boolean done, List finder } private static List apply(GoalChecklistView.Filter filter, GoalChecklistView.Sort sort, boolean descending) { - return new GoalChecklistView(filter, sort, descending).apply(ENTRIES, NAMES::get); + return new GoalChecklistView(filter, sort, descending, GoalChecklistView.ALL_CATEGORIES).apply(ENTRIES, NAMES::get); } @Test @@ -59,4 +63,74 @@ void sortsByFinderNameIgnoringCase() { apply(GoalChecklistView.Filter.ALL, GoalChecklistView.Sort.FINDER, false)); } + @Test + void sortsByFinderDescendingWithEntriesWithoutFinderLast() { + assertEquals(List.of(EARLY_BY_BEN, LATE_BY_ANNA, MISSING, SKIPPED), + apply(GoalChecklistView.Filter.ALL, GoalChecklistView.Sort.FINDER, true)); + } + + @Test + void usesTheAlphabeticallyFirstOfSeveralFinders() { + ChecklistEntry shared = entry("shared", true, List.of(BEN, ANNA), 5L); + ChecklistEntry onlyBen = entry("onlyBen", true, List.of(BEN), 6L); + + assertEquals(List.of(shared, onlyBen), + new GoalChecklistView(GoalChecklistView.Filter.ALL, GoalChecklistView.Sort.FINDER, false, GoalChecklistView.ALL_CATEGORIES) + .apply(List.of(onlyBen, shared), NAMES::get)); + } + + @Test + void resolvesEachFinderNameAtMostOnce() { + Map calls = new HashMap<>(); + List many = new ArrayList<>(); + for (int i = 0; i < 50; i++) many.add(entry("e" + i, true, List.of(i % 2 == 0 ? ANNA : BEN), (long) i)); + many.add(MISSING); + + new GoalChecklistView(GoalChecklistView.Filter.ALL, GoalChecklistView.Sort.FINDER, false, GoalChecklistView.ALL_CATEGORIES) + .apply(many, uuid -> { + calls.merge(uuid, 1, Integer::sum); + return NAMES.get(uuid); + }); + + assertEquals(Map.of(ANNA, 1, BEN, 1), calls); + } + + @Test + void doesNotResolveNamesOfFilteredOutEntries() { + List asked = new ArrayList<>(); + + new GoalChecklistView(GoalChecklistView.Filter.MISSING, GoalChecklistView.Sort.FINDER, false, GoalChecklistView.ALL_CATEGORIES) + .apply(ENTRIES, uuid -> { + asked.add(uuid); + return NAMES.get(uuid); + }); + + assertEquals(List.of(), asked); + } + + private static final List CATEGORIES = List.of( + new ChecklistCategory(Mockito.mock(LocalizableMessage.class), Mockito.mock(ItemStack.class), List.of(MISSING)), + new ChecklistCategory(Mockito.mock(LocalizableMessage.class), Mockito.mock(ItemStack.class), List.of(EARLY_BY_BEN, SKIPPED))); + + @Test + void aCategoryShowsOnlyItsEntries() { + GoalChecklistView view = GoalChecklistView.DEFAULT.toggleCategory(1); + + assertEquals(List.of(EARLY_BY_BEN, SKIPPED), view.select(ENTRIES, CATEGORIES)); + } + + @Test + void choosingTheShownCategoryAgainShowsEverything() { + GoalChecklistView view = GoalChecklistView.DEFAULT.toggleCategory(1).toggleCategory(1); + + assertEquals(ENTRIES, view.select(ENTRIES, CATEGORIES)); + } + + @Test + void aCategoryTheGoalDoesNotHaveShowsEverything() { + GoalChecklistView view = GoalChecklistView.DEFAULT.toggleCategory(1); + + assertEquals(ENTRIES, view.select(ENTRIES, List.of())); + } + } diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/BorderManagerTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/BorderManagerTest.java index f0954194..afe60462 100644 --- a/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/BorderManagerTest.java +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/BorderManagerTest.java @@ -2,18 +2,29 @@ import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.abstraction.AbstractChallenge; +import net.cyperia.challenges.plugin.management.server.BorderManager.Containment; +import net.cyperia.commons.common.config.Document; +import net.cyperia.commons.common.config.document.GsonDocument; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; +import org.bukkit.WorldBorder; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.MockedStatic; +import java.util.ArrayList; +import java.util.List; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -21,19 +32,34 @@ class BorderManagerTest { + private static final double VANILLA = 59_999_968d; + private MockedStatic challenges; private MockedStatic bukkit; private BorderManager border; private final World world = mock(World.class, RETURNS_DEEP_STUBS); + private final FakeBorder real = new FakeBorder(world); + private final List drawn = new ArrayList<>(); + private final AbstractChallenge level = challenge("level-border"); @BeforeEach void setUp() { - // update() walks the game worlds; deep stubs hand it an empty list challenges = mockStatic(Challenges.class, RETURNS_DEEP_STUBS); bukkit = mockStatic(Bukkit.class); bukkit.when(Bukkit::getMinecraftVersion).thenReturn("1.21.4"); + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(any(Location.class))).thenReturn(true); + bukkit.when(() -> Bukkit.getWorld("world")).thenReturn(world); + bukkit.when(Bukkit::createWorldBorder).thenAnswer(_ -> { + FakeBorder border = new FakeBorder(null); + drawn.add(border); + return border; + }); + when(Challenges.getInstance().getGameWorldStorage().getGameWorlds()).thenReturn(List.of(world)); + when(world.getWorldBorder()).thenReturn(real); + when(world.getName()).thenReturn("world"); + when(world.getEnvironment()).thenReturn(World.Environment.NORMAL); + when(world.getSpawnLocation()).thenAnswer(_ -> new Location(world, 12, 64, 7)); border = new BorderManager(); - when(world.getWorldBorder().getSize()).thenReturn(59_999_968d); } @AfterEach @@ -43,18 +69,27 @@ void tearDown() { } @Test - void withoutGrowthTheWorldKeepsItsOwnBorder() { + void withNothingSetPlayersKeepTheWorldsOwnBorder() { + border.update(0); + assertFalse(border.isActive()); - assertEquals(59_999_968d, border.getSize(world)); + assertTrue(drawn.isEmpty()); + assertEquals(VANILLA, border.getSize(world)); } @Test - void growthsAddUpOnABorderThatStartsAtOneBlock() { - AbstractChallenge level = challenge("level-border"); - AbstractChallenge damage = challenge("damage-border"); + void aGrowingBorderStartsAtOneBlockAroundTheSpawn() { + border.setGrowth(level, 4, false); - border.setGrowth(level, 0, false); - assertEquals(1, border.getSize(world)); + assertEquals(5, drawn().size); + assertEquals(12.5, drawn().centerX); + assertEquals(7.5, drawn().centerZ); + assertEquals(0, drawn().warningDistance); + } + + @Test + void growthsAddUp() { + AbstractChallenge damage = challenge("damage-border"); border.setGrowth(level, 4, false); border.setGrowth(damage, 3, false); @@ -67,9 +102,207 @@ void growthsAddUpOnABorderThatStartsAtOneBlock() { assertEquals(6, border.getSize(world)); } + @Test + void aBorderSetWithTheCommandIsWhereAGrowingBorderStarts() { + border.setCenter(world, new Location(world, 300.5, 0, 300.5)); + border.setSize(10, 0); + + border.setGrowth(level, 4, false); + + assertEquals(14, drawn().size); + assertEquals(300.5, drawn().centerX); + assertEquals(300.5, drawn().centerZ); + } + + @Test + void sizeChangesGoOnTopOfTheCommandsBorder() { + border.setCenter(world, new Location(world, 300.5, 0, 300.5)); + border.setSize(10, 0); + + border.changeSize(1); + assertEquals(11, drawn().size); + assertEquals(20, drawn().lastTicks, 1); + + border.changeSize(1); + assertEquals(12, drawn().size); + assertEquals(300.5, drawn().centerX); + } + + @Test + void sizeChangesWithoutABorderWaitForOne() { + border.changeSize(2); + assertFalse(border.isActive()); + assertTrue(drawn.isEmpty()); + + border.setSize(10, 0); + assertEquals(10, drawn().size); + border.changeSize(1); + assertEquals(11, drawn().size); + } + + @Test + void aSizeSetWhileAChallengeGrowsTheBorderIsWhereItGrowsOnFrom() { + border.setGrowth(level, 4, false); + border.changeSize(2); + assertEquals(7, border.getSize(world)); + + border.setSize(10, 0); + assertEquals(10, drawn().size); + + border.setGrowth(level, 6, false); + assertEquals(12, drawn().size); + } + + @Test + void sizeChangesStopAtOneBlock() { + border.setSize(3, 0); + border.changeSize(-10); + assertEquals(1, drawn().size); + } + + @Test + void aNewBorderAppearsAtItsSizeInsteadOfSlidingInFromTheHorizon() { + border.setSize(10, 5); + assertEquals(10, drawn().size); + assertEquals(0, drawn().lastTicks); + + border.setSize(20, 5); + assertEquals(20, drawn().size); + assertEquals(100, drawn().lastTicks, 1); + } + + @Test + void theWorldsOwnBorderIsNeverWritten() { + border.setCenter(world, new Location(world, 300.5, 0, 300.5)); + border.setSize(10, 0); + border.setGrowth(level, 4, false); + border.changeSize(3); + border.reset(); + + assertEquals(0, real.writes); + } + + @Test + void aResetLeavesOnlyWhatChallengesGrow() { + border.setSize(10, 0); + border.reset(); + assertFalse(border.isActive()); + + border.setSize(10, 0); + border.setGrowth(level, 4, false); + border.reset(); + assertTrue(border.isActive()); + assertEquals(5, border.getSize(world)); + } + + @Test + void theBorderOutlivesARestart() { + border.setCenter(world, new Location(world, 300.5, 0, -20.5)); + border.setSize(10, 0); + border.changeSize(2); + border.setDamage(2, 0.5); + border.setContainment(Containment.PUSH); + Document save = new GsonDocument(); + border.writeGameState(save); + + BorderManager restarted = new BorderManager(); + restarted.loadGameState(save); + + assertEquals(12, restarted.getSize(world)); + assertEquals(300.5, restarted.getCenter(world).getX()); + assertEquals(-20.5, restarted.getCenter(world).getZ()); + assertEquals(2, restarted.getDamageBuffer()); + assertEquals(0.5, restarted.getDamagePerBlock()); + assertEquals(Containment.PUSH, restarted.getContainment()); + } + + @Test + void aSaveWithoutASizeHasNoBorder() { + border.changeSize(2); + Document save = new GsonDocument(); + border.writeGameState(save); + + BorderManager restarted = new BorderManager(); + restarted.loadGameState(save); + + assertFalse(restarted.isActive()); + assertEquals(Containment.DAMAGE, restarted.getContainment()); + } + + @Test + void aNetherBorderIsCenteredAtEightTimesItsCoordinates() { + World nether = mock(World.class, RETURNS_DEEP_STUBS); + when(nether.getEnvironment()).thenReturn(World.Environment.NETHER); + when(Challenges.getInstance().getGameWorldStorage().getGameWorlds()).thenReturn(List.of(nether)); + + border.setCenter(nether, new Location(nether, 10, 70, -3)); + border.setSize(10, 0); + + assertEquals(80, drawn().centerX); + assertEquals(-24, drawn().centerZ); + } + + @Test + void theDistanceOutsideIsMeasuredFromWhereTheClientStopsWalking() { + border.setCenter(world, new Location(world, 0.5, 0, 0.5)); + border.setSize(9, 0); + + // drawn from -4 to 5, walkable from -4 to 5; at 10 it is drawn from -4.5 to 5.5 and walkable from -5 to 6 + assertEquals(0, border.distanceOutside(new Location(world, 4.7, 64, 0))); + assertEquals(4, border.distanceOutside(new Location(world, 9, 64, 0)), 1e-9); + assertEquals(7, border.distanceOutside(new Location(world, 2, 64, -11)), 1e-9); + + border.setSize(10, 0); + assertEquals(0, border.distanceOutside(new Location(world, 5.7, 64, 0))); + assertEquals(0, border.distanceOutside(new Location(world, -4.7, 64, 0))); + assertEquals(0.5, border.distanceOutside(new Location(world, 6.5, 64, 0)), 1e-9); + } + + @Test + void aSlidingBorderHoldsPlayersToWhereItIsDrawnNow() { + border.setCenter(world, new Location(world, 0.5, 0, 0.5)); + border.setSize(20, 0); + border.setSize(4, 60); + + assertEquals(4, border.getSize(world)); + assertEquals(20, border.getDrawnSize(world), 0.1); + assertFalse(border.isOutside(new Location(world, 8.5, 64, 0.5))); + assertEquals(0, border.distanceOutside(new Location(world, 8.5, 64, 0.5))); + } + + @Test + void aBorderUsedBeforeAResetStartsAtItsNewSize() { + border.setSize(5000, 0); + border.reset(); + border.setSize(100, 10); + + assertEquals(100, drawn().size); + assertEquals(0, drawn().lastTicks); + assertEquals(100, border.getDrawnSize(world)); + } + + @Test + void aCenterMovedDuringASlideKeepsItSliding() { + border.setSize(20, 0); + border.setSize(4, 60); + border.setCenter(world, new Location(world, 50, 0, 50)); + + assertEquals(4, drawn().size); + assertEquals(1200, drawn().lastTicks, 2); + assertEquals(50, drawn().centerX); + } + + @Test + void aBorderWithoutASlideIsDrawnAtItsSize() { + border.setSize(20, 0); + border.setSize(4, 0); + + assertEquals(4, border.getDrawnSize(world)); + } + @Test void aFractionalSizeHoldsPlayersToTheWholeBlocksTheClientCollidesWith() { - border.setCenter(world, new Location(world, 0.5, 64, 0.5)); + border.setCenter(world, new Location(world, 0.5, 0, 0.5)); border.setGrowth(challenge("damage-border"), 4.1, false); // drawn from -2.05 to 3.05, walkable from -3 to 4 @@ -81,7 +314,7 @@ void aFractionalSizeHoldsPlayersToTheWholeBlocksTheClientCollidesWith() { @Test void aPlayerOutsideIsPutJustInsideWhereTheyCrossed() { - border.setCenter(world, new Location(world, 0.5, 64, 0.5)); + border.setCenter(world, new Location(world, 0.5, 0, 0.5)); border.setGrowth(challenge("damage-border"), 9, false); Block feet = mock(Block.class); @@ -92,11 +325,7 @@ void aPlayerOutsideIsPutJustInsideWhereTheyCrossed() { when(feet.getRelative(BlockFace.DOWN)).thenReturn(ground); when(world.getBlockAt(any(Location.class))).thenReturn(feet); - Player player = mock(Player.class); - when(player.getWorld()).thenReturn(world); - when(player.getWidth()).thenReturn(0.6); - when(player.getLocation()).thenReturn(new Location(world, 40, 64, 2)); - + Player player = player(); border.teleportInside(player); ArgumentCaptor target = ArgumentCaptor.forClass(Location.class); @@ -107,9 +336,30 @@ void aPlayerOutsideIsPutJustInsideWhereTheyCrossed() { assertEquals(64, target.getValue().getY(), 1e-9); } + @Test + void aPlayerWhoseTeleportIsStillOnItsWayIsNotSentAgain() { + border.setCenter(world, new Location(world, 0.5, 0, 0.5)); + border.setGrowth(challenge("damage-border"), 9, false); + Block feet = mock(Block.class); + when(feet.isPassable()).thenReturn(true); + when(feet.getRelative(any(BlockFace.class))).thenReturn(feet); + when(world.getBlockAt(any(Location.class))).thenReturn(feet); + + Player player = player(); + CompletableFuture pending = new CompletableFuture<>(); + when(player.teleportAsync(any(Location.class))).thenReturn(pending); + border.teleportInside(player); + border.teleportInside(player); + verify(player, times(1)).teleportAsync(any(Location.class)); + + pending.complete(true); + border.teleportInside(player); + verify(player, times(2)).teleportAsync(any(Location.class)); + } + @Test void overTheVoidAPlayerIsPutOnTheCenterInstead() { - border.setCenter(world, new Location(world, 0.5, 64, 0.5)); + border.setCenter(world, new Location(world, 0.5, 0, 0.5)); border.setGrowth(challenge("damage-border"), 9, false); Block air = mock(Block.class); @@ -119,11 +369,7 @@ void overTheVoidAPlayerIsPutOnTheCenterInstead() { when(world.getBlockAt(any(Location.class))).thenReturn(air); when(world.getMinHeight()).thenReturn(0); - Player player = mock(Player.class); - when(player.getWorld()).thenReturn(world); - when(player.getWidth()).thenReturn(0.6); - when(player.getLocation()).thenReturn(new Location(world, 40, 64, 2)); - + Player player = player(); border.teleportInside(player); ArgumentCaptor target = ArgumentCaptor.forClass(Location.class); @@ -132,10 +378,141 @@ void overTheVoidAPlayerIsPutOnTheCenterInstead() { assertEquals(0.5, target.getValue().getZ(), 1e-9); } + private FakeBorder drawn() { + assertEquals(1, drawn.size(), "one border per world"); + return drawn.getFirst(); + } + + private Player player() { + Player player = mock(Player.class); + when(player.getWorld()).thenReturn(world); + when(player.getWidth()).thenReturn(0.6); + when(player.getLocation()).thenReturn(new Location(world, 40, 64, 2)); + when(player.getUniqueId()).thenReturn(UUID.randomUUID()); + when(player.teleportAsync(any(Location.class))).thenReturn(CompletableFuture.completedFuture(true)); + return player; + } + private static AbstractChallenge challenge(String name) { AbstractChallenge challenge = mock(AbstractChallenge.class); when(challenge.getUniqueName()).thenReturn(name); return challenge; } + private static final class FakeBorder implements WorldBorder { + + private final World world; + private double size = VANILLA; + private double centerX; + private double centerZ; + private int warningDistance = 5; + private int warningTicks = 300; + private long lastTicks; + private int writes; + + FakeBorder(@Nullable World world) { + this.world = world; + } + + @Override + public @Nullable World getWorld() { + return world; + } + + @Override + public void reset() { + size = VANILLA; + centerX = 0; + centerZ = 0; + } + + @Override + public double getSize() { + return size; + } + + @Override + public void setSize(double newSize) { + changeSize(newSize, 0); + } + + @Override + public void changeSize(double newSize, long ticks) { + writes++; + size = newSize; + lastTicks = ticks; + } + + @Override + public @NotNull Location getCenter() { + return new Location(world, centerX, 0, centerZ); + } + + @Override + public void setCenter(double x, double z) { + writes++; + centerX = x; + centerZ = z; + } + + @Override + public void setCenter(@NotNull Location location) { + setCenter(location.getX(), location.getZ()); + } + + @Override + public double getDamageBuffer() { + return 5; + } + + @Override + public void setDamageBuffer(double blocks) { + } + + @Override + public double getDamageAmount() { + return 0.2; + } + + @Override + public void setDamageAmount(double damage) { + } + + @Override + public int getWarningTimeTicks() { + return warningTicks; + } + + @Override + public void setWarningTimeTicks(int ticks) { + warningTicks = ticks; + } + + @Override + public int getWarningDistance() { + return warningDistance; + } + + @Override + public void setWarningDistance(int distance) { + warningDistance = distance; + } + + @Override + public boolean isInside(@NotNull Location location) { + return true; + } + + @Override + public double getMaxSize() { + return VANILLA; + } + + @Override + public double getMaxCenterCoordinate() { + return 29_999_984d; + } + + } + } diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/PlayerFoldersTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/PlayerFoldersTest.java new file mode 100644 index 00000000..bdfdf352 --- /dev/null +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/PlayerFoldersTest.java @@ -0,0 +1,38 @@ +package net.cyperia.challenges.plugin.management.server; + +import net.cyperia.commons.common.misc.FileUtils; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +class PlayerFoldersTest { + + @Test + void playerFoldersSurviveTheWorldDeletionEmpty(@TempDir File container) throws IOException { + File level = new File(container, "world"); + File data = new File(level, "players/data"); + File stats = new File(level, "players/stats"); + assertTrue(data.mkdirs() && stats.mkdirs()); + Files.writeString(new File(data, "player.dat").toPath(), "inventory"); + + List folders = WorldManager.listPlayerFolders(level); + FileUtils.deleteWorldFolder(level); + folders.forEach(File::mkdirs); + + assertTrue(data.isDirectory()); + assertTrue(stats.isDirectory()); + assertArrayEquals(new String[0], data.list()); + } + + @Test + void aLevelWithoutPlayerFoldersHasNoneToKeep(@TempDir File container) { + assertEquals(List.of(), WorldManager.listPlayerFolders(new File(container, "world"))); + } + +} diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/WorldManagerTerrainPrefetchTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/WorldManagerTerrainPrefetchTest.java new file mode 100644 index 00000000..83820900 --- /dev/null +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/WorldManagerTerrainPrefetchTest.java @@ -0,0 +1,134 @@ +package net.cyperia.challenges.plugin.management.server; + +import net.cyperia.challenges.plugin.Challenges; +import net.cyperia.commons.bukkit.utils.logging.Logger; +import net.cyperia.commons.common.config.document.GsonDocument; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.World; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.*; + +class WorldManagerTerrainPrefetchTest { + + private MockedStatic challenges; + private MockedStatic logger; + private WorldManager manager; + private final Location at = mock(Location.class); + + @BeforeEach + void setUp() { + challenges = mockStatic(Challenges.class, RETURNS_DEEP_STUBS); + challenges.when(() -> Challenges.getInstance().getConfigDocument()).thenReturn(new GsonDocument()); + logger = mockStatic(Logger.class); + manager = new WorldManager(); + } + + @AfterEach + void tearDown() { + logger.close(); + challenges.close(); + } + + @Test + void completesImmediatelyWithoutAPrefetcher() { + assertTrue(manager.prefetchTerrain(at).isDone()); + } + + @Test + void delegatesToTheInstalledPrefetcher() { + CompletableFuture pending = new CompletableFuture<>(); + manager.setTerrainPrefetcher(location -> { + assertSame(at, location); + return pending; + }); + + CompletableFuture result = manager.prefetchTerrain(at); + + assertFalse(result.isDone()); + pending.complete(null); + assertTrue(result.isDone()); + } + + @Test + void rejectsNull() { + assertThrows(NullPointerException.class, () -> manager.setTerrainPrefetcher(null)); + } + + @Test + void anExceptionalFutureStillCompletes() { + manager.setTerrainPrefetcher(location -> CompletableFuture.failedFuture(new IllegalStateException("boom"))); + + CompletableFuture result = manager.prefetchTerrain(at); + + assertTrue(result.isDone()); + assertFalse(result.isCompletedExceptionally()); + } + + @Test + void aThrowingPrefetcherStillCompletes() { + manager.setTerrainPrefetcher(location -> { + throw new NoSuchMethodError("prefetch"); + }); + + CompletableFuture result = manager.prefetchTerrain(at); + + assertTrue(result.isDone()); + assertFalse(result.isCompletedExceptionally()); + } + + @Test + void aNullFutureStillCompletes() { + manager.setTerrainPrefetcher(location -> null); + + assertTrue(manager.prefetchTerrain(at).isDone()); + } + + @Test + void loadsTheChunkOnlyAfterThePrefetchCompleted() { + World world = mock(World.class); + Chunk chunk = mock(Chunk.class); + when(at.getWorld()).thenReturn(world); + when(world.getChunkAtAsync(at)).thenReturn(CompletableFuture.completedFuture(chunk)); + try (MockedStatic bukkit = mockStatic(Bukkit.class)) { + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(at)).thenReturn(true); + CompletableFuture pending = new CompletableFuture<>(); + manager.setTerrainPrefetcher(location -> pending); + AtomicReference received = new AtomicReference<>(); + + CompletableFuture done = manager.loadChunkAfterPrefetch(at, received::set); + + verify(world, never()).getChunkAtAsync(any(Location.class)); + assertFalse(done.isDone()); + pending.complete(null); + verify(world).getChunkAtAsync(at); + assertSame(chunk, received.get()); + assertTrue(done.isDone()); + } + } + + @Test + void aFailedChunkLoadFailsTheFuture() { + World world = mock(World.class); + when(at.getWorld()).thenReturn(world); + when(world.getChunkAtAsync(at)).thenReturn(CompletableFuture.failedFuture(new IllegalStateException("boom"))); + try (MockedStatic bukkit = mockStatic(Bukkit.class)) { + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(at)).thenReturn(true); + + assertTrue(manager.loadChunkAfterPrefetch(at, chunk -> { }).isCompletedExceptionally()); + } + } + +} diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/CommandTreesTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/CommandTreesTest.java index 01f5ecae..6f03213e 100644 --- a/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/CommandTreesTest.java +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/CommandTreesTest.java @@ -109,6 +109,26 @@ void timeTakesNamedTimesAndTicks() { assertFalse(runs("time set dusk", sender)); } + @Test + void worldborderTakesTheVanillaSubcommandsAndAMode() { + register(new WorldborderCommand()); + CommandSender sender = senderWith(ChallengesPermissions.COMMAND_WORLDBORDER); + + assertTrue(runs("worldborder set 10", sender)); + assertTrue(runs("worldborder set 10.5 30", sender)); + assertTrue(runs("worldborder add -4 5", sender)); + assertTrue(runs("worldborder center 300.5 -20", sender)); + assertTrue(runs("worldborder damage buffer 0", sender)); + assertTrue(runs("worldborder damage amount 0.2", sender)); + assertTrue(runs("worldborder mode push", sender)); + assertTrue(runs("worldborder mode damage", sender)); + assertTrue(runs("worldborder get", sender)); + assertTrue(runs("worldborder reset", sender)); + assertFalse(runs("worldborder set 0", sender)); + assertFalse(runs("worldborder mode bounce", sender)); + assertFalse(runs("worldborder set 10", senderWith())); + } + @Test void genericCommandsAreTheOnesANetworkToolboxProvides() { assertTrue(new HealCommand().info().isGeneric()); @@ -117,6 +137,7 @@ void genericCommandsAreTheOnesANetworkToolboxProvides() { assertTrue(HelpCommand.INFO.isGeneric()); assertFalse(new TimerCommand().info().isGeneric()); assertFalse(new BackCommand().info().isGeneric()); + assertFalse(new WorldborderCommand().info().isGeneric()); } @Test diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/DatabaseCommandTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/DatabaseCommandTest.java new file mode 100644 index 00000000..553e9e4e --- /dev/null +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/DatabaseCommandTest.java @@ -0,0 +1,58 @@ +package net.cyperia.challenges.plugin.spigot.command; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.Executor; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class DatabaseCommandTest { + + private final Queue async = new ArrayDeque<>(); + private final Queue global = new ArrayDeque<>(); + private final List events = new ArrayList<>(); + + private final Executor asyncExecutor = async::add; + private final Executor globalExecutor = global::add; + + @Test + void runsTheDatabaseCallOnlyOnTheAsyncExecutor() { + DatabaseCommand.offThread(asyncExecutor, globalExecutor, () -> { + events.add("db"); + return "doc"; + }, doc -> events.add("apply " + doc), ex -> events.add("error")); + + assertTrue(events.isEmpty()); + async.poll().run(); + assertEquals(List.of("db"), events); + } + + @Test + void appliesTheResultOnTheGlobalExecutor() { + DatabaseCommand.offThread(asyncExecutor, globalExecutor, () -> "doc", + doc -> events.add("apply " + doc), ex -> events.add("error")); + + async.poll().run(); + assertTrue(events.isEmpty()); + global.poll().run(); + assertEquals(List.of("apply doc"), events); + } + + @Test + void reportsAFailureWithoutApplying() { + DatabaseCommand.offThread(asyncExecutor, globalExecutor, () -> { + throw new IOException("down"); + }, doc -> events.add("apply"), ex -> events.add("error " + ex.getMessage())); + + async.poll().run(); + assertEquals(List.of("error down"), events); + assertTrue(global.isEmpty()); + } + +} diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/VillageCommandTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/VillageCommandTest.java new file mode 100644 index 00000000..0b365d96 --- /dev/null +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/VillageCommandTest.java @@ -0,0 +1,67 @@ +package net.cyperia.challenges.plugin.spigot.command; + +import org.bukkit.Location; +import org.junit.jupiter.api.Test; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class VillageCommandTest { + + private static final int[] RADII = {100, 250, 500}; + + private final Queue ticks = new ArrayDeque<>(); + + private void runAllTicks() { + while (!ticks.isEmpty()) ticks.poll().run(); + } + + @Test + void searchesNothingBeforeTheFirstTick() { + List searched = new ArrayList<>(); + VillageCommand.searchRings(RADII, 0, radius -> { + searched.add(radius); + return null; + }, ticks::add, village -> { }, () -> { }); + assertTrue(searched.isEmpty()); + } + + @Test + void widensOneRingPerTickUntilFound() { + List searched = new ArrayList<>(); + Location found = new Location(null, 1, 2, 3); + List result = new ArrayList<>(); + VillageCommand.searchRings(RADII, 0, radius -> { + searched.add(radius); + return radius == 250 ? found : null; + }, ticks::add, result::add, () -> result.add(null)); + + ticks.poll().run(); + assertEquals(List.of(100), searched); + ticks.poll().run(); + assertEquals(List.of(100, 250), searched); + assertTrue(ticks.isEmpty()); + assertEquals(List.of(found), result); + } + + @Test + void reportsNoneAfterTheLastRing() { + List searched = new ArrayList<>(); + AtomicInteger none = new AtomicInteger(); + VillageCommand.searchRings(RADII, 0, radius -> { + searched.add(radius); + return null; + }, ticks::add, village -> { throw new AssertionError(); }, none::incrementAndGet); + + runAllTicks(); + assertEquals(List.of(100, 250, 500), searched); + assertEquals(1, none.get()); + } + +} diff --git a/plugin/src/test/java/net/cyperia/commons/bukkit/utils/misc/RegionsTest.java b/plugin/src/test/java/net/cyperia/commons/bukkit/utils/misc/RegionsTest.java index d2f855d6..ad5b6430 100644 --- a/plugin/src/test/java/net/cyperia/commons/bukkit/utils/misc/RegionsTest.java +++ b/plugin/src/test/java/net/cyperia/commons/bukkit/utils/misc/RegionsTest.java @@ -58,6 +58,7 @@ void mockServer() { @AfterEach void closeServer() { bukkit.close(); + Regions.regionized = () -> false; } @Test @@ -281,4 +282,49 @@ void forEachRegion_scansInlineWhenThePluginIsDisabledOnShutdown() { assertTrue(done.isDone()); } + + @Test + void remove_onlyMarksNonPersistentWhileARegionisedServerStops() { + Regions.regionized = () -> true; + bukkit.when(Bukkit::isStopping).thenReturn(true); + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(entity)).thenReturn(true); + + Regions.remove(plugin, entity); + + verify(entity).setPersistent(false); + verify(entity, never()).remove(); + } + + @Test + void remove_removesInlineWhileANonRegionisedServerStops() { + bukkit.when(Bukkit::isStopping).thenReturn(true); + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(entity)).thenReturn(true); + when(entity.isValid()).thenReturn(true); + + Regions.remove(plugin, entity); + + verify(entity).remove(); + } + + @Test + void remove_skipsAnEntityThatIsAlreadyGone() { + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(entity)).thenReturn(true); + when(entity.isValid()).thenReturn(false); + + Regions.remove(plugin, entity); + + verify(entity, never()).remove(); + } + + @Test + void remove_isScheduledOnTheEntityFromAnotherThread() { + Regions.regionized = () -> true; + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(entity)).thenReturn(false); + when(entityScheduler.execute(any(), any(), any(), anyLong())).thenReturn(true); + + Regions.remove(plugin, entity); + + verify(entityScheduler).execute(eq(plugin), any(), eq(null), eq(1L)); + verify(entity, never()).remove(); + } }