RynthSuite as of 2026-09-27 (internal 1816d05): AutoVendor (UtilityBelt port), missile/magic facing and arc line of sight, nav waypoint skipping, rebuff batch and item-enchant fixes, crafting fallback, Loot Editor AutoVendor folder and command-line open, release 2026.9.27.2
This commit is contained in:
parent
a19ee1904e
commit
d55ffda4ed
33 changed files with 4364 additions and 207 deletions
94
Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorCommands.cs
vendored
Normal file
94
Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorCommands.cs
vendored
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
using System;
|
||||
using RynthCore.Plugin.RynthAi.Vendor;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>
|
||||
/// UtilityBelt's /ub autovendor and /ub vendor commands. Parsed here (chat thread),
|
||||
/// run by AutoVendorManager on the plugin tick thread.
|
||||
/// </summary>
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
private AutoVendorManager? _autoVendor;
|
||||
|
||||
/// <summary>
|
||||
/// /ub autovendor [cancel|stop|quit|profile]
|
||||
/// /ub vendor {open[p] [name|id|hex|selected] | opencancel | buy[all] | sell[all] |
|
||||
/// clearbuy | clearsell | addbuy[p] [count] item | addsell[p] [count] item}
|
||||
/// Returns false when the verb isn't an AutoVendor verb.
|
||||
/// </summary>
|
||||
private bool TryHandleAutoVendorCommand(string cmd, string fullCommand)
|
||||
{
|
||||
if (cmd != "autovendor" && cmd != "vendor")
|
||||
return false;
|
||||
|
||||
var av = _autoVendor;
|
||||
if (av == null)
|
||||
{
|
||||
ChatLine("[RynthAi] AutoVendor isn't ready yet (log in first).");
|
||||
return true;
|
||||
}
|
||||
|
||||
string rest = AfterWords(fullCommand, 2); // everything after "/ub <verb>"
|
||||
|
||||
if (cmd == "autovendor")
|
||||
{
|
||||
av.Enqueue(() => av.CommandAutoVendor(rest));
|
||||
return true;
|
||||
}
|
||||
|
||||
string action = rest;
|
||||
string args = string.Empty;
|
||||
int asp = rest.IndexOf(' ');
|
||||
if (asp >= 0)
|
||||
{
|
||||
action = rest.Substring(0, asp);
|
||||
args = rest.Substring(asp + 1).Trim();
|
||||
}
|
||||
action = action.ToLowerInvariant();
|
||||
|
||||
switch (action)
|
||||
{
|
||||
case "buy":
|
||||
case "buyall": av.Enqueue(av.CommandBuyAll); break;
|
||||
case "sell":
|
||||
case "sellall": av.Enqueue(av.CommandSellAll); break;
|
||||
case "clearbuy": av.Enqueue(av.CommandClearBuy); break;
|
||||
case "clearsell": av.Enqueue(av.CommandClearSell); break;
|
||||
// UB: "open" with no name picks the nearest vendor, like openp.
|
||||
case "open": av.Enqueue(() => av.CommandOpen(args, partial: args.Length == 0)); break;
|
||||
case "openp": av.Enqueue(() => av.CommandOpen(args, partial: true)); break;
|
||||
case "opencancel": av.Enqueue(av.CommandOpenCancel); break;
|
||||
case "addbuy":
|
||||
case "addbuyp":
|
||||
if (args.Length == 0) { VendorUsage(); break; }
|
||||
av.Enqueue(() => av.CommandAddBuy(args, partial: action == "addbuyp"));
|
||||
break;
|
||||
case "addsell":
|
||||
case "addsellp":
|
||||
if (args.Length == 0) { VendorUsage(); break; }
|
||||
av.Enqueue(() => av.CommandAddSell(args, partial: action == "addsellp"));
|
||||
break;
|
||||
default:
|
||||
VendorUsage();
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The text after the first <paramref name="words"/> space-separated words, trimmed.</summary>
|
||||
private static string AfterWords(string text, int words)
|
||||
{
|
||||
int i = 0;
|
||||
string s = text ?? string.Empty;
|
||||
for (int w = 0; w < words; w++)
|
||||
{
|
||||
while (i < s.Length && char.IsWhiteSpace(s[i])) i++;
|
||||
while (i < s.Length && !char.IsWhiteSpace(s[i])) i++;
|
||||
}
|
||||
return i < s.Length ? s.Substring(i).Trim() : string.Empty;
|
||||
}
|
||||
|
||||
private void VendorUsage()
|
||||
=> ChatLine("[RynthAi] Usage: /ub vendor {open[p] <vendorname,vendorid,vendorhex> | buyall | sellall | clearbuy | clearsell | opencancel | addbuy[p] [count] <item> | addsell[p] [count] <item>}");
|
||||
}
|
||||
1470
Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs
vendored
Normal file
1470
Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs
vendored
Normal file
File diff suppressed because it is too large
Load diff
497
Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs
vendored
Normal file
497
Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs
vendored
Normal file
|
|
@ -0,0 +1,497 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using RynthCore.Loot;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Vendor;
|
||||
|
||||
// Pure planning for AutoVendor, a port of UtilityBelt's AutoVendor.DoVendoring /
|
||||
// GetBuyItems / GetSellItems / ItemIsSafeToGetRidOf / AddItemToSellList. No host calls:
|
||||
// the manager fills these views from the engine's vendor snapshot and the inventory,
|
||||
// executes the plan, waits for the server, and plans again. One transaction per plan,
|
||||
// buying before selling, exactly as UB does.
|
||||
|
||||
/// <summary>The open vendor (engine VendorInfo).</summary>
|
||||
internal sealed class VendorView
|
||||
{
|
||||
public uint Id { get; init; }
|
||||
public string Name { get; init; } = string.Empty;
|
||||
/// <summary>Vendor pays value x BuyRate when you sell.</summary>
|
||||
public float BuyRate { get; init; } = 1f;
|
||||
/// <summary>Vendor charges value x SellRate when you buy.</summary>
|
||||
public float SellRate { get; init; } = 1f;
|
||||
public uint ItemTypes { get; init; }
|
||||
public int MaxValue { get; init; }
|
||||
public bool UsesAltCurrency { get; init; }
|
||||
|
||||
public bool Buys(uint itemType) => (ItemTypes & itemType) != 0;
|
||||
}
|
||||
|
||||
/// <summary>One item on the vendor's list (engine VendorItem).</summary>
|
||||
internal sealed class Listing
|
||||
{
|
||||
public uint Id { get; init; }
|
||||
public string Name { get; init; } = string.Empty;
|
||||
public AcObjectClass Class { get; init; }
|
||||
public uint ItemType { get; init; }
|
||||
/// <summary>How many the vendor has; negative = unlimited.</summary>
|
||||
public int Amount { get; init; } = -1;
|
||||
public int StackSize { get; init; } = 1;
|
||||
public int MaxStackSize { get; init; } = 1;
|
||||
/// <summary>Value of the listed stack.</summary>
|
||||
public int Value { get; init; }
|
||||
/// <summary>Engine's per-unit price at this vendor (0 = unknown).</summary>
|
||||
public int UnitPrice { get; init; }
|
||||
/// <summary>Burden of the listed stack.</summary>
|
||||
public int Burden { get; init; }
|
||||
public bool NeedsContainerSlot { get; init; }
|
||||
|
||||
public bool Unlimited => Amount < 0;
|
||||
public bool IsNote => Class == AcObjectClass.TradeNote || (ItemType & AutoVendorPlanner.ItemTypePromissoryNote) != 0;
|
||||
public int UnitValue => StackSize > 1 ? Value / StackSize : Value;
|
||||
}
|
||||
|
||||
/// <summary>A vendor item the profile wants, with how many (int.MaxValue = all you can afford).</summary>
|
||||
internal sealed class BuyWant
|
||||
{
|
||||
public Listing Item { get; init; } = null!;
|
||||
public int Amount { get; init; }
|
||||
public string RuleName { get; init; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>An inventory item that passed the safety checks and a Sell rule.</summary>
|
||||
internal sealed class SellItem
|
||||
{
|
||||
public uint Id { get; init; }
|
||||
public string Name { get; init; } = string.Empty;
|
||||
public AcObjectClass Class { get; init; }
|
||||
public uint ItemType { get; init; }
|
||||
public int StackSize { get; init; } = 1;
|
||||
/// <summary>Value of the whole stack.</summary>
|
||||
public int Value { get; init; }
|
||||
public string RuleName { get; init; } = string.Empty;
|
||||
public string Location { get; init; } = string.Empty;
|
||||
public int SortSlot { get; init; }
|
||||
|
||||
public bool IsNote => Class == AcObjectClass.TradeNote || (ItemType & AutoVendorPlanner.ItemTypePromissoryNote) != 0;
|
||||
public int UnitValue => StackSize > 1 ? Value / StackSize : Value;
|
||||
}
|
||||
|
||||
/// <summary>Money and room, read fresh before each plan.</summary>
|
||||
internal sealed class PackState
|
||||
{
|
||||
/// <summary>Pyreals, or the vendor's alt currency.</summary>
|
||||
public long Funds { get; init; }
|
||||
/// <summary>Free item slots in the MAIN pack (UB: Weenie(player).FreeSpace).</summary>
|
||||
public int FreeMainSlots { get; init; }
|
||||
public int FreeContainerSlots { get; init; }
|
||||
public int PyrealStackSize { get; init; } = AutoVendorPlanner.DefaultPyrealStackSize;
|
||||
}
|
||||
|
||||
internal enum PlanKind : byte
|
||||
{
|
||||
Done = 0,
|
||||
Buy = 1,
|
||||
Sell = 2,
|
||||
Split = 3,
|
||||
Fatal = 4,
|
||||
}
|
||||
|
||||
internal readonly record struct BuyLine(Listing Item, int Amount);
|
||||
|
||||
internal sealed class VendorPlan
|
||||
{
|
||||
public PlanKind Kind { get; init; }
|
||||
public List<BuyLine> Buys { get; init; } = new();
|
||||
public List<SellItem> Sells { get; init; } = new();
|
||||
/// <summary>Buy: estimated cost. Sell: estimated payout.</summary>
|
||||
public long Total { get; init; }
|
||||
public SellItem? SplitItem { get; init; }
|
||||
public int SplitAmount { get; init; }
|
||||
public string Message { get; init; } = string.Empty;
|
||||
|
||||
public static VendorPlan Done() => new() { Kind = PlanKind.Done };
|
||||
public static VendorPlan Fatal(string msg) => new() { Kind = PlanKind.Fatal, Message = msg };
|
||||
public static VendorPlan Split(SellItem item, int amount, string why) =>
|
||||
new() { Kind = PlanKind.Split, SplitItem = item, SplitAmount = amount, Message = why };
|
||||
}
|
||||
|
||||
/// <summary>What the manager read about an inventory item for UB's "safe to get rid of" checks.</summary>
|
||||
internal sealed class SafetyFacts
|
||||
{
|
||||
/// <summary>Has appraisal data: without it the checks below can't be trusted, so never sell.</summary>
|
||||
public bool Appraised { get; init; }
|
||||
public AcObjectClass Class { get; init; }
|
||||
public int Value { get; init; }
|
||||
/// <summary>ACE IsSellable (69); null = unknown (treated as sellable, like UB's default).</summary>
|
||||
public bool? CanBeSold { get; init; }
|
||||
public bool IsRare { get; init; }
|
||||
public bool InMainPack { get; init; }
|
||||
public bool Equipped { get; init; }
|
||||
public int Attuned { get; init; }
|
||||
public int Bonded { get; init; }
|
||||
public bool Retained { get; init; }
|
||||
public int TimesTinkered { get; init; }
|
||||
public int Imbued { get; init; }
|
||||
public string Inscription { get; init; } = string.Empty;
|
||||
/// <summary>A pack or focus (holds items).</summary>
|
||||
public bool HoldsItems { get; init; }
|
||||
}
|
||||
|
||||
internal static class AutoVendorPlanner
|
||||
{
|
||||
public const int MaxVendorBuyCount = 5000; // UB MAX_VENDOR_BUY_COUNT
|
||||
public const int MaxSellLines = 99; // UB: GDLE rejects 100+ items per transaction
|
||||
public const int DefaultPyrealStackSize = 25000;
|
||||
public const uint PyrealWcid = 273;
|
||||
public const uint ItemTypePromissoryNote = 0x00040000;
|
||||
|
||||
// UB ShopItemListTypes: shop category names for the test-mode report.
|
||||
private static readonly (uint Bit, string Name)[] ShopCategories =
|
||||
{
|
||||
(0x00000001, "Weapons"), (0x00000002, "Armor"), (0x00000004, "Clothing"), (0x00000008, "Jewelry"),
|
||||
(0x00000010, "Miscellaneous"), (0x00000020, "Food"), (0x00000080, "Miscellaneous"), (0x00000100, "Weapons"),
|
||||
(0x00000200, "Containers"), (0x00000400, "Miscellaneous"), (0x00000800, "Gems"), (0x00001000, "Spell Components"),
|
||||
(0x00002000, "Books, Paper"), (0x00004000, "Keys, Tools"), (0x00008000, "Magic Items"), (0x00040000, "Trade Notes"),
|
||||
(0x00080000, "Mana Stones"), (0x00100000, "Services"), (0x00400000, "Cooking Items"), (0x00800000, "Alchemical Items"),
|
||||
(0x01000000, "Fletching Items"), (0x04000000, "Alchemical Items"), (0x08000000, "Fletching Items"), (0x20000000, "Keys, Tools"),
|
||||
};
|
||||
|
||||
public static string CategoryName(uint itemType)
|
||||
{
|
||||
foreach (var (bit, name) in ShopCategories)
|
||||
if ((itemType & bit) != 0) return name;
|
||||
return $"Unknown Category 0x{itemType:X8}";
|
||||
}
|
||||
|
||||
// ── Prices (ACE Vendor.GetSellCost / GetBuyCost, as the engine checks them) ──────────
|
||||
|
||||
/// <summary>What you pay for one created stack worth <paramref name="stackValue"/>.</summary>
|
||||
public static long PlayerPays(VendorView v, bool isNote, long stackValue)
|
||||
{
|
||||
float rate = isNote ? 1.15f : v.SellRate;
|
||||
float product = rate * stackValue;
|
||||
return Math.Max(1L, (long)Math.Ceiling(product - 0.1));
|
||||
}
|
||||
|
||||
/// <summary>What the vendor pays for one item (whole stack) worth <paramref name="value"/>.</summary>
|
||||
public static long VendorPays(VendorView v, bool isNote, long value)
|
||||
{
|
||||
float rate = isNote ? 1.0f : v.BuyRate;
|
||||
float product = rate * value;
|
||||
return Math.Max(1L, (long)Math.Floor(product + 0.1));
|
||||
}
|
||||
|
||||
/// <summary>Per-unit price: the engine's figure, else UB's (int)(Value/Stack) x rate rounded like ACE.</summary>
|
||||
public static long UnitPrice(VendorView v, Listing item)
|
||||
{
|
||||
if (item.UnitPrice > 0) return item.UnitPrice;
|
||||
if (item.UnitValue <= 0) return 0;
|
||||
return PlayerPays(v, item.IsNote, item.UnitValue);
|
||||
}
|
||||
|
||||
/// <summary>The engine's EstimateBuy: stackables in full stacks, limited listings at least the whole listing.</summary>
|
||||
public static long EstimateCost(VendorView v, Listing item, int amount)
|
||||
{
|
||||
if (amount <= 0) return 0;
|
||||
long unitValue = Math.Max(0, item.UnitValue);
|
||||
long cost;
|
||||
if (item.MaxStackSize > 1)
|
||||
{
|
||||
long max = item.MaxStackSize;
|
||||
long full = amount / max;
|
||||
long rem = amount % max;
|
||||
cost = full * PlayerPays(v, item.IsNote, unitValue * max) + (rem > 0 ? PlayerPays(v, item.IsNote, unitValue * rem) : 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
cost = amount * PlayerPays(v, item.IsNote, unitValue);
|
||||
}
|
||||
if (!item.Unlimited)
|
||||
cost = Math.Max(cost, PlayerPays(v, item.IsNote, Math.Max(0, item.Value)));
|
||||
return cost;
|
||||
}
|
||||
|
||||
/// <summary>Largest amount in [0, max] whose EstimateCost fits <paramref name="money"/> (cost only grows with amount).</summary>
|
||||
public static int MostAffordable(VendorView v, Listing item, int max, long money)
|
||||
{
|
||||
int lo = 0, hi = Math.Max(0, max);
|
||||
while (lo < hi)
|
||||
{
|
||||
int mid = lo + (hi - lo + 1) / 2;
|
||||
if (EstimateCost(v, item, mid) <= money) lo = mid;
|
||||
else hi = mid - 1;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
public static int SlotsFor(Listing item, int amount)
|
||||
{
|
||||
int max = Math.Max(1, item.MaxStackSize);
|
||||
return (int)((amount + (long)max - 1) / max);
|
||||
}
|
||||
|
||||
/// <summary>UB PyrealsWillFitInMainPack: always leaves one main-pack slot free.</summary>
|
||||
public static bool PyrealsFit(PackState p, double amount)
|
||||
{
|
||||
int stack = Math.Max(1, p.PyrealStackSize);
|
||||
return p.FreeMainSlots - Math.Ceiling(amount / stack) > 0;
|
||||
}
|
||||
|
||||
// ── Safety (UB ItemIsSafeToGetRidOf + Util.IsItemSafeToGetRidOf, stricter) ──────────
|
||||
|
||||
/// <summary>Null when the item may be sold; otherwise the reason it never will be.</summary>
|
||||
public static string? UnsafeReason(SafetyFacts f, bool onlyFromMainPack)
|
||||
{
|
||||
if (!f.Appraised) return "not identified";
|
||||
if (f.Equipped) return "equipped";
|
||||
if (f.Class == AcObjectClass.Money) return "money";
|
||||
if (f.Class == AcObjectClass.Container || f.HoldsItems) return "container";
|
||||
if (f.Class == AcObjectClass.Foci) return "focus";
|
||||
if (f.Value <= 0) return "no value";
|
||||
if (f.CanBeSold == false) return "not sellable";
|
||||
if (f.IsRare) return "rare";
|
||||
if (onlyFromMainPack && !f.InMainPack) return "not in main pack";
|
||||
if (f.Attuned != 0) return "attuned";
|
||||
if (f.Bonded != 0) return "bonded";
|
||||
if (f.Retained) return "retained";
|
||||
if (f.TimesTinkered > 0) return "tinkered";
|
||||
if (f.Imbued != 0) return "imbued";
|
||||
if (!string.IsNullOrEmpty(f.Inscription)) return "inscribed";
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// UB VendorInfo.WillBuyItem. Trade notes skip the value cap like UB, but the vendor must
|
||||
/// still list the note item type: the engine refuses anything outside the vendor's types.
|
||||
/// </summary>
|
||||
public static bool VendorWillBuy(VendorView v, uint itemType, bool isNote, int unitValue)
|
||||
{
|
||||
if (!v.Buys(itemType)) return false;
|
||||
if (isNote) return true;
|
||||
return v.MaxValue > 0 && unitValue <= v.MaxValue;
|
||||
}
|
||||
|
||||
// ── Buy list (UB GetBuyItems) ────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Keep # buys (count - have), where have is the inventory count by exact name (containers:
|
||||
/// by object class, and only the first container rule). Keep buys int.MaxValue. Sorted
|
||||
/// trade notes last, then cheapest unit price first.
|
||||
/// </summary>
|
||||
public static List<BuyWant> BuildBuyWants(
|
||||
VendorView v,
|
||||
IEnumerable<(Listing Item, BuyDecision Decision)> judged,
|
||||
Func<string, int> countByName,
|
||||
Func<AcObjectClass, int> countByClass)
|
||||
{
|
||||
var list = judged.ToList();
|
||||
var wants = new List<BuyWant>();
|
||||
bool buyingContainers = false;
|
||||
|
||||
foreach (var (item, d) in list)
|
||||
{
|
||||
if (d.Kind != BuyKind.KeepUpTo) continue;
|
||||
if (item.Class == AcObjectClass.Container)
|
||||
{
|
||||
int have = countByClass(AcObjectClass.Container);
|
||||
if (!buyingContainers && d.KeepCount > have)
|
||||
{
|
||||
buyingContainers = true;
|
||||
wants.Add(new BuyWant { Item = item, Amount = d.KeepCount - have, RuleName = d.RuleName });
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
int have = countByName(item.Name);
|
||||
if (d.KeepCount > have)
|
||||
wants.Add(new BuyWant { Item = item, Amount = d.KeepCount - have, RuleName = d.RuleName });
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var (item, d) in list)
|
||||
if (d.Kind == BuyKind.Keep)
|
||||
wants.Add(new BuyWant { Item = item, Amount = int.MaxValue, RuleName = d.RuleName });
|
||||
|
||||
return wants
|
||||
.OrderBy(w => w.Item.IsNote ? 1 : 0)
|
||||
.ThenBy(w => UnitPrice(v, w.Item))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>UB GetSellItems sort: trade notes last, then cheapest stack payout first.</summary>
|
||||
public static List<SellItem> SortSells(VendorView v, IEnumerable<SellItem> items) =>
|
||||
items.OrderBy(s => s.IsNote ? 1 : 0)
|
||||
.ThenBy(s => VendorPays(v, s.IsNote, s.Value))
|
||||
.ToList();
|
||||
|
||||
// ── One transaction (UB DoVendoring) ─────────────────────────────────────
|
||||
|
||||
/// <param name="wants">From BuildBuyWants (already sorted).</param>
|
||||
/// <param name="sells">From SortSells.</param>
|
||||
public static VendorPlan PlanNext(VendorView v, IReadOnlyList<BuyWant> wants, IReadOnlyList<SellItem> sells, PackState p)
|
||||
{
|
||||
// ── Buy first ──
|
||||
var buys = new List<BuyLine>();
|
||||
long totalCost = 0;
|
||||
int totalSlots = 0, totalContainerSlots = 0;
|
||||
|
||||
// UB re-orders by the listing's raw Value here (a stable sort over the price order).
|
||||
foreach (var want in wants.OrderBy(w => w.Item.Value))
|
||||
{
|
||||
Listing item = want.Item;
|
||||
long price = UnitPrice(v, item);
|
||||
if (price <= 0)
|
||||
return VendorPlan.Fatal(string.Format(CultureInfo.InvariantCulture,
|
||||
"AutoVendor Fatal - No vendor price found while adding {0:n0}x {1}[0x{2:X8}] Value: {3:n}",
|
||||
want.Amount, item.Name, item.Id, (double)price));
|
||||
|
||||
bool fits;
|
||||
if (item.NeedsContainerSlot)
|
||||
fits = p.FreeContainerSlots - totalContainerSlots > 0;
|
||||
else
|
||||
fits = p.FreeMainSlots - totalSlots > (item.IsNote ? 0 : 1);
|
||||
|
||||
if (totalCost + price <= p.Funds && fits)
|
||||
{
|
||||
long affordable = (p.Funds - totalCost) / price;
|
||||
long count = Math.Min(affordable, want.Amount);
|
||||
count = Math.Min(count, MaxVendorBuyCount);
|
||||
if (!item.Unlimited) count = Math.Min(count, item.Amount);
|
||||
|
||||
if (item.NeedsContainerSlot)
|
||||
{
|
||||
count = Math.Min(count, p.FreeContainerSlots - totalContainerSlots);
|
||||
}
|
||||
else if (p.FreeMainSlots < SlotsFor(item, (int)count) + totalSlots)
|
||||
{
|
||||
// UB: limit to what fits, keeping two slots spare (never below zero).
|
||||
long fit = (long)Math.Max(1, item.MaxStackSize) * Math.Max(0, (p.FreeMainSlots - 2) - totalSlots);
|
||||
count = Math.Min(count, fit);
|
||||
}
|
||||
|
||||
// The engine's exact cost can exceed the per-unit estimate (a limited listing
|
||||
// costs at least the whole listing): take the most that still fits the money.
|
||||
if (count > 0 && totalCost + EstimateCost(v, item, (int)count) > p.Funds)
|
||||
count = MostAffordable(v, item, (int)count, p.Funds - totalCost);
|
||||
if (count <= 0)
|
||||
break;
|
||||
|
||||
int n = (int)count;
|
||||
buys.Add(new BuyLine(item, n));
|
||||
if (item.NeedsContainerSlot) totalContainerSlots += n;
|
||||
else totalSlots += SlotsFor(item, n);
|
||||
totalCost += EstimateCost(v, item, n);
|
||||
|
||||
if (want.Amount > n)
|
||||
break; // couldn't take all of it: don't reach for the next item
|
||||
}
|
||||
else if (buys.Count > 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (buys.Count > 0)
|
||||
return new VendorPlan { Kind = PlanKind.Buy, Buys = buys, Total = totalCost };
|
||||
|
||||
// ── Then sell ──
|
||||
// nextBuy: the item we want but couldn't afford (notes are sold only to pay for it).
|
||||
// An alt-currency vendor isn't paid in pyreals, so selling can't fund its items.
|
||||
Listing? nextBuy = !v.UsesAltCurrency && wants.Count > 0 ? wants[0].Item : null;
|
||||
|
||||
var chosen = new List<SellItem>();
|
||||
long totalValue = 0;
|
||||
for (int i = 0; i < sells.Count && chosen.Count < MaxSellLines; i++)
|
||||
{
|
||||
SellItem item = sells[i];
|
||||
int stack = Math.Max(1, item.StackSize);
|
||||
long stackPayout = VendorPays(v, item.IsNote, item.Value);
|
||||
double unit = (double)stackPayout / stack;
|
||||
|
||||
// Never sell notes to buy notes, and never sell notes when there's nothing to buy.
|
||||
if (item.IsNote && (nextBuy == null || nextBuy.IsNote))
|
||||
break;
|
||||
|
||||
// Selling notes to afford something: one note at a time, and only on its own.
|
||||
if (nextBuy != null && item.IsNote)
|
||||
{
|
||||
if (chosen.Count > 0) break;
|
||||
if (!PyrealsFit(p, unit))
|
||||
return VendorPlan.Fatal($"AutoVendor Fatal - No inventory room to sell {item.Name}");
|
||||
|
||||
SellItem? single = null;
|
||||
foreach (var s in sells)
|
||||
if (s.IsNote && s.StackSize <= 1 && string.Equals(s.Name, item.Name, StringComparison.Ordinal))
|
||||
{ single = s; break; }
|
||||
if (single != null)
|
||||
return new VendorPlan { Kind = PlanKind.Sell, Sells = new List<SellItem> { single }, Total = VendorPays(v, true, single.Value) };
|
||||
|
||||
return VendorPlan.Split(item, 1, $"one {item.Name} to afford {nextBuy.Name}");
|
||||
}
|
||||
|
||||
// Can't sell the whole stack? Split off what the pyreals will fit.
|
||||
if (!PyrealsFit(p, totalValue + stackPayout))
|
||||
{
|
||||
if (chosen.Count < 1)
|
||||
{
|
||||
int newStack = unit > 0 ? (int)Math.Floor((p.FreeMainSlots - 2) * (double)Math.Max(1, p.PyrealStackSize) / unit) : 0;
|
||||
newStack = Math.Min(newStack, stack - 1);
|
||||
if (newStack > 0)
|
||||
return VendorPlan.Split(item, newStack, "the pyreals for the whole stack won't fit");
|
||||
return VendorPlan.Fatal($"AutoVendor Fatal - No inventory room to sell {item.Name}");
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
chosen.Add(item);
|
||||
totalValue += stackPayout;
|
||||
}
|
||||
|
||||
if (chosen.Count > 0)
|
||||
return new VendorPlan { Kind = PlanKind.Sell, Sells = chosen, Total = totalValue };
|
||||
|
||||
return VendorPlan.Done();
|
||||
}
|
||||
|
||||
// ── /ub vendor addsell (UB AddItemToSellList) ────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Whole stacks that fit in the remaining count are taken; if units are still missing,
|
||||
/// the smallest stack bigger than what's missing is returned to be split.
|
||||
/// </summary>
|
||||
public static (List<SellItem> Whole, int Missing, SellItem? SplitFrom) PlanAddSell(IReadOnlyList<SellItem> matches, int count)
|
||||
{
|
||||
var whole = new List<SellItem>();
|
||||
int needed = Math.Max(0, count);
|
||||
SellItem? oversized = null;
|
||||
foreach (var m in matches)
|
||||
{
|
||||
if (needed == 0) break;
|
||||
int stack = Math.Max(1, m.StackSize);
|
||||
if (stack <= needed)
|
||||
{
|
||||
whole.Add(m);
|
||||
needed -= stack;
|
||||
}
|
||||
else if (oversized == null || oversized.StackSize > stack)
|
||||
{
|
||||
oversized = m;
|
||||
}
|
||||
}
|
||||
return (whole, needed, needed > 0 ? oversized : null);
|
||||
}
|
||||
|
||||
// ── Shared parsing ───────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>"[count] name" as UB's addbuy/addsell read it; count defaults to 1.</summary>
|
||||
public static (int Count, string Name) ParseCountAndName(string args)
|
||||
{
|
||||
string s = (args ?? string.Empty).Trim();
|
||||
int sp = s.IndexOf(' ');
|
||||
if (sp > 0 && int.TryParse(s.Substring(0, sp), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n))
|
||||
return (n, s.Substring(sp + 1).Trim());
|
||||
return (1, s);
|
||||
}
|
||||
}
|
||||
318
Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorRules.cs
vendored
Normal file
318
Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorRules.cs
vendored
Normal file
|
|
@ -0,0 +1,318 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Loot.VTank;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Vendor;
|
||||
|
||||
// Pure rule judging for AutoVendor: no host, no WorldObject. The manager hands in a
|
||||
// per-condition matcher (VTankLootEvaluator.MatchCondition) and the facts it has about
|
||||
// the item; this file decides which conditions can be answered with that data and turns
|
||||
// the answers into a profile verdict. Kept dependency-free so the test project can link it.
|
||||
//
|
||||
// Selling is destructive, so every answer is three-valued: Yes, No, or Unknown ("we don't
|
||||
// have the data VTank would use"). A rule with an Unknown condition never counts as a
|
||||
// match. UB leans on VTank's own evaluator; ours has approximations (buffed damage, colour
|
||||
// similarity, base skill), and those node types always read Unknown here.
|
||||
|
||||
internal enum Tri : byte
|
||||
{
|
||||
No = 0,
|
||||
Yes = 1,
|
||||
Unknown = 2,
|
||||
}
|
||||
|
||||
/// <summary>What the manager knows about an item before judging it.</summary>
|
||||
internal readonly struct ItemFacts
|
||||
{
|
||||
/// <summary>An item on the vendor's list: only the engine's vendor snapshot is known.</summary>
|
||||
public bool IsVendorListing { get; init; }
|
||||
/// <summary>Inventory item with appraisal (ID) data.</summary>
|
||||
public bool Appraised { get; init; }
|
||||
public AcObjectClass ObjectClass { get; init; }
|
||||
/// <summary>The item's spell list can be read (appraised and the host exposes spell ids).</summary>
|
||||
public bool HasSpellData { get; init; }
|
||||
public bool HasPalettes { get; init; }
|
||||
public bool HasCharacterSkills { get; init; }
|
||||
public bool HasCharacterLevel { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>The profile's answer for one item.</summary>
|
||||
internal sealed class ProfileVerdict
|
||||
{
|
||||
/// <summary>First rule that matched (Certain) or might match (!Certain); null = no rule can match.</summary>
|
||||
public VTankLootRule? Rule { get; init; }
|
||||
public int RuleIndex { get; init; } = -1;
|
||||
/// <summary>True when Rule definitely matched, or when no rule can match at all.</summary>
|
||||
public bool Certain { get; init; }
|
||||
/// <summary>Some Keep / Keep # rule anywhere in the profile matches or might match.</summary>
|
||||
public bool KeepPossible { get; init; }
|
||||
/// <summary>Name of a Keep / Keep # rule that matches or might match (for messages).</summary>
|
||||
public string KeepRuleName { get; init; } = string.Empty;
|
||||
/// <summary>Why the deciding rule could not be judged (node type name), when !Certain.</summary>
|
||||
public string UnknownReason { get; init; } = string.Empty;
|
||||
|
||||
public string RuleName => Rule == null ? string.Empty : AutoVendorRules.RuleLabel(Rule, RuleIndex);
|
||||
}
|
||||
|
||||
internal enum BuyKind : byte
|
||||
{
|
||||
None = 0,
|
||||
/// <summary>Keep: buy as many as you can afford.</summary>
|
||||
Keep = 1,
|
||||
/// <summary>Keep #: buy up to the rule's count.</summary>
|
||||
KeepUpTo = 2,
|
||||
}
|
||||
|
||||
internal readonly record struct BuyDecision(BuyKind Kind, int KeepCount, string RuleName);
|
||||
|
||||
internal readonly record struct SellDecision(bool Sell, string RuleName, string Reason);
|
||||
|
||||
internal static class AutoVendorRules
|
||||
{
|
||||
// STypeInt keys a vendor listing carries (engine VendorItem: ItemType, Burden,
|
||||
// MaxStackSize, StackSize, Value). Anything else on a listing is unknown.
|
||||
internal static readonly HashSet<int> ListingIntKeys = new() { 1, 5, 11, 12, 19 };
|
||||
|
||||
// Keys the client keeps in PublicWeenieDesc, readable without appraisal
|
||||
// (items/containers capacity, locations, wielded location, stack sizes, material).
|
||||
internal static readonly HashSet<int> PwdIntKeys = new() { 6, 7, 9, 10, 11, 12, 131 };
|
||||
|
||||
// Decal's synthetic LongValueKey ids start at 0x0D000000; RynthAi reads STypes only.
|
||||
internal const int MaxStandardKey = 0xFFFF;
|
||||
|
||||
// RynthAi derives ObjectClass from ITEM_TYPE alone. Decal splits these further
|
||||
// (Misc -> HealingKit/Lockpick, Book -> Scroll/Journal/Sign, Container -> Foci,
|
||||
// Key -> Lockpick, Food -> Plant), so an ObjectClass test on them is unknown.
|
||||
internal static readonly HashSet<AcObjectClass> CoarseClasses = new()
|
||||
{
|
||||
AcObjectClass.Unknown, AcObjectClass.Misc, AcObjectClass.Book,
|
||||
AcObjectClass.Container, AcObjectClass.Food, AcObjectClass.Key,
|
||||
};
|
||||
|
||||
public static string RuleLabel(VTankLootRule rule, int index)
|
||||
=> string.IsNullOrWhiteSpace(rule.Name) ? $"#{index}" : rule.Name.Trim();
|
||||
|
||||
/// <summary>Can this condition be answered for an item with these facts?</summary>
|
||||
public static bool CanJudge(VTankLootCondition cond, in ItemFacts f)
|
||||
{
|
||||
var d = cond.DataLines;
|
||||
switch (cond.NodeType)
|
||||
{
|
||||
case VTankNodeTypes.DisabledRule:
|
||||
case VTankNodeTypes.DamagePercentGE: // VTank itself always answers "no"
|
||||
case VTankNodeTypes.ObjectClass: // coarse classes handled in JudgeObjectClass
|
||||
return true;
|
||||
|
||||
case VTankNodeTypes.CharacterMainPackEmptySlotsGE:
|
||||
return true;
|
||||
case VTankNodeTypes.CharacterSkillGE:
|
||||
return f.HasCharacterSkills;
|
||||
case VTankNodeTypes.CharacterLevelGE:
|
||||
case VTankNodeTypes.CharacterLevelLE:
|
||||
return f.HasCharacterLevel;
|
||||
|
||||
case VTankNodeTypes.StringValueMatch:
|
||||
{
|
||||
if (!TryKey(d, 1, out int key)) return false;
|
||||
if (key == 1) return true; // Name
|
||||
return !f.IsVendorListing && f.Appraised && key <= MaxStandardKey;
|
||||
}
|
||||
|
||||
case VTankNodeTypes.LongValKeyLE:
|
||||
case VTankNodeTypes.LongValKeyGE:
|
||||
case VTankNodeTypes.LongValKeyE:
|
||||
case VTankNodeTypes.LongValKeyNE:
|
||||
case VTankNodeTypes.LongValKeyFlagExists:
|
||||
{
|
||||
if (!TryKey(d, 1, out int key) || key < 0 || key > MaxStandardKey) return false;
|
||||
if (f.IsVendorListing) return ListingIntKeys.Contains(key);
|
||||
return f.Appraised || PwdIntKeys.Contains(key);
|
||||
}
|
||||
|
||||
case VTankNodeTypes.DoubleValKeyLE:
|
||||
case VTankNodeTypes.DoubleValKeyGE:
|
||||
{
|
||||
if (!TryKey(d, 1, out int key) || key < 0 || key > MaxStandardKey) return false;
|
||||
return !f.IsVendorListing && f.Appraised;
|
||||
}
|
||||
|
||||
case VTankNodeTypes.SpellNameMatch:
|
||||
case VTankNodeTypes.SpellMatch:
|
||||
case VTankNodeTypes.SpellCountGE:
|
||||
return !f.IsVendorListing && f.HasSpellData;
|
||||
|
||||
case VTankNodeTypes.SlotExactPalette:
|
||||
return !f.IsVendorListing && f.HasPalettes;
|
||||
|
||||
case VTankNodeTypes.TotalRatingsGE:
|
||||
return !f.IsVendorListing && f.Appraised;
|
||||
|
||||
// Approximated or not implemented by RynthAi's evaluator: never trusted.
|
||||
case VTankNodeTypes.AnySimilarColor:
|
||||
case VTankNodeTypes.SimilarColorArmorType:
|
||||
case VTankNodeTypes.SlotSimilarColor:
|
||||
case VTankNodeTypes.CharacterBaseSkill:
|
||||
case VTankNodeTypes.MinDamageGE:
|
||||
case VTankNodeTypes.BuffedMedianDamageGE:
|
||||
case VTankNodeTypes.BuffedMissileDamageGE:
|
||||
case VTankNodeTypes.BuffedLongValKeyGE:
|
||||
case VTankNodeTypes.BuffedDoubleValKeyGE:
|
||||
case VTankNodeTypes.CalcdBuffedTinkedDamageGE:
|
||||
case VTankNodeTypes.CalcedBuffedTinkedTargetMeleeGE:
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>ObjectClass test without the evaluator: unknown for classes Decal splits further.</summary>
|
||||
public static Tri JudgeObjectClass(VTankLootCondition cond, AcObjectClass itemClass)
|
||||
{
|
||||
if (!TryKey(cond.DataLines, 0, out int target)) return Tri.Unknown;
|
||||
if (CoarseClasses.Contains(itemClass)) return Tri.Unknown;
|
||||
return (int)itemClass == target ? Tri.Yes : Tri.No;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Judge one condition. <paramref name="match"/> is only called for conditions that
|
||||
/// CanJudge says are answerable; if it throws (malformed data line) the answer is Unknown.
|
||||
/// </summary>
|
||||
public static Tri JudgeCondition(VTankLootCondition cond, in ItemFacts f, Func<VTankLootCondition, bool> match)
|
||||
{
|
||||
if (!CanJudge(cond, f)) return Tri.Unknown;
|
||||
if (cond.NodeType == VTankNodeTypes.ObjectClass) return JudgeObjectClass(cond, f.ObjectClass);
|
||||
try { return match(cond) ? Tri.Yes : Tri.No; }
|
||||
catch { return Tri.Unknown; }
|
||||
}
|
||||
|
||||
/// <summary>All conditions must hold: any No -> No, else any Unknown -> Unknown, else Yes.</summary>
|
||||
public static Tri JudgeRule(VTankLootRule rule, Func<VTankLootCondition, Tri> cond, out string unknownReason)
|
||||
{
|
||||
unknownReason = string.Empty;
|
||||
if (rule.Conditions.Count == 0) return Tri.Yes;
|
||||
bool unknown = false;
|
||||
foreach (var c in rule.Conditions)
|
||||
{
|
||||
Tri t = cond(c);
|
||||
if (t == Tri.No) { unknownReason = string.Empty; return Tri.No; }
|
||||
if (t == Tri.Unknown && !unknown)
|
||||
{
|
||||
unknown = true;
|
||||
unknownReason = VTankNodeTypes.DisplayName(c.NodeType);
|
||||
}
|
||||
}
|
||||
return unknown ? Tri.Unknown : Tri.Yes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// VTank order: the first rule that matches decides. A rule that might match stops the
|
||||
/// scan too (we can't know whether it or a later rule applies). Also records whether
|
||||
/// any Keep / Keep # rule anywhere could match, which AutoVendor treats as "never sell".
|
||||
/// </summary>
|
||||
public static ProfileVerdict Decide(IReadOnlyList<VTankLootRule> rules, Func<VTankLootCondition, Tri> cond)
|
||||
{
|
||||
VTankLootRule? decided = null;
|
||||
int decidedIdx = -1;
|
||||
bool certain = true;
|
||||
string reason = string.Empty;
|
||||
bool keepPossible = false;
|
||||
string keepName = string.Empty;
|
||||
|
||||
for (int i = 0; i < rules.Count; i++)
|
||||
{
|
||||
var rule = rules[i];
|
||||
bool isKeep = rule.Action is VTankLootAction.Keep or VTankLootAction.KeepUpTo;
|
||||
if (decided != null && (!isKeep || keepPossible))
|
||||
continue; // only still scanning for keep rules
|
||||
|
||||
Tri t = JudgeRule(rule, cond, out string why);
|
||||
if (t == Tri.No) continue;
|
||||
|
||||
if (isKeep && !keepPossible)
|
||||
{
|
||||
keepPossible = true;
|
||||
keepName = RuleLabel(rule, i);
|
||||
}
|
||||
if (decided == null)
|
||||
{
|
||||
decided = rule;
|
||||
decidedIdx = i;
|
||||
certain = t == Tri.Yes;
|
||||
reason = why;
|
||||
}
|
||||
}
|
||||
|
||||
return new ProfileVerdict
|
||||
{
|
||||
Rule = decided,
|
||||
RuleIndex = decidedIdx,
|
||||
Certain = decided == null || certain,
|
||||
UnknownReason = reason,
|
||||
KeepPossible = keepPossible,
|
||||
KeepRuleName = keepName,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// UB GetBuyItems for one vendor listing: Keep # buys up to the count, Keep buys all it
|
||||
/// can afford. First match decides, as in VTank. A rule we can't judge (a listing carries
|
||||
/// only name, type, value, stack and burden) is handled so we never buy more than VTank would:
|
||||
/// an unjudgeable non-buy rule ends the scan with no purchase (it might be the one that
|
||||
/// matches); an unjudgeable Keep / Keep # rule lets the scan go on, since either way the
|
||||
/// item gets bought, and the smallest count seen is used.
|
||||
/// </summary>
|
||||
public static BuyDecision DecideBuy(IReadOnlyList<VTankLootRule> rules, Func<VTankLootCondition, Tri> cond)
|
||||
{
|
||||
long cap = long.MaxValue;
|
||||
for (int i = 0; i < rules.Count; i++)
|
||||
{
|
||||
var rule = rules[i];
|
||||
Tri t = JudgeRule(rule, cond, out _);
|
||||
if (t == Tri.No) continue;
|
||||
|
||||
long count = rule.Action switch
|
||||
{
|
||||
VTankLootAction.KeepUpTo => Math.Max(0, rule.KeepCount ?? 0),
|
||||
VTankLootAction.Keep => int.MaxValue,
|
||||
_ => -1,
|
||||
};
|
||||
if (count < 0)
|
||||
return new BuyDecision(BuyKind.None, 0, RuleLabel(rule, i)); // a non-buy rule matches or might
|
||||
|
||||
cap = Math.Min(cap, count);
|
||||
if (t == Tri.Yes)
|
||||
{
|
||||
int n = (int)Math.Min(cap, int.MaxValue);
|
||||
return n == int.MaxValue
|
||||
? new BuyDecision(BuyKind.Keep, int.MaxValue, RuleLabel(rule, i))
|
||||
: new BuyDecision(BuyKind.KeepUpTo, n, RuleLabel(rule, i));
|
||||
}
|
||||
}
|
||||
return new BuyDecision(BuyKind.None, 0, string.Empty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// UB GetSellItems (result.IsSell), stricter: the deciding rule must be a Sell rule that
|
||||
/// definitely matched, and no Keep / Keep # rule anywhere in the profile may match or
|
||||
/// possibly match the item.
|
||||
/// </summary>
|
||||
public static SellDecision JudgeSell(ProfileVerdict v)
|
||||
{
|
||||
if (v.Rule == null) return new SellDecision(false, string.Empty, "no rule matches");
|
||||
if (v.Rule.Action != VTankLootAction.Sell)
|
||||
return new SellDecision(false, v.RuleName, $"first rule is {v.Rule.Action}");
|
||||
if (!v.Certain)
|
||||
return new SellDecision(false, v.RuleName, $"rule '{v.RuleName}' needs {v.UnknownReason} data we don't have");
|
||||
if (v.KeepPossible)
|
||||
return new SellDecision(false, v.RuleName, $"also matches keep rule '{v.KeepRuleName}'");
|
||||
return new SellDecision(true, v.RuleName, string.Empty);
|
||||
}
|
||||
|
||||
private static bool TryKey(IList<string> d, int idx, out int value)
|
||||
{
|
||||
value = 0;
|
||||
return d != null && idx < d.Count
|
||||
&& int.TryParse(d[idx].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out value);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue