diff --git a/spec/System/TestAbyssTimelessJewel_spec.lua b/spec/System/TestAbyssTimelessJewel_spec.lua index 1f64037c529..93e859b4d5f 100644 --- a/spec/System/TestAbyssTimelessJewel_spec.lua +++ b/spec/System/TestAbyssTimelessJewel_spec.lua @@ -300,6 +300,50 @@ describe("Abyss timeless jewels", function() assert.matches("abyss_special_small_attribute25, 1, 0, 0", build.timelessData.searchListFallback, nil, true) end) + it("generates useful non-uniform fallback weights with Weighted Score", function() + build.skillsTab:PasteSocketGroup("Ethereal Knives 20/0 1\n") + runCallback("OnFrame") + local socketId + for id, node in pairs(build.spec.nodes) do + if node.isJewelSocket and node.name ~= "Charm Socket" then + socketId = id + break + end + end + assert.is_truthy(socketId, "fixture requires a passive-tree jewel socket") + + build.timelessData.jewelType = { id = 11 } + build.timelessData.conquerorType = { } + build.timelessData.jewelSocket = { id = socketId } + build.itemsTab.tradeQuery.statSortSelectionList = { + { stat = "FullDPS", label = "Full DPS", weightMult = 1 }, + { stat = "TotalEHP", label = "Effective Hit Pool", weightMult = 0.5 }, + } + build.treeTab:FindTimelessJewel() + local controls = main.popups[1].controls + controls.fallbackWeightsList:SelByValue("WeightedScore", "stat") + + local ok, errMsg = pcall(controls.fallbackWeightsButton.onClick) + assert.is_true(ok, errMsg) + + local distinctWeights = { } + local usefulWeightCount = 0 + for line in build.timelessData.searchListFallback:gmatch("[^\r\n]+") do + local weight1, weight2 = line:match("^[^,]+,%s*([^,]+),%s*([^,]+)") + weight1, weight2 = tonumber(weight1), tonumber(weight2) + if weight1 and weight2 and math.abs(weight1) + math.abs(weight2) > 0 then + usefulWeightCount = usefulWeightCount + 1 + distinctWeights[weight1 .. "," .. weight2] = true + end + end + local distinctWeightCount = 0 + for _ in pairs(distinctWeights) do + distinctWeightCount = distinctWeightCount + 1 + end + assert.is_true(usefulWeightCount > 0, "Generate must produce at least one useful fallback weight") + assert.is_true(distinctWeightCount > 1, "Weighted Score must not collapse every node to one weight") + end) + it("reads Zorath seed 6564 node and Inquisitor ascendancy changes", function() data.timelessJewelLUTs[11] = parseAbyssJewel(11, zorathExampleData()) local expected = { diff --git a/spec/System/TestItemDBControl_spec.lua b/spec/System/TestItemDBControl_spec.lua index c0df467b265..a054b129076 100644 --- a/spec/System/TestItemDBControl_spec.lua +++ b/spec/System/TestItemDBControl_spec.lua @@ -62,6 +62,58 @@ describe("ItemDBControl", function() assert.are.equal(-math.huge, invalidItem.measuredPower) end) + it("preserves negative WeightedScore results", function() + local function makeItem(name) + return { + name = name, + base = {}, + enchantModLines = {}, + implicitModLines = {}, + explicitModLines = {}, + baseModList = {}, + } + end + local betterItem = makeItem("Better Item") + local worseItem = makeItem("Worse Item") + local takenDamage = { + [betterItem] = 80, + [worseItem] = 120, + } + local itemsTab = { + activeItemSet = { useSecondWeaponSet = false }, + slots = { ["Body Armour"] = { shown = function() return true end } }, + tradeQuery = { statSortSelectionList = { + { stat = "PhysicalTakenHit", weightMult = 1, transform = function(value) return -value end }, + } }, + IsItemValidForSlot = function() return true end, + } + itemsTab.build = { + itemsTab = itemsTab, + calcsTab = { + GetMiscCalculator = function() + return function(args) + return { PhysicalTakenHit = takenDamage[args.repItem] } + end, { PhysicalTakenHit = 100 } + end, + }, + } + local control = new("ItemDBControl"):ItemDBControl(nil, { 0, 0, 100, 100 }, itemsTab, { + list = { worseItem, betterItem }, + }, "RARE") + for _, entry in ipairs(control.sortDropList) do + if entry.stat == "WeightedScore" then + control.sortDetail = entry + end + end + control.sortOrder = { control.sortControl.STAT, control.sortControl.NAME } + + control:ListBuilder() + + assert.are.same({ betterItem, worseItem }, control.list) + assert.is_true(betterItem.measuredPower < 0) + assert.is_true(worseItem.measuredPower < betterItem.measuredPower) + end) + it("searches Foulborn modifier text without case sensitivity", function() local item = new("Item"):Item([[ Rarity: Unique diff --git a/spec/System/TestNotableDBControl_spec.lua b/spec/System/TestNotableDBControl_spec.lua new file mode 100644 index 00000000000..b17de0ebea3 --- /dev/null +++ b/spec/System/TestNotableDBControl_spec.lua @@ -0,0 +1,64 @@ +describe("NotableDBControl", function() + local function findSortEntry(control, statName) + for _, entry in ipairs(control.sortDropList) do + if entry.stat == statName then + return entry + end + end + end + local function newAnointFixture(weights, includeSecondCandidate) + local candidates = { + { dn = "Candidate A", sd = {}, recipe = { "Fixture Oil" }, modKey = "CandidateA" }, + { dn = "Candidate B", sd = {}, recipe = { "Fixture Oil" }, modKey = "CandidateB" }, + } + local displayItem = { base = { type = "Amulet" } } + local outputs = { + [displayItem] = { FullDPS = 200, TotalEHP = 100 }, + [candidates[1]] = { FullDPS = 180, TotalEHP = 120 }, + [candidates[2]] = { FullDPS = 150, TotalEHP = 140 }, + } + local itemsTab = { + displayItem = displayItem, + tradeQuery = { statSortSelectionList = weights or {} }, + anointItem = function(_, node) return node end, + } + itemsTab.build = { + itemsTab = itemsTab, + calcsTab = { + GetMiscCalculator = function() + return function(args) + return outputs[args.repItem] or { FullDPS = 100, TotalEHP = 100 } + end + end, + }, + } + local list = includeSecondCandidate and candidates or { candidates[1] } + local control = new("NotableDBControl"):NotableDBControl(nil, { 0, 0, 100, 100 }, itemsTab, list, "ANOINT") + control.sortOrder = { control.sortControl.STAT, control.sortControl.NAME } + return control, candidates + end + + it("sorts WeightedScore anoints against the displayed item", function() + local weights = { + { stat = "FullDPS", weightMult = 1 }, + { stat = "TotalEHP", weightMult = 1 }, + } + local control, candidates = newAnointFixture(weights, true) + control.sortDetail = findSortEntry(control, "WeightedScore") + + control:ListBuilder() + + assert.are.same({ candidates[2], candidates[1] }, control.list) + assert.is_true(candidates[2].measuredPower > candidates[1].measuredPower) + assert.are.equal(candidates[2].measuredPower, control.sortMaxPower) + end) + + it("keeps scalar anoint impact relative to the item without an anoint", function() + local control, candidates = newAnointFixture() + control.sortDetail = findSortEntry(control, "FullDPS") + + control:ListBuilder() + + assert.are.equal(80, candidates[1].measuredPower) + end) +end) diff --git a/spec/System/TestTradeQuery_spec.lua b/spec/System/TestTradeQuery_spec.lua index ee577c3875b..249ecbd2dc3 100644 --- a/spec/System/TestTradeQuery_spec.lua +++ b/spec/System/TestTradeQuery_spec.lua @@ -261,6 +261,40 @@ describe("TradeQuery", function() end) end) + describe("SetStatWeights", function() + local capturedControls + local originalOpenPopup + local originalClosePopup + before_each(function() + originalOpenPopup = main.OpenPopup + originalClosePopup = main.ClosePopup + main.OpenPopup = function(_, _, _, _, controls) + capturedControls = controls + end + main.ClosePopup = function() end + end) + after_each(function() + main.OpenPopup = originalOpenPopup + main.ClosePopup = originalClosePopup + end) + + it("marks the build modified after saving changed weights", function() + local itemsTab = {} + local tradeQuery = new("TradeQuery"):TradeQuery(itemsTab) + tradeQuery:SetStatWeights() + for _, entry in ipairs(capturedControls.ListControl.list) do + if entry.stat.stat == "FullDPS" then + entry.stat.weightMult = 0.75 + break + end + end + capturedControls.finalise.onClick() + + assert.is_true(itemsTab.modFlag) + assert.are.equal(0.75, tradeQuery.statSortSelectionList[1].weightMult) + end) + end) + describe("ComputeStatDetails", function() it("uses Trader's FullDPS fallback inputs", function() mock_tradeQuery.statSortSelectionList = { { label = "Full DPS", stat = "FullDPS", weightMult = 1 } } diff --git a/spec/System/TestWeightedScore_spec.lua b/spec/System/TestWeightedScore_spec.lua new file mode 100644 index 00000000000..8998d60dd6b --- /dev/null +++ b/spec/System/TestWeightedScore_spec.lua @@ -0,0 +1,308 @@ +local WeightedScore = LoadModule("Modules/WeightedScore") + +describe("WeightedScore module", function() + it("provides default and configured weights", function() + local defaults = WeightedScore.defaultWeights() + assert.are.equal(2, #defaults) + assert.are.equal("FullDPS", defaults[1].stat) + assert.are.equal("TotalEHP", defaults[2].stat) + + local custom = { { stat = "TotalDPS", label = "DPS", weightMult = 2.0 } } + local cases = { + { label = "nil build", expected = defaults }, + { + label = "empty selection", + build = { itemsTab = { tradeQuery = { statSortSelectionList = {} } } }, + expected = defaults, + }, + { + label = "configured selection", + build = { itemsTab = { tradeQuery = { statSortSelectionList = custom } } }, + expected = custom, + }, + } + + for _, case in ipairs(cases) do + assert.are.same(case.expected, WeightedScore.getWeights(case.build), case.label) + end + end) + + it("weightsRequireFullDPS identifies active FullDPS weights", function() + local cases = { + { + label = "ordinary stats", + weights = { { stat = "TotalEHP", weightMult = 0.5 }, { stat = "TotalDPS", weightMult = 1.0 } }, + expected = false, + }, + { + label = "FullDPS among other stats", + weights = { { stat = "TotalEHP", weightMult = 0.5 }, { stat = "FullDPS", weightMult = 1.0 } }, + expected = true, + }, + { label = "zero FullDPS weight", weights = { { stat = "FullDPS", weightMult = 0 } }, expected = false }, + } + + for _, case in ipairs(cases) do + assert.are.equal(case.expected, WeightedScore.weightsRequireFullDPS(case.weights), case.label) + end + end) +end) + +describe("WeightedScore — tree integration", function() + before_each(function() + newBuild() + end) + + local function findStat(statName) + for _, stat in ipairs(data.powerStatList) do + if stat.stat == statName then return stat end + end + end + + local function drainPowerBuild(stat) + build.calcsTab.powerBuildFlag = true + build.calcsTab.powerStat = stat + build.calcsTab.nodePowerMaxDepth = 1 + local iterations = 0 + repeat + build.calcsTab:BuildPower() + iterations = iterations + 1 + until not build.calcsTab.powerBuilder or iterations >= 1000 + assert.is_nil(build.calcsTab.powerBuilder, "depth-1 Power Builder must finish within 1000 steps") + end + + it("registers WeightedScore as the final shared non-minion power stat", function() + local stat = findStat("WeightedScore") + assert.is_not_nil(stat) + assert.are.equal("WeightedScore", data.powerStatList[#data.powerStatList].stat) + assert.is_nil(findStat("MinionWeightedScore")) + end) + + it("power report requests FullDPS for WeightedScore when active weights use FullDPS", function() + local stat = findStat("WeightedScore") + assert.is_not_nil(stat) + + local originalGetMiscCalculator = build.calcsTab.GetMiscCalculator + local calledUseFullDPS = { } + build.calcsTab.GetMiscCalculator = function() + local function calcFunc(_, useFullDPS) + calledUseFullDPS[#calledUseFullDPS + 1] = useFullDPS + return { + FullDPS = 110, + TotalEHP = 100, + CombinedDPS = 0, + TotalDPS = 0, + TotalDotDPS = 0, + } + end + return calcFunc, { + FullDPS = 100, + TotalEHP = 100, + CombinedDPS = 0, + TotalDPS = 0, + TotalDotDPS = 0, + } + end + + drainPowerBuild(stat) + build.calcsTab.GetMiscCalculator = originalGetMiscCalculator + + assert.is_true(#calledUseFullDPS > 0, "fixture should exercise candidate calculations") + for _, useFullDPS in ipairs(calledUseFullDPS) do + assert.is_true(useFullDPS) + end + end) + + it("power stat helpers keep positive WeightedScore deltas and baselines on the same scale", function() + local weightedScore = findStat("WeightedScore") + local fullDPS = findStat("FullDPS") + local life = findStat("Life") + local baseOutput = { FullDPS = 100, TotalEHP = 100, TotalDPS = 0, TotalDotDPS = 0, CombinedDPS = 0 } + local betterOutput = { FullDPS = 120, TotalEHP = 100, TotalDPS = 0, TotalDotDPS = 0, CombinedDPS = 0 } + + assert.is_true(data.powerStatList.RequiresFullDPS(weightedScore, build)) + assert.is_true(data.powerStatList.RequiresFullDPS(fullDPS, build)) + assert.is_false(data.powerStatList.RequiresFullDPS(life, build)) + local baseValue = data.powerStatList.GetValue(baseOutput, weightedScore, build, baseOutput) + local betterValue = data.powerStatList.GetValue(betterOutput, weightedScore, build, baseOutput) + local delta = build.calcsTab:CalculatePowerStat(weightedScore, betterOutput, baseOutput) + assert.is_true(math.abs(baseValue - 1500) < 0.0001) + assert.is_true(math.abs(betterValue - 1700) < 0.0001) + assert.is_true(betterValue > baseValue) + assert.is_true(math.abs(delta - 200) < 0.0001) + assert.is_true(math.abs(delta / baseValue - 2 / 15) < 0.0001) + assert.are.equal(123, data.powerStatList.GetValue({ Life = 123 }, life, build, baseOutput)) + build.itemsTab.tradeQuery.statSortSelectionList = { { stat = "TotalEHP", weightMult = 1 } } + assert.is_false(data.powerStatList.RequiresFullDPS(weightedScore, build)) + end) + + it("getValue on WeightedScore entry reuses provided calcBase", function() + local stat = findStat("WeightedScore") + assert.is_not_nil(stat) + assert.is_function(stat.getValue) + + local originalGetMiscCalculator = build.calcsTab.GetMiscCalculator + local getMiscCalculatorCalls = 0 + build.calcsTab.GetMiscCalculator = function() + getMiscCalculatorCalls = getMiscCalculatorCalls + 1 + return function() + return { FullDPS = 1, TotalEHP = 1 } + end, { FullDPS = 1, TotalEHP = 1 } + end + + local score = stat.getValue( + { FullDPS = 120, TotalEHP = 100, TotalDPS = 0, TotalDotDPS = 0, CombinedDPS = 0 }, + build, + { FullDPS = 100, TotalEHP = 100, TotalDPS = 0, TotalDotDPS = 0, CombinedDPS = 0 } + ) + build.calcsTab.GetMiscCalculator = originalGetMiscCalculator + + assert.are.equal(0, getMiscCalculatorCalls) + assert.is_true(score > 0) + end) + + local function buildWithWeightEditor(openEditor) + return { itemsTab = { tradeQuery = { + SetStatWeights = function(_, previousSelection, onSave) + openEditor(previousSelection, onSave) + end, + } } } + end + + it("invalidates cached candidate scores after editing weights", function() + local list = { + { label = "Default", stat = nil }, + { label = "Weighted Score", stat = "WeightedScore" }, + } + local candidates = { + { label = "Damage", scores = { damage = 2, defence = 1 } }, + { label = "Defence", scores = { damage = 1, defence = 2 } }, + } + local weight = "damage" + local controls = { + sort = { + SelByValue = function() end, + }, + } + local function applySort(stat) + for _, candidate in ipairs(candidates) do + candidate.sortValues = candidate.sortValues or { } + candidate.sortValue = candidate.sortValues[stat] or candidate.scores[weight] + candidate.sortValues[stat] = candidate.sortValue + end + table.sort(candidates, function(a, b) return a.sortValue > b.sortValue end) + end + local function clearSortValues() + for _, candidate in ipairs(candidates) do + candidate.sortValues = nil + end + end + local build = buildWithWeightEditor(function(_, onSave) + weight = "defence" + onSave() + end) + local handler = WeightedScore.createSortHandler(list, controls, build, applySort, clearSortValues) + + handler(2, list[2]) + assert.are.equal("Damage", candidates[1].label) + handler(3, list[3]) + assert.are.equal("Defence", candidates[1].label) + end) +end) + +describe("WeightedScore — report invalidation", function() + before_each(function() + newBuild() + end) + + it("invalidates the selected Compare Power report after editing weights", function() + local compareTab = build.compareTab + local control = compareTab.controls.comparePowerStatSelect + local weightedIndex + for index, entry in ipairs(control.list) do + if entry.stat == "WeightedScore" then + weightedIndex = index + break + end + end + build.itemsTab.tradeQuery.SetStatWeights = function(_, _, onSave) + onSave() + end + + control:SetSel(weightedIndex) + compareTab.comparePowerDirty = false + control:SetSel(weightedIndex + 1) + + assert.is_true(compareTab.comparePowerDirty) + end) +end) + +describe("WeightedScore — crafted affix sorting", function() + local originalGetMiscCalculator + + before_each(function() + newBuild() + originalGetMiscCalculator = build.calcsTab.GetMiscCalculator + end) + + after_each(function() + build.calcsTab.GetMiscCalculator = originalGetMiscCalculator + end) + + it("sorts crafted affixes against the displayed item", function() + local itemsTab = build.itemsTab + itemsTab:CreateDisplayItemFromRaw([[ +Rarity: RARE +Weighted Sort Helmet +Royal Burgonet +Item Level: 86 +Crafted: true +Prefix: {range:0.5}IncreasedLife6 +Prefix: None +Prefix: None +Suffix: None +Suffix: None +Suffix: None +Quality: 20 +Implicits: 0 ++65 to maximum Life +]]) + itemsTab.tradeQuery.statSortSelectionList = { + { stat = "FullDPS", label = "Full DPS", weightMult = 1 }, + { stat = "TotalEHP", label = "Effective Hit Pool", weightMult = 1 }, + } + itemsTab.controls.craftingSorting:SelByValue("WeightedScore", "stat") + + local calcCount = 0 + build.calcsTab.GetMiscCalculator = function() + return function(params) + calcCount = calcCount + 1 + local item = params and params.repItem + local modCount = item and #item.explicitModLines or 0 + if item == itemsTab.displayItem then + return { FullDPS = 200, TotalEHP = 100 } + elseif modCount >= 2 then + return { FullDPS = 180, TotalEHP = 120 } + elseif modCount == 1 then + return { FullDPS = 150, TotalEHP = 140 } + end + return { FullDPS = 100, TotalEHP = 100 } + end + end + + local control = itemsTab.controls.displayItemAffix1 + itemsTab:UpdateAffixControl( + control, + itemsTab.displayItem, + "Prefix", + "prefixes", + 1, + { } + ) + + assert.is_true(calcCount > 0) + assert.is_not_nil(control.list[2].modList) + local highestScoredMod = itemsTab.displayItem.affixes[control.list[2].modList[1]] + assert.are.equal(1, #highestScoredMod, "the best modifier for the displayed item must sort first") + end) +end) diff --git a/src/Classes/CalcsTab.lua b/src/Classes/CalcsTab.lua index 95386e5f20f..102909fa1ae 100644 --- a/src/Classes/CalcsTab.lua +++ b/src/Classes/CalcsTab.lua @@ -495,7 +495,7 @@ end -- Estimate the offensive and defensive power of all unallocated nodes function CalcsTabClass:PowerBuilder() -- local timer_start = GetTime() - local useFullDPS = self.powerStat and self.powerStat.stat == "FullDPS" + local useFullDPS = self.powerStat and data.powerStatList.RequiresFullDPS(self.powerStat, self.build) local calcFunc, calcBase = self:GetMiscCalculator() local cache = { } local distanceMap = { } @@ -740,8 +740,8 @@ function CalcsTabClass:PowerBuilder() end function CalcsTabClass:CalculatePowerStat(selection, original, modified) - local originalValue = data.powerStatList.GetFromOutput(original, selection) - local modifiedValue = data.powerStatList.GetFromOutput(modified, selection) + local originalValue = data.powerStatList.GetValue(original, selection, self.build, modified) + local modifiedValue = data.powerStatList.GetValue(modified, selection, self.build, modified) return originalValue - modifiedValue end diff --git a/src/Classes/CompareTab.lua b/src/Classes/CompareTab.lua index 7682fe7b02d..ce5450d0a4c 100644 --- a/src/Classes/CompareTab.lua +++ b/src/Classes/CompareTab.lua @@ -15,6 +15,7 @@ local calcsHelpers = require("Classes.CompareCalcsHelpers") local buildListHelpers = require("Modules.BuildListHelpers") local itemSlotHelper = require("Modules.ItemSlotHelper") local configVisibility = require("Modules.ConfigVisibility") +local WeightedScore = require("Modules.WeightedScore") -- Node IDs below this value are normal passive tree nodes; IDs at or above are cluster jewel nodes local CLUSTER_NODE_OFFSET = 65536 @@ -977,8 +978,18 @@ function CompareTabClass:InitControls() t_insert(powerStatList, entry) end end + WeightedScore.appendEditWeightsAction(powerStatList, function() + self.controls.comparePowerStatSelect:SelByValue(self.comparePowerStat and self.comparePowerStat.stat, "stat") + WeightedScore.editWeights(self.primaryBuild, function() + if self.comparePowerStat and self.comparePowerStat.stat == "WeightedScore" then + self.comparePowerDirty = true + end + end) + end) self.controls.comparePowerStatSelect = new("DropDownControl"):DropDownControl(nil, {0, 0, 200, 20}, powerStatList, function(index, value) - if value and value.stat and value ~= self.comparePowerStat then + if value and value.action then + value.action() + elseif value and value.stat and value ~= self.comparePowerStat then self.comparePowerStat = value self.comparePowerDirty = true elseif value and not value.stat then @@ -2515,10 +2526,17 @@ end -- Coroutine: calculate power of compared build elements against primary build function CompareTabClass:ComparePowerBuilder(compareEntry, powerStat, categories) local results = {} - local useFullDPS = powerStat.stat == "FullDPS" + local useFullDPS = data.powerStatList.RequiresFullDPS(powerStat, self.primaryBuild) + local function getPowerCalculator() + local calcFunc, calcBase = self.calcs.getMiscCalculator(self.primaryBuild) + if useFullDPS then + calcBase = calcFunc(nil, true) + end + return calcFunc, calcBase + end -- Get calculator for primary build - local calcFunc, calcBase = self.calcs.getMiscCalculator(self.primaryBuild) + local calcFunc, calcBase = getPowerCalculator() -- Find display stat for formatting local displayStat = nil @@ -2621,7 +2639,7 @@ function CompareTabClass:ComparePowerBuilder(compareEntry, powerStat, categories end -- Get baseline stat value for percentage calculation - local baseStatValue = data.powerStatList.GetFromOutput(calcBase, powerStat) + local baseStatValue = data.powerStatList.GetValue(calcBase, powerStat, self.primaryBuild, calcBase) -- Helper to format an impact value and compute percentage local function formatImpact(impact) @@ -2917,9 +2935,7 @@ function CompareTabClass:ComparePowerBuilder(compareEntry, powerStat, categories self.primaryBuild.buildFlag = true -- Get a fresh calculator with the added group (pcall to guarantee cleanup) - local ok, gemCalcFunc, gemCalcBase = pcall(function() - return self.calcs.getMiscCalculator(self.primaryBuild) - end) + local ok, gemCalcFunc, gemCalcBase = pcall(getPowerCalculator) -- Always remove the temporarily added group t_remove(pGroups) @@ -3000,9 +3016,7 @@ function CompareTabClass:ComparePowerBuilder(compareEntry, powerStat, categories t_insert(pMainGroup.gemList, tempGem) self.primaryBuild.buildFlag = true - local ok, sgCalcFunc, sgCalcBase = pcall(function() - return self.calcs.getMiscCalculator(self.primaryBuild) - end) + local ok, sgCalcFunc, sgCalcBase = pcall(getPowerCalculator) -- Always remove the temporarily added gem t_remove(pMainGroup.gemList) @@ -3070,7 +3084,7 @@ function CompareTabClass:ComparePowerBuilder(compareEntry, powerStat, categories local ok, cfgCalcFunc, cfgCalcBase = pcall(function() self.primaryBuild.configTab:BuildModList() self.primaryBuild.buildFlag = true - return self.calcs.getMiscCalculator(self.primaryBuild) + return getPowerCalculator() end) -- Always restore original value diff --git a/src/Classes/ItemDBControl.lua b/src/Classes/ItemDBControl.lua index d8f650450b3..1903ea29e62 100644 --- a/src/Classes/ItemDBControl.lua +++ b/src/Classes/ItemDBControl.lua @@ -8,6 +8,7 @@ local ipairs = ipairs local t_insert = table.insert local m_max = math.max local m_floor = math.floor +local WeightedScore = require("Modules.WeightedScore") ---@class ItemDBControl: ListControl @@ -52,7 +53,12 @@ function ItemDBClass:ItemDBControl(anchor, rect, itemsTab, db, dbType) end) if dbType == "UNIQUE" then self.controls.sort = new("DropDownControl"):DropDownControl({"BOTTOMLEFT",self,"TOPLEFT"}, {0, baseY + 20, 179, 18}, self.sortDropList, function(index, value) - self:SetSortMode(value.sortMode) + if value.action then + value.action() + self.controls.sort:SelByValue(self.sortMode, "sortMode") + else + self:SetSortMode(value.sortMode) + end end) self.controls.league = new("DropDownControl"):DropDownControl({"LEFT",self.controls.sort,"RIGHT"}, {2, 0, 179, 18}, self.leagueList, function(index, value) self.listBuildFlag = true @@ -231,9 +237,14 @@ function ItemDBClass:BuildSortOrder() itemField=stat.itemField, stat=stat.stat, transform=stat.transform, + requiresFullDPS=stat.requiresFullDPS, + getValue=stat.getValue, }) end end + WeightedScore.appendEditWeightsAction(self.sortDropList, function() + WeightedScore.editWeights(self.itemsTab.build, function() self.listBuildFlag = true end) + end) wipeTable(self.sortOrder) if self.controls.sort then self.controls.sort:CheckDroppedWidth(true) @@ -256,7 +267,7 @@ function ItemDBClass:ListBuilder() end if self.sortDetail and self.sortDetail.stat then -- stat-based - local useFullDPS = self.sortDetail.stat == "FullDPS" + local useFullDPS = data.powerStatList.RequiresFullDPS(self.sortDetail, self.itemsTab.build) local start = GetTime() local calcFunc, calcBase = self.itemsTab.build.calcsTab:GetMiscCalculator(self.build) for itemIndex, item in ipairs(list) do @@ -264,7 +275,7 @@ function ItemDBClass:ListBuilder() for slotName, slot in pairs(self.itemsTab.slots) do if self.itemsTab:IsItemValidForSlot(item, slotName) and not slot.inactive and (not slot.weaponSet or slot.weaponSet == (self.itemsTab.activeItemSet.useSecondWeaponSet and 2 or 1)) and slot.shown() then local output = calcFunc(item.base.flask and { toggleFlask = item } or item.base.tincture and { toggleTincture = item } or { repSlotName = slotName, repItem = item }, useFullDPS) - local measuredPower = data.powerStatList.GetFromOutput(output, self.sortDetail) + local measuredPower = data.powerStatList.GetValue(output, self.sortDetail, self.itemsTab.build, calcBase) item.measuredPower = m_max(item.measuredPower, measuredPower) end end diff --git a/src/Classes/ItemsTab.lua b/src/Classes/ItemsTab.lua index b4db34b2473..728bd91785b 100644 --- a/src/Classes/ItemsTab.lua +++ b/src/Classes/ItemsTab.lua @@ -18,6 +18,7 @@ local m_modf = math.modf local buySimilar = require("Classes.CompareBuySimilar") local addImplicit = require("Modules.AddImplicitPopup") local gemTooltip = require("Classes.GemTooltip") +local WeightedScore = require("Modules.WeightedScore") local rarityDropList = { { label = colorCodes.NORMAL.."Normal", rarity = "NORMAL" }, @@ -665,6 +666,13 @@ holding Shift will put it in the second.]]) table.insert(sortingOptions, option) end end + local activeCraftingSort = sortingOptions[1] + WeightedScore.appendEditWeightsAction(sortingOptions, function() + self.controls.craftingSorting:SelByValue(activeCraftingSort.stat, "stat") + WeightedScore.editWeights(self.build, function() + self:UpdateAffixControls() + end) + end) -- Section: Catalysts self.controls.displayItemSectionCatalyst = new("Control"):Control({"TOPLEFT",self.controls.displayItemSectionQuality,"BOTTOMLEFT"}, {0, 0, 0, function() return (self.controls.displayItemCatalyst:IsShown() or self.controls.displayItemCatalystQualityEdit:IsShown()) and 28 or 0 @@ -739,8 +747,13 @@ holding Shift will put it in the second.]]) -- cluster jewels don't have good comparison support and sorting would be misleading not (self.displayItem.base.type == "Jewel" and self.displayItem.base.subType == "Cluster") end - self.controls.craftingSorting = new("DropDownControl"):DropDownControl({ "LEFT", self.controls.craftingSortingLabel, "RIGHT" }, { 4, 0, 200, 20 }, sortingOptions, function() - self:UpdateAffixControls() + self.controls.craftingSorting = new("DropDownControl"):DropDownControl({ "LEFT", self.controls.craftingSortingLabel, "RIGHT" }, { 4, 0, 200, 20 }, sortingOptions, function(index, value) + if value.action then + value.action() + else + activeCraftingSort = value + self:UpdateAffixControls() + end end) -- Section: Affix Selection @@ -2384,6 +2397,7 @@ function ItemsTabClass:UpdateAffixControl(control, item, affixType, outputTable, if sortOption.stat and self.controls.craftingSortingLabel.shown() then local calcFunc = self.build.calcsTab:GetMiscCalculator() local slotName = self:GetComparisonSlotNameForItem(self.displayItem, true) + local useFullDPS = data.powerStatList.RequiresFullDPS(sortOption, self.build) local testSubject = new("Item"):Item(self.displayItem:BuildRaw()) local controlPowerCache = powerCache if selAffix and selAffix ~= "None" then @@ -2391,6 +2405,9 @@ function ItemsTabClass:UpdateAffixControl(control, item, affixType, outputTable, testSubject:Craft() controlPowerCache = { } end + -- Contextual stats use the displayed item as their reference; testSubject only builds replacement candidates. + local calcBase = sortOption.getValue + and calcFunc({ repSlotName = slotName, repItem = self.displayItem }, useFullDPS) local function pickModifierFromList(modList) -- pick mid tier modifier from a group if #modList == 1 then @@ -2422,9 +2439,11 @@ function ItemsTabClass:UpdateAffixControl(control, item, affixType, outputTable, t_insert(testSubject.explicitModLines, modLine) end testSubject:BuildAndParseRaw() - power = data.powerStatList.GetFromOutput( - calcFunc({ repSlotName = slotName, repItem = testSubject }), - sortOption + power = data.powerStatList.GetValue( + calcFunc({ repSlotName = slotName, repItem = testSubject }, useFullDPS), + sortOption, + self.build, + calcBase ) testSubject = new("Item"):Item(originalItem) else @@ -2439,9 +2458,11 @@ function ItemsTabClass:UpdateAffixControl(control, item, affixType, outputTable, end testSubject:BuildModList() - power = data.powerStatList.GetFromOutput( - calcFunc({ repSlotName = slotName, repItem = testSubject }), - sortOption + power = data.powerStatList.GetValue( + calcFunc({ repSlotName = slotName, repItem = testSubject }, useFullDPS), + sortOption, + self.build, + calcBase ) for _ = 1, modCount do t_remove(testSubject.explicitModLines, #testSubject.explicitModLines) @@ -2945,7 +2966,7 @@ function ItemsTabClass:EnchantDisplayItem(enchantSlot) item:BuildAndParseRaw() return item end - local function getSortValue(entry, stat, calcFunc, slotName, useFullDPS) + local function getSortValue(entry, stat, calcFunc, calcBase, slotName, useFullDPS) entry.sortValues = entry.sortValues or { } if entry.sortValues[stat] ~= nil then return entry.sortValues[stat] @@ -2967,7 +2988,7 @@ function ItemsTabClass:EnchantDisplayItem(enchantSlot) end item:BuildAndParseRaw() local output = calcFunc({ repSlotName = slotName, repItem = item }, useFullDPS) - local value = data.powerStatList.GetFromOutput(output, sortStats[stat]) + local value = data.powerStatList.GetValue(output, sortStats[stat], self.build, calcBase) entry.sortValues[stat] = value return value end @@ -2979,9 +3000,10 @@ function ItemsTabClass:EnchantDisplayItem(enchantSlot) if stat then local slotName = self:GetComparisonSlotNameForItem(self.displayItem, true) local calcFunc = self.build.calcsTab:GetMiscCalculator() - local useFullDPS = stat == "FullDPS" + local useFullDPS = data.powerStatList.RequiresFullDPS(sortStats[stat], self.build) + local calcBase = calcFunc({ repSlotName = slotName, repItem = self.displayItem }, useFullDPS) for _, entry in ipairs(enchantmentList) do - entry.sortValue = getSortValue(entry, stat, calcFunc, slotName, useFullDPS) + entry.sortValue = getSortValue(entry, stat, calcFunc, calcBase, slotName, useFullDPS) end table.sort(enchantmentList, function(a, b) if a.sortValue ~= b.sortValue then @@ -3006,6 +3028,12 @@ function ItemsTabClass:EnchantDisplayItem(enchantSlot) controls.enchantment:SetSel(1, true) end end + local function clearSortValues() + for _, entry in ipairs(enchantmentList) do + entry.sortValue = nil + entry.sortValues = nil + end + end if haveSkills then controls.skillLabel = new("LabelControl"):LabelControl({"TOPRIGHT",nil,"TOPLEFT"}, {95, 20, 0, 16}, "^7Skill:") controls.skill = new("DropDownControl"):DropDownControl({"TOPLEFT",nil,"TOPLEFT"}, {100, 20, 180, 18}, skillList, function(index, value) @@ -3040,9 +3068,8 @@ function ItemsTabClass:EnchantDisplayItem(enchantSlot) end end) controls.sortLabel = new("LabelControl"):LabelControl({"TOPRIGHT",nil,"TOPLEFT"}, {350, 45, 0, 16}, "^7Sort by:") - controls.sort = new("DropDownControl"):DropDownControl({"TOPLEFT",nil,"TOPLEFT"}, {355, 45, 240, 18}, sortList, function(index, value) - applySort(value.stat, true) - end) + controls.sort = new("DropDownControl"):DropDownControl({"TOPLEFT",nil,"TOPLEFT"}, {355, 45, 240, 18}, sortList, + WeightedScore.createSortHandler(sortList, controls, self.build, applySort, clearSortValues)) controls.enchantmentLabel = new("LabelControl"):LabelControl({"TOPRIGHT",nil,"TOPLEFT"}, {95, 70, 0, 16}, "^7Enchantment:") controls.enchantment = new("DropDownControl"):DropDownControl({"TOPLEFT",nil,"TOPLEFT"}, {100, 70, 495, 18}, enchantmentList) controls.enchantment.tooltipFunc = function(tooltip, mode, index) @@ -3321,7 +3348,7 @@ function ItemsTabClass:CorruptDisplayItem() control:SelByValue(entry.val, "mod") end end - local function getSortValue(entry, modType, stat, calcFunc, slotName, useFullDPS) + local function getSortValue(entry, modType, stat, calcFunc, calcBase, slotName, useFullDPS) entry.sortValues = entry.sortValues or { } if entry.sortValues[stat] ~= nil then return entry.sortValues[stat] @@ -3342,17 +3369,17 @@ function ItemsTabClass:CorruptDisplayItem() end item:BuildAndParseRaw() local output = calcFunc({ repSlotName = slotName, repItem = item }, useFullDPS) - local value = data.powerStatList.GetFromOutput(output, sortStats[stat]) + local value = data.powerStatList.GetValue(output, sortStats[stat], self.build, calcBase) entry.sortValues[stat] = value return value end - local function sortModType(modType, stat, calcFunc, slotName, useFullDPS) + local function sortModType(modType, stat, calcFunc, calcBase, slotName, useFullDPS) if not implicitList[modType] then return end if stat then for _, entry in ipairs(implicitList[modType]) do - entry.sortValue = getSortValue(entry, modType, stat, calcFunc, slotName, useFullDPS) + entry.sortValue = getSortValue(entry, modType, stat, calcFunc, calcBase, slotName, useFullDPS) end table.sort(implicitList[modType], function(a, b) if a.sortValue ~= b.sortValue then @@ -3372,12 +3399,13 @@ function ItemsTabClass:CorruptDisplayItem() end local slotName = self:GetComparisonSlotNameForItem(self.displayItem, true) local calcFunc = stat and self.build.calcsTab:GetMiscCalculator() or nil - local useFullDPS = stat == "FullDPS" + local useFullDPS = stat and data.powerStatList.RequiresFullDPS(sortStats[stat], self.build) + local calcBase = stat and calcFunc({ repSlotName = slotName, repItem = self.displayItem }, useFullDPS) if currentModType ~= "ScourgeUpside" then - sortModType(currentModType, stat, calcFunc, slotName, useFullDPS) + sortModType(currentModType, stat, calcFunc, calcBase, slotName, useFullDPS) else - sortModType("ScourgeUpside", stat, calcFunc, slotName, useFullDPS) - sortModType("ScourgeDownside", stat, calcFunc, slotName, useFullDPS) + sortModType("ScourgeUpside", stat, calcFunc, calcBase, slotName, useFullDPS) + sortModType("ScourgeDownside", stat, calcFunc, calcBase, slotName, useFullDPS) end if currentModType ~= "ScourgeUpside" then buildCorruptLists(currentModType) @@ -3392,6 +3420,14 @@ function ItemsTabClass:CorruptDisplayItem() control:UpdateSearch() end end + local function clearSortValues() + for _, entries in pairs(implicitList) do + for _, entry in ipairs(entries) do + entry.sortValue = nil + entry.sortValues = nil + end + end + end local function corruptItem(addingImplicits) local item = new("Item"):Item(self.displayItem:BuildRaw()) item.id = self.displayItem.id @@ -3557,9 +3593,8 @@ function ItemsTabClass:CorruptDisplayItem() end) controls.source.enabled = #sourceList > 1 controls.sortLabel = new("LabelControl"):LabelControl({"TOPRIGHT",nil,"TOPLEFT"}, {350, 20, 0, 16}, "^7Sort by:") - controls.sort = new("DropDownControl"):DropDownControl({"TOPLEFT",nil,"TOPLEFT"}, {355, 20, 240, 18}, sortList, function(index, value) - applySort(value.stat) - end) + controls.sort = new("DropDownControl"):DropDownControl({"TOPLEFT",nil,"TOPLEFT"}, {355, 20, 240, 18}, sortList, + WeightedScore.createSortHandler(sortList, controls, self.build, applySort, clearSortValues)) local implicitRowSize = 20 local implicitYPos = 35 controls.implicitCannotBeChangedLabel = new("LabelControl"):LabelControl({ "TOPLEFT", nil, "TOPLEFT" }, { 20, implicitYPos + implicitRowSize, 0, 20 }, "^7This Items Implicits Cannot Be Changed") @@ -3631,7 +3666,7 @@ function ItemsTabClass:AddCustomModifierToDisplayItem() listMod.sortValues = nil end end - local function getSortValue(listMod, stat, calcFunc, slotName, useFullDPS) + local function getSortValue(listMod, stat, calcFunc, calcBase, slotName, useFullDPS) listMod.sortValues = listMod.sortValues or { } if listMod.sortValues[stat] ~= nil then return listMod.sortValues[stat] @@ -3643,7 +3678,7 @@ function ItemsTabClass:AddCustomModifierToDisplayItem() end item:BuildAndParseRaw() local output = calcFunc({ repSlotName = slotName, repItem = item }, useFullDPS) - local value = data.powerStatList.GetFromOutput(output, sortStats[stat]) + local value = data.powerStatList.GetValue(output, sortStats[stat], self.build, calcBase) listMod.sortValues[stat] = value return value end @@ -3655,9 +3690,10 @@ function ItemsTabClass:AddCustomModifierToDisplayItem() if stat then local slotName = self:GetComparisonSlotNameForItem(self.displayItem, true) local calcFunc = self.build.calcsTab:GetMiscCalculator() - local useFullDPS = stat == "FullDPS" + local useFullDPS = data.powerStatList.RequiresFullDPS(sortStats[stat], self.build) + local calcBase = calcFunc({ repSlotName = slotName, repItem = self.displayItem }, useFullDPS) for _, listMod in ipairs(modList) do - listMod.sortValue = getSortValue(listMod, stat, calcFunc, slotName, useFullDPS) + listMod.sortValue = getSortValue(listMod, stat, calcFunc, calcBase, slotName, useFullDPS) end table.sort(modList, function(a, b) if a.sortValue ~= b.sortValue then @@ -3682,6 +3718,12 @@ function ItemsTabClass:AddCustomModifierToDisplayItem() controls.modSelect:SetSel(1, true) end end + local function clearSortValues() + for _, listMod in ipairs(modList) do + listMod.sortValue = nil + listMod.sortValues = nil + end + end local function buildDropRestricted(baseCategories, modDb) local base = self.displayItem.base local subTypeName = base.subType and base.type .. ": " .. base.subType @@ -3934,9 +3976,8 @@ function ItemsTabClass:AddCustomModifierToDisplayItem() controls.sortLabel.shown = function() return sourceList[controls.source.selIndex].sourceId ~= "CUSTOM" end - controls.sort = new("DropDownControl"):DropDownControl({"TOPLEFT",nil,"TOPLEFT"}, {355, 20, 240, 18}, sortList, function(index, value) - applySort(value.stat, true) - end) + controls.sort = new("DropDownControl"):DropDownControl({"TOPLEFT",nil,"TOPLEFT"}, {355, 20, 240, 18}, sortList, + WeightedScore.createSortHandler(sortList, controls, self.build, applySort, clearSortValues)) controls.sort.shown = function() return sourceList[controls.source.selIndex].sourceId ~= "CUSTOM" end diff --git a/src/Classes/NotableDBControl.lua b/src/Classes/NotableDBControl.lua index 8253f4a471f..4f4c18565ff 100644 --- a/src/Classes/NotableDBControl.lua +++ b/src/Classes/NotableDBControl.lua @@ -11,6 +11,7 @@ local m_max = math.max local m_floor = math.floor local m_huge = math.huge local s_format = string.format +local WeightedScore = require("Modules.WeightedScore") ---@param node table ---@return boolean @@ -36,7 +37,12 @@ function NotableDBClass:NotableDBControl(anchor, rect, itemsTab, db, dbType) self.sortOrder = { } self.sortMode = "NAME" self.controls.sort = new("DropDownControl"):DropDownControl({"BOTTOMLEFT",self,"TOPLEFT"}, {0, -22, 360, 18}, self.sortDropList, function(index, value) - self:SetSortMode(value.sortMode) + if value.action then + value.action() + self.controls.sort:SelByValue(self.sortMode, "sortMode") + else + self:SetSortMode(value.sortMode) + end end) self.controls.search = new("EditControl"):EditControl({"BOTTOMLEFT",self,"TOPLEFT"}, {0, -2, 258, 18}, "", "Search", "%c", 100, function() self.listBuildFlag = true @@ -99,9 +105,14 @@ function NotableDBClass:BuildSortOrder() itemField=stat.itemField, stat=stat.stat, transform=stat.transform, + requiresFullDPS=stat.requiresFullDPS, + getValue=stat.getValue, }) end end + WeightedScore.appendEditWeightsAction(self.sortDropList, function() + WeightedScore.editWeights(self.itemsTab.build, function() self.listBuildFlag = true end) + end) wipeTable(self.sortOrder) if self.controls.sort then self.controls.sort.selIndex = 1 @@ -115,6 +126,9 @@ function NotableDBClass:BuildSortOrder() end function NotableDBClass:CalculatePowerStat(selection, original, modified) + if selection.getValue then + return data.powerStatList.GetValue(original, selection, self.itemsTab.build, modified) + end local originalValue = data.powerStatList.GetFromOutput(original, selection) local modifiedValue = data.powerStatList.GetFromOutput(modified, selection) return originalValue - modifiedValue @@ -134,12 +148,15 @@ function NotableDBClass:ListBuilder() local start = GetTime() local calcFunc = self.itemsTab.build.calcsTab:GetMiscCalculator() local itemType = self.itemsTab.displayItem.base.type - local calcBase = calcFunc({ repSlotName = itemType, repItem = self.itemsTab:anointItem(nil) }) + local useFullDPS = data.powerStatList.RequiresFullDPS(self.sortDetail, self.itemsTab.build) + -- Contextual stats compare with the displayed item; scalar stats retain the historical no-anoint delta. + local referenceItem = self.sortDetail.getValue and self.itemsTab.displayItem or self.itemsTab:anointItem(nil) + local calcBase = calcFunc({ repSlotName = itemType, repItem = referenceItem }, useFullDPS) self.sortMaxPower = 0 for nodeIndex, node in ipairs(list) do node.measuredPower = 0 if node.modKey ~= "" then - local output = calcFunc({ repSlotName = itemType, repItem = self.itemsTab:anointItem(node) }) + local output = calcFunc({ repSlotName = itemType, repItem = self.itemsTab:anointItem(node) }, useFullDPS) node.measuredPower = self:CalculatePowerStat(self.sortDetail, output, calcBase) if node.measuredPower == m_huge then t_insert(infinites, node) diff --git a/src/Classes/TradeQuery.lua b/src/Classes/TradeQuery.lua index eeefec021f7..1b3ad0eb471 100644 --- a/src/Classes/TradeQuery.lua +++ b/src/Classes/TradeQuery.lua @@ -8,6 +8,7 @@ local dkjson = require "dkjson" local itemSlotHelper = require("Modules.ItemSlotHelper") local tradeHelpers = require("Classes.TradeHelpers") +local WeightedScore = require("Modules.WeightedScore") local get_time = os.time local t_insert = table.insert @@ -257,23 +258,24 @@ function TradeQueryClass:PullCXData() end local function initStatSortSelectionList(list) - t_insert(list, { - label = "Full DPS", - stat = "FullDPS", - weightMult = 1.0, - }) - t_insert(list, { - label = "Effective Hit Pool", - stat = "TotalEHP", - weightMult = 0.5, - }) + for _, weight in ipairs(WeightedScore.defaultWeights()) do + t_insert(list, weight) + end end -- we do not want to overwrite previous list if the new list is the default, e.g. hitting reset multiple times in a row local function isSameAsDefaultList(list) - return list and #list == 2 - and list[1].stat == "FullDPS" and list[1].weightMult == 1.0 - and list[2].stat == "TotalEHP" and list[2].weightMult == 0.5 + local defaultWeights = WeightedScore.defaultWeights() + if not list or #list ~= #defaultWeights then + return false + end + for index, weight in ipairs(defaultWeights) do + local selectedWeight = list[index] + if selectedWeight.stat ~= weight.stat or selectedWeight.weightMult ~= weight.weightMult then + return false + end + end + return true end -- Opens the item pricing popup @@ -689,8 +691,12 @@ Highest Weight - Displays the order retrieved from trade]] end -- Popup to set stat weight multipliers for sorting -function TradeQueryClass:SetStatWeights(previousSelectionList) +function TradeQueryClass:SetStatWeights(previousSelectionList, onSave) previousSelectionList = previousSelectionList or {} + if not self.statSortSelectionList or (#self.statSortSelectionList) == 0 then + self.statSortSelectionList = { } + initStatSortSelectionList(self.statSortSelectionList) + end local controls = { } local statList = { } local sliderController = { index = 1 } @@ -704,7 +710,7 @@ function TradeQueryClass:SetStatWeights(previousSelectionList) { -410, 45, 400, listHeight }, statList, sliderController) for _, stat in ipairs(data.powerStatList) do - if not stat.ignoreForItems and stat.label ~= "Name" then + if not stat.ignoreForItems and stat.label ~= "Name" and stat.stat ~= "WeightedScore" then t_insert(statList, { label = "0 : "..stat.label, stat = { @@ -768,10 +774,12 @@ function TradeQueryClass:SetStatWeights(previousSelectionList) if (#statSortSelectionList) > 0 then --THIS SHOULD REALLY GIVE A WARNING NOT JUST USE PREVIOUS self.statSortSelectionList = statSortSelectionList + self.itemsTab.modFlag = true end for row_idx in pairs(self.resultTbl) do self:UpdateControlsWithItems(row_idx) end + if onSave then onSave() end end) controls.cancel = new("ButtonControl"):ButtonControl({ "BOTTOM", nil, "BOTTOM" }, { 0, -10, 80, 20 }, "Cancel", function() if previousSelectionList and #previousSelectionList > 0 then @@ -789,7 +797,7 @@ function TradeQueryClass:SetStatWeights(previousSelectionList) self.statSortSelectionList = { } initStatSortSelectionList(self.statSortSelectionList) main:ClosePopup() - self:SetStatWeights(previousSelection) + self:SetStatWeights(previousSelection, onSave) end) main:OpenPopup(420, popupHeight, "Stat Weight Multipliers", controls) end diff --git a/src/Classes/TradeQueryGenerator.lua b/src/Classes/TradeQueryGenerator.lua index 097a2e7f948..5ca88b8c0e8 100644 --- a/src/Classes/TradeQueryGenerator.lua +++ b/src/Classes/TradeQueryGenerator.lua @@ -5,6 +5,7 @@ -- local dkjson = require "dkjson" +local WeightedScore = require("Modules.WeightedScore") local curl = require("lcurl.safe") local m_max = math.max local s_format = string.format @@ -162,40 +163,7 @@ function TradeQueryGeneratorClass:TradeQueryGenerator(queryTab) end function TradeQueryGeneratorClass.WeightedRatioOutputs(baseOutput, newOutput, statWeights) - local meanStatDiff = 0 - - local function ratioModSums(...) - local baseModSum = 0 - local newModSum = 0 - for _, mod in ipairs({ ... }) do - baseModSum = baseModSum + data.powerStatList.GetFromOutput(baseOutput, mod, true) - newModSum = newModSum + data.powerStatList.GetFromOutput(newOutput, mod, true) - end - - if baseModSum == math.huge then - return 0 - else - if newModSum == math.huge then - return data.misc.maxStatIncrease - else - return math.min(newModSum / ((baseModSum ~= 0) and baseModSum or 1), data.misc.maxStatIncrease) - end - end - end - for _, statTable in ipairs(statWeights) do - local modSumRatio - if statTable.stat == "FullDPS" and not (baseOutput["FullDPS"] and newOutput["FullDPS"]) then - modSumRatio = ratioModSums({ stat = "TotalDPS" }, { stat = "TotalDotDPS" }, { stat = "CombinedDPS" }) - else - modSumRatio = ratioModSums(statTable) - end - -- some weights, such as damage taken from hit need to be negated as lower is better for them - if statTable.transform then - modSumRatio = statTable.transform(modSumRatio) - end - meanStatDiff = meanStatDiff + modSumRatio * statTable.weightMult - end - return meanStatDiff + return WeightedScore.computeRatioScore(baseOutput, newOutput, statWeights) end function TradeQueryGeneratorClass:ProcessMod(modId, mod, tradeQueryStatsParsed, itemCategoriesMask, itemCategoriesOverride) diff --git a/src/Classes/TreeTab.lua b/src/Classes/TreeTab.lua index 5cce675e443..b10dedf5458 100644 --- a/src/Classes/TreeTab.lua +++ b/src/Classes/TreeTab.lua @@ -16,6 +16,7 @@ local m_floor = math.floor local m_abs = math.abs local s_format = string.format local tradeHelpers = require("Classes.TradeHelpers") +local WeightedScore = require("Modules.WeightedScore") local dkjson = require "dkjson" ---@class TreeTab: ControlHost @@ -253,7 +254,14 @@ function TreeTabClass:TreeTab(build) -- Control for selecting the power stat to sort by (Defense, DPS, etc) self.controls.treeHeatMapStatSelect = new("DropDownControl"):DropDownControl({ "LEFT", self.controls.nodePowerMaxDepthSelect, "RIGHT" }, { 8, 0, 150, 20 }, nil, function(index, value) - self:SetPowerCalc(value) + if value.action then + value.action() + if self.build.calcsTab.powerStat then + self.controls.treeHeatMapStatSelect:SelByValue(self.build.calcsTab.powerStat.stat, "stat") + end + else + self:SetPowerCalc(value) + end end) self.controls.treeHeatMap.tooltipText = function() local offCol, defCol = main.nodePowerTheme:match("(%a+)/(%a+)") @@ -266,6 +274,9 @@ function TreeTabClass:TreeTab(build) t_insert(self.powerStatList, stat) end end + WeightedScore.appendEditWeightsAction(self.powerStatList, function() + WeightedScore.editWeights(self.build, function() self:SetPowerCalc(self.build.calcsTab.powerStat) end) + end) -- Show/Hide Power Report Button self.controls.powerReport = new("ButtonControl"):ButtonControl({ "LEFT", self.controls.treeHeatMapStatSelect, "RIGHT" }, { 8, 0, 150, 20 }, @@ -1950,16 +1961,23 @@ function TreeTabClass:FindTimelessJewel() local function generateFallbackWeights(nodes, powerStat) local calcFunc, calcBase = self.build.calcsTab:GetMiscCalculator(self.build) + local useFullDPS = data.powerStatList.RequiresFullDPS(powerStat, self.build) + if useFullDPS then + calcBase = calcFunc(nil, true) + end local newList = { } - local basePower = data.powerStatList.GetFromOutput(calcBase, powerStat) + local function getStatValue(output) + return data.powerStatList.GetValue(output, powerStat, self.build, calcBase) + end + local basePower = getStatValue(calcBase) for _, newNode in ipairs(nodes) do local powerEntry = { id = newNode.id } -- nodes that have multiple lines are represented as a list in newNode.node local nodeLines = newNode.node or { newNode } for i = 1, #nodeLines do local node = nodeLines[i] - local nodeOutput = calcFunc({ addNodes = { [node] = true } }) - local nodePower = data.powerStatList.GetFromOutput(nodeOutput, powerStat) + local nodeOutput = calcFunc({ addNodes = { [node] = true } }, useFullDPS) + local nodePower = getStatValue(nodeOutput) -- avoid infinity if basePower == 0 then powerEntry["weight" .. i] = 0 @@ -2123,14 +2141,31 @@ function TreeTabClass:FindTimelessJewel() label = "Sort by " .. stat.label, stat = stat.stat, transform = stat.transform, + requiresFullDPS = stat.requiresFullDPS, + getValue = stat.getValue, }) end end - controls.fallbackWeightsList = new("DropDownControl"):DropDownControl({"TOPLEFT", controls.nodeSelect, "BOTTOMLEFT"}, {0, rowSpacing, 200, rowHeight}, fallbackWeightsList, function(index) - timelessData.fallbackWeightMode.idx = index + local selectedFallbackStatIndex = timelessData.fallbackWeightMode.idx or 1 + if not fallbackWeightsList[selectedFallbackStatIndex] then + selectedFallbackStatIndex = 1 + end + local selectedFallbackStat = fallbackWeightsList[selectedFallbackStatIndex] + WeightedScore.appendEditWeightsAction(fallbackWeightsList, function() + controls.fallbackWeightsList:SelByValue(selectedFallbackStat.stat, "stat") + WeightedScore.editWeights(self.build) + end) + controls.fallbackWeightsList = new("DropDownControl"):DropDownControl({"TOPLEFT", controls.nodeSelect, "BOTTOMLEFT"}, {0, rowSpacing, 200, rowHeight}, fallbackWeightsList, function(index, value) + if value.action then + value.action() + else + selectedFallbackStatIndex = index + selectedFallbackStat = value + timelessData.fallbackWeightMode.idx = index + end end) controls.fallbackWeightsLabel = new("LabelControl"):LabelControl({"RIGHT", controls.fallbackWeightsList, "LEFT"}, {-labelSpacing, 0, 0, labelHeight}, "^7Fallback Weight Mode:") - controls.fallbackWeightsList.selIndex = timelessData.fallbackWeightMode.idx or 1 + controls.fallbackWeightsList.selIndex = selectedFallbackStatIndex controls.fallbackWeightsButton = new("ButtonControl"):ButtonControl({"LEFT", controls.fallbackWeightsList, "RIGHT"}, {5, 0, 66, 18}, "Generate", function() setupFallbackWeights() controls.searchListFallbackButton.label = "^4Fallback Nodes" diff --git a/src/Modules/AddImplicitPopup.lua b/src/Modules/AddImplicitPopup.lua index b324c47cddb..1443e98afe0 100644 --- a/src/Modules/AddImplicitPopup.lua +++ b/src/Modules/AddImplicitPopup.lua @@ -1,5 +1,6 @@ local m_max = math.max local t_insert = table.insert +local WeightedScore = require("Modules.WeightedScore") local M = {} @@ -209,7 +210,7 @@ function M.AddImplicitToDisplayItem(itemsTab, displayItem) t_insert(item.implicitModLines, modLine) end end - local function getSortValue(listMod, stat, calcFunc, slotName, useFullDPS) + local function getSortValue(listMod, stat, calcFunc, calcBase, slotName, useFullDPS) listMod.sortValues = listMod.sortValues or {} if listMod.sortValues[stat] ~= nil then return listMod.sortValues[stat] @@ -219,7 +220,7 @@ function M.AddImplicitToDisplayItem(itemsTab, displayItem) applyCandidateMod(item, listMod) item:BuildAndParseRaw() local output = calcFunc({ repSlotName = slotName, repItem = item }, useFullDPS) - local value = data.powerStatList.GetFromOutput(output, sortStats[stat]) + local value = data.powerStatList.GetValue(output, sortStats[stat], itemsTab.build, calcBase) listMod.sortValues[stat] = value return value end @@ -232,10 +233,11 @@ function M.AddImplicitToDisplayItem(itemsTab, displayItem) if stat then local slotName = displayItem:GetPrimarySlot() local calcFunc = itemsTab.build.calcsTab:GetMiscCalculator() - local useFullDPS = stat == "FullDPS" + local useFullDPS = data.powerStatList.RequiresFullDPS(sortStats[stat], itemsTab.build) + local calcBase = calcFunc({ repSlotName = slotName, repItem = displayItem }, useFullDPS) for _, listMods in ipairs(modList) do for _, listMod in ipairs(listMods) do - listMod.sortValue = getSortValue(listMod, stat, calcFunc, slotName, useFullDPS) + listMod.sortValue = getSortValue(listMod, stat, calcFunc, calcBase, slotName, useFullDPS) end table.sort(listMods, function(a, b) if a.sortValue ~= b.sortValue then @@ -293,6 +295,17 @@ function M.AddImplicitToDisplayItem(itemsTab, displayItem) controls.modSelect:SetSel(1, true) end end + local function clearSortValues() + for _, group in ipairs(modGroups) do + group.sortValue = nil + end + for _, listMods in ipairs(modList) do + for _, listMod in ipairs(listMods) do + listMod.sortValue = nil + listMod.sortValues = nil + end + end + end local function addModifier() local item = new("Item"):Item(displayItem:BuildRaw()) item.id = displayItem.id @@ -327,9 +340,8 @@ function M.AddImplicitToDisplayItem(itemsTab, displayItem) controls.sortLabel.shown = function() return sourceList[controls.source.selIndex].sourceId ~= "CUSTOM" end - controls.sort = new("DropDownControl"):DropDownControl({ "TOPLEFT", nil, "TOPLEFT" }, { 355, 20, 240, 18 }, sortList, function(index, value) - applySort(value.stat, true) - end) + controls.sort = new("DropDownControl"):DropDownControl({ "TOPLEFT", nil, "TOPLEFT" }, { 355, 20, 240, 18 }, sortList, + WeightedScore.createSortHandler(sortList, controls, itemsTab.build, applySort, clearSortValues)) controls.sort.shown = function() return sourceList[controls.source.selIndex].sourceId ~= "CUSTOM" end diff --git a/src/Modules/Data.lua b/src/Modules/Data.lua index f83e02f96cd..85cc3459766 100644 --- a/src/Modules/Data.lua +++ b/src/Modules/Data.lua @@ -6,6 +6,7 @@ local dkjson = require("dkjson") LoadModule("Data/Global") +local WeightedScore = require("Modules.WeightedScore") local m_min = math.min local m_max = math.max local m_floor = math.floor @@ -124,12 +125,14 @@ end ---@field ignoreForItems? boolean ---@field reverseSort? boolean ---@field itemField string? +---@field requiresFullDPS? boolean|fun(build?: table): boolean +---@field getValue? fun(output: any, build?: table, calcBase?: table): number ---@type PowerStat[] data.powerStatList = { { stat=nil, label="Offence/Defence", combinedOffDef=true, ignoreForItems=true }, { stat=nil, label="Name", itemField="Name", ignoreForNodes=true, reverseSort=true, transform=function(value) return value:gsub("^The ","") end}, - { stat="FullDPS", label="Full DPS" }, + { stat="FullDPS", label="Full DPS", requiresFullDPS=true }, { stat="CombinedDPS", label="Combined DPS" }, { stat="TotalDPS", label="Hit DPS" }, { stat="WithImpaleDPS", label="Impale + Hit DPS" }, @@ -211,6 +214,28 @@ function data.powerStatList.GetFromOutput(output, statTable, skipTransform) return getEntry() end +---@param output any Calc output +---@param statTable PowerStat Table with stats as in data.powerStatList +---@param build? table Build that owns the candidate calculation +---@param calcBase? table Output of the baseline calculation +---@return number +function data.powerStatList.GetValue(output, statTable, build, calcBase) + if statTable.getValue then + return statTable.getValue(output, build, calcBase) + end + return data.powerStatList.GetFromOutput(output, statTable) +end + +---@param statTable PowerStat Table with stats as in data.powerStatList +---@param build? table Build that owns the candidate calculation +---@return boolean +function data.powerStatList.RequiresFullDPS(statTable, build) + if type(statTable.requiresFullDPS) == "function" then + return statTable.requiresFullDPS(build) + end + return statTable.requiresFullDPS == true +end + -- these stats don't exist on minions or generally don't exist on both player and minion local minionNonApplicableStats = { AverageDamage = true, @@ -224,7 +249,7 @@ local minionNonApplicableStats = { } for i = 1, #data.powerStatList do local statEntry = data.powerStatList[i] - if (not statEntry.stat) or statEntry.stat:match("DPS") or minionNonApplicableStats[statEntry.stat] then + if (not statEntry.stat) or statEntry.stat == "WeightedScore" or statEntry.stat:match("DPS") or minionNonApplicableStats[statEntry.stat] then goto statContinue end local minionStat = copyTable(statEntry) @@ -233,6 +258,19 @@ for i = 1, #data.powerStatList do t_insert(data.powerStatList, minionStat) ::statContinue:: end +t_insert(data.powerStatList, { + stat="WeightedScore", + label="Weighted Score", + requiresFullDPS=function(build) + return WeightedScore.weightsRequireFullDPS(WeightedScore.getWeights(build)) + end, + getValue=function(output, build, calcBase) + local weights = WeightedScore.getWeights(build) + -- Trader multiplies ratio scores by 1000 to create weight points. Reuse it so + -- Calcs/Compare deltas and every ranking or normalization preserve one scale. + return WeightedScore.computeRatioScore(calcBase, output, weights) * 1000 + end, +}) data.misc = { -- magic numbers ServerTickTime = 0.033, ServerTickRate = 1 / 0.033, diff --git a/src/Modules/WeightedScore.lua b/src/Modules/WeightedScore.lua new file mode 100644 index 00000000000..7b5fd10c2df --- /dev/null +++ b/src/Modules/WeightedScore.lua @@ -0,0 +1,121 @@ +-- Path of Building +-- +-- Module: Weighted Score +-- Shared weighted stat score computation and weight management for stat-based ranking. +-- + +local WeightedScore = {} + +-- Default stat weight configuration used when no custom weights are saved. +function WeightedScore.defaultWeights() + return { + { stat = "FullDPS", label = "Full DPS", weightMult = 1.0 }, + { stat = "TotalEHP", label = "Effective Hit Pool", weightMult = 0.5 }, + } +end + +-- Returns the current stat weight list from the build's trade query settings, +-- falling back to defaults if none are configured or the build is not available. +function WeightedScore.getWeights(build) + local tradeQuery = build and build.itemsTab and build.itemsTab.tradeQuery + if tradeQuery and tradeQuery.statSortSelectionList and #tradeQuery.statSortSelectionList > 0 then + return tradeQuery.statSortSelectionList + end + return WeightedScore.defaultWeights() +end + +-- Open the shared Trade Query weight editor. onSave only runs after Save, so +-- consumers can invalidate derived scores without reacting to Cancel. +function WeightedScore.editWeights(build, onSave) + local tradeQuery = build and build.itemsTab and build.itemsTab.tradeQuery + if tradeQuery then + tradeQuery:SetStatWeights(nil, onSave) + end +end + +-- Returns true when any active weight targets FullDPS, so callers can route +-- through the FullDPS-aware calculation path. +function WeightedScore.weightsRequireFullDPS(weights) + for _, statTable in ipairs(weights) do + if statTable.stat == "FullDPS" and statTable.weightMult ~= 0 then + return true + end + end + return false +end + +-- Compute a weighted ratio score comparing newOutput to baseOutput. +-- Each stat contributes: weight * (new output / base output), using the +-- shared power-stat accessor so minion and transformed stats match Trade Query. +-- A neutral candidate (same as base) scores approximately sum(weights). +-- Higher score means the candidate is better. +-- Missing or zero stats are handled safely (no crash, no infinite values). +function WeightedScore.computeRatioScore(baseOutput, newOutput, weights) + local weightedScore = 0.0 + local function computeStatSumRatio(...) + local baseStatSum = 0 + local candidateStatSum = 0 + for _, statTable in ipairs({ ... }) do + baseStatSum = baseStatSum + data.powerStatList.GetFromOutput(baseOutput, statTable, true) + candidateStatSum = candidateStatSum + data.powerStatList.GetFromOutput(newOutput, statTable, true) + end + if baseStatSum == math.huge then + return 0 + elseif candidateStatSum == math.huge then + return data.misc.maxStatIncrease + else + return math.min(candidateStatSum / ((baseStatSum ~= 0) and baseStatSum or 1), data.misc.maxStatIncrease) + end + end + for _, statTable in ipairs(weights) do + local statSumRatio + if statTable.stat == "FullDPS" and not (baseOutput["FullDPS"] and newOutput["FullDPS"]) then + -- FullDPS fallback: use combined DPS components when FullDPS is not directly available + statSumRatio = computeStatSumRatio({ stat = "TotalDPS" }, { stat = "TotalDotDPS" }, { stat = "CombinedDPS" }) + else + statSumRatio = computeStatSumRatio(statTable) + end + if statTable.transform then + statSumRatio = statTable.transform(statSumRatio) + end + weightedScore = weightedScore + statSumRatio * statTable.weightMult + end + return weightedScore +end + +-- Append "Edit Weights..." after WeightedScore so the +-- score remains the final metric while its configuration stays adjacent. +function WeightedScore.appendEditWeightsAction(sortDropList, openEditor) + for _, entry in ipairs(sortDropList) do + if entry.stat == "WeightedScore" then + table.insert(sortDropList, { + label = colorCodes.TIP .. "Edit Weights...", + action = openEditor, + }) + return + end + end +end + +-- Keep the selected metric while opening the editor. Saving clears cached +-- candidate scores before reapplying that metric; cancelling leaves them intact. +function WeightedScore.createSortHandler(sortDropList, controls, build, applySort, clearSortValues) + local activeSort = sortDropList[1] + WeightedScore.appendEditWeightsAction(sortDropList, function() + controls.sort:SelByValue(activeSort.stat, "stat") + WeightedScore.editWeights(build, function() + clearSortValues() + applySort(activeSort.stat, true) + end) + end) + return function(index, value) + if value.action then + value.action() + else + activeSort = value + applySort(value.stat, true) + end + end +end + +return WeightedScore