Module:Sandbox/Pillow/UnitsOverview: Difference between revisions

From Heroes of Might and Magic: Olden Era Official Wiki
Pillow (talk | contribs)
No edit summary
Pillow (talk | contribs)
No edit summary
Line 238: Line 238:
             units[id].attackType = computeAttackType(row)
             units[id].attackType = computeAttackType(row)
             units[id].cost = computeCost(row)
             units[id].cost = computeCost(row)
            local baseid = id:gsub('_alt$', ''):gsub('_upg$', '')
         end
         end


units[id].units_weekly = growths[id:gsub('_alt$', ''):gsub('_upg$', '')]
units[id].units_weekly = growths[baseid]


         -- Save the names based on which language row we are currently looping over
         -- Save the names based on which language row we are currently looping over

Revision as of 09:23, 20 July 2026

CreatureFactionTierCostGrowth💬HealthAttackDefenseDamageMoraleLuckInitiativeSpeedAttack type
SwordsmanTempleI8512442-30054Melee Attack
Guard CaptainTempleI11012652-30064Melee Attack
Sun's AegisTempleI11015582-30055Melee Attack
CrossbowmanTempleII9510533-40043Ranged Attack
AustringerTempleII13010533-40044Ranged Attack
MarksmanTempleII13010633-40063Ranged,
no range penalty
GriffinTempleIII27030765-90095Melee Attack
Temple GriffinTempleIII36030865-900127Melee Attack
Guardian GriffinTempleIII360309107-700106Melee Attack
LightweaverTempleIV31035111111-112042Ranged Attack
HierophantTempleIV44035131611-112064Ranged Attack
Sun HeraldTempleIV44035161311-182053Ranged Attack
CavalryTempleV85085121710-1410107Melee Attack
Noble CavalryTempleV122085121712-1610137Melee Attack
Sunspear CavalryTempleV122085142212-1620108Melee Attack
InquisitorTempleVI100090202419-230074Melee Attack
Mother SuperiorTempleVI1500125202819-230095Melee Attack
ExcommunicatorTempleVI150090262423-330086Melee Attack
AngelTempleVII2400 1225303050-750084Ranged Attack
ArchangelTempleVII4000 2225353050-7500125Ranged,
no penalties
ApotheosisTempleVII4000 2300303550-75001010Ranged Attack
Necropolis
SkeletonNecropolisI356411-30043Melee Attack
Skeleton WarriorNecropolisI506432-30054Melee Attack
Skeleton ArcherNecropolisI506411-30043Ranged Attack
WightNecropolisII1008302-40056Melee Attack
WraithNecropolisII1308602-40077Melee Attack
PhantasmNecropolisII1308642-40067Melee Attack
Undead PetNecropolisIII12014463-50055Melee Attack
BarghestNecropolisIII16014463-50086Melee Attack
Armored HoundNecropolisIII16018483-50055Melee Attack
GraverobberNecropolisIV2403011106-90043Long Reach
Merchant of DeathNecropolisIV3403011107-100054Long Reach
KennelmasterNecropolisIV3403014106-90056Long Reach
LichNecropolisV32045121213-160042Ranged Attack
Pestilent LichNecropolisV46045121216-160053Ranged Attack
Sanguine LichNecropolisV46045121613-160043Ranged Attack
Dread KnightNecropolisVI70080191812-140097Melee Attack
Avatar of WarNecropolisVI110080192018-2000108Melee Attack
Hollow ReaperNecropolisVI110080251824-2600117Melee Attack
VampireNecropolisVII1200 1150222025-2500116Melee Attack
Vampire LordNecropolisVII2000 2175222630-3000138Melee,
no counter
Vampire ScholarNecropolisVII2000 2150272030-3000125Long Reach
Grove
FaunGroveI11511433-50042Ranged,
no melee penalty
Faun ArcherGroveI15011433-50053Ranged,
no penalties
Faun WarriorGroveI15011664-60064Melee Attack
HopletGroveII18518654-81165Melee Attack
Dawn HopletGroveII25018954-81266Melee,
no counter
Dusk HopletGroveII25018774-82195Melee Attack
Vine IriyadGroveIII220456115-70023Melee Attack
Fungal IriyadGroveIII300456114-80034Melee Attack
Crystal IriyadGroveIII300456115-70035Melee Attack
NaiadGroveIV36040111010-140055Ranged Attack
Vernal NaiadGroveIV51040111414-180076Ranged Attack
Brumal NaiadGroveIV51040151014-180065Ranged Attack
HerbomancerGroveV64060121415-180064Long Reach
SporemancerGroveV91060161815-180086Long Reach
MurmurmancerGroveV91060121418-180085Long Reach
QilinGroveVI1200130222024-300296Melee Attack
Thunder QilinGroveVI1900130222030-3602118Melee Attack
Mist QilinGroveVI1900130242227-3602137Melee Attack
PhoenixGroveVII2900 1200282645-6500148Melee Attack
Flaming PhoenixGroveVII4800 2300362745-65001610Melee Attack
Energy PhoenixGroveVII4800 2250283945-65001510Melee Attack
Hive
ParasiteHiveI807332-40043Long Reach
Warden ParasiteHiveI1009362-40054Long Reach
Ravager ParasiteHiveI1007632-40065Long Reach
LocustHiveII13012543-50065Melee Attack
Overgrown LocustHiveII17016543-50076Melee Attack
Harvester LocustHiveII17012744-50077Melee Attack
HornetHiveIII255207104-900107Melee Attack
ChanterHiveIII350257104-900411Melee Attack
StingerHiveIII350207104-900129Melee Attack
Fire LarvaHiveIV10016444-40044Melee Attack
ScorpionHiveIV30040121210-121154Melee Attack
Volcanic ScorpionHiveIV42055121410-121265Melee Attack
Spelaean ScorpionHiveIV42040141212-142164Melee Attack
ReaverHiveV75045181210-4010116Melee Attack
Menacing ReaverHiveV108045181820-3030127Melee Attack
Maniacal ReaverHiveV108045181210-4020126Melee Attack
WaurmsHiveVI1200120212121-230178Melee Attack
DevourerHiveVI1900120212127-2903710Melee Attack
PyroborosHiveVI1900120212121-230288Ranged,
no melee penalty
Hive QueenHiveVII2100 1200252560-600086Melee Attack
Hive MotherHiveVII3400 2275252560-6000136Melee Attack
Hive HuntressHiveVII3400 2250252570-700089Melee,
no counter
Schism
Ra'ShothSchismI8010333-30044Melee Attack
Stinging Ra'ShothSchismI10010553-30044Ranged Attack
Ferocious Ra'ShothSchismI10010333-30066Melee Attack
CultistSchismII16515544-60043Long Reach
BinderSchismII22015574-60055Long Reach
VotarySchismII22015944-80044Long Reach
Aga'Shoth RiderSchismIII19520775-70064Melee Attack
Aga'Shoth TamerSchismIII27020885-70097Melee Attack
Aga'Shoth Mat'haSchismIII27025775-70076Melee Attack
Grand ShothSchismIV45050111110-130085Melee Attack
Unspeakable ShothSchismIV63050111110-130088Melee Attack
Unthinkable ShothSchismIV63050111110-1300136Melee Attack
ConcubusSchismV58060161314-200052Ranged Attack
Mistress of ChainsSchismV84060201314-200074Ranged Attack
BewitcherSchismV84060161320-200066Ranged,
no melee penalty
ArbitratorSchismVI120075202018-220054Ranged Attack
Rift ArbitratorSchismVI190075262818-2200105Ranged Attack
Bloated ArbitratorSchismVI190075282222-260085Ranged Attack
Abyssal EnvoySchismVII2500 1250303040-600085Melee Attack
Abyssal OverseerSchismVII4200 2250404040-600096Melee Attack
Abyssal ExecutorSchismVII4200 2250353560-6000107Melee Attack
Dungeon
TroglodyteDungeonI508231-30044Melee Attack
Infernal TroglodyteDungeonI608361-30065Melee Attack
Toxic TroglodyteDungeonI608531-40054Melee Attack
InfiltratorDungeonII12013643-60165Melee Attack
Guile InfiltratorDungeonII16013643-60267Melee Attack
Bleak InfiltratorDungeonII16013643-60296Melee Attack
Onyx DancerDungeonIII16520885-70042Ranged Attack
Jasper DancerDungeonIII23020885-70054Ranged,
no melee penalty
Aureate DancerDungeonIII23020885-70073Ranged Attack
MinotaurDungeonIV38040111112-141055Melee Attack
Minotaur LordDungeonIV53040111512-141066Melee Attack
Minotaur VanguardDungeonIV53040151114-162056Melee Attack
MedusaDungeonV49055151411-150042Ranged,
no range penalty
Medusa SculptorDungeonV70055201815-150054Ranged,
no range penalty
Medusa QueenDungeonV70055171411-150083Ranged,
no range penalty
HydraDungeonVI1200130242225-280064Melee,
no counter
Chthonic HydraDungeonVI1800160243025-280065Melee,
no counter
Infernal HydraDungeonVI1800130302630-380086Melee,
no counter
Cave DragonDungeonVII3000 1275292550-6000118Melee Attack
Black DragonDungeonVII5000 2350293265-7500149Melee Attack
Ashen DragonDungeonVII5000 2300372565-75001211Melee Attack
Neutral
Pixie NeutralI1006222-20088Melee Attack
Gnat NeutralI666666-60066Melee Attack
Ghoul NeutralII20020964-70055Melee Attack
Peasant NeutralII1505111-10011Melee Attack
Halfling NeutralII1506663-33066Ranged Attack
Animated Armor NeutralIII30025484-120014Melee Attack
Groll NeutralIII30040865-70085Melee Attack
Starchild NeutralIV6003513912-180053Ranged Attack
Unicorn NeutralIV60040161310-1000106Melee Attack
Kittenhorn NeutralIV60040101010-153366Melee Attack
Primal Remnant NeutralIV6005091813-140065Melee Attack
Faerie Dragon NeutralV100075151515-1500105Melee Attack
Giant Toad NeutralV100095192218-180084Melee Attack
Worldwatcher NeutralVI160075252525-250083Ranged,
no range penalty
Dragonslayer NeutralVI160085242827-360096Melee Attack
Couatl NeutralVI160095261921-2800128Melee Attack
Sentinel of Glory NeutralVII5000400404050-500077Melee Attack
Dragon NeutralVII3000250293250-6000107Melee Attack
Red Dragon NeutralVII5000325333260-7000129Melee Attack
Avatar NeutralVIII30030010-100055Melee Attack
Lich Dragon NeutralVIII30000999666699-990099Melee Attack

