Модуль:Prototypes/Машина/Станок: различия между версиями

мНет описания правки
мНет описания правки
 
(не показано 8 промежуточных версий этого же участника)
Строка 12: Строка 12:


-----------------------------------------------------------
-----------------------------------------------------------
-- Функция для сортировки рецептов
-- Вспомогательные функции
-----------------------------------------------------------
-----------------------------------------------------------
local function sortRecipesByPriority(recipes)
local function sortRecipesByPriority(recipes)
Строка 35: Строка 35:
end
end


-----------------------------------------------------------
-- Функция для получения деталей рецепта
-----------------------------------------------------------
local function getRecipeDetails(recipeId)
local function getRecipeDetails(recipeId)
     for _, recipe in ipairs(recipeData) do
     for _, recipe in ipairs(recipeData) do
Строка 47: Строка 44:
end
end


-----------------------------------------------------------
-- Функция для поиска информации об исследовании для рецепта
-----------------------------------------------------------
local function findInResearch(recipeId)
local function findInResearch(recipeId)
     for _, research in ipairs(researchData) do
     for _, research in ipairs(researchData) do
Строка 67: Строка 61:
end
end


-----------------------------------------------------------
-- Функция для получения деталей пакета рецептов
-----------------------------------------------------------
local function getRecipePackDetails(packId)
local function getRecipePackDetails(packId)
     for _, pack in ipairs(recipePackData) do
     for _, pack in ipairs(recipePackData) do
Строка 80: Строка 71:


-----------------------------------------------------------
-----------------------------------------------------------
-- Функция, гарантирующая, что список рецептов пакета – таблица
-- Функция для сбора рецептов из станка
-----------------------------------------------------------
-----------------------------------------------------------
local function getPackRecipes(pack)
local function getLatheRecipes(lathe)
    if not pack then
     local recipes = {}
        return {}
    end
    if type(pack.recipes) == "table" then
        return pack.recipes
    elseif type(pack.recipes) == "string" then
        return { pack.recipes }
    else
        return {}
    end
end
 
-----------------------------------------------------------
-- Основная функция модуля
-----------------------------------------------------------
function p.main(frame)
    local latheId = frame.args[1] or ""
    if latheId == "" then
        return '<div style="color:red;">Не указан ID станка.</div>'
    end
 
    local lathe = nil
    for _, data in ipairs(latheData) do
        if data.id == latheId then
            lathe = data
            break
        end
    end
 
    if not lathe then
        return '<div style="color:red;">Станок с ID "' .. latheId .. '" не найден.</div>'
    end
 
     local materialMapping = {}
    for _, material in ipairs(materialData) do
        if material.id then
            materialMapping[material.id] = material.stackEntity or material.id or material.name
        end
    end
 
     local chemMapping = {}
     local chemMapping = {}
     for id, chem in pairs(chemData) do
     for id, chem in pairs(chemData) do
