FORGOTTEN TOWNS

FORGOTTEN TOWNS / MODDINGDOCUMENTATIE

Moddingwiki ↗

Java-API-referentie (Javadoc)

MOD API 15

Door de wiki bladeren

Documentatie van de huidige Mod API.

De technische documentatie is beschikbaar in het Engels. Code en veldnamen volgen de huidige Mod API.

MODDINGDOCUMENTATIE

Customize a mod's interface and rules

The Mod API provides validated presentation themes and shared typed settings readers. The SDK presentation examples include covers and about/ui.json. Gameplay settings and tables are captured with the save profile; presentation is captured separately and does not change save compatibility.

Change the presentation

Put this file at about/ui.json. Paths below are relative to about/.

{
  "schema": 1,
  "colors": {"ink":"#422A17", "paper":"#FAEDCB", "border":"#7E582D", "accent":"#DBB33D"},
  "metrics": {"fontSize":14, "smallFontSize":12, "tradeRowHeight":88},
  "images": {"button.buy":"art/buy.png", "map.background":"art/map.png"},
  "labels": {"buy.apple":"mods.your_mod.buy_apples"},
  "assets": {}
}

Only reference images that you supply. Omit a slot to retain the game's appearance. Each shipped theme starts with the game's parchment, oak and gold colors and empty override maps. Themes do not need a manifest field. Use Apply & reload after changing a theme; Refresh in Mods reloads covers and descriptions, but does not reload a running world's UI assets.

Native and default mod menus share HudDesignTokens.Surface and HudDrawing: a light parchment gradient, darker recessed sections, then opaque light cards and buttons. Selected tabs and toggles use a filled gold state; unavailable buttons use muted parchment. ModUi uses the same defaults, including stock and trading tabs. Bundled themes leave color overrides empty so they inherit this hierarchy. Explicit custom colors and image skins still take precedence.

labels values must belong to mods.<owner>.… and exist in all thirteen ordinary manifest translation catalogs. They replace captions, never actions. For instance, renaming a Buy button does not allow it to skip gold or stock validation. Dynamic quantities and costs normally stay in the native caption; an alias replaces that caption in full, so preserve that information in your design.

Colors and spacing

Field Supported values
colors ink, muted, paper, selected, border, accent, button, buttonText, closeButton, closeBorder, closeText, scrollTrack, scrollThumb
Color notation #RRGGBB or #RRGGBBAA
fontSize, smallFontSize 12-18 and 10-16 logical pixels
bodyPadding, cornerRadius 24-52 and 0-20 pixels
tradeRowHeight, exportRowHeight 80-120 and 34-64 pixels
reservationRowHeight, townRowHeight 60-80 and 52-90 pixels
reservationCompactRowHeight 38-64 pixels; current single-line reservation rows, default 42 (reservationRowHeight remains accepted for older engines)
recruitRowHeight, scrollbarWidth 76-120 and 8-20 pixels

Metrics apply to the shared settlement surfaces, not every unrelated native window. Invalid colors, unknown metrics and out-of-range values fail validation instead of silently falling back. The layouts retain minimum sizes so a theme cannot move a purchase target outside its visible row.

Images and buttons

Surface Semantic image slots or button IDs
Shared chrome modal.background, modal.icon, row, row.selected, scroll.track, scroll.thumb
Settlement content surface.overview, surface.trade, resource.<resourceId>
Map map.background, surface.mapDetails, map.city, map.city.current, map.city.disabled, map.city.<stageId>.<state>
Settlement actions rename, overview, trade, shipments, close
Trade tabs tab.traders, tab.settlements, tab.buy, tab.sell
Trade rows buy.<resourceId>, sell.<resourceId>, quantity.minus.buy.<resourceId>, quantity.plus.buy.<resourceId>; corresponding sell variants
Export selector export.add.<resourceId>, export.remove.<resourceId>
Reservations tab.storage, tab.reservations, reserve.add.<resourceId>, reserve.release.<resourceId>, quantity.minus, quantity.plus, quantity.ten
Map actions city.previous, city.next, tab.overview, tab.recruitment, order.<offerId>, trade, close
Equipment conversion, including Sundering tab.operation, tab.storage, category.<lowercase gear slot>, submit, close; resource and modal image slots above

