Snapshot for release 2026.10.30.1 (internal 50ae062)

This commit is contained in:
Tom Bohar 2026-10-31 06:01:30 -04:00
commit 76aca938b6
52 changed files with 6242 additions and 60 deletions

View file

@ -2,16 +2,27 @@ using System;
namespace RynthCore.Plugin.RynthDefective.Model;
internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection, Settings, Spell, Corpses }
internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection, Settings, Spell, Corpses,
Quantity, Split, Give, Buy }
/// <summary>A parsed "/rdef ..." line. Use: <see cref="Slot"/> (1-based) or <see cref="Text"/> (an item name).</summary>
internal sealed record DefCommand(DefVerb Verb, int Slot = 0, string Text = "", string Error = "");
/// <summary>
/// A parsed "/rdef ..." line. Use: <see cref="Slot"/> (1-based) or <see cref="Text"/> (an item name).
/// The quantity box's verbs (qty, split, give, buy): <see cref="Amount"/> (null = the box's number) and
/// <see cref="Text"/> (split: the pack; buy: the item's name).
/// </summary>
internal sealed record DefCommand(DefVerb Verb, int Slot = 0, string Text = "", string Error = "", QtyAmount? Amount = null);
internal static class DefCommandParser
{
public const string Usage =
"/rdef [use <slot or item name> | set <slot> [item name] | spell <slot> <spell name> | clear <slot> | bind <slot> <key> | unbind <slot> | "
+ "weapons [search] | fav | slots <count> | list | status | settings | panels (the game panel buttons) | selection | corpses [clear]]";
+ "weapons [search] | fav | slots <count> | list | status | settings | panels (the game panel buttons) | selection | corpses [clear] | "
+ "qty [number|max|half] | split [number] [into <pack>] | give [number] | buy [number] [item name]]";
public const string QtyUsage = "Usage: /rdef qty <number|max|half>, e.g. /rdef qty 25 (the Selection window's number)";
public const string SplitUsage = "Usage: /rdef split [number|max|half] [into <pack>], e.g. /rdef split 25 or /rdef split 25 into Sack";
public const string GiveUsage = "Usage: /rdef give [number|max|half], e.g. /rdef give 10 (to the last player or NPC you selected)";
public const string BuyUsage = "Usage: /rdef buy [number|max|half] [item name], e.g. /rdef buy 25 or /rdef buy 25 Mana Scarab (a vendor open)";
/// <summary>Parses the arguments after "/rdef" (blank = show or hide the bar).</summary>
public static DefCommand Parse(string? args)
@ -68,6 +79,31 @@ internal static class DefCommandParser
return int.TryParse(rest, out int count) && count >= DefSettings.SlotsMin && count <= DefSettings.SlotCountMax
? new DefCommand(DefVerb.Slots, count)
: Fail($"How many slots? {DefSettings.SlotsMin} to {DefSettings.SlotCountMax}, e.g. /rdef slots 10");
// The quantity box (2026-10-30, Quantity/QuantityController.cs).
case "qty": case "quantity": case "amount":
{
if (rest.Length == 0) return new DefCommand(DefVerb.Quantity);
return QuantityRules.TryParse(rest, out QtyAmount q, out string why)
? new DefCommand(DefVerb.Quantity, Amount: q)
: Fail(why + " " + QtyUsage);
}
case "split":
{
if (!QuantityRules.TryParseLeading(rest, out QtyAmount? q, out string tail, out string why)) return Fail(why + " " + SplitUsage);
string into = StripWord(tail, "into", "in", "to");
return new DefCommand(DefVerb.Split, Text: into, Amount: q);
}
case "give":
{
if (!QuantityRules.TryParseLeading(rest, out QtyAmount? q, out string tail, out string why)) return Fail(why + " " + GiveUsage);
if (tail.Length > 0) return Fail($"'{tail}' isn't a quantity. {GiveUsage}");
return new DefCommand(DefVerb.Give, Amount: q);
}
case "buy":
{
if (!QuantityRules.TryParseLeading(rest, out QtyAmount? q, out string tail, out string why)) return Fail(why + " " + BuyUsage);
return new DefCommand(DefVerb.Buy, Text: StripWord(tail, "of"), Amount: q);
}
default:
// "/rdef Stamina Kit" is a shorthand for use.
return new DefCommand(DefVerb.Use, Text: a);
@ -91,4 +127,14 @@ internal static class DefCommandParser
}
private static DefCommand Fail(string error) => new(DefVerb.Error, Error: error);
/// <summary>The text without a leading word ("into Sack" -> "Sack").</summary>
private static string StripWord(string text, params string[] words)
{
string t = text.Trim();
foreach (string w in words)
if (t.Length > w.Length && t.StartsWith(w, StringComparison.OrdinalIgnoreCase) && char.IsWhiteSpace(t[w.Length]))
return t[(w.Length + 1)..].Trim();
return t;
}
}

View file

@ -111,6 +111,12 @@ internal sealed class DefSettings
/// the picker opens from the settings window, the bar's right-click menu and /rdef weapons.
/// </summary>
public bool WeaponsButtonOnBar;
/// <summary>
/// The quantity box under a stack or a vendor's item in the Selection window (2026-10-30): how many,
/// and Split / Give / Buy that many. On (the default, and what a file from before reads as).
/// /rdef qty, split, give and buy work either way.
/// </summary>
public bool QuantityBox = true;
public bool BarOpen;
public bool PickerOpen;

View file

@ -68,6 +68,7 @@ internal sealed class DefStore
st.SwapWhileBotRuns = Bool(s, "swapWhileBotRuns", st.SwapWhileBotRuns);
st.WeaponsButtonOnBar = Bool(s, "weaponsButtonOnBar", st.WeaponsButtonOnBar); // missing (a file from before 2026-10-29): off
st.IndependentBar = Bool(s, "independentBar", st.IndependentBar); // missing (a file from before 2026-10-27): off
st.QuantityBox = Bool(s, "quantityBox", st.QuantityBox); // missing (a file from before 2026-10-30): on
st.BarOpen = Bool(s, "barOpen", st.BarOpen);
st.PickerOpen = Bool(s, "pickerOpen", st.PickerOpen);
st.Clamp();
@ -166,6 +167,7 @@ internal sealed class DefStore
w.WriteBoolean("swapWhileBotRuns", s.SwapWhileBotRuns);
w.WriteBoolean("weaponsButtonOnBar", s.WeaponsButtonOnBar);
w.WriteBoolean("independentBar", s.IndependentBar);
w.WriteBoolean("quantityBox", s.QuantityBox);
w.WriteBoolean("barOpen", s.BarOpen);
w.WriteBoolean("pickerOpen", s.PickerOpen);
w.WriteEndObject();

View file