Строка 128: Строка 80:
     end
     end


     local out = ''
     -- Вспомогательная функция для обработки одного рецепта
     local recipes = {}
     local function processRecipe(recipeId, defaultDiscipline, isEmag)
 
         local recipe = getRecipeDetails(recipeId)
    -- Обработка staticRecipes (старый формат)
        if recipe then
    if lathe.Lathe and lathe.Lathe.staticRecipes then
             if recipe.result then
         for _, recipeId in ipairs(lathe.Lathe.staticRecipes) do
                 local info = {
            local recipe = getRecipeDetails(recipeId)
                    id = recipe.id,
             if recipe and recipe.result then
                 table.insert(recipes, {
                     result = recipe.result,
                     result = recipe.result,
                     completetime = recipe.completetime,
                     completetime = recipe.completetime,
                     materials = recipe.materials,
                     materials = recipe.materials,
                     discipline = "Static",
                     discipline = defaultDiscipline,
                     tier = 0
                    tier = 0,
                 })
                    isEmag = isEmag or false
             elseif recipe and recipe.resultReagents then
                }
                if defaultDiscipline ~= "Static" then
                    local researchInfo = findInResearch(recipeId)
                     if researchInfo then
                        info.discipline = researchInfo.discipline
                        info.tier = researchInfo.tier
                        info.researchName = researchInfo.name
                    end
                end
                 table.insert(recipes, info)
             elseif recipe.resultReagents then
                 for reagent, amount in pairs(recipe.resultReagents) do
                 for reagent, amount in pairs(recipe.resultReagents) do
                     local reagentName = chemMapping[reagent] or reagent
                     local reagentName = chemMapping[reagent] or reagent
                     table.insert(recipes, {
                     table.insert(recipes, {
                        id = recipe.id,
                         result = reagentName .. "|amount=" .. amount .. "ед.|mode-chem=1",
                         result = reagentName .. "|amount=" .. amount .. "ед.|mode-chem=1",
                         completetime = recipe.completetime,
                         completetime = recipe.completetime,
                         materials = recipe.materials,
                         materials = recipe.materials,
                         discipline = "Static",
                         discipline = defaultDiscipline,
                         tier = 0
                         tier = 0,
                        isEmag = isEmag or false
                     })
                     })
                     break  
                     break
                 end
                 end
            else
                out = out .. '<div style="color:red;">Ошибка: Рецепт с ID "' .. recipeId .. '" не найден или поля result/resultReagents отсутствуют.</div>'
             end
             end
         end
         end
     end
     end


     -- Обработка dynamicRecipes (старый формат)
     -- Обработка рецептов для lathe.Lathe (старый и новый формат)
     if lathe.Lathe and lathe.Lathe.dynamicRecipes then
     if lathe.Lathe then
        for _, recipeId in ipairs(lathe.Lathe.dynamicRecipes) do
        if lathe.Lathe.staticRecipes then
            local recipe = getRecipeDetails(recipeId)
            for _, recipeId in ipairs(lathe.Lathe.staticRecipes) do
            if recipe then
                 processRecipe(recipeId, "Static", false)
                 local researchInfo = findInResearch(recipeId)
                if researchInfo then
                    table.insert(recipes, {
                        result = recipe.result,
                        completetime = recipe.completetime,
                        materials = recipe.materials,
                        discipline = researchInfo.discipline,
                        tier = researchInfo.tier,
                        researchName = researchInfo.name
                    })
                end
             end
             end
         end
         end
    end
        if lathe.Lathe.dynamicRecipes then
 
            for _, recipeId in ipairs(lathe.Lathe.dynamicRecipes) do
    -- Обработка emagStaticRecipes (старый формат)
                processRecipe(recipeId, "Dynamic", false)
    if lathe.EmagLatheRecipes and lathe.EmagLatheRecipes.emagStaticRecipes then
        for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagStaticRecipes) do
            local recipe = getRecipeDetails(recipeId)
            if recipe then
                table.insert(recipes, {
                    result = recipe.result,
                    completetime = recipe.completetime,
                    materials = recipe.materials,
                    discipline = "Static",
                    tier = 0,
                    isEmag = true
                })
             end
             end
         end
         end
    end
        if lathe.Lathe.staticPacks then
 
            for _, packId in ipairs(lathe.Lathe.staticPacks) do
    -- Обработка emagDynamicRecipes (старый формат)
                local pack = getRecipePackDetails(packId)
    if lathe.EmagLatheRecipes and lathe.EmagLatheRecipes.emagDynamicRecipes then
                if pack and pack.recipes then
        for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagDynamicRecipes) do
                    local packRecipes = type(pack.recipes) ~= "table" and { pack.recipes } or pack.recipes
            local recipe = getRecipeDetails(recipeId)
                    for _, recipeId in ipairs(packRecipes) do
            if recipe then
                         processRecipe(recipeId, "Static", false)
                local researchInfo = findInResearch(recipeId)
                     end
                if researchInfo then
                    table.insert(recipes, {
                        result = recipe.result,
                        completetime = recipe.completetime,
                         materials = recipe.materials,
                        discipline = researchInfo.discipline,
                        tier = researchInfo.tier,
                        researchName = researchInfo.name,
                        isEmag = true
                     })
                 end
                 end
             end
             end
         end
         end
    end
        if lathe.Lathe.dynamicPacks then
 
            for _, packId in ipairs(lathe.Lathe.dynamicPacks) do
    -- Обработка staticPacks (новый формат)
                local pack = getRecipePackDetails(packId)
    if lathe.Lathe and lathe.Lathe.staticPacks then
                if pack and pack.recipes then
        for _, packId in ipairs(lathe.Lathe.staticPacks) do
                    local packRecipes = type(pack.recipes) ~= "table" and { pack.recipes } or pack.recipes
            local pack = getRecipePackDetails(packId)
            if pack then
                local packRecipes = getPackRecipes(pack)
                if #packRecipes > 0 then
                     for _, recipeId in ipairs(packRecipes) do
                     for _, recipeId in ipairs(packRecipes) do
                         local recipe = getRecipeDetails(recipeId)
                         processRecipe(recipeId, "Dynamic", false)
                        if recipe and recipe.result then
                            table.insert(recipes, {
                                result = recipe.result,
                                completetime = recipe.completetime,
                                materials = recipe.materials,
                                discipline = "Static",
                                tier = 0
                            })
                        elseif recipe and recipe.resultReagents then
                            for reagent, amount in pairs(recipe.resultReagents) do
                                local reagentName = chemMapping[reagent] or reagent
                                table.insert(recipes, {
                                    result = reagentName .. "|amount=" .. amount .. "ед.|mode-chem=1",
                                    completetime = recipe.completetime,
                                    materials = recipe.materials,
                                    discipline = "Static",
                                    tier = 0
                                })
                                break
                            end
                        else
                            out = out .. '<div style="color:red;">Ошибка: Рецепт с ID "' .. recipeId .. '" не найден или поля result/resultReagents отсутствуют.</div>'
                        end
                     end
                     end
                else
                    out = out .. '<div style="color:red;">Ошибка: Пакет рецептов с ID "' .. packId .. '" не содержит рецепты.</div>'
                 end
                 end
            else
                out = out .. '<div style="color:red;">Ошибка: Пакет рецептов с ID "' .. packId .. '" не найден.</div>'
             end
             end
         end
         end
     end
     end


     -- Обработка dynamicPacks (новый формат)
     if lathe.EmagLatheRecipes then
    if lathe.Lathe and lathe.Lathe.dynamicPacks then
        if lathe.EmagLatheRecipes.emagStaticRecipes then
        for _, packId in ipairs(lathe.Lathe.dynamicPacks) do
            for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagStaticRecipes) do
            local pack = getRecipePackDetails(packId)
                processRecipe(recipeId, "Static", true)
            if pack then
            end
                local packRecipes = getPackRecipes(pack)
        end
                if #packRecipes > 0 then
        if lathe.EmagLatheRecipes.emagDynamicRecipes then
            for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagDynamicRecipes) do
                processRecipe(recipeId, "Dynamic", true)
            end
        end
        if lathe.EmagLatheRecipes.emagStaticPacks then
            for _, packId in ipairs(lathe.EmagLatheRecipes.emagStaticPacks) do
                local pack = getRecipePackDetails(packId)
                if pack and pack.recipes then
                    local packRecipes = type(pack.recipes) ~= "table" and { pack.recipes } or pack.recipes
                     for _, recipeId in ipairs(packRecipes) do
                     for _, recipeId in ipairs(packRecipes) do
                         local recipe = getRecipeDetails(recipeId)
                         processRecipe(recipeId, "Static", true)
                        if recipe then
                            local researchInfo = findInResearch(recipeId)
                            if researchInfo then
                                table.insert(recipes, {
                                    result = recipe.result,
                                    completetime = recipe.completetime,
                                    materials = recipe.materials,
                                    discipline = researchInfo.discipline,
                                    tier = researchInfo.tier,
                                    researchName = researchInfo.name
                                })
                            end
                        end
                     end
                     end
                else
                    out = out .. '<div style="color:red;">Ошибка: Пакет рецептов с ID "' .. packId .. '" не содержит рецепты.</div>'
                 end
                 end
            else
                out = out .. '<div style="color:red;">Ошибка: Пакет рецептов с ID "' .. packId .. '" не найден.</div>'
             end
             end
         end
         end
    end
        if lathe.EmagLatheRecipes.emagDynamicPacks then
 
            for _, packId in ipairs(lathe.EmagLatheRecipes.emagDynamicPacks) do
    -- Обработка emagStaticPacks (новый формат)
                local pack = getRecipePackDetails(packId)
    if lathe.EmagLatheRecipes and lathe.EmagLatheRecipes.emagStaticPacks then
                if pack and pack.recipes then
        for _, packId in ipairs(lathe.EmagLatheRecipes.emagStaticPacks) do
                    local packRecipes = type(pack.recipes) ~= "table" and { pack.recipes } or pack.recipes
            local pack = getRecipePackDetails(packId)
            if pack then
                local packRecipes = getPackRecipes(pack)
                if #packRecipes > 0 then
                     for _, recipeId in ipairs(packRecipes) do
                     for _, recipeId in ipairs(packRecipes) do
                         local recipe = getRecipeDetails(recipeId)
                         processRecipe(recipeId, "Dynamic", true)
                        if recipe then
                            table.insert(recipes, {
                                result = recipe.result,
                                completetime = recipe.completetime,
                                materials = recipe.materials,
                                discipline = "Static",
                                tier = 0,
                                isEmag = true
                            })
                        end
                     end
                     end
                else
                    out = out .. '<div style="color:red;">Ошибка: Пакет рецептов с ID "' .. packId .. '" не содержит рецепты.</div>'
                 end
                 end
            else
                out = out .. '<div style="color:red;">Ошибка: Пакет рецептов с ID "' .. packId .. '" не найден.</div>'
             end
             end
         end
         end
     end
     end


     -- Обработка emagDynamicPacks (новый формат)
     sortRecipesByPriority(recipes)
     if lathe.EmagLatheRecipes and lathe.EmagLatheRecipes.emagDynamicPacks then
    return recipes
        for _, packId in ipairs(lathe.EmagLatheRecipes.emagDynamicPacks) do