Button images use button.<buttonId>, optionally followed by .normal or .disabled. For example, button.buy.apple.normal falls back to button.buy.apple, then button.buy, then button. The caption remains readable over the image. Disabled controls are also dimmed and keep their host validation. Images are stretched to the supplied bounds; leave internal padding in button artwork. Map backgrounds preserve aspect ratio, and city positions remain normalized.

Close buttons default to the same soft red fill and centered cross as native dialogs. Their closeButton, closeBorder and closeText colors override the fill, outline and symbol; ordinary button colors do not replace these defaults. button.close images and labels.close aliases remain supported. The cross is centered independently of font metrics and UI language.

The map's ornament uses the existing compass asset. To replace that or other native UI artwork, add an exact logical path under assets:

{
  "assets/ui/campaign/map_compass.png": "art/compass.png"
}

This is the value of the theme's assets object, not another top-level file. Only existing PNGs under assets/ui/ can be replaced this way. These replacements are global; when two enabled packs replace the same native asset, the later pack wins. Use semantic slots for owner-specific changes. Sundering's actual bench, shard and particle artwork remains authored in its normal registry data and assets/; Shared Quarters and Love & Birth use native citizen/residence screens and do not inject separate windows or buttons.

Theme files are limited to 64 KiB, referenced PNGs to 8 MiB each, 4096 pixels per edge and 8,000,000 pixels each, and one theme to 128 unique images / 32 MiB / 32,000,000 decoded pixels. Paths cannot escape about/. The loader validates and snapshots the theme before rendering; it never reads image files every frame.

Live menu background

An optional menuBackground object in about/ui.json replaces the global camera tour:

{
  "stageId": "c0_kingdom_harbor",
  "transitionSeconds": 10,
  "views": [
    {"x":59,"y":142,"z":18,"zoom":0.42,"seconds":60},
    {"x":75,"y":129,"z":18,"zoom":0.85,"seconds":60}
  ]
}

The selected stage must have a data-defined bootstrap containing ambient.start. The host installs that stage's scenery and cast, skipping quest.start, and advances only the existing ambient routes and conversations. It never attaches this world to the player session, saves it, advances the world calendar, awards platform achievements, or starts campaign progression. Menu music continues.

Each view holds for seconds - transitionSeconds, then smoothly travels to the next. The last returns to the first; actor routes continue across camera loops. Zoom is relative to 1920 by 1080 and fitted to the actual window. These are positions in the existing isometric projection, not rotations of the map. Supply 2-16 views, 5-300 seconds each, at most 900 seconds total; transition time is 1-20 seconds and must be shorter than every view. Zoom is 0.2-2, coordinates must be finite, and generated-world bounds are checked before display.

Like other presentation inputs, the tour is captured at startup without changing the save profile. The last enabled pack supplying it wins. Unknown fields and invalid bounds fail validation; stage and ambient references are checked by the activation child process. A generation/render-preparation failure retains the bundled assets/ui/menu_first_frame.png still. This opening harbor capture also covers the return to the menu until the live scene is ready, and loading without a retained outgoing frame. It fills the window without stretching and receives the same dimming as the live view. Exploration fog is disabled only for the disposable menu scene. The base five-minute tour lives in assets/data/menu_background.json, referencing C0's data/presentation/c0_menu_tour.json.

The background uses the retained visible renderer at a maximum of 30 frames per second and releases its world and GPU resources when gameplay loading starts. Its menu controls remain a separate cached texture. It adds no video asset or decoder dependency.

Tune the example mods