@ -0,0 +1,406 @@
// ============================================================================
// RynthDefective - Model/Quantity.cs
// The quantity box's rules (2026-10-30): how many of a stack a split or a
// give takes, how many of a vendor's item a buy asks for, what that costs and
// why it can't go. Pure (no host), so RynthDefective.Tests checks every rule.
//
// Retail AC keeps this number in its toolbar: the stack slider and the number
// beside the selected item's name (the client's split_amount global, which a
// drag and the vendor's buy list read). RynthCore's "Hide retail toolbar"
// hides it with the rest of the toolbar, and the plugin API can't read or set
// it (API 92), so the box keeps a number of its own and acts through the
// engine's calls: SplitStackInternal, GiveObjectTo and VendorBuy.
//
// The counts:
// split takes 1 .. stack-1 (one always stays: the whole stack is a move);
// "max" is stack-1, "half" is half the stack.
// give hands over 1 .. the whole stack; "max" is the whole stack.
// buy asks for exactly the number; "max" is the most the vendor has, you
// can pay for, and your packs and burden take (VendorQuote.MaxBuy).
// box a typed number stays as typed (1 .. MaxAmount); "max" and "half"
// are of what is selected: the whole stack, or the most you can buy.
// ============================================================================
using System;
using System.Globalization;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective.Model;
internal enum QtyWord { Number, Max, Half }
/// <summary>A quantity as typed: a number, "max" or "half".</summary>
internal readonly record struct QtyAmount(QtyWord Word, int Number = 0)
{
public static QtyAmount Of(int n) => new(QtyWord.Number, n);
public static readonly QtyAmount Max = new(QtyWord.Max);
public static readonly QtyAmount Half = new(QtyWord.Half);
public override string ToString() => Word switch
{
QtyWord.Max => "max",
QtyWord.Half => "half",
_ => Number.ToString(CultureInfo.InvariantCulture),
};
}
internal static class QuantityRules
{
/// <summary>The most one request carries: the engine's vendor limit (an ItemProfile packs 24 bits).</summary>
public const int MaxAmount = 0x7FFFFF;
public const string Usage = "a number (25, 1,000), max or half";
/// <summary>"25", "1,000", "max" / "all", "half" / "1/2". False with the reason and the usage.</summary>
public static bool TryParse(string? text, out QtyAmount amount, out string why)
{
amount = default;
why = string.Empty;
string t = (text ?? string.Empty).Trim();
switch (t.ToLowerInvariant())
{
case "max": case "all": case "most":
amount = QtyAmount.Max;
return true;
case "half": case "1/2":
amount = QtyAmount.Half;
return true;
}
string digits = t.Replace(",", "", StringComparison.Ordinal).Replace("_", "", StringComparison.Ordinal);
if (digits.Length > 0 && (char.IsDigit(digits[0]) || digits[0] == '-' || digits[0] == '+')
&& long.TryParse(digits, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out long n))
{
if (n < 1) { why = $"The quantity is at least 1 (not {t})."; return false; }
if (n > MaxAmount) { why = $"{t} is more than one request can carry (at most {MaxAmount.ToString("N0", CultureInfo.InvariantCulture)})."; return false; }
amount = QtyAmount.Of((int)n);
return true;
}
why = t.Length == 0 ? $"How many? {Usage}." : $"'{t}' isn't a quantity: {Usage}.";
return false;
}
/// <summary>Whether a word reads as a quantity (a number of any size, or max / half), so "25 into Sack" splits off the 25.</summary>
public static bool LooksLikeAmount(string word)
{
string w = word.Trim().ToLowerInvariant();
if (w is "max" or "all" or "most" or "half" or "1/2") return true;
return w.Length > 0 && (char.IsDigit(w[0]) || ((w[0] == '-' || w[0] == '+') && w.Length > 1 && char.IsDigit(w[1])));
}
/// <summary>
/// The arguments of split / give / buy: an optional quantity first, then the rest ("into Sack", an
/// item name). False only when the first word reads as a quantity and is a wrong one ("0", "-3").
/// </summary>
public static bool TryParseLeading(string? args, out QtyAmount? amount, out string rest, out string why)
{
amount = null;
why = string.Empty;
string a = (args ?? string.Empty).Trim();
int sp = a.IndexOf(' ');
string first = sp < 0 ? a : a[..sp];
rest = sp < 0 ? string.Empty : a[(sp + 1)..].Trim();
if (first.Length == 0 || !LooksLikeAmount(first))
{
rest = a;
return true;
}
if (!TryParse(first, out QtyAmount q, out why)) return false;
amount = q;
return true;
}
/// <summary><paramref name="n"/> within 1 .. <paramref name="max"/> (1 when max is below 1).</summary>
public static int Clamp(int n, int max) => max < 1 ? 1 : Math.Clamp(n, 1, max);
/// <summary>Half of <paramref name="of"/>, at least 1.</summary>
public static int HalfOf(int of) => Math.Max(1, of / 2);
/// <summary>How many a split takes from a stack of <paramref name="stack"/>: at least one stays; 0 = not a stack.</summary>
public static int SplitCount(int n, int stack) => stack < 2 ? 0 : Clamp(n, stack - 1);
/// <summary>How many a give hands over: up to the whole stack; 0 = nothing there.</summary>
public static int GiveCount(int n, int stack) => stack < 1 ? 0 : Clamp(n, stack);
/// <summary>A split's count from what was typed (or the box's number): "max" stack-1, "half" half the stack.</summary>
public static int ForSplit(QtyAmount a, int stack) => stack < 2 ? 0 : a.Word switch
{
QtyWord.Max => stack - 1,
QtyWord.Half => SplitCount(HalfOf(stack), stack),
_ => SplitCount(a.Number, stack),
};
/// <summary>A give's count: "max" the whole stack, "half" half of it.</summary>
public static int ForGive(QtyAmount a, int stack) => stack < 1 ? 0 : a.Word switch
{
QtyWord.Max => stack,
QtyWord.Half => HalfOf(stack),
_ => GiveCount(a.Number, stack),
};
/// <summary>
/// The box's number after /rdef qty or a button: a typed number as typed (1 .. MaxAmount); "max"
/// and "half" of <paramref name="max"/> (the whole stack, or the most you can buy). 0 when max or
/// half has nothing to be of.
/// </summary>
public static int ForBox(QtyAmount a, int max) => a.Word switch
{
QtyWord.Max => max >= 1 ? Math.Min(max, MaxAmount) : 0,
QtyWord.Half => max >= 1 ? HalfOf(Math.Min(max, MaxAmount)) : 0,
_ => Math.Clamp(a.Number, 1, MaxAmount),
};
/// <summary>A buy's count: exactly the number typed (VendorQuote.Refusal says when it can't go); "max" the most you can buy.</summary>
public static int ForBuy(QtyAmount a, int maxBuy) => a.Word switch
{
QtyWord.Max => Math.Max(0, maxBuy),
QtyWord.Half => maxBuy >= 1 ? HalfOf(maxBuy) : 0,
_ => a.Number,
};
public static string N(long n) => n.ToString("N0", CultureInfo.InvariantCulture);
}
/// <summary>
/// One vendor item and what the player has: the box's price, its "max" and why a buy can't go. The
/// rules are ACE's, as the engine's VendorTrade.EstimateBuy applies them (the engine checks again
/// before it sends): a stackable item comes in stacks of MaxStack, each priced on its own
/// (max(1, ceil(value x rate - 0.1)), promissory notes at 1.15), anything else one per slot; a
/// limited listing (usually what another player sold, handed over whole) costs at least the whole
/// listing. Unknown funds, slots or burden (-1) aren't held against the buy.
/// </summary>
internal sealed record VendorQuote
{
public const uint ItemTypePromissoryNote = 0x00040000;
public string Name { get; init; } = string.Empty;
public uint ItemType { get; init; }
public int UnitValue { get; init; }
/// <summary>What one costs at this vendor (the engine's server-rounded figure; shown, not summed).</summary>
public int UnitPrice { get; init; }
public int ListingValue { get; init; }
public int UnitBurden { get; init; }
public int ListingBurden { get; init; }
/// <summary>The largest stack (above 0 = stackable, ACE's rule).</summary>
public int MaxStack { get; init; }
public bool Unlimited { get; init; }
/// <summary>How many the vendor has (a limited listing).</summary>
public int Stock { get; init; }
public float SellRate { get; init; } = 1f;
public bool NeedsContainerSlot { get; init; }
public string Currency { get; init; } = "pyreals";
/// <summary>Pyreals (or the vendor's own currency) you have; -1 = unknown.</summary>
public long Funds { get; init; } = -1;
public int FreeItemSlots { get; init; } = -1;
public int FreeContainerSlots { get; init; } = -1;
public long FreeBurden { get; init; } = -1;
public bool Stackable => MaxStack > 0;
/// <summary>From the engine's vendor snapshot (API v67) and what the player has.</summary>
public static VendorQuote From(VendorInfo info, VendorItem item, int freeItemSlots, int freeContainerSlots, long freeBurden)
{
int stack = Math.Max(1, item.StackSize);
bool alt = info.UsesAltCurrency;
return new VendorQuote
{
Name = item.Name,
ItemType = item.ItemType,
UnitValue = item.UnitValue,
UnitPrice = item.UnitPrice,
ListingValue = item.Value,
UnitBurden = stack > 1 ? item.Burden / stack : item.Burden,
ListingBurden = item.Burden,
MaxStack = item.MaxStackSize,
Unlimited = item.Unlimited || item.Amount < 0,
Stock = Math.Max(0, item.Amount),
SellRate = info.SellRate,
NeedsContainerSlot = item.NeedsContainerSlot,
Currency = alt ? (info.AltCurrencyName.Length > 0 ? info.AltCurrencyName : "the vendor's currency") : "pyreals",
Funds = alt ? info.AltCurrencyHave : info.PlayerCoins,
FreeItemSlots = freeItemSlots,
FreeContainerSlots = freeContainerSlots,
FreeBurden = freeBurden,
};
}
/// <summary>What the player pays for one created stack worth <paramref name="stackValue"/> (ACE Vendor.GetSellCost).</summary>
public long PaysForStack(long stackValue)
{
float rate = ItemType == ItemTypePromissoryNote ? 1.15f : SellRate;
float product = rate * stackValue;
return Math.Max(1L, (long)Math.Ceiling(product - 0.1));
}
/// <summary>Cost, pack slots and burden of buying <paramref name="n"/>.</summary>
public void Estimate(int n, out long cost, out long slots, out long burden)
{
long unitValue = Math.Max(0, UnitValue), unitBurden = Math.Max(0, UnitBurden);
if (n < 1) { cost = slots = burden = 0; return; }
if (Stackable)
{
long max = MaxStack, full = n / max, rem = n % max;
cost = full * PaysForStack(unitValue * max) + (rem > 0 ? PaysForStack(unitValue * rem) : 0);
slots = full + (rem > 0 ? 1 : 0);
}
else
{
cost = n * PaysForStack(unitValue);
slots = n;
}
burden = n * unitBurden;
if (!Unlimited)
{
cost = Math.Max(cost, PaysForStack(Math.Max(0, ListingValue)));
slots = Math.Max(slots, 1);
burden = Math.Max(burden, Math.Max(0, ListingBurden));
}
}
public long Cost(int n)
{
Estimate(n, out long cost, out _, out _);
return cost;
}
private int FreeSlots => NeedsContainerSlot ? FreeContainerSlots : FreeItemSlots;
/// <summary>Money, room and burden allow <paramref name="n"/> (the vendor's stock aside).</summary>
private bool Fits(int n)
{
Estimate(n, out long cost, out long slots, out long burden);
if (Funds >= 0 && cost > Funds) return false;
if (FreeSlots >= 0 && slots > FreeSlots) return false;
if (FreeBurden >= 0 && burden > FreeBurden) return false;
return true;
}
/// <summary>
/// The most you can buy now: what the vendor has, you can pay for, and your packs and burden take
/// (cost, slots and burden only grow with the count, so a halving search finds it). With nothing
/// known to limit an unlimited item, one full stack (one, for an item that doesn't stack). 0 = not even one.
/// </summary>
public int MaxBuy()
{
int cap = Unlimited ? QuantityRules.MaxAmount : Math.Min(Stock, QuantityRules.MaxAmount);
if (Unlimited && Funds < 0 && FreeSlots < 0 && FreeBurden < 0) cap = Stackable ? Math.Max(1, MaxStack) : 1;
if (cap < 1 || !Fits(1)) return 0;
int lo = 1, hi = cap;
while (lo < hi)
{
int mid = lo + (hi - lo + 1) / 2;
if (Fits(mid)) lo = mid; else hi = mid - 1;
}
return lo;
}
/// <summary>Why buying <paramref name="n"/> can't go, or null when it can (as far as the plugin can tell).</summary>
public string? Refusal(int n)
{
if (n < 1) return "The quantity is at least 1.";
if (n > QuantityRules.MaxAmount) return $"{QuantityRules.N(n)} is more than one buy can carry (at most {QuantityRules.N(QuantityRules.MaxAmount)}).";
if (!Unlimited && n > Stock)
return Stock < 1 ? $"The vendor has no {Name} left." : $"The vendor has only {QuantityRules.N(Stock)} {Name}.";
Estimate(n, out long cost, out long slots, out long burden);
string what = $"{QuantityRules.N(n)} {Name}";
if (Funds >= 0 && cost > Funds)
return $"Not enough {Currency}: {what} cost {QuantityRules.N(cost)}, you have {QuantityRules.N(Funds)}{CanBuy()}.";
int free = FreeSlots;
if (free >= 0 && slots > free)
{
if (NeedsContainerSlot)
return free == 0 ? $"No room for another pack: {what} need a container slot of their own."
: $"Not enough container slots: {what} need {QuantityRules.N(slots)}, you have {free}{CanBuy()}.";
return free == 0 ? "The pack is full: no free slot for " + what + "."
: $"Not enough room in your packs: {what} need {QuantityRules.N(slots)} free slots, you have {free}{CanBuy()}.";
}
if (FreeBurden >= 0 && burden > FreeBurden)
return $"Too heavy: {what} weigh {QuantityRules.N(burden)} burden, you can carry {QuantityRules.N(FreeBurden)} more{CanBuy()}.";
return null;
}
private string CanBuy()
{
int max = MaxBuy();
return max >= 1 ? $" (you can buy {QuantityRules.N(max)})" : string.Empty;
}
/// <summary>The price line under the Buy button: "300 pyreals · you have 1,250".</summary>
public string PriceLine(int n)
{
string cost = n >= 1 ? QuantityRules.N(Cost(n)) + " " + Currency : "-";
return Funds >= 0 ? $"{cost} · you have {QuantityRules.N(Funds)}" : cost;
}
}
/// <summary>What the quantity box's actions say (chat and the Selection window). Pure.</summary>
internal static class QtyReplies
{
public const string NothingSelected = "Nothing is selected. Select a stack in your pack (or an item in a vendor's list) first.";
public const string Busy = "Wait a moment: the last split, give or buy is still waiting for the server.";
public const string NoSplitApi = "This RynthCore can't split stacks for a plugin.";
public const string NoGiveApi = "This RynthCore can't give items for a plugin (it needs plugin API v62).";
public const string NoTradeApi = "This RynthCore can't trade with vendors for a plugin (it needs plugin API v67).";
public const string NoVendor = "No vendor is open: talk to a vendor first.";
public const string NoVendorItem = "Select the item in the vendor's list first (or type its name: /rdef buy 25 Mana Scarab).";
public const string VendorUnreadable = "RynthCore can't trade with this vendor (its list couldn't be read): use the game's own Buy.";
public const string VendorBusy = "A trade with the vendor is still going: wait a moment.";
public const string NoGiveTarget = "Who to? Select the player or NPC first, then the stack: Give goes to the last one you selected.";
public const string MaxNeedsSelection = "max and half are of what is selected: select a stack or a vendor's item first. Usage: /rdef qty <number|max|half>";
public static string NotAStack(string name) => $"That's not a stack: {name} is a single item.";
public static string Wielded(string name) => $"{name} is wielded: take it off first.";
public static string NotReachable(string name) => $"{name} isn't in your packs or in the container you have open.";
public static string NotCarried(string name) => $"{name} isn't in your packs: pick it up first.";
public static string VendorsItem(string name) => $"{name} is the vendor's: Buy takes it (/rdef buy N).";
public static string PackFull(string where) =>
$"{Cap(where)} is full. Pick another pack for the split (the 'into' button, or /rdef split 25 into <pack>).";
public static string NoSuchPack(string typed, string packs) => $"No pack called '{typed}'. Your packs: {packs}.";
public static string NotSent(string what) => $"The {what} couldn't be sent (the game isn't ready for it): nothing changed.";
public static string Splitting(int n, string name, string into) => $"Split {QuantityRules.N(n)} {name} into {into}.";
public static string Gave(int n, string name, string to) => $"Gave {QuantityRules.N(n)} {name} to {to}.";
public static string Bought(int n, string name, long cost, string currency) =>
cost > 0 ? $"Bought {QuantityRules.N(n)} {name} for {QuantityRules.N(cost)} {currency}." : $"Bought {QuantityRules.N(n)} {name}.";
public static string Refused(string what, uint error) =>
error != 0 ? $"The server refused the {what} (error 0x{error:X4}): nothing changed." : $"The server refused the {what}: nothing changed.";
public static string NoAnswer(string what) => $"No answer from the server for the {what}: check your pack before trying again.";
/// <summary>
/// The engine's refusal of a buy (VendorTradeStatus.Message, Compatibility/VendorTrade.cs) in the
/// player's words. Unknown messages are passed on as they are.
/// </summary>
public static string VendorRefusal(string? message)
{
string m = (message ?? string.Empty).Trim();
if (m.Length == 0) return "The vendor didn't sell it.";
if (m.StartsWith("costs ", StringComparison.Ordinal))
{
// "costs 300 pyreals, you have 200" / "costs 3 Ancient Mattekar Claws, you have 1"
int comma = m.IndexOf(", you have ", StringComparison.Ordinal);
string head = comma > 0 ? m[6..comma] : m[6..];
int sp = head.IndexOf(' ');
string currency = sp > 0 ? head[(sp + 1)..] : "pyreals";
return $"Not enough {currency}: it {m}.";
}
if (m.StartsWith("needs ", StringComparison.Ordinal) && m.Contains("free pack slots", StringComparison.Ordinal))
return m.EndsWith("you have 0", StringComparison.Ordinal) ? $"The pack is full: it {m}." : $"Not enough room in your packs: it {m}.";
if (m.StartsWith("needs ", StringComparison.Ordinal) && m.Contains("container slots", StringComparison.Ordinal))
return $"No room for another pack: it {m}.";
if (m.StartsWith("adds ", StringComparison.Ordinal) && m.Contains("burden", StringComparison.Ordinal))
return $"Too heavy: it {m}.";
if (m.Contains("vendor only has", StringComparison.Ordinal) || m.StartsWith("bad amount", StringComparison.Ordinal))
return "The vendor doesn't have that many.";
if (m.Contains("no vendor open", StringComparison.Ordinal) || m.Contains("vendor window is closed", StringComparison.Ordinal)
|| m.Contains("vendor closed", StringComparison.Ordinal) || m.Contains("is not the open vendor", StringComparison.Ordinal))
return "The vendor is closed: talk to it again.";
if (m.Contains("not on this vendor's list", StringComparison.Ordinal) || m.Contains("no longer on the vendor's list", StringComparison.Ordinal))
return "The vendor doesn't sell that any more.";
if (m.Contains("requests already waiting", StringComparison.Ordinal))
return VendorBusy;
if (m.Contains("could not read your", StringComparison.Ordinal) || m.Contains("could not count your", StringComparison.Ordinal))
return $"RynthCore couldn't count your money ({m}): try again in a moment.";
return $"The vendor didn't sell it: {m}.";
}
private static string Cap(string s) => s.Length == 0 ? s : char.ToUpperInvariant(s[0]) + s[1..];
}

