From 6487b5adcc6ae8fb6b09310420363fb8f313e23d Mon Sep 17 00:00:00 2001 From: Trilleo Date: Tue, 6 Oct 2026 15:37:07 +0800 Subject: [PATCH 1/3] Feature: Add resource regions to towns Parts of a town whose blocks grow back and whose spawners keep animals and monsters about, gathered only by the town's residents. Gathering is cleared at LOWEST and Towny's own refusal lifted through a one-tick permit, so residents of a town that denies them building, destroying and using can still gather, and nothing else. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 36 +++ CLAUDE.md | 28 +- README.md | 22 +- docs/DEVELOPER_GUIDE.md | 97 ++++++- .../net/trilleo/mc/plugins/tritown/Main.kt | 15 + .../commands/gathering/GatherCommand.kt | 210 ++++++++++++++ .../commands/gathering/ResourcesCommand.kt | 40 +++ .../tritown/config/GatheringSettings.kt | 59 ++++ .../mc/plugins/tritown/gathering/AreaCheck.kt | 45 +++ .../mc/plugins/tritown/gathering/Cuboid.kt | 71 +++++ .../plugins/tritown/gathering/GatherAccess.kt | 50 ++++ .../tritown/gathering/GatherCategory.kt | 47 +++ .../tritown/gathering/GatherEditors.kt | 127 ++++++++ .../tritown/gathering/GatherManager.kt | 274 ++++++++++++++++++ .../tritown/gathering/GatherNotices.kt | 58 ++++ .../tritown/gathering/GatherPermits.kt | 44 +++ .../plugins/tritown/gathering/GatherStats.kt | 29 ++ .../mc/plugins/tritown/gathering/Harvest.kt | 95 ++++++ .../mc/plugins/tritown/gathering/Regrowth.kt | 130 +++++++++ .../tritown/gathering/ResourceRegion.kt | 157 ++++++++++ .../mc/plugins/tritown/gathering/Spawners.kt | 161 ++++++++++ .../gathering/storage/JsonGatherStorage.kt | 100 +++++++ .../tritown/gathering/storage/StoredRegion.kt | 66 +++++ .../tritown/guis/gathering/GatherItemsGUI.kt | 193 ++++++++++++ .../tritown/guis/gathering/GatherListGUI.kt | 59 ++++ .../tritown/guis/gathering/GatherNodeGUI.kt | 223 ++++++++++++++ .../guis/gathering/GatherNodeListGUI.kt | 129 +++++++++ .../tritown/guis/gathering/GatherRegionGUI.kt | 198 +++++++++++++ .../tritown/guis/gathering/GatherRender.kt | 160 ++++++++++ .../guis/gathering/GatherSpawnerGUI.kt | 221 ++++++++++++++ .../guis/gathering/GatherSpawnerListGUI.kt | 142 +++++++++ .../tritown/guis/gathering/ResourcesGUI.kt | 102 +++++++ .../plugins/tritown/guis/menu/MainMenuGUI.kt | 10 +- .../gathering/GatherBlockListener.kt | 206 +++++++++++++ .../gathering/GatherEntityListener.kt | 105 +++++++ .../gathering/GatherTownyListener.kt | 69 +++++ .../listeners/gathering/GatherWandListener.kt | 70 +++++ .../mc/plugins/tritown/mobs/MobSetup.kt | 16 +- .../tritown/tasks/gathering/GatherSaveTask.kt | 24 ++ .../tritown/tasks/gathering/GatherTickTask.kt | 22 ++ src/main/resources/config.yml | 35 +++ src/main/resources/lang/en_US.yml | 224 ++++++++++++++ src/main/resources/lang/zh_CN.yml | 224 ++++++++++++++ 43 files changed, 4382 insertions(+), 11 deletions(-) create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/gathering/GatherCommand.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/gathering/ResourcesCommand.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/config/GatheringSettings.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/AreaCheck.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/Cuboid.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherAccess.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherCategory.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherEditors.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherManager.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherNotices.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherPermits.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherStats.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/Harvest.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/Regrowth.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/ResourceRegion.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/Spawners.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/storage/JsonGatherStorage.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/storage/StoredRegion.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherItemsGUI.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherListGUI.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherNodeGUI.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherNodeListGUI.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherRegionGUI.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherRender.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherSpawnerGUI.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherSpawnerListGUI.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/ResourcesGUI.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/gathering/GatherBlockListener.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/gathering/GatherEntityListener.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/gathering/GatherTownyListener.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/gathering/GatherWandListener.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/tasks/gathering/GatherSaveTask.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/tasks/gathering/GatherTickTask.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index f1b02ed..9e2f61d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,42 @@ ## Unreleased +### New Features + +#### Towns + ++ Added **resource regions**: parts of a town whose resources grow back on their own, and which only the town's + residents can gather. Made for a starter town that new players join. + + Mining, foraging, farming and excavation: ore turns to a stand-in block such as bedrock and comes back, trees + regrow, and crops are replanted as seedlings and grow through their stages. A crop can only be harvested ripe. + + Husbandry and combat: spawners keep animals or monsters about, replace those lost after a set time and keep them + from wandering off. Monsters can be given a level, and do not burn in daylight. + + Residents can gather even when the town denies them the right to build, destroy and use. Only the gathering itself + is allowed: they still cannot build, open anything or break a block that is not a ripe resource. + + Nothing in a region can be changed by anyone else either. Nothing grows, spreads, decays, burns, floods or + explodes there except through TriTown, and animals there cannot be led away, renamed or bred. + + Walking into a region shows its name and what can be gathered, or why you cannot gather there. ++ Resource regions are set up in game by administrators with `/tritown gather`. + + Draw a region with the wand (`/tritown gather wand`) inside one town's land, then `/tritown gather create `. + + Add a resource by clicking a block, or a seed for a crop, in your own inventory: every block of that kind in the + region becomes one. Set how long it takes to grow back, what stands in for it meanwhile, whether it keeps its + vanilla drops, extra drops with their own chances, and what it may grow back as by weight, for an ore vein that is + different every time. + + Add a spawner by standing where it belongs and clicking a spawn egg. Set how many mobs it keeps, how quickly it + replaces them, how far they roam and how strong its monsters are. + + Rename, close, resize, outline and regrow regions from the editor. `/tritown gather build` lets you change a + region freely without anything counting as a harvest. + + Harvested blocks keep growing back across restarts. Deleting a region, or the town it belongs to, grows everything + back first and removes its mobs. ++ Players see their town's resource regions, and a tally of what they have gathered in each category, from the new + **Resource Regions** button in the main menu or with `/tritown resources`. + +### Technical Details + +#### Combat + ++ `MobSetup.spawn` takes a `prepare` callback that runs before the mob joins the world. + ## Version 1.5.0 ### New Features diff --git a/CLAUDE.md b/CLAUDE.md index 224f557..51e3411 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -68,7 +68,7 @@ The server console reads commands from the terminal running Gradle. src/main/kotlin/net/trilleo/mc/plugins/tritown/ ├── Main.kt # Plugin entry point (Main.instance, Main.reload()) ├── commands/ # Sub-commands (auto-registered) -│ ├── admin/ adventure/ economy/ info/ items/ menu/ mobs/ +│ ├── admin/ adventure/ economy/ gathering/ info/ items/ menu/ mobs/ │ └── moderation/ news/ protection/ scoreboard/ shop/ storage/ trade/ ├── combat/ # Combat: stats, DamageMath, the health lens, the HUD, indicators (not scanned) ├── config/ # PluginConfig (typed config.yml wrapper), EconomySettings @@ -77,9 +77,11 @@ src/main/kotlin/net/trilleo/mc/plugins/tritown/ ├── economy/ # The economy: ledger, accounts, currencies, Vault provider, statistics, │ # storage (not scanned) ├── enums/ # AccountType, FlowCategory, StatsWindow, TransactionType, FillMode, … +├── gathering/ # Resource regions: nodes that grow back, spawners, Towny permits, storage (not scanned) ├── gear/ # Gear: its data, stats, drawing and refreshing, the Forge and its costs (not scanned) ├── guis/ # GUIs (auto-registered, extend PluginGUI / PagedPluginGUI); admin/ is the panel, -│ # menu/ the main menu, news/ the news, forge/ the Forge, bestiary/ the bestiary; +│ # menu/ the main menu, news/ the news, forge/ the Forge, bestiary/ the bestiary, +│ # gathering/ the region editor and the players' Resource Regions menu; │ # ConfirmGUI asks before the irreversible ├── items/ # Custom items (auto-registered, extend PluginItem) ├── listeners/ # Event listeners, including Towny events (auto-registered) @@ -110,7 +112,7 @@ src/main/resources/ The plugin uses `PackageScanner` to discover components at startup — you **never** edit `plugin.yml` or wire things manually. Just extend the right base class and place the file in the correct package. Packages outside the table below are never scanned, which is why the economy core lives in `economy/`, the shop core in `shops/`, the trade core -in `trades/`, the storage core in `storage/` and the news core in `news/`: each has to be alive before the registrars build the commands and menus that read it. `menu/` is outside +in `trades/`, the storage core in `storage/`, the news core in `news/` and resource regions in `gathering/`: each has to be alive before the registrars build the commands and menus that read it. `menu/` is outside the scan for a simpler reason: `MenuItem` is not a `PluginItem`, because it is named in each holder's language. | Component | Base Class | Package | @@ -360,6 +362,26 @@ The main menu (`guis/menu`) is how players reach TriTown, opened from the menu i `NewsRender.material`. - **Every editor click re-checks `tritown.news.manage`**, not only the command that opened the menu. +## Working with Resource Regions + +**Parts of a town whose resources grow back, gathered only by its residents.** See +[Resource Regions](docs/DEVELOPER_GUIDE.md#resource-regions). + +- **Go through `GatherManager`** — it is the only thing that reads or writes a region or a harvested block. `save()` + after editing a region in place; harvested blocks are flushed by `GatherSaveTask`. +- **Gathering overrides Towny only through a permit.** Decide at `LOWEST`, cancel what is refused, and leave a + `GatherPermits.grant` for what is allowed; `GatherTownyListener` lifts Towny's refusal only where a permit matches. + Never un-cancel a Towny event, or a Bukkit event Towny cancelled, without one, and never lift building: a starter + town's residents must still be unable to build, destroy or use anything that is not gathering. +- **Ask `GatherAccess.refusal`** before anyone gathers. It re-reads Towny on every call; a region keeps only its town's + UUID. +- **A region is held still.** Anything new that could change a block inside one — a mechanic, a mob, an item — must be + refused in `GatherBlockListener` unless it is a harvest, and anything that grows there grows through `Regrowth`. +- **Never overwrite a rebuilt spot.** A harvested block is only put back while the stand-in TriTown left is still there. +- **Spawner mobs are recognised by their PDC tag**, through `Spawners`, and are never eligible for loot. A new + husbandry or combat interaction goes in `GatherEntityListener` with its own permit. +- **Every editor click re-checks `tritown.gather.admin.edit`**, not only the command that opened the menu. + ## Working with Combat **Fights with mobs are in RPG numbers; fights between players are vanilla.** See [Combat](docs/DEVELOPER_GUIDE.md#combat). diff --git a/README.md b/README.md index 6a41cd9..07cc062 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ TriTown is in early development; see the [change log](CHANGELOG.md) for what has **A menu in every hotbar.** Every player carries a glowing item in the last slot of their hotbar; right-click it, or run `/tt menu`, for everything TriTown offers in one place. Your profile sits at the top — balance, founding credit, -leaderboard rank, town and nation — and below it are your town at a glance with a shortcut into +leaderboard rank, town and nation — beside it your town's resource regions, when it has any, and below it are your town at a glance with a shortcut into [TownyMenu](https://github.com/Trilleo/TownyMenu), your storage, the global shop, a list of the players near enough to trade with (anyone waiting for your answer first), a list of players to pay, the richest players as heads, the server's vital signs, the Forge, the server news, your bestiary, a sidebar switch, and the admin panel for those allowed it. Anything switched off on the server, or that you may not @@ -33,6 +33,16 @@ starting balance. Only founding a town with `/t new` can spend it: TriTown takes new player who spends their balance by mistake can still found a town. Joining someone else's town gives it up, and `/balance` shows it while you hold it. +**Resource regions in town.** Mark out part of a town — a mine, a farm, a wood, animal pens, a monster arena — and +its resources grow back on their own. Ore turns to bedrock when mined and returns, crops are replanted and grow through +their stages, trees regrow, and spawners keep animals and monsters about. Only the town's residents can gather there, +and they can even when the town denies them building, destroying and using everywhere else, which suits a starter town +new players join. Nothing else in a region can be changed by anyone, and nothing grows, burns or explodes there except +through TriTown. Everything is set up in game: draw the region with a wand, then click blocks, seeds and spawn eggs in +your inventory to add resources and spawners, and set each one's regrow time, the block that stands in while it is gone, +extra drops with their chances, and — for an ore vein that is different every time — what it may grow back as. +Players find their town's regions from the main menu or `/tt resources`, along with a tally of what they have gathered. + **A sidebar that follows you.** A scoreboard that changes with where you are standing: a new player without a town is pointed at joining one, your own claims show your town's level, residents, land, bank, upkeep and any warning, another town's claims show whose land it is and what the plot costs, and enemy territory says so. Values sit under headings that @@ -168,6 +178,8 @@ itself, are still anyone's. | `/tt mob ` | Inspect mob levels and the balance (OP only) | | `/tt item ` | Hand out the server's own items and gear (OP only) | | `/tt forge` | Craft gear, and upgrade, refine, reforge or salvage it | +| `/tt resources` | See your town's resource regions and what you have gathered | +| `/tt gather …` | Set up resource regions (OP only) | `/eco` takes `give`, `take` and `set` (` [currency]`), `reset ` back to the starting balance, `info ` for an account's details, `history [player]` to browse recorded transactions in a menu, and `flush` to @@ -281,6 +293,14 @@ version stays available as `/tritown:balance` and so on. | `mobs.nameplates` | `true` | Show a levelled mob's level and health when a player looks at it | | `mobs.ranks.exempt` | bosses | Kinds of mob that never spawn as elites or champions | | `towns.founding-credit` | `100.0` | Credit only `/t new` can spend, given once to players without a town; `0` is off | +| `gathering.enabled` | `true` | Turn resource regions off entirely | +| `gathering.max-volume` | `250000` | The most blocks one region may cover | +| `gathering.default-regrow-seconds` | `60` | How long a newly added resource takes to grow back | +| `gathering.depleted-blocks.` | `BEDROCK` / `AIR` | What stands in for a harvested block, per category, unless the resource sets one | +| `gathering.spawner-range` | `48` | How close a player has to be for a spawner to call up mobs | +| `gathering.effects` | `true` | Particles and a chime when a block grows back | +| `gathering.entry-titles` | `true` | Show a region's name when a player walks in | +| `gathering.save-interval` | `60` | Seconds between writing harvested blocks to disk | | `news.enabled` | `true` | Turn the server news off entirely | | `news.join-message.enabled` | `true` | List a player's unread posts a moment after they join | | `news.join-message.delay-seconds` | `3` | How long after joining | diff --git a/docs/DEVELOPER_GUIDE.md b/docs/DEVELOPER_GUIDE.md index 0abf285..a0ee763 100644 --- a/docs/DEVELOPER_GUIDE.md +++ b/docs/DEVELOPER_GUIDE.md @@ -2,7 +2,7 @@ This guide explains how to create **commands**, **listeners**, **GUIs**, **tasks**, **custom items**, **recipes**, work with **translations** and the **configuration** system using TriTown's registration system, and how to build on -**Towny**, the **Vault economy**, the **admin panel**, **shops**, **player trades**, **personal storage**, **item protection**, the **news**, **combat** and the **sidebar**. Commands, listeners, GUIs, tasks, custom items, and recipes all +**Towny**, the **Vault economy**, the **admin panel**, **shops**, **player trades**, **personal storage**, **item protection**, the **news**, **resource regions**, **combat** and the **sidebar**. Commands, listeners, GUIs, tasks, custom items, and recipes all follow the same pattern: extend a base class (or implement an interface), place the file in the correct package, and the plugin handles the rest automatically at startup. The configuration system provides typed access to `config.yml` values. @@ -3386,6 +3386,97 @@ checks on each click as well as the command. `NewsSettings` is a snapshot swapped in whole on a reload. The posts themselves are never re-read on a reload; every change to them is already on disk. +## Resource Regions + +Parts of a town whose resources grow back, which only the town's residents may gather. An administrator draws a box +with the wand, and sets up in game which blocks are resources and which mobs the region keeps; nothing about a region +lives in `config.yml`, whose `gathering` block only sets the rules. + +The core lives under `gathering/`, which is **not a scanned package**: `GatherManager` has to be loaded before the main +menu asks whether the viewer's town has a region. The menus are in `guis/gathering/`, the commands in +`commands/gathering/` (`/tritown gather` for administrators, `/tritown resources` for players), the listeners in +`listeners/gathering/`, and the tasks in `tasks/gathering/`. + +### The model + +| Type | What it is | +|:------------------|:-----------------------------------------------------------------------------------------------| +| `ResourceRegion` | A box (`Cuboid`) in one town, its name, whether it is open, its nodes and its spawners | +| `ResourceNode` | A kind of block that grows back: category, regrow time, stand-in block, drops, regrowth pool | +| `ResourceSpawner` | A spot that keeps up to N mobs of one type about, replacing them after a delay | +| `DepletedNode` | A harvested block waiting to grow back: what it was, what was put in its place, and when | +| `GatherCategory` | Mining, foraging, farming, excavation (blocks); husbandry, combat (spawners) | +| `GatherManager` | Every region and every harvested block, and the only thing that reads or writes either | +| `GatherAccess` | Who may gather where: the owning town's residents, on land the town still owns | +| `GatherPermits` | The one gathering action each player is cleared for this tick (see below) | +| `Harvest` | Deciding a break and, once every plugin has had its say, carrying it out | +| `Regrowth` | Putting a stand-in down, growing crops through their stages, and putting the block back | +| `Spawners` | The mobs each spawner keeps, recognised by a PDC tag so they survive a restart | +| `GatherEditors` | The wand, each administrator's selection, building mode, and particle outlines | +| `AreaCheck` | Whether a box can be a region: small enough, clear of others, inside one town's land | + +A node is a *kind* of block, not a position: every block of that kind inside the region is one, so an administrator +builds a mine out of ore and adds one rule. A crop (`ResourceNode.isStaged`) is only ripe at its last stage and is put +back as a seedling; anything else is replaced by its stand-in — the node's own `depleted` block, or the category's from +`gathering.depleted-blocks`. A column plant (sugar cane, cactus, bamboo) takes the same plant stacked above it along, +since the game breaks those too. Growing back never overwrites a rebuilt spot: if the block is no longer the stand-in +TriTown left, the record is dropped. + +### Gathering against Towny's permissions + +A starter town usually denies its residents the right to build, destroy and use. Gathering must work anyway, without +handing those rights out, so the decision is made before Towny's: + +1. A `LOWEST` handler (`GatherBlockListener.onBreak`, `GatherEntityListener.onHit`/`onInteract`) decides. A refused + action is cancelled there, and Towny — whose handlers ignore cancelled events — never sees it. +2. An approved action leaves a **permit** in `GatherPermits` for that player, that block and that tick. +3. Towny then fires its own `TownyDestroyEvent`, `TownyItemuseEvent` or `TownySwitchEvent`. + `GatherTownyListener` lifts the refusal only where a permit matches, and suppresses Towny's message. + +Every other action Towny judges as it always would. Building is never lifted. A new way to gather — a right-click +harvest, fishing — needs its own `LOWEST` decision and permit; never un-cancel a Towny event without one. + +`GatherTownyListener` also cancels Towny's `MobSpawnRemovalEvent` and `MobRemovalEvent` for spawner mobs, so a town +with mobs switched off keeps its arena, and deletes a town's regions when Towny deletes the town. + +### Protection inside a region + +`GatherBlockListener` keeps a region exactly as it was built: nothing may be placed, poured, tilled, stripped, +fertilised or trampled, and growth, spread, fading, forming, leaf decay, fire, liquids flowing in, pistons and +explosions are all held still — TriTown does the growing. An administrator in building mode (`/tritown gather build`) +is left to Towny alone, and breaking a harvested spot in building mode forgets it. + +Spawner mobs (`GatherEntityListener`) may only be hurt, sheared or milked by gatherers; they cannot be leashed, +renamed or bred, do not burn in daylight or transform, and are walked back when they stray. A hostile spawner mob is +called up through `MobSetup.spawn` with its level, and is never eligible for loot, so a spawner is never a new faucet. + +### Storage + +`JsonGatherStorage` keeps two files under `/gathering/`, both written through `AtomicFile`: + +- `regions.json` — the definitions, written the moment one is edited (`GatherManager.save()`). If neither it nor its + backup can be read, `GatherManager.isReady` stays false and the feature switches itself off rather than start empty. +- `depleted.json` — the harvested blocks, flushed by `GatherSaveTask` and once more at shutdown, so a restart picks + every one back up. Losing it only leaves those blocks as their stand-ins until an administrator runs + `/tritown gather regrow`. + +Items (extra drops) are stored with `ItemCodec`, the same way shop entries are. + +### Ticking + +`GatherTickTask` runs every second on the server thread: `Regrowth.tick` puts back what is due and steps crops on a +stage, `Spawners.tick` stocks every spawner within `spawner-range` of a player, and `GatherNotices.tick` shows a title to +anyone who walked into a region. Nothing in an unloaded chunk is touched; it waits for the chunk to load. + +### Rules + +- **Go through `GatherManager`** for every region and harvested block; `save()` after editing a region in place. +- **Ask `GatherAccess.refusal`** before letting anyone gather. It re-reads Towny every time. +- **Never cache a town's name or claims** — a region keeps only the town's UUID. +- **Spawner mobs are recognised by their tag**, never by their type or position. Count them through `Spawners`. +- **Every editor click re-checks `tritown.gather.admin.edit`**, not only the command that opened the menu. +- **A region's name is administrator-written MiniMessage**, embedded as written, like a shop's. + ## Combat Fights with mobs happen in RPG numbers: players and mobs have health pools in the hundreds and thousands, and hits come @@ -3557,7 +3648,9 @@ has just decided about. - **Transformations keep the kind only if it still fits.** A drowned Gravewalker is an ordinary drowned at the same level, and a split never keeps a kind. - **Summoned minions share their summoner's kind**, through `MobSetup.spawn`, which is also what - `/tritown mob spawn [level]` uses. Neither is ever eligible for loot. `mob kinds` lists them all. + `/tritown mob spawn [level]` uses. Neither is ever eligible for loot. `mob kinds` lists them all. Its + `prepare` callback runs before the mob joins the world, so a tag it sets — a resource spawner's — is already there + when other plugins, Towny among them, see the spawn. ### Abilities diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/Main.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/Main.kt index f7c0dec..8e85826 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/Main.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/Main.kt @@ -16,6 +16,9 @@ import net.trilleo.mc.plugins.tritown.economy.storage.JsonPulseStorage import net.trilleo.mc.plugins.tritown.economy.vault.TriTownVaultEconomy import net.trilleo.mc.plugins.tritown.economy.vault.VaultRegistration import net.trilleo.mc.plugins.tritown.enums.ProviderMode +import net.trilleo.mc.plugins.tritown.gathering.GatherManager +import net.trilleo.mc.plugins.tritown.gathering.Spawners +import net.trilleo.mc.plugins.tritown.gathering.storage.JsonGatherStorage import net.trilleo.mc.plugins.tritown.guis.storage.StorageGUI import net.trilleo.mc.plugins.tritown.menu.MenuItem import net.trilleo.mc.plugins.tritown.mobs.ActiveMobs @@ -133,6 +136,14 @@ class Main : JavaPlugin() { NewsSettings.load(pluginConfig, logger) NewsManager.start(JsonNewsStorage(dataFolder, logger), logger) + // Before the registrars, like the shops: the main menu asks whether the viewer's town has a region. + GatheringSettings.load(pluginConfig) + if (GatheringSettings.snapshot.enabled) { + GatherManager.start(JsonGatherStorage(dataFolder, logger), logger) + // The worlds loaded before TriTown did, so their spawner mobs never reached the listener. + server.worlds.forEach { world -> world.entities.forEach(Spawners::adopt) } + } + ItemRegistrar.registerAll(this) RecipeRegistrar.registerAll(this) @@ -194,6 +205,8 @@ class Main : JavaPlugin() { StorageSettings.load(pluginConfig) // Only the settings, as with the shops: every change to a post is already on disk. NewsSettings.load(pluginConfig, logger) + // Only the settings, as with the shops: every change to a region is already on disk. + GatheringSettings.load(pluginConfig) // The material may have changed, or the item been switched off. MainMenuSettings.load(pluginConfig, logger) @@ -224,6 +237,8 @@ class Main : JavaPlugin() { server.onlinePlayers.forEach(SpeedSync::clear) ShopManager.shutdown() + // After the tasks, so the last write of harvested blocks cannot race the flush task. + GatherManager.shutdown() PlayerDataManager.saveAll() ServerDataManager.save() diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/gathering/GatherCommand.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/gathering/GatherCommand.kt new file mode 100644 index 0000000..e672b02 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/gathering/GatherCommand.kt @@ -0,0 +1,210 @@ +package net.trilleo.mc.plugins.tritown.commands.gathering + +import net.trilleo.mc.plugins.tritown.gathering.* +import net.trilleo.mc.plugins.tritown.guis.gathering.GatherListGUI +import net.trilleo.mc.plugins.tritown.guis.gathering.GatherRegionGUI +import net.trilleo.mc.plugins.tritown.guis.gathering.GatherRender +import net.trilleo.mc.plugins.tritown.registration.PluginCommand +import net.trilleo.mc.plugins.tritown.utils.InventoryUtil +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player + +/** + * Draws resource regions and opens their editor. + * + * What a region grows and spawns is set up in the menus; this covers what a + * menu cannot — the wand, creating and deleting a region, and building inside + * one. + */ +class GatherCommand : PluginCommand( + name = "gather", + description = "Set up resource regions", + usage = "/tritown gather ", + permission = GatherEditors.ADMIN_PERMISSION, +) { + + override val extraPermissions = + ACTIONS.map { permissionFor(it) } + GatherRender.EDIT_PERMISSION + GatherAccess.BYPASS_PERMISSION + + override fun execute(sender: CommandSender, args: Array): Boolean { + if (!GatherManager.isReady) { + sender.sendPrefixed(sender.tr("command.gather.unavailable")) + return true + } + + val action = args.firstOrNull()?.lowercase() + if (action == null || action !in ACTIONS) { + sendUsage(sender) + return true + } + + if (!sender.hasPermission(permissionFor(action))) { + sender.sendPrefixed(sender.tr("command.gather.no-permission-action", "action" to action)) + return true + } + + val player = sender as? Player ?: run { + if (action == "delete" || action == "regrow") { + run(sender, action, args) + } else { + sender.sendPrefixed(sender.tr("command.gather.players-only")) + } + return true + } + + run(player, action, args) + return true + } + + override fun tabComplete(sender: CommandSender, args: Array): List = when (args.size) { + 1 -> ACTIONS.filter { sender.hasPermission(permissionFor(it)) && it.startsWith(args[0], ignoreCase = true) } + 2 -> when (args[0].lowercase()) { + "edit", "delete", "show", "regrow" -> GatherManager.ids().filter { it.startsWith(args[1], ignoreCase = true) } + else -> emptyList() + } + + 3 -> if (args[0].equals("delete", ignoreCase = true)) { + listOf(CONFIRM).filter { it.startsWith(args[2], ignoreCase = true) } + } else emptyList() + + else -> emptyList() + } + + private fun run(sender: CommandSender, action: String, args: Array) { + when (action) { + "list" -> GatherListGUI.show(sender as Player) + "wand" -> wand(sender as Player) + "create" -> create(sender as Player, args) + "edit" -> edit(sender as Player, args) + "delete" -> delete(sender, args) + "build" -> build(sender as Player) + "show" -> show(sender as Player, args) + "regrow" -> regrow(sender, args) + } + } + + // ── Actions ───────────────────────────────────────────────────────── + + private fun wand(player: Player) { + InventoryUtil.give(player, listOf(GatherEditors.wand())) + player.sendPrefixed(player.tr("command.gather.wand")) + } + + private fun create(player: Player, args: Array) { + val id = args.getOrNull(1)?.lowercase() + if (id == null) { + player.sendPrefixed(player.tr("command.gather.usage.create")) + return + } + if (!ResourceRegion.isValidId(id) || GatherManager.get(id) != null) { + player.sendPrefixed(player.tr("command.gather.create-failed", "id" to id)) + return + } + + val area = GatherEditors.selection(player).area() + val result = AreaCheck.check(area) + if (result !is AreaCheck.Result.Ok) { + player.sendPrefixed(AreaCheck.message(player, result)) + return + } + + val name = args.drop(2).joinToString(" ").ifBlank { id } + val region = GatherManager.create(id, name, area!!, result.townId) ?: run { + player.sendPrefixed(player.tr("command.gather.create-failed", "id" to id)) + return + } + + player.sendPrefixed( + player.tr("command.gather.created", "id" to region.id, "town" to GatherAccess.townName(player, region)) + ) + GatherRegionGUI.show(player, region) + } + + /** Opens the region named, or the one the player is standing in. */ + private fun edit(player: Player, args: Array) { + val region = args.getOrNull(1)?.let { resolve(player, it) ?: return } ?: GatherManager.at(player.location) + if (region == null) { + player.sendPrefixed(player.tr("command.gather.not-in-region")) + return + } + GatherRegionGUI.show(player, region) + } + + /** + * Deletes a region once the word is typed out. Everything it harvested is + * grown back first, and its spawners' mobs taken away, so the ground is + * left as it was built. + */ + private fun delete(sender: CommandSender, args: Array) { + val region = resolve(sender, args.getOrNull(1) ?: return sendUsage(sender)) ?: return + + if (!args.getOrNull(2).equals(CONFIRM, ignoreCase = true)) { + sender.sendPrefixed(sender.tr("command.gather.delete-confirm", "id" to region.id)) + return + } + + Spawners.clear(region) + GatherManager.delete(region.id) + sender.sendPrefixed(sender.tr("command.gather.deleted", "id" to region.id)) + } + + private fun build(player: Player) { + val building = GatherEditors.toggleBuilding(player) + player.sendPrefixed(player.tr(if (building) "command.gather.build-on" else "command.gather.build-off")) + } + + private fun show(player: Player, args: Array) { + val region = args.getOrNull(1)?.let { resolve(player, it) ?: return } ?: GatherManager.at(player.location) + val area = region?.area ?: GatherEditors.selection(player).area() + if (area == null) { + player.sendPrefixed(player.tr("command.gather.not-in-region")) + return + } + GatherEditors.outline(player, area, OUTLINE_SECONDS) + player.sendPrefixed(player.tr("gathering.editor.outlined", "seconds" to OUTLINE_SECONDS)) + } + + private fun regrow(sender: CommandSender, args: Array) { + val region = resolve(sender, args.getOrNull(1) ?: return sendUsage(sender)) ?: return + val count = Regrowth.regrowAll(region) + sender.sendPrefixed(sender.tr("gathering.editor.regrown", "amount" to count)) + } + + // ── Helpers ───────────────────────────────────────────────────────── + + private fun resolve(sender: CommandSender, id: String): ResourceRegion? { + val region = GatherManager.get(id) + if (region == null) sender.sendPrefixed(sender.tr("command.gather.unknown", "id" to id)) + return region + } + + private fun sendUsage(sender: CommandSender) { + sender.sendPrefixed(sender.tr("command.gather.usage.header")) + for (action in ACTIONS) { + if (sender.hasPermission(permissionFor(action))) sender.sendPrefixed(usageFor(sender, action)) + } + } + + /** Spelled out rather than built from the action, so every line is a key the translation test can see. */ + private fun usageFor(sender: CommandSender, action: String): String = when (action) { + "list" -> sender.tr("command.gather.usage.list") + "wand" -> sender.tr("command.gather.usage.wand") + "create" -> sender.tr("command.gather.usage.create") + "edit" -> sender.tr("command.gather.usage.edit") + "delete" -> sender.tr("command.gather.usage.delete") + "build" -> sender.tr("command.gather.usage.build") + "show" -> sender.tr("command.gather.usage.show") + else -> sender.tr("command.gather.usage.regrow") + } + + private companion object { + const val CONFIRM = "confirm" + const val OUTLINE_SECONDS = 15 + + val ACTIONS = listOf("list", "wand", "create", "edit", "delete", "build", "show", "regrow") + + fun permissionFor(action: String): String = "${GatherEditors.ADMIN_PERMISSION}.$action" + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/gathering/ResourcesCommand.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/gathering/ResourcesCommand.kt new file mode 100644 index 0000000..65e1826 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/gathering/ResourcesCommand.kt @@ -0,0 +1,40 @@ +package net.trilleo.mc.plugins.tritown.commands.gathering + +import net.trilleo.mc.plugins.tritown.gathering.GatherManager +import net.trilleo.mc.plugins.tritown.guis.gathering.ResourcesGUI +import net.trilleo.mc.plugins.tritown.registration.PluginCommand +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player + +/** + * Lists the resource regions of the player's town, and what they have gathered. + * + * No permission, like `/tritown menu`: what a player sees is already limited + * to their own town. + */ +class ResourcesCommand : PluginCommand( + name = "resources", + description = "See your town's resource regions", + usage = "/tritown resources", +) { + + override fun execute(sender: CommandSender, args: Array): Boolean { + val player = sender as? Player ?: run { + sender.sendPrefixed(sender.tr("command.resources.players-only")) + return true + } + if (!GatherManager.isReady) { + player.sendPrefixed(player.tr("command.gather.unavailable")) + return true + } + if (!ResourcesGUI.hasRegions(player)) { + player.sendPrefixed(player.tr("command.resources.none")) + return true + } + + ResourcesGUI.show(player) + return true + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/GatheringSettings.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/GatheringSettings.kt new file mode 100644 index 0000000..e5f4def --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/GatheringSettings.kt @@ -0,0 +1,59 @@ +package net.trilleo.mc.plugins.tritown.config + +import net.trilleo.mc.plugins.tritown.gathering.GatherCategory +import org.bukkit.Material + +/** + * An immutable snapshot of the `gathering` block of `config.yml`. + * + * @param enabled whether resource regions exist at all + * @param maxVolume the most blocks one region may cover + * @param defaultRegrow seconds a new resource takes to grow back + * @param depleted what stands in for a harvested block, per block category + * @param spawnerRange how close a player has to be for a spawner to call up mobs + * @param effects whether a node growing back shows particles and plays a sound + * @param entryTitles whether walking into a region shows its name + * @param saveSeconds seconds between writing harvested blocks to disk + */ +data class GatheringSettings( + val enabled: Boolean, + val maxVolume: Long, + val defaultRegrow: Int, + val depleted: Map, + val spawnerRange: Double, + val effects: Boolean, + val entryTitles: Boolean, + val saveSeconds: Long, +) { + + /** The block a harvested node of [category] leaves behind when its rule names none. */ + fun depletedFor(category: GatherCategory): Material = depleted[category] ?: Material.BEDROCK + + companion object { + + @Volatile + private var current: GatheringSettings? = null + + val snapshot: GatheringSettings + get() = current ?: error("Gathering settings have not been loaded yet") + + val isLoaded: Boolean + get() = current != null + + fun load(config: PluginConfig): GatheringSettings = read(config).also { current = it } + + private fun read(config: PluginConfig): GatheringSettings = GatheringSettings( + enabled = config.getBoolean("gathering.enabled", true), + maxVolume = config.getLong("gathering.max-volume", 250_000L).coerceAtLeast(1L), + defaultRegrow = config.getInt("gathering.default-regrow-seconds", 60).coerceIn(1, 86_400), + depleted = GatherCategory.entries.filter { it.forBlocks }.associateWith { category -> + val name = config.getString("gathering.depleted-blocks.${category.name.lowercase()}", "BEDROCK") + Material.matchMaterial(name)?.takeIf { it.isBlock } ?: Material.BEDROCK + }, + spawnerRange = config.getDouble("gathering.spawner-range", 48.0).coerceIn(8.0, 256.0), + effects = config.getBoolean("gathering.effects", true), + entryTitles = config.getBoolean("gathering.entry-titles", true), + saveSeconds = config.getLong("gathering.save-interval", 60L).coerceIn(5L, 3600L), + ) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/AreaCheck.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/AreaCheck.kt new file mode 100644 index 0000000..c1226dc --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/AreaCheck.kt @@ -0,0 +1,45 @@ +package net.trilleo.mc.plugins.tritown.gathering + +import com.palmergames.bukkit.towny.TownyAPI +import net.trilleo.mc.plugins.tritown.config.GatheringSettings +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.command.CommandSender +import java.util.* + +/** + * Whether a box an administrator drew can be a region: small enough, clear of + * every other region, and owned — at its four corners and its middle — by a + * single town, which becomes the region's. + */ +object AreaCheck { + + sealed interface Result { + data class Ok(val townId: UUID) : Result + data object NoSelection : Result + data class TooLarge(val volume: Long, val max: Long) : Result + data object NotOneTown : Result + data class Overlaps(val id: String) : Result + } + + fun check(area: Cuboid?, except: String? = null): Result { + area ?: return Result.NoSelection + val world = area.bukkitWorld() ?: return Result.NoSelection + + val max = GatheringSettings.snapshot.maxVolume + if (area.volume > max) return Result.TooLarge(area.volume, max) + + GatherManager.overlapping(area, except)?.let { return Result.Overlaps(it.id) } + + val towns = area.footprint(world).map { TownyAPI.getInstance().getTown(it)?.uuid }.toSet() + val town = towns.singleOrNull() ?: return Result.NotOneTown + return Result.Ok(town) + } + + fun message(sender: CommandSender, result: Result): String = when (result) { + is Result.Ok -> "" + Result.NoSelection -> sender.tr("gathering.area.no-selection") + is Result.TooLarge -> sender.tr("gathering.area.too-large", "volume" to result.volume, "max" to result.max) + Result.NotOneTown -> sender.tr("gathering.area.not-town") + is Result.Overlaps -> sender.tr("gathering.area.overlaps", "id" to result.id) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/Cuboid.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/Cuboid.kt new file mode 100644 index 0000000..3e9359c --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/Cuboid.kt @@ -0,0 +1,71 @@ +package net.trilleo.mc.plugins.tritown.gathering + +import org.bukkit.Bukkit +import org.bukkit.Location +import org.bukkit.World +import org.bukkit.block.Block + +/** A box of whole blocks in one world, both corners included. */ +data class Cuboid( + val world: String, + val minX: Int, + val minY: Int, + val minZ: Int, + val maxX: Int, + val maxY: Int, + val maxZ: Int, +) { + + val volume: Long + get() = (maxX - minX + 1).toLong() * (maxY - minY + 1) * (maxZ - minZ + 1) + + fun bukkitWorld(): World? = Bukkit.getWorld(world) + + fun contains(world: String, x: Int, y: Int, z: Int): Boolean = + world == this.world && x in minX..maxX && y in minY..maxY && z in minZ..maxZ + + fun contains(block: Block): Boolean = contains(block.world.name, block.x, block.y, block.z) + + fun contains(location: Location): Boolean = + contains(location.world.name, location.blockX, location.blockY, location.blockZ) + + fun overlaps(other: Cuboid): Boolean = + world == other.world && + minX <= other.maxX && maxX >= other.minX && + minY <= other.maxY && maxY >= other.minY && + minZ <= other.maxZ && maxZ >= other.minZ + + /** The middle of the box at its floor, which is where a region is said to be. */ + fun center(world: World): Location = + Location(world, (minX + maxX) / 2.0 + 0.5, minY.toDouble(), (minZ + maxZ) / 2.0 + 0.5) + + /** The four corner columns and the middle, at the floor: the spots a town has to own. */ + fun footprint(world: World): List = listOf( + Location(world, minX.toDouble(), minY.toDouble(), minZ.toDouble()), + Location(world, maxX.toDouble(), minY.toDouble(), minZ.toDouble()), + Location(world, minX.toDouble(), minY.toDouble(), maxZ.toDouble()), + Location(world, maxX.toDouble(), minY.toDouble(), maxZ.toDouble()), + center(world), + ) + + companion object { + fun of(a: Location, b: Location): Cuboid = Cuboid( + world = a.world.name, + minX = minOf(a.blockX, b.blockX), minY = minOf(a.blockY, b.blockY), minZ = minOf(a.blockZ, b.blockZ), + maxX = maxOf(a.blockX, b.blockX), maxY = maxOf(a.blockY, b.blockY), maxZ = maxOf(a.blockZ, b.blockZ), + ) + } +} + +/** One block's address, for keying what has been harvested. */ +data class BlockKey(val world: String, val x: Int, val y: Int, val z: Int) { + + fun block(): Block? = Bukkit.getWorld(world)?.getBlockAt(x, y, z) + + fun isLoaded(): Boolean = Bukkit.getWorld(world)?.isChunkLoaded(x shr 4, z shr 4) == true + + companion object { + fun of(block: Block) = BlockKey(block.world.name, block.x, block.y, block.z) + fun of(location: Location) = BlockKey(location.world.name, location.blockX, location.blockY, location.blockZ) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherAccess.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherAccess.kt new file mode 100644 index 0000000..e189b05 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherAccess.kt @@ -0,0 +1,50 @@ +package net.trilleo.mc.plugins.tritown.gathering + +import com.palmergames.bukkit.towny.TownyAPI +import net.trilleo.mc.plugins.tritown.protection.Protection +import net.trilleo.mc.plugins.tritown.utils.TownyUtil +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Location +import org.bukkit.entity.Player + +/** + * Who may gather in a region: the residents of the town that owns it, on + * ground the town still owns. + * + * Towny is asked afresh every time, so a player who leaves the town, or a claim + * the town gives up, stops gathering on the spot. + */ +object GatherAccess { + + /** Gathering in any region, whatever town the player belongs to. */ + const val BYPASS_PERMISSION = "tritown.gather.bypass" + + /** Why a player may not gather somewhere. */ + enum class Refusal { CLOSED, NOT_RESIDENT, UNCLAIMED } + + /** Why [player] may not gather in [region] at [at], or `null` when they may. */ + fun refusal(player: Player, region: ResourceRegion, at: Location): Refusal? { + if (!region.enabled) return Refusal.CLOSED + if (TownyAPI.getInstance().getTown(at)?.uuid != region.townId) return Refusal.UNCLAIMED + if (player.hasPermission(BYPASS_PERMISSION) || isResident(player, region)) return null + return Refusal.NOT_RESIDENT + } + + fun isResident(player: Player, region: ResourceRegion): Boolean = + TownyAPI.getInstance().getResident(player)?.townOrNull?.uuid == region.townId + + /** The name of the town that owns [region], safe inside MiniMessage. */ + fun townName(player: Player, region: ResourceRegion): String = + TownyAPI.getInstance().getTown(region.townId)?.name?.let(TownyUtil::name) ?: player.tr("common.unknown") + + /** Tells [player], in the action bar, why they cannot gather here. */ + fun hint(player: Player, region: ResourceRegion, refusal: Refusal) { + Protection.hint(player, message(player, region, refusal)) + } + + fun message(player: Player, region: ResourceRegion, refusal: Refusal): String = when (refusal) { + Refusal.CLOSED -> player.tr("gathering.refuse.closed") + Refusal.NOT_RESIDENT -> player.tr("gathering.refuse.resident", "town" to townName(player, region)) + Refusal.UNCLAIMED -> player.tr("gathering.refuse.unclaimed") + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherCategory.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherCategory.kt new file mode 100644 index 0000000..c2b5067 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherCategory.kt @@ -0,0 +1,47 @@ +package net.trilleo.mc.plugins.tritown.gathering + +import org.bukkit.Material +import org.bukkit.Tag +import org.bukkit.block.data.Ageable +import org.bukkit.entity.Enemy +import org.bukkit.entity.EntityType + +/** + * What kind of gathering a resource is: what a region advertises and what a + * player's tally is kept under. + * + * The first four are for blocks, the last two for what a spawner calls up. + */ +enum class GatherCategory(val key: String, val icon: Material, val forBlocks: Boolean) { + MINING("gathering.category.mining", Material.IRON_PICKAXE, true), + FORAGING("gathering.category.foraging", Material.IRON_AXE, true), + FARMING("gathering.category.farming", Material.IRON_HOE, true), + EXCAVATION("gathering.category.excavation", Material.IRON_SHOVEL, true), + HUSBANDRY("gathering.category.husbandry", Material.WHEAT, false), + COMBAT("gathering.category.combat", Material.IRON_SWORD, false); + + /** The next category of the same family, for a button that cycles through them. */ + fun next(): GatherCategory { + val family = entries.filter { it.forBlocks == forBlocks } + return family[(family.indexOf(this) + 1) % family.size] + } + + companion object { + + /** A first guess at a block's category, which the administrator can change. */ + fun of(material: Material): GatherCategory = when { + Tag.LOGS.isTagged(material) || Tag.LEAVES.isTagged(material) || material == Material.BAMBOO -> FORAGING + material.isBlock && material.createBlockData() is Ageable -> FARMING + material in FARMED -> FARMING + Tag.MINEABLE_SHOVEL.isTagged(material) -> EXCAVATION + Tag.MINEABLE_AXE.isTagged(material) -> FORAGING + else -> MINING + } + + /** A hostile mob is fought for; anything else is kept. */ + fun of(type: EntityType): GatherCategory = + if (type.entityClass?.let { Enemy::class.java.isAssignableFrom(it) } == true) COMBAT else HUSBANDRY + + private val FARMED = setOf(Material.MELON, Material.PUMPKIN, Material.SUGAR_CANE, Material.CACTUS) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherEditors.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherEditors.kt new file mode 100644 index 0000000..4e46ec7 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherEditors.kt @@ -0,0 +1,127 @@ +package net.trilleo.mc.plugins.tritown.gathering + +import net.trilleo.mc.plugins.tritown.Main +import net.trilleo.mc.plugins.tritown.utils.Lang +import net.trilleo.mc.plugins.tritown.utils.itemStack +import org.bukkit.Bukkit +import org.bukkit.Color +import org.bukkit.Location +import org.bukkit.Material +import org.bukkit.NamespacedKey +import org.bukkit.Particle +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import org.bukkit.persistence.PersistentDataType +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * What administrators setting regions up are part-way through: the corners + * they have picked with the wand, and whether they are building. + * + * Building lifts a region's protection for that administrator alone, so a + * mine can be dug out or a farm laid without anything counting as a harvest. + * Towny's own rules still apply to them. + */ +object GatherEditors { + + /** Setting regions up: the wand, building mode and every `/tritown gather` action. */ + const val ADMIN_PERMISSION = "tritown.gather.admin" + + private val WAND = NamespacedKey("tritown", "gather-wand") + private const val OUTLINE_STEP = 1.0 + private const val OUTLINE_MAX_POINTS = 3000 + private const val OUTLINE_PERIOD = 10L + + class Selection(var first: Location? = null, var second: Location? = null) { + fun area(): Cuboid? { + val a = first ?: return null + val b = second ?: return null + if (a.world != b.world) return null + return Cuboid.of(a, b) + } + } + + private val selections = ConcurrentHashMap() + private val building = ConcurrentHashMap.newKeySet() + + fun selection(player: Player): Selection = selections.getOrPut(player.uniqueId) { Selection() } + + fun isBuilding(player: Player): Boolean = player.uniqueId in building + + /** Turns building on or off for [player], and returns whether it is now on. */ + fun toggleBuilding(player: Player): Boolean = + if (building.remove(player.uniqueId)) false else building.add(player.uniqueId) + + fun forget(player: Player) { + selections.remove(player.uniqueId) + building.remove(player.uniqueId) + } + + fun wand(): ItemStack = itemStack(Material.BLAZE_ROD) { + name(Lang.item("gathering.wand.name")) + lore(Lang.item("gathering.wand.lore")) + pdc(WAND, PersistentDataType.BYTE, 1.toByte()) + } + + fun isWand(item: ItemStack?): Boolean = + item != null && !item.type.isAir && item.persistentDataContainer.has(WAND, PersistentDataType.BYTE) + + /** + * Traces the edges of [area] in particles that only [player] sees, for + * [seconds]. A very large box is traced more sparsely rather than not at all. + */ + fun outline(player: Player, area: Cuboid, seconds: Int, color: Color = Color.LIME) { + val world = area.bukkitWorld() ?: return + val points = edges(area) + val stride = (points.size / OUTLINE_MAX_POINTS + 1) + val dust = Particle.DustOptions(color, 1.2f) + val runs = (seconds * 20L / OUTLINE_PERIOD).toInt() + + var done = 0 + lateinit var task: org.bukkit.scheduler.BukkitTask + task = Bukkit.getScheduler().runTaskTimer(Main.instance, Runnable { + if (!player.isOnline || player.world != world || done++ >= runs) { + task.cancel() + return@Runnable + } + for (i in points.indices step stride) { + val (x, y, z) = points[i] + player.spawnParticle(Particle.DUST, x, y, z, 1, 0.0, 0.0, 0.0, 0.0, dust) + } + }, 0L, OUTLINE_PERIOD) + } + + private fun edges(area: Cuboid): List> { + val x0 = area.minX.toDouble() + val y0 = area.minY.toDouble() + val z0 = area.minZ.toDouble() + val x1 = area.maxX + 1.0 + val y1 = area.maxY + 1.0 + val z1 = area.maxZ + 1.0 + + fun line(from: Triple, to: Triple) = buildList { + val length = maxOf(to.first - from.first, to.second - from.second, to.third - from.third) + var t = 0.0 + while (t <= length) { + val f = if (length == 0.0) 0.0 else t / length + add( + Triple( + from.first + (to.first - from.first) * f, + from.second + (to.second - from.second) * f, + from.third + (to.third - from.third) * f, + ) + ) + t += OUTLINE_STEP + } + } + + val corners = listOf(x0, x1).flatMap { x -> listOf(y0, y1).flatMap { y -> listOf(z0, z1).map { z -> Triple(x, y, z) } } } + return buildList { + for (a in corners) for (b in corners) { + val differ = listOf(a.first != b.first, a.second != b.second, a.third != b.third).count { it } + if (differ == 1 && (a.first <= b.first && a.second <= b.second && a.third <= b.third)) addAll(line(a, b)) + } + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherManager.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherManager.kt new file mode 100644 index 0000000..b45908a --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherManager.kt @@ -0,0 +1,274 @@ +package net.trilleo.mc.plugins.tritown.gathering + +import net.trilleo.mc.plugins.tritown.gathering.storage.* +import net.trilleo.mc.plugins.tritown.shops.ItemCodec +import org.bukkit.Location +import org.bukkit.Material +import org.bukkit.block.Block +import org.bukkit.entity.EntityType +import java.util.* +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicBoolean +import java.util.logging.Logger + +/** + * Every resource region, every block harvested in one, and the only thing that + * reads or writes either. + * + * A region is written out the moment it is edited, like a shop. Harvested + * blocks change on every swing, so they only mark the store dirty and are + * flushed by [net.trilleo.mc.plugins.tritown.tasks.gathering.GatherSaveTask] — + * a crash costs at most one interval of them, and they are written once more + * at shutdown so a restart picks every one back up where it left off. + */ +object GatherManager { + + private val regions = ConcurrentHashMap() + private val depleted = ConcurrentHashMap() + private val dirty = AtomicBoolean(false) + + private lateinit var storage: JsonGatherStorage + private lateinit var logger: Logger + + @Volatile + var isReady: Boolean = false + private set + + fun start(store: JsonGatherStorage, pluginLogger: Logger) { + storage = store + logger = pluginLogger + + val loaded = try { + store.loadRegions() + } catch (e: GatherStorageException) { + logger.severe("Resource regions are unavailable: ${e.message}") + isReady = false + return + } + + regions.clear() + loaded.mapNotNull(::toRegion).forEach { regions[it.id] = it } + + depleted.clear() + store.loadDepleted().forEach { stored -> + if (regions.containsKey(stored.region)) { + val node = toDepleted(stored) + depleted[node.key] = node + } + } + + dirty.set(false) + isReady = true + logger.info("Loaded ${regions.size} resource region(s) with ${depleted.size} block(s) growing back") + } + + fun shutdown() { + if (!isReady) return + dirty.set(true) + flush() + isReady = false + regions.clear() + depleted.clear() + } + + // ── Regions ───────────────────────────────────────────────────────── + + fun get(id: String): ResourceRegion? = regions[id.lowercase()] + + fun all(): List = regions.values.sortedBy { it.id } + + fun ids(): List = regions.keys.sorted() + + /** The regions of the town with [townId]. */ + fun ofTown(townId: UUID): List = all().filter { it.townId == townId } + + /** The region [block] is in, if any. */ + fun at(block: Block): ResourceRegion? = + if (!isReady) null else regions.values.firstOrNull { it.area.contains(block) } + + fun at(location: Location): ResourceRegion? = + if (!isReady) null else regions.values.firstOrNull { it.area.contains(location) } + + /** The region that would collide with [area], other than [except]. */ + fun overlapping(area: Cuboid, except: String? = null): ResourceRegion? = + regions.values.firstOrNull { it.id != except && it.area.overlaps(area) } + + /** Creates an empty region. Returns `null` when [id] is malformed or taken. */ + fun create(id: String, name: String, area: Cuboid, townId: UUID): ResourceRegion? { + val key = id.lowercase() + if (!ResourceRegion.isValidId(key) || regions.containsKey(key)) return null + + val region = ResourceRegion(key, name, area, townId) + regions[key] = region + save() + return region + } + + /** Takes [id] out, having grown back everything it harvested so nothing is left as bedrock. */ + fun delete(id: String): ResourceRegion? { + val region = regions[id.lowercase()] ?: return null + Regrowth.regrowAll(region) + regions.remove(region.id) + save() + return region + } + + /** Writes every region out now, for an edit that must not be lost. */ + fun save() { + if (!isReady) return + storage.saveRegions(regions.values.sortedBy { it.id }.map(::toStored)) + } + + // ── Harvested blocks ──────────────────────────────────────────────── + + fun depletedAt(key: BlockKey): DepletedNode? = depleted[key] + + fun depletedAt(block: Block): DepletedNode? = depleted[BlockKey.of(block)] + + fun depletedIn(region: ResourceRegion): List = depleted.values.filter { it.regionId == region.id } + + fun allDepleted(): Collection = depleted.values + + fun markDepleted(node: DepletedNode) { + depleted[node.key] = node + dirty.set(true) + } + + fun clearDepleted(key: BlockKey) { + if (depleted.remove(key) != null) dirty.set(true) + } + + /** Writes the harvested blocks out when any changed since the last write. */ + fun flush() { + if (!isReady) return + if (!dirty.compareAndSet(true, false)) return + storage.saveDepleted(depleted.values.map(::toStored)) + } + + // ── Conversion ────────────────────────────────────────────────────── + + private fun toRegion(stored: StoredRegion): ResourceRegion? { + val town = runCatching { UUID.fromString(stored.town) }.getOrNull() ?: run { + logger.warning("Skipped the resource region ${stored.id}: it names no town") + return null + } + + return ResourceRegion( + id = stored.id.lowercase(), + name = stored.name.ifBlank { stored.id }, + area = Cuboid(stored.world, stored.minX, stored.minY, stored.minZ, stored.maxX, stored.maxY, stored.maxZ), + townId = town, + enabled = stored.enabled, + nodes = stored.nodes.mapNotNull { toNode(stored.id, it) }.toMutableList(), + spawners = stored.spawners.mapNotNull { toSpawner(stored.id, it) }.toMutableList(), + ) + } + + private fun toNode(regionId: String, stored: StoredNode): ResourceNode? { + val block = Material.matchMaterial(stored.block)?.takeIf { it.isBlock } ?: run { + logger.warning("Dropped a resource of an unknown block (${stored.block}) from $regionId") + return null + } + + return ResourceNode( + id = stored.id.ifBlank { UUID.randomUUID().toString() }, + block = block, + category = enumOrDefault(stored.category, GatherCategory.of(block)), + regrowSeconds = stored.regrowSeconds.coerceAtLeast(1), + depleted = stored.depleted?.let(Material::matchMaterial)?.takeIf { it.isBlock }, + vanillaDrops = stored.vanillaDrops, + drops = stored.drops.mapNotNull { drop -> + ItemCodec.decode(drop.item)?.let { ResourceDrop(it, drop.chance) } + }.toMutableList(), + pool = stored.pool.mapNotNull { entry -> + Material.matchMaterial(entry.block)?.takeIf { it.isBlock }?.let { PoolEntry(it, entry.weight) } + }.toMutableList(), + ) + } + + private fun toSpawner(regionId: String, stored: StoredSpawner): ResourceSpawner? { + val type = EntityType.entries.firstOrNull { it.name.equals(stored.entity, ignoreCase = true) } ?: run { + logger.warning("Dropped a spawner of an unknown mob (${stored.entity}) from $regionId") + return null + } + + return ResourceSpawner( + id = stored.id.ifBlank { UUID.randomUUID().toString() }, + type = type, + category = enumOrDefault(stored.category, GatherCategory.of(type)), + x = stored.x, + y = stored.y, + z = stored.z, + maxAlive = stored.maxAlive.coerceAtLeast(1), + respawnSeconds = stored.respawnSeconds.coerceAtLeast(1), + radius = stored.radius.coerceAtLeast(1), + level = stored.level.coerceAtLeast(1), + ) + } + + private fun toStored(region: ResourceRegion): StoredRegion = StoredRegion( + id = region.id, + name = region.name, + world = region.area.world, + minX = region.area.minX, + minY = region.area.minY, + minZ = region.area.minZ, + maxX = region.area.maxX, + maxY = region.area.maxY, + maxZ = region.area.maxZ, + town = region.townId.toString(), + enabled = region.enabled, + nodes = region.nodes.map { node -> + StoredNode( + id = node.id, + block = node.block.name, + category = node.category.name, + regrowSeconds = node.regrowSeconds, + depleted = node.depleted?.name, + vanillaDrops = node.vanillaDrops, + drops = node.drops.map { StoredDrop(ItemCodec.encode(it.item), it.chance) }, + pool = node.pool.map { StoredPoolEntry(it.block.name, it.weight) }, + ) + }, + spawners = region.spawners.map { spawner -> + StoredSpawner( + id = spawner.id, + entity = spawner.type.name, + category = spawner.category.name, + x = spawner.x, + y = spawner.y, + z = spawner.z, + maxAlive = spawner.maxAlive, + respawnSeconds = spawner.respawnSeconds, + radius = spawner.radius, + level = spawner.level, + ) + }, + ) + + private fun toDepleted(stored: StoredDepleted) = DepletedNode( + key = BlockKey(stored.world, stored.x, stored.y, stored.z), + regionId = stored.region, + nodeId = stored.node, + original = stored.original, + placed = stored.placed, + depletedAt = stored.depletedAt, + regrowAt = stored.regrowAt, + ) + + private fun toStored(node: DepletedNode) = StoredDepleted( + world = node.key.world, + x = node.key.x, + y = node.key.y, + z = node.key.z, + region = node.regionId, + node = node.nodeId, + original = node.original, + placed = node.placed, + depletedAt = node.depletedAt, + regrowAt = node.regrowAt, + ) + + private inline fun > enumOrDefault(name: String, default: T): T = + enumValues().firstOrNull { it.name.equals(name, ignoreCase = true) } ?: default +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherNotices.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherNotices.kt new file mode 100644 index 0000000..4a794ce --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherNotices.kt @@ -0,0 +1,58 @@ +package net.trilleo.mc.plugins.tritown.gathering + +import net.kyori.adventure.title.Title +import net.trilleo.mc.plugins.tritown.config.GatheringSettings +import net.trilleo.mc.plugins.tritown.utils.ComponentUtil +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Bukkit +import org.bukkit.entity.Player +import java.time.Duration +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * Tells a player when they walk into a resource region: its name, what can be + * gathered there, and whether they may. + * + * Checked once a second rather than on every step, which is quick enough for + * someone walking in and costs nothing while nobody moves. + */ +object GatherNotices { + + private val inside = ConcurrentHashMap() + private val times = Title.Times.times(Duration.ofMillis(250), Duration.ofMillis(1800), Duration.ofMillis(500)) + + fun tick() { + val titles = GatheringSettings.snapshot.entryTitles + for (player in Bukkit.getOnlinePlayers()) { + val region = GatherManager.at(player.location) + val previous = inside[player.uniqueId] + if (region?.id == previous) continue + + if (region == null) inside.remove(player.uniqueId) else inside[player.uniqueId] = region.id + if (region != null && titles) announce(player, region) + } + } + + fun forget(player: Player) { + inside.remove(player.uniqueId) + } + + private fun announce(player: Player, region: ResourceRegion) { + val refusal = GatherAccess.refusal(player, region, player.location) + val subtitle = if (refusal == null) { + val categories = region.categories().joinToString(player.tr("gathering.list-separator")) { player.tr(it.key) } + player.tr("gathering.enter.open", "categories" to categories.ifEmpty { player.tr("common.none") }) + } else { + GatherAccess.message(player, region, refusal) + } + + player.showTitle( + Title.title( + ComponentUtil.parse(player.tr("gathering.enter.title", "name" to region.name)), + ComponentUtil.parse(subtitle), + times, + ) + ) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherPermits.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherPermits.kt new file mode 100644 index 0000000..ae56991 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherPermits.kt @@ -0,0 +1,44 @@ +package net.trilleo.mc.plugins.tritown.gathering + +import org.bukkit.Bukkit +import org.bukkit.Location +import org.bukkit.entity.Player +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * The one gathering action each player has been cleared for this tick. + * + * A town can deny its own residents the right to build, destroy and use, and + * gathering has to work anyway, without handing those rights out. So TriTown + * decides first, at `LOWEST`, and leaves a permit for exactly that player, + * that block and that tick. When Towny then asks its own permission events, + * [net.trilleo.mc.plugins.tritown.listeners.gathering.GatherTownyListener] + * lifts the refusal only where a permit matches. Every other action in the + * town — the next block over, the same block a tick later — Towny judges as + * it always would. + */ +object GatherPermits { + + private data class Permit(val key: BlockKey, val tick: Int) + + private val permits = ConcurrentHashMap() + + fun grant(player: Player, at: Location) { + permits[player.uniqueId] = Permit(BlockKey.of(at), Bukkit.getCurrentTick()) + } + + /** Whether [player] was cleared to act at [at] this tick. */ + fun isGranted(player: Player, at: Location): Boolean { + val permit = permits[player.uniqueId] ?: return false + if (permit.tick != Bukkit.getCurrentTick()) { + permits.remove(player.uniqueId, permit) + return false + } + return permit.key == BlockKey.of(at) + } + + fun forget(player: Player) { + permits.remove(player.uniqueId) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherStats.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherStats.kt new file mode 100644 index 0000000..b7f3b3f --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/GatherStats.kt @@ -0,0 +1,29 @@ +package net.trilleo.mc.plugins.tritown.gathering + +import net.trilleo.mc.plugins.tritown.data.PlayerDataManager +import org.bukkit.entity.Player + +/** + * How much each player has gathered, per category: a block harvested or a + * spawner's mob killed counts one. + * + * Kept in the player's [net.trilleo.mc.plugins.tritown.data.PlayerData] as + * one object of counters. + */ +object GatherStats { + + private const val KEY = "gathering" + + fun add(player: Player, category: GatherCategory) { + val data = PlayerDataManager.get(player) + val counts = data.getJsonObject(KEY) + val name = category.name.lowercase() + counts.addProperty(name, (counts.get(name)?.asLong ?: 0L) + 1L) + data.set(KEY, counts) + } + + fun of(player: Player): Map { + val counts = PlayerDataManager.get(player).getJsonObject(KEY) + return GatherCategory.entries.associateWith { counts.get(it.name.lowercase())?.asLong ?: 0L } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/Harvest.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/Harvest.kt new file mode 100644 index 0000000..2ba6b5c --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/Harvest.kt @@ -0,0 +1,95 @@ +package net.trilleo.mc.plugins.tritown.gathering + +import net.trilleo.mc.plugins.tritown.Main +import net.trilleo.mc.plugins.tritown.protection.ItemOwnership +import net.trilleo.mc.plugins.tritown.protection.Protection +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Bukkit +import org.bukkit.block.Block +import org.bukkit.entity.Player +import org.bukkit.event.block.BlockBreakEvent +import java.util.* +import java.util.concurrent.ConcurrentHashMap +import kotlin.random.Random + +/** + * Breaking a block inside a resource region. + * + * The decision is made in [check], before Towny looks at the break, and the + * harvest itself in [complete], once every plugin has had its say. Between the + * two the approved break is remembered here, so nothing that was refused — or + * that some other plugin cancelled — is ever counted, dropped or depleted. + */ +object Harvest { + + /** What [check] made of a break. */ + sealed interface Outcome { + data class Allowed(val node: ResourceNode) : Outcome + data class Refused(val refusal: GatherAccess.Refusal) : Outcome + data class Regrowing(val seconds: Long) : Outcome + data object Unripe : Outcome + data object Protected : Outcome + } + + private data class Pending(val key: BlockKey, val regionId: String, val nodeId: String, val tick: Int) + + private val pending = ConcurrentHashMap() + + /** What breaking [block] in [region] means for [player]. */ + fun check(player: Player, region: ResourceRegion, block: Block): Outcome { + val regrowing = Regrowth.secondsLeft(block) + val node = region.nodeFor(block.type) + if (regrowing == null && node == null) return Outcome.Protected + GatherAccess.refusal(player, region, block.location)?.let { return Outcome.Refused(it) } + if (regrowing != null) return Outcome.Regrowing(regrowing) + if (node == null || !node.isRipe(block)) return Outcome.Unripe + return Outcome.Allowed(node) + } + + /** Tells [player] why a break was refused. */ + fun explain(player: Player, region: ResourceRegion, outcome: Outcome) { + when (outcome) { + is Outcome.Refused -> GatherAccess.hint(player, region, outcome.refusal) + is Outcome.Regrowing -> Protection.hint(player, player.tr("gathering.hint.regrowing", "seconds" to outcome.seconds)) + Outcome.Unripe -> Protection.hint(player, player.tr("gathering.hint.unripe")) + Outcome.Protected -> Protection.hint(player, player.tr("gathering.hint.protected")) + is Outcome.Allowed -> Unit + } + } + + /** Remembers that [player] was cleared to harvest [block] as [node] this tick. */ + fun approve(player: Player, region: ResourceRegion, node: ResourceNode, block: Block) { + pending[player.uniqueId] = Pending(BlockKey.of(block), region.id, node.id, Bukkit.getCurrentTick()) + } + + /** + * Harvests the block [event] breaks, if it was approved: swaps vanilla's + * drops for the node's when it says so, rolls the extra drops, and leaves + * a stand-in to grow back. + */ + fun complete(event: BlockBreakEvent) { + val player = event.player + val approved = pending.remove(player.uniqueId) ?: return + val block = event.block + if (approved.tick != Bukkit.getCurrentTick() || approved.key != BlockKey.of(block)) return + + val region = GatherManager.get(approved.regionId) ?: return + val node = region.node(approved.nodeId) ?: return + + if (!node.vanillaDrops) event.isDropItems = false + val extras = node.drops.filter { Random.nextDouble(100.0) < it.chance }.map { it.item.clone() } + if (extras.isNotEmpty()) { + val at = block.location.toCenterLocation() + Bukkit.getScheduler().runTask(Main.instance, Runnable { + if (player.isOnline) extras.forEach { ItemOwnership.dropFor(player, it, at) } + }) + } + + Regrowth.deplete(region, node, block) + GatherStats.add(player, node.category) + } + + fun forget(player: Player) { + pending.remove(player.uniqueId) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/Regrowth.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/Regrowth.kt new file mode 100644 index 0000000..a4d6aac --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/Regrowth.kt @@ -0,0 +1,130 @@ +package net.trilleo.mc.plugins.tritown.gathering + +import net.kyori.adventure.key.Key +import net.kyori.adventure.sound.Sound +import net.trilleo.mc.plugins.tritown.Main +import net.trilleo.mc.plugins.tritown.config.GatheringSettings +import org.bukkit.Bukkit +import org.bukkit.Material +import org.bukkit.Particle +import org.bukkit.block.Block +import org.bukkit.block.data.Ageable +import org.bukkit.block.data.BlockData +import java.util.* + +/** + * Taking a node out of the world when it is harvested, and putting it back. + * + * A harvested node is written down with what it was and what stands in its + * place, then the stand-in is put down a tick later, once the game has + * finished breaking the block. A crop is put back as a seedling and grows + * through its stages as its time runs; anything else waits as its stand-in. + * + * Growing back never overwrites a rebuilt spot: if the block is no longer the + * stand-in TriTown left, the record is dropped and the block left alone. + */ +object Regrowth { + + private const val MAX_COLUMN = 16 + + private val random = Random() + private val growSound = Sound.sound(Key.key("minecraft:block.amethyst_block.chime"), Sound.Source.BLOCK, 0.6f, 1.4f) + + /** + * Records [block], about to be broken as [node], and puts its stand-in down + * on the next tick. A column plant takes everything of its kind stacked on + * top of it along, since the game breaks those too. + */ + fun deplete(region: ResourceRegion, node: ResourceNode, block: Block) { + val now = System.currentTimeMillis() + val regrowAt = now + node.regrowSeconds * 1000L + val original = block.blockData.clone() + val standIn = standIn(node, original) + + GatherManager.markDepleted( + DepletedNode(BlockKey.of(block), region.id, node.id, original.asString, standIn.material.name, now, regrowAt) + ) + + if (node.isColumn) { + var above = block.getRelative(0, 1, 0) + var count = 0 + while (above.type == node.block && count++ < MAX_COLUMN) { + GatherManager.markDepleted( + DepletedNode( + BlockKey.of(above), region.id, node.id, above.blockData.asString, + Material.AIR.name, now, regrowAt, + ) + ) + above = above.getRelative(0, 1, 0) + } + } + + Bukkit.getScheduler().runTask(Main.instance, Runnable { + if (block.type.isAir || block.type == node.block) block.setBlockData(standIn, false) + }) + } + + /** + * Moves every harvested node on: puts back those that are due, and steps + * a growing crop on to the stage its time has reached. A node in an + * unloaded chunk waits for it to load. + */ + fun tick() { + val now = System.currentTimeMillis() + for (node in GatherManager.allDepleted().toList()) { + if (!node.key.isLoaded()) continue + if (now >= node.regrowAt) regrow(node, effects = true) else grow(node, now) + } + } + + /** Puts back everything [region] has harvested, at once. */ + fun regrowAll(region: ResourceRegion): Int { + val nodes = GatherManager.depletedIn(region) + nodes.forEach { regrow(it, effects = false) } + return nodes.size + } + + /** How long until the node at [block] is back, in whole seconds, or `null` when it is not growing back. */ + fun secondsLeft(block: Block): Long? = GatherManager.depletedAt(block)?.let { node -> + ((node.regrowAt - System.currentTimeMillis()) / 1000L).coerceAtLeast(0L) + 1L + } + + private fun regrow(node: DepletedNode, effects: Boolean) { + GatherManager.clearDepleted(node.key) + val block = node.key.block() ?: return + if (block.type.name != node.placed) return + + val original = runCatching { Bukkit.createBlockData(node.original) }.getOrNull() ?: return + val rule = GatherManager.get(node.regionId)?.node(node.nodeId) + val data = rule?.rollRegrowth(random)?.let { material -> + if (material == original.material) original else material.createBlockData() + } ?: original + + block.setBlockData(data, false) + if (effects && GatheringSettings.snapshot.effects && !data.material.isAir) { + val center = block.location.toCenterLocation() + block.world.spawnParticle(Particle.HAPPY_VILLAGER, center, 8, 0.35, 0.35, 0.35, 0.0) + block.world.playSound(growSound, center.x, center.y, center.z) + } + } + + /** Steps a crop on to the stage its time has reached, without ever ripening it early. */ + private fun grow(node: DepletedNode, now: Long) { + val block = node.key.block() ?: return + if (block.type.name != node.placed) return + val data = block.blockData as? Ageable ?: return + if (data.maximumAge <= 0) return + + val stage = (node.progress(now) * data.maximumAge).toInt().coerceIn(0, data.maximumAge - 1) + if (stage <= data.age) return + data.age = stage + block.setBlockData(data, false) + } + + private fun standIn(node: ResourceNode, original: BlockData): BlockData { + if (node.growsInStages && original is Ageable) { + return (original.clone() as Ageable).apply { age = 0 } + } + return (node.depleted ?: GatheringSettings.snapshot.depletedFor(node.category)).createBlockData() + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/ResourceRegion.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/ResourceRegion.kt new file mode 100644 index 0000000..f06ef74 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/ResourceRegion.kt @@ -0,0 +1,157 @@ +package net.trilleo.mc.plugins.tritown.gathering + +import org.bukkit.Location +import org.bukkit.Material +import org.bukkit.Tag +import org.bukkit.block.Block +import org.bukkit.block.data.Ageable +import org.bukkit.entity.EntityType +import org.bukkit.inventory.ItemStack +import java.util.* + +/** + * A part of a town whose resources grow back, and that only the town's + * residents may gather. + * + * Everything inside [area] is protected: only a ripe [ResourceNode] may be + * broken, nothing may be placed, and nothing grows, spreads or decays except + * through TriTown. The town is remembered by UUID, and Towny is asked again on + * every harvest whether the ground is still the town's. + * + * [name] is administrator-written MiniMessage, shown as written. + */ +class ResourceRegion( + val id: String, + var name: String, + var area: Cuboid, + var townId: UUID, + var enabled: Boolean = true, + val nodes: MutableList = mutableListOf(), + val spawners: MutableList = mutableListOf(), +) { + + /** The rule for blocks of [material], or `null` when they are not a resource here. */ + fun nodeFor(material: Material): ResourceNode? = nodes.firstOrNull { it.block == material } + + fun node(id: String): ResourceNode? = nodes.firstOrNull { it.id == id } + + fun spawner(id: String): ResourceSpawner? = spawners.firstOrNull { it.id == id } + + /** Every category the region offers, in the enum's order. */ + fun categories(): List = + (nodes.map { it.category } + spawners.map { it.category }).distinct().sortedBy { it.ordinal } + + companion object { + private val VALID_ID = Regex("[a-z0-9_-]{1,32}") + + fun isValidId(id: String): Boolean = VALID_ID.matches(id) + } +} + +/** + * One kind of block in a region that can be harvested, and how it grows back. + * + * Every block of [block] inside the region is a node, so an administrator + * builds a mine out of ore and adds one rule, rather than registering each + * block. A crop is ripe only at its last stage, and grows back through its + * stages; anything else is replaced by its [depleted] block until it returns. + * + * @param depleted what stands in for a harvested node, or `null` for the category's default + * @param vanillaDrops whether the block drops what it would in vanilla, before [drops] are added + * @param pool what the node may grow back as, by weight; empty to grow back as itself + */ +class ResourceNode( + val id: String = UUID.randomUUID().toString(), + var block: Material, + var category: GatherCategory, + var regrowSeconds: Int, + var depleted: Material? = null, + var vanillaDrops: Boolean = true, + val drops: MutableList = mutableListOf(), + val pool: MutableList = mutableListOf(), +) { + + /** Whether the node is a crop that ripens in stages, and grows back through them. */ + val growsInStages: Boolean + get() = depleted == null && isStaged(block) + + /** Whether breaking the node takes the same plant stacked on top of it as well. */ + val isColumn: Boolean + get() = block in COLUMNS + + /** Whether [block] is ready to be harvested. */ + fun isRipe(block: Block): Boolean { + if (block.type != this.block) return false + val data = block.blockData as? Ageable ?: return true + return !growsInStages || data.age >= data.maximumAge + } + + /** One draw from [pool], or `null` to grow back as whatever was there. */ + fun rollRegrowth(random: Random): Material? { + val total = pool.sumOf { it.weight.coerceAtLeast(0) } + if (total <= 0) return null + var pick = random.nextInt(total) + for (entry in pool) { + pick -= entry.weight.coerceAtLeast(0) + if (pick < 0) return entry.block + } + return null + } + + companion object { + private val STAGED = setOf(Material.NETHER_WART, Material.COCOA, Material.SWEET_BERRY_BUSH) + private val COLUMNS = setOf(Material.SUGAR_CANE, Material.CACTUS, Material.BAMBOO) + + fun isStaged(material: Material): Boolean = + (Tag.CROPS.isTagged(material) || material in STAGED) && material.createBlockData() is Ageable + } +} + +/** An extra item a node or its harvest may give, [chance] percent of the time. */ +class ResourceDrop(val item: ItemStack, var chance: Double) + +/** One block a node may grow back as, and how likely it is against the others. */ +class PoolEntry(val block: Material, var weight: Int) + +/** + * A spot in a region that keeps up to [maxAlive] mobs of [type] about, calling + * up another [respawnSeconds] after one is lost. + * + * Its mobs stay within [radius] blocks of it. A hostile one is [level]; an + * animal has no level. + */ +class ResourceSpawner( + val id: String = UUID.randomUUID().toString(), + var type: EntityType, + var category: GatherCategory, + var x: Double, + var y: Double, + var z: Double, + var maxAlive: Int, + var respawnSeconds: Int, + var radius: Int, + var level: Int = 1, +) { + fun location(region: ResourceRegion): Location? = region.area.bukkitWorld()?.let { Location(it, x, y, z) } +} + +/** + * A harvested block waiting to grow back. + * + * [original] is the block as it was, as Bukkit's block data string; [placed] + * is what TriTown put in its place, and if anything else is there by the time + * it is due, somebody has rebuilt the spot and it is left alone. + */ +data class DepletedNode( + val key: BlockKey, + val regionId: String, + val nodeId: String, + val original: String, + val placed: String, + val depletedAt: Long, + val regrowAt: Long, +) { + /** How far through growing back the node is, from 0 to 1. */ + fun progress(now: Long): Double = + if (regrowAt <= depletedAt) 1.0 else ((now - depletedAt).toDouble() / (regrowAt - depletedAt)).coerceIn(0.0, 1.0) +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/Spawners.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/Spawners.kt new file mode 100644 index 0000000..689be9d --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/Spawners.kt @@ -0,0 +1,161 @@ +package net.trilleo.mc.plugins.tritown.gathering + +import net.trilleo.mc.plugins.tritown.config.GatheringSettings +import net.trilleo.mc.plugins.tritown.mobs.MobSetup +import org.bukkit.Bukkit +import org.bukkit.Location +import org.bukkit.NamespacedKey +import org.bukkit.Particle +import org.bukkit.entity.Enemy +import org.bukkit.entity.Entity +import org.bukkit.entity.LivingEntity +import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason +import org.bukkit.persistence.PersistentDataType +import java.util.* +import java.util.concurrent.ConcurrentHashMap +import kotlin.random.Random + +/** + * The animals and monsters a region's spawners keep about. + * + * Each mob carries the region and spawner that called it up, so it is still + * recognised after a restart; [adopt] counts it back in when its chunk loads, + * and gets rid of one whose spawner is gone. Which mobs are alive is kept + * only in memory, re-learned the same way. + * + * A spawner only works while a player is in range, and keeps its mobs within + * reach of it, walking any that stray back. + */ +object Spawners { + + private val KEY = NamespacedKey("tritown", "gather-spawner") + private const val SPOT_TRIES = 10 + private const val STRAY_MARGIN = 4 + + private val alive = ConcurrentHashMap>() + private val nextSpawn = ConcurrentHashMap() + + /** Set while TriTown is calling a mob up, so Towny's spawn rules can be told to let it be. */ + @Volatile + var isSpawning: Boolean = false + private set + + fun isSpawned(entity: Entity): Boolean = entity.persistentDataContainer.has(KEY, PersistentDataType.STRING) + + /** The region and spawner [entity] belongs to, or `null` when it is not a spawner's or the spawner is gone. */ + fun ownerOf(entity: Entity): Pair? { + val tag = entity.persistentDataContainer.get(KEY, PersistentDataType.STRING) ?: return null + val region = GatherManager.get(tag.substringBefore('/')) ?: return null + val spawner = region.spawner(tag.substringAfter('/')) ?: return null + return region to spawner + } + + /** Counts a loaded spawner mob back in, or removes it when its spawner no longer exists. */ + fun adopt(entity: Entity) { + if (!isSpawned(entity)) return + val (_, spawner) = ownerOf(entity) ?: run { + entity.remove() + return + } + alive.getOrPut(spawner.id) { ConcurrentHashMap.newKeySet() } += entity.uniqueId + } + + fun forget(entity: Entity) { + val (_, spawner) = ownerOf(entity) ?: return + alive[spawner.id]?.remove(entity.uniqueId) + } + + /** Removes every loaded mob [spawner] called up, for a spawner that is being deleted or moved. */ + fun clear(spawner: ResourceSpawner) { + alive.remove(spawner.id)?.forEach { Bukkit.getEntity(it)?.remove() } + nextSpawn.remove(spawner.id) + } + + fun clear(region: ResourceRegion) = region.spawners.forEach(::clear) + + /** How many of [spawner]'s mobs are loaded and alive. */ + fun count(spawner: ResourceSpawner): Int = living(spawner).size + + fun tick() { + val now = System.currentTimeMillis() + val range = GatheringSettings.snapshot.spawnerRange + for (region in GatherManager.all()) { + if (!region.enabled) continue + for (spawner in region.spawners) tick(region, spawner, now, range) + } + } + + private fun tick(region: ResourceRegion, spawner: ResourceSpawner, now: Long, range: Double) { + val home = spawner.location(region) ?: return + if (!home.isChunkLoaded) return + + val mobs = living(spawner) + mobs.forEach { keepNear(it, region, spawner, home) } + if (home.getNearbyPlayers(range).isEmpty()) return + + if (mobs.size >= spawner.maxAlive) { + nextSpawn[spawner.id] = now + spawner.respawnSeconds * 1000L + return + } + if (now < (nextSpawn[spawner.id] ?: 0L)) return + + spot(region, spawner, home)?.let { spawn(region, spawner, it) } + nextSpawn[spawner.id] = now + spawner.respawnSeconds * 1000L + } + + private fun living(spawner: ResourceSpawner): List { + val ids = alive[spawner.id] ?: return emptyList() + val mobs = ids.mapNotNull { Bukkit.getEntity(it) as? LivingEntity }.filter { it.isValid && !it.isDead } + ids.retainAll(mobs.map { it.uniqueId }.toSet()) + return mobs + } + + private fun spawn(region: ResourceRegion, spawner: ResourceSpawner, at: Location) { + val prepare: (Entity) -> Unit = { mob -> + mob.persistentDataContainer.set(KEY, PersistentDataType.STRING, "${region.id}/${spawner.id}") + (mob as? LivingEntity)?.removeWhenFarAway = false + } + + isSpawning = true + val mob = try { + if (spawner.category == GatherCategory.COMBAT && isHostile(spawner)) { + MobSetup.spawn(at, spawner.type, spawner.level, null, prepare) + } else { + at.world.spawnEntity(at, spawner.type, SpawnReason.CUSTOM) { prepare(it) } as? LivingEntity + } + } finally { + isSpawning = false + } + + mob ?: return + alive.getOrPut(spawner.id) { ConcurrentHashMap.newKeySet() } += mob.uniqueId + if (GatheringSettings.snapshot.effects) { + at.world.spawnParticle(Particle.POOF, at.clone().add(0.0, 0.5, 0.0), 8, 0.3, 0.3, 0.3, 0.02) + } + } + + /** Walks a mob that has wandered off, or left the region, back to its spawner. */ + private fun keepNear(mob: LivingEntity, region: ResourceRegion, spawner: ResourceSpawner, home: Location) { + val far = mob.world != home.world || + mob.location.distanceSquared(home) > (spawner.radius + STRAY_MARGIN).let { it * it }.toDouble() + if (!far && region.area.contains(mob.location)) return + spot(region, spawner, home)?.let { MobSetup.teleport(mob, it) } + } + + /** A spot within [ResourceSpawner.radius] of the spawner, inside the region, that a mob can stand on. */ + private fun spot(region: ResourceRegion, spawner: ResourceSpawner, home: Location): Location? { + repeat(SPOT_TRIES) { + val dx = Random.nextInt(-spawner.radius, spawner.radius + 1) + val dz = Random.nextInt(-spawner.radius, spawner.radius + 1) + for (dy in intArrayOf(0, 1, -1, 2, -2)) { + val spot = home.clone().add(dx.toDouble(), dy.toDouble(), dz.toDouble()).toBlockLocation() + .add(0.5, 0.0, 0.5) + if (region.area.contains(spot) && MobSetup.standable(spot)) return spot + } + } + return null + } + + private fun isHostile(spawner: ResourceSpawner): Boolean = + spawner.type.entityClass?.let { Enemy::class.java.isAssignableFrom(it) } == true +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/storage/JsonGatherStorage.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/storage/JsonGatherStorage.kt new file mode 100644 index 0000000..b4bad1b --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/storage/JsonGatherStorage.kt @@ -0,0 +1,100 @@ +package net.trilleo.mc.plugins.tritown.gathering.storage + +import com.google.gson.GsonBuilder +import com.google.gson.JsonObject +import com.google.gson.JsonParser +import com.google.gson.reflect.TypeToken +import net.trilleo.mc.plugins.tritown.utils.AtomicFile +import java.io.File +import java.util.logging.Logger + +/** + * Keeps resource regions, and the blocks harvested in them, under + * `/gathering/`. + * + * Two files, because they change at very different rates: a region is edited + * now and then and written at once, while harvested blocks change on every + * swing of a pickaxe and are flushed on an interval. Both are written through + * [AtomicFile], and a file that will not parse falls back to its backup. + */ +class JsonGatherStorage(directory: File, private val logger: Logger) { + + private val root = File(directory, DIRECTORY) + private val regionsFile = File(root, REGIONS_FILE) + private val depletedFile = File(root, DEPLETED_FILE) + private val gson = GsonBuilder().setPrettyPrinting().create() + private val ioLock = Any() + private val depletedType = object : TypeToken>() {}.type + + /** + * Every stored region. + * + * @throws GatherStorageException when neither the file nor its backup can be + * read, which keeps the feature off rather than letting an empty list + * overwrite the regions on the next save + */ + fun loadRegions(): List = synchronized(ioLock) { + val document = readWithBackup(regionsFile) ?: return emptyList() + val array = document.getAsJsonArray(KEY_REGIONS) ?: return emptyList() + array.mapNotNull { element -> + runCatching { gson.fromJson(element, StoredRegion::class.java) }.getOrNull() + ?.takeIf { it.id.isNotBlank() } + ?: run { + logger.warning("Skipped an unreadable region in ${regionsFile.name}") + null + } + } + } + + fun saveRegions(regions: List) = write(regionsFile, KEY_REGIONS, regions) + + /** Every harvested block. Losing this file only means those blocks stay as they are. */ + fun loadDepleted(): List = synchronized(ioLock) { + val document = runCatching { readWithBackup(depletedFile) }.getOrNull() ?: return emptyList() + val array = document.getAsJsonArray(KEY_DEPLETED) ?: return emptyList() + runCatching { gson.fromJson>(array, depletedType) }.getOrNull().orEmpty() + } + + fun saveDepleted(nodes: List) = write(depletedFile, KEY_DEPLETED, nodes) + + private fun write(file: File, key: String, values: Any) = synchronized(ioLock) { + root.mkdirs() + val document = JsonObject().apply { + addProperty(KEY_VERSION, SCHEMA) + add(key, gson.toJsonTree(values)) + } + try { + AtomicFile.write(file.toPath(), File(root, "${file.name}.bak").toPath(), gson.toJson(document)) + } catch (e: Exception) { + logger.severe("Failed to write ${file.name}: [${e.javaClass.simpleName}] ${e.message}") + } + } + + private fun readWithBackup(file: File): JsonObject? { + root.mkdirs() + read(file)?.let { return it } + if (file.exists()) logger.warning("${file.name} could not be read; falling back to the backup") + val backup = File(root, "${file.name}.bak") + read(backup)?.let { return it } + if (backup.exists()) throw GatherStorageException("Neither ${file.name} nor its backup could be read") + return null + } + + private fun read(file: File): JsonObject? { + if (!file.exists()) return null + return runCatching { JsonParser.parseString(file.readText()).asJsonObject }.getOrNull() + } + + private companion object { + const val DIRECTORY = "gathering" + const val REGIONS_FILE = "regions.json" + const val DEPLETED_FILE = "depleted.json" + const val KEY_VERSION = "schemaVersion" + const val KEY_REGIONS = "regions" + const val KEY_DEPLETED = "depleted" + const val SCHEMA = 1 + } +} + +/** Raised when stored regions cannot be read, and must not be silently replaced. */ +class GatherStorageException(message: String) : Exception(message) diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/storage/StoredRegion.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/storage/StoredRegion.kt new file mode 100644 index 0000000..a52df4d --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/gathering/storage/StoredRegion.kt @@ -0,0 +1,66 @@ +package net.trilleo.mc.plugins.tritown.gathering.storage + +/** + * A resource region as it sits on disk. + * + * Kept apart from the live model for the same reason a shop is: items are + * Base64 here, so the storage layer never names a Bukkit type. Gson builds these + * by reflection, so every field needs a default. + */ +data class StoredRegion( + val id: String = "", + val name: String = "", + val world: String = "", + val minX: Int = 0, + val minY: Int = 0, + val minZ: Int = 0, + val maxX: Int = 0, + val maxY: Int = 0, + val maxZ: Int = 0, + val town: String = "", + val enabled: Boolean = true, + val nodes: List = emptyList(), + val spawners: List = emptyList(), +) + +data class StoredNode( + val id: String = "", + val block: String = "", + val category: String = "MINING", + val regrowSeconds: Int = 60, + val depleted: String? = null, + val vanillaDrops: Boolean = true, + val drops: List = emptyList(), + val pool: List = emptyList(), +) + +data class StoredDrop(val item: String = "", val chance: Double = 100.0) + +data class StoredPoolEntry(val block: String = "", val weight: Int = 1) + +data class StoredSpawner( + val id: String = "", + val entity: String = "", + val category: String = "HUSBANDRY", + val x: Double = 0.0, + val y: Double = 0.0, + val z: Double = 0.0, + val maxAlive: Int = 3, + val respawnSeconds: Int = 30, + val radius: Int = 6, + val level: Int = 1, +) + +/** A harvested block on disk; see [net.trilleo.mc.plugins.tritown.gathering.DepletedNode]. */ +data class StoredDepleted( + val world: String = "", + val x: Int = 0, + val y: Int = 0, + val z: Int = 0, + val region: String = "", + val node: String = "", + val original: String = "", + val placed: String = "", + val depletedAt: Long = 0L, + val regrowAt: Long = 0L, +) diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherItemsGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherItemsGUI.kt new file mode 100644 index 0000000..2c8d417 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherItemsGUI.kt @@ -0,0 +1,193 @@ +package net.trilleo.mc.plugins.tritown.guis.gathering + +import net.kyori.adventure.text.Component +import net.trilleo.mc.plugins.tritown.enums.PagedLayout +import net.trilleo.mc.plugins.tritown.gathering.* +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PagedPluginGUI +import net.trilleo.mc.plugins.tritown.utils.ChatPrompt +import net.trilleo.mc.plugins.tritown.utils.ComponentUtil +import net.trilleo.mc.plugins.tritown.utils.LoreUtil +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.ClickType +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.inventory.ItemStack +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * A resource's two lists: the extra items a harvest may give, each with its + * chance, and the blocks it may grow back as, each with its weight. + * + * Either is added to by clicking an item in your own inventory, which is + * copied and never taken, the way a shop entry is added. + */ +class GatherItemsGUI : PagedPluginGUI( + id = ID, + titleKey = "gui.gather-drops.title", + rows = 6, + layout = PagedLayout.FRAMED, +) { + + enum class Mode { DROPS, POOL } + + private val modes = ConcurrentHashMap() + + override fun title(player: Player): Component = ComponentUtil.parse( + player.tr(if (modeOf(player) == Mode.DROPS) "gui.gather-drops.title" else "gui.gather-pool.title") + ) + + override fun getItems(player: Player): List { + val node = GatherRender.node(player) ?: return emptyList() + return when (modeOf(player)) { + Mode.DROPS -> node.drops.map { drop(player, it) } + Mode.POOL -> node.pool.map { pool(player, node, it) } + } + } + + override fun navButtons(player: Player): Map { + val drops = modeOf(player) == Mode.DROPS + return mapOf( + BACK_OFFSET to GatherRender.button( + player, Material.ARROW, "gui.gather-node.back-node", listOf(player.tr("gui.gather-node.back-node-lore")), + ), + HELP_OFFSET to GatherRender.button( + player, Material.PAPER, + if (drops) "gui.gather-drops.add" else "gui.gather-pool.add", + listOf(player.tr(if (drops) "gui.gather-drops.add-lore" else "gui.gather-pool.add-lore")), + ), + ) + } + + override fun onNavClick(event: InventoryClickEvent, offset: Int) { + val player = event.whoClicked as? Player ?: return + if (offset != BACK_OFFSET) return + val region = GatherRender.region(player) ?: return + val node = GatherRender.node(player) ?: return + GatherRender.click(player) + GatherRender.navigate { GatherNodeGUI.show(player, region, node) } + } + + override fun onClick(event: InventoryClickEvent) { + val player = event.whoClicked as? Player + if (player != null && event.clickedInventory === player.inventory) { + event.isCancelled = true + if (!GatherRender.mayEdit(player)) return + val node = GatherRender.node(player) ?: return + val item = event.currentItem?.takeUnless { it.type.isAir } ?: return + add(player, node, item) + refresh(player, event.view.topInventory) + return + } + super.onClick(event) + } + + override fun onContentClick(event: InventoryClickEvent, page: Int) { + val player = event.whoClicked as? Player ?: return + if (!GatherRender.mayEdit(player)) return + val region = GatherRender.region(player) ?: return + val node = GatherRender.node(player) ?: return + val index = contentIndex(event, page) ?: return + val mode = modeOf(player) + val size = if (mode == Mode.DROPS) node.drops.size else node.pool.size + if (index >= size) return + + if (event.click == ClickType.SHIFT_LEFT) { + if (mode == Mode.DROPS) node.drops.removeAt(index) else node.pool.removeAt(index) + GatherManager.save() + refresh(player, event.inventory) + return + } + + GatherRender.navigate { + player.closeInventory() + val question = if (mode == Mode.DROPS) "gathering.editor.prompt-chance" else "gathering.editor.prompt-weight" + ChatPrompt.ask(player, player.tr(question)) { input -> + if (!apply(node, mode, index, input)) player.sendPrefixed(player.tr("common.invalid-amount")) + show(player, region, node, mode) + } + } + } + + private fun apply(node: ResourceNode, mode: Mode, index: Int, input: String): Boolean { + when (mode) { + Mode.DROPS -> { + val chance = input.removeSuffix("%").trim().toDoubleOrNull()?.takeIf { it > 0.0 && it <= 100.0 } + ?: return false + node.drops.getOrNull(index)?.chance = chance + } + + Mode.POOL -> { + val weight = input.trim().toIntOrNull()?.takeIf { it in 1..MAX_WEIGHT } ?: return false + node.pool.getOrNull(index)?.weight = weight + } + } + GatherManager.save() + return true + } + + private fun add(player: Player, node: ResourceNode, item: ItemStack) { + when (modeOf(player)) { + Mode.DROPS -> node.drops += ResourceDrop(item.clone(), DEFAULT_CHANCE) + Mode.POOL -> { + val block = GatherRender.blockOf(item) ?: run { + player.sendPrefixed(player.tr("gathering.editor.not-a-block")) + return + } + if (node.pool.any { it.block == block }) return + node.pool += PoolEntry(block, 1) + } + } + GatherManager.save() + GatherRender.click(player) + } + + private fun drop(player: Player, drop: ResourceDrop): ItemStack = LoreUtil.withLore( + drop.item.clone(), + listOf( + player.tr("gui.gather-drops.chance", "chance" to formatChance(drop.chance)), + "", + player.tr("gui.gather-drops.click"), + player.tr("gui.gather-items.shift-click"), + ), + ) + + private fun pool(player: Player, node: ResourceNode, entry: PoolEntry): ItemStack { + val total = node.pool.sumOf { it.weight }.coerceAtLeast(1) + return GatherRender.card( + GatherRender.blockIcon(entry.block), + player.tr("gui.gather-nodes.name", "block" to GatherRender.blockName(entry.block)), + listOf( + player.tr( + "gui.gather-pool.weight", + "weight" to entry.weight, "chance" to formatChance(entry.weight * 100.0 / total), + ), + "", + player.tr("gui.gather-pool.click"), + player.tr("gui.gather-items.shift-click"), + ), + ) + } + + private fun formatChance(chance: Double): String = "%.1f".format(Locale.ROOT, chance) + + private fun modeOf(player: Player): Mode = modes[player.uniqueId] ?: Mode.DROPS + + companion object { + const val ID = "gather-items" + private const val BACK_OFFSET = 3 + private const val HELP_OFFSET = 5 + private const val DEFAULT_CHANCE = 100.0 + private const val MAX_WEIGHT = 10_000 + + fun show(player: Player, region: ResourceRegion, node: ResourceNode, mode: Mode): Boolean { + val gui = GUIManager.getGUI(ID) as? GatherItemsGUI ?: return false + gui.modes[player.uniqueId] = mode + GatherRender.setContext(player, GatherRender.Context(region.id, nodeId = node.id)) + return GUIManager.open(player, ID) + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherListGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherListGUI.kt new file mode 100644 index 0000000..f85a15e --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherListGUI.kt @@ -0,0 +1,59 @@ +package net.trilleo.mc.plugins.tritown.guis.gathering + +import net.trilleo.mc.plugins.tritown.enums.PagedLayout +import net.trilleo.mc.plugins.tritown.gathering.GatherAccess +import net.trilleo.mc.plugins.tritown.gathering.GatherManager +import net.trilleo.mc.plugins.tritown.gathering.ResourceRegion +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PagedPluginGUI +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.inventory.ItemStack + +/** Every resource region on the server, for an administrator to pick one to edit. */ +class GatherListGUI : PagedPluginGUI( + id = ID, + titleKey = "gui.gather-list.title", + rows = 6, + layout = PagedLayout.FRAMED, +) { + + override fun getItems(player: Player): List = GatherManager.all().map { icon(player, it) } + + override fun navButtons(player: Player): Map = mapOf( + HELP_OFFSET to GatherRender.button( + player, Material.BLAZE_ROD, "gui.gather-list.help", + listOf(player.tr("gui.gather-list.help-lore")), + ), + ) + + override fun onContentClick(event: InventoryClickEvent, page: Int) { + val player = event.whoClicked as? Player ?: return + if (!GatherRender.mayEdit(player)) return + val region = GatherManager.all().getOrNull(contentIndex(event, page) ?: return) ?: return + GatherRender.click(player) + GatherRender.navigate { GatherRegionGUI.show(player, region) } + } + + private fun icon(player: Player, region: ResourceRegion): ItemStack { + val lines = listOf( + player.tr("gui.gather-list.id", "id" to region.id), + player.tr("gui.gather-list.town", "town" to GatherAccess.townName(player, region)), + GatherRender.coordinates(player, region), + player.tr("gui.gather-list.offers", "categories" to GatherRender.categories(player, region)), + player.tr(if (region.enabled) "gui.gather-list.open" else "gui.gather-list.closed"), + "", + player.tr("gui.gather-list.click"), + ) + return GatherRender.card(GatherRender.icon(region), region.name, lines, glow = region.enabled) + } + + companion object { + const val ID = "gather-list" + private const val HELP_OFFSET = 3 + + fun show(player: Player): Boolean = GUIManager.open(player, ID) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherNodeGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherNodeGUI.kt new file mode 100644 index 0000000..b1f50e4 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherNodeGUI.kt @@ -0,0 +1,223 @@ +package net.trilleo.mc.plugins.tritown.guis.gathering + +import net.kyori.adventure.text.Component +import net.trilleo.mc.plugins.tritown.config.GatheringSettings +import net.trilleo.mc.plugins.tritown.gathering.GatherManager +import net.trilleo.mc.plugins.tritown.gathering.ResourceNode +import net.trilleo.mc.plugins.tritown.gathering.ResourceRegion +import net.trilleo.mc.plugins.tritown.registration.GUIFrame +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PluginGUI +import net.trilleo.mc.plugins.tritown.utils.ChatPrompt +import net.trilleo.mc.plugins.tritown.utils.ComponentUtil +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.ClickType +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.ItemStack + +/** + * One resource of a region: what it counts as, how long it takes to grow back, + * what stands in for it meanwhile, and what it drops. + */ +class GatherNodeGUI : PluginGUI( + id = ID, + titleKey = "gui.gather-node.title", + rows = 6, +) { + + private enum class Button { CATEGORY, REGROW, DEPLETED, VANILLA, DROPS, POOL, DELETE, BACK } + + private val layout: Map = buildMap { + listOf(Button.CATEGORY, Button.REGROW, Button.DEPLETED, Button.VANILLA) + .zip(GUIFrame.spacedColumns(4)).forEach { (button, column) -> put(3 * ROW_SIZE + column, button) } + listOf(Button.DROPS, Button.POOL, Button.DELETE) + .zip(GUIFrame.spacedColumns(3)).forEach { (button, column) -> put(4 * ROW_SIZE + column, button) } + put(BACK_SLOT, Button.BACK) + } + + override fun title(player: Player): Component { + val block = GatherRender.node(player)?.block?.let(GatherRender::blockName) ?: "" + return ComponentUtil.parse(player.tr("gui.gather-node.title", "block" to block)) + } + + override fun setup(player: Player, inventory: Inventory) { + val node = GatherRender.node(player) ?: return + GUIFrame.draw(inventory, layout.keys + INFO_SLOT) + inventory.setItem( + INFO_SLOT, + GatherRender.card( + GatherRender.blockIcon(node.block), + player.tr("gui.gather-nodes.name", "block" to GatherRender.blockName(node.block)), + summary(player, node), + ), + ) + layout.forEach { (slot, button) -> inventory.setItem(slot, render(player, node, button)) } + } + + override fun onClick(event: InventoryClickEvent) { + event.isCancelled = true + if (event.clickedInventory !== event.view.topInventory) return + val player = event.whoClicked as? Player ?: return + if (!GatherRender.mayEdit(player)) return + val region = GatherRender.region(player) ?: return + val node = GatherRender.node(player) ?: return + + when (layout[event.rawSlot]) { + Button.CATEGORY -> change(player) { node.category = node.category.next() } + Button.VANILLA -> change(player) { node.vanillaDrops = !node.vanillaDrops } + Button.REGROW -> promptRegrow(player, region, node) + Button.DEPLETED -> promptDepleted(player, region, node) + Button.DROPS -> open(player) { GatherItemsGUI.show(player, region, node, GatherItemsGUI.Mode.DROPS) } + Button.POOL -> open(player) { GatherItemsGUI.show(player, region, node, GatherItemsGUI.Mode.POOL) } + Button.DELETE -> if (event.click == ClickType.SHIFT_LEFT) { + region.nodes.remove(node) + GatherManager.save() + player.sendPrefixed( + player.tr("gathering.editor.node-removed", "block" to GatherRender.blockName(node.block)) + ) + open(player) { GatherNodeListGUI.show(player, region) } + } + + Button.BACK -> open(player) { GatherNodeListGUI.show(player, region) } + null -> Unit + } + } + + private fun change(player: Player, edit: () -> Unit) { + edit() + GatherManager.save() + GatherRender.click(player) + GUIManager.refresh(player) + } + + private fun open(player: Player, action: () -> Unit) { + GatherRender.click(player) + GatherRender.navigate(action) + } + + private fun promptRegrow(player: Player, region: ResourceRegion, node: ResourceNode) { + GatherRender.navigate { + player.closeInventory() + ChatPrompt.ask(player, player.tr("gathering.editor.prompt-regrow")) { input -> + val seconds = GatherRender.parseSeconds(input) + if (seconds == null) player.sendPrefixed(player.tr("common.invalid-amount")) + else { + node.regrowSeconds = seconds + GatherManager.save() + } + show(player, region, node) + } + } + } + + private fun promptDepleted(player: Player, region: ResourceRegion, node: ResourceNode) { + GatherRender.navigate { + player.closeInventory() + ChatPrompt.ask(player, player.tr("gathering.editor.prompt-depleted")) { input -> + if (input.equals(DEFAULT_WORD, ignoreCase = true)) { + node.depleted = null + GatherManager.save() + } else { + val block = Material.matchMaterial(input)?.takeIf { it.isBlock } + if (block == null) player.sendPrefixed(player.tr("gathering.editor.not-a-block")) + else { + node.depleted = block + GatherManager.save() + } + } + show(player, region, node) + } + } + } + + private fun render(player: Player, node: ResourceNode, button: Button): ItemStack = when (button) { + Button.CATEGORY -> GatherRender.button( + player, node.category.icon, "gui.gather-node.category", + listOf( + player.tr("gui.gather-node.current", "value" to player.tr(node.category.key)), + player.tr("gui.gather-node.category-lore"), + ), + ) + + Button.REGROW -> GatherRender.button( + player, Material.CLOCK, "gui.gather-node.regrow", + listOf( + player.tr("gui.gather-node.current", "value" to GatherRender.duration(player, node.regrowSeconds)), + player.tr("gui.gather-node.regrow-lore"), + ), + ) + + Button.DEPLETED -> GatherRender.button( + player, Material.BEDROCK, "gui.gather-node.depleted", + listOf( + player.tr("gui.gather-node.current", "value" to depletedName(player, node)), + player.tr("gui.gather-node.depleted-lore"), + ), + ) + + Button.VANILLA -> GatherRender.button( + player, if (node.vanillaDrops) Material.LIME_DYE else Material.GRAY_DYE, "gui.gather-node.vanilla", + listOf( + player.tr(if (node.vanillaDrops) "gui.gather-node.vanilla-on" else "gui.gather-node.vanilla-off"), + player.tr("gui.gather-node.vanilla-lore"), + ), + ) + + Button.DROPS -> GatherRender.button( + player, Material.CHEST, "gui.gather-node.drops", + listOf(player.tr("gui.gather-node.drops-lore", "amount" to node.drops.size)), + ) + + Button.POOL -> GatherRender.button( + player, Material.DIAMOND_ORE, "gui.gather-node.pool", + listOf(player.tr("gui.gather-node.pool-lore", "amount" to node.pool.size)), + ) + + Button.DELETE -> GatherRender.button( + player, Material.LAVA_BUCKET, "gui.gather-node.delete", + listOf(player.tr("gui.gather-node.delete-lore")), + ) + + Button.BACK -> GatherRender.button( + player, Material.ARROW, "gui.gather-node.back", + listOf(player.tr("gui.gather-node.back-lore")), + ) + } + + companion object { + const val ID = "gather-node" + + private const val ROW_SIZE = 9 + private const val INFO_SLOT = 13 + private const val BACK_SLOT = 49 + private const val DEFAULT_WORD = "default" + + fun show(player: Player, region: ResourceRegion, node: ResourceNode): Boolean { + GatherRender.setContext(player, GatherRender.Context(region.id, nodeId = node.id)) + return GUIManager.open(player, ID) + } + + /** What a resource is set to, a line per setting, for its icon and its menu. */ + fun summary(player: Player, node: ResourceNode): List = listOf( + player.tr("gui.gather-node.line-category", "value" to player.tr(node.category.key)), + player.tr("gui.gather-node.line-regrow", "value" to GatherRender.duration(player, node.regrowSeconds)), + player.tr("gui.gather-node.line-depleted", "value" to depletedName(player, node)), + player.tr(if (node.vanillaDrops) "gui.gather-node.vanilla-on" else "gui.gather-node.vanilla-off"), + player.tr("gui.gather-node.line-drops", "amount" to node.drops.size), + player.tr("gui.gather-node.line-pool", "amount" to node.pool.size), + ) + + private fun depletedName(player: Player, node: ResourceNode): String = when { + node.growsInStages -> player.tr("gui.gather-node.seedling") + else -> { + val block = node.depleted ?: GatheringSettings.snapshot.depletedFor(node.category) + val name = if (block.isAir) player.tr("gui.gather-node.air") else GatherRender.blockName(block) + if (node.depleted == null) player.tr("gui.gather-node.default", "value" to name) else name + } + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherNodeListGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherNodeListGUI.kt new file mode 100644 index 0000000..9b24588 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherNodeListGUI.kt @@ -0,0 +1,129 @@ +package net.trilleo.mc.plugins.tritown.guis.gathering + +import net.trilleo.mc.plugins.tritown.config.GatheringSettings +import net.trilleo.mc.plugins.tritown.enums.PagedLayout +import net.trilleo.mc.plugins.tritown.gathering.GatherCategory +import net.trilleo.mc.plugins.tritown.gathering.GatherManager +import net.trilleo.mc.plugins.tritown.gathering.ResourceNode +import net.trilleo.mc.plugins.tritown.gathering.ResourceRegion +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PagedPluginGUI +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.ClickType +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.inventory.ItemStack + +/** + * The kinds of block a region grows back. + * + * A resource is added by clicking a block — or a seed, for a crop — in your + * own inventory. Nothing is taken: only the kind of block is read, and every + * block of that kind inside the region becomes a node. + */ +class GatherNodeListGUI : PagedPluginGUI( + id = ID, + titleKey = "gui.gather-nodes.title", + rows = 6, + layout = PagedLayout.FRAMED, +) { + + override fun getItems(player: Player): List = + GatherRender.region(player)?.nodes?.map { icon(player, it) }.orEmpty() + + override fun navButtons(player: Player): Map = mapOf( + BACK_OFFSET to GatherRender.button( + player, Material.ARROW, "gui.gather-region.back-region", + listOf(player.tr("gui.gather-region.back-region-lore")), + ), + ADD_OFFSET to GatherRender.button( + player, Material.PAPER, "gui.gather-nodes.add", + listOf(player.tr("gui.gather-nodes.add-lore")), + ), + ) + + override fun onNavClick(event: InventoryClickEvent, offset: Int) { + val player = event.whoClicked as? Player ?: return + val region = GatherRender.region(player) ?: return + if (offset == BACK_OFFSET) { + GatherRender.click(player) + GatherRender.navigate { GatherRegionGUI.show(player, region) } + } + } + + override fun onClick(event: InventoryClickEvent) { + val player = event.whoClicked as? Player + if (player != null && event.clickedInventory === player.inventory) { + event.isCancelled = true + if (!GatherRender.mayEdit(player)) return + val region = GatherRender.region(player) ?: return + event.currentItem?.let { add(player, region, it) } + return + } + super.onClick(event) + } + + override fun onContentClick(event: InventoryClickEvent, page: Int) { + val player = event.whoClicked as? Player ?: return + if (!GatherRender.mayEdit(player)) return + val region = GatherRender.region(player) ?: return + val node = region.nodes.getOrNull(contentIndex(event, page) ?: return) ?: return + + if (event.click == ClickType.SHIFT_LEFT) { + region.nodes.remove(node) + GatherManager.save() + player.sendPrefixed(player.tr("gathering.editor.node-removed", "block" to GatherRender.blockName(node.block))) + refresh(player, event.inventory) + return + } + + GatherRender.click(player) + GatherRender.navigate { GatherNodeGUI.show(player, region, node) } + } + + private fun add(player: Player, region: ResourceRegion, item: ItemStack) { + if (item.type.isAir) return + val block = GatherRender.blockOf(item) ?: run { + player.sendPrefixed(player.tr("gathering.editor.not-a-block")) + return + } + + region.nodeFor(block)?.let { existing -> + GatherRender.navigate { GatherNodeGUI.show(player, region, existing) } + return + } + + val node = ResourceNode( + block = block, + category = GatherCategory.of(block), + regrowSeconds = GatheringSettings.snapshot.defaultRegrow, + ) + region.nodes += node + GatherManager.save() + player.sendPrefixed(player.tr("gathering.editor.node-added", "block" to GatherRender.blockName(block))) + GatherRender.navigate { GatherNodeGUI.show(player, region, node) } + } + + private fun icon(player: Player, node: ResourceNode): ItemStack = GatherRender.card( + GatherRender.blockIcon(node.block), + player.tr("gui.gather-nodes.name", "block" to GatherRender.blockName(node.block)), + GatherNodeGUI.summary(player, node) + listOf( + "", + player.tr("gui.gather-nodes.click"), + player.tr("gui.gather-nodes.shift-click"), + ), + ) + + companion object { + const val ID = "gather-nodes" + private const val BACK_OFFSET = 3 + private const val ADD_OFFSET = 5 + + fun show(player: Player, region: ResourceRegion): Boolean { + GatherRender.setContext(player, GatherRender.Context(region.id)) + return GUIManager.open(player, ID) + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherRegionGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherRegionGUI.kt new file mode 100644 index 0000000..32c1f8d --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherRegionGUI.kt @@ -0,0 +1,198 @@ +package net.trilleo.mc.plugins.tritown.guis.gathering + +import net.kyori.adventure.text.Component +import net.trilleo.mc.plugins.tritown.gathering.* +import net.trilleo.mc.plugins.tritown.registration.GUIFrame +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PluginGUI +import net.trilleo.mc.plugins.tritown.utils.ChatPrompt +import net.trilleo.mc.plugins.tritown.utils.ComponentUtil +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.ItemStack + +/** + * One resource region: what it offers, and everything about it an + * administrator can change — its resources, its spawners, its name and its + * bounds, and whether it is open. + */ +class GatherRegionGUI : PluginGUI( + id = ID, + titleKey = "gui.gather-region.title", + rows = 6, +) { + + private enum class Button { RESOURCES, SPAWNERS, RENAME, TOGGLE, OUTLINE, REGROW, RESIZE, BACK } + + private val layout: Map = buildMap { + val columns = GUIFrame.spacedColumns(4) + listOf(Button.RESOURCES, Button.SPAWNERS, Button.RENAME, Button.TOGGLE) + .zip(columns).forEach { (button, column) -> put(FIRST_ROW * ROW_SIZE + column, button) } + listOf(Button.OUTLINE, Button.REGROW, Button.RESIZE) + .zip(GUIFrame.spacedColumns(3)).forEach { (button, column) -> put(SECOND_ROW * ROW_SIZE + column, button) } + put(BACK_SLOT, Button.BACK) + } + + override fun title(player: Player): Component { + val name = GatherRender.region(player)?.name ?: "" + return ComponentUtil.parse(player.tr("gui.gather-region.title", "name" to name)) + } + + override fun setup(player: Player, inventory: Inventory) { + val region = GatherRender.region(player) ?: return + GUIFrame.draw(inventory, layout.keys + INFO_SLOT) + inventory.setItem(INFO_SLOT, info(player, region)) + layout.forEach { (slot, button) -> inventory.setItem(slot, render(player, region, button)) } + } + + override fun onClick(event: InventoryClickEvent) { + event.isCancelled = true + if (event.clickedInventory !== event.view.topInventory) return + val player = event.whoClicked as? Player ?: return + if (!GatherRender.mayEdit(player)) return + val region = GatherRender.region(player) ?: return + + when (layout[event.rawSlot]) { + Button.RESOURCES -> open(player) { GatherNodeListGUI.show(player, region) } + Button.SPAWNERS -> open(player) { GatherSpawnerListGUI.show(player, region) } + Button.RENAME -> rename(player, region) + Button.TOGGLE -> { + region.enabled = !region.enabled + GatherManager.save() + GatherRender.click(player) + GUIManager.refresh(player) + } + + Button.OUTLINE -> { + GatherRender.navigate { player.closeInventory() } + GatherEditors.outline(player, region.area, OUTLINE_SECONDS) + player.sendPrefixed(player.tr("gathering.editor.outlined", "seconds" to OUTLINE_SECONDS)) + } + + Button.REGROW -> { + val count = Regrowth.regrowAll(region) + player.sendPrefixed(player.tr("gathering.editor.regrown", "amount" to count)) + GatherRender.click(player) + GUIManager.refresh(player) + } + + Button.RESIZE -> resize(player, region) + Button.BACK -> open(player) { GatherListGUI.show(player) } + null -> Unit + } + } + + private fun open(player: Player, action: () -> Unit) { + GatherRender.click(player) + GatherRender.navigate(action) + } + + private fun rename(player: Player, region: ResourceRegion) { + GatherRender.navigate { + player.closeInventory() + ChatPrompt.ask(player, player.tr("gathering.editor.prompt-name")) { input -> + region.name = input + GatherManager.save() + show(player, region) + } + } + } + + private fun resize(player: Player, region: ResourceRegion) { + val area = GatherEditors.selection(player).area() + when (val result = AreaCheck.check(area, except = region.id)) { + is AreaCheck.Result.Ok -> { + if (result.townId != region.townId) { + player.sendPrefixed(player.tr("gathering.area.other-town")) + return + } + Regrowth.regrowAll(region) + region.area = area!! + GatherManager.save() + player.sendPrefixed(player.tr("gathering.editor.resized", "volume" to area.volume)) + GUIManager.refresh(player) + } + + else -> player.sendPrefixed(AreaCheck.message(player, result)) + } + } + + private fun info(player: Player, region: ResourceRegion): ItemStack { + val area = region.area + val lines = listOf( + player.tr("gui.gather-list.id", "id" to region.id), + player.tr("gui.gather-list.town", "town" to GatherAccess.townName(player, region)), + GatherRender.coordinates(player, region), + player.tr( + "gui.gather-region.size", + "x" to area.maxX - area.minX + 1, "y" to area.maxY - area.minY + 1, "z" to area.maxZ - area.minZ + 1, + ), + player.tr("gui.gather-list.offers", "categories" to GatherRender.categories(player, region)), + player.tr("gui.gather-region.regrowing", "amount" to GatherManager.depletedIn(region).size), + ) + return GatherRender.card(GatherRender.icon(region), region.name, lines) + } + + private fun render(player: Player, region: ResourceRegion, button: Button): ItemStack = when (button) { + Button.RESOURCES -> GatherRender.button( + player, Material.IRON_PICKAXE, "gui.gather-region.resources", + listOf(player.tr("gui.gather-region.resources-lore", "amount" to region.nodes.size)), + ) + + Button.SPAWNERS -> GatherRender.button( + player, Material.SPAWNER, "gui.gather-region.spawners", + listOf(player.tr("gui.gather-region.spawners-lore", "amount" to region.spawners.size)), + ) + + Button.RENAME -> GatherRender.button( + player, Material.NAME_TAG, "gui.gather-region.rename", + listOf(player.tr("gui.gather-region.rename-lore")), + ) + + Button.TOGGLE -> GatherRender.button( + player, if (region.enabled) Material.LIME_DYE else Material.GRAY_DYE, + if (region.enabled) "gui.gather-region.enabled" else "gui.gather-region.disabled", + listOf(player.tr("gui.gather-region.toggle-lore")), + ) + + Button.OUTLINE -> GatherRender.button( + player, Material.SPYGLASS, "gui.gather-region.outline", + listOf(player.tr("gui.gather-region.outline-lore")), + ) + + Button.REGROW -> GatherRender.button( + player, Material.BONE_MEAL, "gui.gather-region.regrow", + listOf(player.tr("gui.gather-region.regrow-lore")), + ) + + Button.RESIZE -> GatherRender.button( + player, Material.BLAZE_ROD, "gui.gather-region.resize", + listOf(player.tr("gui.gather-region.resize-lore")), + ) + + Button.BACK -> GatherRender.button( + player, Material.ARROW, "gui.gather-region.back", + listOf(player.tr("gui.gather-region.back-lore")), + ) + } + + companion object { + const val ID = "gather-region" + + private const val ROW_SIZE = 9 + private const val INFO_SLOT = 13 + private const val FIRST_ROW = 3 + private const val SECOND_ROW = 4 + private const val BACK_SLOT = 49 + private const val OUTLINE_SECONDS = 15 + + fun show(player: Player, region: ResourceRegion): Boolean { + GatherRender.setContext(player, GatherRender.Context(region.id)) + return GUIManager.open(player, ID) + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherRender.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherRender.kt new file mode 100644 index 0000000..9f3c44d --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherRender.kt @@ -0,0 +1,160 @@ +package net.trilleo.mc.plugins.tritown.guis.gathering + +import net.kyori.adventure.key.Key +import net.kyori.adventure.sound.Sound +import net.trilleo.mc.plugins.tritown.Main +import net.trilleo.mc.plugins.tritown.gathering.* +import net.trilleo.mc.plugins.tritown.utils.LoreUtil +import net.trilleo.mc.plugins.tritown.utils.itemStack +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Bukkit +import org.bukkit.Material +import org.bukkit.entity.EntityType +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * What every gathering menu draws with, and what each administrator is + * editing as they move between them. + * + * The menus close and reopen as an administrator goes from a region to one of + * its resources and back, and a chat prompt closes them altogether, so where + * they are is kept here rather than in any one menu. + */ +object GatherRender { + + /** Every editor click re-checks this, not only the command that opened the menu. */ + const val EDIT_PERMISSION = "${GatherEditors.ADMIN_PERMISSION}.edit" + + data class Context(val regionId: String, val nodeId: String? = null, val spawnerId: String? = null) + + private val contexts = ConcurrentHashMap() + private val click = Sound.sound(Key.key("minecraft:ui.button.click"), Sound.Source.UI, 1f, 1f) + + fun setContext(player: Player, context: Context) { + contexts[player.uniqueId] = context + } + + fun region(player: Player): ResourceRegion? = contexts[player.uniqueId]?.regionId?.let(GatherManager::get) + + fun node(player: Player): ResourceNode? { + val context = contexts[player.uniqueId] ?: return null + return context.nodeId?.let { region(player)?.node(it) } + } + + fun spawner(player: Player): ResourceSpawner? { + val context = contexts[player.uniqueId] ?: return null + return context.spawnerId?.let { region(player)?.spawner(it) } + } + + /** Whether [player] may still edit; closes their menu when they may not. */ + fun mayEdit(player: Player): Boolean { + if (player.hasPermission(EDIT_PERMISSION)) return true + navigate { player.closeInventory() } + return false + } + + /** Opens the next menu on the following tick, as every menu reached by a click must. */ + fun navigate(open: () -> Unit) { + Bukkit.getScheduler().runTask(Main.instance, Runnable { open() }) + } + + fun click(player: Player) = player.playSound(click) + + fun button(player: Player, material: Material, nameKey: String, lore: List): ItemStack = + itemStack(material) { + name(player.tr(nameKey)) + meta { lore(LoreUtil.wrapLore(lore.joinToString(""))) } + } + + fun card(material: Material, name: String, lines: List, glow: Boolean = false): ItemStack = + itemStack(material) { + name(name) + meta { + lore(LoreUtil.wrapLore(lines.joinToString(""))) + if (glow) setEnchantmentGlintOverride(true) + } + } + + /** The categories [region] offers, joined into one line. */ + fun categories(player: Player, region: ResourceRegion): String = + region.categories().joinToString(player.tr("gathering.list-separator")) { player.tr(it.key) } + .ifEmpty { player.tr("common.none") } + + /** What a region is shown as: the icon of the first thing it offers. */ + fun icon(region: ResourceRegion): Material = region.categories().firstOrNull()?.icon ?: Material.GRASS_BLOCK + + /** An item that shows [block], or a stand-in for a block that has no item form, like a crop. */ + fun blockIcon(block: Material): Material = when { + block.isItem && !block.isAir -> block + else -> CROP_ITEMS[block] ?: Material.STRUCTURE_VOID + } + + fun eggOf(type: EntityType): Material = Material.matchMaterial("${type.name}_SPAWN_EGG") ?: Material.SPAWNER + + /** The mob a spawn egg calls up, or `null` when [item] is not one. */ + fun eggType(item: ItemStack): EntityType? { + val name = item.type.name + if (!name.endsWith(EGG_SUFFIX)) return null + return EntityType.entries.firstOrNull { it.name == name.removeSuffix(EGG_SUFFIX) } + } + + /** + * The block an item stands for, when it can be a resource: the block + * itself, or the crop a seed or vegetable is planted as. + */ + fun blockOf(item: ItemStack): Material? = SEED_BLOCKS[item.type] ?: item.type.takeIf { it.isBlock && !it.isAir } + + /** A block's name in [player]'s own client language. */ + fun blockName(block: Material): String = "" + + fun entityName(type: EntityType): String = "" + + fun coordinates(player: Player, region: ResourceRegion): String { + val area = region.area + return player.tr( + "gathering.coordinates", + "world" to area.world, + "x" to (area.minX + area.maxX) / 2, + "y" to area.minY, + "z" to (area.minZ + area.maxZ) / 2, + ) + } + + /** [seconds] as minutes and seconds, or seconds alone under a minute. */ + fun duration(player: Player, seconds: Int): String = + if (seconds < 60) player.tr("gathering.time-seconds", "seconds" to seconds) + else player.tr("gathering.time", "minutes" to seconds / 60, "seconds" to seconds % 60) + + /** A number of seconds an administrator typed: `90`, `90s`, `5m` or `2h`. */ + fun parseSeconds(input: String): Int? { + val text = input.trim().lowercase() + val unit = when (text.lastOrNull()) { + 's' -> 1 + 'm' -> 60 + 'h' -> 3600 + else -> null + } + val number = (if (unit != null) text.dropLast(1) else text).trim().toIntOrNull() ?: return null + val seconds = number.toLong() * (unit ?: 1) + return seconds.takeIf { it in 1..MAX_SECONDS }?.toInt() + } + + private const val MAX_SECONDS = 7L * 24 * 3600 + private const val EGG_SUFFIX = "_SPAWN_EGG" + + private val SEED_BLOCKS = mapOf( + Material.WHEAT_SEEDS to Material.WHEAT, + Material.CARROT to Material.CARROTS, + Material.POTATO to Material.POTATOES, + Material.BEETROOT_SEEDS to Material.BEETROOTS, + Material.COCOA_BEANS to Material.COCOA, + Material.SWEET_BERRIES to Material.SWEET_BERRY_BUSH, + Material.TORCHFLOWER_SEEDS to Material.TORCHFLOWER_CROP, + Material.PITCHER_POD to Material.PITCHER_CROP, + ) + + private val CROP_ITEMS = SEED_BLOCKS.entries.associate { (item, block) -> block to item } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherSpawnerGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherSpawnerGUI.kt new file mode 100644 index 0000000..742b0e8 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherSpawnerGUI.kt @@ -0,0 +1,221 @@ +package net.trilleo.mc.plugins.tritown.guis.gathering + +import net.kyori.adventure.text.Component +import net.trilleo.mc.plugins.tritown.gathering.* +import net.trilleo.mc.plugins.tritown.registration.GUIFrame +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PluginGUI +import net.trilleo.mc.plugins.tritown.utils.ChatPrompt +import net.trilleo.mc.plugins.tritown.utils.ComponentUtil +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.ClickType +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.ItemStack +import kotlin.math.floor + +/** One spawner: how many mobs it keeps, how quickly it replaces them, how far they roam, and how strong they are. */ +class GatherSpawnerGUI : PluginGUI( + id = ID, + titleKey = "gui.gather-spawner.title", + rows = 6, +) { + + private enum class Button { MAX, RESPAWN, RADIUS, LEVEL, CATEGORY, MOVE, DELETE, BACK } + + /** A number an administrator types in chat, with its question and its limits. */ + private enum class Field(val min: Int, val max: Int) { + MAX(1, 32), RESPAWN(1, 86_400), RADIUS(1, 32), LEVEL(1, 200) + } + + private val layout: Map = buildMap { + listOf(Button.MAX, Button.RESPAWN, Button.RADIUS, Button.LEVEL) + .zip(GUIFrame.spacedColumns(4)).forEach { (button, column) -> put(3 * ROW_SIZE + column, button) } + listOf(Button.CATEGORY, Button.MOVE, Button.DELETE) + .zip(GUIFrame.spacedColumns(3)).forEach { (button, column) -> put(4 * ROW_SIZE + column, button) } + put(BACK_SLOT, Button.BACK) + } + + override fun title(player: Player): Component { + val mob = GatherRender.spawner(player)?.type?.let(GatherRender::entityName) ?: "" + return ComponentUtil.parse(player.tr("gui.gather-spawner.title", "mob" to mob)) + } + + override fun setup(player: Player, inventory: Inventory) { + val region = GatherRender.region(player) ?: return + val spawner = GatherRender.spawner(player) ?: return + GUIFrame.draw(inventory, layout.keys + INFO_SLOT) + inventory.setItem( + INFO_SLOT, + GatherRender.card( + GatherRender.eggOf(spawner.type), + player.tr("gui.gather-spawners.name", "mob" to GatherRender.entityName(spawner.type)), + summary(player, spawner) + player.tr("gui.gather-spawner.alive", "amount" to Spawners.count(spawner)), + ), + ) + layout.forEach { (slot, button) -> inventory.setItem(slot, render(player, region, spawner, button)) } + } + + override fun onClick(event: InventoryClickEvent) { + event.isCancelled = true + if (event.clickedInventory !== event.view.topInventory) return + val player = event.whoClicked as? Player ?: return + if (!GatherRender.mayEdit(player)) return + val region = GatherRender.region(player) ?: return + val spawner = GatherRender.spawner(player) ?: return + + when (layout[event.rawSlot]) { + Button.MAX -> prompt(player, region, spawner, Field.MAX) + Button.RESPAWN -> prompt(player, region, spawner, Field.RESPAWN) + Button.RADIUS -> prompt(player, region, spawner, Field.RADIUS) + Button.LEVEL -> prompt(player, region, spawner, Field.LEVEL) + Button.CATEGORY -> { + spawner.category = spawner.category.next() + GatherManager.save() + GatherRender.click(player) + GUIManager.refresh(player) + } + + Button.MOVE -> { + val at = player.location + if (!region.area.contains(at)) { + player.sendPrefixed(player.tr("gathering.editor.stand-inside")) + return + } + Spawners.clear(spawner) + spawner.x = at.blockX + 0.5 + spawner.y = at.blockY.toDouble() + spawner.z = at.blockZ + 0.5 + GatherManager.save() + player.sendPrefixed(player.tr("gathering.editor.spawner-moved")) + GUIManager.refresh(player) + } + + Button.DELETE -> if (event.click == ClickType.SHIFT_LEFT) { + GatherSpawnerListGUI.remove(player, region, spawner) + GatherRender.navigate { GatherSpawnerListGUI.show(player, region) } + } + + Button.BACK -> { + GatherRender.click(player) + GatherRender.navigate { GatherSpawnerListGUI.show(player, region) } + } + + null -> Unit + } + } + + private fun prompt(player: Player, region: ResourceRegion, spawner: ResourceSpawner, field: Field) { + val question = when (field) { + Field.MAX -> player.tr("gathering.editor.prompt-max", "max" to field.max) + Field.RESPAWN -> player.tr("gathering.editor.prompt-respawn") + Field.RADIUS -> player.tr("gathering.editor.prompt-radius", "max" to field.max) + Field.LEVEL -> player.tr("gathering.editor.prompt-level", "max" to field.max) + } + + GatherRender.navigate { + player.closeInventory() + ChatPrompt.ask(player, question) { input -> + val value = if (field == Field.RESPAWN) GatherRender.parseSeconds(input) else input.trim().toIntOrNull() + if (value == null || value !in field.min..field.max) { + player.sendPrefixed(player.tr("common.invalid-amount")) + } else { + when (field) { + Field.MAX -> spawner.maxAlive = value + Field.RESPAWN -> spawner.respawnSeconds = value + Field.RADIUS -> spawner.radius = value + Field.LEVEL -> spawner.level = value + } + GatherManager.save() + } + show(player, region, spawner) + } + } + } + + private fun render(player: Player, region: ResourceRegion, spawner: ResourceSpawner, button: Button): ItemStack = + when (button) { + Button.MAX -> GatherRender.button( + player, Material.EGG, "gui.gather-spawner.max", + listOf( + player.tr("gui.gather-node.current", "value" to spawner.maxAlive), + player.tr("gui.gather-spawner.max-lore"), + ), + ) + + Button.RESPAWN -> GatherRender.button( + player, Material.CLOCK, "gui.gather-spawner.respawn", + listOf( + player.tr("gui.gather-node.current", "value" to GatherRender.duration(player, spawner.respawnSeconds)), + player.tr("gui.gather-spawner.respawn-lore"), + ), + ) + + Button.RADIUS -> GatherRender.button( + player, Material.LEAD, "gui.gather-spawner.radius", + listOf( + player.tr("gui.gather-node.current", "value" to spawner.radius), + player.tr("gui.gather-spawner.radius-lore"), + ), + ) + + Button.LEVEL -> GatherRender.button( + player, Material.EXPERIENCE_BOTTLE, "gui.gather-spawner.level", + listOf( + player.tr("gui.gather-node.current", "value" to spawner.level), + player.tr("gui.gather-spawner.level-lore"), + ), + ) + + Button.CATEGORY -> GatherRender.button( + player, spawner.category.icon, "gui.gather-node.category", + listOf( + player.tr("gui.gather-node.current", "value" to player.tr(spawner.category.key)), + player.tr("gui.gather-node.category-lore"), + ), + ) + + Button.MOVE -> GatherRender.button( + player, Material.COMPASS, "gui.gather-spawner.move", + listOf(player.tr("gui.gather-spawner.move-lore")), + ) + + Button.DELETE -> GatherRender.button( + player, Material.LAVA_BUCKET, "gui.gather-spawner.delete", + listOf(player.tr("gui.gather-spawner.delete-lore")), + ) + + Button.BACK -> GatherRender.button( + player, Material.ARROW, "gui.gather-spawner.back", + listOf(player.tr("gui.gather-spawner.back-lore", "id" to region.id)), + ) + } + + companion object { + const val ID = "gather-spawner" + + private const val ROW_SIZE = 9 + private const val INFO_SLOT = 13 + private const val BACK_SLOT = 49 + + fun show(player: Player, region: ResourceRegion, spawner: ResourceSpawner): Boolean { + GatherRender.setContext(player, GatherRender.Context(region.id, spawnerId = spawner.id)) + return GUIManager.open(player, ID) + } + + fun summary(player: Player, spawner: ResourceSpawner): List = listOf( + player.tr("gui.gather-node.line-category", "value" to player.tr(spawner.category.key)), + player.tr("gui.gather-spawner.line-max", "amount" to spawner.maxAlive), + player.tr("gui.gather-spawner.line-respawn", "value" to GatherRender.duration(player, spawner.respawnSeconds)), + player.tr("gui.gather-spawner.line-radius", "amount" to spawner.radius), + player.tr("gui.gather-spawner.line-level", "amount" to spawner.level), + player.tr( + "gui.gather-spawner.line-at", + "x" to floor(spawner.x).toInt(), "y" to floor(spawner.y).toInt(), "z" to floor(spawner.z).toInt(), + ), + ) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherSpawnerListGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherSpawnerListGUI.kt new file mode 100644 index 0000000..1bbe85d --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/GatherSpawnerListGUI.kt @@ -0,0 +1,142 @@ +package net.trilleo.mc.plugins.tritown.guis.gathering + +import net.trilleo.mc.plugins.tritown.enums.PagedLayout +import net.trilleo.mc.plugins.tritown.gathering.* +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PagedPluginGUI +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.ClickType +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.inventory.ItemStack + +/** + * The spawners of a region: pens of animals and arenas of monsters. + * + * A spawner is added where the administrator stands, by clicking a spawn egg + * in their own inventory. The egg is only read, never used up. + */ +class GatherSpawnerListGUI : PagedPluginGUI( + id = ID, + titleKey = "gui.gather-spawners.title", + rows = 6, + layout = PagedLayout.FRAMED, +) { + + override fun getItems(player: Player): List = + GatherRender.region(player)?.spawners?.map { icon(player, it) }.orEmpty() + + override fun navButtons(player: Player): Map = mapOf( + BACK_OFFSET to GatherRender.button( + player, Material.ARROW, "gui.gather-region.back-region", + listOf(player.tr("gui.gather-region.back-region-lore")), + ), + ADD_OFFSET to GatherRender.button( + player, Material.PAPER, "gui.gather-spawners.add", + listOf(player.tr("gui.gather-spawners.add-lore")), + ), + ) + + override fun onNavClick(event: InventoryClickEvent, offset: Int) { + val player = event.whoClicked as? Player ?: return + val region = GatherRender.region(player) ?: return + if (offset == BACK_OFFSET) { + GatherRender.click(player) + GatherRender.navigate { GatherRegionGUI.show(player, region) } + } + } + + override fun onClick(event: InventoryClickEvent) { + val player = event.whoClicked as? Player + if (player != null && event.clickedInventory === player.inventory) { + event.isCancelled = true + if (!GatherRender.mayEdit(player)) return + val region = GatherRender.region(player) ?: return + event.currentItem?.let { add(player, region, it) } + return + } + super.onClick(event) + } + + override fun onContentClick(event: InventoryClickEvent, page: Int) { + val player = event.whoClicked as? Player ?: return + if (!GatherRender.mayEdit(player)) return + val region = GatherRender.region(player) ?: return + val spawner = region.spawners.getOrNull(contentIndex(event, page) ?: return) ?: return + + if (event.click == ClickType.SHIFT_LEFT) { + remove(player, region, spawner) + refresh(player, event.inventory) + return + } + + GatherRender.click(player) + GatherRender.navigate { GatherSpawnerGUI.show(player, region, spawner) } + } + + private fun add(player: Player, region: ResourceRegion, item: ItemStack) { + if (item.type.isAir) return + val type = GatherRender.eggType(item) ?: run { + player.sendPrefixed(player.tr("gathering.editor.not-an-egg")) + return + } + val at = player.location + if (!region.area.contains(at)) { + player.sendPrefixed(player.tr("gathering.editor.stand-inside")) + return + } + + val category = GatherCategory.of(type) + val spawner = ResourceSpawner( + type = type, + category = category, + x = at.blockX + 0.5, + y = at.blockY.toDouble(), + z = at.blockZ + 0.5, + maxAlive = if (category == GatherCategory.COMBAT) DEFAULT_HOSTILE else DEFAULT_ANIMALS, + respawnSeconds = DEFAULT_RESPAWN, + radius = DEFAULT_RADIUS, + ) + region.spawners += spawner + GatherManager.save() + player.sendPrefixed(player.tr("gathering.editor.spawner-added", "mob" to GatherRender.entityName(type))) + GatherRender.navigate { GatherSpawnerGUI.show(player, region, spawner) } + } + + private fun icon(player: Player, spawner: ResourceSpawner): ItemStack = GatherRender.card( + GatherRender.eggOf(spawner.type), + player.tr("gui.gather-spawners.name", "mob" to GatherRender.entityName(spawner.type)), + GatherSpawnerGUI.summary(player, spawner) + listOf( + "", + player.tr("gui.gather-spawners.click"), + player.tr("gui.gather-spawners.shift-click"), + ), + ) + + companion object { + const val ID = "gather-spawners" + private const val BACK_OFFSET = 3 + private const val ADD_OFFSET = 5 + private const val DEFAULT_ANIMALS = 4 + private const val DEFAULT_HOSTILE = 3 + private const val DEFAULT_RESPAWN = 30 + private const val DEFAULT_RADIUS = 6 + + fun show(player: Player, region: ResourceRegion): Boolean { + GatherRender.setContext(player, GatherRender.Context(region.id)) + return GUIManager.open(player, ID) + } + + /** Takes [spawner] out of [region], and its mobs out of the world. */ + fun remove(player: Player, region: ResourceRegion, spawner: ResourceSpawner) { + Spawners.clear(spawner) + region.spawners.remove(spawner) + GatherManager.save() + player.sendPrefixed( + player.tr("gathering.editor.spawner-removed", "mob" to GatherRender.entityName(spawner.type)) + ) + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/ResourcesGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/ResourcesGUI.kt new file mode 100644 index 0000000..c5c5a14 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/gathering/ResourcesGUI.kt @@ -0,0 +1,102 @@ +package net.trilleo.mc.plugins.tritown.guis.gathering + +import com.palmergames.bukkit.towny.TownyAPI +import net.trilleo.mc.plugins.tritown.enums.PagedLayout +import net.trilleo.mc.plugins.tritown.gathering.* +import net.trilleo.mc.plugins.tritown.guis.menu.MainMenuGUI +import net.trilleo.mc.plugins.tritown.guis.menu.MenuRender +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PagedPluginGUI +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.inventory.ItemStack + +/** + * A player's view of their town's resource regions: where each is, what it + * offers and how much of it is growing back, with their own tally of what they + * have gathered above the list. Clicking a region traces its border so it is + * easy to find. + */ +class ResourcesGUI : PagedPluginGUI( + id = ID, + titleKey = "gui.resources.title", + rows = 6, + layout = PagedLayout.FRAMED, +) { + + override fun getItems(player: Player): List = regions(player).map { icon(player, it) } + + override fun topButtons(player: Player): Map = mapOf(STATS_OFFSET to stats(player)) + + override fun navButtons(player: Player): Map = mapOf(MenuRender.BACK_OFFSET to MenuRender.back(player)) + + override fun onNavClick(event: InventoryClickEvent, offset: Int) { + val player = event.whoClicked as? Player ?: return + if (offset == MenuRender.BACK_OFFSET) MenuRender.later(player) { MainMenuGUI.show(player) } + } + + override fun onContentClick(event: InventoryClickEvent, page: Int) { + val player = event.whoClicked as? Player ?: return + val region = regions(player).getOrNull(contentIndex(event, page) ?: return) ?: return + MenuRender.later(player) { + player.closeInventory() + GatherEditors.outline(player, region.area, OUTLINE_SECONDS) + player.sendPrefixed( + player.tr( + "gathering.menu.located", + "name" to region.name, "coordinates" to GatherRender.coordinates(player, region), + ) + ) + } + } + + private fun regions(player: Player): List { + val town = TownyAPI.getInstance().getResident(player)?.townOrNull ?: return emptyList() + return GatherManager.ofTown(town.uuid).filter { it.enabled } + } + + private fun icon(player: Player, region: ResourceRegion): ItemStack { + val lines = buildList { + add(GatherRender.coordinates(player, region)) + add(player.tr("gui.gather-list.offers", "categories" to GatherRender.categories(player, region))) + region.nodes.forEach { node -> + add(player.tr("gui.resources.node", "block" to GatherRender.blockName(node.block), + "time" to GatherRender.duration(player, node.regrowSeconds))) + } + region.spawners.forEach { spawner -> + add(player.tr("gui.resources.spawner", "mob" to GatherRender.entityName(spawner.type), + "amount" to spawner.maxAlive)) + } + add(player.tr("gui.gather-region.regrowing", "amount" to GatherManager.depletedIn(region).size)) + add("") + add(player.tr("gui.resources.click")) + } + return GatherRender.card(GatherRender.icon(region), region.name, lines) + } + + private fun stats(player: Player): ItemStack { + val counts = GatherStats.of(player) + val lines = GatherCategory.entries.map { category -> + player.tr("gui.resources.stat", "category" to player.tr(category.key), "amount" to counts[category]) + } + return GatherRender.card(Material.BOOK, player.tr("gui.resources.stats"), lines) + } + + companion object { + const val ID = "resources" + private const val STATS_OFFSET = 4 + private const val OUTLINE_SECONDS = 15 + + /** Whether [player]'s town has a region open to gather in, so the main menu knows to offer this. */ + fun hasRegions(player: Player): Boolean { + if (!GatherManager.isReady) return false + val town = TownyAPI.getInstance().getResident(player)?.townOrNull ?: return false + return GatherManager.ofTown(town.uuid).any { it.enabled } + } + + fun show(player: Player): Boolean = GUIManager.open(player, ID) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/menu/MainMenuGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/menu/MainMenuGUI.kt index 900d1ed..49b8ec6 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/menu/MainMenuGUI.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/menu/MainMenuGUI.kt @@ -11,6 +11,7 @@ import net.trilleo.mc.plugins.tritown.economy.EconomyService import net.trilleo.mc.plugins.tritown.enums.FillMode import net.trilleo.mc.plugins.tritown.guis.admin.AdminPanelGUI import net.trilleo.mc.plugins.tritown.guis.admin.PanelRender +import net.trilleo.mc.plugins.tritown.guis.gathering.ResourcesGUI import net.trilleo.mc.plugins.tritown.guis.storage.StorageRender import net.trilleo.mc.plugins.tritown.mobs.BestiaryRecords import net.trilleo.mc.plugins.tritown.news.NewsManager @@ -39,7 +40,8 @@ import java.util.concurrent.ConcurrentHashMap /** * The way in to everything TriTown offers a player. * - * The profile sits on its own at the top, and the buttons below it are laid + * The profile sits at the top — beside the viewer's town's resource regions, + * when it has any — and the buttons below it are laid * out in rows of up to three. A button for something the server has switched * off, or the viewer may not use, is left out rather than shown greyed, and * each row is centred on what is left — so the menu never has a hole in it, @@ -57,7 +59,7 @@ class MainMenuGUI : PluginGUI( ) { private enum class Button { - PROFILE, TOWN, STORAGE, SHOP, TRADE, PAY, LEADERBOARD, SERVER, FORGE, NEWS, BESTIARY, SIDEBAR, ADMIN, CLOSE + PROFILE, RESOURCES, TOWN, STORAGE, SHOP, TRADE, PAY, LEADERBOARD, SERVER, FORGE, NEWS, BESTIARY, SIDEBAR, ADMIN, CLOSE } /** Which button each slot holds, per viewer, since the buttons shown depend on who is looking. */ @@ -78,6 +80,7 @@ class MainMenuGUI : PluginGUI( val player = event.whoClicked as? Player ?: return when (layouts[player.uniqueId]?.get(event.rawSlot)) { Button.TOWN -> MenuRender.later(player) { player.performCommand(TOWNY_MENU_COMMAND) } + Button.RESOURCES -> MenuRender.later(player) { CommandRegistrar.run(player, "resources") } Button.STORAGE -> MenuRender.later(player) { CommandRegistrar.run(player, "storage") } Button.SHOP -> MenuRender.later(player) { CommandRegistrar.run(player, "trades") } Button.TRADE -> MenuRender.later(player) { PlayerPickerGUI.show(player, PlayerPickerGUI.Mode.TRADE) } @@ -115,7 +118,7 @@ class MainMenuGUI : PluginGUI( */ private fun layout(player: Player): Map { val rows = listOf( - listOf(Button.PROFILE), + listOfNotNull(Button.PROFILE, Button.RESOURCES.takeIf { ResourcesGUI.hasRegions(player) }), listOfNotNull( Button.TOWN.takeIf { hasTownyMenu() }, Button.STORAGE.takeIf { StorageManager.isAvailable }, @@ -161,6 +164,7 @@ class MainMenuGUI : PluginGUI( private fun render(player: Player, button: Button): ItemStack = when (button) { Button.PROFILE -> profile(player) Button.TOWN -> town(player) + Button.RESOURCES -> card(player, Material.IRON_PICKAXE, "gui.menu.resources", "gui.menu.resources-lore") Button.STORAGE -> storage(player) Button.SHOP -> card(player, Material.EMERALD, "gui.menu.shop", "gui.menu.shop-lore") Button.TRADE -> trade(player) diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/gathering/GatherBlockListener.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/gathering/GatherBlockListener.kt new file mode 100644 index 0000000..48dffbb --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/gathering/GatherBlockListener.kt @@ -0,0 +1,206 @@ +package net.trilleo.mc.plugins.tritown.listeners.gathering + +import net.trilleo.mc.plugins.tritown.gathering.* +import net.trilleo.mc.plugins.tritown.protection.Protection +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Material +import org.bukkit.Tag +import org.bukkit.block.Block +import org.bukkit.entity.Player +import org.bukkit.event.EventHandler +import org.bukkit.event.EventPriority +import org.bukkit.event.Listener +import org.bukkit.event.block.* +import org.bukkit.event.entity.EntityChangeBlockEvent +import org.bukkit.event.entity.EntityExplodeEvent +import org.bukkit.event.player.PlayerBucketEmptyEvent +import org.bukkit.event.player.PlayerBucketFillEvent +import org.bukkit.event.player.PlayerHarvestBlockEvent +import org.bukkit.event.player.PlayerInteractEvent +import org.bukkit.event.world.StructureGrowEvent + +/** + * Harvesting inside resource regions, and keeping everything else in them as + * the administrator built it. + * + * Only a ripe node may be broken, and only by the town's residents. Nothing may + * be placed, poured, tilled, stripped or trampled, and the world itself is + * held still: nothing grows, spreads, decays, burns, melts or explodes there, + * because TriTown does the growing. An administrator in building mode is left + * to Towny alone. + */ +class GatherBlockListener : Listener { + + // ── Breaking ──────────────────────────────────────────────────────── + + /** + * Decides a break before Towny does. An approved harvest leaves a permit + * so a town that denies its residents the right to destroy still lets + * them gather; anything else is refused here and never reaches Towny. + */ + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onBreak(event: BlockBreakEvent) { + val block = event.block + val region = GatherManager.at(block) ?: return + val player = event.player + + if (GatherEditors.isBuilding(player)) { + GatherManager.clearDepleted(BlockKey.of(block)) + return + } + + when (val outcome = Harvest.check(player, region, block)) { + is Harvest.Outcome.Allowed -> { + Harvest.approve(player, region, outcome.node, block) + GatherPermits.grant(player, block.location) + } + + else -> { + event.isCancelled = true + Harvest.explain(player, region, outcome) + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + fun onHarvest(event: BlockBreakEvent) { + Harvest.complete(event) + } + + // ── Changing the region ───────────────────────────────────────────── + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onPlace(event: BlockPlaceEvent) { + if (refuses(event.player, event.block)) event.isCancelled = true + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onMultiPlace(event: BlockMultiPlaceEvent) { + if (event.replacedBlockStates.any { refuses(event.player, it.block) }) event.isCancelled = true + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onEmpty(event: PlayerBucketEmptyEvent) { + if (refuses(event.player, event.block)) event.isCancelled = true + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onFill(event: PlayerBucketFillEvent) { + if (refuses(event.player, event.block)) event.isCancelled = true + } + + /** Berries picked by hand would come back on the plant's own schedule, outside the region's. */ + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onPick(event: PlayerHarvestBlockEvent) { + if (refuses(event.player, event.harvestedBlock)) event.isCancelled = true + } + + /** Trampling farmland, and tools that reshape a block: stripping, tilling, paths, wax and fire. */ + @EventHandler(priority = EventPriority.LOWEST) + fun onInteract(event: PlayerInteractEvent) { + val block = event.clickedBlock ?: return + val reshapes = when (event.action) { + Action.PHYSICAL -> block.type == Material.FARMLAND + Action.RIGHT_CLICK_BLOCK -> event.item?.type?.let(::reshapes) == true + else -> false + } + if (reshapes && refuses(event.player, block, hint = event.action != Action.PHYSICAL)) { + event.setUseInteractedBlock(org.bukkit.event.Event.Result.DENY) + event.setUseItemInHand(org.bukkit.event.Event.Result.DENY) + } + } + + // ── The world ─────────────────────────────────────────────────────── + + /** Mobs trampling crops, sheep eating grass, endermen lifting blocks, sand falling. */ + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onEntityChange(event: EntityChangeBlockEvent) { + val player = event.entity as? Player + if (player != null && GatherEditors.isBuilding(player)) return + if (GatherManager.at(event.block) != null) event.isCancelled = true + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onGrow(event: BlockGrowEvent) = still(event, event.block) + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onFertilize(event: BlockFertilizeEvent) = still(event, event.block) + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onSpread(event: BlockSpreadEvent) = still(event, event.block) + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onFade(event: BlockFadeEvent) = still(event, event.block) + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onForm(event: BlockFormEvent) = still(event, event.block) + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onDecay(event: LeavesDecayEvent) = still(event, event.block) + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onBurn(event: BlockBurnEvent) = still(event, event.block) + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onIgnite(event: BlockIgniteEvent) { + val player = event.player + if (player != null && GatherEditors.isBuilding(player)) return + still(event, event.block) + } + + /** Water or lava running in from outside would wash crops away and make obsidian of nodes. */ + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onFlow(event: BlockFromToEvent) { + if (GatherManager.at(event.toBlock) != null && GatherManager.at(event.block) == null) event.isCancelled = true + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onStructure(event: StructureGrowEvent) { + event.blocks.removeIf { GatherManager.at(it.location) != null } + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onBlockExplode(event: BlockExplodeEvent) { + event.blockList().removeIf { GatherManager.at(it) != null } + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onEntityExplode(event: EntityExplodeEvent) { + event.blockList().removeIf { GatherManager.at(it) != null } + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onPistonExtend(event: BlockPistonExtendEvent) { + if (pistonTouches(event.block, event.blocks, event.direction)) event.isCancelled = true + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onPistonRetract(event: BlockPistonRetractEvent) { + if (pistonTouches(event.block, event.blocks, event.direction)) event.isCancelled = true + } + + // ── Helpers ───────────────────────────────────────────────────────── + + /** Whether [player] may not change [block], telling them so when [hint] is set. */ + private fun refuses(player: Player, block: Block, hint: Boolean = true): Boolean { + if (GatherManager.at(block) == null || GatherEditors.isBuilding(player)) return false + if (hint) Protection.hint(player, player.tr("gathering.hint.protected")) + return true + } + + private fun still(event: org.bukkit.event.Cancellable, block: Block) { + if (GatherManager.at(block) != null) event.isCancelled = true + } + + private fun pistonTouches(piston: Block, moved: List, direction: org.bukkit.block.BlockFace): Boolean = + GatherManager.at(piston) != null || + moved.any { GatherManager.at(it) != null || GatherManager.at(it.getRelative(direction)) != null } + + private fun reshapes(item: Material): Boolean = + Tag.ITEMS_AXES.isTagged(item) || Tag.ITEMS_SHOVELS.isTagged(item) || Tag.ITEMS_HOES.isTagged(item) || + item in RESHAPING + + private companion object { + val RESHAPING = setOf(Material.BONE_MEAL, Material.HONEYCOMB, Material.FLINT_AND_STEEL, Material.FIRE_CHARGE) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/gathering/GatherEntityListener.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/gathering/GatherEntityListener.kt new file mode 100644 index 0000000..220d962 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/gathering/GatherEntityListener.kt @@ -0,0 +1,105 @@ +package net.trilleo.mc.plugins.tritown.listeners.gathering + +import net.trilleo.mc.plugins.tritown.gathering.* +import net.trilleo.mc.plugins.tritown.protection.Protection +import org.bukkit.Material +import org.bukkit.entity.Entity +import org.bukkit.entity.Mob +import org.bukkit.entity.Player +import org.bukkit.event.EventHandler +import org.bukkit.event.EventPriority +import org.bukkit.event.Listener +import org.bukkit.event.entity.* +import org.bukkit.event.player.PlayerInteractEntityEvent +import org.bukkit.event.world.EntitiesLoadEvent + +/** + * The mobs a region's spawners keep about. + * + * Only the town's residents may hurt, shear or milk them, and a resident does + * so even where the town denies residents the right to destroy or use: the hit + * or the click is cleared here first and Towny's refusal of it lifted (see + * [GatherPermits]). Nobody may lead them off, rename them or breed more, and + * the sun does not burn them, so a spawner always has what it was set up for. + */ +class GatherEntityListener : Listener { + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onHit(event: EntityDamageByEntityEvent) { + val victim = event.entity + val (region, _) = Spawners.ownerOf(victim) ?: return + val player = Protection.responsible(event.damager) ?: return + if (GatherEditors.isBuilding(player)) return + // Anyone may defend themselves against a monster that has come for them. + if ((victim as? Mob)?.target == player) return + + val refusal = GatherAccess.refusal(player, region, victim.location) + if (refusal != null) { + event.isCancelled = true + GatherAccess.hint(player, region, refusal) + return + } + GatherPermits.grant(player, victim.location) + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onInteract(event: PlayerInteractEntityEvent) { + val entity = event.rightClicked + val (region, _) = Spawners.ownerOf(entity) ?: return + val player = event.player + if (GatherEditors.isBuilding(player)) return + + val held = player.inventory.getItem(event.hand).type + if (held == Material.NAME_TAG || held == Material.LEAD) { + event.isCancelled = true + return + } + + val refusal = GatherAccess.refusal(player, region, entity.location) + if (refusal != null) { + event.isCancelled = true + GatherAccess.hint(player, region, refusal) + return + } + GatherPermits.grant(player, entity.location) + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + fun onDeath(event: EntityDeathEvent) { + val entity = event.entity + val (_, spawner) = Spawners.ownerOf(entity) ?: return + Spawners.forget(entity) + entity.killer?.let { GatherStats.add(it, spawner.category) } + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onBreed(event: EntityBreedEvent) { + if (spawned(event.mother) || spawned(event.father)) event.isCancelled = true + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onLeash(event: org.bukkit.event.entity.PlayerLeashEntityEvent) { + if (spawned(event.entity)) event.isCancelled = true + } + + /** Burning in daylight; fire a player or a block sets is still fire. */ + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onCombust(event: EntityCombustEvent) { + if (event !is EntityCombustByEntityEvent && event !is EntityCombustByBlockEvent && spawned(event.entity)) { + event.isCancelled = true + } + } + + /** A drowned zombie or a struck pig would stop being the mob its spawner counts. */ + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onTransform(event: EntityTransformEvent) { + if (spawned(event.entity)) event.isCancelled = true + } + + @EventHandler + fun onLoad(event: EntitiesLoadEvent) { + event.entities.forEach(Spawners::adopt) + } + + private fun spawned(entity: Entity): Boolean = entity !is Player && Spawners.isSpawned(entity) +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/gathering/GatherTownyListener.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/gathering/GatherTownyListener.kt new file mode 100644 index 0000000..c78cd2c --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/gathering/GatherTownyListener.kt @@ -0,0 +1,69 @@ +package net.trilleo.mc.plugins.tritown.listeners.gathering + +import com.palmergames.bukkit.towny.event.DeleteTownEvent +import com.palmergames.bukkit.towny.event.MobRemovalEvent +import com.palmergames.bukkit.towny.event.actions.TownyActionEvent +import com.palmergames.bukkit.towny.event.actions.TownyDestroyEvent +import com.palmergames.bukkit.towny.event.actions.TownyItemuseEvent +import com.palmergames.bukkit.towny.event.actions.TownySwitchEvent +import com.palmergames.bukkit.towny.event.mobs.MobSpawnRemovalEvent +import net.trilleo.mc.plugins.tritown.Main +import net.trilleo.mc.plugins.tritown.gathering.GatherManager +import net.trilleo.mc.plugins.tritown.gathering.GatherPermits +import net.trilleo.mc.plugins.tritown.gathering.Spawners +import org.bukkit.event.EventHandler +import org.bukkit.event.EventPriority +import org.bukkit.event.Listener + +/** + * Where resource regions meet Towny's own rules. + * + * A town can deny its residents the right to destroy and use anything, and + * a starter town usually does. Gathering is the one exception: an action + * TriTown has already cleared, for that player at that block this tick (see + * [GatherPermits]), has Towny's refusal lifted. Nothing else is touched, so a + * resident still cannot build, open a door or break a block that is not a + * ripe resource. Building is never lifted at all. + * + * Towny's mob rules would also remove a spawner's monsters from a town that + * has mobs switched off, so those are let be. + */ +class GatherTownyListener : Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + fun onDestroy(event: TownyDestroyEvent) = lift(event) + + @EventHandler(priority = EventPriority.HIGHEST) + fun onItemuse(event: TownyItemuseEvent) = lift(event) + + @EventHandler(priority = EventPriority.HIGHEST) + fun onSwitch(event: TownySwitchEvent) = lift(event) + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + fun onSpawnRemoval(event: MobSpawnRemovalEvent) { + if (Spawners.isSpawning || event.entity?.let(Spawners::isSpawned) == true) event.isCancelled = true + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + fun onRemoval(event: MobRemovalEvent) { + if (Spawners.isSpawned(event.entity)) event.isCancelled = true + } + + /** A deleted town's regions go with it, each grown back first so nothing is left as bedrock. */ + @EventHandler(priority = EventPriority.MONITOR) + fun onTownDeleted(event: DeleteTownEvent) { + val regions = GatherManager.ofTown(event.townUUID) + for (region in regions) { + Spawners.clear(region) + GatherManager.delete(region.id) + Main.instance.logger.info("Removed the resource region ${region.id}: its town ${event.townName} was deleted") + } + } + + private fun lift(event: TownyActionEvent) { + if (event.isCancelled && GatherPermits.isGranted(event.player, event.location)) { + event.isCancelled = false + event.suppressMessage() + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/gathering/GatherWandListener.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/gathering/GatherWandListener.kt new file mode 100644 index 0000000..c533b70 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/gathering/GatherWandListener.kt @@ -0,0 +1,70 @@ +package net.trilleo.mc.plugins.tritown.listeners.gathering + +import net.trilleo.mc.plugins.tritown.gathering.* +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Color +import org.bukkit.event.EventHandler +import org.bukkit.event.EventPriority +import org.bukkit.event.Listener +import org.bukkit.event.block.Action +import org.bukkit.event.block.BlockBreakEvent +import org.bukkit.event.player.PlayerInteractEvent +import org.bukkit.event.player.PlayerQuitEvent +import org.bukkit.inventory.EquipmentSlot + +/** + * The region wand: a left click picks the first corner, a right click the + * second, and each pick traces the box chosen so far. + * + * Also lets go of everything gathering remembers about a player who leaves. + */ +class GatherWandListener : Listener { + + @EventHandler(priority = EventPriority.LOWEST) + fun onUse(event: PlayerInteractEvent) { + if (event.hand != EquipmentSlot.HAND || !GatherEditors.isWand(event.item)) return + val block = event.clickedBlock ?: return + val player = event.player + if (!player.hasPermission(GatherEditors.ADMIN_PERMISSION)) return + + val first = when (event.action) { + Action.LEFT_CLICK_BLOCK -> true + Action.RIGHT_CLICK_BLOCK -> false + else -> return + } + event.isCancelled = true + + val selection = GatherEditors.selection(player) + if (first) selection.first = block.location else selection.second = block.location + player.sendPrefixed( + player.tr( + if (first) "gathering.wand.first" else "gathering.wand.second", + "x" to block.x, "y" to block.y, "z" to block.z, + ) + ) + + val area = selection.area() ?: return + player.sendPrefixed(player.tr("gathering.wand.size", "volume" to area.volume)) + GatherEditors.outline(player, area, OUTLINE_SECONDS, Color.AQUA) + } + + /** A creative-mode click breaks a block outright, which a wand must never do. */ + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onBreak(event: BlockBreakEvent) { + if (GatherEditors.isWand(event.player.inventory.itemInMainHand)) event.isCancelled = true + } + + @EventHandler + fun onQuit(event: PlayerQuitEvent) { + val player = event.player + GatherEditors.forget(player) + GatherPermits.forget(player) + GatherNotices.forget(player) + Harvest.forget(player) + } + + private companion object { + const val OUTLINE_SECONDS = 10 + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/mobs/MobSetup.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/mobs/MobSetup.kt index c8226eb..1e973d1 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/mobs/MobSetup.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/mobs/MobSetup.kt @@ -32,8 +32,17 @@ object MobSetup { * summoner's minion, or one an administrator asks for — as [kind] if one is * given, with the affixes the kind always has. It is unranked, and never * eligible: it drops nothing beyond vanilla's loot. + * + * [prepare] runs before the mob joins the world, so anything it marks the + * mob with is already there when other plugins see the spawn. */ - fun spawn(at: Location, type: EntityType, level: Int, kind: MobKindDef?): LivingEntity? { + fun spawn( + at: Location, + type: EntityType, + level: Int, + kind: MobKindDef?, + prepare: (LivingEntity) -> Unit = {}, + ): LivingEntity? { val profile = MobProfile( level = level, rank = MobRank.NORMAL, @@ -43,7 +52,10 @@ object MobSetup { kind = kind?.id, ) val entity = at.world.spawnEntity(at, type, SpawnReason.CUSTOM) { spawned -> - (spawned as? LivingEntity)?.let { MobProfiles.assign(it, profile) } + (spawned as? LivingEntity)?.let { + MobProfiles.assign(it, profile) + prepare(it) + } } val mob = entity as? LivingEntity ?: run { entity.remove() diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/tasks/gathering/GatherSaveTask.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/tasks/gathering/GatherSaveTask.kt new file mode 100644 index 0000000..4f9dc70 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/tasks/gathering/GatherSaveTask.kt @@ -0,0 +1,24 @@ +package net.trilleo.mc.plugins.tritown.tasks.gathering + +import net.trilleo.mc.plugins.tritown.config.GatheringSettings +import net.trilleo.mc.plugins.tritown.gathering.GatherManager +import net.trilleo.mc.plugins.tritown.registration.PluginTask + +/** + * Writes the blocks harvested in resource regions to disk on an interval, off + * the main thread. Regions themselves are written the moment they are edited. + */ +class GatherSaveTask : PluginTask( + delay = saveIntervalTicks(), + period = saveIntervalTicks(), + async = true, +) { + override fun run() { + GatherManager.flush() + } +} + +private fun saveIntervalTicks(): Long { + val seconds = if (GatheringSettings.isLoaded) GatheringSettings.snapshot.saveSeconds else 60L + return seconds * 20L +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/tasks/gathering/GatherTickTask.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/tasks/gathering/GatherTickTask.kt new file mode 100644 index 0000000..7f4e8ba --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/tasks/gathering/GatherTickTask.kt @@ -0,0 +1,22 @@ +package net.trilleo.mc.plugins.tritown.tasks.gathering + +import net.trilleo.mc.plugins.tritown.gathering.GatherManager +import net.trilleo.mc.plugins.tritown.gathering.GatherNotices +import net.trilleo.mc.plugins.tritown.gathering.Regrowth +import net.trilleo.mc.plugins.tritown.gathering.Spawners +import net.trilleo.mc.plugins.tritown.registration.PluginTask + +/** + * Once a second: grows harvested nodes back, keeps the spawners stocked, and + * greets players walking into a region. + * + * On the server thread, since all three change the world or talk to players. + */ +class GatherTickTask : PluginTask(delay = 20L, period = 20L) { + override fun run() { + if (!GatherManager.isReady) return + Regrowth.tick() + Spawners.tick() + GatherNotices.tick() + } +} diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index c4e8759..4282daa 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -363,6 +363,41 @@ towns: # Set to 0 to turn it off. founding-credit: 100.0 +# ── Resource Gathering ────────────────────────────────────────────────────── +# Parts of a town whose resources grow back: a mine whose ore returns, a farm +# that replants itself, a wood that regrows, pens that keep their animals and +# an arena that keeps its monsters. Only the town's residents may gather there, +# even when the town denies them building, destroying and using everywhere +# else, and nothing else in a region can be changed. Regions are drawn with +# /tritown gather wand and set up in game with /tritown gather; these are the +# rules that apply to all of them. +gathering: + # Turn resource regions off entirely. Existing regions are left on disk untouched. + # Changing this needs a restart. + enabled: true + # The most blocks one region may cover, so a slip of the wand cannot take in a whole town. + max-volume: 250000 + # Seconds a newly added resource takes to grow back, until it is given its own time. + default-regrow-seconds: 60 + # What stands in for a harvested block until it grows back, by the resource's + # category, unless the resource names its own. Crops are put back as seedlings + # and grow through their stages instead. AIR leaves a gap. + depleted-blocks: + mining: BEDROCK + foraging: AIR + farming: AIR + excavation: BEDROCK + # How close a player has to be for a spawner to call its mobs up. + spawner-range: 48 + # Particles and a chime when a block grows back, and a puff when a mob appears. + effects: true + # Show a region's name, and whether you may gather there, when you walk in. + entry-titles: true + # Seconds between writing harvested blocks to disk. A crash loses at most this + # long of them, and those blocks simply stay as they are. Regions themselves + # are always written the moment they are changed. + save-interval: 60 + # ── News ──────────────────────────────────────────────────────────────────── # Update notes for the server, read from the main menu or with /tritown news. # Posts are written in game — /tritown news manage, or the Manage button in the diff --git a/src/main/resources/lang/en_US.yml b/src/main/resources/lang/en_US.yml index 7c39ee3..29780b4 100644 --- a/src/main/resources/lang/en_US.yml +++ b/src/main/resources/lang/en_US.yml @@ -26,6 +26,7 @@ command: adventure: "Adventure" mobs: "Mobs" items: "Items" + gathering: "Gathering" help: header: "TriTown Commands" @@ -245,6 +246,36 @@ command: stats: "/tritown shop stats - what a shop has traded" + gather: + description: "Set up resource regions" + unavailable: "Resource regions are switched off or could not be loaded. Check the server log." + no-permission-action: "You don't have permission to use /tritown gather {action}." + players-only: "Only a player can do that." + unknown: "There is no resource region with the id {id}." + not-in-region: "You are not standing in a resource region. Name one instead." + wand: "You have the region wand. Left-click a block for one corner and right-click another for the opposite corner, then /tritown gather create ." + create-failed: "{id} is taken or is not a usable id. Use lowercase letters, digits, dashes and underscores." + created: "Created the resource region {id} for {town}. Add its resources in the editor." + delete-confirm: "Deleting a region cannot be undone. Everything it harvested grows back first. Run /tritown gather delete {id} confirm to go ahead." + deleted: "Deleted the resource region {id}." + build-on: "Building mode is on: you can change resource regions freely, and nothing you break counts as a harvest. Towny's own rules still apply to you." + build-off: "Building mode is off. Resource regions are protected again." + usage: + header: "Resource regions" + list: "/tritown gather list - every region on the server" + wand: "/tritown gather wand - the tool for picking a region's corners" + create: "/tritown gather create [name] - turn your selection into a region" + edit: "/tritown gather edit [id] - set up a region's resources and spawners" + delete: "/tritown gather delete confirm - remove a region for good" + build: "/tritown gather build - change regions without anything counting as a harvest" + show: "/tritown gather show [id] - trace a region's border, or your selection" + regrow: "/tritown gather regrow - grow everything back at once" + + resources: + description: "See your town's resource regions" + players-only: "Only a player can open a menu." + none: "Your town has no resource regions." + # The item in the last hotbar slot that opens the main menu. menu-item: name: "TriTown Menu" @@ -404,6 +435,8 @@ gui: profile-stats: "Click to see your combat stats" forge: "Forge" forge-lore: "Craft gear from what mobs drop, and make it stronger." + resources: "Resource Regions" + resources-lore: "Where your town's resources grow back, and how much you have gathered." bestiary: "Bestiary" bestiary-lore: "Every one of the server's own mobs you have slain, and what each gave you." bestiary-found: "Found: {found}/{total}" @@ -1254,6 +1287,197 @@ gui: click: "Click to forge it" confirm: "Forge this piece?" + gather-list: + title: "Resource regions" + id: "Id: {id}" + town: "Town: {town}" + offers: "Offers: {categories}" + open: "Open for gathering" + closed: "Closed" + click: "Click to edit it" + help: "Making a region" + help-lore: "Take the wand with /tritown gather wand, pick two corners inside one town, then run /tritown gather create ." + + gather-region: + title: "Region: {name}" + size: "Size: {x} × {y} × {z}" + regrowing: "Growing back: {amount} blocks" + resources: "Resources" + resources-lore: "The blocks that grow back here. {amount} set up." + spawners: "Spawners" + spawners-lore: "The animals and monsters kept here. {amount} set up." + rename: "Rename" + rename-lore: "Type a new name in chat. MiniMessage colours work." + enabled: "Open" + disabled: "Closed" + toggle-lore: "Click to open or close the region. A closed region stays protected, but nobody can gather in it and its spawners rest." + outline: "Show the border" + outline-lore: "Trace the region's edges in particles for a few seconds." + regrow: "Grow everything back" + regrow-lore: "Put back every block harvested here, at once." + resize: "Resize to your selection" + resize-lore: "Move the region to the corners you picked with the wand. They must belong to the same town." + back: "All regions" + back-lore: "Back to the list of regions." + back-region: "Back to the region" + back-region-lore: "Back to this region's settings." + + gather-nodes: + title: "Resources" + name: "{block}" + add: "Add a resource" + add-lore: "Click a block in your own inventory, or a seed for a crop. Every block of that kind in the region becomes a resource. Your item stays where it is." + click: "Click to edit it" + shift-click: "Shift-click to remove it" + + gather-node: + title: "Resource: {block}" + current: "Now: {value}" + category: "Category" + category-lore: "Click to change what kind of gathering this counts as." + regrow: "Regrow time" + regrow-lore: "Click and type a time in chat, such as 90, 5m or 1h." + depleted: "While growing back" + depleted-lore: "Click and type a block name in chat, such as bedrock or air, or default for the category's. A crop with none set is replanted as a seedling and grows through its stages." + vanilla: "Vanilla drops" + vanilla-on: "Drops what it does in vanilla" + vanilla-off: "Drops only its extra drops" + vanilla-lore: "Click to switch. Turn it off to give only the items you list." + drops: "Extra drops" + drops-lore: "Items a harvest may give, each with its own chance. {amount} set up." + pool: "Grows back as" + pool-lore: "Blocks this may come back as instead, by weight: an ore vein that is different every time. Empty to come back as itself. {amount} set up." + delete: "Remove this resource" + delete-lore: "Shift-click. Blocks of this kind become ordinary protected blocks." + back: "All resources" + back-lore: "Back to the region's resources." + back-node: "Back to the resource" + back-node-lore: "Back to this resource's settings." + line-category: "Category: {value}" + line-regrow: "Grows back in: {value}" + line-depleted: "Meanwhile: {value}" + line-drops: "Extra drops: {amount}" + line-pool: "Grows back as: {amount} choices" + seedling: "a seedling" + air: "nothing" + default: "{value} (default)" + + gather-drops: + title: "Extra drops" + chance: "Chance: {chance}%" + click: "Click to change the chance" + add: "Add a drop" + add-lore: "Click an item in your own inventory. It is copied, stack size and all, and given whole when the chance comes up. Your item stays where it is." + + gather-pool: + title: "Grows back as" + weight: "Weight: {weight} ({chance}%)" + click: "Click to change the weight" + add: "Add a block" + add-lore: "Click a block in your own inventory. Give each a resource of its own too, or it cannot be harvested once it grows." + + gather-items: + shift-click: "Shift-click to remove it" + + gather-spawners: + title: "Spawners" + name: "{mob}" + add: "Add a spawner" + add-lore: "Stand where it should be, inside the region, and click a spawn egg in your own inventory. The egg is not used up." + click: "Click to edit it" + shift-click: "Shift-click to remove it and its mobs" + + gather-spawner: + title: "Spawner: {mob}" + alive: "About now: {amount}" + max: "Most at once" + max-lore: "Click and type how many it keeps about." + respawn: "Respawn time" + respawn-lore: "Click and type how long it waits to replace one, such as 30 or 2m." + radius: "Roaming radius" + radius-lore: "Click and type how far its mobs may wander. Strays are brought back." + level: "Mob level" + level-lore: "Click and type the level of its monsters. Animals have none." + move: "Move here" + move-lore: "Put the spawner where you stand. Its mobs are taken away and come back there." + delete: "Remove this spawner" + delete-lore: "Shift-click. Its mobs are taken away too." + back: "All spawners" + back-lore: "Back to the spawners of {id}." + line-max: "Most at once: {amount}" + line-respawn: "Respawns in: {value}" + line-radius: "Roams: {amount} blocks" + line-level: "Level: {amount}" + line-at: "At: {x}, {y}, {z}" + + resources: + title: "Resource Regions" + node: "• {block} grows back in {time}" + spawner: "• {mob} up to {amount} at once" + click: "Click to trace its border" + stats: "What you have gathered" + stat: "{category}: {amount}" + +# Resource regions: parts of a town whose resources grow back, which only its residents may gather. +gathering: + category: + mining: "Mining" + foraging: "Foraging" + farming: "Farming" + excavation: "Excavation" + husbandry: "Husbandry" + combat: "Combat" + list-separator: ", " + time: "{minutes}m {seconds}s" + time-seconds: "{seconds}s" + coordinates: "At: {x}, {y}, {z} ({world})" + enter: + title: "{name}" + open: "Gather here: {categories}" + refuse: + closed: "This resource region is closed." + resident: "Only residents of {town} can gather here." + unclaimed: "This resource region is no longer on its town's land." + hint: + regrowing: "Growing back… {seconds}s" + unripe: "Not ripe yet." + protected: "This is part of a resource region and cannot be changed." + menu: + located: "{name} is outlined around you. {coordinates}" + area: + no-selection: "Pick two corners with the wand first, in the same world." + too-large: "That box is {volume} blocks. A region may be at most {max}." + not-town: "The box has to lie within one town's land: its four corners and its middle." + other-town: "The new box belongs to another town. Make a new region there instead." + overlaps: "That box overlaps the region {id}." + wand: + name: "Region Wand" + lore: "Left-click: first corner. Right-click: second corner." + first: "First corner: {x}, {y}, {z}" + second: "Second corner: {x}, {y}, {z}" + size: "Selected {volume} blocks." + editor: + prompt-name: "Type the region's new name. MiniMessage colours work." + prompt-regrow: "Type how long it takes to grow back, such as 90, 5m or 1h." + prompt-depleted: "Type the block that stands in while it grows back, such as bedrock, air or default." + prompt-chance: "Type the chance, in percent, from 0.1 to 100." + prompt-weight: "Type the weight, a whole number. A block of weight 10 comes up ten times as often as one of weight 1." + prompt-max: "Type how many it keeps about at once, from 1 to {max}." + prompt-respawn: "Type how long it waits to replace one, such as 30 or 2m." + prompt-radius: "Type how far its mobs may roam, from 1 to {max} blocks." + prompt-level: "Type the level of its monsters, from 1 to {max}." + node-added: "Added {block} as a resource." + node-removed: "{block} is no longer a resource." + not-a-block: "That is not a block that can be placed." + not-an-egg: "Click a spawn egg to add a spawner." + stand-inside: "Stand inside the region first." + spawner-added: "Added a spawner of {mob} where you stand." + spawner-removed: "Removed the spawner of {mob} and its mobs." + spawner-moved: "Moved the spawner to where you stand." + outlined: "Tracing the border for {seconds} seconds." + regrown: "Grew back {amount} blocks." + resized: "The region now covers {volume} blocks." + shop: traded: "Traded {amount}x {item} for {price}." traded-items: "Traded {amount}x {item}." diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index 5fe6edf..d95947a 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -26,6 +26,7 @@ command: adventure: "冒险" mobs: "怪物" items: "物品" + gathering: "资源采集" help: header: "TriTown 命令" @@ -245,6 +246,36 @@ command: stats: "/tritown shop stats - 商店的交易统计" + gather: + description: "设置资源区" + unavailable: "资源区已关闭或未能加载。请查看服务器日志。" + no-permission-action: "你没有权限使用 /tritown gather {action}。" + players-only: "只有玩家才能这样做。" + unknown: "不存在 ID 为 {id} 的资源区。" + not-in-region: "你不在任何资源区内。请改为指定一个。" + wand: "你拿到了区域魔杖。左键点击方块选择一个角,右键点击另一个方块选择对角,然后输入 /tritown gather create 。" + create-failed: "{id} 已被占用或不是可用的 ID。请使用小写字母、数字、短横线和下划线。" + created: "已为 {town} 创建资源区 {id}。请在编辑器中添加资源。" + delete-confirm: "删除资源区后无法撤销。被采集的方块会先全部再生。输入 /tritown gather delete {id} confirm 以继续。" + deleted: "已删除资源区 {id}。" + build-on: "建造模式已开启:你可以随意修改资源区,破坏的方块不算作采集。Towny 自身的规则仍对你有效。" + build-off: "建造模式已关闭。资源区重新受到保护。" + usage: + header: "资源区管理" + list: "/tritown gather list - 服务器上的所有资源区" + wand: "/tritown gather wand - 用来选择资源区角落的工具" + create: "/tritown gather create [名称] - 将选区设为资源区" + edit: "/tritown gather edit [id] - 设置资源区的资源与刷怪点" + delete: "/tritown gather delete confirm - 永久删除资源区" + build: "/tritown gather build - 修改资源区而不计为采集" + show: "/tritown gather show [id] - 显示资源区或选区的边界" + regrow: "/tritown gather regrow - 立即让所有资源再生" + + resources: + description: "查看你所在城镇的资源区" + players-only: "只有玩家才能打开菜单。" + none: "你所在的城镇没有资源区。" + # 快捷栏最后一格中用于打开主菜单的物品。 menu-item: name: "TriTown 菜单" @@ -403,6 +434,8 @@ gui: profile-stats: "点击查看你的战斗属性" forge: "锻造台" forge-lore: "用怪物的掉落物打造装备,并让它变得更强。" + resources: "资源区" + resources-lore: "你所在城镇的资源会在哪里再生,以及你采集了多少。" bestiary: "图鉴" bestiary-lore: "你击杀过的每一种服务器专属怪物,以及它们给了你什么。" bestiary-found: "已发现:{found}/{total}" @@ -1254,6 +1287,197 @@ gui: click: "点击打造" confirm: "打造这件装备?" + gather-list: + title: "资源区" + id: "ID:{id}" + town: "城镇:{town}" + offers: "可采集:{categories}" + open: "开放采集" + closed: "已关闭" + click: "点击进行编辑" + help: "创建资源区" + help-lore: "用 /tritown gather wand 拿取魔杖,在同一个城镇内选择两个角,然后输入 /tritown gather create 。" + + gather-region: + title: "资源区:{name}" + size: "大小:{x} × {y} × {z}" + regrowing: "再生中:{amount} 个方块" + resources: "资源" + resources-lore: "在这里会再生的方块。已设置 {amount} 种。" + spawners: "刷怪点" + spawners-lore: "在这里饲养的动物与怪物。已设置 {amount} 个。" + rename: "重命名" + rename-lore: "在聊天栏输入新名称。支持 MiniMessage 颜色。" + enabled: "开放" + disabled: "关闭" + toggle-lore: "点击开放或关闭资源区。关闭的资源区仍受保护,但无人可以采集,刷怪点也会暂停。" + outline: "显示边界" + outline-lore: "用粒子描出资源区的边缘,持续几秒。" + regrow: "全部再生" + regrow-lore: "立即恢复这里所有被采集的方块。" + resize: "按选区调整大小" + resize-lore: "将资源区移到你用魔杖选择的角落。选区必须属于同一个城镇。" + back: "所有资源区" + back-lore: "返回资源区列表。" + back-region: "返回资源区" + back-region-lore: "返回这个资源区的设置。" + + gather-nodes: + title: "资源" + name: "{block}" + add: "添加资源" + add-lore: "点击你背包中的方块,作物则点击其种子。资源区内所有这种方块都会成为资源。你的物品不会被拿走。" + click: "点击进行编辑" + shift-click: "Shift+点击移除" + + gather-node: + title: "资源:{block}" + current: "当前:{value}" + category: "类别" + category-lore: "点击切换它计为哪种采集。" + regrow: "再生时间" + regrow-lore: "点击后在聊天栏输入时间,例如 90、5m 或 1h。" + depleted: "再生期间" + depleted-lore: "点击后在聊天栏输入方块名称,例如 bedrock 或 air,输入 default 则使用类别默认值。未设置的作物会以幼苗重新种下,并逐阶段生长。" + vanilla: "原版掉落" + vanilla-on: "按原版掉落" + vanilla-off: "只掉落额外掉落物" + vanilla-lore: "点击切换。关闭后只给予你列出的物品。" + drops: "额外掉落" + drops-lore: "采集时可能给予的物品,各有其概率。已设置 {amount} 个。" + pool: "再生为" + pool-lore: "它可能按权重再生成的其他方块:每次都不同的矿脉。留空则再生为原方块。已设置 {amount} 个。" + delete: "移除此资源" + delete-lore: "Shift+点击。这种方块将变为普通的受保护方块。" + back: "所有资源" + back-lore: "返回资源区的资源列表。" + back-node: "返回资源" + back-node-lore: "返回这个资源的设置。" + line-category: "类别:{value}" + line-regrow: "再生时间:{value}" + line-depleted: "再生期间:{value}" + line-drops: "额外掉落:{amount}" + line-pool: "再生为:{amount} 种选择" + seedling: "幼苗" + air: "空" + default: "{value} (默认)" + + gather-drops: + title: "额外掉落" + chance: "概率:{chance}%" + click: "点击修改概率" + add: "添加掉落物" + add-lore: "点击你背包中的物品。它会连同堆叠数量一起被复制,概率命中时整组给予。你的物品不会被拿走。" + + gather-pool: + title: "再生为" + weight: "权重:{weight} ({chance}%)" + click: "点击修改权重" + add: "添加方块" + add-lore: "点击你背包中的方块。也请为每种方块单独设置资源,否则它再生后将无法采集。" + + gather-items: + shift-click: "Shift+点击移除" + + gather-spawners: + title: "刷怪点" + name: "{mob}" + add: "添加刷怪点" + add-lore: "站在资源区内想要的位置,点击你背包中的刷怪蛋。刷怪蛋不会被消耗。" + click: "点击进行编辑" + shift-click: "Shift+点击移除它及其生物" + + gather-spawner: + title: "刷怪点:{mob}" + alive: "当前数量:{amount}" + max: "最大数量" + max-lore: "点击后输入它同时保持的数量。" + respawn: "重生时间" + respawn-lore: "点击后输入补充一只所需的等待时间,例如 30 或 2m。" + radius: "活动半径" + radius-lore: "点击后输入其生物可游荡的距离。走远的会被带回。" + level: "生物等级" + level-lore: "点击后输入其怪物的等级。动物没有等级。" + move: "移到这里" + move-lore: "将刷怪点移到你所站的位置。现有生物会被移除,并在新位置重新出现。" + delete: "移除此刷怪点" + delete-lore: "Shift+点击。其生物也会被移除。" + back: "所有刷怪点" + back-lore: "返回 {id} 的刷怪点。" + line-max: "最大数量:{amount}" + line-respawn: "重生时间:{value}" + line-radius: "活动范围:{amount} 格" + line-level: "等级:{amount}" + line-at: "位置:{x}, {y}, {z}" + + resources: + title: "资源区" + node: "• {block} {time} 后再生" + spawner: "• {mob} 最多同时 {amount} 只" + click: "点击显示它的边界" + stats: "你的采集记录" + stat: "{category}:{amount}" + +# 资源区:城镇中资源会再生、仅限其居民采集的区域。 +gathering: + category: + mining: "采矿" + foraging: "伐木" + farming: "耕种" + excavation: "挖掘" + husbandry: "畜牧" + combat: "战斗" + list-separator: "、" + time: "{minutes}分{seconds}秒" + time-seconds: "{seconds}秒" + coordinates: "位置:{x}, {y}, {z} ({world})" + enter: + title: "{name}" + open: "可在此采集:{categories}" + refuse: + closed: "这个资源区已关闭。" + resident: "只有 {town} 的居民才能在这里采集。" + unclaimed: "这个资源区已不在其城镇的领地上。" + hint: + regrowing: "再生中… {seconds}秒" + unripe: "还没有成熟。" + protected: "这是资源区的一部分,不能修改。" + menu: + located: "{name} 的边界已在你周围标出。{coordinates}" + area: + no-selection: "请先用魔杖在同一个世界中选择两个角。" + too-large: "这个选区有 {volume} 个方块。一个资源区最多 {max} 个。" + not-town: "选区必须位于同一个城镇的领地内:包括四个角和中心。" + other-town: "新的选区属于另一个城镇。请在那里新建一个资源区。" + overlaps: "这个选区与资源区 {id} 重叠。" + wand: + name: "区域魔杖" + lore: "左键:第一个角。右键:第二个角。" + first: "第一个角:{x}, {y}, {z}" + second: "第二个角:{x}, {y}, {z}" + size: "已选择 {volume} 个方块。" + editor: + prompt-name: "输入资源区的新名称。支持 MiniMessage 颜色。" + prompt-regrow: "输入再生所需时间,例如 90、5m 或 1h。" + prompt-depleted: "输入再生期间替代的方块,例如 bedrock、air 或 default。" + prompt-chance: "输入概率百分比,从 0.1 到 100。" + prompt-weight: "输入权重(整数)。权重为 10 的方块出现的次数是权重为 1 的十倍。" + prompt-max: "输入同时保持的数量,从 1 到 {max}。" + prompt-respawn: "输入补充一只所需的等待时间,例如 30 或 2m。" + prompt-radius: "输入其生物可游荡的距离,从 1 到 {max} 格。" + prompt-level: "输入其怪物的等级,从 1 到 {max}。" + node-added: "已将 {block} 添加为资源。" + node-removed: "{block} 不再是资源。" + not-a-block: "这不是可以放置的方块。" + not-an-egg: "请点击刷怪蛋来添加刷怪点。" + stand-inside: "请先站到资源区内。" + spawner-added: "已在你所站的位置添加 {mob} 的刷怪点。" + spawner-removed: "已移除 {mob} 的刷怪点及其生物。" + spawner-moved: "已将刷怪点移到你所站的位置。" + outlined: "正在显示边界,持续 {seconds} 秒。" + regrown: "已再生 {amount} 个方块。" + resized: "资源区现在覆盖 {volume} 个方块。" + shop: traded: "以 {price} 成交 {amount}个 {item}。" traded-items: "成交 {amount}个 {item}。" From 9a2e7b80f304e4ff20195339d897c61fb3180add Mon Sep 17 00:00:00 2001 From: Trilleo Date: Tue, 6 Oct 2026 15:56:29 +0800 Subject: [PATCH 2/3] Internal: Update docs to Minecraft 26.3 Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 8 ++++---- README.md | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 51e3411..e0d181e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,8 +4,8 @@ TriTown is a Minecraft Paper plugin that adds custom town features for the Trilleo server on top of [Towny](https://github.com/TownyAdvanced/Towny). Where [TownyMenu](https://github.com/Trilleo/TownyMenu) is a general -GUI for Towny's existing features, TriTown holds functionality specific to this server. It targets Minecraft 26.2 (Paper -API 26.2), hard-depends on Towny and Vault, and is written in Kotlin. [README.md](README.md) has the player-facing +GUI for Towny's existing features, TriTown holds functionality specific to this server. It targets Minecraft 26.3 (Paper +API 26.3), hard-depends on Towny and Vault, and is written in Kotlin. [README.md](README.md) has the player-facing overview. ## Tech Stack @@ -14,7 +14,7 @@ overview. |:---------------|:-------------------------------------------------| | Language | Kotlin 2.3.10 | | Build | Gradle 9.7.1 (Kotlin DSL) | -| Platform | Paper API 26.2 (MC 26.2) | +| Platform | Paper API 26.3 (MC 26.3) | | Towny | 0.103.2.7 (`towny_version` in gradle.properties) | | Vault API | 1.7.1 (`vault_api_version` in gradle.properties) | | FancyNpcs API | 2.9.2 (`fancynpcs_version`, API artifact only) | @@ -58,7 +58,7 @@ Before finishing any task that changes the plugin, do all of the following: ``` The local test server lives in `run/` (gitignored). `copyPlugin` puts the matching Towny jar in `run/plugins/`, but the -Paper 26.2 jar (`run/paper-*.jar`), Vault, and FancyNpcs (Maven carries its API only) must be downloaded by hand, and +Paper 26.3 jar (`run/paper-*.jar`), Vault, and FancyNpcs (Maven carries its API only) must be downloaded by hand, and `eula.txt` accepted, before `startServer` works. No economy plugin is needed — TriTown supplies the economy itself. The server console reads commands from the terminal running Gradle. diff --git a/README.md b/README.md index 07cc062..605066c 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ built on. | Dependency | Version | |:---------------|:------------------------------------| -| Paper | 26.2+ | +| Paper | 26.3+ | | Java | 25+ | | Towny | 0.103.2.7+ | | Vault | 1.7+ | @@ -141,7 +141,7 @@ The compiled JAR is placed in `build/libs/`. Run `./gradlew copyPlugin` to copy into `run/plugins/` for the local test server, or `./gradlew startServer` to copy them and start the server. Before the first start: -- download a Paper 26.2 jar from [papermc.io](https://papermc.io/downloads/paper) into `run/`; +- download a Paper 26.3 jar from [papermc.io](https://papermc.io/downloads/paper) into `run/`; - put Vault into `run/plugins/`; - put [FancyNpcs](https://modrinth.com/plugin/fancynpcs) into `run/plugins/` as well, to test shop NPCs — only its API is published to Maven, so the plugin itself is not fetched by the build; From 08ee318dd2fc8a0be91cce73e392e7f82d548ae3 Mon Sep 17 00:00:00 2001 From: Trilleo Date: Tue, 6 Oct 2026 16:03:02 +0800 Subject: [PATCH 3/3] Update: Plugin version 1.5.1 release --- CHANGELOG.md | 2 ++ gradle.properties | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e2f61d..9157760 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## Version 1.5.1 + ### New Features #### Towns diff --git a/gradle.properties b/gradle.properties index e8a0b50..20e69ce 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,7 +1,7 @@ kotlin.code.style=official # Plugin Properties -plugin_version=1.5.0 +plugin_version=1.5.1 # Dependency Versions towny_version=0.103.2.7