-- MaravillasForever Guild Companion Addon -- Tracks character progress, professions, deaths, duels and instance activity. -- Offers an in-game Overview / History / Activity / Export control panel. local ADDON_NAME = "MaravillasForever" -- Same build as .toc and the current website download. local ADDON_VERSION = "0.1.8-beta" local frame = CreateFrame("Frame") -- Forward declarations let the event dispatcher refresh an already-open panel. local controlPanel, RefreshPanel local nextPanelRefresh = 0 -- ========================================================================= -- BASE64 & CRC32 EXPORT ENCODER (CORRUPTION CHECK, NOT AUTHENTICATION) -- ========================================================================= local b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' local function ToBase64(data) return ((data:gsub('.', function(x) local r,b='',x:byte() for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end return r; end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x) if (#x < 6) then return '' end local c=0 for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end return b64chars:sub(c+1,c+1) end)..({ '', '==', '=' })[#data%3+1]) end -- Fast CRC-32 table generator local crcTable = {} for i = 0, 255 do local crc = i for j = 1, 8 do if bit.band(crc, 1) == 1 then crc = bit.bxor(bit.rshift(crc, 1), 0xEDB88320) else crc = bit.rshift(crc, 1) end end crcTable[i] = crc end local function CalculateCRC32(s) local crc = 0xFFFFFFFF for i = 1, #s do local byte = string.byte(s, i) local idx = bit.band(bit.bxor(crc, byte), 0xFF) crc = bit.bxor(bit.rshift(crc, 8), crcTable[idx]) end crc = bit.bxor(crc, 0xFFFFFFFF) return string.format("%08X", crc) end -- Mini JSON Serializer for WoW Lua local function SerializeJSON(val) local t = type(val) if t == "table" then local isArray = #val > 0 local parts = {} if isArray then for _, v in ipairs(val) do table.insert(parts, SerializeJSON(v)) end return "[" .. table.concat(parts, ",") .. "]" else for k, v in pairs(val) do table.insert(parts, string.format("%q:%s", tostring(k), SerializeJSON(v))) end return "{" .. table.concat(parts, ",") .. "}" end elseif t == "number" then return tostring(val) elseif t == "boolean" then return val and "true" or "false" elseif t == "string" then return string.format("%q", val) else return "null" end end -- ========================================================================= -- DATABASE & STAT TRACKING -- ========================================================================= local function InitDB() if not MaravillasForeverDB then MaravillasForeverDB = { version = 1, characters = {}, bountiesClaimed = {}, deathLog = {}, lastSync = 0, latestExportString = "" } end -- Report the running build when WoW next saves SavedVariables. MaravillasForeverDB.addonVersion = ADDON_VERSION if not MaravillasForeverDB.characters then MaravillasForeverDB.characters = {} end if not MaravillasForeverDB.bountiesClaimed then MaravillasForeverDB.bountiesClaimed = {} end if not MaravillasForeverDB.deathLog then MaravillasForeverDB.deathLog = {} end if not MaravillasForeverDB.eventLog then MaravillasForeverDB.eventLog = {} end if not MaravillasForeverDB.eventSequence then MaravillasForeverDB.eventSequence = 0 end if MaravillasForeverDB.relayEnabled == nil then MaravillasForeverDB.relayEnabled = false end if MaravillasForeverDB.squadRelayEnabled == nil then MaravillasForeverDB.squadRelayEnabled = true end if not MaravillasForeverDB.relaySeen then MaravillasForeverDB.relaySeen = {} end if not MaravillasForeverDB.relayCharacters then MaravillasForeverDB.relayCharacters = {} end if not MaravillasForeverDB.relayPeers then MaravillasForeverDB.relayPeers = {} end if not MaravillasForeverDB.duelLog then MaravillasForeverDB.duelLog = {} end if not MaravillasForeverDB.activeInstances then MaravillasForeverDB.activeInstances = {} end end -- Protect snapshot reads from absent or restricted Forever client APIs. -- Retain the last valid value instead of overwriting progress with a fabricated zero. local function SafeNumericRead(fn, fallback, minimum, maximum) if type(fn) ~= "function" then return fallback end local ok, value = pcall(fn) if not ok or type(value) ~= "number" then return fallback end if type(issecretvalue) == "function" then local secretOk, secret = pcall(issecretvalue, value) if not secretOk or secret then return fallback end end if value ~= value or value < minimum or value > maximum then return fallback end return math.floor(value) end -- Forever can populate the character surname after the first login callback. -- Prefer the full display name when available, then retry the snapshot shortly. local function PlayerFullName() if type(GetUnitName) == "function" then local ok, value = pcall(GetUnitName, "player", true) if ok and type(value) == "string" and value ~= "" then return value end end return UnitName("player") end local function GetCharacterKey() local name = PlayerFullName() local realm = GetNormalizedRealmName() or GetRealmName() or "Forever" if not name or name == "" then return nil end return name .. "-" .. realm end -- Squad Relay v1: addon-only GUILD traffic; never forwards someone else's event. -- Messages are untrusted until independently verified. No addon can write files on demand. local RELAY_PREFIX = "MFR1" local relayQueue = {} local relayTicking = false local relayHeartbeat = nil local function RelayAPI() return C_ChatInfo and C_ChatInfo.RegisterAddonMessagePrefix and C_ChatInfo.SendAddonMessage end local function RelayActive() return MaravillasForeverDB and MaravillasForeverDB.squadRelayEnabled and RelayAPI() and IsInGuild and IsInGuild() end local function CleanField(value, maxLength) return tostring(value or ""):gsub("[%c|]", " "):sub(1, maxLength) end local function PumpRelay() if #relayQueue == 0 then relayTicking = false return end if RelayActive() then C_ChatInfo.SendAddonMessage(RELAY_PREFIX, table.remove(relayQueue, 1), "GUILD") else relayQueue = {} end if C_Timer and C_Timer.After then C_Timer.After(1.25, PumpRelay) else relayTicking = false end end local function QueueRelay(message) if not RelayActive() or #message > 240 or #relayQueue >= 80 then return end table.insert(relayQueue, message) if not relayTicking then relayTicking = true PumpRelay() end end local function BroadcastEvent(event) if not event or not event.id then return end if event.type == "duel" then QueueRelay(table.concat({ "U", CleanField(event.id, 110), CleanField(event.character, 32), tostring(math.floor(tonumber(event.timestamp) or 0)), CleanField(event.winner, 32), CleanField(event.loser, 32) }, "|")) return end if event.type ~= "death" and event.type ~= "level_up" then return end local code = event.type == "death" and "D" or "L" QueueRelay(table.concat({ code, CleanField(event.id, 110), CleanField(event.character, 32), tostring(math.floor(tonumber(event.timestamp) or 0)), tostring(math.floor(tonumber(event.level) or 0)), CleanField(event.killer, 45), CleanField(event.zone, 45) }, "|")) end local function BroadcastSnapshot() local key = GetCharacterKey() local c = key and MaravillasForeverDB.characters[key] if not c then return end QueueRelay(table.concat({ "S", CleanField(c.name, 32), CleanField(c.realm, 32), tostring(c.lastUpdated or 0), tostring(c.level or 1), tostring(c.xp or 0), tostring(c.xpMax or 0), tostring(c.restedXP or 0), tostring(c.money or 0), tostring(c.deaths or 0), tostring(c.kills or 0), CleanField(c.class, 16), CleanField(c.race, 24), CleanField(c.currentZone, 45) }, "|")) end -- Guild peer versions are hints, not authenticated release metadata. -- Only the website release catalog establishes the recommended download. local newestPeerVersion = nil local announcedPeerVersion = nil local function VersionParts(version) if type(version) ~= "string" or #version > 32 then return nil end local major, minor, patch, suffix = version:match("^(%d+)%.(%d+)%.(%d+)%-(%w[%w%.%-]*)$") if not major then major, minor, patch = version:match("^(%d+)%.(%d+)%.(%d+)$") end if not major then return nil end major, minor, patch = tonumber(major), tonumber(minor), tonumber(patch) if not major or not minor or not patch or major > 999 or minor > 999 or patch > 999 then return nil end return {major, minor, patch, suffix} end local function IsNewerVersion(candidate, installed) local a, b = VersionParts(candidate), VersionParts(installed) if not a or not b then return false end for i = 1, 3 do if a[i] ~= b[i] then return a[i] > b[i] end end if a[4] == b[4] then return false end if not a[4] then return true end if not b[4] then return false end return a[4] > b[4] end local function ShowPeerUpdateIfSafe() if not newestPeerVersion or announcedPeerVersion == newestPeerVersion then return end if type(InCombatLockdown) == "function" and InCombatLockdown() then return end announcedPeerVersion = newestPeerVersion print("|cffff8000[MaravillasForever]|r A guild member reports a newer addon (" .. newestPeerVersion .. "). This is unverified; check |cffffd100forever.pondere.moe/releases|r for the official download.") end local function OnSquadRelay(prefix, message, channel, sender) if prefix ~= RELAY_PREFIX or channel ~= "GUILD" or not RelayActive() then return end if type(message) ~= "string" or #message > 255 then return end local senderName = tostring(sender or ""):match("^[^-]+") if not senderName or senderName == PlayerFullName() then return end MaravillasForeverDB.relayPeers[sender] = time() local fields = {} for field in (message .. "|"):gmatch("(.-)|") do table.insert(fields, field) end if fields[1] == "V" then if #fields ~= 2 or not VersionParts(fields[2]) then return end if IsNewerVersion(fields[2], ADDON_VERSION) and (not newestPeerVersion or IsNewerVersion(fields[2], newestPeerVersion)) then newestPeerVersion = fields[2] ShowPeerUpdateIfSafe() end elseif fields[1] == "H" then QueueRelay("V|" .. ADDON_VERSION) BroadcastSnapshot() -- On join: replay bounded history with delayed sends to avoid flooding. local log = MaravillasForeverDB.eventLog for i = math.max(1, #log - 19), #log do if log[i] and log[i].character == PlayerFullName() then BroadcastEvent(log[i]) end end elseif fields[1] == "S" then if #fields ~= 14 or fields[2] ~= senderName then return end local when = tonumber(fields[4]) local level = tonumber(fields[5]) if not when or when < 1 or when > time() + 300 or not level or level < 1 or level > 100 then return end -- Store relayed snapshots separately; they are never treated as the local character. MaravillasForeverDB.relayCharacters = MaravillasForeverDB.relayCharacters or {} local key = fields[2] .. "-" .. fields[3] local prev = MaravillasForeverDB.relayCharacters[key] if not prev or (prev.lastUpdated or 0) < when then MaravillasForeverDB.relayCharacters[key] = { name = fields[2], realm = fields[3], lastUpdated = when, level = level, xp = tonumber(fields[6]) or 0, xpMax = tonumber(fields[7]) or 400, restedXP = tonumber(fields[8]) or 0, money = tonumber(fields[9]) or 0, deaths = tonumber(fields[10]) or 0, kills = tonumber(fields[11]) or 0, class = fields[12], race = fields[13], currentZone = fields[14] } end elseif fields[1] == "U" then if #fields ~= 6 or fields[3] ~= senderName then return end local id, at, winner, loser = fields[2], tonumber(fields[4]), fields[5], fields[6] if #id > 180 or not id:match("^[%w:_.@%-]+$") or not at or at < 1 or at > time() + 300 then return end if winner == "" or loser == "" or winner == loser then return end if winner ~= senderName and loser ~= senderName then return end if MaravillasForeverDB.relaySeen[id] then return end MaravillasForeverDB.relaySeen[id] = true table.insert(MaravillasForeverDB.eventLog, { id = id, character = senderName, type = "duel", winner = winner, loser = loser, timestamp = at, relayed = true }) elseif fields[1] == "D" or fields[1] == "L" then if #fields ~= 7 or fields[3] ~= senderName then return end local id, at, level = fields[2], tonumber(fields[4]), tonumber(fields[5]) if not id:match("^[%w:_.@%-]+$") or #id > 180 or not at or at < 1 or not level or level < 1 or level > 100 then return end if MaravillasForeverDB.relaySeen[id] then return end MaravillasForeverDB.relaySeen[id] = true local event = { id = id, character = fields[3], timestamp = at, level = level, type = fields[1] == "D" and "death" or "level_up", killer = fields[6], zone = fields[7], relayed = true } table.insert(MaravillasForeverDB.eventLog, event) -- Never rebroadcast received events: no echo loops. end end local function StartSquadRelay() if not RelayAPI() or not RelayActive() then return end C_ChatInfo.RegisterAddonMessagePrefix(RELAY_PREFIX) QueueRelay("H") QueueRelay("V|" .. ADDON_VERSION) BroadcastSnapshot() if not relayHeartbeat and C_Timer and C_Timer.NewTicker then relayHeartbeat = C_Timer.NewTicker(90, function() if RelayActive() then QueueRelay("V|" .. ADDON_VERSION) BroadcastSnapshot() end end) end end local function RecordEvent(eventType, details) if not MaravillasForeverDB then InitDB() end MaravillasForeverDB.eventSequence = MaravillasForeverDB.eventSequence + 1 local event = details or {} event.id = (GetCharacterKey() or "Unknown") .. ":" .. tostring(time()) .. ":" .. tostring(MaravillasForeverDB.eventSequence) event.character = PlayerFullName() or "Unknown" event.realm = GetNormalizedRealmName() or GetRealmName() or "Forever" event.type = eventType event.timestamp = time() table.insert(MaravillasForeverDB.eventLog, event) BroadcastEvent(event) if MaravillasForeverDB.relayEnabled and (eventType == "death" or eventType == "level_up") and IsInGuild and IsInGuild() and SendChatMessage then local msg = "[MaravillasForever] " .. event.character .. (eventType == "death" and (" died at level " .. tostring(event.level or "?")) or (" reached level " .. tostring(event.level or "?"))) SendChatMessage(msg, "GUILD") end return event end -- Instance visits: one owner-authored entry and exit per continuous session. -- Entry/exit do NOT prove a boss kill or a completed dungeon. local function TrackInstanceVisit() if type(GetInstanceInfo) ~= "function" then return end local key = GetCharacterKey() if not key then return end local name, kind, _, difficultyName, _, _, _, instanceId = GetInstanceInfo() local isTracked = (kind == "party" or kind == "raid") and type(name) == "string" and name ~= "" local active = MaravillasForeverDB.activeInstances[key] local id = math.floor(tonumber(instanceId) or 0) if id < 0 then id = 0 end local identity = isTracked and (kind .. ":" .. tostring(id) .. ":" .. name) or nil if active and active.identity ~= identity then RecordEvent("instance_exit", { runId = active.runId, instanceName = active.name, instanceType = active.kind, instanceId = active.instanceId, difficulty = active.difficulty }) MaravillasForeverDB.activeInstances[key] = nil end if identity and not MaravillasForeverDB.activeInstances[key] then local details = { instanceName = name, instanceType = kind, instanceId = id, difficulty = tostring(difficultyName or "") } local event = RecordEvent("instance_enter", details) event.runId = event.id MaravillasForeverDB.activeInstances[key] = { identity = identity, runId = event.id, name = name, kind = kind, instanceId = id, difficulty = details.difficulty } end end -- Automatic wipe detection (conservative): a full, unchanged instance group -- must be observed ALIVE at a combat pull and DEAD after that pull. -- Partial deaths, party reshuffles, disconnects and resets without deaths -- are not counted. SavedVariables contain one owner-authored event per pull. local wipePull = nil local wipeGeneration = 0 local function WipeGroupUnits() local units = {} local raid = IsInRaid and IsInRaid() if raid then local total = GetNumGroupMembers and GetNumGroupMembers() or 0 if total < 2 or total > 40 then return nil end for i = 1, total do table.insert(units, "raid" .. i) end else local n = GetNumSubgroupMembers and GetNumSubgroupMembers() or (GetNumPartyMembers and GetNumPartyMembers() or 0) if n < 1 or n > 4 then return nil end table.insert(units, "player") for i = 1, n do table.insert(units, "party" .. i) end end return units end local function WipeGroupSnapshot(requireAlive) if type(UnitGUID) ~= "function" or type(UnitExists) ~= "function" or type(UnitIsDeadOrGhost) ~= "function" then return nil end local units = WipeGroupUnits() if not units then return nil end local snapshot, seen = {}, {} for _, unit in ipairs(units) do if not UnitExists(unit) or (UnitIsConnected and not UnitIsConnected(unit)) then return nil end local guid = UnitGUID(unit) if not guid or seen[guid] then return nil end if requireAlive and UnitIsDeadOrGhost(unit) then return nil end seen[guid] = true table.insert(snapshot, guid) end return snapshot end local function WipeGroupAllDead(snapshot) local units = WipeGroupUnits() if not units or #units ~= #snapshot then return false end local memberIds = {} for _, id in ipairs(snapshot) do memberIds[id] = true end for _, unit in ipairs(units) do if not UnitExists(unit) or (UnitIsConnected and not UnitIsConnected(unit)) or not memberIds[UnitGUID(unit)] or not UnitIsDeadOrGhost(unit) then return false end memberIds[UnitGUID(unit)] = nil end for _ in pairs(memberIds) do return false end return true end local function OnWipePullStart() if type(GetInstanceInfo) ~= "function" then return end TrackInstanceVisit() local key = GetCharacterKey() local active = key and MaravillasForeverDB.activeInstances[key] if not active or not active.runId then return end local members = WipeGroupSnapshot(true) if not members then return end wipeGeneration = wipeGeneration + 1 wipePull = {runId = active.runId, members = members, generation = wipeGeneration, finished = false} end local function CheckAutomaticWipe() local pull = wipePull if not pull or pull.finished or pull.confirming or not WipeGroupAllDead(pull.members) then return end -- A stable full-group death must persist before it can count as a wipe. -- Without a timer there is no confirmation, so fail closed. if not C_Timer or not C_Timer.After then return end pull.confirming = true local generation = pull.generation local function confirm() if wipePull ~= pull or pull.finished or pull.generation ~= generation then return end pull.confirming = false if not WipeGroupAllDead(pull.members) then return end local key = GetCharacterKey() local active = key and MaravillasForeverDB.activeInstances[key] if not active or active.runId ~= pull.runId then return end pull.finished = true RecordEvent("instance_wipe", { runId = active.runId, instanceName = active.name, instanceType = active.kind, instanceId = active.instanceId, difficulty = active.difficulty, detection = "group_all_dead", groupSize = #pull.members }) print("|cffff8000[MaravillasForever]|r Automatically recorded a group wipe in " .. active.name .. ".") if controlPanel and controlPanel:IsShown() and controlPanel.selectedTab ~= 4 and RefreshPanel then RefreshPanel() end end C_Timer.After(3, confirm) end local function EndWipePullSoon() local pull = wipePull if not pull then return end CheckAutomaticWipe() -- Keep a brief grace period after leaving combat for delayed party deaths; -- never allow deaths long after a pull to create a false wipe. if C_Timer and C_Timer.After then C_Timer.After(12, function() if wipePull == pull then wipePull = nil end end) else wipePull = nil end end -- Primary and secondary professions from the character's skill lines. -- Uses localized names via GetSkillLineInfo and stable skill-line IDs where available. local professionNames = { [171] = "Alchemy", [164] = "Blacksmithing", [333] = "Enchanting", [202] = "Engineering", [182] = "Herbalism", [773] = "Inscription", [755] = "Jewelcrafting", [165] = "Leatherworking", [186] = "Mining", [393] = "Skinning", [197] = "Tailoring", [185] = "Cooking", [356] = "Fishing", [129] = "First Aid" } local professionByName = { ["Alchemy"] = 171, ["Blacksmithing"] = 164, ["Enchanting"] = 333, ["Engineering"] = 202, ["Herbalism"] = 182, ["Inscription"] = 773, ["Jewelcrafting"] = 755, ["Leatherworking"] = 165, ["Mining"] = 186, ["Skinning"] = 393, ["Tailoring"] = 197, ["Cooking"] = 185, ["Fishing"] = 356, ["First Aid"] = 129 } local function ReadProfessions() local list = {} -- WoW Forever exposes GetProfessions/GetProfessionInfo but can omit the -- older GetNumSkillLines/GetSkillLineInfo pair entirely. if type(GetProfessions) == "function" and type(GetProfessionInfo) == "function" then local ok, first, second, archaeology, fishing, cooking, firstAid = pcall(GetProfessions) if ok then local seen = {} local slots = {first, second, archaeology, fishing, cooking, firstAid} -- Numeric iteration is intentional: nil slots can precede later skills. for index = 1, 6 do local slot = slots[index] if type(slot) == "number" and slot > 0 then local valid, name, _, skill, maxSkill, _, _, skillLineID = pcall(GetProfessionInfo, slot) if valid and type(name) == "string" and type(skill) == "number" then local id = professionNames[skillLineID] and skillLineID or professionByName[name] if id and not seen[id] then table.insert(list, {id = id, name = professionNames[id], skill = math.max(0, math.floor(skill)), maxSkill = math.max(1, math.floor(tonumber(maxSkill) or 1))}) seen[id] = true end end end end return list end end if type(GetNumSkillLines) ~= "function" or type(GetSkillLineInfo) ~= "function" then return nil end local localizedNames = {} if type(GetSpellInfo) == "function" then local spells = { [171] = 2259, [164] = 2018, [333] = 7411, [202] = 4036, [182] = 2366, [773] = 45357, [755] = 25229, [165] = 2108, [186] = 2575, [393] = 8613, [197] = 3908, [185] = 2550, [356] = 7620, [129] = 3273 } for id, spell in pairs(spells) do local localized = GetSpellInfo(spell) if type(localized) == "string" then localizedNames[localized] = id end end end for i = 1, GetNumSkillLines() do local name, isHeader, _, rank, _, _, maximum = GetSkillLineInfo(i) if not isHeader and type(name) == "string" then local id = professionByName[name] or localizedNames[name] if id and type(rank) == "number" then table.insert(list, {id = id, name = professionNames[id], skill = math.max(0, rank), maxSkill = math.max(1, tonumber(maximum) or 1)}) end end end return list end -- Classic talent APIs are absent on some Forever client builds. Never erase a -- previously good allocation when a client returns partial/unready talent data. local function ReadClassicTalents() if type(GetNumTalentTabs) ~= "function" or type(GetTalentTabInfo) ~= "function" or type(GetNumTalents) ~= "function" or type(GetTalentInfo) ~= "function" then return nil end local okCount, count = pcall(GetNumTalentTabs) if not okCount or count ~= 3 then return nil end local trees, spent = {}, 0 for tab = 1, count do local okInfo, first, second = pcall(GetTalentTabInfo, tab) if not okInfo then return nil end local treeName = type(first) == "string" and first or type(second) == "string" and second or ("Tree " .. tab) local okNum, numTalents = pcall(GetNumTalents, tab) if not okNum or type(numTalents) ~= "number" or numTalents < 1 or numTalents > 40 or numTalents % 1 ~= 0 then return nil end local talents, points = {}, 0 for index = 1, numTalents do local okTalent, name, icon, tier, column, rank, maximum = pcall(GetTalentInfo, tab, index) if not okTalent or type(name) ~= "string" or name == "" or type(tier) ~= "number" or tier < 1 or tier > 7 or tier % 1 ~= 0 or type(column) ~= "number" or column < 1 or column > 4 or column % 1 ~= 0 or type(rank) ~= "number" or rank < 0 or rank % 1 ~= 0 or type(maximum) ~= "number" or maximum < 1 or maximum > 5 or rank > maximum then return nil end local talent = {index = index, name = name, tier = tier, column = column, rank = rank, maxRank = maximum} if type(icon) == "number" and icon >= 0 and icon % 1 == 0 then talent.icon = icon end table.insert(talents, talent) points = points + rank end table.insert(trees, {index = tab, name = treeName, pointsSpent = points, talents = talents}) spent = spent + points end local snapshot = {schemaVersion = 1, capturedAt = time(), trees = trees} if type(GetUnspentTalentPoints) == "function" then local ok, remaining = pcall(GetUnspentTalentPoints) if ok and type(remaining) == "number" and remaining >= 0 and remaining <= 100 and remaining % 1 == 0 then snapshot.unspentPoints = remaining end end return snapshot end -- Forever 1.60.x has a single C_Traits tree laid out as three adjacent -- specialization panels. Its old GetNumTalentTabs globals are not installed. local modernTreeNames = { WARRIOR = {"Arms", "Fury", "Protection"}, PALADIN = {"Holy", "Protection", "Retribution"}, HUNTER = {"Beast Mastery", "Marksmanship", "Survival"}, ROGUE = {"Assassination", "Combat", "Subtlety"}, PRIEST = {"Discipline", "Holy", "Shadow"}, SHAMAN = {"Elemental", "Enhancement", "Restoration"}, MAGE = {"Arcane", "Fire", "Frost"}, WARLOCK = {"Affliction", "Demonology", "Destruction"}, DRUID = {"Balance", "Feral Combat", "Restoration"}, } local function ReadModernTalents() if type(C_ClassTalents) ~= "table" or type(C_ClassTalents.GetActiveConfigID) ~= "function" or type(C_Traits) ~= "table" or type(C_Traits.GetConfigInfo) ~= "function" or type(C_Traits.GetTreeNodes) ~= "function" or type(C_Traits.GetNodeInfo) ~= "function" or type(C_Traits.GetEntryInfo) ~= "function" or type(C_Traits.GetDefinitionInfo) ~= "function" then return nil end -- Never publish preview points before the player applies changes. local ok, result = pcall(function() local configID = C_ClassTalents.GetActiveConfigID() if not configID then return nil end if type(C_Traits.ConfigHasStagedChanges) == "function" and C_Traits.ConfigHasStagedChanges(configID) then return nil end local config = C_Traits.GetConfigInfo(configID) if not config or type(config.treeIDs) ~= "table" or #config.treeIDs ~= 1 then return nil end local nodes = C_Traits.GetTreeNodes(config.treeIDs[1]) if type(nodes) ~= "table" or #nodes < 3 or #nodes > 120 then return nil end local _, classID = UnitClass("player") local names = modernTreeNames[classID] if not names then return nil end local raw = {} for _, nodeID in ipairs(nodes) do local node = C_Traits.GetNodeInfo(configID, nodeID) if node and type(node.posX) == "number" and type(node.posY) == "number" and type(node.entryIDs) == "table" and #node.entryIDs > 0 then -- A non-spell node can be a gate or a subtree selector. local active = node.activeEntry local entryID = active and active.entryID or node.entryIDs[1] local entry = C_Traits.GetEntryInfo(configID, entryID) local definition = entry and entry.definitionID and C_Traits.GetDefinitionInfo(entry.definitionID) if definition and (definition.spellID or definition.overrideName) then local spell = definition.spellID and type(C_Spell) == "table" and type(C_Spell.GetSpellInfo) == "function" and C_Spell.GetSpellInfo(definition.spellID) local name = definition.overrideName or (spell and spell.name) if type(name) ~= "string" or name == "" then return nil end local rank = active and active.rank or 0 local maximum = node.maxRanks or entry.maxRanks if type(rank) ~= "number" or rank < 0 or rank % 1 ~= 0 or type(maximum) ~= "number" or maximum < 1 or maximum > 5 or rank > maximum then return nil end local icon = definition.overrideIcon or (spell and spell.iconID) table.insert(raw, {x = node.posX, y = node.posY, name = name, rank = rank, maxRank = maximum, icon = icon}) end end end if #raw < 3 then return nil end -- Three panels are laid out horizontally, not three separate config trees. -- Cluster x-coordinates; this avoids assuming a fixed client UI scale. local low, high = raw[1].x, raw[1].x for _, node in ipairs(raw) do low = math.min(low, node.x); high = math.max(high, node.x) end if low == high then return nil end local centers = {low, (low + high) / 2, high} for _ = 1, 12 do local sums, counts = {0, 0, 0}, {0, 0, 0} for _, node in ipairs(raw) do local group = 1 for i = 2, 3 do if math.abs(node.x - centers[i]) < math.abs(node.x - centers[group]) then group = i end end node.group = group sums[group], counts[group] = sums[group] + node.x, counts[group] + 1 end for i = 1, 3 do if counts[i] == 0 then return nil end centers[i] = sums[i] / counts[i] end end local trees, total = {}, 0 for i = 1, 3 do local members, xMin, xMax, yMin, yMax = {}, math.huge, -math.huge, math.huge, -math.huge for _, node in ipairs(raw) do if node.group == i then table.insert(members, node) xMin, xMax = math.min(xMin, node.x), math.max(xMax, node.x) yMin, yMax = math.min(yMin, node.y), math.max(yMax, node.y) end end if #members < 1 or #members > 40 then return nil end local talents, spent, positions = {}, 0, {} table.sort(members, function(a, b) return a.y == b.y and a.x < b.x or a.y < b.y end) for index, node in ipairs(members) do local col = xMax > xMin and math.floor((node.x - xMin) * 3 / (xMax - xMin) + 0.5) + 1 or 2 local tier = yMax > yMin and math.floor((node.y - yMin) * 6 / (yMax - yMin) + 0.5) + 1 or 1 local position = tier .. ":" .. col if positions[position] then return nil end positions[position] = true local talent = {index = index, name = node.name, tier = tier, column = col, rank = node.rank, maxRank = node.maxRank} if type(node.icon) == "number" and node.icon >= 0 and node.icon % 1 == 0 then talent.icon = node.icon end table.insert(talents, talent) spent = spent + node.rank end total = total + spent table.insert(trees, {index = i, name = names[i], pointsSpent = spent, talents = talents}) end if total > 100 then return nil end return {schemaVersion = 1, capturedAt = time(), trees = trees} end) return ok and result or nil end local function ReadTalents() return ReadModernTalents() or ReadClassicTalents() end local function GenerateExportPayload() local name = PlayerFullName() local realm = GetNormalizedRealmName() or GetRealmName() or "Forever" local _, class = UnitClass("player") local _, race = UnitRace("player") local key = GetCharacterKey() local currentData = (key and MaravillasForeverDB.characters[key]) or {} local level = SafeNumericRead(function() return UnitLevel("player") end, currentData.level or 1, 1, 100) local xp = SafeNumericRead(function() return UnitXP("player") end, currentData.xp or 0, 0, 4294967295) local xpMax = SafeNumericRead(function() return UnitXPMax("player") end, currentData.xpMax or 400, 0, 4294967295) local restedXP = SafeNumericRead(GetXPExhaustion, currentData.restedXP or 0, 0, 4294967295) local currentZone = GetRealZoneText() or GetZoneText() or currentData.currentZone or "Azeroth" local money = SafeNumericRead(GetMoney, currentData.money or 0, 0, 9007199254740991) local kills = SafeNumericRead(GetPVPLifetimeStats, currentData.kills or 0, 0, 4294967295) local deaths = currentData.deaths or 0 local payload = { version = 1, -- Export protocol version, not addon build. addonVersion = ADDON_VERSION, timestamp = time(), character = { name = name, realm = realm, class = class or "WARRIOR", race = race or "Orc", level = level, xp = xp, xpMax = xpMax, restedXP = restedXP, currentZone = currentZone, money = money, deaths = deaths, kills = kills, professions = currentData.professions or {}, talents = ReadTalents() or currentData.talents }, bounties = MaravillasForeverDB.bountiesClaimed, deaths = MaravillasForeverDB.deathLog, events = MaravillasForeverDB.eventLog, duels = MaravillasForeverDB.duelLog, relayCharacters = MaravillasForeverDB.relayCharacters or {} } local jsonStr = SerializeJSON(payload) local b64 = ToBase64(jsonStr) local crc = CalculateCRC32(b64) local exportString = "!MF:1:" .. b64 .. "#" .. crc MaravillasForeverDB.latestExportString = exportString MaravillasForeverDB.lastSync = time() -- Export generation time, not proof of upload. return exportString, payload end local function UpdateCharacterData(refreshTalents) local key = GetCharacterKey() if not key then return end local name = PlayerFullName() local _, class = UnitClass("player") local _, race = UnitRace("player") local currentData = MaravillasForeverDB.characters[key] or {} local level = SafeNumericRead(function() return UnitLevel("player") end, currentData.level or 1, 1, 100) local xp = SafeNumericRead(function() return UnitXP("player") end, currentData.xp or 0, 0, 4294967295) local xpMax = SafeNumericRead(function() return UnitXPMax("player") end, currentData.xpMax or 400, 0, 4294967295) local restedXP = SafeNumericRead(GetXPExhaustion, currentData.restedXP or 0, 0, 4294967295) local currentZone = GetRealZoneText() or GetZoneText() or currentData.currentZone or "Azeroth" local money = SafeNumericRead(GetMoney, currentData.money or 0, 0, 9007199254740991) local kills = SafeNumericRead(GetPVPLifetimeStats, currentData.kills or 0, 0, 4294967295) local deaths = currentData.deaths or 0 local currentProfessions = ReadProfessions() MaravillasForeverDB.characters[key] = { name = name, realm = GetNormalizedRealmName() or GetRealmName() or "Forever", class = class or "WARRIOR", race = race or "Orc", level = level, xp = xp, xpMax = xpMax, restedXP = restedXP, currentZone = currentZone, money = money, deaths = deaths, kills = kills, professions = currentProfessions or currentData.professions or {}, talents = (refreshTalents and ReadTalents()) or currentData.talents, lastUpdated = time() } -- Auto check bounties if level >= 20 and not MaravillasForeverDB.bountiesClaimed["first_to_20"] then MaravillasForeverDB.bountiesClaimed["first_to_20"] = { claimedBy = name, claimedByRealm = GetNormalizedRealmName() or GetRealmName() or "Forever", timestamp = time(), detail = "Reached Level 20 in " .. currentZone } end if level >= 40 and not MaravillasForeverDB.bountiesClaimed["first_to_40"] then MaravillasForeverDB.bountiesClaimed["first_to_40"] = { claimedBy = name, claimedByRealm = GetNormalizedRealmName() or GetRealmName() or "Forever", timestamp = time(), detail = "Reached Level 40 in " .. currentZone } end if level >= 60 and not MaravillasForeverDB.bountiesClaimed["first_to_60"] then MaravillasForeverDB.bountiesClaimed["first_to_60"] = { claimedBy = name, claimedByRealm = GetNormalizedRealmName() or GetRealmName() or "Forever", timestamp = time(), detail = "Achieved Max Level 60!" } end if money >= 1000000 and not MaravillasForeverDB.bountiesClaimed["first_100_gold"] then MaravillasForeverDB.bountiesClaimed["first_100_gold"] = { claimedBy = name, claimedByRealm = GetNormalizedRealmName() or GetRealmName() or "Forever", timestamp = time(), detail = "Accumulated 100 Gold!" } end -- Export only on demand; serializing the full history after every XP tick is expensive. end -- ========================================================================= -- COMBAT & DEATH TRACKING -- ========================================================================= local lastAttacker = "Defeated in battle" local lastAttackerAt = 0 local ATTACKER_MEMORY_SECONDS = 15 local function RememberAttacker(sourceName, spellName) if type(sourceName) ~= "string" or sourceName == "" or sourceName == "You" then return end local source = sourceName:sub(1, 70) local spell = type(spellName) == "string" and spellName:sub(1, 50) or nil lastAttacker = spell and spell ~= "" and spell ~= "Melee" and (source .. " (" .. spell .. ")") or source lastAttackerAt = GetTime and GetTime() or 0 end -- Forever can use the older chat-combat events. Match only messages addressed -- to the player, so damage to party members never claims our next death. local function TrackLegacyIncomingDamage(message) if type(message) ~= "string" then return end local source, spell = message:match("^(.+) ([^ ]+) damaged [Yy]ou") if not source then source, spell = message:match("^(.+) ([^ ]+) hit [Yy]ou") end if not source then source = message:match("^(.+) [Mm]elee hit [Yy]ou") end if not source then source, spell = message:match("^(.+)'s (.+) hits [Yy]ou") end if not source then source = message:match("^(.+) hits [Yy]ou") end if source then RememberAttacker(source, spell) end end -- A death transition should produce one event, even if the client repeats PLAYER_DEAD. -- Keep this session-only: SavedVariables and exported history remain unchanged. local deathRecordedUntilAlive = false local function ResetDeathLatchIfAlive() if not deathRecordedUntilAlive or type(UnitIsDeadOrGhost) ~= "function" then return end local ok, dead = pcall(UnitIsDeadOrGhost, "player") if ok and dead == false then deathRecordedUntilAlive = false end end local function OnPlayerDead() if deathRecordedUntilAlive then return end local key = GetCharacterKey() if not key then return end if not MaravillasForeverDB then InitDB() end if not MaravillasForeverDB.characters[key] then UpdateCharacterData() end local char = MaravillasForeverDB.characters[key] if not char then return end deathRecordedUntilAlive = true char.deaths = (char.deaths or 0) + 1 local zone = GetRealZoneText() or GetZoneText() or "Unknown Zone" local level = UnitLevel("player") local name = PlayerFullName() if lastAttackerAt == 0 or (GetTime and GetTime() - lastAttackerAt > ATTACKER_MEMORY_SECONDS) then -- Unknown cause is not proof of a falling or elevator incident. lastAttacker = "Unknown cause" end local death = RecordEvent("death", {level = level, killer = lastAttacker, zone = zone}) table.insert(MaravillasForeverDB.deathLog, { id = death.id, character = name, realm = death.realm, level = level, killer = lastAttacker, zone = zone, timestamp = death.timestamp }) local deathCause = lastAttacker lastAttacker = "Defeated in battle" lastAttackerAt = 0 if deathCause:find("Elevator") and not MaravillasForeverDB.bountiesClaimed["elevator_boss"] then MaravillasForeverDB.bountiesClaimed["elevator_boss"] = { claimedBy = name, claimedByRealm = GetNormalizedRealmName() or GetRealmName() or "Forever", timestamp = time(), detail = "Fell to the " .. deathCause .. " in " .. zone } end UpdateCharacterData() print("|cffff8000[MaravillasForever]|r Recorded death to " .. deathCause .. " at Lv " .. level .. ".") end -- Duel tracking: WoW does not provide a winner in DUEL_FINISHED. -- Accept only localized system winner lines when a duel is underway. local pendingDuel = nil local lastDuelResult = nil local function NameOnly(name) return tostring(name or ""):match("^[^-]+") or "" end -- Match game-localized %s / %1$s / %2$s placeholders without -- assuming winner and loser have a fixed capture order. local function TemplatePattern(template) if type(template) ~= "string" then return nil end local captures, pieces, cursor = {}, {}, 1 while cursor <= #template do local startIndex, endIndex, position = template:find("%%(%d+)%$s", cursor) if not startIndex then startIndex, endIndex = template:find("%s", cursor, true) position = nil end if not startIndex then break end local literal = template:sub(cursor, startIndex - 1) table.insert(pieces, (literal:gsub("([^%w])", "%%%1"))) table.insert(pieces, "(.+)") table.insert(captures, position and tonumber(position) or (#captures + 1)) cursor = endIndex + 1 end if #captures ~= 2 then return nil end table.insert(pieces, (template:sub(cursor):gsub("([^%w])", "%%%1"))) return "^" .. table.concat(pieces) .. "$", captures end local function DetectDuelResult(message) if not pendingDuel or not message then return end local templates = { "DUEL_WINNER_KNOCKOUT", "DUEL_WINNER_RETREAT" } for _, key in ipairs(templates) do local template = _G[key] local pattern, order = TemplatePattern(template) if pattern then local first, second = message:match(pattern) if first and second then local parts = {} parts[order[1]] = first parts[order[2]] = second local winner, loser = parts[1], parts[2] if not winner or not loser then return end winner, loser = NameOnly(winner), NameOnly(loser) local myself = PlayerFullName() if (winner == myself and loser == pendingDuel.name) or (loser == myself and winner == pendingDuel.name) then local signature = winner .. "|" .. loser .. "|" .. tostring(pendingDuel.started) if lastDuelResult ~= signature then lastDuelResult = signature local selfRealm = GetNormalizedRealmName() or GetRealmName() or "Forever" -- Only transmit the opponent's realm if the game supplied it -- in the duel request. Never guess that both players share one. local winnerRealm = winner == myself and selfRealm or pendingDuel.realm local loserRealm = loser == myself and selfRealm or pendingDuel.realm local event = RecordEvent("duel", { winner = winner, loser = loser, winnerRealm = winnerRealm, loserRealm = loserRealm, duelStartedAt = pendingDuel.started }) table.insert(MaravillasForeverDB.duelLog, { id = event.id, winner = winner, loser = loser, timestamp = event.timestamp }) print("|cffff8000[MaravillasForever]|r Duel: " .. winner .. " defeated " .. loser) end pendingDuel = nil return end end end end end local function TrackDuelRequest(opponent) local name = NameOnly(opponent) -- Realm suffixes are optional on the client's system messages. local realm = tostring(opponent or ""):match("^[^-]+%-(.+)$") if realm == "" then realm = nil end if name ~= "" then pendingDuel = {name = name, realm = realm, started = time()} end end -- Event dispatcher frame:RegisterEvent("ADDON_LOADED") frame:RegisterEvent("PLAYER_LOGIN") frame:RegisterEvent("PLAYER_ENTERING_WORLD") frame:RegisterEvent("PLAYER_LEVEL_UP") frame:RegisterEvent("PLAYER_XP_UPDATE") frame:RegisterEvent("ZONE_CHANGED_NEW_AREA") frame:RegisterEvent("ZONE_CHANGED") frame:RegisterEvent("PLAYER_DEAD") -- Forever clients do not necessarily expose these legacy combat channels. -- Never let an unavailable optional event abort addon initialization or /mf. local optionalCombatEvents = { "CHAT_MSG_COMBAT_CREATURE_VS_SELF_HITS", "CHAT_MSG_COMBAT_HOSTILEPLAYER_HITS", "CHAT_MSG_SPELL_CREATURE_VS_SELF_DAMAGE", "CHAT_MSG_SPELL_HOSTILEPLAYER_DAMAGE", "CHAT_MSG_SPELL_PERIODIC_SELF_DAMAGE", } local optionalCombatEventCount = 0 for _, optionalEvent in ipairs(optionalCombatEvents) do local ok = pcall(frame.RegisterEvent, frame, optionalEvent) if ok then optionalCombatEventCount = optionalCombatEventCount + 1 end end frame:RegisterEvent("PLAYER_REGEN_DISABLED") frame:RegisterEvent("PLAYER_REGEN_ENABLED") frame:RegisterEvent("GROUP_ROSTER_UPDATE") frame:RegisterEvent("UNIT_HEALTH") frame:RegisterEvent("UNIT_FLAGS") frame:RegisterEvent("PLAYER_ALIVE") frame:RegisterEvent("PLAYER_UNGHOST") frame:RegisterEvent("PLAYER_MONEY") frame:RegisterEvent("SKILL_LINES_CHANGED") frame:RegisterEvent("CHAT_MSG_SKILL") frame:RegisterEvent("CHAT_MSG_ADDON") frame:RegisterEvent("PLAYER_GUILD_UPDATE") frame:RegisterEvent("DUEL_REQUESTED") frame:RegisterEvent("DUEL_FINISHED") frame:RegisterEvent("CHAT_MSG_SYSTEM") -- Client flavors differ: optional talent events must never abort startup. for _, talentEvent in ipairs({"CHARACTER_POINTS_CHANGED", "PLAYER_TALENT_UPDATE"}) do pcall(frame.RegisterEvent, frame, talentEvent) end frame:SetScript("OnEvent", function(self, event, ...) if event == "ADDON_LOADED" then local addon = ... if addon == ADDON_NAME then InitDB() UpdateCharacterData(true) end elseif event == "PLAYER_LOGIN" or event == "PLAYER_ENTERING_WORLD" then InitDB() UpdateCharacterData(true) if C_Timer and C_Timer.After then C_Timer.After(2, function() UpdateCharacterData(true) end) C_Timer.After(10, function() UpdateCharacterData(true) end) end TrackInstanceVisit() StartSquadRelay() ResetDeathLatchIfAlive() print("|cffff8000[MaravillasForever]|r Ready. Use |cffffd100/mf|r for Overview, History, Activity and Export; |cffffd100/mf squad|r for relay status.") elseif event == "CHAT_MSG_ADDON" then OnSquadRelay(...) elseif event == "PLAYER_GUILD_UPDATE" then StartSquadRelay() elseif event == "DUEL_REQUESTED" then TrackDuelRequest(...) elseif event == "DUEL_FINISHED" then -- Delay clearing briefly because the localized victory line can arrive afterward. if C_Timer and C_Timer.After then local prior = pendingDuel C_Timer.After(5, function() if pendingDuel == prior then pendingDuel = nil end end) end elseif event == "CHAT_MSG_SYSTEM" then DetectDuelResult(...) elseif event == "PLAYER_LEVEL_UP" then local newLevel = ... RecordEvent("level_up", {level = newLevel, zone = GetRealZoneText() or GetZoneText() or "Azeroth"}) UpdateCharacterData(true) BroadcastSnapshot() print("|cffff8000[MaravillasForever]|r Triumphant! Level " .. newLevel .. " reached.") elseif event == "CHARACTER_POINTS_CHANGED" or event == "PLAYER_TALENT_UPDATE" then UpdateCharacterData(true) elseif event == "PLAYER_XP_UPDATE" or event == "ZONE_CHANGED_NEW_AREA" or event == "ZONE_CHANGED" or event == "PLAYER_MONEY" or event == "SKILL_LINES_CHANGED" or event == "CHAT_MSG_SKILL" then UpdateCharacterData() if event == "ZONE_CHANGED_NEW_AREA" or event == "ZONE_CHANGED" then TrackInstanceVisit() wipePull = nil end elseif event == "CHAT_MSG_COMBAT_CREATURE_VS_SELF_HITS" or event == "CHAT_MSG_COMBAT_HOSTILEPLAYER_HITS" or event == "CHAT_MSG_SPELL_CREATURE_VS_SELF_DAMAGE" or event == "CHAT_MSG_SPELL_HOSTILEPLAYER_DAMAGE" or event == "CHAT_MSG_SPELL_PERIODIC_SELF_DAMAGE" then TrackLegacyIncomingDamage(...) elseif event == "PLAYER_DEAD" then OnPlayerDead() CheckAutomaticWipe() elseif event == "PLAYER_REGEN_DISABLED" then OnWipePullStart() elseif event == "PLAYER_REGEN_ENABLED" then EndWipePullSoon() ShowPeerUpdateIfSafe() elseif event == "GROUP_ROSTER_UPDATE" then -- Never count a party that shrank or changed during a fight. if wipePull and not WipeGroupUnits() then wipePull = nil end CheckAutomaticWipe() elseif event == "UNIT_HEALTH" or event == "UNIT_FLAGS" or event == "PLAYER_ALIVE" or event == "PLAYER_UNGHOST" then if event == "PLAYER_ALIVE" or event == "PLAYER_UNGHOST" then ResetDeathLatchIfAlive() end CheckAutomaticWipe() end -- Keep visible stats current without rebuilding the full history on every -- combat/health callback. Hot XP and currency events refresh at most once/sec. if controlPanel and controlPanel:IsShown() and controlPanel.selectedTab ~= 4 and RefreshPanel and (event == "PLAYER_LEVEL_UP" or event == "PLAYER_XP_UPDATE" or event == "PLAYER_DEAD" or event == "PLAYER_MONEY" or event == "SKILL_LINES_CHANGED" or event == "CHAT_MSG_SKILL" or event == "ZONE_CHANGED" or event == "ZONE_CHANGED_NEW_AREA" or event == "CHAT_MSG_SYSTEM" or event == "PLAYER_ENTERING_WORLD" or event == "PLAYER_GUILD_UPDATE") then local now = GetTime and GetTime() or 0 if now >= nextPanelRefresh then nextPanelRefresh = now + 1 RefreshPanel() end end end) -- ========================================================================= -- IN-GAME MARAVILLASFOREVER CONTROL PANEL (/maravillasforever) -- ========================================================================= local function StatCounts() InitDB() local own, relayed = 0, 0 for _, event in ipairs(MaravillasForeverDB.eventLog) do if event.relayed then relayed = relayed + 1 else own = own + 1 end end local peers = 0 for _ in pairs(MaravillasForeverDB.relayCharacters or {}) do peers = peers + 1 end return own, relayed, peers end local function IntegritySummary() InitDB() local seen = {} local duplicates, localDeaths = 0, 0 for _, event in ipairs(MaravillasForeverDB.eventLog) do if event.id then if seen[event.id] then duplicates = duplicates + 1 end seen[event.id] = true end if event.type == "death" and not event.relayed then localDeaths = localDeaths + 1 end end local missing = 0 for _, death in ipairs(MaravillasForeverDB.deathLog) do if death.id and not seen[death.id] then missing = missing + 1 end end if duplicates > 0 or missing > 0 then return "|cffff7070CHECK HISTORY|r: " .. duplicates .. " repeated IDs, " .. missing .. " death entries without events" end return "|cff84dba4OK|r: " .. localDeaths .. " local death events, no duplicate IDs or missing death-event links" end local function AddLabel(parent, text, point, relative, relativePoint, x, y, color) local label = parent:CreateFontString(nil, "OVERLAY", "GameFontNormal") label:SetPoint(point, relative, relativePoint, x, y) label:SetJustifyH("LEFT") if color then label:SetTextColor(color[1], color[2], color[3]) end label:SetText(text) return label end local function MakeButton(parent, label, width, x, onClick) local button = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate") button:SetSize(width, 25) button:SetPoint("TOPLEFT", parent, "TOPLEFT", x, -63) button:SetText(label) button:SetScript("OnClick", onClick) return button end local function ActivitySummary(character) local lines = { "|cffffcc66INSTANCE ACTIVITY (YOUR CHARACTER)|r" } local name = character.name or PlayerFullName() local entered, exited, wipes, wins, losses = 0, 0, 0, 0, 0 for _, event in ipairs(MaravillasForeverDB.eventLog or {}) do if not event.relayed and event.character == name then if event.type == "instance_enter" then entered = entered + 1 elseif event.type == "instance_exit" then exited = exited + 1 elseif event.type == "instance_wipe" then wipes = wipes + 1 elseif event.type == "duel" then if event.winner == name then wins = wins + 1 end if event.loser == name then losses = losses + 1 end end end end table.insert(lines, "Entries: " .. entered .. " Exits: " .. exited .. " Wipe observations: " .. wipes) table.insert(lines, "|cffaaaaaaEntries are individual visits, not completed dungeon clears.|r") table.insert(lines, "|cffaaaaaaWipes are per-character observations, not unique guild wipes.|r") table.insert(lines, "") table.insert(lines, "|cffffcc66REPORTED DUELS|r") table.insert(lines, "Wins: " .. wins .. " Losses: " .. losses) table.insert(lines, "|cffaaaaaaResults count on the website only after both players confirm.|r") table.insert(lines, "") table.insert(lines, "|cffffcc66PROFESSIONS|r") local professions = {} for _, profession in ipairs(character.professions or {}) do if type(profession) == "table" and profession.name then table.insert(professions, profession) end end table.sort(professions, function(a, b) return tostring(a.name) < tostring(b.name) end) if #professions == 0 then table.insert(lines, "No profession skills recorded yet.") else for _, profession in ipairs(professions) do table.insert(lines, tostring(profession.name) .. ": " .. tostring(profession.skill or 0) .. " / " .. tostring(profession.maxSkill or "?")) end end table.insert(lines, "") table.insert(lines, "|cffaaaaaaIn-memory snapshot. Use /reload or logout to save to disk.|r") return table.concat(lines, "\n") end local function BuildPanel() if controlPanel then return end local panel = CreateFrame("Frame", "MaravillasForeverControlPanel", UIParent, "BackdropTemplate") panel:SetSize(570, 405) panel:SetPoint("CENTER") panel:SetFrameStrata("DIALOG") panel:SetClampedToScreen(true) panel:SetMovable(true) panel:EnableMouse(true) panel:RegisterForDrag("LeftButton") panel:SetScript("OnDragStart", panel.StartMoving) panel:SetScript("OnDragStop", panel.StopMovingOrSizing) panel:SetBackdrop({ bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background-Dark", edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border", tile = true, tileSize = 32, edgeSize = 24, insets = { left = 8, right = 8, top = 8, bottom = 8 } }) AddLabel(panel, "|cffef6faeMaravillasForever|r Guild Companion", "TOPLEFT", panel, "TOPLEFT", 22, -20) local status = AddLabel(panel, "", "TOPLEFT", panel, "TOPLEFT", 22, -101, { 0.76, 0.8, 0.88 }) panel.status = status local overview = CreateFrame("Frame", nil, panel) overview:SetPoint("TOPLEFT", panel, "TOPLEFT", 20, -125) overview:SetPoint("BOTTOMRIGHT", panel, "BOTTOMRIGHT", -20, 38) local stats = AddLabel(overview, "", "TOPLEFT", overview, "TOPLEFT", 5, -5) stats:SetWidth(505) stats:SetJustifyV("TOP") panel.stats = stats local refresh = CreateFrame("Button", nil, overview, "UIPanelButtonTemplate") refresh:SetSize(95, 24) refresh:SetPoint("BOTTOMLEFT", overview, "BOTTOMLEFT", 4, 3) refresh:SetText("Refresh") refresh:SetScript("OnClick", function() UpdateCharacterData() RefreshPanel() end) local relayToggle = CreateFrame("Button", nil, overview, "UIPanelButtonTemplate") relayToggle:SetSize(138, 24) relayToggle:SetPoint("LEFT", refresh, "RIGHT", 8, 0) relayToggle:SetScript("OnClick", function() MaravillasForeverDB.squadRelayEnabled = not MaravillasForeverDB.squadRelayEnabled if MaravillasForeverDB.squadRelayEnabled then StartSquadRelay() else relayQueue = {} end RefreshPanel() end) panel.relayToggle = relayToggle local history = CreateFrame("Frame", nil, panel) history:SetAllPoints(overview) local historyText = AddLabel(history, "", "TOPLEFT", history, "TOPLEFT", 5, -5) historyText:SetWidth(505) historyText:SetJustifyV("TOP") panel.historyText = historyText local activity = CreateFrame("Frame", nil, panel) activity:SetAllPoints(overview) local activityScroll = CreateFrame("ScrollFrame", nil, activity, "UIPanelScrollFrameTemplate") activityScroll:SetPoint("TOPLEFT", activity, "TOPLEFT", 5, -4) activityScroll:SetPoint("BOTTOMRIGHT", activity, "BOTTOMRIGHT", -25, 1) local activityContent = CreateFrame("Frame", nil, activityScroll) activityContent:SetSize(490, 230) activityScroll:SetScrollChild(activityContent) local activityText = AddLabel(activityContent, "", "TOPLEFT", activityContent, "TOPLEFT", 3, -3) activityText:SetWidth(465) activityText:SetJustifyV("TOP") panel.activityText = activityText panel.activityContent = activityContent local export = CreateFrame("Frame", nil, panel) export:SetAllPoints(overview) local description = AddLabel(export, "Manual fallback: select all, Ctrl+C, and paste into the website.", "TOPLEFT", export, "TOPLEFT", 5, -3) description:SetWidth(510) local scroll = CreateFrame("ScrollFrame", "MaravillasForeverExportScroll", export, "UIPanelScrollFrameTemplate") scroll:SetPoint("TOPLEFT", export, "TOPLEFT", 5, -27) scroll:SetPoint("BOTTOMRIGHT", export, "BOTTOMRIGHT", -25, 34) local edit = CreateFrame("EditBox", "MaravillasForeverExportEditBox", scroll) edit:SetMultiLine(true) edit:SetFontObject(ChatFontNormal) edit:SetAutoFocus(false) edit:SetWidth(475) edit:SetScript("OnEscapePressed", function() panel:Hide() end) scroll:SetScrollChild(edit) panel.exportEdit = edit local selectAll = CreateFrame("Button", nil, export, "UIPanelButtonTemplate") selectAll:SetSize(110, 24) selectAll:SetPoint("BOTTOMLEFT", export, "BOTTOMLEFT", 5, 3) selectAll:SetText("Select All") selectAll:SetScript("OnClick", function() edit:SetFocus() edit:HighlightText() end) local tabs = { { "Overview", overview }, { "History", history }, { "Activity", activity }, { "Export", export } } local function ShowTab(selected) for index, pair in ipairs(tabs) do if index == selected then pair[2]:Show() else pair[2]:Hide() end end panel.selectedTab = selected RefreshPanel() if selected == 4 then edit:SetFocus() edit:HighlightText() end end for index, pair in ipairs(tabs) do MakeButton(panel, pair[1], 110, 20 + (index - 1) * 116, function() ShowTab(index) end) end local close = CreateFrame("Button", nil, panel, "UIPanelButtonTemplate") close:SetSize(90, 25) close:SetPoint("BOTTOMRIGHT", panel, "BOTTOMRIGHT", -20, 12) close:SetText("Close") close:SetScript("OnClick", function() panel:Hide() end) panel.overview = overview panel.history = history panel.activity = activity panel.exportTab = export panel.ShowTab = ShowTab controlPanel = panel panel:Hide() end RefreshPanel = function() if not controlPanel then return end InitDB() local key = GetCharacterKey() local character = (key and MaravillasForeverDB.characters[key]) or {} local own, relayed, peers = StatCounts() local lastSaved = tonumber(MaravillasForeverDB.lastSync) or 0 local guildStatus = RelayActive() and "Enabled (guild available)" or "Disabled / no guild connection" local recentPeers = 0 for _, lastSeen in pairs(MaravillasForeverDB.relayPeers or {}) do if time() - lastSeen <= 300 then recentPeers = recentPeers + 1 end end controlPanel.status:SetText("|cff96e0b7Squad Relay|r: " .. guildStatus .. " |cffccccccRecent peers:|r " .. recentPeers) controlPanel.relayToggle:SetText(MaravillasForeverDB.squadRelayEnabled and "Disable Squad Relay" or "Enable Squad Relay") local gold = math.floor((tonumber(character.money) or 0) / 10000) local xp = tonumber(character.xp) or 0 local xpMax = tonumber(character.xpMax) or 0 controlPanel.stats:SetText( "|cffffcc66YOUR CHARACTER|r\n" .. (character.name or "Not initialized") .. " | " .. (character.class or "?") .. " | Lv " .. tostring(character.level or "?") .. "\n" .. "XP: " .. xp .. " / " .. xpMax .. " Rested: " .. tostring(character.restedXP or 0) .. "\n" .. "Zone: " .. (character.currentZone or "Unknown") .. " Gold: " .. gold .. "g\n" .. "Deaths: " .. tostring(character.deaths or 0) .. " PvP kills: " .. tostring(character.kills or 0) .. "\n\n" .. "|cffffcc66SAVED RECORDS|r\n" .. "Local events: " .. own .. " Relayed events: " .. relayed .. "\n" .. "Death history rows: " .. #MaravillasForeverDB.deathLog .. " Cached teammates: " .. peers .. "\n" .. "Integrity: " .. IntegritySummary() .. "\n" .. "Last in-memory export: " .. (lastSaved > 0 and date("%Y-%m-%d %H:%M", lastSaved) or "Not yet") .. "\n\n" .. "|cffaaaaaaData reaches the website when WoW saves SavedVariables\n" .. "on /reload or logout. This screen shows in-memory data.|r" ) local lines = { "|cffffcc66RECENT EVENTS (local and relayed)|r" } local log = MaravillasForeverDB.eventLog or {} if #log == 0 then table.insert(lines, "No recorded events yet.") end for i = #log, math.max(1, #log - 9), -1 do local event = log[i] if event then local source = event.relayed and "[Squad] " or "[You] " local what if event.type == "duel" then what = tostring(event.winner or "?") .. " defeated " .. tostring(event.loser or "?") .. " in a duel" elseif event.type == "death" then what = "died to " .. tostring(event.killer or "unknown") elseif event.type == "level_up" then what = "reached level " .. tostring(event.level or "?") elseif event.type == "instance_enter" then what = "entered " .. tostring(event.instanceName or "an instance") elseif event.type == "instance_exit" then what = "left " .. tostring(event.instanceName or "an instance") elseif event.type == "instance_wipe" then what = "observed a group wipe in " .. tostring(event.instanceName or "an instance") else what = "recorded " .. tostring(event.type or "an event") end table.insert(lines, source .. tostring(event.character or "?") .. " " .. what) end end table.insert(lines, "") table.insert(lines, "|cffaaaaaaEvent IDs are kept for deduplication after each import.|r") controlPanel.historyText:SetText(table.concat(lines, "\n")) if controlPanel.selectedTab == 3 then controlPanel.activityText:SetText(ActivitySummary(character)) controlPanel.activityContent:SetHeight(math.max(230, controlPanel.activityText:GetStringHeight() + 22)) end if controlPanel.selectedTab == 4 then local exportString = GenerateExportPayload() controlPanel.exportEdit:SetText(exportString) end end local function ShowExportWindow(tab) InitDB() UpdateCharacterData() BuildPanel() controlPanel:Show() controlPanel.ShowTab(tab or 1) end SLASH_MARAVILLASFOREVER1 = "/maravillasforever" SLASH_MARAVILLASFOREVER2 = "/mf" SlashCmdList["MARAVILLASFOREVER"] = function(msg) local command = (msg or ""):lower():match("^%s*(.-)%s*$") if command == "relay on" then InitDB() MaravillasForeverDB.relayEnabled = true print("|cffff8000[MaravillasForever]|r Guild announcements enabled.") elseif command == "relay off" then InitDB() MaravillasForeverDB.relayEnabled = false print("|cffff8000[MaravillasForever]|r Guild announcements disabled.") elseif command == "squad" then InitDB() local _, _, peers = StatCounts() print("|cffff8000[MaravillasForever]|r Squad Relay: " .. (MaravillasForeverDB.squadRelayEnabled and "on" or "off") .. "; cached teammate snapshots: " .. peers) elseif command == "squad on" then InitDB() MaravillasForeverDB.squadRelayEnabled = true StartSquadRelay() print("|cffff8000[MaravillasForever]|r Squad Relay enabled.") elseif command == "squad off" then InitDB() MaravillasForeverDB.squadRelayEnabled = false relayQueue = {} print("|cffff8000[MaravillasForever]|r Squad Relay disabled.") elseif command == "duels" then InitDB() print("|cffff8000[MaravillasForever]|r Recorded duel results: " .. #MaravillasForeverDB.duelLog .. ". Open /maravillasforever history to review recent wins.") elseif command == "version" then print("|cffff8000[MaravillasForever]|r Installed: " .. ADDON_VERSION .. ". Official releases: forever.pondere.moe/releases") if newestPeerVersion then print("|cffff8000[MaravillasForever]|r Guild peer reported: " .. newestPeerVersion .. " (unverified).") else print("|cffff8000[MaravillasForever]|r No newer guild peer version observed this session.") end elseif command == "status" then InitDB() local key = GetCharacterKey() print("|cffff8000[MaravillasForever]|r Addon " .. ADDON_VERSION .. " | Character key: " .. tostring(key or "unavailable")) print("|cffff8000[MaravillasForever]|r Supported incoming combat channels: " .. optionalCombatEventCount .. "/" .. #optionalCombatEvents) if type(UnitGUID) == "function" then local ok, guid = pcall(UnitGUID, "player") if ok and type(guid) == "string" then -- Diagnostic only: never rewrite name/realm keys or infer an old owner's identity. local homeRealmId = guid:match("^Player%-(%d+)%-") print("|cffff8000[MaravillasForever]|r Player GUID: " .. guid .. " | GUID realm ID: " .. tostring(homeRealmId or "unknown")) else print("|cffff8000[MaravillasForever]|r Player GUID unavailable on this client.") end end local own, relayed, peers = StatCounts() print("|cffff8000[MaravillasForever]|r Events: " .. own .. " local, " .. relayed .. " unverified relay | Observed peers: " .. peers) print("|cffff8000[MaravillasForever]|r " .. IntegritySummary()) print("|cffff8000[MaravillasForever]|r Squad Relay: " .. (MaravillasForeverDB.squadRelayEnabled and "on" or "off") .. " | Guild announcements: " .. (MaravillasForeverDB.relayEnabled and "on" or "off")) print("|cffff8000[MaravillasForever]|r Sync: use /reload or logout to save; importing that file on the website is separate. Last export: " .. (MaravillasForeverDB.lastSync and MaravillasForeverDB.lastSync > 0 and date("%Y-%m-%d %H:%M", MaravillasForeverDB.lastSync) or "never")) else ShowExportWindow(command == "export" and 4 or command == "history" and 2 or command == "activity" and 3 or 1) end end