From f2d5ead478c3507850ed2ae38565c83031e39c27 Mon Sep 17 00:00:00 2001 From: Trilleo Date: Mon, 21 Sep 2026 22:48:37 +0800 Subject: [PATCH 1/6] Feature: Add personal storage and retire vanilla containers Every player gets a paged, chest-sized storage from the main menu or /tritown storage, with quick deposit, sorting, page withdrawal, shulker and bundle unpacking, named pages with icons, and an overview. Extra pages are bought at a geometric price and recorded as a new STORAGE money sink. Chests, barrels, shulker boxes and ender chests can no longer be placed, and existing ones are withdraw-only. Administrators can inspect or edit any storage, and the admin panel gains a Storage section. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 38 ++ CLAUDE.md | 24 +- README.md | 60 +- docs/DEVELOPER_GUIDE.md | 149 ++++- .../net/trilleo/mc/plugins/tritown/Main.kt | 13 + .../tritown/commands/admin/AdminCommand.kt | 18 +- .../commands/storage/StorageCommand.kt | 140 ++++ .../plugins/tritown/config/StorageSettings.kt | 79 +++ .../plugins/tritown/economy/EconomyContext.kt | 1 + .../tritown/economy/TransactionReason.kt | 1 + .../mc/plugins/tritown/enums/FlowCategory.kt | 6 + .../tritown/guis/admin/AdminPanelGUI.kt | 34 +- .../tritown/guis/admin/AdminStorageGUI.kt | 146 +++++ .../tritown/guis/admin/EconomyFlowGUI.kt | 2 + .../plugins/tritown/guis/menu/MainMenuGUI.kt | 27 +- .../tritown/guis/storage/StorageGUI.kt | 599 ++++++++++++++++++ .../guis/storage/StoragePageSettingsGUI.kt | 157 +++++ .../tritown/guis/storage/StoragePagesGUI.kt | 110 ++++ .../tritown/guis/storage/StorageRender.kt | 107 ++++ .../storage/ContainerLockListener.kt | 212 +++++++ .../storage/StorageSessionListener.kt | 25 + .../plugins/tritown/storage/PlayerStorage.kt | 68 ++ .../mc/plugins/tritown/storage/SlotFill.kt | 105 +++ .../plugins/tritown/storage/StorageItems.kt | 78 +++ .../plugins/tritown/storage/StorageManager.kt | 359 +++++++++++ .../plugins/tritown/storage/StoragePricing.kt | 43 ++ .../storage/storage/JsonStorageStore.kt | 109 ++++ .../tritown/storage/storage/StorageStore.kt | 55 ++ .../tritown/tasks/storage/StorageSaveTask.kt | 33 + src/main/resources/config.yml | 41 +- src/main/resources/lang/en_US.yml | 123 ++++ src/main/resources/lang/zh_CN.yml | 123 ++++ .../plugins/tritown/storage/SlotFillTest.kt | 77 +++ .../tritown/storage/StoragePricingTest.kt | 52 ++ .../storage/storage/JsonStorageStoreTest.kt | 88 +++ 35 files changed, 3281 insertions(+), 21 deletions(-) create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/storage/StorageCommand.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/config/StorageSettings.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/AdminStorageGUI.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/storage/StorageGUI.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/storage/StoragePageSettingsGUI.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/storage/StoragePagesGUI.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/storage/StorageRender.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/storage/ContainerLockListener.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/storage/StorageSessionListener.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/PlayerStorage.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/SlotFill.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/StorageItems.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/StorageManager.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/StoragePricing.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/storage/JsonStorageStore.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/storage/StorageStore.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/tasks/storage/StorageSaveTask.kt create mode 100644 src/test/kotlin/net/trilleo/mc/plugins/tritown/storage/SlotFillTest.kt create mode 100644 src/test/kotlin/net/trilleo/mc/plugins/tritown/storage/StoragePricingTest.kt create mode 100644 src/test/kotlin/net/trilleo/mc/plugins/tritown/storage/storage/JsonStorageStoreTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index da5b699..603ccfe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,44 @@ ## Unreleased +### New Features + +#### Storage + ++ Added a storage for every player, opened from the main menu or with `/tritown storage`. Each page is the size of a + large chest and works like one, with a row of buttons beneath it. + + **Quick deposit** stores everything in your main inventory that your storage already holds some of, **Sort** + merges and orders a page (shift-click for every page), and **Take page** moves a page into your inventory. + + **Unpack** empties a shulker box or bundle straight into your storage. Full ones can't be stored as they are. + + Name your pages, give them icons, and jump between them from an overview of every page. + + Every player starts with `storage.free-pages` pages (default `2`). More can be bought up to `storage.max-pages` + (default `27`), each costing `storage.price.multiplier` times the one before, starting at `storage.price.base`. + Every purchase asks for confirmation first. ++ Administrators with `tritown.storage.admin` can open anyone's storage, online or not, with + `/tritown storage view `, and hand out pages with `/tritown storage pages `. ++ Added a **Storage** section to the admin panel (`tritown.admin.storage`). It lists every storage, fullest first, with + how many pages were bought and what they earned, and opens any of them read-only. + +#### Misc + ++ Vanilla containers are retired in favour of the storage. Chests, trapped chests, barrels, shulker boxes, ender + chests, chest and hopper minecarts and chest boats can no longer be placed, by players or by dispensers. + + The ones already placed become withdraw-only, so nothing stored in them is lost. Hoppers can still empty them but + can no longer fill them. + + Each group can be left alone under `storage.lock-containers`, and `tritown.storage.bypass` exempts builders. + +#### Economy + ++ Storage pages are a new money sink, listed as **Storage pages** in the admin panel's economy breakdown and in + `/eco history`. + +### Technical Details + ++ Added the storage core under `storage/`: `StorageManager` (loading, the one-editor lock, pricing and saving), + one JSON file per player under `plugins/TriTown/storage/`, written atomically with a backup, on a single writer thread. ++ `StorageGUI` is the first menu that lets the game move items itself, with the button row, shift-clicks and + double-clicks guarded by hand. + ## Version 1.3.0 ### New Features diff --git a/CLAUDE.md b/CLAUDE.md index 634d92d..db4ac65 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -69,7 +69,7 @@ src/main/kotlin/net/trilleo/mc/plugins/tritown/ ├── Main.kt # Plugin entry point (Main.instance, Main.reload()) ├── commands/ # Sub-commands (auto-registered) │ ├── admin/ economy/ info/ menu/ news/ -│ └── moderation/ scoreboard/ shop/ trade/ +│ └── moderation/ scoreboard/ shop/ storage/ trade/ ├── config/ # PluginConfig (typed config.yml wrapper), EconomySettings ├── data/ # JSON-persisted PlayerData / ServerData and their managers ├── economy/ # The economy: ledger, accounts, currencies, Vault provider, statistics, @@ -84,6 +84,7 @@ src/main/kotlin/net/trilleo/mc/plugins/tritown/ ├── recipes/ # Recipes (auto-registered, implement PluginRecipe) ├── registration/ # Auto-registration engine (do not modify lightly) ├── shops/ # Admin shops: model, trading, storage, FancyNpcs bridge (not scanned) +├── storage/ # Personal storage: pages, pricing, the viewer lock, files (not scanned) ├── tasks/ # Scheduled tasks (auto-registered, extend PluginTask) ├── towns/ # Town founding credit (not scanned) ├── trades/ # Player trades: sessions, escrow, the swap (not scanned) @@ -99,7 +100,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/` 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/` 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 the scan for a simpler reason: `MenuItem` is not a `PluginItem`, because it is named in each holder's language. | Component | Base Class | Package | @@ -272,6 +273,25 @@ The panel in `guis/admin` is where an owner reads the server; `/tritown admin` o - **Both windows are drawn for their viewer**, never for a side, and anything that changes the table calls `TradeGUI.redraw` so the two can never disagree. +## Working with Storage + +**A storage holds a player's belongings, and replaces vanilla containers.** See +[Personal Storage](docs/DEVELOPER_GUIDE.md#personal-storage). + +- **Go through `StorageManager`** — it is the only thing that loads, changes or writes a storage. Charge for a page with + `buyPage`, which withdraws before granting. +- **One editor per storage.** Open one through `StorageGUI.open`, which takes the lock with `StorageManager.claim`; + anything that changes a storage's items without holding it would be overwritten by the editor's next copy-back. +- **`StorageGUI` is the only menu that lets the game move items.** Every other GUI cancels its clicks. A change to it + keeps the button row untouchable, keeps shift-clicks and `COLLECT_TO_CURSOR` out of the game's hands, and checks + `StorageItems.accepts` before anything lands on a page. +- **Leave the storage menu through `leave`**, never by opening another menu directly: `GUIManager` does not deliver a + close to a menu that is replaced, and `finish` is what copies the page back and lets go of the lock. +- **Encode on the server thread, write on the writer.** Items are encoded in `StorageManager.toStored`; `StorageStore` + only ever sees text. +- **Recognise a vanilla container by its inventory's holder**, never by `InventoryType`: TriTown's own menus are + chest-shaped too and have no holder. + ## Working with the Main Menu The main menu (`guis/menu`) is how players reach TriTown, opened from the menu item in hotbar slot 8 or with diff --git a/README.md b/README.md index 144ded0..af8964c 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,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 -[TownyMenu](https://github.com/Trilleo/TownyMenu), the global shop, a list of the players near enough to trade with +[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 server news, a sidebar switch, and the admin panel for those allowed it. Anything switched off on the server, or that you may not use, is simply left out, and what remains is centred. The item cannot be moved, dropped, stored, crafted with or handed @@ -40,6 +40,14 @@ group them, inside a shared header and footer carrying the server name and addre in `config.yml`; the wording lives in the language files, so everyone reads it in their own language. Players turn it on and off with `/tt scoreboard`, and it takes turns with Towny's own plot HUD rather than fighting it for the screen. +**A storage of your own.** Every player gets a storage reached from the menu, wherever they are standing: pages the +size of a large chest, used exactly like one, with a row of buttons beneath for turning pages, depositing everything +you already store some of, sorting, emptying a page into your inventory, and unpacking a shulker box or bundle straight +into it. Name your pages and give them icons, and see every page at once in an overview. The first pages are free and +more can be bought, each a little dearer than the last. It replaces vanilla containers: chests, barrels, shulker boxes +and ender chests can no longer be placed, and the ones already in the world can only be emptied — never filled, not +even by a hopper — so nothing anyone stored is lost. + **Shops the server runs.** Admin shops, set up entirely in game: click an item in your own inventory to put it on the shelf and it is sold exactly as you made it, custom name, enchantments and all. An entry can be sold, bought back, or both, and priced in currency, items, or a mix of the two. Give it a stock that refills on a timer, a limit on how much @@ -66,9 +74,10 @@ server's languages, and players read their own. **An admin panel.** `/tt admin` opens a menu that reads the server back to you. The economy section shows how much currency exists and who holds it, what created it and what removed it — new players, shops, Towny, administrators or -another plugin — with the net drift per day, how unevenly wealth is spread, how fast money circulates, and a chart of +storage pages or another plugin — with the net drift per day, how unevenly wealth is spread, how fast money circulates, and a chart of the window drawn as columns. Read any of it over the last day, week or month, or over everything on record. Every -shop's takings are in there too, next to the economy they act on. +shop's takings are in there too, next to the economy they act on, and every player's storage — how full it is, how +many pages were bought — which you can open and look through, online or not. **English and Simplified Chinese.** Every message, menu and item TriTown shows is translated. By default each player sees whichever of the two their Minecraft client is set to, and everyone else sees English. Set `language` in @@ -129,6 +138,7 @@ Prebuilt jars are attached to every [GitHub release](https://github.com/Trilleo/ | `/trade ` | Ask another player to trade | | `/tt shop …` | Set up the server's shops (OP only) | | `/tt news` | Read the server news | +| `/tt storage` | Open your storage | | `/tt admin [section]` | Open the admin panel (OP only) | `/eco` takes `give`, `take` and `set` (` [currency]`), `reset ` back to the starting balance, @@ -149,8 +159,14 @@ is open. There is no permission node: whether players may trade at all is `playe every post read, and `manage` to write them, which needs `tritown.news.manage` — as does the **Manage** button in the news. -`/tt admin` opens the panel itself, and `economy` or `shops` opens that section directly. Opening the panel needs -`tritown.admin`; the sections need `tritown.admin.economy` and `tritown.admin.shops` on top of it. +`/tt storage` opens your storage; there is no permission node, since whether it runs at all is `storage.enabled`. +Administrators with `tritown.storage.admin` also get `view `, which opens anyone's storage — online or not — to +change, and `pages `, which hands out pages for free. `tritown.storage.bypass` lets a +builder place and fill the containers the storage replaces. + +`/tt admin` opens the panel itself, and `economy`, `shops` or `storage` opens that section directly. Opening the panel +needs `tritown.admin`; the sections need `tritown.admin.economy`, `tritown.admin.shops` and `tritown.admin.storage` on +top of it. Commands are sub-commands of `/tritown` (alias `/tt`) unless noted. The economy commands are registered as top-level commands as well, which `economy.commands.top-level-aliases` turns off — they are then only reachable as @@ -201,6 +217,14 @@ version stays available as `/tritown:balance` and so on. | `player-trades.enabled` | `true` | Turn player-to-player trading off entirely | | `player-trades.distance` | `10.0` | How close two players must be to trade, and stay while the menu is open | | `player-trades.request-expiry` | `60` | Seconds an unanswered trade request stands | +| `storage.enabled` | `true` | Turn the storage and the container lock off (turning it on needs a restart) | +| `storage.free-pages` | `2` | Pages every player has without paying | +| `storage.max-pages` | `27` | The most pages a storage can reach, free ones included | +| `storage.price.base` | `500.0` | What the first bought page costs | +| `storage.price.multiplier` | `1.5` | How much dearer each bought page is than the one before | +| `storage.save-interval` | `30` | Seconds between writing changed storages; closing one writes it at once | +| `storage.lock-containers.enabled` | `true` | Stop containers being placed, and make placed ones withdraw-only | +| `storage.lock-containers.` | `true` | Each of `chests`, `shulker-boxes` and `ender-chest` on its own | | `towns.founding-credit` | `100.0` | Credit only `/t new` can spend, given once to players without a town; `0` is off | | `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 | @@ -272,6 +296,32 @@ Shops live in `plugins/TriTown/shops/shops.json`, written atomically with a `.ba written straight away; stock levels and sales figures are written every `shops.save-interval` seconds, so a crash costs at most that long of counters and never a shop. +### Storage + +Open your storage from the main menu or with `/tt storage`. Each page is five rows of ordinary slots, and you move +items in and out of them just as you would a chest. The row beneath holds the buttons: + +- **Previous** and **Next** turn the page. On your last page, **Next** offers the next page for sale instead, with its + price, and asks before charging you. Each page bought costs `storage.price.multiplier` times the one before. +- **All pages** shows every page at once — its name, how full it is and what it mostly holds — and opens any of them. +- **Quick deposit** stores everything in your main inventory that your storage already holds some of. Your hotbar is + left alone. +- **Sort** merges and orders the page; shift-click sorts every page. +- **Take page** moves as much of the page as fits into your inventory. +- **Unpack** empties a shulker box or bundle into your storage: pick one up and click the button with it. A full box + or bundle cannot be stored as it is, and shulker boxes can no longer be placed, so this is how their contents come + home. +- **Page settings** renames the page (typed in chat) or gives it an icon (click any item in your inventory). + +Chests, trapped chests, barrels, shulker boxes, ender chests, chest and hopper minecarts and chest boats cannot be +placed, by players or by dispensers. The ones already in the world still open, but only to take things out; hoppers +can still empty them but not fill them. Each group can be left alone under `storage.lock-containers`. + +Storages live in `plugins/TriTown/storage/.json`, one per player, written atomically with a `.bak` copy beside +it. A storage is written when it is closed, when its page is turned, every `storage.save-interval` seconds while it +is open, and on a clean shutdown. If a file and its backup are both unreadable, that player's storage stays closed — +and the file untouched — rather than opening empty. + ### Player trades Shift-right-click the other player, or run `/trade `. They get a request with **Accept** and **Deny** buttons, diff --git a/docs/DEVELOPER_GUIDE.md b/docs/DEVELOPER_GUIDE.md index 4865a27..7ba8dd7 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**, the **news** and the **sidebar**. Commands, listeners, GUIs, tasks, custom items, and recipes all +**Towny**, the **Vault economy**, the **admin panel**, **shops**, **player trades**, **personal storage**, the **news** 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. @@ -2498,16 +2498,16 @@ right-clicking the menu item or with `/tritown menu` (`commands/menu/MenuCommand | `LeaderboardGUI` | `menu-leaderboard` | The top 112 of `BaltopCache` as heads, with the viewer's rank on each page | Every one of them opens at six rows. `MainMenuGUI` puts the profile alone at the top and lays the buttons out in rows of -up to three with `GUIFrame.spacedColumns`. **A button for something switched off or not permitted is left out, not +up to four with `GUIFrame.spacedColumns`. **A button for something switched off or not permitted is left out, not greyed**, and each row is centred on what remains: the global shop only when shops are on and the viewer passes its -gate, trading only when `player-trades.enabled`, pay and the leaderboard only with the economy running and the +gate, the storage only while `StorageManager.isAvailable`, trading only when `player-trades.enabled`, pay and the leaderboard only with the economy running and the command's permission (`CommandRegistrar.canRun`), the news only while `NewsManager.isAvailable`, the sidebar switch only while the sidebar runs, the admin panel only with `tritown.admin`, and the TownyMenu shortcut only when TownyMenu is enabled. Empty rows are dropped, so the menu never has a hole in it. The two list menus use `PagedLayout.CENTERED` and keep *Back* and one extra button either side of the page number (`MenuRender.BACK_OFFSET`, `EXTRA_OFFSET`). **The menu points the way; it does not do the work.** Each button runs the command or opens the menu that already owns -the action — `/trades`, `/trade `, `/pay `, `/tritown news` through `CommandRegistrar.run`, the admin panel, +the action — `/trades`, `/tritown storage`, `/trade `, `/pay `, `/tritown news` through `CommandRegistrar.run`, the admin panel, TownyMenu through its own `/townymenu` — so there is exactly one place each rule and message lives. Paying asks for the amount with `ChatPrompt` and hands it to `/pay`, which validates it. @@ -2560,6 +2560,7 @@ surface: apart from writing the economy to disk on request, nothing in it change | `EconomyPanelGUI` | `admin-economy` | Supply, accounts, distribution, faucets, sinks, net, and the chart | | `EconomyFlowGUI` | `admin-flow` | Every category and every kind of account, in full | | `AdminShopsGUI` | `admin-shops` | Every shop's takings, opening into that shop's own figures | +| `AdminStorageGUI` | `admin-storage` | Every storage on file, fullest first, opening into it read-only | Adding a section means adding a card to `AdminPanelGUI` and a menu of its own — nothing else in the panel changes. @@ -2575,8 +2576,10 @@ account-type names, and the cards themselves — so the same number reads the sa next to the largest one, green where the supply grew and red where it shrank. It reads as a chart at a glance without a single custom texture, and the exact figures are in the lore. -Permissions: `tritown.admin` (`AdminPanelGUI.PERMISSION`) opens the panel, `tritown.admin.economy` and -`tritown.admin.shops` open the sections. A card the viewer may not open is not drawn at all, and the rest are centred +Permissions: `tritown.admin` (`AdminPanelGUI.PERMISSION`) opens the panel, `tritown.admin.economy`, +`tritown.admin.shops` and `tritown.admin.storage` open the sections. The storage list opens a storage read-only; only +an administrator who also holds `tritown.storage.admin` can shift-click into one to change it, and then it is the +storage menu doing the changing, not the panel. A card the viewer may not open is not drawn at all, and the rest are centred along the row with `GUIFrame.spacedColumns`, so a missing card leaves no gap. The panel is reached from the [main menu](#main-menu) as well as by command, so its bottom row leads back there. @@ -3014,6 +3017,140 @@ calls the trade off if they leave it hanging. `TradeSettings` is a snapshot swapped in whole on a reload, the way `ShopSettings` is. +## Personal Storage + +Every player's own paged storage, reached from the main menu or with `/tritown storage`. It replaces vanilla +containers: chests, barrels, shulker boxes and ender chests can no longer be placed, and the ones already in the world +are withdraw-only. + +The core lives under `storage/`, which is **not a scanned package** — the same reason `shops/` and `trades/` are not. +`StorageManager` has to be alive before the registrars build the main menu that reads it. The menus are in +`guis/storage` (plus `guis/admin/AdminStorageGUI`), the command is `commands/storage/StorageCommand`, the listeners +are `listeners/storage/ContainerLockListener` and `StorageSessionListener`, and the flush is +`tasks/storage/StorageSaveTask`. + +### The model + +| Type | What it is | +|:-------------------|:------------------------------------------------------------------------------------| +| `StoragePage` | 45 slots (a large chest less the button row), plus a name and icon the owner picked | +| `PlayerStorage` | One player's pages, how many they bought, and items a load could not decode | +| `StorageManager` | Loading, the viewer lock, pages and prices, depositing, and saving | +| `StoragePricing` | What the next page costs, free of Bukkit so it can be tested | +| `SlotFill` | Depositing into and sorting slots, written against `Rules` so it can be tested | +| `StorageItems` | `SlotFill`'s rules for real items, what a storage accepts, and unpacking containers | +| `JsonStorageStore` | One file per player under `storage/`, written through `AtomicFile` | + +A storage owns `free-pages + purchased` pages, capped at `max-pages`. **`purchased` is stored rather than a page +count**, so raising `free-pages` applies to everyone and the price of the next page stays where each player left it. +`pageCount` never drops below the last page that still holds anything, so lowering the allowance can never hide a +player's items. Pages are only created when they are opened or filled. + +Go through `StorageManager` for everything. It loads a storage the first time it is asked for and keeps it while its +owner is online or anyone is looking at it; `unloadIfIdle` writes it and lets it go after that. + +### The viewer lock + +**One person at a time may change a storage.** `StorageManager.claim` hands out `Access.EDIT` to the first viewer and +`Access.READ` to anyone else who may inspect (`tritown.storage.admin`); a player who may not is refused with +`storage.error.busy`. `release` gives it back. This is what lets the storage menu copy its screen back into the model +without ever overwriting another window's changes: there is never another window that can change it. + +A read-only viewer follows the editor. Every copy-back redraws the other viewers of the same page. + +### The menu lets the game move items + +`StorageGUI` is **the one menu in TriTown that does not cancel clicks** on its content. Players sort their storage the +way they would sort a chest, so the top five rows are real slots, and everything around them is guarded instead: + +* **The button row is untouchable.** A click, number-key swap or drag that reaches slot 45 or beyond is cancelled. +* **`COLLECT_TO_CURSOR` is cancelled everywhere**, because a double-click gathers from every slot on screen, buttons + included. +* **A shift-click from the player's inventory is done by hand** into the page's own slots. Left to the game it would + merge into any matching stack on screen, and a button is a stack on screen. +* **Only a whitelist of actions may touch a page slot** (`CONTENT_ACTIONS`), and anything being placed there must pass + `StorageItems.accepts`. That refuses a shulker box or bundle with anything in it — a page of full boxes would hold + many pages' worth and nobody would buy one — and the menu item. +* **A read-only view cancels every click** that touches the storage. + +The screen is copied back into the model on the tick after every allowed click or drag, when the page is switched, and +when the menu closes. A button that changes the storage itself (deposit, sort, take page, unpack) copies the screen +back first, changes the model, then redraws from the model. + +**Opening another menu from here does not deliver a close to this one**, because `GUIManager` has already moved on to +the new inventory. Every button that leaves the storage goes through `leave`, which calls `finish` — copy back, write, +release — on the tick the next menu opens. `finish` is idempotent, so the quit listener and a real close can both call +it. + +Buttons: previous and next page (next becomes **Buy page** on the last page), the overview (`StoragePagesGUI`), quick +deposit (the main inventory without the hotbar, only materials already stored), sort (shift for every page), take +page, **Unpack** (click it holding a shulker box or bundle; nothing moves unless all of it fits), page settings +(`StoragePageSettingsGUI`: rename through `ChatPrompt`, icon from any item in the player's inventory), and the page +info, which leads back to the main menu or, for an administrator, the storage list. + +### Buying pages + +`StorageManager.buyPage` charges first and grants the page only once the money has gone: the four-argument +`EconomyUtil.withdraw` with `EconomyContext.SOURCE_STORAGE` and `TransactionReason.STORAGE_PAGE`, which +`FlowCategory.of` maps to `STORAGE`. Storage pages are a pure sink. The price is +`base × multiplier^(n − 1)` for the n-th page bought, rounded to the currency's smallest unit; a page too dear to +hold in a `Money` is simply not for sale. A purchase always goes through `ConfirmGUI`. + +`/tritown storage pages ` hands pages out without moving money, so there is nothing to +attribute. + +### Saving + +Items can only be encoded on the server thread, so `toStored` runs there, and the finished text is handed to a +**single writer thread**, so two saves of one storage can never land out of order. Closing a storage and turning its +page both write it straight away; `StorageSaveTask` flushes whatever is still dirty every `storage.save-interval` +seconds. `Main.onDisable` closes every open storage (`StorageGUI.closeAll`) before `StorageManager.shutdown` drains +the writer and writes everything once more. + +A file that will not parse falls back to its `.bak`, and when neither can be read the storage is **unavailable, not +empty** — an empty one would be written over the player's items the moment they closed it. A single item that cannot be +decoded is set aside in `unreadable` and carried through every save untouched. + +**Crash window.** The server writes a player's inventory on its own schedule. A crash after an item is taken out of a +storage, but before that storage is next written, can leave the item in both places. Writing on close and on every +page turn keeps the window to the time someone is actively moving items around in one page. + +### The container lock + +`ContainerLockListener` refuses placing a chest, trapped chest, barrel, ender chest or any shulker box, placing a +chest or hopper minecart or a chest boat, and a dispenser doing either. Crafting is left alone, since chests go into +hoppers and minecarts. + +A container already in the world is **withdraw-only**. The listener recognises one by **the holder of its inventory** +(`Chest`, `DoubleChest`, `Barrel`, `ShulkerBox`, `StorageMinecart`, `ChestBoat`, or the `ENDER_CHEST` type), never by +`InventoryType` — TriTown's own menus and other plugins' are chest-shaped too, and they have no holder. It cancels +anything that would put an item in: placing or swapping into a top slot, a shift-click from the player's inventory, +a number key that carries an item in, and any drag touching the top. Taking out is always allowed. +`InventoryMoveItemEvent` is cancelled when the **destination** is locked, so hoppers can still empty a chest but not +fill one. A hopper minecart already running is left unlocked for the same reason: it is part of a machine. + +Each group has its own switch under `storage.lock-containers`, the whole lock follows `storage.enabled`, and +`tritown.storage.bypass` exempts a player. + +### Settings + +| Key | What it does | +|:--------------------------------------|:-------------------------------------------------------------| +| `storage.enabled` | Turns the storage and the lock off; turning it on needs a restart | +| `storage.free-pages` | Pages every player has without paying | +| `storage.max-pages` | The most pages a storage can reach (at most 256) | +| `storage.price.base` | What the first bought page costs | +| `storage.price.multiplier` | How much dearer each page is than the one before (1 to 10) | +| `storage.save-interval` | Seconds between flushes of changed storages | +| `storage.lock-containers.enabled` | The lock as a whole | +| `storage.lock-containers.chests` | Chests, trapped chests, barrels, chest minecarts, chest boats | +| `storage.lock-containers.shulker-boxes` | Every colour of shulker box | +| `storage.lock-containers.ender-chest` | The ender chest | + +`StorageSettings` is a snapshot swapped in whole on a reload, the way `ShopSettings` is. A reload never re-reads the +storage files. + + ## Server News Update notes for the server. Administrators write a post in game — a title, an optional summary and label, and 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 738fd4c..147e081 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/Main.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/Main.kt @@ -11,6 +11,7 @@ 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.guis.storage.StorageGUI import net.trilleo.mc.plugins.tritown.menu.MenuItem import net.trilleo.mc.plugins.tritown.news.NewsManager import net.trilleo.mc.plugins.tritown.news.storage.JsonNewsStorage @@ -18,6 +19,8 @@ import net.trilleo.mc.plugins.tritown.registration.* import net.trilleo.mc.plugins.tritown.scoreboard.ScoreboardService import net.trilleo.mc.plugins.tritown.shops.ShopManager import net.trilleo.mc.plugins.tritown.shops.storage.JsonShopStorage +import net.trilleo.mc.plugins.tritown.storage.StorageManager +import net.trilleo.mc.plugins.tritown.storage.storage.JsonStorageStore import net.trilleo.mc.plugins.tritown.trades.TradeManager import net.trilleo.mc.plugins.tritown.utils.EconomyUtil import net.trilleo.mc.plugins.tritown.utils.Lang @@ -108,6 +111,10 @@ class Main : JavaPlugin() { TownSettings.load(pluginConfig) MainMenuSettings.load(pluginConfig, logger) + // Before the registrars, like the shops: the main menu reads a player's storage as it is drawn. + StorageSettings.load(pluginConfig) + if (StorageSettings.snapshot.enabled) StorageManager.start(JsonStorageStore(dataFolder, logger), logger) + // Before the registrars, for the same reason as the shops: the main menu reads the news as it is drawn. NewsSettings.load(pluginConfig, logger) NewsManager.start(JsonNewsStorage(dataFolder, logger), logger) @@ -155,6 +162,8 @@ class Main : JavaPlugin() { TradeSettings.load(pluginConfig) TownSettings.load(pluginConfig) + // Only the settings, as with the shops: the storage files are never re-read while players hold them open. + StorageSettings.load(pluginConfig) // Only the settings, as with the shops: every change to a post is already on disk. NewsSettings.load(pluginConfig, logger) @@ -177,6 +186,10 @@ class Main : JavaPlugin() { // the server is about to save. TradeManager.shutdown() + // Every open storage copies its page back before the storages are written for the last time. + StorageGUI.closeAll() + StorageManager.shutdown() + // So no menu item is saved into an inventory and left behind once TriTown is gone. MenuItem.stripAll() diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/admin/AdminCommand.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/admin/AdminCommand.kt index ed1e125..7af15f8 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/admin/AdminCommand.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/admin/AdminCommand.kt @@ -2,6 +2,7 @@ package net.trilleo.mc.plugins.tritown.commands.admin import net.trilleo.mc.plugins.tritown.guis.admin.AdminPanelGUI import net.trilleo.mc.plugins.tritown.guis.admin.AdminShopsGUI +import net.trilleo.mc.plugins.tritown.guis.admin.AdminStorageGUI import net.trilleo.mc.plugins.tritown.guis.admin.EconomyPanelGUI import net.trilleo.mc.plugins.tritown.registration.GUIManager import net.trilleo.mc.plugins.tritown.registration.PluginCommand @@ -20,11 +21,15 @@ import org.bukkit.entity.Player class AdminCommand : PluginCommand( name = "admin", description = "Open the admin panel", - usage = "/tritown admin [economy|shops]", + usage = "/tritown admin [economy|shops|storage]", permission = AdminPanelGUI.PERMISSION, ) { - override val extraPermissions = listOf(AdminPanelGUI.ECONOMY_PERMISSION, AdminPanelGUI.SHOPS_PERMISSION) + override val extraPermissions = listOf( + AdminPanelGUI.ECONOMY_PERMISSION, + AdminPanelGUI.SHOPS_PERMISSION, + AdminPanelGUI.STORAGE_PERMISSION, + ) override fun execute(sender: CommandSender, args: Array): Boolean { val player = sender as? Player ?: run { @@ -44,6 +49,12 @@ class AdminCommand : PluginCommand( return true } + // Read off disk first, so it opens a moment later rather than here. + if (section == "storage") { + AdminStorageGUI.show(player) + return true + } + if (!GUIManager.open(player, guiFor(section))) { player.sendPrefixed(player.tr("command.admin.unavailable")) } @@ -68,10 +79,11 @@ class AdminCommand : PluginCommand( private fun permissionFor(section: String?): String? = when (section) { "economy" -> AdminPanelGUI.ECONOMY_PERMISSION "shops" -> AdminPanelGUI.SHOPS_PERMISSION + "storage" -> AdminPanelGUI.STORAGE_PERMISSION else -> null } private companion object { - val SECTIONS = listOf("economy", "shops") + val SECTIONS = listOf("economy", "shops", "storage") } } diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/storage/StorageCommand.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/storage/StorageCommand.kt new file mode 100644 index 0000000..eb6494d --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/storage/StorageCommand.kt @@ -0,0 +1,140 @@ +package net.trilleo.mc.plugins.tritown.commands.storage + +import net.trilleo.mc.plugins.tritown.economy.EconomyService +import net.trilleo.mc.plugins.tritown.enums.AccountType +import net.trilleo.mc.plugins.tritown.guis.storage.StorageGUI +import net.trilleo.mc.plugins.tritown.registration.PluginCommand +import net.trilleo.mc.plugins.tritown.storage.StorageManager +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.Bukkit +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player +import java.util.* + +/** + * Opening your storage, and — for administrators — anyone else's. + * + * It declares no permission on purpose, the way `/tritown menu` does: every + * player has a storage, and whether the feature runs at all is + * `storage.enabled` in the configuration rather than a node. Looking into or + * changing another player's storage needs [ADMIN_PERMISSION]. + */ +class StorageCommand : PluginCommand( + name = "storage", + description = "Open your storage", + usage = "/tritown storage [view |pages ]", +) { + + override val extraPermissions = listOf(ADMIN_PERMISSION, BYPASS_PERMISSION) + + override fun execute(sender: CommandSender, args: Array): Boolean { + if (!StorageManager.isAvailable) { + sender.sendPrefixed(error(sender, "storage.error.unavailable")) + return true + } + + when (args.firstOrNull()?.lowercase()) { + null -> { + val player = sender as? Player ?: run { + sender.sendPrefixed(sender.tr("command.storage.players-only")) + return true + } + StorageGUI.open(player, player.uniqueId) + } + + VIEW -> if (admin(sender)) view(sender, args.getOrNull(1)) + PAGES -> if (admin(sender)) pages(sender, args) + else -> sender.sendPrefixed(sender.tr("command.storage.usage")) + } + return true + } + + override fun tabComplete(sender: CommandSender, args: Array): List { + if (!sender.hasPermission(ADMIN_PERMISSION)) return emptyList() + val options = when (args.size) { + 1 -> listOf(VIEW, PAGES) + 2 -> Bukkit.getOnlinePlayers().map { it.name } + 3 -> if (args[0].equals(PAGES, ignoreCase = true)) listOf(ADD, SET) else emptyList() + else -> emptyList() + } + return options.filter { it.startsWith(args.last(), ignoreCase = true) } + } + + /** Opens [name]'s storage, online or not, for the administrator who asked. */ + private fun view(sender: CommandSender, name: String?) { + val player = sender as? Player ?: run { + sender.sendPrefixed(sender.tr("command.storage.players-only")) + return + } + val owner = name?.let(::resolve) ?: run { + player.sendPrefixed(error(player, "command.storage.not-found", "name" to ComponentUtil.escape(name.orEmpty()))) + return + } + StorageGUI.open(player, owner) + } + + /** Gives a player pages for free, or sets how many they own. */ + private fun pages(sender: CommandSender, args: Array) { + val name = args.getOrNull(1) + val mode = args.getOrNull(2)?.lowercase() + val amount = args.getOrNull(3)?.toIntOrNull() + if (name == null || mode !in setOf(ADD, SET) || amount == null) { + sender.sendPrefixed(sender.tr("command.storage.usage")) + return + } + + val owner = resolve(name) ?: run { + sender.sendPrefixed(error(sender, "command.storage.not-found", "name" to ComponentUtil.escape(name))) + return + } + val storage = StorageManager.get(owner) ?: run { + sender.sendPrefixed(error(sender, "storage.error.unreadable")) + return + } + + val target = if (mode == ADD) StorageManager.owned(storage) + amount else amount + StorageManager.setOwned(storage, target) + StorageManager.unloadIfIdle(owner) + + sender.sendPrefixed( + sender.tr( + "command.storage.pages-set", + "name" to ComponentUtil.escape(name), + "amount" to StorageManager.owned(storage), + ) + ) + } + + /** + * The player called [name], without ever asking Mojang: someone online, someone + * the server has cached, or someone TriTown's economy has an account for. + */ + private fun resolve(name: String): UUID? = + Bukkit.getPlayerExact(name)?.uniqueId + ?: Bukkit.getOfflinePlayerIfCached(name)?.uniqueId + ?: EconomyService.resolveByName(name)?.takeIf { it.type == AccountType.PLAYER }?.uuid + + private fun admin(sender: CommandSender): Boolean { + if (sender.hasPermission(ADMIN_PERMISSION)) return true + sender.sendPrefixed(sender.tr("command.no-permission")) + return false + } + + private fun error(sender: CommandSender, key: String, vararg args: Pair): String = + sender.tr("common.error", "message" to sender.tr(key, *args)) + + companion object { + /** Opening, changing and handing out pages of any player's storage. */ + const val ADMIN_PERMISSION = "tritown.storage.admin" + + /** Placing and filling the vanilla containers the storage replaces. */ + const val BYPASS_PERMISSION = "tritown.storage.bypass" + + private const val VIEW = "view" + private const val PAGES = "pages" + private const val ADD = "add" + private const val SET = "set" + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/StorageSettings.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/StorageSettings.kt new file mode 100644 index 0000000..6ac82ef --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/StorageSettings.kt @@ -0,0 +1,79 @@ +package net.trilleo.mc.plugins.tritown.config + +/** + * An immutable snapshot of the `storage` block of `config.yml`. + * + * Built whole and swapped in on a reload, the same way [ShopSettings] is, so a + * page being bought while the configuration is re-read cannot be priced from + * half of it. + * + * @param enabled whether players have a storage at all + * @param freePages how many pages every player has without paying + * @param maxPages the most pages a storage can reach, free ones included + * @param priceBase what the first bought page costs + * @param priceMultiplier how much dearer each bought page is than the one before + * @param saveIntervalSeconds how often changed storages are written out + * @param lock which vanilla containers are withdraw-only + */ +data class StorageSettings( + val enabled: Boolean, + val freePages: Int, + val maxPages: Int, + val priceBase: Double, + val priceMultiplier: Double, + val saveIntervalSeconds: Long, + val lock: ContainerLock, +) { + + /** + * Which groups of vanilla containers can no longer be placed or filled. + * + * @param chests chests, trapped chests, barrels, chest and hopper minecarts, and chest boats + * @param shulkerBoxes every colour of shulker box + * @param enderChest the ender chest + */ + data class ContainerLock( + val chests: Boolean, + val shulkerBoxes: Boolean, + val enderChest: Boolean, + ) + + companion object { + + /** The most pages a storage may be configured to reach. */ + const val PAGE_LIMIT = 256 + + @Volatile + private var current: StorageSettings? = null + + /** The settings in force. */ + val snapshot: StorageSettings + get() = current ?: error("Storage settings have not been loaded yet") + + /** Whether [load] has run. */ + val isLoaded: Boolean + get() = current != null + + /** Reads the `storage` block from [config] and makes it the current snapshot. */ + fun load(config: PluginConfig): StorageSettings = read(config).also { current = it } + + private fun read(config: PluginConfig): StorageSettings { + val maxPages = config.getInt("storage.max-pages", 27).coerceIn(1, PAGE_LIMIT) + val locking = config.getBoolean("storage.lock-containers.enabled", true) + + return StorageSettings( + enabled = config.getBoolean("storage.enabled", true), + freePages = config.getInt("storage.free-pages", 2).coerceIn(1, maxPages), + maxPages = maxPages, + priceBase = config.getDouble("storage.price.base", 500.0).coerceAtLeast(0.0), + priceMultiplier = config.getDouble("storage.price.multiplier", 1.5).coerceIn(1.0, 10.0), + saveIntervalSeconds = config.getLong("storage.save-interval", 30L).coerceIn(5L, 3600L), + lock = ContainerLock( + chests = locking && config.getBoolean("storage.lock-containers.chests", true), + shulkerBoxes = locking && config.getBoolean("storage.lock-containers.shulker-boxes", true), + enderChest = locking && config.getBoolean("storage.lock-containers.ender-chest", true), + ), + ) + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/economy/EconomyContext.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/economy/EconomyContext.kt index 6a46868..832e03d 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/economy/EconomyContext.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/economy/EconomyContext.kt @@ -44,4 +44,5 @@ object EconomyContext { const val SOURCE_TOWNY = "towny" const val SOURCE_SHOP = "shop" const val SOURCE_TRADE = "trade" + const val SOURCE_STORAGE = "storage" } diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/economy/TransactionReason.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/economy/TransactionReason.kt index fc46c57..313e63e 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/economy/TransactionReason.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/economy/TransactionReason.kt @@ -28,6 +28,7 @@ object TransactionReason { const val SHOP_BUY = "money.reason.shop-buy" const val SHOP_SELL = "money.reason.shop-sell" const val TRADE = "money.reason.trade" + const val STORAGE_PAGE = "money.reason.storage-page" /** Encodes [key] and its [args] into the single string that is stored with the transaction. */ fun of(key: String, vararg args: Pair): String = diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/enums/FlowCategory.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/enums/FlowCategory.kt index df2e903..e0ac273 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/enums/FlowCategory.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/enums/FlowCategory.kt @@ -22,6 +22,9 @@ enum class FlowCategory { /** Bought from, or sold to, one of the server's own shops. */ SHOP, + /** Pages of a player's storage, bought from the server. Always a sink. */ + STORAGE, + /** Anything Towny moved: bank deposits and withdrawals, plot sales, upkeep, taxes. */ TOWNY, @@ -42,6 +45,7 @@ enum class FlowCategory { get() = when (this) { STARTING_BALANCE -> "money.flow.starting-balance" SHOP -> "money.flow.shop" + STORAGE -> "money.flow.storage" TOWNY -> "money.flow.towny" ADMIN -> "money.flow.admin" PAYMENT -> "money.flow.payment" @@ -65,10 +69,12 @@ enum class FlowCategory { return when { key == TransactionReason.STARTING_BALANCE -> STARTING_BALANCE key == TransactionReason.SHOP_BUY || key == TransactionReason.SHOP_SELL -> SHOP + key == TransactionReason.STORAGE_PAGE -> STORAGE key == TransactionReason.TOWNY || key == TransactionReason.TOWN_DELETED -> TOWNY key == TransactionReason.ADMIN_SET || key == TransactionReason.ADMIN_RESET -> ADMIN key == TransactionReason.PAYMENT || key == TransactionReason.TRADE -> PAYMENT source == EconomyContext.SOURCE_SHOP -> SHOP + source == EconomyContext.SOURCE_STORAGE -> STORAGE source == EconomyContext.SOURCE_TOWNY -> TOWNY key == TransactionReason.EXTERNAL -> EXTERNAL else -> OTHER diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/AdminPanelGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/AdminPanelGUI.kt index 7e8fbff..530ab21 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/AdminPanelGUI.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/AdminPanelGUI.kt @@ -3,8 +3,10 @@ package net.trilleo.mc.plugins.tritown.guis.admin import com.palmergames.bukkit.towny.TownyAPI import net.trilleo.mc.plugins.tritown.Main import net.trilleo.mc.plugins.tritown.config.ShopSettings +import net.trilleo.mc.plugins.tritown.config.StorageSettings import net.trilleo.mc.plugins.tritown.economy.EconomyPulse import net.trilleo.mc.plugins.tritown.enums.FillMode +import net.trilleo.mc.plugins.tritown.enums.FlowCategory import net.trilleo.mc.plugins.tritown.enums.StatsWindow import net.trilleo.mc.plugins.tritown.guis.menu.MainMenuGUI import net.trilleo.mc.plugins.tritown.guis.menu.MenuRender @@ -13,6 +15,7 @@ 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.shops.ShopManager +import net.trilleo.mc.plugins.tritown.storage.StorageManager import net.trilleo.mc.plugins.tritown.utils.EconomyUtil import net.trilleo.mc.plugins.tritown.utils.TownyUtil import net.trilleo.mc.plugins.tritown.utils.tr @@ -38,7 +41,7 @@ class AdminPanelGUI : PluginGUI( fillMode = FillMode.NONE, ) { - private enum class Card { ECONOMY, SHOPS, SERVER } + private enum class Card { ECONOMY, SHOPS, STORAGE, SERVER } override fun setup(player: Player, inventory: Inventory) { val cards = cardsFor(player) @@ -48,6 +51,7 @@ class AdminPanelGUI : PluginGUI( val item = when (card) { Card.ECONOMY -> economy(player) Card.SHOPS -> shops(player) + Card.STORAGE -> storage(player) Card.SERVER -> server(player) } inventory.setItem(slot, item) @@ -68,6 +72,7 @@ class AdminPanelGUI : PluginGUI( when (cardsFor(player)[event.rawSlot]) { Card.ECONOMY -> GUIManager.openLater(player, EconomyPanelGUI.ID) Card.SHOPS -> GUIManager.openLater(player, AdminShopsGUI.ID) + Card.STORAGE -> MenuRender.later(player) { AdminStorageGUI.show(player) } Card.SERVER, null -> Unit } } @@ -77,6 +82,7 @@ class AdminPanelGUI : PluginGUI( val cards = listOfNotNull( Card.ECONOMY.takeIf { player.hasPermission(ECONOMY_PERMISSION) }, Card.SHOPS.takeIf { player.hasPermission(SHOPS_PERMISSION) }, + Card.STORAGE.takeIf { player.hasPermission(STORAGE_PERMISSION) }, Card.SERVER, ) return GUIFrame.spacedColumns(cards.size).zip(cards) @@ -131,6 +137,31 @@ class AdminPanelGUI : PluginGUI( return PanelRender.card(Material.EMERALD, player.tr("gui.admin.shops"), lines) } + private fun storage(player: Player): ItemStack { + val lines = mutableListOf(player.tr("gui.admin.storage-lore")) + + if (!StorageManager.isAvailable) { + lines += player.tr("gui.admin.storage-off") + } else { + val settings = StorageSettings.snapshot + lines += "" + lines += player.tr("gui.admin.storage-free", "amount" to settings.freePages, "max" to settings.maxPages) + lines += player.tr("gui.admin.storage-open", "amount" to StorageManager.cachedAll().size) + if (EconomyPulse.isEnabled) { + val revenue = EconomyPulse.window(StatsWindow.DAY.hours).destroyedBy[FlowCategory.STORAGE] ?: 0L + lines += player.tr( + "gui.admin.storage-revenue", + "amount" to PanelRender.money(revenue), + "window" to player.tr(StatsWindow.DAY.key), + ) + } + } + + lines += "" + lines += player.tr("gui.admin.click-open") + return PanelRender.card(Material.ENDER_CHEST, player.tr("gui.admin.storage"), lines) + } + /** * What the server is running, in the two or three numbers that say whether * anything is wrong before the sections are opened. @@ -166,6 +197,7 @@ class AdminPanelGUI : PluginGUI( const val ECONOMY_PERMISSION = "tritown.admin.economy" const val SHOPS_PERMISSION = "tritown.admin.shops" + const val STORAGE_PERMISSION = "tritown.admin.storage" private const val CARD_ROW = 2 private const val BACK_SLOT = 49 diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/AdminStorageGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/AdminStorageGUI.kt new file mode 100644 index 0000000..dfb40fe --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/AdminStorageGUI.kt @@ -0,0 +1,146 @@ +package net.trilleo.mc.plugins.tritown.guis.admin + +import net.trilleo.mc.plugins.tritown.commands.storage.StorageCommand +import net.trilleo.mc.plugins.tritown.config.StorageSettings +import net.trilleo.mc.plugins.tritown.economy.EconomyPulse +import net.trilleo.mc.plugins.tritown.enums.FillMode +import net.trilleo.mc.plugins.tritown.enums.FlowCategory +import net.trilleo.mc.plugins.tritown.enums.PagedLayout +import net.trilleo.mc.plugins.tritown.guis.menu.MenuRender +import net.trilleo.mc.plugins.tritown.guis.storage.StorageGUI +import net.trilleo.mc.plugins.tritown.guis.storage.StorageRender +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PagedPluginGUI +import net.trilleo.mc.plugins.tritown.storage.StorageManager +import net.trilleo.mc.plugins.tritown.storage.StoragePage +import net.trilleo.mc.plugins.tritown.storage.storage.StorageSummary +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Bukkit +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.ClickType +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.inventory.ItemStack +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * Every storage on the server, fullest first. + * + * Read from disk each time it is opened, without decoding an item, so it shows + * offline players too. Clicking a storage opens it read-only; shift-clicking + * opens it to change, for an administrator who may. + */ +class AdminStorageGUI : PagedPluginGUI( + id = ID, + titleKey = "gui.admin-storage.title", + rows = 6, + fillMode = FillMode.NONE, + layout = PagedLayout.FRAMED, +) { + + private val snapshots = ConcurrentHashMap>() + + override fun getItems(player: Player): List { + if (!StorageManager.isAvailable) { + return listOf( + PanelRender.card(Material.BARRIER, player.tr("gui.admin-storage.disabled"), listOf(player.tr("gui.admin-storage.disabled-lore"))) + ) + } + val summaries = snapshots[player.uniqueId].orEmpty() + return listOf(header(player, summaries)) + summaries.map { row(player, it) } + } + + override fun onContentClick(event: InventoryClickEvent, page: Int) { + event.isCancelled = true + val player = event.whoClicked as? Player ?: return + + // The header takes the first position, so the storages start one behind it. + val index = (contentIndex(event, page) ?: return) - 1 + val summary = snapshots[player.uniqueId]?.getOrNull(index) ?: return + + val edit = event.click == ClickType.SHIFT_LEFT && player.hasPermission(StorageCommand.ADMIN_PERMISSION) + MenuRender.later(player) { StorageGUI.open(player, summary.owner, readOnly = !edit) } + } + + override fun navButtons(player: Player): Map = mapOf( + BACK_OFFSET to PanelRender.card( + Material.ARROW, + player.tr("gui.admin-storage.back"), + listOf(player.tr("gui.admin-storage.back-lore")), + ), + ) + + override fun onNavClick(event: InventoryClickEvent, offset: Int) { + val player = event.whoClicked as? Player ?: return + if (offset == BACK_OFFSET) GUIManager.openLater(player, AdminPanelGUI.ID) + } + + override fun onClose(event: InventoryCloseEvent) { + super.onClose(event) + snapshots.remove(event.player.uniqueId) + } + + // ── Rendering ─────────────────────────────────────────────────────── + + private fun header(player: Player, summaries: List): ItemStack { + val window = PanelState.window(player) + val lines = mutableListOf( + player.tr("gui.admin-storage.count", "amount" to summaries.size), + player.tr("gui.admin-storage.bought", "amount" to summaries.sumOf { it.purchased }), + player.tr("gui.admin-storage.slots", "amount" to summaries.sumOf { it.usedSlots }), + ) + if (EconomyPulse.isEnabled) { + val revenue = EconomyPulse.window(window.hours).destroyedBy[FlowCategory.STORAGE] ?: 0L + lines += player.tr( + "gui.admin-storage.revenue", + "amount" to PanelRender.money(revenue), + "window" to player.tr(window.key), + ) + } + lines += "" + lines += player.tr("gui.admin-storage.header-lore") + + return PanelRender.card(Material.WRITABLE_BOOK, player.tr("gui.admin-storage.header"), lines) + } + + private fun row(player: Player, summary: StorageSummary): ItemStack { + val settings = StorageSettings.snapshot + val owned = (settings.freePages + summary.purchased).coerceAtMost(settings.maxPages) + + val lines = mutableListOf( + player.tr("gui.admin-storage.pages", "amount" to owned, "bought" to summary.purchased), + player.tr( + "gui.admin-storage.used", + "amount" to summary.usedSlots, + "total" to owned * StoragePage.SIZE, + ), + "", + player.tr("gui.admin-storage.click-view"), + ) + if (player.hasPermission(StorageCommand.ADMIN_PERMISSION)) lines += player.tr("gui.admin-storage.click-edit") + + return MenuRender.head(Bukkit.getOfflinePlayer(summary.owner), player.tr("gui.admin-storage.owner", "name" to StorageRender.ownerName(summary.owner)), lines) + } + + companion object { + const val ID = "admin-storage" + + private const val BACK_OFFSET = 2 + + /** Reads every storage off disk and opens the list for [viewer] once it has. */ + fun show(viewer: Player) { + val gui = GUIManager.getGUI(ID) as? AdminStorageGUI ?: return + if (!StorageManager.isAvailable) { + GUIManager.open(viewer, ID) + return + } + StorageManager.summaries { summaries -> + if (!viewer.isOnline) return@summaries + gui.snapshots[viewer.uniqueId] = summaries.sortedByDescending { it.usedSlots } + GUIManager.open(viewer, ID) + } + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/EconomyFlowGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/EconomyFlowGUI.kt index a9526d3..6bda3cd 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/EconomyFlowGUI.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/EconomyFlowGUI.kt @@ -173,6 +173,7 @@ class EconomyFlowGUI : PagedPluginGUI( private fun material(category: FlowCategory): Material = when (category) { FlowCategory.STARTING_BALANCE -> Material.EGG FlowCategory.SHOP -> Material.EMERALD + FlowCategory.STORAGE -> Material.ENDER_CHEST FlowCategory.TOWNY -> Material.BELL FlowCategory.ADMIN -> Material.COMMAND_BLOCK FlowCategory.PAYMENT -> Material.ENDER_PEARL @@ -193,6 +194,7 @@ class EconomyFlowGUI : PagedPluginGUI( private fun descriptionOf(category: FlowCategory): String = when (category) { FlowCategory.STARTING_BALANCE -> "gui.admin-flow.about-starting-balance" FlowCategory.SHOP -> "gui.admin-flow.about-shop" + FlowCategory.STORAGE -> "gui.admin-flow.about-storage" FlowCategory.TOWNY -> "gui.admin-flow.about-towny" FlowCategory.ADMIN -> "gui.admin-flow.about-admin" FlowCategory.PAYMENT -> "gui.admin-flow.about-payment" 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 da313c2..66b2349 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 @@ -2,12 +2,14 @@ package net.trilleo.mc.plugins.tritown.guis.menu import com.palmergames.bukkit.towny.TownyAPI import net.trilleo.mc.plugins.tritown.config.ShopSettings +import net.trilleo.mc.plugins.tritown.config.StorageSettings import net.trilleo.mc.plugins.tritown.economy.BaltopCache import net.trilleo.mc.plugins.tritown.economy.CurrencyRegistry 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.storage.StorageRender import net.trilleo.mc.plugins.tritown.news.NewsManager import net.trilleo.mc.plugins.tritown.news.NewsReadState import net.trilleo.mc.plugins.tritown.registration.CommandRegistrar @@ -17,6 +19,7 @@ import net.trilleo.mc.plugins.tritown.registration.PluginGUI import net.trilleo.mc.plugins.tritown.scoreboard.ScoreboardService import net.trilleo.mc.plugins.tritown.shops.ShopAccess import net.trilleo.mc.plugins.tritown.shops.ShopManager +import net.trilleo.mc.plugins.tritown.storage.StorageManager import net.trilleo.mc.plugins.tritown.towns.FoundingCredit import net.trilleo.mc.plugins.tritown.trades.TradeManager import net.trilleo.mc.plugins.tritown.utils.* @@ -50,7 +53,7 @@ class MainMenuGUI : PluginGUI( fillMode = FillMode.NONE, ) { - private enum class Button { PROFILE, TOWN, SHOP, TRADE, PAY, LEADERBOARD, SERVER, NEWS, SIDEBAR, ADMIN, CLOSE } + private enum class Button { PROFILE, TOWN, STORAGE, SHOP, TRADE, PAY, LEADERBOARD, SERVER, NEWS, SIDEBAR, ADMIN, CLOSE } /** Which button each slot holds, per viewer, since the buttons shown depend on who is looking. */ private val layouts = ConcurrentHashMap>() @@ -70,6 +73,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.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) } Button.PAY -> MenuRender.later(player) { PlayerPickerGUI.show(player, PlayerPickerGUI.Mode.PAY) } @@ -103,6 +107,7 @@ class MainMenuGUI : PluginGUI( listOf(Button.PROFILE), listOfNotNull( Button.TOWN.takeIf { hasTownyMenu() }, + Button.STORAGE.takeIf { StorageManager.isAvailable }, Button.SHOP.takeIf { globalShopFor(player) }, Button.TRADE.takeIf { TradeManager.isEnabled }, ), @@ -143,6 +148,7 @@ class MainMenuGUI : PluginGUI( private fun render(player: Player, button: Button): ItemStack = when (button) { Button.PROFILE -> profile(player) Button.TOWN -> town(player) + Button.STORAGE -> storage(player) Button.SHOP -> card(player, Material.EMERALD, "gui.menu.shop", "gui.menu.shop-lore") Button.TRADE -> trade(player) Button.PAY -> card(player, Material.GOLD_INGOT, "gui.menu.pay", "gui.menu.pay-lore") @@ -219,6 +225,25 @@ class MainMenuGUI : PluginGUI( return PanelRender.card(Material.BELL, player.tr("gui.menu.town"), lines) } + /** How many pages the viewer has, and what the next one costs, so buying one is never a surprise. */ + private fun storage(player: Player): ItemStack { + val lines = mutableListOf(player.tr("gui.menu.storage-lore")) + StorageManager.get(player.uniqueId)?.let { storage -> + lines += "" + lines += player.tr( + "gui.menu.storage-pages", + "amount" to StorageManager.pageCount(storage), + "max" to StorageSettings.snapshot.maxPages, + ) + StorageManager.nextPageCost(storage)?.let { + lines += player.tr("gui.menu.storage-next", "amount" to StorageRender.money(it)) + } + } + lines += "" + lines += player.tr("gui.admin.click-open") + return PanelRender.card(Material.ENDER_CHEST, player.tr("gui.menu.storage"), lines) + } + /** Glows while somebody is waiting for an answer, which is the one thing here worth interrupting for. */ private fun trade(player: Player): ItemStack { val waiting = TradeManager.requestersFor(player.uniqueId).count { Bukkit.getPlayer(it) != null } diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/storage/StorageGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/storage/StorageGUI.kt new file mode 100644 index 0000000..4e97e46 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/storage/StorageGUI.kt @@ -0,0 +1,599 @@ +package net.trilleo.mc.plugins.tritown.guis.storage + +import net.kyori.adventure.text.Component +import net.trilleo.mc.plugins.tritown.Main +import net.trilleo.mc.plugins.tritown.commands.storage.StorageCommand +import net.trilleo.mc.plugins.tritown.enums.FillMode +import net.trilleo.mc.plugins.tritown.guis.ConfirmGUI +import net.trilleo.mc.plugins.tritown.guis.admin.AdminStorageGUI +import net.trilleo.mc.plugins.tritown.guis.admin.PanelRender +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.GUIFrame +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PluginGUI +import net.trilleo.mc.plugins.tritown.storage.* +import net.trilleo.mc.plugins.tritown.utils.ComponentUtil +import net.trilleo.mc.plugins.tritown.utils.itemStack +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Bukkit +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.ClickType +import org.bukkit.event.inventory.InventoryAction +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.event.inventory.InventoryDragEvent +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.ItemStack +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * One page of a player's storage. + * + * The top five rows are real slots, and this is the one menu in TriTown that + * lets the game move items itself: a player sorts their storage the way they + * would sort a chest. Everything else is guarded. The bottom row is buttons and + * nothing may be put into it or taken out of it, a shift-click into the page is + * done by hand so it can never land on a button, and anything the storage will + * not hold is turned away before it reaches a slot. + * + * What is on screen is copied back into the storage after every change, when + * the page is switched and when the menu closes. Whoever changes a storage has + * to be the one person holding it — see [StorageManager.claim] — so two windows + * can never write different versions of the same page. + */ +class StorageGUI : PluginGUI( + id = ID, + titleKey = "gui.storage.title", + rows = ROWS, + fillMode = FillMode.NONE, +) { + + /** Whose storage [viewer] is looking at, which page, and whether they may change it. */ + private class View(val owner: UUID, var page: Int, val access: StorageManager.Access) { + var inventory: Inventory? = null + val canEdit: Boolean get() = access == StorageManager.Access.EDIT + } + + private val views = ConcurrentHashMap() + + override fun title(player: Player): Component { + val view = views[player.uniqueId] ?: return super.title(player) + val storage = StorageManager.cached(view.owner) + val total = storage?.let(StorageManager::pageCount) ?: 1 + val name = StorageRender.pageName(player, storage?.pageOrNull(view.page), view.page) + + val title = if (view.owner == player.uniqueId) { + player.tr("gui.storage.title", "name" to name, "page" to view.page + 1, "total" to total) + } else { + player.tr( + "gui.storage.title-inspect", + "owner" to StorageRender.ownerName(view.owner), + "page" to view.page + 1, + "total" to total, + ) + } + return ComponentUtil.parse(title) + } + + override fun setup(player: Player, inventory: Inventory) { + val view = views[player.uniqueId] ?: return + val storage = StorageManager.cached(view.owner) ?: return + view.inventory = inventory + + val page = storage.page(view.page) + for (slot in 0 until StoragePage.SIZE) inventory.setItem(slot, page.slots[slot]?.clone()) + + GUIFrame.draw(inventory, (0 until StoragePage.SIZE).toList()) + buttons(player, view, storage).forEach { (slot, item) -> inventory.setItem(slot, item) } + } + + // ── Clicks ────────────────────────────────────────────────────────── + + override fun onClick(event: InventoryClickEvent) { + val player = event.whoClicked as? Player ?: return + val view = views[player.uniqueId] ?: run { + event.isCancelled = true + return + } + + if (event.action == InventoryAction.COLLECT_TO_CURSOR) { + // Gathers matching items from every slot on screen, buttons included. + event.isCancelled = true + return + } + + val slot = event.rawSlot + when { + slot in BUTTON_SLOTS -> { + event.isCancelled = true + button(player, view, slot, event.click) + } + + slot in 0 until StoragePage.SIZE -> content(player, view, event) + + event.action == InventoryAction.MOVE_TO_OTHER_INVENTORY -> { + event.isCancelled = true + if (view.canEdit) shiftIn(player, view, event) + } + } + } + + override fun onDrag(event: InventoryDragEvent) { + val player = event.whoClicked as? Player ?: return + val view = views[player.uniqueId] + val intoTop = event.rawSlots.any { it < ROWS * ROW_SIZE } + if (!intoTop) return + + when { + view == null || !view.canEdit || event.rawSlots.any { it in BUTTON_SLOTS } -> event.isCancelled = true + !StorageItems.accepts(event.oldCursor) -> { + event.isCancelled = true + StorageRender.refuse(player, "storage.error.not-allowed") + } + + else -> snapshotLater(player, view) + } + } + + override fun onClose(event: InventoryCloseEvent) { + val player = event.player as? Player ?: return + finish(player) + } + + /** + * A click on one of the page's own slots, which the game carries out unless + * it would put something the storage refuses there. + */ + private fun content(player: Player, view: View, event: InventoryClickEvent) { + if (!view.canEdit || event.action !in CONTENT_ACTIONS) { + event.isCancelled = true + return + } + + val incoming = when (event.action) { + InventoryAction.PLACE_ALL, InventoryAction.PLACE_SOME, InventoryAction.PLACE_ONE, + InventoryAction.SWAP_WITH_CURSOR -> event.cursor + + InventoryAction.HOTBAR_SWAP -> if (event.click == ClickType.SWAP_OFFHAND) { + player.inventory.itemInOffHand + } else { + player.inventory.getItem(event.hotbarButton) + } + + else -> null + } + + if (!StorageItems.accepts(incoming)) { + event.isCancelled = true + StorageRender.refuse(player, "storage.error.not-allowed") + return + } + + snapshotLater(player, view) + } + + /** + * A shift-click in the player's own inventory, moved onto the page by hand. + * + * Left to the game, it would merge into any stack on screen that matched, + * and a button is a stack on screen. + */ + private fun shiftIn(player: Player, view: View, event: InventoryClickEvent) { + val clicked = event.currentItem ?: return + if (clicked.type.isAir) return + if (!StorageItems.accepts(clicked)) { + StorageRender.refuse(player, "storage.error.not-allowed") + return + } + + val storage = StorageManager.cached(view.owner) ?: return + snapshot(view) + + val leftover = SlotFill.insert(listOf(storage.page(view.page).slots), clicked.clone(), StorageItems.rules) + if (leftover != null && leftover.amount == clicked.amount) return + + event.clickedInventory?.setItem(event.slot, leftover) + StorageManager.markDirty(storage) + redraw(player, view) + } + + // ── Buttons ───────────────────────────────────────────────────────── + + private fun button(player: Player, view: View, slot: Int, click: ClickType) { + val storage = StorageManager.cached(view.owner) ?: return + val pages = StorageManager.pageCount(storage) + + when (slot) { + SLOT_PREVIOUS -> if (view.page > 0) switchPage(player, view, view.page - 1) + SLOT_OVERVIEW -> leave(player) { StoragePagesGUI.show(player, view.owner, view.page, readOnly = !view.canEdit) } + SLOT_DEPOSIT -> if (view.canEdit) quickDeposit(player, view, storage) + SLOT_SORT -> if (view.canEdit) sort(player, view, storage, everyPage = click.isShiftClick) + SLOT_INFO -> leave(player) { back(player, view) } + SLOT_WITHDRAW -> if (view.canEdit) withdrawPage(player, view, storage) + SLOT_UNPACK -> if (view.canEdit) unpackLater(player, view) + SLOT_SETTINGS -> if (canRename(player, view)) { + leave(player) { StoragePageSettingsGUI.show(player, view.owner, view.page) } + } + + SLOT_NEXT -> when { + view.page + 1 < pages -> switchPage(player, view, view.page + 1) + view.owner == player.uniqueId && view.canEdit && StorageManager.nextPageCost(storage) != null -> + leave(player) { offerPage(player, view.page) } + } + } + } + + /** Puts every stack from the main inventory whose material is already stored into the storage. */ + private fun quickDeposit(player: Player, view: View, storage: PlayerStorage) { + snapshot(view) + val materials = StorageManager.materials(storage) + var moved = 0 + + for (index in MAIN_INVENTORY) { + val stack = player.inventory.getItem(index) ?: continue + if (stack.type !in materials || !StorageItems.accepts(stack)) continue + + val leftover = StorageManager.deposit(storage, view.page, stack.clone()) + moved += stack.amount - (leftover?.amount ?: 0) + player.inventory.setItem(index, leftover) + } + + if (moved == 0) { + StorageRender.refuse(player, "storage.error.nothing-to-deposit") + return + } + MenuRender.click(player) + player.sendPrefixed(player.tr("storage.deposited", "amount" to moved)) + redraw(player, view) + } + + private fun sort(player: Player, view: View, storage: PlayerStorage, everyPage: Boolean) { + snapshot(view) + val targets = if (everyPage) (0 until StorageManager.pageCount(storage)) else listOf(view.page) + targets.forEach { SlotFill.sort(storage.page(it).slots, StorageItems.rules, StorageItems.order) } + + StorageManager.markDirty(storage) + MenuRender.click(player) + redraw(player, view) + } + + /** Moves as much of the page as fits into the player's inventory, leaving the rest where it was. */ + private fun withdrawPage(player: Player, view: View, storage: PlayerStorage) { + snapshot(view) + val page = storage.page(view.page) + var moved = 0 + + for (index in page.slots.indices) { + val stack = page.slots[index] ?: continue + val leftover = player.inventory.addItem(stack.clone()).values.firstOrNull() + moved += stack.amount - (leftover?.amount ?: 0) + page.slots[index] = leftover + } + + if (moved == 0) { + StorageRender.refuse(player, "storage.error.inventory-full") + return + } + StorageManager.markDirty(storage) + MenuRender.click(player) + redraw(player, view) + } + + /** + * Empties the shulker box or bundle on the cursor into the storage. + * + * Run on the next tick, once the refused click has settled, so the cursor + * read is the one the player really holds. Nothing moves unless all of it + * fits: a box half unpacked would leave the player to work out what went where. + */ + private fun unpackLater(player: Player, view: View) { + Bukkit.getScheduler().runTask(Main.instance, Runnable { + if (views[player.uniqueId] !== view || player.openInventory.topInventory !== view.inventory) return@Runnable + val storage = StorageManager.cached(view.owner) ?: return@Runnable + + val cursor = player.itemOnCursor + if (!StorageItems.isContainer(cursor)) { + StorageRender.refuse(player, "storage.error.unpack-hint") + return@Runnable + } + val contents = StorageItems.unpacked(cursor) + if (contents.isEmpty()) { + StorageRender.refuse(player, "storage.error.unpack-empty") + return@Runnable + } + + snapshot(view) + if (!StorageManager.fits(storage, contents)) { + StorageRender.refuse(player, "storage.error.no-room") + return@Runnable + } + + contents.forEach { StorageManager.deposit(storage, view.page, it.clone()) } + player.setItemOnCursor(StorageItems.emptied(cursor)) + MenuRender.click(player) + player.sendPrefixed(player.tr("storage.unpacked", "amount" to contents.sumOf { it.amount })) + redraw(player, view) + }) + } + + private fun back(player: Player, view: View) { + if (view.owner == player.uniqueId) MainMenuGUI.show(player) else AdminStorageGUI.show(player) + } + + private fun canRename(player: Player, view: View): Boolean = + view.canEdit && (view.owner == player.uniqueId || player.hasPermission(StorageCommand.ADMIN_PERMISSION)) + + // ── Drawing ───────────────────────────────────────────────────────── + + private fun buttons(player: Player, view: View, storage: PlayerStorage): Map { + val pages = StorageManager.pageCount(storage) + val buttons = mutableMapOf() + + if (view.page > 0) { + buttons[SLOT_PREVIOUS] = card(player, Material.ARROW, "gui.storage.previous", "gui.storage.previous-lore") + } + buttons[SLOT_OVERVIEW] = card(player, Material.BOOKSHELF, "gui.storage.overview", "gui.storage.overview-lore") + buttons[SLOT_INFO] = info(player, view, storage) + + if (view.canEdit) { + buttons[SLOT_DEPOSIT] = card(player, Material.HOPPER, "gui.storage.deposit", "gui.storage.deposit-lore") + buttons[SLOT_SORT] = card(player, Material.COMPARATOR, "gui.storage.sort", "gui.storage.sort-lore") + buttons[SLOT_WITHDRAW] = card(player, Material.DROPPER, "gui.storage.withdraw", "gui.storage.withdraw-lore") + buttons[SLOT_UNPACK] = card(player, Material.SHULKER_BOX, "gui.storage.unpack", "gui.storage.unpack-lore") + } + if (canRename(player, view)) { + buttons[SLOT_SETTINGS] = card(player, Material.NAME_TAG, "gui.storage.settings", "gui.storage.settings-lore") + } + + val buyable = view.owner == player.uniqueId && view.canEdit + when { + view.page + 1 < pages -> + buttons[SLOT_NEXT] = card(player, Material.ARROW, "gui.storage.next", "gui.storage.next-lore") + + buyable -> StorageRender.buyCard(player, storage)?.let { buttons[SLOT_NEXT] = it } + } + return buttons + } + + private fun info(player: Player, view: View, storage: PlayerStorage): ItemStack { + val page = storage.pageOrNull(view.page) + val lines = mutableListOf( + player.tr("gui.storage.info-page", "page" to view.page + 1, "total" to StorageManager.pageCount(storage)), + player.tr("gui.storage.overview-used", "amount" to (page?.used ?: 0), "total" to StoragePage.SIZE), + ) + if (view.owner != player.uniqueId) { + lines += player.tr("gui.storage.info-owner", "owner" to StorageRender.ownerName(view.owner)) + } + if (!view.canEdit) lines += player.tr("gui.storage.info-read-only") + lines += "" + lines += player.tr(if (view.owner == player.uniqueId) "gui.storage.info-back" else "gui.storage.info-back-admin") + + return PanelRender.card( + StorageRender.icon(page), + player.tr("gui.storage.info", "name" to StorageRender.pageName(player, page, view.page)), + lines, + ) + } + + private fun card(player: Player, material: Material, nameKey: String, loreKey: String): ItemStack = + PanelRender.card(material, player.tr(nameKey), listOf(player.tr(loreKey))) + + // ── Keeping the storage and the screen the same ───────────────────── + + /** Copies what is on screen into the storage. */ + private fun snapshot(view: View) { + if (!view.canEdit) return + val inventory = view.inventory ?: return + val storage = StorageManager.cached(view.owner) ?: return + val page = storage.page(view.page) + + var changed = false + for (slot in 0 until StoragePage.SIZE) { + val shown = inventory.getItem(slot)?.takeIf { !it.type.isAir }?.clone() + if (shown != page.slots[slot]) { + page.slots[slot] = shown + changed = true + } + } + + if (changed) { + StorageManager.markDirty(storage) + watchers(view).forEach { GUIManager.refresh(it) } + } + } + + /** + * Copies the page back on the next tick, once the game has carried the + * click out; the screen only shows its result after this handler returns. + */ + private fun snapshotLater(player: Player, view: View) { + Bukkit.getScheduler().runTask(Main.instance, Runnable { + if (views[player.uniqueId] === view && player.openInventory.topInventory === view.inventory) snapshot(view) + }) + } + + /** Rewrites [player]'s screen from the storage, after something changed it behind the screen's back. */ + private fun redraw(player: Player, view: View) { + GUIManager.refresh(player) + watchers(view).forEach { GUIManager.refresh(it) } + } + + /** Everyone else looking at the same page read-only, whose screens have to follow it. */ + private fun watchers(view: View): List = views.entries + .filter { (_, other) -> other !== view && other.owner == view.owner && other.page == view.page && !other.canEdit } + .mapNotNull { (viewer, _) -> Bukkit.getPlayer(viewer) } + .filter { GUIManager.openGUI(it)?.id == ID } + + private fun switchPage(player: Player, view: View, target: Int) { + snapshot(view) + MenuRender.later(player) { + if (views[player.uniqueId] !== view) return@later + // Once more, for anything moved between the click and now. + snapshot(view) + view.page = target + GUIManager.open(player, ID) + } + } + + /** + * Leaves the storage for another menu. + * + * Opening another menu from here does not deliver a close to this one, so + * the storage is let go of by hand, on the tick the next menu opens. + */ + private fun leave(player: Player, then: () -> Unit) { + MenuRender.later(player) { + finish(player) + then() + } + } + + /** Copies the page back, lets go of the storage and writes it. Safe to call more than once. */ + fun finish(player: Player) { + val view = views.remove(player.uniqueId) ?: return + snapshot(view) + StorageManager.cached(view.owner)?.let { if (it.dirty) StorageManager.save(it) } + StorageManager.release(view.owner, player.uniqueId) + } + + /** Every viewer with a storage open. */ + fun viewerIds(): Set = views.keys.toSet() + + companion object { + + const val ID = "storage" + + private const val ROWS = 6 + private const val ROW_SIZE = 9 + + private const val SLOT_PREVIOUS = 45 + private const val SLOT_OVERVIEW = 46 + private const val SLOT_DEPOSIT = 47 + private const val SLOT_SORT = 48 + private const val SLOT_INFO = 49 + private const val SLOT_WITHDRAW = 50 + private const val SLOT_UNPACK = 51 + private const val SLOT_SETTINGS = 52 + private const val SLOT_NEXT = 53 + + private val BUTTON_SLOTS = StoragePage.SIZE until ROWS * ROW_SIZE + + /** The player's main inventory without the hotbar, which quick deposit never empties. */ + private val MAIN_INVENTORY = 9..35 + + /** What the game may do on a page slot; anything else is refused. */ + private val CONTENT_ACTIONS = setOf( + InventoryAction.NOTHING, + InventoryAction.PICKUP_ALL, + InventoryAction.PICKUP_SOME, + InventoryAction.PICKUP_HALF, + InventoryAction.PICKUP_ONE, + InventoryAction.PLACE_ALL, + InventoryAction.PLACE_SOME, + InventoryAction.PLACE_ONE, + InventoryAction.SWAP_WITH_CURSOR, + InventoryAction.HOTBAR_SWAP, + InventoryAction.DROP_ALL_SLOT, + InventoryAction.DROP_ONE_SLOT, + InventoryAction.MOVE_TO_OTHER_INVENTORY, + InventoryAction.CLONE_STACK, + InventoryAction.PICKUP_ALL_INTO_BUNDLE, + InventoryAction.PICKUP_SOME_INTO_BUNDLE, + ) + + private fun gui(): StorageGUI? = GUIManager.getGUI(ID) as? StorageGUI + + /** + * Opens page [page] of [owner]'s storage for [viewer]. + * + * @param readOnly open it only to look, even when [viewer] could change it + * @return `false` when it could not be opened; [viewer] has been told why + */ + fun open(viewer: Player, owner: UUID, page: Int = 0, readOnly: Boolean = false): Boolean { + val gui = gui() ?: return false + if (!StorageManager.isAvailable) { + viewer.sendPrefixed(viewer.tr("common.error", "message" to viewer.tr("storage.error.unavailable"))) + return false + } + + gui.finish(viewer) + val storage = StorageManager.get(owner) ?: run { + StorageRender.refuse(viewer, "storage.error.unreadable") + return false + } + + val inspect = viewer.uniqueId != owner && viewer.hasPermission(StorageCommand.ADMIN_PERMISSION) + val access = StorageManager.claim(owner, viewer.uniqueId, inspect, readOnly) ?: run { + StorageRender.refuse(viewer, "storage.error.busy") + StorageManager.unloadIfIdle(owner) + return false + } + + val index = page.coerceIn(0, StorageManager.pageCount(storage) - 1) + gui.views[viewer.uniqueId] = View(owner, index, access) + if (!GUIManager.open(viewer, ID)) { + gui.finish(viewer) + return false + } + return true + } + + /** Closes [player]'s storage, if they have one open, so it is copied back before anything else happens. */ + fun close(player: Player) { + val gui = gui() ?: return + gui.finish(player) + if (GUIManager.openGUI(player)?.id == ID) player.closeInventory() + } + + /** Closes every open storage, for a shutdown. */ + fun closeAll() { + val gui = gui() ?: return + gui.viewerIds().mapNotNull(Bukkit::getPlayer).forEach(::close) + } + + /** Asks [player] whether to buy one more page, going back to page [returnTo] if they do not. */ + fun offerPage(player: Player, returnTo: Int) { + val storage = StorageManager.get(player.uniqueId) ?: return + val card = StorageRender.buyCard(player, storage) ?: return + + val confirm = itemStack(Material.LIME_CONCRETE) { + name(player.tr("gui.storage.buy-confirm")) + } + ConfirmGUI.show( + player, + title = player.tr("gui.storage.buy-title"), + subject = card, + choices = listOf(ConfirmGUI.Choice(confirm) { buy(it, returnTo) }), + onCancel = { open(it, it.uniqueId, returnTo) }, + ) + } + + /** Buys a page for [player] and opens it, or says why not and goes back to [returnTo]. */ + private fun buy(player: Player, returnTo: Int) { + when (StorageManager.buyPage(player)) { + StorageManager.Purchase.BOUGHT -> { + val storage = StorageManager.get(player.uniqueId) ?: return + val page = StorageManager.owned(storage) + player.sendPrefixed(player.tr("storage.bought", "page" to page)) + open(player, player.uniqueId, page - 1) + } + + StorageManager.Purchase.CANNOT_AFFORD -> { + StorageRender.refuse(player, "storage.error.cannot-afford") + open(player, player.uniqueId, returnTo) + } + + StorageManager.Purchase.AT_MAX -> { + StorageRender.refuse(player, "storage.error.max-pages") + open(player, player.uniqueId, returnTo) + } + + StorageManager.Purchase.UNAVAILABLE -> StorageRender.refuse(player, "storage.error.unavailable") + } + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/storage/StoragePageSettingsGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/storage/StoragePageSettingsGUI.kt new file mode 100644 index 0000000..c23ddaa --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/storage/StoragePageSettingsGUI.kt @@ -0,0 +1,157 @@ +package net.trilleo.mc.plugins.tritown.guis.storage + +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer +import net.trilleo.mc.plugins.tritown.commands.storage.StorageCommand +import net.trilleo.mc.plugins.tritown.enums.FillMode +import net.trilleo.mc.plugins.tritown.guis.admin.PanelRender +import net.trilleo.mc.plugins.tritown.guis.menu.MenuRender +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.storage.StorageManager +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.event.inventory.InventoryCloseEvent +import org.bukkit.inventory.Inventory +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * Naming a storage page and choosing what it is shown as. + * + * Only the page's name and icon change here, never what it holds, so this does + * not take the storage's lock: its owner can rename a page while an + * administrator is looking through it. + */ +class StoragePageSettingsGUI : PluginGUI( + id = ID, + titleKey = "gui.storage-settings.title", + rows = 6, + fillMode = FillMode.NONE, +) { + + private data class Target(val owner: UUID, val page: Int) + + private val targets = ConcurrentHashMap() + + override fun setup(player: Player, inventory: Inventory) { + val target = targets[player.uniqueId] ?: return + val storage = StorageManager.get(target.owner) ?: return + val page = storage.pageOrNull(target.page) + + GUIFrame.draw(inventory, BUTTONS + PREVIEW_SLOT + BACK_SLOT) + inventory.setItem(PREVIEW_SLOT, StorageRender.pageCard(player, page, target.page, current = false).also { item -> + item.editMeta { it.lore(null) } + }) + inventory.setItem( + SLOT_RENAME, + PanelRender.card(Material.NAME_TAG, player.tr("gui.storage-settings.rename"), listOf(player.tr("gui.storage-settings.rename-lore"))) + ) + inventory.setItem( + SLOT_ICON, + PanelRender.card(Material.ITEM_FRAME, player.tr("gui.storage-settings.icon"), listOf(player.tr("gui.storage-settings.icon-lore"))) + ) + inventory.setItem( + SLOT_RESET, + PanelRender.card(Material.BARRIER, player.tr("gui.storage-settings.reset"), listOf(player.tr("gui.storage-settings.reset-lore"))) + ) + inventory.setItem(BACK_SLOT, PanelRender.card(Material.ARROW, player.tr("gui.storage-settings.back"), listOf(player.tr("gui.storage-settings.back-lore")))) + } + + override fun onClick(event: InventoryClickEvent) { + event.isCancelled = true + val player = event.whoClicked as? Player ?: return + val target = targets[player.uniqueId] ?: return + if (!mayEdit(player, target)) return + val storage = StorageManager.get(target.owner) ?: return + + if (event.clickedInventory === player.inventory) { + val clicked = event.currentItem ?: return + if (clicked.type.isAir) return + storage.page(target.page).icon = clicked.type.name + StorageManager.save(storage) + MenuRender.click(player) + GUIManager.refresh(player) + return + } + if (event.clickedInventory !== event.view.topInventory) return + + when (event.rawSlot) { + SLOT_RENAME -> MenuRender.later(player) { rename(player, target) } + SLOT_ICON -> player.sendPrefixed(player.tr("gui.storage-settings.icon-hint")) + SLOT_RESET -> { + storage.pageOrNull(target.page)?.let { page -> + page.name = null + page.icon = null + StorageManager.save(storage) + } + MenuRender.click(player) + GUIManager.refresh(player) + } + + BACK_SLOT -> MenuRender.later(player) { backToPage(player, target) } + } + } + + override fun onClose(event: InventoryCloseEvent) { + val target = targets.remove(event.player.uniqueId) ?: return + StorageManager.unloadIfIdle(target.owner) + } + + /** Asks for the page's new name in chat, then comes back here. */ + private fun rename(player: Player, target: Target) { + player.closeInventory() + + ChatPrompt.ask(player, player.tr("gui.storage-settings.rename-prompt", "amount" to MAX_NAME)) { input -> + val plain = PlainTextComponentSerializer.plainText().serialize(ComponentUtil.parse(input)).trim() + val storage = StorageManager.get(target.owner) + when { + storage == null || !mayEdit(player, target) -> Unit + plain.isEmpty() || plain.length > MAX_NAME -> + StorageRender.refuse(player, "storage.error.bad-name", "amount" to MAX_NAME) + + else -> { + storage.page(target.page).name = plain + StorageManager.save(storage) + player.sendPrefixed(player.tr("storage.renamed", "name" to ComponentUtil.escape(plain))) + } + } + show(player, target.owner, target.page) + } + } + + private fun backToPage(player: Player, target: Target) { + targets.remove(player.uniqueId) + StorageGUI.open(player, target.owner, target.page) + } + + private fun mayEdit(player: Player, target: Target): Boolean = + target.owner == player.uniqueId || player.hasPermission(StorageCommand.ADMIN_PERMISSION) + + companion object { + const val ID = "storage-settings" + + /** The longest name a page may have, in characters. */ + private const val MAX_NAME = 32 + + private const val PREVIEW_SLOT = 13 + private const val SLOT_RENAME = 29 + private const val SLOT_ICON = 31 + private const val SLOT_RESET = 33 + private const val BACK_SLOT = 49 + + private val BUTTONS = listOf(SLOT_RENAME, SLOT_ICON, SLOT_RESET) + + /** Opens the settings of page [page] of [owner]'s storage for [viewer]. */ + fun show(viewer: Player, owner: UUID, page: Int): Boolean { + val gui = GUIManager.getGUI(ID) as? StoragePageSettingsGUI ?: return false + gui.targets[viewer.uniqueId] = Target(owner, page) + return GUIManager.open(viewer, ID) + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/storage/StoragePagesGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/storage/StoragePagesGUI.kt new file mode 100644 index 0000000..2f4d5bc --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/storage/StoragePagesGUI.kt @@ -0,0 +1,110 @@ +package net.trilleo.mc.plugins.tritown.guis.storage + +import net.kyori.adventure.text.Component +import net.trilleo.mc.plugins.tritown.enums.FillMode +import net.trilleo.mc.plugins.tritown.enums.PagedLayout +import net.trilleo.mc.plugins.tritown.guis.admin.PanelRender +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.storage.StorageManager +import net.trilleo.mc.plugins.tritown.utils.ComponentUtil +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.event.inventory.InventoryCloseEvent +import org.bukkit.inventory.ItemStack +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * Every page of a storage at once: what each is called, how full it is and what + * it mostly holds, so a player can go straight to the page they want. The offer + * of another page sits at the end of the list, where a new page would appear. + */ +class StoragePagesGUI : PagedPluginGUI( + id = ID, + titleKey = "gui.storage-pages.title", + rows = 6, + fillMode = FillMode.NONE, + layout = PagedLayout.FRAMED, +) { + + /** Whose storage [viewer] is looking over, which page they came from, and whether they may change it. */ + private data class Context(val owner: UUID, val current: Int, val readOnly: Boolean) + + private val contexts = ConcurrentHashMap() + + override fun title(player: Player): Component { + val context = contexts[player.uniqueId] ?: return super.title(player) + if (context.owner == player.uniqueId) return super.title(player) + return ComponentUtil.parse( + player.tr("gui.storage-pages.title-inspect", "owner" to StorageRender.ownerName(context.owner)) + ) + } + + override fun getItems(player: Player): List { + val context = contexts[player.uniqueId] ?: return emptyList() + val storage = StorageManager.get(context.owner) ?: return emptyList() + + val pages = (0 until StorageManager.pageCount(storage)).map { index -> + StorageRender.pageCard(player, storage.pageOrNull(index), index, current = index == context.current) + } + val buy = if (canBuy(player, context)) StorageRender.buyCard(player, storage) else null + return pages + listOfNotNull(buy) + } + + override fun onContentClick(event: InventoryClickEvent, page: Int) { + event.isCancelled = true + val player = event.whoClicked as? Player ?: return + val context = contexts[player.uniqueId] ?: return + val storage = StorageManager.get(context.owner) ?: return + + val index = contentIndex(event, page) ?: return + val pages = StorageManager.pageCount(storage) + when { + index < pages -> MenuRender.later(player) { + StorageGUI.open(player, context.owner, index, context.readOnly) + } + + index == pages && canBuy(player, context) && StorageManager.nextPageCost(storage) != null -> + MenuRender.later(player) { StorageGUI.offerPage(player, context.current) } + } + } + + override fun navButtons(player: Player): Map = mapOf( + MenuRender.BACK_OFFSET to PanelRender.card( + Material.ARROW, + player.tr("gui.storage-pages.back"), + listOf(player.tr("gui.storage-pages.back-lore")), + ), + ) + + override fun onNavClick(event: InventoryClickEvent, offset: Int) { + val player = event.whoClicked as? Player ?: return + val context = contexts[player.uniqueId] ?: return + if (offset == MenuRender.BACK_OFFSET) { + MenuRender.later(player) { StorageGUI.open(player, context.owner, context.current, context.readOnly) } + } + } + + override fun onClose(event: InventoryCloseEvent) { + super.onClose(event) + // An offline player's storage was loaded only to be shown here. + contexts.remove(event.player.uniqueId)?.let { StorageManager.unloadIfIdle(it.owner) } + } + + private fun canBuy(player: Player, context: Context): Boolean = context.owner == player.uniqueId && !context.readOnly + + companion object { + const val ID = "storage-pages" + + /** Opens the overview of [owner]'s storage for [viewer], who came from page [current]. */ + fun show(viewer: Player, owner: UUID, current: Int, readOnly: Boolean): Boolean { + val gui = GUIManager.getGUI(ID) as? StoragePagesGUI ?: return false + gui.contexts[viewer.uniqueId] = Context(owner, current, readOnly) + return GUIManager.open(viewer, ID) + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/storage/StorageRender.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/storage/StorageRender.kt new file mode 100644 index 0000000..668af22 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/storage/StorageRender.kt @@ -0,0 +1,107 @@ +package net.trilleo.mc.plugins.tritown.guis.storage + +import net.kyori.adventure.key.Key +import net.kyori.adventure.sound.Sound +import net.trilleo.mc.plugins.tritown.economy.Money +import net.trilleo.mc.plugins.tritown.guis.admin.PanelRender +import net.trilleo.mc.plugins.tritown.storage.PlayerStorage +import net.trilleo.mc.plugins.tritown.storage.StorageManager +import net.trilleo.mc.plugins.tritown.storage.StoragePage +import net.trilleo.mc.plugins.tritown.utils.ComponentUtil +import net.trilleo.mc.plugins.tritown.utils.EconomyUtil +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Bukkit +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import java.util.* + +/** The pieces the storage menus are drawn with. */ +object StorageRender { + + private val refuse = Sound.sound(Key.key("minecraft:block.note_block.bass"), Sound.Source.UI, 1f, 0.8f) + + /** What a page is shown as when its owner has not picked anything. */ + val DEFAULT_ICON: Material = Material.CHEST + + /** [money] written out with the server's currency, escaped for embedding in MiniMessage. */ + fun money(money: Money): String { + val amount = StorageManager.toDouble(money) + return if (EconomyUtil.isAvailable) ComponentUtil.escape(EconomyUtil.format(amount)) else amount.toString() + } + + /** [owner]'s name, escaped, or a short form of their id when the server has never seen them. */ + fun ownerName(owner: UUID): String = + ComponentUtil.escape(Bukkit.getOfflinePlayer(owner).name ?: owner.toString().substringBefore('-')) + + /** The name [page] is shown by: the one its owner gave it, or its number. */ + fun pageName(viewer: Player, page: StoragePage?, index: Int): String = + page?.name?.let(ComponentUtil::escape) ?: viewer.tr("gui.storage.page-default", "page" to index + 1) + + /** The material [page] is shown as. */ + fun icon(page: StoragePage?): Material = + page?.icon?.let(Material::matchMaterial)?.takeIf { it.isItem && !it.isAir } ?: DEFAULT_ICON + + /** An item's name in the viewer's own language, whatever language the server runs in. */ + fun itemName(material: Material): String = "" + + /** + * [page] as a card for the overview: its name, how full it is, and what + * there is most of. + */ + fun pageCard(viewer: Player, page: StoragePage?, index: Int, current: Boolean): ItemStack { + val used = page?.used ?: 0 + val lines = mutableListOf( + viewer.tr("gui.storage.overview-used", "amount" to used, "total" to StoragePage.SIZE), + ) + + val top = page?.slots?.filterNotNull() + ?.groupBy { it.type } + ?.mapValues { (_, stacks) -> stacks.sumOf { it.amount } } + ?.entries?.sortedByDescending { it.value } + ?.take(PREVIEW_SIZE) + .orEmpty() + if (top.isNotEmpty()) { + lines += "" + top.forEach { (material, amount) -> + lines += viewer.tr("gui.storage.overview-item", "amount" to amount, "name" to itemName(material)) + } + } + + lines += "" + lines += viewer.tr(if (current) "gui.storage.overview-current" else "gui.storage.overview-open") + + return PanelRender.card(icon(page), viewer.tr("gui.storage.overview-name", "name" to pageName(viewer, page, index)), lines) + .also { item -> if (current) item.editMeta { it.setEnchantmentGlintOverride(true) } } + } + + /** The offer of one more page, or `null` when [storage] cannot grow. */ + fun buyCard(viewer: Player, storage: PlayerStorage): ItemStack? { + val cost = StorageManager.nextPageCost(storage) ?: return null + val page = StorageManager.owned(storage) + 1 + return PanelRender.card( + Material.WRITABLE_BOOK, + viewer.tr("gui.storage.buy", "page" to page), + listOf( + viewer.tr("gui.storage.buy-cost", "amount" to money(cost)), + viewer.tr("gui.storage.buy-balance", "amount" to balance(viewer)), + "", + viewer.tr("gui.storage.buy-click"), + ), + ) + } + + /** [player]'s balance, written out, or a dash when there is no economy to ask. */ + fun balance(player: Player): String = + if (EconomyUtil.isAvailable) ComponentUtil.escape(EconomyUtil.format(EconomyUtil.balance(player))) + else player.tr("common.none") + + /** Tells [player] why something did not happen, with a sound so a refused click is never silent. */ + fun refuse(player: Player, key: String, vararg args: Pair) { + player.playSound(refuse) + player.sendPrefixed(player.tr("common.error", "message" to player.tr(key, *args))) + } + + private const val PREVIEW_SIZE = 3 +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/storage/ContainerLockListener.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/storage/ContainerLockListener.kt new file mode 100644 index 0000000..ba9778e --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/storage/ContainerLockListener.kt @@ -0,0 +1,212 @@ +package net.trilleo.mc.plugins.tritown.listeners.storage + +import net.trilleo.mc.plugins.tritown.commands.storage.StorageCommand +import net.trilleo.mc.plugins.tritown.config.StorageSettings +import net.trilleo.mc.plugins.tritown.storage.StorageManager +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.Tag +import org.bukkit.block.Barrel +import org.bukkit.block.Chest +import org.bukkit.block.DoubleChest +import org.bukkit.block.ShulkerBox +import org.bukkit.entity.ChestBoat +import org.bukkit.entity.Entity +import org.bukkit.entity.Player +import org.bukkit.entity.minecart.HopperMinecart +import org.bukkit.entity.minecart.StorageMinecart +import org.bukkit.event.EventHandler +import org.bukkit.event.Listener +import org.bukkit.event.block.BlockDispenseEvent +import org.bukkit.event.block.BlockPlaceEvent +import org.bukkit.event.entity.EntityPlaceEvent +import org.bukkit.event.inventory.* +import org.bukkit.event.player.PlayerQuitEvent +import org.bukkit.inventory.Inventory +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * Retires the vanilla containers the storage replaces. + * + * None of them can be placed any more, and the ones already in the world are + * withdraw-only: a player can empty a chest into their storage, but not fill + * one, and neither can a hopper. Crafting is left alone, since a chest goes into + * hoppers and minecarts that have nothing to do with storing things. + * + * A container is recognised by what holds its inventory, never by the + * inventory's type. TriTown's own menus and other plugins' are chest-shaped too, + * and they have no block or entity behind them. + */ +class ContainerLockListener : Listener { + + /** When each player was last told a container is withdraw-only, so a busy click is not a busy chat. */ + private val lastHint = ConcurrentHashMap() + + // ── Placing ───────────────────────────────────────────────────────── + + @EventHandler(ignoreCancelled = true) + fun onPlace(event: BlockPlaceEvent) { + if (!isLockedMaterial(event.blockPlaced.type) || exempt(event.player)) return + event.isCancelled = true + refusePlacing(event.player) + } + + @EventHandler(ignoreCancelled = true) + fun onEntityPlace(event: EntityPlaceEvent) { + if (!isLockedEntity(event.entity)) return + val player = event.player + if (player != null && exempt(player)) return + event.isCancelled = true + player?.let(::refusePlacing) + } + + /** A dispenser places shulker boxes, minecarts and boats just as a player would. */ + @EventHandler(ignoreCancelled = true) + fun onDispense(event: BlockDispenseEvent) { + if (!lockActive()) return + val type = event.item.type + if (isLockedMaterial(type) || isLockedVehicle(type)) event.isCancelled = true + } + + // ── Filling ───────────────────────────────────────────────────────── + + @EventHandler(ignoreCancelled = true) + fun onClick(event: InventoryClickEvent) { + val player = event.whoClicked as? Player ?: return + val top = event.view.topInventory + if (!isLocked(top) || exempt(player)) return + + val inTop = event.rawSlot in 0 until top.size + val fills = when (event.action) { + InventoryAction.MOVE_TO_OTHER_INVENTORY -> !inTop + InventoryAction.HOTBAR_SWAP, InventoryAction.HOTBAR_MOVE_AND_READD -> inTop && swapsSomethingIn(player, event) + in TAKING -> false + else -> inTop + } + if (!fills) return + + event.isCancelled = true + hint(player) + } + + @EventHandler(ignoreCancelled = true) + fun onDrag(event: InventoryDragEvent) { + val player = event.whoClicked as? Player ?: return + val top = event.view.topInventory + if (!isLocked(top) || exempt(player)) return + if (event.rawSlots.none { it < top.size }) return + + event.isCancelled = true + hint(player) + } + + /** Hoppers and droppers may still pull from a container; they may not push into one. */ + @EventHandler(ignoreCancelled = true) + fun onHopper(event: InventoryMoveItemEvent) { + if (isLocked(event.destination)) event.isCancelled = true + } + + @EventHandler + fun onQuit(event: PlayerQuitEvent) { + lastHint.remove(event.player.uniqueId) + } + + // ── What is locked ────────────────────────────────────────────────── + + private fun lockActive(): Boolean = StorageManager.isAvailable + + private fun lock(): StorageSettings.ContainerLock? = + if (lockActive()) StorageSettings.snapshot.lock else null + + private fun exempt(player: Player): Boolean = player.hasPermission(StorageCommand.BYPASS_PERMISSION) + + private fun isLockedMaterial(type: Material): Boolean { + val lock = lock() ?: return false + return when { + Tag.SHULKER_BOXES.isTagged(type) -> lock.shulkerBoxes + type == Material.ENDER_CHEST -> lock.enderChest + type == Material.CHEST || type == Material.TRAPPED_CHEST || type == Material.BARREL -> lock.chests + else -> false + } + } + + /** The minecart and boat items that carry a container. */ + private fun isLockedVehicle(type: Material): Boolean { + val lock = lock() ?: return false + if (!lock.chests) return false + return type == Material.CHEST_MINECART || type == Material.HOPPER_MINECART || + type.name.endsWith("_CHEST_BOAT") || type.name.endsWith("_CHEST_RAFT") + } + + private fun isLockedEntity(entity: Entity): Boolean { + val lock = lock() ?: return false + return lock.chests && (entity is StorageMinecart || entity is HopperMinecart || entity is ChestBoat) + } + + /** + * Whether [inventory] belongs to one of the retired containers. + * + * A hopper minecart can no longer be placed, but one already running is + * left to work: it is part of a machine, and locking it would stop it + * pulling items out of the very chests players are meant to empty. + */ + private fun isLocked(inventory: Inventory): Boolean { + val lock = lock() ?: return false + if (inventory.type == InventoryType.ENDER_CHEST) return lock.enderChest + + return when (inventory.getHolder(false)) { + is ShulkerBox -> lock.shulkerBoxes + is Chest, is DoubleChest, is Barrel, is StorageMinecart, is ChestBoat -> lock.chests + else -> false + } + } + + /** A number key or the off-hand key swaps an item in only when the key's slot holds one. */ + private fun swapsSomethingIn(player: Player, event: InventoryClickEvent): Boolean { + val incoming = if (event.click == ClickType.SWAP_OFFHAND) { + player.inventory.itemInOffHand + } else { + player.inventory.getItem(event.hotbarButton) + } + return incoming != null && !incoming.type.isAir + } + + // ── Telling the player ────────────────────────────────────────────── + + private fun refusePlacing(player: Player) { + player.sendPrefixed(player.tr("common.error", "message" to player.tr("storage.lock.no-place"))) + } + + private fun hint(player: Player) { + val now = System.currentTimeMillis() + val last = lastHint[player.uniqueId] + if (last != null && now - last < HINT_COOLDOWN_MS) return + lastHint[player.uniqueId] = now + player.sendActionBar(ComponentUtil.parse(player.tr("storage.lock.withdraw-only"))) + } + + private companion object { + const val HINT_COOLDOWN_MS = 2_000L + + /** What only ever moves items out of the container. */ + val TAKING = setOf( + InventoryAction.NOTHING, + InventoryAction.PICKUP_ALL, + InventoryAction.PICKUP_SOME, + InventoryAction.PICKUP_HALF, + InventoryAction.PICKUP_ONE, + InventoryAction.DROP_ALL_SLOT, + InventoryAction.DROP_ONE_SLOT, + InventoryAction.DROP_ALL_CURSOR, + InventoryAction.DROP_ONE_CURSOR, + InventoryAction.COLLECT_TO_CURSOR, + InventoryAction.CLONE_STACK, + InventoryAction.PICKUP_FROM_BUNDLE, + InventoryAction.PICKUP_ALL_INTO_BUNDLE, + InventoryAction.PICKUP_SOME_INTO_BUNDLE, + ) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/storage/StorageSessionListener.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/storage/StorageSessionListener.kt new file mode 100644 index 0000000..2670590 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/storage/StorageSessionListener.kt @@ -0,0 +1,25 @@ +package net.trilleo.mc.plugins.tritown.listeners.storage + +import net.trilleo.mc.plugins.tritown.guis.storage.StorageGUI +import net.trilleo.mc.plugins.tritown.storage.StorageManager +import org.bukkit.event.EventHandler +import org.bukkit.event.EventPriority +import org.bukkit.event.Listener +import org.bukkit.event.player.PlayerQuitEvent + +/** + * Writes a player's storage when they leave. + * + * An open storage is closed first, while the page on screen can still be + * copied back, and only then is the storage written and let go of — unless an + * administrator is still looking through it, in which case it goes when they do. + */ +class StorageSessionListener : Listener { + + @EventHandler(priority = EventPriority.LOWEST) + fun onQuit(event: PlayerQuitEvent) { + val player = event.player + StorageGUI.close(player) + StorageManager.unloadIfIdle(player.uniqueId, leaving = true) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/PlayerStorage.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/PlayerStorage.kt new file mode 100644 index 0000000..6a06213 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/PlayerStorage.kt @@ -0,0 +1,68 @@ +package net.trilleo.mc.plugins.tritown.storage + +import org.bukkit.inventory.ItemStack +import java.util.* + +/** + * One page of a storage: the five rows above the storage menu's buttons. + * + * @param name a name the owner gave it, as they typed it; escaped whenever it is shown + * @param icon the name of the material it is shown as in the overview + */ +class StoragePage(var name: String? = null, var icon: String? = null) { + + val slots: Array = arrayOfNulls(SIZE) + + /** How many slots hold something. */ + val used: Int get() = slots.count { it != null } + + val isEmpty: Boolean get() = slots.all { it == null } + + companion object { + /** Slots on a page: a large chest less the row of buttons. */ + const val SIZE = 45 + } +} + +/** + * Everything one player keeps in their storage. + * + * Only [StorageManager] creates or changes one. The pages list only ever holds + * pages that have been opened or filled, so a storage that owns twenty pages + * but has used two keeps two in memory and on disk. + * + * @param purchased how many pages the owner has paid for, or been given, beyond the free ones + * @param unreadable items a load could not decode, carried along untouched so a save never drops them + */ +class PlayerStorage( + val owner: UUID, + @Volatile var purchased: Int, + pages: List, + val unreadable: List, +) { + + private val pages: MutableList = pages.toMutableList() + + /** Pages that exist, which may be fewer than the pages owned. */ + val existing: List get() = pages + + /** Whether anything has changed since this storage was last written. */ + @Volatile + var dirty: Boolean = false + + /** The page at [index], created blank when it has not been used yet. */ + fun page(index: Int): StoragePage { + require(index >= 0) { "Pages are counted from zero" } + while (pages.size <= index) pages += StoragePage() + return pages[index] + } + + /** The page at [index] when it exists, without creating it. */ + fun pageOrNull(index: Int): StoragePage? = pages.getOrNull(index) + + /** One past the last page that holds anything, so pages with items are never hidden. */ + val filledPages: Int get() = pages.indexOfLast { !it.isEmpty } + 1 + + /** How many slots hold something, across every page. */ + val usedSlots: Int get() = pages.sumOf { it.used } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/SlotFill.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/SlotFill.kt new file mode 100644 index 0000000..a28aaed --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/SlotFill.kt @@ -0,0 +1,105 @@ +package net.trilleo.mc.plugins.tritown.storage + +/** + * Putting stacks into rows of slots the way a chest would, and tidying them. + * + * Written against [Rules] rather than `ItemStack`, so the arithmetic — which + * stacks merge, where the rest goes, what comes back — can be tested without a + * server. [StorageItems] supplies the rules for real items. + */ +object SlotFill { + + /** How the stacks being moved behave. */ + interface Rules { + /** Whether [a] and [b] are the same item and may share a slot. */ + fun similar(a: T, b: T): Boolean + + /** The most of [stack] one slot holds. */ + fun maxStack(stack: T): Int + + fun amount(stack: T): Int + + /** A copy of [stack] holding [amount]. */ + fun withAmount(stack: T, amount: Int): T + } + + /** + * Puts [stack] into [pages], in order: first on top of the matching stacks + * that have room, then into empty slots. + * + * Merging goes through every page before an empty slot is used, so a deposit + * tops up what is already stored rather than starting a new stack beside it. + * + * @return what did not fit, or `null` when all of it did + */ + fun insert(pages: List>, stack: T, rules: Rules): T? { + var left = rules.amount(stack) + val max = rules.maxStack(stack).coerceAtLeast(1) + + for (slots in pages) { + for (index in slots.indices) { + if (left <= 0) return null + val held = slots[index] ?: continue + if (!rules.similar(held, stack)) continue + + val room = max - rules.amount(held) + if (room <= 0) continue + val moved = minOf(room, left) + slots[index] = rules.withAmount(held, rules.amount(held) + moved) + left -= moved + } + } + + for (slots in pages) { + for (index in slots.indices) { + if (left <= 0) return null + if (slots[index] != null) continue + + val moved = minOf(max, left) + slots[index] = rules.withAmount(stack, moved) + left -= moved + } + } + + return if (left > 0) rules.withAmount(stack, left) else null + } + + /** + * Merges the stacks in [slots] and orders them by [order], packed to the front. + * + * Nothing is lost: every item that went in comes back out, only in fewer + * stacks where they could be joined. + * + * @return whether the page was sorted; it is left untouched when it could not be + */ + fun sort(slots: Array, rules: Rules, order: Comparator): Boolean { + val merged = mutableListOf() + for (stack in slots.filterNotNull().sortedWith(order)) { + var left = rules.amount(stack) + val max = rules.maxStack(stack).coerceAtLeast(1) + + for (index in merged.indices) { + if (left <= 0) break + val held = merged[index] + if (!rules.similar(held, stack)) continue + val moved = minOf(max - rules.amount(held), left) + if (moved <= 0) continue + merged[index] = rules.withAmount(held, rules.amount(held) + moved) + left -= moved + } + + while (left > 0) { + val size = minOf(max, left) + merged += rules.withAmount(stack, size) + left -= size + } + } + + val ordered = merged.sortedWith(order) + // Only an oversized stack could split into more than there are slots, and + // then the page is left as it was rather than losing the overflow. + if (ordered.size > slots.size) return false + for (index in slots.indices) slots[index] = ordered.getOrNull(index) + return true + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/StorageItems.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/StorageItems.kt new file mode 100644 index 0000000..ccd15c3 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/StorageItems.kt @@ -0,0 +1,78 @@ +package net.trilleo.mc.plugins.tritown.storage + +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer +import net.trilleo.mc.plugins.tritown.menu.MenuItem +import org.bukkit.Tag +import org.bukkit.block.ShulkerBox +import org.bukkit.inventory.ItemStack +import org.bukkit.inventory.meta.BlockStateMeta +import org.bukkit.inventory.meta.BundleMeta + +/** + * What a storage will hold, and how its items are merged, ordered and unpacked. + */ +object StorageItems { + + /** [SlotFill]'s rules for real items. */ + val rules = object : SlotFill.Rules { + override fun similar(a: ItemStack, b: ItemStack): Boolean = a.isSimilar(b) + override fun maxStack(stack: ItemStack): Int = stack.maxStackSize + override fun amount(stack: ItemStack): Int = stack.amount + override fun withAmount(stack: ItemStack, amount: Int): ItemStack = stack.clone().apply { this.amount = amount } + } + + /** By material, then by name, so like sits beside like and a renamed stack keeps its place. */ + val order: Comparator = compareBy { it.type.name } + .thenBy { stack -> stack.itemMeta?.displayName()?.let(PlainTextComponentSerializer.plainText()::serialize) ?: "" } + .thenByDescending { it.amount } + + /** + * Whether [item] may be put in a storage. + * + * A shulker box or bundle with anything inside is refused, because a page + * of full boxes would hold many pages' worth and nobody would buy one; the + * Unpack button empties them in instead. The menu item never leaves its slot. + */ + fun accepts(item: ItemStack?): Boolean { + if (item == null || item.type.isAir) return true + if (MenuItem.isMenuItem(item)) return false + return contents(item).isEmpty() + } + + /** Whether [item] is a container Unpack can empty, whatever it holds. */ + fun isContainer(item: ItemStack?): Boolean = + item != null && (Tag.SHULKER_BOXES.isTagged(item.type) || item.itemMeta is BundleMeta) + + /** What [item] carries inside it, when it is a shulker box or a bundle. */ + fun contents(item: ItemStack): List { + val meta = item.itemMeta ?: return emptyList() + if (meta is BundleMeta) return meta.items.filter { !it.type.isAir } + if (meta is BlockStateMeta && Tag.SHULKER_BOXES.isTagged(item.type) && meta.hasBlockState()) { + val box = meta.blockState as? ShulkerBox ?: return emptyList() + return box.inventory.contents.filterNotNull().filter { !it.type.isAir } + } + return emptyList() + } + + /** + * Everything [item] carries, with any container inside it emptied out too, + * so a bundle packed in a shulker box cannot ride into the storage full. + */ + fun unpacked(item: ItemStack): List = contents(item).flatMap { inner -> + if (contents(inner).isEmpty()) listOf(inner) else listOf(emptied(inner)) + unpacked(inner) + } + + /** [item] with nothing inside it. */ + fun emptied(item: ItemStack): ItemStack { + val copy = item.clone() + copy.editMeta { meta -> + if (meta is BundleMeta) meta.setItems(null) + if (meta is BlockStateMeta && meta.hasBlockState()) { + val box = meta.blockState as? ShulkerBox ?: return@editMeta + box.inventory.clear() + meta.blockState = box + } + } + return copy + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/StorageManager.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/StorageManager.kt new file mode 100644 index 0000000..e80e324 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/StorageManager.kt @@ -0,0 +1,359 @@ +package net.trilleo.mc.plugins.tritown.storage + +import net.trilleo.mc.plugins.tritown.Main +import net.trilleo.mc.plugins.tritown.config.StorageSettings +import net.trilleo.mc.plugins.tritown.economy.CurrencyRegistry +import net.trilleo.mc.plugins.tritown.economy.EconomyContext +import net.trilleo.mc.plugins.tritown.economy.Money +import net.trilleo.mc.plugins.tritown.economy.TransactionReason +import net.trilleo.mc.plugins.tritown.shops.ItemCodec +import net.trilleo.mc.plugins.tritown.storage.storage.* +import net.trilleo.mc.plugins.tritown.utils.EconomyUtil +import org.bukkit.Bukkit +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import java.util.* +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.logging.Logger + +/** + * Every player's storage, and the only thing that reads or writes one. + * + * A storage is loaded the first time it is opened and kept while its owner is + * online or anyone is looking at it. Everything that changes one runs on the + * server thread — items can only be encoded there — and the finished text is + * handed to a single writer thread, so two saves of the same storage can never + * land out of order. + * + * One person at a time may change a storage. Its owner normally; an + * administrator inspecting it otherwise. Anyone else who opens it while it is + * being changed gets a read-only view, or is turned away if they cannot inspect. + */ +object StorageManager { + + /** What a viewer may do with the storage they opened. */ + enum class Access { EDIT, READ } + + /** How buying a page went. */ + enum class Purchase { BOUGHT, AT_MAX, CANNOT_AFFORD, UNAVAILABLE } + + private val loaded = ConcurrentHashMap() + private val editors = ConcurrentHashMap() + private val viewers = ConcurrentHashMap>() + + private lateinit var store: StorageStore + private lateinit var logger: Logger + private var writer: ExecutorService? = null + + @Volatile + var isReady: Boolean = false + private set + + /** Whether players can use their storage right now. */ + val isAvailable: Boolean + get() = isReady && StorageSettings.isLoaded && StorageSettings.snapshot.enabled + + fun start(storageStore: StorageStore, pluginLogger: Logger) { + store = storageStore + logger = pluginLogger + writer = Executors.newSingleThreadExecutor { runnable -> Thread(runnable, "TriTown-Storage").apply { isDaemon = true } } + isReady = true + } + + /** + * Writes every loaded storage and waits for the writer to finish. + * + * Called after every open storage menu has been closed, so what is written + * is what the players last saw. + */ + fun shutdown() { + if (!isReady) return + isReady = false + + val pending = loaded.values.map(::toStored) + writer?.let { executor -> + executor.shutdown() + executor.awaitTermination(10, TimeUnit.SECONDS) + } + writer = null + pending.forEach(store::save) + + loaded.clear() + editors.clear() + viewers.clear() + } + + // ── Loading ───────────────────────────────────────────────────────── + + /** + * [owner]'s storage, loading it when it is not in memory. + * + * @return `null` when the feature is off or the storage's file cannot be read + */ + fun get(owner: UUID): PlayerStorage? { + if (!isReady) return null + loaded[owner]?.let { return it } + + val stored = try { + store.load(owner) + } catch (e: StorageStoreException) { + logger.severe("The storage of $owner is unavailable: ${e.message}") + return null + } + + val storage = stored?.let { fromStored(owner, it) } ?: PlayerStorage(owner, 0, emptyList(), emptyList()) + return loaded.putIfAbsent(owner, storage) ?: storage + } + + /** [owner]'s storage when it is already in memory, without loading it. */ + fun cached(owner: UUID): PlayerStorage? = loaded[owner] + + /** Every storage in memory right now. */ + fun cachedAll(): Collection = loaded.values + + /** + * Writes [owner]'s storage and forgets it, once nobody needs it in memory. + * + * @param leaving whether [owner] is on their way out, and so counts as offline + */ + fun unloadIfIdle(owner: UUID, leaving: Boolean = false) { + if (!viewers[owner].isNullOrEmpty()) return + if (!leaving && Bukkit.getPlayer(owner) != null) return + + val storage = loaded.remove(owner) ?: return + if (storage.dirty) save(storage) + } + + // ── Who is looking ────────────────────────────────────────────────── + + /** + * Lets [viewer] into [owner]'s storage. + * + * @param inspect whether [viewer] may inspect other players' storage, which + * earns a read-only view of one that is being changed instead of a refusal + * @param readOnly whether [viewer] only wants to look + * @return what [viewer] may do, or `null` when someone else is changing it + * and [viewer] may not look over their shoulder + */ + fun claim(owner: UUID, viewer: UUID, inspect: Boolean, readOnly: Boolean = false): Access? { + val access = when { + readOnly -> Access.READ + editors.putIfAbsent(owner, viewer).let { it == null || it == viewer } -> Access.EDIT + inspect -> Access.READ + else -> return null + } + viewers.computeIfAbsent(owner) { ConcurrentHashMap.newKeySet() }.add(viewer) + return access + } + + /** Lets go of [owner]'s storage for [viewer], and unloads it when that was the last reason to keep it. */ + fun release(owner: UUID, viewer: UUID) { + editors.remove(owner, viewer) + viewers[owner]?.let { set -> + set.remove(viewer) + if (set.isEmpty()) viewers.remove(owner, set) + } + unloadIfIdle(owner) + } + + /** Who is changing [owner]'s storage, if anyone. */ + fun editorOf(owner: UUID): UUID? = editors[owner] + + // ── Pages ─────────────────────────────────────────────────────────── + + /** The pages [storage] has paid for or was given, capped at the configured maximum. */ + fun owned(storage: PlayerStorage): Int { + val settings = StorageSettings.snapshot + return (settings.freePages + storage.purchased).coerceAtMost(settings.maxPages) + } + + /** + * The pages [storage] can open: those it owns, and any beyond them that + * still hold items after an owner lowered the allowance, so nothing stored + * is ever hidden. + */ + fun pageCount(storage: PlayerStorage): Int = maxOf(owned(storage), storage.filledPages) + + /** What one more page costs [storage], or `null` when it is at the maximum. */ + fun nextPageCost(storage: PlayerStorage): Money? { + val settings = StorageSettings.snapshot + return StoragePricing.next( + purchased = storage.purchased, + owned = owned(storage), + maxPages = settings.maxPages, + base = settings.priceBase, + multiplier = settings.priceMultiplier, + scale = scale(), + ) + } + + /** + * Sells [player] one more page. + * + * Charged first, and the page only granted once the money has gone, so a + * refusal anywhere leaves the storage as it was. + */ + fun buyPage(player: Player): Purchase { + val storage = get(player.uniqueId) ?: return Purchase.UNAVAILABLE + val cost = nextPageCost(storage) ?: return Purchase.AT_MAX + if (!EconomyUtil.isAvailable) return Purchase.UNAVAILABLE + + val page = owned(storage) + 1 + val charged = EconomyUtil.withdraw( + player, + toDouble(cost), + EconomyContext.SOURCE_STORAGE, + TransactionReason.of(TransactionReason.STORAGE_PAGE, "page" to page), + ) + if (!charged) return Purchase.CANNOT_AFFORD + + storage.purchased++ + save(storage) + return Purchase.BOUGHT + } + + /** Sets how many pages [storage] owns in total, for free. Never below the free pages. */ + fun setOwned(storage: PlayerStorage, pages: Int) { + val settings = StorageSettings.snapshot + storage.purchased = (pages.coerceIn(1, settings.maxPages) - settings.freePages).coerceAtLeast(0) + save(storage) + } + + /** [money] as the `Double` Vault speaks in. */ + fun toDouble(money: Money): Double = + if (CurrencyRegistry.isLoaded) CurrencyRegistry.primary.toDouble(money) else money.toDouble(DEFAULT_SCALE) + + private fun scale(): Int = if (CurrencyRegistry.isLoaded) CurrencyRegistry.primary.fractionalDigits else DEFAULT_SCALE + + // ── Items ─────────────────────────────────────────────────────────── + + /** + * Puts [stack] into [storage], trying [first] before the other pages it can open. + * + * @return what did not fit, or `null` when all of it did + */ + fun deposit(storage: PlayerStorage, first: Int, stack: ItemStack): ItemStack? { + val order = listOf(first) + (0 until pageCount(storage)).filter { it != first } + val leftover = SlotFill.insert(order.map { storage.page(it).slots }, stack, StorageItems.rules) + if (leftover == null || leftover.amount != stack.amount) markDirty(storage) + return leftover + } + + /** + * Whether [items] would all fit in [storage] together, tried on a copy so + * nothing is moved when they would not. + */ + fun fits(storage: PlayerStorage, items: List): Boolean { + val copies = (0 until pageCount(storage)).map { index -> + storage.page(index).slots.map { it?.clone() }.toTypedArray() + } + return items.all { SlotFill.insert(copies, it, StorageItems.rules) == null } + } + + /** The materials anywhere in [storage], for depositing like with like. */ + fun materials(storage: PlayerStorage): Set = + storage.existing.flatMap { page -> page.slots.mapNotNull { it?.type } }.toSet() + + // ── Saving ────────────────────────────────────────────────────────── + + /** Records that [storage] changed, to be written by the next flush. */ + fun markDirty(storage: PlayerStorage) { + storage.dirty = true + } + + /** Writes [storage] now, off the server thread. */ + fun save(storage: PlayerStorage) { + if (!isReady) return + storage.dirty = false + val stored = toStored(storage) + val executor = writer + if (executor == null || executor.isShutdown) store.save(stored) else executor.execute { store.save(stored) } + } + + /** Writes every storage that changed since it was last written. */ + fun flushDirty() { + if (!isReady) return + loaded.values.filter { it.dirty }.forEach(::save) + } + + /** + * How much every storage on file holds, handed to [callback] on the server thread. + * + * Read on the writer thread, behind any save still waiting, and then + * corrected with what is in memory, which is always the newer of the two. + */ + fun summaries(callback: (List) -> Unit) { + val executor = writer ?: return + val live = loaded.values.associate { it.owner to summaryOf(it) } + + executor.execute { + val onFile = runCatching { store.summaries() }.getOrElse { + logger.warning("Could not read the storage summaries: ${it.message}") + emptyList() + } + val merged = (onFile.associateBy { it.owner } + live).values.toList() + Bukkit.getScheduler().runTask(Main.instance, Runnable { callback(merged) }) + } + } + + private fun summaryOf(storage: PlayerStorage) = StorageSummary( + owner = storage.owner, + purchased = storage.purchased, + pages = storage.existing.size, + usedSlots = storage.usedSlots, + ) + + // ── Conversion ────────────────────────────────────────────────────── + + private fun toStored(storage: PlayerStorage): StoredStorage { + val pages = storage.existing.map { page -> + StoredPage( + name = page.name, + icon = page.icon, + slots = page.slots.withIndex() + .filter { it.value != null } + .associate { (index, item) -> index.toString() to ItemCodec.encode(item!!) }, + ) + } + val trimmed = pages.dropLastWhile { it.name == null && it.icon == null && it.slots.isNullOrEmpty() } + + return StoredStorage( + owner = storage.owner.toString(), + purchased = storage.purchased, + pages = trimmed, + unreadable = storage.unreadable, + ) + } + + private fun fromStored(owner: UUID, stored: StoredStorage): PlayerStorage { + val unreadable = stored.unreadable.orEmpty().toMutableList() + + val pages = stored.pages.orEmpty().map { storedPage -> + StoragePage(storedPage.name, storedPage.icon).also { page -> + storedPage.slots.orEmpty().forEach { (key, encoded) -> + val index = key.toIntOrNull()?.takeIf { it in 0 until StoragePage.SIZE } + val item = ItemCodec.decode(encoded) + if (index == null || item == null || page.slots[index] != null) { + unreadable += encoded + } else { + page.slots[index] = item + } + } + } + } + + if (unreadable.size > stored.unreadable.orEmpty().size) { + logger.warning( + "Set aside ${unreadable.size - stored.unreadable.orEmpty().size} unreadable item(s) in the storage of $owner" + ) + } + + return PlayerStorage(owner, stored.purchased.coerceAtLeast(0), pages, unreadable) + } + + private const val DEFAULT_SCALE = 2 +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/StoragePricing.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/StoragePricing.kt new file mode 100644 index 0000000..5174cf7 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/StoragePricing.kt @@ -0,0 +1,43 @@ +package net.trilleo.mc.plugins.tritown.storage + +import net.trilleo.mc.plugins.tritown.economy.Money +import java.math.BigDecimal +import java.math.RoundingMode + +/** + * What storage pages cost. + * + * Each page bought costs [base] times [multiplier] for every page bought before + * it, so the first is [base] and the price climbs from there. Counting bought + * pages rather than owned ones keeps the price where a player left it when an + * owner hands out more free pages. + * + * Kept free of Bukkit and the economy, so the arithmetic can be tested alone. + */ +object StoragePricing { + + /** + * The price of one more page for a storage that has bought [purchased] and + * owns [owned] pages, at [scale] fractional digits. + * + * @return `null` when [owned] has reached [maxPages], or the price no longer + * fits in an amount of money + */ + fun next(purchased: Int, owned: Int, maxPages: Int, base: Double, multiplier: Double, scale: Int): Money? { + if (owned >= maxPages) return null + return cost(purchased + 1, base, multiplier, scale) + } + + /** The [nth] page bought, counting from one, or `null` when it is beyond any amount of money. */ + fun cost(nth: Int, base: Double, multiplier: Double, scale: Int): Money? { + require(nth >= 1) { "Pages bought are counted from one" } + if (!base.isFinite() || !multiplier.isFinite() || base < 0.0 || multiplier < 1.0) return null + + val price = BigDecimal.valueOf(base) + .multiply(BigDecimal.valueOf(multiplier).pow(nth - 1)) + .setScale(scale, RoundingMode.HALF_UP) + .movePointRight(scale) + + return runCatching { Money(price.longValueExact()) }.getOrNull() + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/storage/JsonStorageStore.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/storage/JsonStorageStore.kt new file mode 100644 index 0000000..859af3c --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/storage/JsonStorageStore.kt @@ -0,0 +1,109 @@ +package net.trilleo.mc.plugins.tritown.storage.storage + +import com.google.gson.GsonBuilder +import com.google.gson.JsonObject +import com.google.gson.JsonParser +import net.trilleo.mc.plugins.tritown.utils.AtomicFile +import java.io.File +import java.util.* +import java.util.logging.Logger + +/** + * Keeps each player's storage in a file of its own under `/storage/`. + * + * One file per player, so saving one storage never rewrites anyone else's. + * Writes go through [AtomicFile], with the previous copy kept as `.bak`, and a + * file that will not parse falls back to that backup. When neither can be read + * the load fails outright: an empty storage handed back instead would be saved + * over the player's items the moment they closed it. + */ +class JsonStorageStore(directory: File, private val logger: Logger) : StorageStore { + + private val root = File(directory, DIRECTORY) + private val gson = GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create() + private val ioLock = Any() + + override fun load(owner: UUID): StoredStorage? = synchronized(ioLock) { + val file = fileOf(owner) + val backup = backupOf(owner) + + val document = read(file) ?: run { + if (file.exists()) logger.warning("${file.name} could not be read; falling back to the backup") + read(backup) ?: run { + if (file.exists() || backup.exists()) { + throw StorageStoreException("Neither ${file.name} nor its backup could be read") + } + return null + } + } + + val version = document.get(KEY_VERSION)?.asInt ?: SCHEMA_VERSION + if (version > SCHEMA_VERSION) { + throw StorageStoreException("${file.name} was written by a newer TriTown (schema $version)") + } + + val body = document.getAsJsonObject(KEY_STORAGE) ?: return null + return runCatching { gson.fromJson(body, StoredStorage::class.java) } + .getOrElse { throw StorageStoreException("${file.name} does not hold a storage", it) } + } + + override fun save(storage: StoredStorage) = synchronized(ioLock) { + val owner = storage.owner?.let { runCatching { UUID.fromString(it) }.getOrNull() } ?: run { + logger.severe("Refused to save a storage without a valid owner") + return + } + root.mkdirs() + + val document = JsonObject().apply { + addProperty(KEY_VERSION, SCHEMA_VERSION) + add(KEY_STORAGE, gson.toJsonTree(storage)) + } + + try { + AtomicFile.write(fileOf(owner).toPath(), backupOf(owner).toPath(), gson.toJson(document)) + } catch (e: Exception) { + logger.severe("Failed to write the storage of $owner: [${e.javaClass.simpleName}] ${e.message}") + } + } + + override fun summaries(): List = synchronized(ioLock) { + val files = root.listFiles { file -> file.isFile && file.name.endsWith(EXTENSION) } ?: return emptyList() + + files.mapNotNull { file -> + val owner = runCatching { UUID.fromString(file.name.removeSuffix(EXTENSION)) }.getOrNull() + ?: return@mapNotNull null + val body = read(file)?.getAsJsonObject(KEY_STORAGE) ?: return@mapNotNull null + + val pages = body.getAsJsonArray("pages") + val used = pages?.sumOf { page -> + page.takeIf { it.isJsonObject }?.asJsonObject?.getAsJsonObject("slots")?.size() ?: 0 + } ?: 0 + + StorageSummary( + owner = owner, + purchased = body.get("purchased")?.asInt ?: 0, + pages = pages?.size() ?: 0, + usedSlots = used, + ) + } + } + + private fun fileOf(owner: UUID) = File(root, "$owner$EXTENSION") + + private fun backupOf(owner: UUID) = File(root, "$owner$EXTENSION.bak") + + private fun read(file: File): JsonObject? { + if (!file.exists()) return null + return runCatching { JsonParser.parseString(file.readText()).asJsonObject }.getOrNull() + } + + companion object { + /** The layout this store writes. A newer one is refused rather than guessed at. */ + const val SCHEMA_VERSION = 1 + + private const val DIRECTORY = "storage" + private const val EXTENSION = ".json" + private const val KEY_VERSION = "schemaVersion" + private const val KEY_STORAGE = "storage" + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/storage/StorageStore.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/storage/StorageStore.kt new file mode 100644 index 0000000..6d17e5e --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/storage/storage/StorageStore.kt @@ -0,0 +1,55 @@ +package net.trilleo.mc.plugins.tritown.storage.storage + +import java.util.* + +/** + * Where players' storages are kept between restarts. + * + * Deals only in [StoredStorage], whose items are already encoded text, so a + * store never touches a Bukkit type and can write from any thread. + */ +interface StorageStore { + + /** + * [owner]'s storage, or `null` when they have never stored anything. + * + * @throws StorageStoreException when a file exists but cannot be read, which + * must stop that storage rather than let an empty one overwrite it + */ + fun load(owner: UUID): StoredStorage? + + /** Replaces [storage]'s file with what it holds now. */ + fun save(storage: StoredStorage) + + /** A light count of every storage on file, read without decoding a single item. */ + fun summaries(): List +} + +/** + * One storage as it is written to disk. + * + * Fields are nullable because Gson fills a missing one with `null` whatever the + * declaration says; [StoredPage.slots] maps a slot's index to its encoded item, + * so an empty slot costs nothing. + * + * @param unreadable items that could not be decoded, kept as they were found so + * they are never written away + */ +data class StoredStorage( + val owner: String? = null, + val purchased: Int = 0, + val pages: List? = null, + val unreadable: List? = null, +) + +data class StoredPage( + val name: String? = null, + val icon: String? = null, + val slots: Map? = null, +) + +/** How much one storage holds, for the admin panel. */ +data class StorageSummary(val owner: UUID, val purchased: Int, val pages: Int, val usedSlots: Int) + +/** Raised when a storage file exists but cannot be read, and must not be silently replaced. */ +class StorageStoreException(message: String, cause: Throwable? = null) : Exception(message, cause) diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/tasks/storage/StorageSaveTask.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/tasks/storage/StorageSaveTask.kt new file mode 100644 index 0000000..85e1e46 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/tasks/storage/StorageSaveTask.kt @@ -0,0 +1,33 @@ +package net.trilleo.mc.plugins.tritown.tasks.storage + +import net.trilleo.mc.plugins.tritown.config.StorageSettings +import net.trilleo.mc.plugins.tritown.registration.PluginTask +import net.trilleo.mc.plugins.tritown.storage.StorageManager + +/** + * Writes changed storages to disk on an interval. + * + * Runs on the server thread, because items can only be encoded there; the + * encoded text is written on the storage's own writer thread. Closing a storage + * or switching its page writes it too, so this only bounds what a crash can + * cost while someone is still moving items around in one. + */ +class StorageSaveTask : PluginTask( + delay = saveIntervalTicks(), + period = saveIntervalTicks(), +) { + override fun run() { + StorageManager.flushDirty() + } +} + +/** + * The configured save interval in ticks. + * + * Read at construction, which is safe because the storage settings are loaded + * in `onEnable` before the task registrar runs. + */ +private fun saveIntervalTicks(): Long { + val seconds = if (StorageSettings.isLoaded) StorageSettings.snapshot.saveIntervalSeconds else 30L + return seconds * 20L +} diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 270775c..b71d600 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -9,9 +9,9 @@ message-prefix: "[TriTown language: auto # ── Main Menu ─────────────────────────────────────────────────────────────── -# The menu players reach everything TriTown offers from: their balance and town, -# the global shop, trading and paying other players, the leaderboard, the -# sidebar switch and a shortcut into TownyMenu. /tritown menu opens it too. +# The menu players reach everything TriTown offers from: their balance, town and +# storage, the global shop, trading and paying other players, the leaderboard, +# the sidebar switch and a shortcut into TownyMenu. /tritown menu opens it too. main-menu: item: # Keep the menu item in the last slot of every player's hotbar. Right-clicking @@ -180,6 +180,41 @@ player-trades: # Seconds an unanswered request stands before it lapses. request-expiry: 60 +# ── Storage ───────────────────────────────────────────────────────────────── +# Every player's own storage, opened from the main menu or with /tritown storage. +# A page is a large chest: five rows for items above a row of buttons for moving +# between pages, depositing, sorting, and unpacking shulker boxes and bundles. +# +# It replaces vanilla containers, which can no longer be placed. The ones already +# in the world can only be emptied, so nothing anyone stored is lost. +# tritown.storage.bypass lets a builder place and fill them anyway. +storage: + # Turn the storage off entirely. Containers are then left as vanilla has them. + # Switching it back on needs a restart. + enabled: true + # Pages every player has without paying. + free-pages: 2 + # The most pages a storage can reach, free ones included. + max-pages: 27 + # Each page bought costs base × multiplier for every page bought before it: + # with these, 500, then 750, 1125, 1687.50 and so on. A multiplier of 1 keeps + # every page at the same price. Buying pages takes money out of the economy. + price: + base: 500.0 + multiplier: 1.5 + # Seconds between writing changed storages to disk. Closing a storage or + # turning its page writes it straight away, so this only covers a crash while + # someone is still moving items around in one. + save-interval: 30 + lock-containers: + # Stop the containers below being placed, and make the ones already placed + # withdraw-only. Hoppers can still pull items out of them, but not push in. + enabled: true + # Chests, trapped chests, barrels, chest and hopper minecarts, and chest boats. + chests: true + shulker-boxes: true + ender-chest: true + # ── Towns ─────────────────────────────────────────────────────────────────── towns: # Money set aside for a player's first town, on top of their starting balance. diff --git a/src/main/resources/lang/en_US.yml b/src/main/resources/lang/en_US.yml index f45d731..fd610e1 100644 --- a/src/main/resources/lang/en_US.yml +++ b/src/main/resources/lang/en_US.yml @@ -21,6 +21,7 @@ command: admin: "Admin" menu: "Menu" news: "News" + storage: "Storage" help: header: "TriTown Commands" @@ -127,6 +128,13 @@ command: unpinned: "Sidebar back to matching where you stand." unknown-board: "No board named {board}." + storage: + description: "Open your storage" + players-only: "Your storage is a menu, so only players can open it." + usage: "Usage: /tritown storage [view |pages ]" + not-found: "No player called {name} has played here." + pages-set: "{name} now has {amount} storage pages." + trades: description: "Open the server's global shop" players-only: "A shop is a menu, so only players can open it." @@ -278,11 +286,13 @@ money: shop-buy: "Bought at {shop}" shop-sell: "Sold at {shop}" trade: "Player trade" + storage-page: "Storage page {page}" # Where money comes from and where it goes, as the admin panel groups it. flow: starting-balance: "New players" shop: "Shops" + storage: "Storage pages" towny: "Towny" admin: "Administration" payment: "Player payments" @@ -295,6 +305,7 @@ money: command: "TriTown command" towny: "Towny" shop: "Shop" + storage: "Storage" account-type: player: "player" @@ -339,6 +350,10 @@ gui: town-open: "Click to open TownyMenu" shop: "Global Shop" shop-lore: "Buy from the server and sell back to it, wherever you are standing." + storage: "Storage" + storage-lore: "Your own storage, open from anywhere. Vanilla chests can only be emptied now." + storage-pages: "Pages: {amount}/{max}" + storage-next: "Next page: {amount}" trade: "Trade" trade-lore: "Swap items and money with a player standing near you. Shift-right-clicking them works too." trade-waiting: "{amount} waiting for your answer" @@ -405,6 +420,12 @@ gui: shops-taken: "Taken in: {amount}" shops-paid: "Paid out: {amount}" shops-off: "Shops are switched off." + storage: "Storage" + storage-lore: "Every player's storage, and what its pages have earned." + storage-free: "Free pages: {amount} of up to {max}" + storage-open: "Loaded now: {amount}" + storage-revenue: "Pages sold over {window}: {amount}" + storage-off: "Storage is switched off." server: "Server" server-version: "TriTown {version}" server-provider: "Economy: {provider}" @@ -565,6 +586,7 @@ gui: paid: "Paid: {amount}" about-starting-balance: "Paid once to each new player." about-shop: "The server's own shops selling and buying back." + about-storage: "Players buying more pages of storage." about-towny: "Upkeep, taxes, plot sales and bank movements." about-admin: "Balances given, taken, set or reset by an administrator." about-payment: "Players paying each other." @@ -1003,6 +1025,81 @@ gui: back-lore: "Return to where you were." # Asked before something that cannot be undone. + storage: + title: "{name} · {page}/{total}" + title-inspect: "{owner}'s storage · {page}/{total}" + page-default: "Page {page}" + previous: "Previous page" + previous-lore: "Go back one page." + next: "Next page" + next-lore: "Go on to the next page." + overview: "All pages" + overview-lore: "See every page at once and jump straight to one." + deposit: "Quick deposit" + deposit-lore: "Store everything in your inventory that your storage already holds some of. Your hotbar is left alone." + sort: "Sort" + sort-lore: "Merge and order this page.Shift-click to sort every page." + withdraw: "Take page" + withdraw-lore: "Move as much of this page as fits into your inventory." + unpack: "Unpack" + unpack-lore: "Click here holding a shulker box or bundle to empty it into your storage. Full ones can't be stored or placed any more." + settings: "Page settings" + settings-lore: "Rename this page or pick its icon." + info: "{name}" + info-page: "Page {page} of {total}" + info-owner: "Owner: {owner}" + info-read-only: "Read only" + info-back: "Click to go back to the menu" + info-back-admin: "Click to go back to the list" + overview-name: "{name}" + overview-used: "Used: {amount}/{total}" + overview-item: "• {amount}× {name}" + overview-current: "You are on this page" + overview-open: "Click to open" + buy: "Buy page {page}" + buy-cost: "Costs: {amount}" + buy-balance: "You have: {amount}" + buy-click: "Click to buy" + buy-title: "Buy a storage page?" + buy-confirm: "Buy" + + storage-pages: + title: "Your storage" + title-inspect: "{owner}'s storage" + back: "Back" + back-lore: "Return to the page you were on." + + storage-settings: + title: "Page settings" + rename: "Rename" + rename-lore: "Type a new name in chat." + rename-prompt: "Type a name for this page, up to {amount} characters." + icon: "Icon" + icon-lore: "Click any item in your inventory to show this page as it." + icon-hint: "Click an item in your own inventory to use it as the icon." + reset: "Reset" + reset-lore: "Go back to the page number and the default icon." + back: "Back" + back-lore: "Return to the page." + + admin-storage: + title: "Storage" + header: "Every storage" + header-lore: "Read from disk when this list was opened." + count: "Storages: {amount}" + bought: "Pages bought: {amount}" + slots: "Slots in use: {amount}" + revenue: "Pages sold over {window}: {amount}" + owner: "{name}" + pages: "Pages: {amount} ({bought} bought)" + used: "Used: {amount}/{total}" + click-view: "Click to look through it" + click-edit: "Shift-click to change it" + disabled: "Storage is switched off" + disabled-lore: "Set storage.enabled to true in config.yml and restart." + back: "Back" + back-lore: "Return to the admin panel." + confirm: title: "Are you sure?" cancel: "Cancel" @@ -1038,6 +1135,32 @@ shop: # Player-to-player trading, outside the menu itself. +# A player's own storage, and the vanilla containers it replaces. +storage: + bought: "You bought page {page} of your storage." + deposited: "Deposited {amount} items." + unpacked: "Unpacked {amount} items into your storage." + renamed: "Page renamed to {name}." + + # Shown inside common.error, which colours them. + error: + unavailable: "Storage is not available on this server right now." + unreadable: "That storage could not be read. Ask an administrator to check the server log." + busy: "Someone else is changing that storage right now. Try again in a moment." + not-allowed: "Full shulker boxes, full bundles and the menu item can't go in your storage. Unpack boxes and bundles instead." + no-room: "Your storage doesn't have room for all of that." + inventory-full: "Your inventory is full." + nothing-to-deposit: "Nothing in your inventory matches what you already have stored." + unpack-hint: "Pick up a shulker box or bundle, then click Unpack with it." + unpack-empty: "That is already empty." + cannot-afford: "You can't afford that page." + max-pages: "Your storage already has every page it can." + bad-name: "A page name has to be 1 to {amount} characters." + + lock: + no-place: "Containers are retired on this server. Keep your items in your storage instead: /tritown storage" + withdraw-only: "This container is withdraw-only. Open your storage from the menu." + trade: done: "Traded with {name}." money-prompt: "Type how much to put up. You have {amount}." diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index fa52029..77af1fb 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -21,6 +21,7 @@ command: admin: "管理" menu: "菜单" news: "公告" + storage: "仓库" help: header: "TriTown 命令" @@ -127,6 +128,13 @@ command: unpinned: "侧边栏已恢复为根据所在位置自动切换。" unknown-board: "不存在名为 {board} 的板面。" + storage: + description: "打开你的仓库" + players-only: "仓库是一个菜单,只有玩家才能打开。" + usage: "用法:/tritown storage [view |pages ]" + not-found: "没有名为 {name} 的玩家来过本服务器。" + pages-set: "{name} 现在拥有 {amount} 页仓库。" + trades: description: "打开服务器的全局商店" players-only: "商店是菜单,只有玩家能打开。" @@ -277,11 +285,13 @@ money: shop-buy: "在 {shop} 购买" shop-sell: "在 {shop} 出售" trade: "玩家交易" + storage-page: "仓库第 {page} 页" # 资金的来源与去向,管理面板按此归类统计。 flow: starting-balance: "新玩家" shop: "商店" + storage: "仓库页" towny: "Towny" admin: "管理操作" payment: "玩家转账" @@ -294,6 +304,7 @@ money: command: "TriTown 命令" towny: "Towny" shop: "商店" + storage: "仓库" account-type: player: "玩家" @@ -338,6 +349,10 @@ gui: town-open: "点击 打开 TownyMenu" shop: "全局商店" shop-lore: "无论身在何处,都能向服务器购买物品或把物品卖回给它。" + storage: "仓库" + storage-lore: "属于你自己的仓库,随时随地都能打开。原版箱子现在只能取出物品。" + storage-pages: "页数:{amount}/{max}" + storage-next: "下一页价格:{amount}" trade: "交易" trade-lore: "与身边的玩家交换物品和金钱。也可以潜行右键点击对方发起交易。" trade-waiting: "{amount} 人正在等待你的回复" @@ -404,6 +419,12 @@ gui: shops-taken: "收取:{amount}" shops-paid: "支付:{amount}" shops-off: "商店已关闭。" + storage: "仓库" + storage-lore: "所有玩家的仓库,以及仓库页带来的收入。" + storage-free: "免费页数:{amount} (上限 {max} 页)" + storage-open: "当前已加载:{amount}" + storage-revenue: "{window}售出仓库页:{amount}" + storage-off: "仓库已关闭。" server: "服务器" server-version: "TriTown {version}" server-provider: "经济提供方:{provider}" @@ -564,6 +585,7 @@ gui: paid: "支出:{amount}" about-starting-balance: "每名新玩家只发放一次。" about-shop: "服务器自己的商店卖出与回收。" + about-storage: "玩家购买更多仓库页。" about-towny: "维护费、税收、地块交易与银行存取。" about-admin: "管理员发放、收回、设定或重置余额。" about-payment: "玩家之间的转账。" @@ -1003,6 +1025,81 @@ gui: back-lore: "回到之前的界面。" # 执行无法撤销的操作前进行确认。 + storage: + title: "{name} · {page}/{total}" + title-inspect: "{owner} 的仓库 · {page}/{total}" + page-default: "第 {page} 页" + previous: "上一页" + previous-lore: "返回上一页。" + next: "下一页" + next-lore: "前往下一页。" + overview: "全部页面" + overview-lore: "一次查看所有页面,并直接跳到其中一页。" + deposit: "快速存入" + deposit-lore: "把背包里仓库中已有同类的物品全部存入仓库。快捷栏不受影响。" + sort: "整理" + sort-lore: "合并并排序本页。Shift+点击 整理所有页面。" + withdraw: "取出本页" + withdraw-lore: "把本页物品尽可能多地移入你的背包。" + unpack: "拆包" + unpack-lore: "手持潜影盒或收纳袋点击这里,把里面的物品倒进仓库。装有物品的潜影盒和收纳袋已无法存放或放置。" + settings: "页面设置" + settings-lore: "重命名本页或选择它的图标。" + info: "{name}" + info-page: "第 {page} 页,共 {total} 页" + info-owner: "所有者:{owner}" + info-read-only: "只读" + info-back: "点击 返回菜单" + info-back-admin: "点击 返回列表" + overview-name: "{name}" + overview-used: "已用:{amount}/{total}" + overview-item: "• {amount}× {name}" + overview-current: "你正在这一页" + overview-open: "点击 打开" + buy: "购买第 {page} 页" + buy-cost: "价格:{amount}" + buy-balance: "你的余额:{amount}" + buy-click: "点击 购买" + buy-title: "购买一页仓库?" + buy-confirm: "购买" + + storage-pages: + title: "你的仓库" + title-inspect: "{owner} 的仓库" + back: "返回" + back-lore: "回到你之前所在的页面。" + + storage-settings: + title: "页面设置" + rename: "重命名" + rename-lore: "在聊天栏输入新名称。" + rename-prompt: "请输入本页的名称,最多 {amount} 个字符。" + icon: "图标" + icon-lore: "点击背包中的任意物品,把它设为本页的图标。" + icon-hint: "点击你自己背包中的物品,把它设为图标。" + reset: "重置" + reset-lore: "恢复为页码名称和默认图标。" + back: "返回" + back-lore: "回到该页面。" + + admin-storage: + title: "仓库" + header: "所有仓库" + header-lore: "数据在打开此列表时从磁盘读取。" + count: "仓库数:{amount}" + bought: "已购页数:{amount}" + slots: "已用格子:{amount}" + revenue: "{window}售出仓库页:{amount}" + owner: "{name}" + pages: "页数:{amount} (已购 {bought} 页)" + used: "已用:{amount}/{total}" + click-view: "点击 查看" + click-edit: "Shift+点击 修改" + disabled: "仓库已关闭" + disabled-lore: "在 config.yml 中把 storage.enabled 设为 true 并重启服务器。" + back: "返回" + back-lore: "返回管理面板。" + confirm: title: "确定吗?" cancel: "取消" @@ -1038,6 +1135,32 @@ shop: # 玩家之间的交易在菜单之外发出的消息。 +# 玩家自己的仓库,以及被它取代的原版容器。 +storage: + bought: "你购买了仓库的第 {page} 页。" + deposited: "已存入 {amount} 个物品。" + unpacked: "已把 {amount} 个物品拆包存入仓库。" + renamed: "页面已重命名为 {name}。" + + # 显示在 common.error 中,由它上色。 + error: + unavailable: "本服务器的仓库暂时不可用。" + unreadable: "无法读取该仓库。请联系管理员查看服务器日志。" + busy: "其他人正在修改这个仓库,请稍后再试。" + not-allowed: "装有物品的潜影盒、收纳袋以及菜单物品不能放入仓库。请改用拆包。" + no-room: "你的仓库没有足够的空间放下这些物品。" + inventory-full: "你的背包已满。" + nothing-to-deposit: "背包里没有与仓库中已有物品相同的物品。" + unpack-hint: "先拿起一个潜影盒或收纳袋,再用它点击拆包。" + unpack-empty: "它已经是空的了。" + cannot-afford: "你买不起这一页。" + max-pages: "你的仓库已达到页数上限。" + bad-name: "页面名称须为 1 到 {amount} 个字符。" + + lock: + no-place: "本服务器已停用容器方块。请把物品存放在你的仓库中:/tritown storage" + withdraw-only: "这个容器只能取出物品。请从菜单打开你的仓库。" + trade: done: "已与 {name} 完成交易。" money-prompt: "请输入要放上的金额。你拥有 {amount}。" diff --git a/src/test/kotlin/net/trilleo/mc/plugins/tritown/storage/SlotFillTest.kt b/src/test/kotlin/net/trilleo/mc/plugins/tritown/storage/SlotFillTest.kt new file mode 100644 index 0000000..ef5225d --- /dev/null +++ b/src/test/kotlin/net/trilleo/mc/plugins/tritown/storage/SlotFillTest.kt @@ -0,0 +1,77 @@ +package net.trilleo.mc.plugins.tritown.storage + +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull + +/** + * Depositing and sorting move a player's items around without them watching + * each slot, so what matters is that nothing is ever lost or made up. + */ +class SlotFillTest { + + private data class Stack(val type: String, val amount: Int, val max: Int = 64) + + private val rules = object : SlotFill.Rules { + override fun similar(a: Stack, b: Stack) = a.type == b.type + override fun maxStack(stack: Stack) = stack.max + override fun amount(stack: Stack) = stack.amount + override fun withAmount(stack: Stack, amount: Int) = stack.copy(amount = amount) + } + + private val byType = compareBy { it.type } + + @Test + fun `a deposit tops up matching stacks on every page before starting a new one on the first`() { + val first = arrayOf(null, Stack("dirt", 10)) + val second = arrayOf(Stack("dirt", 60), null) + + assertNull(SlotFill.insert(listOf(first, second), Stack("dirt", 60), rules)) + + assertContentEquals(arrayOf(Stack("dirt", 2), Stack("dirt", 64)), first) + assertContentEquals(arrayOf(Stack("dirt", 64), null), second) + } + + @Test + fun `what does not fit comes back`() { + val page = arrayOf(Stack("stone", 60), null) + + val leftover = SlotFill.insert(listOf(page), Stack("stone", 100), rules) + + assertEquals(Stack("stone", 32), leftover) + assertContentEquals(arrayOf(Stack("stone", 64), Stack("stone", 64)), page) + } + + @Test + fun `an item that does not stack takes a slot each`() { + val page = arrayOfNulls(3) + + val leftover = SlotFill.insert(listOf(page), Stack("sword", 2, max = 1), rules) + + assertNull(leftover) + assertContentEquals(arrayOf(Stack("sword", 1, 1), Stack("sword", 1, 1), null), page) + } + + @Test + fun `sorting merges stacks, orders them, and keeps every item`() { + val page = arrayOf(Stack("stone", 40), null, Stack("dirt", 5), Stack("stone", 40), null) + + SlotFill.sort(page, rules, byType) + + assertContentEquals( + arrayOf(Stack("dirt", 5), Stack("stone", 64), Stack("stone", 16), null, null), + page, + ) + } + + @Test + fun `a page that cannot be sorted without losing items is left alone`() { + val page = arrayOf(Stack("stone", 200), null) + val before = page.copyOf() + + assertFalse(SlotFill.sort(page, rules, byType)) + assertContentEquals(before, page) + } +} diff --git a/src/test/kotlin/net/trilleo/mc/plugins/tritown/storage/StoragePricingTest.kt b/src/test/kotlin/net/trilleo/mc/plugins/tritown/storage/StoragePricingTest.kt new file mode 100644 index 0000000..43621b1 --- /dev/null +++ b/src/test/kotlin/net/trilleo/mc/plugins/tritown/storage/StoragePricingTest.kt @@ -0,0 +1,52 @@ +package net.trilleo.mc.plugins.tritown.storage + +import net.trilleo.mc.plugins.tritown.economy.Money +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** + * Pages get dearer the more a player has bought, and the price has to be the + * same wherever it is read: on the button, in the confirmation and at the till. + */ +class StoragePricingTest { + + @Test + fun `the first page bought costs the base price`() { + assertEquals(Money(50_000), StoragePricing.cost(1, 500.0, 1.5, 2)) + } + + @Test + fun `each page costs the multiplier more than the one before`() { + assertEquals(Money(75_000), StoragePricing.cost(2, 500.0, 1.5, 2)) + assertEquals(Money(112_500), StoragePricing.cost(3, 500.0, 1.5, 2)) + assertEquals(Money(168_750), StoragePricing.cost(4, 500.0, 1.5, 2)) + } + + @Test + fun `prices are rounded to the currency's smallest unit`() { + assertEquals(Money(33), StoragePricing.cost(2, 0.1, 3.333, 2)) + assertEquals(Money(2), StoragePricing.cost(2, 1.0, 1.5, 0)) + } + + @Test + fun `a multiplier of one keeps every page at the same price`() { + assertEquals(Money(10_000), StoragePricing.cost(20, 100.0, 1.0, 2)) + } + + @Test + fun `the next page is priced by how many were bought, not how many are owned`() { + assertEquals(Money(50_000), StoragePricing.next(purchased = 0, owned = 2, maxPages = 27, 500.0, 1.5, 2)) + assertEquals(Money(75_000), StoragePricing.next(purchased = 1, owned = 5, maxPages = 27, 500.0, 1.5, 2)) + } + + @Test + fun `a storage at the maximum has no next page`() { + assertNull(StoragePricing.next(purchased = 25, owned = 27, maxPages = 27, 500.0, 1.5, 2)) + } + + @Test + fun `a price too large to hold is refused rather than wrapped`() { + assertNull(StoragePricing.cost(256, 1_000_000.0, 10.0, 2)) + } +} diff --git a/src/test/kotlin/net/trilleo/mc/plugins/tritown/storage/storage/JsonStorageStoreTest.kt b/src/test/kotlin/net/trilleo/mc/plugins/tritown/storage/storage/JsonStorageStoreTest.kt new file mode 100644 index 0000000..9ca0612 --- /dev/null +++ b/src/test/kotlin/net/trilleo/mc/plugins/tritown/storage/storage/JsonStorageStoreTest.kt @@ -0,0 +1,88 @@ +package net.trilleo.mc.plugins.tritown.storage.storage + +import java.io.File +import java.nio.file.Files +import java.util.* +import java.util.logging.Level +import java.util.logging.Logger +import kotlin.test.* + +/** + * A storage file holds a player's belongings, so what it must never do is lose + * them: not to a crash mid-write, and not to a file it cannot read being + * replaced with an empty one. + */ +class JsonStorageStoreTest { + + private val directory: File = Files.createTempDirectory("tritown-storage").toFile() + private val logger = Logger.getAnonymousLogger().apply { level = Level.OFF } + private val store = JsonStorageStore(directory, logger) + + private val owner = UUID.fromString("00000000-0000-0000-0000-000000000001") + private val file = File(File(directory, "storage"), "$owner.json") + private val backup = File(File(directory, "storage"), "$owner.json.bak") + + @AfterTest + fun cleanUp() { + directory.deleteRecursively() + } + + private fun sample(purchased: Int = 3) = StoredStorage( + owner = owner.toString(), + purchased = purchased, + pages = listOf( + StoredPage(name = "Ores", icon = "IRON_ORE", slots = mapOf("0" to "encoded-iron", "44" to "encoded-gold")), + StoredPage(slots = mapOf("3" to "encoded-dirt")), + ), + unreadable = listOf("mystery"), + ) + + @Test + fun `a player who never stored anything has no storage`() { + assertNull(store.load(owner)) + } + + @Test + fun `a storage survives a round trip`() { + store.save(sample()) + assertEquals(sample(), store.load(owner)) + } + + @Test + fun `an unreadable file falls back to the backup`() { + store.save(sample(purchased = 1)) + store.save(sample(purchased = 2)) + file.writeText("{ not json") + + assertEquals(1, store.load(owner)?.purchased) + } + + @Test + fun `a storage that cannot be read at all is refused rather than started empty`() { + store.save(sample()) + file.writeText("{ not json") + backup.writeText("{ nor this") + + assertFailsWith { store.load(owner) } + } + + @Test + fun `a file from a newer version is refused`() { + store.save(sample()) + file.writeText(file.readText().replace("\"schemaVersion\": 1", "\"schemaVersion\": 99")) + + assertFailsWith { store.load(owner) } + } + + @Test + fun `summaries count what is stored without decoding it`() { + store.save(sample()) + val other = UUID.fromString("00000000-0000-0000-0000-000000000002") + store.save(StoredStorage(owner = other.toString(), purchased = 0, pages = emptyList())) + + val summaries = store.summaries().associateBy { it.owner } + + assertEquals(StorageSummary(owner, purchased = 3, pages = 2, usedSlots = 3), summaries[owner]) + assertEquals(StorageSummary(other, purchased = 0, pages = 0, usedSlots = 0), summaries[other]) + } +} From 396d32941ae16c57fcbddb30e9d73e3d55c40909 Mon Sep 17 00:00:00 2001 From: Trilleo Date: Mon, 21 Sep 2026 22:55:45 +0800 Subject: [PATCH 2/6] Improvement: Let containers be placed as decoration Chests, barrels, shulker boxes, ender chests, chest minecarts and chest boats can be placed again, with a warning that nothing can be stored in them. They stay withdraw-only, and an empty one no longer opens. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 9 +-- README.md | 16 ++--- docs/DEVELOPER_GUIDE.md | 16 +++-- .../plugins/tritown/config/StorageSettings.kt | 2 +- .../storage/ContainerLockListener.kt | 71 +++++++++---------- src/main/resources/config.yml | 14 ++-- src/main/resources/lang/en_US.yml | 3 +- src/main/resources/lang/zh_CN.yml | 3 +- 8 files changed, 68 insertions(+), 66 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 603ccfe..2a21716 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,10 +22,11 @@ #### Misc -+ Vanilla containers are retired in favour of the storage. Chests, trapped chests, barrels, shulker boxes, ender - chests, chest and hopper minecarts and chest boats can no longer be placed, by players or by dispensers. - + The ones already placed become withdraw-only, so nothing stored in them is lost. Hoppers can still empty them but - can no longer fill them. ++ Vanilla containers are decoration now, in favour of the storage. Chests, trapped chests, barrels, shulker boxes, + ender chests, chest minecarts and chest boats can still be placed, with a warning, but nothing can be put in them. + + One with items inside opens only to take them out, so nothing stored in them is lost. An empty one does not open + at all. + + Hoppers can still empty them but can no longer fill them. + Each group can be left alone under `storage.lock-containers`, and `tritown.storage.bypass` exempts builders. #### Economy diff --git a/README.md b/README.md index af8964c..e7e293c 100644 --- a/README.md +++ b/README.md @@ -45,8 +45,8 @@ size of a large chest, used exactly like one, with a row of buttons beneath for you already store some of, sorting, emptying a page into your inventory, and unpacking a shulker box or bundle straight into it. Name your pages and give them icons, and see every page at once in an overview. The first pages are free and more can be bought, each a little dearer than the last. It replaces vanilla containers: chests, barrels, shulker boxes -and ender chests can no longer be placed, and the ones already in the world can only be emptied — never filled, not -even by a hopper — so nothing anyone stored is lost. +and ender chests are decoration now. They can still be placed, but nothing can be put in them — not even by a hopper — +one with items inside only lets them be taken out, and an empty one does not open. Nothing anyone stored is lost. **Shops the server runs.** Admin shops, set up entirely in game: click an item in your own inventory to put it on the shelf and it is sold exactly as you made it, custom name, enchantments and all. An entry can be sold, bought back, or @@ -223,7 +223,7 @@ version stays available as `/tritown:balance` and so on. | `storage.price.base` | `500.0` | What the first bought page costs | | `storage.price.multiplier` | `1.5` | How much dearer each bought page is than the one before | | `storage.save-interval` | `30` | Seconds between writing changed storages; closing one writes it at once | -| `storage.lock-containers.enabled` | `true` | Stop containers being placed, and make placed ones withdraw-only | +| `storage.lock-containers.enabled` | `true` | Make containers decoration: withdraw-only, and closed once empty | | `storage.lock-containers.` | `true` | Each of `chests`, `shulker-boxes` and `ender-chest` on its own | | `towns.founding-credit` | `100.0` | Credit only `/t new` can spend, given once to players without a town; `0` is off | | `news.enabled` | `true` | Turn the server news off entirely | @@ -309,13 +309,13 @@ items in and out of them just as you would a chest. The row beneath holds the bu - **Sort** merges and orders the page; shift-click sorts every page. - **Take page** moves as much of the page as fits into your inventory. - **Unpack** empties a shulker box or bundle into your storage: pick one up and click the button with it. A full box - or bundle cannot be stored as it is, and shulker boxes can no longer be placed, so this is how their contents come - home. + or bundle cannot be stored as it is, so this is how its contents come home. - **Page settings** renames the page (typed in chat) or gives it an icon (click any item in your inventory). -Chests, trapped chests, barrels, shulker boxes, ender chests, chest and hopper minecarts and chest boats cannot be -placed, by players or by dispensers. The ones already in the world still open, but only to take things out; hoppers -can still empty them but not fill them. Each group can be left alone under `storage.lock-containers`. +Chests, trapped chests, barrels, shulker boxes, ender chests, chest minecarts and chest boats are decoration. They can +still be placed, with a warning, but nothing can be put in them: one with items inside opens only to take things out, +and an empty one does not open at all. Hoppers can still empty them but not fill them. Each group can be left alone +under `storage.lock-containers`. Storages live in `plugins/TriTown/storage/.json`, one per player, written atomically with a `.bak` copy beside it. A storage is written when it is closed, when its page is turned, every `storage.save-interval` seconds while it diff --git a/docs/DEVELOPER_GUIDE.md b/docs/DEVELOPER_GUIDE.md index 7ba8dd7..4ea700e 100644 --- a/docs/DEVELOPER_GUIDE.md +++ b/docs/DEVELOPER_GUIDE.md @@ -3020,8 +3020,8 @@ calls the trade off if they leave it hanging. ## Personal Storage Every player's own paged storage, reached from the main menu or with `/tritown storage`. It replaces vanilla -containers: chests, barrels, shulker boxes and ender chests can no longer be placed, and the ones already in the world -are withdraw-only. +containers: chests, barrels, shulker boxes and ender chests are decoration — withdraw-only while they hold anything, and +closed once empty. The core lives under `storage/`, which is **not a scanned package** — the same reason `shops/` and `trades/` are not. `StorageManager` has to be alive before the registrars build the main menu that reads it. The menus are in @@ -3117,17 +3117,19 @@ page turn keeps the window to the time someone is actively moving items around i ### The container lock -`ContainerLockListener` refuses placing a chest, trapped chest, barrel, ender chest or any shulker box, placing a -chest or hopper minecart or a chest boat, and a dispenser doing either. Crafting is left alone, since chests go into -hoppers and minecarts. +`ContainerLockListener` lets a chest, trapped chest, barrel, ender chest, shulker box, chest minecart or chest boat be +placed, as decoration, and warns the player who placed it (`storage.lock.decoration`, at `MONITOR` so a placement +something else refused says nothing). Crafting is left alone. -A container already in the world is **withdraw-only**. The listener recognises one by **the holder of its inventory** +**An empty container does not open**: `InventoryOpenEvent` is cancelled when the inventory is empty, so a decorative +chest never shows an inventory that looks as if it were waiting to be filled. For an ender chest that is the viewer's +own ender inventory. A container with anything in it opens, and is **withdraw-only**. The listener recognises one by **the holder of its inventory** (`Chest`, `DoubleChest`, `Barrel`, `ShulkerBox`, `StorageMinecart`, `ChestBoat`, or the `ENDER_CHEST` type), never by `InventoryType` — TriTown's own menus and other plugins' are chest-shaped too, and they have no holder. It cancels anything that would put an item in: placing or swapping into a top slot, a shift-click from the player's inventory, a number key that carries an item in, and any drag touching the top. Taking out is always allowed. `InventoryMoveItemEvent` is cancelled when the **destination** is locked, so hoppers can still empty a chest but not -fill one. A hopper minecart already running is left unlocked for the same reason: it is part of a machine. +fill one. A hopper minecart is left unlocked for the same reason: it is part of a machine. Each group has its own switch under `storage.lock-containers`, the whole lock follows `storage.enabled`, and `tritown.storage.bypass` exempts a player. diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/StorageSettings.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/StorageSettings.kt index 6ac82ef..f464407 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/StorageSettings.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/StorageSettings.kt @@ -28,7 +28,7 @@ data class StorageSettings( /** * Which groups of vanilla containers can no longer be placed or filled. * - * @param chests chests, trapped chests, barrels, chest and hopper minecarts, and chest boats + * @param chests chests, trapped chests, barrels, chest minecarts and chest boats * @param shulkerBoxes every colour of shulker box * @param enderChest the ender chest */ diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/storage/ContainerLockListener.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/storage/ContainerLockListener.kt index ba9778e..e121bbc 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/storage/ContainerLockListener.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/storage/ContainerLockListener.kt @@ -15,11 +15,10 @@ import org.bukkit.block.ShulkerBox import org.bukkit.entity.ChestBoat import org.bukkit.entity.Entity import org.bukkit.entity.Player -import org.bukkit.entity.minecart.HopperMinecart import org.bukkit.entity.minecart.StorageMinecart import org.bukkit.event.EventHandler +import org.bukkit.event.EventPriority import org.bukkit.event.Listener -import org.bukkit.event.block.BlockDispenseEvent import org.bukkit.event.block.BlockPlaceEvent import org.bukkit.event.entity.EntityPlaceEvent import org.bukkit.event.inventory.* @@ -31,10 +30,11 @@ import java.util.concurrent.ConcurrentHashMap /** * Retires the vanilla containers the storage replaces. * - * None of them can be placed any more, and the ones already in the world are - * withdraw-only: a player can empty a chest into their storage, but not fill - * one, and neither can a hopper. Crafting is left alone, since a chest goes into - * hoppers and minecarts that have nothing to do with storing things. + * They can still be placed, as decoration, with a warning that they will not + * hold anything. Every one of them is withdraw-only: a player can empty a chest + * into their storage, but not fill one, and neither can a hopper. One with + * nothing left in it does not open at all, so a decorative chest never shows + * an empty inventory that looks as if it were waiting to be filled. * * A container is recognised by what holds its inventory, never by the * inventory's type. TriTown's own menus and other plugins' are chest-shaped too, @@ -47,28 +47,32 @@ class ContainerLockListener : Listener { // ── Placing ───────────────────────────────────────────────────────── - @EventHandler(ignoreCancelled = true) + /** Placing is allowed, as decoration, but the player is told what they are putting down. */ + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) fun onPlace(event: BlockPlaceEvent) { if (!isLockedMaterial(event.blockPlaced.type) || exempt(event.player)) return - event.isCancelled = true - refusePlacing(event.player) + warnPlacing(event.player) } - @EventHandler(ignoreCancelled = true) + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) fun onEntityPlace(event: EntityPlaceEvent) { - if (!isLockedEntity(event.entity)) return - val player = event.player - if (player != null && exempt(player)) return - event.isCancelled = true - player?.let(::refusePlacing) + val player = event.player ?: return + if (!isLockedEntity(event.entity) || exempt(player)) return + warnPlacing(player) } - /** A dispenser places shulker boxes, minecarts and boats just as a player would. */ + // ── Opening ───────────────────────────────────────────────────────── + + /** An empty container is decoration and does not open; one with items in it opens to be emptied. */ @EventHandler(ignoreCancelled = true) - fun onDispense(event: BlockDispenseEvent) { - if (!lockActive()) return - val type = event.item.type - if (isLockedMaterial(type) || isLockedVehicle(type)) event.isCancelled = true + fun onOpen(event: InventoryOpenEvent) { + val player = event.player as? Player ?: return + val inventory = event.inventory + if (!isLocked(inventory) || exempt(player)) return + if (!inventory.isEmpty) return + + event.isCancelled = true + hint(player, "storage.lock.empty") } // ── Filling ───────────────────────────────────────────────────────── @@ -89,7 +93,7 @@ class ContainerLockListener : Listener { if (!fills) return event.isCancelled = true - hint(player) + hint(player, "storage.lock.withdraw-only") } @EventHandler(ignoreCancelled = true) @@ -100,7 +104,7 @@ class ContainerLockListener : Listener { if (event.rawSlots.none { it < top.size }) return event.isCancelled = true - hint(player) + hint(player, "storage.lock.withdraw-only") } /** Hoppers and droppers may still pull from a container; they may not push into one. */ @@ -133,25 +137,16 @@ class ContainerLockListener : Listener { } } - /** The minecart and boat items that carry a container. */ - private fun isLockedVehicle(type: Material): Boolean { - val lock = lock() ?: return false - if (!lock.chests) return false - return type == Material.CHEST_MINECART || type == Material.HOPPER_MINECART || - type.name.endsWith("_CHEST_BOAT") || type.name.endsWith("_CHEST_RAFT") - } - private fun isLockedEntity(entity: Entity): Boolean { val lock = lock() ?: return false - return lock.chests && (entity is StorageMinecart || entity is HopperMinecart || entity is ChestBoat) + return lock.chests && (entity is StorageMinecart || entity is ChestBoat) } /** * Whether [inventory] belongs to one of the retired containers. * - * A hopper minecart can no longer be placed, but one already running is - * left to work: it is part of a machine, and locking it would stop it - * pulling items out of the very chests players are meant to empty. + * A hopper minecart is left alone: it is part of a machine, and locking it + * would stop it pulling items out of the very chests players are meant to empty. */ private fun isLocked(inventory: Inventory): Boolean { val lock = lock() ?: return false @@ -176,16 +171,16 @@ class ContainerLockListener : Listener { // ── Telling the player ────────────────────────────────────────────── - private fun refusePlacing(player: Player) { - player.sendPrefixed(player.tr("common.error", "message" to player.tr("storage.lock.no-place"))) + private fun warnPlacing(player: Player) { + player.sendPrefixed(player.tr("storage.lock.decoration")) } - private fun hint(player: Player) { + private fun hint(player: Player, key: String) { val now = System.currentTimeMillis() val last = lastHint[player.uniqueId] if (last != null && now - last < HINT_COOLDOWN_MS) return lastHint[player.uniqueId] = now - player.sendActionBar(ComponentUtil.parse(player.tr("storage.lock.withdraw-only"))) + player.sendActionBar(ComponentUtil.parse(player.tr(key))) } private companion object { diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index b71d600..05dcd1f 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -185,9 +185,10 @@ player-trades: # A page is a large chest: five rows for items above a row of buttons for moving # between pages, depositing, sorting, and unpacking shulker boxes and bundles. # -# It replaces vanilla containers, which can no longer be placed. The ones already -# in the world can only be emptied, so nothing anyone stored is lost. -# tritown.storage.bypass lets a builder place and fill them anyway. +# It replaces vanilla containers. They can still be placed as decoration, with a +# warning, but nothing can be put in them: one with items inside only lets them be +# taken out, and an empty one does not open at all. Nothing anyone stored is lost. +# tritown.storage.bypass lets a builder use them as vanilla does. storage: # Turn the storage off entirely. Containers are then left as vanilla has them. # Switching it back on needs a restart. @@ -207,10 +208,11 @@ storage: # someone is still moving items around in one. save-interval: 30 lock-containers: - # Stop the containers below being placed, and make the ones already placed - # withdraw-only. Hoppers can still pull items out of them, but not push in. + # Make the containers below decoration: withdraw-only while they hold + # anything, and closed once empty. Placing one warns the player. Hoppers can + # still pull items out of them, but not push in. enabled: true - # Chests, trapped chests, barrels, chest and hopper minecarts, and chest boats. + # Chests, trapped chests, barrels, chest minecarts and chest boats. chests: true shulker-boxes: true ender-chest: true diff --git a/src/main/resources/lang/en_US.yml b/src/main/resources/lang/en_US.yml index fd610e1..5c4b17b 100644 --- a/src/main/resources/lang/en_US.yml +++ b/src/main/resources/lang/en_US.yml @@ -1158,8 +1158,9 @@ storage: bad-name: "A page name has to be 1 to {amount} characters." lock: - no-place: "Containers are retired on this server. Keep your items in your storage instead: /tritown storage" + decoration: "Containers are decoration on this server: nothing can be put in them, and an empty one won't open. Keep your items in your storage instead: /tritown storage" withdraw-only: "This container is withdraw-only. Open your storage from the menu." + empty: "This container is empty. It is only decoration now." trade: done: "Traded with {name}." diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index 77af1fb..ff37a65 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -1158,8 +1158,9 @@ storage: bad-name: "页面名称须为 1 到 {amount} 个字符。" lock: - no-place: "本服务器已停用容器方块。请把物品存放在你的仓库中:/tritown storage" + decoration: "本服务器的容器仅作装饰:无法放入物品,空的容器也无法打开。请把物品存放在你的仓库中:/tritown storage" withdraw-only: "这个容器只能取出物品。请从菜单打开你的仓库。" + empty: "这个容器是空的,现在只是装饰。" trade: done: "已与 {name} 完成交易。" From 8098d6a8cf21746d81d50084a85a49868b5c9ef0 Mon Sep 17 00:00:00 2001 From: Trilleo Date: Mon, 21 Sep 2026 22:55:54 +0800 Subject: [PATCH 3/6] Internal: Correct the container lock's description in StorageSettings Co-Authored-By: Claude Opus 5 --- .../net/trilleo/mc/plugins/tritown/config/StorageSettings.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/StorageSettings.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/StorageSettings.kt index f464407..f319b37 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/StorageSettings.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/StorageSettings.kt @@ -26,7 +26,7 @@ data class StorageSettings( ) { /** - * Which groups of vanilla containers can no longer be placed or filled. + * Which groups of vanilla containers are decoration: withdraw-only, and closed once empty. * * @param chests chests, trapped chests, barrels, chest minecarts and chest boats * @param shulkerBoxes every colour of shulker box From 3db329df347b814ac2ce60e8bd230aa02d743339 Mon Sep 17 00:00:00 2001 From: Trilleo Date: Tue, 22 Sep 2026 10:55:18 +0800 Subject: [PATCH 4/6] Feature: Add item protection Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 29 ++ CLAUDE.md | 22 +- README.md | 14 + docs/DEVELOPER_GUIDE.md | 126 ++++++++- docs/UTILITY_GUIDE.md | 4 +- .../net/trilleo/mc/plugins/tritown/Main.kt | 2 + .../commands/protection/ProtectionCommand.kt | 72 +++++ .../tritown/config/ProtectionSettings.kt | 59 +++++ .../protection/ActionDropListener.kt | 107 ++++++++ .../protection/ContainerProtectionListener.kt | 248 ++++++++++++++++++ .../protection/DropProtectionListener.kt | 134 ++++++++++ .../protection/EntityProtectionListener.kt | 135 ++++++++++ .../mc/plugins/tritown/menu/MenuItem.kt | 3 +- .../mc/plugins/tritown/protection/Claims.kt | 147 +++++++++++ .../plugins/tritown/protection/DropWindows.kt | 81 ++++++ .../tritown/protection/ItemOwnership.kt | 59 +++++ .../plugins/tritown/protection/Protection.kt | 74 ++++++ .../mc/plugins/tritown/utils/InventoryUtil.kt | 5 +- src/main/resources/config.yml | 31 +++ src/main/resources/lang/en_US.yml | 16 ++ src/main/resources/lang/zh_CN.yml | 16 ++ .../tritown/protection/DropWindowsTest.kt | 55 ++++ 22 files changed, 1433 insertions(+), 6 deletions(-) create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/protection/ProtectionCommand.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/config/ProtectionSettings.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/ActionDropListener.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/ContainerProtectionListener.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/DropProtectionListener.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/EntityProtectionListener.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/protection/Claims.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/protection/DropWindows.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/protection/ItemOwnership.kt create mode 100644 src/main/kotlin/net/trilleo/mc/plugins/tritown/protection/Protection.kt create mode 100644 src/test/kotlin/net/trilleo/mc/plugins/tritown/protection/DropWindowsTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a21716..42e11fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,32 @@ + Added a **Storage** section to the admin panel (`tritown.admin.storage`). It lists every storage, fullest first, with how many pages were bought and what they earned, and opens any of them read-only. +#### Item Protection + ++ Items now belong to the player who has them, and the only way to hand one to someone else is a trade + (`/trade `). + + Items you drop can only be picked up by you. So can whatever you mine, harvest, shear or fish up, the loot of a + mob you kill (with a bow or a tamed pet too), and a vault's reward. + + Death drops, and anything the world drops by itself, can still be picked up by anyone. + + Mobs, allays and foxes can't pick up anyone's items. Piglins still barter, and pay back whoever threw the gold. + + Only the player who fired an arrow or trident can pick it back up. ++ Containers belong to whoever fills them, for as long as anything is inside: furnaces, hoppers, brewing stands, + droppers, crafters, decorated pots, shelves, chiseled bookshelves, jukeboxes, campfires and lecterns. + + Nobody else can open, feed, empty or break one, or blow it up. An empty container is free for anyone again, so + shared furnaces still work. + + Hoppers carry the owner along: your items can fill a free container, which becomes yours, but never someone + else's. + + Anyone can still read a lectern. Only its owner can take the book. ++ Item frames, armor stands, allays, and mobs you have saddled, armoured or given a chest are yours too. Nobody else + can take the item, shear it off, ride the mob, or break the frame or stand. ++ Items the plugin hands you that don't fit in your inventory, from a trade, a shop or your storage, now drop as + yours. ++ Administrators with `tritown.protection.admin` can see who owns the container or entity they are looking at with + `/tritown protection inspect`, and clear the claim with `release`. `tritown.protection.bypass` lets staff open, take + from and break anything. ++ Everything can be tuned or switched off under `item-protection` in `config.yml`, including a list of worlds where + nothing is protected. + #### Misc + Vanilla containers are decoration now, in favour of the storage. Chests, trapped chests, barrels, shulker boxes, @@ -38,6 +64,9 @@ + Added the storage core under `storage/`: `StorageManager` (loading, the one-editor lock, pricing and saving), one JSON file per player under `plugins/TriTown/storage/`, written atomically with a backup, on a single writer thread. ++ Added the item protection core under `protection/`: `ItemOwnership` (drop owners, kept on the game's own `Item` + owner field), `DropWindows` (per-tick windows that credit drops which do not exist yet), and `Claims` (container + and entity claims in their persistent data, released lazily). + `StorageGUI` is the first menu that lets the game move items itself, with the button row, shift-clicks and double-clicks guarded by hand. diff --git a/CLAUDE.md b/CLAUDE.md index db4ac65..00cfa59 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/ economy/ info/ menu/ news/ +│ ├── admin/ economy/ info/ menu/ news/ protection/ │ └── moderation/ scoreboard/ shop/ storage/ trade/ ├── config/ # PluginConfig (typed config.yml wrapper), EconomySettings ├── data/ # JSON-persisted PlayerData / ServerData and their managers @@ -81,6 +81,8 @@ src/main/kotlin/net/trilleo/mc/plugins/tritown/ ├── listeners/ # Event listeners, including Towny events (auto-registered) ├── menu/ # The main menu item and the invariant that keeps it unique (not scanned) ├── news/ # Server news: posts, storage, read state, notifications (not scanned) +├── protection/ # Item protection: drop owners, drop windows, container and entity claims +│ # (not scanned) ├── recipes/ # Recipes (auto-registered, implement PluginRecipe) ├── registration/ # Auto-registration engine (do not modify lightly) ├── shops/ # Admin shops: model, trading, storage, FancyNpcs bridge (not scanned) @@ -292,6 +294,24 @@ The panel in `guis/admin` is where an owner reads the server; `/tritown admin` o - **Recognise a vanilla container by its inventory's holder**, never by `InventoryType`: TriTown's own menus are chest-shaped too and have no holder. +## Working with Item Protection + +**Items belong to the player who has them; a trade is the only way to hand one over.** See +[Item Protection](docs/DEVELOPER_GUIDE.md#item-protection). + +- **An item in an inventory is never marked.** Ownership exists only on a dropped `Item` (the game's own owner field, + set through `ItemOwnership`) and as a claim on a container or entity holder (`Claims`). Never stamp an `ItemStack` + with an owner: a mark nothing strips follows the item into an inventory and stops it stacking. +- **Never drop an item for a player with `dropItemNaturally` alone.** Use `ItemOwnership.dropFor`, or + `InventoryUtil.give`, whose overflow already does. +- **A drop that does not exist yet gets a window.** Call `ItemOwnership.expect` from the event that names the player. + The spawn claims it. Death drops stay public through `suppress`. +- **Claims are released lazily.** `Claims.ownerOf` clears a claim on a vacant holder (empty and unviewed). Never add a + task to release them, and read with `Claims.recorded` only for what a destroyed holder leaves behind. +- **Ask `Protection.settings(world)` first** in every handler, and let `Protection.BYPASS_PERMISSION` through. +- **A new holder of player items** (a block, an entity, a feature that spills items) must be taught to `Claims.of` + or given an owner before it ships. Otherwise it becomes a way to hand items over outside a trade. + ## Working with the Main Menu The main menu (`guis/menu`) is how players reach TriTown, opened from the menu item in hotbar slot 8 or with diff --git a/README.md b/README.md index e7e293c..868228a 100644 --- a/README.md +++ b/README.md @@ -122,6 +122,12 @@ first start: Prebuilt jars are attached to every [GitHub release](https://github.com/Trilleo/TriTown/releases). +**Your items stay yours.** Like Hypixel SkyBlock, the only way to give another player an item is a trade. What you drop, +mine, harvest, fish up or loot from a mob you killed can only be picked up by you. A furnace, hopper, brewing stand or +decorated pot belongs to whoever filled it until it is empty again, and so do item frames, armor stands and the saddle +on your horse. Nobody else can open, empty, break or blow them up. Death drops, and anything the world drops by +itself, are still anyone's. + ## Commands | Command | Description | @@ -140,6 +146,7 @@ Prebuilt jars are attached to every [GitHub release](https://github.com/Trilleo/ | `/tt news` | Read the server news | | `/tt storage` | Open your storage | | `/tt admin [section]` | Open the admin panel (OP only) | +| `/tt protection ` | See or clear who owns what you look at (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 @@ -164,6 +171,10 @@ Administrators with `tritown.storage.admin` also get `view `, which open change, and `pages `, which hands out pages for free. `tritown.storage.bypass` lets a builder place and fill the containers the storage replaces. +`/tt protection inspect` shows who owns the container, item frame, armor stand or mob you are looking at, and +`release` clears that claim; both need `tritown.protection.admin`. `tritown.protection.bypass` lets staff open, take +from and break anything a player has claimed. + `/tt admin` opens the panel itself, and `economy`, `shops` or `storage` opens that section directly. Opening the panel needs `tritown.admin`; the sections need `tritown.admin.economy`, `tritown.admin.shops` and `tritown.admin.storage` on top of it. @@ -225,6 +236,9 @@ version stays available as `/tritown:balance` and so on. | `storage.save-interval` | `30` | Seconds between writing changed storages; closing one writes it at once | | `storage.lock-containers.enabled` | `true` | Make containers decoration: withdraw-only, and closed once empty | | `storage.lock-containers.` | `true` | Each of `chests`, `shulker-boxes` and `ender-chest` on its own | +| `item-protection.enabled` | `true` | Items only change hands through a trade | +| `item-protection.disabled-worlds` | `[]` | Worlds where nothing is protected | +| `item-protection.` | `true` | Each of `drops`, `actions`, `mob-loot`, `projectiles`, `containers`, `entities`, `explosion-guard` | | `towns.founding-credit` | `100.0` | Credit only `/t new` can spend, given once to players without a town; `0` is off | | `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 | diff --git a/docs/DEVELOPER_GUIDE.md b/docs/DEVELOPER_GUIDE.md index 4ea700e..541a3b5 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**, the **news** 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** 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. @@ -3153,6 +3153,130 @@ Each group has its own switch under `storage.lock-containers`, the whole lock fo storage files. +## Item Protection + +Items belong to the player who has them, and the only way to hand one to another player is a [trade](#player-trades). +The core lives in `protection/`, outside the scan. The listeners are in `listeners/protection/` and the admin command +is `commands/protection/ProtectionCommand`. + +### The model + +**An item in an inventory is never marked.** It is its holder's by being there, so stacks merge as usual and the +trade, shop and storage code never think about ownership. Ownership is recorded only once an item leaves a player: + +- **On the ground**, as the dropped `Item`'s own owner field (`Item#setOwner`). The game saves it with the entity, + refuses a pickup by anyone else, and will not merge two drops with different owners. `ItemOwnership` is the only + place that sets it. +- **In a container or entity holder**, as a claim: the owner's UUID under `tritown:claim` in the holder's persistent + data. `Claims` is the only thing that reads or writes one. + +Public items are the ones the world drops by itself, plus every player's death drops: leaf decay, water and piston +farms, explosions nobody owns. + +### Dropped items + +| Where it comes from | Who owns it | +|:--------------------|:------------| +| `PlayerDropItemEvent`, and any spawn whose thrower is an online player | The dropper | +| `BlockDropItemEvent` (mining, breaking crops) | The breaker, or the block's claimant if it was a claimed container | +| `EntityDeathEvent` (not players) | The mob's claimant, else its `killer` (which covers bows and tamed pets) | +| Right-clicking a block or an entity, shearing, `BlockDispenseLootEvent` | The player | +| `PlayerFishEvent` (`CAUGHT_FISH`) | The angler | +| A claimed dispenser, dropper, crafter or campfire | The claimant | +| `EntityDropItemEvent` from a claimed entity | The claimant | +| `PiglinBarterEvent` | Whoever threw the gold, recorded on the piglin as it picks it up | +| `PlayerDeathEvent` | Nobody: a suppression window keeps them public | + +Most of these drops do not exist yet when the event names the player, so the event opens a **window** at the spot +through `ItemOwnership.expect(location, owner)`, and `ItemSpawnEvent` claims it. `DropWindows` holds the windows. It is +plain Kotlin, tested in `DropWindowsTest`. A window matches spawns within two blocks, in the tick it was opened and +the next. The nearest window wins, and a suppression beats all of them. + +**Never stamp an `ItemStack` to carry an owner.** A mark nothing stripped would follow the item into an inventory and +stop it stacking with its twins. + +`EntityPickupItemEvent` refuses every entity but the owner: allays, foxes, villagers and zombies included. The one +exception is a piglin taking its barter material. `PlayerPickupArrowEvent` only lets the shooter pick an arrow or +trident back up. + +**Handing a player items the plugin gives them** goes through `InventoryUtil.give`, whose overflow is dropped with +`ItemOwnership.dropFor(player, stack)`. Never drop an item meant for a player with `dropItemNaturally` alone. + +### Claims + +`Claims.of(inventory | block | entity)` gives a `ClaimHolder`, or `null` for anything that is not one: + +- Every block entity with an inventory: furnaces, hoppers, droppers, dispensers, brewing stands, crafters, barrels, + chests (both halves answer to the left one's claim), shulker boxes, decorated pots, chiseled bookshelves, shelves, + jukeboxes, lecterns. +- Campfires. +- Item frames, armor stands and allays. +- Mobs that are not `Enemy` and can wear a saddle or body armour, including a chested horse's inventory. +- Minecarts and boats with an inventory. + +It is never kept, and it is never built for a holderless inventory (TriTown's menus), the ender chest, a player or a +villager. + +**Claims are read lazily.** `Claims.ownerOf(holder)` clears a claim on a holder that is *vacant*: empty, with nobody +viewing it. No task ever releases one, and a shared furnace is free the moment its owner takes the last item out. A +viewer keeps even an empty claim alive, or a hopper could claim the container out from under them. `Claims.recorded` +reads a claim without that check. It is for what a destroyed block or entity leaves behind, when its contents can no +longer be counted. + +Blocks are read through `getState(false)`, the live block entity, so a claim is written without `update()`. Only +the items inside make a claim worth anything, and moving them is what marks the chunk to be saved. + +The rules, in `ContainerProtectionListener` and `EntityProtectionListener`: + +- Opening a free container claims it for the opener. Only one non-bypass viewer may have a free container open. + Closing an empty one releases it. +- `InventoryMoveItemEvent` / `InventoryPickupItemEvent`: an owned item may enter a free holder, which becomes the + owner's, or the owner's own. Anything else is cancelled. A public source never changes a destination's owner. A copper + golem never targets a claimed block. +- A non-owner cannot break, blow up or shoot apart a claimed holder, destroy a claimed minecart, take a lectern's book, + or right-click a claimed interaction block, frame, stand or mob. `explosion-guard` removes claimed containers from an + explosion's block list. +- A frame, stand or mob is claimed when an item goes on. For stands and mobs that is read a tick later, because the + item lands after the event. + +`Protection.settings(world)` returns the settings, or `null` when protection is off or off in that world. Every +handler asks it first. `tritown.protection.bypass` (`Protection.BYPASS_PERMISSION`) exempts a player from every claim. +Vanilla's own pickup check still applies to them, because it runs before any event. + +`/tritown protection inspect|release` (`tritown.protection.admin`) shows or clears the claim on the block or entity in +the crosshair. + +### Adding a way for items to leave a player + +Any new feature that spills items into the world, or lets something hold a player's items, has to say whose they are: + +1. **A drop the feature makes itself**: use `ItemOwnership.dropFor`, or `bind` the `Item` it creates. +2. **A drop the game makes a moment later**: call `ItemOwnership.expect` from the event that names the player. +3. **A new kind of holder**: teach `Claims.of` to recognise it, and refuse non-owners on every event that reaches + inside it. + +### Known gaps + +- Flower pots and composters have no block entity to hold a claim, so they are left alone. +- Leads dropped from a broken fence knot are public. +- Death drops are public on purpose, so a player can still give their items away by dying next to someone. + +### Settings + +| Key | What it does | +|:----------------------------------|:----------------------------------------------------------------------| +| `item-protection.enabled` | Everything below | +| `item-protection.disabled-worlds` | Worlds, by name, where nothing is protected | +| `item-protection.drops` | Player drops are the dropper's | +| `item-protection.actions` | Mining, harvesting, shearing, fishing and loot credit the player | +| `item-protection.mob-loot` | A mob's loot is its killer's | +| `item-protection.projectiles` | Only the shooter picks an arrow or trident back up | +| `item-protection.containers` | Containers and interaction blocks are claimed by whoever fills them | +| `item-protection.entities` | Frames, stands, allays and equipped mobs are claimed the same way | +| `item-protection.explosion-guard` | Explosions and mobs leave claimed containers standing | + +`ProtectionSettings` is a snapshot swapped in whole on a reload. + ## Server News Update notes for the server. Administrators write a post in game — a title, an optional summary and label, and diff --git a/docs/UTILITY_GUIDE.md b/docs/UTILITY_GUIDE.md index dcceb4e..ec871c8 100644 --- a/docs/UTILITY_GUIDE.md +++ b/docs/UTILITY_GUIDE.md @@ -928,7 +928,7 @@ InventoryUtil.give(player, goods) | Method | Return | Description | |:---------------------------|:------------------|:-------------------------------------------------------------------------------| | `hasSpaceFor(player, items)` | `Boolean` | Whether every stack would fit, tested against a copy of the player's storage | -| `give(player, items)` | `Unit` | Adds the stacks, dropping at the player's feet whatever will not fit | +| `give(player, items)` | `Unit` | Adds the stacks, dropping what will not fit at the player's feet, as theirs | | `split(items)` | `List` | Breaks oversized stacks down into ones the game allows | ### Behavior Details @@ -939,6 +939,8 @@ InventoryUtil.give(player, goods) `hasSpaceFor` and `give` run their input through `split` first. - **Nothing is ever lost**: `give` drops what will not fit rather than discarding it. Check `hasSpaceFor` beforehand and a drop only happens when something else filled the inventory in between. +- **Nobody else can take the drop**: overflow goes through `ItemOwnership.dropFor`, so it belongs to the player it was + meant for (see [Item Protection](DEVELOPER_GUIDE.md#item-protection)). --- 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 147e081..a66b908 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/Main.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/Main.kt @@ -109,6 +109,7 @@ class Main : JavaPlugin() { TradeSettings.load(pluginConfig) TownSettings.load(pluginConfig) + ProtectionSettings.load(pluginConfig) MainMenuSettings.load(pluginConfig, logger) // Before the registrars, like the shops: the main menu reads a player's storage as it is drawn. @@ -162,6 +163,7 @@ class Main : JavaPlugin() { TradeSettings.load(pluginConfig) TownSettings.load(pluginConfig) + ProtectionSettings.load(pluginConfig) // Only the settings, as with the shops: the storage files are never re-read while players hold them open. StorageSettings.load(pluginConfig) // Only the settings, as with the shops: every change to a post is already on disk. diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/protection/ProtectionCommand.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/protection/ProtectionCommand.kt new file mode 100644 index 0000000..5c47cd6 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/protection/ProtectionCommand.kt @@ -0,0 +1,72 @@ +package net.trilleo.mc.plugins.tritown.commands.protection + +import net.trilleo.mc.plugins.tritown.protection.ClaimHolder +import net.trilleo.mc.plugins.tritown.protection.Claims +import net.trilleo.mc.plugins.tritown.protection.Protection +import net.trilleo.mc.plugins.tritown.registration.PluginCommand +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.command.CommandSender +import org.bukkit.entity.Player + +/** + * Who owns the container or entity an administrator is looking at, and + * clearing that claim, say when a player left a furnace full and quit for good. + */ +class ProtectionCommand : PluginCommand( + name = "protection", + description = "See or clear who owns a container or entity", + usage = "/tritown protection ", + permission = Protection.ADMIN_PERMISSION, +) { + + override val extraPermissions = listOf(Protection.BYPASS_PERMISSION) + + override fun execute(sender: CommandSender, args: Array): Boolean { + val player = sender as? Player ?: run { + sender.sendPrefixed(sender.tr("command.protection.players-only")) + return true + } + val action = args.firstOrNull()?.lowercase() + if (action != INSPECT && action != RELEASE) { + player.sendPrefixed(player.tr("command.protection.usage")) + return true + } + + val holder = target(player) ?: run { + player.sendPrefixed(player.tr("common.error", "message" to player.tr("command.protection.no-target"))) + return true + } + val owner = Claims.ownerOf(holder) + + when { + owner == null -> player.sendPrefixed(player.tr("command.protection.public")) + action == INSPECT -> player.sendPrefixed( + player.tr("command.protection.owner", "name" to ComponentUtil.escape(Protection.nameOf(owner))) + ) + + else -> { + Claims.release(holder) + player.sendPrefixed( + player.tr("command.protection.released", "name" to ComponentUtil.escape(Protection.nameOf(owner))) + ) + } + } + return true + } + + override fun tabComplete(sender: CommandSender, args: Array): List = + if (args.size == 1) listOf(INSPECT, RELEASE).filter { it.startsWith(args[0], ignoreCase = true) } else emptyList() + + /** The entity in the crosshair if there is one, the block otherwise. */ + private fun target(player: Player): ClaimHolder? = + player.getTargetEntity(REACH)?.let(Claims::of) + ?: player.getTargetBlockExact(REACH)?.let(Claims::of) + + private companion object { + const val INSPECT = "inspect" + const val RELEASE = "release" + const val REACH = 6 + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/ProtectionSettings.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/ProtectionSettings.kt new file mode 100644 index 0000000..8f981e2 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/ProtectionSettings.kt @@ -0,0 +1,59 @@ +package net.trilleo.mc.plugins.tritown.config + +/** + * An immutable snapshot of the `item-protection` block of `config.yml`. + * + * Built whole and swapped in on a reload, the same way [TradeSettings] is, so a + * hopper moving items while the configuration is re-read cannot see half of it. + * + * @param enabled whether items are protected at all + * @param disabledWorlds worlds, by name, where nothing is protected + * @param drops whether what a player drops belongs to them + * @param actions whether what a player mines, harvests, shears or fishes up belongs to them + * @param mobLoot whether a mob's loot belongs to the player who killed it + * @param projectiles whether only the shooter may pick an arrow or trident back up + * @param containers whether a container belongs to whoever fills it, for as long as it holds anything + * @param entities whether item frames, armor stands, allays and equipped mobs belong to whoever filled them + * @param explosionGuard whether explosions leave claimed containers standing + */ +data class ProtectionSettings( + val enabled: Boolean, + val disabledWorlds: Set, + val drops: Boolean, + val actions: Boolean, + val mobLoot: Boolean, + val projectiles: Boolean, + val containers: Boolean, + val entities: Boolean, + val explosionGuard: Boolean, +) { + + companion object { + + @Volatile + private var current: ProtectionSettings? = null + + /** The settings in force. */ + val snapshot: ProtectionSettings + get() = current ?: error("Item protection settings have not been loaded yet") + + /** Whether [load] has run. */ + val isLoaded: Boolean + get() = current != null + + /** Reads the `item-protection` block from [config] and makes it the current snapshot. */ + fun load(config: PluginConfig): ProtectionSettings = read(config).also { current = it } + + private fun read(config: PluginConfig): ProtectionSettings = ProtectionSettings( + enabled = config.getBoolean("item-protection.enabled", true), + disabledWorlds = config.getStringList("item-protection.disabled-worlds").map { it.lowercase() }.toSet(), + drops = config.getBoolean("item-protection.drops", true), + actions = config.getBoolean("item-protection.actions", true), + mobLoot = config.getBoolean("item-protection.mob-loot", true), + projectiles = config.getBoolean("item-protection.projectiles", true), + containers = config.getBoolean("item-protection.containers", true), + entities = config.getBoolean("item-protection.entities", true), + explosionGuard = config.getBoolean("item-protection.explosion-guard", true), + ) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/ActionDropListener.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/ActionDropListener.kt new file mode 100644 index 0000000..df5b70c --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/ActionDropListener.kt @@ -0,0 +1,107 @@ +package net.trilleo.mc.plugins.tritown.listeners.protection + +import net.trilleo.mc.plugins.tritown.protection.Claims +import net.trilleo.mc.plugins.tritown.protection.ItemOwnership +import net.trilleo.mc.plugins.tritown.protection.Protection +import org.bukkit.block.TileState +import org.bukkit.entity.Item +import org.bukkit.entity.Player +import org.bukkit.event.EventHandler +import org.bukkit.event.EventPriority +import org.bukkit.event.Event +import org.bukkit.event.Listener +import org.bukkit.event.block.Action +import org.bukkit.event.block.BlockDispenseLootEvent +import org.bukkit.event.block.BlockDropItemEvent +import org.bukkit.event.entity.EntityDeathEvent +import org.bukkit.event.entity.EntityDropItemEvent +import org.bukkit.event.player.PlayerFishEvent +import org.bukkit.event.player.PlayerInteractEntityEvent +import org.bukkit.event.player.PlayerInteractEvent +import org.bukkit.event.player.PlayerShearEntityEvent + +/** + * Credits a drop to the player whose action produced it: mining, farming, + * shearing, fishing, killing a mob, opening a vault. + * + * Where the drops already exist as entities, they are bound on the spot. + * Everywhere else a window is opened at the spot and the spawn claims it (see + * [ItemOwnership.expect]). Anything a claimed holder leaves behind goes to its + * claimant rather than to whoever broke or killed it. + */ +class ActionDropListener : Listener { + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + fun onBlockDrop(event: BlockDropItemEvent) { + val settings = Protection.settings(event.block.world) ?: return + val claimant = if (settings.containers) { + (event.blockState as? TileState)?.let { Claims.recorded(it.persistentDataContainer) } + } else null + val owner = claimant ?: event.player.uniqueId.takeIf { settings.actions } ?: return + + event.items.forEach { ItemOwnership.bind(it, owner) } + // A container's contents are spilled by the block itself, and may not come through this event. + ItemOwnership.expect(event.block, owner) + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + fun onDeath(event: EntityDeathEvent) { + val entity = event.entity + if (entity is Player) return + val settings = Protection.settings(entity.world) ?: return + + val claimant = if (settings.entities) Claims.recorded(entity.persistentDataContainer) else null + val owner = claimant ?: entity.killer?.uniqueId?.takeIf { settings.mobLoot } ?: return + ItemOwnership.expect(entity.location, owner) + } + + /** What an entity drops by itself — a frame's item, an allay's — is its claimant's. */ + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + fun onEntityDrop(event: EntityDropItemEvent) { + val settings = Protection.settings(event.entity.world) ?: return + if (!settings.entities || event.itemDrop.owner != null) return + Claims.recorded(event.entity.persistentDataContainer)?.let { ItemOwnership.bind(event.itemDrop, it) } + } + + /** + * Everything a right-click can knock loose: berries, glow berries, honeycomb, + * pumpkin seeds, bone meal from a composter, brushing. + */ + @EventHandler(priority = EventPriority.MONITOR) + fun onInteractBlock(event: PlayerInteractEvent) { + if (event.action != Action.RIGHT_CLICK_BLOCK || event.useInteractedBlock() == Event.Result.DENY) return + val block = event.clickedBlock ?: return + if (Protection.settings(block.world)?.actions != true) return + ItemOwnership.expect(block, event.player.uniqueId) + } + + /** A scute brushed off an armadillo, a bowl of stew milked from a mooshroom. */ + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + fun onInteractEntity(event: PlayerInteractEntityEvent) { + val entity = event.rightClicked + if (Protection.settings(entity.world)?.actions != true) return + ItemOwnership.expect(entity.location, event.player.uniqueId) + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + fun onShear(event: PlayerShearEntityEvent) { + val entity = event.entity + if (Protection.settings(entity.world)?.actions != true) return + ItemOwnership.expect(entity.location, event.player.uniqueId) + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + fun onFish(event: PlayerFishEvent) { + if (event.state != PlayerFishEvent.State.CAUGHT_FISH) return + if (Protection.settings(event.player.world)?.actions != true) return + (event.caught as? Item)?.let { ItemOwnership.bind(it, event.player.uniqueId) } + } + + /** A vault's or trial spawner's reward. */ + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + fun onLoot(event: BlockDispenseLootEvent) { + val player = event.player ?: return + if (Protection.settings(event.block.world)?.actions != true) return + ItemOwnership.expect(event.block, player.uniqueId) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/ContainerProtectionListener.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/ContainerProtectionListener.kt new file mode 100644 index 0000000..dd5deee --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/ContainerProtectionListener.kt @@ -0,0 +1,248 @@ +package net.trilleo.mc.plugins.tritown.listeners.protection + +import io.papermc.paper.event.entity.ItemTransportingEntityValidateTargetEvent +import io.papermc.paper.event.player.PlayerInsertLecternBookEvent +import net.trilleo.mc.plugins.tritown.protection.ClaimHolder +import net.trilleo.mc.plugins.tritown.protection.Claims +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.block.* +import org.bukkit.entity.Player +import org.bukkit.event.Event +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.inventory.InventoryCloseEvent +import org.bukkit.event.inventory.InventoryMoveItemEvent +import org.bukkit.event.inventory.InventoryOpenEvent +import org.bukkit.event.inventory.InventoryPickupItemEvent +import org.bukkit.event.player.PlayerInteractEvent +import org.bukkit.event.player.PlayerTakeLecternBookEvent +import org.bukkit.event.vehicle.VehicleDestroyEvent + +/** + * Containers belong to whoever fills them, for as long as they hold anything. + * + * Only the owner can open, feed, empty or break a claimed container. One + * player at a time can have a free one open, and opening it claims it, so a + * hopper cannot slip somebody else's items in while a viewer is taking things + * out. Hoppers carry the owner along with the items: X's items can fill a free + * container, which becomes X's, but never one that Y holds. + * + * Interaction blocks — decorated pots, chiseled bookshelves, shelves, + * jukeboxes and campfires — follow the same rule through right-clicks. A lectern + * can still be read by anyone. Only taking its book is the owner's. + */ +class ContainerProtectionListener : Listener { + + // ── Opening ───────────────────────────────────────────────────────── + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) + fun onOpen(event: InventoryOpenEvent) { + val player = event.player as? Player ?: return + if (Protection.settings(player.world)?.containers != true) return + if (event.inventory.getHolder(false) is Lectern || Protection.bypasses(player)) return + val holder = Claims.of(event.inventory) ?: return + + // Asked before the owner, because reading the owner of an empty holder nobody else is viewing releases it. + val inUse = event.inventory.viewers.any { it != player && it is Player && !Protection.bypasses(it) } + val owner = if (inUse) Claims.recorded(holder) else Claims.ownerOf(holder) + if (Protection.refuses(player, owner)) { + event.isCancelled = true + Protection.hintOwned(player, owner!!) + } else if (inUse) { + event.isCancelled = true + Protection.hint(player, player.tr("protection.hint.in-use")) + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + fun onOpened(event: InventoryOpenEvent) { + val player = event.player as? Player ?: return + if (Protection.settings(player.world)?.containers != true || Protection.bypasses(player)) return + if (event.inventory.getHolder(false) is Lectern) return + val holder = Claims.of(event.inventory) ?: return + if (Claims.ownerOf(holder) == null) Claims.claim(holder, player.uniqueId) + } + + @EventHandler + fun onClose(event: InventoryCloseEvent) { + if (!event.inventory.isEmpty) return + Claims.of(event.inventory)?.let(Claims::release) + } + + // ── Hoppers, droppers and hopper minecarts ────────────────────────── + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) + fun onMove(event: InventoryMoveItemEvent) { + // Cheapest first: most moves are between holders nobody has claimed. + val source = Claims.of(event.source) ?: return + val from = Claims.ownerOf(source) ?: return + val world = source.location.world ?: return + if (Protection.settings(world)?.containers != true) return + + val destination = Claims.of(event.destination) ?: return + if (!accept(destination, from)) event.isCancelled = true + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) + fun onHopperPickup(event: InventoryPickupItemEvent) { + val from = event.item.owner ?: return + if (Protection.settings(event.item.world)?.containers != true) return + + val destination = Claims.of(event.inventory) + if (destination == null || !accept(destination, from)) event.isCancelled = true + } + + /** Whether [owner]'s items may go into [destination], claiming it for them if nobody holds it. */ + private fun accept(destination: ClaimHolder, owner: java.util.UUID): Boolean { + val holder = Claims.ownerOf(destination) + if (holder == null) Claims.claim(destination, owner) + return holder == null || holder == owner + } + + /** A copper golem never carries items out of, or into, something a player holds. */ + @EventHandler + fun onGolemTarget(event: ItemTransportingEntityValidateTargetEvent) { + if (!event.isAllowed || Protection.settings(event.block.world)?.containers != true) return + val holder = Claims.of(event.block) ?: return + if (Claims.ownerOf(holder) != null) event.isAllowed = false + } + + // ── Breaking, placing and blowing up ──────────────────────────────── + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) + fun onBreak(event: BlockBreakEvent) { + val player = event.player + if (Protection.settings(player.world)?.containers != true) return + val holder = Claims.of(event.block) ?: return + val owner = Claims.ownerOf(holder) + if (!Protection.refuses(player, owner)) return + event.isCancelled = true + Protection.hintOwned(player, owner!!) + } + + /** A block placed with items already inside it, such as a filled shulker box, is its placer's. */ + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + fun onPlace(event: BlockPlaceEvent) { + if (Protection.settings(event.player.world)?.containers != true) return + val holder = Claims.of(event.blockPlaced) ?: return + if (holder.isVacant()) Claims.release(holder) else Claims.claim(holder, event.player.uniqueId) + } + + @EventHandler(ignoreCancelled = true) + fun onEntityExplode(event: EntityExplodeEvent) { + if (Protection.settings(event.entity.world)?.explosionGuard != true) return + event.blockList().removeIf(::isHeld) + } + + @EventHandler(ignoreCancelled = true) + fun onBlockExplode(event: BlockExplodeEvent) { + if (Protection.settings(event.block.world)?.explosionGuard != true) return + event.blockList().removeIf(::isHeld) + } + + /** An arrow through a decorated pot, a wither chewing through a furnace. */ + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) + fun onEntityChangeBlock(event: EntityChangeBlockEvent) { + if (event.entity is Player) return + val settings = Protection.settings(event.block.world) ?: return + if (!settings.containers) return + val holder = Claims.of(event.block) ?: return + val owner = Claims.ownerOf(holder) ?: return + + val player = Protection.responsible(event.entity) + if (if (player != null) Protection.refuses(player, owner) else settings.explosionGuard) event.isCancelled = true + } + + private fun isHeld(block: Block): Boolean = Claims.of(block)?.let(Claims::ownerOf) != null + + // ── Minecarts and boats ───────────────────────────────────────────── + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) + fun onVehicleDestroy(event: VehicleDestroyEvent) { + val vehicle = event.vehicle + if (Protection.settings(vehicle.world)?.containers != true) return + val holder = Claims.of(vehicle) ?: return + val owner = Claims.ownerOf(holder) ?: return + + val player = Protection.responsible(event.attacker) + if (player != null && Protection.refuses(player, owner)) { + event.isCancelled = true + Protection.hintOwned(player, owner) + return + } + ItemOwnership.expect(vehicle.location, owner) + } + + // ── What a claimed block produces ─────────────────────────────────── + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + fun onDispense(event: BlockDispenseEvent) = expectFromClaimant(event.block) + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + fun onCraft(event: CrafterCraftEvent) = expectFromClaimant(event.block) + + /** A campfire drops what it has finished cooking. */ + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + fun onCook(event: BlockCookEvent) { + if (event.block.getState(false) is Campfire) expectFromClaimant(event.block) + } + + private fun expectFromClaimant(block: Block) { + if (Protection.settings(block.world)?.containers != true) return + val holder = Claims.of(block) ?: return + Claims.ownerOf(holder)?.let { ItemOwnership.expect(block, it) } + } + + // ── Interaction blocks ────────────────────────────────────────────── + + @EventHandler(priority = EventPriority.LOW) + fun onInteract(event: PlayerInteractEvent) { + val block = interactionBlock(event) ?: return + val holder = Claims.of(block) ?: return + val owner = Claims.ownerOf(holder) + if (!Protection.refuses(event.player, owner)) return + + event.setUseInteractedBlock(Event.Result.DENY) + event.setUseItemInHand(Event.Result.DENY) + Protection.hintOwned(event.player, owner!!) + } + + /** Claimed on the click, before the item goes in; if nothing does, the next reader lets the claim go. */ + @EventHandler(priority = EventPriority.MONITOR) + fun onInteracted(event: PlayerInteractEvent) { + if (event.useInteractedBlock() == Event.Result.DENY || Protection.bypasses(event.player)) return + val block = interactionBlock(event) ?: return + val holder = Claims.of(block) ?: return + if (Claims.ownerOf(holder) == null) Claims.claim(holder, event.player.uniqueId) + } + + private fun interactionBlock(event: PlayerInteractEvent): Block? { + if (event.action != org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK) return null + val block = event.clickedBlock ?: return null + if (Protection.settings(block.world)?.containers != true) return null + return block.takeIf { block.getState(false).let { it is DecoratedPot || it is ChiseledBookshelf || it is Shelf || it is Jukebox || it is Campfire } } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + fun onLecternInsert(event: PlayerInsertLecternBookEvent) { + if (Protection.settings(event.block.world)?.containers != true || Protection.bypasses(event.player)) return + Claims.of(event.block)?.let { Claims.claim(it, event.player.uniqueId) } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) + fun onLecternTake(event: PlayerTakeLecternBookEvent) { + val player = event.player + if (Protection.settings(player.world)?.containers != true) return + val holder = Claims.of(event.lectern.block) ?: return + val owner = Claims.ownerOf(holder) + if (!Protection.refuses(player, owner)) return + event.isCancelled = true + Protection.hintOwned(player, owner!!) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/DropProtectionListener.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/DropProtectionListener.kt new file mode 100644 index 0000000..215541a --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/DropProtectionListener.kt @@ -0,0 +1,134 @@ +package net.trilleo.mc.plugins.tritown.listeners.protection + +import net.trilleo.mc.plugins.tritown.protection.DropWindows +import net.trilleo.mc.plugins.tritown.protection.ItemOwnership +import net.trilleo.mc.plugins.tritown.protection.Protection +import org.bukkit.Bukkit +import org.bukkit.NamespacedKey +import org.bukkit.entity.Piglin +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.PlayerDropItemEvent +import org.bukkit.event.player.PlayerPickupArrowEvent +import org.bukkit.event.player.PlayerQuitEvent +import org.bukkit.persistence.PersistentDataType +import java.util.* + +/** + * Items on the ground: who they belong to, and who may pick them up. + * + * What a player drops is theirs, and so is whatever an action of theirs + * produced (see [ActionDropListener]). Death drops, and anything the world drops + * by itself, are public. Only the owner can pick up an owned item. No mob, + * allay or fox can either, except that a piglin still takes gold to barter with + * and pays the thrower back. + */ +class DropProtectionListener : Listener { + + // ── Giving a drop its owner ───────────────────────────────────────── + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + fun onDrop(event: PlayerDropItemEvent) { + val settings = Protection.settings(event.player.world) ?: return + if (settings.drops) ItemOwnership.bind(event.itemDrop, event.player.uniqueId) + } + + /** A death's drops stay public, even when the killer's window reaches them. */ + @EventHandler(priority = EventPriority.LOWEST) + fun onDeath(event: PlayerDeathEvent) { + if (Protection.settings(event.player.world) == null) return + ItemOwnership.suppress(event.player.location) + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) + fun onSpawn(event: ItemSpawnEvent) { + val item = event.entity + if (item.owner != null) return + val settings = Protection.settings(item.world) ?: return + + when (val match = ItemOwnership.match(item.location)) { + DropWindows.Match.Public -> return + is DropWindows.Match.Owned -> return ItemOwnership.bind(item, match.owner) + DropWindows.Match.None -> Unit + } + + // Whatever a player threw that no event above saw, such as what a closed crafting grid spills. + val thrower = item.thrower ?: return + if (settings.drops && Bukkit.getPlayer(thrower) != null) ItemOwnership.bind(item, thrower) + } + + // ── Picking up ────────────────────────────────────────────────────── + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + fun onPickup(event: EntityPickupItemEvent) { + val owner = event.item.owner ?: return + val entity = event.entity + + // The game already refuses anyone but the owner; this covers a plugin that lets it through. + if (entity is Player) { + if (entity.uniqueId != owner) event.isCancelled = true + return + } + + if (entity is Piglin && event.item.itemStack.type in entity.barterList) { + entity.persistentDataContainer.set(BARTER_OWNER, PersistentDataType.STRING, owner.toString()) + return + } + event.isCancelled = true + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + fun onBarter(event: PiglinBarterEvent) { + val piglin = event.entity + val owner = barterOwner(piglin) ?: return + piglin.persistentDataContainer.remove(BARTER_OWNER) + ItemOwnership.expect(piglin.location, owner) + } + + /** Gold a piglin was still holding when it died goes back to whoever threw it, not to the killer. */ + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) + fun onPiglinDeath(event: EntityDeathEvent) { + val piglin = event.entity as? Piglin ?: return + val owner = barterOwner(piglin) ?: return + if (piglin.killer?.uniqueId == owner) return + + val held = piglin.equipment.itemInOffHand + if (held.isEmpty) return + val index = event.drops.indexOfFirst { it.isSimilar(held) } + if (index < 0) return + val stack = event.drops.removeAt(index) + piglin.world.dropItemNaturally(piglin.location, stack) { ItemOwnership.bind(it, owner) } + } + + @EventHandler(ignoreCancelled = true) + fun onMerge(event: ItemMergeEvent) { + if (event.entity.owner != event.target.owner) event.isCancelled = true + } + + /** An arrow or trident only goes back to whoever fired it. */ + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + fun onArrowPickup(event: PlayerPickupArrowEvent) { + val settings = Protection.settings(event.player.world) ?: return + if (!settings.projectiles) return + + val shooter = event.arrow.ownerUniqueId ?: return + if (shooter == event.player.uniqueId) return + if (Bukkit.getOfflinePlayer(shooter).hasPlayedBefore()) event.isCancelled = true + } + + @EventHandler + fun onQuit(event: PlayerQuitEvent) { + Protection.forget(event.player) + } + + private fun barterOwner(piglin: Piglin): UUID? = + piglin.persistentDataContainer.get(BARTER_OWNER, PersistentDataType.STRING) + ?.let { runCatching { UUID.fromString(it) }.getOrNull() } + + private companion object { + val BARTER_OWNER = NamespacedKey("tritown", "barter_owner") + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/EntityProtectionListener.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/EntityProtectionListener.kt new file mode 100644 index 0000000..4fbc639 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/EntityProtectionListener.kt @@ -0,0 +1,135 @@ +package net.trilleo.mc.plugins.tritown.listeners.protection + +import io.papermc.paper.event.player.PlayerItemFrameChangeEvent +import net.trilleo.mc.plugins.tritown.Main +import net.trilleo.mc.plugins.tritown.protection.Claims +import net.trilleo.mc.plugins.tritown.protection.ItemOwnership +import net.trilleo.mc.plugins.tritown.protection.Protection +import org.bukkit.entity.ArmorStand +import org.bukkit.entity.Entity +import org.bukkit.entity.ItemFrame +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.BlockShearEntityEvent +import org.bukkit.event.entity.EntityDamageByEntityEvent +import org.bukkit.event.hanging.HangingBreakByEntityEvent +import org.bukkit.event.player.PlayerArmorStandManipulateEvent +import org.bukkit.event.player.PlayerInteractEntityEvent + +/** + * Entities that hold a player's items: item frames, armor stands, allays, and + * mobs a player has saddled, armoured or given a chest. + * + * Each belongs to whoever put the item there, for as long as it holds one. + * Nobody else can take the item, shear it off, knock it loose or break what + * holds it. What the entity drops when it is destroyed anyway goes to its + * owner (see [ActionDropListener]). + */ +class EntityProtectionListener : Listener { + + // ── Item frames ───────────────────────────────────────────────────── + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) + fun onFrameChange(event: PlayerItemFrameChangeEvent) { + if (event.action == PlayerItemFrameChangeEvent.ItemFrameChangeAction.PLACE) return + refuse(event.player, event.itemFrame) { event.isCancelled = true } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + fun onFramePlaced(event: PlayerItemFrameChangeEvent) { + if (event.action != PlayerItemFrameChangeEvent.ItemFrameChangeAction.PLACE) return + claimFor(event.player, event.itemFrame) + } + + /** A frame's item knocked loose by a hit, or a stand struck down. */ + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) + fun onDamage(event: EntityDamageByEntityEvent) { + val entity = event.entity + if (entity !is ItemFrame && entity !is ArmorStand) return + val player = Protection.responsible(event.damager) ?: return + refuse(player, entity) { event.isCancelled = true } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) + fun onHangingBreak(event: HangingBreakByEntityEvent) { + val player = Protection.responsible(event.remover) ?: return + refuse(player, event.entity) { event.isCancelled = true } + } + + /** Whatever the frame drops as its breaker takes it down is theirs, when nobody claimed it. */ + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + fun onHangingBroken(event: HangingBreakByEntityEvent) { + val player = Protection.responsible(event.remover) ?: return + if (Protection.settings(player.world)?.actions != true) return + ItemOwnership.expect(event.entity.location, player.uniqueId) + } + + // ── Armor stands ──────────────────────────────────────────────────── + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) + fun onManipulate(event: PlayerArmorStandManipulateEvent) { + refuse(event.player, event.rightClicked) { event.isCancelled = true } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + fun onManipulated(event: PlayerArmorStandManipulateEvent) { + claimNextTick(event.player, event.rightClicked) + } + + // ── Allays and mounts ─────────────────────────────────────────────── + + /** Riding, feeding, opening or shearing a mob someone else has equipped. */ + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) + fun onInteract(event: PlayerInteractEntityEvent) { + val entity = event.rightClicked + if (entity is ItemFrame || entity is ArmorStand || entity is Player) return + refuse(event.player, entity) { event.isCancelled = true } + } + + /** The item goes on after the event, so whether anything did is read a tick later. */ + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + fun onInteracted(event: PlayerInteractEntityEvent) { + val entity = event.rightClicked + if (entity is ItemFrame || entity is ArmorStand || entity is Player) return + claimNextTick(event.player, entity) + } + + /** A dispenser's shears only take a saddle off a mob whose owner also holds the dispenser. */ + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) + fun onDispenserShear(event: BlockShearEntityEvent) { + if (Protection.settings(event.entity.world)?.entities != true) return + val holder = Claims.of(event.entity) ?: return + val owner = Claims.ownerOf(holder) ?: return + val dispenser = Claims.of(event.block)?.let(Claims::ownerOf) + if (dispenser != owner) event.isCancelled = true + } + + // ── Shared ────────────────────────────────────────────────────────── + + private inline fun refuse(player: Player, entity: Entity, cancel: () -> Unit) { + if (Protection.settings(entity.world)?.entities != true) return + val holder = Claims.of(entity) ?: return + val owner = Claims.ownerOf(holder) + if (!Protection.refuses(player, owner)) return + cancel() + Protection.hintOwned(player, owner!!) + } + + private fun claimFor(player: Player, entity: Entity) { + if (Protection.settings(entity.world)?.entities != true || Protection.bypasses(player)) return + val holder = Claims.of(entity) ?: return + if (Claims.ownerOf(holder) == null) Claims.claim(holder, player.uniqueId) + } + + private fun claimNextTick(player: Player, entity: Entity) { + if (Protection.settings(entity.world)?.entities != true || Protection.bypasses(player)) return + if (Claims.of(entity) == null) return + val owner = player.uniqueId + entity.scheduler.run(Main.instance, { + val holder = Claims.of(entity) ?: return@run + if (Claims.ownerOf(holder) == null && !holder.isVacant()) Claims.claim(holder, owner) + }, null) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/menu/MenuItem.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/menu/MenuItem.kt index 5e47ce2..c2a9a2a 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/menu/MenuItem.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/menu/MenuItem.kt @@ -3,6 +3,7 @@ package net.trilleo.mc.plugins.tritown.menu import net.trilleo.mc.plugins.tritown.Main import net.trilleo.mc.plugins.tritown.config.MainMenuSettings import net.trilleo.mc.plugins.tritown.news.NewsReadState +import net.trilleo.mc.plugins.tritown.protection.ItemOwnership import net.trilleo.mc.plugins.tritown.registration.PluginItem import net.trilleo.mc.plugins.tritown.utils.LoreUtil import net.trilleo.mc.plugins.tritown.utils.itemStack @@ -157,7 +158,7 @@ object MenuItem { */ private fun relocate(player: Player, displaced: ItemStack) { val leftover = player.inventory.addItem(displaced).values - leftover.forEach { player.world.dropItemNaturally(player.location, it) } + leftover.forEach { ItemOwnership.dropFor(player, it) } player.sendPrefixed(player.tr(if (leftover.isEmpty()) "menu-item.relocated" else "menu-item.dropped")) } } diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/protection/Claims.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/protection/Claims.kt new file mode 100644 index 0000000..0ff508c --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/protection/Claims.kt @@ -0,0 +1,147 @@ +package net.trilleo.mc.plugins.tritown.protection + +import io.papermc.paper.block.TileStateInventoryHolder +import org.bukkit.Location +import org.bukkit.NamespacedKey +import org.bukkit.block.Block +import org.bukkit.block.Campfire +import org.bukkit.block.Chest +import org.bukkit.block.DoubleChest +import org.bukkit.block.TileState +import org.bukkit.entity.* +import org.bukkit.inventory.EquipmentSlot +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.InventoryHolder +import org.bukkit.persistence.PersistentDataContainer +import org.bukkit.persistence.PersistentDataType +import java.util.* + +/** + * Something that can hold a player's items out in the world: a container, an + * interaction block such as a decorated pot, or an entity such as an item frame. + * + * Built by [Claims.of] each time it is needed and never kept, because the block + * or entity behind it can be gone by the next tick. + */ +class ClaimHolder internal constructor( + internal val data: PersistentDataContainer, + val location: Location, + private val vacancy: () -> Boolean, +) { + /** + * Whether nothing is inside and nobody has it open. + * + * A viewer keeps the claim alive even on an empty holder. Otherwise a + * hopper could claim it out from under them and fill it with items the + * viewer would then take. + */ + fun isVacant(): Boolean = vacancy() +} + +/** + * Who owns a container or an entity holder. + * + * A holder belongs to whoever fills it, for as long as it holds anything. The + * claim is the owner's UUID in the holder's own persistent data, so the world + * saves it with the block or entity. It is read lazily: [ownerOf] clears a + * claim on a holder that has been emptied and closed. No task ever has to release one, + * and a shared furnace is free again the moment its owner takes the last item out. + * + * Blocks are read through `getState(false)`, the live block entity rather than + * a snapshot, so a claim is written without an `update()`. A claim is only + * worth anything while items are inside, and moving those items is what marks + * the chunk to be saved. + * + * Never claimed: menus with no holder (TriTown's own, and other plugins'), + * the ender chest, which is already per player, and players themselves. + * Villagers, piglins and other mobs that carry items of their own are not + * holders either. Only mobs a player can saddle or armour are. + */ +object Claims { + + private val KEY = NamespacedKey("tritown", "claim") + + /** The slots a player fills on a mount or a pet. */ + private val MOUNT_SLOTS = listOf(EquipmentSlot.SADDLE, EquipmentSlot.BODY) + + // ── Finding a holder ──────────────────────────────────────────────── + + fun of(inventory: Inventory): ClaimHolder? = when (val holder = inventory.getHolder(false)) { + is DoubleChest -> (holder.leftSide as? Chest)?.let { of(it.block) } + is TileState -> of(holder.block) + is Entity -> of(holder) + else -> null + } + + fun of(block: Block): ClaimHolder? { + val state = block.getState(false) as? TileState ?: return null + val location = block.location.toCenterLocation() + + if (state is Chest) { + // Both halves of a double chest answer to the claim on its left half. + val inventory = state.inventory + val left = (inventory.getHolder(false) as? DoubleChest)?.leftSide as? Chest + val owner = left?.block?.getState(false) as? TileState ?: state + return ClaimHolder(owner.persistentDataContainer, location) { vacant(inventory) } + } + + val vacancy: () -> Boolean = when (state) { + is TileStateInventoryHolder -> { { vacant(state.inventory) } } + is Campfire -> { { (0 until state.size).all { state.getItem(it)?.isEmpty ?: true } } } + else -> return null + } + return ClaimHolder(state.persistentDataContainer, location, vacancy) + } + + fun of(entity: Entity): ClaimHolder? { + val vacancy: () -> Boolean = when { + entity is ItemFrame -> { { entity.item.isEmpty } } + entity is ArmorStand -> { { EquipmentSlot.entries.all { slot -> isBare(entity, slot) } } } + entity is Allay -> { { entity.equipment.itemInMainHand.isEmpty && vacant(entity.inventory) } } + entity is Mob && entity !is Enemy && MOUNT_SLOTS.any(entity::canUseEquipmentSlot) -> { + { + MOUNT_SLOTS.all { slot -> isBare(entity, slot) } && + ((entity as? InventoryHolder)?.inventory?.let(::vacant) ?: true) + } + } + + entity is Vehicle && entity is InventoryHolder -> { { vacant(entity.inventory) } } + else -> return null + } + return ClaimHolder(entity.persistentDataContainer, entity.location, vacancy) + } + + private fun vacant(inventory: Inventory): Boolean = inventory.isEmpty && inventory.viewers.isEmpty() + + private fun isBare(entity: LivingEntity, slot: EquipmentSlot): Boolean = + !entity.canUseEquipmentSlot(slot) || entity.equipment?.getItem(slot)?.isEmpty ?: true + + // ── Reading and writing a claim ───────────────────────────────────── + + /** Who holds [holder], or `null` when nobody does. A vacant holder loses its claim here. */ + fun ownerOf(holder: ClaimHolder): UUID? { + val owner = recorded(holder.data) ?: return null + if (!holder.isVacant()) return owner + release(holder) + return null + } + + /** + * The claim written on [data], whether or not anything is still inside. + * + * For what a block or entity leaves behind as it is destroyed, when its + * contents can no longer be counted: the claim still says whose they were. + */ + fun recorded(holder: ClaimHolder): UUID? = recorded(holder.data) + + fun recorded(data: PersistentDataContainer): UUID? = + data.get(KEY, PersistentDataType.STRING)?.let { runCatching { UUID.fromString(it) }.getOrNull() } + + fun claim(holder: ClaimHolder, owner: UUID) { + holder.data.set(KEY, PersistentDataType.STRING, owner.toString()) + } + + fun release(holder: ClaimHolder) { + holder.data.remove(KEY) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/protection/DropWindows.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/protection/DropWindows.kt new file mode 100644 index 0000000..d0539d3 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/protection/DropWindows.kt @@ -0,0 +1,81 @@ +package net.trilleo.mc.plugins.tritown.protection + +import java.util.* + +/** + * Short-lived notes that say "whatever drops here, now, belongs to this player". + * + * Most drops do not exist yet when the game says who caused them. A mob's loot, + * berries picked off a bush and a dropper's item all appear a moment after the + * event that names the player. So the event opens a window at that spot, and the + * item's spawn claims it. Nothing is written onto the `ItemStack`: a mark that + * was never stripped would follow the item into an inventory and stop it + * stacking. + * + * A window lasts the tick it was opened in and the next one, which is as long + * as the game ever takes to spawn the drops. A window with no owner is a + * *suppression*. It wins over any other window at the same spot, so a player's + * death drops stay public even when their killer's window overlaps them. + * + * Kept free of Bukkit so the matching can be tested on plain coordinates. + * + * @param clock the current server tick + * @param radius how far from the window's centre a spawn still counts, in blocks + */ +class DropWindows(private val clock: () -> Int, radius: Double = 2.0) { + + /** What a spawn at a point matched. */ + sealed interface Match { + data object None : Match + data object Public : Match + data class Owned(val owner: UUID) : Match + } + + private data class Window(val world: UUID, val x: Double, val y: Double, val z: Double, val owner: UUID?, val tick: Int) + + private val radiusSquared = radius * radius + private val windows = ArrayList() + + fun expect(world: UUID, x: Double, y: Double, z: Double, owner: UUID) { + open(Window(world, x, y, z, owner, clock())) + } + + fun suppress(world: UUID, x: Double, y: Double, z: Double) { + open(Window(world, x, y, z, null, clock())) + } + + /** The owner a drop spawning at this point should have: a suppression first, then the nearest window. */ + fun match(world: UUID, x: Double, y: Double, z: Double): Match { + prune() + var nearest: Window? = null + var nearestDistance = Double.MAX_VALUE + for (window in windows) { + if (window.world != world) continue + val distance = square(window.x - x) + square(window.y - y) + square(window.z - z) + if (distance > radiusSquared) continue + if (window.owner == null) return Match.Public + if (distance < nearestDistance) { + nearest = window + nearestDistance = distance + } + } + return nearest?.owner?.let { Match.Owned(it) } ?: Match.None + } + + private fun open(window: Window) { + prune() + windows += window + } + + private fun prune() { + val oldest = clock() - LIFETIME_TICKS + windows.removeIf { it.tick < oldest } + } + + private fun square(value: Double) = value * value + + private companion object { + /** Ticks after the one a window was opened in that it still matches. */ + const val LIFETIME_TICKS = 1 + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/protection/ItemOwnership.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/protection/ItemOwnership.kt new file mode 100644 index 0000000..10fe7c8 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/protection/ItemOwnership.kt @@ -0,0 +1,59 @@ +package net.trilleo.mc.plugins.tritown.protection + +import org.bukkit.Bukkit +import org.bukkit.Location +import org.bukkit.block.Block +import org.bukkit.entity.Item +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import java.util.* + +/** + * Who a dropped item belongs to. + * + * The owner is the game's own field, [Item.getOwner]. The game saves it with + * the entity, refuses a pickup by anyone else, and never merges two drops with + * different owners. `/give` already uses it for whatever does not fit. Nothing + * else records ownership, and an item in an inventory is never marked at all: + * it is its holder's by being there. + * + * Drops that do not exist yet are given an owner through [expect], which the + * item's spawn consumes (see [DropWindows]). + */ +object ItemOwnership { + + private val windows = DropWindows(Bukkit::getCurrentTick) + + fun ownerOf(item: Item): UUID? = item.owner + + fun bind(item: Item, owner: UUID) { + item.owner = owner + } + + /** + * Drops [stack] at [player]'s feet as theirs, for items the plugin hands a + * player that do not fit. + * + * Never drop an item for a player with `dropItemNaturally` alone: anyone + * standing nearby could take it. + */ + fun dropFor(player: Player, stack: ItemStack): Item = + player.world.dropItemNaturally(player.location, stack) { item -> + if (Protection.settings(player.world) != null) bind(item, player.uniqueId) + } + + /** Drops spawning near [location] this tick or the next belong to [owner]. */ + fun expect(location: Location, owner: UUID) { + windows.expect(location.world.uid, location.x, location.y, location.z, owner) + } + + fun expect(block: Block, owner: UUID) = expect(block.location.toCenterLocation(), owner) + + /** Drops spawning near [location] this tick or the next stay public, whatever else expects them. */ + fun suppress(location: Location) { + windows.suppress(location.world.uid, location.x, location.y, location.z) + } + + fun match(location: Location): DropWindows.Match = + windows.match(location.world.uid, location.x, location.y, location.z) +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/protection/Protection.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/protection/Protection.kt new file mode 100644 index 0000000..d0b3d23 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/protection/Protection.kt @@ -0,0 +1,74 @@ +package net.trilleo.mc.plugins.tritown.protection + +import net.trilleo.mc.plugins.tritown.config.ProtectionSettings +import net.trilleo.mc.plugins.tritown.utils.ComponentUtil +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Bukkit +import org.bukkit.World +import org.bukkit.entity.Entity +import org.bukkit.entity.Player +import org.bukkit.entity.Projectile +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * Where item protection applies, who is exempt from it, and how a refusal is + * told to the player. + * + * Every listener asks [settings] for its own switch. It gets `null` when + * protection is off entirely, or off in the world the event happened in. + */ +object Protection { + + /** Opening, taking from and breaking anything another player has claimed. */ + const val BYPASS_PERMISSION = "tritown.protection.bypass" + + /** `/tritown protection`: seeing and clearing who owns a container or entity. */ + const val ADMIN_PERMISSION = "tritown.protection.admin" + + private const val HINT_COOLDOWN_MS = 2_000L + + /** When each player was last told something is not theirs, so a busy click is not a busy chat. */ + private val lastHint = ConcurrentHashMap() + + /** The settings in force in [world], or `null` when nothing there is protected. */ + fun settings(world: World): ProtectionSettings? { + if (!ProtectionSettings.isLoaded) return null + val settings = ProtectionSettings.snapshot + if (!settings.enabled || world.name.lowercase() in settings.disabledWorlds) return null + return settings + } + + fun bypasses(player: Player): Boolean = player.hasPermission(BYPASS_PERMISSION) + + /** Whether [player] may not touch something [owner] holds. */ + fun refuses(player: Player, owner: UUID?): Boolean = + owner != null && owner != player.uniqueId && !bypasses(player) + + /** The player behind [entity]: the entity itself, or whoever fired it. */ + fun responsible(entity: Entity?): Player? = when (entity) { + is Player -> entity + is Projectile -> entity.shooter as? Player + else -> null + } + + /** A player's name, without ever asking Mojang: only the name the server already knows. */ + fun nameOf(owner: UUID): String = Bukkit.getOfflinePlayer(owner).name ?: owner.toString().take(8) + + /** Tells [player], in the action bar, that [owner] holds what they reached for. */ + fun hintOwned(player: Player, owner: UUID) { + hint(player, player.tr("protection.hint.owned", "name" to ComponentUtil.escape(nameOf(owner)))) + } + + fun hint(player: Player, message: String) { + val now = System.currentTimeMillis() + val last = lastHint[player.uniqueId] + if (last != null && now - last < HINT_COOLDOWN_MS) return + lastHint[player.uniqueId] = now + player.sendActionBar(ComponentUtil.parse(message)) + } + + fun forget(player: Player) { + lastHint.remove(player.uniqueId) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/utils/InventoryUtil.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/utils/InventoryUtil.kt index 6162f20..1668947 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/utils/InventoryUtil.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/utils/InventoryUtil.kt @@ -1,5 +1,6 @@ package net.trilleo.mc.plugins.tritown.utils +import net.trilleo.mc.plugins.tritown.protection.ItemOwnership import org.bukkit.Bukkit import org.bukkit.entity.Player import org.bukkit.inventory.ItemStack @@ -40,7 +41,7 @@ object InventoryUtil { /** * Puts [items] into the player's storage, dropping at their feet whatever - * will not fit. + * will not fit. Nobody but the player can pick those drops up. * * Space is checked before anything is handed over, so a drop only happens * when something else filled the inventory in between. Dropping is still @@ -51,7 +52,7 @@ object InventoryUtil { val leftover = player.inventory.addItem(*split(items).toTypedArray()) for (stack in leftover.values) { - player.world.dropItemNaturally(player.location, stack) + ItemOwnership.dropFor(player, stack) } } diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 05dcd1f..0fad59e 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -217,6 +217,37 @@ storage: shulker-boxes: true ender-chest: true +# ── Item protection ───────────────────────────────────────────────────────── +# Items belong to the player who has them. The only way to hand one to another +# player is a trade (/tritown trade). What is in your inventory is yours; these +# settings decide what stays yours once it leaves it. Death drops are always +# public, as is anything the world drops by itself (leaf decay, water farms). +# tritown.protection.bypass lets staff open, take from and break anything. +item-protection: + enabled: true + # Worlds where nothing is protected, such as a minigame or creative world. + disabled-worlds: [] + # What a player drops can only be picked up by them. + drops: true + # What a player mines, harvests, shears or fishes up drops as theirs. + actions: true + # A mob's loot belongs to the player who killed it, by hand, bow or pet. + mob-loot: true + # Only the player who fired an arrow or trident can pick it back up. + projectiles: true + # A container belongs to whoever fills it, for as long as anything is in it: + # furnaces, hoppers, brewing stands, droppers, crafters, decorated pots, + # shelves, jukeboxes, campfires, lecterns and the like. Nobody else can open, + # feed, empty or break it, and hoppers can't carry one player's items into + # another's container. An empty container is free for anyone again. + containers: true + # Item frames, armor stands, allays, and mobs a player has saddled, armoured or + # given a chest belong to whoever put the item there. Nobody else can take it, + # shear it off, ride the mob or break the frame or stand. + entities: true + # Explosions leave a claimed container standing, so nobody can blow one open. + explosion-guard: true + # ── Towns ─────────────────────────────────────────────────────────────────── towns: # Money set aside for a player's first town, on top of their starting balance. diff --git a/src/main/resources/lang/en_US.yml b/src/main/resources/lang/en_US.yml index 5c4b17b..049072c 100644 --- a/src/main/resources/lang/en_US.yml +++ b/src/main/resources/lang/en_US.yml @@ -22,6 +22,7 @@ command: menu: "Menu" news: "News" storage: "Storage" + protection: "Protection" help: header: "TriTown Commands" @@ -135,6 +136,15 @@ command: not-found: "No player called {name} has played here." pages-set: "{name} now has {amount} storage pages." + protection: + description: "See or clear who owns a container or entity" + players-only: "Look at a container or entity in game to use this." + usage: "Usage: /tritown protection " + no-target: "Look at a container, item frame, armor stand or mob first." + public: "Nobody owns that: anyone can use it." + owner: "That belongs to {name}." + released: "Released {name}'s claim. Anyone can use it now." + trades: description: "Open the server's global shop" players-only: "A shop is a menu, so only players can open it." @@ -1162,6 +1172,12 @@ storage: withdraw-only: "This container is withdraw-only. Open your storage from the menu." empty: "This container is empty. It is only decoration now." +# Refusals shown in the action bar when an item belongs to someone else. +protection: + hint: + owned: "That belongs to {name}. Items only change hands through a trade." + in-use: "Someone else is using that right now." + trade: done: "Traded with {name}." money-prompt: "Type how much to put up. You have {amount}." diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index ff37a65..ead2674 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -22,6 +22,7 @@ command: menu: "菜单" news: "公告" storage: "仓库" + protection: "物品保护" help: header: "TriTown 命令" @@ -135,6 +136,15 @@ command: not-found: "没有名为 {name} 的玩家来过本服务器。" pages-set: "{name} 现在拥有 {amount} 页仓库。" + protection: + description: "查看或清除容器、实体的所有者" + players-only: "请在游戏中看着一个容器或实体使用此命令。" + usage: "用法:/tritown protection " + no-target: "请先看着一个容器、物品展示框、盔甲架或生物。" + public: "它不归属任何人:所有人都可以使用。" + owner: "它归属于 {name}。" + released: "已解除 {name} 的归属。现在所有人都可以使用。" + trades: description: "打开服务器的全局商店" players-only: "商店是菜单,只有玩家能打开。" @@ -1162,6 +1172,12 @@ storage: withdraw-only: "这个容器只能取出物品。请从菜单打开你的仓库。" empty: "这个容器是空的,现在只是装饰。" +# 物品归属他人时在动作栏显示的提示。 +protection: + hint: + owned: "它归属于 {name}。物品只能通过交易转手。" + in-use: "其他人正在使用它。" + trade: done: "已与 {name} 完成交易。" money-prompt: "请输入要放上的金额。你拥有 {amount}。" diff --git a/src/test/kotlin/net/trilleo/mc/plugins/tritown/protection/DropWindowsTest.kt b/src/test/kotlin/net/trilleo/mc/plugins/tritown/protection/DropWindowsTest.kt new file mode 100644 index 0000000..e791c91 --- /dev/null +++ b/src/test/kotlin/net/trilleo/mc/plugins/tritown/protection/DropWindowsTest.kt @@ -0,0 +1,55 @@ +package net.trilleo.mc.plugins.tritown.protection + +import java.util.* +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * A window decides who owns a drop nobody else has claimed, so a miss hands the + * item to everyone and a false match hands it to the wrong player. + */ +class DropWindowsTest { + + private var tick = 100 + private val windows = DropWindows({ tick }) + + private val world = UUID.randomUUID() + private val alice = UUID.randomUUID() + private val bob = UUID.randomUUID() + + @Test + fun `a spawn near a window belongs to its owner`() { + windows.expect(world, 0.5, 64.5, 0.5, alice) + assertEquals(DropWindows.Match.Owned(alice), windows.match(world, 0.8, 64.2, 0.4)) + } + + @Test + fun `a spawn out of reach, or in another world, matches nothing`() { + windows.expect(world, 0.5, 64.5, 0.5, alice) + assertEquals(DropWindows.Match.None, windows.match(world, 5.0, 64.5, 0.5)) + assertEquals(DropWindows.Match.None, windows.match(UUID.randomUUID(), 0.5, 64.5, 0.5)) + } + + @Test + fun `the nearest window wins`() { + windows.expect(world, 0.0, 64.0, 0.0, alice) + windows.expect(world, 1.5, 64.0, 0.0, bob) + assertEquals(DropWindows.Match.Owned(bob), windows.match(world, 1.2, 64.0, 0.0)) + } + + @Test + fun `a suppression beats any window around it`() { + windows.expect(world, 0.0, 64.0, 0.0, alice) + windows.suppress(world, 1.0, 64.0, 0.0) + assertEquals(DropWindows.Match.Public, windows.match(world, 0.1, 64.0, 0.0)) + } + + @Test + fun `a window lasts its own tick and the next, and no longer`() { + windows.expect(world, 0.0, 64.0, 0.0, alice) + tick += 1 + assertEquals(DropWindows.Match.Owned(alice), windows.match(world, 0.0, 64.0, 0.0)) + tick += 1 + assertEquals(DropWindows.Match.None, windows.match(world, 0.0, 64.0, 0.0)) + } +} From 21cbee2c1bb9d4d34a5986eb6556587e870a4df4 Mon Sep 17 00:00:00 2001 From: Trilleo Date: Tue, 22 Sep 2026 10:59:57 +0800 Subject: [PATCH 5/6] Improvement: Stop pistons breaking claimed containers Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 2 +- docs/DEVELOPER_GUIDE.md | 4 +++ .../protection/ContainerProtectionListener.kt | 35 +++++++++++++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 42e11fb..79e2825 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,7 +31,7 @@ + Only the player who fired an arrow or trident can pick it back up. + Containers belong to whoever fills them, for as long as anything is inside: furnaces, hoppers, brewing stands, droppers, crafters, decorated pots, shelves, chiseled bookshelves, jukeboxes, campfires and lecterns. - + Nobody else can open, feed, empty or break one, or blow it up. An empty container is free for anyone again, so + + Nobody else can open, feed, empty or break one, blow it up, or break it with a piston. An empty container is free for anyone again, so shared furnaces still work. + Hoppers carry the owner along: your items can fill a free container, which becomes yours, but never someone else's. diff --git a/docs/DEVELOPER_GUIDE.md b/docs/DEVELOPER_GUIDE.md index 541a3b5..f9bb643 100644 --- a/docs/DEVELOPER_GUIDE.md +++ b/docs/DEVELOPER_GUIDE.md @@ -3236,6 +3236,10 @@ The rules, in `ContainerProtectionListener` and `EntityProtectionListener`: - A non-owner cannot break, blow up or shoot apart a claimed holder, destroy a claimed minecart, take a lectern's book, or right-click a claimed interaction block, frame, stand or mob. `explosion-guard` removes claimed containers from an explosion's block list. +- A piston never moves or breaks a claimed holder. The game only ever breaks a block entity whose move reaction + is `BREAK`, such as a decorated pot, and that block is not always in the event's list. So the blocks around + everything that moves, and the one in front of the head, are checked as well, but only the breakable ones. A + piston door beside a claimed furnace still works. - A frame, stand or mob is claimed when an item goes on. For stands and mobs that is read a tick later, because the item lands after the event. diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/ContainerProtectionListener.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/ContainerProtectionListener.kt index dd5deee..ad3ae86 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/ContainerProtectionListener.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/protection/ContainerProtectionListener.kt @@ -7,6 +7,7 @@ import net.trilleo.mc.plugins.tritown.protection.Claims 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.World import org.bukkit.block.* import org.bukkit.entity.Player import org.bukkit.event.Event @@ -146,6 +147,36 @@ class ContainerProtectionListener : Listener { event.blockList().removeIf(::isHeld) } + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) + fun onPistonExtend(event: BlockPistonExtendEvent) { + if (pistonBreaksHolder(event.block.world, event.blocks, event.block.getRelative(event.direction))) { + event.isCancelled = true + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) + fun onPistonRetract(event: BlockPistonRetractEvent) { + if (pistonBreaksHolder(event.block.world, event.blocks, null)) event.isCancelled = true + } + + /** + * Whether a piston would move or break a claimed holder. + * + * The game never moves a block entity, but it breaks one whose move reaction + * is `BREAK`, such as a decorated pot, and spills its contents as public drops. + * Those blocks are not always in [moved], so the blocks around everything + * that moves, and the one in front of the head, are checked too. Only the + * breakable ones among them count, so a piston door beside a claimed furnace + * still works. + */ + private fun pistonBreaksHolder(world: World, moved: List, head: Block?): Boolean { + if (Protection.settings(world)?.containers != true) return false + if (moved.any(::isHeld)) return true + + val around = moved.flatMap { block -> FACES.map(block::getRelative) } + listOfNotNull(head) + return around.distinct().any { it.pistonMoveReaction == PistonMoveReaction.BREAK && isHeld(it) } + } + /** An arrow through a decorated pot, a wither chewing through a furnace. */ @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) fun onEntityChangeBlock(event: EntityChangeBlockEvent) { @@ -245,4 +276,8 @@ class ContainerProtectionListener : Listener { event.isCancelled = true Protection.hintOwned(player, owner!!) } + + private companion object { + val FACES = listOf(BlockFace.UP, BlockFace.DOWN, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST) + } } From 1319d1a8b06af2f46394d4a6bf5320101085d000 Mon Sep 17 00:00:00 2001 From: Trilleo Date: Tue, 22 Sep 2026 12:04:41 +0800 Subject: [PATCH 6/6] Update: Plugin version 1.4.0 release --- CHANGELOG.md | 2 ++ gradle.properties | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 79e2825..fc7205a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## Version 1.4.0 + ### New Features #### Storage diff --git a/gradle.properties b/gradle.properties index bdf6316..c35acf0 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,7 +1,7 @@ kotlin.code.style=official # Plugin Properties -plugin_version=1.3.0 +plugin_version=1.4.0 # Dependency Versions towny_version=0.103.2.7