local p = {}

local FACTION_ORDER = {
    human = 1,
    undead = 2,
    nature = 3,
    demon = 4,
    unfrozen = 5,
    dungeon = 6,
    neutral = 7,
}

local FACTION_MAPPING = {
    Temple = 'human',
    Necropolis = 'undead',
    Grove = 'nature',
    Hive = 'demon',
    Schism = 'unfrozen',
    Dungeon = 'dungeon',
    Neutral = 'neutral'
}

-- Note: The right side is just a fallback, it will seldom be used.
local TRANSLATION_IDS = {
    creature =              'Creature',
    faction =               'Faction',
    tier =                  'Tier',
    wiki_cost =             'Cost',
    units_weekly =          'Growth',
    hp =                    'Hp',
    offence =               'Offence',
    defence =               'Defence',
    damage =                'Damage',
    initiative =            'Initiative',
    morale =                'Morale',
    luck =                  'Luck',
    speed =                 'Speed',
    wiki_units_neutral =    'Neutral',
    wiki_units_attack_type = 'Attack type',
    melee_attack =          'Melee Attack', -- melee_attack = 1
    wiki_units_no_counter = 'Melee,<br>no counter', -- melee_attack_no_counter = 2
    remote_attack         = 'Long Reach', -- remote_attack = 3
    ranged_attack         = 'Ranged Attack', -- ranged_attack = 4
    wiki_units_no_close = 'Ranged,<br>no melee penalty', -- ranged_attack_no_close = 5
    wiki_units_no_range = 'Ranged,<br>no range penalty', -- ranged_attack_no_range = 6
    wiki_units_no_range_close = 'Ranged,<br>no penalties', -- ranged_attack_no_range_close = 7
}