end
            local pack = getRecipePackDetails(packId)
 
            if pack then
-----------------------------------------------------------
                local packRecipes = getPackRecipes(pack)
-- Общие таблицы для форматирования вывода
                if #packRecipes > 0 then
-----------------------------------------------------------
                    for _, recipeId in ipairs(packRecipes) do
local disciplineMapping = {
                        local recipe = getRecipeDetails(recipeId)
    Arsenal = "Арсенал",
                        if recipe then
     Industrial = "Промышленность",
                            local researchInfo = findInResearch(recipeId)
    Experimental = "Экспериментальное",
                            if researchInfo then
    CivilianServices = "Обслуживание персонала"
                                table.insert(recipes, {
}
                                    result = recipe.result,
local tierColors = {
                                    completetime = recipe.completetime,
    [1] = "#54d554",
                                    materials = recipe.materials,
    [2] = "#ed9000",
                                    discipline = researchInfo.discipline,
    [3] = "#d72a2a"
                                    tier = researchInfo.tier,
}
                                    researchName = researchInfo.name,
local materialMappingGlobal = {}
                                    isEmag = true
for _, material in ipairs(materialData) do
                                })
    if material.id then
                            end
        materialMappingGlobal[material.id] = material.stackEntity or material.id or material.name
                        end
    end
                    end