View file

@ -0,0 +1,252 @@
// ============================================================================
// RynthDefective - Quantity/QtyWorld.cs
// What the quantity box (QuantityController) needs from the game, as an
// interface so the tests drive it offline (RynthDefective.Tests), and the
// engine host's side of it. Plugin pump thread only.
//
// Every call is behind its Has* check: splitting (SplitStackInternal, as old
// as the plugin API), giving with a count (GiveObjectTo, v62), vendor trading
// (v67), the server's refusals (v70) and the pack column's order (v80) are
// each used only where the engine has them. Nothing here needs more than the
// live release's API 92, and the Selection window itself needs v90.
// ============================================================================
using System;
using System.Collections.Generic;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective.Quantity;
internal enum QtyPackKind { Main, Side, Open }
/// <summary>A place a split can go: the main pack, a side pack, or the container you have open.</summary>
internal readonly record struct QtyPack(uint Id, string Name, int Capacity, int Count, QtyPackKind Kind)
{
/// <summary>Free item slots; -1 = unknown (the server decides).</summary>
public int Free => Capacity > 0 && Count >= 0 ? Math.Max(0, Capacity - Count) : -1;
/// <summary>In a sentence: "the main pack", "Sack", "Chest".</summary>
public string Where => Kind == QtyPackKind.Main ? "the main pack" : Name;
/// <summary>On a button: "Main pack", "Sack", "Chest (open)".</summary>
public string Label => Kind switch
{
QtyPackKind.Main => "Main pack",
QtyPackKind.Open => Name + " (open)",
_ => Name,
};
}
internal interface IQtyWorld
{
long NowMs { get; }
uint PlayerId { get; }
uint SelectedId { get; }
/// <summary>AC's selection before this one (0 = none or unknown).</summary>
uint PreviousSelectedId { get; }
/// <summary>The chest or corpse you have open (0 = none).</summary>
uint OpenContainerId { get; }
bool TryGetName(uint id, out string name);
/// <summary>The client knows the object.</summary>
bool Exists(uint id);
/// <summary>Someone to give to: a player or an NPC (a creature that isn't a monster).</summary>
bool CanReceive(uint id);
/// <summary>Where it is: its container and its wielder (0 = none). False = the client doesn't know it.</summary>
bool TryGetOwner(uint id, out uint container, out uint wielder);
/// <summary>Its stack size; 0 = unknown.</summary>
int StackOf(uint id);
/// <summary>The main pack first, then the side packs (the pack column's order), then the open container.</summary>
IReadOnlyList<QtyPack> Packs();
bool CanSplit { get; }
/// <summary>Splits <paramref name="n"/> off the stack into <paramref name="into"/> (a new stack there).</summary>
bool Split(uint id, uint into, int n);
bool CanGive { get; }
/// <summary>Gives <paramref name="n"/> of it (0 = the whole of it) to a player or NPC.</summary>
bool Give(uint id, uint to, int n);
/// <summary>Counts the server's refusals (0 when the engine can't say): note it before a send, compare after.</summary>
int RefusalSeq { get; }
bool LastRefusal(out uint error, out uint eventType, out uint objectId);
bool CanTrade { get; }
/// <summary>The vendor open now (false = none).</summary>
bool TryGetVendor(out VendorInfo info);
IReadOnlyList<VendorItem> VendorItems();
/// <summary>Asks the engine to buy; the request id, or 0 when it refused at once (the trade status says why).</summary>
uint Buy(uint vendorId, uint itemId, int n);
bool TryGetTradeStatus(out VendorTradeStatus status);
/// <summary>Free container slots (for packs and foci bought); -1 = unknown.</summary>
int FreeContainerSlots();
/// <summary>Burden you can still carry (three times your capacity, as ACE); -1 = unknown.</summary>
long FreeBurden();
}
/// <summary>The engine host's side (RynthCoreHost). Plugin pump thread only.</summary>
internal sealed class HostQtyWorld : IQtyWorld
{
// STypeInt
private const uint EncumbranceVal = 5, ItemsCapacity = 6, ContainersCapacity = 7, StackSize = 12, EncumbranceCapacity = 96;
private const uint ItemTypeCreature = 0x10, ItemTypeContainer = 0x200;
// PublicWeenieDesc bitfield (ObjectDescriptionFlag).
private const uint BitPlayer = 0x8, BitAttackable = 0x10;
private const int MainPackDefault = 102, ContainerSlotsDefault = 7;
private readonly RynthCoreHost _h;
private uint[] _contents = new uint[256];
private uint[] _order = new uint[16];
private uint _vendorId, _vendorGeneration;
private VendorItem[] _vendorItems = Array.Empty<VendorItem>();
public HostQtyWorld(RynthCoreHost host) => _h = host;
public long NowMs => Environment.TickCount64;
public uint PlayerId => _h.HasGetPlayerId ? _h.GetPlayerId() : 0;
public uint SelectedId => _h.HasGetSelectedItemId ? _h.GetSelectedItemId() : 0;
public uint PreviousSelectedId => _h.HasGetPreviousSelectedItemId ? _h.GetPreviousSelectedItemId() : 0;
public uint OpenContainerId => _h.HasGetGroundContainerId ? _h.GetGroundContainerId() : 0;
public bool TryGetName(uint id, out string name)
{
name = string.Empty;
if (id == 0 || !_h.TryGetObjectName(id, out string n) || string.IsNullOrWhiteSpace(n)) return false;
name = n.Trim();
return true;
}
public bool Exists(uint id) => id != 0 && _h.TryGetItemType(id, out _);
/// <summary>
/// A creature that is a player (description bit Player 0x8) or isn't attackable (Attackable 0x10: a
/// monster): a monster selected in a fight never becomes the give target. Without the description
/// bits (an older engine) any creature; the server refuses a give it doesn't take.
/// </summary>
public bool CanReceive(uint id)
{
if (id == 0 || !_h.TryGetItemType(id, out uint t) || (t & ItemTypeCreature) == 0) return false;
if (!_h.HasGetObjectBitfield || !_h.TryGetObjectBitfield(id, out uint bits)) return true;
return (bits & BitPlayer) != 0 || (bits & BitAttackable) == 0;
}
public bool TryGetOwner(uint id, out uint container, out uint wielder)
{
container = wielder = 0;
if (id == 0) return false;
if (_h.HasGetObjectOwnershipInfo && _h.TryGetObjectOwnershipInfo(id, out container, out wielder, out _)) return true;
return false;
}
public int StackOf(uint id) => id != 0 && _h.TryGetObjectIntProperty(id, StackSize, out int s) && s > 0 ? s : 0;
private int Int(uint id, uint stype) => _h.TryGetObjectIntProperty(id, stype, out int v) ? v : -1;
public IReadOnlyList<QtyPack> Packs()
{
var packs = new List<QtyPack>(8);
uint player = PlayerId;
if (player == 0) return packs;
int mainCap = Int(player, ItemsCapacity);
packs.Add(new QtyPack(player, "Main pack", mainCap > 0 ? mainCap : MainPackDefault, Count(player), QtyPackKind.Main));
// The side packs, in the pack column's order when the engine knows it (v80), else as the client lists them.
var ids = new List<uint>(8);
if (_h.HasContainerOrder && _h.TryGetContainerOrder(player, true, ref _order, out int ordered) && ordered > 0)
for (int i = 0; i < ordered && i < _order.Length; i++) ids.Add(_order[i]);
else if (_h.HasGetContainerContents)
{
int n = _h.GetContainerContents(player, _contents);
if (n > _contents.Length && n <= 4096) { _contents = new uint[n]; n = _h.GetContainerContents(player, _contents); }
for (int i = 0; i < n && i < _contents.Length; i++) ids.Add(_contents[i]);
}
var names = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (uint id in ids)
{
if (id == 0 || !_h.TryGetItemType(id, out uint type) || (type & ItemTypeContainer) == 0) continue;
int cap = Int(id, ItemsCapacity);
if (cap <= 0) continue; // a focus holds no items
if (TryGetOwner(id, out uint c, out uint w) && (c != player || w != 0)) continue;
string name = TryGetName(id, out string nm) ? nm : "Pack";
names[name] = names.TryGetValue(name, out int seen) ? seen + 1 : 1;
if (names[name] > 1) name += " " + names[name];
packs.Add(new QtyPack(id, name, cap, Count(id), QtyPackKind.Side));
}
uint open = OpenContainerId;
if (open != 0 && open != player && !packs.Exists(p => p.Id == open))
{
string name = TryGetName(open, out string nm) ? nm : "The open container";
packs.Add(new QtyPack(open, name, Int(open, ItemsCapacity), Count(open), QtyPackKind.Open));
}
return packs;
}
private int Count(uint container) => _h.HasGetNumContainedItems ? _h.GetNumContainedItems(container) : -1;
public bool CanSplit => _h.HasSplitStackInternal;
// Slot 0 with a count below the stack: the client's StackableSplitToContainer, as the engine's own
// Inventory panel splits (InventoryModel). The new stack takes a free slot of the target.
public bool Split(uint id, uint into, int n) => CanSplit && n >= 1 && _h.SplitStackInternal(id, into, 0, n);
public bool CanGive => _h.HasGiveObjectTo;
public bool Give(uint id, uint to, int n) => CanGive && _h.GiveObjectTo(id, to, Math.Max(0, n));
public int RefusalSeq => _h.HasGetLastWeenieError && _h.TryGetLastWeenieError(out int seq, out _, out _, out _) ? seq : 0;
public bool LastRefusal(out uint error, out uint eventType, out uint objectId)
{
error = eventType = objectId = 0;
return _h.HasGetLastWeenieError && _h.TryGetLastWeenieError(out _, out error, out eventType, out objectId);
}
public bool CanTrade => _h.HasVendorTrade;
public bool TryGetVendor(out VendorInfo info)
{
info = null!;
return CanTrade && _h.TryGetVendorInfo(out info) && info.VendorId != 0;
}
/// <summary>The open vendor's list, read again only when the vendor or its list (Generation) changed.</summary>
public IReadOnlyList<VendorItem> VendorItems()
{
if (!TryGetVendor(out VendorInfo info))
{
_vendorId = 0;
_vendorItems = Array.Empty<VendorItem>();
return _vendorItems;
}
if (info.VendorId != _vendorId || info.Generation != _vendorGeneration || _vendorItems.Length == 0)
{
_vendorItems = _h.GetVendorItems();
_vendorId = info.VendorId;
_vendorGeneration = info.Generation;
}
return _vendorItems;
}
public uint Buy(uint vendorId, uint itemId, int n) => CanTrade ? _h.VendorBuy(itemId, n, vendorId) : 0;
public bool TryGetTradeStatus(out VendorTradeStatus status)
{
status = null!;
return CanTrade && _h.TryGetVendorTradeStatus(out status);
}
public int FreeContainerSlots()
{
uint player = PlayerId;
if (player == 0 || !_h.HasGetNumContainedContainers) return -1;
int n = _h.GetNumContainedContainers(player);
if (n < 0) return -1;
int cap = Int(player, ContainersCapacity);
return Math.Max(0, (cap > 0 ? cap : ContainerSlotsDefault) - n);
}
public long FreeBurden()
{
uint player = PlayerId;
if (player == 0) return -1;
int carried = Int(player, EncumbranceVal), cap = Int(player, EncumbranceCapacity);
if (carried < 0 || cap <= 0) return -1; // unknown: the engine checks with its own reading
return Math.Max(0, 3L * cap - carried);
}
}

