Модуль:Песочница/Pok
Материал из Space Station 14 Вики
Для документации этого модуля может быть создана страница Модуль:Песочница/Pok/doc
local p = {}
---------------------------------------------------------------------
-- Загрузка данных
---------------------------------------------------------------------
local itemData = mw.loadData("Модуль:IanComradeBot/prototypes/fills/Item.json/data")
local tableData = mw.loadData("Модуль:IanComradeBot/prototypes/table.json/data")
local gearData = mw.loadData("Модуль:IanComradeBot/startingGear.json/data")
local jobData = mw.loadData("Модуль:IanComradeBot/job.json/data")
local gearRoleLoadout = mw.loadData("Модуль:IanComradeBot/roleLoadout.json/data")
local loadoutData = mw.loadData("Модуль:IanComradeBot/loadout.json/data")
local loadoutGroupData = mw.loadData("Модуль:IanComradeBot/loadoutGroup.json/data")
local cargoData = mw.loadData("Модуль:IanComradeBot/prototypes/сargo.json/base")
local latheData = mw.loadData("Модуль:IanComradeBot/prototypes/lathe.json/data")
local recipeData = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipes.json/data")
local researchData = mw.loadData("Модуль:IanComradeBot/prototypes/research.json/data")
local materialData = mw.loadData("Модуль:IanComradeBot/prototypes/materials.json/data")
local chemDataLathe = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
local vendingMachinesData = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines.json/data")
local inventoriesData = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines/inventories.json/data")
---------------------------------------------------------------------
-- Функции для обратного поиска
---------------------------------------------------------------------
local function searchItemInStructure(struct, targetId)
if type(struct) ~= "table" then
return false
end
if struct.id and struct.id == targetId then
return true
end
for _, v in pairs(struct) do
if type(v) == "table" then
if searchItemInStructure(v, targetId) then
return true
end
end
end
return false
end
---------------------------------------------------------------------
local function findRelatedTables(initialList)
local results = {}
local function recursiveSearch(tblId)
if results[tblId] then
return
end
results[tblId] = true
for id, entry in pairs(tableData) do
if type(entry) == "table" then
for _, value in pairs(entry) do
if type(value) == "table" and value.tableId and value.tableId == tblId then
recursiveSearch(id)
end
end
end
end
end
for _, tblId in ipairs(initialList) do
recursiveSearch(tblId)
end
local res = {}
for id in pairs(results) do
table.insert(res, id)
end
return res
end
local function searchTableIdInStructure(struct, tableIds)
if type(struct) ~= "table" then
return false
end
if struct.tableId then
for _, tid in ipairs(tableIds) do
if struct.tableId == tid then
return true
end
end
end
for _, v in pairs(struct) do
if type(v) == "table" then
if searchTableIdInStructure(v, tableIds) then
return true
end
end
end
return false
end
---------------------------------------------------------------------
-- Общая логика поиска хранилищ, содержащих указанный targetId
---------------------------------------------------------------------
local function findMatchingStorages(targetId)
local initialTables = {}
for key, tblEntry in pairs(tableData) do
if type(tblEntry) == "table" then
if searchItemInStructure(tblEntry, targetId) then
local tableId = tblEntry.id or key
table.insert(initialTables, tableId)
end
end
end
local allRelatedTables = {}
if #initialTables > 0 then
allRelatedTables = findRelatedTables(initialTables)
end
local matchingStorages = {}
for storageKey, storage in pairs(itemData) do
if type(storage) == "table" then
local found = false
if storage.EntityTableContainerFill
and storage.EntityTableContainerFill.containers then
if searchTableIdInStructure(storage.EntityTableContainerFill.containers, allRelatedTables) then
found = true
end
end
if searchItemInStructure(storage, targetId) then
found = true
end
if found then
local actualId = storage.id or storageKey
table.insert(matchingStorages, actualId)
end
end
end
return matchingStorages
end
---------------------------------------------------------------------
function p.reverseContained(frame)
local targetId = frame.args[2]
if not targetId or targetId == "" then
return "Ошибка: не указан id предмета для обратного поиска."
end
local matchingStorages = findMatchingStorages(targetId)
local filteredStorages = {}
for _, sid in ipairs(matchingStorages) do
local skip = false
for _, cargo in pairs(cargoData) do
if type(cargo) == "table" and cargo.product == sid then
skip = true
break
end
end
if not skip then
table.insert(filteredStorages, sid)
end
end
if #filteredStorages == 0 then
return ""
end
local filteredStoragesLinks = {}
for _, storage in ipairs(filteredStorages) do
table.insert(filteredStoragesLinks, "[[{{#invoke:Entity Lookup|getname|" .. storage .. "}}|{{#invoke:Entity Lookup|getname|" .. storage .. "}}]]")
end
return "Находится хранилище: " .. table.concat(filteredStorages, ", ")
end
---------------------------------------------------------------------
function p.reverseEquipment(frame)
local targetId = frame.args[2]
local slotFilter = frame.args[3]
if not targetId or targetId == "" then
return "Ошибка: не указан id оборудования для обратного поиска."
end
local results = {}
-- Обработка startingGear (gearData)
for _, gear in pairs(gearData) do
local currentGearId = gear.id or "Unknown"
if gear.equipment then
for slot, equipId in pairs(gear.equipment) do
if equipId == targetId and (not slotFilter or slot == slotFilter) then
local foundJob = nil
for jobId, job in pairs(jobData) do
if job.startingGear == currentGearId then
foundJob = jobId
break
end
end
if foundJob then
table.insert(results, "{{ucfirst:{{#invoke:Ftl|main|translation|" .. foundJob .. "}}}}")
end
end
end
end
end
-- Обработка loadout (loadoutData)
for _, loadout in pairs(loadoutData) do
if loadout.equipment then
for slot, equipId in pairs(loadout.equipment) do
if equipId == targetId and (not slotFilter or slot == slotFilter) then
local foundGroupId = nil
-- Поиск группы в loadoutGroupData, в которой присутствует loadout.id
for _, group in pairs(loadoutGroupData) do
if group.loadouts and type(group.loadouts) == "table" then
for _, lId in ipairs(group.loadouts) do
if lId == loadout.id then
foundGroupId = group.id
break
end
end
end
if foundGroupId then break end
end
local foundJob = nil
-- Поиск роли в gearRoleLoadout, где группы содержат найденный id группы
if foundGroupId then
for _, role in pairs(gearRoleLoadout) do
if role.groups then
for _, g in ipairs(role.groups) do
if g == foundGroupId then
foundJob = role.id
break
end
end
end
if foundJob then break end
end
end
if foundJob then
table.insert(results, "{{ucfirst:{{#invoke:Ftl|main|translation|" .. foundJob .. "}}}}")
end
end
end
end
end
if #results == 0 then
return "Оборудование с id " .. targetId .. " не найдено в наборах экипировки."
end
return "Начальная экипировка роли: " .. table.concat(results, ", ")
end
---------------------------------------------------------------------
function p.reverseCargo(frame)
local searchValue = frame.args[2]
if not searchValue or searchValue == "" then
return "Ошибка: не указано значение для поиска в режиме cargo."
end
-- Сначала ищем прямые совпадения в cargoData по product
local directCargo = {}
for _, entry in ipairs(cargoData) do
if entry.product == searchValue then
table.insert(directCargo, entry.id)
end
end
if #directCargo > 0 then
return "Найденные записи cargo: " .. table.concat(directCargo, ", ")
end
-- Если не найдено прямых совпадений, выполняем обратный поиск как в reverseContained,
-- но оставляем только те хранилища, которые присутствуют в cargoData (т.е. имеют product равный их id)
local matchingStorages = findMatchingStorages(searchValue)
local cargoStorages = {}
for _, sid in ipairs(matchingStorages) do
for _, cargo in pairs(cargoData) do
if type(cargo) == "table" and cargo.product == sid then
table.insert(cargoStorages, sid)
break
end
end
end
if #cargoStorages == 0 then
return ""
end
local cargoLinks = {}
for _, storage in ipairs(cargoStorages) do
table.insert(cargoLinks, "[[Таблица грузов#{{#invoke:Entity Lookup|getname|" .. storage .. "}}|{{#invoke:Entity Lookup|getname|" .. storage .. "}}]]")
end
return "Заказ груза: " .. table.concat(cargoLinks, ", ")
end
---------------------------------------------------------------------
local function getRecipeById(recipeId)
for _, recipe in ipairs(recipeData) do
if recipe.id == recipeId then
return recipe
end
end
return nil
end
function p.reverseLathe(frame)
local targetResult = frame.args[2]
if not targetResult or targetResult == "" then
return "Ошибка: не указан результат рецепта для обратного поиска."
end
local matchingLathes = {}
local function checkRecipes(recipeIds)
for _, recipeId in ipairs(recipeIds or {}) do
local recipe = getRecipeById(recipeId)
if recipe and recipe.result == targetResult then
return true
end
end
return false
end
for _, lathe in ipairs(latheData) do
local found = false
if lathe.Lathe then
if checkRecipes(lathe.Lathe.staticRecipes) or checkRecipes(lathe.Lathe.dynamicRecipes) then
found = true
end
end
if not found and lathe.EmagLatheRecipes then
if checkRecipes(lathe.EmagLatheRecipes.emagStaticRecipes) or checkRecipes(lathe.EmagLatheRecipes.emagDynamicRecipes) then
found = true
end
end
if found and lathe.id then
table.insert(matchingLathes, lathe.id)
end
end
if #matchingLathes == 0 then
return ""
end
local matchingLathesLinks = {}
for _, storage in ipairs(matchingLathes) do
table.insert(matchingLathesLinks, "[[{{#invoke:Entity Lookup|getname|" .. storage .. "}}|{{#invoke:Entity Lookup|getname|" .. storage .. "}}]]")
end
return "Может быть напечатано на станке: " .. table.concat(matchingLathesLinks, ", ")
end
---------------------------------------------------------------------
function p.reverseVending(frame)
local invMode = frame.args[2] or "" -- режим поиска: "inventory", "contraband", "emag" или пустая строка для всех
local targetId = frame.args[3]
if not targetId or targetId == "" then
return "Ошибка: не указан id предмета для обратного поиска в торговых автоматах."
end
local matchingInventoryIds = {}
-- Перебираем все инвентарные записи
for _, inventory in pairs(inventoriesData) do
if inventory.id then
local found = false
if (invMode == "inventory" or invMode == "" or not invMode) and inventory.startingInventory and type(inventory.startingInventory) == "table" then
if inventory.startingInventory[targetId] then
found = true
end
end
if (invMode == "contraband" or invMode == "" or not invMode) and inventory.contrabandInventory and type(inventory.contrabandInventory) == "table" then
if inventory.contrabandInventory[targetId] then
found = true
end
end
if (invMode == "emag" or invMode == "" or not invMode) and inventory.emaggedInventory and type(inventory.emaggedInventory) == "table" then
if inventory.emaggedInventory[targetId] then
found = true
end
end
if found then
table.insert(matchingInventoryIds, inventory.id)
end
end
end
if #matchingInventoryIds == 0 then
return ""
end
local matchingVendingMachines = {}
for _, vm in pairs(vendingMachinesData) do
if vm.VendingMachine and vm.VendingMachine.pack then
local packId = vm.VendingMachine.pack
for _, invId in ipairs(matchingInventoryIds) do
if packId == invId then
if vm.id then
table.insert(matchingVendingMachines, vm.id)
end
break
end
end
end
end
if #matchingVendingMachines == 0 then
return ""
end
local matchingVendingMachinesLinks = {}
for _, storage in ipairs(matchingVendingMachines) do
table.insert(matchingVendingMachinesLinks, "[[{#invoke:Entity Lookup|getname|" .. storage .. "}}|{{#invoke:Entity Lookup|getname|" .. storage .. "}}]]")
end
return "Содержится в торгомате: " .. table.concat(matchingVendingMachines, ", ")
end
---------------------------------------------------------------------
-- Основная функция модуля
---------------------------------------------------------------------
function p.main(frame)
local mode = frame.args[1]
if not mode or mode == "" then
return "Ошибка: не указан режим обратного поиска. Доступные режимы: reverseContained, reverseEquipment, reverseCargo, reverseLathe, reverseVending."
end
if mode == "reverseContained" then
return mw.getCurrentFrame():preprocess(p.reverseContained(frame))
elseif mode == "reverseEquipment" then
return mw.getCurrentFrame():preprocess(p.reverseEquipment(frame))
elseif mode == "reverseCargo" then
return mw.getCurrentFrame():preprocess(p.reverseCargo(frame))
elseif mode == "reverseLathe" then
return mw.getCurrentFrame():preprocess(p.reverseLathe(frame))
elseif mode == "reverseVending" then
return mw.getCurrentFrame():preprocess(p.reverseVending(frame))
else
return "Неизвестный режим: " .. mode .. ". Доступные режимы: reverseContained, reverseEquipment, reverseCargo, reverseLathe, reverseVending."
end
end
return p