local RESOURCE_ICONS = {
    wood_cost     = 'Wood',
    ore_cost      = 'Ore',
    mercury_cost  = 'Mercury',
    dust_cost     = 'Dust',
    crystal_cost  = 'Crystal',
    gemstone_cost = 'Gemstones'
}

local STAT_ICONS = {
    hp          = 'Icon_Stats_Health',
    offence     = 'Icon_Stats_Attack',
    defence     = 'Icon_Stats_Defence',
    damage      = 'Icon_Stats_Damage',
    morale      = 'Icon_Stats_Morale',
    luck        = 'Icon_Stats_Luck',
    initiative  = 'Icon_Stats_Initiative',
    speed       = 'Icon_Stats_Speed',
}

local ATTACK_RANKS = {
    base_passive_melee_attack_name = 1,                 -- Swordsman     100,   0,   0,   0,   0,   0,   0,   0,   0
    base_passive_melee_attack_no_counter_name = 2,      -- Vampire Lord  101,   0,   0,   0,   0,   0,   0,   0,   0
    base_passive_remote_attack_name = 3,                -- Graverobber     0, 100,   0,   0,   0,   0,   0,   0,   0
    base_passive_ranged_attack_name = 4,                -- Onyx Dancer    50, 100, 100,  90,  80,  70,  60,  50,  50
    base_passive_ranged_attack_no_close_name = 5,       -- Apotheosis    100, 100, 100,  90,  80,  70,  60,  50,  50
    base_passive_ranged_attack_no_range_name = 6,       -- Marksman       50, 100, 100, 100, 100, 100, 100, 100, 100
    base_passive_ranged_attack_no_range_close_name = 7, -- Halfling      100, 100, 100, 100, 100, 100, 100, 100, 100
}

