diff --git a/Changelog/2026-10-05-release-0.5.17-item-info-format.md b/Changelog/2026-10-05-release-0.5.17-item-info-format.md new file mode 100644 index 0000000..9d1bb22 --- /dev/null +++ b/Changelog/2026-10-05-release-0.5.17-item-info-format.md @@ -0,0 +1,71 @@ +# RynthAi 0.5.17-legacy-ui: item info line matches the ACECustom appraisal + +Date: 2026-10-05 +Branch: `feat/t11-loot-support` (uncommitted, on top of 0.5.16) + +## Problem + +The item info line (`/ra iteminfo`, ID on click) printed values that disagreed with the +appraisal panel. Example, a T11 Fire Staff: + +``` +Flaming Quarter Staff (Fire Staff), Craft 9 + FireRend, CritMult (2.66), 1,789.68-2069, 0.14v, 20%a, 20%md + [CD 24] +``` + +The appraisal panel shows Damage 1790 - 2069, Crushing Blow 3.66x, Fire Rending +176%, +Attack +20%, Melee Defense +20.0%, Weapon Grade S (100%) and "Wield requires: 2,000 Item +Augmentations". + +## Fixes (`ItemInfo/MagItemDescriber.cs`) + +- **Damage range:** the low end is rounded to a whole number like the client + (`2069 * (1 - 0.135)` gives 1790), with no group separator or decimals. Variance now shows + three places (`0.135v`), so values ending in 5 are no longer rounded off. +- **Attack and defense bonuses** are signed like the appraisal panel (`+20%a`, `+20%md`). + Penalties keep their `-`. A bonus that rounds to 0 is no longer printed. +- **Crushing Blow:** shows the multiplier a crit actually deals, 1 + CriticalMultiplier + (`Crushing Blow 3.66x`), instead of the raw `CritMult (2.66)`. As on the server, a stored 1.0 + (a normal 2x crit) is not shown. +- **Biting Strike:** shown as a crit chance (`Biting Strike 15%`) instead of `CritFreq (0.15)`. +- **Imbue strengths** are read from the "Property Details:" text: `FireRend +176%`, + `AR 30.0%`, `CS +12.5%`, `CB 2.5x`. Rendings are matched by damage keyword, and a culture + space before `%` is accepted. Items without detail text keep the bare Mag labels (`CS AR`). +- **T11 data from the item text:** + - weapon grade on the identity line (`Grade S (100%)`, under the Damage field setting); + - item-aug, Triune Weave and charm wield gates on the requirements line + (`Wield 2,000 Item Augs`, under the Wield setting); + - Cast on Strike procs (`Proc Force Arc 13%`, under the Imbues setting); + - zone modifiers on the ratings line (`Mods: Damage Resist +6, Max Health +100`, under the + Ratings setting). +- A raw `WieldRequirement.Int64Stat` (13) requirement no longer prints as `Skill 9008 2500`. + +Result for the staff above: + +``` +Flaming Quarter Staff (Fire Staff), Grade S (100%), Craft 9 + FireRend +176%, Crushing Blow 3.66x, 1790-2069, 0.135v, +20%a, +20%md + [CD 24] Wield 2,000 Item Augs +``` + +## Tests + +`Tools/RynthCore.RynthAiHostTests/Tests/MagItemDescriberTests.cs` adds 5 tests: +- the staff from the report, line for line; +- Biting Strike and a defense penalty; +- bare and detailed imbue labels; +- Int64 wield requirement hidden; +- T11 armor modifiers and Triune gate. + +All 5 pass. In the full host run, the only failure is the dungeon map bake check, which reads +the real dat files and is unrelated to this change. + +## Build 0.5.17-legacy-ui + +- `HandWrittenVersion` = `0.5.17-legacy-ui`. +- NativeAOT publish (win-x86), `-p:Version=0.5.17-legacy-ui`, staged at + `D:\rynth-merge\stage-suite\RynthAi-0.5.17\` (17,387,008 bytes, file version 0.5.17.0). +- Deploy: the live 0.5.16 DLL is saved to + `C:\Games\RynthSuite\RynthAi\PreviousReleases\0.5.16\`, then replaced. AC was running at + build time, so the copy waited for it to close; deployed 2026-10-06 00:14. diff --git a/Changelog/2026-10-05-t11-loot-support.md b/Changelog/2026-10-05-t11-loot-support.md new file mode 100644 index 0000000..e47c108 --- /dev/null +++ b/Changelog/2026-10-05-t11-loot-support.md @@ -0,0 +1,113 @@ +# T11 loot support (ACECustom tier 11+ items) + +Date: 2026-10-05 +Branch: `feat/t11-loot-support` +RynthAi plugin version: 0.5.16-legacy-ui (the deployed build was 0.5.15-legacy-ui from +`fix/restore-sk-features`; the branch's interim 0.5.1 / 0.5.2 numbers would have collided with +existing `PreviousReleases` folders) + +## Build 0.5.16-legacy-ui + +- NativeAOT publish (win-x86): `-p:Version=0.5.16-legacy-ui`, staged at + `D:\rynth-merge\stage-suite\RynthAi-0.5.16\` (17,372,672 bytes, file version 0.5.16.0). +- Deploy: the live 0.5.15 DLL is saved to + `C:\Games\RynthSuite\RynthAi\PreviousReleases\0.5.15\`, then replaced with 0.5.16. +- Server tiers are capped at 25 for now, so the tier estimate is capped at 25 + (`T11Catalog.MaxTier`). + +## Why + +ACECustom's tier 11+ drops don't look like retail items to a loot engine: + +- Every drop is renamed `T11 - ` and has no material. +- The appraisal strips the item-augmentation wield requirement (PropertyInt 158/159/160, + `WieldRequirement.Int64Stat = 13`) and prints it as text instead + (`Wield requires: 2,000 Item Augmentations`, plus Triune Weave and charm gates). +- Weapon grade (`- Weapon Grade: B+ (86% of max damage)`), Cast on Strike and the rolled + zone modifiers (`Modifiers:` block, `- Damage Rating +41 [14-69]`) exist only as text. + Weapons carry it in LongDesc, armor, clothing and jewelry in the Use string. +- A Gear* rating that comes from a modifier is removed from the appraisal's ratings, so + `TotalRatings` and `GearDamage >= N` rules read 0 on T11 gear. +- The player's item-augmentation and charm counts aren't sent at login. + +The change is client-only. Nothing changes on the server. + +## What changed + +### LootSdk (`Shared/RynthCore.LootSdk/T11/`) + +- `T11ItemInfo.Parse(name, longDesc, use)` reads the server's exact text: grade, damage %, + wield gates (any thousands separator), Cast on Strike, zone lock and the modifier block. + Modifier lines get their value, roll band and roll %, and unknown server keys + (`Modifier N`) are kept. Malformed text never throws. +- `T11Catalog` holds the ZoneModifiers catalog (key, name, Gear* rating), the weapon + sub-grades (S = 16 ... F- = 1) and the tier estimate from the wield gates. The item-aug + gate gives T11-T15 (2,000 = T11, 2,500 = T12, +500 per tier, frozen at 4,000 from T15). + From T16 the server adds a Triune Weave gate of 500 x (tier - 15), which gives T16-T25 + (500 = T16 ... 5,000 = T25, capped at 25). +- `T11PlayerAugs` / `T11AugReportParser` read the `/aug` reply (item augmentations, + Triune Weave, the four charms) and decide whether every wield gate is met. +- `T11Keys` adds virtual long keys in the block `0x52590000`, so they can't collide with + real properties: + + | Key | Value | + |-----|-------| + | T11: Is T11 | 1 / 0 | + | T11: Tier (est.) | 11-25 | + | T11: Weapon Grade | 16 = S ... 1 = F- (named in the editor) | + | T11: Damage % of Max | 0-100 | + | T11: Wield Item Augs / Wield Triune Weave | the gate amounts | + | T11: Can Wield | 1 yes, 0 no, -1 unknown (no `/aug` read, or not appraised yet) | + | T11: Modifier Count / Modifier Ratings / Avg Roll % / Best Roll % | from the modifier block | + | T11: Has Slot Special / Cast on Strike Count / Zone Locked | flags and counts | + | T11 Mod: | one key per catalog modifier (its rolled value) | + +- `LootRuleText`: the T11 keys and NetherResistRating (377) are now in the long-key picker. + The Use (14) and LongDesc (16) string keys and wield requirement 13 "Int64 Property" were + added, and Weapon Grade gets a value table. + +### RynthAi plugin + +- `WorldObject.Values(int)` answers the T11 virtual keys. For T11-named items it restores the + stripped keys when the live value is absent or 0: + 158 = 13, 159 = 9008, 160 = the item-aug gate, and 370-379 from the modifier lines. + As a result, existing wield-requirement rules, `TotalRatings` and `Gear*` rules work on + T11 gear without being edited. A value the item really has always wins. +- `T11ItemSupport` caches parsed text per object (re-parses only when the text changes, + drops entries on object delete and logout) and holds the player's counters. +- The `/aug` reply is read from chat. The ILT Hub already requests it at login. +- New command `/ra t11`: + - `/ra t11` shows the counters the loot rules use; + - `/ra t11 augs ` saves an item-augmentation override (`T11ItemAugsOverride`, + -1 = automatic); + - `/ra t11 refresh` sends `/aug`; + - `/ra t11 item [0xId]` shows how the selected item was read and its T11 key values. +- `StringValueKey.Use = 14` added. + +## Tests + +- `Tools/RynthCore.LootSdkTests`: new `LootT11Tests.cs` covers the parser on server-format + weapon and armor text, non-T11 and malformed input, tier estimates, the `/aug` reader and + its time window, wield checks, every virtual key, the stripped-key fallbacks and the + editor names. The wield-requirements length check is now 14. The T16 armor fixture uses + the server's real gate (500 Triune Weave), and T16-T25 cases cover the Triune gate, + the fallback without one, the T25 cap and a T25 weapon. Result: 8022 assertions, 0 failed. +- `Tools/RynthCore.RynthAiHostTests`: new `T11LootTests.cs` runs T11 items through + `VTankLootEvaluator`, covering virtual keys, restored 158/159/160, TotalRatings from + modifiers, live values winning, retail items untouched, and Can Wield from `/aug` and the + override. All 6 pass. The suite's one failure (map bake against local dats) fails the + same way without this change. +- The RynthAi NativeAOT publish (win-x86) builds with no warnings. + +## Limits + +- The tier estimate uses the server's default weapon-scaling table (ACECustom + `WeaponScalingManager.BuildDefaults`). A server owner who retunes it changes the gates, + but not the parser. The admin `/weaponscaling` command prints the live table, which a + later change could read. +- Without a Triune Weave gate (before an ID, or on a server that disables it) T16+ items + read as T15. +- A `/aug` line format change on the server needs a parser update. `/ra t11 augs ` is + the fallback. +- Item text is only available after an ID. Before that, a T11 item reads as T11 (from its + name) with unknown gates. diff --git a/Changelog/2026-10-06-release-0.5.18-item-info-click.md b/Changelog/2026-10-06-release-0.5.18-item-info-click.md new file mode 100644 index 0000000..1348255 --- /dev/null +++ b/Changelog/2026-10-06-release-0.5.18-item-info-click.md @@ -0,0 +1,48 @@ +# RynthAi 0.5.18-legacy-ui: item info replaces the loot rule line on select / click + +Date: 2026-10-06 +Branch: `feat/t11-loot-support` (uncommitted, on top of 0.5.17) + +## Problem + +With item info set to print on a left or right mouse click, selecting an item printed the +loot inspect verdict (`: [Keep] New Rule`) instead of the configured item info output. + +Cause, in `RynthAiPlugin.OnSelectedTargetChange`: +- Loot inspect is on by default (`_lootInspectMode = true`) and printed its verdict for every + item selected, whatever the item info settings were. +- Item info on select was queued from inside that loot inspect block. It only ran while loot + inspect was on, and it ignored the "Print on select" setting (`OnSelect`). +- No item info trigger wrote anything to the logs, so the logs couldn't show what happened. + +## Fixes + +- **Item info replaces the loot verdict.** When item info is enabled for the selected item's + class (on select or on a mouse click), the loot rule line is no longer printed. With item info + off, the loot verdict prints as before. `/ra lootcheck` still prints it on demand, and + `/ra lootcheck off` turns the automatic line off. +- **"Print on select" is honoured.** The select trigger only queues item info when `OnSelect` + is on, and it no longer depends on loot inspect being on. The click trigger is unchanged. +- **Logging.** Each trigger decision writes one `[ItemInfo]` line to the engine log + (`C:\Games\RynthCore\Logs\RynthCore..log`) and the daily RynthAi diagnostics file: + - on-select queue; + - click queue, or why a click was skipped (nothing selected, not cached, class filter); + - deduped by the other trigger; + - waiting for ID data; + - printed (line count, identified flag, first line), or why nothing printed. + +## Note on settings + +Silentkelpie's item info prefix is an empty string, so its lines print without the +`[RynthAi] ` prefix. Set it in the Item Info window if the prefix is wanted. + +## Build 0.5.18-legacy-ui + +- `HandWrittenVersion` = `0.5.18-legacy-ui`. +- NativeAOT publish (win-x86), `-p:Version=0.5.18-legacy-ui`, staged at + `D:\rynth-merge\stage-suite\RynthAi-0.5.18\` (17,391,616 bytes, file version 0.5.18.0). +- Host tests: 418 passed. The one failure is the unrelated dungeon map bake check, which reads + the real dat files. +- Deploy: the live 0.5.17 DLL is saved to + `C:\Games\RynthSuite\RynthAi\PreviousReleases\0.5.17\`, then replaced. AC was running, so + the copy waited for it to close; deployed 2026-10-06 00:32. diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs index 03f889c..c9ff602 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs @@ -39,6 +39,8 @@ public enum LongValueKey public enum StringValueKey { Name = 1, + // ACECustom puts the T11 "Modifiers:" block of armor, clothing and jewelry here. + Use = 14, ShortDesc = 15, LongDesc = 16, PluralName = 20, @@ -117,13 +119,27 @@ public class WorldObject public int Values(int key, int defaultValue) { + // T11 virtual keys are computed from the item's text, never stored on the object. + if (RynthCore.Loot.T11.T11Keys.IsVirtual(key)) + return Loot.T11ItemSupport.VirtualValue(this, key, defaultValue); + var o = Overlay; if (o != null) { if (o.Ints.TryGetValue(unchecked((uint)key), out int v)) return v; - if (!o.LiveFallback) return defaultValue; + if (!o.LiveFallback) return Loot.T11ItemSupport.StrippedValue(this, key, defaultValue); } - return Cache?.GetIntProperty(Id, (uint)key, defaultValue) ?? defaultValue; + if (Cache == null) return Loot.T11ItemSupport.StrippedValue(this, key, defaultValue); + + // T11 appraisals omit the item-aug wield gate (158-160) and modifier-carried ratings + // (370-379); an absent or zero value there falls back to what the item's text says. + if (RynthCore.Loot.T11.T11Keys.IsStrippedKey(key)) + { + int live = Cache.GetIntProperty(Id, (uint)key, int.MinValue); + if (live != int.MinValue && live != 0) return live; + return Loot.T11ItemSupport.StrippedValue(this, key, live == int.MinValue ? defaultValue : 0); + } + return Cache.GetIntProperty(Id, (uint)key, defaultValue); } public string Values(StringValueKey key, string defaultValue) diff --git a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemDescriber.cs b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemDescriber.cs index dab4088..6c574e6 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemDescriber.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemDescriber.cs @@ -1,17 +1,26 @@ // MagItemDescriber.cs — one-line "Mag-style" item info (Mag-Tools ItemInfo / UtilityBelt ub-IT ItemInfo). // // Gold Ornate Long Sword (Slash Sword), Noble Relic Set, CS, Undead Slayer, Tinks 4, -// Applied: Steel x2, 152.48-236, 0.35v, +18%a, 12%md, Legendary Blood Thirst, Wield Lvl 180, +// Applied: Steel x2, 152-236, 0.35v, +18%a, +12%md, Legendary Blood Thirst, Wield Lvl 180, // Heavy Weapons 375, Diff 270, Craft 8, [D 3, CD 2] // // The same fields can also print as the pet-roster layout (IltPetStats: identity line, stats // line, ratings/requirements line), plus a spells line: // // Gold Ornate Long Sword (Slash Sword), Noble Relic Set, Tinks 4, Applied: Steel x2, Craft 8 -// CS, Undead Slayer, 152.48-236, 0.35v, 18%a, 12%md +// CS, Undead Slayer, 152-236, 0.35v, +18%a, +12%md // [D 3, CD 2] Wield Lvl 180, Heavy Weapons 375, Diff 270 // Spells: Legendary Blood Thirst // +// Values follow what the ACECustom appraisal panel shows: the low damage end is rounded like the +// client, Crushing Blow is the dealt multiplier (1 + CriticalMultiplier), and imbue strengths, +// the T11 weapon grade, procs, zone modifiers and item-aug wield gates come from the description +// text because the server keeps those properties off the wire: +// +// Flaming Quarter Staff (Fire Staff), Grade S (100%), Craft 9 +// FireRend +176%, Crushing Blow 3.66x, 1790-2069, 0.135v, +20%a, +20%md +// [CD 24] Wield 2,000 Item Augs +// // Field order and per-class gating follow ub-IT (Tools/ItemInfo.cs ItemDescriptions.ToString, // Lib/ItemDescribeMagShorthand.cs, Lib/ItemInfoHelper/ItemIdentifyFieldSet.cs); labels and the // spell filter follow Mag-Tools. All ids are raw ACE properties (RynthCore reads CBaseQualities by @@ -20,7 +29,9 @@ using System; using System.Collections.Generic; using System.Globalization; using System.Text; +using System.Text.RegularExpressions; using RynthCore.Loot; +using RynthCore.Loot.T11; namespace RynthCore.Plugin.RynthAi.ItemInfo; @@ -186,8 +197,13 @@ internal static class MagItemDescriber private const uint FloatIgnoreArmor = 155; // armor cleaving // ── ACE PropertyString ids ─────────────────────────────────────────────── + private const uint StringUse = 14; // ACECustom: T11 armor/jewelry "Modifiers:" block + private const uint StringLongDesc = 16; // ACECustom: "Property Details:" lines (imbue strengths, grade, gates) private const uint StringTinkerLog = 9007; // ACECustom: CSV of applied material ids + /// ACECustom's WieldRequirement.Int64Stat: the client gets it as text, never as properties. + private const int WieldReqInt64Stat = 13; + /// Gear ratings are small (1..~50). Anything above is a wrong key leaking through. private const int MaxPlausibleRating = 200; @@ -270,6 +286,10 @@ internal static class MagItemDescriber const MagItemSection Id = MagItemSection.Identity, Cbt = MagItemSection.Combat, Req = MagItemSection.Requirements; string I(int v) => v.ToString(CultureInfo.InvariantCulture); + // Text-only appraisal data (empty until the item has been IDed). + string longDesc = item.GetString(StringLongDesc); + T11ItemInfo t11 = T11ItemInfo.Parse(item.Name, longDesc, item.GetString(StringUse)); + // ── Set ───────────────────────────────────────────────────────────────── int set = Int(IntEquipmentSet); if (set > 0 && Show(MagItemInfoField.Set)) @@ -281,19 +301,27 @@ internal static class MagItemDescriber // ── Imbues (ImbuedEffect 179 plus ImbuedEffect2..5 = 303..306) ───────── if (Show(MagItemInfoField.Imbues)) - d.Add(Cbt, ImbueLabels(Int(IntImbued) | Int(303) | Int(304) | Int(305) | Int(306))); + d.Add(Cbt, ImbueLabels(Int(IntImbued) | Int(303) | Int(304) | Int(305) | Int(306), ImbueStrengths(longDesc))); if (Has(Field.ArmorCleave) && Show(MagItemInfoField.ArmorCleave) && Dbl(FloatIgnoreArmor, 0) != 0) d.Add(Cbt, "AC"); if (Has(Field.CritStats) && Show(MagItemInfoField.CritStats)) { + // A crit deals 1 + CriticalMultiplier; a stored 1.0 is a normal 2x crit, so ACE only + // calls it Crushing Blow above 1.0. double critMult = Dbl(FloatCritMultiplier, 0); - if (critMult > 0) d.Add(Cbt, $"CritMult ({Fmt(critMult)})"); + if (critMult > 1) d.Add(Cbt, $"Crushing Blow {Fmt(critMult + 1)}x"); + // Biting Strike replaces the base crit chance with this fraction. double critFreq = Dbl(FloatCritFrequency, 0); - if (critFreq > 0) d.Add(Cbt, $"CritFreq ({Fmt(critFreq)})"); + if (critFreq > 0) d.Add(Cbt, $"Biting Strike {Math.Round(critFreq * 100).ToString(CultureInfo.InvariantCulture)}%"); } + // T11 Cast on Strike procs: "Proc Force Arc 13%". + if (Show(MagItemInfoField.Imbues)) + foreach (var (procName, chance) in t11.Procs) + d.Add(Cbt, $"Proc {procName} {Fmt(chance)}%"); + if (Has(Field.Splits) && Show(MagItemInfoField.Splits)) { int splits = Int(IntSplitArrows); @@ -333,6 +361,10 @@ internal static class MagItemDescriber } // ── Damage ────────────────────────────────────────────────────────────── + // T11 weapon grade sits with the identity fields: "Grade S (100%)". + if (Has(Field.Damage) && Show(MagItemInfoField.Damage) && t11.GradeRank > 0) + d.Add(Id, t11.DamagePercent >= 0 ? $"Grade {t11.Grade} ({I(t11.DamagePercent)}%)" : $"Grade {t11.Grade}"); + if (Has(Field.Damage) && Show(MagItemInfoField.Damage)) AddDamage(d, cls, Int(IntMaxDamage), Dbl(FloatVariance, 0), Int(IntElementalBonus), Dbl(FloatDamageMod, 1), Dbl(FloatVsMonsters, 1)); @@ -359,6 +391,9 @@ internal static class MagItemDescriber { AddWieldRequirement(d, Int(IntWieldReq), Int(IntWieldSkill), Int(IntWieldValue)); AddWieldRequirement(d, Int(IntWieldReq2), Int(IntWieldSkill2), Int(IntWieldValue2)); + // T11 gates (item augs, Triune Weave, charms) only exist as "Wield requires:" text. + foreach (T11WieldGate gate in t11.WieldGates) + d.Add(Req, $"Wield {gate.Amount.ToString("N0", CultureInfo.InvariantCulture)} {GateName(gate.Counter)}"); } if (Show(MagItemInfoField.Activation)) @@ -418,7 +453,18 @@ internal static class MagItemDescriber // ── Ratings ───────────────────────────────────────────────────────────── if (Show(MagItemInfoField.Ratings)) + { d.Add(MagItemSection.Ratings, RatingsCluster(item, options.HiddenRatings)); + // T11 zone modifiers: the server drops a modifier's Gear* rating from the ratings it + // sends, so the modifier lines are the only place those values appear. + if (t11.Modifiers.Count > 0) + { + var mods = new List(t11.Modifiers.Count); + foreach (T11Modifier m in t11.Modifiers) + mods.Add(m.Value != 0 ? $"{m.Name} {(m.Value > 0 ? "+" : "")}{I(m.Value)}" : m.Name); + d.Add(MagItemSection.Ratings, "Mods: " + string.Join(", ", mods)); + } + } if (cls == AcObjectClass.Misc && Show(MagItemInfoField.Keyring) && item.Name.Contains("Keyring", StringComparison.OrdinalIgnoreCase)) @@ -432,15 +478,18 @@ internal static class MagItemDescriber /// Mag imbue labels ("CS AR"), plus the ACE flags Mag predates (missile imbue, nether /// rend); empty when no known bit is set. - private static string ImbueLabels(int mask) + private static string ImbueLabels(int mask, IReadOnlyDictionary strengths) { if (mask == 0) return string.Empty; var sb = new StringBuilder(); + // Bare labels stay Mag-style "CS AR"; once a strength is shown, commas keep values readable. + string sep = strengths.Count > 0 ? ", " : " "; void Flag(int bit, string label) { if ((mask & bit) == 0) return; - if (sb.Length > 0) sb.Append(' '); + if (sb.Length > 0) sb.Append(sep); sb.Append(label); + if (strengths.TryGetValue(bit, out string? value)) sb.Append(' ').Append(value); } Flag(0x0001, "CS"); Flag(0x0002, "CB"); @@ -461,6 +510,52 @@ internal static class MagItemDescriber return sb.ToString(); // only unknown bits → empty → field skipped } + // ACECustom "Property Details:" imbue lines, e.g. "- Fire Rending: +176% Dmg", + // "- Armor Rending: 12.5% Ignored", "- Crippling Blow: 2.5x Crit Dmg". The value may carry a + // culture space before '%' and group separators. + private static readonly Regex ImbueDetailLine = new( + @"^\s*-\s*(?[A-Za-z' ]+?)\s*:\s*(?[+-]?[\d.,]+\s?[%x])", + RegexOptions.Multiline | RegexOptions.CultureInvariant); + + /// + /// Imbue bit → strength text ("+176%", "12.5%", "2.5x") from the description. Rendings are + /// matched by damage keyword because the server builds their names from DamageType.DisplayName. + /// + private static IReadOnlyDictionary ImbueStrengths(string longDesc) + { + var result = new Dictionary(); + if (string.IsNullOrEmpty(longDesc)) return result; + foreach (Match m in ImbueDetailLine.Matches(longDesc)) + { + int bit = ImbueBitForDetail(m.Groups["name"].Value); + if (bit != 0 && !result.ContainsKey(bit)) + result[bit] = m.Groups["value"].Value.Replace(" ", ""); + } + return result; + } + + private static int ImbueBitForDetail(string name) + { + bool Has(string s) => name.Contains(s, StringComparison.OrdinalIgnoreCase); + if (Has("Critical Strike")) return 0x0001; + if (Has("Crippling Blow")) return 0x0002; + if (Has("Armor Rending")) return 0x0004; + if (!Has("Rending")) return 0; + if (Has("Slash")) return 0x0008; + if (Has("Pierc")) return 0x0010; + if (Has("Bludg")) return 0x0020; + if (Has("Acid")) return 0x0040; + if (Has("Cold") || Has("Frost")) return 0x0080; + if (Has("Electric") || Has("Lightning")) return 0x0100; + if (Has("Fire")) return 0x0200; + if (Has("Nether")) return 0x4000; + return 0; + } + + /// Short wield-gate counter names: "Item Augs", "Triune Weave", charm names. + private static string GateName(T11Counter counter) => + counter == T11Counter.ItemAugmentations ? "Item Augs" : T11Catalog.CounterName(counter); + /// Melee "min-max", variance, "+elem", "+mod%", wand "+N% vs. Monsters" (combat line). private static void AddDamage(MagItemDescription d, AcObjectClass cls, int maxDmg, double variance, int elemBonus, double dmgMod, double vsMonsters) @@ -469,12 +564,13 @@ internal static class MagItemDescriber if (cls != AcObjectClass.MissileWeapon && maxDmg > 0) { string max = maxDmg.ToString(CultureInfo.InvariantCulture); - d.Add(Cbt, variance > 0 - ? (maxDmg - maxDmg * variance).ToString("N2", CultureInfo.InvariantCulture) + "-" + max - : max); + // The appraisal panel rounds the low end to a whole number (2069 * 0.865 → 1790). + long min = (long)Math.Round(maxDmg * (1 - variance), MidpointRounding.AwayFromZero); + d.Add(Cbt, variance > 0 ? min.ToString(CultureInfo.InvariantCulture) + "-" + max : max); } + // Three places: loot variances are often x.xx5 and two places would misreport them. if (variance > 0) - d.Add(Cbt, Math.Round(variance, 2).ToString(CultureInfo.InvariantCulture) + "v"); + d.Add(Cbt, Math.Round(variance, 3).ToString("0.###", CultureInfo.InvariantCulture) + "v"); if (elemBonus != 0) d.Add(Cbt, "+" + elemBonus.ToString(CultureInfo.InvariantCulture)); // A missing/zero multiplier means "no bonus" (0 would print as -100%). @@ -484,18 +580,21 @@ internal static class MagItemDescriber d.Add(Cbt, "+" + Math.Round((vsMonsters - 1) * 100).ToString(CultureInfo.InvariantCulture) + "% vs. Monsters"); } - /// Mag "18%a" from a 1.0-based multiplier; skips missing (≤0) and neutral 1.0. + /// Mag "+18%a" from a 1.0-based multiplier; skips missing (≤0) and neutral 1.0. private static void AddPercent(MagItemDescription d, double multiplier, string suffix, int decimals) { if (multiplier <= 0 || multiplier == 1) return; double pct = Math.Round((multiplier - 1) * 100, decimals); - d.Add(MagItemSection.Combat, pct.ToString(CultureInfo.InvariantCulture) + suffix); + if (pct == 0) return; // rounds to nothing at this precision + // Signed like the appraisal panel ("Bonus to Attack Skill +20%"); penalties keep their '-'. + d.Add(MagItemSection.Combat, (pct > 0 ? "+" : "") + pct.ToString(CultureInfo.InvariantCulture) + suffix); } /// "Wield Lvl 180" for a level requirement, else "Heavy Weapons 375". private static void AddWieldRequirement(MagItemDescription d, int reqType, int skillOrAttr, int value) { - if (value <= 0) return; + // Int64 gates name a counter, not a skill; the T11 text supplies those. + if (value <= 0 || reqType == WieldReqInt64Stat) return; string v = value.ToString(CultureInfo.InvariantCulture); d.Add(MagItemSection.Requirements, reqType == 7 // WieldRequirement.Level ? "Wield Lvl " + v diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index 89aa75c..ce8fca2 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -1773,6 +1773,7 @@ internal sealed partial class LegacyDashboardRenderer dst.YieldToVTank = tmp.YieldToVTank; dst.ShowTerrainPassability = tmp.ShowTerrainPassability; dst.GiveQueueIntervalMs = tmp.GiveQueueIntervalMs; + dst.T11ItemAugsOverride = tmp.T11ItemAugsOverride; dst.SpellCastIntervalMs = tmp.SpellCastIntervalMs; dst.AttackSpellIntervalMs = tmp.AttackSpellIntervalMs; dst.EmbeddedNavs = tmp.EmbeddedNavs; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index 2368a7f..dda4742 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -267,6 +267,13 @@ public sealed class LegacyUiSettings public int GiveQueueIntervalMs = 150; + /// + /// Item augmentation count used for T11 wield gates in loot rules ("T11: Can Wield"). + /// -1 = automatic (read from the server's "/aug" reply). ACECustom doesn't send the count + /// at login, so this is the fallback when "/aug" is unavailable. Set with /ra t11 augs. + /// + public int T11ItemAugsOverride = -1; + public int SpellCastIntervalMs = 400; /// diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/T11ItemSupport.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/T11ItemSupport.cs new file mode 100644 index 0000000..db348fb --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/T11ItemSupport.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Generic; +using RynthCore.Loot.T11; + +namespace RynthCore.Plugin.RynthAi.Loot; + +/// +/// T11 (tier 11+ ACECustom) loot support for : +/// answers the virtual T11 keys () and puts back the wield-requirement and +/// rating properties the server strips from T11 appraisals. Parsed item text is cached per +/// object and re-parsed only when the text changes. Holds the player's "/aug" counters for +/// the "Can Wield" key. One character per process, so the state is static. +/// +internal static class T11ItemSupport +{ + /// The logged-in character's T11 wield counters. + public static T11PlayerAugs Player { get; } = new(); + + private static readonly T11AugReportParser AugParser = new(); + private static readonly object Gate = new(); + private static readonly Dictionary Parsed = new(); + + // Bound so a long session's corpse items can't grow the cache without limit; a full + // clear is fine because re-parsing is cheap and only happens for items still in use. + private const int MaxEntries = 4096; + + private sealed class Entry + { + public string Name = string.Empty; + public string LongDesc = string.Empty; + public string Use = string.Empty; + public T11ItemInfo Info = T11ItemInfo.None; + } + + /// True when carries the server's T11 drop prefix. + public static bool HasT11Name(string? name) + => !string.IsNullOrEmpty(name) && name.StartsWith(T11Catalog.NamePrefix, StringComparison.Ordinal); + + /// The parsed T11 view of ( for other items). + public static T11ItemInfo Get(WorldObject item) + { + string name = item.Name.Length > 0 ? item.Name : item.Values(StringValueKey.Name, string.Empty); + string longDesc = item.Values(StringValueKey.LongDesc, string.Empty); + string use = item.Values(StringValueKey.Use, string.Empty); + + lock (Gate) + { + if (Parsed.TryGetValue(item.Id, out Entry? e) + && string.Equals(e.Name, name, StringComparison.Ordinal) + && string.Equals(e.LongDesc, longDesc, StringComparison.Ordinal) + && string.Equals(e.Use, use, StringComparison.Ordinal)) + return e.Info; + } + + T11ItemInfo info = T11ItemInfo.Parse(name, longDesc, use); + lock (Gate) + { + if (Parsed.Count >= MaxEntries) Parsed.Clear(); + Parsed[item.Id] = new Entry { Name = name, LongDesc = longDesc, Use = use, Info = info }; + } + return info; + } + + /// A virtual T11 key's value, or for an unused id. + public static int VirtualValue(WorldObject item, int key, int defaultValue) + { + try + { + return T11Keys.TryGetValue(Get(item), key, Player, out int value) ? value : defaultValue; + } + catch + { + return defaultValue; + } + } + + /// + /// The value a T11 appraisal stripped for a retail key (158/159/160, 370-379), else + /// . Only T11-named items are parsed, so other items pay a + /// string compare. + /// + public static int StrippedValue(WorldObject item, int key, int fallback) + { + if (!T11Keys.IsStrippedKey(key)) return fallback; + try + { + string name = item.Name.Length > 0 ? item.Name : item.Values(StringValueKey.Name, string.Empty); + if (!HasT11Name(name)) return fallback; + return T11Keys.TryGetStrippedValue(Get(item), key, out int value) ? value : fallback; + } + catch + { + return fallback; + } + } + + /// Feeds a chat line to the "/aug" reader. Returns true when a counter changed. + public static bool OnChat(string? text) => AugParser.Feed(text, Environment.TickCount64, Player); + + /// Applies the saved item-aug override (-1 = automatic). Cheap; called every tick. + public static void SyncOverride(int itemAugsOverride) + => Player.ItemAugOverride = itemAugsOverride >= 0 ? itemAugsOverride : null; + + /// Drops the cached parse of a deleted object. + public static void Forget(int objectId) + { + lock (Gate) Parsed.Remove(objectId); + } + + /// Forgets the character's counters and every cached item (logout). + public static void Reset() + { + Player.Clear(); + lock (Gate) Parsed.Clear(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index 08cd4cc..b821e81 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -36,6 +36,7 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] /ra attackable — check if target is attackable"); ChatLine("[RynthAi] /ra wielded — show wielded items"); ChatLine("[RynthAi] /ra dumpprops [0xId] — every property of the selection (else yourself)"); + ChatLine("[RynthAi] /ra t11 [augs |refresh|item] — T11 loot: wield counters, aug override, parsed item"); ChatLine("[RynthAi] /ra mexec — evaluate meta expression"); ChatLine("[RynthAi] /ra listvars — show session variables"); ChatLine("[RynthAi] /ra listpvars — show persistent variables"); diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs index 99145fc..0036d27 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs @@ -215,10 +215,14 @@ public sealed partial class RynthAiPlugin return; } if (requestId && Host.HasRequestId) Host.RequestId(uid); + ItemInfoLog($"0x{uid:X8}: waiting for ID data (requested={requestId && Host.HasRequestId})"); _itemInfoPendingId = itemId; _itemInfoPendingSince = Environment.TickCount64; } + /// One "[ItemInfo]" line in the engine log and the daily RynthAi file per trigger decision. + private static void ItemInfoLog(string message) => RynthLog.Write(LogCat.UI, "[ItemInfo] " + message); + /// /// Select / click triggers: unless the same item was queued /// automatically within (one click can raise both triggers). @@ -226,7 +230,11 @@ public sealed partial class RynthAiPlugin internal void QueueAutoItemInfo(int itemId, bool requestId) { long now = Environment.TickCount64; - if (itemId == _itemInfoLastAutoId && now - _itemInfoLastAutoAt < AutoDedupeMs) return; + if (itemId == _itemInfoLastAutoId && now - _itemInfoLastAutoAt < AutoDedupeMs) + { + ItemInfoLog($"0x{(uint)itemId:X8}: already queued by the other trigger"); + return; + } _itemInfoLastAutoId = itemId; _itemInfoLastAutoAt = now; QueueItemInfo(itemId, requestId); @@ -288,12 +296,19 @@ public sealed partial class RynthAiPlugin var s = ItemInfoSettings; if (s == null || s.ClickTrigger == MagItemInfoSettings.ClickOff || !Host.HasGetSelectedItemId) return; + string button = MagItemInfoCatalog.ClickTriggers[s.ClickTrigger]; uint selected = Host.GetSelectedItemId(); - if (selected == 0) return; + if (selected == 0) { ItemInfoLog($"{button}: nothing selected"); return; } int id = unchecked((int)selected); WorldObject? obj = _objectCache?[id]; - if (obj == null || !IsLootableClass(obj.ObjectClass) || !ItemInfoWantsClass(s, obj.ObjectClass)) return; + if (obj == null) { ItemInfoLog($"{button}: 0x{selected:X8} not in the object cache"); return; } + if (!IsLootableClass(obj.ObjectClass) || !ItemInfoWantsClass(s, obj.ObjectClass)) + { + ItemInfoLog($"{button}: '{obj.Name}' ({obj.ObjectClass}) skipped by the class filters"); + return; + } + ItemInfoLog($"{button}: 0x{selected:X8} '{obj.Name}': click queue"); QueueAutoItemInfo(id, requestId: true); } @@ -344,8 +359,14 @@ public sealed partial class RynthAiPlugin private void PrintItemInfo(int itemId, bool identified) { List? lines = BuildItemInfoLines(itemId, out string? error); - if (lines == null || lines.Count == 0) { ChatLine("[RynthAi] " + error); return; } + if (lines == null || lines.Count == 0) + { + ItemInfoLog($"0x{(uint)itemId:X8}: not printed: {error}"); + ChatLine("[RynthAi] " + error); + return; + } if (!identified) lines[0] += " (not identified — stats may be incomplete)"; + ItemInfoLog($"0x{(uint)itemId:X8}: printed {lines.Count} line(s), identified={identified}: {lines[0]}"); var s = ItemInfoSettings; string prefix = s?.Prefix ?? "[RynthAi] "; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs index 620439a..f4c1df3 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs @@ -140,6 +140,7 @@ public sealed partial class RynthAiPlugin catch (Exception ex) { RynthLog.Exception(LogCat.General, ex, "item info tick"); } try { _navBreadcrumbs?.Tick(); } catch (Exception ex) { RynthLog.Exception(LogCat.Navigation, ex, "nav breadcrumbs tick"); } + Loot.T11ItemSupport.SyncOverride(_dashboard?.Settings.T11ItemAugsOverride ?? -1); } /// Drop per-character feature objects. The translator is disposed only on plugin shutdown. @@ -158,6 +159,7 @@ public sealed partial class RynthAiPlugin _huds = null; _itemInfoUi = null; ResetGroundLoot(clearCaches: true); + Loot.T11ItemSupport.Reset(); if (!disposeTranslator) return; try { _translator?.Dispose(); } catch (Exception ex) { RynthLog.Exception(LogCat.Chat, ex, "translator dispose"); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index 98976bc..6d15cc6 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -2041,17 +2041,25 @@ public sealed partial class RynthAiPlugin : RynthPluginBase if (Host.HasQueryHealth) Host.QueryHealth(currentTargetId); } - if (_lootInspectMode && currentTargetId != 0) + if (currentTargetId != 0) { int sid = unchecked((int)currentTargetId); WorldObject? obj = _objectCache?[sid]; // Skip non-items (monsters, players, NPCs, doors, corpses, portals, etc.) if (obj != null && IsLootableClass(obj.ObjectClass)) { - InspectLootRuleForItem(sid, quiet: true); var itemInfo = _dashboard?.Settings.ItemInfoSettings; - if (itemInfo != null && ItemInfoWantsClass(itemInfo, obj.ObjectClass)) + bool infoWanted = itemInfo != null && ItemInfoWantsClass(itemInfo, obj.ObjectClass); + // Item info (on select or on click) is the answer for this item; the loot + // verdict line would print in its place. /ra lootcheck still prints it on demand. + bool infoHandles = infoWanted && (itemInfo!.OnSelect || itemInfo.ClickTrigger != ItemInfo.MagItemInfoSettings.ClickOff); + if (_lootInspectMode && !infoHandles) + InspectLootRuleForItem(sid, quiet: true); + if (infoWanted && itemInfo!.OnSelect) + { + ItemInfoLog($"select 0x{currentTargetId:X8} '{obj.Name}': on-select queue"); QueueAutoItemInfo(sid, requestId: false); + } } } } @@ -2087,6 +2095,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _scrollLearner?.OnChat(text); _metaManager?.HandleChat(text, chatType); _questTracker?.OnChatLine(text); + // The "/aug" reply carries the T11 wield counters (ILT Hub requests it at login). + try { Loot.T11ItemSupport.OnChat(text); } + catch (Exception ex) { RynthLog.Exception(LogCat.Looting, ex, "T11 /aug parse"); } CheckChatForSafetyStops(text); try { OnOwnCorpseChat(text); } catch { } } @@ -2120,6 +2131,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _objectCache?.OnDeleteObject(objectId); _combatManager?.OnObjectDeleted(objectId); // D7/D8: free per-id maps + clear cast-wait if it was our target _scrollLearner?.OnObjectDeleted(objectId); // a read scroll is consumed + Loot.T11ItemSupport.Forget(unchecked((int)objectId)); HandleCorpseObjectDeleted(objectId); } catch (Exception ex) @@ -3121,6 +3133,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "listgvars": HandleListGvarsCommand(); break; case "dumpprops": HandleDumpPropsCommand(parts); break; case "version": HandleVersionCommand(); break; + case "t11": HandleT11Command(parts); break; case "wielded": HandleWieldedCommand(); break; case "scan": HandleScanCommand(); break; case "buildinfo": HandleBuildInfoCommand(); break; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiT11Command.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiT11Command.cs new file mode 100644 index 0000000..c070bfc --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiT11Command.cs @@ -0,0 +1,124 @@ +using System; +using System.Globalization; +using System.Linq; +using RynthCore.Loot.T11; +using RynthCore.Plugin.RynthAi.Loot; + +namespace RynthCore.Plugin.RynthAi; + +public sealed partial class RynthAiPlugin +{ + /// + /// /ra t11 [augs <n|auto> | refresh | item [0xId]]: T11 loot support. + /// No argument shows the wield counters the loot rules use; "augs" sets or clears the + /// item-aug override; "refresh" asks the server for "/aug"; "item" shows how the selected + /// item's T11 text was read and the values its virtual loot keys return. + /// + private void HandleT11Command(string[] parts) + { + string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : string.Empty; + switch (sub) + { + case "": + case "status": + PrintT11Status(); + break; + case "augs": + SetT11ItemAugOverride(parts.Length >= 4 ? parts[3] : string.Empty); + break; + case "refresh": + if (!Host.HasInvokeChatParser) { ChatLine("[RynthAi] This engine can't send chat commands."); break; } + Host.InvokeChatParser("/aug"); + ChatLine("[RynthAi] T11: sent /aug - the counters update from its reply."); + break; + case "item": + PrintT11Item(parts.Length >= 4 ? parts[3] : null); + break; + default: + ChatLine("[RynthAi] Usage: /ra t11 [augs | refresh | item [0xId]]"); + break; + } + } + + /// The counters the "T11: Can Wield" loot key compares wield gates against. + private void PrintT11Status() + { + T11PlayerAugs p = T11ItemSupport.Player; + int saved = _dashboard?.Settings.T11ItemAugsOverride ?? -1; + string updated = p.UpdatedUtc is DateTime t ? t.ToLocalTime().ToString("t", CultureInfo.CurrentCulture) : "never"; + ChatLine($"[RynthAi] === T11 loot (last /aug read: {updated}) ==="); + foreach ((T11Counter counter, string name) in T11Catalog.CounterNames) + { + long? v = p.Get(counter); + string source = counter == T11Counter.ItemAugmentations && saved >= 0 ? " (override)" : string.Empty; + ChatLine($"[RynthAi] {name}: {(v.HasValue ? v.Value.ToString("N0", CultureInfo.CurrentCulture) : "unknown")}{source}"); + } + if (p.UpdatedUtc == null && saved < 0) + ChatLine("[RynthAi] Unknown counters make \"T11: Can Wield\" -1. Use /ra t11 refresh, or /ra t11 augs ."); + } + + /// /ra t11 augs <n|auto>: saves the item-aug override (-1 = read from /aug). + private void SetT11ItemAugOverride(string arg) + { + if (_dashboard == null) { ChatLine("[RynthAi] Settings aren't loaded yet."); return; } + int value; + if (arg.Equals("auto", StringComparison.OrdinalIgnoreCase) || arg == "-1") + value = -1; + else if (!int.TryParse(arg.Replace(",", string.Empty), NumberStyles.Integer, CultureInfo.InvariantCulture, out value) || value < 0) + { + ChatLine("[RynthAi] Usage: /ra t11 augs (n = your item augmentation count)"); + return; + } + _dashboard.Settings.T11ItemAugsOverride = value; + _dashboard.SaveSettings(); + T11ItemSupport.SyncOverride(value); + ChatLine(value < 0 + ? "[RynthAi] T11: item augmentations now come from /aug." + : $"[RynthAi] T11: item augmentations fixed at {value:N0} for loot rules."); + } + + /// /ra t11 item [0xId]: the parsed T11 text of an item (selected item by default). + private void PrintT11Item(string? idArg) + { + uint id = 0; + if (!string.IsNullOrEmpty(idArg)) + uint.TryParse(idArg.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? idArg[2..] : idArg, + NumberStyles.HexNumber, CultureInfo.InvariantCulture, out id); + if (id == 0 && Host.HasGetSelectedItemId) id = Host.GetSelectedItemId(); + if (id == 0) { ChatLine("[RynthAi] T11: select an item first (or pass 0xId)."); return; } + + int iid = unchecked((int)id); + WorldObject item = _objectCache?[iid] + ?? new WorldObject(iid, Host.TryGetObjectName(id, out string n) ? n : string.Empty) { Cache = _objectCache }; + T11ItemInfo info = T11ItemSupport.Get(item); + if (!info.IsT11) + { + bool appraised = !Host.HasHasAppraisalData || Host.HasAppraisalData(id); + ChatLine(appraised + ? $"[RynthAi] T11: {item.Name} is not a T11 item." + : $"[RynthAi] T11: {item.Name} isn't appraised yet - ID it and try again."); + return; + } + + ChatLine($"[RynthAi] === T11: {item.Name} (0x{id:X8}) ==="); + ChatLine($"[RynthAi] Tier ~{info.EstimatedTier}" + (info.Grade != null ? $", grade {info.Grade} ({info.DamagePercent}% of max damage)" : string.Empty) + + (info.ZoneLocked ? ", zone locked" : string.Empty)); + foreach (T11WieldGate g in info.WieldGates) + ChatLine($"[RynthAi] Wield requires {g.Amount:N0} {T11Catalog.CounterName(g.Counter)}"); + foreach (T11Modifier m in info.Modifiers) + { + string band = m.Min.HasValue && m.Max.HasValue ? $" [{m.Min}-{m.Max}] roll {m.RollPercent}%" : string.Empty; + ChatLine($"[RynthAi] Mod {m.Name} {(m.IsSlotSpecial ? "(special)" : "+" + m.Value)}{band}"); + } + foreach ((string name, double chance) in info.Procs) + ChatLine($"[RynthAi] Cast on strike: {name} ({chance.ToString("0.#", CultureInfo.CurrentCulture)}%)"); + + int canWield = item.Values(T11Keys.CanWield, -1); + ChatLine($"[RynthAi] Can wield: {(canWield == 1 ? "yes" : canWield == 0 ? "no" : "unknown (no /aug read, or not appraised)")}" + + $", modifier ratings {info.ModifierRatingTotal}, average roll {info.AverageRollPercent}%"); + string keys = string.Join(", ", T11Keys.Names() + .Where(k => k.Id < T11Keys.ModifierBase) + .Select(k => $"{k.Name.Replace("T11: ", string.Empty)}={item.Values(k.Id, 0)}")); + ChatLine($"[RynthAi] Loot keys: {keys}"); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiVersionCommand.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiVersionCommand.cs index d4a8b66..23c50c5 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiVersionCommand.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiVersionCommand.cs @@ -44,7 +44,7 @@ public sealed partial class RynthAiPlugin private static unsafe class PluginModule { /// RynthPluginVersion's hand-written string (it never changes between builds). - public const string HandWrittenVersion = "0.5.0-legacy-ui"; + public const string HandWrittenVersion = "0.5.18-legacy-ui"; private const uint FromAddress = 0x4, UnchangedRefCount = 0x2; diff --git a/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs b/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs index 6190985..24fb2ce 100644 --- a/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs +++ b/Shared/RynthCore.LootSdk/Editing/LootRuleText.cs @@ -38,17 +38,25 @@ public static class LootRuleText // ── Key tables (the common ones; unknown ids show as "key N") ────────── - public static readonly (int Id, string Name)[] LongKeys = + /// Retail / Decal long keys, then RynthAi's virtual T11 keys (T11Keys; RynthAi-only). + public static readonly (int Id, string Name)[] LongKeys = BuildLongKeys(); + + private static (int Id, string Name)[] BuildLongKeys() { - (5, "EncumbVal"), (9, "Locations"), (19, "Value"), (25, "Level"), (28, "ArmorLevel"), (44, "Damage"), (45, "DamageType"), - (48, "WeaponSkill"), (54, "MaxDamage"), - (87, "MaxStructure"), (88, "Structure"), (105, "ItemWorkmanship"), (107, "ItemMaxMana"), - (131, "MaterialType"), (158, "WieldRequirements"), (159, "WieldSkilltype"), (160, "WieldDifficulty"), - (218, "EquippedSlots"), (353, "ImbuedEffect"), (370, "DamageRating"), (371, "DamageResistRating"), - (372, "CritRating"), (373, "CritResistRating"), (374, "CritDamageRating"), - (375, "CritDamageResistRating"), (376, "HealBoostRating"), (379, "VitalityRating"), - (0x0D000000, "Type (WCID)"), // Decal's synthetic key: the weenie class id - }; + var keys = new List<(int, string)> + { + (5, "EncumbVal"), (9, "Locations"), (19, "Value"), (25, "Level"), (28, "ArmorLevel"), (44, "Damage"), (45, "DamageType"), + (48, "WeaponSkill"), (54, "MaxDamage"), + (87, "MaxStructure"), (88, "Structure"), (105, "ItemWorkmanship"), (107, "ItemMaxMana"), + (131, "MaterialType"), (158, "WieldRequirements"), (159, "WieldSkilltype"), (160, "WieldDifficulty"), + (218, "EquippedSlots"), (353, "ImbuedEffect"), (370, "DamageRating"), (371, "DamageResistRating"), + (372, "CritRating"), (373, "CritResistRating"), (374, "CritDamageRating"), + (375, "CritDamageResistRating"), (376, "HealBoostRating"), (377, "NetherResistRating"), (379, "VitalityRating"), + (0x0D000000, "Type (WCID)"), // Decal's synthetic key: the weenie class id + }; + keys.AddRange(T11.T11Keys.Names()); + return keys.ToArray(); + } public static readonly (int Id, string Name)[] DoubleKeys = { @@ -56,9 +64,10 @@ public static class LootRuleText (63, "WeaponOffense"), (152, "ElementalDamageVsMonsters"), (167, "ManaRate"), }; + /// String keys. Use (14) and LongDesc (16) hold the T11 "Modifiers:" / "Property Details:" text. public static readonly (int Id, string Name)[] StringKeys = { - (1, "Name"), (5, "Inscription"), (7, "Title"), + (1, "Name"), (5, "Inscription"), (7, "Title"), (14, "Use"), (16, "LongDesc"), }; /// @@ -85,12 +94,15 @@ public static class LootRuleText // ── Value tables (what a long key's number means) ────────────────────── - /// WieldRequirements (158): what WieldDifficulty is checked against (ACE's WieldRequirement enum). + /// + /// WieldRequirements (158): what WieldDifficulty is checked against (ACE's WieldRequirement + /// enum). 13 is ACECustom's Int64Stat, the T11 item-aug gate (RynthAi restores it on T11 items). + /// public static readonly (int Id, string Name)[] WieldRequirements = { (0, "Invalid"), (1, "Skill"), (2, "Base Skill"), (3, "Attribute"), (4, "Base Attribute"), (5, "Vital"), (6, "Base Vital"), (7, "Level"), (8, "Training"), (9, "Int Property"), - (10, "Bool Property"), (11, "Creature Type"), (12, "Heritage"), + (10, "Bool Property"), (11, "Creature Type"), (12, "Heritage"), (13, "Int64 Property"), }; /// MaterialType (131): ACE's MaterialType enum, in id order (grouped cloth, gems, hides, metals, stone, wood). @@ -134,6 +146,7 @@ public static class LootRuleText 131 => Materials, 158 => WieldRequirements, 159 => Skills, + T11.T11Keys.WeaponGrade => T11.T11Catalog.Grades, _ => null, }; @@ -141,7 +154,7 @@ public static class LootRuleText public static bool ValueTableIsFlags(int longKey) => longKey == 45; /// The long keys that have a value table, for the vocabulary. - public static readonly int[] KeysWithValueTables = { 45, 48, 131, 158, 159 }; + public static readonly int[] KeysWithValueTables = { 45, 48, 131, 158, 159, T11.T11Keys.WeaponGrade }; /// /// True for the conditions whose value is picked by name when the key has a diff --git a/Shared/RynthCore.LootSdk/T11/T11Catalog.cs b/Shared/RynthCore.LootSdk/T11/T11Catalog.cs new file mode 100644 index 0000000..233cb72 --- /dev/null +++ b/Shared/RynthCore.LootSdk/T11/T11Catalog.cs @@ -0,0 +1,197 @@ +using System; +using System.Collections.Generic; + +namespace RynthCore.Loot.T11; + +/// +/// The player counter a T11 wield gate is checked against. On the server these are +/// PropertyInt64 values (WieldRequirement.Int64Stat); the client never receives the +/// gate as properties, only as a "Wield requires: N <counter>" description line. +/// +public enum T11Counter +{ + /// LumAugItemCount (PropertyInt64 9008). The server checks the raw count, without Triune Weave. + ItemAugmentations = 9008, + /// TriuneWeaveCount (PropertyInt64 50000), the T16+ armor gate. + TriuneWeave = 50000, + /// BattlemagesWrathCharmCount (PropertyInt64 50001). + BattlemagesWrath = 50001, + /// NetherVeilCharmCount (PropertyInt64 50002). + NetherVeil = 50002, + /// CrashingSteelCharmCount (PropertyInt64 50003). + CrashingSteel = 50003, + /// TrueShotCharmCount (PropertyInt64 50004). + TrueShot = 50004, +} + +/// One Zone Control modifier the server can stamp on T11 gear. +/// The server's catalog key (ZoneModifiers.Catalog). +/// The name printed at the start of the appraisal line. +/// The retail Gear* rating property the modifier sets, or 0. +/// True for the one-per-slot specials, whose line has no roll band. +public sealed record T11ModifierDef(int Key, string Name, int RatingKey, bool SlotSpecial); + +/// +/// Static T11 tables mirrored from ACECustom: weapon sub-grades, the Zone Control +/// modifier catalog, the wield-gate counter names and the tier-from-gate estimate. +/// Pure data, shared by the RynthAi evaluator, the loot editor and the tests. +/// +public static class T11Catalog +{ + /// The name prefix the server gives every tier 11+ drop (ApplyT11NamePrefix). + public const string NamePrefix = "T11 - "; + + /// Retail rating keys counted by the TotalRatings condition (VTank's set). + public static readonly int[] TotalRatingKeys = { 370, 371, 372, 373, 374, 375, 376, 379 }; + + /// + /// Weapon sub-grades best to worst with their rank (S = 16 ... F- = 1, 0 = no grade). + /// Order and labels follow WeaponScalingManager.SubGradeBands. + /// + public static readonly (int Id, string Name)[] Grades = + { + (16, "S"), (15, "A+"), (14, "A"), (13, "A-"), (12, "B+"), (11, "B"), (10, "B-"), + (9, "C+"), (8, "C"), (7, "C-"), (6, "D+"), (5, "D"), (4, "D-"), (3, "F+"), (2, "F"), (1, "F-"), + }; + + /// + /// ZoneModifiers.Catalog (ACECustom). Rating keys: 370 Damage, 371 Damage Resist, 372 Crit, + /// 373 Crit Resist, 374 Crit Damage, 375 Crit Damage Resist, 376 Healing Boost, + /// 377 Nether Resist, 379 Max Health. + /// + public static readonly T11ModifierDef[] Modifiers = + { + new(19, "Max Health", 379, false), + new(25, "Armor Level", 0, false), + new(28, "Damage Rating", 370, false), + new(29, "Crit Damage Rating", 374, false), + new(31, "Healing Boost", 376, false), + new(32, "Spell Duration", 0, false), + new(33, "Crit Chance", 372, false), + new(41, "Fortify Vitals", 0, true), + new(42, "Battle Mending", 0, true), + new(43, "All Attributes", 0, false), + new(44, "Pct HP Damage", 0, true), + new(45, "Cheat Death", 0, true), + new(46, "Regeneration", 0, true), + new(47, "Max Health Pct", 0, false), + new(48, "Life on Hit", 0, false), + new(49, "Reinforced", 0, false), + new(50, "Damage Resist", 371, false), + new(51, "Crit Damage Resist", 375, false), + new(52, "Crit Resist", 373, false), + new(53, "Nether Resist", 377, false), + }; + + // Longest names first, so "Max Health Pct" is tried before "Max Health". + private static readonly T11ModifierDef[] ModifiersByNameLength = SortByNameLength(Modifiers); + + private static T11ModifierDef[] SortByNameLength(T11ModifierDef[] defs) + { + var copy = (T11ModifierDef[])defs.Clone(); + Array.Sort(copy, (a, b) => b.Name.Length.CompareTo(a.Name.Length)); + return copy; + } + + /// + /// The catalog entry whose name starts as a whole word + /// ("Max Health Pct +2%" is Max Health Pct, not Max Health), or null. + /// + public static T11ModifierDef? MatchModifier(string text) + { + foreach (var def in ModifiersByNameLength) + { + if (!text.StartsWith(def.Name, StringComparison.OrdinalIgnoreCase)) continue; + if (text.Length == def.Name.Length || text[def.Name.Length] == ' ') return def; + } + return null; + } + + /// The catalog entry for a server key, or null. + public static T11ModifierDef? ModifierByKey(int key) + { + foreach (var def in Modifiers) + if (def.Key == key) return def; + return null; + } + + /// Rank of a sub-grade label ("B+" = 12), or 0 when it isn't one. + public static int GradeRank(string? label) + { + if (string.IsNullOrEmpty(label)) return 0; + foreach (var (id, name) in Grades) + if (string.Equals(name, label, StringComparison.OrdinalIgnoreCase)) return id; + return 0; + } + + /// The words a "Wield requires:" line uses for each counter. + public static readonly (T11Counter Counter, string Name)[] CounterNames = + { + (T11Counter.ItemAugmentations, "Item Augmentations"), + (T11Counter.TriuneWeave, "Triune Weave"), + (T11Counter.BattlemagesWrath, "Battlemage's Wrath"), + (T11Counter.NetherVeil, "Nether Veil"), + (T11Counter.CrashingSteel, "Crashing Steel"), + (T11Counter.TrueShot, "True Shot"), + }; + + /// The counter named by a "Wield requires:" line, or null. + public static T11Counter? CounterByName(string name) + { + foreach (var (counter, n) in CounterNames) + if (string.Equals(n, name.Trim(), StringComparison.OrdinalIgnoreCase)) return counter; + return null; + } + + /// Display name of a counter. + public static string CounterName(T11Counter counter) + { + foreach (var (c, n) in CounterNames) + if (c == counter) return n; + return counter.ToString(); + } + + /// Highest loot tier on the server's default weapon-scaling ladder (T11-T25). + public const int MaxTier = 25; + + /// + /// Triune Weave required per tier above 15 on the default ladder: 500 at T16 up to 5,000 + /// at T25. Weapons and armor carry the same Triune gate; weapons add a family-charm gate + /// of the same size, which isn't needed for the estimate. + /// + public const int TriunePerTier = 500; + + /// + /// The loot tier implied by an item-augmentation wield gate, using the server's default + /// weapon-scaling table: T11 = 2,000, T12 = 2,500, then +500 per tier, capped at 4,000. + /// Without a Triune Weave gate the cap makes T15 and above read as 15 (see the + /// three-argument overload). Returns 11 for a T11-named item with no gate read yet, and 0 + /// for anything else. The server owner can retune the table, so this is an estimate. + /// + public static int EstimateTier(int itemAugGate, bool isT11) + { + if (itemAugGate <= 0) return isT11 ? 11 : 0; + if (itemAugGate < 2500) return 11; + return Math.Min(15, 12 + (itemAugGate - 2500) / 500); + } + + /// + /// The loot tier implied by both T11 wield gates. The item-aug gate stops rising at T15, + /// so from T16 the Triune Weave gate ( x (tier - 15)) carries + /// the tier: 500 = T16 ... 5,000 = T25. Any Triune gate means T16 or higher (the server + /// only stamps it from T16) and the result is capped at . Without a + /// Triune gate this is . + /// + public static int EstimateTier(int itemAugGate, int triuneGate, bool isT11) + { + if (triuneGate > 0) return Math.Clamp(15 + triuneGate / TriunePerTier, 16, MaxTier); + return EstimateTier(itemAugGate, isT11); + } + + /// Modifier keys with a rating, for callers that map Gear* keys back to modifiers. + public static IEnumerable RatingModifiers() + { + foreach (var def in Modifiers) + if (def.RatingKey != 0) yield return def; + } +} diff --git a/Shared/RynthCore.LootSdk/T11/T11ItemInfo.cs b/Shared/RynthCore.LootSdk/T11/T11ItemInfo.cs new file mode 100644 index 0000000..6181ab0 --- /dev/null +++ b/Shared/RynthCore.LootSdk/T11/T11ItemInfo.cs @@ -0,0 +1,348 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.RegularExpressions; + +namespace RynthCore.Loot.T11; + +/// One "Wield requires: N <counter>" gate. +public readonly record struct T11WieldGate(T11Counter Counter, int Amount); + +/// One line of the appraisal's "Modifiers:" section. +public sealed class T11Modifier +{ + /// Catalog key (T11Catalog.Modifiers), or 0 for a name the catalog doesn't know. + public int Key { get; init; } + /// The modifier name as printed. + public string Name { get; init; } = string.Empty; + /// The rolled value (the first number after the name; 0 for value-less specials). + public int Value { get; init; } + /// Low end of the "[min-max]" roll band, or null when the line has none. + public int? Min { get; init; } + /// High end of the "[min-max]" roll band, or null when the line has none. + public int? Max { get; init; } + /// Where the value landed in its band, 0-100, or -1 without a usable band. + public int RollPercent { get; init; } = -1; + /// The retail Gear* rating key the modifier sets, or 0. + public int RatingKey { get; init; } + /// True for a one-per-slot special (Fortify Vitals, Battle Mending, ...). + public bool IsSlotSpecial { get; init; } +} + +/// +/// What the client can learn about a T11 (tier 11+) ACECustom drop. The server keeps the +/// T11 properties (weapon quality, loot tier, the Zone Control record, the item-aug wield +/// gate) out of the appraisal and prints them as description text instead, so this is +/// parsed from the name, LongDesc (key 16) and Use (key 14). See ACECustom AppraiseInfo +/// (BuildProperties, BuildWeapon, PromoteZoneModifierLines) for the formats. +/// +public sealed class T11ItemInfo +{ + /// A non-T11 item: every field at its default. + public static readonly T11ItemInfo None = new(); + + /// True when the item is T11 gear (name prefix, or T11-only text in its description). + public bool IsT11 { get; private set; } + /// True when the name starts with "T11 - ". + public bool HasNamePrefix { get; private set; } + /// Weapon sub-grade label ("B+"), or null. + public string? Grade { get; private set; } + /// Sub-grade rank, S = 16 ... F- = 1, 0 = no grade. + public int GradeRank { get; private set; } + /// "N% of max damage" from the grade line, or -1. + public int DamagePercent { get; private set; } = -1; + /// Every wield gate, at most one per counter. + public IReadOnlyList WieldGates => _gates; + /// The Zone Control modifier lines, in appraisal order. + public IReadOnlyList Modifiers => _modifiers; + /// "Cast on Strike" lines: spell name and proc chance percent. + public IReadOnlyList<(string Name, double ChancePercent)> Procs => _procs; + /// True when the appraisal said "Zone Locked (Power Reduced)" (depends on where the examiner stood). + public bool ZoneLocked { get; private set; } + /// True when the item had appraisal text (false for a T11 name seen before its ID). + public bool HasText { get; private set; } + + private readonly List _gates = new(); + private readonly List _modifiers = new(); + private readonly List<(string, double)> _procs = new(); + + /// The item-augmentation gate, or 0 when there is none. + public int WieldItemAugs => GateAmount(T11Counter.ItemAugmentations); + + /// The amount required of , or 0 when it isn't gated. + public int GateAmount(T11Counter counter) + { + foreach (var g in _gates) + if (g.Counter == counter) return g.Amount; + return 0; + } + + /// + /// The estimated loot tier (11-25), or 0 for non-T11 items. T16 and up come from the + /// Triune Weave gate; an item without one reads at most 15. + /// + public int EstimatedTier => T11Catalog.EstimateTier(WieldItemAugs, GateAmount(T11Counter.TriuneWeave), IsT11); + + /// Sum of modifier values that land on the TotalRatings keys. + public int ModifierRatingTotal + { + get + { + int total = 0; + foreach (var m in _modifiers) + if (Array.IndexOf(T11Catalog.TotalRatingKeys, m.RatingKey) >= 0) total += m.Value; + return total; + } + } + + /// Sum of modifier values that set , or 0. + public int RatingFromModifiers(int ratingKey) + { + int total = 0; + foreach (var m in _modifiers) + if (m.RatingKey == ratingKey) total += m.Value; + return total; + } + + /// The value of the modifier with catalog key , or 0 when absent. + public int ModifierValue(int key) + { + foreach (var m in _modifiers) + if (m.Key == key) return m.Value; + return 0; + } + + /// Average roll position (0-100) of the banded modifiers, or 0 without any. + public int AverageRollPercent + { + get + { + int sum = 0, n = 0; + foreach (var m in _modifiers) + if (m.RollPercent >= 0) { sum += m.RollPercent; n++; } + return n == 0 ? 0 : (int)Math.Round(sum / (double)n, MidpointRounding.AwayFromZero); + } + } + + /// Best roll position (0-100) of the banded modifiers, or 0 without any. + public int BestRollPercent + { + get + { + int best = 0; + foreach (var m in _modifiers) + if (m.RollPercent > best) best = m.RollPercent; + return best; + } + } + + /// True when any modifier is a slot special. + public bool HasSlotSpecial + { + get + { + foreach (var m in _modifiers) + if (m.IsSlotSpecial) return true; + return false; + } + } + + // ── Parsing ───────────────────────────────────────────────────────────── + + private const RegexOptions Opt = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase; + + // "- Weapon Grade: B+ (86% of max damage)" / "- Weapon Grade: S" + private static readonly Regex GradeLine = new( + @"^-?\s*Weapon Grade:\s*(?S|[A-DF][+-]?)(?=\s|\(|$)(?:\s*\((?\d+)% of max damage\))?", Opt); + + // "- Wield requires: 2,000 Item Augmentations" (weapons) / "Wield requires: 2,000 Item Augmentations" (armor). + // ACE prints N0, so the group separator follows the server's culture: keep digits only. + private static readonly Regex WieldLine = new( + @"^-?\s*Wield requires:\s*(?\d[\d,.\s']*?)\s+(?[A-Za-z' ]+?)\s*$", Opt); + + // "- Cast on Strike: Force Arc (13% proc chance)" + private static readonly Regex ProcLine = new( + @"^-\s*Cast on Strike:\s*(?.+?)\s*\((?\d+(?:\.\d+)?)% proc chance\)\s*$", Opt); + + // A modifier's value: the first signed whole number after the name. + private static readonly Regex FirstNumber = new(@"[+-]?\d+", RegexOptions.CultureInvariant); + + // The roll band at the end of a modifier line: "[14-69]". + private static readonly Regex Band = new(@"\[(?\d+)\s*-\s*(?\d+)\]\s*$", RegexOptions.CultureInvariant); + + // An uncatalogued modifier from a newer server: "Some Name +12 [5-20]" or "Modifier 60 +3 [1-5]". + private static readonly Regex GenericModifier = new(@"^(?.+?)\s+(?[+-]?\d+)", RegexOptions.CultureInvariant); + // Checked before GenericModifier, whose lazy name would stop at "Modifier" and read the key as the value. + private static readonly Regex UnknownKeyName = new(@"^(?Modifier (?\d+))(?=\s|$)", RegexOptions.CultureInvariant); + + private const string ModifiersHeader = "Modifiers:"; + private const string ZoneLockedText = "Zone Locked (Power Reduced)"; + + /// + /// Parses an item. , and + /// may be null or empty (an item not yet appraised has no text; + /// the name prefix alone still marks it T11). Never throws. + /// + public static T11ItemInfo Parse(string? name, string? longDesc, string? use) + { + bool prefix = !string.IsNullOrEmpty(name) && name.StartsWith(T11Catalog.NamePrefix, StringComparison.Ordinal); + if (!prefix && string.IsNullOrEmpty(longDesc) && string.IsNullOrEmpty(use)) return None; + + var info = new T11ItemInfo + { + HasNamePrefix = prefix, + HasText = !string.IsNullOrEmpty(longDesc) || !string.IsNullOrEmpty(use), + }; + try + { + info.ParseText(longDesc); + info.ParseText(use); + } + catch + { + // Malformed text never breaks loot evaluation; whatever parsed so far stands. + } + + // Grade, gates and banded modifiers only appear on T11 gear; Cast on Strike and the + // zone-lock line alone do not mark an item. + info.IsT11 = prefix || info.GradeRank > 0 || info._gates.Count > 0 || info._modifiers.Count > 0; + return info.IsT11 ? info : None; + } + + private void ParseText(string? text) + { + if (string.IsNullOrEmpty(text)) return; + string[] lines = text.Replace("\r\n", "\n").Split('\n'); + for (int i = 0; i < lines.Length; i++) + { + string line = lines[i].Trim(); + if (line.Length == 0) continue; + + if (line.Contains(ZoneLockedText, StringComparison.OrdinalIgnoreCase)) { ZoneLocked = true; continue; } + + if (string.Equals(line, ModifiersHeader, StringComparison.OrdinalIgnoreCase)) + { + i = ParseModifierBlock(lines, i + 1) - 1; + continue; + } + + Match m = GradeLine.Match(line); + if (m.Success && GradeRank == 0) + { + Grade = m.Groups["g"].Value.ToUpperInvariant(); + GradeRank = T11Catalog.GradeRank(Grade); + if (m.Groups["pct"].Success && int.TryParse(m.Groups["pct"].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int pct)) + DamagePercent = pct; + continue; + } + + m = WieldLine.Match(line); + if (m.Success && T11Catalog.CounterByName(m.Groups["what"].Value) is T11Counter counter) + { + int amount = DigitsOnly(m.Groups["n"].Value); + if (amount > 0) AddGate(counter, amount); + continue; + } + + m = ProcLine.Match(line); + if (m.Success && double.TryParse(m.Groups["pct"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out double chance)) + _procs.Add((m.Groups["name"].Value, chance)); + } + } + + /// Reads "- ..." lines after a "Modifiers:" header; returns the index of the first line not consumed. + private int ParseModifierBlock(string[] lines, int start) + { + int i = start; + for (; i < lines.Length; i++) + { + string line = lines[i].Trim(); + if (line.Length == 0 || !line.StartsWith("-", StringComparison.Ordinal)) break; + string body = line.Substring(1).Trim(); + if (body.Length == 0) continue; + if (body.Contains(ZoneLockedText, StringComparison.OrdinalIgnoreCase)) { ZoneLocked = true; continue; } + _modifiers.Add(ParseModifier(body)); + } + return i; + } + + private static T11Modifier ParseModifier(string body) + { + T11ModifierDef? def = T11Catalog.MatchModifier(body); + string name; + string rest; + int key = 0; + if (def != null) + { + name = def.Name; + key = def.Key; + rest = body.Substring(def.Name.Length); + } + else if (UnknownKeyName.Match(body) is { Success: true } k + && int.TryParse(k.Groups["key"].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsedKey)) + { + key = parsedKey; + name = k.Groups["name"].Value; + rest = body.Substring(name.Length); + def = T11Catalog.ModifierByKey(parsedKey); + if (def != null) name = def.Name; + } + else + { + Match g = GenericModifier.Match(body); + name = g.Success ? g.Groups["name"].Value.Trim() : body; + rest = g.Success ? body.Substring(g.Groups["name"].Length) : string.Empty; + } + + int value = 0; + Match num = FirstNumber.Match(rest); + if (num.Success) int.TryParse(num.Value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out value); + + int? min = null, max = null; + int roll = -1; + Match band = Band.Match(rest); + if (band.Success + && int.TryParse(band.Groups["min"].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int lo) + && int.TryParse(band.Groups["max"].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int hi)) + { + min = lo; + max = hi; + if (hi > lo) roll = Math.Clamp((int)Math.Round((value - lo) * 100.0 / (hi - lo), MidpointRounding.AwayFromZero), 0, 100); + } + + return new T11Modifier + { + Key = key, + Name = name, + Value = value, + Min = min, + Max = max, + RollPercent = roll, + RatingKey = def?.RatingKey ?? 0, + IsSlotSpecial = def?.SlotSpecial ?? false, + }; + } + + private void AddGate(T11Counter counter, int amount) + { + for (int i = 0; i < _gates.Count; i++) + { + if (_gates[i].Counter != counter) continue; + if (amount > _gates[i].Amount) _gates[i] = new T11WieldGate(counter, amount); + return; + } + _gates.Add(new T11WieldGate(counter, amount)); + } + + private static int DigitsOnly(string s) + { + long v = 0; + foreach (char c in s) + { + if (c < '0' || c > '9') continue; + v = v * 10 + (c - '0'); + if (v > int.MaxValue) return int.MaxValue; + } + return (int)v; + } +} diff --git a/Shared/RynthCore.LootSdk/T11/T11Keys.cs b/Shared/RynthCore.LootSdk/T11/T11Keys.cs new file mode 100644 index 0000000..f64397f --- /dev/null +++ b/Shared/RynthCore.LootSdk/T11/T11Keys.cs @@ -0,0 +1,161 @@ +using System.Collections.Generic; + +namespace RynthCore.Loot.T11; + +/// +/// Virtual long-value keys for T11 loot rules. A loot rule uses them like any long key +/// (LongValKeyGE / LE / E / NE), so VTank-format profiles need no new node types. RynthAi +/// answers them from ; other loot engines (VTank, Mag) don't know +/// them and read them as 0. +/// +public static class T11Keys +{ + /// + /// First id of the reserved block ("RY" in the high bytes). Far above retail STypeInt ids, + /// ACECustom's custom ids (9000-50999) and Decal's 0x0D000000 WCID key. + /// + public const int Base = 0x52590000; + + /// 1 when the item is T11 gear, else 0. + public const int IsT11 = Base + 1; + /// Estimated loot tier from the wield gates (11-25; T16+ from the Triune Weave gate), 0 for non-T11. + public const int EstimatedTier = Base + 2; + /// Weapon sub-grade rank: S = 16, A+ = 15 ... F- = 1, 0 = no grade. + public const int WeaponGrade = Base + 3; + /// The weapon's damage as a percent of a perfect roll, 0 when not shown. + public const int DamagePercent = Base + 4; + /// Item augmentations required to wield, 0 for none. + public const int WieldItemAugs = Base + 5; + /// 1 = this character meets every wield gate, 0 = it doesn't, -1 = a needed counter is unknown. + public const int CanWield = Base + 6; + /// Number of Zone Control modifier lines. + public const int ModifierCount = Base + 7; + /// Sum of modifier values that count toward TotalRatings. + public const int ModifierRatingTotal = Base + 8; + /// Average roll position of the banded modifiers, 0-100. + public const int AverageRollPercent = Base + 9; + /// Best roll position of the banded modifiers, 0-100. + public const int BestRollPercent = Base + 10; + /// 1 when the item has a slot special (Fortify Vitals, Battle Mending, ...). + public const int HasSlotSpecial = Base + 11; + /// Number of "Cast on Strike" procs. + public const int CastOnStrikeCount = Base + 12; + /// 1 when the appraisal said "Zone Locked (Power Reduced)". Depends on where you stood when it was appraised. + public const int ZoneLocked = Base + 13; + /// Triune Weave required to wield (T16+ armor), 0 for none. + public const int WieldTriuneWeave = Base + 14; + + /// + /// Base of the per-modifier keys: ModifierBase + catalog key is that modifier's value + /// on the item, 0 when absent (ModifierBase + 28 = Damage Rating). + /// + public const int ModifierBase = Base + 0x100; + + /// One past the last id in the block. + public const int End = Base + 0x200; + + /// True for any id in the T11 block. + public static bool IsVirtual(int key) => key > Base && key < End; + + /// The per-modifier key for a catalog key. + public static int ForModifier(int catalogKey) => ModifierBase + catalogKey; + + /// Editor names for every T11 key, summary keys first. + public static IEnumerable<(int Id, string Name)> Names() + { + yield return (IsT11, "T11: Is T11"); + yield return (EstimatedTier, "T11: Tier (est.)"); + yield return (WeaponGrade, "T11: Weapon Grade"); + yield return (DamagePercent, "T11: Damage % of Max"); + yield return (WieldItemAugs, "T11: Wield Item Augs"); + yield return (WieldTriuneWeave, "T11: Wield Triune Weave"); + yield return (CanWield, "T11: Can Wield"); + yield return (ModifierCount, "T11: Modifier Count"); + yield return (ModifierRatingTotal, "T11: Modifier Ratings"); + yield return (AverageRollPercent, "T11: Avg Roll %"); + yield return (BestRollPercent, "T11: Best Roll %"); + yield return (HasSlotSpecial, "T11: Has Slot Special"); + yield return (CastOnStrikeCount, "T11: Cast on Strike Count"); + yield return (ZoneLocked, "T11: Zone Locked"); + foreach (var def in T11Catalog.Modifiers) + yield return (ForModifier(def.Key), "T11 Mod: " + def.Name); + } + + /// + /// The value of T11 key for . CanWield needs + /// ; without it CanWield reads -1 (unknown) for gated items. + /// Returns false for an id outside the block or an unused id in it. + /// + public static bool TryGetValue(T11ItemInfo item, int key, T11PlayerAugs? player, out int value) + { + value = 0; + if (!IsVirtual(key)) return false; + if (key >= ModifierBase) + { + int catalogKey = key - ModifierBase; + if (T11Catalog.ModifierByKey(catalogKey) == null) return false; + value = item.ModifierValue(catalogKey); + return true; + } + switch (key) + { + case IsT11: value = item.IsT11 ? 1 : 0; return true; + case EstimatedTier: value = item.EstimatedTier; return true; + case WeaponGrade: value = item.GradeRank; return true; + case DamagePercent: value = item.DamagePercent < 0 ? 0 : item.DamagePercent; return true; + case WieldItemAugs: value = item.WieldItemAugs; return true; + case WieldTriuneWeave: value = item.GateAmount(T11Counter.TriuneWeave); return true; + case CanWield: + // Before its ID a T11 item's gates are unknown, so it can't count as wieldable yet. + if (item.WieldGates.Count == 0) value = item.IsT11 && !item.HasText ? -1 : 1; + else value = player?.CanWield(item) ?? -1; + return true; + case ModifierCount: value = item.Modifiers.Count; return true; + case ModifierRatingTotal: value = item.ModifierRatingTotal; return true; + case AverageRollPercent: value = item.AverageRollPercent; return true; + case BestRollPercent: value = item.BestRollPercent; return true; + case HasSlotSpecial: value = item.HasSlotSpecial ? 1 : 0; return true; + case CastOnStrikeCount: value = item.Procs.Count; return true; + case ZoneLocked: value = item.ZoneLocked ? 1 : 0; return true; + default: return false; + } + } + + /// + /// The value the server stripped from a T11 item's appraisal, for the retail keys loot rules + /// already use: wield requirement slot 1 (158 = 13 Int64 Property, 159 = 9008, 160 = the + /// item-aug gate) and the Gear* ratings a modifier line carries (370-379). Only call this + /// when the live property is absent. Returns false when the item supplies no value. + /// + public static bool TryGetStrippedValue(T11ItemInfo item, int key, out int value) + { + value = 0; + if (!item.IsT11) return false; + switch (key) + { + case 158: + if (item.WieldItemAugs <= 0) return false; + value = WieldRequirementInt64Stat; + return true; + case 159: + if (item.WieldItemAugs <= 0) return false; + value = (int)T11Counter.ItemAugmentations; + return true; + case 160: + if (item.WieldItemAugs <= 0) return false; + value = item.WieldItemAugs; + return true; + } + if (key < 370 || key > 379) return false; + int fromMods = item.RatingFromModifiers(key); + if (fromMods == 0) return false; + value = fromMods; + return true; + } + + /// ACECustom's WieldRequirement.Int64Stat (the value after HeritageType = 12). + public const int WieldRequirementInt64Stat = 13; + + /// True for the retail keys can answer. + public static bool IsStrippedKey(int key) => key is 158 or 159 or 160 || (key >= 370 && key <= 379); +} diff --git a/Shared/RynthCore.LootSdk/T11/T11PlayerAugs.cs b/Shared/RynthCore.LootSdk/T11/T11PlayerAugs.cs new file mode 100644 index 0000000..bb1a6d4 --- /dev/null +++ b/Shared/RynthCore.LootSdk/T11/T11PlayerAugs.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.RegularExpressions; + +namespace RynthCore.Loot.T11; + +/// +/// The player counters T11 wield gates are checked against. ACECustom doesn't send these at +/// login (they aren't [SendOnLogin]), so they come from the "/aug" reply, or from a manual +/// item-aug override. Thread-safe: chat writes it, loot evaluation reads it. +/// +public sealed class T11PlayerAugs +{ + private readonly object _gate = new(); + private readonly Dictionary _counts = new(); + private long? _itemAugOverride; + + /// When the counters were last updated from "/aug" (UTC), or null. + public DateTime? UpdatedUtc { get; private set; } + + /// The manual item-aug count that replaces the "/aug" value, or null for automatic. + public long? ItemAugOverride + { + get { lock (_gate) return _itemAugOverride; } + set { lock (_gate) _itemAugOverride = value is < 0 ? null : value; } + } + + /// Records one counter read from "/aug". + public void Set(T11Counter counter, long value) + { + lock (_gate) + { + _counts[counter] = Math.Max(0, value); + UpdatedUtc = DateTime.UtcNow; + } + } + + /// + /// The player's count for , or null when unknown. Item + /// augmentations honour the manual override. + /// + public long? Get(T11Counter counter) + { + lock (_gate) + { + if (counter == T11Counter.ItemAugmentations && _itemAugOverride.HasValue) return _itemAugOverride; + return _counts.TryGetValue(counter, out long v) ? v : null; + } + } + + /// Forgets the "/aug" counts (logout). The manual override is kept. + public void Clear() + { + lock (_gate) + { + _counts.Clear(); + UpdatedUtc = null; + } + } + + /// + /// Whether the player meets every wield gate of : 1 = yes (or the + /// item has no gate), 0 = a gate is not met, -1 = a needed counter is unknown. Mirrors the + /// server's check (Player_Inventory, WieldRequirement.Int64Stat): raw counter >= amount. + /// + public int CanWield(T11ItemInfo item) + { + bool unknown = false; + foreach (var gate in item.WieldGates) + { + long? have = Get(gate.Counter); + if (have == null) { unknown = true; continue; } + if (have.Value < gate.Amount) return 0; + } + return unknown ? -1 : 1; + } +} + +/// +/// Reads ACECustom's "/aug" reply into . The reply is one chat line +/// per counter ("Item:1,234", "Triune Weave: 5 (adds ...)"), so a bare "Item:" line is only +/// trusted shortly after the "Advanced Augmentation Levels:" header. +/// +public sealed class T11AugReportParser +{ + /// How long after the header (or the last accepted line) reply lines are trusted. + public const long WindowMs = 5000; + + private const RegexOptions Opt = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase; + private static readonly Regex Header = new(@"^Advanced Augmentation Levels:\s*$", Opt); + private static readonly Regex Line = new(@"^(?[A-Za-z' ]+?)\s*:\s*(?\d[\d,.\s']*)", Opt); + + private long _openUntil = long.MinValue; + + /// + /// Feeds one chat line. Returns true when it updated a counter. + /// is any monotonic millisecond clock. + /// + public bool Feed(string? text, long nowMs, T11PlayerAugs into) + { + if (string.IsNullOrEmpty(text)) return false; + string line = text.Trim(); + if (Header.IsMatch(line)) + { + _openUntil = nowMs + WindowMs; + return false; + } + if (nowMs > _openUntil) return false; + + Match m = Line.Match(line); + if (!m.Success) return false; + T11Counter? counter = CounterFor(m.Groups["what"].Value.Trim()); + if (counter == null) return false; + + long value = 0; + foreach (char c in m.Groups["n"].Value) + { + if (c < '0' || c > '9') { if (c == ' ' || c == ',' || c == '.' || c == '\'') continue; break; } + value = value * 10 + (c - '0'); + } + into.Set(counter.Value, value); + _openUntil = nowMs + WindowMs; + return true; + } + + /// The counter a "/aug" line label stands for, or null for the ones T11 gates don't use. + private static T11Counter? CounterFor(string label) => label.ToLowerInvariant() switch + { + "item" => T11Counter.ItemAugmentations, + "triune weave" => T11Counter.TriuneWeave, + "battlemage's wrath charm" => T11Counter.BattlemagesWrath, + "nether veil charm" => T11Counter.NetherVeil, + "crashing steel charm" => T11Counter.CrashingSteel, + "true shot charm" => T11Counter.TrueShot, + _ => null, + }; +} diff --git a/Tools/RynthCore.LootSdkTests/LootT11Tests.cs b/Tools/RynthCore.LootSdkTests/LootT11Tests.cs new file mode 100644 index 0000000..a47e696 --- /dev/null +++ b/Tools/RynthCore.LootSdkTests/LootT11Tests.cs @@ -0,0 +1,210 @@ +using System; +using System.Linq; +using RynthCore.Loot.Editing; +using RynthCore.Loot.T11; + +namespace RynthCore.LootSdkTests; + +// T11 (ACECustom tier 11+) loot support: the item-text parser against the server's exact +// strings, tier estimates, the "/aug" reply reader, wield checks, virtual keys, the stripped +// wield/rating fallbacks, and the editor's key names and grade table. +internal static partial class Program +{ + // A T13 weapon as ACECustom appraises it: Property Details then Modifiers in LongDesc. + private const string T11WeaponLongDesc = + "A finely made sword.\n\n" + + "Property Details:\n" + + "- Weapon Grade: B+ (86% of max damage)\n" + + "- Wield requires: 3,000 Item Augmentations\n" + + "- Wield requires: 25 Crashing Steel\n" + + "- Cast on Strike: Force Arc (13% proc chance)\n" + + "\n" + + "Modifiers:\n" + + "- Damage Rating +41 [14-69]\n" + + "- Crit Damage Rating +10 [5-15]\n" + + "- Pct HP Damage 2%\n" + + "- Zone Locked (Power Reduced)\n"; + + // T16 armor: gates in LongDesc without a dash, Modifiers in the Use string. + private const string T11ArmorLongDesc = + "Sturdy plate.\n" + + "Wield requires: 4.000 Item Augmentations\n" + + "Wield requires: 500 Triune Weave\n"; + + private const string T11ArmorUse = + "Modifiers:\n" + + "- Damage Resist +8 [2-12]\n" + + "- Max Health +120 [40-200]\n" + + "- Max Health Pct +2% [1-4]\n" + + "- Modifier 60 +3 [1-5]\n"; + + private static void RunT11Tests() + { + Console.WriteLine("\n-- T11 loot --"); + TestT11WeaponParse(); + TestT11ArmorParse(); + TestT11NonT11(); + TestT11Tier(); + TestT11AugReport(); + TestT11Keys(); + TestT11Editor(); + } + + private static void TestT11WeaponParse() + { + T11ItemInfo w = T11ItemInfo.Parse("T11 - Tachi", T11WeaponLongDesc, null); + Check(w.IsT11 && w.HasNamePrefix, "weapon: T11 by prefix"); + Eq(w.Grade, "B+", "weapon: grade label"); + Eq(w.GradeRank, 12, "weapon: grade rank B+ = 12"); + Eq(w.DamagePercent, 86, "weapon: damage % of max"); + Eq(w.WieldItemAugs, 3000, "weapon: item-aug gate with group separator"); + Eq(w.GateAmount(T11Counter.CrashingSteel), 25, "weapon: charm gate"); + Eq(w.Procs.Count, 1, "weapon: one cast on strike"); + Eq(w.Procs.Count > 0 ? w.Procs[0].Name : "", "Force Arc", "weapon: proc name"); + Eq(w.Procs.Count > 0 ? w.Procs[0].ChancePercent : 0, 13.0, "weapon: proc chance"); + Check(w.ZoneLocked, "weapon: zone locked line inside Modifiers"); + Eq(w.Modifiers.Count, 3, "weapon: zone lock line is not a modifier"); + T11Modifier dr = w.Modifiers.First(m => m.Key == 28); + Eq(dr.Value, 41, "weapon: Damage Rating value"); + Eq((dr.Min, dr.Max), ((int?)14, (int?)69), "weapon: Damage Rating band"); + Eq(dr.RollPercent, 49, "weapon: Damage Rating roll (41-14)/(69-14)"); + Check(w.Modifiers.Any(m => m.Key == 44 && m.IsSlotSpecial), "weapon: slot special without a band"); + Check(w.HasSlotSpecial, "weapon: HasSlotSpecial"); + Eq(w.RatingFromModifiers(370), 41, "weapon: 370 from Damage Rating"); + Eq(w.RatingFromModifiers(374), 10, "weapon: 374 from Crit Damage Rating"); + Eq(w.ModifierRatingTotal, 51, "weapon: modifier rating total"); + Eq(w.EstimatedTier, 13, "weapon: 3,000 gate = T13"); + Eq(w.BestRollPercent, 50, "weapon: best roll (Crit Damage 10 in 5-15)"); + } + + private static void TestT11ArmorParse() + { + T11ItemInfo a = T11ItemInfo.Parse("T11 - Celdon Breastplate", T11ArmorLongDesc, T11ArmorUse); + Check(a.IsT11, "armor: T11"); + Eq(a.Grade, null, "armor: no weapon grade"); + Eq(a.WieldItemAugs, 4000, "armor: dot group separator, no dash"); + Eq(a.GateAmount(T11Counter.TriuneWeave), 500, "armor: Triune Weave gate"); + Eq(a.EstimatedTier, 16, "armor: 500 Triune Weave = T16"); + Eq(T11Keys.TryGetValue(a, T11Keys.EstimatedTier, null, out int at) ? at : 0, 16, "armor: tier key reads T16"); + Eq(a.Modifiers.Count, 4, "armor: modifiers from Use"); + Check(a.Modifiers.Any(m => m.Key == 47 && m.Value == 2), "armor: Max Health Pct is not Max Health"); + Check(a.Modifiers.Any(m => m.Key == 19 && m.Value == 120), "armor: Max Health"); + Check(a.Modifiers.Any(m => m.Key == 60 && m.Name == "Modifier 60" && m.Value == 3), "armor: unknown server key kept"); + Eq(a.RatingFromModifiers(371), 8, "armor: 371 from Damage Resist"); + Eq(a.RatingFromModifiers(379), 120, "armor: 379 from Max Health"); + Eq(a.ModifierRatingTotal, 128, "armor: rating total 371 + 379"); + } + + private static void TestT11NonT11() + { + Check(!T11ItemInfo.Parse("Tachi", "A finely made sword.", "").IsT11, "plain item is not T11"); + Check(!T11ItemInfo.Parse(null, null, null).IsT11, "no text is not T11"); + Check(!T11ItemInfo.Parse("Wand", "- Cast on Strike: Bolt (5% proc chance)", null).IsT11, "a proc alone doesn't mark T11"); + Check(T11ItemInfo.Parse("T11 - Robe", null, null).IsT11, "unappraised T11 name still T11"); + Eq(T11ItemInfo.Parse("T11 - Robe", null, null).EstimatedTier, 11, "unappraised T11 = tier 11"); + Check(!T11ItemInfo.Parse("T11 - Robe", null, null).HasText, "unappraised T11 has no text"); + Eq(T11Keys.TryGetValue(T11ItemInfo.Parse("T11 - Robe", null, null), T11Keys.CanWield, new T11PlayerAugs(), out int cw) ? cw : 99, -1, + "unappraised T11: Can Wield unknown"); + Eq(T11Keys.TryGetValue(T11ItemInfo.Parse("T11 - Robe", "A robe.", null), T11Keys.CanWield, null, out int cw2) ? cw2 : 99, 1, + "appraised T11 without a gate: wieldable"); + Check(!T11ItemInfo.Parse("x", "Modifiers:\n- ", "\n\n- [").IsT11, "malformed text doesn't throw or mark"); + } + + private static void TestT11Tier() + { + Eq(T11Catalog.EstimateTier(0, false), 0, "tier: nothing"); + Eq(T11Catalog.EstimateTier(2000, true), 11, "tier: 2,000 = T11"); + Eq(T11Catalog.EstimateTier(2500, true), 12, "tier: 2,500 = T12"); + Eq(T11Catalog.EstimateTier(3500, true), 14, "tier: 3,500 = T14"); + Eq(T11Catalog.EstimateTier(9000, true), 15, "tier: capped at 15"); + + // T16-T25: the item-aug gate is frozen at 4,000, the Triune Weave gate carries the tier. + Eq(T11Catalog.EstimateTier(4000, 0, true), 15, "tier: 4,000 without Triune = T15"); + Eq(T11Catalog.EstimateTier(3000, 0, true), 13, "tier: no Triune falls back to the item-aug gate"); + Eq(T11Catalog.EstimateTier(4000, 500, true), 16, "tier: 500 Triune = T16"); + Eq(T11Catalog.EstimateTier(4000, 1500, true), 18, "tier: 1,500 Triune = T18"); + Eq(T11Catalog.EstimateTier(4000, 5000, true), 25, "tier: 5,000 Triune = T25"); + Eq(T11Catalog.EstimateTier(4000, 9000, true), T11Catalog.MaxTier, "tier: capped at T25"); + Eq(T11Catalog.EstimateTier(4000, 250, true), 16, "tier: any Triune gate is at least T16"); + Eq(T11Catalog.EstimateTier(0, 0, false), 0, "tier: nothing (three-argument)"); + + // A T25 weapon as appraised: item augs frozen at 4,000, Triune and family charm 5,000 each. + T11ItemInfo t25 = T11ItemInfo.Parse("T11 - Tachi", + "Property Details:\n" + + "- Weapon Grade: A (95% of max damage)\n" + + "- Wield requires: 4,000 Item Augmentations\n" + + "- Wield requires: 5,000 Triune Weave\n" + + "- Wield requires: 5,000 Crashing Steel\n", null); + Eq(t25.EstimatedTier, 25, "tier: T25 weapon from its Triune gate"); + Eq(t25.GateAmount(T11Counter.CrashingSteel), 5000, "tier: T25 weapon charm gate"); + } + + private static void TestT11AugReport() + { + var p = new T11PlayerAugs(); + var r = new T11AugReportParser(); + Check(!r.Feed("Item:2,500", 0, p), "aug: Item line before the header ignored"); + Check(!r.Feed("Advanced Augmentation Levels:", 1000, p), "aug: header opens the window"); + Check(r.Feed("Item:2,500", 1100, p), "aug: Item line read"); + Check(r.Feed("Triune Weave: 3 (adds 3% damage)", 1200, p), "aug: Triune Weave read"); + Check(r.Feed("Crashing Steel Charm: 20", 1300, p), "aug: charm read"); + Check(!r.Feed("Item:9999", 1300 + T11AugReportParser.WindowMs + 1, p), "aug: window closes"); + Eq(p.Get(T11Counter.ItemAugmentations), (long?)2500, "aug: item count"); + Eq(p.Get(T11Counter.TriuneWeave), (long?)3, "aug: triune count"); + Eq(p.Get(T11Counter.NetherVeil), null, "aug: unreported counter unknown"); + + T11ItemInfo weapon = T11ItemInfo.Parse("T11 - Tachi", T11WeaponLongDesc, null); + Eq(p.CanWield(weapon), 0, "wield: 2,500 < 3,000"); + p.ItemAugOverride = 3000; + Eq(p.CanWield(weapon), 0, "wield: crashing steel 20 < 25"); + p.Set(T11Counter.CrashingSteel, 25); + Eq(p.CanWield(weapon), 1, "wield: override + charm met"); + p.Clear(); + Eq(p.Get(T11Counter.ItemAugmentations), (long?)3000, "aug: Clear keeps the override"); + Eq(p.CanWield(weapon), -1, "wield: charm unknown after Clear"); + } + + private static void TestT11Keys() + { + T11ItemInfo w = T11ItemInfo.Parse("T11 - Tachi", T11WeaponLongDesc, null); + int V(int key, T11PlayerAugs? pl = null) => T11Keys.TryGetValue(w, key, pl, out int v) ? v : int.MinValue; + Eq(V(T11Keys.IsT11), 1, "key: IsT11"); + Eq(V(T11Keys.EstimatedTier), 13, "key: tier"); + Eq(V(T11Keys.WeaponGrade), 12, "key: grade"); + Eq(V(T11Keys.DamagePercent), 86, "key: damage %"); + Eq(V(T11Keys.WieldItemAugs), 3000, "key: wield item augs"); + Eq(V(T11Keys.CanWield), -1, "key: can wield unknown without player"); + Eq(V(T11Keys.ModifierCount), 3, "key: modifier count"); + Eq(V(T11Keys.ModifierRatingTotal), 51, "key: modifier ratings"); + Eq(V(T11Keys.CastOnStrikeCount), 1, "key: procs"); + Eq(V(T11Keys.ZoneLocked), 1, "key: zone locked"); + Eq(V(T11Keys.ForModifier(28)), 41, "key: per-modifier Damage Rating"); + Eq(V(T11Keys.ForModifier(50)), 0, "key: absent modifier = 0"); + Eq(V(T11Keys.ModifierBase + 999), int.MinValue, "key: unknown modifier id unused"); + Eq(V(370), int.MinValue, "key: retail key isn't virtual"); + Check(T11Keys.IsVirtual(T11Keys.IsT11) && !T11Keys.IsVirtual(T11Keys.Base) && !T11Keys.IsVirtual(T11Keys.End), "key: block bounds"); + + int S(T11ItemInfo item, int key) => T11Keys.TryGetStrippedValue(item, key, out int v) ? v : int.MinValue; + Eq(S(w, 158), 13, "stripped: 158 = Int64 Property"); + Eq(S(w, 159), 9008, "stripped: 159 = item augs stat"); + Eq(S(w, 160), 3000, "stripped: 160 = gate"); + Eq(S(w, 370), 41, "stripped: 370 from modifier"); + Eq(S(w, 371), int.MinValue, "stripped: no modifier for 371"); + Eq(S(T11ItemInfo.None, 158), int.MinValue, "stripped: non-T11 gives nothing"); + Eq(S(T11ItemInfo.Parse("T11 - Robe", null, null), 160), int.MinValue, "stripped: no gate read yet"); + Check(T11Keys.IsStrippedKey(158) && T11Keys.IsStrippedKey(379) && !T11Keys.IsStrippedKey(161), "stripped: key set"); + } + + private static void TestT11Editor() + { + Check(LootRuleText.LongKeys.Any(k => k.Id == T11Keys.CanWield && k.Name == "T11: Can Wield"), "editor: Can Wield key named"); + Check(LootRuleText.LongKeys.Any(k => k.Id == T11Keys.ForModifier(28) && k.Name == "T11 Mod: Damage Rating"), "editor: per-modifier key named"); + Check(LootRuleText.LongKeys.Any(k => k.Id == 377), "editor: NetherResistRating listed"); + Eq(LootRuleText.LongKeys.Select(k => k.Id).Distinct().Count(), LootRuleText.LongKeys.Length, "editor: long key ids unique"); + Check(ReferenceEquals(LootRuleText.ValueTableFor(T11Keys.WeaponGrade), T11Catalog.Grades), "editor: grade value table"); + Eq(LootRuleText.ValueName(T11Keys.WeaponGrade, "12"), "B+", "editor: grade 12 named B+"); + Eq(LootRuleText.WieldRequirements.First(w => w.Id == 13).Name, "Int64 Property", "editor: wield requirement 13"); + Check(LootRuleText.StringKeys.Any(k => k.Id == 14) && LootRuleText.StringKeys.Any(k => k.Id == 16), "editor: Use and LongDesc string keys"); + Eq(T11Catalog.Grades.Select(g => g.Name).Distinct().Count(), T11Catalog.Grades.Length, "editor: grade names unique"); + } +} diff --git a/Tools/RynthCore.LootSdkTests/LootValueNameTests.cs b/Tools/RynthCore.LootSdkTests/LootValueNameTests.cs index 03b6bd3..f65f912 100644 --- a/Tools/RynthCore.LootSdkTests/LootValueNameTests.cs +++ b/Tools/RynthCore.LootSdkTests/LootValueNameTests.cs @@ -67,7 +67,7 @@ internal static partial class Program Eq(LootRuleText.Materials.First(m => m.Id == 15).Name, "Black Garnet", "material 15"); Eq(LootRuleText.Materials.Length, 78, "materials 0..77"); Eq(LootRuleText.WieldRequirements.First(w => w.Id == 2).Name, "Base Skill", "wield requirement 2 (RawSkill)"); - Eq(LootRuleText.WieldRequirements.Length, 13, "wield requirements 0..12"); + Eq(LootRuleText.WieldRequirements.Length, 14, "wield requirements 0..13 (13 = ACECustom Int64 Property)"); Eq(LootRuleText.DamageTypes.First(d => d.Id == 64).Name, "Electric", "damage type 64"); // Lookup and labels; unknown and odd values stay expressible. diff --git a/Tools/RynthCore.LootSdkTests/Program.cs b/Tools/RynthCore.LootSdkTests/Program.cs index 7eb1fd1..c0069ca 100644 --- a/Tools/RynthCore.LootSdkTests/Program.cs +++ b/Tools/RynthCore.LootSdkTests/Program.cs @@ -44,6 +44,7 @@ internal static partial class Program TestMalformedInputs(); RunLootEditTests(args); RunLootAddTests(args); + RunT11Tests(); Console.WriteLine($"\nGolden tests: {_asserts} assertions, {_fails} failed."); diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index a1cef53..988aa01 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -37,6 +37,8 @@ internal static class Program var runner = new Runner(); NativeLootTests.Register(runner); VTankLootTests.Register(runner); + T11LootTests.Register(runner); + MagItemDescriberTests.Register(runner); ExpressionTests.Register(runner); MetaTests.Register(runner); MetaSchedulerTests.Register(runner); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MagItemDescriberTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MagItemDescriberTests.cs new file mode 100644 index 0000000..8f6607a --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MagItemDescriberTests.cs @@ -0,0 +1,125 @@ +using System.Collections.Generic; +using RynthCore.Loot; +using RynthCore.Plugin.RynthAi.ItemInfo; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The Mag-style item info line (/ra iteminfo, ID-on-click) against what the ACECustom appraisal +// panel shows for the same item: whole-number damage range, signed bonuses, Crushing Blow as the +// dealt multiplier, and the imbue strength / grade / wield gate that only exist as text. +internal static class MagItemDescriberTests +{ + public static void Register(Runner r) + { + r.Add("iteminfo: T11 fire staff matches the appraisal panel", T11FireStaff); + r.Add("iteminfo: Biting Strike and a defense penalty", BitingStrikeAndPenalty); + r.Add("iteminfo: retail imbues stay bare labels without detail text", RetailImbuesBare); + r.Add("iteminfo: Int64 wield requirement never prints as a skill", Int64WieldHidden); + r.Add("iteminfo: T11 armor modifiers print on the ratings line", T11ArmorModifiers); + } + + /// In-memory property bag standing in for the client object cache. + private sealed class FakeItem : IItemPropertySource + { + public readonly Dictionary Ints = new(); + public readonly Dictionary Doubles = new(); + public readonly Dictionary Strings = new(); + + public FakeItem(string name, AcObjectClass cls) { Name = name; ObjectClass = cls; } + + public string Name { get; } + public AcObjectClass ObjectClass { get; } + public bool TryGetInt(uint stype, out int value) => Ints.TryGetValue(stype, out value); + public bool TryGetDouble(uint stype, out double value) => Doubles.TryGetValue(stype, out value); + public string GetString(uint stype) => Strings.TryGetValue(stype, out string? v) ? v : string.Empty; + public IReadOnlyList SpellIds { get; } = new List(); + } + + private static List Pet(FakeItem item) => MagItemDescriber.Build(item, MagItemInfoOptions.Default).ToPetLines(); + + // The item from the bug report: ACECustom shows Damage 1790 - 2069, Bonus to Attack Skill + // +20%, Melee Defense +20.0%, Crushing Blow 3.66x, Fire Rending +176%, Grade S (100%), + // Crit Dam 24, Wield requires 2,000 Item Augmentations. + private static void T11FireStaff() + { + var staff = new FakeItem("Flaming Quarter Staff", AcObjectClass.MeleeWeapon); + staff.Ints[44] = 2069; // max damage + staff.Ints[45] = 0x10; // fire + staff.Ints[353] = 7; // staff mastery + staff.Ints[105] = 9; // workmanship + staff.Ints[179] = 0x0200; // Fire Rending + staff.Ints[374] = 24; // crit damage rating + staff.Doubles[22] = 0.135; // variance + staff.Doubles[62] = 1.20; // attack + staff.Doubles[29] = 1.20; // melee defense + staff.Doubles[136] = 2.66; // CriticalMultiplier (Crushing Blow 3.66x) + staff.Strings[16] = + "Property Details:\n" + + "- Weapon Grade: S (100% of max damage)\n" + + "- Properties: 2 of 5\n" + + "- Crushing Blow: 3.66x Crit Dmg\n" + + "- Fire Rending: +176% Dmg\n" + + "- Effective Melee Defense: 39851\n" + + "- Wield requires: 2,000 Item Augmentations\n"; + + List lines = Pet(staff); + Check.Eq(lines.Count, 3, "line count"); + Check.Eq(lines[0], "Flaming Quarter Staff (Fire Staff), Grade S (100%), Craft 9", "identity line"); + Check.Eq(lines[1], "FireRend +176%, Crushing Blow 3.66x, 1790-2069, 0.135v, +20%a, +20%md", "combat line"); + Check.Eq(lines[2], "[CD 24] Wield 2,000 Item Augs", "ratings / requirements line"); + } + + private static void BitingStrikeAndPenalty() + { + var sword = new FakeItem("Sword", AcObjectClass.MeleeWeapon); + sword.Ints[44] = 100; + sword.Doubles[147] = 0.15; // Biting Strike + sword.Doubles[136] = 1.0; // normal 2x crit, not Crushing Blow + sword.Doubles[29] = 0.95; // -5% melee defense + string line = MagItemDescriber.Describe(sword, MagItemInfoOptions.Default); + Check.True(line.Contains("Biting Strike 15%"), $"Biting Strike shown: {line}"); + Check.False(line.Contains("Crushing Blow"), $"1.0 multiplier is not Crushing Blow: {line}"); + Check.True(line.Contains("-5%md"), $"penalty keeps its sign: {line}"); + Check.True(line.Contains(", 100,") || line.EndsWith(", 100"), $"no variance prints max only: {line}"); + } + + private static void RetailImbuesBare() + { + var axe = new FakeItem("Axe", AcObjectClass.MeleeWeapon); + axe.Ints[179] = 0x0001 | 0x0004; // CS + AR + string line = MagItemDescriber.Describe(axe, MagItemInfoOptions.Default); + Check.True(line.Contains(", CS AR"), $"bare Mag labels: {line}"); + + axe.Strings[16] = + "Property Details:\n" + + "- Critical Strike: +12.5 % Crit Chance\n" + // culture space before % + "- Armor Rending: 30.0% Ignored\n"; + line = MagItemDescriber.Describe(axe, MagItemInfoOptions.Default); + Check.True(line.Contains("CS +12.5%, AR 30.0%"), $"strengths from detail text: {line}"); + } + + private static void Int64WieldHidden() + { + var mace = new FakeItem("Mace", AcObjectClass.MeleeWeapon); + mace.Ints[158] = 13; // WieldRequirement.Int64Stat + mace.Ints[159] = 9008; // LumAugItemCount + mace.Ints[160] = 2500; + string line = MagItemDescriber.Describe(mace, MagItemInfoOptions.Default); + Check.False(line.Contains("Skill 9008"), $"no fake skill name: {line}"); + } + + private static void T11ArmorModifiers() + { + var helm = new FakeItem("T11 - Helm", AcObjectClass.Armor); + helm.Strings[16] = "Wield requires: 500 Triune Weave\n"; + helm.Strings[14] = + "Modifiers:\n" + + "- Damage Resist +6 [2-12]\n" + + "- Max Health +100 [40-200]\n"; + List lines = Pet(helm); + string last = lines[^1]; + Check.True(last.Contains("Mods: Damage Resist +6, Max Health +100"), $"modifiers listed: {last}"); + Check.True(last.Contains("Wield 500 Triune Weave"), $"triune gate listed: {last}"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/T11LootTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/T11LootTests.cs new file mode 100644 index 0000000..f0e9af3 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/T11LootTests.cs @@ -0,0 +1,127 @@ +using RynthCore.Loot; +using RynthCore.Loot.T11; +using RynthCore.Loot.VTank; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.Loot; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; +using N = RynthCore.Loot.VTank.VTankNodeTypes; + +namespace RynthCore.RynthAiHostTests.Tests; + +// T11 (ACECustom tier 11+) items through the real evaluator: the virtual T11 keys answered by +// WorldObject.Values, the wield requirement and ratings the server strips put back from the +// item text, and "Can Wield" fed by the "/aug" reply. +internal static class T11LootTests +{ + private const string WeaponLongDesc = + "Property Details:\n" + + "- Weapon Grade: A- (91% of max damage)\n" + + "- Wield requires: 2,500 Item Augmentations\n" + + "\n" + + "Modifiers:\n" + + "- Damage Rating +30 [14-69]\n" + + "- Crit Chance +4 [1-8]\n"; + + private const string ArmorUse = + "Modifiers:\n" + + "- Damage Resist +6 [2-12]\n" + + "- Max Health +100 [40-200]\n"; + + public static void Register(Runner r) + { + r.Add("loot t11: virtual keys read the item text", VirtualKeys); + r.Add("loot t11: stripped wield requirement 158/159/160 restored", StrippedWield); + r.Add("loot t11: modifier ratings feed Gear* keys and TotalRatings", ModifierRatings); + r.Add("loot t11: a live rating wins over the modifier text", LiveRatingWins); + r.Add("loot t11: retail items are untouched", RetailUntouched); + r.Add("loot t11: Can Wield from the /aug reply and the override", CanWield); + } + + private static VTankLootCondition C(int node, params string[] data) => new(node, "0", data); + + private static bool M(WorldObject item, params VTankLootCondition[] conds) + { + var rule = new VTankLootRule { Name = "r", Action = VTankLootAction.Keep }; + rule.Conditions.AddRange(conds); + return VTankLootEvaluator.Match(rule, item); + } + + private static string K(int key) => key.ToString(System.Globalization.CultureInfo.InvariantCulture); + + private static Item Weapon() => new Item("T11 - Tachi", AcObjectClass.MeleeWeapon).Str(16, WeaponLongDesc); + + private static void VirtualKeys() + { + T11ItemSupport.Reset(); + WorldObject w = Weapon(); + Check.Eq(w.Values(T11Keys.IsT11, -5), 1, "IsT11"); + Check.Eq(w.Values(T11Keys.EstimatedTier, -5), 12, "2,500 gate = T12"); + Check.Eq(w.Values(T11Keys.WeaponGrade, -5), 13, "A- = 13"); + Check.True(M(w, C(N.LongValKeyGE, "12", K(T11Keys.WeaponGrade))), "rule: grade B+ or better"); + Check.False(M(w, C(N.LongValKeyGE, "14", K(T11Keys.WeaponGrade))), "rule: grade A or better"); + Check.True(M(w, C(N.LongValKeyGE, "25", K(T11Keys.ForModifier(28)))), "rule: Damage Rating mod >= 25"); + Check.True(M(w, C(N.LongValKeyE, "0", K(T11Keys.ZoneLocked))), "rule: not zone locked"); + Check.Eq(w.Values(T11Keys.Base + 0x1FF, -5), -5, "unused virtual id = default"); + Check.Eq(new Item("Tachi").Wo.Values(T11Keys.IsT11, -5), 0, "retail item: IsT11 = 0"); + } + + private static void StrippedWield() + { + T11ItemSupport.Reset(); + WorldObject w = Weapon(); + Check.Eq(w.Values(158, 0), T11Keys.WieldRequirementInt64Stat, "158 = Int64 Property"); + Check.Eq(w.Values(159, 0), 9008, "159 = item augs"); + Check.Eq(w.Values(160, 0), 2500, "160 = gate"); + Check.True(M(w, C(N.LongValKeyLE, "2500", "160")), "rule: wield difficulty <= 2500"); + Check.False(M(w, C(N.LongValKeyLE, "2000", "160")), "rule: wield difficulty <= 2000"); + Check.Eq(w.Values(161, -1), -1, "other keys keep the default"); + } + + private static void ModifierRatings() + { + T11ItemSupport.Reset(); + WorldObject w = Weapon(); + Check.Eq(w.Values(370, 0), 30, "370 Damage Rating from text"); + Check.Eq(w.Values(372, 0), 4, "372 Crit from text"); + Check.True(M(w, C(N.TotalRatingsGE, "34")), "TotalRatings counts modifier ratings"); + Check.False(M(w, C(N.TotalRatingsGE, "35")), "TotalRatings exact"); + + WorldObject armor = new Item("T11 - Celdon Breastplate", AcObjectClass.Armor).Str(14, ArmorUse); + Check.Eq(armor.Values(371, 0), 6, "371 from the Use string"); + Check.True(M(armor, C(N.TotalRatingsGE, "106")), "armor TotalRatings 371 + 379"); + } + + private static void LiveRatingWins() + { + T11ItemSupport.Reset(); + WorldObject w = Weapon().Int(370, 7); + Check.Eq(w.Values(370, 0), 7, "a property the item has is never replaced"); + } + + private static void RetailUntouched() + { + T11ItemSupport.Reset(); + WorldObject retail = new Item("Tachi", AcObjectClass.MeleeWeapon).Str(16, WeaponLongDesc); + Check.Eq(retail.Values(160, 0), 0, "no T11 prefix: no stripped-key fallback"); + Check.Eq(retail.Values(370, -1), -1, "no T11 prefix: rating default kept"); + } + + private static void CanWield() + { + T11ItemSupport.Reset(); + WorldObject w = Weapon(); + Check.Eq(w.Values(T11Keys.CanWield, -5), -1, "unknown before /aug"); + T11ItemSupport.OnChat("Advanced Augmentation Levels:"); + T11ItemSupport.OnChat("Item:2,400"); + Check.Eq(w.Values(T11Keys.CanWield, -5), 0, "2,400 < 2,500"); + Check.False(M(w, C(N.LongValKeyE, "1", K(T11Keys.CanWield))), "rule: wieldable fails"); + T11ItemSupport.SyncOverride(2500); + Check.Eq(w.Values(T11Keys.CanWield, -5), 1, "override 2,500 meets the gate"); + T11ItemSupport.SyncOverride(-1); + Check.Eq(w.Values(T11Keys.CanWield, -5), 0, "back to the /aug count"); + Check.Eq(new Item("T11 - Robe").Wo.Values(T11Keys.CanWield, -5), -1, "not appraised yet: unknown"); + Check.Eq(new Item("T11 - Robe").Str(16, "A robe.").Wo.Values(T11Keys.CanWield, -5), 1, "appraised, no gate: wieldable"); + T11ItemSupport.Reset(); + } +}