View file

@ -0,0 +1,552 @@
// ============================================================================
// RynthDefective - Quantity/QuantityController.cs
// The quantity box (2026-10-30): one number, and what it does to what is
// selected. Asked for by a player: "to select a portion of a stack, or buy
// multiple of an item from a vendor, I need a place to type in the number".
//
// a stack you carry Split N into the main pack, a side pack or the
// (or in the chest you have container you have open; Give N to the player
// open) or NPC you selected last
// an item in a vendor's list Buy N, with the price, your pyreals, the room
// in your packs and your burden checked first
//
// The Selection window shows the box under what is selected (QuantityRow);
// /rdef qty, split, give and buy do the same from chat, hotkeys and metas.
// Nothing here needs the engine's Inventory panel or RynthInventory.
//
// One action at a time. Each one answers once: at once when it can't go
// (why, in the player's words), or when the game answers (the stack got
// smaller, the item left your packs, the vendor's trade finished) or doesn't
// (a refusal from the server, or no answer in time).
//
// Threads: everything on the plugin pump, except Value and Into, which the
// Selection window sets from the render thread (single ints).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Threading;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective.Quantity;
internal enum QtyMode { None, Single, Stack, Vendor }
/// <summary>Where the selected item is, for a split or a give.</summary>
internal enum QtyWhere { Unknown, Carried, Wielded, Open, Elsewhere }
/// <summary>What is selected, as the box sees it.</summary>
internal sealed record QtySubject(QtyMode Mode, uint Id, string Name, int Stack, QtyWhere Where)
{
public static readonly QtySubject Nothing = new(QtyMode.None, 0, string.Empty, 0, QtyWhere.Unknown);
/// <summary>A vendor's item: its price and what you have.</summary>
public VendorQuote? Quote { get; init; }
public uint VendorId { get; init; }
/// <summary>The most you can buy now (vendor items).</summary>
public int MaxBuy { get; init; }
/// <summary>What the box's "max" is of: the whole stack, or the most you can buy; 0 = nothing.</summary>
public int BoxMax => Mode switch
{
QtyMode.Stack => Stack,
QtyMode.Vendor => MaxBuy,
_ => 0,
};
}
/// <summary>The box as the Selection window draws it (built on the tick).</summary>
internal sealed record QuantityView(QtySubject Subject, QtyPack[] Targets, int TargetIndex, uint GiveTo, string GiveName,
bool Busy, bool CanSplit, bool CanGive)
{
public QtyPack? Target => TargetIndex >= 0 && TargetIndex < Targets.Length ? Targets[TargetIndex] : null;
}
/// <summary>The last thing the box did, for the Selection window's line.</summary>
internal sealed record QtyStatus(string Text, bool Ok, long AtMs);
internal sealed class QuantityController
{
/// <summary>How long a split, a give (the server may walk you to the NPC first) and a buy wait for the game.</summary>
public const long SplitAnswerMs = 6000, GiveAnswerMs = 20_000, BuyAnswerMs = 15_000;
/// <summary>A refusal that doesn't name the item is ours if nothing changed this long after it.</summary>
public const long RefusalGraceMs = 1500;
/// <summary>The last player or NPC selected stays the give target this long.</summary>
public const long GiveTargetMs = 10 * 60 * 1000;
public const long StatusShownMs = 8000;
/// <summary>InventoryServerSaveFailed: the server refused a move, split or give of this item.</summary>
private const uint InventorySaveFailed = 0x00A0;
private int _value = 1;
private uint _into;
private volatile QtyStatus? _status;
private uint _lastSelection, _giveId;
private string _giveName = string.Empty;
private long _giveAtMs;
private Pending? _pending;
/// <summary>Every answer (ok, text): the plugin writes it in chat.</summary>
public Action<bool, string> Report = (_, _) => { };
/// <summary>The box's number (1 .. MaxAmount). Any thread.</summary>
public int Value
{
get => Volatile.Read(ref _value);
set => Volatile.Write(ref _value, Math.Clamp(value, 1, QuantityRules.MaxAmount));
}
/// <summary>The pack a split goes into (its id); 0 or a pack that's gone = the main pack. Any thread.</summary>
public uint Into
{
get => Volatile.Read(ref _into);
set => Volatile.Write(ref _into, value);
}
public bool Busy => _pending != null;
/// <summary>The last answer while it is fresh. Any thread.</summary>
public QtyStatus? StatusAt(long nowMs)
{
QtyStatus? s = _status;
return s != null && nowMs - s.AtMs < StatusShownMs ? s : null;
}
public void Reset()
{
_pending = null;
_status = null;
_giveId = _lastSelection = 0;
_giveName = string.Empty;
Into = 0;
}
private void Say(IQtyWorld w, bool ok, string text)
{
_status = new QtyStatus(text, ok, w.NowMs);
Report(ok, text);
}
// ── What is selected ────────────────────────────────────────────────────
public QtySubject Analyze(IQtyWorld w)
{
uint sel = w.SelectedId;
if (sel == 0) return QtySubject.Nothing;
string name = w.TryGetName(sel, out string n) ? n : $"0x{sel:X8}";
if (w.CanTrade && w.TryGetVendor(out VendorInfo info))
{
foreach (VendorItem it in w.VendorItems())
{
if (it.ObjectId != sel) continue;
VendorQuote q = Quote(w, info, it);
return new QtySubject(QtyMode.Vendor, sel, it.Name.Length > 0 ? it.Name : name, Math.Max(1, it.StackSize), QtyWhere.Elsewhere)
{
Quote = q,
VendorId = info.VendorId,
MaxBuy = q.MaxBuy(),
};
}
}
int stack = w.StackOf(sel);
return new QtySubject(stack >= 2 ? QtyMode.Stack : QtyMode.Single, sel, name, Math.Max(1, stack), WhereIs(w, sel));
}
private static QtyWhere WhereIs(IQtyWorld w, uint id)
{
uint player = w.PlayerId;
if (player == 0 || !w.TryGetOwner(id, out uint c, out uint wielder)) return QtyWhere.Unknown;
if (wielder != 0 && wielder == player) return QtyWhere.Wielded;
if (c == player) return QtyWhere.Carried;
if (c != 0 && w.TryGetOwner(c, out uint outer, out uint outerWielder) && outer == player && outerWielder == 0) return QtyWhere.Carried;
if (c != 0 && c == w.OpenContainerId) return QtyWhere.Open;
return QtyWhere.Elsewhere;
}
private static bool Owned(IQtyWorld w, uint id)
{
QtyWhere where = WhereIs(w, id);
return where is QtyWhere.Carried or QtyWhere.Wielded;
}
private static VendorQuote Quote(IQtyWorld w, VendorInfo info, VendorItem item)
{
int free = 0;
foreach (QtyPack p in w.Packs())
{
if (p.Kind == QtyPackKind.Open) continue;
if (p.Free < 0) { free = -1; break; }
free += p.Free;
}
return VendorQuote.From(info, item, free, w.FreeContainerSlots(), w.FreeBurden());
}
/// <summary>
/// The Selection window's box: for a vendor's item, or a stack you carry, wield (it says to take it
/// off) or have in the open container. Not for a stack on the ground or in someone else's hands. Plugin tick.
/// </summary>
public QuantityView? View(IQtyWorld w)
{
QtySubject s = Analyze(w);
if (s.Mode is not (QtyMode.Stack or QtyMode.Vendor)) return null;
if (s.Mode == QtyMode.Stack && s.Where is not (QtyWhere.Carried or QtyWhere.Wielded or QtyWhere.Open)) return null;
QtyPack[] targets = s.Mode == QtyMode.Stack ? new List<QtyPack>(w.Packs()).ToArray() : Array.Empty<QtyPack>();
int index = 0;
uint into = Into;
for (int i = 0; i < targets.Length; i++) if (targets[i].Id == into) { index = i; break; }
TryGiveTarget(w, s.Id, out uint to, out string toName);
return new QuantityView(s, targets, targets.Length == 0 ? -1 : index, to, toName, Busy, w.CanSplit, w.CanGive);
}
// ── The give target: the last player or NPC selected ─────────────────────
/// <summary>Notes a newly selected player or NPC (not you, not a monster) as the give target. Plugin tick, a few times a second.</summary>
public void NoteSelection(IQtyWorld w)
{
uint sel = w.SelectedId;
if (sel == _lastSelection) return;
_lastSelection = sel;
if (sel == 0 || sel == w.PlayerId || !w.CanReceive(sel)) return;
_giveId = sel;
_giveName = w.TryGetName(sel, out string n) ? n : $"0x{sel:X8}";
_giveAtMs = w.NowMs;
}
/// <summary>Who a give goes to: the last player or NPC selected (within GiveTargetMs and still there), else AC's previous selection.</summary>
public bool TryGiveTarget(IQtyWorld w, uint item, out uint to, out string name)
{
uint player = w.PlayerId;
if (_giveId != 0 && _giveId != item && w.NowMs - _giveAtMs < GiveTargetMs && w.Exists(_giveId))
{
to = _giveId;
name = _giveName;
return true;
}
uint prev = w.PreviousSelectedId;
if (prev != 0 && prev != item && prev != player && w.CanReceive(prev))
{
to = prev;
name = w.TryGetName(prev, out string n) ? n : $"0x{prev:X8}";
return true;
}
to = 0;
name = string.Empty;
return false;
}
// ── /rdef qty ───────────────────────────────────────────────────────────
/// <summary>Sets the box (null: says what it is). "max" and "half" are of what is selected.</summary>
public void SetBox(IQtyWorld w, QtyAmount? amount)
{
QtySubject s = Analyze(w);
if (amount is { } a)
{
if (a.Word != QtyWord.Number && s.BoxMax < 1)
{
Say(w, false, s.Mode == QtyMode.Vendor ? s.Quote?.Refusal(1) ?? QtyReplies.MaxNeedsSelection : QtyReplies.MaxNeedsSelection);
return;
}
Value = QuantityRules.ForBox(a, s.BoxMax);
}
Say(w, true, $"Quantity {QuantityRules.N(Value)}{About(s)}.");
}
private string About(QtySubject s) => s.Mode switch
{
QtyMode.Stack => $" (the selected {s.Name}: a stack of {QuantityRules.N(s.Stack)}; a split takes up to {QuantityRules.N(s.Stack - 1)})",
QtyMode.Vendor when s.Quote != null => $" (the vendor's {s.Name}: {s.Quote.PriceLine(Value)}; you can buy {QuantityRules.N(s.MaxBuy)})",
_ => string.Empty,
};
// ── Split ───────────────────────────────────────────────────────────────
/// <summary>
/// Splits the box's number (or <paramref name="amount"/>) off the selected stack into
/// <paramref name="into"/> (a pack's name; empty = the pack chosen in the window, else the main pack).
/// </summary>
public void Split(IQtyWorld w, QtyAmount? amount, string into)
{
if (_pending != null) { Say(w, false, QtyReplies.Busy); return; }
if (!w.CanSplit) { Say(w, false, QtyReplies.NoSplitApi); return; }
QtySubject s = Analyze(w);
string? why = s.Mode switch
{
QtyMode.None => QtyReplies.NothingSelected,
QtyMode.Vendor => QtyReplies.VendorsItem(s.Name),
QtyMode.Single => QtyReplies.NotAStack(s.Name),
_ => s.Where switch
{
QtyWhere.Wielded => QtyReplies.Wielded(s.Name),
QtyWhere.Carried or QtyWhere.Open => null,
_ => QtyReplies.NotReachable(s.Name),
},
};
if (why != null) { Say(w, false, why); return; }
IReadOnlyList<QtyPack> packs = w.Packs();
if (!TryPickTarget(packs, into, out QtyPack target, out why)) { Say(w, false, why); return; }
if (target.Free == 0) { Say(w, false, QtyReplies.PackFull(target.Where)); return; }
int n = QuantityRules.ForSplit(amount ?? QtyAmount.Of(Value), s.Stack);
var p = new Pending
{
Kind = PendingKind.Split, Id = s.Id, Name = s.Name, N = n, Where = target.Where,
StackBefore = s.Stack, RefusalSeq = w.RefusalSeq, AtMs = w.NowMs,
};
if (!w.Split(s.Id, target.Id, n)) { Say(w, false, QtyReplies.NotSent("split")); return; }
_pending = p;
}
/// <summary>The split's pack: the one named, else the one chosen in the window (if it's still there), else the main pack.</summary>
internal bool TryPickTarget(IReadOnlyList<QtyPack> packs, string typed, out QtyPack target, out string why)
{
target = default;
why = string.Empty;
if (packs.Count == 0) { why = "Your packs can't be read yet: try again in a moment."; return false; }
string t = (typed ?? string.Empty).Trim();
if (t.Length == 0)
{
uint into = Into;
target = packs[0];
foreach (QtyPack p in packs) if (p.Id == into) { target = p; break; }
return true;
}
string low = t.ToLowerInvariant();
if (low is "main" or "main pack" or "mainpack" or "pack" or "me" or "inventory")
{
target = packs[0];
return true;
}
if (low is "open" or "chest" or "container" or "the chest" or "the open container")
{
foreach (QtyPack p in packs) if (p.Kind == QtyPackKind.Open) { target = p; return true; }
why = "No chest or other container is open: open it first, or split into one of your packs.";
return false;
}
// The pack's own name: the whole of it, then its start, then any part of it.
foreach (QtyPack p in packs) if (p.Name.Equals(t, StringComparison.OrdinalIgnoreCase) || p.Label.Equals(t, StringComparison.OrdinalIgnoreCase)) { target = p; return true; }
foreach (QtyPack p in packs) if (p.Name.StartsWith(t, StringComparison.OrdinalIgnoreCase)) { target = p; return true; }
foreach (QtyPack p in packs) if (p.Name.Contains(t, StringComparison.OrdinalIgnoreCase)) { target = p; return true; }
var names = new List<string>(packs.Count);
foreach (QtyPack p in packs) names.Add(p.Label);
why = QtyReplies.NoSuchPack(t, string.Join(", ", names));
return false;
}
// ── Give ────────────────────────────────────────────────────────────────
/// <summary>Gives the box's number (or <paramref name="amount"/>) of the selected stack to the last player or NPC selected.</summary>
public void Give(IQtyWorld w, QtyAmount? amount)
{
if (_pending != null) { Say(w, false, QtyReplies.Busy); return; }
if (!w.CanGive) { Say(w, false, QtyReplies.NoGiveApi); return; }
QtySubject s = Analyze(w);
string? why = s.Mode switch
{
QtyMode.None => QtyReplies.NothingSelected,
QtyMode.Vendor => QtyReplies.VendorsItem(s.Name),
_ => s.Where switch
{
QtyWhere.Wielded => QtyReplies.Wielded(s.Name),
QtyWhere.Carried => null,
_ => QtyReplies.NotCarried(s.Name),
},
};
if (why != null) { Say(w, false, why); return; }
if (!TryGiveTarget(w, s.Id, out uint to, out string toName)) { Say(w, false, QtyReplies.NoGiveTarget); return; }
int n = QuantityRules.ForGive(amount ?? QtyAmount.Of(Value), s.Stack);
var p = new Pending
{
Kind = PendingKind.Give, Id = s.Id, Name = s.Name, N = n, Where = toName,
StackBefore = s.Stack, RefusalSeq = w.RefusalSeq, AtMs = w.NowMs,
};
// 0 = the whole of it (the give the client sends for a drag of the whole stack).
if (!w.Give(s.Id, to, n >= s.Stack ? 0 : n)) { Say(w, false, QtyReplies.NotSent("give")); return; }
_pending = p;
}
// ── Buy ─────────────────────────────────────────────────────────────────
/// <summary>Buys the box's number (or <paramref name="amount"/>) of the selected vendor item, or the one named.</summary>
public void Buy(IQtyWorld w, QtyAmount? amount, string itemName)
{
if (_pending != null) { Say(w, false, QtyReplies.Busy); return; }
if (!w.CanTrade) { Say(w, false, QtyReplies.NoTradeApi); return; }
if (!w.TryGetVendor(out VendorInfo info)) { Say(w, false, QtyReplies.NoVendor); return; }
if (!info.TradingAvailable) { Say(w, false, QtyReplies.VendorUnreadable); return; }
if (info.TradeInFlight) { Say(w, false, QtyReplies.VendorBusy); return; }
IReadOnlyList<VendorItem> items = w.VendorItems();
VendorItem? item;
string name = (itemName ?? string.Empty).Trim();
if (name.Length > 0)
{
item = FindVendorItem(items, name, out string? why);
if (item == null) { Say(w, false, why!); return; }
}
else
{
item = null;
uint sel = w.SelectedId;
foreach (VendorItem it in items) if (it.ObjectId == sel && sel != 0) { item = it; break; }
if (item == null) { Say(w, false, QtyReplies.NoVendorItem); return; }
}
VendorQuote q = Quote(w, info, item);
int n = amount is { } a ? QuantityRules.ForBuy(a, q.MaxBuy()) : Value;
if (n < 1) { Say(w, false, q.Refusal(1) ?? $"You can't buy any {item.Name} now."); return; }
string? refusal = q.Refusal(n);
if (refusal != null) { Say(w, false, refusal); return; }
uint request = w.Buy(info.VendorId, item.ObjectId, n);
if (request == 0)
{
Say(w, false, QtyReplies.VendorRefusal(w.TryGetTradeStatus(out VendorTradeStatus st) ? st.Message : null));
return;
}
_pending = new Pending
{
Kind = PendingKind.Buy, Id = item.ObjectId, Name = item.Name, N = n, RequestId = request,
Cost = q.Cost(n), Currency = q.Currency, AtMs = w.NowMs,
};
}
/// <summary>A vendor's item by name: the whole name, else the one whose name starts so, else the one that holds it. Several = ask for more.</summary>
internal static VendorItem? FindVendorItem(IReadOnlyList<VendorItem> items, string name, out string? why)
{
why = null;
foreach (VendorItem it in items) if (it.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) return it;
foreach (bool starts in new[] { true, false })
{
VendorItem? found = null;
var names = new List<string>();
foreach (VendorItem it in items)
{
bool match = starts ? it.Name.StartsWith(name, StringComparison.OrdinalIgnoreCase) : it.Name.Contains(name, StringComparison.OrdinalIgnoreCase);
if (!match) continue;
if (!names.Exists(x => x.Equals(it.Name, StringComparison.OrdinalIgnoreCase))) names.Add(it.Name);
found ??= it;
}
if (names.Count == 1) return found;
if (names.Count > 1)
{
why = $"'{name}' could be {string.Join(", ", names.GetRange(0, Math.Min(5, names.Count)))}{(names.Count > 5 ? ", ..." : "")}: type more of the name.";
return null;
}
}
why = $"The vendor doesn't sell '{name}'.";
return null;
}
// ── Waiting for the game ────────────────────────────────────────────────
private enum PendingKind { Split, Give, Buy }
private sealed class Pending
{
public PendingKind Kind;
public uint Id;
public string Name = string.Empty;
public int N;
/// <summary>Split: the pack ("the main pack"); give: who to.</summary>
public string Where = string.Empty;
public int StackBefore;
public int RefusalSeq;
public long AtMs;
public long RefusedAtMs;
public uint Error;
public bool RefusalNamesItem;
public uint RequestId;
public long Cost;
public string Currency = string.Empty;
}
/// <summary>Plugin tick: the give target, and the answer to the action in flight.</summary>
public void Tick(IQtyWorld w)
{
NoteSelection(w);
Pending? p = _pending;
if (p == null) return;
long now = w.NowMs;
switch (p.Kind)
{
case PendingKind.Split:
{
int stack = w.StackOf(p.Id);
if (stack > 0 && stack < p.StackBefore) Finish(w, true, QtyReplies.Splitting(p.N, p.Name, p.Where));
else if (RefusedNow(w, p, now)) Finish(w, false, QtyReplies.Refused("split", p.Error));
else if (now - p.AtMs >= SplitAnswerMs) Finish(w, false, QtyReplies.NoAnswer("split"));
break;
}
case PendingKind.Give:
{
int stack = w.StackOf(p.Id);
bool left = !w.Exists(p.Id) || !Owned(w, p.Id);
if (left || (stack > 0 && stack < p.StackBefore)) Finish(w, true, QtyReplies.Gave(p.N, p.Name, p.Where));
else if (RefusedNow(w, p, now)) Finish(w, false, QtyReplies.Refused("give", p.Error));
else if (now - p.AtMs >= GiveAnswerMs) Finish(w, false, QtyReplies.NoAnswer("give"));
break;
}
case PendingKind.Buy:
WatchBuy(w, p, now);
break;
}
}
private void WatchBuy(IQtyWorld w, Pending p, long now)
{
if (w.TryGetTradeStatus(out VendorTradeStatus s))
{
if (s.RequestId == p.RequestId)
{
if (s.State == VendorTradeState.Refused) { Finish(w, false, QtyReplies.VendorRefusal(s.Message)); return; }
if (s.State == VendorTradeState.Done)
{
if (s.Result == VendorTradeResult.Accepted)
Finish(w, true, QtyReplies.Bought(p.N, p.Name, s.Estimate > 0 ? s.Estimate : p.Cost, p.Currency));
else if (s.Result == VendorTradeResult.TimedOut)
Finish(w, false, $"No answer from the vendor about {QuantityRules.N(p.N)} {p.Name}: check your pack and {p.Currency} before trying again.");
else
Finish(w, false, $"The vendor didn't sell {QuantityRules.N(p.N)} {p.Name}: the server said no (money, room, or too busy).");
return;
}
}
else if (s.RequestId > p.RequestId)
{
// Another plugin's trade came after ours: the engine keeps only the newest one's status.
Finish(w, true, $"Asked the vendor for {QuantityRules.N(p.N)} {p.Name}; another trade followed it, so check your pack.");
return;
}
}
if (now - p.AtMs >= BuyAnswerMs)
Finish(w, false, $"No answer about {QuantityRules.N(p.N)} {p.Name}: check your pack and {p.Currency} before trying again.");
}
/// <summary>
/// The server refused it: a refusal naming the item (InventoryServerSaveFailed) at once, any other
/// new refusal once nothing changed for RefusalGraceMs after it (a fight's own errors pass by).
/// </summary>
private static bool RefusedNow(IQtyWorld w, Pending p, long now)
{
int seq = w.RefusalSeq;
if (p.RefusedAtMs == 0 && seq != 0 && seq != p.RefusalSeq && w.LastRefusal(out uint error, out uint eventType, out uint obj))
{
p.RefusalSeq = seq;
bool names = eventType == InventorySaveFailed && obj != 0;
if (names && obj != p.Id) return false; // another item's
p.RefusedAtMs = now;
p.Error = error;
p.RefusalNamesItem = names;
}
return p.RefusedAtMs != 0 && (p.RefusalNamesItem || now - p.RefusedAtMs >= RefusalGraceMs);
}
private void Finish(IQtyWorld w, bool ok, string text)
{
_pending = null;
Say(w, ok, text);
}
}