end
                else
 
                    out = out .. '<div style="color:red;">Ошибка: Пакет рецептов с ID "' .. packId .. '" не содержит рецепты.</div>'
-----------------------------------------------------------
                end
-- Функция для формирования строки рецепта
             else
-----------------------------------------------------------
                out = out .. '<div style="color:red;">Ошибка: Пакет рецептов с ID "' .. packId .. '" не найден.</div>'
local function formatRecipe(recipe, timeMultiplier, materialUseMultiplier)
            end
    local out = ""
    local ct = recipe.completetime or 0
    local scaledTime = ct * timeMultiplier
    out = out .. '{{Шаблон:Prototypes/Машина/Станок/base|product=' .. recipe.result
    out = out .. '|complete-time={{#invoke:Code/Формат/Время|main|seconds|' .. scaledTime .. '}}|materials='
 
    if recipe.materials then
        local materialEntries = {}
        for material, amount in pairs(recipe.materials) do
             local stackEntity = materialMappingGlobal[material] or material
            local scaledAmount = (amount * materialUseMultiplier) / 100
            table.insert(materialEntries, string.format('<b>[[File:%s.png|32x32px|link=]] %g {{#invoke:Entity Lookup|getname|%s}}</b>', stackEntity, scaledAmount, stackEntity))
         end
         end
        out = out .. table.concat(materialEntries)
    else
        out = out .. 'Нет данных о материалах'
     end
     end


     sortRecipesByPriority(recipes)
     if recipe.discipline ~= "Static" then
        local tierColor = tierColors[recipe.tier] or "#FFFFFF"
        local disciplineName = disciplineMapping[recipe.discipline] or "Неизвестная дисциплина"
        out = out .. '|info=<div style="font-weight:600;"><span style="margin:8px;">[[File:' .. recipe.discipline .. '.png|16x16px|link=]]</span> [[Руководство по исследованию и разработке|' .. disciplineName
        out = out .. ']], уровень: <span style="color: ' .. tierColor .. '">' .. recipe.tier .. '</span> </div>'
    end
 
    if recipe.isEmag then
        out = out .. '|mode-emag=1'
    end
 
    if recipe.discipline ~= "Static" then
        out = out .. '|mode-research=1'
    end
 
    out = out .. '}}'
    return out
