Skip to content

2 ‐ Dev Guide

krœt.net edited this page Nov 12, 2026 · 6 revisions

Developer Guide

This guide targets contributors who build, extend, or review TradeShuffler.

1. Repository layout

tradeshuffler-mod/
├─ common/      # loader-neutral logic: client/server config models and stores, shuffle rules, facades, i18n, update service (no Minecraft classes)
├─ shared/      # Minecraft-dependent runtime for both sides (server services, client screen logic, payloads, mixins, textures), bundled into both loader jars
├─ fabric/      # Fabric entrypoints (common + client) and loader glue
├─ neoforge/    # NeoForge entrypoints (common + client) and loader glue
├─ config/      # matrix-targets.json (versions SSOT), mod.properties (mod id/name/group)
├─ gradle/      # wrapper + shared build scripts (matrix defaults, Java conventions, mod info, TurtleLib dependency)
├─ settings.gradle, build.gradle, gradlew   # standalone build + repo-level tasks
├─ version.properties                       # mod version + required TurtleLib version
├─ update-sources.properties
└─ README.md

Base package: net.kroet.tradeshuffler. Mod id: tradeshuffler.

TradeShuffler depends on TurtleLib. It compiles against the TurtleLib core jar attached to the TurtleLib GitHub release, whose version is turtlelib_dependency_version in version.properties. The same value is the minimum TurtleLib version in the mod metadata. Players install TurtleLib as its own mod; TradeShuffler jars do not bundle it.

2. Tooling requirements

  • A JDK 17+ to start Gradle. The compile toolchain (the java value of the selected matrix target, currently Java 25) is detected automatically or downloaded.
  • Source of truth for versions: config/matrix-targets.json. Builds without parameters use the first target.
  • Use this repository's own wrapper: ./gradlew. It is a standalone build.

3. Build and test

Use test tasks for normal validation/debugging:

  • ./gradlew testTradeShuffler

Other tasks:

  • ./gradlew build builds both loader jars into dist/.
  • ./gradlew verifyMatrixTargets validates the build matrix.
  • ./gradlew releaseTradeShuffler runs the clean release build for all matrix targets.

Code formatting:

  • Java formatting is enforced with Spotless (Eclipse JDT formatter, settings in config/spotless-eclipse-formatter.properties). spotlessCheck runs with build, testTradeShuffler and releaseTradeShuffler and fails on unformatted code; ./gradlew spotlessApply fixes it.
  • Null safety is checked with JSpecify: every package is @NullMarked (package-info.java), and values that may be null are marked @Nullable. nullCheck runs the Eclipse compiler with the rules in config/jdt_null_analysis.prefs (the same ones VS Code uses) on every source set; it runs with check, build and testTradeShuffler and fails on any null warning.
  • All text files use LF line endings, only *.bat uses CRLF (.gitattributes, .editorconfig).

Game tests

  • ./gradlew gameTestTradeShuffler starts a Fabric and then a NeoForge game test server and runs the server-side tests: zombie conversion keeps the trade plan and the traded flag, level-up unlocks exactly the planned trades, a profession change discards the plan, plan and flag survive saving, a shuffle request rerolls until the first trade, a trade without XP locks shuffling too (also after a restock), and rapid shuffles at a cartographer roll the plan (with its exploration maps) only once shuffling pauses. A failing test ends the task with an error.
  • The test functions live once in shared/src/gametest/java; fabric/src/gametest (@GameTest methods, entrypoint fabric-gametest) and neoforge/src/gametest (RegisterGameTestsEvent, own empty structure) only register them. These source sets never end up in a mod jar, and build does not run them.
  • The test servers install the TurtleLib loader jar, so the task needs the hrobasti-mods workspace; in a lone clone it stops with a hint.
  • Test villagers run with NoAI: without a registered job site POI, their brain would reset the profession at once.
  • Run directories: fabric/build/run/gameTest and neoforge/build/run/gameTest.

To develop TradeShuffler and TurtleLib together, clone TurtleLib next to this repository (../turtle-lib-mod) and add -PuseLocalTurtleLib=true. The build then uses the local TurtleLib sources instead of the release jar. Inside the hrobasti-mods workspace this is the default.

Development runs

  • Fabric: ./gradlew :tradeshuffler-fabric:runClient / runServer (run directory fabric/run).
  • NeoForge: ./gradlew :tradeshuffler-neoforge:runClient / runServer (run directory neoforge/run).
  • TurtleLib is a separate mod at runtime: put the matching TurtleLib loader jar into fabric/run/mods or neoforge/run/mods.
  • For a dedicated dev server, add eula=true to run/eula.txt. The run/ directories are not versioned.

4. Architecture rules (important)

4.1 Client and server

