FORGOTTEN TOWNS
Sample mods Settlement TradingCONTENT API 15
Browse the study

Original source preserved
22 October 2026
File checksums ↗

SETTLEMENT MAP / JAVA SOURCE

SettlementMapMod.java

src/settlementmap/SettlementMapMod.java

Preserved original · 10,154 bytesDownload original file
package settlementmap;

import forgottentowns.mod.api.*;
import java.util.*;

/** Campaign map extension using shared trading rules and captured city/faction tables. */
public final class SettlementMapMod implements GameMod {
    /** Creates the campaign map extension entry point. */
    public SettlementMapMod() { }
    /** Registers authored city locations and recruitment offers.
     * @param context startup API and captured location table
     * @throws IllegalArgumentException if the required core is unavailable or a location/faction table is malformed
     */
    @Override public void register(ModContext context) {
        context.registerKeyboardShortcut(new KeyboardShortcut("settlement_map:open_map", "mods.settlement_map.shortcut",
                KeyboardShortcut.Command.SETTLEMENT_MAP, 77, 0, "settlement_map"));
        var core=context.requireSettlementTradeCore("settlement_trading");
        if (!(context.dataTable("locations") instanceof List<?> rows)) throw new IllegalArgumentException("locations must be an array");
        List<SettlementMap.Location> locations = new ArrayList<>(); Set<String> stages = new HashSet<>();
        for (Object row : rows) {
            if (!(row instanceof Map<?,?> data)) throw new IllegalArgumentException("location must be an object");
            if (!Set.of("stage","nameKey","descriptionKey","exports","recruits","useSettlementName").containsAll(data.keySet())
                    || !data.keySet().containsAll(Set.of("stage","nameKey","descriptionKey","exports","recruits"))) throw new IllegalArgumentException("Unknown or missing location field");
            String stage = text(data,"stage");
            if (!stage.matches("c[0-9]+_[a-z0-9_]+") || !stages.add(stage)) throw new IllegalArgumentException("Duplicate or invalid stage " + stage);
            List<SettlementMap.Recruit> offers = new ArrayList<>();
            if (!(data.get("recruits") instanceof List<?> recruits) || !(data.get("exports") instanceof Map<?,?> exports))
                throw new IllegalArgumentException("location requires exports and recruits");
            Set<String> ids = new HashSet<>();
            for (Object raw : recruits) {
                if (!(raw instanceof Map<?,?> recruit)) throw new IllegalArgumentException("recruit must be an object");
                if(!Set.of("id","unit","gold","perSeason","requiresCompletedStage").containsAll(recruit.keySet()))throw new IllegalArgumentException("Unknown recruit field");
                if(recruit.containsKey("requiresCompletedStage")&&!(recruit.get("requiresCompletedStage") instanceof String))throw new IllegalArgumentException("Invalid recruitment unlock");
                String id = text(recruit,"id"); if (!ids.add(id)) throw new IllegalArgumentException("Duplicate offer " + id);
                offers.add(new SettlementMap.Recruit(id,text(recruit,"unit"),number(recruit.get("gold"),1,100000),
                        number(recruit.get("perSeason"),0,1000),recruit.get("requiresCompletedStage") instanceof String value ? value : ""));
            }
            Map<String,Integer> goods = new TreeMap<>(); exports.forEach((id,value) -> goods.put(id.toString(),number(value,0,100000)));
            Object useName = data.containsKey("useSettlementName") ? data.get("useSettlementName") : Boolean.TRUE;
            if (!(useName instanceof Boolean useSettlementName)) throw new IllegalArgumentException("useSettlementName must be boolean");
            locations.add(new SettlementMap.Location(stage,text(data,"nameKey"),text(data,"descriptionKey"),goods,offers,useSettlementName));
        }
        List<SettlementMap.Location> authored = List.copyOf(locations);
        var factionTable = readFactions(context.dataTable("factions"));
        var factions = new java.util.concurrent.atomic.AtomicReference<List<SettlementMap.Faction>>(List.of());
        context.onRegistriesReady(registries -> {
            Set<String> resources = new HashSet<>();
            registries.entries("resources").forEach(resource -> resources.add(resource.id()));
            for (var placeable : registries.entries("placeables")) {
                if (placeable.values().get("craftedResource") instanceof Map<?,?> crafted)
                    resources.add(crafted.get("resourceId") instanceof String id ? id : "crafted_placeable_" + placeable.id());
            }
            List<SettlementMap.Faction> resolved = new ArrayList<>();
            for (var row : factionTable) {
                var faction = row.faction(); Set<String> refused = new HashSet<>(faction.refusedResources());
                for (var resource : registries.entries("resources"))
                    if (row.refusedStockpiles().contains(resource.values().get("stockpileZoneId"))) refused.add(resource.id());
                if (!resources.containsAll(faction.exports().keySet()) || !resources.containsAll(refused))
                    throw new IllegalArgumentException("Unknown faction resource " + faction.id());
                resolved.add(new SettlementMap.Faction(faction.id(),faction.nameKey(),faction.descriptionKey(),faction.biome(),
                        faction.x(),faction.y(),faction.travelDays(),faction.exports(),faction.recruits(),refused,
                        faction.buyFromPlayerPercent(),faction.initialGold(),faction.seasonalGold()));
            }
            factions.set(List.copyOf(resolved));
        });
        context.registerSettlementMap(new SettlementMap() {
            @Override public boolean supports(SettlementTrading.World world) { return !world.campaignStage().isBlank() && !world.campaignProfile().isBlank(); }
            @Override public List<Location> locations(SettlementTrading.World world) { return authored; }
            @Override public List<Faction> factions(SettlementTrading.World world) { return factions.get(); }
            @Override public int travelDays(String biome) { return core.economy().travelDays(biome); }
        });
    }
    private record FactionRow(SettlementMap.Faction faction,Set<String> refusedStockpiles) { }
    private static List<FactionRow> readFactions(Object table) {
        if (!(table instanceof List<?> rows) || rows.size()>32) throw new IllegalArgumentException("Invalid factions table");
        List<FactionRow> factions=new ArrayList<>(); Set<String> ids=new HashSet<>();
        for (Object row:rows) {
            if (!(row instanceof Map<?,?> data) || !data.keySet().equals(Set.of("id","nameKey","descriptionKey","biome","x","y",
                    "travelDays","exports","recruits","refusedResources","refusedStockpiles","buyFromPlayerPercent","initialGold","seasonalGold")))
                throw new IllegalArgumentException("Invalid faction fields");
            String id=text(data,"id"),name=text(data,"nameKey"),description=text(data,"descriptionKey");
            if(!id.matches("settlement_map:[a-z][a-z0-9_]*") || !ids.add(id)
                    || !name.startsWith("mods.settlement_map.") || !description.startsWith("mods.settlement_map."))
                throw new IllegalArgumentException("Invalid faction identity " + id);
            if (!(data.get("exports") instanceof Map<?,?> exports) || exports.size()>15
                    || !(data.get("recruits") instanceof List<?> recruits) || recruits.size()>32)
                throw new IllegalArgumentException("Invalid faction stock");
            Map<String,Integer> goods=new TreeMap<>(); exports.forEach((key,value)->goods.put(key.toString(),number(value,0,100000)));
            List<SettlementMap.Recruit> offers=new ArrayList<>(); Set<String> offerIds=new HashSet<>();
            for(Object raw:recruits) {
                if(!(raw instanceof Map<?,?> recruit) || !recruit.keySet().equals(Set.of("id","unit","gold","perSeason")))
                    throw new IllegalArgumentException("Invalid faction recruit");
                String offer=text(recruit,"id"); if(!offer.matches("[a-z][a-z0-9_]*") || !offerIds.add(offer)) throw new IllegalArgumentException("Duplicate/invalid recruit");
                offers.add(new SettlementMap.Recruit(offer,text(recruit,"unit"),number(recruit.get("gold"),1,100000),number(recruit.get("perSeason"),0,1000),""));
            }
            factions.add(new FactionRow(new SettlementMap.Faction(id,name,description,text(data,"biome"),coordinate(data.get("x")),coordinate(data.get("y")),
                    number(data.get("travelDays"),1,48),goods,offers,strings(data.get("refusedResources")),number(data.get("buyFromPlayerPercent"),0,1000),
                    number(data.get("initialGold"),0,100000),number(data.get("seasonalGold"),0,100000)),strings(data.get("refusedStockpiles"))));
        }
        return List.copyOf(factions);
    }
    private static Set<String> strings(Object value) {
        if(!(value instanceof List<?> list) || list.size()>4096) throw new IllegalArgumentException("Expected bounded strings");
        Set<String> result=new HashSet<>(); for(Object entry:list) {
            if(!(entry instanceof String id) || id.isBlank() || !result.add(id)) throw new IllegalArgumentException("Invalid or duplicate string");
        }
        return Set.copyOf(result);
    }
    private static double coordinate(Object value) {
        if(!(value instanceof Number n) || !Double.isFinite(n.doubleValue()) || n.doubleValue()<0 || n.doubleValue()>1)
            throw new IllegalArgumentException("Faction coordinates must be within 0..1");
        return n.doubleValue();
    }
    private static String text(Map<?,?> data,String key) {
        if (!(data.get(key) instanceof String value) || value.isBlank()) throw new IllegalArgumentException("Missing " + key); return value;
    }
    private static int number(Object value,int min,int max) {
        if (!(value instanceof Number n) || !Double.isFinite(n.doubleValue()) || n.doubleValue()!=n.intValue() || n.intValue()<min || n.intValue()>max)
            throw new IllegalArgumentException("Expected integer within " + min + ".." + max); return n.intValue();
    }
}