feat(kæde): kæden kører — skifter frie marker, tænder mellemled, opretter flows
This commit is contained in:
@@ -0,0 +1,321 @@
|
||||
-- AD Chain (kæde-kørsel)
|
||||
-- Hvert minut (efter opstartsfristen): læs gården (ADChainData), byg kæden (ADChainModel), find manglende
|
||||
-- afgrøder (ADCropPlan) og lad ADChainRun skifte frie marker, tænde/slukke mellemled og oprette/stoppe flows.
|
||||
-- Resultatet gemmes i ADChain.last til Kæder-fanen. Tilstanden (byChain, pausede rødder, afviste forslag)
|
||||
-- gemmes i ADSmartPickup_chain.xml under spillets gem. Spiladgang kun inde i funktioner (filen dofile's i test).
|
||||
|
||||
ADChain = {}
|
||||
ADChain.FILE_NAME = "ADSmartPickup_chain.xml"
|
||||
ADChain.ROOT = "ADSmartPickupChain"
|
||||
ADChain.TICK_MS = 60000
|
||||
ADChain.STARTUP_GRACE_MS = 120000
|
||||
ADChain.MAX_FIELD_SWITCHES = 2
|
||||
ADChain.MAX_NEW_FLOWS = 2
|
||||
ADChain.LOG_PREFIX = "ADSmartPickup: kæde: "
|
||||
-- Et afvist forslag vises igen, når manglen for afgrøden har ændret sig mere end dette.
|
||||
ADChain.DISMISS_CHANGE = 0.25
|
||||
|
||||
ADChain.state = {byChain = {}, paused = {}, dismissed = {}}
|
||||
ADChain.last = nil
|
||||
-- run-id -> true: flows kæden oprettede stoppet, fordi der ikke var traktor/vogn (kun i hukommelsen)
|
||||
ADChain.noVehicle = {}
|
||||
ADChain.switchCount = 0
|
||||
ADChain.now = 0
|
||||
ADChain.timer = 0
|
||||
ADChain.collectFailed = false
|
||||
|
||||
local function contains(list, value)
|
||||
for _, item in ipairs(list or {}) do if item == value then return true end end
|
||||
return false
|
||||
end
|
||||
|
||||
local function sortedKeys(map)
|
||||
local keys = {}
|
||||
for key in pairs(map or {}) do table.insert(keys, key) end
|
||||
table.sort(keys, function(a, b) return tostring(a) < tostring(b) end)
|
||||
return keys
|
||||
end
|
||||
|
||||
-- ---- rene hjælpere ----
|
||||
|
||||
function ADChain.newState()
|
||||
return {byChain = {}, paused = {}, dismissed = {}}
|
||||
end
|
||||
|
||||
function ADChain.stateToRecords(state)
|
||||
local records = {byChain = sortedKeys(state.byChain), paused = sortedKeys(state.paused), dismissed = {}}
|
||||
local ids = {}
|
||||
for id in pairs(state.dismissed or {}) do table.insert(ids, id) end
|
||||
table.sort(ids)
|
||||
for _, id in ipairs(ids) do
|
||||
local entry = state.dismissed[id]
|
||||
table.insert(records.dismissed, {id = id, fruit = entry.fruit, missingHa = entry.missingHa})
|
||||
end
|
||||
return records
|
||||
end
|
||||
|
||||
function ADChain.stateFromRecords(records)
|
||||
local state = ADChain.newState()
|
||||
if records == nil then return state end
|
||||
for _, key in ipairs(records.byChain or {}) do state.byChain[key] = true end
|
||||
for _, key in ipairs(records.paused or {}) do state.paused[key] = true end
|
||||
for _, entry in ipairs(records.dismissed or {}) do
|
||||
local id = tonumber(entry.id)
|
||||
if id ~= nil and entry.fruit ~= nil and entry.fruit ~= "" then
|
||||
state.dismissed[id] = {fruit = entry.fruit, missingHa = tonumber(entry.missingHa) or 0}
|
||||
end
|
||||
end
|
||||
return state
|
||||
end
|
||||
|
||||
-- Afviste forslag beholdes kun mens manglen for afgrøden findes og har ændret sig højst 25 %.
|
||||
function ADChain.pruneDismissed(dismissed, shortages)
|
||||
local byFruit = {}
|
||||
for _, shortage in ipairs(shortages or {}) do byFruit[shortage.fruit] = shortage.missingHa end
|
||||
local kept = {}
|
||||
for id, entry in pairs(dismissed or {}) do
|
||||
local now = byFruit[entry.fruit]
|
||||
local before = entry.missingHa or 0
|
||||
if now ~= nil and math.abs(now - before) <= math.abs(before) * ADChain.DISMISS_CHANGE then
|
||||
kept[id] = {fruit = entry.fruit, missingHa = before}
|
||||
end
|
||||
end
|
||||
return kept
|
||||
end
|
||||
|
||||
-- {[mark] = {fruit, missingHa}} -> {[mark] = afgrøde} (ADCropPlan.choose's dismissed)
|
||||
function ADChain.dismissedFruits(dismissed)
|
||||
local result = {}
|
||||
for id, entry in pairs(dismissed or {}) do result[id] = entry.fruit end
|
||||
return result
|
||||
end
|
||||
|
||||
function ADChain.unionFruits(usedFruits, fieldDemand)
|
||||
local result = {}
|
||||
for fruit in pairs(usedFruits or {}) do result[fruit] = true end
|
||||
for fruit in pairs(fieldDemand or {}) do result[fruit] = true end
|
||||
return result
|
||||
end
|
||||
|
||||
-- Kopi af opskrifterne hvor pausede rødder er slukket (så de ikke skaber nye behov).
|
||||
function ADChain.recipesWithPaused(recipes, paused)
|
||||
local result = {}
|
||||
for index, recipe in ipairs(recipes or {}) do
|
||||
local copy = {}
|
||||
for key, value in pairs(recipe) do copy[key] = value end
|
||||
if (paused or {})[recipe.key] then copy.enabled = false end
|
||||
result[index] = copy
|
||||
end
|
||||
return result
|
||||
end
|
||||
|
||||
-- Rødder hvis flows ikke må stoppes: kædens aktuelle rødder + pausede rødder (pause rører intet).
|
||||
function ADChain.activeRoots(chain, paused)
|
||||
local result = {}
|
||||
for _, root in ipairs((chain or {}).roots or {}) do result[root.key] = true end
|
||||
for key in pairs(paused or {}) do result[key] = true end
|
||||
return result
|
||||
end
|
||||
|
||||
-- Mest brugte Wait-pulje blandt forsyningsflows til bygningen, ellers "".
|
||||
function ADChain.waitPoolFor(runs, building)
|
||||
local counts, best, bestCount = {}, "", 0
|
||||
for _, run in ipairs(runs or {}) do
|
||||
local group = run.waitPoolGroup
|
||||
if run.kind == "supply" and group ~= nil and group ~= "" and contains(run.targetBuildingIds, building) then
|
||||
counts[group] = (counts[group] or 0) + 1
|
||||
end
|
||||
end
|
||||
for _, group in ipairs(sortedKeys(counts)) do
|
||||
if counts[group] > bestCount then best, bestCount = group, counts[group] end
|
||||
end
|
||||
return best
|
||||
end
|
||||
|
||||
function ADChain.flowName(fillTitle, buildingName)
|
||||
return "Kæde: " .. tostring(fillTitle) .. " → " .. tostring(buildingName)
|
||||
end
|
||||
|
||||
local function covers(run, edge)
|
||||
return contains(run.targetBuildingIds, edge.consumer)
|
||||
and (run.ingredientMode ~= "manual" or contains(run.ingredients, edge.fillType))
|
||||
end
|
||||
|
||||
-- Bruger en af de aktuelle kanter stadig flowet? -> kantens rodnøgle (flowet flyttes dertil), ellers nil.
|
||||
function ADChain.stillNeeded(runView, edges)
|
||||
for _, edge in ipairs(edges or {}) do
|
||||
if covers(runView, edge) then return edge.rootKey end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- {[forbruger|vare] = "ok"|"missing"|"stopped"|"noVehicle"} for hver kant.
|
||||
function ADChain.flowStatus(edges, runs, noVehicle)
|
||||
local result = {}
|
||||
for _, edge in ipairs(edges or {}) do
|
||||
local status = "missing"
|
||||
for _, run in ipairs(runs or {}) do
|
||||
if run.kind == "supply" and covers(run, edge) then
|
||||
if not run.stopped then status = "ok"; break end
|
||||
if (noVehicle or {})[run.id] then status = "noVehicle"
|
||||
elseif status == "missing" then status = "stopped" end
|
||||
end
|
||||
end
|
||||
result[tostring(edge.consumer) .. "|" .. tostring(edge.fillType)] = status
|
||||
end
|
||||
return result
|
||||
end
|
||||
|
||||
-- Flows i det format ADChainActions regner på.
|
||||
function ADChain.runsView(runs)
|
||||
local list = {}
|
||||
for _, run in ipairs(runs or {}) do
|
||||
table.insert(list, {id = run.id, name = run.name, kind = run.kind, targetBuildingIds = run.targetBuildingIds,
|
||||
ingredientMode = run.ingredientMode, ingredients = run.ingredients, stopped = run.stopped == true,
|
||||
chain = run.chain, waitPoolGroup = run.waitPoolGroup})
|
||||
end
|
||||
return list
|
||||
end
|
||||
|
||||
-- ---- evaluering ----
|
||||
|
||||
local function farmId()
|
||||
return g_currentMission ~= nil and g_currentMission.getFarmId ~= nil and g_currentMission:getFarmId() or 1
|
||||
end
|
||||
|
||||
local function plan(data, state)
|
||||
local recipes = ADChain.recipesWithPaused(data.recipes, state.paused)
|
||||
local chain = ADChainModel.build(recipes, data.husbandry, data.crops)
|
||||
local used = ADChain.unionFruits(data.usedFruits, chain.fieldDemand)
|
||||
local shortages = ADCropPlan.shortages(chain.fieldDemand, data.stock, data.fields, data.yields)
|
||||
state.dismissed = ADChain.pruneDismissed(state.dismissed, shortages)
|
||||
local actions = ADCropPlan.choose(shortages, data.fields, used, data.yields, data.prices, ADChain.dismissedFruits(state.dismissed))
|
||||
-- de ægte opskrifter (ikke kopien): en pauset rod er stadig tændt og må ikke "tændes" og overtages af kæden
|
||||
local prod = ADChainActions.productions(data.recipes, chain.needRecipes, next(state.paused) ~= nil)
|
||||
return {chain = chain, shortages = shortages, actions = actions, prod = prod, edges = ADChainActions.edges(chain)}
|
||||
end
|
||||
|
||||
-- act = true: udfør handlingerne (tick). Uden act kun en frisk visning (GUI).
|
||||
function ADChain.evaluate(adEnv, act)
|
||||
local state = ADChain.state
|
||||
local ok, data = pcall(ADChainData.collect, adEnv, farmId(), state.byChain)
|
||||
if not ok then
|
||||
if not ADChain.collectFailed then Logging.warning(ADChain.LOG_PREFIX .. "gården kunne ikke læses: %s", tostring(data)) end
|
||||
ADChain.collectFailed = true
|
||||
return ADChain.last
|
||||
end
|
||||
ADChain.collectFailed = false
|
||||
local okPlan, result = pcall(plan, data, state)
|
||||
if not okPlan then
|
||||
Logging.warning(ADChain.LOG_PREFIX .. "kæden kunne ikke beregnes: %s", tostring(result))
|
||||
return ADChain.last
|
||||
end
|
||||
if act and ADChainRun ~= nil then ADChainRun.apply(adEnv, data, result) end
|
||||
local runs = ADChain.runsView(ADRunsController.store.runs)
|
||||
local paused = {}
|
||||
for key in pairs(state.paused) do paused[key] = true end
|
||||
ADChain.last = {chain = result.chain, shortages = result.shortages, actions = result.actions, edges = result.edges,
|
||||
missingFlows = ADChainActions.missingFlows(result.edges, runs), flowStatus = ADChain.flowStatus(result.edges, runs, ADChain.noVehicle),
|
||||
paused = paused, data = data, fields = data.fields, titles = data.fillTitles, at = ADChain.now, switchCount = ADChain.switchCount}
|
||||
return ADChain.last
|
||||
end
|
||||
|
||||
function ADChain.tick(adEnv, dt)
|
||||
if adEnv == nil then return end
|
||||
ADChain.now = ADChain.now + (dt or 0)
|
||||
ADChain.timer = ADChain.timer + (dt or 0)
|
||||
if ADChain.now < ADChain.STARTUP_GRACE_MS or ADChain.timer < ADChain.TICK_MS then return end
|
||||
ADChain.timer = 0
|
||||
ADChain.evaluate(adEnv, true)
|
||||
end
|
||||
|
||||
-- ---- GUI-handlinger ----
|
||||
|
||||
local function suggestionFor(fieldId)
|
||||
for _, action in ipairs(ADChain.last ~= nil and ADChain.last.actions or {}) do
|
||||
if action.fieldId == fieldId then return action end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- Godkend forslag: marken får kædens afgrøde som mål (kilde "chain").
|
||||
function ADChain.approve(fieldId)
|
||||
local action = suggestionFor(fieldId)
|
||||
if action == nil then return false end
|
||||
ADFieldJobs.setTarget(fieldId, action.to, "chain")
|
||||
Logging.info(ADChain.LOG_PREFIX .. "F%s: forslag godkendt: %s -> %s", tostring(fieldId), tostring(action.from), tostring(action.to))
|
||||
return true
|
||||
end
|
||||
|
||||
-- Afvis forslag: vises ikke igen, før manglen for afgrøden ændrer sig > 25 %.
|
||||
function ADChain.dismiss(fieldId)
|
||||
local action = suggestionFor(fieldId)
|
||||
if action == nil then return false end
|
||||
local missingHa = 0
|
||||
for _, shortage in ipairs(ADChain.last.shortages or {}) do
|
||||
if shortage.fruit == action.to then missingHa = shortage.missingHa end
|
||||
end
|
||||
ADChain.state.dismissed[fieldId] = {fruit = action.to, missingHa = missingHa}
|
||||
Logging.info(ADChain.LOG_PREFIX .. "F%s: forslag %s afvist", tostring(fieldId), tostring(action.to))
|
||||
return true
|
||||
end
|
||||
|
||||
function ADChain.setPaused(rootKey, isPaused)
|
||||
if rootKey == nil then return end
|
||||
ADChain.state.paused[rootKey] = isPaused and true or nil
|
||||
Logging.info(ADChain.LOG_PREFIX .. "%s %s", tostring(rootKey), isPaused and "på pause" or "genoptaget")
|
||||
end
|
||||
|
||||
-- ---- gem / indlæs (samme sti-opslag som runs; skrives kun fra ADRunsController.save) ----
|
||||
|
||||
local function getPath()
|
||||
local path = ADRunsStorage ~= nil and ADRunsStorage.getPath() or nil
|
||||
if path == nil then return nil end
|
||||
return (path:gsub(ADRunsStorage.FILE_NAME .. "$", ADChain.FILE_NAME))
|
||||
end
|
||||
|
||||
function ADChain.save()
|
||||
local path = getPath()
|
||||
if path == nil then return false end
|
||||
local xmlFile = XMLFile.create("ADSmartPickupChain", path, ADChain.ROOT)
|
||||
if xmlFile == nil then return false end
|
||||
local records = ADChain.stateToRecords(ADChain.state)
|
||||
for index, key in ipairs(records.byChain) do
|
||||
xmlFile:setString(string.format("%s.byChain.recipe(%d)#key", ADChain.ROOT, index - 1), key)
|
||||
end
|
||||
for index, key in ipairs(records.paused) do
|
||||
xmlFile:setString(string.format("%s.paused.root(%d)#key", ADChain.ROOT, index - 1), key)
|
||||
end
|
||||
for index, entry in ipairs(records.dismissed) do
|
||||
local key = string.format("%s.dismissed.field(%d)", ADChain.ROOT, index - 1)
|
||||
xmlFile:setInt(key .. "#id", entry.id)
|
||||
xmlFile:setString(key .. "#fruit", entry.fruit)
|
||||
xmlFile:setString(key .. "#missingHa", string.format("%.2f", entry.missingHa or 0))
|
||||
end
|
||||
xmlFile:save()
|
||||
xmlFile:delete()
|
||||
return true
|
||||
end
|
||||
|
||||
function ADChain.load()
|
||||
ADChain.state = ADChain.newState()
|
||||
ADChain.noVehicle = {}
|
||||
local path = getPath()
|
||||
if path == nil or not fileExists(path) then return end
|
||||
local xmlFile = XMLFile.load("ADSmartPickupChain", path)
|
||||
if xmlFile == nil then return end
|
||||
local records = {byChain = {}, paused = {}, dismissed = {}}
|
||||
xmlFile:iterate(ADChain.ROOT .. ".byChain.recipe", function(_, key)
|
||||
table.insert(records.byChain, xmlFile:getString(key .. "#key"))
|
||||
end)
|
||||
xmlFile:iterate(ADChain.ROOT .. ".paused.root", function(_, key)
|
||||
table.insert(records.paused, xmlFile:getString(key .. "#key"))
|
||||
end)
|
||||
xmlFile:iterate(ADChain.ROOT .. ".dismissed.field", function(_, key)
|
||||
table.insert(records.dismissed, {id = xmlFile:getInt(key .. "#id"), fruit = xmlFile:getString(key .. "#fruit"),
|
||||
missingHa = tonumber(xmlFile:getString(key .. "#missingHa"))})
|
||||
end)
|
||||
xmlFile:delete()
|
||||
ADChain.state = ADChain.stateFromRecords(records)
|
||||
Logging.info(ADChain.LOG_PREFIX .. "%d produktioner tændt af kæden, %d pausede kæder indlæst", #records.byChain, #records.paused)
|
||||
end
|
||||
Reference in New Issue
Block a user