local ATTACK_ICONS = {
    base_passive_melee_attack_name = 'Base_passive_melee_attack',
    base_passive_melee_attack_no_counter_name = 'Base_passive_noncounter',
    base_passive_remote_attack_name = 'Base_passive_remote_attack',
    base_passive_ranged_attack_name = 'Base_passive_ranged_attack', -- TODO: clarify icon
    base_passive_ranged_attack_no_close_name = 'Base passive duelist', -- TODO: clarify icon
    base_passive_ranged_attack_no_range_name = 'Base_passive_sharpshooter', -- TODO: clarify icon
    base_passive_ranged_attack_no_range_close_name = 'Arbitrator_passive_1', -- TODO: clarify icon
}
local ATTACK_WORDS = {
    base_passive_melee_attack_name = 'melee_attack',
    base_passive_melee_attack_no_counter_name = 'wiki_units_no_counter',
    base_passive_remote_attack_name = 'remote_attack',
    base_passive_ranged_attack_name = 'ranged_attack',
    base_passive_ranged_attack_no_close_name = 'wiki_units_no_close',
    base_passive_ranged_attack_no_range_name = 'wiki_units_no_range',
    base_passive_ranged_attack_no_range_close_name = 'wiki_units_no_range_close',
}

local ROMAN = { 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII' }

local PAGES = {
    Stinger = 'Stinger_(unit)',
}

local MORALE_AND_LUCK = {
    '<span class="elevated1">1</span>',
    '<span class="elevated2">2</span>',
    '<span class="elevated3">3</span>',
}

-- Awards a number from 0 to 3 for a unit, based on how upgraded it is
------------------------------------------------------------------------------------------------------------------------
local function computeUpgradeRank(row)
    local base = (row['base'] and row['base'] ~= "") and 1 or 0
    local upgrade = (row['upgrade'] and row['upgrade'] ~= "") and 10 or 0
    local sum = base + upgrade
    if sum == 1 then
        return 3
    elseif sum == 10 then
        return 1
    elseif sum == 0 then
        return 0
    else
        return 2
    end
end

-- Returns one of the ATTACK_RANKS keys (e.g. 'base_passive_melee_attack_name') or an empty string
------------------------------------------------------------------------------------------------------------------------
local function computeAttackType(row)
    local abilities = row['shared_abilities']
    if type(abilities) ~= "string" then
        return ""
    end
    for key, _ in pairs(ATTACK_RANKS) do
        local pattern = "%f[%w]" .. key .. "%f[%W]"
        if string.match(abilities, pattern) then
            return key
        end
    end
    return ""
end

-- Returns a rich wikitext with numbers and icons
------------------------------------------------------------------------------------------------------------------------
local function computeCost(row)
    local gold = row['gold_cost']
    local cost = gold .. '[[File:Icon_Resource_Gold.png|24px|link=]]'
    for key, icon in pairs(RESOURCE_ICONS) do
        local val = row[key]
        if val and val ~= '' and val ~= 0 then
            cost = cost .. ' ' .. val .. '[[File:Icon_Resource_' .. icon .. '.png|24px|link=]]'
        end
    end
    return cost
end

-- Retrieves the data from Cargo
------------------------------------------------------------------------------------------------------------------------
local function query(lang, forcedFaction)
    local tables = 'Unit, Translation'
    local fields = '' ..
        'Unit.id=id, ' ..
        'Unit.faction=faction, ' ..
        'Unit.tier=tier, ' ..
        'Unit.hp=hp, ' ..
        'Unit.offence=offence, ' ..
        'Unit.defence=defence, ' ..
        'Unit.damage_min=damage_min, ' ..
        'Unit.damage_max=damage_max, ' ..
        'Unit.morale=morale, ' ..
        'Unit.luck=luck, ' ..
        'Unit.initiative=initiative, ' ..
        'Unit.speed=speed, ' ..
        'Unit.shared_abilities=shared_abilities, ' .. -- we use it for range detection
        -- costs
        'Unit.gold_cost=gold_cost, ' ..
        'Unit.wood_cost=wood_cost, ' ..
        'Unit.ore_cost=ore_cost, ' ..
        'Unit.mercury_cost=mercury_cost, ' ..
        'Unit.dust_cost=dust_cost, ' ..
        'Unit.crystal_cost=crystal_cost, ' ..
        'Unit.gemstone_cost=gemstone_cost, ' ..
        -- upgrade
        'Unit.base_sid=base, ' ..
        'Unit.upgrade_sid=upgrade, ' ..
        -- Translation
        'Translation.language=language, ' ..
        'Translation.name=transName'

    -- where:
    local where = {}
    if forcedFaction then
        table.insert(where, 'Unit.faction="' .. forcedFaction .. '"')
    end
    table.insert(where, '(Translation.language = "en" OR Translation.language = "' .. lang .. '")')

    -- Get BOTH the English row AND the target language row
    local cargoArgs = {
        join = 'Unit.id = Translation.target_id',
        where = table.concat(where, ' AND '),
        orderBy = 'Unit.id ASC',
        limit = 1000 -- Increased limit since each unit will return 2 rows
    }

    return mw.ext.cargo.query(tables, fields, cargoArgs)
end

local function queryGrowths()
    local results = mw.ext.cargo.query(
		'MapObject',
		'units_hire_sid, units_weekly',
		{
			where = 'units_weekly > 0',
			limit = 200
		}
    )
   
   local growths = {}

   for _, row in ipairs(results) do
       growths[row.units_hire_sid] = row.units_weekly
   end

   return growths
end

-- Scans the Cargo results and folds the EN and lang rows into a single row
------------------------------------------------------------------------------------------------------------------------
local function consolidateResults(results, growths, lang)
    local units = {}
    for _, row in ipairs(results) do
        local id = row['id']

        -- If this is the first time seeing this id, set up its basic stats
        if not units[id] then
            units[id] = mw.clone(row)
            units[id].upgradeRank = computeUpgradeRank(row)
            units[id].attackType = computeAttackType(row)
            units[id].cost = computeCost(row)
            local baseid = id:gsub('_alt$', ''):gsub('_upg$', '')
        end

		units[id].units_weekly = growths[baseid]

        -- Save the names based on which language row we are currently looping over
        if row['language'] == 'en' then
            units[id].nameEn = row['transName']
        end
        if row['language'] == lang then
            units[id].nameX = row['transName']
        end
    end

    -- Convert the Dictionary into an Array
    local unitsArray = {}
    for _, unitData in pairs(units) do
        table.insert(unitsArray, unitData)
    end

    return unitsArray
end

-- Decides the order between two units, for sorting purposes.
------------------------------------------------------------------------------------------------------------------------
local function sortUnits(unitA, unitB)
    local rankA = FACTION_ORDER[unitA.faction] or 99
    local rankB = FACTION_ORDER[unitB.faction] or 99

    if rankA ~= rankB then
        return rankA < rankB
    end

    if unitA.tier ~= unitB.tier then
        return unitA.tier < unitB.tier
    end

    if unitA.upgradeRank ~= unitB.upgradeRank then
        return unitA.upgradeRank < unitB.upgradeRank
    end

    return unitA.hp < unitB.hp
end

-- Retrieves the text for some specific ids from Cargo Translations.
------------------------------------------------------------------------------------------------------------------------
local function translateIds(ids, lang, extra)
    -- Key list
    local list = {}
    for key, _ in pairs(ids) do
        list[#list + 1] = key
    end
    local idListString = '"' .. table.concat(list, '", "') .. '"'

    -- Cargo
    local where = {}
    table.insert(where, 'target_id IN (' .. idListString .. ')')
    table.insert(where, 'language = "' .. lang .. '"')
    if extra then
        table.insert(where, extra)
    end
    local results = mw.ext.cargo.query('Translation', 'target_id, name', {
        where = table.concat(where, ' AND '),
        limit = 100
    })

    -- Dictionary
    local dictionary = mw.clone(ids)
    for key, value in pairs(dictionary) do
        --dictionary[key] = value .. '[[Data:WikiTranslations/' .. lang .. '#' .. key .. '|💬]]'
        dictionary[key] = value .. '💬'
    end
    for _, row in ipairs(results) do
        local name = row['name']
        if name and name ~= '' and not name:find('💬') then
            dictionary[row['target_id']] = name
        end
    end
    return dictionary
end

-- Displays a variable
------------------------------------------------------------------------------------------------------------------------
local function dump(target)
    return '<pre>' .. mw.dumpObject(target) .. '</pre>'
end

-- Builds an icon+text combo for the unit's name
------------------------------------------------------------------------------------------------------------------------
local function renderUnitName(u, suffix)
    local stem = PAGES[u.nameEn] or u.nameEn
    local page = stem .. suffix
    local img = '[[File:' .. u.nameEn .. ' icon.png|64px|link=' .. page .. ']]'
    local text = '[[' .. page .. '|' .. u.nameX .. ']]'
    return img .. ' ' .. text
end

-- Boilerplate for the header cells
------------------------------------------------------------------------------------------------------------------------
local function addTh(tr, text)
    tr:tag('th'):wikitext(text):done()
end

-- Boilerplate for stat tds
------------------------------------------------------------------------------------------------------------------------
local function createStat(tr, value, pngName)
    tr:tag('td'):wikitext(value .. '[[File:' .. pngName .. '.png|link=]]'):done()
end

-- Boilerplate for the separator
------------------------------------------------------------------------------------------------------------------------
local function addSeparator(htmlTable, className, content)
    htmlTable:tag('tr')
        :addClass('separator')
        :addClass(className)
        :tag('td'):attr('data-sort-value', ''):attr('colspan', 100):wikitext(content):done()
end

------------------------------------------------------------------------------------------------------------------------
local function addFactionWords(words, lang, suffix, frame)
    for key, _ in pairs(FACTION_ORDER) do
        if key == 'neutral' then
            local file = '[[File:Primordial_Chaos.png|24px]]'
            words[key] = file .. ' [[Neutral_Units' .. suffix .. '|'.. words.wiki_units_neutral .. ']]'
        else
            words[key] = frame:preprocess('{{F|' .. key .. '|' .. lang .. '}}')
        end
    end
end

------------------------------------------------------------------------------------------------------------------------
local function renderIconWithHint(fileName, text, frame)
    local file = '[[File:' .. fileName .. '.png|32px|link=]]';
    return frame:preprocess('{{Hint|' .. file .. '|' .. text .. '}}')
end

------------------------------------------------------------------------------------------------------------------------
local function createHeader(htmlTable, words, frame)
    local header = htmlTable:tag('tr')
    -- 1 to 5 (general)
    addTh(header, words.creature)
    addTh(header, words.faction)
    addTh(header, words.tier)
    addTh(header, words.wiki_cost)
    addTh(header, words.units_weekly)
    -- 6 to 13 (main stats)
    addTh(header, renderIconWithHint(STAT_ICONS.hp, words.hp, frame))
    addTh(header, renderIconWithHint(STAT_ICONS.offence, words.offence, frame))
    addTh(header, renderIconWithHint(STAT_ICONS.defence, words.defence, frame))
    addTh(header, renderIconWithHint(STAT_ICONS.damage, words.damage, frame))
    addTh(header, renderIconWithHint(STAT_ICONS.morale, words.morale, frame))
    addTh(header, renderIconWithHint(STAT_ICONS.luck, words.luck, frame))
    addTh(header, renderIconWithHint(STAT_ICONS.initiative, words.initiative, frame))
    addTh(header, renderIconWithHint(STAT_ICONS.speed, words.speed, frame))
    -- 14 (others)
    addTh(header, renderIconWithHint('Sunlight_cavalry_passive_3', words.wiki_units_attack_type, frame))
end

------------------------------------------------------------------------------------------------------------------------
local function createBody(htmlTable, units, words, suffix, frame)
    local currentTier = units[1].tier
    local currentFaction = units[1].faction
    for _, u in ipairs(units) do

        -- separators
        if u.faction ~= currentFaction then
            currentFaction = u.faction
            currentTier = u.tier
            addSeparator(htmlTable, 'separator-large', words[currentFaction])
        elseif u.tier ~= currentTier then
            currentTier = u.tier
            addSeparator(htmlTable, 'separator-tiny', '')
        end

        local tr = htmlTable:tag('tr'):addClass('unit')
        if u.upgradeRank == 2 or u.upgradeRank == 3 then
            tr:addClass('upgraded')
        end
        -- 1 to 5 (general)
        tr:tag('td'):wikitext(renderUnitName(u, suffix)):done()
        tr:tag('td'):wikitext(words[currentFaction]):done()
        tr:tag('td'):wikitext(ROMAN[tonumber(u.tier)]):done()
        tr:tag('td'):attr('data-sort-value', string.match(u.cost, "^%d+")):wikitext(u.cost):done()
        tr:tag('td'):wikitext(tonumber(u.units_weekly)):done()
        -- 6 to 13 (main stats)
        createStat(tr, u.hp, STAT_ICONS.hp)
        createStat(tr, u.offence, STAT_ICONS.offence)
        createStat(tr, u.defence, STAT_ICONS.defence)
        createStat(tr, u.damage_min .. '-' .. u.damage_max, STAT_ICONS.damage)
        createStat(tr, MORALE_AND_LUCK[tonumber(u.morale)] or u.morale, STAT_ICONS.morale)
        createStat(tr, MORALE_AND_LUCK[tonumber(u.luck)] or u.luck, STAT_ICONS.luck)
        createStat(tr, u.initiative, STAT_ICONS.initiative)
        createStat(tr, u.speed, STAT_ICONS.speed)
        -- 14 (others)
        local wording = ATTACK_WORDS[u.attackType]
        local icon =  renderIconWithHint(ATTACK_ICONS[u.attackType], words[wording], frame)
        tr:tag('td'):attr('data-sort-value', ATTACK_RANKS[u.attackType]):wikitext(icon):done()
    end
end

-- Main public function
------------------------------------------------------------------------------------------------------------------------
function p.display(frame)
    --do return dump(frame) end

    -- Args
    local args = frame.args
    local lang = args.lang ~= '' and args.lang or 'en'
    --lang = 'ru'
    local forcedFaction = FACTION_MAPPING[args.faction] or nil
    --forcedFaction = 'human'

    -- Language
    local suffix = lang ~= 'en' and '/' .. lang or ''
    local words = translateIds(TRANSLATION_IDS, lang)
    addFactionWords(words, lang, suffix, frame)

    -- Cargo
    local results = query(lang, forcedFaction)
    local growth = queryGrowths()
    local units = consolidateResults(results, growth, lang)
    table.sort(units, sortUnits)

    -- Table
    local htmlTable = mw.html.create('table')
    htmlTable:addClass('wikitable sortable')
    if forcedFaction then
        htmlTable:addClass('forced-faction')
    end
    createHeader(htmlTable, words, frame)
    createBody(htmlTable, units, words, suffix, frame)

    -- Output
    local styleTag = frame:extensionTag('templatestyles', '', { src = frame:getTitle() .. '/styles.css' })
    return '<div class="units-overview">' .. styleTag .. tostring(htmlTable) .. '</div>'
end

return p