La documentazione tecnica è disponibile in inglese. Code and field names follow the current Mod API.
DOCUMENTAZIONE DI MODIFICA
Colony simulation extensions
Register a ColonyExtension to add persistent colony behaviour. Its callbacks receive scoped
queries and validated commands inside the running game.
Two complete projects demonstrate this boundary:
- Shared Quarters adds bed-based housing and crowding moods.
- Love & Birth uses conversations, relationships, family housing, pregnancy and children.
Both compile against only forgotten-towns-mod-api-15.jar. Neither requires the other, Sundering,
an engine JAR, reflection, or changes to game source. Their game rules live in their own JARs.
Start with a world-owned extension
Register a factory during your GameMod.register callback:
context.registerColonyExtension(MyColonyRules::new);
The game creates a fresh ColonyExtension for each world. Never put world state in static fields.
Use restore(Map<String,String>) to recover your state and save() to capture it. Your namespace
is chosen by the loader from your manifest ID, so one mod cannot write another mod's save state.
update(ColonyContext) runs on first attachment, after restoration and once per game minute.
It can also run after conversations, native event delivery or a player changes a home assignment, including while paused. A minute is
30 real seconds at normal speed. There are 20 minutes per day, 12 days per season and 48 days per year.
Use view().day() and a saved last-processed day to prevent duplicate daily events on refresh or load.
Development calendar jumps advance the date; they do not replay every skipped day.
onConversation(context, firstId, secondId) fires once when the simulation starts a social exchange.
Audio admission, muting and camera position do not determine whether the event occurs. It does not
promise the conversation finishes. The normal talk cooldown still controls how frequently citizens talk.
Callbacks run synchronously on the simulation thread. Keep them short. Contexts and their views expire when the callback returns. Immutable value records may be retained, but represent an old snapshot. Callback failures stop the operation and identify the mod; the game does not silently discard its rules.
Query bounded snapshots
context.view() provides:
| Query | Result |
|---|---|
citizens() / citizen(id) |
Roster values: identity, name, sex, life/role flags, location, projected household and bed requirement |
homes() / home(id) / homeOf(citizenId) |
Zone identity/type, floor area, living residents, complete bed footprints and exclusive bed assignments |
nearby(position, radius) |
Living citizens within 0-32 tiles on the same level, using the shared snapshot's spatial index |
day() / daysPerSeason() / daysPerYear() |
The world's calendar |
Nearby queries use Chebyshev distance: radius three includes a seven-by-seven tile square. Beds are adjacent only when their complete footprints share a cardinal edge on the same level. A corner does not count. Home area is the zone's floor-tile count, including furniture tiles.
Query the view again after commands to obtain refreshed values. Avoid asking for a fresh full snapshot after every modifier; collect the decisions, apply them, then query once more if necessary.
Use commands, not engine managers
modify(citizenId, modifiers) replaces only your mod's derived effects. Modifiers.NONE clears
them. Effects can restrict work/promotion, ordinary eating and individual-bed needs; change actor scale
or an existing visual archetype; supply a namespaced household and preferred bed; and add localized
roster statuses. A work restriction releases existing claims and drops carried resources through normal
accounting before the citizen switches to needs and idle behavior. Fed citizens maintain hunger;
citizens exempt from an individual bed maintain rest. Restrictions combine using logical AND.
Visual scale multiplies and is clamped to 0.25-2. Conflicting nonempty visual/household/bed overrides
resolve in lexical mod-ID order, with the last taking precedence. Coordinate such overrides with dependencies.
The Mod API provides permitsProfession and allAttributesBonus. Profession restrictions suppress the
profession labels and all their bonuses, including auras. Primary attribute bonuses add across mods
up to 100 per attribute and affect combat statistics as well as the overview. Both are projections
rebuilt from mod state, so refreshing or loading cannot stack growth. The eight-argument
constructor keeps professions enabled and adds no attributes. Love & Birth uses these fields for
permanently professionless colony-born people and +1 to every primary attribute from adulthood.
assignHome(citizenId, homeId) checks eligibility, household policy and bed capacity before changing
an assignment. Failure preserves the old home. spawnCivilian(nearId, female, appearanceVariant)
uses normal unique identity allocation and nearby walkable placement; it returns -1 when placement
is unavailable. Spawning is explicit: save the outcome so a retry never duplicates a citizen.
dailyRoll(eventKey, bound) returns a deterministic value for the world seed, day, mod ID and key.
It does not consume the base game's random stream. Include your saved event sequence for repeated
same-day conversations. Save outcomes that must stay fixed when a later-day retry is necessary.
Housing and happiness
Register HousingPolicy for supported home zone IDs. A policy can expand occupancy to one resident
per bed, restrict that expansion to a shared household, and allow soldiers with a household into
residential zones. Policies are additive: Shared Quarters can allow strangers while Love & Birth
provides family-only expansion when installed alone. An existing resident is not evicted if a bed is
removed; they may have to sleep on the floor. Bed-exempt citizens do not consume a bed slot.
moods(view, citizen) runs after all extensions have projected modifiers. It must be read-only.
Return localized Mood values, each from −100 to +100 happiness per game minute, matching the
base game's recurring happiness sources. An empty stacking key adds normally. A shared nonempty
key applies only the effect with the largest absolute amount, preventing overlapping auras stacking.
These sources appear in the normal happiness breakdown. Ordinary food, weather and rest-room effects
continue to apply alongside mod sources.
Citizen affinity
Override ColonyExtension.affinities(ColonyContext.View) to expose directed feelings in the native
citizen roster. Return immutable ColonyAffinity(fromCitizenId, toCitizenId, value) records, for example:
@Override
public List<ColonyAffinity> affinities(ColonyContext.View world) {
return List.of(new ColonyAffinity(1, 2, 45), new ColonyAffinity(2, 1, -12));
}
Use actual saved citizen IDs in a real mod. Values must be −100…100; IDs must be positive and distinct. The host accepts at most 16,384 directed pairs per mod and rejects duplicates from the same provider. Zero values and missing/dead participants are omitted. Different mods' feelings remain separate; hovering identifies the provider. The default callback returns no affinities, so older mods need no changes.
This read-only callback runs after extension updates, at simulation boundaries and after loading. Conversations mark projections dirty for the next boundary. The host publishes immutable per-citizen lists with a revision only when values change; rendering never invokes mod callbacks. The scoped view must not be retained. Relationship rules and save persistence remain entirely mod-owned.
Expand a citizen to see a scrollable Affinity column beside Happiness, with names, outgoing (→) and
incoming (←) signed values and bars. Fully neutral relationships are hidden. In the Mod API, override
ColonyExtension.providesAffinities() to return true to expose the panel before any relationships
exist. Without an active provider the roster column and inspector Relationships tab are absent.
Older providers remain compatible: returning affinity data also enables the presentation.
Capability and relationship changes share the snapshot revision; drawing never calls mod code.
Love & Birth declares this capability, retains feelings after pairing and keeps updating them through
conversations. The host does not calculate feelings or invent replacement values.
State, settings and localization
Save at most 16,384 string entries and one MiB of UTF-8 keys/values per mod. Include a schema number and validate restored data. The atomic game save contains detached strings, not serialized mod classes. Derived modifiers and moods must be rebuilt after loading. Updated JARs and settings change the diagnostic fingerprint; loading is allowed when content and saved state remain compatible. A nonempty state map without its registered colony restorer is a critical error, not silently discarded data.
Optional manifest field "settings": "settings.json" points to a captured JSON object of at most
128 scalar values and 64 KiB. Read its immutable contents through ModContext.settings() during
registration. Validate keys, types and ranges in your mod. The Mod API supports native player settings; choose Apply & reload to rebuild the session in the same window after changing them.
Notification, status and mood keys must begin with mods.<your_id>. and belong in all thirteen translation
catalogs. Status arguments can contain current names or numbers. Presentation name/description and an
optional cover remain in the reserved about/ folder; see covers and descriptions.
Current limits
The API exposes citizen/home views, the citizen commands above, recurring projections, conversation
events and mod save state. Settlement trading adds detached town/production
queries through ColonyContext.settlement() and production(), plus a dedicated trade policy.
The Mod API provides physical inventory, native work and placeable construction, including
terminal callbacks and save-stable job IDs. The Mod API provides native events and player notifications,
with the standalone Memorials example. Structural/crafting/hauling submission, arbitrary new work
executors, terrain mutation, custom combat AI and custom UI panels remain outside this interface.