TradeShuffler is a client and server mod: the server validates requests and generates trades; the client only requests and renders. Anything that decides about trades runs on the server.

  • shared contains code for both sides. Client-only code (screens, rendering) must only be reached from client entrypoints or client mixins.
  • The Fabric metadata uses "environment": "*" with a main and a client entrypoint; NeoForge uses one @Mod class for both sides and one with dist = Dist.CLIENT.
  • Loader modules declare evaluationDependsOn(':tradeshuffler-common') / (':tradeshuffler-shared'), because their jars bundle the outputs of these modules.

4.2 TurtleLib facades

TurtleLib is used only through UpdateFacade in common; feature, UI and entrypoint code never import TurtleLib. Add a facade only when TradeShuffler starts using another TurtleLib part. Translations use Minecraft's lang files, not TurtleLib.

4.3 Minecraft API access

Private Minecraft members are reached through compile-checked accessor/invoker mixins in shared, never through reflection by name.

Mixins live in shared and are loader-neutral (Minecraft 26.x ships unobfuscated, so no refmap is needed). Both configs are listed in fabric.mod.json and neoforge.mods.toml.

tradeshuffler.mixins.json (both sides, package net.kroet.tradeshuffler.shared.mixin):

Mixin Target Purpose
MerchantMenuAccessor MerchantMenu Accessors for trader and tradeContainer.
AbstractVillagerInvoker AbstractVillager Invoker for addOffersFromTradeSet and accessor for the raw offers field (trade plan generation and consumption).
VillagerInvoker Villager Invoker for updateSpecialPrices(Player).
VillagerTradePlanMixin Villager Implements TradeShufflerVillager (traded flag, trade plan, PlanPacer); saves/loads flag and plan; startTrading TAIL schedules the plan and sends the trade state; updateTrades HEAD consumes a planned batch; tick TAIL generates the plan.
AbstractVillagerNotifyTradeMixin AbstractVillager notifyTrade TAIL, villagers on the server only: sets the traded flag on the first trade and resends the state.
ZombieVillagerTradePlanMixin ZombieVillager Implements TradeShufflerZombieVillager; keeps traded flag and plan (same save keys) while the villager is a zombie.
MobConversionMixin Mob convertTo RETURN: ZombieConversion carries flag and plan through infection and cure.

tradeshuffler.client.mixins.json (client only, package net.kroet.tradeshuffler.shared.mixin.client):

Mixin Target Purpose
MerchantScreenMixin MerchantScreen Constructor: forgets the trade state and a pending shuffle of the previous screen. Adds the shuffle button in init and implements ShuffleButtonHost; @WrapOperation on the getOffers() call sites (preview list); locks and decorates preview rows; guards postButtonClick.
AbstractContainerScreenMixin AbstractContainerScreen containerTick and keyPressed for screens implementing ShuffleButtonHost; MerchantScreen declares neither method.
MerchantScreenTradeOfferButtonMixin MerchantScreen$TradeOfferButton Implements PreviewRowButton (row index) and sets the tooltip of preview rows.
MerchantScreenAccessor MerchantScreen Accessor for scrollOff.

4.4 Networking

Payloads are vanilla CustomPacketPayload records with StreamCodecs in shared/network; the loader modules only register them.

Payload Direction Id Fields
ShuffleRequestPayload client → server tradeshuffler:shuffle_request containerId
TradeStatePayload server → client tradeshuffler:trade_state containerId, shuffleBlockReason (ShuffleEligibility.Verdict name, empty = allowed), preview (up to 4 PreviewBatch(level, offers))
  • TradeShufflerNetworkBindings holds two small interfaces installed by the loader entrypoints: Server (canReceive, sendTradeState) and Client (serverSupportsShuffle, sendShuffleRequest). They are separate so a dedicated server never loads client networking classes. Until a loader installs them, no-op bindings apply.
  • Fabric: PayloadTypeRegistry.serverboundPlay() / clientboundPlay(), ServerPlayNetworking and ClientPlayNetworking (canSend checks).
  • NeoForge: RegisterPayloadHandlersEvent with an optional() registrar (playToServer with handler, playToClient without); the client handler is registered via RegisterClientPayloadHandlersEvent in the client entrypoint. hasChannel checks, PacketDistributor / ClientPacketDistributor.
  • The server only sends to players whose client registered the channels. With optional channels, NeoForge accepts vanilla connections.
  • On the client, ClientTradeState keeps the latest state for the open merchant menu; it is cleared when a merchant screen opens and on disconnect.

