--[[ FarmHUD.lua - FS25_FarmHUD Collects live telemetry from the running savegame and writes it to a small JSON file a few times per second: /My Games/FarmingSimulator2025/modSettings/FS25_FarmHUD/live.json A separate local web server (see the "server/" folder of this project, NOT part of the mod itself) reads that file and serves a browser dashboard. Design notes / why it's built this way --------------------------------------- - Vehicle speed / RPM / cruise control / fuel come from the official Motorized, Drivable and FillUnit specializations (GDN LUADOC, confirmed against this game's own shipped script reference). These are reliable. - g_currentMission.vehicleSystem.vehicles is the same array the engine itself uses internally (VehicleSystem:addVehicle inserts into it), so it is a safe way to enumerate every vehicle in the savegame. - g_currentMission.environment (day/time/weather) is NOT part of the documented scripting API - Giants never published a class for it, so its exact field names have always been something the modding community had to discover by inspection (see e.g. the well-known "Data Dump" mod). Because of that, everything below related to weather/forecast is written defensively: every access is wrapped in pcall, several plausible field/method names are tried, and a console command (fhudDumpEnvironment) is provided to snapshot the *real* structure on your PC to a debug file, in case a future game update renames things. - Every single field is fetched through safeCall()/pcall so one unexpected nil never breaks the whole export - missing data just shows up as "null" in the JSON and "-" in the dashboard instead of an error. What's exported (deliberately broad, so new dashboard features can be built by editing only web/*.js/css/html, without touching this file or restarting the game): - mission: map id/size, current farm id/name/money, playtime, savegame index, multiplayer flag - session: difficulty/gameplay toggles from missionInfo (economic difficulty, whether weeds/stones/plowing-required/traffic are on, ...) - farms: every farm that owns at least one farmland (+ your own), including its loan - farmlands: every plot's id/name/price/owner - silos: per-building fill levels by fill type - husbandries: per-building animal counts, plus best-effort productivity/happiness/health and per-subtype cluster breakdown - productions: recipes + stock (unchanged) - prices: current sell price/liter for every fill type actually seen elsewhere in this snapshot (silos + vehicle tanks) - not the full ~100+ fill type table, just what's relevant right now - players[]: every connected player in the session (name, farm, admin) - single player still reports one entry - missions[]: active/available field missions (contracts) - best effort, see the note on that collector - player: rough world position, whether you're in a vehicle - time / weather: see notes above; now also wind + season progress - vehicles[]: id/name/type/position/heading/speed, RPM/load/motor state, cruise control, ALL fill units (not just fuel), damage/dirt, operating hours, price, owning farm, directly attached implement ids AND what it's itself attached to, turned-on/folded/lights state, whether any player (not just you) is sitting in it - fields[]: real polygon boundary (from the AI field definition nodes, same points the game itself uses), current fruit type + a rough ripeness percent, refreshed every FIELD_REFRESH_INTERVAL_MS - crop state changes over minutes, not milliseconds, so this runs on its own slower timer instead of the main 250ms loop. A few of the additions above (farm.stats/loan details, husbandry productivity, active missions) are NOT in the officially documented LUADOC the same way vehicle/FillUnit data is - they're read the same defensive way as weather (safeCall, several candidate names, never throws). fhudDumpFarmStats (like fhudDumpEnvironment) writes the real structure to a debug file so field names can be corrected quickly if a game update changes them. ]] FarmHUD = {} FarmHUD.MOD_NAME = g_currentModName or "FS25_FarmHUD" FarmHUD.MOD_DIR = g_currentModDirectory or "" FarmHUD.WRITE_INTERVAL_MS = 250 -- ~4 updates/sec, plenty for a dashboard and gentle on disk IO FarmHUD.FIELD_REFRESH_INTERVAL_MS = 3000 -- crop state is slow-changing; no need to resample every frame FarmHUD.VERSION = "1.4.0.0" local function safeCall(fn, ...) if fn == nil then return nil end local ok, result = pcall(fn, ...) if ok then return result end return nil end -- Build a reverse lookup for a Giants-style enum table (e.g. WeatherType.SUN = 0, -- ProductionPoint.PROD_STATUS.RUNNING = 1, ...) so a numeric id from the game -- can be turned back into a readable name. local function buildEnumNames(enumTable) local names = {} if enumTable ~= nil then for key, value in pairs(enumTable) do if type(value) == "number" then names[value] = key end end end return names end local function enumToName(id, nameLookup) if id == nil or nameLookup == nil then return nil end return nameLookup[id] end --- Resolve (and create if needed) the folder the live.json file lives in. --- --- NOTE: this deliberately does NOT use the engine global --- g_currentModSettingsDirectory. With several mods installed, that global --- gets reassigned as each mod loads and is NOT reliably scoped to "this --- mod's own folder" by the time a later event (like loadMap) reads it - --- in testing it pointed at a *different*, later-loaded mod's folder. Building --- the path explicitly from our own mod name (same pattern Courseplay uses) --- is unambiguous. function FarmHUD:getSettingsDir() local dir = getUserProfileAppPath() .. "modSettings/" .. FarmHUD.MOD_NAME .. "/" createFolder(dir) return dir end function FarmHUD:loadMap(name) self.settingsDir = self:getSettingsDir() self.liveFilePath = self.settingsDir .. "live.json" self.debugFilePath = self.settingsDir .. "debug_environment.json" self.debugFarmStatsPath = self.settingsDir .. "debug_farm_stats.json" self.timeSinceWrite = 0 self.timeSinceFieldRefresh = FarmHUD.FIELD_REFRESH_INTERVAL_MS -- refresh fields immediately on the first update self.cachedFields = {} self.weatherTypeNames = buildEnumNames(WeatherType) self.productionStatusNames = ProductionPoint ~= nil and buildEnumNames(ProductionPoint.PROD_STATUS) or {} self.hasLoggedWriteError = false addConsoleCommand("fhudDumpEnvironment", "Dump environment/weather debug info to debug_environment.json", "consoleCommandDumpEnvironment", self) addConsoleCommand("fhudDumpFarmStats", "Dump this farm's stats/loan debug info to debug_farm_stats.json", "consoleCommandDumpFarmStats", self) print(string.format("[FarmHUD] ready - writing live data to: %s", self.liveFilePath)) end function FarmHUD:deleteMap() if self.liveFilePath ~= nil then -- best effort: let a viewer know the game is no longer running local file = io.open(self.liveFilePath, "w") if file ~= nil then file:write(Json.encode({ connected = false, timestamp = getTimeSec ~= nil and getTimeSec() or 0 })) file:close() end end removeConsoleCommand("fhudDumpEnvironment") removeConsoleCommand("fhudDumpFarmStats") end function FarmHUD:update(dt) self.timeSinceFieldRefresh = self.timeSinceFieldRefresh + dt if self.timeSinceFieldRefresh >= FarmHUD.FIELD_REFRESH_INTERVAL_MS then self.timeSinceFieldRefresh = 0 local ok, fields = pcall(function() return self:collectFields() end) if ok then self.cachedFields = fields end end self.timeSinceWrite = self.timeSinceWrite + dt if self.timeSinceWrite < FarmHUD.WRITE_INTERVAL_MS then return end self.timeSinceWrite = 0 local ok, err = pcall(function() self:writeSnapshot() end) if not ok and not self.hasLoggedWriteError then self.hasLoggedWriteError = true print("[FarmHUD] error while collecting/writing data: " .. tostring(err)) end end -------------------------------------------------------------------------------- -- Data collection -------------------------------------------------------------------------------- function FarmHUD:collectMissionInfo() local info = {} if g_currentMission == nil then return info end info.mapId = safeCall(function() return g_currentMission.missionInfo.mapId end) info.mapSize = safeCall(function() return g_currentMission.terrainSize end) info.farmId = safeCall(function() return g_currentMission:getFarmId() end) local farmId = info.farmId if farmId ~= nil and g_farmManager ~= nil then local farm = safeCall(function() return g_farmManager:getFarmById(farmId) end) if farm ~= nil then info.money = safeCall(function() return farm.money end) info.farmName = safeCall(function() return farm.name end) end end -- Session-level info: savegame slot, total playtime, multiplayer. -- All plain fields on missionInfo (no method calls), same low-risk -- pattern as mapId/farmId above. local missionInfo = g_currentMission.missionInfo if missionInfo ~= nil then info.savegameIndex = safeCall(function() return missionInfo.savegameIndex end) info.savegameName = safeCall(function() return missionInfo.savegameName or missionInfo.mapTitle end) -- playTime is observed in FS as minutes (matches the in-game -- statistics screen); exported as-is plus a derived hours value so -- either the dashboard or FarmHUD can use whichever's convenient. info.playTimeMinutes = safeCall(function() return missionInfo.playTime end) info.playTimeHours = info.playTimeMinutes ~= nil and (info.playTimeMinutes / 60) or nil end info.isMultiplayer = safeCall(function() return g_currentMission:getIsServer() ~= nil and true or nil end) if g_currentMission.missionDynamicInfo ~= nil then info.isMultiplayer = safeCall(function() return g_currentMission.missionDynamicInfo.isMultiplayer end) end info.serverName = safeCall(function() return g_currentMission.missionDynamicInfo.serverName end) return info end --- Difficulty/gameplay session toggles - these live as plain fields on --- missionInfo (set once at savegame creation, shown in the "new game" --- wizard), so this is the same low-risk plain-field read as mapId/farmId, --- just grouped separately since it's config rather than live telemetry. function FarmHUD:collectSessionSettings() local info = {} local missionInfo = g_currentMission and g_currentMission.missionInfo if missionInfo == nil then return info end info.economicDifficulty = safeCall(function() return missionInfo.economicDifficulty end) info.difficulty = safeCall(function() return missionInfo.difficulty end) info.growthMode = safeCall(function() return missionInfo.growthMode end) info.plowingRequiredEnabled = safeCall(function() return missionInfo.plowingRequiredEnabled end) info.stonesEnabled = safeCall(function() return missionInfo.stonesEnabled end) info.weedsEnabled = safeCall(function() return missionInfo.weedsEnabled end) info.trafficEnabled = safeCall(function() return missionInfo.trafficEnabled end) info.fuelUsage = safeCall(function() return missionInfo.fuelUsage end) info.helperBuyFruitEnabled = safeCall(function() return missionInfo.helperBuyFruitEnabled end) info.automaticMotorStartEnabled = safeCall(function() return missionInfo.automaticMotorStartEnabled end) return info end function FarmHUD:collectTimeInfo() local info = {} local env = g_currentMission and g_currentMission.environment if env == nil then return info end info.currentDay = safeCall(function() return env.currentDay end) info.currentHour = safeCall(function() return env.currentHour end) info.dayTimeMinutes = safeCall(function() return env.dayTime end) if info.dayTimeMinutes == nil then -- dayTime is sometimes stored in milliseconds since midnight instead of minutes local ms = safeCall(function() return env.dayTimeMS or env.dayTime end) info.dayTimeMinutes = ms end info.timeScale = safeCall(function() return env.timeAdjustment end) info.daysPerPeriod = safeCall(function() return env.daysPerPeriod end) info.currentSeason = safeCall(function() return env.currentSeason end) info.isNight = safeCall(function() return env.isNight and env:isNight() or nil end) -- How far into the current season/period we are, as a 0-100 percent - -- derived from two already-read plain fields (currentDay wraps per -- period on most maps), so this is cheap and doesn't need a new API. local dayInPeriod = safeCall(function() return env.currentDayInPeriod end) info.dayInPeriod = dayInPeriod if dayInPeriod ~= nil and info.daysPerPeriod ~= nil and info.daysPerPeriod > 0 then info.seasonProgressPercent = math.min(100, (dayInPeriod / info.daysPerPeriod) * 100) end return info end --- Best-effort weather + forecast extraction. See the file header for why --- this tries multiple candidate names instead of relying on a single one. function FarmHUD:collectWeatherInfo() local info = { forecast = {} } local env = g_currentMission and g_currentMission.environment local weather = env and env.weather if weather == nil then return info end local typeId = safeCall(function() return weather:getCurrentWeatherType() end) if typeId == nil then typeId = safeCall(function() return weather.currentWeatherType end) end if typeId == nil then typeId = safeCall(function() return weather:getWeatherType() end) end info.currentTypeId = typeId info.currentTypeName = enumToName(typeId, self.weatherTypeNames) local temperature = safeCall(function() return weather:getCurrentTemperature() end) if temperature == nil then temperature = safeCall(function() return weather:getTemperature() end) end if temperature == nil then temperature = safeCall(function() return weather.temperature end) end info.temperatureCelsius = temperature info.isRaining = safeCall(function() return weather:getIsRaining() end) info.isSnowing = safeCall(function() return weather:getIsSnowing() end) info.rainFallScale = safeCall(function() return weather.rainFallScale end) info.snowHeight = safeCall(function() return weather.snowHeight end) -- Wind matters for spraying/spreading in FS25 (drift). Not part of the -- documented LUADOC (same caveat as the rest of this function), so try -- a couple of plausible names and normalize direction to 0-360°. local windX = safeCall(function() return weather.windVelocityX or (weather.wind and weather.wind.x) end) local windZ = safeCall(function() return weather.windVelocityZ or (weather.wind and weather.wind.z) end) info.windSpeed = safeCall(function() return weather:getWindVelocity() end) if info.windSpeed == nil and windX ~= nil and windZ ~= nil then info.windSpeed = math.sqrt(windX * windX + windZ * windZ) end if windX ~= nil and windZ ~= nil then info.windDirectionDeg = (math.deg(math.atan(windX, windZ)) + 360) % 360 end local forecastTable = safeCall(function() return weather:getForecast() end) if forecastTable == nil then forecastTable = safeCall(function() return weather.forecast end) end if forecastTable == nil then forecastTable = safeCall(function() return weather.forecastDays end) end if type(forecastTable) == "table" then for i, entry in ipairs(forecastTable) do local wtype = nil local minTemp, maxTemp = nil, nil if type(entry) == "table" then wtype = entry.weatherType or entry.type or entry.weatherTypeId or entry[1] minTemp = entry.minTemperature or entry.tMin maxTemp = entry.maxTemperature or entry.tMax else wtype = entry end table.insert(info.forecast, { dayOffset = i, typeId = wtype, typeName = enumToName(wtype, self.weatherTypeNames), minTemperatureCelsius = minTemp, maxTemperatureCelsius = maxTemp, }) end end return info end --- Extract everything we can about one vehicle. Wrapped so a weird/partial --- mod vehicle can never take down the whole export. function FarmHUD:collectVehicleData(vehicle, controlledVehicle) local ok, data = pcall(function() local d = {} d.id = safeCall(function() return vehicle:getUniqueId() end) d.name = safeCall(function() return vehicle:getFullName() end) or safeCall(function() return vehicle:getName() end) d.typeName = safeCall(function() return vehicle.typeName end) d.isControlledByPlayer = (vehicle == controlledVehicle) -- Which farm owns this vehicle (Ownable, documented spec) - needed -- to tell vehicles apart on multi-farm/MP savegames. d.ownerFarmId = safeCall(function() return vehicle:getOwnerFarmId() end) -- Whether ANY player is sitting in it right now (Enterable, -- documented), not just whether it's YOUR controlled vehicle - -- useful in multiplayer to see who's driving what. d.isOccupiedByAnyPlayer = safeCall(function() return vehicle.getIsEntered ~= nil and vehicle:getIsEntered() end) -- NOTE: getWorldTranslation/getWorldRotation return 3 values each. -- safeCall() only forwards a single return value (it's meant for -- simple getters), so routing multi-return calls through it silently -- truncated y/z/heading to nil for every vehicle. Use pcall directly -- here instead, since pcall itself forwards all of a call's results. if vehicle.rootNode ~= nil then local ok1, x, y, z = pcall(getWorldTranslation, vehicle.rootNode) if ok1 then d.x = x d.y = y d.z = z end local ok2, _, ry, _ = pcall(getWorldRotation, vehicle.rootNode) if ok2 then d.headingRad = ry end end d.speedKmh = safeCall(function() return vehicle:getLastSpeed() end) -- Motorized (engine) data - only present on self-propelled vehicles. -- getMotorRpmPercentage()/getMotorLoadPercentage() were observed -- returning a 0-1 fraction (e.g. -0.63) rather than a 0-100 value -- despite the "Percentage" name, so normalize defensively: only -- values that are already clearly > 1 are treated as 0-100. if vehicle.getMotorRpmReal ~= nil then d.rpm = safeCall(function() return vehicle:getMotorRpmReal() end) local rpmPercent = safeCall(function() return vehicle:getMotorRpmPercentage() end) d.rpmPercent = rpmPercent ~= nil and (math.abs(rpmPercent) <= 1.5 and rpmPercent * 100 or rpmPercent) or nil d.motorStarted = safeCall(function() return vehicle:getIsMotorStarted() end) local loadPercent = safeCall(function() return vehicle:getMotorLoadPercentage() end) d.motorLoadPercent = loadPercent ~= nil and (math.abs(loadPercent) <= 1.5 and loadPercent * 100 or loadPercent) or nil end -- Drivable (cruise control) - only present on driveable vehicles if vehicle.getCruiseControlState ~= nil then d.cruiseControlState = safeCall(function() return vehicle:getCruiseControlState() end) d.cruiseControlActive = d.cruiseControlState ~= nil and d.cruiseControlState ~= 0 d.cruiseControlSpeed = safeCall(function() return vehicle:getCruiseControlSpeed() end) d.cruiseControlMaxSpeed = safeCall(function() return vehicle:getCruiseControlMaxSpeed() end) end -- Fuel: find whichever fill unit is the vehicle's energy source if vehicle.getConsumerFillUnitIndex ~= nil and FillType ~= nil then local fuelTypes = { FillType.DIESEL, FillType.ELECTRICCHARGE, FillType.METHANE } for _, fillType in ipairs(fuelTypes) do local fillUnitIndex = safeCall(function() return vehicle:getConsumerFillUnitIndex(fillType) end) if fillUnitIndex ~= nil then d.fuelLevel = safeCall(function() return vehicle:getFillUnitFillLevel(fillUnitIndex) end) d.fuelCapacity = safeCall(function() return vehicle:getFillUnitCapacity(fillUnitIndex) end) d.fuelType = fillType break end end end -- ALL tanks (grain, seed, fertilizer, milk, water, ... not just fuel) - -- FillUnit:getFillUnits() (confirmed against this game's shipped -- source) returns the raw fillUnits array with plain fillType/ -- fillLevel/capacity fields, no need to know indices up front. if vehicle.getFillUnits ~= nil then local fillUnits = safeCall(function() return vehicle:getFillUnits() end) if fillUnits ~= nil then d.fillUnits = {} for index, fu in ipairs(fillUnits) do local fillTypeName = g_fillTypeManager ~= nil and safeCall(function() return g_fillTypeManager:getFillTypeTitleByIndex(fu.fillType) end) or nil table.insert(d.fillUnits, { index = index, fillTypeId = fu.fillType, fillTypeName = fillTypeName, fillLevel = fu.fillLevel, capacity = fu.capacity, }) end end end -- Wear (Wearable) and dirt (Washable) - both observed/expected as a -- 0-1 fraction (same "Percentage-named-but-fraction" convention as -- RPM/load above), normalized the same defensive way. if vehicle.getDamageAmount ~= nil then local damage = safeCall(function() return vehicle:getDamageAmount() end) d.damagePercent = damage ~= nil and (math.abs(damage) <= 1.5 and damage * 100 or damage) or nil end if vehicle.getDirtAmount ~= nil then local dirt = safeCall(function() return vehicle:getDirtAmount() end) d.dirtPercent = dirt ~= nil and (math.abs(dirt) <= 1.5 and dirt * 100 or dirt) or nil end -- Operating hours, value. getOperatingTime() returns self.operatingTime -- with no documented unit; following this engine's consistent -- milliseconds convention elsewhere (dayTime, etc.). local operatingTime = safeCall(function() return vehicle:getOperatingTime() end) d.operatingHours = operatingTime ~= nil and (operatingTime / 3600000) or nil d.price = safeCall(function() return vehicle:getPrice() end) d.sellPrice = safeCall(function() return vehicle:getSellPrice() end) -- What's directly attached to this vehicle (e.g. a trailer behind a -- tractor) - lets the dashboard group/graph vehicle "trains" later -- without needing another mod change. if vehicle.getAttachedImplements ~= nil then local implements = safeCall(function() return vehicle:getAttachedImplements() end) if implements ~= nil then d.attachedImplementIds = {} for _, implement in ipairs(implements) do if implement.object ~= nil then local implId = safeCall(function() return implement.object:getUniqueId() end) if implId ~= nil then table.insert(d.attachedImplementIds, implId) end end end end end -- What this vehicle is ITSELF hitched to (Attachable, documented) - -- the reverse direction of attachedImplementIds above, so a -- trailer/implement can be traced back up to whatever's towing it. if vehicle.getAttacherVehicle ~= nil then local attacherVehicle = safeCall(function() return vehicle:getAttacherVehicle() end) if attacherVehicle ~= nil then d.attacherVehicleId = safeCall(function() return attacherVehicle:getUniqueId() end) end end -- Turned on/off (TurnOnVehicle, documented - sprayers, sowing -- machines, mowers, etc.) and folded/unfolded (Foldable, documented - -- transport vs. working width). Both simply absent (nil) on -- vehicles without that specialization, e.g. a plain trailer. if vehicle.getIsTurnedOn ~= nil then d.isTurnedOn = safeCall(function() return vehicle:getIsTurnedOn() end) end if vehicle.getIsFolded ~= nil then d.isFolded = safeCall(function() return vehicle:getIsFolded() end) end -- Lights: raw bitmask (Lights specialization) plus the two states -- most people actually care about decoded out of it. Bit meaning -- isn't in the shipped source to confirm exactly, so this is -- best-effort like the weather fields - a wrong/missing value just -- shows as null, nothing breaks. if vehicle.spec_lights ~= nil then d.lightsTypesMask = safeCall(function() return vehicle.spec_lights.lightsTypesMask end) if type(d.lightsTypesMask) == "number" then d.lightsLowBeamOn = bitAND(d.lightsTypesMask, 1) ~= 0 d.lightsHighBeamOn = bitAND(d.lightsTypesMask, 2) ~= 0 end end return d end) if ok then return data end return nil end function FarmHUD:collectVehicles() local list = {} local vehicles = g_currentMission and g_currentMission.vehicleSystem and g_currentMission.vehicleSystem.vehicles if vehicles == nil then return list end local controlledVehicle = g_currentMission.controlledVehicle for _, vehicle in ipairs(vehicles) do local entry = self:collectVehicleData(vehicle, controlledVehicle) if entry ~= nil then table.insert(list, entry) end end return list end --- All farmland plots (id, price, who owns it) - confirmed against this --- game's shipped Farmland.lua (plain fields, no getters needed). function FarmHUD:collectFarmlands() local list = {} if g_farmlandManager == nil then return list end local farmlands = safeCall(function() return g_farmlandManager:getFarmlands() end) if farmlands == nil then return list end for _, farmland in pairs(farmlands) do local ok, entry = pcall(function() return { id = farmland.id, name = farmland.name, price = farmland.price, isOwned = farmland.isOwned, farmId = farmland.farmId, } end) if ok then table.insert(list, entry) end end return list end --- Every farm that actually owns something right now, plus the current --- player's own farm. Deliberately built from farmland ownership rather --- than a "get all farms" call, since FarmManager isn't in the shipped --- source to verify such a call against. function FarmHUD:collectFarms(farmlands, currentFarmId) local list = {} local seen = {} local function addFarm(farmId) if farmId == nil or seen[farmId] or g_farmManager == nil then return end seen[farmId] = true local farm = safeCall(function() return g_farmManager:getFarmById(farmId) end) if farm ~= nil then table.insert(list, { id = farmId, name = safeCall(function() return farm.name end), money = safeCall(function() return farm.money end), -- loan is a plain field on Farm (confirmed - it's what the -- in-game finance screen reads); loanMaximum is best-effort -- since the exact getter name isn't in the shipped source. loan = safeCall(function() return farm.loan end), loanMaximum = safeCall(function() return farm.getLoanMaximum and farm:getLoanMaximum() end), }) end end addFarm(currentFarmId) for _, farmland in ipairs(farmlands) do if farmland.isOwned then addFarm(farmland.farmId) end end return list end local function resolveFillTypeName(fillTypeId) if fillTypeId == nil or g_fillTypeManager == nil then return nil end return safeCall(function() return g_fillTypeManager:getFillTypeTitleByIndex(fillTypeId) end) end --- {fillTypeId, fillTypeName, fillLevel} for every fill type above a small --- noise threshold in a Storage instance (used by both silos and production --- points - same underlying Storage class per Storage.registerXMLPaths calls --- in both PlaceableSilo and ProductionPoint). local function collectStorageFillTypes(storage) local out = {} if storage == nil or storage.getFillLevels == nil then return out end local levels = safeCall(function() return storage:getFillLevels() end) if levels ~= nil then for fillTypeId, level in pairs(levels) do if type(level) == "number" and level > 0.01 then table.insert(out, { fillTypeId = fillTypeId, fillTypeName = resolveFillTypeName(fillTypeId), fillLevel = level, }) end end end return out end --- Generic pass over every placeable (building) in the savegame, pulling out --- silo fill levels, husbandry (animal building) headcounts, and production --- point recipes/stock. Wrapped per placeable so one broken/modded building --- can't stop the rest. function FarmHUD:collectPlaceables() local silos = {} local husbandries = {} local productions = {} local placeables = g_currentMission and g_currentMission.placeableSystem and g_currentMission.placeableSystem.placeables if placeables == nil then return silos, husbandries, productions end for _, placeable in ipairs(placeables) do pcall(function() local id = safeCall(function() return placeable:getUniqueId() end) or tostring(placeable) local name = safeCall(function() return placeable:getName() end) local ownerFarmId = safeCall(function() return placeable:getOwnerFarmId() end) if placeable.spec_silo ~= nil and placeable.getFillLevels ~= nil then local levels = safeCall(function() return placeable:getFillLevels() end) local fillTypesOut = {} if levels ~= nil then for fillTypeId, level in pairs(levels) do if type(level) == "number" and level > 0.01 then table.insert(fillTypesOut, { fillTypeId = fillTypeId, fillTypeName = resolveFillTypeName(fillTypeId), fillLevel = level, }) end end end table.insert(silos, { id = id, name = name, ownerFarmId = ownerFarmId, fillTypes = fillTypesOut, }) end if placeable.spec_husbandryAnimals ~= nil and placeable.getNumOfAnimals ~= nil then local husbandry = { id = id, name = name, ownerFarmId = ownerFarmId, numAnimals = safeCall(function() return placeable:getNumOfAnimals() end), maxNumAnimals = safeCall(function() return placeable:getMaxNumOfAnimals() end), } -- Productivity/happiness/health: shown as percentages in the -- animal screen, but the exact getter names aren't in the -- shipped source to confirm - tried defensively, best-effort -- like weather. A missing value just doesn't show up. local spec = placeable.spec_husbandryAnimals husbandry.productivityPercent = safeCall(function() local p = placeable.getProductivity and placeable:getProductivity() or spec.productivity return p ~= nil and (math.abs(p) <= 1.5 and p * 100 or p) or nil end) husbandry.happinessPercent = safeCall(function() local h = placeable.getHappiness and placeable:getHappiness() or spec.happiness return h ~= nil and (math.abs(h) <= 1.5 and h * 100 or h) or nil end) husbandry.healthPercent = safeCall(function() local h = placeable.getHealth and placeable:getHealth() or spec.health return h ~= nil and (math.abs(h) <= 1.5 and h * 100 or h) or nil end) -- Per-subtype breakdown (e.g. calves vs. cows) if the -- clusters API is available on this animal type. if placeable.getClusters ~= nil then local clusters = safeCall(function() return placeable:getClusters() end) if type(clusters) == "table" then husbandry.clusters = {} for _, cluster in ipairs(clusters) do local ok3, entry = pcall(function() return { subTypeIndex = cluster.subTypeIndex, numAnimals = cluster.numAnimals, age = cluster.age, isMale = cluster.isMale, } end) if ok3 then table.insert(husbandry.clusters, entry) end end end end table.insert(husbandries, husbandry) end -- Production points (dairies, sawmills, bakeries, ...): confirmed -- against this game's shipped PlaceableProductionPoint.lua - the -- actual ProductionPoint instance (recipes + combined in/out -- storage) lives at spec_productionPoint.productionPoint. if placeable.spec_productionPoint ~= nil then local pp = placeable.spec_productionPoint.productionPoint if pp ~= nil then local recipes = {} if type(pp.productions) == "table" then for _, prod in ipairs(pp.productions) do local inputs, outputs = {}, {} if type(prod.inputs) == "table" then for _, inp in ipairs(prod.inputs) do table.insert(inputs, { fillTypeId = inp.fillType, fillTypeName = resolveFillTypeName(inp.fillType), amount = inp.amount, }) end end if type(prod.outputs) == "table" then for _, out in ipairs(prod.outputs) do table.insert(outputs, { fillTypeId = out.fillType, fillTypeName = resolveFillTypeName(out.fillType), amount = out.amount, }) end end table.insert(recipes, { id = prod.id, name = prod.name, status = prod.status, statusName = enumToName(prod.status, self.productionStatusNames), inputs = inputs, outputs = outputs, }) end end table.insert(productions, { id = id, name = name, ownerFarmId = ownerFarmId, contents = collectStorageFillTypes(pp.storage), recipes = recipes, }) end end end) end return silos, husbandries, productions end --- Best-effort player state. Like weather, the player/localPlayer object --- isn't part of the documented LUADOC, so this tries a couple of plausible --- globals and never throws if none of them match this game version. function FarmHUD:collectPlayerInfo() local info = {} local player = (g_currentMission and g_currentMission.player) or g_localPlayer if player == nil then return info end info.isControllingVehicle = g_currentMission ~= nil and g_currentMission.controlledVehicle ~= nil local rootNode = safeCall(function() return player.rootNode end) if rootNode ~= nil then local ok, x, y, z = pcall(getWorldTranslation, rootNode) if ok then info.x, info.y, info.z = x, y, z end end return info end --- Every connected player in the session (name, which farm, admin/master). --- On single player this still reports exactly one entry. userManager is --- the documented way to enumerate connected users; connectedUsers is the --- plain field it's built from - both tried since naming has moved around --- release to release historically. function FarmHUD:collectPlayersList() local list = {} local userManager = g_currentMission and g_currentMission.userManager if userManager == nil then return list end local users = safeCall(function() return userManager:getUsers() end) if users == nil then users = safeCall(function() return userManager.connectedUsers end) end if type(users) ~= "table" then return list end for _, user in pairs(users) do local ok, entry = pcall(function() return { nickname = safeCall(function() return user:getNickname() end) or user.nickname, farmId = safeCall(function() return user:getFarmId() end) or user.farmId, isMasterUser = safeCall(function() return user:getIsMasterUser() end) or user.isMasterUser, isAdmin = safeCall(function() return user:getIsAdmin() end) or user.isAdmin, } end) if ok then table.insert(list, entry) end end return list end --- Active/available field missions (contracts) - reward, field, type, time --- left. missionManager is documented; the exact fields on each mission --- object vary by mission type (a "mowing" contract has different data --- than a "transport" one), so only the handful common to every --- AbstractFieldMission subtype are read, all defensively. function FarmHUD:collectMissionsList() local list = {} local missionManager = g_missionManager if missionManager == nil then return list end local missions = safeCall(function() return missionManager:getMissions() end) if type(missions) ~= "table" then return list end for _, mission in pairs(missions) do local ok, entry = pcall(function() return { type = mission.type and mission.type.name, fieldId = mission.field and mission.field.fieldId, reward = safeCall(function() return mission:getReward() end) or mission.reward, status = mission.status, farmId = mission.farmId, timeRemaining = safeCall(function() return mission:getRemainingTime() end), } end) if ok then table.insert(list, entry) end end return list end --- Current sell price/liter for every fill type actually seen elsewhere in --- this snapshot (silo contents + vehicle tanks) - deliberately NOT every --- fill type FS25 knows about (~100+, mostly irrelevant noise). economyManager --- is the documented pricing source. function FarmHUD:collectPrices(fillTypeIds) local prices = {} if g_currentMission == nil or g_currentMission.economyManager == nil then return prices end local economyManager = g_currentMission.economyManager for fillTypeId in pairs(fillTypeIds) do local price = safeCall(function() return economyManager:getPricePerLiter(fillTypeId) end) if price ~= nil then prices[tostring(fillTypeId)] = { fillTypeId = fillTypeId, fillTypeName = resolveFillTypeName(fillTypeId), pricePerLiter = price, } end end return prices end --- Every field's real boundary polygon + current crop, so the dashboard can --- draw the same field overview the in-game map shows. --- --- Geometry: field.polygonPoints (confirmed against this game's shipped --- Field.lua) are the actual i3d nodes used for the field's AI/PDA outline - --- their world positions ARE the field boundary, no approximation needed. --- --- Crop: field.fieldState:update(x, z) is a native (engine-side) method - --- not in the shipped Lua source, but FieldManager.lua itself calls it the --- same way, so it's confirmed safe to call. It re-samples the density map --- at that point and refreshes fieldState.fruitTypeIndex/growthState. function FarmHUD:collectFields() local list = {} if g_fieldManager == nil or g_fieldManager.fields == nil then return list end for index, field in ipairs(g_fieldManager.fields) do local ok, entry = pcall(function() local fieldState = field.fieldState if fieldState ~= nil and fieldState.update ~= nil then fieldState:update(field.posX, field.posZ) end local points = {} if field.polygonPoints ~= nil then for _, node in ipairs(field.polygonPoints) do local ok2, x, _, z = pcall(getWorldTranslation, node) if ok2 then table.insert(points, { x = x, z = z }) end end end local fruitTypeIndex = fieldState and fieldState.fruitTypeIndex local isUnknownFruit = fruitTypeIndex == nil or (FruitType ~= nil and fruitTypeIndex == FruitType.UNKNOWN) local fruitTypeName, fruitTitle, growthPercent = nil, nil, nil if not isUnknownFruit and g_fruitTypeManager ~= nil then fruitTypeName = safeCall(function() return g_fruitTypeManager:getFruitTypeNameByIndex(fruitTypeIndex) end) local fillTypeIndex = safeCall(function() return g_fruitTypeManager:getFillTypeIndexByFruitTypeIndex(fruitTypeIndex) end) if fillTypeIndex ~= nil and g_fillTypeManager ~= nil then fruitTitle = safeCall(function() return g_fillTypeManager:getFillTypeTitleByIndex(fillTypeIndex) end) end local desc = safeCall(function() return g_fruitTypeManager:getFruitTypeByIndex(fruitTypeIndex) end) if desc ~= nil and type(desc.maxHarvestingGrowthState) == "number" and desc.maxHarvestingGrowthState > 0 and fieldState ~= nil and type(fieldState.growthState) == "number" then growthPercent = math.min(100, (fieldState.growthState / desc.maxHarvestingGrowthState) * 100) end end return { id = index, name = field.name, areaHa = field.areaHa, posX = field.posX, posZ = field.posZ, points = points, farmlandId = fieldState and fieldState.farmlandId, ownerFarmId = fieldState and fieldState.ownerFarmId, fruitTypeIndex = isUnknownFruit and nil or fruitTypeIndex, fruitTypeName = fruitTypeName, fruitTitle = fruitTitle, growthState = fieldState and fieldState.growthState, growthPercent = growthPercent, } end) if ok then table.insert(list, entry) end end return list end function FarmHUD:writeSnapshot() local missionInfo = self:collectMissionInfo() local farmlands = self:collectFarmlands() local silos, husbandries, productions = self:collectPlaceables() local vehicles = self:collectVehicles() -- Fill types actually in play right now (silo contents + every -- vehicle's tanks) - collectPrices() only prices these, not FS25's -- entire ~100+ fill type table. local relevantFillTypes = {} for _, silo in ipairs(silos) do for _, ft in ipairs(silo.fillTypes or {}) do relevantFillTypes[ft.fillTypeId] = true end end for _, vehicle in ipairs(vehicles) do for _, fu in ipairs(vehicle.fillUnits or {}) do if fu.fillTypeId ~= nil then relevantFillTypes[fu.fillTypeId] = true end end end local snapshot = { connected = true, modVersion = FarmHUD.VERSION, timestamp = getTimeSec ~= nil and getTimeSec() or os.clock(), mission = missionInfo, session = self:collectSessionSettings(), farms = self:collectFarms(farmlands, missionInfo.farmId), farmlands = farmlands, silos = silos, husbandries = husbandries, productions = productions, prices = self:collectPrices(relevantFillTypes), players = self:collectPlayersList(), missions = self:collectMissionsList(), fields = self.cachedFields or {}, player = self:collectPlayerInfo(), time = self:collectTimeInfo(), weather = self:collectWeatherInfo(), vehicles = vehicles, controlledVehicleId = g_currentMission and g_currentMission.controlledVehicle and safeCall(function() return g_currentMission.controlledVehicle:getUniqueId() end) or nil, } local json = Json.encode(snapshot) local file = io.open(self.liveFilePath, "w") if file ~= nil then file:write(json) file:close() end end -------------------------------------------------------------------------------- -- Debug helper: dump the real shape of g_currentMission.environment so field -- names can be corrected quickly if a game update changes them. -------------------------------------------------------------------------------- local function describeValue(value, depth) local t = type(value) if t == "table" and depth > 0 then local out = {} for k, v in pairs(value) do local key = tostring(k) out[key] = describeValue(v, depth - 1) end return out elseif t == "function" then return "" elseif t == "userdata" then return "" elseif t == "table" then return "" else return value end end function FarmHUD:consoleCommandDumpEnvironment() local env = g_currentMission and g_currentMission.environment if env == nil then print("[FarmHUD] g_currentMission.environment is nil (are you in a savegame?)") return end local ok, dump = pcall(function() return { environment = describeValue(env, 2), weather = env.weather ~= nil and describeValue(env.weather, 2) or nil, } end) if not ok then print("[FarmHUD] failed to build debug dump: " .. tostring(dump)) return end local file = io.open(self.debugFilePath, "w") if file ~= nil then file:write(Json.encode(dump)) file:close() print("[FarmHUD] wrote " .. self.debugFilePath) else print("[FarmHUD] could not open " .. tostring(self.debugFilePath) .. " for writing") end end --- Same idea as consoleCommandDumpEnvironment, for the farm's stats/loan --- object - run this in-game (~ key) if farm-level income/expense --- breakdown ever needs adding, to see the real structure without guessing. function FarmHUD:consoleCommandDumpFarmStats() local farmId = g_currentMission and safeCall(function() return g_currentMission:getFarmId() end) local farm = farmId ~= nil and g_farmManager ~= nil and safeCall(function() return g_farmManager:getFarmById(farmId) end) if not farm then print("[FarmHUD] no current farm found (are you in a savegame?)") return end local ok, dump = pcall(function() return { farm = describeValue(farm, 2), stats = farm.stats ~= nil and describeValue(farm.stats, 2) or nil, } end) if not ok then print("[FarmHUD] failed to build debug dump: " .. tostring(dump)) return end local file = io.open(self.debugFarmStatsPath, "w") if file ~= nil then file:write(Json.encode(dump)) file:close() print("[FarmHUD] wrote " .. self.debugFarmStatsPath) else print("[FarmHUD] could not open " .. tostring(self.debugFarmStatsPath) .. " for writing") end end addModEventListener(FarmHUD)