diff --git a/Beasts.lua b/Beasts.lua new file mode 100644 index 0000000..7bc2645 --- /dev/null +++ b/Beasts.lua @@ -0,0 +1,1339 @@ +-- Freewood-OctoWoW-Beasts: Archiv wilder Tiere +-- Lernt beim Spielen (anvisieren, Wildtierkunde, Zaehmen), kennt optional Startdaten +-- aus Freewood-OctoWoW-BeastsData und teilt eigene Funde per Export/Import. +-- +-- Eigene Eintraege (db.beasts[npcID]): +-- name, fid (Familien-ID), family (Text aus dem Spiel), lvl1, lvl2, c (Klassifizierung), +-- zone, tameable, diet (Kuerzel mfcbur), seen, lored, tamed, tamedAt, firstSeen, updated, +-- grid = { [Karte] = { [Zellen-Nr] = Anzahl } } (Raster 200 x 200, Zelle = 0,5 % der Karte), +-- petAbilities = { {name, rank, spellID, passive} }, +-- extra = { "Zeile aus Wildtierkunde" } +-- Importierte Eintraege liegen getrennt in db.imported[npcID] und ueberschreiben nie eigene Daten. + +local ADDON, NS = ... + +local FW = _G.Freewood +if not FW or not FW:RequireAPI(1, ADDON) then + return +end + +local Util = FW.Util +local L = FW.L +local Pet = FW.Pet +if not Pet then + return +end + +local GRID = 200 -- Raster: 200 x 200 Zellen pro Karte (Zelle = 0,5 %) +local MAX_CELLS = 800 -- hoechstens so viele verschiedene Zellen pro Tier +local MAX_EXTRA = 8 +local MAX_PETABIL = 60 +local MAX_IMPORT = 500 +local STAY_INTERVAL = 10 -- Sekunden: in derselben Zelle erst danach erneut zaehlen +local LORE_INTERVAL = 4 -- Sekunden zwischen zwei Tooltip-Auslesungen pro Tier + +local DIET_ORDER = "mfcbur" + +local FOOD_ALIASES = { + m = { "fleisch", "meat" }, + f = { "fisch", "fish" }, + c = { "käse", "kaese", "cheese" }, + b = { "brot", "bread" }, + u = { "fungus", "pilz", "pilze", "mushroom" }, + r = { "obst", "frucht", "früchte", "fruit" }, +} +local FOOD_BY_NAME = {} +for code, names in pairs(FOOD_ALIASES) do + for _, n in ipairs(names) do + FOOD_BY_NAME[n] = code + end +end + +local function GetMeta(field) + local fn = (C_AddOns and C_AddOns.GetAddOnMetadata) or GetAddOnMetadata + if fn then + local ok, value = pcall(fn, ADDON, field) + if ok then + return value + end + end + return nil +end + +local Beasts = FW:NewModule("Beasts", { + version = GetMeta("Version") or "dev", + title = L.BEAST_TITLE, + description = L.BEAST_DESC, + defaults = { + beasts = {}, imported = {}, relay = {}, familyNames = {}, + settings = { seed = true, mapPower = 1.0, share = { guild = false, party = false, raid = false, global = false }, people = {} }, + sync = { have = {}, sent = 0, received = 0 }, + }, +}) +NS.Beasts = Beasts +FW.Beasts = Beasts + +local function Now() + return (GetTime and GetTime()) or time() +end + +local function Num(v, lo, hi) + if type(v) == "number" and v == v and v ~= math.huge and v ~= -math.huge then + if lo and v < lo then + return nil + end + if hi and v > hi then + return nil + end + return v + end + return nil +end + +local function Str(v, max) + if type(v) ~= "string" then + return nil + end + v = v:gsub("[%c]", " ") + if v == "" then + return nil + end + return v:sub(1, max or 64) +end + +------------------------------------------------------------------------ +-- Nahrung +------------------------------------------------------------------------ + +-- Liste von Texten ("Fleisch", "Fisch") in Kuerzel ("mf"), Reihenfolge fest +function Beasts.FoodsToCodes(list) + local have = {} + for _, text in ipairs(list or {}) do + if type(text) == "string" then + local code = FOOD_BY_NAME[string.lower((text:gsub("^%s+", ""):gsub("%s+$", "")))] + if code then + have[code] = true + end + end + end + local out = {} + for i = 1, #DIET_ORDER do + local c = DIET_ORDER:sub(i, i) + if have[c] then + out[#out + 1] = c + end + end + return table.concat(out) +end + +local function CleanDiet(v) + if type(v) ~= "string" then + return nil + end + local out = {} + for i = 1, #DIET_ORDER do + local c = DIET_ORDER:sub(i, i) + if v:find(c, 1, true) then + out[#out + 1] = c + end + end + if #out == 0 then + return nil + end + return table.concat(out) +end + +------------------------------------------------------------------------ +-- Startdaten +------------------------------------------------------------------------ + +function Beasts:SeedNpcs() + local seed = _G.FreewoodBeastsSeed + return seed and seed.npcs or nil +end + +function Beasts:HasSeed() + return self:SeedNpcs() ~= nil +end + +function Beasts:SeedEnabled() + return self.db.settings.seed ~= false and self:HasSeed() +end + +function Beasts:SeedEntry(id) + if not self:SeedEnabled() then + return nil + end + return self:SeedNpcs()[id] +end + +function Beasts:SetSeedEnabled(on) + self.db.settings.seed = on and true or false + self.index = nil + FW:Fire("BEASTS_UPDATED") +end + +------------------------------------------------------------------------ +-- Karten- und Gebietsnamen +------------------------------------------------------------------------ + +local mapNames, areaNames = {}, {} + +function Beasts.MapName(mapID) + if not mapID then + return nil + end + local cached = mapNames[mapID] + if cached ~= nil then + return cached or nil + end + local name + if C_Map and C_Map.GetMapInfo then + local ok, info = pcall(C_Map.GetMapInfo, mapID) + if ok and info then + name = info.name + end + end + mapNames[mapID] = name or false + return name +end + +function Beasts.AreaName(areaID) + if not areaID then + return nil + end + local cached = areaNames[areaID] + if cached ~= nil then + return cached or nil + end + local name + if C_Map and C_Map.GetAreaInfo then + local ok, value = pcall(C_Map.GetAreaInfo, areaID) + if ok then + name = value + end + end + areaNames[areaID] = name or false + return name +end + +------------------------------------------------------------------------ +-- Eigene Eintraege +------------------------------------------------------------------------ + +Beasts.GRID = GRID + +local function CellIndex(x, y) + local cx = math.min(GRID - 1, math.max(0, math.floor(x * GRID))) + local cy = math.min(GRID - 1, math.max(0, math.floor(y * GRID))) + return cy * GRID + cx +end + +local function GridCount(grid) + local n = 0 + if type(grid) == "table" then + for _, cells in pairs(grid) do + for _ in pairs(cells) do + n = n + 1 + end + end + end + return n +end + +-- Eine Sichtung in die Zelle eintragen. Rueckgabe: true wenn die Zelle neu ist. +local function AddSighting(e, m, idx, amount) + e.grid = e.grid or {} + local cells = e.grid[m] + if not cells then + cells = {} + e.grid[m] = cells + end + local n = cells[idx] + if n then + cells[idx] = math.min(65535, n + (amount or 1)) + return false + end + if GridCount(e.grid) >= MAX_CELLS then + return false + end + cells[idx] = math.min(65535, amount or 1) + return true +end + +-- Raster als Liste { {m, x, y, n} } (x,y = Zellen 0..199), haeufigste zuerst +local function FlattenGrid(grid) + local list = {} + for m, cells in pairs(grid or {}) do + for idx, n in pairs(cells) do + list[#list + 1] = { m = m, x = idx % GRID, y = math.floor(idx / GRID), n = n } + end + end + table.sort(list, function(a, b) + if a.n ~= b.n then + return a.n > b.n + end + if a.m ~= b.m then + return a.m < b.m + end + if a.y ~= b.y then + return a.y < b.y + end + return a.x < b.x + end) + while #list > MAX_CELLS do + list[#list] = nil + end + return list +end + +function Beasts:Touch(id) + local e = self.db.beasts[id] + if not e then + e = { firstSeen = time(), updated = time() } + self.db.beasts[id] = e + self.isNew = true + end + return e +end + +-- Kurze Pruefsumme der wichtigen Felder: nur bei Aenderung wird neu gezeichnet und "updated" gesetzt +local function Signature(e) + local abil = 0 + for _, a in ipairs(e.petAbilities or {}) do + abil = abil + (a.rank or 0) + 1 + end + return table.concat({ + tostring(e.name), tostring(e.fid), tostring(e.family), tostring(e.lvl1), tostring(e.lvl2), tostring(e.c), + tostring(e.zone), tostring(e.seen), tostring(e.lored), tostring(e.tameable), tostring(e.tamed), + tostring(e.diet), GridCount(e.grid), e.extra and #e.extra or 0, abil, + }, "|") +end + +function Beasts:Commit(id, e, before) + if Signature(e) ~= before then + e.updated = time() + self.index = nil + FW:Fire("BEASTS_UPDATED", id) + return true + end + return false +end + +local function PlayerPoint() + local loc = Util.GetPlayerLocation() + if loc and loc.mapID and loc.x and loc.y then + return loc.mapID, loc.x, loc.y, loc.zone + end + return nil, nil, nil, loc and loc.zone +end + +local function CleanLine(text) + text = text:gsub("|c%x%x%x%x%x%x%x%x", ""):gsub("|r", ""):gsub("|T.-|t", "") + return (text:gsub("^%s+", ""):gsub("%s+$", "")) +end + +-- Liest den Tooltip einer Einheit. Rueckgabe: nil oder +-- { tameable=bool, diet="mf"|nil, extra={...} } (nur wenn Wildtierkunde-Zeilen da sind) +function Beasts:ReadLore(unit, name) + if not (C_TooltipInfo and C_TooltipInfo.GetUnit) then + return nil + end + local ok, data = pcall(C_TooltipInfo.GetUnit, unit) + if not ok or type(data) ~= "table" or type(data.lines) ~= "table" then + return nil + end + local info = { extra = {} } + local found = false + local level = UnitLevel and Util.Clean(UnitLevel(unit)) + if type(level) ~= "number" then + level = nil + end + local typeLow = UnitCreatureType and Util.Clean(UnitCreatureType(unit)) + typeLow = type(typeLow) == "string" and string.lower(typeLow) or nil + for i, line in ipairs(data.lines) do + local text = type(line) == "table" and Util.Clean(line.leftText) + if type(text) == "string" and i > 1 then + text = CleanLine(text) + local low = string.lower(text) + if text == "" or text == name then + -- nichts + elseif low == "wildtier" or low == "beast" or (typeLow and low == typeLow) then + -- Typzeile + elseif low == "zähmbar" or low == "zaehmbar" or low == "tameable" then + info.tameable = true + found = true + elseif low:find("^ernährung:") or low:find("^ernaehrung:") or low:find("^diet:") then + local rest = text:match(":%s*(.+)$") or "" + local foods = {} + for part in rest:gmatch("[^,]+") do + foods[#foods + 1] = part + end + local codes = Beasts.FoodsToCodes(foods) + if codes ~= "" then + info.diet = codes + end + found = true + elseif low:find("^spezialisierung:") or low:find("^specialization:") then + found = true + elseif low:find("^stufe") or low:find("^level") or (level and level > 0 and low:find(tostring(level), 1, true) and low:find("%d")) then + -- Stufenzeile + elseif #info.extra < MAX_EXTRA then + info.extra[#info.extra + 1] = text:sub(1, 120) + end + end + end + if not found then + return nil + end + return info +end + +local function AddExtra(e, lines) + if not lines or #lines == 0 then + return + end + e.extra = e.extra or {} + for _, line in ipairs(lines) do + local dup = false + for _, have in ipairs(e.extra) do + if have == line then + dup = true + break + end + end + if not dup and #e.extra < MAX_EXTRA then + e.extra[#e.extra + 1] = line + end + end +end + +-- Einheit beobachten und ins Archiv uebernehmen +-- Rueckgabe: true, wenn die Einheit ein Wildtier fuers Archiv ist +-- Geheime Werte (secret values) fuehren zum Abbruch ohne Fehlermeldung. +function Beasts:Observe(unit) + local ok, result = pcall(self.ObserveImpl, self, unit) + if ok then + return result and true or false + end + return false +end + +function Beasts:ObserveImpl(unit) + if Util.IsSecret(unit) or not UnitExists(unit) then + return false + end + local isPlayer, controlled = UnitIsPlayer(unit), UnitPlayerControlled(unit) + if Util.IsSecret(isPlayer) or Util.IsSecret(controlled) or isPlayer or controlled then + return false + end + local guid = Util.Clean(UnitGUID(unit)) + if type(guid) ~= "string" then + return false + end + -- Octo/1.12: GUID ist ein Hex-String (0xF130...), nicht "Creature-..." + local hexKind = Util.ParseHexGUID(guid) + if hexKind then + if hexKind ~= "Creature" then + return false + end + elseif not guid:find("^Creature") then + return false + end + local id = Util.GetNpcID(guid) + if not id then + return false + end + + local family = UnitCreatureFamily and Util.Clean(UnitCreatureFamily(unit)) + if family == "" then + family = nil + end + local known = self.db.beasts[id] ~= nil + local inSeed = self:SeedNpcs() and self:SeedNpcs()[id] ~= nil + local name = Util.Clean(UnitName(unit)) + + local lore + local now = Now() + local last = self.loreAt[id] + if (family or known or inSeed) and (not last or now - last >= LORE_INTERVAL) then + self.loreAt[id] = now + lore = self:ReadLore(unit, name) + end + + if not (family or inSeed or known or lore) then + return false + end + + local e = self:Touch(id) + local wasNew = self.isNew + self.isNew = nil + local before = wasNew and "" or Signature(e) + + e.name = Str(name, 64) or e.name + e.seen = true + e.lastSeen = time() + if family then + e.family = Str(family, 48) + local fid = Pet.GetFamilyID(family) + if fid then + e.fid = fid + self.db.familyNames[fid] = e.family + end + end + local lvl = UnitLevel and Util.Clean(UnitLevel(unit)) + if type(lvl) == "number" and lvl > 0 then + e.lvl1 = (e.lvl1 and math.min(e.lvl1, lvl)) or lvl + e.lvl2 = (e.lvl2 and math.max(e.lvl2, lvl)) or lvl + end + local class = UnitClassification and Util.Clean(UnitClassification(unit)) + if type(class) == "string" and class ~= "normal" and class ~= "trivial" and class ~= "minus" then + e.c = class + end + + local m, x, y, zone = PlayerPoint() + if zone and zone ~= "" then + e.zone = Str(zone, 64) + end + if m and x and y then + local idx = CellIndex(x, y) + local key = m * GRID * GRID + idx + local lastAt = self.trackAt[id] + if self.lastCell[id] ~= key or not lastAt or now - lastAt >= STAY_INTERVAL then + self.lastCell[id] = key + self.trackAt[id] = now + AddSighting(e, m, idx) + end + end + + if lore then + e.lored = true + if lore.tameable then + e.tameable = true + end + if lore.diet then + e.diet = lore.diet + end + AddExtra(e, lore.extra) + end + + if self:Commit(id, e, before) and wasNew then + FW:Debug(string.format(FW.L.BEAST_LEARNED, e.name or tostring(id))) + end + return true +end + +-- Solange ein Wildtier im Ziel ist, jede Sekunde die Position festhalten +function Beasts:StartTracking() + if self.tracking then + return + end + self.tracking = true + local function tick() + if not Beasts:IsEnabled() or not UnitExists("target") or not Beasts:Observe("target") then + Beasts.tracking = false + return + end + C_Timer.After(1, tick) + end + C_Timer.After(1, tick) +end + +-- Begleiter wurde erfasst: das Tier gilt als gezaehmt, Zauberbuch wird mitgenommen +function Beasts:OnPetUpdated(key, rec) + if type(rec) ~= "table" or rec.src == "import" or not rec.npcID or key ~= Pet.activeKey then + return + end + local e = self:Touch(rec.npcID) + local before = self.isNew and "" or Signature(e) + self.isNew = nil + e.tamed = true + e.tameable = true + e.tamedAt = e.tamedAt or time() + if type(rec.family) == "string" and rec.family ~= "" then + e.family = Str(rec.family, 48) + local fid = Pet.GetFamilyID(rec.family) + if fid then + e.fid = fid + self.db.familyNames[fid] = e.family + end + end + if type(rec.foods) == "table" and #rec.foods > 0 then + local codes = Beasts.FoodsToCodes(rec.foods) + if codes ~= "" then + e.diet = codes + end + end + local list = {} + for _, a in ipairs(rec.abilities or {}) do + if #list >= MAX_PETABIL then + break + end + if type(a) == "table" and type(a.name) == "string" then + list[#list + 1] = { name = a.name, rank = a.rank, spellID = a.spellID, passive = a.passive and true or nil } + end + end + if #list > 0 then + e.petAbilities = list + end + self:Commit(rec.npcID, e, before) +end + +------------------------------------------------------------------------ +-- Zusammengefuehrte Sicht (eigen, Import, Startdaten) +------------------------------------------------------------------------ + +function Beasts.StatusOf(own, imp) + local tamed = (own and own.tamed) or (imp and imp.tamed) + local lored = (own and own.lored) or (imp and imp.lored) + if tamed then + return "tamed" + elseif lored then + return "lored" + elseif own or imp then + return "seen" + end + return "unknown" +end + +local function SeedZone(seed) + if not seed then + return nil + end + return Beasts.MapName(seed.m) or Beasts.AreaName(seed.a) +end + +function Beasts:FamilyText(fid, fallback) + if not fid then + return fallback + end + return self.db.familyNames[fid] or Pet.FamilyDisplay(fid) +end + +function Beasts:Summary(id) + local own, imp, seed = self.db.beasts[id], self.db.imported[id], self:SeedEntry(id) + local fid = (own and own.fid) or (imp and imp.fid) or (seed and seed.f ~= "" and seed.f) or nil + local familyText = (own and own.family) or (imp and imp.family) + local s = { + id = id, + own = own, imp = imp, seed = seed, + name = (own and own.name) or (imp and imp.name) or (seed and seed.n) or string.format(FW.L.BEAST_UNNAMED, id), + fid = fid, + status = Beasts.StatusOf(own, imp), + zone = (own and own.zone) or (imp and imp.zone) or SeedZone(seed), + lvl1 = (own and own.lvl1) or (imp and imp.lvl1) or (seed and seed.l and seed.l[1]), + lvl2 = (own and own.lvl2) or (imp and imp.lvl2) or (seed and seed.l and seed.l[2]), + c = (own and own.c) or (imp and imp.c) or (seed and seed.c), + diet = (own and own.diet) or (imp and imp.diet) or (seed and seed.d ~= "" and seed.d) or nil, + tameable = (own and own.tameable) or (imp and imp.tameable) or (seed and true) or nil, + } + s.family = (own and own.family) or self:FamilyText(fid, familyText) + s.sortName = string.lower(s.name) + return s +end + +-- Alle Eintraege als Liste (ohne Filter), nach Namen sortiert +function Beasts:Index() + if self.index then + return self.index + end + local ids = {} + for id in pairs(self.db.beasts) do + ids[id] = true + end + for id in pairs(self.db.imported) do + ids[id] = true + end + local seed = self:SeedEnabled() and self:SeedNpcs() + if seed then + for id in pairs(seed) do + ids[id] = true + end + end + local list = {} + for id in pairs(ids) do + list[#list + 1] = self:Summary(id) + end + table.sort(list, function(a, b) + if a.sortName ~= b.sortName then + return a.sortName < b.sortName + end + return a.id < b.id + end) + self.index = list + return list +end + +-- Filter: { text, fid, zone, status } +-- Name und Rang (Zahl) eines Zaubers aus den Spieldaten; nil, wenn noch nicht bekannt +function Beasts.SpellInfo(spellID) + local name, rank + if C_Spell and C_Spell.GetSpellInfo then + local ok, info = pcall(C_Spell.GetSpellInfo, spellID) + if ok and type(info) == "table" then + name = info.name + end + end + if C_Spell and C_Spell.GetSpellSubtext then + local ok, text = pcall(C_Spell.GetSpellSubtext, spellID) + if ok and type(text) == "string" then + rank = tonumber(string.match(text, "(%d+)")) + end + end + return name, rank or 0 +end + +-- Faehigkeiten, die ein Tier beim Zaehmen lehrt (Startdaten) bzw. die sein Begleiter hat: +-- { [name] = { [rang] = true } } plus Hoechstrang; im Eintrag zwischengespeichert, sobald alle Namen bekannt sind +function Beasts:Abilities(s) + if s.abil then + return s.abil + end + local map, complete = {}, true + local function add(name, rank) + local e = map[name] + if not e then + e = { ranks = {}, max = 0 } + map[name] = e + end + e.ranks[rank] = true + if rank > e.max then + e.max = rank + end + end + if s.seed and s.seed.t then + for _, spellID in ipairs(s.seed.t) do + local name, rank = Beasts.SpellInfo(spellID) + if name then + add(name, rank) + else + complete = false + end + end + end + local pa = (s.own and s.own.petAbilities) or (s.imp and s.imp.petAbilities) + for _, a in ipairs(pa or {}) do + if a.name then + add(a.name, tonumber(a.rank) or 0) + end + end + if complete then + s.abil = map + end + return map +end + +-- filter: text, fid, zone, status, ability (Name), rank (Zahl), rankMin (true = "ab diesem Rang") +-- Zweiter Rueckgabewert: Zahl der Tiere ohne Faehigkeitsdaten (nur bei Faehigkeitsfilter) +function Beasts:Filtered(filter) + local out = {} + local missing = 0 + local text = filter.text and filter.text ~= "" and string.lower(filter.text) or nil + for _, s in ipairs(self:Index()) do + local ok = true + if filter.fid and s.fid ~= filter.fid then + ok = false + elseif filter.zone and s.zone ~= filter.zone then + ok = false + elseif filter.status and s.status ~= filter.status then + ok = false + elseif text then + local hay = s.sortName .. " " .. string.lower(s.family or "") .. " " .. string.lower(s.zone or "") + if not hay:find(text, 1, true) then + ok = false + end + end + if ok and filter.ability then + local abil = self:Abilities(s) + if not next(abil) then + missing = missing + 1 + ok = false + else + local e = abil[filter.ability] + if not e then + ok = false + elseif filter.rank then + if filter.rankMin then + ok = e.max >= filter.rank + else + ok = e.ranks[filter.rank] == true + end + end + end + end + if ok then + out[#out + 1] = s + end + end + return out, missing +end + +-- Alle Faehigkeiten (Namen, sortiert) und die Raenge einer Faehigkeit +function Beasts:AbilityChoices() + local names, seen = {}, {} + for _, s in ipairs(self:Index()) do + for name in pairs(self:Abilities(s)) do + if not seen[name] then + seen[name] = true + names[#names + 1] = name + end + end + end + table.sort(names) + return names +end + +function Beasts:AbilityRanks(name) + local ranks, seen = {}, {} + for _, s in ipairs(self:Index()) do + local e = self:Abilities(s)[name] + if e then + for r in pairs(e.ranks) do + if r > 0 and not seen[r] then + seen[r] = true + ranks[#ranks + 1] = r + end + end + end + end + table.sort(ranks) + return ranks +end + +-- Familien und Gebiete, die im Index vorkommen (fuer die Auswahllisten) +function Beasts:FilterChoices() + local fams, zones, famSeen, zoneSeen = {}, {}, {}, {} + for _, s in ipairs(self:Index()) do + if s.fid and not famSeen[s.fid] then + famSeen[s.fid] = true + fams[#fams + 1] = { id = s.fid, text = self:FamilyText(s.fid) } + end + if s.zone and not zoneSeen[s.zone] then + zoneSeen[s.zone] = true + zones[#zones + 1] = s.zone + end + end + table.sort(fams, function(a, b) + return a.text < b.text + end) + table.sort(zones) + return fams, zones +end + +-- Fundorte gruppiert nach Karte: { {mapID, name, own={ {x,y,n} }, imp={...}, seed={ {x,y} }} } +-- x,y in Zehntel-Prozent (0..1000) +function Beasts:Locations(s) + local groups, order = {}, {} + local function group(m) + local g = groups[m] + if not g then + g = { mapID = m, name = Beasts.MapName(m) or ("Map " .. tostring(m)), own = {}, imp = {}, seed = {} } + groups[m] = g + order[#order + 1] = g + end + return g + end + local function addGrid(entry, key) + for m, cells in pairs(entry and entry.grid or {}) do + local g = group(m) + for idx, n in pairs(cells) do + g[key][#g[key] + 1] = { (idx % GRID) * 5 + 2.5, math.floor(idx / GRID) * 5 + 2.5, n } + end + table.sort(g[key], function(a, b) + if a[3] ~= b[3] then + return a[3] > b[3] + end + if a[2] ~= b[2] then + return a[2] < b[2] + end + return a[1] < b[1] + end) + end + end + addGrid(s.own, "own") + addGrid(s.imp, "imp") + if s.seed and s.seed.m and s.seed.p then + local g = group(s.seed.m) + for i = 1, #s.seed.p - 1, 2 do + g.seed[#g.seed + 1] = { s.seed.p[i], s.seed.p[i + 1] } + end + end + table.sort(order, function(a, b) + local ca = #a.own + #a.imp + #a.seed + local cb = #b.own + #b.imp + #b.seed + if ca ~= cb then + return ca > cb + end + return a.name < b.name + end) + return order +end + +-- Gewichte pro Rasterzelle fuer eine Karte, ueber mehrere Tiere (ids = { [npcID] = true }) +-- Rueckgabe: { [Zellen-Nr] = Gewicht } +function Beasts:MapWeights(ids, mapID) + local weights = {} + local function add(idx, w) + weights[idx] = (weights[idx] or 0) + w + end + for id in pairs(ids) do + local own, imp, seed = self.db.beasts[id], self.db.imported[id], self:SeedEntry(id) + local oc = own and own.grid and own.grid[mapID] + if oc then + for idx, n in pairs(oc) do + add(idx, 2 + math.min(n, 8) * 0.25) + end + end + local ic = imp and imp.grid and imp.grid[mapID] + if ic then + for idx, n in pairs(ic) do + add(idx, 1.5 + math.min(n, 8) * 0.15) + end + end + if seed and seed.m == mapID and seed.p then + for i = 1, #seed.p - 1, 2 do + local cx = math.min(GRID - 1, math.floor(seed.p[i] / 1000 * GRID)) + local cy = math.min(GRID - 1, math.floor(seed.p[i + 1] / 1000 * GRID)) + add(cy * GRID + cx, 1) + end + end + end + return weights +end + +-- Punkte fuer die Codex-Karte (wie "Auf Karte zeigen" in der Datenbank): +-- { {m, x, y, n, name, k}, ... } mit x, y als Anteil 0..1; ids = { [npcID] = true } +local MAP_POINTS_MAX = 3000 +function Beasts:MapPoints(ids) + local pts = {} + for id in pairs(ids) do + local sum = self:Summary(id) + local name = (sum and sum.name) or ("#" .. tostring(id)) + local function addGrid(entry) + for m, cells in pairs(entry and entry.grid or {}) do + for idx, n in pairs(cells) do + pts[#pts + 1] = { m = m, x = ((idx % GRID) + 0.5) / GRID, + y = (math.floor(idx / GRID) + 0.5) / GRID, n = n, name = name, k = "u" } + end + end + end + addGrid(self.db.beasts[id]) + addGrid(self.db.imported[id]) + local seed = self:SeedEntry(id) + if seed and seed.m and seed.p then + for i = 1, #seed.p - 1, 2 do + pts[#pts + 1] = { m = seed.m, x = seed.p[i] / 1000, y = seed.p[i + 1] / 1000, n = 1, name = name, k = "u" } + end + end + end + if #pts > MAP_POINTS_MAX then + table.sort(pts, function(a, b) return a.n > b.n end) + for i = #pts, MAP_POINTS_MAX + 1, -1 do + pts[i] = nil + end + end + return pts +end + +-- Tiere mit Funden in der Naehe einer Kartenzelle: { {id, own, imp, seed}, ... }, meiste Funde zuerst +function Beasts:BeastsAt(ids, mapID, cx, cy, radius) + local out = {} + local function near(idx) + local x = idx % GRID + local y = math.floor(idx / GRID) + return math.abs(x - cx) <= radius and math.abs(y - cy) <= radius + end + for id in pairs(ids) do + local own, imp, seed = self.db.beasts[id], self.db.imported[id], self:SeedEntry(id) + local h = { id = id, own = 0, imp = 0, seed = 0 } + local oc = own and own.grid and own.grid[mapID] + if oc then + for idx, n in pairs(oc) do + if near(idx) then h.own = h.own + n end + end + end + local ic = imp and imp.grid and imp.grid[mapID] + if ic then + for idx, n in pairs(ic) do + if near(idx) then h.imp = h.imp + n end + end + end + if seed and seed.m == mapID and seed.p then + for i = 1, #seed.p - 1, 2 do + local x = math.min(GRID - 1, math.floor(seed.p[i] / 1000 * GRID)) + local y = math.min(GRID - 1, math.floor(seed.p[i + 1] / 1000 * GRID)) + if math.abs(x - cx) <= radius and math.abs(y - cy) <= radius then h.seed = h.seed + 1 end + end + end + if h.own + h.imp + h.seed > 0 then + h.total = h.own * 3 + h.imp * 2 + h.seed + out[#out + 1] = h + end + end + table.sort(out, function(a, b) + if a.total ~= b.total then return a.total > b.total end + return a.id < b.id + end) + return out +end + +------------------------------------------------------------------------ +-- Ereignisse +------------------------------------------------------------------------ + +function Beasts:OnTargetChanged() + if self:Observe("target") then + self:StartTracking() + end +end + +function Beasts:OnMouseover() + self:Observe("mouseover") +end + +function Beasts:OnTargetAura(unit) + if unit ~= "target" then + return + end + -- Wildtierkunde zeigt sich als Aura: kurz warten, dann Tooltip erneut lesen + if self.auraTimer then + return + end + self.auraTimer = true + C_Timer.After(0.4, function() + Beasts.auraTimer = nil + local guid = Util.Clean(UnitGUID("target")) + local id = type(guid) == "string" and Util.GetNpcID(guid) or nil + if id then + Beasts.loreAt[id] = nil + end + Beasts:Observe("target") + end) +end + +-- Alte Eintraege (Punktlisten) ins Raster uebertragen, Typzeile aus den Hinweisen entfernen +local function MigrateEntry(e) + if type(e) ~= "table" then + return + end + if type(e.locs) == "table" then + for _, p in ipairs(e.locs) do + if type(p) == "table" and type(p.m) == "number" and type(p.x) == "number" and type(p.y) == "number" then + AddSighting(e, p.m, CellIndex(p.x / 1000, p.y / 1000)) + end + end + e.locs = nil + end + if type(e.extra) == "table" then + local keep = {} + for _, line in ipairs(e.extra) do + local low = type(line) == "string" and string.lower(line) or "" + if low ~= "wildtier" and low ~= "beast" and low ~= "" then + keep[#keep + 1] = line + end + end + e.extra = #keep > 0 and keep or nil + end +end + +-- Alte Eintraege umwandeln. Laeuft bei OnEnable, denn OnInitialize wuerde bei schon +-- bereitem Core noch vor der Definition dieser Funktionen aufgerufen. +function Beasts:Migrate() + for _, e in pairs(self.db.beasts) do + MigrateEntry(e) + end + for _, e in pairs(self.db.imported) do + MigrateEntry(e) + end + self.index = nil +end + +function Beasts:OnEnable() + self.loreAt = self.loreAt or {} + self.trackAt = self.trackAt or {} + self.lastCell = self.lastCell or {} + self:Migrate() + FW:RegisterEvent("PLAYER_TARGET_CHANGED", self.OnTargetChanged, self) + FW:RegisterEvent("UPDATE_MOUSEOVER_UNIT", self.OnMouseover, self) + FW:RegisterEvent("UNIT_AURA", self.OnTargetAura, self) + FW:On("PET_UPDATED", self.OnPetUpdated, self) + if self.Sync then + self.Sync:Start() + end +end + +function Beasts:OnDisable() + if self.Sync then + self.Sync:Stop() + end + FW:UnregisterEvent("PLAYER_TARGET_CHANGED", self) + FW:UnregisterEvent("UPDATE_MOUSEOVER_UNIT", self) + FW:UnregisterEvent("UNIT_AURA", self) + FW:Off("PET_UPDATED", self) +end + +------------------------------------------------------------------------ +-- Export / Import +-- Geteilt werden nur eigene Funde, nichts Persoenliches. +------------------------------------------------------------------------ + +local function SanitizeList(src, max, fn) + local list = {} + if type(src) ~= "table" then + return list + end + for _, v in ipairs(src) do + if #list >= max then + break + end + local clean = fn(v) + if clean ~= nil then + list[#list + 1] = clean + end + end + return list +end + +local function Sanitize(src) + if type(src) ~= "table" then + return nil + end + local id = Num(src.id, 1, 10000000) + if not id then + return nil + end + local r = { + id = math.floor(id), + name = Str(src.name, 64), + fid = Str(src.fid, 24), + family = Str(src.family, 48), + lvl1 = Num(src.lvl1, 1, 120), + lvl2 = Num(src.lvl2, 1, 120), + c = Str(src.c, 16), + zone = Str(src.zone, 64), + tameable = (src.tameable == true) or nil, + diet = CleanDiet(src.diet), + seen = (src.seen == true) or nil, + lored = (src.lored == true) or nil, + tamed = (src.tamed == true) or nil, + updated = Num(src.updated, 1, 4102444800) or time(), + } + -- Raster: flache Liste cells { {m,x,y,n} } (neu) oder Punkte locs (alt, Zehntel-Prozent) + local grid, total = {}, 0 + local function put(m, cx, cy, n) + if total >= MAX_CELLS then + return + end + local cells = grid[m] + if not cells then + cells = {} + grid[m] = cells + end + local idx = cy * GRID + cx + if not cells[idx] then + total = total + 1 + end + cells[idx] = math.max(cells[idx] or 0, n) + end + if type(src.cells) == "table" then + for _, p in ipairs(src.cells) do + if type(p) == "table" then + local m, x, y, n = Num(p.m, 1, 100000), Num(p.x, 0, GRID - 1), Num(p.y, 0, GRID - 1), Num(p.n, 1, 65535) + if m and x and y and n then + put(m, math.floor(x), math.floor(y), math.floor(n)) + end + end + end + end + if type(src.locs) == "table" then + for _, p in ipairs(src.locs) do + if type(p) == "table" then + local m, x, y = Num(p.m, 1, 100000), Num(p.x, 0, 1000), Num(p.y, 0, 1000) + if m and x and y then + put(m, math.min(GRID - 1, math.floor(x / 1000 * GRID)), math.min(GRID - 1, math.floor(y / 1000 * GRID)), 1) + end + end + end + end + r.grid = total > 0 and grid or nil + r.petAbilities = SanitizeList(src.petAbilities, MAX_PETABIL, function(a) + if type(a) ~= "table" then + return nil + end + local n = Str(a.name, 64) + if not n then + return nil + end + return { name = n, rank = Num(a.rank, 0, 20), spellID = Num(a.spellID, 1, 10000000), passive = (a.passive == true) or nil } + end) + r.extra = SanitizeList(src.extra, MAX_EXTRA, function(v) + return Str(v, 120) + end) + if #r.petAbilities == 0 then r.petAbilities = nil end + if #r.extra == 0 then r.extra = nil end + return r +end + +function Beasts:ExportData() + local list = {} + for id, e in pairs(self.db.beasts) do + local copy = {} + for k, v in pairs(e) do + copy[k] = v + end + copy.id = id + copy.cells = FlattenGrid(e.grid) + local clean = Sanitize(copy) + if clean then + -- Ausgabe als flache Liste statt verschachtelter Tabelle + clean.cells = FlattenGrid(clean.grid) + clean.grid = nil + if #clean.cells == 0 then + clean.cells = nil + end + list[#list + 1] = clean + end + end + table.sort(list, function(a, b) + return a.id < b.id + end) + if #list == 0 then + return {} + end + return { list = list } +end + +-- Was geteilt werden darf: der eigene Eintrag, sonst ein ueber das Brett erhaltener (db.relay) aus der Ebene "importiert" +function Beasts:ShareEntry(id) + local e = self.db.beasts[id] + if e then return e end + local relay = self.db.relay + if relay and relay[id] then return self.db.imported[id] end + return nil +end + +-- Ids aller teilbaren Eintraege: eigene Funde und ueber das Brett erhaltene +function Beasts:ShareIds() + local out = {} + for id, e in pairs(self.db.beasts) do + if type(id) == "number" and (e.seen or e.lored or e.tamed) then out[id] = e end + end + for id in pairs(self.db.relay or {}) do + local e = self.db.imported[id] + if type(id) == "number" and e and not out[id] then out[id] = e end + end + return out +end + +-- Eigener Eintrag als bereinigter Datensatz zum Teilen (flache Zellenliste), nil wenn leer +function Beasts:ShareRecord(id) + local e = self:ShareEntry(id) + if not e then + return nil + end + local copy = {} + for k, v in pairs(e) do + copy[k] = v + end + copy.id = id + copy.cells = FlattenGrid(e.grid) + local clean = Sanitize(copy) + if not clean then + return nil + end + clean.cells = FlattenGrid(clean.grid) + clean.grid = nil + if #clean.cells == 0 then + clean.cells = nil + end + return clean +end + +-- Zahl der eigenen teilbaren Eintraege und ihr Pruefwert (Reihenfolge egal) +function Beasts:ShareSummary() + local n, h = 0, 0 + for id, e in pairs(self:ShareIds()) do + n = n + 1 + h = (h + id * 131 + ((e.updated or 0) % 1000003)) % 2147483647 + end + return n, h +end + +function Beasts:ValidateImport(data) + if type(data) ~= "table" or type(data.list) ~= "table" or #data.list == 0 then + return false, L.BEAST_IMPORT_EMPTY + end + if #data.list > MAX_IMPORT then + return false, L.BEAST_IMPORT_TOO_MANY + end + return true +end + +function Beasts:ImportData(data, opts) + opts = opts or {} + local added, updated, skipped = 0, 0, 0 + for _, item in ipairs(data.list) do + local clean = Sanitize(item) + if not clean then + skipped = skipped + 1 + else + local id = clean.id + clean.id = nil + local old = self.db.imported[id] + if old and not opts.merge and (old.updated or 0) >= clean.updated then + skipped = skipped + 1 + else + if old then + -- Fundorte beider Staende zusammenfuehren, Merkmale vereinen + local merged = { grid = {} } + for _, source in ipairs({ old.grid or {}, clean.grid or {} }) do + for m, cells in pairs(source) do + for idx, n in pairs(cells) do + local have = merged.grid[m] and merged.grid[m][idx] + if have then + merged.grid[m][idx] = math.max(have, n) + else + AddSighting(merged, m, idx, n) + end + end + end + end + clean.grid = GridCount(merged.grid) > 0 and merged.grid or nil + clean.seen = clean.seen or old.seen + clean.lored = clean.lored or old.lored + clean.tamed = clean.tamed or old.tamed + clean.tameable = clean.tameable or old.tameable + clean.updated = math.max(old.updated or 0, clean.updated) + if not clean.petAbilities then clean.petAbilities = old.petAbilities end + if not clean.extra then clean.extra = old.extra end + updated = updated + 1 + else + added = added + 1 + end + clean.importedAt = time() + self.db.imported[id] = clean + if clean.fid and clean.family then + self.db.familyNames[clean.fid] = self.db.familyNames[clean.fid] or clean.family + end + end + end + end + self.index = nil + FW:Fire("BEASTS_UPDATED") + return string.format(FW.L.BEAST_IMPORT_STATS, added, updated, skipped) +end + +FW.Export.RegisterHandler("beasts", { + label = function() + return FW.L.BEAST_EXPORT_LABEL + end, + export = function() + return Beasts:ExportData() + end, + validate = function(data) + return Beasts:ValidateImport(data) + end, + import = function(data) + return Beasts:ImportData(data) + end, +}) diff --git a/BeastsUI.lua b/BeastsUI.lua new file mode 100644 index 0000000..145d0af --- /dev/null +++ b/BeastsUI.lua @@ -0,0 +1,1122 @@ +-- Freewood-OctoWoW-Beasts: Tab "Wildtiere" +-- Links Suche, Filter und Liste, rechts Familienfaktoren, Nahrung, Fundorte und Faehigkeiten. + +local ADDON, NS = ... + +local FW = _G.Freewood +local Beasts = NS.Beasts +if not FW or not Beasts then + return +end + +local UI = FW.UI +local Pet = FW.Pet + +local LIST_W = 300 +local ROW_H, ROW_GAP = 50, 6 +local CARD_W, CARD_H, CARD_GAP = 170, 48, 10 +local ITEM_H = 24 + +local FAMILY_ICON = { + bat = "Ability_Hunter_Pet_Bat", bear = "Ability_Hunter_Pet_Bear", boar = "Ability_Hunter_Pet_Boar", + carrionbird = "Ability_Hunter_Pet_Vulture", cat = "Ability_Hunter_Pet_Cat", crab = "Ability_Hunter_Pet_Crab", + crocolisk = "Ability_Hunter_Pet_Crocolisk", gorilla = "Ability_Hunter_Pet_Gorilla", + hyena = "Ability_Hunter_Pet_Hyena", owl = "Ability_Hunter_Pet_Owl", raptor = "Ability_Hunter_Pet_Raptor", + scorpid = "Ability_Hunter_Pet_Scorpid", spider = "Ability_Hunter_Pet_Spider", + tallstrider = "Ability_Hunter_Pet_TallStrider", turtle = "Ability_Hunter_Pet_Turtle", + windserpent = "Ability_Hunter_Pet_WindSerpent", wolf = "Ability_Hunter_Pet_Wolf", +} + +local function FamilyIcon(fid) + return "Interface\\Icons\\" .. (FAMILY_ICON[fid] or "Ability_Hunter_BeastTaming") +end + +local STATUS_COLOR = { tamed = "success", lored = "goldLight", seen = "text", unknown = "textDim" } + +local function StatusText(status) + local L = FW.L + if status == "tamed" then return L.BEAST_STATUS_TAMED end + if status == "lored" then return L.BEAST_STATUS_LORED end + if status == "seen" then return L.BEAST_STATUS_SEEN end + return L.BEAST_STATUS_UNKNOWN +end + +local function LevelText(s) + local L = FW.L + if not s.lvl1 then + return nil + end + local range = (s.lvl2 and s.lvl2 ~= s.lvl1) and (s.lvl1 .. "-" .. s.lvl2) or tostring(s.lvl1) + local text = string.format(L.BEAST_LEVEL, range) + if s.c == "elite" then + text = text .. " " .. L.BEAST_ELITE + elseif s.c == "rare" then + text = text .. " " .. L.BEAST_RARE + elseif s.c == "rareelite" then + text = text .. " " .. L.BEAST_RAREELITE + elseif s.c == "worldboss" then + text = text .. " " .. L.BEAST_BOSS + elseif type(s.c) == "string" and s.c ~= "" then + local key = string.lower(s.c) + if key == "rare" then text = text .. " " .. L.BEAST_RARE end + end + return text +end + +local function Subtitle(s) + local parts = { s.family or FW.L.BEAST_FAMILY_UNKNOWN } + local lvl = LevelText(s) + if lvl then + parts[#parts + 1] = lvl + end + if s.zone then + parts[#parts + 1] = s.zone + end + return table.concat(parts, " - ") +end + +local function FoodList(codes) + local out = {} + if type(codes) == "string" then + for i = 1, #codes do + local c = codes:sub(i, i) + out[#out + 1] = FW.L["BEAST_FOOD_" .. c] or c + end + end + return out +end + +local function SpellName(spellID) + if C_Spell and C_Spell.GetSpellInfo then + local ok, info = pcall(C_Spell.GetSpellInfo, spellID) + if ok and type(info) == "table" and info.name then + return info.name + end + end + return "Spell " .. tostring(spellID) +end + +local function SpellRank(spellID) + if C_Spell and C_Spell.GetSpellSubtext then + local ok, text = pcall(C_Spell.GetSpellSubtext, spellID) + if ok and type(text) == "string" and text ~= "" then + return text + end + end + return nil +end + +------------------------------------------------------------------------ +-- Auswahlliste (Dropdown) +------------------------------------------------------------------------ + +local popup + +local function ClosePopup() + if popup then + popup:Hide() + popup.owner = nil + end +end + +local function GetPopup() + if popup then + return popup + end + popup = UI.CreatePanel(UIParent, "bgDeep", "gold") + popup:SetFrameStrata("FULLSCREEN_DIALOG") + popup:SetClampedToScreen(true) + popup:EnableMouse(true) + popup.scroll = UI.CreateScrollFrame(popup) + popup.scroll:SetPoint("TOPLEFT", popup, "TOPLEFT", 3, -3) + popup.scroll:SetPoint("BOTTOMRIGHT", popup, "BOTTOMRIGHT", -3, 3) + popup.items = {} + popup:Hide() + return popup +end + +local function OpenPopup(anchor, options, currentKey, onPick) + local p = GetPopup() + if p:IsShown() and p.owner == anchor then + ClosePopup() + return + end + p.owner = anchor + for i, opt in ipairs(options) do + local item = p.items[i] + if not item then + item = CreateFrame("Button", nil, p.scroll.child) + item:SetHeight(ITEM_H) + item.bg = item:CreateTexture(nil, "BACKGROUND") + item.bg:SetAllPoints() + item.label = UI.CreateLabel(item, "", { size = 12 }) + item.label:SetPoint("LEFT", item, "LEFT", 8, 0) + item.label:SetPoint("RIGHT", item, "RIGHT", -8, 0) + item.label:SetWordWrap(false) + item:SetScript("OnEnter", function(self) + self.bg:SetColorTexture(UI.Color("hover")) + end) + item:SetScript("OnLeave", function(self) + self.bg:SetColorTexture(UI.Color(self.active and "card" or "bgDeep")) + end) + item:SetScript("OnClick", function(self) + local cb = p.onPick + ClosePopup() + if cb then + cb(self.key) + end + end) + p.items[i] = item + end + item.key = opt.key + item.active = (opt.key == currentKey) + item.bg:SetColorTexture(UI.Color(item.active and "card" or "bgDeep")) + item.label:SetText(opt.text) + item.label:SetTextColor(UI.Color(item.active and "goldLight" or "text")) + item:ClearAllPoints() + item:SetPoint("TOPLEFT", p.scroll.child, "TOPLEFT", 0, -(i - 1) * ITEM_H) + item:SetPoint("TOPRIGHT", p.scroll.child, "TOPRIGHT", 0, -(i - 1) * ITEM_H) + item:Show() + end + for i = #options + 1, #p.items do + p.items[i]:Hide() + end + p.onPick = onPick + p.scroll:SetContentHeight(#options * ITEM_H) + p.scroll:ScrollToTop() + + p:SetScale((anchor:GetEffectiveScale() or 1) / (UIParent:GetEffectiveScale() or 1)) + p:SetSize(math.max(anchor:GetWidth() or 150, 190), math.min(#options * ITEM_H + 6, 270)) + p:ClearAllPoints() + p:SetPoint("TOPLEFT", anchor, "BOTTOMLEFT", 0, -2) + p:Show() +end + +local function CreateSelect(parent, width, getOptions, getKey, onPick) + local button + button = UI.CreateButton(parent, "", width, 24, function() + OpenPopup(button, getOptions(), getKey(), function(key) + onPick(key) + end) + end, "default") + button.label:ClearAllPoints() + button.label:SetPoint("LEFT", button, "LEFT", 8, 0) + button.label:SetPoint("RIGHT", button, "RIGHT", -8, 0) + button.label:SetJustifyH("LEFT") + button.label:SetWordWrap(false) + return button +end + +------------------------------------------------------------------------ +-- Suchfeld +------------------------------------------------------------------------ + +local function CreateSearchBox(parent, width, placeholder, onChange) + local box = UI.CreatePanel(parent, "bgDeep", "bronze") + box:SetSize(width, 26) + local edit = CreateFrame("EditBox", nil, box) + edit:SetAutoFocus(false) + edit:SetPoint("TOPLEFT", box, "TOPLEFT", 8, -2) + edit:SetPoint("BOTTOMRIGHT", box, "BOTTOMRIGHT", -8, 2) + edit:SetMaxLetters(48) + if not edit:SetFont(UI.GetFontPath("body"), 12, "") then + edit:SetFont("Fonts\\FRIZQT__.TTF", 12, "") + end + edit:SetTextColor(UI.Color("text")) + local hint = UI.CreateLabel(box, placeholder, { size = 12, color = "textDim" }) + hint:SetPoint("LEFT", box, "LEFT", 10, 0) + local function Sync() + if (edit:GetText() or "") == "" then + hint:Show() + else + hint:Hide() + end + end + edit:SetScript("OnTextChanged", function() + Sync() + onChange(edit:GetText() or "") + end) + edit:SetScript("OnEscapePressed", function(self) + self:ClearFocus() + end) + edit:SetScript("OnEditFocusGained", function() + UI.SetBorderColor(box, "gold") + end) + edit:SetScript("OnEditFocusLost", function() + UI.SetBorderColor(box, "bronze") + end) + box.edit = edit + Sync() + return box +end + +------------------------------------------------------------------------ +-- Listenzeile +------------------------------------------------------------------------ + +local function CreateListRow(parent, onSelect) + local row = CreateFrame("Button", nil, parent) + row:SetHeight(ROW_H) + + row.bg = row:CreateTexture(nil, "BACKGROUND") + row.bg:SetAllPoints() + UI.AddBorder(row, "bronze", 0.6) + + row.icon = row:CreateTexture(nil, "ARTWORK") + row.icon:SetSize(34, 34) + row.icon:SetPoint("LEFT", row, "LEFT", 8, 0) + row.icon:SetTexCoord(0.08, 0.92, 0.08, 0.92) + + row.name = UI.CreateLabel(row, "", { font = "heading", size = 13, color = "goldLight" }) + row.name:SetPoint("TOPLEFT", row, "TOPLEFT", 52, -10) + row.name:SetWidth(LIST_W - 150) + row.name:SetWordWrap(false) + + row.sub = UI.CreateLabel(row, "", { size = 11, color = "textDim" }) + row.sub:SetPoint("TOPLEFT", row.name, "BOTTOMLEFT", 0, -6) + row.sub:SetWidth(LIST_W - 76) + row.sub:SetWordWrap(false) + + row.chip = UI.CreateChip(row, "", "textDim") + row.chip:SetPoint("TOPRIGHT", row, "TOPRIGHT", -10, -9) + + local function Refresh() + if row.selected then + row.bg:SetColorTexture(UI.Color("hover")) + UI.SetBorderColor(row, "gold") + elseif row.hover then + row.bg:SetColorTexture(UI.Color("hover", 0.7)) + UI.SetBorderColor(row, "bronze") + else + row.bg:SetColorTexture(UI.Color("card")) + UI.SetBorderColor(row, "bronze", 0.6) + end + end + function row:SetSelected(selected) + self.selected = selected + Refresh() + end + row:SetScript("OnEnter", function() + row.hover = true + Refresh() + end) + row:SetScript("OnLeave", function() + row.hover = false + Refresh() + end) + row:SetScript("OnClick", function() + onSelect(row.id) + end) + Refresh() + return row +end + +------------------------------------------------------------------------ +-- Stapel im Detailbereich (wiederverwendete Bausteine) +------------------------------------------------------------------------ + +local function NewStack(scroll) + local s = { child = scroll.child, y = 0, pool = { label = {}, row = {}, chip = {} }, used = { label = 0, row = 0, chip = 0 } } + + local function take(kind, create) + s.used[kind] = s.used[kind] + 1 + local item = s.pool[kind][s.used[kind]] + if not item then + item = create() + s.pool[kind][s.used[kind]] = item + end + item:Show() + return item + end + + function s:Reset() + for kind, list in pairs(self.pool) do + for _, item in ipairs(list) do + item:Hide() + end + self.used[kind] = 0 + end + self.y = 0 + end + + function s:Gap(h) + self.y = self.y + h + end + + function s:Heading(text) + local fs = take("label", function() + return UI.CreateLabel(self.child, "", { size = 12 }) + end) + UI.SetFont(fs, "heading", 14) + fs:SetTextColor(UI.Color("goldLight")) + fs:SetWordWrap(false) + fs:ClearAllPoints() + fs:SetPoint("TOPLEFT", self.child, "TOPLEFT", 0, -self.y) + fs:SetPoint("TOPRIGHT", self.child, "TOPRIGHT", 0, -self.y) + fs:SetHeight(20) + fs:SetText(text) + self.y = self.y + 24 + end + + function s:Text(text, colorKey) + local fs = take("label", function() + return UI.CreateLabel(self.child, "", { size = 12 }) + end) + UI.SetFont(fs, "body", 12) + fs:SetTextColor(UI.Color(colorKey or "textDim")) + fs:SetWordWrap(true) + fs:SetJustifyV("TOP") + fs:ClearAllPoints() + fs:SetPoint("TOPLEFT", self.child, "TOPLEFT", 0, -self.y) + fs:SetPoint("TOPRIGHT", self.child, "TOPRIGHT", 0, -self.y) + local lines = math.max(1, math.ceil(#text / 75)) + fs:SetHeight(lines * 15) + fs:SetText(text) + self.y = self.y + lines * 15 + 4 + end + + -- Marken nebeneinander (einzeilig, bricht bei Bedarf um) + function s:Chips(list, colorKey) + local x, rowY = 0, self.y + for _, text in ipairs(list) do + local chip = take("chip", function() + return UI.CreateChip(self.child, "", "bronze") + end) + chip:SetText(text, colorKey or "goldAntique") + local w = chip:GetWidth() or 60 + if x > 0 and x + w > 500 then + x = 0 + rowY = rowY + 26 + end + chip:ClearAllPoints() + chip:SetPoint("TOPLEFT", self.child, "TOPLEFT", x, -rowY) + x = x + w + 6 + end + self.y = rowY + 28 + end + + -- Zeile: links Text, rechts Text oder Marke; optional klickbar + function s:Row(left, right, rightColor, onClick, selected) + local row = take("row", function() + local r = CreateFrame("Button", nil, self.child) + r:SetHeight(26) + r.bg = r:CreateTexture(nil, "BACKGROUND") + r.bg:SetAllPoints() + UI.AddBorder(r, "bronze", 0.6) + r.left = UI.CreateLabel(r, "", { size = 12 }) + r.left:SetPoint("LEFT", r, "LEFT", 10, 0) + r.left:SetWordWrap(false) + r.right = UI.CreateLabel(r, "", { size = 11, color = "textDim", justify = "RIGHT" }) + r.right:SetPoint("RIGHT", r, "RIGHT", -10, 0) + r.right:SetWordWrap(false) + r.left:SetPoint("RIGHT", r.right, "LEFT", -8, 0) + local function paint() + if r.selected then + r.bg:SetColorTexture(UI.Color("hover")) + UI.SetBorderColor(r, "gold") + elseif r.hover and r.clickable then + r.bg:SetColorTexture(UI.Color("hover", 0.7)) + UI.SetBorderColor(r, "bronze") + else + r.bg:SetColorTexture(UI.Color("card")) + UI.SetBorderColor(r, "bronze", 0.6) + end + end + r.paint = paint + r:SetScript("OnEnter", function() + r.hover = true + paint() + end) + r:SetScript("OnLeave", function() + r.hover = false + paint() + end) + r:SetScript("OnClick", function() + if r.onClick then + r.onClick() + end + end) + return r + end) + row.onClick = onClick + row.clickable = onClick ~= nil + row.selected = selected and true or false + row.left:SetText(left or "") + row.right:SetText(right or "") + row.right:SetTextColor(UI.Color(rightColor or "textDim")) + row:ClearAllPoints() + row:SetPoint("TOPLEFT", self.child, "TOPLEFT", 0, -self.y) + row:SetPoint("TOPRIGHT", self.child, "TOPRIGHT", 0, -self.y) + row.paint() + self.y = self.y + 30 + return row + end + + function s:Height() + return self.y + end + + return s +end + +------------------------------------------------------------------------ +-- Tab +------------------------------------------------------------------------ + +local function FactorColor(f) + if f > 1.0001 then + return "goldLight" + elseif f < 0.9999 then + return "danger" + end + return "text" +end + +local function Build(content) + local L = FW.L + local f = CreateFrame("Frame", nil, content) + + local rows = {} + local filter = { text = "", fid = nil, zone = nil, status = nil, ability = nil, rank = nil, rankMin = false } + local selectedGroup + + ---------------- linke Spalte ---------------- + local title = UI.CreateLabel(f, L.BEAST_TITLE, { font = "heading", size = 14, color = "goldLight" }) + title:SetPoint("TOPLEFT", f, "TOPLEFT", 0, 0) + local countLabel = UI.CreateLabel(f, "", { size = 11, color = "textDim", justify = "RIGHT" }) + countLabel:SetPoint("TOPRIGHT", f, "TOPLEFT", LIST_W, 0) + countLabel:SetWidth(LIST_W - 90) + countLabel:SetWordWrap(false) + + local listDivider = UI.CreateDivider(f) + listDivider:SetPoint("TOPLEFT", f, "TOPLEFT", 0, -26) + listDivider:SetWidth(LIST_W) + + local search = CreateSearchBox(f, LIST_W, L.BEAST_SEARCH, function(text) + filter.text = text + if f.Refresh then f.Refresh() end + end) + search:SetPoint("TOPLEFT", f, "TOPLEFT", 0, -36) + + local familySelect, zoneSelect + familySelect = CreateSelect(f, 146, function() + local fams = Beasts:FilterChoices() + local opts = { { key = false, text = FW.L.BEAST_ALL_FAMILIES } } + for _, fam in ipairs(fams) do + opts[#opts + 1] = { key = fam.id, text = fam.text } + end + return opts + end, function() + return filter.fid or false + end, function(key) + filter.fid = key or nil + if f.Refresh then f.Refresh() end + end) + familySelect:SetPoint("TOPLEFT", f, "TOPLEFT", 0, -68) + + zoneSelect = CreateSelect(f, 146, function() + local _, zones = Beasts:FilterChoices() + local opts = { { key = false, text = FW.L.BEAST_ALL_ZONES } } + for _, z in ipairs(zones) do + opts[#opts + 1] = { key = z, text = z } + end + return opts + end, function() + return filter.zone or false + end, function(key) + filter.zone = key or nil + if f.Refresh then f.Refresh() end + end) + zoneSelect:SetPoint("TOPLEFT", f, "TOPLEFT", 154, -68) + + -- Faehigkeit, die das Zaehmen lehrt (und Rang) + local abilitySelect, rankSelect + abilitySelect = CreateSelect(f, 186, function() + local opts = { { key = false, text = FW.L.BEAST_ALL_ABILITIES } } + for _, name in ipairs(Beasts:AbilityChoices()) do + opts[#opts + 1] = { key = name, text = name } + end + return opts + end, function() + return filter.ability or false + end, function(key) + filter.ability = key or nil + filter.rank, filter.rankMin = nil, false + if f.Refresh then f.Refresh() end + end) + abilitySelect:SetPoint("TOPLEFT", f, "TOPLEFT", 0, -98) + + rankSelect = CreateSelect(f, 108, function() + local opts = { { key = false, text = FW.L.BEAST_ALL_RANKS } } + if filter.ability then + local ranks = Beasts:AbilityRanks(filter.ability) + for _, r in ipairs(ranks) do + opts[#opts + 1] = { key = r, text = string.format(FW.L.BEAST_RANK_EXACT, r) } + end + for i, r in ipairs(ranks) do + if i > 1 then + opts[#opts + 1] = { key = -r, text = string.format(FW.L.BEAST_RANK_MIN, r) } + end + end + end + return opts + end, function() + if not filter.rank then + return false + end + return filter.rankMin and -filter.rank or filter.rank + end, function(key) + if key then + filter.rank, filter.rankMin = math.abs(key), key < 0 + else + filter.rank, filter.rankMin = nil, false + end + if f.Refresh then f.Refresh() end + end) + rankSelect:SetPoint("TOPLEFT", f, "TOPLEFT", 192, -98) + + -- Statusfilter + local statusButtons = {} + local statusDefs = { + { key = false, text = function() return FW.L.BEAST_STATUS_ALL end, w = 44 }, + { key = "seen", text = function() return FW.L.BEAST_STATUS_SEEN end, w = 58 }, + { key = "lored", text = function() return FW.L.BEAST_STATUS_LORED end, w = 66 }, + { key = "tamed", text = function() return FW.L.BEAST_STATUS_TAMED end, w = 60 }, + { key = "unknown", text = function() return FW.L.BEAST_STATUS_UNKNOWN end, w = 60 }, + } + local prev + for _, def in ipairs(statusDefs) do local def = def + local b = UI.CreateButton(f, def.text(), def.w, 22, function() + filter.status = def.key or nil + if f.Refresh then f.Refresh() end + end, "ghost") + UI.SetFont(b.label, "body", 11) + if prev then + b:SetPoint("LEFT", prev, "RIGHT", 3, 0) + else + b:SetPoint("TOPLEFT", f, "TOPLEFT", 0, -128) + end + b.def = def + statusButtons[#statusButtons + 1] = b + prev = b + end + + local listScroll = UI.CreateScrollFrame(f) + listScroll:SetPoint("TOPLEFT", f, "TOPLEFT", 0, -158) + listScroll:SetPoint("BOTTOMLEFT", f, "BOTTOMLEFT", 0, 62) + listScroll:SetWidth(LIST_W) + + local emptyLabel = UI.CreateLabel(listScroll.child, "", { size = 12, color = "textDim", justifyV = "TOP" }) + emptyLabel:SetPoint("TOPLEFT", listScroll.child, "TOPLEFT", 4, -6) + emptyLabel:SetPoint("TOPRIGHT", listScroll.child, "TOPRIGHT", -4, -6) + emptyLabel:SetHeight(120) + emptyLabel:SetWordWrap(true) + + -- Schalter: Startdaten anzeigen oder selbst erkunden + local seedToggle = UI.CreateCheckbox(f, L.BEAST_SEED_TOGGLE, function() + return Beasts:SeedEnabled() + end, function(on) + Beasts:SetSeedEnabled(on) + end) + seedToggle:SetPoint("BOTTOMLEFT", f, "BOTTOMLEFT", 0, 4) + UI.AttachTooltip(seedToggle, L.BEAST_SEED_TOGGLE, { L.BEAST_SEED_TIP1, L.BEAST_SEED_TIP2 }) + + -- Auf Octo/1.12 zeichnet die Codex-Karte (dieselbe wie "Auf Karte zeigen" in der Datenbank); + -- ohne Codex bleibt die alte Beasts-Ebene. + local Overlay = NS.MapOverlay + do + local C = FW.Codex + local M = C and C.Map + if M and M.Show then + local W = { _mode = nil, _single = nil, pts = nil } + setmetatable(W, { __index = function(t, k) + if k == "mode" or k == "singleID" then + if rawget(t, "pts") and M.points == rawget(t, "pts") then + return rawget(t, k == "mode" and "_mode" or "_single") + end + return nil + end + end }) + local function Put(ids, label, mode, single) + local pts = Beasts:MapPoints(ids) + if M:Show(pts, label) then + W.pts = M.points + W._mode, W._single = mode, single + end + FW:Fire("BEASTS_MAP_CHANGED") + end + function W:ShowSingle(id, name) + Put({ [id] = true }, name, "single", id) + end + function W:ShowMany(ids, count) + Put(ids, string.format(FW.L.BEAST_MAP_MANY, count), "many", nil) + end + function W:Clear() + if M.points and M.points == rawget(W, "pts") then + M:Clear() + end + W.pts, W._mode, W._single = nil, nil, nil + FW:Fire("BEASTS_MAP_CHANGED") + end + function W:Focus() end + Overlay = W + end + end + local mapToggle = UI.CreateCheckbox(f, L.BEAST_MAP_FILTERED, function() + return Overlay and Overlay.mode == "many" + end, function(on) + if not Overlay then + return + end + if on then + f.ShowFilteredOnMap() + else + Overlay:Clear() + end + end) + mapToggle:SetPoint("BOTTOMLEFT", f, "BOTTOMLEFT", 0, 32) + UI.AttachTooltip(mapToggle, L.BEAST_MAP_FILTERED, { L.BEAST_MAP_FILTERED_TIP }) + + local separator = f:CreateTexture(nil, "ARTWORK") + separator:SetColorTexture(UI.Color("bronze", 0.4)) + separator:SetWidth(1) + separator:SetPoint("TOPLEFT", f, "TOPLEFT", LIST_W + 10, 0) + separator:SetPoint("BOTTOMLEFT", f, "BOTTOMLEFT", LIST_W + 10, 0) + + ---------------- rechte Spalte ---------------- + local detail = CreateFrame("Frame", nil, f) + detail:SetPoint("TOPLEFT", f, "TOPLEFT", LIST_W + 22, 0) + detail:SetPoint("BOTTOMRIGHT", f, "BOTTOMRIGHT", 0, 0) + + local hint = UI.CreateLabel(f, L.BEAST_SELECT, { size = 12, color = "textDim", justifyV = "TOP" }) + hint:SetPoint("TOPLEFT", f, "TOPLEFT", LIST_W + 22, -4) + hint:SetPoint("TOPRIGHT", f, "TOPRIGHT", 0, -4) + hint:SetWordWrap(true) + + -- Bild: 3D-Modell des Tiers (aus der NPC-Nummer), solange es nicht laedt das Familien-Symbol + local portrait = UI.CreatePanel(detail, "bgDeep", "bronze") + portrait:SetSize(64, 64) + portrait:SetPoint("TOPLEFT", detail, "TOPLEFT", 0, 0) + local portraitIcon = portrait:CreateTexture(nil, "ARTWORK") + portraitIcon:SetPoint("TOPLEFT", portrait, "TOPLEFT", 6, -6) + portraitIcon:SetPoint("BOTTOMRIGHT", portrait, "BOTTOMRIGHT", -6, 6) + portraitIcon:SetTexCoord(0.08, 0.92, 0.08, 0.92) + local model = CreateFrame("PlayerModel", nil, portrait) + model:SetPoint("TOPLEFT", portrait, "TOPLEFT", 2, -2) + model:SetPoint("BOTTOMRIGHT", portrait, "BOTTOMRIGHT", -2, 2) + model:SetAlpha(0) + -- 1.12 kennt OnModelLoaded nicht: dann bleibt das Modell unsichtbar und das Symbol steht + pcall(model.SetScript, model, "OnModelLoaded", function(self) + self:SetAlpha(1) + portraitIcon:Hide() + end) + + local nameLabel = UI.CreateLabel(detail, "", { font = "heading", size = 20, color = "goldLight" }) + nameLabel:SetPoint("TOPLEFT", detail, "TOPLEFT", 76, -2) + nameLabel:SetWidth(330) + nameLabel:SetWordWrap(false) + + local subLabel = UI.CreateLabel(detail, "", { size = 12, color = "textDim" }) + subLabel:SetPoint("TOPLEFT", detail, "TOPLEFT", 76, -32) + subLabel:SetWidth(400) + subLabel:SetWordWrap(false) + + local mapButton = UI.CreateButton(detail, L.BEAST_MAP_SHOW, 170, 22, function() + local id = Beasts.selectedID + if not (Overlay and id) then + return + end + if Overlay.mode == "single" and Overlay.singleID == id then + Overlay:Clear() + else + Overlay:ShowSingle(id, Beasts:Summary(id).name) + Overlay:Focus(selectedGroup) + end + end, "primary") + mapButton:SetPoint("TOPLEFT", detail, "TOPLEFT", 76, -46) + + local stateChip = UI.CreateChip(detail, "", "success") + stateChip:SetPoint("TOPRIGHT", detail, "TOPRIGHT", 0, -4) + local sourceChip = UI.CreateChip(detail, "", "textDim") + sourceChip:SetPoint("RIGHT", stateChip, "LEFT", -6, 0) + + local headDivider = UI.CreateDivider(detail) + headDivider:SetPoint("TOPLEFT", detail, "TOPLEFT", 0, -76) + headDivider:SetPoint("TOPRIGHT", detail, "TOPRIGHT", 0, -76) + + -- Familienfaktoren + local cards = {} + local defs = { + { key = "hp", label = L.PET_HEALTH }, + { key = "dmg", label = L.PET_DAMAGE }, + { key = "armor", label = L.PET_ARMOR }, + } + for i, def in ipairs(defs) do + local card = UI.CreateStatCard(detail, def.label, CARD_W, CARD_H) + UI.SetFont(card.value, "heading", 15) + card:SetPoint("TOPLEFT", detail, "TOPLEFT", (i - 1) * (CARD_W + CARD_GAP), -88) + cards[def.key] = card + end + + local coordsArea = UI.CreateTextArea(detail, 100, 64) + coordsArea:SetPoint("BOTTOMLEFT", detail, "BOTTOMLEFT", 0, 0) + coordsArea:SetPoint("BOTTOMRIGHT", detail, "BOTTOMRIGHT", 0, 0) + coordsArea:SetHeight(64) + local coordsHint = UI.CreateLabel(detail, L.BEAST_COORDS_HINT, { size = 11, color = "textDim" }) + coordsHint:SetPoint("BOTTOMLEFT", coordsArea, "TOPLEFT", 0, 4) + coordsHint:SetPoint("BOTTOMRIGHT", coordsArea, "TOPRIGHT", 0, 4) + coordsHint:SetWordWrap(false) + + local sectionScroll = UI.CreateScrollFrame(detail) + sectionScroll:SetPoint("TOPLEFT", detail, "TOPLEFT", 0, -146) + sectionScroll:SetPoint("BOTTOMRIGHT", detail, "BOTTOMRIGHT", 0, 90) + local stack = NewStack(sectionScroll) + + ---------------- Inhalt fuellen ---------------- + local function CoordsText(g) + local lines = { g.name } + local function add(tag, list) + local limit = math.min(#list, 40) + for i = 1, limit do + local p = list[i] + local times = (p[3] and p[3] > 1) and string.format(" (x%d)", p[3]) or "" + lines[#lines + 1] = string.format("[%s] %.1f, %.1f%s", tag, p[1] / 10, p[2] / 10, times) + end + if #list > limit then + lines[#lines + 1] = string.format("[%s] ... +%d", tag, #list - limit) + end + end + add(FW.L.BEAST_TAG_OWN, g.own) + add(FW.L.BEAST_TAG_IMPORT, g.imp) + add(FW.L.BEAST_TAG_START, g.seed) + return table.concat(lines, "\n") + end + + local ShowDetail + + local function FillSections(s) + local L2 = FW.L + stack:Reset() + + -- Nahrung + stack:Heading(L2.BEAST_FOOD) + local foods = FoodList(s.diet) + if #foods == 0 then + stack:Text(L2.BEAST_FOOD_UNKNOWN, "textDim") + else + stack:Chips(foods, "goldAntique") + end + stack:Gap(6) + + -- Fundorte + stack:Heading(L2.BEAST_LOCATIONS) + local groups = Beasts:Locations(s) + if #groups == 0 then + stack:Text(L2.BEAST_LOCATIONS_NONE, "textDim") + coordsArea:SetText("") + else + local keep + for _, g in ipairs(groups) do + if selectedGroup == g.mapID then + keep = g + end + end + if not keep then + keep = groups[1] + selectedGroup = keep.mapID + end + for _, g in ipairs(groups) do local g = g + local tags = {} + if #g.own > 0 then tags[#tags + 1] = L2.BEAST_TAG_OWN .. " " .. #g.own end + if #g.imp > 0 then tags[#tags + 1] = L2.BEAST_TAG_IMPORT .. " " .. #g.imp end + if #g.seed > 0 then tags[#tags + 1] = L2.BEAST_TAG_START .. " " .. #g.seed end + stack:Row(g.name, table.concat(tags, " | "), "textDim", function() + selectedGroup = g.mapID + FillSections(s) + end, g.mapID == selectedGroup) + end + coordsArea:SetText(CoordsText(keep)) + end + stack:Gap(6) + + -- Faehigkeiten durch Zaehmen (Startdaten) + if s.seed and s.seed.t and #s.seed.t > 0 then + stack:Heading(L2.BEAST_TEACHES) + for _, spellID in ipairs(s.seed.t) do + local name, rank = Beasts.SpellInfo(spellID) + stack:Row(SpellName(spellID), SpellRank(spellID) or "", "goldLight", function() + if name then + filter.ability = name + filter.rank, filter.rankMin = (rank and rank > 0) and rank or nil, false + if f.Refresh then f.Refresh() end + end + end) + end + stack:Gap(6) + end + + -- Faehigkeiten des Begleiters, beim Zaehmen erfasst + local pa = (s.own and s.own.petAbilities) or (s.imp and s.imp.petAbilities) + if pa and #pa > 0 then + stack:Heading(L2.BEAST_PETABIL) + for _, a in ipairs(pa) do local a = a + local right = a.rank and a.rank > 0 and (FW.L.PET_RANK and string.format(FW.L.PET_RANK, a.rank) or ("Rang " .. a.rank)) or "" + if a.passive then + right = (right ~= "" and (right .. " | ") or "") .. L2.BEAST_PASSIVE + end + stack:Row(a.name, right, "goldLight", function() + if a.name then + filter.ability = a.name + filter.rank, filter.rankMin = (tonumber(a.rank) and tonumber(a.rank) > 0) and tonumber(a.rank) or nil, false + if f.Refresh then f.Refresh() end + end + end) + end + stack:Gap(6) + end + + -- Hinweise aus Wildtierkunde + local extra = (s.own and s.own.extra) or (s.imp and s.imp.extra) + if extra and #extra > 0 then + stack:Heading(L2.BEAST_EXTRA) + for _, line in ipairs(extra) do + stack:Text(line, "text") + end + end + + sectionScroll:SetContentHeight(stack:Height() + 4) + end + + function ShowDetail(id) + local s = id and Beasts:Summary(id) + if not s then + detail:Hide() + hint:Show() + return + end + hint:Hide() + detail:Show() + + nameLabel:SetText(s.name) + subLabel:SetText(Subtitle(s)) + portraitIcon:SetTexture(FamilyIcon(s.fid)) + portraitIcon:Show() + model:SetAlpha(0) + pcall(function() + model:ClearModel() + model:SetCreature(s.id) + if model.SetPortraitZoom then + model:SetPortraitZoom(1) + end + end) + local fileID = model.GetModelFileID and model:GetModelFileID() + if type(fileID) == "number" and fileID > 0 then + model:SetAlpha(1) + portraitIcon:Hide() + end + f.UpdateMapButton() + stateChip:SetText(StatusText(s.status), STATUS_COLOR[s.status]) + if s.own then + sourceChip:SetText(FW.L.BEAST_TAG_OWN, "textDim") + sourceChip:Show() + elseif s.imp then + sourceChip:SetText(FW.L.BEAST_TAG_IMPORT, "textDim") + sourceChip:Show() + elseif s.seed then + sourceChip:SetText(FW.L.BEAST_TAG_START, "textDim") + sourceChip:Show() + else + sourceChip:Hide() + end + + local mods = s.fid and Pet.GetFamilyModsByID(s.fid) or nil + for key, card in pairs(cards) do + local v = mods and mods[key] + if v then + card:SetValue(string.format("x%.2f", v), FactorColor(v)) + else + card:SetValue(FW.L.BEAST_FACTOR_UNKNOWN, "textDim") + end + end + + FillSections(s) + sectionScroll:ScrollToTop() + end + + function f.UpdateMapButton() + local id = Beasts.selectedID + if not (Overlay and id) then + return + end + if Overlay.mode == "single" and Overlay.singleID == id then + mapButton:SetLabel(FW.L.BEAST_MAP_HIDE) + else + mapButton:SetLabel(FW.L.BEAST_MAP_SHOW) + end + end + + function f.ShowFilteredOnMap() + local ids, count = {}, 0 + for _, s in ipairs(Beasts:Filtered(filter)) do + ids[s.id] = true + count = count + 1 + end + local wasMany = Overlay.mode == "many" + Overlay:ShowMany(ids, count) + if not wasMany then + Overlay:Focus(nil) + end + end + + local function SelectBeast(id) + if Beasts.selectedID ~= id then + selectedGroup = nil + end + Beasts.selectedID = id + for _, row in ipairs(rows) do + row:SetSelected(row.id == id) + end + ShowDetail(id) + end + + function f.Refresh() + local L2 = FW.L + local list, missing = Beasts:Filtered(filter) + local total = #Beasts:Index() + + if filter.ability then + countLabel:SetText(string.format(L2.BEAST_COUNT_NOABIL, #list, total, missing or 0)) + else + countLabel:SetText(string.format(L2.BEAST_COUNT, #list, total)) + end + abilitySelect:SetLabel(filter.ability or L2.BEAST_ALL_ABILITIES) + local rankText = L2.BEAST_ALL_RANKS + if filter.rank then + rankText = string.format(filter.rankMin and L2.BEAST_RANK_MIN or L2.BEAST_RANK_EXACT, filter.rank) + end + rankSelect:SetLabel(rankText) + rankSelect:SetButtonEnabled(filter.ability ~= nil) + + local famText, zoneText = L2.BEAST_ALL_FAMILIES, L2.BEAST_ALL_ZONES + if filter.fid then famText = Beasts:FamilyText(filter.fid) end + if filter.zone then zoneText = filter.zone end + familySelect:SetLabel(famText) + zoneSelect:SetLabel(zoneText) + for _, b in ipairs(statusButtons) do + local active = (b.def.key or nil) == filter.status + b:SetStyle(active and "primary" or "ghost") + end + seedToggle:Refresh() + if Beasts:HasSeed() then + seedToggle:Show() + else + seedToggle:Hide() + end + + local selectedStillListed = false + for i, s in ipairs(list) do + local row = rows[i] + if not row then + row = CreateListRow(listScroll.child, SelectBeast) + rows[i] = row + end + row.id = s.id + row.name:SetText(s.name) + row.sub:SetText(Subtitle(s)) + row.icon:SetTexture(FamilyIcon(s.fid)) + row.icon:SetDesaturated(s.status == "unknown") + row.chip:SetText(StatusText(s.status), STATUS_COLOR[s.status]) + row:ClearAllPoints() + row:SetPoint("TOPLEFT", listScroll.child, "TOPLEFT", 0, -(i - 1) * (ROW_H + ROW_GAP)) + row:SetPoint("TOPRIGHT", listScroll.child, "TOPRIGHT", 0, -(i - 1) * (ROW_H + ROW_GAP)) + row:SetSelected(s.id == Beasts.selectedID) + row:Show() + if s.id == Beasts.selectedID then + selectedStillListed = true + end + end + for i = #list + 1, #rows do + rows[i]:Hide() + end + listScroll:SetContentHeight(math.max(#list * (ROW_H + ROW_GAP), 130)) + + if #list == 0 then + emptyLabel:SetText((total == 0) and L2.BEAST_EMPTY_EXPLORE or L2.BEAST_EMPTY_FILTER) + emptyLabel:Show() + else + emptyLabel:Hide() + end + + if not selectedStillListed then + Beasts.selectedID = list[1] and list[1].id or nil + selectedGroup = nil + for _, row in ipairs(rows) do + row:SetSelected(row.id == Beasts.selectedID and row:IsShown()) + end + end + ShowDetail(Beasts.selectedID) + if Overlay and Overlay.mode == "many" then + f.ShowFilteredOnMap() + end + mapToggle:Refresh() + end + + FW:On("BEASTS_MAP_CHANGED", function() + mapToggle:Refresh() + if f.UpdateMapButton then + f.UpdateMapButton() + end + end) + + f:SetScript("OnHide", ClosePopup) + + FW:On("BEASTS_UPDATED", function() + if f:IsVisible() then + if f.Refresh then f.Refresh() end + end + end) + FW:On("PET_UPDATED", function() + if f:IsVisible() then + if f.Refresh then f.Refresh() end + end + end) + + if f.Refresh then f.Refresh() end + return f +end + +UI:RegisterTab("beasts", { + label = function() + return FW.L.BEAST_TAB + end, + order = 50, + build = Build, + onShow = function(f) + if f.Refresh then f.Refresh() end + end, +}) + +SLASH_FREEWOODBEASTS1 = "/fwbeasts" +SlashCmdList["FREEWOODBEASTS"] = function(msg) + msg = string.lower(strtrim(msg or "")) + if msg == "map" or msg == "karte" then + if NS.MapOverlay then + NS.MapOverlay:Debug() + end + elseif string.sub(msg, 1, 7) == "mapsize" then + local n = tonumber(string.match(msg, "(%d+)")) + if n then + Beasts.db.settings.mapMinSize = math.max(8, math.min(128, n)) + if NS.MapOverlay then + NS.MapOverlay:Refresh() + end + end + FW:Print(string.format(FW.L.BEAST_MAP_MINSIZE, Beasts.db.settings.mapMinSize or 32)) + elseif msg == "maptest" then + if NS.MapOverlay then + NS.MapOverlay:Test() + end + else + UI:Toggle("beasts") + end +end diff --git a/Freewood-OctoWoW-Beasts.toc b/Freewood-OctoWoW-Beasts.toc new file mode 100644 index 0000000..b765f0c --- /dev/null +++ b/Freewood-OctoWoW-Beasts.toc @@ -0,0 +1,15 @@ +## Interface: 11200 +## Title: Freewood |cffc89b3cBeasts|r +## Notes: Archive of wild beasts: where they live, what they eat, what taming teaches. Learns while you play, with export and import. +## Notes-deDE: Archiv wilder Tiere: wo sie leben, was sie fressen, was das Zähmen lehrt. Lernt beim Spielen, mit Export und Import. +## Author: Lacustat +## Version: 0.1.148 +## Dependencies: Freewood-OctoWoW-Core, Freewood-OctoWoW-Pet +## OptionalDeps: Freewood-OctoWoW-BeastsData, Freewood-OctoWoW-Codex + +Locales.lua +Beasts.lua +Sync.lua +MapOverlay.lua +BeastsUI.lua +SyncUI.lua diff --git a/Locales.lua b/Locales.lua new file mode 100644 index 0000000..9d811c6 --- /dev/null +++ b/Locales.lua @@ -0,0 +1,219 @@ +-- Freewood-OctoWoW-Beasts: Texte (de/en) +local FW = _G.Freewood +if not FW then + return +end + +FW:AddLocale("enUS", { + BEAST_TITLE = "Beasts", + BEAST_DESC = "Archive of wild beasts, filled by what you see, research and tame.", + BEAST_TAB = "Beasts", + BEAST_SEARCH = "Search...", + BEAST_ALL_FAMILIES = "All families", + BEAST_SHARE_HEADER = "Share beast data", + BEAST_SHARE_NOTE = "Only sightings, Beast Lore info and abilities of tamed beasts are shared. No character names, no notes. Everything is off until you switch it on. Channels you switch on are used for sending and receiving.", + BEAST_SHARE_GUILD = "Share with my guild", + BEAST_SHARE_GUILD_TIP = "Send and receive beast data with guild members who use Freewood Beasts.", + BEAST_SHARE_PARTY = "Share with my group", + BEAST_SHARE_PARTY_TIP = "Send and receive beast data with your party members.", + BEAST_SHARE_RAID = "Share with my raid", + BEAST_SHARE_RAID_TIP = "Send and receive beast data with your raid members.", + BEAST_SHARE_GLOBAL = "Share globally (experimental)", + BEAST_SHARE_GLOBAL_TIP = "Joins a hidden chat channel on your realm and exchanges beast data with everyone who uses the addon and has this on. Experimental: may not work on every client.", + BEAST_SHARE_STATS = "Sent: %d beasts | Received: %d beasts", + BEAST_SHARE_GLOBAL_OFF = "Global channel: off", + BEAST_SHARE_GLOBAL_OK = "Global channel: connected", + BEAST_SHARE_GLOBAL_JOINING = "Global channel: connecting ...", + BEAST_SHARE_GLOBAL_FAILED = "Global channel: could not connect", + BEAST_SHARE_GLOBAL_UNAVAILABLE = "Global channel: not available on this client", + BEAST_PEOPLE_BUTTON = "Share with people ...", + BEAST_PEOPLE_TITLE = "Share with people", + BEAST_PEOPLE_NOTE = "Data is only exchanged if you and the other person have added each other. Add a Battle.net friend or a character name exactly as it appears in game.", + BEAST_PEOPLE_EMPTY = "Nobody added yet.", + BEAST_PEOPLE_BNET = "Battle.net", + BEAST_PEOPLE_CHAR = "Character", + BEAST_PEOPLE_ADD = "Add a character name:", + BEAST_PEOPLE_ADD_BUTTON = "Add", + BEAST_PEOPLE_FRIENDS = "Choose from Battle.net friends ...", + BEAST_PEOPLE_EXISTS = "This person is already on the list.", + BEAST_PEOPLE_INVALID = "That name is not valid.", + BEAST_PEOPLE_NOFRIENDS = "No Battle.net friends found.", + BEAST_PEOPLE_BN_OFF = "Battle.net sending is not available on this client.", + BEAST_PEOPLE_COUNT = "People on your list: %d", + BEAST_ALL_ZONES = "All zones", + BEAST_ALL_ABILITIES = "All abilities", + BEAST_ALL_RANKS = "All ranks", + BEAST_RANK_EXACT = "Rank %d", + BEAST_RANK_MIN = "Rank %d and up", + BEAST_COUNT_NOABIL = "%d of %d | %d without data", + BEAST_FAMILY = "Family", + BEAST_ZONE = "Zone", + BEAST_STATUS_ALL = "All", + BEAST_STATUS_SEEN = "Seen", + BEAST_STATUS_LORED = "Researched", + BEAST_STATUS_TAMED = "Tamed", + BEAST_STATUS_UNKNOWN = "Unknown", + BEAST_STATUS_IMPORT = "Import", + BEAST_SEED_TOGGLE = "Show starter data (from the addon Tamed)", + BEAST_SEED_TIP1 = "On: you see the known beasts and locations right away.", + BEAST_SEED_TIP2 = "Off: you explore on your own, only beasts you saw, researched, tamed or imported show up.", + BEAST_COUNT = "%d of %d", + BEAST_EMPTY_EXPLORE = "No beasts recorded yet. Target wild beasts, use Beast Lore or tame one and it will appear here.", + BEAST_EMPTY_FILTER = "No beasts match these filters.", + BEAST_SELECT = "Select a beast from the list.", + BEAST_LEVEL = "Level %s", + BEAST_ELITE = "Elite", + BEAST_RARE = "Rare", + BEAST_RAREELITE = "Rare Elite", + BEAST_BOSS = "Boss", + BEAST_TAMEABLE = "Tameable", + BEAST_FAMILY_UNKNOWN = "Family unknown", + BEAST_FACTOR_UNKNOWN = "-", + BEAST_FOOD = "Diet", + BEAST_FOOD_UNKNOWN = "unknown", + BEAST_FOOD_m = "Meat", + BEAST_FOOD_f = "Fish", + BEAST_FOOD_c = "Cheese", + BEAST_FOOD_b = "Bread", + BEAST_FOOD_u = "Fungus", + BEAST_FOOD_r = "Fruit", + BEAST_LOCATIONS = "Locations", + BEAST_LOCATIONS_NONE = "No locations known yet.", + BEAST_POINTS = "%d points", + BEAST_TAG_OWN = "own", + BEAST_TAG_IMPORT = "import", + BEAST_TAG_START = "starter", + BEAST_COORDS_HINT = "Coordinates (select a zone above, Ctrl+C to copy):", + BEAST_TEACHES = "Taming teaches (starter data)", + BEAST_PETABIL = "Companion abilities (recorded when tamed)", + BEAST_EXTRA = "Notes from Beast Lore", + BEAST_PASSIVE = "passive", + BEAST_EXPORT_LABEL = "Beasts", + BEAST_IMPORT_EMPTY = "The code contains no beasts.", + BEAST_IMPORT_TOO_MANY = "The code contains too many beasts.", + BEAST_IMPORT_STATS = "%d new, %d updated, %d skipped", + BEAST_LEARNED = "Beast archive: new entry %s", + BEAST_UNNAMED = "Unknown beast (%d)", + BEAST_MAP_SHOW = "Show on map", + BEAST_MAP_HIDE = "Remove from map", + BEAST_MAP_FILTERED = "Show filtered beasts on the map", + BEAST_MAP_FILTERED_TIP = "Draws the areas of all beasts in the current list on the world map.", + BEAST_MAP_LABEL = "Freewood: %s (click to remove)", + BEAST_MAP_MANY = "%d beasts", + BEAST_MAP_MINSIZE = "Beasts: smallest map area is %d pixels (change with /fwbeasts mapsize 32)", + BEAST_HOVER_TITLE = "Beasts found here", + BEAST_HOVER_LEVEL = "level %s", + BEAST_HOVER_OWN = "own %d", + BEAST_HOVER_IMPORTED = "imported %d", + BEAST_HOVER_SEED = "starter data %d", + BEAST_HOVER_MORE = "... and %d more", + BEAST_CELLS = "%d fields", + BEAST_MAP_RESTART = "Beasts: texture not found. Please quit the game completely and start it again (a /reload does not load new files).", +}) + +FW:AddLocale("deDE", { + BEAST_TITLE = "Wildtiere", + BEAST_DESC = "Archiv wilder Tiere, gefüllt durch das, was du siehst, erforschst und zähmst.", + BEAST_TAB = "Wildtiere", + BEAST_SEARCH = "Suchen...", + BEAST_ALL_FAMILIES = "Alle Familien", + BEAST_SHARE_HEADER = "Wildtier-Daten teilen", + BEAST_SHARE_NOTE = "Geteilt werden nur Sichtungen, Wildtierkunde-Infos und Fähigkeiten gezähmter Tiere. Keine Charakternamen, keine Notizen. Alles ist aus, bis du es einschaltest. Eingeschaltete Kanäle werden zum Senden und Empfangen genutzt.", + BEAST_SHARE_GUILD = "Mit meiner Gilde teilen", + BEAST_SHARE_GUILD_TIP = "Wildtier-Daten mit Gildenmitgliedern austauschen, die Freewood Beasts nutzen.", + BEAST_SHARE_PARTY = "Mit meiner Gruppe teilen", + BEAST_SHARE_PARTY_TIP = "Wildtier-Daten mit den Mitgliedern deiner Gruppe austauschen.", + BEAST_SHARE_RAID = "Mit meinem Schlachtzug teilen", + BEAST_SHARE_RAID_TIP = "Wildtier-Daten mit den Mitgliedern deines Schlachtzugs austauschen.", + BEAST_SHARE_GLOBAL = "Global teilen (experimentell)", + BEAST_SHARE_GLOBAL_TIP = "Tritt einem versteckten Chatkanal auf deinem Server bei und tauscht Wildtier-Daten mit allen aus, die das Addon nutzen und es eingeschaltet haben. Experimentell: funktioniert eventuell nicht auf jedem Client.", + BEAST_SHARE_STATS = "Gesendet: %d Tiere | Empfangen: %d Tiere", + BEAST_SHARE_GLOBAL_OFF = "Globaler Kanal: aus", + BEAST_SHARE_GLOBAL_OK = "Globaler Kanal: verbunden", + BEAST_SHARE_GLOBAL_JOINING = "Globaler Kanal: verbindet ...", + BEAST_SHARE_GLOBAL_FAILED = "Globaler Kanal: Verbindung nicht möglich", + BEAST_SHARE_GLOBAL_UNAVAILABLE = "Globaler Kanal: auf diesem Client nicht verfügbar", + BEAST_PEOPLE_BUTTON = "Mit Personen teilen ...", + BEAST_PEOPLE_TITLE = "Mit Personen teilen", + BEAST_PEOPLE_NOTE = "Daten werden nur ausgetauscht, wenn du und die andere Person euch gegenseitig eingetragen habt. Trage einen Battle.net-Freund oder einen Charakternamen genau so ein, wie er im Spiel steht.", + BEAST_PEOPLE_EMPTY = "Noch niemand eingetragen.", + BEAST_PEOPLE_BNET = "Battle.net", + BEAST_PEOPLE_CHAR = "Charakter", + BEAST_PEOPLE_ADD = "Charakternamen hinzufügen:", + BEAST_PEOPLE_ADD_BUTTON = "Hinzufügen", + BEAST_PEOPLE_FRIENDS = "Aus Battle.net-Freunden wählen ...", + BEAST_PEOPLE_EXISTS = "Diese Person steht schon in der Liste.", + BEAST_PEOPLE_INVALID = "Dieser Name ist nicht gültig.", + BEAST_PEOPLE_NOFRIENDS = "Keine Battle.net-Freunde gefunden.", + BEAST_PEOPLE_BN_OFF = "Der Battle.net-Versand ist auf diesem Client nicht verfügbar.", + BEAST_PEOPLE_COUNT = "Personen in deiner Liste: %d", + BEAST_ALL_ZONES = "Alle Gebiete", + BEAST_ALL_ABILITIES = "Alle Fähigkeiten", + BEAST_ALL_RANKS = "Alle Ränge", + BEAST_RANK_EXACT = "Rang %d", + BEAST_RANK_MIN = "ab Rang %d", + BEAST_COUNT_NOABIL = "%d von %d | %d ohne Daten", + BEAST_FAMILY = "Familie", + BEAST_ZONE = "Gebiet", + BEAST_STATUS_ALL = "Alle", + BEAST_STATUS_SEEN = "Gesehen", + BEAST_STATUS_LORED = "Erforscht", + BEAST_STATUS_TAMED = "Gezähmt", + BEAST_STATUS_UNKNOWN = "Unbekannt", + BEAST_STATUS_IMPORT = "Import", + BEAST_SEED_TOGGLE = "Startdaten anzeigen (aus dem Addon Tamed)", + BEAST_SEED_TIP1 = "An: du siehst die bekannten Tiere und Fundorte sofort.", + BEAST_SEED_TIP2 = "Aus: du erkundest selbst, nur gesehene, erforschte, gezähmte oder importierte Tiere erscheinen.", + BEAST_COUNT = "%d von %d", + BEAST_EMPTY_EXPLORE = "Noch keine Wildtiere erfasst. Visiere Wildtiere an, nutze Wildtierkunde oder zähme eines, dann erscheint es hier.", + BEAST_EMPTY_FILTER = "Keine Tiere für diese Filter.", + BEAST_SELECT = "Wähle ein Tier aus der Liste.", + BEAST_LEVEL = "Stufe %s", + BEAST_ELITE = "Elite", + BEAST_RARE = "Selten", + BEAST_RAREELITE = "Selten, Elite", + BEAST_BOSS = "Boss", + BEAST_TAMEABLE = "Zähmbar", + BEAST_FAMILY_UNKNOWN = "Familie unbekannt", + BEAST_FACTOR_UNKNOWN = "-", + BEAST_FOOD = "Nahrung", + BEAST_FOOD_UNKNOWN = "unbekannt", + BEAST_FOOD_m = "Fleisch", + BEAST_FOOD_f = "Fisch", + BEAST_FOOD_c = "Käse", + BEAST_FOOD_b = "Brot", + BEAST_FOOD_u = "Fungus", + BEAST_FOOD_r = "Obst", + BEAST_LOCATIONS = "Fundorte", + BEAST_LOCATIONS_NONE = "Noch keine Fundorte bekannt.", + BEAST_POINTS = "%d Punkte", + BEAST_TAG_OWN = "eigene", + BEAST_TAG_IMPORT = "Import", + BEAST_TAG_START = "Startdaten", + BEAST_COORDS_HINT = "Koordinaten (Gebiet oben wählen, Strg+C zum Kopieren):", + BEAST_TEACHES = "Zähmen lehrt (Startdaten)", + BEAST_PETABIL = "Fähigkeiten des Begleiters (beim Zähmen erfasst)", + BEAST_EXTRA = "Hinweise aus Wildtierkunde", + BEAST_PASSIVE = "passiv", + BEAST_EXPORT_LABEL = "Wildtiere", + BEAST_IMPORT_EMPTY = "Der Code enthält keine Wildtiere.", + BEAST_IMPORT_TOO_MANY = "Der Code enthält zu viele Wildtiere.", + BEAST_IMPORT_STATS = "%d neu, %d aktualisiert, %d übersprungen", + BEAST_LEARNED = "Wildtier-Archiv: neuer Eintrag %s", + BEAST_UNNAMED = "Unbekanntes Tier (%d)", + BEAST_MAP_SHOW = "Auf Karte zeigen", + BEAST_MAP_HIDE = "Von Karte nehmen", + BEAST_MAP_FILTERED = "Gefilterte Tiere auf der Karte zeigen", + BEAST_MAP_FILTERED_TIP = "Zeichnet die Gebiete aller Tiere der aktuellen Liste auf die Weltkarte.", + BEAST_MAP_LABEL = "Freewood: %s (Klick zum Entfernen)", + BEAST_MAP_MANY = "%d Tiere", + BEAST_MAP_MINSIZE = "Beasts: kleinstes Gebiet auf der Karte ist %d Pixel (ändern mit /fwbeasts mapsize 32)", + BEAST_HOVER_TITLE = "Hier gefundene Wildtiere", + BEAST_HOVER_LEVEL = "Stufe %s", + BEAST_HOVER_OWN = "eigene %d", + BEAST_HOVER_IMPORTED = "importiert %d", + BEAST_HOVER_SEED = "Startdaten %d", + BEAST_HOVER_MORE = "... und %d weitere", + BEAST_CELLS = "%d Felder", + BEAST_MAP_RESTART = "Beasts: Textur nicht gefunden. Bitte das Spiel komplett beenden und neu starten (/reload lädt neue Dateien nicht).", +}) diff --git a/MapOverlay.lua b/MapOverlay.lua new file mode 100644 index 0000000..12b5071 --- /dev/null +++ b/MapOverlay.lua @@ -0,0 +1,528 @@ +-- Freewood-OctoWoW-Beasts: Gebiete auf der Weltkarte +-- Zeichnet weiche grüne Flecken ueber die Kartenflaeche, dort wo Tiere gefunden wurden. +-- (Blizzards blaue Quest-Gebiete kommen aus der Engine und gehen nur fuer Quests; hier wird +-- deshalb auf Blizzards Kartenflaeche mit eigenen Texturen gezeichnet.) + +local ADDON, NS = ... + +local FW = _G.Freewood +local Beasts = NS.Beasts +if not FW or not Beasts then + return +end + +local UI = FW.UI +local MAX_BLOBS = 1500 +local BLOB_SIZE = 0.05 +local BIN = 3 -- Zellen je Fleck (3 Zellen = 1,5 % der Karte) -- Durchmesser eines Flecks als Anteil der Kartenbreite + +local Overlay = { ids = nil, label = nil, hooked = false } +NS.MapOverlay = Overlay + +local layer, textures, infoButton, lessButton, moreButton, StartHover + +-- Fleck: weicher Kreis aus eigener Bilddatei. Neue Dateien kennt das Spiel erst nach einem +-- kompletten Neustart; bis dahin gibt es eckige Kaestchen als Notloesung. +local TEXTURE = "Interface\\AddOns\\Freewood-OctoWoW-Beasts\\Textures\\Blob.tga" +local warned = false + +local function TextureAvailable() + if type(GetFileIDFromPath) == "function" then + return GetFileIDFromPath(TEXTURE) ~= nil + end + return true +end + +local function StyleBlob(tex, available) + if available then + tex:SetTexture(TEXTURE) + else + tex:SetColorTexture(1, 1, 1, 1) + end +end + +local function Canvas() + local wm = _G.WorldMapFrame + if not wm then + return nil + end + if wm.GetCanvas then + local ok, c = pcall(wm.GetCanvas, wm) + if ok and c then + return c + end + end + return wm.ScrollContainer and wm.ScrollContainer.Child or nil +end + +local function EnsureLayer() + if layer then + return layer + end + local canvas = Canvas() + if not canvas then + return nil + end + layer = CreateFrame("Frame", nil, canvas) + layer:SetAllPoints(canvas) + layer:SetFrameLevel((canvas:GetFrameLevel() or 1) + 400) + if _G.WorldMapFrame and _G.WorldMapFrame.GetFrameStrata then + layer:SetFrameStrata(_G.WorldMapFrame:GetFrameStrata()) + end + layer:SetScript("OnSizeChanged", function(_, w, h) + if w and w > 1 and Overlay.ids then + Overlay:Refresh() + end + end) + textures = {} + StartHover(layer) + return layer +end + +local function EnsureInfoButton() + if infoButton then + return infoButton + end + local wm = _G.WorldMapFrame + if not wm then + return nil + end + infoButton = UI.CreateButton(wm, "", 300, 22, function() + Overlay:Clear() + end, "default") + infoButton:SetFrameStrata("HIGH") + infoButton:SetFrameLevel((wm:GetFrameLevel() or 1) + 60) + local anchor = wm.ScrollContainer or wm + infoButton:SetPoint("TOPLEFT", anchor, "TOPLEFT", 12, -12) + infoButton:Hide() + + local function change(delta) + local settings = Beasts.db.settings + local value = (settings.mapPower or 1.0) + delta + settings.mapPower = math.max(0.25, math.min(3, value)) + Overlay:Refresh() + end + lessButton = UI.CreateButton(wm, "-", 24, 22, function() change(-0.25) end, "default") + moreButton = UI.CreateButton(wm, "+", 24, 22, function() change(0.25) end, "default") + for _, b in ipairs({ lessButton, moreButton }) do + b:SetFrameStrata("HIGH") + b:SetFrameLevel((wm:GetFrameLevel() or 1) + 60) + b:Hide() + end + lessButton:SetPoint("LEFT", infoButton, "RIGHT", 6, 0) + moreButton:SetPoint("LEFT", lessButton, "RIGHT", 4, 0) + return infoButton +end + +local function CurrentMapID() + local wm = _G.WorldMapFrame + if wm and wm.GetMapID then + local ok, id = pcall(wm.GetMapID, wm) + if ok then + return id + end + end + return nil +end + +-- Alles neu zeichnen +function Overlay:Refresh() + local f = EnsureLayer() + if not f then + return + end + for _, t in ipairs(textures) do + t:Hide() + end + local btn = EnsureInfoButton() + if not self.ids or not next(self.ids) then + if btn then + btn:Hide() + lessButton:Hide() + moreButton:Hide() + end + return + end + if btn then + lessButton:Show() + moreButton:Show() + btn:SetLabel(string.format(FW.L.BEAST_MAP_LABEL, self.label or "")) + btn:SetWidth(math.max(200, (btn.label:GetStringWidth() or 200) + 24)) + btn:Show() + end + + local mapID = CurrentMapID() + if not mapID then + return + end + local weights = Beasts:MapWeights(self.ids, mapID) + local canvas = Canvas() or f + local width, height = canvas:GetWidth() or 1, canvas:GetHeight() or 1 + local grid = Beasts.GRID + if width < 2 or height < 2 then + -- Karte noch nicht eingerichtet (Groesse 0): spaeter noch einmal, nie durch 0 teilen + self.lastDraw = { mapID = mapID, width = width, height = height, waiting = true } + if _G.C_Timer and not self.retrying then + self.retrying = true + _G.C_Timer.After(0.2, function() + Overlay.retrying = false + if Overlay.ids then + Overlay:Refresh() + end + end) + end + return + end + + -- Fundorte zu Feldern zusammenfassen: je BIN x BIN Zellen ein Fleck (Mittelpunkt der Funde), + -- die Flecken sind gross genug, dass Nachbarn zu einer Flaeche verschmelzen + local bins, nbins, ncells = {}, 0, 0 + for idx in pairs(weights) do + ncells = ncells + 1 + local cx = idx % grid + local cy = math.floor(idx / grid) + local key = math.floor(cy / BIN) * 1000 + math.floor(cx / BIN) + local b = bins[key] + if not b then + b = { sx = 0, sy = 0, n = 0 } + bins[key] = b + nbins = nbins + 1 + end + b.sx, b.sy, b.n = b.sx + cx + 0.5, b.sy + cy + 0.5, b.n + 1 + end + + -- Mindestgroesse in Bildschirm-Pixeln, umgerechnet auf die Einheiten der Kartenflaeche + local scale = self:CanvasScale() + local minSize = (Beasts.db.settings.mapMinSize or 32) / scale + local size = math.max(minSize * 1.5, width * BLOB_SIZE) + self.hoverRadius = math.max(1, math.floor(size / 2 / width * grid * 0.8)) + self.lastScale = scale + + local available = TextureAvailable() + if not available and not warned then + warned = true + FW:Print(FW.L.BEAST_MAP_RESTART) + end + self.lastDraw = { mapID = mapID, cells = ncells, blobs = nbins, size = size, width = width, height = height, texture = available } + self.drawnMap = mapID + local alpha = math.min(1, 0.85 * (Beasts.db.settings.mapPower or 1.0)) + -- Der Rand der Bilddatei laeuft weich aus; damit auch ein einzelner Fundort deutlich zu sehen ist, + -- wird jeder Fleck zweimal gelegt (aussen gross, innen kleiner = kraeftiger Kern) + local i = 0 + for _, b in pairs(bins) do + if i >= MAX_BLOBS then + break + end + i = i + 1 + local x = (b.sx / b.n) / grid * width + local y = -(b.sy / b.n) / grid * height + for layerNo = 1, 2 do + local k = i * 2 - 2 + layerNo + local tex = textures[k] + if not tex then + tex = f:CreateTexture(nil, "OVERLAY") + StyleBlob(tex, available) + textures[k] = tex + elseif tex.available ~= available then + StyleBlob(tex, available) + end + tex.available = available + local d = layerNo == 1 and size or size * 0.6 + tex:ClearAllPoints() + tex:SetSize(d, d) + tex:SetPoint("CENTER", f, "TOPLEFT", x, y) + tex:SetVertexColor(0.1, 1.0, 0.3, alpha) + tex:Show() + end + end +end + +-- Faktor Kartenflaeche -> Bildschirm (aendert sich beim Zoomen) +function Overlay:CanvasScale() + local canvas = Canvas() + local s = 1 + if canvas and canvas.GetEffectiveScale and _G.UIParent then + local a, b = canvas:GetEffectiveScale(), _G.UIParent:GetEffectiveScale() + if type(a) == "number" and type(b) == "number" and b > 0 and a > 0 then + s = a / b + end + end + return s +end + +-- Mouseover: welche Tiere wurden in der Naehe des Mauszeigers gefunden + +local function MouseOverMap() + local wm = _G.WorldMapFrame + local sc = wm and wm.ScrollContainer + if type(sc) ~= "table" or type(sc.GetNormalizedCursorPosition) ~= "function" then + return nil + end + local focus + if GetMouseFoci then + focus = GetMouseFoci() + focus = focus and focus[1] + elseif GetMouseFocus then + focus = GetMouseFocus() + end + -- nur wenn der Zeiger ueber der Karte (oder einem Kartensymbol) ist, nicht ueber Fenstern davor + local f, ok = focus, (focus == nil) + local depth = 0 + while f and depth < 12 do + if f == sc then + ok = true + break + end + f = f.GetParent and f:GetParent() or nil + depth = depth + 1 + end + if not ok then + return nil + end + local x, y = sc:GetNormalizedCursorPosition() + if not x or x < 0 or x > 1 or y < 0 or y > 1 then + return nil + end + return x, y +end + +function Overlay:UpdateHover() + if not self.ids or not self.drawnMap then + return self:HideHover() + end + local x, y = MouseOverMap() + if not x then + return self:HideHover() + end + local grid = Beasts.GRID + local cx = math.min(grid - 1, math.floor(x * grid)) + local cy = math.min(grid - 1, math.floor(y * grid)) + local key = cy * grid + cx + if key == self.hoverKey and self.hoverShown ~= nil then + return + end + self.hoverKey = key + local hits = Beasts:BeastsAt(self.ids, self.drawnMap, cx, cy, self.hoverRadius or 3) + if #hits == 0 then + return self:HideHover() + end + local tip = _G.GameTooltip + tip:SetOwner(_G.WorldMapFrame, "ANCHOR_CURSOR") + tip:AddLine(FW.L.BEAST_HOVER_TITLE, 0.94, 0.75, 0.36) + local shown = 0 + for _, h in ipairs(hits) do + if shown >= 12 then + break + end + shown = shown + 1 + local sm = Beasts:Summary(h.id) + local left = sm.name + local lvl = sm.lvl1 and (sm.lvl2 and sm.lvl2 ~= sm.lvl1 and (sm.lvl1 .. "-" .. sm.lvl2) or tostring(sm.lvl1)) or nil + local right = {} + if sm.family and sm.family ~= "" then right[#right + 1] = sm.family end + if lvl then right[#right + 1] = string.format(FW.L.BEAST_HOVER_LEVEL, lvl) end + local counts = {} + if h.own > 0 then counts[#counts + 1] = string.format(FW.L.BEAST_HOVER_OWN, h.own) end + if h.imp > 0 then counts[#counts + 1] = string.format(FW.L.BEAST_HOVER_IMPORTED, h.imp) end + if h.seed > 0 then counts[#counts + 1] = string.format(FW.L.BEAST_HOVER_SEED, h.seed) end + tip:AddDoubleLine(left, table.concat(right, ", "), 0.42, 0.75, 0.44, 0.8, 0.8, 0.8) + if #counts > 0 then + tip:AddLine(" " .. table.concat(counts, " | "), 0.65, 0.65, 0.65) + end + end + if #hits > shown then + tip:AddLine(string.format(FW.L.BEAST_HOVER_MORE, #hits - shown), 0.8, 0.8, 0.8) + end + tip:Show() + self.hoverShown = true +end + +function Overlay:HideHover() + self.hoverKey = nil + if self.hoverShown then + self.hoverShown = nil + local tip = _G.GameTooltip + if tip:GetOwner() == _G.WorldMapFrame then + tip:Hide() + end + end +end + +local hoverElapsed = 0 +StartHover = function(f) + f:SetScript("OnUpdate", function(_, elapsed) + hoverElapsed = hoverElapsed + elapsed + if hoverElapsed < 0.08 then + return + end + hoverElapsed = 0 + if Overlay.ids then + local sc = Overlay:CanvasScale() + if Overlay.lastScale and math.abs(sc - Overlay.lastScale) > 0.01 then + Overlay:Refresh() + end + Overlay:UpdateHover() + end + end) +end + +-- Mit den Karten-Ereignissen von Blizzard verbinden (einmalig, spaeter erneut versuchbar) +function Overlay:Hook() + if self.hooked then + return true + end + local wm = _G.WorldMapFrame + if not wm or not Canvas() then + return false + end + self.hooked = true + if wm.OnMapChanged then + pcall(hooksecurefunc, wm, "OnMapChanged", function() + Overlay:Refresh() + end) + end + if wm.HookScript then + wm:HookScript("OnShow", function() + Overlay:Refresh() + end) + end + return true +end + +-- ids: { [npcID] = true } oder nil, label: Text fuers Knopfchen auf der Karte +function Overlay:SetTargets(ids, label) + self.ids = ids + self.label = label + self:Hook() + self:Refresh() + FW:Fire("BEASTS_MAP_CHANGED") +end + +function Overlay:Clear() + self:HideHover() + self.mode = nil + self.singleID = nil + self:SetTargets(nil, nil) +end + +function Overlay:IsShowing(id) + return self.mode == "single" and self.singleID == id +end + +-- Karten-IDs mit Zellenzahl fuer eine Menge Tiere +function Overlay:MapCounts(ids) + local counts = {} + for id in pairs(ids) do + local own, imp, seed = Beasts.db.beasts[id], Beasts.db.imported[id], Beasts:SeedEntry(id) + for _, e in ipairs({ own or false, imp or false }) do + for m, cells in pairs(e and e.grid or {}) do + for _ in pairs(cells) do + counts[m] = (counts[m] or 0) + 1 + end + end + end + if seed and seed.m and seed.p then + counts[seed.m] = (counts[seed.m] or 0) + math.floor(#seed.p / 2) + end + end + return counts +end + +-- Weltkarte oeffnen und auf ein passendes Gebiet stellen: erst das gewuenschte, dann das +-- aktuelle (wenn es Daten hat), sonst das Gebiet mit den meisten Fundorten +function Overlay:Focus(preferMap) + local wm = _G.WorldMapFrame + if not wm or not self.ids then + return + end + local counts = self:MapCounts(self.ids) + local target + if preferMap and counts[preferMap] then + target = preferMap + else + local current = CurrentMapID() + if current and counts[current] then + target = current + else + local best = 0 + for m, n in pairs(counts) do + if n > best or (n == best and target and m < target) then + best, target = n, m + end + end + end + end + if not wm:IsShown() then + if type(ToggleWorldMap) == "function" then + pcall(ToggleWorldMap) + else + pcall(wm.Show, wm) + end + end + if target and wm.SetMapID and target ~= CurrentMapID() then + pcall(wm.SetMapID, wm, target) + end + self:Refresh() + return target +end + +-- Ein einzelnes Tier +function Overlay:ShowSingle(id, name) + self.mode = "single" + self.singleID = id + self:SetTargets({ [id] = true }, name) +end + +-- Alle Tiere der aktuellen Liste +function Overlay:ShowMany(ids, count) + self.mode = "many" + self.singleID = nil + self:SetTargets(ids, string.format(FW.L.BEAST_MAP_MANY, count)) +end + +-- Falls die Karte erst spaeter geladen wird +FW:RegisterEvent("ADDON_LOADED", function(_, name) + if name == "Blizzard_WorldMap" then + Overlay:Hook() + Overlay:Refresh() + end +end, Overlay) + +-- Diagnose: /fwbeasts map +function Overlay:Debug() + local wm = _G.WorldMapFrame + local canvas = Canvas() + local d = self.lastDraw + FW:Print("Karte: " .. tostring(CurrentMapID()) .. ", Flaeche " .. tostring(canvas and canvas:GetWidth()) .. " x " + .. tostring(canvas and canvas:GetHeight()) .. ", Ebene " .. tostring(canvas and canvas:GetFrameLevel()) + .. ", Overlay-Ebene " .. tostring(layer and layer:GetFrameLevel())) + if d and d.blobs then + FW:Print("Flecken " .. tostring(d.blobs) .. ", Groesse " .. string.format("%.1f", d.size or 0) .. ", Flaeche " .. string.format("%.0f x %.0f", d.width or 0, d.height or 0) + .. ", Zeichenebene " .. tostring(layer and layer:GetFrameLevel())) + end + FW:Print("Anzeige: " .. tostring(self.mode) .. ", Tiere " .. tostring(self.ids and (function() local n = 0 for _ in pairs(self.ids) do n = n + 1 end return n end)() or 0) + .. ", Zellen auf dieser Karte " .. tostring(d and d.cells)) + if layer and textures and textures[1] then + FW:Print("Erster Fleck: sichtbar " .. tostring(textures[1]:IsVisible()) .. ", Grösse " .. tostring(textures[1]:GetWidth())) + end +end + +-- Test: grosser roter Kasten in der Kartenmitte, zeigt ob ueberhaupt gezeichnet wird +function Overlay:Test() + local f = EnsureLayer() + if not f then + FW:Print("Weltkarte nicht gefunden.") + return + end + if not f.testTex then + f.testTex = f:CreateTexture(nil, "OVERLAY") + f.testTex:SetColorTexture(1, 0.1, 0.1, 0.6) + f.testTex:SetSize(160, 160) + f.testTex:SetPoint("CENTER", f, "CENTER", 0, 0) + end + if f.testTex:IsShown() then + f.testTex:Hide() + else + f.testTex:Show() + end +end