Files
docs
Code
1 234
docs/EnchainSMP-Design-Spec.md
# EnchainSMP — Design Document & Technical Specification
## 1. Purpose
EnchainSMP is a Paper plugin for Minecraft 1.21.x that broadens vanilla enchantment use while retaining vanilla enchantment level caps. It also rewards online players with a non-repeating personal sequence of enchanted books and adds configurable hybrid effects for Blast Protection and Infinity.
This document specifies behavior and implementation boundaries; it does not claim that the plugin has been implemented.
## 2. Targets and principles
- **Server:** Paper 1.21.x; compile and run against Java 21.
- **Threading:** Bukkit/Paper world, entity, inventory, and event operations run on the server thread. Only immutable persistence snapshots may be written asynchronously.
- **Enchantment source:** Discover vanilla enchantments from the server registry and accept only entries in the `minecraft` namespace. Do not hard-code a version-specific list.
- **Level rule:** Every stored or applied enchantment level must be between its vanilla minimum and maximum. Never create an over-cap result.
- **Compatibility rule:** Universal anvil application bypasses item applicability and mutual-exclusion restrictions. It does not bypass the maximum level, anvil payment, inventory capacity, or event cancellation.
- **Custom-item identity:** Use a namespaced persistent-data tag to identify EnchainSMP custom weapons. Do not rely on display names or lore as identity.
## 3. Feature specifications
### 3.1 Universal enchantability in anvils
An enchanted book may be combined with any non-empty item, regardless of whether the enchantment normally applies to that item. Existing enchantments that are normally incompatible do not prevent the combination. Books may also be combined with items that already have other enchantments.
For each enchantment on the input book:
1. Resolve its vanilla enchantment key and vanilla maximum level.
2. Normalize the incoming level to the range `1..maximum` so malformed or command-created over-level books cannot produce over-level output.
3. If the target has no such enchantment, add the normalized level.
4. If the target has the same enchantment, combine equal levels by adding one level, capped at the vanilla maximum. If levels differ, keep the higher level, also capped at the maximum.
5. Preserve the target's other item metadata and enchantments.
The preview and committed output must be calculated by the same service. On taking the result, the plugin must commit a single output, consume the corresponding target and book inputs, and charge the displayed anvil level cost. A cancelled event, stale preview, invalid input, insufficient levels, or an invalid result must not consume inputs. Shift-click result collection is cancelled to avoid bypassing the single-output transaction. Anvil break chance and other native behavior should remain enabled unless Paper's transaction path makes that impossible; if so, document the difference and cover it in tests.
Vanilla enchantment levels are read from the enchantment definition at runtime, not from an independently maintained list. Enchanted books are created with the corresponding stored enchantment and a legal level.
### 3.2 Scheduled book distribution
- Default interval: **15 minutes** (18,000 server ticks at 20 TPS).
- At each reward pulse, each currently online player is considered independently.
- Each eligible player receives one book selected randomly from that player's remaining enchantment pool. Two different players may receive the same enchantment on the same pulse.
- Pool identity is the enchantment key, not the level. A randomly chosen legal level may vary between rewards without counting as a repeat.
- The pool contains every vanilla enchantment discovered in the `minecraft` namespace, including curses. Non-vanilla/plugin enchantments are excluded.
- When the last entry is drawn, that player has completed the cycle. Their pool is refilled for the next reward pulse; the just-awarded enchantment is not immediately repeated as part of the completed cycle.
- Offline players do not accumulate rewards or advance their pools. The timer begins after plugin enable; missed pulses during shutdown are not replayed.
- A full inventory does not discard the reward: drop the book at the player's current location with normal pickup behavior.
On first participation, initialize that player's pool from the current vanilla registry. When a server update adds or removes vanilla enchantments, reconcile saved pools against the current registry: discard keys that no longer exist and add newly discovered keys without resetting still-valid uncollected entries.
### 3.3 Spear and trident compatibility
Vanilla tridents retain native behavior whenever the server supports it. EnchainSMP must not apply a native effect a second time. Custom spears are identified through the custom-item tag and routed through a spear adapter, so the core implementation does not depend on one specific 1.21.x server exposing a particular spear material or API.
For tagged custom spears, and for other explicitly supported custom weapons, implement these effects:
- **Riptide:** On valid use, propel the wielder in their look direction using a level-scaled velocity. Apply only in the configured vanilla-like water/rain conditions by default; respect event cancellation, cooldown, and a configurable safety bound on velocity.
- **Loyalty:** Track the launched custom projectile and its owner. After impact or a defined return condition, return it to its owner; stop tracking on pickup, owner logout/invalidity, or a bounded timeout. Do not create additional copies.
- **Channeling:** On a valid projectile hit during a thunderstorm with a valid strike location, trigger lightning at the impact location. Avoid duplicating native trident lightning. Any custom weather or sky-visibility override must be explicitly configurable.
- **Impaling:** Apply the configured vanilla-like bonus to eligible aquatic targets when a custom spear hits, for both melee and tracked projectile impacts. Eligibility and damage calculation must be centralized so a hit cannot receive the bonus twice.
If the exact Paper minor release provides a native spear item/mechanic, a version adapter may delegate to it. Otherwise, a tagged base item plus plugin-managed use/projectile handling is the supported custom-spear path. The adapter must fail closed: an unrecognized custom item must not receive invented behavior.
### 3.4 Blast Protection on weapons
Blast Protection on armor remains vanilla. If an item classified as a weapon carries Blast Protection and the feature is enabled, a successful hit triggers a blast at the target's impact location. Supported triggers are melee entity hits and tracked spear/projectile hits; cancelled hits and hits with no valid target do not trigger.
The blast must not damage the attacking player and must not break blocks or start fires. Implement it as a visual explosion plus plugin-managed area damage, rather than relying on an ordinary world explosion whose radius could damage the attacker. Exclude the attacker explicitly from the damage pass. Use normal damage events for affected entities so other plugins can inspect or cancel the damage. Respect PvP rules and cancelled damage events; do not recursively trigger another Blast Protection blast from the secondary damage.
The exact impact target receives the configured impact effect. Other eligible nearby entities may receive distance-scaled damage up to the configured radius. A per-hit guard prevents duplicate processing when multiple event paths observe the same hit. Weapon classification uses known vanilla weapon types plus the EnchainSMP custom-weapon tag; arbitrary items do not become weapons solely because their display name says so.
### 3.5 Infinity on consumable and usable items
When enabled, Infinity prevents an enchanted item from being consumed or depleted by its own use while preserving the use's normal effect:
- **Food and drink:** The player still receives the normal food, saturation, and potion effects. Restore one copy of the enchanted item after successful consumption instead of cancelling the consume event (which would also suppress the effect).
- **Durability-based use:** Cancel durability loss for an item carrying Infinity, including custom tools and weapons.
- **Stack depletion:** Restore the consumed item to its original slot where possible, then another inventory slot; if neither is available, drop it safely at the player's feet. This handles a potion's returned container occupying the formerly open slot.
- **Other usable items:** Add support only through an explicit use adapter that can preserve the item's normal use effect and prevent its depletion. Do not cancel generic interactions indiscriminately.
The restoration operation must be tied to the original successful use and must not duplicate the item if the player changes slots, disconnects, dies, or inventory contents change before restoration. Track a use token and a copy of the original enchanted item; reconcile the inventory before restoring, and discard the pending restore if the original item is still present at its full pre-use count. Enchanted arrows or unrelated ammunition are not made infinite unless the ammunition itself is supported and carries Infinity.
## 4. Architecture
Suggested package root: `com.example.enchainsmp` (replace with the final chosen package before implementation).
| Component | Responsibility |
|---|---|
| `EnchainSMPPlugin` | Plugin lifecycle, configuration load, service construction, listener and task registration, orderly shutdown. |
| `EnchainConfig` | Typed access to validated settings and defaults. |
| `VanillaEnchantmentCatalog` | Enumerate vanilla registry entries, resolve keys and level bounds, produce legal enchanted books. |
| `UniversalAnvilService` | Shared anvil preview and transaction calculation, input validation, cost and output handling. |
| `RewardScheduler` | Periodic online-player reward pulse and inventory/drop fallback. |
| `PlayerEnchantmentPoolStore` | In-memory per-player pools, registry reconciliation, durable serialization. |
| `SpearCompatibilityService` | Native/custom item routing, projectile ownership and custom spear effects. |
| `HybridEnchantmentService` | Blast Protection hit effects and Infinity restoration/durability behavior. |
| `EnchainItemTags` | Persistent-data keys and custom item classification helpers. |
| `AnvilListener`, `RewardListener`, `CombatListener`, `ItemUseListener` | Thin Bukkit/Paper event adapters that delegate to services. |
Listeners should remain thin and share the same services used by scheduled tasks. Any tracked projectile or pending item restoration must have bounded lifetime and be cleared on plugin disable. Register only the listeners and repeating task needed for enabled features.
## 5. Persistence and recovery
Store per-player pool state under UUID, never player name. A suitable lightweight initial format is `plugins/EnchainSMP/player-data.yml`, with a schema version and a list of remaining namespaced enchantment keys per UUID. Keep the active state in memory; mutate it on the main thread. For asynchronous writes, serialize an immutable snapshot on the main thread and write that snapshot off-thread using a temporary file followed by an atomic replace where supported. Never access Bukkit configuration, player, inventory, or world objects from the writer thread.
Save after a player's pool changes, on player quit, periodically, and during plugin disable. A failed write must log an actionable error and retain the in-memory state for a later retry. Pool removal and reward delivery cannot be made fully crash-atomic with a plain YAML file; the implementation should document this narrow crash window and favor preventing repeat rewards during normal operation. If stronger transactional guarantees are required later, replace the store with a transactional database without changing the pool service contract.
## 6. Configuration
Example `config.yml`:
```yaml
rewards:
enabled: true
interval-minutes: 15
first-reward-after-interval: true
drop-at-player-when-full: true
anvil:
universal-enchantability: true
enforce-vanilla-maximum-level: true
allow-incompatible-enchantments-together: true
cancel-shift-click-result: true
spear:
enabled: true
riptide-requires-water-or-rain: true
riptide-velocity-per-level: 1.5
maximum-riptide-velocity: 4.5
loyalty-return-timeout-seconds: 30
channeling-requires-thunderstorm: true
impaling-extra-damage-per-level: 2.5
blast-protection-weapon:
enabled: true
radius: 4.0
maximum-damage: 8.0
damage-falloff: true
break-blocks: false
set-fire: false
damage-attacker: false
infinity:
enabled: true
prevent-durability-loss: true
restore-consumed-items: true
drop-restored-item-when-inventory-full: true
```
Validate numeric values at startup: interval and timeout must be positive; radius, damage, and velocity must be finite and non-negative; per-feature switches must be respected by listeners and scheduled tasks. Invalid values should fall back to documented defaults and produce a warning. `break-blocks`, `set-fire`, and `damage-attacker` are intentionally fixed false safety settings in this specification; they are shown explicitly so the safety contract is visible, not to offer unsafe overrides.
## 7. Permissions and administration
The core mechanics have no permission requirement: eligible online players receive rewards and may use the anvil/hybrid effects. Add an administrative reload command only if command handling is included in the first implementation. If provided, protect it with `enchainsmp.admin`; reload must validate configuration before replacing active settings and must not clear saved player pools.
## 8. Event and task flow
### Anvil
1. On anvil preparation, validate inputs and calculate a legal result from the current inputs.
2. Show the result and matching cost only when the transaction can be committed.
3. On result collection, reject unsupported bulk collection, revalidate the current inputs and cost, and ensure the event is not cancelled by another plugin.
4. Commit one output and consume inputs/levels exactly once; clear or refresh the preview.
### Reward pulse
1. Resolve the current online player set on the server thread.
2. For each player, obtain or initialize their reconciled pool.
3. Remove one random key and create a legal book at a legal random level.
4. Add the book to inventory; if it does not fit and fallback is enabled, drop it at the player's feet.
5. Persist a snapshot of updated pool state.
### Combat effect
1. Ignore cancelled damage events and non-entity attacks.
2. Resolve the held/launching weapon and enchantments, including tracked projectile ownership.
3. Route native tridents to native mechanics; run custom spear behavior only for tagged custom items.
4. Trigger eligible effects once, excluding the attacker from Blast Protection area damage.
### Infinity use
1. Identify the exact enchanted item and successful consume/use event.
2. Record a pending restoration token before the normal use completes.
3. Allow normal use effects; prevent item durability loss where applicable.
4. Reconcile the post-use inventory and restore exactly one item only when it was actually depleted.
## 9. Operational safeguards
- Namespaced enchantment keys are the serialized identity; never serialize registry iteration indexes.
- Bound temporary projectile and item-use tracking with expiry and lifecycle cleanup.
- Guard custom damage against recursive secondary effects.
- Avoid forcing custom effects through cancelled events or inventing damage when the originating hit was denied.
- Log persistence failures and invalid configuration; avoid per-tick or per-hit console spam.
- Do not let an unavailable enchantment key invalidate an entire player record; skip that key and reconcile it away.
## 10. Acceptance criteria and test plan
### Universal anvil
- A vanilla book can apply each vanilla enchantment to an otherwise ineligible item.
- Mutually exclusive enchantments can coexist when enabled by this specification.
- Equal levels combine by one, different levels retain the higher, and no result exceeds the registry maximum.