Files
WoW-Hybrid-gateway/ops/port_octo_character_stats.py

263 lines
17 KiB
Python

#!/usr/bin/env python3
"""Port Octo's BetterCharacterStats engine into the native 70334 character window.
Reads the Octo client's AddOns/BetterCharacterStats (read-only) and writes three WoWHybridUI files:
OctoStatsLocale.lua - BCS Localization.lua (pattern table), unchanged apart from the header
OctoStatsEngine.lua - BCS helper.lua (gear/talent/aura scanning) behind a 1.12 -> 70334 API shim
OctoStatsValues.lua - the BCS Set*/Get* stat functions, writing into recorder rows instead of 1.12 frames
The presentation (native Stats pane categories) is hand-written in OctoStatsPane.lua.
Every rewrite below is asserted to apply exactly, so an Octo update that changes the source fails loudly.
"""
import argparse, hashlib, re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_SRC = Path('/home/praxis/Games/octo/drive_c/Octowow/Interface/AddOns/BetterCharacterStats')
OUT = ROOT / 'client_addons/WoWHybridUI'
ENGINE_SHIM = r'''-- Generated by ops/port_octo_character_stats.py from Octo BetterCharacterStats helper.lua (sha256 %(sha)s).
-- 1.12 APIs used by the engine, served from 70334 APIs. Locals shadow the globals for this file only.
local SPELLS_PER_PAGE = 1000000000 -- the source's page arithmetic then reduces to slot = offset + index
local BOOKTYPE_SPELL = "spell"
local DEBUFF_BASE = 1000
local function AuraAt(index, filter)
return C_UnitAuras and C_UnitAuras.GetAuraDataByIndex and C_UnitAuras.GetAuraDataByIndex("player", index, filter)
end
-- 1.12 GetPlayerBuff(slot0, filter) -> buff index or -1. Helpful and harmful indices are kept apart.
local function GetPlayerBuff(slot, filter)
local index = slot + 1
if not AuraAt(index, filter) then return -1 end
return filter == "HARMFUL" and DEBUFF_BASE + index or index
end
-- 1.12 UnitBuff returned the icon path; the source compares it for Zeal / Water Shield. Return the aura name instead
-- (the comparisons are rewritten to names below).
local function UnitBuff(unit, slot)
local data = AuraAt(slot + 1, "HELPFUL")
if data then return data.name, data.applications end
end
local function TalentProvider() return GatewayTurtleTalents end
local function TalentsOf(tab)
local provider = TalentProvider(); if not provider then return {} end
local tabs = provider:ClassTabs(); local info = tabs[tab]
return info and provider.talentsByTab[info.id] or {}
end
local function GetNumTalentTabs() local provider = TalentProvider(); return provider and #provider:ClassTabs() or 0 end
local function GetNumTalents(tab) return #TalentsOf(tab) end
local function GetTalentInfo(tab, index)
local talent = TalentsOf(tab)[index]; if not talent then return end
return nil, nil, nil, nil, TalentProvider():Rank(talent.id, false), #talent.ranks
end
local function GetNumSpellTabs() return C_SpellBook and C_SpellBook.GetNumSpellBookSkillLines() or 0 end
local function GetSpellTabInfo(tab)
local info = C_SpellBook.GetSpellBookSkillLineInfo(tab)
if info then return info.name, info.iconID, info.itemIndexOffset, info.numSpellBookItems end
return nil, nil, 0, 0
end
-- 1.12 skill list, enough for the weapon/defense skill lookups by name.
local SKILL_IDS = {43,44,45,46,54,55,95,136,160,162,172,173,176,226,228,229,473}
local function GetSkillLineInfo(index)
local id = SKILL_IDS[index]; if not id then return end
local skill = C_SkillInfo and C_SkillInfo.GetSkillLineInfoByID and C_SkillInfo.GetSkillLineInfoByID(id)
if not skill or not skill.name then return "", false, false, 0, 0, 0 end
return skill.name, false, false, skill.rank or 0, 0, skill.modifier or 0
end
-- 1.12 calls with no 70334 global, served from their 70334 equivalents (file locals only, no global writes).
local function GetItemInfo(item) -- 1.12 tuple = 70334 tuple without itemLevel (4th)
if not (C_Item and C_Item.GetItemInfo) or not item then return end
local name, link, quality, _, minLevel, itemType, subType, stack, equipLoc, texture = C_Item.GetItemInfo(item)
return name, link, quality, minLevel, itemType, subType, stack, equipLoc, texture
end
local function GetSpellName(slot) return C_SpellBook.GetSpellBookItemName(slot, Enum.SpellBookSpellBank.Player) end
local function OffhandHasWeapon() return C_PaperDollInfo.OffhandHasWeapon() and 1 or nil end
-- Weapon item subclass -> skill line; fist weapons and empty hands = Unarmed, as BCS GetWeaponSkillForWeaponType.
local WEAPON_SKILL = {[0]=44,[1]=172,[2]=45,[3]=46,[4]=54,[5]=160,[6]=229,[7]=43,[8]=55,[10]=136,[13]=162,[15]=173,[16]=176,[18]=226,[19]=228}
local function SkillOf(id)
local skill = id and C_SkillInfo.GetSkillLineInfoByID(id)
if not skill or not skill.rank then return 0, 0 end
return skill.rank, skill.modifier or 0
end
local function SlotSkill(slot, unarmed)
local link = GetInventoryItemLink("player", slot)
if not link then return unarmed and SkillOf(162) or 0, 0 end
local _, _, _, _, _, classID, subclassID = C_Item.GetItemInfoInstant(link)
if classID ~= 2 then return 0, 0 end
return SkillOf(WEAPON_SKILL[subclassID])
end
local function UnitAttackBothHands()
local mb, mm = SlotSkill(16, true)
local ob, om = SlotSkill(17, false)
return mb, mm, ob, om
end
local function UnitRangedAttack() return SlotSkill(18, false) end
local function UnitDefense() return SkillOf(95) end
local function InstallTooltipShims(tooltip)
function tooltip:SetPlayerBuff(index)
self:ClearLines()
if index > DEBUFF_BASE then return self:SetUnitDebuff("player", index - DEBUFF_BASE) end
return self:SetUnitBuff("player", index)
end
function tooltip:SetTalent(tab, index)
self:ClearLines()
local provider, talent = TalentProvider(), TalentsOf(tab)[index]
if not provider or not talent then return end
local rank = provider:Rank(talent.id, false)
local record = talent.ranks[math.max(1, rank)]
local ok, text = pcall(provider.FormatDescription, record, provider.spellRecords)
if ok and type(text) == "string" then
for line in string.gmatch(text, "[^\n]+") do self:AddLine(line) end
end
end
function tooltip:SetSpell(slot) return self:SetSpellBookItem(slot, Enum.SpellBookSpellBank.Player) end
-- A 70334 GameTooltip without an owner fills no lines (1.12 scanned unowned tooltips). Anchor it, hidden, first.
for _, method in ipairs({"SetHyperlink", "SetInventoryItem", "SetSpellBookItem", "SetUnitBuff", "SetUnitDebuff"}) do
local original = tooltip[method]
if original then
tooltip[method] = function(self, ...)
if not self:IsOwned(WorldFrame) then self:SetOwner(WorldFrame, "ANCHOR_NONE") end
return original(self, ...)
end
end
end
end
'''
VALUES_HEADER = r'''-- Generated by ops/port_octo_character_stats.py from Octo BetterCharacterStats.lua (sha256 %(sha)s).
-- The stat functions run unchanged against recorder rows (OctoStatsPane.lua); tooltips go to a line recorder.
local OctoStatsThis
BCS.TipRecorder = BCS.TipRecorder or {} -- methods are filled in by OctoStatsPane.lua
local GameTooltip = BCS.TipRecorder
function BCS:RunWithThis(frame, fn) OctoStatsThis = frame; local ok, err = pcall(fn); OctoStatsThis = nil; return ok, err end
-- 1.12 calls with no 70334 global, served from their 70334 equivalents (file locals only, no global writes).
local function GetItemInfo(item) -- 1.12 tuple = 70334 tuple without itemLevel (4th)
if not (C_Item and C_Item.GetItemInfo) or not item then return end
local name, link, quality, _, minLevel, itemType, subType, stack, equipLoc, texture = C_Item.GetItemInfo(item)
return name, link, quality, minLevel, itemType, subType, stack, equipLoc, texture
end
local function GetSpellName(slot) return C_SpellBook.GetSpellBookItemName(slot, Enum.SpellBookSpellBank.Player) end
local function OffhandHasWeapon() return C_PaperDollInfo.OffhandHasWeapon() and 1 or nil end
-- Weapon item subclass -> skill line; fist weapons and empty hands = Unarmed, as BCS GetWeaponSkillForWeaponType.
local WEAPON_SKILL = {[0]=44,[1]=172,[2]=45,[3]=46,[4]=54,[5]=160,[6]=229,[7]=43,[8]=55,[10]=136,[13]=162,[15]=173,[16]=176,[18]=226,[19]=228}
local function SkillOf(id)
local skill = id and C_SkillInfo.GetSkillLineInfoByID(id)
if not skill or not skill.rank then return 0, 0 end
return skill.rank, skill.modifier or 0
end
local function SlotSkill(slot, unarmed)
local link = GetInventoryItemLink("player", slot)
if not link then return unarmed and SkillOf(162) or 0, 0 end
local _, _, _, _, _, classID, subclassID = C_Item.GetItemInfoInstant(link)
if classID ~= 2 then return 0, 0 end
return SkillOf(WEAPON_SKILL[subclassID])
end
local function UnitAttackBothHands()
local mb, mm = SlotSkill(16, true)
local ob, om = SlotSkill(17, false)
return mb, mm, ob, om
end
local function UnitRangedAttack() return SlotSkill(18, false) end
local function UnitDefense() return SkillOf(95) end
'''
VALUES_EXTRA = r'''
-- 1.12 global strings this file reads; the client's own value wins wherever 70334 still has it.
local ARMOR, ARMOR_COLON = ARMOR or "Armor", ARMOR_COLON or "Armor:"
local ARMOR_TOOLTIP = ARMOR_TOOLTIP or "Damage reduction against level %d: %.2f%%"
local ATTACK_POWER_COLON, MELEE_ATTACK_POWER = ATTACK_POWER_COLON or "Attack Power:", MELEE_ATTACK_POWER or "Melee Attack Power"
local MELEE_ATTACK_POWER_TOOLTIP = MELEE_ATTACK_POWER_TOOLTIP or "Increases damage with melee weapons by %.1f damage per second."
local ATTACK_POWER_MAGIC_NUMBER = ATTACK_POWER_MAGIC_NUMBER or 14
local ATTACK_SPEED_COLON, DAMAGE_COLON, DEFENSE_COLON = ATTACK_SPEED_COLON or "Speed:", DAMAGE_COLON or "Damage:", DEFENSE_COLON or "Defense:"
-- 1.12 PaperDollFormatStat (FrameXML/PaperDollFrame.lua): the 70334 one has another signature and writes other fields.
local function PaperDollFormatStat(name, base, posBuff, negBuff, frame, textString)
posBuff, negBuff = posBuff or 0, negBuff or 0
local effective = max(0, base + posBuff + negBuff)
local text = HIGHLIGHT_FONT_COLOR_CODE .. name .. " " .. effective
if posBuff == 0 and negBuff == 0 then
text = text .. FONT_COLOR_CODE_CLOSE
textString:SetText(effective)
else
if posBuff > 0 or negBuff < 0 then text = text .. " (" .. base .. FONT_COLOR_CODE_CLOSE end
if posBuff > 0 then text = text .. FONT_COLOR_CODE_CLOSE .. GREEN_FONT_COLOR_CODE .. "+" .. posBuff .. FONT_COLOR_CODE_CLOSE end
if negBuff < 0 then text = text .. RED_FONT_COLOR_CODE .. " " .. negBuff .. FONT_COLOR_CODE_CLOSE end
if posBuff > 0 or negBuff < 0 then text = text .. HIGHLIGHT_FONT_COLOR_CODE .. ")" .. FONT_COLOR_CODE_CLOSE end
textString:SetText((negBuff < 0 and RED_FONT_COLOR_CODE or GREEN_FONT_COLOR_CODE) .. effective .. FONT_COLOR_CODE_CLOSE)
end
frame.tooltip = text
end
'''
def sub_exact(text, old, new, count=None, label=''):
n = text.count(old)
if n == 0 or (count is not None and n != count):
raise SystemExit(f'rewrite {label!r} expected {count or ">=1"} matches of {old!r}, found {n}')
return text.replace(old, new)
def port(src):
loc = (src / 'Localization.lua').read_text(encoding='utf-8')
helper = (src / 'helper.lua').read_text(encoding='utf-8')
main = (src / 'BetterCharacterStats.lua').read_text(encoding='utf-8')
sha = {n: hashlib.sha256((src / n).read_bytes()).hexdigest() for n in ('Localization.lua', 'helper.lua', 'BetterCharacterStats.lua')}
locale = f'-- Generated by ops/port_octo_character_stats.py from Octo BetterCharacterStats Localization.lua (sha256 {sha["Localization.lua"]}).\n' + loc
h = helper
h = sub_exact(h, 'local BCS_Tooltip = BetterCharacterStatsTooltip or CreateFrame("GameTooltip", "BetterCharacterStatsTooltip", nil, "GameTooltipTemplate")\nlocal BCS_Prefix = "BetterCharacterStatsTooltip"',
'local BCS_Tooltip = OctoStatsScanTooltip or CreateFrame("GameTooltip", "OctoStatsScanTooltip", nil, "GameTooltipTemplate")\nlocal BCS_Prefix = "OctoStatsScanTooltip"\nInstallTooltipShims(BCS_Tooltip)', 1, 'tooltip')
# 70334 links have empty fields (item:123::::...); the 1.12 pattern needs digits in every field.
h = sub_exact(h, '"(item:%d+:%d+:%d+:%d+)"', '"(item:[%-%d:]+)"', None, 'link pattern')
h = sub_exact(h, 'icon == "Interface\\\\Icons\\\\Spell_Holy_CrusaderStrike"', 'icon == L["Zeal"] or icon == "Zeal"', 1, 'zeal')
h = sub_exact(h, 'icon == "Interface\\\\Icons\\\\Ability_Shaman_WaterShield"', 'icon == L["Water Shield"] or icon == "Water Shield"', 1, 'water shield')
# 1.12 BCS read melee crit from the Attack spell tooltip (= Source PLAYER_CRIT_PERCENTAGE); 70334's tooltip has no such
# line. The same Source value reaches 70334 as ActivePlayerData.CritPercentage -> native GetCritChance().
h = sub_exact(h, 'function BCS:GetCritChance()\n\tlocal crit = 0\n', 'function BCS:GetCritChance()\n\tif GetCritChance then return GetCritChance() or 0 end\n\tlocal crit = 0\n', 1, 'melee crit')
# #119 (2026-11-26): scan gear once per equipped-link change (was twice per rebuild, ~280 ms hitch).
h = sub_exact(h, '-- Run all scans based on dirty flags\nfunction BCS:RunScans()\n\tif BCS.needScanGear then\n\t\tScanAllGear()\n\tend\n\tif BCS.needScanTalents then\n\t\tScanAllTalents()\n\tend\n\tif BCS.needScanGear then\n\t\tScanAllGear()\n\tend\n\tif BCS.needScanAuras then\n\t\tScanAllAuras()\n\tend\nend\n\n',
'-- Equipped-link signature; nil while any equipped item lacks cached data (its tooltip may be incomplete, so never skip).\nlocal function GearSignature()\n\tlocal parts = {}\n\tfor slot = 1, 19 do\n\t\tlocal link = GetInventoryItemLink("player", slot)\n\t\tif link and not GetItemInfo(link) then return nil end\n\t\tparts[slot] = link or ""\n\tend\n\treturn table.concat(parts, "|")\nend\n\n-- Run all scans based on dirty flags.\n-- 2026-11-26 (#119): the gear scan (tooltip parse of every slot, ~140 ms) ran twice per rebuild and again after every\n-- UNIT_INVENTORY_CHANGED/SKILL_LINES_CHANGED, so reopening the character window hitched ~280 ms. It reads no talent\n-- state: scan once, and only when the equipped links changed.\nfunction BCS:RunScans()\n\tif BCS.needScanTalents then\n\t\tScanAllTalents()\n\tend\n\tif BCS.needScanGear then\n\t\tlocal signature = GearSignature()\n\t\tif not signature or signature ~= BCS.lastGearSignature then\n\t\t\tScanAllGear()\n\t\t\tBCS.lastGearSignature = signature\n\t\tend\n\tend\n\tif BCS.needScanAuras then\n\t\tScanAllAuras()\n\tend\nend\n\n', 1, 'gear scan once')
# Per-source totals (gear / talents / auras) for the Stats pane breakdown: each row shows its parts from the
# same cache its total is built from, so nothing is counted twice.
h = sub_exact(h, 'BCS.ScanAllAuras = ScanAllAuras\n', 'BCS.ScanAllAuras = ScanAllAuras\nBCS.Cache = BCScache\n', 1, 'cache export')
# #114 (2026-11-30): 1.12 printed an ACTIVE set bonus as "Set: ..." (only inactive ones had "(N) "); 70334 prefixes
# every set line with "(N) " and colours active ones green. Strip the prefix on green lines so the 1.12 "^Set:"
# patterns count active bonuses again; grey (inactive) lines keep the prefix and stay uncounted, as in 1.12.
h = sub_exact(h, 'InstallTooltipShims(BCS_Tooltip)\n',
'InstallTooltipShims(BCS_Tooltip)\n'
'local function BCS_LineText(fs)\n'
'\tlocal text = fs and fs:GetText()\n'
'\tif text and strfind(text, "^%(%d+%) Set: ") then\n'
'\t\tlocal r, g, b = fs:GetTextColor()\n'
'\t\tif g and g > 0.8 and r < 0.5 and b < 0.5 then text = gsub(text, "^%(%d+%) ", "", 1) end\n'
'\tend\n'
'\treturn text\n'
'end\n', 1, 'set line text')
h = sub_exact(h, '_G[BCS_Prefix .. "TextLeft" .. line]:GetText()', 'BCS_LineText(_G[BCS_Prefix .. "TextLeft" .. line])', 8, 'set line reads')
engine = ENGINE_SHIM % {'sha': sha['helper.lua']} + h
lines = main.split('\n')
start = next(i for i, l in enumerate(lines) if l.startswith('local function StatFrame_OnUpdate()'))
end = next(i for i, l in enumerate(lines) if l.startswith('function BCS:UpdatePaperdollStats('))
head_end = next(i for i, l in enumerate(lines) if l.startswith('BCS.Debug = false'))
body = '\n'.join(lines[:head_end] + lines[start:end])
body = sub_exact(body, 'BCSConfig = BCSConfig or {}\n', '', 1, 'config')
body = re.sub(r'_G\[statFrame:GetName\(\) \.\. "StatText"\]', 'statFrame.StatText', body)
body = re.sub(r'_G\[statFrame:GetName\(\) \.\. "Label"\]', 'statFrame.Label', body)
body = re.sub(r'getglobal\(statFrame:GetName\(\) \.\. "StatText"\)', 'statFrame.StatText', body)
body = re.sub(r'getglobal\(statFrame:GetName\(\) \.\. "Label"\)', 'statFrame.Label', body)
if 'GetName()' in body: raise SystemExit('unported frame name lookup left in stat functions')
body = re.sub(r'\bthis\b', 'OctoStatsThis', body)
body = re.sub(r'\barg1\b', '0.2', body)
if re.search(r'\bgetn\b|\bgfind\b', body): raise SystemExit('Lua 5.0 table/string call left in stat functions')
values = VALUES_HEADER % {'sha': sha['BetterCharacterStats.lua']} + VALUES_EXTRA + body + '\n'
return {'OctoStatsLocale.lua': locale, 'OctoStatsEngine.lua': engine, 'OctoStatsValues.lua': values}
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--source', type=Path, default=DEFAULT_SRC)
p.add_argument('--out', type=Path, default=OUT)
a = p.parse_args()
for name, text in port(a.source).items():
(a.out / name).write_text(text, encoding='utf-8')
print(name, len(text))
if __name__ == '__main__':
main()