View file

@ -89,6 +89,25 @@ buttons (All, Melee, Missile, War, Void) narrow it, and the one you leave presse
hand is highlighted. **One click wields.** `+` in front of a row adds a favourite; favourites and the last
weapons you wielded are listed first (they are also in their kind's group).
## The quantity box
Under a selected stack, or an item in an open vendor's list, the Selection window shows how many: type the
number (the game gets no keys while the box has the keyboard) or pick 1, 10, 100, half or max.
* **A stack you carry** (or one in the chest you have open): **Split N** puts N into a new stack in the main
pack, a side pack or the open container (*into ...* picks; the number is its free slots). One always stays in
the stack, so more than the stack splits all but one. **Give N** hands N (up to the whole stack) to the last
player or NPC you selected: select them, then the stack.
* **An item in a vendor's list**: **Buy N**, with its price and your pyreals (or the vendor's own currency).
*max* is the most you can buy: what the vendor has, what you can pay for, what your packs and burden take.
A buy that can't go says why before anything is sent ("Not enough pyreals: 100 Mana Scarab cost 1,200, you
have 1,000 (you can buy 83)", "The pack is full ..."); the engine checks again before it sends.
* Every action answers once, in chat and on the box's last line: done, the server's refusal, or no answer.
One action at a time.
* The same from chat, hotkeys and metas, with the window hidden: `/rdef qty`, `/rdef split`, `/rdef give`,
`/rdef buy` (below). It doesn't need the Inventory panel or RynthInventory.
* Retail AC kept this number in its toolbar; RynthCore's *Hide retail toolbar* hides it with the toolbar.
## Busy, combat and RynthAi
* One item action at a time: a request waits while the client is busy, a gesture animates, RynthAi waits on
@ -123,6 +142,11 @@ weapons you wielded are listed first (they are also in their kind's group).
/rdef weapons [search] show the weapon picker
/rdef fav make the selected weapon a favourite (or take it out)
/rdef slots <n> how many slots the script-window bar shows (1-24)
/rdef qty [n | max | half] the quantity box's number (alone: what it is and what it's of)
/rdef split [n] [into <pack>] split n (or the box's number) off the selected stack; pack: main, a side
pack's name, or open (the chest you have open)
/rdef give [n] give n of the selected stack to the last player or NPC you selected
/rdef buy [n] [item name] buy n of the selected vendor item (or the one named) from the open vendor
/rdef list | status | help
```
@ -131,8 +155,8 @@ slot N is bar slot 18+N, or bar slot N when the bar is independent of the game's
## Settings
Shortcuts bar: the windows shown, independent of the game's toolbar, slot picture size, allow weapon swaps
under RynthAi, picker row icon size. Script-window bar: slots (1-24), slots per row, button size, picker row
Shortcuts bar: the windows shown, the quantity box under the selection (on by default), independent of the
game's toolbar, slot picture size, allow weapon swaps under RynthAi, picker row icon size. Script-window bar: slots (1-24), slots per row, button size, picker row
icon size, item icons on/off, counts and keys on/off, allow weapon swaps under RynthAi. Kept per character
with the slots, favourites and recent weapons in
`<RynthSuite>\RynthDefective\characters\<server>_<character>.json`.
@ -146,3 +170,4 @@ Pages, arrow auto-equip, gear highlight, summon cooldown counters and the war-ma
RynthCore engine API 71 with ImGui for the windows (op level 2 for pictures; text buttons without it);
API 90 for the Shortcuts bar, Game Panels and Selection. `/rdef use` works on any engine with UseObject.
The quantity commands: splitting on any engine, giving with a count API 62, buying API 67.

View file

@ -31,7 +31,7 @@
pictures) are checked first; so are the UseDone count (v63), wield/refusal info (v70) and
the chat parser the key binding goes through. Below v71 it still uses items (/rdef use). -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Draws the Shortcuts bar (the game's 18 slots and its own), the Game Panels buttons and the Selection window: one-touch kits, potions, weapons and spells by slot or key, and a fast weapon picker. Settings: the bar's gear or /rdef settings.</RynthPluginDescription>
<RynthPluginDescription>Draws the Shortcuts bar (the game's 18 slots and its own), the Game Panels buttons and the Selection window (with a quantity box: split, give or buy that many): one-touch kits, potions, weapons and spells by slot or key, and a fast weapon picker. Settings: the bar's gear or /rdef settings.</RynthPluginDescription>
</PropertyGroup>
<ItemGroup>

View file

@ -0,0 +1,76 @@
// ============================================================================
// RynthDefective - RynthDefectivePlugin.Quantity.cs
// The quantity box (2026-10-30, Quantity/QuantityController.cs): its commands
// (/rdef qty, split, give, buy), the Selection window's buttons, and the tick
// that notes the give target and watches the action in flight.
//
// It lives here, with the Selection window, because the number is about what
// is selected (as retail's toolbar had it): it needs no inventory panel, and
// every command works with the window hidden or on an engine without it.
// ============================================================================
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Quantity;
using RynthCore.Plugin.RynthDefective.ShortcutBar;
namespace RynthCore.Plugin.RynthDefective;
public sealed partial class RynthDefectivePlugin
{
private readonly QuantityController _qty = new();
private HostQtyWorld? _qtyWorld;
private long _nextQtyTickMs;
private HostQtyWorld QtyWorld => _qtyWorld ??= new HostQtyWorld(Host);
/// <summary>Every answer of the box goes to chat (and to the window's line).</summary>
private void InitQuantity()
{
_qty.Report = (ok, text) => Reply.Say(ok, text);
}
private void RunQuantityCommand(DefCommand c)
{
switch (c.Verb)
{
case DefVerb.Quantity: _qty.SetBox(QtyWorld, c.Amount); break;
case DefVerb.Split: _qty.Split(QtyWorld, c.Amount, c.Text); break;
case DefVerb.Give: _qty.Give(QtyWorld, c.Amount); break;
case DefVerb.Buy: _qty.Buy(QtyWorld, c.Amount, c.Text); break;
}
}
/// <summary>A button in the Selection window's box, with the count it showed (queued from the render thread).</summary>
private void RunQuantityClick(QtyClick click, int n)
{
if (!_identityKnown) return;
QtyAmount amount = QtyAmount.Of(n);
switch (click)
{
case QtyClick.Split: _qty.Split(QtyWorld, amount, string.Empty); break;
case QtyClick.Give: _qty.Give(QtyWorld, amount); break;
case QtyClick.Buy: _qty.Buy(QtyWorld, amount, string.Empty); break;
}
}
/// <summary>Plugin tick, ten times a second: the give target and the answer to the action in flight.</summary>
private void TickQuantity(long now)
{
if (!_inWorld || !_identityKnown || now < _nextQtyTickMs) return;
_nextQtyTickMs = now + 100;
try { _qty.Tick(QtyWorld); }
catch (System.Exception ex) { Host.Log($"[RynthDefective] quantity tick failed: {ex.GetType().Name}: {ex.Message}"); }
}
/// <summary>The Selection window's box for what is selected (null: none, or the setting is off).</summary>
private QuantityView? QuantityViewNow()
{
if (!_session.Settings.QuantityBox) return null;
try { return _qty.View(QtyWorld); }
catch (System.Exception ex)
{
Host.Log($"[RynthDefective] quantity view failed: {ex.GetType().Name}: {ex.Message}");
return null;
}
}
}

View file

@ -48,7 +48,11 @@ public sealed partial class RynthDefectivePlugin
System.Threading.Volatile.Write(ref _selectionDrawnMs, Environment.TickCount64);
try
{
_selectionWindow ??= new SelectionWindow(Host, id => QueueBar(() => { if (!Host.UseObject(id)) Print("That can't be used now."); }));
_selectionWindow ??= new SelectionWindow(Host, id => QueueBar(() => { if (!Host.UseObject(id)) Print("That can't be used now."); }))
{
Quantity = _qty,
QuantityAction = (click, n) => QueueBar(() => RunQuantityClick(click, n)),
};
wantHeight = _selectionWindow.Draw(_selectionView);
_selectionFailures = 0;
return 1;
@ -86,11 +90,16 @@ public sealed partial class RynthDefectivePlugin
Host.QueryHealth(sel);
}
// The quantity box (a stack, or an item in the open vendor's list).
Quantity.QuantityView? qty = QuantityViewNow();
string where = string.Empty;
float relative = float.NaN;
Items.CarriedItem? carried = null;
foreach (var it in _session.Items()) if (it.Id == sel) { carried = it; break; }
if (carried != null) where = CarriedText(carried);
if (qty?.Subject.Mode == Quantity.QtyMode.Vendor && qty.Subject.Quote is { } quote)
where = "the vendor's" + (quote.UnitPrice > 0 ? $" · {quote.UnitPrice.ToString("N0", CultureInfo.InvariantCulture)} {quote.Currency} each" : "");
else if (carried != null) where = CarriedText(carried);
else if (Host.TryGetObjectPosition(sel, out uint oc, out float ox, out float oy, out float oz) && oc != 0
&& Host.TryGetPlayerPose(out uint pc, out float px, out float py, out float pz, out float qw, out _, out _, out float qz) && pc != 0)
{
@ -106,12 +115,13 @@ public sealed partial class RynthDefectivePlugin
where = $"{dist.ToString(dist < 10 ? "0.0" : "0", CultureInfo.InvariantCulture)} yd {Compass(bearing)}";
}
// Not carried (on the ground, in a corpse or chest): AC's own stack size.
if (carried == null && Host.TryGetObjectIntProperty(sel, StackSizeProperty, out int stack) && stack > 1)
if (carried == null && qty?.Subject.Mode != Quantity.QtyMode.Vendor
&& Host.TryGetObjectIntProperty(sel, StackSizeProperty, out int stack) && stack > 1)
where = "stack of " + stack.ToString("N0", CultureInfo.InvariantCulture) + (where.Length > 0 ? " · " + where : "");
HealthSeen? h = _health;
float health = h != null && h.Id == sel ? h.Ratio : -1f;
return new SelectionView(true, sel, name, where, relative, health, h?.Current ?? 0, h?.Max ?? 0);
return new SelectionView(true, sel, name, where, relative, health, h?.Current ?? 0, h?.Max ?? 0) { Qty = qty };
}
private const uint StackSizeProperty = 12; // PropertyInt.StackSize

View file

@ -63,6 +63,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
public override int Initialize()
{
_reply = new CommandReply("[RynthDefective]", (t, c) => Host.WriteToChat(t, c), t => Host.Log(t));
InitQuantity();
_ui.Log = msg => Host.Log(msg);
// The shortcut bar (plugin API v90) draws with ImGui.NET bound to the engine's cimgui, in its look.
RynthCore.Plugin.Shared.ImGuiNativeBinding.Ensure(msg => Host.Log("[RynthDefective] " + msg));
@ -115,6 +116,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
_nextIdentityTryMs = Environment.TickCount64;
_session.Use.ResetSession();
_world?.Reset();
_qty.Reset();
}
public override void OnLogout()
@ -126,6 +128,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
_session.LoggedIn = false;
_session.Use.ResetSession();
_world?.Reset();
_qty.Reset();
_barView = RynthCore.Plugin.RynthDefective.ShortcutBar.BarSnapshot.NotReady;
foreach (UiWindow? w in new[] { _barWindow, _pickerWindow, _settingsWindow })
if (w != null) { w.Visible = false; w.NeedsPass = true; }
@ -276,6 +279,13 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
case DefVerb.Status:
PrintStatus();
break;
case DefVerb.Quantity:
case DefVerb.Split:
case DefVerb.Give:
case DefVerb.Buy:
// The quantity box: each answers once, at once when it can't go, else when the game answers.
RunQuantityCommand(c);
break;
}
MarkAllForPass();
}
@ -287,6 +297,8 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
Print("RynthDefective draws the Shortcuts bar, the Game Panels buttons and the Selection window. Its settings: /rdef settings, "
+ "or the gear on the bar; right-click the bar's title to show or hide Game Panels and Selection.");
Print("A key for a slot: /rdef bind 1 F9 (or Edit slots in the bar). Any item by name from Settings > Hotkeys: /rc hotkey add F9 /rdef use Stamina Kit.");
Print("How many of a stack or a vendor's item: the box under it in the Selection window, or /rdef qty 25, then /rdef split, /rdef give "
+ "(to the last player or NPC you selected) or /rdef buy (the selected vendor item, or /rdef buy 25 <item name>).");
}
private void PrintSlots()
@ -440,6 +452,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
if (_saveDueMs != 0 && now >= _saveDueMs) SaveNow();
TickBar(now);
TickSelection(now);
TickQuantity(now);
TickCorpses(now);
// With the shortcut bar the old script-window bar stays shut (the weapon picker is still one), and

View file

@ -0,0 +1,290 @@
// ============================================================================
// RynthDefective - ShortcutBar/SelectionWindow.Quantity.cs
// The quantity box under the selection (2026-10-30, Quantity/QuantityController):
// for a stack, a number with 1 / 10 / 100 / half / max, Split N into a pack
// and Give N to the last player or NPC selected; for an item in a vendor's
// list, Buy N with its price and what you have. Retail AC had this number in
// its toolbar (gone with "Hide retail toolbar"); this one is RynthDefective's.
//
// line 1 the number (typed: the game gets no keys while it has the
// keyboard) and the quick numbers
// line 2 Split N | into <pack> | Give N or Buy N | the price
// line 3 what the last action did, or what the buttons will do
//
// Render thread: draws the view the tick built. The number and the pack are
// set at once (QuantityController.Value / Into); the actions go to the tick.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Quantity;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthDefective.ShortcutBar;
/// <summary>A click on one of the box's buttons.</summary>
internal enum QtyClick { Split, Give, Buy }
internal sealed partial class SelectionWindow
{
/// <summary>The box's number and pack (set from here) and its last answer; null = no box.</summary>
public QuantityController? Quantity { get; set; }
/// <summary>A Split / Give / Buy click, with the count on the button (queued to the tick).</summary>
public Action<QtyClick, int>? QuantityAction { get; set; }
private const float QRow = 18, QGap = 4, QField = 54, QChipGap = 3;
private const string IntoPopupId = "##qty_into";
private static readonly uint OkColor = Argb(0xFF73D885), BadColor = Argb(0xFFE0564E), WarnColor = Argb(0xFFE8B04A);
/// <summary>The box's height under the selection (pixels); 0 = none.</summary>
private float QuantityHeight(QuantityView? q) =>
q == null || Quantity == null ? 0f
: MathF.Ceiling(Px(QGap) + Px(QRow) + Px(QGap) + Px(QRow) + Px(QGap) + Fs(Font(RynthUiFont.Narrow9)) + Px(Pad));
private void DrawQuantity(ImDrawListPtr dl, QuantityView q, Vector2 top, float width)
{
QuantityController ctl = Quantity!;
float pad = Px(Pad), rowH = Px(QRow), gap = Px(QGap);
float left = top.X + pad, right = top.X + width - pad;
dl.AddLine(new Vector2(left, top.Y), new Vector2(right, top.Y), A(_line, 0.8f));
QtySubject s = q.Subject;
int value = ctl.Value;
float y = top.Y + gap;
// Line 1: the number and the quick numbers.
float fieldW = Math.Min(Px(QField), Math.Max(Px(30), right - left));
NumberField(ctl, new Vector2(left, y), fieldW, rowH, s);
float x = left + fieldW + Px(QChipGap + 2);
int max = s.BoxMax;
string none = s.Mode == QtyMode.Vendor ? s.Quote?.Refusal(1) ?? "You can't buy any now." : "Nothing to count.";
if (Chip(dl, "##qty_1", "1", ref x, y, rowH, right, true, "One.")) ctl.Value = 1;
if (Chip(dl, "##qty_10", "10", ref x, y, rowH, right, true, "Ten.")) ctl.Value = 10;
if (Chip(dl, "##qty_100", "100", ref x, y, rowH, right, true, "A hundred.")) ctl.Value = 100;
string halfTip = max < 1 ? none
: s.Mode == QtyMode.Vendor ? $"Half of the most you can buy now ({QuantityRules.N(QuantityRules.HalfOf(max))})."
: $"Half the stack ({QuantityRules.N(QuantityRules.HalfOf(max))}).";
if (Chip(dl, "##qty_half", "half", ref x, y, rowH, right, max >= 1, halfTip)) ctl.Value = QuantityRules.ForBox(QtyAmount.Half, max);
string maxTip = max < 1 ? none
: s.Mode == QtyMode.Vendor ? $"The most you can buy now ({QuantityRules.N(max)}): what the vendor has, you can pay for and your packs take."
: $"The whole stack ({QuantityRules.N(max)}). A split still leaves one.";
if (Chip(dl, "##qty_max", "max", ref x, y, rowH, right, max >= 1, maxTip)) ctl.Value = QuantityRules.ForBox(QtyAmount.Max, max);
ImFontPtr sf = Font(RynthUiFont.Narrow9);
string of = s.Mode == QtyMode.Stack ? "of " + QuantityRules.N(s.Stack) : max >= 1 ? "up to " + QuantityRules.N(max) : string.Empty;
float ofW = of.Length > 0 ? sf.CalcTextSizeA(Fs(sf), float.MaxValue, 0f, of).X : 0f;
if (of.Length > 0 && x + ofW <= right + 0.5f)
dl.AddText(sf, Fs(sf), new Vector2(MathF.Round(right - ofW), MathF.Round(y + (rowH - Fs(sf)) * 0.5f)), _faint, of);
// Line 2: what the number does.
y += rowH + gap;
x = left;
if (s.Mode == QtyMode.Stack) StackButtons(dl, q, ctl, value, ref x, y, rowH, right);
else VendorButtons(dl, q, value, ref x, y, rowH, right);
// Line 3: the last answer, or what the buttons do.
y += rowH + gap;
QtyStatus? st = ctl.StatusAt(Environment.TickCount64);
string line;
uint color;
if (st != null) { line = st.Text; color = st.Ok ? OkColor : BadColor; }
else if (q.Busy) { line = "Waiting for the server..."; color = _dim; }
else Hint(q, value, out line, out color);
if (line.Length > 0)
{
ImGui.SetCursorScreenPos(new Vector2(left, y));
ImGui.InvisibleButton("##qty_line", new Vector2(Math.Max(1, right - left), Math.Max(1, Fs(sf))));
SafeImGui.SetItemTooltip(line);
Clip(dl, sf, Fs(sf), new Vector2(left, y), color, line, right - left);
}
}
private void StackButtons(ImDrawListPtr dl, QuantityView q, QuantityController ctl, int value, ref float x, float y, float h, float right)
{
QtySubject s = q.Subject;
bool reach = s.Where is QtyWhere.Carried or QtyWhere.Open;
int split = QuantityRules.SplitCount(value, s.Stack);
QtyPack? into = q.Target;
string splitTip = !q.CanSplit ? QtyReplies.NoSplitApi
: q.Busy ? QtyReplies.Busy
: s.Where == QtyWhere.Wielded ? QtyReplies.Wielded(s.Name)
: !reach ? QtyReplies.NotReachable(s.Name)
: into is { Free: 0 } full ? QtyReplies.PackFull(full.Where)
: $"Split {QuantityRules.N(split)} off the stack of {QuantityRules.N(s.Stack)} into {into?.Where ?? "the main pack"}: a new stack there."
+ (value >= s.Stack ? " One always stays in the stack." : string.Empty);
bool canSplit = q.CanSplit && !q.Busy && reach;
if (Chip(dl, "##qty_split", "Split " + QuantityRules.N(split), ref x, y, h, right, canSplit, splitTip, primary: true))
QuantityAction?.Invoke(QtyClick.Split, split);
// Where the split goes.
if (into is { } t)
{
string free = t.Free >= 0 ? " · " + t.Free.ToString(System.Globalization.CultureInfo.InvariantCulture) : string.Empty;
string label = "into " + t.Label + free;
float before = x;
if (Chip(dl, "##qty_into_btn", label, ref x, y, h, right, q.Targets.Length > 1 && !q.Busy,
q.Targets.Length > 1 ? "Where the split goes: the main pack, a side pack or the container you have open (the number is its free slots)."
: "Where the split goes (your only pack).", textColor: t.Free == 0 ? BadColor : null, caret: q.Targets.Length > 1))
ImGui.OpenPopup(IntoPopupId);
if (x == before && right - x > Px(40))
{
// No room for the whole label: the pack's name cut short.
if (Chip(dl, "##qty_into_btn2", "into...", ref x, y, h, right, q.Targets.Length > 1 && !q.Busy, "Into " + t.Label + free + ".", caret: q.Targets.Length > 1))
ImGui.OpenPopup(IntoPopupId);
}
IntoMenu(q, ctl);
}
// Give to the last player or NPC selected.
int give = QuantityRules.GiveCount(value, s.Stack);
bool canGive = q.CanGive && !q.Busy && s.Where == QtyWhere.Carried && q.GiveTo != 0;
string giveTip = !q.CanGive ? QtyReplies.NoGiveApi
: q.Busy ? QtyReplies.Busy
: s.Where == QtyWhere.Wielded ? QtyReplies.Wielded(s.Name)
: s.Where != QtyWhere.Carried ? QtyReplies.NotCarried(s.Name)
: q.GiveTo == 0 ? QtyReplies.NoGiveTarget
: $"Give {QuantityRules.N(give)} {s.Name} to {q.GiveName} (the last player or NPC you selected).";
if (Chip(dl, "##qty_give", "Give " + QuantityRules.N(give), ref x, y, h, right, canGive, giveTip))
QuantityAction?.Invoke(QtyClick.Give, give);
}
private void IntoMenu(QuantityView q, QuantityController ctl)
{
if (!ImGui.IsPopupOpen(IntoPopupId)) return;
ImGui.PushStyleColor(ImGuiCol.PopupBg, WithAlpha(_bg, 0xFA));
ImGui.PushStyleColor(ImGuiCol.Border, _line);
ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, Px(4));
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(6), Px(5)));
bool open = ImGui.BeginPopup(IntoPopupId);
ImGui.PopStyleVar(2);
ImGui.PopStyleColor(2);
if (!open) return;
try
{
ImGui.TextDisabled("Split into");
ImGui.Separator();
for (int i = 0; i < q.Targets.Length; i++)
{
QtyPack p = q.Targets[i];
string free = p.Free < 0 ? "" : p.Free == 0 ? " (full)" : $" ({p.Free} free)";
// A menu item's label is drawn as it is (not a printf format); "##" keeps two packs of one name apart.
if (ImGui.MenuItem(p.Label + free + "##qty_into_" + i, null, i == q.TargetIndex, p.Free != 0))
ctl.Into = p.Kind == QtyPackKind.Main ? 0 : p.Id;
}
}
finally { ImGui.EndPopup(); }
}
private void VendorButtons(ImDrawListPtr dl, QuantityView q, int value, ref float x, float y, float h, float right)
{
QtySubject s = q.Subject;
VendorQuote? quote = s.Quote;
string? why = quote?.Refusal(value);
string tip = q.Busy ? QtyReplies.Busy
: why ?? (quote != null ? $"Buy {QuantityRules.N(value)} {s.Name} for {QuantityRules.N(quote.Cost(value))} {quote.Currency}. The vendor checks again before it sells." : "Buy.");
if (Chip(dl, "##qty_buy", "Buy " + QuantityRules.N(value), ref x, y, h, right, !q.Busy, tip, primary: why == null))
QuantityAction?.Invoke(QtyClick.Buy, value);
if (quote == null) return;
ImFontPtr sf = Font(RynthUiFont.Narrow9);
string price = quote.PriceLine(value);
Clip(dl, sf, Fs(sf), new Vector2(x + Px(2), MathF.Round(y + (h - Fs(sf)) * 0.5f)), why != null ? WarnColor : _dim, price, right - x - Px(2));
}
private void Hint(QuantityView q, int value, out string line, out uint color)
{
QtySubject s = q.Subject;
color = _faint;
if (s.Mode == QtyMode.Vendor)
{
string? why = s.Quote?.Refusal(value);
if (why != null) { line = why; color = WarnColor; return; }
line = s.Quote is { UnitPrice: > 0 } qq ? $"{QuantityRules.N(qq.UnitPrice)} {qq.Currency} each. /rdef buy N does the same." : "/rdef buy N does the same.";
return;
}
line = s.Where switch
{
QtyWhere.Wielded => QtyReplies.Wielded(s.Name),
QtyWhere.Open => "In the open container: Split takes them into your pack.",
QtyWhere.Carried when q.GiveTo != 0 => $"Give goes to {q.GiveName}.",
QtyWhere.Carried => "Split makes a new stack. To give: select the NPC, then this.",
_ => QtyReplies.NotReachable(s.Name),
};
if (s.Where is QtyWhere.Wielded or QtyWhere.Elsewhere or QtyWhere.Unknown) color = WarnColor;
}
/// <summary>The number: typed (keys stay out of the game while it has the keyboard), 1 or more.</summary>
private void NumberField(QuantityController ctl, Vector2 p, float w, float h, QtySubject s)
{
ImDrawListPtr dl = ImGui.GetWindowDrawList();
Vector2 size = new(w, h);
dl.AddRectFilled(p, p + size, _inset, Px(3));
ImFontPtr f = Font(RynthUiFont.Dash10);
ImGui.PushFont(f);
ImGui.SetWindowFontScale(_r);
float fs = ImGui.GetFontSize();
ImGui.PushStyleColor(ImGuiCol.FrameBg, 0u);
ImGui.PushStyleColor(ImGuiCol.FrameBgHovered, 0u);
ImGui.PushStyleColor(ImGuiCol.FrameBgActive, 0u);
ImGui.PushStyleColor(ImGuiCol.Border, 0u);
ImGui.PushStyleColor(ImGuiCol.Text, _text);
ImGui.PushStyleColor(ImGuiCol.TextSelectedBg, A(_accent, 0.45f));
ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 0f);
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(Px(4), Math.Max(0f, (h - fs) * 0.5f)));
bool active, hovered;
try
{
ImGui.SetCursorScreenPos(p);
ImGui.SetNextItemWidth(w);
int v = ctl.Value;
if (ImGui.InputInt("##qty_n", ref v, 0, 0, ImGuiInputTextFlags.AutoSelectAll | ImGuiInputTextFlags.CharsDecimal) && v >= 1)
ctl.Value = v;
active = ImGui.IsItemActive();
hovered = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(s.Mode == QtyMode.Vendor
? "How many to buy. Type it, or pick one beside it."
: "How many: Split and Give use this number. Type it, or pick one beside it.");
}
finally
{
ImGui.PopStyleVar(2);
ImGui.PopStyleColor(6);
ImGui.SetWindowFontScale(1f);
ImGui.PopFont();
}
dl.AddRect(p, p + size, active ? _accent : hovered ? A(_accent, 0.6f) : _line, Px(3));
}
/// <summary>A small flat button at x (moved past it); left out (false) when it doesn't fit before <paramref name="right"/>.</summary>
private bool Chip(ImDrawListPtr dl, string id, string label, ref float x, float y, float h, float right, bool enabled, string tip,
bool primary = false, uint? textColor = null, bool caret = false)
{
ImFontPtr f = Font(RynthUiFont.Narrow10);
float tw = f.CalcTextSizeA(Fs(f), float.MaxValue, 0f, label).X;
float caretW = caret ? Px(9) : 0f;
float w = MathF.Ceiling(tw + caretW + Px(10));
if (x + w > right + 0.5f) return false;
Vector2 p = new(MathF.Round(x), y), size = new(w, h);
ImGui.SetCursorScreenPos(p);
bool clicked = ImGui.InvisibleButton(id, size);
bool hot = enabled && ImGui.IsItemHovered();
if (tip.Length > 0) SafeImGui.SetItemTooltip(tip);
uint fill = primary ? A(_accent, hot ? 0.45f : 0.28f) : hot ? _key : A(_key, 0.6f);
dl.AddRectFilled(p, p + size, enabled ? fill : A(_key, 0.25f), Px(3));
dl.AddRect(p, p + size, hot ? _accent : A(_line, enabled ? 1f : 0.5f), Px(3));
uint tc = !enabled ? _faint : textColor ?? (hot || primary ? _text : _dim);
float tx = MathF.Round(p.X + (w - tw - caretW) * 0.5f);
dl.AddText(f, Fs(f), new Vector2(tx, MathF.Round(p.Y + (h - Fs(f)) * 0.5f)), tc, label);
if (caret)
{
// A small down arrow after the label.
float cx = tx + tw + Px(5), cy = p.Y + h * 0.5f, r = Px(2.5f);
dl.AddTriangleFilled(new Vector2(cx - r, cy - r * 0.5f), new Vector2(cx + r, cy - r * 0.5f), new Vector2(cx, cy + r * 0.7f), tc);
}
x += w + Px(QChipGap);
return clicked && enabled;
}
}

View file

@ -9,6 +9,8 @@
//
// the name row drag to move; Ctrl+wheel: bigger or smaller (30-250%);
// right-click: hide it (Settings > UI > Toolbar, /rdef selection).
// the quantity under a stack or a vendor's item (2026-10-30): how many, and
// Split / Give / Buy that many (SelectionWindow.Quantity.cs).
//
// AC's render thread; reads the view the tick built (SelectionView).
// ============================================================================
@ -17,6 +19,7 @@ using System;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthDefective.Quantity;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
@ -36,9 +39,12 @@ internal sealed record SelectionView(
uint Max)
{
public static readonly SelectionView NotReady = new(false, 0, string.Empty, string.Empty, float.NaN, -1f, 0, 0);
/// <summary>The quantity box for a stack or a vendor's item; null = none.</summary>
public QuantityView? Qty { get; init; }
}
internal sealed class SelectionWindow
internal sealed partial class SelectionWindow
{
public const string Title = "Selection";
@ -90,7 +96,10 @@ internal sealed class SelectionWindow
float pad = Px(Pad), icon = Px(Icon);
float height = MathF.Ceiling(2 * pad + icon);
Vector2 max = origin + new Vector2(width, height);
// The quantity box under it (a stack, or a vendor's item): one background for both.
QuantityView? qty = v.Ready && v.Id != 0 ? v.Qty : null;
float qtyH = QuantityHeight(qty);
Vector2 max = origin + new Vector2(width, height + qtyH);
dl.AddRectFilled(origin, max, A(_bg, 0.94f), Px(Radius));
dl.AddRect(origin, max, _line, Px(Radius));
@ -165,9 +174,11 @@ internal sealed class SelectionWindow
dl.AddText(uf, Fs(uf), new Vector2(MathF.Round(up.X + (useW - uw) * 0.5f), MathF.Round(up.Y + (Px(UseH) - Fs(uf)) * 0.5f)), hot ? _text : _dim, "USE");
if (use) _use(v.Id);
if (qty != null && qtyH > 0) DrawQuantity(dl, qty, new Vector2(origin.X, origin.Y + height), width);
ImGui.SetCursorScreenPos(origin);
ImGui.Dummy(new Vector2(width, height));
return height;
ImGui.Dummy(new Vector2(width, height + qtyH));
return height + qtyH;
}
/// <summary>Text cut with "..." to <paramref name="room"/> pixels.</summary>

View file

@ -51,6 +51,13 @@ internal sealed class BarSettingsView
WindowBox(w, BarTitle, "Shortcuts bar", "set.win.bar", "The item bar (/rdef). Its RynthCore bar button is the lightning bolt.");
WindowBox(w, PanelsTitle, "Game panel buttons", "set.win.panels", "Buttons for the game's own panels: pack, spellbook, map ... (/rdef panels).");
WindowBox(w, SelectionTitle, "Selection", "set.win.sel", "What is selected, how far and which way, and a creature's health (/rdef selection).");
if (WindowShown(SelectionTitle) != null)
{
w.Checkbox("Quantity box under a stack or a vendor's item", "set.qty", st.QuantityBox, v => { st.QuantityBox = v; Changed(); });
w.Tooltip("In the Selection window: how many, with 1 / 10 / 100 / half / max, then Split that many into a pack, "
+ "Give that many to the last player or NPC you selected, or Buy that many from the open vendor.\n"
+ "/rdef qty, /rdef split, /rdef give and /rdef buy do the same with it off. Kept for this character.");
}
w.SeparatorText("Shortcuts bar");
w.Checkbox("Independent of the game's toolbar", "set.indep", st.IndependentBar, v => Tell(_s.SetIndependent(v)));
@ -86,7 +93,8 @@ internal sealed class BarSettingsView
w.SeparatorText("About");
w.TextWrapped(SettingsPanel.Credit);
w.TextDisabled("Commands: /rdef (show or hide the bar), /rdef settings, /rdef panels, /rdef selection, /rdef weapons, /rdef use <slot or name>, /rdef help.");
w.TextDisabled("Commands: /rdef (show or hide the bar), /rdef settings, /rdef panels, /rdef selection, /rdef weapons, /rdef use <slot or name>, "
+ "/rdef qty, /rdef split, /rdef give, /rdef buy, /rdef help.");
}
private void WindowBox(UiWindow w, string title, string label, string id, string tip)