Mod Authored settings and tables
Sundering Its normal JSON operations define workstation costs, recipes, work duration, success rates, outputs, essences, sprite paths and particle parameters. Its deterministic conversion and optional polygon implementation are in its own small Java entrypoint.
Shared Quarters settings.json: home/crowding zone sets, tiles per resident, crowding/sharing mood values, household exemption and soldier housing.
Love & Birth settings.json: affinity gains/warmth/threshold, relationship moods, conception/failure chances, pregnancy/feeding/childhood seasons, prenatal leave, cooldown years, child aura/scale/visual IDs and birth appearance/sex distribution.
Settlement Trading settings.json: travel days, seasonal income, export cap, estimate ceiling, workstation utilization and buy/sell multipliers. data/production.json: natural-input and collection-infrastructure rules.
Settlement Trading: Campaign Uses the required Settlement Trading core's economy and production table; owns data/markets.json for city identities, unlock stages, initial gold and exports.
Settlement Trading: Campaign Map data/locations.json for names/descriptions, goods, unit offers, gold prices, seasonal quotas and additional unlocks; city travel comes from the required core. data/factions.json owns faction coordinates, explicit trade/delivery terms and recruitment.

ModSettings reads bounded scalar values and requireAllRead() rejects unknown keys. The trading rows describe the preserved source examples. Their policies and data now ship natively; current controls live under Settings → Settlement Trading. The legacy production table remains readable for compatibility, while recurring supply uses recorded completed packing output. Settlement Trading publishes one immutable SettlementTradeCore, containing the TradeEconomy and TradeProductionRules read from its own files. Both extensions resolve this core from their declared dependency. TravelRules supplies its biome travel behavior. TradeProductionRules parses a captured table and validates its resource/placeable references in onRegistriesReady. Collection rules run in authored order: each grants a resource when all listed stations exist and at least one listed prerequisite input is already free. An empty prerequisite list needs only the stations. Fuel is deliberately absent from the offline estimate; live crafting is unchanged.

Only the core ships common economy and production configuration. Recruitment prices and quotas are in the map's location/faction tables; explicit faction terms override common travel and pricing.

Interface behavior and boundaries

Town, product, reservation, export, shipment and recruitment lists clip their content and scroll independently with the wheel or scrollbar. Wide trade panels show Buy and Sell columns together; compact panels switch between them. Every product has its own quantity and buy/sell button showing the total gold amount. Physical reservations keep an explicit shared quantity control.

The examples compile against the public API JAR alone. They do not import mutable game managers, use reflection, intercept rendering, scan save files or issue developer commands. The host owns inventory, gold, save receipts, recruitment arrival placement and the profile-wide seasonal clock. The mods supply rules and consume detached snapshots through supported hooks.

There are intentional engine limits: the 12-day season/48-day year, immutable callback snapshots, non-cheating inventory commands, the bounded recruitment queue, supported housing zone types and existing actor archetypes. Themes can restyle supported surfaces, not inject arbitrary layouts or new button actions. A new mechanic or window still needs a reusable typed engine capability before a mod can use it. This is a supported mod API, not unrestricted access to every internal class.

Gameplay settings, JSON tables and JAR edits change the recorded fingerprint. Updates may load when content and state restoration validate. Keep backups and retain stable definition IDs. Cover and theme changes alone preserve the profile. See Saves and updates.

Review checklist

Validate the pack independently, then with its declared dependencies. Check a compact panel and a language with longer labels. Try an empty list, a long list, depleted stock and insufficient gold. Check the disabled appearance and scroll to the last row. Keep validation of actions in the host command; never make button visibility the only check protecting a purchase.

Native player settings

Open Settings → Mod Settings from either the main menu or the in-game pause menu. Expand an installed pack to see its own controls and any registered keyboard shortcuts. Disabled packs can still expose general settings without executing their code; keyboard commands appear only for packs active in the running session. Both trading extensions link to their required core's settings. Packs without a schema explain that they have no menu-editable general settings.