end
 
-----------------------------------------------------------
-- Функция для поиска и вывода рецептов по ID станка
-----------------------------------------------------------
function p.lathe(frame)
    local latheId = frame.args[1] or ""
    if latheId == "" then
        return '<div style="color:red;">Не указан ID станка.</div>'
    end


    -- Таблица для перевода названий дисциплин
     local lathe = nil
     local disciplineMapping = {
    for _, data in ipairs(latheData) do
        Arsenal = "Арсенал",
         if data.id == latheId then
         Industrial = "Промышленность",
            lathe = data
        Experimental = "Экспериментальное",
            break
         CivilianServices = "Обслуживание персонала"
         end
     }
     end


     -- Таблица для цветов по уровням
     if not lathe then
    local tierColors = {
         return '<div style="color:red;">Станок с ID "' .. latheId .. '" не найден.</div>'
         [1] = "#54d554",
     end
        [2] = "#ed9000",
        [3] = "#d72a2a"
     }


     local materialUseMultiplier = (lathe.Lathe and lathe.Lathe.materialUseMultiplier) or 1
     local materialUseMultiplier = (lathe.Lathe and lathe.Lathe.materialUseMultiplier) or 1
     local timeMultiplier = (lathe.Lathe and lathe.Lathe.timeMultiplier) or 1
     local timeMultiplier = (lathe.Lathe and lathe.Lathe.timeMultiplier) or 1
    local recipes = getLatheRecipes(lathe)
    local out = ""
    for _, recipe in ipairs(recipes) do
        out = out .. formatRecipe(recipe, timeMultiplier, materialUseMultiplier)
    end
    return mw.getCurrentFrame():preprocess(out)
end
-----------------------------------------------------------
-- Функция для поиска и вывода рецептов по ID предмета
-----------------------------------------------------------
function p.item(frame)
    local itemId = frame.args[1] or ""
    if itemId == "" then
        return '<div style="color:red;">Не указан ID предмета.</div>'
    end


     for _, recipe in ipairs(recipes) do
    local recipesOutput = ""
         local scaledTime = recipe.completetime * timeMultiplier
    local foundAny = false
         out = out .. '{{Шаблон:Prototypes/Машина/Станок|product=' .. recipe.result
 
         out = out .. '|complete-time={{#invoke:Code/Формат/Время|main|seconds|' .. scaledTime
     for _, lathe in ipairs(latheData) do
        out = out .. '}}|materials='
         local recipes = getLatheRecipes(lathe)
         local materialUseMultiplier = (lathe.Lathe and lathe.Lathe.materialUseMultiplier) or 1
         local timeMultiplier = (lathe.Lathe and lathe.Lathe.timeMultiplier) or 1


         if recipe.materials then
         for _, recipe in ipairs(recipes) do
            local materialEntries = {}
            if recipe.id == itemId or recipe.result == itemId then
            for material, amount in pairs(recipe.materials) do
                 foundAny = true
                 local stackEntity = materialMapping[material] or material
                 local recipeStr = formatRecipe(recipe, timeMultiplier, materialUseMultiplier)
                 local scaledAmount = (amount * materialUseMultiplier) / 100
                 recipeStr = recipeStr:gsub("}}$", "|method-container=" .. lathe.id .. "}}")
                 table.insert(materialEntries, string.format('<b>[[File:%s.png|32x32px|link=]] %g {{#invoke:Entity Lookup|getname|%s}}</b>', stackEntity, scaledAmount, stackEntity))
                recipesOutput = recipesOutput .. recipeStr
             end
             end
            out = out .. table.concat(materialEntries)
        else
            out = out .. 'Нет данных о материалах'
         end
         end
    end
    if not foundAny then
        return '<div style="color:red;">Рецепт для предмета с ID "' .. itemId .. '" не найден во всех станках.</div>'
    end
    local out = '<div class="grid-item-compressed">' .. recipesOutput .. '</div>'
    return mw.getCurrentFrame():preprocess(out)