4.5 Shuffle rules and villager state

  • ShuffleEligibility (common/rules) decides from plain facts whether a shuffle is allowed and returns the first failing rule as a Verdict: shuffle enabled, matching container, trader is a Villager, alive and trading with the player, traded flag not set, XP 0, novice level, profession has novice trades, job site (if requireJobSite), cooldown elapsed. ShuffleFacts in shared collects these facts from the game.
  • ShuffleCooldown tracks the last accepted shuffle per player in server ticks (shuffleCooldownTicks); a player's entry is removed when they leave, and all entries on server start.
  • The traded flag is stored in the villager's save data under tradeshuffler:traded (only written when true) and is never cleared. Vanilla ignores unknown keys, so removing the mod leaves villagers intact.
  • TradeStateService sends TradeStatePayload when trading starts and after the first completed trade. Container and cooldown are not part of that check; they only apply to requests (ShuffleRequestHandler).

4.6 Trade plan (binding preview)

  • LevelPlan<T> (common/rules) holds pre-generated batches for the levels above the current one (fromLevel() to 5), with a stamp of profession and villager type. Operations: isValidFor(stamp, level), nextMissingLevel(), put, take(level) (returns the batch and drops all levels up to it), dropUpTo(level), isComplete().
  • TradePlanService (shared/server) uses it as LevelPlan<MerchantOffers>, stored per villager through TradeShufflerVillager and saved under tradeshuffler:trade_plan (TradePlanCodec: profession, type, from_level, list of {level, offers} in vanilla's offer format).
  • Generation: scheduled when a player who can receive TradeShuffler payloads opens the screen without a complete plan, and after a shuffle. Pacing lives in PlanPacer and GenerationBudget (common/rules): after a shuffle generation waits until shuffling has paused for 40 ticks (every shuffle restarts the wait), and server-wide at most one level is generated per server tick. Reason: generating runs vanilla trade functions such as minecraft:exploration_map, which search for structures, create map data and claim the structure. The Villager#tick hook asks the pacer and generates via addOffersFromTradeSet (vanilla's trade set path, so data packs apply). When the plan is complete, the trading player gets a new trade state.
  • Consumption: the Villager#updateTrades HEAD hook. Empty offers (new profession, reset, shuffle) clear the plan and let vanilla roll the novice batch. A batch for the new level is appended instead of vanilla's roll, then prices are updated and the state is resent. Without a batch, vanilla rolls the level and the plan is regenerated; the client never saw that level, so the preview stays binding.
  • Invalidation: a stamp mismatch or a lower level discards the plan; batches up to the current level are dropped (a level set by commands brings no trades of the skipped levels, as in vanilla). A master keeps no plan.
  • Zombie infection and cure: vanilla only copies offers and XP; MobConversionMixin + ZombieConversion carry the plan and the traded flag over, so the preview stays binding and a villager nobody traded with can still be shuffled after the cure.
  • Preview: TradeStatePayload carries the batches only when the plan is complete and previewEnabled is on; batches are copied, empty ones are left out.
  • In 26.3, a villager levels up immediately during the trade, also while the trading screen is open.

4.7 Preview display (client)

  • ClientTradeState keeps the last trade state for the open merchant screen; PreviewView filters its batches to levels above getTraderLevel() (so a batch never shows twice after a level-up) and respects the client config previewEnabled.
  • Without real offers no preview is shown, so the screen never treats a preview row as the selected trade.
  • The combined list (real offers + preview offers) exists only at MerchantScreen's own getOffers() call sites in extractContents, mouseScrolled, mouseDragged and mouseClicked, rebuilt on every access. MerchantMenu is never changed, so server logic, auto-fill and other mods see the real offers. Vanilla scrolling and scroll bounds work for the longer list unchanged.
  • At extractContents TAIL, rows beyond the real offers get active = false (disabled sprite, not clickable), a translucent black overlay (previewDimAlpha) and a 2 px stripe in the level badge color (previewLevelStripe). graphics.nextStratum() puts the overlay above the row items. postButtonClick additionally ignores indices beyond the real offers.
  • Preview row tooltips combine the hovered item's own tooltip with "Unlocks at " and a base-price note (tradeshuffler.screen.preview.*); item zones match vanilla's trade offer button.

4.8 Shuffling and the shuffle button

  • ShuffleService runs on the server thread after a request was accepted: setOffers(null) + getOffers() (vanilla regenerates the novice batch through the trade set path), updateSpecialPrices, sendMerchantOffers, MerchantMenu#slotsChanged (recomputes the result slot, so a previously selected offer cannot be taken for free), then a new TradeStatePayload.
  • ShuffleButtonController (client) creates the 20×20 SpriteIconButton with the tradeshuffler:shuffle / shuffle_disabled sprites at leftPos - 22 + offsetX (at least 2), topPos + 18 + offsetY. State is updated in the screen tick, never while rendering. Visible: config enabled, server accepts shuffle requests, a trade state for this container arrived, and showProgressBar(). Active: no block reason and the local check getTraderXp() == 0. Otherwise the button is greyed out and its tooltip adds the reason (tradeshuffler.screen.shuffle.tooltip.unavailable.<reason>, unknown reasons fall back to …unavailable.other). The server never sends text, only the reason name.
  • After a request the button stays disabled until the next trade state arrives, or for at most 20 ticks (a rejected request gets no answer).
  • Key mapping key.tradeshuffler.shuffle (TradeShufflerKeyMappings), unbound by default, in the category tradeshuffler:tradeshuffler. Fabric registers it via KeyMapping.Category.register + KeyMappingHelper, NeoForge via RegisterKeyMappingsEvent. Vanilla key mappings do not fire while a screen is open, so AbstractContainerScreenMixin checks the key in keyPressed.

5. Config model notes

  • Client config (TradeShufflerClientConfig, file config/tradeshuffler.json): shuffle button visibility and offset, preview settings, update controls (updateCheckEnabled, UpdateChannel). Loaded by the client entrypoints via ClientConfigHolder. Edited in TradeShufflerConfigScreen (shared/client, one screen for both loaders), registered via TradeShufflerModMenuApi (Fabric, Mod Menu entrypoint) and IConfigScreenFactory (NeoForge client entrypoint); saving applies the values immediately.
  • Server config (TradeShufflerServerConfig, file config/tradeshuffler-server.json): shuffleEnabled, previewEnabled, requireJobSite, shuffleCooldownTicks. Loaded on server start (dedicated and integrated) via ServerConfigHolder.
  • Both stores normalize values on load and write the file back, so a missing file is created with defaults.
  • New config fields are additive: missing values in an existing file fall back to their defaults, so no configVersion bump is needed.

6. Assets and licensing

TradeShuffler is licensed under MIT. The jars bundle no third-party code or assets; THIRD_PARTY_NOTICES.md records that, the platform and test dependencies ("Not shipped") and the Minecraft depictions ("Trademarks"). A bundled third-party component would need a permissive license, a table row in the notices and its license text under src/main/resources/licenses/; the workspace check command verifies this.

  • The mod icon (256×256) lives once in common/src/main/resources/assets/tradeshuffler/icon.png and is referenced as icon in fabric.mod.json and iconFile in neoforge.mods.toml. It shows a Minecraft villager (Mojang), recorded under "Trademarks" in THIRD_PARTY_NOTICES.md as not covered by the MIT license.
  • Button textures live in shared/src/main/resources/assets/tradeshuffler/textures/gui/sprites/ (shuffle.png, shuffle_disabled.png, 18×18 with the symbol centered for a 20×20 button).

7. Update source metadata pipeline

Update provider metadata is maintained in update-sources.properties (flat key/value). Empty project ids disable the update check.

During common:processResources, it is copied into resources as:

  • tradeshuffler-update-sources.properties

TradeShufflerUpdateService loads this bundled resource via java.util.Properties.

8. Release/documentation workflow

Before publishing to GitHub/Modrinth/CurseForge:

  1. run all relevant test tasks
  2. build loader artifacts (clean-first):
    • ./gradlew releaseTradeShuffler
  3. verify generated jars in dist
  4. confirm common and shared classes and resources are bundled in both loader jars
  5. confirm README and wiki reflect current behavior
  6. GitHub releases are immutable: create the release as a draft, attach all assets, then publish

9. Contribution checklist

  • keep code changes loader-safe and minimal
  • run ./gradlew spotlessApply before committing
  • add/update tests for behavior changes
  • keep user-facing text in docs and locale keys aligned
  • update the User Guide whenever player-visible behavior or configuration changes

10. Locale key naming convention (i18n)

Locale keys must be grouped by feature/setting and use dot-separated segments.

10.1 Base pattern

  • Labels / fixed texts: tradeshuffler.<area>.<setting>[.<detail>]
  • Tooltips: tradeshuffler.<area>.<setting>.tooltip.<variant>.<kind>
  • Key bindings: key.tradeshuffler.<action>; key-binds section: key.category.tradeshuffler.tradeshuffler

Where:

  • <area> is typically screen, config or update
  • <setting> is the exact setting path
  • <variant> identifies option/state
  • <kind> is usually desc (description) or label

10.2 Rules for new keys

  • Keep all 14 language files structurally identical and in the same order. LocaleFilesConsistencyTest enforces this.
  • Place keys in thematic blocks: base strings first, then one block per feature/setting.
  • The server never sends literal text; all UI text is resolved on the client.

For translation file naming, language-code mapping, and contribution workflow, see:

  • the GitHub wiki's Translations page