Validate & save saves only that pack's general settings, preserving the load order and other packs' preferences. Cancel restores its saved general settings; Reset defaults clears the general-settings draft. General changes take effect after restarting the game. The pause menu never reloads a running world's simulation rules. Keyboard changes are independent and apply immediately, with primary/alternate slots, clearing, and explicit confirmation when replacing another command. Resetting the base game's keybindings preserves mod preferences and does not reclaim their active keys.

Native Settlement Trading exposes its economy controls and map shortcut in the separate Settings → Settlement Trading tab. Its previous player overrides remain valid. Shared Quarters exposes its numeric and boolean housing settings; Love & Birth exposes its numeric lifecycle and relationship settings. Town Inspector exposes unit/zone inspection toggles, Sundering exposes its extraction chance bonus, while the native map retains its original shortcut identity. Content identifier strings (such as child sprite IDs and home-zone sets) remain authored in pack JSON. No menu embeds these packs' setting names or values.

The original Main menu → Mods → Settings editor also remains available.

Done keeps a draft in the Mods menu; Cancel discards the open form's edits. Reset defaults clears that form's overrides. Click Apply & reload to validate and start a fresh session in the same window. Changes affect all worlds using this mod profile. They do not modify installed pack files or Workshop downloads.

Authors opt in with "settingsSchema": "settings-schema.json" in the manifest, alongside their existing "settings": "settings.json". For example, if the default settings contain "travelDays.MEADOWS": 3:

[
  {
    "key": "travelDays.MEADOWS",
    "type": "integer",
    "labelKey": "mods.your_mod.travel.label",
    "descriptionKey": "mods.your_mod.travel.help",
    "min": 1,
    "max": 48,
    "step": 1
  }
]

Every field must reference an existing scalar default. Supported types are boolean, integer, number and choice; numeric fields require finite min, max, step values, and a choice supplies "choices": {"value": "mods.your_mod.choice.label"}. All labels/help/choice labels must be owned by the mod and supplied in all thirteen runtime translation catalogs. Forms are readable while disabled without executing mod code. Limits: 64 KiB per schema, 64 fields, 32 choices, numeric bounds ±1,000,000.

The host stores per-mod overrides in the settings object of the user mod profile's enabled.json, validates them against the schema, then runs ordinary activation validation. A failed candidate leaves the saved profile untouched. Disabling a mod retains its preferences for later use. Dependencies still load first, and the shared trading core receives the effective settings before its extensions.

Only the effective settings enter the captured gameplay hash; presentation edits remain separate. The captured session includes settings/<modId>.json when overrides change defaults. Changing gameplay settings participates in normal save compatibility checks: keep a backup before altering an ongoing game.

Mod-owned keyboard shortcuts

Register a shortcut in the pack's GameMod.register method:

context.registerKeyboardShortcut(new KeyboardShortcut(
        "your_mod:map", "mods.your_mod.shortcuts.map",
        KeyboardShortcut.Command.SETTLEMENT_MAP, 77, 0, ""));

The ID and translated label belong to the registering pack. Supply the label in every supported language. key and modifiers use GLFW key codes and Shift/Control/Alt/Super bits; the example defaults to M. The current operations are SETTLEMENT_MAP and COLONY_PANELS, backed by the same capability checks as their HUD buttons. This API does not execute arbitrary mod callbacks on the UI thread. Base commands win an unresolved default collision; the editor can explicitly reassign it.

The final argument is an optional obsolete preference ID to migrate. Settlement Map declares its former settlement_map identity here, so migration requires no pack-specific case in the engine. Preferences use namespaced action IDs in local keyboard settings. Disabling a pack removes its commands while preserving those preferences. Mods cannot dispatch a legacy gameplay key by choosing its physical shortcut: registered operations follow a separate command path.

Use explicit-value TravelRules and TradeEconomy constructors. New trade packs own their setting names, defaults and parsing, then pass validated values into these shared utility types.