end


        -- Информация об исследовании
-----------------------------------------------------------
        if recipe.discipline ~= "Static" then
-- Функция для поиска и вывода рецептов по ID материала
            local tierColor = tierColors[recipe.tier] or "#FFFFFF"
-----------------------------------------------------------
            local disciplineName = disciplineMapping[recipe.discipline] or "Неизвестная дисциплина"
function p.material(frame)
    local materialId = frame.args[1] or ""
    if materialId == "" then
        return '<div style="color:red;">Не указан ID материала.</div>'
    end


            out = out .. '|info=<div style="font-weight:600;"><span style="margin:8px;">[[File:' .. recipe.discipline .. '.png|16x16px|link=]]</span> [[Руководство по исследованию и разработке|' .. disciplineName
    local recipesOutput = ""
            out = out .. ']], уровень: <span style="color: ' .. tierColor .. '">' .. recipe.tier .. '</span> </div>'
    local foundAny = false
        end


         -- Пометка при взломе EMAG
    for _, lathe in ipairs(latheData) do
         if recipe.isEmag then
         local recipes = getLatheRecipes(lathe)
            out = out .. '|mode-emag=1'
         local materialUseMultiplier = (lathe.Lathe and lathe.Lathe.materialUseMultiplier) or 1
        end
        local timeMultiplier = (lathe.Lathe and lathe.Lathe.timeMultiplier) or 1


         -- Пометка для исследуемой технологии
         for _, recipe in ipairs(recipes) do
        if recipe.discipline ~= "Static" then
            if recipe.materials then
            out = out .. '|mode-research=1'
                for matId, _ in pairs(recipe.materials) do
                    if matId == materialId then
                        foundAny = true
                        local recipeStr = formatRecipe(recipe, timeMultiplier, materialUseMultiplier)
                        recipeStr = recipeStr:gsub("}}$", "|method-container=" .. lathe.id .. "}}")
                        recipesOutput = recipesOutput .. recipeStr
                        break
                    end
                end
            end
         end
         end
    end


         out = out .. '}}'
    if not foundAny then
         return '<div style="color:red;">Для материала с ID "' .. materialId .. '" рецептов не найдено во всех станках.</div>'
     end
     end


    local out = '<div class="grid-item-compressed">' .. recipesOutput .. '</div>'
     return mw.getCurrentFrame():preprocess(out)
     return mw.getCurrentFrame():preprocess(out)
end
-----------------------------------------------------------
-- Функция для универсального вызова из шаблона
-----------------------------------------------------------
function p.main(frame)
    local arguments = require("Модуль:Arguments").getArgs(frame, { unwrap = true })
    local mode = arguments[1] or ""
    local id  = arguments[2] or ""
   
    -- Для обеспечения работы mw.getCurrentFrame(), переиспользуем исходный frame
    local newFrame = {
        args = { id },
        getCurrentFrame = frame.getCurrentFrame or function() return frame end
    }
   
    if mode == "lathe" then
        return p.lathe(newFrame)
    elseif mode == "item" then
        return p.item(newFrame)
    elseif mode == "material" then
        return p.material(newFrame)
    else
        return '<div style="color:red;">Неверный режим вызова: "' .. mode .. '". Используйте "lathe", "item" или "material".</div>'
    end
end
end


return p
return p